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

729 lines
27 KiB
Svelte

<script lang="ts">
import "$lib/components/workbench/project.css";
import Modal from "$lib/components/ui/Modal.svelte";
import StudioHeader from "$lib/components/workbench/StudioHeader.svelte";
import { resolve } from "$app/paths";
import { goto } from "$app/navigation";
import { untrack } from "svelte";
import { page as pageStore } from "$app/state";
import {
createMutation,
createQuery,
useQueryClient,
} from "@tanstack/svelte-query";
import {
agentApi,
assetUrl,
jobsApi,
settings,
workbenchApi,
type WorkbenchStageKey,
} from "$lib/api";
import { connectEvents } from "$lib/events";
import { parseDbTs } from "$lib/dbtime";
import { handleJobEvent, progressFor } from "$lib/jobProgress";
import { storageSet } from "$lib/storage";
import { toast } from "$lib/toast";
import AppShell from "$lib/components/shell/AppShell.svelte";
import Icon from "$lib/components/ui/Icon.svelte";
import Skeleton from "$lib/components/ui/Skeleton.svelte";
import StageStepper from "$lib/components/workbench/StageStepper.svelte";
import ScriptStagePanel from "$lib/components/workbench/ScriptStagePanel.svelte";
import StyleStagePanel from "$lib/components/workbench/StyleStagePanel.svelte";
import StoryboardStagePanel from "$lib/components/workbench/StoryboardStagePanel.svelte";
import AssetsStagePanel from "$lib/components/workbench/AssetsStagePanel.svelte";
import ShotStagePanel from "$lib/components/workbench/ShotStagePanel.svelte";
import { t } from "$lib/i18n.svelte";
/**
* 五段创作工作台 (a2): stepper + stage artifact panel + agent/task side
* column. Only confirmed snapshots flow downstream; drafts are clearly
* flagged and never treated as final. In-flow generation rides the shared
* queue (HEL-612) so tasks and results come back to this project.
*/
const client = useQueryClient();
let { projectId: suppliedId }: { projectId: number } = $props();
const projectId = untrack(() => suppliedId);
let editor = $state<{saveDraft:()=>void;hasUnsavedDraft:()=>boolean}|null>(null);
let compareOpen = $state(false);
const STAGE_ORDER: WorkbenchStageKey[] = [
"script",
"style",
"storyboard",
"assets",
"shot",
];
const overviewQuery = createQuery({
queryKey: ["workbench", projectId],
queryFn: () => workbenchApi.overview(projectId),
refetchInterval: 2500,
});
const jobsQuery = createQuery({
queryKey: ["jobs", projectId],
queryFn: () => jobsApi.list(projectId),
refetchInterval: 5000,
});
const agentsQuery = createQuery({
queryKey: ["agents-registry"],
queryFn: agentApi.listNamedAgents,
staleTime: 60_000,
});
const settingsQuery = createQuery({
queryKey: ["settings"],
queryFn: settings.get,
staleTime: 60_000,
});
const overview = $derived($overviewQuery.data);
const stages = $derived(overview?.stages ?? []);
// ?stage= selects the open stage; default = first not-confirmed one.
const urlStage = $derived(
pageStore.url.searchParams.get("stage") as WorkbenchStageKey | null,
);
const fallbackStage = $derived.by(() => {
for (const key of STAGE_ORDER) {
const s = stages.find((x) => x.stage_key === key);
if (!s || s.status !== "confirmed") return key;
}
return "shot";
});
const stageKey = $derived(
urlStage && STAGE_ORDER.includes(urlStage) ? urlStage : fallbackStage,
);
const currentStage = $derived(stages.find((s) => s.stage_key === stageKey));
function selectStage(key: string) {
if (Number(pageStore.params.id) !== projectId) return;
noteOpen = false;
const url = new URL(pageStore.url);
url.searchParams.set("stage", key);
goto(resolve(`/workbench/${pageStore.params.id}${url.search}${url.hash}`), {
keepFocus: true,
noScroll: true,
});
}
function advanceAfterConfirm(key: WorkbenchStageKey) {
const idx = STAGE_ORDER.indexOf(key);
if (idx >= 0 && idx < STAGE_ORDER.length - 1) {
selectStage(STAGE_ORDER[idx + 1]);
}
}
// ── Live job feed (shared queue) ───────────────────────────────────
$effect(() => {
const off = connectEvents((ev) => {
handleJobEvent(ev);
if (ev.type.startsWith("job.")) {
client.invalidateQueries({ queryKey: ["jobs", projectId] });
if (ev.type === "job.completed" || ev.type === "job.failed") {
client.invalidateQueries({ queryKey: ["workbench", projectId] });
client.invalidateQueries({ queryKey: ["projects"] });
}
}
});
return off;
});
// ── Stage mutations ────────────────────────────────────────────────
const instructions = $state<Record<string,string>>({});
let runWatchKey = $state<WorkbenchStageKey | null>(null);
let chosenStyleId = $state<string | null>(null);
let noteOpen = $state(false),
noteText = $state(""),
noteBusy = $state(false);
$effect(() => {
void stageKey;
noteOpen = false;
noteText = '';
compareOpen = false;
});
async function saveNote() {
noteBusy = true;
try {
await workbenchApi.saveNote(projectId, stageKey, noteText);
await client.invalidateQueries({ queryKey: ["workbench", projectId] });
noteOpen = false;
toast.success("助手建议已保存");
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
noteBusy = false;
}
}
// Keep the chosen style selector in sync with the stage payload.
let lastStyleSync = $state("");
$effect(() => {
const styleStage = stages.find((s) => s.stage_key === "style");
if (!styleStage) return;
const directions = (
styleStage.content as unknown as { directions?: { id: string }[] } | null
)?.directions;
const stamp = JSON.stringify(directions ?? []) + styleStage.chosen_style_id;
if (stamp === lastStyleSync) return;
lastStyleSync = stamp;
const ids = (directions ?? []).map((d) => d.id);
chosenStyleId =
styleStage.chosen_style_id && ids.includes(styleStage.chosen_style_id)
? styleStage.chosen_style_id
: (ids[0] ?? null);
});
// Toast once a watched run finishes (success or Chinese failure reason).
$effect(() => {
if (!runWatchKey) return;
const stage = stages.find((s) => s.stage_key === runWatchKey);
if (!stage || stage.status === "running") return;
if (stage.status === "awaiting_confirm") {
toast.success(t("workbench.runDone", { agent: agentName(runWatchKey) }));
} else if (stage.last_run?.status === "failed" && stage.last_run.error) {
toast.error(stage.last_run.error);
}
runWatchKey = null;
});
function agentName(key: string): string {
const agent = ($agentsQuery.data ?? []).find((a) => a.key === key);
return agent ? agent.name : key;
}
function busyFor(key: WorkbenchStageKey): boolean {
const stage = stages.find((s) => s.stage_key === key);
return stage?.status === "running";
}
const runMutation = createMutation({
mutationFn: (args: {key: WorkbenchStageKey; instruction: string}) =>
workbenchApi.runStage(projectId, args.key, args.instruction || undefined),
onSuccess: (_data, args) => {
runWatchKey = args.key;
if ((instructions[args.key] ?? '').trim() === args.instruction) instructions[args.key] = '';
client.invalidateQueries({ queryKey: ["workbench", projectId] });
},
onError: (err) => {
toast.error(
err instanceof Error ? err.message : t("workbench.runFailed"),
);
},
});
const saveMutation = createMutation({
mutationFn: (args: {
key: WorkbenchStageKey;
content: Record<string, unknown>;
}) =>
workbenchApi.patchStage(projectId, args.key, { content: args.content }),
onSuccess: () => {
toast.success(t("workbench.draftSaved"));
client.invalidateQueries({ queryKey: ["workbench", projectId] });
client.invalidateQueries({ queryKey: ["projects"] });
},
onError: (err) => {
toast.error(
err instanceof Error ? err.message : t("workbench.saveFailed"),
);
},
});
const confirmMutation = createMutation({
mutationFn: (key: WorkbenchStageKey) =>
workbenchApi.confirmStage(
projectId,
key,
key === "style" ? chosenStyleId : undefined,
),
onSuccess: (_data, key) => {
toast.success(t("workbench.confirmed", { agent: agentName(key) }));
client.invalidateQueries({ queryKey: ["workbench", projectId] });
client.invalidateQueries({ queryKey: ["projects"] });
advanceAfterConfirm(key);
},
onError: (err) => {
toast.error(
err instanceof Error ? err.message : t("workbench.confirmFailed"),
);
},
});
const restoreMutation = createMutation({
mutationFn: (key: WorkbenchStageKey) =>
workbenchApi.restoreStage(projectId, key),
onSuccess: () => {
toast.success(t("workbench.restored"));
client.invalidateQueries({ queryKey: ["workbench", projectId] });
},
onError: (err) => {
toast.error(
err instanceof Error ? err.message : t("workbench.restoreFailed"),
);
},
});
const importMutation = createMutation({
mutationFn: (text: string) => workbenchApi.importScript(projectId, text),
onSuccess: () => {
toast.success(t("workbench.script.importDone"));
client.invalidateQueries({ queryKey: ["workbench", projectId] });
client.invalidateQueries({ queryKey: ["projects"] });
selectStage("style");
},
onError: (err) => {
toast.error(
err instanceof Error ? err.message : t("workbench.script.importFailed"),
);
},
});
const generateMutation = createMutation({
mutationFn: (payload: {
kind: "image" | "video";
stage_key: WorkbenchStageKey;
target_id?: string;
prompt: string;
negative_prompt?: string;
duration_sec?: number;
}) => workbenchApi.generate(projectId, payload),
onSuccess: (data) => {
toast.success(t("workbench.jobSubmitted"));
client.invalidateQueries({ queryKey: ["workbench", projectId] });
client.invalidateQueries({ queryKey: ["jobs", projectId] });
void data;
},
onError: (err) => {
toast.error(
err instanceof Error ? err.message : t("workbench.jobSubmitFailed"),
);
},
});
const retryMutation = createMutation({
mutationFn: (jobId: number) => jobsApi.retry(jobId),
onSuccess: () => {
toast.success(t("workbench.jobRequeued"));
client.invalidateQueries({ queryKey: ["workbench", projectId] });
client.invalidateQueries({ queryKey: ["jobs", projectId] });
},
});
const cancelMutation = createMutation({
mutationFn: (jobId: number) => jobsApi.cancel(jobId),
onSuccess: () => {
client.invalidateQueries({ queryKey: ["jobs", projectId] });
client.invalidateQueries({ queryKey: ["workbench", projectId] });
},
});
function onGenerate(payload: {
kind: "image" | "video";
targetId: string;
prompt: string;
negativePrompt?: string;
durationSec?: number;
}) {
$generateMutation.mutate({
kind: payload.kind,
stage_key: stageKey,
target_id: payload.targetId,
prompt: payload.prompt,
negative_prompt: payload.negativePrompt,
duration_sec: payload.durationSec,
});
}
// ── Sidebar: agent + tasks ─────────────────────────────────────────
const currentAgent = $derived(
($agentsQuery.data ?? []).find((a) => a.key === stageKey) ?? null,
);
const currentModelName = $derived.by(() => {
const agent = currentAgent;
const s = $settingsQuery.data;
if (!agent || !s) return null;
const pid = s.agent_llm_assignments?.[agent.llm_role];
const profile = (s.llm_profiles ?? []).find((p) => p.id === pid);
return profile?.name ?? null;
});
function openAgentChat() {
if (!currentAgent) return;
storageSet("calliope.agents.activeKey", currentAgent.key);
goto(resolve("/agents"));
}
const projectJobs = $derived(
($jobsQuery.data ?? []).filter(
(j) => j.project_id === projectId &&
(j.kind === "image" || j.kind === "video") &&
(j.payload?.stage_key ?? (j.payload?.workbench as {stage?:string}|undefined)?.stage) === stageKey,
),
);
function jobTime(raw: string | null | undefined): string {
const ts = parseDbTs(raw);
if (!Number.isFinite(ts)) return "";
return new Date(ts).toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
});
}
function jobProgressPct(id: number): number | null {
const entry = progressFor(id);
return entry?.progress ?? null;
}
// ── Header state helpers ───────────────────────────────────────────
const STAGE_LABEL: Record<string, string> = {
script: "故事",
style: "风格",
storyboard: "分镜",
assets: "素材",
shot: "镜头脚本",
};
const STATUS_LABEL: Record<string, string> = {
todo: "workbench.state.todo",
running: "workbench.state.running",
awaiting_confirm: "workbench.state.draft",
confirmed: "workbench.state.confirmed",
};
const STATUS_CLASS: Record<string, string> = {
todo: "",
running: "run",
awaiting_confirm: "warn",
confirmed: "ok",
};
const stageStatus = $derived(currentStage?.status ?? "todo");
const isLastStage = $derived(stageKey === "shot");
const panelProps = $derived.by(() => {
const stage = currentStage;
if (!stage) return null;
return { stage };
});
function handleRun(key: WorkbenchStageKey) {
$runMutation.mutate({key,instruction:(instructions[key] ?? '').trim()});
}
</script>
<AppShell
active="workbench"
title={overview?.project.title ?? "项目"}
workspace
>
{#snippet pageHeader({ openSearch })}<StudioHeader
title={overview?.project.title ?? "项目"}
project
onSearch={openSearch}
/>{/snippet}
{#if !$overviewQuery.data && $overviewQuery.isLoading}<div class="project-load-pad">
<Skeleton height="64px" /><Skeleton height="280px" />
</div>
{:else if !overview}<div class="project-load-pad">
<p class="load-error">
{t("workbench.loadFailed")}<button
class="a-btn ghost"
onclick={() => $overviewQuery.refetch()}
>{t("workbench.retryLoad")}</button
>
</p>
</div>
{:else}
<div class="project-workspace" data-testid="workbench-page">
<StageStepper {stages} activeKey={stageKey} onSelect={selectStage} />
<div class="project-body">
<section class="project-main">
{#if currentStage?.error || (currentStage?.last_run?.status === "failed" && currentStage?.last_run?.error)}<div
class="error-banner"
data-testid="stage-error"
>
{currentStage.last_run?.error ?? currentStage.error}
</div>{/if}
{#if stageStatus === "awaiting_confirm"}<div
class="project-draftbar"
data-testid="draft-banner"
>
<Icon name="project-agent" size={18} /><span
><b>{currentAgent?.name ?? STAGE_LABEL[stageKey] + "助手"}</b
>交回了本阶段草稿。确认后才会交给下一阶段使用。</span
><span class="b3-grow"></span><button
class="a-btn ghost sm"
onclick={openAgentChat}>在智能体中打开</button
><button
class="a-btn secondary sm"
disabled={!currentStage?.confirmed_content}
onclick={() => (compareOpen = true)}>对比已确认版</button
>
</div>{/if}
{#if stageStatus === "running"}<div
class="project-draftbar"
data-testid="running-banner"
>
<span class="breath"></span>{t("workbench.runningHint", {
agent: agentName(stageKey),
})}
</div>{/if}
<div class="project-content">
{#if panelProps}
<div class="stage-panel">
{#if currentStage?.assistant_note || noteOpen}<details
class="stage-note"
open
>
<summary>助手建议 · 待整理到阶段内容</summary>
{#if noteOpen}<textarea
class="a-input"
aria-label="编辑阶段助手建议"
bind:value={noteText}
></textarea>
<div class="note-actions">
<button
class="a-btn ghost sm"
disabled={noteBusy}
onclick={() => (noteOpen = false)}>取消</button
><button
class="a-btn secondary sm"
disabled={noteBusy}
onclick={saveNote}>保存建议</button
>
</div>
{:else}<p>{currentStage?.assistant_note}</p>
<button
class="a-btn ghost sm"
disabled={busyFor(stageKey)}
onclick={() => {
noteText = currentStage?.assistant_note ?? "";
noteOpen = true;
}}>编辑建议</button
>{/if}
</details>{/if}
{#if stageKey === "script"}
<ScriptStagePanel
bind:this={editor}
stage={panelProps.stage}
projectIdea={overview.project.idea}
busy={busyFor("script")}
onSave={(content) =>
$saveMutation.mutate({ key: "script", content })}
onImport={(text) => $importMutation.mutate(text)}
onRun={() => handleRun("script")}
/>
{:else if stageKey === "style"}
<StyleStagePanel
bind:this={editor}
stage={panelProps.stage}
bind:chosenStyleId
busy={busyFor("style")}
onSave={(content) =>
$saveMutation.mutate({ key: "style", content })}
onRun={() => handleRun("style")}
/>
{:else if stageKey === "storyboard"}
<StoryboardStagePanel
bind:this={editor}
{projectId}
stage={panelProps.stage}
busy={busyFor("storyboard")}
onSave={(content) =>
$saveMutation.mutate({ key: "storyboard", content })}
onRun={() => handleRun("storyboard")}
/>
{:else if stageKey === "assets"}
<AssetsStagePanel
bind:this={editor}
stage={panelProps.stage}
{projectId}
busy={busyFor("assets")}
onSave={(content) =>
$saveMutation.mutate({ key: "assets", content })}
onRun={() => handleRun("assets")}
{onGenerate}
onRetryJob={(jobId) => $retryMutation.mutate(jobId)}
/>
{:else}
<ShotStagePanel
bind:this={editor}
stage={panelProps.stage}
{projectId}
busy={busyFor("shot")}
onSave={(content) =>
$saveMutation.mutate({ key: "shot", content })}
onRun={() => handleRun("shot")}
{onGenerate}
onRetryJob={(jobId) => $retryMutation.mutate(jobId)}
/>
{/if}
</div>
{/if}
</div>
</section>
<aside class="project-side">
<section class="project-assistant">
<h3>本阶段助手</h3>
<div class="project-agent">
<span class="agent-icon"><Icon name="project-grid" size={20} /></span>
<div class="b3-grow">
<b>{currentAgent?.name ?? STAGE_LABEL[stageKey] + "助手"}</b
><small
>{currentModelName ?? "未配置模型"} · {currentAgent?.skill_count ??
0} 个技能</small
>
</div>
<button
class="a-btn ghost sm"
disabled={!currentAgent}
onclick={openAgentChat}>对话</button
>
</div>
<div class="stage-input-wrap"><textarea
class="stage-instruction"
bind:value={instructions[stageKey]}
placeholder="补充要求(可选):节奏更慢、第 3 镜改俯拍…"
disabled={busyFor(stageKey)}
data-testid="stage-instruction"
></textarea></div>
<div class="b3-row">
<button
class="a-btn secondary sm b3-grow"
disabled={busyFor(stageKey) || $runMutation.isPending}
onclick={() => handleRun(stageKey)}
data-testid="stage-run-btn"
><Icon name="project-refresh" size={14} />{stageStatus === "todo"
? "生成本阶段"
: "重新生成本阶段"}</button
><button
class="a-btn ghost sm"
disabled={!currentStage?.confirmed_content ||
busyFor(stageKey) ||
$restoreMutation.isPending}
onclick={() => $restoreMutation.mutate(stageKey)}
data-testid="stage-restore-btn">恢复已确认版</button
>
</div>
{#if stageKey === "shot"}<a
class="a-btn secondary sm"
href={resolve("/build-scene")}>三维搭景 · 截取参考图</a
>{/if}
</section>
<section class="project-task-heading">
<h3>阶段任务 <span class="a-tag">{projectJobs.length}</span></h3>
<span class="b3-grow"></span><a
class="a-btn ghost sm"
href={resolve("/tasks")}>全部</a
>
</section>
<div class="project-tasks">
{#if projectJobs.length === 0}
<p class="jobs-empty">{t("workbench.tasksEmpty")}</p>
{:else}
<ul class="jobs-list" data-testid="workbench-jobs">
{#each projectJobs.slice(0, 8) as job (job.id)}
{@const live = jobProgressPct(job.id)}
<li class="job-row">
<span class="job-kind kind-{job.kind}">
<Icon
name={job.kind === "image" ? "image" : "film"}
size={12}
/>
</span>
<span class="job-body">
<span class="job-prompt"
>{job.payload?.prompt ??
job.payload?.source ??
`#${job.id}`}</span
>
<span class="job-time mono"
>{jobTime(job.created_at)}</span
>
</span>
<span class="job-state st-{job.status}">
{#if job.status === "running"}
<span class="breath"></span>
{#if live != null}{Math.round(live)}%{:else}{t(
"workbench.jobRunning",
)}{/if}
{:else if job.status === "pending"}
{t("workbench.jobQueued")}
{:else if job.status === "done"}
{t("workbench.jobDone")}
{:else}
{t("workbench.jobFailed")}
{/if}
</span>
{#if job.status === "pending" || job.status === "running"}
<button
type="button"
class="icon-btn"
title={t("workbench.cancelJob")}
onclick={() => $cancelMutation.mutate(job.id)}
>
<Icon name="stop" size={12} />
</button>
{:else if job.status === "failed"}
<button
type="button"
class="icon-btn"
title={t("workbench.retryJob")}
onclick={() => $retryMutation.mutate(job.id)}
>
<Icon name="project-refresh" size={12} />
</button>
{:else if job.output_paths?.[0]}
<a
class="icon-btn"
href={assetUrl(job.output_paths[0]) ?? "#"}
target="_blank"
rel="noopener external"
title={t("workbench.openOutput")}
>
<Icon name="external-link" size={12} />
</a>
{/if}
</li>
{/each}
</ul>
{/if}
</div>
</aside>
</div>
<footer class="project-footer">
<span class="a-tag {STATUS_CLASS[stageStatus]}"
>{t(STATUS_LABEL[stageStatus])}</span
><span class="project-save-state"
>{currentStage?.draft_edited
? "已编辑 · 草稿待确认"
: "确认后才会交给下一阶段使用"}</span
><span class="b3-grow"></span><button class="a-btn secondary" disabled={busyFor(stageKey) || !currentStage?.content || $saveMutation.isPending} onclick={() => editor?.saveDraft()} data-testid="stage-save-btn">保存草稿</button><button
class="a-btn primary"
disabled={stageStatus !== "awaiting_confirm" ||
$confirmMutation.isPending || !!editor?.hasUnsavedDraft()}
onclick={() => $confirmMutation.mutate(stageKey)}
data-testid="stage-confirm-btn"
><Icon name="project-check" size={14} />{isLastStage
? "确认镜头脚本"
: `确认${STAGE_LABEL[stageKey]},进入${STAGE_LABEL[STAGE_ORDER[STAGE_ORDER.indexOf(stageKey) + 1]]}阶段`}</button
>
</footer>
</div>{/if}
</AppShell>
<Modal bind:open={compareOpen} title="对比已确认版"
><div class="project-compare">
<section>
<h3>已确认版</h3>
<pre>{JSON.stringify(currentStage?.confirmed_content, null, 2)}</pre>
</section>
<section>
<h3>当前草稿</h3>
<pre>{JSON.stringify(currentStage?.content, null, 2)}</pre>
</section>
</div></Modal
>