HEL-892: show source-bound Chinese H3 parameter definitions

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-30 08:17:25 +08:00
co-authored by multica-agent
parent b47e13d169
commit 1470db4053
13 changed files with 3217 additions and 27 deletions
+119
View File
@@ -0,0 +1,119 @@
// Read-only integration against the real detail GET and existing Drawer.
import fs from 'node:fs';
import assert from 'node:assert/strict';
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright');
const out = process.env.H3_BROWSER_OUTPUT || '.local-evidence/h3-document/browser';
fs.mkdirSync(out, { recursive: true });
const checks = [], requests = [], errors = [];
function check(condition, name) { assert.ok(condition, name); checks.push(name); console.log('PASS ' + name); }
const browser = await chromium.launch({ headless: true,
...(process.env.BROWSER_EXECUTABLE ? { executablePath: process.env.BROWSER_EXECUTABLE } : {}) });
try {
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on('request', r => { if (r.url().includes('/api/')) requests.push({ method: r.method(), url: r.url() }); });
page.on('pageerror', e => errors.push(e.message));
const records = await (await fetch('http://127.0.0.1:8247/api/workflows')).json();
const h3 = records.find(r => r.name === 'Minimax-H3提示词增强');
assert.ok(h3);
const detail = await (await fetch(`http://127.0.0.1:8247/api/workflows/${h3.id}`)).json();
const fixed = detail.doc_json.fixed_version;
check(records.length === 157 && fixed.fields.length === 18, '155实际条目和2旧数据夹具,详情GET提供18项定义');
check(!detail.is_enabled && detail.import_state === 'needs_conversion' && !detail.doc_completed_at && !detail.exec_verified_at, '停用、待转换、完成和实跑时间戳为空');
await page.goto('http://127.0.0.1:5173/connections', { waitUntil: 'networkidle' });
check(await page.getByRole('button', { name: '说明', exact: true }).count() === 157, '全部条目均有说明入口');
const dialog = page.getByRole('dialog', { name: '工作流说明' });
async function begin(name) {
const row = page.locator('.wf-row').filter({ has: page.locator('.wf-name').filter({ hasText: name }) }).first();
const button = row.getByRole('button', { name: '说明', exact: true });
await button.focus(); await page.keyboard.press('Enter');
return button;
}
async function loaded() {
await dialog.getByText('用途与来源', { exact: true }).waitFor();
await dialog.evaluate(el => Promise.all(el.getAnimations().map(a => a.finished)));
}
let button = await begin(h3.name); await loaded();
for (const text of ['按源图声明版本核对,目标环境未核对', '说明未定稿', '未验证实跑', '未检查', '169槽0 → 170.prompt', '170槽8 → 172.source']) {
check((await dialog.innerText()).includes(text), '显示:' + text);
}
const summaryNames = fixed.fields.map(f => `节点 ${f.node_id} · ${f.label}(${f.field})`);
check(await dialog.locator('summary').filter({ hasText: /节点 (169|170) · .*(/ }).count() === 18, '18项中文参数定义没有遗漏');
await dialog.getByText('固定版本参数说明', { exact: true }).scrollIntoViewIfNeeded();
await page.screenshot({ path: `${out}/desktop-overview.png` });
// Open each actual parameter and its evidence, compare exact source strings without logging them.
for (let i = 0; i < fixed.fields.length; i++) {
const field = fixed.fields[i];
const summary = dialog.getByText(summaryNames[i], { exact: true });
await summary.click();
const box = summary.locator('..');
check((await box.innerText()).includes(field.effect) && (await box.innerText()).includes(field.limits), `${field.node_id}.${field.field}中文用途、范围和限定`);
check(await box.locator(':scope > pre').textContent() === (typeof field.value === 'string' ? field.value : JSON.stringify(field.value, null, 2)), `${field.node_id}.${field.field}源现值逐字保留`);
await box.getByText('来源依据', { exact: true }).click();
const text = await box.innerText();
check(text.includes(field.pointer) && text.includes(field.named_pointer) && field.evidence.every(index => {
const ev = fixed.sources[index]; return text.includes(ev.commit) && text.includes(ev.sha256) && text.includes(ev.lines.join('~'));
}), `${field.node_id}.${field.field}指针、完整提交、原件SHA与行号`);
if (field.field === 'duration' && field.node_id === '170') await page.screenshot({ path: `${out}/desktop-check-duration.png` });
await summary.click();
}
await page.keyboard.press('Escape'); await dialog.waitFor({ state: 'hidden' });
check(await button.evaluate(el => el === document.activeElement), 'Esc关闭并归还说明入口焦点');
// Read failure and retry; disable query retries for deterministic failure timing via 15s wait.
await page.route(`**/api/workflows/${h3.id}`, route => route.fulfill({ status: 500, contentType: 'application/json', body: '{"detail":"隔离失败夹具"}' }));
await begin(h3.name); await dialog.getByRole('alert').waitFor({ timeout: 20000 });
check(await dialog.getByRole('button', { name: '重试', exact: true }).isVisible(), '详情GET失败显示重试');
check(await dialog.getByText('固定版本参数说明', { exact: true }).count() === 0, '读取失败不展示缓存定义');
await page.unroute(`**/api/workflows/${h3.id}`);
await dialog.getByRole('button', { name: '重试', exact: true }).click(); await loaded();
check((await dialog.innerText()).includes(fixed.notice), 'GET重试恢复18项定义');
await page.keyboard.press('Escape');
// Close a pending GET, switch to a different document, then deliver the old response.
let release;
const held = new Promise(resolve => { release = resolve; });
let entered;
const intercepted = new Promise(resolve => { entered = resolve; });
let completed;
const responseDelivered = new Promise(resolve => { completed = resolve; });
await page.route(`**/api/workflows/${h3.id}`, async route => { entered(); await held; await route.fulfill({ json: detail }); completed(); });
await begin(h3.name); await intercepted;
check((await dialog.innerText()).includes('正在读取说明'), '重新读取期间隐藏旧内容');
await page.keyboard.press('Escape');
await begin('旧工作流回退(隔离测试夹具)'); await loaded(); release(); await responseDelivered;
await page.unroute(`**/api/workflows/${h3.id}`);
check(await dialog.getByText('固定版本参数说明', { exact: true }).count() === 0, '切条后迟到的H3响应不串到旧条目');
check((await dialog.innerText()).includes('隔离库旧条目回退测试'), '旧doc=null回退可读');
await page.keyboard.press('Escape');
await begin('空说明回退(隔离测试夹具)'); await loaded();
check((await dialog.innerText()).includes('此旧工作流暂无说明数据') || (await dialog.innerText()).includes('隔离库旧条目回退测试'), '空doc={}回退可读');
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 390, height: 844 });
button = await begin(h3.name); await loaded();
check(await dialog.evaluate(el => Math.round(el.getBoundingClientRect().width) === 390), '390窄屏抽屉全宽');
for (const fieldName of ['model', 'control_after_generate', 'prompt']) {
const index = fixed.fields.findIndex(f => f.field === fieldName);
const summary = dialog.getByText(summaryNames[index], { exact: true });
await summary.click();
const box = summary.locator('..');
await box.getByText('来源依据', { exact: true }).click();
await summary.scrollIntoViewIfNeeded();
check(await dialog.locator('.drawer-body').evaluate(el => el.scrollWidth <= el.clientWidth), `390窄屏${fieldName}长现值和来源无横向溢出`);
await page.screenshot({ path: `${out}/mobile-${fieldName}.png` });
await summary.click();
}
await dialog.getByRole('button', { name: '关闭', exact: true }).focus(); await page.keyboard.press('Tab');
check(await dialog.evaluate(el => el.contains(document.activeElement)), 'Tab焦点限制在抽屉');
await page.keyboard.press('Shift+Tab');
check(await dialog.evaluate(el => el.contains(document.activeElement)), 'ShiftTab焦点限制在抽屉');
const sourceSummary = dialog.getByText(summaryNames[4], { exact: true });
await sourceSummary.focus(); await page.keyboard.press('Enter');
check(await sourceSummary.locator('..').evaluate(el => el.open), '键盘Enter可展开参数');
await page.keyboard.press('Escape');
check(await button.evaluate(el => el === document.activeElement), '窄屏关闭归还焦点');
check(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), '390窄屏页面无横向溢出');
check(errors.length === 0, '浏览器无脚本错误');
check(requests.every(r => r.method === 'GET'), '浏览全程仅GET,无写入或生成请求');
check(requests.every(r => new URL(r.url).hostname === '127.0.0.1'), '请求仅访问本地隔离服务');
fs.writeFileSync(`${out}/browser-results.json`, JSON.stringify({ viewport: [1440, 390], checks, requests, errors, detailId: h3.id }, null, 2));
} finally {
await browser.close();
}
+78
View File
@@ -0,0 +1,78 @@
"""Foreground local browser check; stop every owned service before returning."""
from __future__ import annotations
import os
import signal
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / ".local-evidence/h3-document/browser"
def main():
OUT.mkdir(parents=True, exist_ok=True)
# Refuse to reuse another operator's service or port.
import socket
for port in (8247, 5173):
with socket.socket() as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", port))
processes = []
logs = []
try:
commands = [
([sys.executable, str(ROOT / "e2e/workflow-document-server.py")], ROOT),
(
["node", "node_modules/vite/bin/vite.js", "--host", "127.0.0.1"],
ROOT / "calliope-web",
),
]
for i, (command, cwd) in enumerate(commands):
log = (OUT / f"service-{i}.log").open("w")
logs.append(log)
processes.append(
subprocess.Popen(
command, cwd=cwd, stdout=log, stderr=log, start_new_session=True
)
)
for url in (
"http://127.0.0.1:8247/api/workflows",
"http://127.0.0.1:5173/connections",
):
deadline = time.monotonic() + 30
while True:
if any(p.poll() is not None for p in processes):
raise RuntimeError("Local service exited; inspect service logs")
try:
with urllib.request.urlopen(url, timeout=1) as response:
if response.status == 200:
break
except (urllib.error.URLError, TimeoutError):
pass
if time.monotonic() > deadline:
raise TimeoutError(url)
time.sleep(0.2)
subprocess.run(["node", "e2e/h3-document.mjs"], cwd=ROOT, check=True)
finally:
for p in processes:
if p.poll() is None:
os.killpg(p.pid, signal.SIGTERM)
try:
p.wait(timeout=10)
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL)
p.wait(timeout=5)
for log in logs:
log.close()
print("All owned browser services stopped.")
if __name__ == "__main__":
main()
+44 -16
View File
@@ -3,32 +3,42 @@
From repo root: .venv/bin/python e2e/workflow-document-server.py
Run Vite on 5173 alongside it. No remote ComfyUI endpoint is configured.
"""
from __future__ import annotations
import asyncio
from pathlib import Path
import uvicorn
from calliope.comfyui.companions import load_companions
from calliope.comfyui.library import import_library
from calliope.config import settings
from calliope.db import get_db, migrate_db
from calliope.routers import workflows
from fastapi import FastAPI
from fastapi.responses import JSONResponse
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / '.local-evidence' / 'ui'
DATA = ROOT / ".local-evidence" / "ui"
settings.data_dir = DATA
settings.db_name = 'library.db'
settings.assets_dir = DATA / 'assets'
settings.db_name = "library.db"
settings.assets_dir = DATA / "assets"
settings.comfyui_endpoints = []
settings.comfyui_base_url = 'http://127.0.0.1:1'
settings.comfyui_base_url = "http://127.0.0.1:1"
app = FastAPI()
app.include_router(workflows.router, prefix='/api/workflows')
app.include_router(workflows.router, prefix="/api/workflows")
@app.get('/api/settings')
@app.middleware("http")
async def read_only(request, call_next):
if request.method != "GET":
return JSONResponse({"detail": "隔离说明服务仅允许GET"}, status_code=405)
return await call_next(request)
@app.get("/api/settings")
def get_settings():
return {'comfyui_endpoints': [], 'comfyui_active_id': None}
return {"comfyui_endpoints": [], "comfyui_active_id": None}
def prepare():
@@ -36,23 +46,41 @@ def prepare():
asyncio.run(migrate_db(settings.db_path))
conn = get_db(settings.db_path)
try:
print(import_library(conn, ROOT / 'example_ComfyUI_workflows', source_commit='ui-browser'))
report = import_library(
conn,
ROOT / "example_ComfyUI_workflows",
source_commit="ui-browser",
companions=load_companions(
ROOT / "docs/hel-892/supplied-api/manifest.json"
),
)
print({"counts": report["counts"], "states": report["states"]})
for name, document in [
('旧工作流回退(隔离测试夹具)', None),
('空说明回退(隔离测试夹具)', '{}'),
("旧工作流回退(隔离测试夹具)", None),
("空说明回退(隔离测试夹具)", "{}"),
]:
if conn.execute('SELECT id FROM workflows WHERE name=?', (name,)).fetchone():
if conn.execute(
"SELECT id FROM workflows WHERE name=?", (name,)
).fetchone():
continue
conn.execute(
'INSERT INTO workflows(name,kind,workflow_json,input_schema,description,'
'is_enabled,doc_json) VALUES (?,?,?,?,?,?,?)',
(name, 'image', '{}', '[]', '隔离库旧条目回退测试;不代表真实工作流。', 0, document),
"INSERT INTO workflows(name,kind,workflow_json,input_schema,description,"
"is_enabled,doc_json) VALUES (?,?,?,?,?,?,?)",
(
name,
"image",
"{}",
"[]",
"隔离库旧条目回退测试;不代表真实工作流。",
0,
document,
),
)
conn.commit()
finally:
conn.close()
if __name__ == '__main__':
if __name__ == "__main__":
prepare()
uvicorn.run(app, host='127.0.0.1', port=8247)
uvicorn.run(app, host="127.0.0.1", port=8247)