Files
aigc-home/calliope-web/src/lib/components/WorkflowTestDialog.svelte
T

828 lines
22 KiB
Svelte
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<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 Drawer from '$lib/components/ui/Drawer.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import ProgressBar from '$lib/components/ui/ProgressBar.svelte';
import SafeMedia from '$lib/components/SafeMedia.svelte';
import { mediaFileProblem, type MediaSlotKind } from '$lib/comfy/imageFile';
import { jobStatusInfo } from '$lib/jobStatus';
import { progressFor } from '$lib/jobProgress';
import { toast } from '$lib/toast';
import { t } from '$lib/i18n.svelte';
/**
* 测试工作流 (HEL-643 L3, E 批抽屉化): 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. Presentation follows HEL-649 §3.8: right-side drawer,
* cyan progress + mono stage log while running, result thumbnails in a
* horizontal row.
*/
interface Props {
open?: boolean;
workflow: Workflow | null;
endpoints: ComfyEndpoint[];
onchanged?: () => void;
}
let {
open = $bindable(false),
workflow,
endpoints,
onchanged,
}: Props = $props();
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);
let errorExpanded = $state(false);
let logBox = $state<HTMLDivElement | 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);
const liveProgress = $derived(
activeJob ? progressFor(activeJob.id) : undefined,
);
const activeInfo = $derived(activeJob ? jobStatusInfo(activeJob) : null);
// Rolling mono stage log (§3.8): one line per distinct worker message.
let stageLog = $state<string[]>([]);
$effect(() => {
if (!activeJob || !activeInfo) {
stageLog = [];
return;
}
const line = liveProgress?.message || activeInfo.detail;
if (!line) return;
if (stageLog[stageLog.length - 1] !== line) stageLog = [...stageLog, line];
});
$effect(() => {
void stageLog.length;
if (logBox) logBox.scrollTop = logBox.scrollHeight;
});
$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 = '';
errorExpanded = false;
stageLog = [];
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>
<Drawer bind:open title={t('wft.title')} width={420}>
{#if wf}
<div class="wft">
<p class="wft-sub">
{wf.name}
<span class="mono wft-id">#{wf.id}</span>
</p>
<label class="field">
<span class="field-label">{t('wft.connection')}</span>
<select
class="a-select full"
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="field-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 && activeInfo}
<div class="wft-active">
<div class="wft-active-head">
<span class="chip run">
<span class="chip-dot" aria-hidden="true"></span>
{t('wft.running')}
</span>
<span class="wft-active-detail">{activeInfo.detail}</span>
<Button variant="secondary" size="sm" onclick={cancelTest}
>{t('wft.cancel')}</Button
>
</div>
<ProgressBar
value={liveProgress?.progress ?? 0}
indeterminate={activeJob.status === 'pending' && !liveProgress}
label={activeInfo.label}
/>
{#if stageLog.length}
<div class="wft-log mono" bind:this={logBox} aria-live="polite">
{#each stageLog as line, i (i)}
<p>{line}</p>
{/each}
</div>
{/if}
</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 as path (path)}
<a
class="wft-out"
href={assetUrl(path)}
download
target="_blank"
rel="noreferrer external"
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')
: errorExpanded || (finishedJob.error ?? '').length <= 160
? finishedJob.error
: (finishedJob.error ?? '').slice(0, 160) + '…'}
</p>
{#if finishedJob.error && finishedJob.error !== 'cancelled' && finishedJob.error.length > 160}
<button
type="button"
class="wft-expand"
onclick={() => (errorExpanded = !errorExpanded)}
>
{errorExpanded ? t('wfd.hideDetails') : t('wfd.showDetails')}
</button>
{/if}
</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}
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="field-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="field-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}
</Drawer>
<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;
}
.a-select.full {
width: 100%;
}
.wft-note {
display: flex;
gap: 8px;
align-items: flex-start;
padding: 8px 10px;
border: 1px solid var(--run-soft);
border-radius: var(--r-sm);
background: var(--run-soft);
color: var(--text-2);
font-size: 12px;
line-height: 1.6;
}
.wft-note :global(.icon) {
color: var(--run);
flex-shrink: 0;
margin-top: 2px;
}
.wft-note p {
margin: 0;
}
.wft-active,
.wft-result {
border: 1px solid var(--line-2);
border-radius: var(--r-md);
padding: 10px 12px;
background: var(--bg-2);
display: flex;
flex-direction: column;
gap: 8px;
}
.wft-active {
border-color: var(--run-soft);
}
.wft-active-head {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.chip {
display: inline-flex;
align-items: center;
gap: 6px;
height: 20px;
padding: 0 8px;
border-radius: var(--r-sm);
font-size: 12px;
font-weight: 600;
}
.chip.run {
color: var(--run);
background: var(--run-soft);
}
.chip-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--run);
animation: wft-breathe 1.6s ease-in-out infinite;
}
@keyframes wft-breathe {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.35;
}
}
:global([data-reduce='1']) .chip-dot {
animation: none;
}
@media (prefers-reduced-motion: reduce) {
.chip-dot {
animation: none;
}
}
.wft-active-detail {
flex: 1;
min-width: 120px;
font-size: 12px;
color: var(--text-2);
}
.wft-log {
max-height: 110px;
overflow-y: auto;
padding: 8px 10px;
border-radius: var(--r-sm);
background: var(--bg);
border: 1px solid var(--line);
font-size: 12px;
line-height: 1.6;
color: var(--text-2);
}
.wft-log p {
margin: 0;
}
.wft-result.ok {
border-color: var(--ok);
}
.wft-result.bad {
border-color: var(--err);
}
.wft-verdict {
margin: 0;
font-size: 13px;
font-weight: 600;
color: var(--text);
}
.wft-result.ok .wft-verdict {
color: var(--ok);
}
.wft-result.bad .wft-verdict {
color: var(--err);
}
.wft-error {
margin: 0;
font-size: 12px;
color: var(--err);
line-height: 1.6;
word-break: break-all;
}
.wft-expand {
align-self: flex-start;
background: none;
border: none;
padding: 0;
font-family: inherit;
font-size: 11px;
color: var(--text-2);
text-decoration: underline;
cursor: pointer;
}
@media (hover: hover) and (pointer: fine) {
.wft-expand:hover {
color: var(--text);
}
}
.wft-outputs {
display: flex;
gap: 8px;
overflow-x: auto;
padding-bottom: 2px;
}
.wft-out {
display: block;
flex: 0 0 auto;
width: 148px;
border: 1px solid var(--line);
border-radius: var(--r-sm);
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(--line);
padding-top: 10px;
}
.wft-history-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.wft-history-head .field-label {
margin-bottom: 0;
}
.link-danger {
background: none;
border: none;
padding: 4px 8px;
font-family: inherit;
font-size: 12px;
color: var(--err);
cursor: pointer;
border-radius: var(--r-sm);
opacity: 0.85;
display: inline-flex;
align-items: center;
}
@media (hover: hover) and (pointer: fine) {
.link-danger:hover {
opacity: 1;
background: var(--err-soft);
}
}
.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: var(--r-sm);
}
.wft-rows li.active {
background: var(--bg-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(--ok);
}
</style>