feat(workflows): import preflight, real test runs and media groups (HEL-643)

- L2 连接核查: /object_info preflight (node existence + combo values) with
  5-min cache + manual refresh; analyze accepts endpoint_id, saved workflows
  get POST /{id}/check; unreachable degrades to 无法核查, never blocks saving
- 测试工作流: jobs.origin='workflow_test' rides the real queue → ComfyUI →
  outputs pipeline; only a downloadable, correctly-typed output counts as a
  pass; dry-run refused; repeat clicks reuse the in-flight job; artifacts
  isolated under assets/_workflow_test/{id}; retention keeps newest 5;
  clear-tests + delete-workflow cascade cleanup; tasks page shows a 测试 badge
- Media groups: Autogrow detection generalized to video/audio lists
  (ref_videos/ref_audios etc.), patcher clones/rewires per media family,
  validation per list kind; entries appear only for actually-wired slots;
  MiniMax H3 Ref2VA official-limit hints keyed off the node class
- 25 new backend tests (preflight / workflow-test / media-groups) against the
  fake ComfyUI; fake server gains /object_info + drop_outputs knobs

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
总工
2026-09-29 19:07:20 +08:00
co-authored by multica-agent
parent 319c7b049b
commit 2ed9d25c24
32 changed files with 3220 additions and 198 deletions
@@ -0,0 +1,579 @@
<script lang="ts">
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { toStore } from 'svelte/store';
import {
apiErrorMessage,
assetUrl,
playgroundApi,
jobsApi,
workflows,
type ComfyEndpoint,
type Job,
type Workflow,
} from '$lib/api';
import ComfyDynamicForm from '$lib/components/ComfyDynamicForm.svelte';
import RefImageGrid from '$lib/components/studio/RefImageGrid.svelte';
import Button from '$lib/components/ui/Button.svelte';
import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import Modal from '$lib/components/ui/Modal.svelte';
import SafeMedia from '$lib/components/SafeMedia.svelte';
import { mediaFileProblem, type MediaSlotKind } from '$lib/comfy/imageFile';
import { jobStatusInfo } from '$lib/jobStatus';
import { toast } from '$lib/toast';
import { t } from '$lib/i18n.svelte';
/**
* 测试工作流 (HEL-643 L3): fill the workflow's REAL input slots, submit
* one REAL run to the chosen ComfyUI through the ordinary job queue, and
* call it a pass only when at least one downloadable output of the right
* media kind came back. Test artifacts are isolated from projects.
*/
interface Props {
open?: boolean;
workflow: Workflow | null;
endpoints: ComfyEndpoint[];
onchanged?: () => void;
}
let { open = $bindable(false), workflow, endpoints, onchanged }: Props = $props();
const client = useQueryClient();
let endpointId = $state('');
let values = $state<Record<string, string | number>>({});
let listValues = $state<Record<string, string[]>>({});
let sizes = $state<Record<string, number>>({});
let uploadingName = $state<Record<string, string>>({});
let rejects = $state<Record<string, { name: string; message: string }[]>>({});
let submitError = $state('');
let confirmOpen = $state(false);
let submitting = $state(false);
let testJobId = $state<number | null>(null);
const wf = $derived(workflow);
const schema = $derived(wf?.input_schema ?? []);
const listEntries = $derived(
schema.filter((i) => i.kind === 'image_list' || i.kind === 'video_list' || i.kind === 'audio_list'),
);
const formEntries = $derived(
schema.filter((i) => i.kind !== 'image_list' && i.kind !== 'video_list' && i.kind !== 'audio_list'),
);
const hasH3Hint = $derived(
listEntries.some((e) => e.media_hint === 'minimax_h3_ref2va'),
);
const outputKind = $derived<'image' | 'video'>(wf?.kind === 'video' ? 'video' : 'image');
const testsQuery = createQuery(
toStore(() => ({
queryKey: ['workflow-tests', wf?.id ?? 0],
queryFn: () => workflows.tests(wf!.id),
enabled: !!wf && open,
refetchInterval: 2000,
})),
);
const jobsQuery = createQuery(
toStore(() => ({
queryKey: ['jobs'],
queryFn: () => jobsApi.list(),
enabled: !!wf && open,
refetchInterval: 5000,
})),
);
const queuedCount = $derived(
($jobsQuery.data ?? []).filter((j) => j.status === 'pending' || j.status === 'running')
.length,
);
const history = $derived(($testsQuery.data ?? []) as Job[]);
const activeJob = $derived.by(() => {
if (testJobId != null) {
const mine = history.find((j) => j.id === testJobId);
if (mine && (mine.status === 'pending' || mine.status === 'running')) return mine;
}
return history.find((j) => j.status === 'pending' || j.status === 'running') ?? null;
});
const finishedJob = $derived.by(() => {
if (testJobId != null) return history.find((j) => j.id === testJobId) ?? null;
return null;
});
const queueBusy = $derived(!!activeJob || submitting);
$effect(() => {
if (!open || !wf) return;
endpointId = wf.endpoint_id ?? '';
values = Object.fromEntries(
schema
.filter((i) => i.defaultValue !== undefined && i.defaultValue !== null)
.map((i) => [i.nodeId, i.defaultValue as string | number]),
);
listValues = {};
sizes = {};
rejects = {};
uploadingName = {};
submitError = '';
testJobId = wf.last_test && (wf.last_test.status === 'pending' || wf.last_test.status === 'running')
? wf.last_test.id
: null;
});
function kindOf(entry: { kind: string }): MediaSlotKind {
if (entry.kind === 'video_list') return 'video';
if (entry.kind === 'audio_list') return 'audio';
return 'image';
}
function unitOf(kind: MediaSlotKind): string {
return kind === 'image' ? '张' : '段';
}
function setRejects(key: string, next: { name: string; message: string }[]) {
rejects = { ...rejects, [key]: next };
}
async function uploadOne(file: File): Promise<string | null> {
const res = await playgroundApi.upload(file);
sizes = { ...sizes, [res.path]: file.size };
return res.path;
}
async function mediaAdd(entry: (typeof listEntries)[number], files: File[]) {
const kind = kindOf(entry);
const key = entry.nodeId;
const max = entry.max ?? 9;
const current = listValues[key] ?? [];
const ok: string[] = [];
const bad: { name: string; message: string }[] = [];
for (const f of files) {
const problem = mediaFileProblem(kind, f);
if (problem) bad.push({ name: f.name, message: problem });
else ok.push(f.name);
}
if (current.length + ok.length > max) {
toast.error(
t('studio.errRefMax', { max, n: current.length, k: ok.length }),
);
if (bad.length) setRejects(key, [...(rejects[key] ?? []), ...bad]);
return;
}
setRejects(key, [...(rejects[key] ?? []), ...bad]);
for (const f of files) {
if (!ok.includes(f.name)) continue;
uploadingName = { ...uploadingName, [key]: f.name };
try {
const path = await uploadOne(f);
if (path) listValues = { ...listValues, [key]: [...(listValues[key] ?? []), path] };
} catch (err) {
toast.error(apiErrorMessage(err));
} finally {
uploadingName = { ...uploadingName, [key]: '' };
}
}
}
async function mediaReplace(entry: (typeof listEntries)[number], index: number, file: File) {
const kind = kindOf(entry);
const key = entry.nodeId;
const problem = mediaFileProblem(kind, file);
if (problem) {
setRejects(key, [...(rejects[key] ?? []), { name: file.name, message: problem }]);
return;
}
uploadingName = { ...uploadingName, [key]: file.name };
try {
const path = await uploadOne(file);
if (path) {
const next = [...(listValues[key] ?? [])];
next[index] = path;
listValues = { ...listValues, [key]: next };
}
} catch (err) {
toast.error(apiErrorMessage(err));
} finally {
uploadingName = { ...uploadingName, [key]: '' };
}
}
function mediaRemove(entry: (typeof listEntries)[number], index: number) {
const key = entry.nodeId;
listValues = { ...listValues, [key]: (listValues[key] ?? []).filter((_, i) => i !== index) };
}
/** Mirrors the backend's validate_input_values for immediate feedback. */
function validate(): string[] {
const errs: string[] = [];
for (const e of schema) {
const label = e.label;
if (e.kind === 'image_list' || e.kind === 'video_list' || e.kind === 'audio_list') {
const n = (listValues[e.nodeId] ?? []).length;
const unit = unitOf(kindOf(e));
if (e.required && n < (e.min ?? 1)) errs.push(t('wft.errListMin', { n: e.min ?? 1, unit, label }));
} else if (e.auto && e.required && e.role === 'prompt') {
const v = values[e.nodeId];
if (!(typeof v === 'string' && v.trim()) && !String(e.defaultValue ?? '').trim()) {
errs.push(t('wft.errRequired', { label }));
}
} else if (e.required && (e.kind === 'image' || e.kind === 'video' || e.kind === 'audio') && e.role !== 'mask') {
if (!values[e.nodeId]) errs.push(t('wft.errRequired', { label }));
}
}
return errs;
}
async function submitTest() {
if (!wf) return;
const errs = validate();
if (errs.length) {
submitError = errs.join(';');
return;
}
submitError = '';
confirmOpen = true;
}
async function reallyRunTest() {
if (!wf) return;
submitting = true;
try {
const inputValues: Record<string, unknown> = { ...values };
for (const [k, v] of Object.entries(listValues)) {
if (v.length) inputValues[k] = v;
}
const res = await workflows.test(wf.id, {
...(endpointId ? { endpoint_id: endpointId } : {}),
input_values: inputValues as Record<string, string | number | string[]>,
});
testJobId = res.job.id;
if (res.reused) toast.info(t('wft.reusedToast'));
void $testsQuery.refetch();
} catch (err) {
submitError = apiErrorMessage(err);
} finally {
submitting = false;
confirmOpen = false;
}
}
async function cancelTest() {
if (!activeJob) return;
try {
await jobsApi.cancel(activeJob.id);
void $testsQuery.refetch();
} catch (err) {
toast.error(apiErrorMessage(err));
}
}
async function clearRecords() {
if (!wf) return;
try {
await workflows.clearTests(wf.id);
testJobId = null;
await $testsQuery.refetch();
onchanged?.();
toast.success(t('wft.cleared'));
} catch (err) {
toast.error(apiErrorMessage(err));
}
}
function resultLine(job: Job): string {
if (job.status === 'done' && (job.output_paths?.length ?? 0) > 0) {
return t('wft.passedShort', { n: job.output_paths.length });
}
if (job.error === 'cancelled') return t('wft.cancelledShort');
return job.error ? job.error.slice(0, 120) : t('wft.failedShort');
}
function timeOf(at: string | null): string {
if (!at) return '—';
const ts = Date.parse(at.replace(' ', 'T') + 'Z');
const d = new Date(Number.isFinite(ts) ? ts : at);
const p = (n: number) => String(n).padStart(2, '0');
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
}
const endpointLabel = $derived(
endpoints.find((e) => e.id === endpointId)?.name ?? t('conn.wfConnectionActive'),
);
</script>
<Modal bind:open title={t('wft.title')} size="lg">
{#if wf}
<div class="wft">
<p class="wft-sub">
{wf.name}
<span class="mono wft-id">#{wf.id}</span>
</p>
<label class="f-field">
<span class="f-label">{t('wft.connection')}</span>
<select class="f-input" bind:value={endpointId} disabled={queueBusy}>
<option value="">{t('conn.wfConnectionActive')}</option>
{#each endpoints as ep (ep.id)}
<option value={ep.id}>{ep.name}</option>
{/each}
</select>
<span class="f-hint">{t('wft.costNote')}</span>
</label>
{#if hasH3Hint}
<div class="wft-note" role="note">
<Icon name="info" size={14} />
<p>{t('wfMedia.h3Limits')}</p>
</div>
{/if}
{#if activeJob}
{@const info = jobStatusInfo(activeJob)}
<div class="wft-active" class:ok={activeJob.status === 'done'} class:bad={activeJob.status === 'failed'}>
<div class="wft-active-head">
<span class="status-chip">{t('wft.running')}</span>
<span class="wft-active-detail">{info.detail}</span>
<Button variant="secondary" size="sm" onclick={cancelTest}>{t('wft.cancel')}</Button>
</div>
</div>
{:else if finishedJob && finishedJob.status === 'done' && (finishedJob.output_paths?.length ?? 0) > 0}
<div class="wft-result ok">
<p class="wft-verdict">{t('wft.passed', { n: finishedJob.output_paths.length })}</p>
<div class="wft-outputs">
{#each finishedJob.output_paths.slice(0, 4) as path (path)}
<a
class="wft-out"
href={assetUrl(path)}
download
target="_blank"
rel="noreferrer"
title={t('wft.download')}
>
<SafeMedia kind={outputKind} src={assetUrl(path)} controls={outputKind === 'video'} />
</a>
{/each}
</div>
</div>
{:else if finishedJob && finishedJob.status !== 'pending' && finishedJob.status !== 'running'}
<div class="wft-result bad">
<p class="wft-verdict">{t('wft.failed')}</p>
<p class="wft-error">{finishedJob.error === 'cancelled' ? t('wft.cancelledShort') : finishedJob.error}</p>
</div>
{/if}
{#if !queueBusy}
<div class="wft-form">
{#each listEntries as entry (entry.nodeId)}
{@const kind = kindOf(entry)}
<RefImageGrid
label={entry.label}
mediaKind={kind}
paths={listValues[entry.nodeId] ?? []}
max={entry.max ?? 9}
sizes={sizes}
uploadingName={uploadingName[entry.nodeId] || undefined}
rejects={rejects[entry.nodeId] ?? []}
onAdd={(files) => 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}
<ComfyDynamicForm inputs={formEntries} bind:values allowUpload showErrors={!!submitError} />
{/if}
</div>
{#if submitError}<span class="f-error" role="alert">{submitError}</span>{/if}
<div class="wft-actions">
<Button variant="primary" loading={submitting} onclick={submitTest}>
{t('wft.submit')}
</Button>
</div>
{/if}
<div class="wft-history">
<div class="wft-history-head">
<span class="f-label">{t('wft.history', { n: history.length })}</span>
{#if history.length}
<button type="button" class="link-danger" onclick={clearRecords}>
{t('wft.clear')}
</button>
{/if}
</div>
{#if history.length === 0}
<p class="wft-empty">{t('wft.never')}</p>
{:else}
<ul class="wft-rows">
{#each history as job (job.id)}
<li class:active={job.id === activeJob?.id}>
<span class="mono wft-row-id">#{job.id}</span>
<span class="wft-row-time">{timeOf(job.created_at)}</span>
<span class="wft-row-result" class:ok={job.status === 'done' && (job.output_paths?.length ?? 0) > 0}>
{resultLine(job)}
</span>
</li>
{/each}
</ul>
{/if}
</div>
</div>
{/if}
</Modal>
<ConfirmDialog
bind:open={confirmOpen}
title={t('wft.confirmTitle')}
message={t('wft.confirmBody', { endpoint: endpointLabel, n: queuedCount })}
confirmLabel={t('wft.submit')}
onconfirm={reallyRunTest}
/>
<style>
.wft {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
}
.wft-sub {
margin: 0;
font-size: 13px;
color: var(--text-2);
}
.wft-id {
color: var(--text-3);
font-size: 11px;
margin-left: 6px;
}
.wft-note {
display: flex;
gap: 8px;
align-items: flex-start;
padding: 8px 10px;
border: 1px solid var(--info, #3b82f6);
border-radius: 8px;
background: var(--surface-2);
color: var(--text-2);
font-size: 12px;
line-height: 1.6;
}
.wft-note p {
margin: 0;
}
.wft-active,
.wft-result {
border: 1px solid var(--border-strong);
border-radius: 8px;
padding: 10px 12px;
background: var(--surface-2);
}
.wft-active-head {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.wft-active-detail {
flex: 1;
min-width: 160px;
font-size: 12px;
color: var(--text-2);
}
.wft-result.ok {
border-color: var(--success);
}
.wft-result.bad {
border-color: var(--error);
}
.wft-verdict {
margin: 0 0 8px;
font-size: 13px;
font-weight: 600;
color: var(--text);
}
.wft-result.ok .wft-verdict {
color: var(--success);
}
.wft-error {
margin: 0;
font-size: 12px;
color: var(--error);
line-height: 1.6;
word-break: break-all;
}
.wft-outputs {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 8px;
}
.wft-out {
display: block;
border: 1px solid var(--border);
border-radius: 8px;
overflow: hidden;
background: var(--bg);
}
.wft-form {
display: flex;
flex-direction: column;
gap: 14px;
}
.wft-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.wft-history {
border-top: 1px solid var(--border);
padding-top: 10px;
}
.wft-history-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.wft-empty {
margin: 6px 0 0;
font-size: 12px;
color: var(--text-3);
}
.wft-rows {
list-style: none;
margin: 6px 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
.wft-rows li {
display: flex;
gap: 10px;
align-items: baseline;
font-size: 12px;
color: var(--text-2);
padding: 4px 6px;
border-radius: 6px;
}
.wft-rows li.active {
background: var(--surface-3);
}
.wft-row-id {
color: var(--text-3);
font-size: 11px;
}
.wft-row-time {
color: var(--text-3);
font-size: 11px;
white-space: nowrap;
}
.wft-row-result {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wft-row-result.ok {
color: var(--success);
}
</style>