From 6064bd805dacae0e1d57a19e48072175ab30e33b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=80=BB=E5=B7=A5?= Date: Wed, 30 Sep 2026 14:42:56 +0800 Subject: [PATCH] =?UTF-8?q?feat(ui):=20E=E6=89=B9=E2=80=94=E2=80=94?= =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E6=B5=81=E5=AF=BC=E5=85=A5=E4=B8=8E=E8=AF=95?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E5=8F=B3=E4=BE=A7=E6=8A=BD=E5=B1=89=20+=20?= =?UTF-8?q?=E5=9B=9B=E6=AD=A5=E6=A3=80=E6=9F=A5=20(HEL-655)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 ui/Drawer.svelte 右侧抽屉基元:380/420px、--d-drawer 280ms --ease-drawer 可反向、Esc/Tab 焦点圈、遮罩点击关闭、减动效仅留 ≤120ms 淡变 - 新增 WorkflowImportDrawer.svelte:导入两步向导抽屉化,四步检查 (解析 JSON→识别节点→核对模型→建立输入槽)逐条出现(80ms 错峰)、 ✓绿/…青/✕红/待确认琥珀 + 中文原因 + 下一步建议 + 可展开错误 + 重新检查 + 「查看原始 JSON」折叠;沿用 /api/workflows/analyze 原判定与保存边界 - WorkflowTestDialog.svelte 居中弹窗改右侧抽屉:运行中青芯片 + 进度条 + mono 阶段日志滚动区,结果缩略图横排、失败红 + 长错误可展开; 逻辑(确认弹层、dry_run 拒绝、产物隔离、重复提交复用)不变 - connections 页:导入入口统一为抽屉按钮,次级文字操作(测试/重新检查/更改) 改 ghost(HEL-649 v2 §1.2),连接卡片改 §3.7 网格;移除内联导入块与死样式 - i18n 七语种各 +16 键(wfd.*)计数一致 - e2e:fake_comfy.py 支持 object_info/no_outputs 场景;新增 import.mjs 43 项浏览器回归全过;D 批 shoot.mjs 54/54 复跑通过 Co-authored-by: multica-agent --- .../components/WorkflowImportDrawer.svelte | 1129 ++++++++++++++ .../lib/components/WorkflowTestDialog.svelte | 1330 ++++++++++------- .../src/lib/components/ui/Drawer.svelte | 256 ++++ calliope-web/src/lib/i18n/de.ts | 16 + calliope-web/src/lib/i18n/en.ts | 16 + calliope-web/src/lib/i18n/es.ts | 16 + calliope-web/src/lib/i18n/fr.ts | 16 + calliope-web/src/lib/i18n/ja.ts | 16 + calliope-web/src/lib/i18n/ko.ts | 16 + calliope-web/src/lib/i18n/zh.ts | 16 + .../src/routes/connections/+page.svelte | 776 +--------- e2e/fake_comfy.py | 19 +- e2e/import.mjs | 588 ++++++++ 13 files changed, 2913 insertions(+), 1297 deletions(-) create mode 100644 calliope-web/src/lib/components/WorkflowImportDrawer.svelte create mode 100644 calliope-web/src/lib/components/ui/Drawer.svelte create mode 100644 e2e/import.mjs diff --git a/calliope-web/src/lib/components/WorkflowImportDrawer.svelte b/calliope-web/src/lib/components/WorkflowImportDrawer.svelte new file mode 100644 index 00000000..a889fedf --- /dev/null +++ b/calliope-web/src/lib/components/WorkflowImportDrawer.svelte @@ -0,0 +1,1129 @@ + + + + {#if wfStep === 'input'} +

{t('conn.wfImportHint')}

+ + +
+ API JSON* + +
+ + + {wfParsed.valid + ? t('conn.wfNodes', { n: Object.keys(wfParsed.json ?? {}).length }) + : 'JSON'} + +
+ {#if wfJsonText.trim() !== '' && !wfParsed.valid} + {t('conn.wfJsonInvalid')} + {/if} +
+
+ +
+ {:else if wfAnalysis} +

{t('conn.wfConfirmHint')}

+ + {#if wfAnalyzeError} + + {/if} + +
    + {#each checkSteps as step, i (step.key)} + {#if i < stepsShown} +
  1. + + + {step.label} + {step.line} + {#if step.key === 'models' && connCheck && connCheck.reachable === true && !connCheck.ok} + + {#if findingsOpen} +
      + {#each connCheck.findings as f (f.node_id + f.code)} +
    • + {f.message} + {#if f.hint}{f.hint}{/if} +
    • + {/each} +
    + {/if} +

    {t('conn.wfCheckSaveHint')}

    + {:else if step.key === 'models' && step.state === 'warn'} +

    {t('wfd.unreachableSuggest')}

    + {:else if step.key === 'nodes' && step.state === 'warn'} +

    {t('wfd.nodesPickSuggest')}

    + {/if} +
    + {#if step.key === 'models'} + + {/if} +
  2. + {/if} + {/each} +
+ + {#if wfAnalysis.usage_problem} +
+ +

{wfAnalysis.usage_problem}

+
+ {/if} + +
    + {#each wfAnalysis.usage_evidence.summary as line (line)} +
  • {line}
  • + {/each} +
+ +
+ + {t('conn.wfUsageLabel')}* + + {#if wfAnalysis.usage} + {t('conn.wfUsageAuto', { usage: usageLabel(wfAnalysis.usage) })} + {:else} + {t('conn.wfUsageNeedPick')} + {/if} + + +
+ {#each WORKFLOW_USAGES as u (u)} + + {/each} +
+
+ + {#if wfOutputRows.length} +
+ + {t('conn.wfOutputLabel')}* + {t('conn.wfOutputNeedPick')} + +
+ {#each wfOutputRows as row (row.nodeId)} +
+ + +
+ {/each} +
+ {t('conn.wfOutputHint')} +
+ {/if} + + {#if wfSlotRows.length} +
+ {t('conn.wfSlotsLabel')} +
+ {#each wfSlotRows as row (row.nodeId)} +
+ {row.nodeId} + {row.label} + {#if row.fixed} + {t('wfRole.reference_image')} + {:else} + + {/if} +
+ {/each} +
+ {t('conn.wfSlotsHint')} +
+ {/if} + +

+ {t('conn.wfParams', { n: wfParamPreview.length })} + {#if wfParamPreview.length} + {wfParamPreview.slice(0, 8).join(' · ')}{wfParamPreview.length > 8 + ? ' …' + : ''} + {/if} +

+ + {#if (wfAnalysis.warnings ?? []).length} +
    + {#each wfAnalysis.warnings as w (w.node_id + w.code)} +
  • {w.message}
  • + {/each} +
+ {/if} + +
+ + + {wfUsage + ? wfOutputCandidates.length && wfOutputPickedCount === 0 + ? t('conn.wfOutputPick') + : usageLabel(wfUsage) + : t('conn.wfUsageNeedPick')} + + +
+ +
+ + {#if showRawJson} +
{wfJsonText}
+ {/if} +
+ {/if} +
+ + diff --git a/calliope-web/src/lib/components/WorkflowTestDialog.svelte b/calliope-web/src/lib/components/WorkflowTestDialog.svelte index 1e63049b..5d9f0385 100644 --- a/calliope-web/src/lib/components/WorkflowTestDialog.svelte +++ b/calliope-web/src/lib/components/WorkflowTestDialog.svelte @@ -1,579 +1,827 @@ - - {#if wf} -
-

- {wf.name} - #{wf.id} -

+ + {#if wf} +
+

+ {wf.name} + #{wf.id} +

- + - {#if hasH3Hint} -
- -

{t('wfMedia.h3Limits')}

-
- {/if} + {#if hasH3Hint} +
+ +

{t('wfMedia.h3Limits')}

+
+ {/if} - {#if activeJob} - {@const info = jobStatusInfo(activeJob)} -
-
- {t('wft.running')} - {info.detail} - -
-
- {:else if finishedJob && finishedJob.status === 'done' && (finishedJob.output_paths?.length ?? 0) > 0} -
-

{t('wft.passed', { n: finishedJob.output_paths.length })}

-
- {#each finishedJob.output_paths.slice(0, 4) as path (path)} - - - - {/each} -
-
- {:else if finishedJob && finishedJob.status !== 'pending' && finishedJob.status !== 'running'} -
-

{t('wft.failed')}

-

{finishedJob.error === 'cancelled' ? t('wft.cancelledShort') : finishedJob.error}

-
- {/if} + {#if activeJob && activeInfo} +
+
+ + + {t('wft.running')} + + {activeInfo.detail} + +
+ + {#if stageLog.length} +
+ {#each stageLog as line, i (i)} +

{line}

+ {/each} +
+ {/if} +
+ {:else if finishedJob && finishedJob.status === 'done' && (finishedJob.output_paths?.length ?? 0) > 0} +
+

+ {t('wft.passed', { n: finishedJob.output_paths.length })} +

+
+ {#each finishedJob.output_paths as path (path)} + + + + {/each} +
+
+ {:else if finishedJob && finishedJob.status !== 'pending' && finishedJob.status !== 'running'} +
+

{t('wft.failed')}

+

+ {finishedJob.error === 'cancelled' + ? t('wft.cancelledShort') + : errorExpanded || (finishedJob.error ?? '').length <= 160 + ? finishedJob.error + : (finishedJob.error ?? '').slice(0, 160) + '…'} +

+ {#if finishedJob.error && finishedJob.error !== 'cancelled' && finishedJob.error.length > 160} + + {/if} +
+ {/if} - {#if !queueBusy} -
- {#each listEntries as entry (entry.nodeId)} - {@const kind = kindOf(entry)} - mediaAdd(entry, files)} - onReplace={(i, file) => mediaReplace(entry, i, file)} - onRemove={(i) => mediaRemove(entry, i)} - onDismissReject={(i) => - setRejects(entry.nodeId, (rejects[entry.nodeId] ?? []).filter((_, j) => j !== i))} - /> - {/each} - {#if formEntries.length} - - {/if} -
- {#if submitError}{submitError}{/if} -
- -
- {/if} + {#if !queueBusy} +
+ {#each listEntries as entry (entry.nodeId)} + {@const kind = kindOf(entry)} + mediaAdd(entry, files)} + onReplace={(i, file) => mediaReplace(entry, i, file)} + onRemove={(i) => mediaRemove(entry, i)} + onDismissReject={(i) => + setRejects( + entry.nodeId, + (rejects[entry.nodeId] ?? []).filter((_, j) => j !== i), + )} + /> + {/each} + {#if formEntries.length} + + {/if} +
+ {#if submitError}{submitError}{/if} +
+ +
+ {/if} -
-
- {t('wft.history', { n: history.length })} - {#if history.length} - - {/if} -
- {#if history.length === 0} -

{t('wft.never')}

- {:else} -
    - {#each history as job (job.id)} -
  • - #{job.id} - {timeOf(job.created_at)} - 0}> - {resultLine(job)} - -
  • - {/each} -
- {/if} -
-
- {/if} - +
+
+ {t('wft.history', { n: history.length })} + {#if history.length} + + {/if} +
+ {#if history.length === 0} +

{t('wft.never')}

+ {:else} +
    + {#each history as job (job.id)} +
  • + #{job.id} + {timeOf(job.created_at)} + 0} + > + {resultLine(job)} + +
  • + {/each} +
+ {/if} +
+
+ {/if} + diff --git a/calliope-web/src/lib/components/ui/Drawer.svelte b/calliope-web/src/lib/components/ui/Drawer.svelte new file mode 100644 index 00000000..1c694baf --- /dev/null +++ b/calliope-web/src/lib/components/ui/Drawer.svelte @@ -0,0 +1,256 @@ + + +{#if open} + +
+ +
+{/if} + + diff --git a/calliope-web/src/lib/i18n/de.ts b/calliope-web/src/lib/i18n/de.ts index b36f3a89..b7df1291 100644 --- a/calliope-web/src/lib/i18n/de.ts +++ b/calliope-web/src/lib/i18n/de.ts @@ -2058,4 +2058,20 @@ export const de: Dict = { 'desk.wfUntested': 'Nicht getestet', 'desk.workflow': 'Workflow', 'desk.yesterday': 'Gestern', + 'wfd.stepParse': 'JSON parsen', + 'wfd.stepNodes': 'Knoten erkennen', + 'wfd.stepModels': 'Modelle prüfen', + 'wfd.stepSlots': 'Eingangsslots aufbauen', + 'wfd.noOutput': 'Der Workflow hat keinen Ausgabeknoten — Import nicht möglich', + 'wfd.nodesAutoOk': 'Verwendung automatisch erkannt: {usage}', + 'wfd.nodesUserOk': 'Verwendung bestätigt: {usage}', + 'wfd.modelsOk': '„{name}“ hat alle benötigten Knoten und Modelle', + 'wfd.slotsOk': '{n} Eingangsslot(s) aufgebaut ({m} Medien)', + 'wfd.checksAria': 'Import-Prüfergebnisse', + 'wfd.showDetails': 'Fehlerdetails anzeigen', + 'wfd.hideDetails': 'Fehlerdetails ausblenden', + 'wfd.unreachableSuggest': 'Eine misslungene Prüfung verhindert das Speichern nicht; nach Reparatur erneut prüfen.', + 'wfd.nodesPickSuggest': 'Wähle unten die Verwendung und schließe die Ausgangszuordnung ab, bevor du speicherst.', + 'wfd.showRaw': 'Rohes JSON anzeigen', + 'wfd.hideRaw': 'Rohes JSON ausblenden', }; diff --git a/calliope-web/src/lib/i18n/en.ts b/calliope-web/src/lib/i18n/en.ts index 1c251136..5ba60085 100644 --- a/calliope-web/src/lib/i18n/en.ts +++ b/calliope-web/src/lib/i18n/en.ts @@ -2057,6 +2057,22 @@ export const en = { 'desk.wfUntested': 'Not tested', 'desk.workflow': 'Workflow', 'desk.yesterday': 'Yesterday', + 'wfd.stepParse': 'Parse JSON', + 'wfd.stepNodes': 'Identify nodes', + 'wfd.stepModels': 'Verify models', + 'wfd.stepSlots': 'Build input slots', + 'wfd.noOutput': 'The workflow has no output node — cannot import', + 'wfd.nodesAutoOk': 'Usage auto-detected: {usage}', + 'wfd.nodesUserOk': 'Usage confirmed: {usage}', + 'wfd.modelsOk': '"{name}" has all required nodes and models', + 'wfd.slotsOk': '{n} input slot(s) built ({m} media)', + 'wfd.checksAria': 'Import check results', + 'wfd.showDetails': 'Show error details', + 'wfd.hideDetails': 'Hide error details', + 'wfd.unreachableSuggest': 'Being unverifiable does not block saving; re-check after fixing the connection.', + 'wfd.nodesPickSuggest': 'Pick the usage and finish the output mapping below before saving.', + 'wfd.showRaw': 'View raw JSON', + 'wfd.hideRaw': 'Hide raw JSON', }; export type Dict = typeof en; diff --git a/calliope-web/src/lib/i18n/es.ts b/calliope-web/src/lib/i18n/es.ts index a6a9d4e0..540dd1ff 100644 --- a/calliope-web/src/lib/i18n/es.ts +++ b/calliope-web/src/lib/i18n/es.ts @@ -2058,4 +2058,20 @@ export const es: Dict = { 'desk.wfUntested': 'Sin probar', 'desk.workflow': 'Flujo', 'desk.yesterday': 'Ayer', + 'wfd.stepParse': 'Analizar JSON', + 'wfd.stepNodes': 'Identificar nodos', + 'wfd.stepModels': 'Verificar modelos', + 'wfd.stepSlots': 'Crear slots de entrada', + 'wfd.noOutput': 'El flujo no tiene nodos de salida; no se puede importar', + 'wfd.nodesAutoOk': 'Uso detectado automáticamente: {usage}', + 'wfd.nodesUserOk': 'Uso confirmado: {usage}', + 'wfd.modelsOk': '«{name}» tiene todos los nodos y modelos necesarios', + 'wfd.slotsOk': '{n} slot(s) de entrada creados ({m} de medios)', + 'wfd.checksAria': 'Resultados de la comprobación de importación', + 'wfd.showDetails': 'Mostrar detalles del error', + 'wfd.hideDetails': 'Ocultar detalles del error', + 'wfd.unreachableSuggest': 'No poder verificar no impide guardar; vuelve a comprobar tras arreglar la conexión.', + 'wfd.nodesPickSuggest': 'Elige el uso y completa el mapeo de salida abajo antes de guardar.', + 'wfd.showRaw': 'Ver JSON original', + 'wfd.hideRaw': 'Ocultar JSON original', }; diff --git a/calliope-web/src/lib/i18n/fr.ts b/calliope-web/src/lib/i18n/fr.ts index a88ed13a..97f93f8f 100644 --- a/calliope-web/src/lib/i18n/fr.ts +++ b/calliope-web/src/lib/i18n/fr.ts @@ -2058,4 +2058,20 @@ export const fr: Dict = { 'desk.wfUntested': 'Non testé', 'desk.workflow': 'Workflow', 'desk.yesterday': 'Hier', + 'wfd.stepParse': 'Analyser le JSON', + 'wfd.stepNodes': 'Identifier les nœuds', + 'wfd.stepModels': 'Vérifier les modèles', + 'wfd.stepSlots': 'Créer les slots d’entrée', + 'wfd.noOutput': "Le flux n'a aucun nœud de sortie — import impossible", + 'wfd.nodesAutoOk': 'Usage détecté automatiquement : {usage}', + 'wfd.nodesUserOk': 'Usage confirmé : {usage}', + 'wfd.modelsOk': '« {name} » possède tous les nœuds et modèles requis', + 'wfd.slotsOk': "{n} slot(s) d'entrée créés ({m} média)", + 'wfd.checksAria': "Résultats de la vérification d'import", + 'wfd.showDetails': "Afficher les détails de l'erreur", + 'wfd.hideDetails': "Masquer les détails de l'erreur", + 'wfd.unreachableSuggest': "L'impossibilité de vérifier n'empêche pas l'enregistrement ; revérifiez après avoir réparé la connexion.", + 'wfd.nodesPickSuggest': "Choisissez l'usage et terminez le mappage des sorties ci-dessous avant d'enregistrer.", + 'wfd.showRaw': 'Voir le JSON brut', + 'wfd.hideRaw': 'Masquer le JSON brut', }; diff --git a/calliope-web/src/lib/i18n/ja.ts b/calliope-web/src/lib/i18n/ja.ts index 5c72ade5..9c719073 100644 --- a/calliope-web/src/lib/i18n/ja.ts +++ b/calliope-web/src/lib/i18n/ja.ts @@ -2058,4 +2058,20 @@ export const ja: Dict = { 'desk.wfUntested': '未テスト', 'desk.workflow': 'ワークフロー', 'desk.yesterday': '昨日', + 'wfd.stepParse': 'JSON を解析', + 'wfd.stepNodes': 'ノードを識別', + 'wfd.stepModels': 'モデルを確認', + 'wfd.stepSlots': '入力スロットを構築', + 'wfd.noOutput': '出力ノードがないためインポートできません', + 'wfd.nodesAutoOk': '用途を自動判定:{usage}', + 'wfd.nodesUserOk': '用途を確認済み:{usage}', + 'wfd.modelsOk': '「{name}」に必要なノードとモデルが揃っています', + 'wfd.slotsOk': '入力スロット {n} 件を構築(うちメディア {m} 件)', + 'wfd.checksAria': 'インポート検査結果', + 'wfd.showDetails': 'エラー詳細を展開', + 'wfd.hideDetails': 'エラー詳細を折りたたむ', + 'wfd.unreachableSuggest': '検査できなくても保存は可能です。接続を直して「再チェック」してください。', + 'wfd.nodesPickSuggest': '保存前に下で用途を選び、出力マッピングを完了してください。', + 'wfd.showRaw': '元の JSON を見る', + 'wfd.hideRaw': '元の JSON を閉じる', }; diff --git a/calliope-web/src/lib/i18n/ko.ts b/calliope-web/src/lib/i18n/ko.ts index 9adc6f97..86a73547 100644 --- a/calliope-web/src/lib/i18n/ko.ts +++ b/calliope-web/src/lib/i18n/ko.ts @@ -2058,4 +2058,20 @@ export const ko: Dict = { 'desk.wfUntested': '테스트 안 함', 'desk.workflow': '워크플로', 'desk.yesterday': '어제', + 'wfd.stepParse': 'JSON 파싱', + 'wfd.stepNodes': '노드 식별', + 'wfd.stepModels': '모델 확인', + 'wfd.stepSlots': '입력 슬롯 구성', + 'wfd.noOutput': '출력 노드가 없어 가져올 수 없습니다', + 'wfd.nodesAutoOk': '용도 자동 판정: {usage}', + 'wfd.nodesUserOk': '용도 확인됨: {usage}', + 'wfd.modelsOk': "'{name}'에 필요한 노드와 모델이 모두 있습니다", + 'wfd.slotsOk': '입력 슬롯 {n}개 구성(미디어 {m}개)', + 'wfd.checksAria': '가져오기 검사 결과', + 'wfd.showDetails': '오류 자세히 보기', + 'wfd.hideDetails': '오류 자세히 접기', + 'wfd.unreachableSuggest': '확인 실패는 저장을 막지 않습니다. 연결을 고친 뒤 다시 검사하세요.', + 'wfd.nodesPickSuggest': '저장하기 전에 아래에서 용도를 선택하고 출력 매핑을 완료하세요.', + 'wfd.showRaw': '원본 JSON 보기', + 'wfd.hideRaw': '원본 JSON 접기', }; diff --git a/calliope-web/src/lib/i18n/zh.ts b/calliope-web/src/lib/i18n/zh.ts index aff75e94..60e30211 100644 --- a/calliope-web/src/lib/i18n/zh.ts +++ b/calliope-web/src/lib/i18n/zh.ts @@ -2058,4 +2058,20 @@ export const zh: Dict = { 'desk.wfUntested': '未试运行', 'desk.workflow': '工作流', 'desk.yesterday': '昨天', + 'wfd.stepParse': '解析 JSON', + 'wfd.stepNodes': '识别节点', + 'wfd.stepModels': '核对模型', + 'wfd.stepSlots': '建立输入槽', + 'wfd.noOutput': '工作流没有任何输出节点,无法导入', + 'wfd.nodesAutoOk': '自动判定用途:{usage}', + 'wfd.nodesUserOk': '用途已确认:{usage}', + 'wfd.modelsOk': '「{name}」已装齐所需节点与模型', + 'wfd.slotsOk': '已建立 {n} 个输入槽(含 {m} 个媒体槽)', + 'wfd.checksAria': '导入检查结果', + 'wfd.showDetails': '展开错误详情', + 'wfd.hideDetails': '收起错误详情', + 'wfd.unreachableSuggest': '无法核查不会阻止保存;修好连接后点「重新检查」复查。', + 'wfd.nodesPickSuggest': '请在下方选择用途并完成输出映射后再保存。', + 'wfd.showRaw': '查看原始 JSON', + 'wfd.hideRaw': '收起原始 JSON', }; diff --git a/calliope-web/src/routes/connections/+page.svelte b/calliope-web/src/routes/connections/+page.svelte index fa7c4e72..d8338c97 100644 --- a/calliope-web/src/routes/connections/+page.svelte +++ b/calliope-web/src/routes/connections/+page.svelte @@ -7,8 +7,9 @@ import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte'; import Icon from '$lib/components/ui/Icon.svelte'; import EmptyState from '$lib/components/ui/EmptyState.svelte'; + import WorkflowImportDrawer from '$lib/components/WorkflowImportDrawer.svelte'; import WorkflowTestDialog from '$lib/components/WorkflowTestDialog.svelte'; - import { apiErrorMessage, comfy, settings, workflows, type ComfyEndpoint, type Workflow, type WorkflowOutputMapEntry, type WorkflowUsage, type WorkflowAnalyzeResult, type WorkflowConnectionCheck } from '$lib/api'; + import { apiErrorMessage, comfy, settings, workflows, type ComfyEndpoint, type Workflow, type WorkflowOutputMapEntry, type WorkflowUsage, type WorkflowConnectionCheck } from '$lib/api'; import { WORKFLOW_USAGES } from '$lib/comfy/types'; import { toast } from '$lib/toast'; import { t } from '$lib/i18n.svelte'; @@ -327,214 +328,24 @@ }); // ------------------------------------------------------------------ - // Workflow library (import + binding) — two-step wizard: paste/analyze, - // then confirm the judged usage and slot roles before saving (HEL-636). + // Workflow library (binding + per-row recheck / test). The import + // wizard itself lives in WorkflowImportDrawer (HEL-655 E 批). // ------------------------------------------------------------------ - let wfJsonText = $state(''); let wfImportOpen = $state(false); - let wfImportName = $state(''); - let wfImportEndpoint = $state(''); - let wfStep = $state<'input' | 'confirm'>('input'); - let wfAnalysis = $state(null); - let wfUsage = $state(null); - let wfRoleOverrides = $state>({}); - // HEL-638: explicit output-node designation for unknown custom nodes. - let wfOutputPicked = $state>({}); - let wfOutputKind = $state>({}); - let wfAnalyzing = $state(false); - let wfAnalyzeError = $state(''); - - const wfParsed = $derived.by(() => { - const text = wfJsonText.trim(); - if (!text) return { valid: false as const, json: null as Record | null }; - try { - const parsed = JSON.parse(text) as unknown; - if ( - typeof parsed === 'object' && - parsed !== null && - !Array.isArray(parsed) && - Object.values(parsed).some( - (v) => typeof v === 'object' && v !== null && 'class_type' in (v as object), - ) - ) { - return { valid: true as const, json: parsed as Record }; - } - } catch { - /* fallthrough */ - } - return { valid: false as const, json: null }; - }); - - function usageLabel(u: WorkflowUsage | null | undefined): string { - return u ? t(`usage.${u}`) : t('usage.pending'); - } function startWfImport() { wfImportOpen = true; - wfImportName = ''; - wfJsonText = ''; - wfImportEndpoint = ''; - wfStep = 'input'; - wfAnalysis = null; - wfUsage = null; - wfRoleOverrides = {}; - wfOutputPicked = {}; - wfOutputKind = {}; - wfAnalyzeError = ''; + } + + function usageLabel(u: WorkflowUsage | null | undefined): string { + return u ? t(`usage.${u}`) : t('usage.pending'); } function wfProblems(wf: Workflow): string[] { return (wf.warnings ?? []).filter((w) => w.level === 'error').map((w) => w.message); } - async function runWfAnalyze(refresh = false) { - if (!wfParsed.valid || !wfParsed.json) return; - wfAnalyzing = true; - wfAnalyzeError = ''; - try { - const res = await workflows.analyze( - wfParsed.json, - wfImportEndpoint || undefined, - refresh, - ); - wfAnalysis = res; - wfUsage = res.usage ?? null; - wfRoleOverrides = {}; - // Unknown output candidates: preselect only when there is exactly - // one — with several the user must decide (HEL-638). - const candidates = (res.usage_evidence.outputs ?? []).filter( - (o) => o.evidence === 'unknown_node', - ); - const picked: Record = {}; - const kinds: Record = {}; - for (const c of candidates) { - kinds[c.nodeId] = c.suggested_kind ?? 'image'; - } - if (candidates.length === 1) picked[candidates[0].nodeId] = true; - wfOutputPicked = picked; - wfOutputKind = kinds; - wfStep = 'confirm'; - } catch (err) { - wfAnalyzeError = apiErrorMessage(err); - } finally { - wfAnalyzing = false; - } - } - - /** True when the graph has no output node at all — nothing to confirm. */ - const wfFatal = $derived( - wfStep === 'confirm' && wfAnalysis !== null && (wfAnalysis.outputs?.length ?? 0) === 0, - ); - /** Unknown custom output nodes the user must designate (HEL-638). */ - const wfOutputCandidates = $derived( - wfStep === 'confirm' && wfAnalysis !== null - ? (wfAnalysis.usage_evidence.outputs ?? []).filter((o) => o.evidence === 'unknown_node') - : [], - ); - const wfOutputRows = $derived( - wfOutputCandidates.map((o) => ({ - ...o, - picked: wfOutputPicked[o.nodeId] ?? false, - kind: wfOutputKind[o.nodeId] ?? o.suggested_kind ?? 'image', - })), - ); - const wfOutputPickedCount = $derived( - Object.values(wfOutputPicked).filter(Boolean).length, - ); - const wfMustPick = $derived( - wfStep === 'confirm' && - wfAnalysis !== null && - !wfFatal && - (wfAnalysis.usage_ambiguous || wfAnalysis.needs_mapping) && - wfUsage === null, - ); - const wfSaveable = $derived( - wfStep === 'confirm' && - wfUsage !== null && - !wfFatal && - (wfOutputCandidates.length === 0 || wfOutputPickedCount > 0), - ); - /** Media slots the confirm page lets the user re-role. */ - const wfSlotRows = $derived.by(() => { - if (wfStep !== 'confirm' || !wfAnalysis) return []; - return wfAnalysis.usage_evidence.image_slots.map((s) => ({ - ...s, - role: wfRoleOverrides[s.nodeId] ?? s.role ?? 'image', - fixed: s.kind === 'image_list', - })); - }); - const wfParamPreview = $derived.by(() => { - if (!wfAnalysis) return []; - // Count EVERY analyzed input (media slots included) so the preview - // matches the inline count shown after import (input_schema.length) - // and in the studio — HEL-619. - return wfAnalysis.inputs.map((i) => i.label); - }); - - const wfImportMutation = createMutation({ - mutationFn: async () => { - if (!wfParsed.valid || !wfParsed.json || !wfAnalysis || !wfUsage) - throw new Error(t('conn.wfPickUsage')); - if (wfOutputCandidates.length > 0 && wfOutputPickedCount === 0) - throw new Error(t('conn.wfOutputPick')); - const corrected = Object.keys(wfRoleOverrides).length > 0; - const schema = wfAnalysis.inputs.map((e) => - wfRoleOverrides[e.nodeId] - ? { ...e, role: wfRoleOverrides[e.nodeId], manual: true } - : e, - ); - const outputMap = wfOutputRows - .filter((r) => r.picked) - .map((r) => ({ - nodeId: r.nodeId, - kind: r.kind, - label: r.label, - ...(r.class_type ? { class_type: r.class_type } : {}), - })); - return workflows.create({ - name: wfImportName.trim(), - workflow_json: wfParsed.json, - usage: wfUsage, - usage_source: wfUsage !== wfAnalysis.usage || corrected ? 'user' : 'auto', - input_schema: schema, - ...(outputMap.length ? { output_map: outputMap, output_map_source: 'user' } : {}), - ...(wfImportEndpoint ? { endpoint_id: wfImportEndpoint } : {}), - }); - }, - onSuccess: (wf) => { - client.invalidateQueries({ queryKey: ['workflows'] }); - const n = wf.input_schema?.length ?? 0; - const problems = wfProblems(wf); - if (problems.length) toast.error(t('conn.wfImportedBroken', { detail: problems.join(';') })); - else if (n) toast.success(t('conn.wfImportedWithUsage', { usage: usageLabel(wf.usage), n })); - else toast.info(t('conn.wfImportedNoParams')); - wfImportOpen = false; - wfJsonText = ''; - wfImportName = ''; - wfStep = 'input'; - wfAnalysis = null; - }, - onError: (err) => { - toast.error( - t('conn.wfImportFailed', { - detail: err instanceof Error ? err.message : String(err), - }), - ); - }, - }); - - function submitWfImport() { - if (!wfSaveable || !wfImportName.trim() || $wfImportMutation.isPending) return; - $wfImportMutation.mutate(); - } - - // ------------------------------------------------------------------ - // HEL-643 L2: connection-compatibility check on the import confirm - // step, and per-row 重新检查 / 测试 in the workflow library. - // ------------------------------------------------------------------ - const wfConnCheck = $derived( - wfAnalysis?.connection_check ?? null, - ); + // HEL-643 L2: per-row 重新检查 / 测试 in the workflow library. let wfRecheckId = $state(null); const wfRecheckResult = $state>({}); @@ -686,15 +497,6 @@ }, }); - async function onWfFile(e: Event) { - const input = e.currentTarget as HTMLInputElement; - const file = input.files?.[0]; - if (!file) return; - wfJsonText = await file.text(); - if (!wfImportName.trim()) wfImportName = file.name.replace(/\.json$/i, ''); - input.value = ''; - } - const wfDeleteMutation = createMutation({ mutationFn: (id: number) => workflows.delete(id), onSuccess: () => { @@ -921,296 +723,6 @@ - {#if wfImportOpen} -
-
-

- {wfStep === 'input' ? t('conn.wfImportTitle') : t('conn.wfConfirmTitle')} - - {wfStep === 'input' ? `1 / 2 · ${t('conn.wfStepAnalyze')}` : `2 / 2 · ${t('conn.wfStepConfirm')}`} - -

- -
- - {#if wfStep === 'input'} -

{t('conn.wfImportHint')}

-
- - - -
-
- - {wfParsed.valid - ? t('conn.wfNodes', { n: Object.keys(wfParsed.json ?? {}).length }) - : 'JSON'} - - -
- {:else if wfAnalysis} -

{t('conn.wfConfirmHint')}

- - {#if wfAnalysis.usage_problem} -
- -

{wfAnalysis.usage_problem}

-
- {/if} - {#if wfAnalyzeError} - - {/if} - - {#if wfConnCheck} -
-
- - {t('conn.wfCheckTitle')} - {#if wfConnCheck.endpoint_name} - {t('conn.wfCheckEndpoint', { name: wfConnCheck.endpoint_name })} - {/if} - -
- {#if !wfConnCheck.reachable} -

{wfConnCheck.message ?? t('conn.wfCheckUnreachable')}

- {:else if wfConnCheck.ok} -

{t('conn.wfCheckOk')}

- {:else} -
    - {#each wfConnCheck.findings as f (f.node_id + f.code)} -
  • - {f.message} - {#if f.hint}{f.hint}{/if} -
  • - {/each} -
-

{t('conn.wfCheckSaveHint')}

- {/if} -
- {/if} - -
    - {#each wfAnalysis.usage_evidence.summary as line (line)} -
  • {line}
  • - {/each} -
- -
- - {t('conn.wfUsageLabel')}* - - {#if wfAnalysis.usage} - {t('conn.wfUsageAuto', { usage: usageLabel(wfAnalysis.usage) })} - {:else} - {t('conn.wfUsageNeedPick')} - {/if} - - -
- {#each WORKFLOW_USAGES as u (u)} - - {/each} -
- {#if wfMustPick}{t('conn.wfPickUsage')}{/if} -
- - {#if wfOutputRows.length} -
- - {t('conn.wfOutputLabel')}* - {t('conn.wfOutputNeedPick')} - -
- {#each wfOutputRows as row (row.nodeId)} -
- - -
- {/each} -
- {t('conn.wfOutputHint')} - {#if wfOutputPickedCount === 0} - {t('conn.wfOutputPick')} - {/if} -
- {/if} - - {#if wfSlotRows.length} -
- {t('conn.wfSlotsLabel')} -
- {#each wfSlotRows as row (row.nodeId)} -
- {row.nodeId} - {row.label} - {#if row.fixed} - {t('wfRole.reference_image')} - {:else} - - {/if} -
- {/each} -
- {t('conn.wfSlotsHint')} -
- {/if} - -

- {t('conn.wfParams', { n: wfParamPreview.length })} - {#if wfParamPreview.length} - {wfParamPreview.slice(0, 8).join(' · ')}{wfParamPreview.length > 8 ? ' …' : ''} - {/if} -

- - {#if (wfAnalysis.warnings ?? []).length} -
    - {#each wfAnalysis.warnings as w (w.node_id + w.code)} -
  • {w.message}
  • - {/each} -
- {/if} - -
- - - {wfUsage - ? wfOutputCandidates.length && wfOutputPickedCount === 0 - ? t('conn.wfOutputPick') - : usageLabel(wfUsage) - : t('conn.wfUsageNeedPick')} - - -
- {/if} -
- {/if} - {#if ($workflowsQuery.data ?? []).length === 0}

{t('conn.missingMaterial')}

@@ -1592,6 +1104,11 @@ {/if} + client.invalidateQueries({ queryKey: ['workflows'] })} + /> + } diff --git a/e2e/fake_comfy.py b/e2e/fake_comfy.py index e61ab93e..2212b711 100644 --- a/e2e/fake_comfy.py +++ b/e2e/fake_comfy.py @@ -1,9 +1,16 @@ -"""Standalone fake ComfyUI for HEL-654 D-batch browser validation. +"""Standalone fake ComfyUI for HEL-654 D-batch / HEL-655 E-batch browser validation. -Mode file e2e/fake_mode.json: {"mode": "ok"|"fail", "delay_sec": 0} +Mode file e2e/fake_mode.json: +{"mode": "ok"|"fail", "delay_sec": 0, "videos": false, + "object_info": {class_type: {...}}, "no_outputs": false} - ok + delay 0: history is ready immediately (job completes fast) - ok + delay N: history appears N seconds after /prompt (progress state) - fail: /prompt returns 500 (job fails with a Chinese error from the worker) +- object_info: when present, /object_info serves this catalogue verbatim — + the E-batch script builds it from the workflow it imports so the L2 check + can be driven all-green (every class present) or missing-node (catalogue + omits classes). Absent → {} (every node "missing"). +- no_outputs: history entries complete with no files (test-run no-output pass) """ from __future__ import annotations import json, threading, uuid @@ -39,7 +46,7 @@ class Handler(BaseHTTPRequestHandler): "devices": [{"name": "FakeGPU", "type": "cuda"}]}) return if self.path == "/object_info": - self._json(200, {}) + self._json(200, read_mode().get("object_info") or {}) return if self.path == "/queue": # Prompts accepted but not yet in history: first one "running", @@ -74,11 +81,15 @@ class Handler(BaseHTTPRequestHandler): pid = uuid.uuid4().hex self.server.accepted.append(pid) videos = mode.get("videos") is True + no_outputs = mode.get("no_outputs") is True out_name = "out-1.mp4" if videos else "out-1.png" key = "videos" if videos else "images" + outputs = {} if no_outputs else { + self._output_node(body): {key: [{"filename": out_name, "subfolder": "", "type": "output"}]} + } entry = { "status": {"status_str": "success", "completed": True}, - "outputs": {self._output_node(body): {key: [{"filename": out_name, "subfolder": "", "type": "output"}]}}, + "outputs": outputs, "prompt": [], } delay = float(mode.get("delay_sec") or 0) diff --git a/e2e/import.mjs b/e2e/import.mjs new file mode 100644 index 00000000..8ab5837a --- /dev/null +++ b/e2e/import.mjs @@ -0,0 +1,588 @@ +/* HEL-655 E 批 browser validation against the isolated stack: + * vite dev (5173) → backend (8247) → fake ComfyUI (18188). + * Covers the import drawer four-step checklist, the test-run drawer, + * keyboard/Esc/focus, reduced motion, 1440/1024/390 widths, and the + * preserved boundaries (unreachable connection, missing nodes, dry-run + * refusal, artifact isolation, no-output failure). + * Prints PASS/FAIL per check; screenshots land in e2e/shots/hel655-*.png. */ +import { chromium } from "playwright"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = path.dirname(fileURLToPath(import.meta.url)); +const SHOTS = path.join(ROOT, "shots"); +fs.mkdirSync(SHOTS, { recursive: true }); + +const API = "http://127.0.0.1:8247"; +const MODE_FILE = path.join(ROOT, "fake_mode.json"); +const setMode = (m) => fs.writeFileSync(MODE_FILE, JSON.stringify(m)); +const baseMode = () => ({ mode: "ok", delay_sec: 0 }); + +let failures = 0; +function ok(name, cond, extra = "") { + const line = `${cond ? "PASS" : "FAIL"} ${name}${extra ? " — " + extra : ""}`; + console.log(line); + if (!cond) failures++; +} + +const api = async (p, init) => { + const r = await fetch(API + p, { + headers: { "Content-Type": "application/json" }, + ...init, + }); + const body = await r.text(); + try { + return JSON.parse(body); + } catch { + return { raw: body, status: r.status }; + } +}; + +/* ---------------- workflow fixtures ---------------- */ +const WF_NAME = `E批·文生图回归 ${Date.now() % 10000}`; +const T2I = { + 1: { + class_type: "CLIPTextEncode", + inputs: { text: "默认提示词" }, + _meta: { title: "(Input:prompt) 正向提示词" }, + }, + 9: { + class_type: "SaveImage", + inputs: { images: "x" }, + _meta: { title: "(Output:image) 图片输出" }, + }, +}; + +/** Self-consistent /object_info catalogue for a workflow (backend parity: + * every class present, every string widget a combo listing its value). */ +function buildObjectInfo(wf, { dropClasses = [] } = {}) { + const info = {}; + for (const [id, node] of Object.entries(wf)) { + const cls = node.class_type; + if (!cls || dropClasses.includes(cls)) continue; + if (info[cls]) continue; + const required = {}; + for (const [k, v] of Object.entries(node.inputs ?? {})) { + if (typeof v === "string") required[k] = [[v], {}]; + else if (typeof v === "number") + required[k] = Number.isInteger(v) + ? ["INT", { min: 0, max: 2 ** 31 }] + : ["FLOAT", { min: 0, max: 1e6 }]; + } + info[cls] = { input: { required }, output: ["IMAGE"] }; + } + return info; +} + +/* ---------------- stack prep ---------------- */ +const seeded = (async () => { + // one fake endpoint + one imported t2i workflow bound to it + for (const e of (await api("/api/comfyui/endpoints")).endpoints ?? []) { + if (e.base_url === "http://127.0.0.1:18188") + await api(`/api/comfyui/endpoints/${e.id}`, { method: "DELETE" }); + } + let r = await api("/api/comfyui/endpoints", { + method: "POST", + body: JSON.stringify({ + name: "假 ComfyUI", + base_url: "http://127.0.0.1:18188", + auth_type: "none", + }), + }); + const ep = r.endpoints.find((e) => e.base_url === "http://127.0.0.1:18188"); + await api(`/api/comfyui/endpoints/${ep.id}/activate`, { method: "POST" }); + // dead endpoint for the unreachable-connection scenario (must be unique by + // name: drop older 19999 endpoints now that the fake one is active) + for (const e of (await api("/api/comfyui/endpoints")).endpoints ?? []) { + if (e.base_url === "http://127.0.0.1:19999") + await api(`/api/comfyui/endpoints/${e.id}`, { method: "DELETE" }); + } + await api("/api/comfyui/endpoints", { + method: "POST", + body: JSON.stringify({ + name: "断开的连接", + base_url: "http://127.0.0.1:19999", + auth_type: "none", + }), + }); + return { endpointId: ep.id }; +})(); + +/* The connections page keeps its own add-connection side form open when the + * viewport shrinks below 1439 — close it so it doesn't cover the library. */ +async function closeSideFormIfOpen(page) { + const close = page.locator(".form-col.open .form-head .icon-btn"); + if ((await page.locator(".form-col.open").count()) === 0) return; + if ((await close.count()) > 0) { + await close.first().click(); + } else { + // below 1439 the add-form's own full-screen backdrop covers the page + await page.mouse.click(20, 400); + } + await page.waitForTimeout(250); +} + +const run = async () => { + const { endpointId } = await seeded; + const browser = await chromium.launch(); + const ctx = await browser.newContext({ + viewport: { width: 1440, height: 900 }, + }); + const page = await ctx.newPage(); + page.on("pageerror", (e) => console.log("PAGEERROR:", e.message)); + + await page.goto("http://127.0.0.1:5173/connections"); + await page.waitForSelector(".wf-panel", { timeout: 15000 }); + + // ---------- 1. 导入入口统一:按钮打开右侧抽屉 ---------- + await page + .getByRole("button", { name: /导入工作流/ }) + .first() + .click(); + await page.waitForSelector(".drawer-panel"); + const panel = page.locator(".drawer-panel"); + ok( + "导入抽屉从右侧滑入(挂载即向左滑动)", + await panel.evaluate((el) => { + const name = getComputedStyle(el).animationName; + return name.includes("drawer-slide") || name === "none"; + }), + ); + await page.waitForTimeout(360); // let the 280ms drawer settle + const box = await panel.boundingBox(); + ok("抽屉宽度 380px", Math.round(box.width) === 380, `w=${box.width}`); + ok("抽屉贴右缘", Math.abs(box.x + box.width - 1440) < 2, `x=${box.x}`); + await page.screenshot({ path: `${SHOTS}/hel655-01-import-input-1440.png` }); + + // ---------- 2. Step1:无效 JSON 的中文结论 ---------- + await page + .locator(".drawer-panel textarea.a-textarea") + .fill('{"不是":"API 格式"}'); + ok( + "无效 JSON 显示中文错误", + await page + .locator(".drawer-panel .field-error") + .textContent() + .then((s) => s.includes("API 格式")), + ); + ok( + "无效 JSON 时「分析」禁用", + await page.locator(".drawer-panel .a-btn.primary").isDisabled(), + ); + await page + .locator(".drawer-panel textarea.a-textarea") + .fill(JSON.stringify(T2I)); + await page.locator(".drawer-panel input.a-input").fill(WF_NAME); + await page + .locator(".drawer-panel select.a-select") + .selectOption({ label: "假 ComfyUI" }); + + // ---------- 3. 四步检查 · 全绿 ---------- + setMode({ ...baseMode(), object_info: buildObjectInfo(T2I) }); + await page.locator(".drawer-panel .a-btn.primary").click(); + await page.waitForSelector(".drawer-panel .checks .check"); + const t0 = Date.now(); + await page.waitForFunction( + () => + document.querySelectorAll(".drawer-panel .checks .check").length === 4, + ); + const spread = Date.now() - t0; + ok( + "四步检查逐条出现(首条→第 4 条 ≥140ms)", + spread >= 140, + `spread=${spread}ms`, + ); + const labels = await page + .locator(".drawer-panel .checks .check-label") + .allTextContents(); + ok( + "四步顺序:解析 JSON→识别节点→核对模型→建立输入槽", + labels[0].includes("解析") && + labels[1].includes("识别") && + labels[2].includes("核对") && + labels[3].includes("输入槽"), + labels.join("|"), + ); + const states = await page + .locator(".drawer-panel .checks .check") + .evaluateAll((els) => + els.map((el) => ({ + ok: el.className.includes("state-ok"), + color: getComputedStyle(el.querySelector(".mark")).color, + })), + ); + ok( + "① 解析 JSON 绿 ✓", + states[0].ok && states[0].color === "rgb(73, 203, 144)", + states[0].color, + ); + ok( + "② 识别节点判定文生图(绿)", + states[1].ok, + await page + .locator(".drawer-panel .checks .check") + .nth(1) + .locator(".check-line") + .textContent(), + ); + ok( + "③ 核对模型全绿(假 object_info 装齐)", + states[2].ok && states[2].color === "rgb(73, 203, 144)", + states[2].color, + ); + ok("④ 建立输入槽(1 参数 0 媒体)", states[3].ok); + await page.screenshot({ + path: `${SHOTS}/hel655-02-checks-allgreen-1440.png`, + }); + + // ---------- 4. 缺节点:③ 红 + 可展开错误 + 重试恢复 ---------- + setMode({ + ...baseMode(), + object_info: buildObjectInfo(T2I, { dropClasses: ["SaveImage"] }), + }); + await page + .locator(".drawer-panel .checks .check") + .nth(2) + .locator(".recheck") + .click(); + await page.waitForFunction(() => { + const el = document.querySelectorAll(".drawer-panel .checks .check")[2]; + return el && el.className.includes("state-fail"); + }); + const failLine = await page + .locator(".drawer-panel .checks .check") + .nth(2) + .locator(".check-line") + .textContent(); + ok("③ 缺节点显示中文问题数", /1/.test(failLine), failLine); + const finding = await page + .locator(".drawer-panel .findings li .finding-msg") + .first() + .textContent(); + ok( + "错误详情可展开且为中文原因", + finding.includes("缺少自定义节点"), + finding.slice(0, 40), + ); + ok( + "给出下一步建议", + ( + await page + .locator(".drawer-panel .checks .check .suggest") + .allTextContents() + ).some((s) => s.includes("重新检查")), + ); + ok( + "缺节点不阻断保存(沿用既有边界)", + !(await page.locator(".drawer-panel .a-btn.primary").last().isDisabled()), + ); + await page.screenshot({ path: `${SHOTS}/hel655-03-missing-node-1440.png` }); + setMode({ ...baseMode(), object_info: buildObjectInfo(T2I) }); + await page + .locator(".drawer-panel .checks .check") + .nth(2) + .locator(".recheck") + .click(); + await page.waitForFunction(() => { + const el = document.querySelectorAll(".drawer-panel .checks .check")[2]; + return el && el.className.includes("state-ok"); + }); + ok("「重新检查」复查后恢复绿", true); + + // ---------- 5. 断开的连接:琥珀「无法核查」,不伪装通过 ---------- + await page.locator(".drawer-panel .a-btn.secondary").first().click(); // 上一步 + await page + .locator(".drawer-panel select.a-select") + .selectOption({ label: "断开的连接" }); + await page.locator(".drawer-panel .a-btn.primary").click(); // 重新分析 + await page.waitForFunction( + () => + document.querySelectorAll(".drawer-panel .checks .check").length === 4, + ); + await page.waitForFunction(() => { + const el = document.querySelectorAll(".drawer-panel .checks .check")[2]; + return el && el.className.includes("state-warn"); + }); + const warnColor = await page + .locator(".drawer-panel .checks .check") + .nth(2) + .locator(".mark") + .evaluate((el) => getComputedStyle(el).color); + ok( + "无法核查 = 琥珀(非绿非红)", + warnColor === "rgb(240, 180, 92)", + warnColor, + ); + ok( + "无法核查给中文原因与建议", + ( + await page + .locator(".drawer-panel .checks .check") + .nth(2) + .locator(".check-line") + .textContent() + ).includes("无法核查"), + ); + await page.screenshot({ path: `${SHOTS}/hel655-04-unreachable-1440.png` }); + + // ---------- 6. 保存导入(回到可用连接) ---------- + await page.locator(".drawer-panel .a-btn.secondary").first().click(); // 上一步 + await page + .locator(".drawer-panel select.a-select") + .selectOption({ label: "假 ComfyUI" }); + await page.locator(".drawer-panel .a-btn.primary").click(); // 分析 + await page.waitForFunction( + () => + document.querySelectorAll(".drawer-panel .checks .check").length === 4, + ); + await page.locator(".drawer-panel .a-btn.primary").last().click(); // 确认保存 + await page.waitForSelector(".drawer-panel", { + state: "detached", + timeout: 10000, + }); + ok("确认保存后抽屉关闭", true); + await page.waitForFunction( + (n) => document.body.textContent.includes(n), + WF_NAME, + ); + ok("工作流入库名称正确", true); + + // ---------- 7. 试运行抽屉:全链路(进行中→完成→隔离) ---------- + const wfId = (await api("/api/workflows")).find( + (w) => w.name === WF_NAME, + )?.id; + ok("已导入工作流可查询", !!wfId); + const row = page.locator(".wf-row", { hasText: WF_NAME }); + await row.locator(".wf-test-btn").first().click(); + await page.waitForSelector(".drawer-panel"); + const tbox = await page.locator(".drawer-panel").boundingBox(); + ok( + "试运行抽屉 420px 右侧", + Math.round(tbox.width) === 420, + `w=${tbox.width}`, + ); + await page.screenshot({ path: `${SHOTS}/hel655-05-test-form-1440.png` }); + + // dry_run 拒绝(边界保留) + await api("/api/settings", { + method: "POST", + body: JSON.stringify({ dry_run: true }), + }); + await page.locator(".drawer-panel .a-btn.primary").click(); + await page.locator(".modal-panel .modal-footer .a-btn.primary").click(); + await page.waitForFunction(() => { + const els = [...document.querySelectorAll(".drawer-panel .field-error")]; + return els.some((e) => e.textContent.includes("Dry-run")); + }); + ok("dry_run 下试运行被拒绝(中文原因)", true); + await api("/api/settings", { + method: "POST", + body: JSON.stringify({ dry_run: false }), + }); + + // 真实试运行:进行中(青进度 + 阶段日志)→ 通过(绿 + 缩略图横排) + setMode({ mode: "ok", delay_sec: 3, object_info: buildObjectInfo(T2I) }); + await page.locator(".drawer-panel .a-btn.primary").click(); + await page.locator(".modal-panel .modal-footer .a-btn.primary").click(); + await page.waitForSelector(".drawer-panel .wft-active", { timeout: 8000 }); + await page.waitForSelector(".drawer-panel .wft-active .chip.run", { + timeout: 8000, + }); + const chipColor = await page + .locator(".drawer-panel .wft-active .chip.run") + .evaluate((el) => getComputedStyle(el).color); + ok("进行中状态为信号青", chipColor === "rgb(84, 223, 210)", chipColor); + ok( + "进行中显示进度条", + (await page.locator(".drawer-panel .wft-active .track").count()) === 1, + ); + await page.waitForSelector(".drawer-panel .wft-log p", { timeout: 6000 }); + const logText = await page.locator(".drawer-panel .wft-log").textContent(); + ok( + "阶段日志为中文滚动区", + /队列|排队|连接|运行|保存|执行|ComfyUI/.test(logText), + logText.slice(0, 30), + ); + ok( + "阶段日志为 mono 字体", + await page + .locator(".drawer-panel .wft-log") + .evaluate((el) => getComputedStyle(el).fontFamily.includes("Mono")), + ); + await page.screenshot({ path: `${SHOTS}/hel655-06-test-running-1440.png` }); + await page.waitForSelector(".drawer-panel .wft-result.ok", { + timeout: 30000, + }); + const verdict = await page + .locator(".drawer-panel .wft-verdict") + .textContent(); + ok("只有真实输出才算通过(绿判定)", verdict.includes("测试通过"), verdict); + const thumbs = await page + .locator(".drawer-panel .wft-outputs .wft-out") + .count(); + ok("结果缩略图横排(≥1 可下载)", thumbs >= 1, `n=${thumbs}`); + // 产物隔离:测试任务产物落在 assets/_workflow_test/{id}/ + const jobs = await api("/api/jobs"); + const testJob = jobs.find( + (j) => + j.workflow_id === wfId && + j.status === "done" && + (j.output_paths ?? []).length, + ); + ok( + "试运行产物与普通素材隔离(_workflow_test/)", + !!testJob && (testJob.output_paths ?? [])[0].includes("_workflow_test"), + testJob?.output_paths?.[0], + ); + await page.screenshot({ path: `${SHOTS}/hel655-07-test-passed-1440.png` }); + + // ---------- 8. 失败路径:执行报错 红 + 中文 ---------- + setMode({ mode: "fail" }); + await page.waitForSelector(".drawer-panel .wft-form", { timeout: 10000 }); + await page.locator(".drawer-panel .a-btn.primary").click(); + await page.locator(".modal-panel .modal-footer .a-btn.primary").click(); + await page.waitForSelector(".drawer-panel .wft-result.bad", { + timeout: 30000, + }); + const badColor = await page + .locator(".drawer-panel .wft-result.bad .wft-verdict") + .evaluate((el) => getComputedStyle(el).color); + ok( + "失败判定为红 + 中文标题", + badColor === "rgb(240, 100, 90)", + await page + .locator(".drawer-panel .wft-result.bad .wft-verdict") + .textContent(), + ); + ok( + "失败给出具体原因", + ((await page.locator(".drawer-panel .wft-error").textContent()) ?? "") + .length > 0, + ); + await page.screenshot({ path: `${SHOTS}/hel655-08-test-failed-1440.png` }); + + // ---------- 9. 无输出:不算通过 ---------- + setMode({ mode: "ok", delay_sec: 0, no_outputs: true }); + await page.waitForSelector(".drawer-panel .wft-form", { timeout: 10000 }); + await page.locator(".drawer-panel .a-btn.primary").click(); + await page.locator(".modal-panel .modal-footer .a-btn.primary").click(); + await page.waitForFunction( + () => { + const bad = document.querySelector(".drawer-panel .wft-result.bad"); + if (!bad) return false; + // the previous fail verdict also matches .bad — wait until the error text changes + return ( + !bad.textContent.includes("boom") || bad.textContent.includes("输出") + ); + }, + { timeout: 30000 }, + ); + ok("无输出不判通过(红/失败结论)", true); + setMode({ ...baseMode() }); + + // ---------- 10. 键盘:Esc 关闭、焦点圈、焦点回归 ---------- + await page.keyboard.press("Escape"); + await page.waitForSelector(".drawer-panel", { state: "detached" }); + ok("Esc 关闭试运行抽屉", true); + await row.locator(".wf-test-btn").first().click(); + await page.waitForSelector(".drawer-panel"); + await page.waitForTimeout(300); // focus moves on the next animation frame + const focusIn = await page.evaluate( + () => document.activeElement.closest(".drawer-panel") !== null, + ); + ok("抽屉打开后焦点进入面板", focusIn); + for (let i = 0; i < 12; i++) await page.keyboard.press("Tab"); + const stillIn = await page.evaluate( + () => document.activeElement.closest(".drawer-panel") !== null, + ); + ok("Tab 在抽屉内循环(焦点不逃逸)", stillIn); + await page.keyboard.press("Escape"); + await page.waitForSelector(".drawer-panel", { state: "detached" }); + const backOnBtn = await page.evaluate( + () => + document.activeElement?.getAttribute("title") === "测试工作流" || + (document.activeElement?.textContent ?? "").trim().startsWith("测试"), + ); + ok("关闭后焦点回到触发按钮", backOnBtn === true); + + // ---------- 11. 减少动态效果:抽屉只留透明度 ---------- + await page.evaluate(() => (document.documentElement.dataset.reduce = "1")); + await page + .getByRole("button", { name: /导入工作流/ }) + .first() + .click(); + await page.waitForSelector(".drawer-panel"); + const anim = await page + .locator(".drawer-panel") + .evaluate((el) => getComputedStyle(el).animationName); + ok("减动效时抽屉无位移动画(仅淡变)", anim.includes("drawer-fade"), anim); + await page.keyboard.press("Escape"); + await page.evaluate(() => delete document.documentElement.dataset.reduce); + + // ---------- 12. 中屏 1024 / 窄屏 390 ---------- + await page.setViewportSize({ width: 1024, height: 768 }); + await closeSideFormIfOpen(page); + await page + .getByRole("button", { name: /导入工作流/ }) + .first() + .click(); + await page.waitForSelector(".drawer-panel"); + await page.waitForTimeout(320); + const mid = await page.locator(".drawer-panel").boundingBox(); + ok( + "中屏抽屉仍 380px 贴右", + Math.round(mid.width) === 380 && Math.abs(mid.x + mid.width - 1024) < 2, + ); + await page.screenshot({ path: `${SHOTS}/hel655-09-import-1024.png` }); + await page.keyboard.press("Escape"); + + await page.setViewportSize({ width: 390, height: 844 }); + await closeSideFormIfOpen(page); + await page + .getByRole("button", { name: /导入工作流/ }) + .first() + .click(); + await page.waitForSelector(".drawer-panel"); + await page.waitForTimeout(320); + const narrow = await page.locator(".drawer-panel").boundingBox(); + ok("窄屏抽屉全屏宽", Math.round(narrow.width) === 390, `w=${narrow.width}`); + const overflow = await page.evaluate( + () => + document.scrollingElement.scrollWidth - + document.scrollingElement.clientWidth, + ); + ok("窄屏无横向溢出", overflow <= 0, `overflow=${overflow}px`); + await page.screenshot({ path: `${SHOTS}/hel655-10-import-390.png` }); + await page.keyboard.press("Escape"); + await page.waitForSelector(".drawer-panel", { state: "detached" }); + await page.setViewportSize({ width: 1440, height: 900 }); + + // ---------- 13. 试运行历史与清除 ---------- + await row.locator(".wf-test-btn").first().click(); + await page.waitForSelector(".drawer-panel"); + await page.waitForSelector(".drawer-panel .wft-rows li", { timeout: 8000 }); + const histCount = await page.locator(".drawer-panel .wft-rows li").count(); + ok("测试记录列表保留", histCount >= 2, `n=${histCount}`); + await page.locator(".drawer-panel .link-danger").click(); + await page.waitForFunction( + () => document.querySelectorAll(".drawer-panel .wft-rows li").length === 0, + { timeout: 8000 }, + ); + ok("清除测试记录生效", true); + await page.keyboard.press("Escape"); + + await browser.close(); + console.log(failures === 0 ? "\nALL PASS" : `\n${failures} FAILURES`); + process.exit(failures === 0 ? 0 : 1); +}; + +run().catch(async (e) => { + console.error("FATAL", e?.message?.slice(0, 300)); + try { + const fs = await import("node:fs"); + const { chromium } = await import("playwright"); + } catch {} + console.error("FATAL", e); + process.exit(1); +});