- 点选金框滑动 + 检视区 150ms 交叉淡变;↑↓/J/K 即时切换、空格播放、 Delete 删除、] 检视区、浮层让位;新记录入场/完成金光/失败抖动,减动效只余短淡变 - 单条删除 5 秒撤销(Toast 金色动作钮),窗口过后才提交 DELETE,离页 flush; 任务页同队列同步;工作流删除保留旧记录并标识「工作流已删除」 - 红/琥珀界线:失败红 + 中文结论展开;done 但文件取不到 → 琥珀「文件缺失」 + 用相同参数重做/移除记录 - 参数页提交自动切结果页;工作流选择器 ↑↓ 真高亮 + Enter 使用(ShellPop arrowRoving 开关) - 记录流 80 条分页(220 条专项:50 次轮询 490ms);任务页 §3.5 芯片+搜索+ 行内进度条+ghost 重试;i18n 七语种 +17 键 Co-authored-by: multica-agent <github@multica.ai>
856 lines
28 KiB
Svelte
856 lines
28 KiB
Svelte
<script lang="ts">
|
|
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
|
|
import { toStore } from 'svelte/store';
|
|
import { tick, untrack } from 'svelte';
|
|
import { SvelteSet } from 'svelte/reactivity';
|
|
import { page } from '$app/state';
|
|
import Icon from '$lib/components/ui/Icon.svelte';
|
|
import Modal from '$lib/components/ui/Modal.svelte';
|
|
import AppShell from '$lib/components/shell/AppShell.svelte';
|
|
import Composer from '$lib/components/generate/Composer.svelte';
|
|
import ContextBar from '$lib/components/generate/ContextBar.svelte';
|
|
import Inspector from '$lib/components/generate/Inspector.svelte';
|
|
import ParamsPanel from '$lib/components/generate/ParamsPanel.svelte';
|
|
import TakeFeed from '$lib/components/generate/TakeFeed.svelte';
|
|
import { createTakeDeleteQueue } from '$lib/components/generate/takeDelete.svelte';
|
|
import { readDeskContext } from '$lib/components/generate/context';
|
|
import {
|
|
changedParams,
|
|
classifySchema,
|
|
listPaths,
|
|
missingMedia,
|
|
schemaDefaults,
|
|
validateForm,
|
|
type BlockReason,
|
|
type DeskKind,
|
|
type FormValue,
|
|
type FormValues,
|
|
} from '$lib/components/generate/schema';
|
|
import { matchesFilter, type FeedFilter } from '$lib/components/generate/takes';
|
|
import { apiErrorMessage, assetUrl, comfy, jobsApi, playgroundApi, projects, settings, workflows } from '$lib/api';
|
|
import { USAGE_BY_KIND, type Job, type Workflow } from '$lib/comfy/types';
|
|
import { compactInputValues } from '$lib/comfy/promptInput';
|
|
import { connectEvents } from '$lib/events';
|
|
import { handleJobEvent } from '$lib/jobProgress';
|
|
import { jobStatusInfo } from '$lib/jobStatus';
|
|
import { parseDbTs } from '$lib/dbtime';
|
|
import { toast } from '$lib/toast';
|
|
import { t } from '$lib/i18n.svelte';
|
|
|
|
/**
|
|
* 生成台 (spec-v2 §3.3, HEL-650 C 批): one desk for images and video — the
|
|
* take feed with the composer below and the inspector on the right.
|
|
* `/image` and `/video` only preselect: the default workflow comes from
|
|
* that kind's usages and the feed opens filtered to it. Slots and params
|
|
* follow the selected workflow's JSON (see generate/schema.ts).
|
|
*/
|
|
interface Props {
|
|
kind: DeskKind;
|
|
}
|
|
|
|
let { kind }: Props = $props();
|
|
|
|
const client = useQueryClient();
|
|
|
|
// ------------------------------------------------------------------
|
|
// Data
|
|
// ------------------------------------------------------------------
|
|
const settingsQuery = createQuery({ queryKey: ['settings'], queryFn: settings.get });
|
|
const workflowsQuery = createQuery({ queryKey: ['workflows'], queryFn: workflows.list });
|
|
const jobsQuery = createQuery({
|
|
queryKey: ['playground-jobs'],
|
|
queryFn: playgroundApi.jobs,
|
|
refetchInterval: 5_000,
|
|
});
|
|
|
|
let ctxDismissed = $state(false);
|
|
const ctx = $derived(ctxDismissed ? null : readDeskContext(page.url, kind));
|
|
const projectsQuery = createQuery(
|
|
toStore(() => ({ queryKey: ['projects'], queryFn: projects.list, enabled: !!ctx })),
|
|
);
|
|
const ctxProjectTitle = $derived(
|
|
($projectsQuery.data ?? []).find((p) => p.id === ctx?.projectId)?.title ??
|
|
t('attach.projectFallback', { id: ctx?.projectId ?? '' }),
|
|
);
|
|
|
|
const endpoints = $derived($settingsQuery.data?.comfyui_endpoints ?? []);
|
|
const activeId = $derived($settingsQuery.data?.comfyui_active_id ?? endpoints[0]?.id ?? '');
|
|
const dryRun = $derived($settingsQuery.data?.dry_run === true);
|
|
|
|
// HEL-636/638: only confirmed usages with a settled output mapping.
|
|
const deskWorkflows = $derived(
|
|
($workflowsQuery.data ?? []).filter((w) => w.is_enabled && (w.usage ?? null) !== null && !w.needs_mapping),
|
|
);
|
|
const workflowById = $derived(new Map(($workflowsQuery.data ?? []).map((w) => [w.id, w])));
|
|
const workflowOf = (job: Job): Workflow | undefined =>
|
|
job.workflow_id != null ? workflowById.get(job.workflow_id) : undefined;
|
|
|
|
const allJobs = $derived($jobsQuery.data ?? []);
|
|
|
|
// Jobs enqueued from this desk — a fast failure can land before the
|
|
// jobs list refetch knows about them.
|
|
const submittedIds = new Set<number>();
|
|
|
|
// D 批: one-shot completion flash / failure shake (SSE-driven) and the
|
|
// 5-second undo window for record deletes.
|
|
const flashIds = new SvelteSet<number>();
|
|
const shakeIds = new SvelteSet<number>();
|
|
const deleteQueue = createTakeDeleteQueue(client);
|
|
const pendingIds = deleteQueue.pending;
|
|
$effect(() => deleteQueue.destroy);
|
|
|
|
function flashTake(id: number, ms: number, set: SvelteSet<number>) {
|
|
set.add(id);
|
|
setTimeout(() => set.delete(id), ms);
|
|
}
|
|
|
|
let feed = $state<TakeFeed | null>(null);
|
|
let orderedIds = $state<number[]>([]);
|
|
|
|
$effect(() => {
|
|
const off = connectEvents((ev) => {
|
|
handleJobEvent(ev);
|
|
if (ev.type === 'job.failed' && !ev.data.cancelled) {
|
|
const id = Number(ev.data.job_id);
|
|
// The SSE backlog replays old failures on every connect.
|
|
const known = allJobs.find((j) => j.id === id);
|
|
if (submittedIds.has(id) || (known && known.status !== 'failed')) {
|
|
toast.error(t('studio.jobFailedToast', { detail: String(ev.data.error ?? '') }));
|
|
}
|
|
flashTake(id, 400, shakeIds);
|
|
}
|
|
if (ev.type === 'job.completed') {
|
|
const id = Number(ev.data.job_id);
|
|
flashTake(id, 950, flashIds);
|
|
// 完成:检视区若正选中该条且为视频,自动播放。
|
|
if (selectedJobId === id) playSignal += 1;
|
|
}
|
|
if (ev.type === 'job.completed' && submittedIds.has(Number(ev.data.job_id)) && ev.data.dry_run) {
|
|
toast.info(t('studio.dryRunToast'));
|
|
}
|
|
if (ev.type.startsWith('job.') || ev.type === 'events.resync') {
|
|
void client.invalidateQueries({ queryKey: ['playground-jobs'] });
|
|
void client.invalidateQueries({ queryKey: ['jobs'] });
|
|
}
|
|
});
|
|
return off;
|
|
});
|
|
|
|
// ------------------------------------------------------------------
|
|
// Form state
|
|
// ------------------------------------------------------------------
|
|
let endpointTouched = $state(false);
|
|
let endpointId = $state('');
|
|
let workflowId = $state<number | null>(null);
|
|
let values = $state<FormValues>({});
|
|
let showErrors = $state(false);
|
|
let submitting = $state(false);
|
|
let sent = $state(false);
|
|
let slotBusy = $state(false);
|
|
let promptEl = $state<HTMLTextAreaElement | null>(null);
|
|
let pickerFor = $state<string | null>(null);
|
|
|
|
const currentWorkflow = $derived(deskWorkflows.find((w) => w.id === workflowId) ?? null);
|
|
const schema = $derived(currentWorkflow?.input_schema ?? []);
|
|
const ds = $derived(classifySchema(schema, currentWorkflow?.kind ?? kind));
|
|
|
|
// Default endpoint follows the workflow binding, then the active one —
|
|
// unless the user picked one explicitly.
|
|
$effect(() => {
|
|
if (endpointTouched) return;
|
|
endpointId = currentWorkflow?.endpoint_id ?? activeId ?? '';
|
|
});
|
|
|
|
// Default workflow: this entry's usages in priority order, runnable ones first.
|
|
$effect(() => {
|
|
if (workflowId != null && deskWorkflows.some((w) => w.id === workflowId)) return;
|
|
const usages = USAGE_BY_KIND[kind];
|
|
const runnable = deskWorkflows.filter((w) => !(w.warnings ?? []).some((x) => x.level === 'error'));
|
|
const pick =
|
|
usages.map((u) => runnable.find((w) => w.usage === u)).find(Boolean) ??
|
|
deskWorkflows.find((w) => usages.includes(w.usage!)) ??
|
|
runnable[0] ??
|
|
deskWorkflows[0];
|
|
workflowId = pick?.id ?? null;
|
|
});
|
|
|
|
/**
|
|
* New workflow → its own defaults, keeping what the user already gave:
|
|
* the prompt / negative prompt (by role) and uploaded images, poured
|
|
* into the new workflow's image slots in order.
|
|
*/
|
|
function carryOver(prev: Workflow | null, prevValues: FormValues, next: Workflow): FormValues {
|
|
const out = schemaDefaults(next.input_schema ?? []);
|
|
const nextDs = classifySchema(next.input_schema ?? [], next.kind);
|
|
if (!prev) return out;
|
|
const prevDs = classifySchema(prev.input_schema ?? [], prev.kind);
|
|
for (const [a, b] of [
|
|
[prevDs.prompt, nextDs.prompt],
|
|
[prevDs.negative, nextDs.negative],
|
|
]) {
|
|
const v = a ? prevValues[a.nodeId] : undefined;
|
|
if (a && b && typeof v === 'string' && v.trim()) out[b.nodeId] = v;
|
|
}
|
|
const images: string[] = [];
|
|
for (const s of prevDs.slots) {
|
|
const v = prevValues[s.inp.nodeId];
|
|
if (s.mediaKind === 'image' && !s.mask && typeof v === 'string' && v) images.push(v);
|
|
}
|
|
for (const g of prevDs.lists) if (g.kind === 'image_list') images.push(...listPaths(prevValues, g));
|
|
for (const s of nextDs.slots) {
|
|
if (s.mediaKind === 'image' && !s.mask && images.length) out[s.inp.nodeId] = images.shift()!;
|
|
}
|
|
const list = nextDs.lists.find((g) => g.kind === 'image_list');
|
|
if (list && images.length) out[list.nodeId] = images.slice(0, list.max ?? 9);
|
|
return out;
|
|
}
|
|
|
|
let lastWf = $state<Workflow | null>(null);
|
|
let ctxApplied = false;
|
|
$effect(() => {
|
|
const wf = currentWorkflow;
|
|
untrack(() => {
|
|
if (!wf) {
|
|
if (lastWf) values = {};
|
|
lastWf = null;
|
|
return;
|
|
}
|
|
if (wf.id === lastWf?.id) return;
|
|
let next = carryOver(lastWf, values, wf);
|
|
if (!ctxApplied && ctx) {
|
|
ctxApplied = true;
|
|
next = applyContext(wf, next);
|
|
}
|
|
lastWf = wf;
|
|
values = next;
|
|
showErrors = false;
|
|
});
|
|
});
|
|
|
|
function applyContext(wf: Workflow, base: FormValues): FormValues {
|
|
if (!ctx) return base;
|
|
const d = classifySchema(wf.input_schema ?? [], wf.kind);
|
|
const out = { ...base };
|
|
if (d.prompt && ctx.prompt) out[d.prompt.nodeId] = ctx.prompt;
|
|
if (d.negative && ctx.negative) out[d.negative.nodeId] = ctx.negative;
|
|
if (d.duration && ctx.durationSec != null) {
|
|
const opts = d.duration.options;
|
|
const v = String(ctx.durationSec);
|
|
if (!opts?.length || opts.includes(v)) out[d.duration.nodeId] = d.duration.kind === 'number' ? ctx.durationSec : v;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function setVal(nodeId: string, v: FormValue) {
|
|
values = { ...values, [nodeId]: v };
|
|
}
|
|
|
|
function restoreAll() {
|
|
const defaults = schemaDefaults(schema);
|
|
const next = { ...values };
|
|
for (const inp of [...ds.common, ...ds.advanced]) {
|
|
if (defaults[inp.nodeId] !== undefined) next[inp.nodeId] = defaults[inp.nodeId];
|
|
else delete next[inp.nodeId];
|
|
}
|
|
values = next;
|
|
}
|
|
|
|
const changedCount = $derived(changedParams(ds, values).length);
|
|
|
|
// ------------------------------------------------------------------
|
|
// Connection & validation
|
|
// ------------------------------------------------------------------
|
|
const probeQuery = createQuery(
|
|
toStore(() => ({
|
|
queryKey: ['comfy-probe', endpointId || null],
|
|
queryFn: () => comfy.testEndpoint({ endpoint_id: endpointId, timeout_sec: 5 }),
|
|
enabled: !!endpointId,
|
|
staleTime: 60_000,
|
|
refetchInterval: 60_000,
|
|
retry: false,
|
|
})),
|
|
);
|
|
const connRec = $derived.by(() => {
|
|
const data = $probeQuery.data;
|
|
if (!endpointId || !data) return null;
|
|
return { ok: data.ok, ms: data.elapsed_ms, at: $probeQuery.dataUpdatedAt };
|
|
});
|
|
const connState = $derived.by(() => {
|
|
if (dryRun) return { state: 'dry' as const };
|
|
if (connRec?.ok) return { state: 'ok' as const, ms: connRec.ms };
|
|
if (connRec?.ok === false) return { state: 'fail' as const };
|
|
return { state: 'untested' as const };
|
|
});
|
|
|
|
function fmtClock(ms: number): string {
|
|
const d = new Date(ms);
|
|
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
|
|
}
|
|
|
|
const errors = $derived(validateForm(schema, ds, values));
|
|
const brokenReasons = $derived(
|
|
(currentWorkflow?.warnings ?? []).filter((w) => w.level === 'error').map((w) => w.message),
|
|
);
|
|
|
|
/** The single reason 生成 is off, in the order a user can fix things. */
|
|
const block = $derived.by<BlockReason | null>(() => {
|
|
if (!currentWorkflow) return { text: t('desk.needWorkflow'), tone: 'warn', target: 'desk-wf' };
|
|
if (!endpoints.length || !endpointId) return { text: t('studio.errNoConn'), tone: 'err', target: 'desk-conn' };
|
|
if (connRec?.ok === false && !dryRun) {
|
|
return { text: t('studio.errConnDown', { time: fmtClock(connRec.at) }), tone: 'err', target: 'desk-conn' };
|
|
}
|
|
if (brokenReasons.length) return { text: t('studio.errWfBroken'), tone: 'err', params: true };
|
|
const missing = missingMedia(ds, values);
|
|
const promptMissing = !!ds.prompt && !!errors[ds.prompt.nodeId] && !String(values[ds.prompt.nodeId] ?? '').trim();
|
|
if (missing.length || promptMissing) {
|
|
const labels = [...missing.map((m) => m.label), ...(promptMissing ? [t('studio.promptLabel')] : [])];
|
|
return {
|
|
text: t('desk.stillNeed', { what: labels.join('、') }),
|
|
tone: 'warn',
|
|
target: missing.length ? `slot-${missing[0].nodeId}` : 'desk-prompt',
|
|
};
|
|
}
|
|
if (errors.firstLast) return { text: errors.firstLast, tone: 'warn', target: `slot-${ds.slots.find((s) => s.firstFrame)?.inp.nodeId}` };
|
|
const firstErr = Object.entries(errors).find(([, m]) => m.trim());
|
|
if (firstErr) {
|
|
const [id, msg] = firstErr;
|
|
if (ds.prompt && id === ds.prompt.nodeId) return { text: msg, tone: 'err', target: 'desk-prompt' };
|
|
return { text: t('desk.paramError', { msg }), tone: 'err', params: true };
|
|
}
|
|
return null;
|
|
});
|
|
|
|
async function reveal() {
|
|
showErrors = true;
|
|
const b = block;
|
|
if (!b) return;
|
|
if (b.params) {
|
|
openParams();
|
|
return;
|
|
}
|
|
await tick();
|
|
const el = b.target ? document.getElementById(b.target) : null;
|
|
if (el && !el.getClientRects().length) {
|
|
// Collapsed narrow composer: focusing inside expands it first.
|
|
promptEl?.focus();
|
|
await tick();
|
|
}
|
|
el?.focus();
|
|
el?.scrollIntoView({ block: 'nearest' });
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// Submit
|
|
// ------------------------------------------------------------------
|
|
let sentTimer: ReturnType<typeof setTimeout> | null = null;
|
|
|
|
async function submit() {
|
|
if (submitting || slotBusy) return;
|
|
if (block) {
|
|
void reveal();
|
|
return;
|
|
}
|
|
const wf = currentWorkflow!;
|
|
submitting = true;
|
|
try {
|
|
const res = await playgroundApi.generate({
|
|
workflow_id: wf.id,
|
|
input_values: compactInputValues(values) as Record<string, unknown>,
|
|
endpoint_id: endpointId || null,
|
|
source: wf.kind === 'image' ? 'studio-image' : 'studio-video',
|
|
});
|
|
submittedIds.add(res.job.id);
|
|
selectedJobId = res.job.id;
|
|
if (!matchesFilter(res.job, filter)) filter = 'all';
|
|
showErrors = false;
|
|
sent = true;
|
|
if (sentTimer) clearTimeout(sentTimer);
|
|
sentTimer = setTimeout(() => (sent = false), 900);
|
|
// C 批审核:从「参数」页提交后自动切到「结果」页,进行中进度可见。
|
|
tab = 'result';
|
|
if (wide) inspOff = false;
|
|
else if (!narrow) inspOpen = true;
|
|
await client.invalidateQueries({ queryKey: ['playground-jobs'] });
|
|
await client.invalidateQueries({ queryKey: ['jobs'] });
|
|
} catch (err) {
|
|
toast.error(t('studio.submitFailedToast', { detail: apiErrorMessage(err) }));
|
|
} finally {
|
|
submitting = false;
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// Feed, selection & inspector
|
|
// ------------------------------------------------------------------
|
|
let filter = $state<FeedFilter>(untrack(() => kind));
|
|
let selectedJobId = $state<number | null>(null);
|
|
let busyId = $state<number | null>(null);
|
|
let tab = $state<'result' | 'params'>('result');
|
|
let inspOff = $state(false);
|
|
let inspOpen = $state(false);
|
|
let wide = $state(true);
|
|
let narrow = $state(false);
|
|
let crossfade = $state(false);
|
|
let playSignal = $state(0);
|
|
let videoEl = $state<HTMLVideoElement | null>(null);
|
|
|
|
$effect(() => {
|
|
const mq = window.matchMedia('(min-width: 1180px)');
|
|
const mq2 = window.matchMedia('(max-width: 760px)');
|
|
const sync = () => {
|
|
wide = mq.matches;
|
|
narrow = mq2.matches;
|
|
};
|
|
sync();
|
|
mq.addEventListener('change', sync);
|
|
mq2.addEventListener('change', sync);
|
|
return () => {
|
|
mq.removeEventListener('change', sync);
|
|
mq2.removeEventListener('change', sync);
|
|
};
|
|
});
|
|
|
|
let nowMs = $state(Date.now());
|
|
const anyActive = $derived(allJobs.some((j) => j.status === 'pending' || j.status === 'running'));
|
|
$effect(() => {
|
|
if (!anyActive) return;
|
|
const id = setInterval(() => (nowMs = Date.now()), 1000);
|
|
return () => clearInterval(id);
|
|
});
|
|
|
|
/** Picked take, else the newest finished one in view (undo-pending rows don't count). */
|
|
const selectedJob = $derived(
|
|
allJobs.find((j) => j.id === selectedJobId && !pendingIds.has(j.id)) ??
|
|
allJobs
|
|
.filter((j) => matchesFilter(j, filter) && !pendingIds.has(j.id) && jobStatusInfo(j).tone === 'ok')
|
|
.sort((a, b) => parseDbTs(b.created_at) - parseDbTs(a.created_at))[0] ??
|
|
null,
|
|
);
|
|
|
|
/**
|
|
* 结果切换 (HEL-648): pointer picks slide the gold frame and cross-fade
|
|
* the inspector; keyboard ↑↓/J/K switch instantly with no animation.
|
|
*/
|
|
function selectTake(job: Job, via: 'pointer' | 'keyboard' = 'pointer') {
|
|
const from = via === 'pointer' ? (feed?.markRect() ?? null) : null;
|
|
selectedJobId = job.id;
|
|
tab = 'result';
|
|
crossfade = via === 'pointer';
|
|
if (via === 'pointer') {
|
|
playSignal += 1;
|
|
if (!wide) inspOpen = true;
|
|
void tick().then(() => feed?.slideFrom(from));
|
|
} else {
|
|
feed?.scrollToJob(job.id);
|
|
}
|
|
}
|
|
|
|
function moveSelection(delta: number) {
|
|
if (!orderedIds.length) return;
|
|
let i = orderedIds.indexOf(selectedJob?.id ?? -1);
|
|
if (i < 0) i = orderedIds.length - 1;
|
|
i = Math.max(0, Math.min(orderedIds.length - 1, i + delta));
|
|
const job = allJobs.find((j) => j.id === orderedIds[i]);
|
|
if (job) selectTake(job, 'keyboard');
|
|
}
|
|
|
|
function openParams() {
|
|
tab = 'params';
|
|
if (wide) inspOff = false;
|
|
else inspOpen = true;
|
|
}
|
|
|
|
function toggleInspector() {
|
|
if (wide) inspOff = !inspOff;
|
|
else inspOpen = !inspOpen;
|
|
}
|
|
|
|
function closeInspector() {
|
|
if (wide) inspOff = true;
|
|
else inspOpen = false;
|
|
}
|
|
|
|
const imageSlotTarget = $derived(
|
|
ds.slots.find((s) => s.mediaKind === 'image' && !s.mask && s.fromResults) ?? null,
|
|
);
|
|
const imageList = $derived(ds.lists.find((g) => g.kind === 'image_list') ?? null);
|
|
|
|
function sendToSlot(path: string) {
|
|
if (imageSlotTarget && !String(values[imageSlotTarget.inp.nodeId] ?? '')) {
|
|
setVal(imageSlotTarget.inp.nodeId, path);
|
|
} else if (imageList) {
|
|
const cur = listPaths(values, imageList);
|
|
if (cur.length >= (imageList.max ?? 9)) {
|
|
toast.error(t('studio.refFull', { max: imageList.max ?? 9 }));
|
|
return;
|
|
}
|
|
setVal(imageList.nodeId, [...cur, path]);
|
|
} else if (imageSlotTarget) {
|
|
setVal(imageSlotTarget.inp.nodeId, path);
|
|
} else {
|
|
return;
|
|
}
|
|
toast.success(t('desk.sentToSlotToast'));
|
|
}
|
|
|
|
/** Fill the composer back with a past take's values (on its own workflow). */
|
|
function reuse(job: Job) {
|
|
const wf = deskWorkflows.find((w) => w.id === job.workflow_id);
|
|
if (!wf) {
|
|
toast.error(t('studio.reuseMissingWf'));
|
|
return;
|
|
}
|
|
const next = schemaDefaults(wf.input_schema ?? []);
|
|
for (const [k, v] of Object.entries((job.payload?.input_values ?? {}) as Record<string, unknown>)) {
|
|
if (typeof v === 'string' || typeof v === 'number') next[k] = v;
|
|
else if (Array.isArray(v) && v.every((p) => typeof p === 'string')) next[k] = v as string[];
|
|
}
|
|
workflowId = wf.id;
|
|
lastWf = wf;
|
|
values = next;
|
|
showErrors = false;
|
|
toast.success(t('studio.reusedToast'));
|
|
void tick().then(() => promptEl?.focus());
|
|
}
|
|
|
|
async function retry(job: Job) {
|
|
if (busyId != null) return;
|
|
busyId = job.id;
|
|
try {
|
|
await jobsApi.retry(job.id);
|
|
toast.success(t('studio.retryQueuedToast'));
|
|
await client.invalidateQueries({ queryKey: ['playground-jobs'] });
|
|
} catch (err) {
|
|
toast.error(t('studio.retryFailedToast', { detail: apiErrorMessage(err) }));
|
|
} finally {
|
|
busyId = null;
|
|
}
|
|
}
|
|
|
|
async function cancel(job: Job) {
|
|
if (busyId != null) return;
|
|
busyId = job.id;
|
|
try {
|
|
await jobsApi.cancel(job.id);
|
|
toast.info(t('studio.cancelToast'));
|
|
await client.invalidateQueries({ queryKey: ['playground-jobs'] });
|
|
} catch (err) {
|
|
toast.error(apiErrorMessage(err));
|
|
} finally {
|
|
busyId = null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 删除整条任务 (§四.4 删除两级制): no dialog — the row collapses out,
|
|
* a 5-second Toast offers 撤销 (row returns with its entrance and is
|
|
* reselected), and only then does the DELETE really hit the backend.
|
|
*/
|
|
function requestDelete(job: Job) {
|
|
if (job.status === 'pending' || job.status === 'running') return;
|
|
const name = workflowOf(job)?.name ?? t('studio.jobName', { id: job.id });
|
|
deleteQueue.request(job, {
|
|
message: () =>
|
|
(job.output_paths?.length ?? 0) > 0
|
|
? t('studio.deletedTakeToast', { name })
|
|
: t('studio.deletedTakeNoFilesToast', { name }),
|
|
onUndo: (j) => {
|
|
feed?.markEnter(j.id);
|
|
const from = feed?.markRect() ?? null;
|
|
selectedJobId = j.id;
|
|
void tick().then(() => {
|
|
feed?.slideFrom(from);
|
|
feed?.scrollToJob(j.id);
|
|
});
|
|
},
|
|
onCommitted: (j) => {
|
|
submittedIds.delete(j.id);
|
|
if (selectedJobId === j.id) selectedJobId = null;
|
|
},
|
|
});
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// 从结果选 (finished image takes → an image slot)
|
|
// ------------------------------------------------------------------
|
|
const imageResults = $derived(
|
|
allJobs
|
|
.filter((j) => j.kind === 'image' && jobStatusInfo(j).tone === 'ok')
|
|
.flatMap((j) => j.output_paths.map((p) => ({ job: j, path: p }))),
|
|
);
|
|
|
|
function pickResult(path: string) {
|
|
const nodeId = pickerFor;
|
|
pickerFor = null;
|
|
if (!nodeId) return;
|
|
const list = ds.lists.find((g) => g.nodeId === nodeId);
|
|
if (list) {
|
|
const cur = listPaths(values, list);
|
|
if (cur.length >= (list.max ?? 9)) toast.error(t('studio.refFull', { max: list.max ?? 9 }));
|
|
else setVal(nodeId, [...cur, path]);
|
|
} else {
|
|
setVal(nodeId, path);
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// 键盘 (§四.8): Ctrl/⌘+Enter 生成 · / 聚焦提示词 · ↑↓/J/K 切换记录
|
|
// (即时无动画)· 空格播放/暂停 · Delete 删选中 · ] 检视区 · Esc 关浮层
|
|
// ------------------------------------------------------------------
|
|
function typing(target: EventTarget | null): boolean {
|
|
const el = target as HTMLElement | null;
|
|
return !!el && (el.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName));
|
|
}
|
|
|
|
/** Focus sits on something that owns the key (button, link, video…). */
|
|
function onInteractive(target: EventTarget | null): boolean {
|
|
const el = target instanceof Element ? target : null;
|
|
return !!el?.closest('button, a, input, textarea, select, label, video, audio, [contenteditable]');
|
|
}
|
|
|
|
function inLayer(target: EventTarget | null): boolean {
|
|
const el = target instanceof Element ? target : null;
|
|
return !!el?.closest('.shell-pop, .modal, [role="dialog"]');
|
|
}
|
|
|
|
function onKeydown(e: KeyboardEvent) {
|
|
if (e.defaultPrevented || pickerFor || inLayer(e.target)) return;
|
|
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
|
|
e.preventDefault();
|
|
void submit();
|
|
return;
|
|
}
|
|
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
|
const key = e.key.toLowerCase();
|
|
if (key === '/' && !typing(e.target)) {
|
|
e.preventDefault();
|
|
promptEl?.focus();
|
|
} else if ((e.key === 'ArrowDown' || key === 'j') && !typing(e.target)) {
|
|
e.preventDefault();
|
|
moveSelection(1);
|
|
} else if ((e.key === 'ArrowUp' || key === 'k') && !typing(e.target)) {
|
|
e.preventDefault();
|
|
moveSelection(-1);
|
|
} else if (e.key === ' ') {
|
|
// 空格播放/暂停:检视区可见且有视频时接管;焦点在控件上时走原生行为。
|
|
if (typing(e.target) || onInteractive(e.target)) return;
|
|
if (videoEl && (wide ? !inspOff : inspOpen)) {
|
|
e.preventDefault();
|
|
if (videoEl.paused) videoEl.play().catch(() => {});
|
|
else videoEl.pause();
|
|
}
|
|
} else if (e.key === ']' && !typing(e.target)) {
|
|
e.preventDefault();
|
|
toggleInspector();
|
|
} else if ((e.key === 'Delete' || e.key === 'Backspace') && !typing(e.target)) {
|
|
const job = selectedJob;
|
|
if (job && job.status !== 'pending' && job.status !== 'running') {
|
|
e.preventDefault();
|
|
requestDelete(job);
|
|
}
|
|
} else if (e.key === 'Escape' && !wide && inspOpen) {
|
|
inspOpen = false;
|
|
}
|
|
}
|
|
</script>
|
|
|
|
<svelte:window onkeydown={onKeydown} />
|
|
|
|
{#snippet ctxBanner()}
|
|
{#if ctx}
|
|
<ContextBar {ctx} projectTitle={ctxProjectTitle} onDismiss={() => (ctxDismissed = true)} />
|
|
{/if}
|
|
{/snippet}
|
|
|
|
{#snippet inspectorToggle()}
|
|
{#if !wide || inspOff}
|
|
<button type="button" class="a-btn ghost sm" aria-keyshortcuts="]" onclick={toggleInspector}>
|
|
<Icon name="info" size={14} />
|
|
{t('desk.openInspector')}
|
|
</button>
|
|
{/if}
|
|
{/snippet}
|
|
|
|
{#snippet paramsTab()}
|
|
<ParamsPanel
|
|
workflow={currentWorkflow}
|
|
{ds}
|
|
{values}
|
|
{errors}
|
|
{showErrors}
|
|
{changedCount}
|
|
onSet={setVal}
|
|
onRestoreAll={restoreAll}
|
|
/>
|
|
{/snippet}
|
|
|
|
<AppShell active={kind} title={t('desk.title')}>
|
|
<div class="desk" class:insp-off={inspOff}>
|
|
<section class="center" aria-label={t('desk.title')}>
|
|
<TakeFeed
|
|
bind:this={feed}
|
|
jobs={allJobs}
|
|
{workflowOf}
|
|
bind:filter
|
|
selectedId={selectedJob?.id ?? null}
|
|
{nowMs}
|
|
{busyId}
|
|
loading={$jobsQuery.isLoading}
|
|
{pendingIds}
|
|
{flashIds}
|
|
{shakeIds}
|
|
bind:orderedIds
|
|
banner={ctxBanner}
|
|
{inspectorToggle}
|
|
onSelect={(job) => selectTake(job, 'pointer')}
|
|
onReuse={reuse}
|
|
onRetry={retry}
|
|
onCancel={cancel}
|
|
onDelete={requestDelete}
|
|
/>
|
|
{#if !$workflowsQuery.isLoading && !deskWorkflows.length}
|
|
<div class="desk-empty" role="note">
|
|
<Icon name="playground" size={16} />
|
|
<span>{t('desk.noWorkflows')}</span>
|
|
<a class="a-btn ghost sm" href="/connections">{t('studio.wfEmptyGo')}</a>
|
|
</div>
|
|
{/if}
|
|
<Composer
|
|
{ds}
|
|
{values}
|
|
workflows={deskWorkflows}
|
|
current={currentWorkflow}
|
|
{endpoints}
|
|
{endpointId}
|
|
conn={connState}
|
|
{errors}
|
|
{showErrors}
|
|
{block}
|
|
{changedCount}
|
|
{submitting}
|
|
{sent}
|
|
bind:slotBusy
|
|
bind:promptEl
|
|
onSet={setVal}
|
|
onPickWorkflow={(wf) => (workflowId = wf.id)}
|
|
onPickEndpoint={(id) => {
|
|
endpointTouched = true;
|
|
endpointId = id;
|
|
}}
|
|
onSubmit={submit}
|
|
onReveal={reveal}
|
|
onOpenParams={openParams}
|
|
onFromResults={(nodeId) => (pickerFor = nodeId)}
|
|
/>
|
|
</section>
|
|
<Inspector
|
|
bind:tab
|
|
job={selectedJob}
|
|
wf={selectedJob ? workflowOf(selectedJob) : undefined}
|
|
{nowMs}
|
|
open={inspOpen}
|
|
inactive={wide ? inspOff : !inspOpen}
|
|
canSendToSlot={!!imageSlotTarget || !!imageList}
|
|
{crossfade}
|
|
{playSignal}
|
|
bind:videoEl
|
|
params={paramsTab}
|
|
onClose={closeInspector}
|
|
onReuse={reuse}
|
|
onRetry={retry}
|
|
onSendToSlot={sendToSlot}
|
|
onDelete={requestDelete}
|
|
/>
|
|
</div>
|
|
</AppShell>
|
|
|
|
<Modal open={pickerFor != null} title={t('studio.pickerTitle')} onclose={() => (pickerFor = null)}>
|
|
{#if imageResults.length}
|
|
<div class="picker-grid">
|
|
{#each imageResults as entry (entry.path)}
|
|
<button type="button" class="picker-item" onclick={() => pickResult(entry.path)}>
|
|
<img src={assetUrl(entry.path)} alt={t('studio.pickerPick')} loading="lazy" />
|
|
</button>
|
|
{/each}
|
|
</div>
|
|
{:else}
|
|
<p class="picker-empty">{t('studio.pickerEmpty')}</p>
|
|
{/if}
|
|
</Modal>
|
|
|
|
<style>
|
|
.desk {
|
|
display: grid;
|
|
grid-template-columns: minmax(0, 1fr) 420px;
|
|
grid-template-rows: minmax(0, 1fr);
|
|
height: 100%;
|
|
min-height: 0;
|
|
transition: grid-template-columns var(--d-drawer) var(--ease-drawer);
|
|
}
|
|
.desk.insp-off {
|
|
grid-template-columns: minmax(0, 1fr) 0px;
|
|
}
|
|
.center {
|
|
display: flex;
|
|
flex-direction: column;
|
|
min-width: 0;
|
|
min-height: 0;
|
|
}
|
|
.desk-empty {
|
|
display: flex;
|
|
align-items: center;
|
|
flex-wrap: wrap;
|
|
gap: var(--sp-3);
|
|
margin: 0 var(--sp-7) var(--sp-3);
|
|
padding: var(--sp-4) var(--sp-5);
|
|
border-radius: var(--r-md);
|
|
background: var(--warn-soft);
|
|
color: var(--warn);
|
|
font-size: var(--fs-aux);
|
|
}
|
|
.picker-grid {
|
|
display: grid;
|
|
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
|
|
gap: var(--sp-4);
|
|
}
|
|
.picker-item {
|
|
padding: 0;
|
|
overflow: hidden;
|
|
border: 1px solid var(--line);
|
|
border-radius: var(--r-md);
|
|
background: var(--bg-3);
|
|
cursor: pointer;
|
|
transition: border-color var(--d-state) ease;
|
|
}
|
|
.picker-item img {
|
|
display: block;
|
|
width: 100%;
|
|
aspect-ratio: 1;
|
|
object-fit: cover;
|
|
}
|
|
@media (hover: hover) and (pointer: fine) {
|
|
.picker-item:hover {
|
|
border-color: var(--line-2);
|
|
}
|
|
}
|
|
.picker-empty {
|
|
margin: 0;
|
|
color: var(--text-3);
|
|
font-size: var(--fs-aux);
|
|
}
|
|
@media (max-width: 1179px) {
|
|
.desk,
|
|
.desk.insp-off {
|
|
grid-template-columns: minmax(0, 1fr);
|
|
}
|
|
.desk-empty {
|
|
margin: 0 var(--sp-6) var(--sp-3);
|
|
}
|
|
}
|
|
@media (max-width: 760px) {
|
|
.desk-empty {
|
|
margin: 0 var(--sp-5) var(--sp-2);
|
|
}
|
|
}
|
|
</style>
|