Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Character Swap Studio: the projects page and the workbench

Claude39a13a6d46b4
diff --git a/src/app/(studio)/character-swap/[id]/page.tsx b/src/app/(studio)/character-swap/[id]/page.tsx
new file mode 100644
index 00000000..617a9a05
--- /dev/null
+++ b/src/app/(studio)/character-swap/[id]/page.tsx
@@ -0,0 +1,21 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { Suspense } from "react";
+import { SwapWorkbench } from "@/components/swap-studio/workbench";
+import { recordExists } from "@/server/records";
+
+export const metadata: Metadata = { title: "Character Swap" };
+
+async function Project({ params }: { params: PageProps<"/character-swap/[id]">["params"] }) {
+ const { id } = await params;
+ if (!recordExists({ kind: "swap-project", ids: [id] })) notFound();
+ return <SwapWorkbench id={id} />;
+}
+
+export default function Page({ params }: PageProps<"/character-swap/[id]">) {
+ return (
+ <Suspense fallback={null}>
+ <Project params={params} />
+ </Suspense>
+ );
+}
diff --git a/src/app/(studio)/character-swap/page.tsx b/src/app/(studio)/character-swap/page.tsx
new file mode 100644
index 00000000..8bc84483
--- /dev/null
+++ b/src/app/(studio)/character-swap/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { SwapStudioHome } from "@/components/swap-studio/home";
+
+export const metadata: Metadata = { title: "Character Swap Studio" };
+
+export default function Page() {
+ return <SwapStudioHome />;
+}
diff --git a/src/components/genjutsu/character-panel.tsx b/src/components/genjutsu/character-panel.tsx
index 1844a441..9281f9b0 100644
--- a/src/components/genjutsu/character-panel.tsx
+++ b/src/components/genjutsu/character-panel.tsx
@@ -1,6 +1,7 @@
"use client";
-import { AudioLines, Cpu, Loader2, Scale, Sparkles, TriangleAlert } from "lucide-react";
+import { AudioLines, Cpu, Drama, Loader2, Scale, Sparkles, TriangleAlert } from "lucide-react";
+import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
@@ -318,6 +319,11 @@ export function CharacterFacts({ engine, maker, cut }: { engine: Engine; maker:
<Scale className="mt-0.5 size-3.5 shrink-0" />
<span>Licences are information: each model&apos;s is under its name above, and your admin decides what runs (Settings → Models &amp; licences).</span>
</p>
+ {/* Whole clips, shot by shot, with masks, anchors, segments and takes: the studio built on the same H3 recipe. */}
+ <Link href="/character-swap" className="inline-flex items-center gap-1 font-medium text-brand-text hover:underline">
+ <Drama className="size-3.5" /> Open in Character Swap Studio
+ <span className="font-normal text-muted-foreground">— whole clips, shot by shot</span>
+ </Link>
</div>
);
}
diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsx
index 8a032bbb..31210062 100644
--- a/src/components/genjutsu/genjutsu-studio.tsx
+++ b/src/components/genjutsu/genjutsu-studio.tsx
@@ -1,6 +1,7 @@
"use client";
import { Brush, Download, Info, Loader2, RotateCcw, Sparkles, Undo2, Wand2 } from "lucide-react";
+import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { nanoid } from "nanoid";
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
@@ -446,7 +447,15 @@ export function GenjutsuStudio() {
return (
<ToolShell title="Genjutsu" tabs={tabs} header={<SetupCode setup={setup} onPaste={apply} />} wide>
- {!clip && <ToolHero title={modeInfo.label} subtitle={`${modeInfo.hint} Priced before it runs; free on your own ComfyUI.`} />}
+ {!clip && (
+ <ToolHero title={modeInfo.label} subtitle={`${modeInfo.hint} Priced before it runs; free on your own ComfyUI.`}>
+ {isCharacter && (
+ <Link href="/character-swap" className="mt-3 inline-flex items-center gap-1 text-[13px] font-medium text-brand-text hover:underline">
+ Whole clips, shot by shot? Open in Character Swap Studio
+ </Link>
+ )}
+ </ToolHero>
+ )}
<div className={cn("mx-auto", clip ? "pt-4" : "mt-8 max-w-[640px]")}>
{!clip ? (
<ClipDrop
diff --git a/src/components/nav-items.ts b/src/components/nav-items.ts
index 7176e2bc..11f9dcc8 100644
--- a/src/components/nav-items.ts
+++ b/src/components/nav-items.ts
@@ -6,6 +6,7 @@ import {
Brush,
Camera,
Clapperboard,
+ Drama,
Crop,
Factory,
FastForward,
@@ -113,6 +114,7 @@ export const NAV: NavGroupDef[] = [
{ href: "/explainer", label: "Explainer", icon: Presentation, keywords: "slides pdf video" },
{ href: "/lipsync", label: "Lipsync & avatars", icon: Mic2, keywords: "talking avatar" },
{ href: "/genjutsu", label: "Genjutsu", icon: WandSparkles, keywords: "swap insert character motion transfer" },
+ { href: "/character-swap", label: "Character Swap Studio", short: "Character swap", icon: Drama, keywords: "h3 akatz swap character whole clip shots segments takes" },
{ href: "/motion-control", label: "Motion control", icon: PersonStanding, keywords: "pose dance transfer" },
{ href: "/video-edit", label: "Edit video", icon: Scissors, keywords: "video edit restyle" },
{ href: "/extend", label: "Extend video", icon: FastForward, keywords: "longer continue" },
diff --git a/src/components/remove-object/frame-stage.tsx b/src/components/remove-object/frame-stage.tsx
index 397ca9c6..64352ee3 100644
--- a/src/components/remove-object/frame-stage.tsx
+++ b/src/components/remove-object/frame-stage.tsx
@@ -28,6 +28,7 @@ export function FrameStage({
clickable,
maxPoints,
children,
+ words = { positive: "remove", negative: "keep", ask: "Click what to remove", frame: "First frame" },
}: {
frame: Frame;
points: PixelPoint[];
@@ -39,6 +40,8 @@ export function FrameStage({
clickable: boolean;
maxPoints: number;
children?: React.ReactNode;
+ /** What the points mean, for the labels (Character Swap Studio: include / exclude on any frame). */
+ words?: { positive: string; negative: string; ask: string; frame: string };
}) {
const box = useRef<HTMLDivElement>(null);
const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null);
@@ -74,7 +77,7 @@ export function FrameStage({
role={clickable ? "application" : undefined}
aria-label={
clickable
- ? `First frame. Click what to remove${pointLabel === "negative" ? " — marking what to keep" : ""}. Arrow keys move a crosshair, Enter adds a point, Delete removes the last. ${points.length} point${points.length === 1 ? "" : "s"} so far.`
+ ? `${words.frame}. ${words.ask}${pointLabel === "negative" ? ` — marking what to ${words.negative}` : ""}. Arrow keys move a crosshair, Enter adds a point, Delete removes the last. ${points.length} point${points.length === 1 ? "" : "s"} so far.`
: undefined
}
onKeyDown={onKey}
@@ -94,7 +97,7 @@ export function FrameStage({
style={{ aspectRatio: `${frame.width} / ${frame.height}`, width: `min(100%, calc(min(46vh, 520px) * ${(frame.width / frame.height).toFixed(4)}))` }}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
- <img src={overlay ?? frame.url} alt="The first frame of the selection" className="absolute inset-0 size-full object-contain select-none" draggable={false} />
+ <img src={overlay ?? frame.url} alt={words.frame === "First frame" ? "The first frame of the selection" : words.frame} className="absolute inset-0 size-full object-contain select-none" draggable={false} />
{points.map((p, i) => (
<span
key={i}
@@ -124,10 +127,10 @@ export function FrameStage({
type="button"
onClick={() => onPoints(points.filter((_, j) => j !== i))}
className="inline-flex h-7 items-center gap-1 rounded-full bg-muted px-2.5 text-[12px] font-medium hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
- aria-label={`Take away point ${i + 1} (${p.label === "negative" ? "keep" : "remove"})`}
+ aria-label={`Take away point ${i + 1} (${p.label === "negative" ? words.negative : words.positive})`}
>
<span className={cn("size-2 rounded-full", p.label === "negative" ? "bg-zinc-500" : "bg-success")} />
- {i + 1} · {p.label === "negative" ? "keep" : "remove"}
+ {i + 1} · {p.label === "negative" ? words.negative : words.positive}
<X className="size-3 text-muted-foreground" />
</button>
</li>
diff --git a/src/components/swap-studio/home.tsx b/src/components/swap-studio/home.tsx
new file mode 100644
index 00000000..40aea647
--- /dev/null
+++ b/src/components/swap-studio/home.tsx
@@ -0,0 +1,180 @@
+"use client";
+
+import { ArrowRight, Drama, Film, Layers, Loader2, Scissors, Sparkles, Trash2, UserRound } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import { useEngine } from "@/lib/api";
+import { characterLicenceLine } from "@/lib/catalog/character-swap";
+import { SWAP_STUDIO, type SwapProjectCard } from "@/lib/catalog/swap-studio";
+import { STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";
+import { useCreateSwapProject, useDeleteSwapProject, useSwapProjects } from "./hooks";
+
+const STEPS = [
+ { icon: Film, title: "Clips and your character", text: "Add whole clips (MP4, MOV, MKV, WebM or AVI, up to 149.66 s) and a picture of who comes in." },
+ { icon: Scissors, title: "Shots and words", text: "Find the edits, keep or replace each shot, transcribe who says what and build the prompts." },
+ { icon: UserRound, title: "Who and the scene", text: "Click who to swap on any frame, track the shot, approve a mask and a scene anchor." },
+ { icon: Layers, title: "Segments and takes", text: "Render each shot in segments that continue from each other, compare takes, keep the best, assemble." },
+];
+
+const ago = (t: number) => {
+ const s = Math.max(0, (Date.now() - t) / 1000);
+ if (s < 60) return "just now";
+ if (s < 3600) return `${Math.round(s / 60)} min ago`;
+ if (s < 86_400) return `${Math.round(s / 3600)} h ago`;
+ return new Date(t).toLocaleDateString();
+};
+
+export function SwapStudioHome() {
+ const router = useRouter();
+ const [engine, setEngine] = useEngine();
+ const projects = useSwapProjects();
+ const create = useCreateSwapProject();
+ const del = useDeleteSwapProject();
+ const [name, setName] = useState("");
+ const [confirm, setConfirm] = useState<SwapProjectCard | null>(null);
+ const nameId = useId();
+
+ const start = () =>
+ create.mutate(
+ { name: name.trim() || undefined, engine },
+ {
+ onSuccess: (p) => router.push(`/character-swap/${p.id}`),
+ onError: (e) => toast.error((e as Error).message),
+ },
+ );
+
+ return (
+ <ToolShell title="Character Swap Studio" engineSwitch={false} header={<EngineSwitch value={engine} onChange={setEngine} />} wide>
+ <ToolHero
+ title="Swap a character through whole clips"
+ subtitle="Akatz Labs' H3 Character Swap workbench, shot by shot: on your GPU with H3 Relay 2.0 (masks, history, lossless continuations), or in the cloud with fal's MiniMax H3 and the swap LoRA."
+ >
+ <form
+ className="mt-6 flex w-full max-w-lg flex-col gap-2 sm:flex-row"
+ onSubmit={(e) => {
+ e.preventDefault();
+ start();
+ }}
+ >
+ <label htmlFor={nameId} className="sr-only">
+ Project name
+ </label>
+ <input
+ id={nameId}
+ value={name}
+ maxLength={SWAP_STUDIO.maxNameChars}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="Name the project (“Rain scene, take 2”)"
+ className="h-10 min-w-0 flex-1 rounded-full border bg-background px-4 text-[14px] outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ <Button type="submit" className="h-10 rounded-full px-5" disabled={create.isPending}>
+ {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Drama className="size-4" />}
+ New project · {engine === "open" ? "your GPU" : "cloud"}
+ </Button>
+ </form>
+ </ToolHero>
+
+ <ol className="mx-auto mt-8 grid max-w-[1040px] gap-3 sm:grid-cols-2 lg:grid-cols-4" aria-label="How it works">
+ {STEPS.map((s, i) => (
+ <li key={s.title} className="rounded-2xl border bg-background p-3 shadow-soft">
+ <span className="flex items-center gap-2 text-[13px] font-semibold">
+ <span className="grid size-7 place-items-center rounded-full bg-brand-faint text-brand-text">
+ <s.icon className="size-4" aria-hidden />
+ </span>
+ {i + 1}. {s.title}
+ </span>
+ <p className="mt-1.5 text-[12px] leading-snug text-pretty text-muted-foreground">{s.text}</p>
+ </li>
+ ))}
+ </ol>
+
+ <section className="mt-8" aria-labelledby="swap-projects">
+ <h2 id="swap-projects" className="mb-3 text-[15px] font-semibold">
+ Projects
+ </h2>
+ {projects.isLoading ? (
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-28 rounded-2xl" />
+ ))}
+ </div>
+ ) : !projects.data?.length ? (
+ <p className="rounded-2xl border border-dashed px-4 py-8 text-center text-[13px] text-muted-foreground">No projects yet — name one above to start.</p>
+ ) : (
+ <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
+ {projects.data.map((p) => (
+ <li key={p.id} className="group relative flex min-w-0 gap-3 rounded-2xl border bg-background p-3 shadow-soft transition-colors hover:border-border-strong">
+ <div className="grid size-20 shrink-0 place-items-center overflow-hidden rounded-xl bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {p.character ? <img src={p.character} alt="" className="size-full object-cover" /> : <Drama className="size-6 text-muted-foreground" aria-hidden />}
+ </div>
+ <div className="min-w-0 flex-1">
+ <Link href={`/character-swap/${p.id}`} className="block truncate text-[14px] font-semibold after:absolute after:inset-0 after:rounded-2xl focus-visible:outline-none">
+ {p.name}
+ </Link>
+ <p className="mt-0.5 text-[12px] text-muted-foreground">
+ {p.engine === "open" ? "Your GPU" : "Cloud"} · {p.clips} clip{p.clips === 1 ? "" : "s"} · {p.swapped}/{p.shots} shots swapped
+ </p>
+ <p className="mt-0.5 text-[12px] text-muted-foreground">
+ {p.assembled ? `${p.assembled} assembled · ` : ""}
+ {p.waiting ? `${p.waiting} waiting · ` : ""}
+ {ago(p.updatedAt)}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => setConfirm(p)}
+ aria-label={`Delete ${p.name}`}
+ className="relative z-10 grid size-8 shrink-0 place-items-center self-start rounded-full text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ >
+ <Trash2 className="size-4" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+
+ <Panel title="Licences" className="mt-8">
+ <ul className="space-y-1 text-[12px] text-pretty text-muted-foreground">
+ <li>Your GPU: {characterLicenceLine("open", STUDIO_MODELS.open.swap)}</li>
+ <li>Cloud: {characterLicenceLine("cloud", STUDIO_MODELS.cloud.swap)}</li>
+ <li>The workbench follows Akatz Labs&apos; H3 Character Swap tool (MIT); its prompts are reused with that notice. The swap LoRA releases are Akatz Labs&apos;.</li>
+ </ul>
+ <Link href="/genjutsu?mode=character" className="mt-3 inline-flex items-center gap-1 text-[13px] font-medium text-brand-text hover:underline">
+ <Sparkles className="size-3.5" /> One quick swap of one part instead? Genjutsu → Character swap <ArrowRight className="size-3.5" />
+ </Link>
+ </Panel>
+
+ <AlertDialog open={!!confirm} onOpenChange={(o) => !o && setConfirm(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete “{confirm?.name}”?</AlertDialogTitle>
+ <AlertDialogDescription>Its clips, shots, masks, anchors and takes go; what it still makes is stopped. Assembled clips stay in the Library.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep it</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() =>
+ confirm &&
+ del.mutate(confirm.id, {
+ onSuccess: () => toast("Project deleted"),
+ onError: (e) => toast.error((e as Error).message),
+ })
+ }
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </ToolShell>
+ );
+}
diff --git a/src/components/swap-studio/hooks.ts b/src/components/swap-studio/hooks.ts
new file mode 100644
index 00000000..fc160b2b
--- /dev/null
+++ b/src/components/swap-studio/hooks.ts
@@ -0,0 +1,128 @@
+"use client";
+
+import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import type { QueueMode, StudioEstimate, SwapProject, SwapProjectCard, SwapProjectView } from "@/lib/catalog/swap-studio";
+import type { SwapEdit } from "@/lib/catalog/swap-studio-edit";
+import type { Engine, PixelPoint } from "@/lib/catalog/types";
+
+/** React Query hooks for /api/swap-studio/** (Character Swap Studio). */
+
+async function json<T>(res: Response): Promise<T> {
+ if (res.status === 204) return undefined as T;
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
+ return body;
+}
+
+const send = async <T>(url: string, method: string, body?: unknown) =>
+ json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));
+
+const base = (id: string) => `/api/swap-studio/projects/${encodeURIComponent(id)}`;
+
+/** Whether anything in the view is still being made (the page polls while it is). */
+export function viewBusy(v: SwapProjectView | undefined): boolean {
+ if (!v) return false;
+ if (Object.values(v.gens).some((g) => g.status === "queued" || g.status === "running")) return true;
+ return v.project.clips.some((c) => c.shots.some((s) => (s.segments ?? []).some((g) => g.takes.some((t) => t.state === "waiting"))));
+}
+
+export function useSwapProjects() {
+ return useQuery({
+ queryKey: ["swap-studio", "projects"],
+ queryFn: async () => (await json<{ items: SwapProjectCard[] }>(await fetch("/api/swap-studio/projects"))).items,
+ refetchInterval: (q) => (q.state.data?.some((p) => p.waiting > 0) ? 5000 : false),
+ });
+}
+
+export function useSwapProject(id: string) {
+ return useQuery({
+ queryKey: ["swap-studio", "project", id],
+ queryFn: async () => json<SwapProjectView>(await fetch(base(id))),
+ retry: (n, e) => !/not found/i.test((e as Error).message) && n < 2,
+ refetchInterval: (q) => (viewBusy(q.state.data) ? 1500 : false),
+ });
+}
+
+/** Prices for the project as it reads now (refetched when it changes). */
+export function useSwapEstimate(id: string, revision: number | undefined, engine: Engine | undefined) {
+ return useQuery({
+ queryKey: ["swap-studio", "estimate", id, revision ?? 0, engine],
+ enabled: revision !== undefined,
+ queryFn: async () => json<StudioEstimate>(await fetch(`${base(id)}/estimate`)),
+ placeholderData: keepPreviousData,
+ staleTime: 10_000,
+ });
+}
+
+/** Put a project the server answered with into the cache (its jobs' states come with the next poll). */
+function useSetProject(id: string) {
+ const qc = useQueryClient();
+ return (p: SwapProject) => {
+ qc.setQueryData<SwapProjectView>(["swap-studio", "project", id], (v) => (v ? { ...v, project: p } : v));
+ void qc.invalidateQueries({ queryKey: ["swap-studio", "project", id] });
+ void qc.invalidateQueries({ queryKey: ["swap-studio", "projects"] });
+ };
+}
+
+export function useCreateSwapProject() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (b: { name?: string; engine: Engine; character?: { image?: string | null; description?: string } }) => send<SwapProject>("/api/swap-studio/projects", "POST", b),
+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["swap-studio", "projects"] }),
+ });
+}
+
+export function useDeleteSwapProject() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => send<void>(base(id), "DELETE"),
+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["swap-studio"] }),
+ });
+}
+
+/** Edits: the page sends anchor imports without an id (the server names them). */
+export type EditInput = SwapEdit extends infer E ? (E extends { type: "anchor-import" } ? Omit<E, "id" | "at"> : E) : never;
+
+export function useSwapEdit(id: string) {
+ const set = useSetProject(id);
+ return useMutation({ mutationFn: (e: EditInput) => send<SwapProject>(base(id), "PATCH", e), onSuccess: set });
+}
+
+export interface ClipInput {
+ url: string;
+ name?: string;
+ duration?: number;
+ width?: number;
+ height?: number;
+ fps?: number;
+ hasAudio?: boolean;
+ bytes?: number;
+}
+
+/** What "Queue …" answers: the project, the takes it made and any notes (a LoRA switched off). */
+export interface QueueAnswer {
+ project: SwapProject;
+ takes: string[];
+ notes: string[];
+}
+
+/** One mutation per job route, each answering with the project (or, for the queue, the project and the takes). */
+function useAction<B, R extends SwapProject | QueueAnswer = SwapProject>(id: string, path: string) {
+ const set = useSetProject(id);
+ return useMutation({ mutationFn: (b: B) => send<R>(`${base(id)}/${path}`, "POST", b), onSuccess: (r) => set("clips" in r ? r : r.project) });
+}
+
+export const useAddClip = (id: string) => useAction<ClipInput>(id, "clips");
+export const usePrepareClip = (id: string) => useAction<{ clipId: string }>(id, "prepare");
+export const useTranscribe = (id: string) => useAction<{ clipId: string }>(id, "transcribe");
+export const useMakeMask = (id: string) =>
+ useAction<{ clipId: string; shotId: string; kind: "track" | "frame"; frame: number; points: PixelPoint[]; size?: { width: number; height: number }; base?: string }>(id, "masks");
+export const useMakeAnchor = (id: string) => useAction<{ clipId: string; shotId: string; segmentId?: string; modelId?: string; seed?: number }>(id, "anchors");
+export const useQueue = (id: string) => useAction<{ clipId: string; shotId: string; segmentId: string; mode: QueueMode }, QueueAnswer>(id, "queue");
+export const useStopTake = (id: string) => useAction<{ clipId: string; shotId: string; segmentId: string; takeId: string }>(id, "takes/stop");
+export const useStopJob = (id: string) =>
+ useAction<{ kind: "mask" | "anchor" | "assembly" | "normalize" | "transcribe"; clipId: string; shotId?: string; segmentId?: string; jobId?: string }>(id, "stop");
+export const useAssemble = (id: string) => useAction<{ clipId: string }>(id, "assemble");
+
+/** The Export decisions download link. */
+export const decisionsHref = (id: string) => `${base(id)}/decisions`;
diff --git a/src/components/swap-studio/parts.tsx b/src/components/swap-studio/parts.tsx
new file mode 100644
index 00000000..05985162
--- /dev/null
+++ b/src/components/swap-studio/parts.tsx
@@ -0,0 +1,173 @@
+"use client";
+
+import { AlertTriangle, CheckCircle2, CircleDashed, CircleSlash, Loader2, Pause } from "lucide-react";
+import { openVideo, releaseVideo, sampleFrames } from "@/components/av/frame-sampler";
+import { frameFromBlob, type Frame } from "@/components/remove-object/frame-stage";
+import { jobState, type GenSummary, type JobStatus } from "@/lib/catalog/swap-studio";
+import type { Engine } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+
+/** Small pieces shared by Character Swap Studio's stages. */
+
+/** "≈ $0.38", "Free · your GPU", "Demo · free", "Price unknown". */
+export function priceText(costUsd: number | null | undefined, o: { demo?: boolean; engine: Engine }): string {
+ if (o.demo) return "Demo · free";
+ if (o.engine === "open") return "Free · your GPU";
+ if (costUsd === undefined) return "…";
+ if (costUsd === null) return "Price unknown";
+ if (costUsd === 0) return "Free";
+ return `≈ $${costUsd < 1 ? costUsd.toFixed(3).replace(/0$/, "") : costUsd.toFixed(2)}`;
+}
+
+const LABELS: Record<JobStatus, string> = {
+ waiting: "Waiting",
+ queued: "Queued",
+ running: "Making",
+ succeeded: "Ready",
+ failed: "Failed",
+ canceled: "Stopped",
+ stopped: "Stopped",
+ missing: "",
+};
+
+/** A job's state as a small chip (with its progress while it runs). */
+export function JobChip({ status, progress, message, className }: { status: JobStatus; progress?: number | null; message?: string | null; className?: string }) {
+ if (status === "missing") return null;
+ const Icon = status === "succeeded" ? CheckCircle2 : status === "failed" ? AlertTriangle : status === "canceled" || status === "stopped" ? CircleSlash : status === "waiting" ? Pause : status === "queued" ? CircleDashed : Loader2;
+ return (
+ <span
+ title={message ?? undefined}
+ className={cn(
+ "inline-flex h-6 max-w-full min-w-0 items-center gap-1 rounded-full px-2 text-[11px] font-medium",
+ status === "succeeded" && "bg-success/12 text-success",
+ status === "failed" && "bg-destructive/10 text-destructive",
+ (status === "canceled" || status === "stopped") && "bg-muted text-muted-foreground",
+ (status === "queued" || status === "running" || status === "waiting") && "bg-brand-faint text-brand-text",
+ className,
+ )}
+ >
+ <Icon className={cn("size-3 shrink-0", status === "running" && "animate-spin")} aria-hidden />
+ <span className="truncate">
+ {LABELS[status]}
+ {status === "running" && progress != null ? ` · ${Math.round(progress * 100)}%` : ""}
+ </span>
+ </span>
+ );
+}
+
+/** A job's chip from its generations. */
+export function GenChip({ genId, stepIds, gens, className }: { genId?: string; stepIds?: string[]; gens: Record<string, GenSummary>; className?: string }) {
+ const s = jobState(genId, stepIds, gens);
+ return <JobChip status={s.status} progress={s.progress} message={s.message} className={className} />;
+}
+
+/** What went wrong with a job, in a line (nothing while it is fine). */
+export function JobError({ genId, stepIds, gens }: { genId?: string; stepIds?: string[]; gens: Record<string, GenSummary> }) {
+ const s = jobState(genId, stepIds, gens);
+ if ((s.status !== "failed" && s.status !== "canceled") || !s.message) return null;
+ return <p className="text-[12px] text-pretty text-destructive">{s.message}</p>;
+}
+
+/** A frame of a video as a still (the browser's decode, at most `maxWidth` wide), for clicking who to swap. */
+export async function grabFrame(src: string, seconds: number, maxWidth = 960): Promise<Frame> {
+ const v = await openVideo(src);
+ try {
+ const width = Math.max(2, Math.min(maxWidth, v.videoWidth || maxWidth));
+ const [f] = await sampleFrames(v, [Math.max(0, Math.min(seconds, (v.duration || seconds) - 0.02))], { width });
+ const canvas = document.createElement("canvas");
+ canvas.width = f.data.width;
+ canvas.height = f.data.height;
+ canvas.getContext("2d")!.putImageData(f.data, 0, 0);
+ const blob = await new Promise<Blob>((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Couldn't read that frame"))), "image/jpeg", 0.9));
+ return frameFromBlob(blob);
+ } finally {
+ releaseVideo(v);
+ }
+}
+
+/** A labelled number input that commits on blur or Enter. */
+export function NumberField({
+ label,
+ value,
+ min,
+ max,
+ onCommit,
+ className,
+ disabled,
+}: {
+ label: string;
+ value: number;
+ min?: number;
+ max?: number;
+ onCommit: (v: number) => void;
+ className?: string;
+ disabled?: boolean;
+}) {
+ return (
+ <label className={cn("flex min-w-0 flex-col gap-1 text-[12px] font-medium", className)}>
+ {label}
+ <input
+ key={value}
+ type="number"
+ inputMode="numeric"
+ defaultValue={value}
+ min={min}
+ max={max}
+ disabled={disabled}
+ onBlur={(e) => {
+ const n = Number(e.currentTarget.value);
+ if (Number.isFinite(n) && n !== value) onCommit(Math.round(n));
+ }}
+ onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
+ className="h-8 w-full min-w-0 rounded-md border bg-background px-2 font-mono text-[13px] tabular-nums outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"
+ />
+ </label>
+ );
+}
+
+/** A textarea that saves when it loses focus (and shows what's saved until then). */
+export function SavedText({
+ label,
+ value,
+ placeholder,
+ onSave,
+ rows = 3,
+ max,
+ hint,
+ disabled,
+}: {
+ label: string;
+ value: string;
+ placeholder?: string;
+ onSave: (v: string) => void;
+ rows?: number;
+ max?: number;
+ hint?: React.ReactNode;
+ disabled?: boolean;
+}) {
+ return (
+ <label className="flex min-w-0 flex-col gap-1">
+ <span className="flex items-baseline justify-between gap-2 text-[12px] font-medium">
+ {label}
+ {hint && <span className="truncate font-normal text-muted-foreground">{hint}</span>}
+ </span>
+ <textarea
+ key={value}
+ defaultValue={value}
+ placeholder={placeholder}
+ rows={rows}
+ maxLength={max}
+ disabled={disabled}
+ onBlur={(e) => e.currentTarget.value !== value && onSave(e.currentTarget.value)}
+ className="w-full min-w-0 resize-y rounded-md border bg-background px-2.5 py-2 text-[13px] leading-snug outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"
+ />
+ </label>
+ );
+}
+
+/** A note in the page's quiet style. */
+export function Note({ children, tone = "muted", className }: { children: React.ReactNode; tone?: "muted" | "warn"; className?: string }) {
+ return (
+ <p className={cn("rounded-lg px-3 py-2 text-[12px] leading-snug text-pretty", tone === "warn" ? "bg-warning/10 text-foreground" : "bg-muted text-muted-foreground", className)}>{children}</p>
+ );
+}
diff --git a/src/components/swap-studio/stage-anchors.tsx b/src/components/swap-studio/stage-anchors.tsx
new file mode 100644
index 00000000..2a2ead79
--- /dev/null
+++ b/src/components/swap-studio/stage-anchors.tsx
@@ -0,0 +1,199 @@
+"use client";
+
+import { Check, ImageUp, Loader2, Sparkles, Trash2 } from "lucide-react";
+import { useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Panel } from "@/components/av/tool-shell";
+import { ToggleRow } from "@/components/faceless/controls";
+import { uploadFile } from "@/lib/api";
+import { ANCHOR_MODELS } from "@/lib/catalog/character-swap";
+import { jobState, SWAP_STUDIO, type AnchorVariant, type GenSummary, type SwapSegment } from "@/lib/catalog/swap-studio";
+import { anchorWords } from "@/lib/catalog/swap-studio-plan";
+import type { Engine } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+import { useMakeAnchor, useStopJob, useSwapEdit } from "./hooks";
+import { GenChip, JobError, Note, priceText, SavedText } from "./parts";
+import type { StageProps } from "./workbench";
+
+/** Make (with the engine's image edit) or import an anchor: the shot's scene anchor, or a segment's own reference. */
+export function AnchorMaker({ id, project, clip, shotId, segment, estimate }: Pick<StageProps, "id" | "project" | "clip" | "estimate"> & { shotId: string; segment?: SwapSegment }) {
+ const make = useMakeAnchor(id);
+ const importer = useSwapEdit(id);
+ const engine = project.engine;
+ const models = estimate?.anchors ?? ANCHOR_MODELS[engine].map((m) => ({ ...m, costUsd: null, offered: true }));
+ const [modelId, setModelId] = useState<string>(models.find((m) => m.offered)?.id ?? ANCHOR_MODELS[engine][0].id);
+ const [importing, setImporting] = useState(false);
+ const file = useRef<HTMLInputElement>(null);
+ const picked = models.find((m) => m.id === modelId);
+ const which = segment ? "reference" : "anchor";
+
+ const doImport = async (f: File) => {
+ if (!f.type.startsWith("image/")) return toast.error("Pick an image");
+ setImporting(true);
+ try {
+ const a = await uploadFile(f);
+ await importer.mutateAsync({ type: "anchor-import", clipId: clip.id, shotId, ...(segment ? { segmentId: segment.id } : {}), url: a.url });
+ toast(`Imported the ${which}`);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setImporting(false);
+ }
+ };
+
+ return (
+ <div className="flex min-w-0 flex-wrap items-end gap-2">
+ <label className="flex min-w-0 flex-1 flex-col gap-1 text-[12px] font-medium">
+ Image model
+ <Select value={modelId} onValueChange={setModelId}>
+ <SelectTrigger className="h-8 w-full min-w-0 text-[13px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {models.map((m) => (
+ <SelectItem key={m.id} value={m.id} disabled={!m.offered}>
+ {m.label} · {priceText(m.costUsd, { demo: estimate?.demo, engine })}
+ {!m.offered ? " · switched off" : ""}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ <Button
+ size="sm"
+ className="h-8 rounded-full"
+ disabled={make.isPending || !project.character.image}
+ title={!project.character.image ? "Add a picture of your character first" : picked?.note}
+ onClick={() =>
+ make.mutate({ clipId: clip.id, shotId, ...(segment ? { segmentId: segment.id } : {}), modelId }, { onSuccess: () => toast(`Making a ${which} with ${picked?.label ?? "the image model"}`), onError: (e) => toast.error((e as Error).message) })
+ }
+ >
+ {make.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />} Make {which}
+ </Button>
+ <Button size="sm" variant="outline" className="h-8 rounded-full" disabled={importing} onClick={() => file.current?.click()}>
+ {importing ? <Loader2 className="size-3.5 animate-spin" /> : <ImageUp className="size-3.5" />} Import
+ </Button>
+ <input ref={file} type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files?.[0] && void doImport(e.target.files[0])} />
+ </div>
+ );
+}
+
+/** A grid of anchor variants with their state, approval and removal. */
+export function AnchorGrid({
+ items,
+ chosen,
+ gens,
+ onChoose,
+ onRemove,
+ onStop,
+ chooseLabel,
+}: {
+ items: AnchorVariant[];
+ chosen: string | null;
+ gens: Record<string, GenSummary>;
+ onChoose: (a: AnchorVariant) => void;
+ onRemove: (a: AnchorVariant) => void;
+ onStop: (a: AnchorVariant) => void;
+ chooseLabel: [string, string];
+}) {
+ if (!items.length) return <p className="text-[12px] text-muted-foreground">None yet.</p>;
+ return (
+ <ul className="grid grid-cols-2 gap-2 sm:grid-cols-3">
+ {items.map((a, i) => {
+ const s = jobState(a.genId, a.stepIds, gens);
+ const on = chosen === a.id;
+ return (
+ <li key={a.id} className={cn("min-w-0 space-y-1.5 rounded-xl border p-2", on && "border-success")}>
+ <div className="grid aspect-video place-items-center overflow-hidden rounded-lg bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {a.url ? <img src={a.url} alt={`Variant ${i + 1}`} className="size-full object-contain" /> : <GenChip genId={a.genId} stepIds={a.stepIds} gens={gens} />}
+ </div>
+ <p className="truncate text-[11px] text-muted-foreground">
+ {i + 1} · {a.source === "imported" ? "Imported" : (ANCHOR_MODELS.cloud.concat(ANCHOR_MODELS.open).find((m) => m.id === a.modelId)?.label ?? "Made")}
+ </p>
+ <JobError genId={a.genId} stepIds={a.stepIds} gens={gens} />
+ <div className="flex flex-wrap gap-1">
+ <Button size="sm" variant={on ? "secondary" : "outline"} className="h-7 rounded-full px-2 text-[12px]" disabled={!a.url || on} onClick={() => onChoose(a)}>
+ <Check className="size-3.5" /> {on ? chooseLabel[1] : chooseLabel[0]}
+ </Button>
+ {s.status === "queued" || s.status === "running" ? (
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2 text-[12px]" onClick={() => onStop(a)}>
+ Stop
+ </Button>
+ ) : (
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2 text-[12px]" aria-label={`Remove variant ${i + 1}`} onClick={() => onRemove(a)}>
+ <Trash2 className="size-3.5" />
+ </Button>
+ )}
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
+const engineWords = (e: Engine) => (e === "open" ? "Qwen-Image-Edit 2511 on your GPU" : "GPT Image 2.5 Sunburst or Nano Banana Pro on fal");
+
+/** Scene anchors: the shot's first frame with your character in it (H3's <Picture 2>), approved before segments use it. */
+export function AnchorsStage(props: StageProps) {
+ const { id, project, clip, shot, gens, edit } = props;
+ const stop = useStopJob(id);
+ if (!shot) return <Note>Pick a shot.</Note>;
+ if (shot.mode !== "generate") return <Note>This shot keeps its original — no anchor needed.</Note>;
+ return (
+ <div className="space-y-3">
+ <Panel title="Scene anchor">
+ <div className="space-y-3">
+ <ToggleRow
+ label="Use a scene anchor"
+ hint="The shot's first frame with your character in it: H3 starts from it (the first segment's Picture 2)"
+ checked={shot.settings.useAnchor}
+ onChange={(useAnchor) => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { settings: { useAnchor } } })}
+ />
+ {shot.settings.useAnchor && (
+ <>
+ <AnchorMaker {...props} shotId={shot.id} />
+ <p className="text-[12px] text-muted-foreground">Made with {engineWords(project.engine)} from your character&apos;s picture and the shot&apos;s first frame.</p>
+ <AnchorGrid
+ items={shot.anchors}
+ chosen={shot.approvedAnchor}
+ gens={gens}
+ chooseLabel={["Approve", "Approved"]}
+ onChoose={(a) => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { approvedAnchor: a.id } })}
+ onRemove={(a) => void edit({ type: "remove-anchor", clipId: clip.id, shotId: shot.id, anchorId: a.id })}
+ onStop={(a) => stop.mutate({ kind: "anchor", clipId: clip.id, shotId: shot.id, jobId: a.id })}
+ />
+ {!shot.approvedAnchor && shot.anchors.some((a) => a.url) && <Note tone="warn">Approve one: the first segment waits for an approved anchor (or set it to “No anchor” in Segments).</Note>}
+ </>
+ )}
+ </div>
+ </Panel>
+ {shot.settings.useAnchor && (
+ <Panel title="What the image model is told">
+ <div className="space-y-3">
+ <SavedText
+ label="Extra instructions"
+ rows={2}
+ max={SWAP_STUDIO.maxPromptChars}
+ value={shot.anchorInstructions}
+ placeholder="keep the umbrella in her left hand"
+ onSave={(anchorInstructions) => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { anchorInstructions } })}
+ />
+ <SavedText
+ label="Custom base prompt"
+ rows={4}
+ max={SWAP_STUDIO.maxPromptChars}
+ value={shot.anchorBasePrompt}
+ placeholder={anchorWords(project, { ...shot, anchorInstructions: "" })}
+ hint="empty: Akatz Labs' brief"
+ onSave={(anchorBasePrompt) => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { anchorBasePrompt } })}
+ />
+ </div>
+ </Panel>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/swap-studio/stage-review.tsx b/src/components/swap-studio/stage-review.tsx
new file mode 100644
index 00000000..cbe7944e
--- /dev/null
+++ b/src/components/swap-studio/stage-review.tsx
@@ -0,0 +1,255 @@
+"use client";
+
+import { Ban, Download, Film, Library, Loader2, Play, Star } from "lucide-react";
+import Link from "next/link";
+import { useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Panel } from "@/components/av/tool-shell";
+import { Segmented } from "@/components/faceless/controls";
+import { characterLicenceLine } from "@/lib/catalog/character-swap";
+import { assemblyPieces, assemblyTakes, currentSegments, DECISION_LABELS, FINISH_UNAVAILABLE, jobState, secondsLabel, SWAP_STUDIO, WORKERS_NOTE, type Decision, type SwapTake } from "@/lib/catalog/swap-studio";
+import { STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";
+import { downloadHref } from "@/lib/library";
+import { cn } from "@/lib/utils";
+import { decisionsHref, useAssemble, useStopJob } from "./hooks";
+import { GenChip, JobError, Note, priceText, SavedText } from "./parts";
+import type { StageProps } from "./workbench";
+
+const DECISIONS = Object.keys(DECISION_LABELS) as Decision[];
+
+interface TakeRef {
+ key: string;
+ label: string;
+ url: string;
+ shotId: string;
+ segmentId: string;
+ take: SwapTake;
+}
+
+/** Every finished take of the clip, for comparing. */
+function finishedTakes({ clip, gens }: Pick<StageProps, "clip" | "gens">): TakeRef[] {
+ const out: TakeRef[] = [];
+ clip.shots.forEach((s, si) =>
+ currentSegments(s).forEach((g, gi) =>
+ g.takes.forEach((t, ti) => {
+ const url = t.genId && gens[t.genId]?.status === "succeeded" ? gens[t.genId].url : undefined;
+ if (url) out.push({ key: t.id, label: `Shot ${si + 1} · segment ${gi + 1} · take ${ti + 1}${g.selectedTake === t.id ? " (chosen)" : ""}`, url, shotId: s.id, segmentId: g.id, take: t });
+ }),
+ ),
+ );
+ return out;
+}
+
+/** Two takes side by side, played together. */
+function Compare({ takes }: { takes: TakeRef[] }) {
+ const [a, setA] = useState<string | undefined>(takes[0]?.key);
+ const [b, setB] = useState<string | undefined>(takes[1]?.key);
+ const va = useRef<HTMLVideoElement>(null);
+ const vb = useRef<HTMLVideoElement>(null);
+ if (takes.length < 2) return <Note>Make two takes of a segment (or of two segments) to compare them side by side.</Note>;
+ const pick = (k: string | undefined) => takes.find((t) => t.key === k);
+ const both = () => {
+ for (const v of [va.current, vb.current]) {
+ if (!v) continue;
+ v.currentTime = 0;
+ void v.play().catch(() => undefined);
+ }
+ };
+ return (
+ <div className="space-y-2">
+ <div className="grid gap-2 sm:grid-cols-2">
+ {(
+ [
+ ["A", a, setA, va],
+ ["B", b, setB, vb],
+ ] as const
+ ).map(([name, value, set, ref]) => (
+ <div key={name} className="min-w-0 space-y-1.5">
+ <Select value={value} onValueChange={set}>
+ <SelectTrigger className="h-8 w-full min-w-0 text-[12px]" aria-label={`Take ${name}`}>
+ <SelectValue placeholder={`Take ${name}`} />
+ </SelectTrigger>
+ <SelectContent>
+ {takes.map((t) => (
+ <SelectItem key={t.key} value={t.key}>
+ {t.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {pick(value) && <video ref={ref} src={pick(value)!.url} controls muted playsInline preload="metadata" className="aspect-video w-full rounded-lg bg-media object-contain" />}
+ </div>
+ ))}
+ </div>
+ <Button size="sm" variant="outline" className="h-8 rounded-full" onClick={both}>
+ <Play className="size-3.5" /> Play both from the start
+ </Button>
+ </div>
+ );
+}
+
+/** Takes & review: compare takes, favourite, keep / maybe / skip with notes, the clip's review, Export decisions. */
+export function ReviewStage(props: StageProps) {
+ const { id, clip, shot, gens, edit } = props;
+ const takes = finishedTakes(props);
+ return (
+ <div className="space-y-3">
+ <Panel
+ title="Compare"
+ aside={
+ <Button asChild size="sm" variant="ghost" className="h-8 rounded-full">
+ <a href={decisionsHref(id)} download>
+ <Download className="size-3.5" /> Export decisions
+ </a>
+ </Button>
+ }
+ >
+ <Compare key={clip.id} takes={takes} />
+ </Panel>
+
+ {shot && shot.mode === "generate" && (
+ <Panel title="This shot's takes">
+ {!currentSegments(shot).some((g) => g.takes.length) ? (
+ <p className="text-[12px] text-muted-foreground">No takes yet — queue segments in Segments.</p>
+ ) : (
+ <ol className="space-y-4">
+ {currentSegments(shot).map((g, gi) =>
+ g.takes.length ? (
+ <li key={g.id} className="space-y-2">
+ <p className="text-[13px] font-medium">
+ Segment {gi + 1} <span className="font-normal text-muted-foreground">· {secondsLabel(g.end - g.start)}</span>
+ </p>
+ <ul className="grid gap-2 sm:grid-cols-2">
+ {g.takes.map((t, ti) => {
+ const s = t.state === "launched" ? jobState(t.genId, t.stepIds, gens) : null;
+ const url = s?.status === "succeeded" && t.genId ? gens[t.genId]?.url : undefined;
+ const ref = { clipId: clip.id, shotId: shot.id, segmentId: g.id, takeId: t.id } as const;
+ return (
+ <li key={t.id} className={cn("min-w-0 space-y-2 rounded-xl border p-2.5", g.selectedTake === t.id && "border-success")}>
+ <div className="flex items-center gap-2">
+ <span className="text-[12px] font-medium">Take {ti + 1}</span>
+ {s ? <GenChip genId={t.genId} stepIds={t.stepIds} gens={gens} /> : <span className="text-[11px] text-muted-foreground">{t.state === "waiting" ? "Waiting" : (t.reason ?? "Stopped")}</span>}
+ <button
+ type="button"
+ onClick={() => void edit({ type: "take", ...ref, favourite: !t.favourite })}
+ aria-pressed={t.favourite}
+ aria-label={t.favourite ? "Unfavourite" : "Favourite"}
+ className="ml-auto grid size-7 place-items-center rounded-full hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ >
+ <Star className={cn("size-4", t.favourite ? "fill-warning text-warning" : "text-muted-foreground")} />
+ </button>
+ </div>
+ {url ? <video src={url} controls muted playsInline preload="metadata" className="aspect-video w-full rounded-lg bg-media object-contain" /> : null}
+ <Segmented label={`Take ${ti + 1} decision`} value={t.decision} options={DECISIONS.map((d) => ({ value: d, label: DECISION_LABELS[d] }))} onChange={(decision) => void edit({ type: "take", ...ref, decision })} />
+ <SavedText label="Notes" rows={2} max={SWAP_STUDIO.maxNotesChars} value={t.notes} placeholder="lips drift at the end" onSave={(notes) => void edit({ type: "take", ...ref, notes })} />
+ {url && g.selectedTake !== t.id && (
+ <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => void edit({ type: "take", ...ref, select: true })}>
+ Use this take
+ </Button>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </li>
+ ) : null,
+ )}
+ </ol>
+ )}
+ </Panel>
+ )}
+
+ <Panel title="This clip's review">
+ <div className="space-y-3">
+ <Segmented label="Clip decision" value={clip.review} options={DECISIONS.map((d) => ({ value: d, label: DECISION_LABELS[d] }))} onChange={(review) => void edit({ type: "clip", clipId: clip.id, review })} />
+ <SavedText label="Notes" rows={2} max={SWAP_STUDIO.maxNotesChars} value={clip.reviewNotes} onSave={(reviewNotes) => void edit({ type: "clip", clipId: clip.id, reviewNotes })} />
+ </div>
+ </Panel>
+ </div>
+ );
+}
+
+/** Assemble: the chosen takes over the original timeline with the clip's own sound; the Finish stage said as not available. */
+export function AssembleStage({ id, project, clip, gens, estimate }: StageProps) {
+ const assemble = useAssemble(id);
+ const stop = useStopJob(id);
+ const found = assemblyPieces(project, clip);
+ const a = clip.assembly;
+ const state = jobState(a?.genId, a?.stepIds, gens);
+ const result = state.status === "succeeded" && a?.genId ? gens[a.genId]?.url : undefined;
+ const current = "pieces" in found && !!a && JSON.stringify(a.takes) === JSON.stringify(assemblyTakes(found.pieces));
+ return (
+ <div className="space-y-3">
+ <Panel title="Assemble the clip" aside={<span className="font-mono text-[11px] text-muted-foreground">{priceText(estimate?.assembly[clip.id], { demo: estimate?.demo, engine: project.engine })}</span>}>
+ <div className="space-y-3">
+ {"problem" in found ? (
+ <Note tone="warn">{found.problem}</Note>
+ ) : (
+ <ol className="flex min-w-0 flex-wrap gap-1.5" aria-label="Pieces">
+ {found.pieces.map((p, i) => (
+ <li key={i} className={cn("rounded-full px-2.5 py-1 text-[11px] font-medium", p.kind === "take" ? "bg-brand-faint text-brand-text" : "bg-muted text-muted-foreground")}>
+ {p.kind === "take" ? "Your character" : "As filmed"} · {secondsLabel(p.end - p.start)}
+ </li>
+ ))}
+ </ol>
+ )}
+ <p className="text-[12px] text-muted-foreground">
+ {project.engine === "open"
+ ? "Each piece is fitted to the clip's size at 24 fps, joined packet by packet, and the clip's own sound goes back on."
+ : "Each piece is cut to its frames, joined (fal keeps 24 fps, H3's rate), and the clip's own sound — or its silence — goes back on."}
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ className="h-9 rounded-full"
+ disabled={"problem" in found || assemble.isPending || state.status === "queued" || state.status === "running" || (current && state.status === "succeeded")}
+ onClick={() => assemble.mutate({ clipId: clip.id }, { onSuccess: () => toast("Assembling the clip"), onError: (e) => toast.error((e as Error).message) })}
+ >
+ {assemble.isPending ? <Loader2 className="size-4 animate-spin" /> : <Film className="size-4" />} {a ? "Assemble again" : "Assemble clip"}
+ </Button>
+ {a && <GenChip genId={a.genId} stepIds={a.stepIds} gens={gens} />}
+ {(state.status === "queued" || state.status === "running") && (
+ <Button size="sm" variant="ghost" className="h-8 rounded-full" onClick={() => stop.mutate({ kind: "assembly", clipId: clip.id })}>
+ Stop
+ </Button>
+ )}
+ {a && !current && state.status === "succeeded" && <span className="text-[12px] text-muted-foreground">The chosen takes changed since — assemble again for the new ones.</span>}
+ </div>
+ <JobError genId={a?.genId} stepIds={a?.stepIds} gens={gens} />
+ {result && (
+ <div className="space-y-2">
+ <video src={result} controls playsInline preload="metadata" className="max-h-[46vh] w-full rounded-xl bg-media" />
+ <div className="flex flex-wrap gap-2">
+ <Button asChild size="sm" className="h-8 rounded-full">
+ <a href={downloadHref(result, `${clip.name}-character-swap.mp4`)}>
+ <Download className="size-3.5" /> Download
+ </a>
+ </Button>
+ <Button asChild size="sm" variant="outline" className="h-8 rounded-full">
+ <Link href="/library">
+ <Library className="size-3.5" /> In the Library
+ </Link>
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ </Panel>
+
+ <Panel title={FINISH_UNAVAILABLE.title} aside={<span className="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground"><Ban className="size-3" /> Not available</span>}>
+ <p className="text-[12px] leading-snug text-pretty text-muted-foreground">{FINISH_UNAVAILABLE.reason}</p>
+ </Panel>
+
+ <Panel title="Where it runs">
+ <ul className="space-y-1.5 text-[12px] leading-snug text-pretty text-muted-foreground">
+ {project.engine === "open" && <li>{WORKERS_NOTE}</li>}
+ {(estimate?.notes ?? []).filter((n) => n !== WORKERS_NOTE).map((n) => (
+ <li key={n}>{n}</li>
+ ))}
+ {!estimate && <li>{characterLicenceLine(project.engine, STUDIO_MODELS[project.engine].swap)}</li>}
+ </ul>
+ </Panel>
+ </div>
+ );
+}
diff --git a/src/components/swap-studio/stage-segments.tsx b/src/components/swap-studio/stage-segments.tsx
new file mode 100644
index 00000000..d90a9942
--- /dev/null
+++ b/src/components/swap-studio/stage-segments.tsx
@@ -0,0 +1,419 @@
+"use client";
+
+import { ChevronDown, Combine, ListVideo, Loader2, Play, RotateCcw, Scissors, Square } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Panel } from "@/components/av/tool-shell";
+import { Segmented, ToggleRow } from "@/components/faceless/controls";
+import { CLOUD_NO_LORA, historyChoicesFor, SWAP_LORAS, WINDOW_CHOICES } from "@/lib/catalog/character-swap";
+import {
+ currentSegments,
+ jobState,
+ layoutFrames,
+ ROLE_LABELS,
+ secondsLabel,
+ segmentStates,
+ SWAP_STUDIO,
+ type GenSummary,
+ type QueueMode,
+ type SegmentState,
+ type SwapRole,
+ type SwapSegment,
+ type SwapShot,
+ type SwapTake,
+} from "@/lib/catalog/swap-studio";
+import { cn } from "@/lib/utils";
+import { useQueue, useStopJob, useStopTake } from "./hooks";
+import { AnchorGrid, AnchorMaker } from "./stage-anchors";
+import { JobChip, Note, NumberField, priceText, SavedText } from "./parts";
+import type { StageProps } from "./workbench";
+
+const STATE_TEXT: Record<SegmentState["status"], string> = { ready: "Current", stale: "Out of date", empty: "No take yet" };
+const ROLES = Object.keys(ROLE_LABELS) as SwapRole[];
+
+/** Generation settings (Akatz's shot fields): LoRA, anchor, mask, render size, seed, window and history. */
+function SettingsPanel({ project, clip, shot, edit }: StageProps & { shot: SwapShot }) {
+ const s = shot.settings;
+ const set = (settings: Partial<SwapShot["settings"]>) => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { settings } });
+ const cloud = project.engine === "cloud";
+ return (
+ <Panel title="Generation settings">
+ <div className="grid gap-3 sm:grid-cols-2">
+ <div className="min-w-0 space-y-1.5">
+ <span className="text-[12px] font-medium">Swap LoRA</span>
+ <Segmented
+ label="Swap LoRA"
+ value={s.lora}
+ options={[
+ { value: "v1.5", label: "V1.5", hint: SWAP_LORAS["v1.5"].label },
+ { value: "v1", label: "V1" },
+ { value: "none", label: "None", hint: cloud ? CLOUD_NO_LORA : "Turbo LoRA alone" },
+ ]}
+ onChange={(lora) => set({ lora })}
+ />
+ {cloud && s.lora === "none" && <p className="text-[12px] text-destructive">{CLOUD_NO_LORA}</p>}
+ </div>
+ <div className="min-w-0 space-y-1.5">
+ <span className="text-[12px] font-medium">Render size</span>
+ <Segmented
+ label="Render size"
+ value={s.renderMp}
+ options={[
+ { value: 0.5, label: "0.5 MP · 480" },
+ { value: 1, label: "1.0 MP · 768" },
+ ]}
+ onChange={(renderMp) => set({ renderMp })}
+ />
+ </div>
+ <label className="flex min-w-0 flex-col gap-1 text-[12px] font-medium">
+ Diffusion window
+ <Select value={String(s.windowFrames)} onValueChange={(v) => set({ windowFrames: Number(v), ...(s.historyFrames >= Number(v) ? { historyFrames: Math.max(...historyChoicesFor(Number(v))) } : {}) })}>
+ <SelectTrigger className="h-8 w-full text-[13px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {WINDOW_CHOICES.map((w) => (
+ <SelectItem key={w} value={String(w)}>
+ {w} frames · {secondsLabel(w)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ <label className="flex min-w-0 flex-col gap-1 text-[12px] font-medium">
+ Continuation history
+ <Select value={String(s.historyFrames)} onValueChange={(v) => set({ historyFrames: Number(v) })}>
+ <SelectTrigger className="h-8 w-full text-[13px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {historyChoicesFor(s.windowFrames).map((h) => (
+ <SelectItem key={h} value={String(h)}>
+ {h} frame{h === 1 ? "" : "s"}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ <NumberField label="Seed for new segments" value={s.seed} min={0} max={SWAP_STUDIO.maxSeed} onCommit={(seed) => set({ seed })} />
+ <div className="space-y-2">
+ <ToggleRow label="Scene anchor" hint="First segment starts from the approved anchor" checked={s.useAnchor} onChange={(useAnchor) => set({ useAnchor })} />
+ <ToggleRow label="Masked generation" hint={cloud ? "Your GPU only — fal's H3 has no mask" : "Only the mask is regenerated"} checked={s.useMask && !cloud} disabled={cloud} onChange={(useMask) => set({ useMask })} />
+ </div>
+ </div>
+ {cloud && <Note className="mt-3">On the cloud the window and history set the default segment layout; a continuing segment starts from the previous take&apos;s last frame (fal&apos;s H3 takes no history).</Note>}
+ </Panel>
+ );
+}
+
+function TakeRow({
+ take,
+ n,
+ seg,
+ selected,
+ gens,
+ onSelect,
+ onStop,
+ onRetry,
+}: {
+ take: SwapTake;
+ n: number;
+ seg: SwapSegment;
+ selected: boolean;
+ gens: Record<string, GenSummary>;
+ onSelect: () => void;
+ onStop: () => void;
+ onRetry: () => void;
+}) {
+ const s = take.state === "launched" ? jobState(take.genId, take.stepIds, gens) : { status: take.state, progress: null, message: take.reason ?? null };
+ const url = take.genId ? gens[take.genId]?.url : undefined;
+ const active = s.status === "waiting" || s.status === "queued" || s.status === "running";
+ return (
+ <li className={cn("flex min-w-0 flex-wrap items-center gap-2 rounded-lg border px-2 py-1.5", selected && "border-success")}>
+ <span className="text-[12px] font-medium">Take {n}</span>
+ <JobChip status={s.status} progress={s.progress} message={s.message} />
+ <span className="font-mono text-[11px] text-muted-foreground">seed {take.seed}</span>
+ {take.state === "waiting" && <span className="text-[11px] text-muted-foreground">waits for the segment before</span>}
+ <span className="ml-auto flex flex-wrap gap-1">
+ {s.status === "succeeded" && (
+ <Button size="sm" variant={selected ? "secondary" : "outline"} className="h-7 rounded-full px-2 text-[12px]" disabled={selected} onClick={onSelect}>
+ {selected ? "Chosen" : "Use this take"}
+ </Button>
+ )}
+ {active && (
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2 text-[12px]" onClick={onStop}>
+ <Square className="size-3" /> Stop
+ </Button>
+ )}
+ {(s.status === "failed" || s.status === "stopped" || s.status === "canceled") && (
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2 text-[12px]" onClick={onRetry}>
+ <RotateCcw className="size-3" /> Try again
+ </Button>
+ )}
+ </span>
+ {s.message && (s.status === "failed" || s.status === "stopped" || s.status === "canceled") && <p className="w-full text-[12px] text-pretty text-destructive">{s.message}</p>}
+ {url && s.status === "succeeded" && (
+ <div className="basis-full">
+ <video src={url} controls muted playsInline preload="metadata" className="aspect-video w-full max-w-xs rounded-md bg-media object-contain" aria-label={`Take ${n}`} data-segment={seg.id} />
+ </div>
+ )}
+ </li>
+ );
+}
+
+function SegmentCard(props: StageProps & { shot: SwapShot; seg: SwapSegment; index: number; state: SegmentState; count: number }) {
+ const { id, project, clip, shot, seg, index, state, gens, estimate, edit } = props;
+ const queue = useQueue(id);
+ const stopTake = useStopTake(id);
+ const stop = useStopJob(id);
+ const [open, setOpen] = useState(false);
+ const set = (patch: Record<string, unknown>) => void edit({ type: "segment", clipId: clip.id, shotId: shot.id, segmentId: seg.id, patch });
+ const run = (mode: QueueMode) =>
+ queue.mutate(
+ { clipId: clip.id, shotId: shot.id, segmentId: seg.id, mode },
+ {
+ onSuccess: (r) => {
+ toast(`Queued ${r.takes.length} take${r.takes.length === 1 ? "" : "s"}`);
+ for (const note of r.notes) toast(note);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ },
+ );
+ const price = estimate?.segments[seg.id];
+ const problem = estimate?.problems[seg.id];
+ const len = seg.end - seg.start;
+ const busy = seg.takes.some((t) => t.state === "waiting" || ["queued", "running"].includes(jobState(t.genId, t.stepIds, gens).status));
+ return (
+ <li className="min-w-0 space-y-2.5 rounded-xl border p-3" aria-label={`Segment ${index + 1}`}>
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <span className="text-[13px] font-semibold">Segment {index + 1}</span>
+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">
+ {seg.start}–{seg.end} · {secondsLabel(len)}
+ {state.windowFrames ? ` · ${state.windowFrames}-frame pass` : ""}
+ </span>
+ <span
+ className={cn(
+ "rounded-full px-2 py-0.5 text-[11px] font-medium",
+ state.status === "ready" ? "bg-success/12 text-success" : state.status === "stale" ? "bg-warning/15 text-foreground" : "bg-muted text-muted-foreground",
+ )}
+ >
+ {STATE_TEXT[state.status]}
+ {state.blocked && state.status !== "ready" ? " · waits for the one before" : ""}
+ </span>
+ {seg.needsReview && <span className="rounded-full bg-warning/15 px-2 py-0.5 text-[11px] font-medium">Check its settings</span>}
+ <span className="ml-auto font-mono text-[12px] text-muted-foreground">{priceText(price, { demo: estimate?.demo, engine: project.engine })}</span>
+ </div>
+
+ <div className="grid gap-2 sm:grid-cols-2">
+ <div className="min-w-0 space-y-1">
+ <span className="text-[12px] font-medium">Start</span>
+ <Segmented
+ label={`Segment ${index + 1} start`}
+ value={seg.connection}
+ options={
+ index
+ ? [
+ { value: "start", label: "Starts fresh" },
+ { value: "continue", label: "Continues previous" },
+ ]
+ : [{ value: "start", label: "Starts fresh" }]
+ }
+ onChange={(connection) => set({ connection })}
+ />
+ </div>
+ {seg.connection === "continue" && (
+ <label className="flex min-w-0 flex-col gap-1 text-[12px] font-medium">
+ History {project.engine === "cloud" ? "(the cloud carries the last frame)" : "(frames of the take before)"}
+ <Select value={String(seg.history)} onValueChange={(v) => set({ history: Number(v) })}>
+ <SelectTrigger className="h-8 w-full text-[13px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {historyChoicesFor(SWAP_STUDIO.maxPassFrames + 1)
+ .filter((h) => h > 0)
+ .map((h) => (
+ <SelectItem key={h} value={String(h)}>
+ {h} frame{h === 1 ? "" : "s"}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ )}
+ <div className="min-w-0 space-y-1 sm:col-span-2">
+ <span className="text-[12px] font-medium">Anchor</span>
+ <Segmented
+ label={`Segment ${index + 1} anchor`}
+ value={seg.anchorMode}
+ options={[
+ { value: "shot", label: "Scene anchor", hint: "The shot's approved scene anchor" },
+ { value: "custom", label: "Reference", hint: "A segment reference of its own" },
+ { value: "none", label: "None" },
+ ]}
+ onChange={(anchorMode) => set({ anchorMode })}
+ />
+ {seg.anchorMode === "shot" && !shot.approvedAnchor && <p className="text-[12px] text-muted-foreground">Approve a scene anchor (Scene anchors), or pick None.</p>}
+ </div>
+ </div>
+
+ {seg.anchorMode === "custom" && (
+ <div className="space-y-2 rounded-lg bg-muted/50 p-2">
+ <AnchorMaker {...props} shotId={shot.id} segment={seg} />
+ <AnchorGrid
+ items={seg.anchors}
+ chosen={seg.anchor}
+ gens={gens}
+ chooseLabel={["Use", "In use"]}
+ onChoose={(a) => set({ anchor: a.id })}
+ onRemove={(a) => void edit({ type: "remove-anchor", clipId: clip.id, shotId: shot.id, segmentId: seg.id, anchorId: a.id })}
+ onStop={(a) => stop.mutate({ kind: "anchor", clipId: clip.id, shotId: shot.id, segmentId: seg.id, jobId: a.id })}
+ />
+ </div>
+ )}
+
+ <button type="button" onClick={() => setOpen((o) => !o)} aria-expanded={open} className="flex items-center gap-1 text-[12px] font-medium text-muted-foreground hover:text-foreground">
+ <ChevronDown className={cn("size-3.5 transition-transform", open && "rotate-180")} /> Words, speaker, prompt and seed
+ </button>
+ {open && (
+ <div className="grid gap-2">
+ <div className="grid gap-2 sm:grid-cols-[1fr_8rem]">
+ <label className="flex min-w-0 flex-col gap-1 text-[12px] font-medium">
+ Who speaks
+ <Select value={seg.speaker ?? "auto"} onValueChange={(v) => set({ speaker: v === "auto" ? null : v })}>
+ <SelectTrigger className="h-8 w-full text-[13px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="auto">From the words · {ROLE_LABELS[state.speaker].label}</SelectItem>
+ {ROLES.map((r) => (
+ <SelectItem key={r} value={r}>
+ {ROLE_LABELS[r].label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ <NumberField label="Seed" value={seg.seed} min={0} max={SWAP_STUDIO.maxSeed} onCommit={(seed) => set({ seed })} />
+ </div>
+ <SavedText label="Words" rows={2} max={SWAP_STUDIO.maxPromptChars} value={seg.dialogue ?? state.dialogue} hint={seg.dialogue === null ? "from the transcript" : "yours"} onSave={(dialogue) => set({ dialogue })} />
+ <SavedText label="Extra direction" rows={2} max={SWAP_STUDIO.maxPromptChars} value={seg.prompt} placeholder="she turns her head slowly to the window" onSave={(prompt) => set({ prompt })} />
+ <SavedText
+ label="Exact prompt for this segment"
+ rows={5}
+ max={SWAP_STUDIO.maxPromptChars}
+ value={seg.performancePrompt ?? state.prompt}
+ hint={seg.performancePrompt === null ? "built from the shot's" : "yours (words and speaker edits keep it)"}
+ onSave={(performancePrompt) => set({ performancePrompt })}
+ />
+ <div>
+ <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => void edit({ type: "update-prompt", clipId: clip.id, shotId: shot.id, segmentId: seg.id })}>
+ <RotateCcw className="size-3.5" /> Update prompt
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {problem && <p className="text-[12px] text-pretty text-destructive">{problem}</p>}
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" className="h-8 rounded-full" onClick={() => run("segment")} disabled={queue.isPending || busy}>
+ {queue.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Play className="size-3.5" />} Queue segment
+ </Button>
+ {index < props.count - 1 && (
+ <Button size="sm" variant="outline" className="h-8 rounded-full" onClick={() => run("from")} disabled={queue.isPending}>
+ <ListVideo className="size-3.5" /> Queue from here
+ </Button>
+ )}
+ </div>
+
+ {seg.takes.length > 0 && (
+ <ol className="space-y-1.5" aria-label={`Segment ${index + 1} takes`}>
+ {seg.takes.map((t, i) => (
+ <TakeRow
+ key={t.id}
+ take={t}
+ n={i + 1}
+ seg={seg}
+ selected={seg.selectedTake === t.id}
+ gens={gens}
+ onSelect={() => void edit({ type: "take", clipId: clip.id, shotId: shot.id, segmentId: seg.id, takeId: t.id, select: true })}
+ onStop={() => stopTake.mutate({ clipId: clip.id, shotId: shot.id, segmentId: seg.id, takeId: t.id }, { onError: (e) => toast.error((e as Error).message) })}
+ onRetry={() => run("segment")}
+ />
+ ))}
+ </ol>
+ )}
+ </li>
+ );
+}
+
+/** Segments: the shot's layout (5/10/15 s, split, merge, move), each segment's settings, queueing, and its takes. */
+export function SegmentsStage(props: StageProps) {
+ const { id, project, clip, shot, estimate, edit } = props;
+ const queue = useQueue(id);
+ const [splitAt, setSplitAt] = useState<number | null>(null);
+ if (!shot) return <Note>Pick a shot.</Note>;
+ if (shot.mode !== "generate") return <Note>This shot keeps its original — switch it to Replace character in Shots to swap it.</Note>;
+ const items = currentSegments(shot);
+ const states = segmentStates(project, clip, shot, items);
+ const len = shot.end - shot.start;
+ const layout = (op: Parameters<StageProps["edit"]>[0] extends infer E ? (E extends { type: "layout"; op: infer O } ? O : never) : never) => void edit({ type: "layout", clipId: clip.id, shotId: shot.id, op });
+ const shotPrice = estimate?.shots[shot.id];
+ const split = splitAt ?? Math.round(len / 2);
+ return (
+ <div className="space-y-3">
+ <SettingsPanel {...props} shot={shot} />
+ <Panel title={`Segments · ${items.length}`} aside={<span className="font-mono text-[11px] text-muted-foreground">{secondsLabel(len)} shot</span>}>
+ <div className="mb-3 flex flex-wrap items-end gap-2">
+ {SWAP_STUDIO.segmentLengths.map((s) => (
+ <Button key={s} size="sm" variant="outline" className="h-8 rounded-full" onClick={() => layout({ op: "partition", frames: Math.min(361, layoutFrames(s)) })}>
+ {s} s segments
+ </Button>
+ ))}
+ <div className="flex items-end gap-1.5">
+ <NumberField label="Split at frame" value={split} min={1} max={len - 1} onCommit={setSplitAt} className="w-28" />
+ <Button size="sm" variant="outline" className="h-8 rounded-full" onClick={() => layout({ op: "split", frame: split })}>
+ <Scissors className="size-3.5" /> Split
+ </Button>
+ </div>
+ </div>
+ {items.length > 1 && (
+ <ul className="mb-3 flex flex-wrap gap-2" aria-label="Boundaries">
+ {items.slice(1).map((g, i) => (
+ <li key={g.id} className="flex items-end gap-1 rounded-lg bg-muted px-2 py-1.5">
+ <NumberField label={`Boundary ${i + 1}`} value={g.start} min={items[i].start + 1} max={g.end - 1} onCommit={(frame) => layout({ op: "boundary", index: i + 1, frame })} className="w-24" />
+ <Button size="sm" variant="ghost" className="h-8 rounded-full px-2" aria-label={`Merge segments ${i + 1} and ${i + 2}`} onClick={() => layout({ op: "merge", index: i + 1 })}>
+ <Combine className="size-3.5" />
+ </Button>
+ </li>
+ ))}
+ </ul>
+ )}
+ <ol className="space-y-3">
+ {items.map((seg, i) => (
+ <SegmentCard key={seg.id} {...props} shot={shot} seg={seg} index={i} state={states[i]} count={items.length} />
+ ))}
+ </ol>
+ <div className="mt-3 flex flex-wrap items-center gap-2 border-t pt-3">
+ <Button
+ className="h-9 rounded-full"
+ disabled={queue.isPending}
+ onClick={() =>
+ queue.mutate(
+ { clipId: clip.id, shotId: shot.id, segmentId: items[0].id, mode: "all" },
+ { onSuccess: (r) => toast(`Queued ${r.takes.length} take${r.takes.length === 1 ? "" : "s"}`), onError: (e) => toast.error((e as Error).message) },
+ )
+ }
+ >
+ {queue.isPending ? <Loader2 className="size-4 animate-spin" /> : <ListVideo className="size-4" />} Queue all segments
+ </Button>
+ <span className="text-[12px] text-muted-foreground">
+ {shotPrice ? `${shotPrice.segments} to make · ` : ""}
+ <span className="font-mono">{priceText(shotPrice?.costUsd, { demo: estimate?.demo, engine: project.engine })}</span>
+ </span>
+ </div>
+ </Panel>
+ </div>
+ );
+}
diff --git a/src/components/swap-studio/stage-shots.tsx b/src/components/swap-studio/stage-shots.tsx
new file mode 100644
index 00000000..9ba38d65
--- /dev/null
+++ b/src/components/swap-studio/stage-shots.tsx
@@ -0,0 +1,178 @@
+"use client";
+
+import { Check, Loader2, Plus, ScanSearch, Trash2, X } from "lucide-react";
+import { useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Panel } from "@/components/av/tool-shell";
+import { Segmented } from "@/components/faceless/controls";
+import { SCENE_THRESHOLD } from "@/lib/av/scene-cuts";
+import { addCut, at, MODE_LABELS, moveCut, removeCut, secondsLabel, shotsFromCuts, tidyCuts, type ShotMode } from "@/lib/catalog/swap-studio";
+import { cn } from "@/lib/utils";
+import { Note } from "./parts";
+import { useSceneCuts } from "./use-scene-cuts";
+import type { StageProps } from "./workbench";
+
+const key = (a: number, b: number) => `${a}-${b}`;
+const pct = (f: number, total: number) => `${(f / total) * 100}%`;
+
+/** Shots: find the edits (FFmpeg's scene score at 0.32), move, add or remove cuts, Replace character or Keep original per shot. */
+export function ShotsStage({ project, clip, edit, src }: StageProps) {
+ const video = useRef<HTMLVideoElement>(null);
+ const scene = useSceneCuts();
+ const [draft, setDraft] = useState<number[] | null>(null);
+ const [modes, setModes] = useState<Record<string, ShotMode>>({});
+ const [frame, setFrame] = useState(0);
+ const [saving, setSaving] = useState(false);
+ const cuts = draft ?? clip.cuts;
+ const total = clip.frames;
+ const shots = useMemo(() => shotsFromCuts(clip, cuts, project.defaults), [clip, cuts, project.defaults]);
+ const modeOf = (a: number, b: number, fallback: ShotMode) => modes[key(a, b)] ?? fallback;
+ const changed = draft !== null || Object.keys(modes).length > 0;
+
+ const seek = (f: number) => {
+ if (video.current) video.current.currentTime = at(f) + 0.5 / 24;
+ setFrame(f);
+ };
+ const detect = async () => {
+ const found = await scene.detect(src, total);
+ if (!found) return;
+ await edit({ type: "detected", clipId: clip.id, cuts: found });
+ toast(found.length ? `Found ${found.length} edit${found.length === 1 ? "" : "s"} — check them, then save the shots` : "No edits found: one continuous shot");
+ };
+ const save = async () => {
+ setSaving(true);
+ const p = await edit({ type: "cuts", clipId: clip.id, cuts, modes: shots.map((s) => modeOf(s.start, s.end, s.mode)) });
+ setSaving(false);
+ if (p) {
+ setDraft(null);
+ setModes({});
+ }
+ };
+
+ return (
+ <div className="space-y-3">
+ <Panel>
+ <video
+ ref={video}
+ src={src}
+ controls
+ playsInline
+ preload="metadata"
+ onTimeUpdate={(e) => setFrame(Math.min(total - 1, Math.floor(e.currentTarget.currentTime * 24)))}
+ className="max-h-[46vh] w-full rounded-xl bg-media"
+ />
+ {/* The timeline: shots by colour, cuts as lines, detected edits dashed, the playhead. */}
+ <div
+ className="relative mt-3 h-10 cursor-pointer overflow-hidden rounded-lg bg-muted"
+ onClick={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ seek(Math.min(total - 1, Math.max(0, Math.round(((e.clientX - r.left) / r.width) * total))));
+ }}
+ aria-hidden
+ >
+ {shots.map((s) => (
+ <div key={s.id} className={cn("absolute inset-y-0", modeOf(s.start, s.end, s.mode) === "generate" ? "bg-brand-faint" : "bg-muted")} style={{ left: pct(s.start, total), width: pct(s.end - s.start, total) }} />
+ ))}
+ {(clip.detected ?? []).map((c) => (
+ <div key={`d${c}`} className="absolute inset-y-1 border-l-2 border-dashed border-warning" style={{ left: pct(c, total) }} />
+ ))}
+ {cuts.map((c) => (
+ <div key={c} className="absolute inset-y-0 w-0.5 bg-foreground" style={{ left: pct(c, total) }} />
+ ))}
+ <div className="absolute inset-y-0 w-0.5 bg-primary" style={{ left: pct(frame, total) }} />
+ </div>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <span className="font-mono text-[12px] tabular-nums text-muted-foreground">
+ Frame {frame} · {secondsLabel(frame)}
+ </span>
+ <Button size="sm" variant="outline" className="h-8 rounded-full" onClick={() => setDraft(addCut(cuts, frame, total))} disabled={frame <= 0 || cuts.includes(frame)}>
+ <Plus className="size-3.5" /> Cut at the playhead
+ </Button>
+ <Button size="sm" variant="outline" className="h-8 rounded-full" onClick={() => void detect()} disabled={scene.busy}>
+ {scene.busy ? <Loader2 className="size-3.5 animate-spin" /> : <ScanSearch className="size-3.5" />}
+ {scene.busy ? `Detecting… ${Math.round(scene.progress * 100)}%` : "Detect edits"}
+ </Button>
+ {scene.busy && (
+ <Button size="sm" variant="ghost" className="h-8 rounded-full" onClick={scene.cancel}>
+ Stop
+ </Button>
+ )}
+ </div>
+ {scene.error && <p className="mt-2 text-[12px] text-destructive">{scene.error}</p>}
+ {clip.detected && (
+ <div className="mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-dashed border-warning/60 px-3 py-2 text-[12px]">
+ <span className="min-w-0 flex-1">
+ {clip.detected.length ? `Detected ${clip.detected.length} edit${clip.detected.length === 1 ? "" : "s"} at frames ${clip.detected.join(", ")}` : "No edits detected"} (scene score over {SCENE_THRESHOLD}).
+ </span>
+ <Button size="sm" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => setDraft(tidyCuts(clip.detected!))}>
+ <Check className="size-3.5" /> Use them
+ </Button>
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => void edit({ type: "detected", clipId: clip.id, cuts: [] })}>
+ <X className="size-3.5" /> Dismiss
+ </Button>
+ </div>
+ )}
+ </Panel>
+
+ <Panel
+ title={`Shots · ${shots.length}`}
+ aside={
+ <Button size="sm" className="h-8 rounded-full" onClick={() => void save()} disabled={saving || (!changed && clip.cutsReviewed)}>
+ {saving ? <Loader2 className="size-3.5 animate-spin" /> : <Check className="size-3.5" />}
+ {changed || !clip.cutsReviewed ? "Save shots" : "Saved"}
+ </Button>
+ }
+ >
+ {!clip.cutsReviewed && !changed && <Note className="mb-3">Confirm the shots before generating: detect the edits (or add cuts at the playhead), then save. H3 swaps one continuous shot at a time.</Note>}
+ {changed && <Note className="mb-3">Changed shots lose their masks, anchors and segments when saved; shots whose frames stay the same keep everything.</Note>}
+ <ol className="space-y-2">
+ {shots.map((s, i) => {
+ const m = modeOf(s.start, s.end, s.mode);
+ const cutAt = i > 0 ? s.start : null;
+ return (
+ <li key={s.id} className="flex min-w-0 flex-wrap items-center gap-2 rounded-lg border px-2.5 py-2">
+ <button type="button" onClick={() => seek(s.start)} className="min-w-0 text-left text-[13px] font-medium hover:underline">
+ Shot {i + 1}
+ <span className="ml-2 font-mono text-[12px] font-normal text-muted-foreground tabular-nums">
+ {s.start}–{s.end} · {secondsLabel(s.end - s.start)}
+ </span>
+ </button>
+ <Segmented
+ label={`Shot ${i + 1}`}
+ value={m}
+ options={(["generate", "preserve"] as const).map((v) => ({ value: v, label: MODE_LABELS[v].label, hint: MODE_LABELS[v].hint }))}
+ onChange={(v) => setModes((x) => ({ ...x, [key(s.start, s.end)]: v }))}
+ className="ml-auto"
+ />
+ {cutAt !== null && (
+ <div className="flex w-full items-center gap-2 text-[12px] text-muted-foreground">
+ <label className="flex items-center gap-1.5">
+ Cut at frame
+ <input
+ key={cutAt}
+ type="number"
+ defaultValue={cutAt}
+ min={1}
+ max={total - 1}
+ onBlur={(e) => {
+ const n = Math.round(Number(e.currentTarget.value));
+ if (Number.isFinite(n) && n !== cutAt) setDraft(moveCut(cuts, cutAt, n, total));
+ }}
+ onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
+ className="h-7 w-20 rounded-md border bg-background px-2 font-mono tabular-nums outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ </label>
+ <button type="button" onClick={() => setDraft(removeCut(cuts, cutAt))} className="inline-flex items-center gap-1 rounded-full px-2 py-1 hover:bg-muted hover:text-foreground" aria-label={`Remove the cut at frame ${cutAt}`}>
+ <Trash2 className="size-3.5" /> Remove cut
+ </button>
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ol>
+ </Panel>
+ </div>
+ );
+}
diff --git a/src/components/swap-studio/stage-who.tsx b/src/components/swap-studio/stage-who.tsx
new file mode 100644
index 00000000..c87a770e
--- /dev/null
+++ b/src/components/swap-studio/stage-who.tsx
@@ -0,0 +1,241 @@
+"use client";
+
+import { Check, Crosshair, Loader2, ScanFace, Trash2, Undo2 } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Slider } from "@/components/ui/slider";
+import { Panel } from "@/components/av/tool-shell";
+import { Segmented, ToggleRow } from "@/components/faceless/controls";
+import { FrameStage, type Frame } from "@/components/remove-object/frame-stage";
+import { WHO_INDEX_LABEL, WHO_LABELS, type SwapWho } from "@/lib/catalog/character-swap";
+import { at, jobState, maskPieceAt, secondsLabel, SWAP_STUDIO, type MaskVersion } from "@/lib/catalog/swap-studio";
+import type { PixelPoint } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+import { useMakeMask, useStopJob } from "./hooks";
+import { GenChip, grabFrame, JobError, Note, priceText } from "./parts";
+import type { StageProps } from "./workbench";
+
+const WORDS = { positive: "include", negative: "exclude", ask: "Click the person to swap", frame: "The shot's frame" };
+
+/** Who to swap: SAM 3.1's words and pick, clicks on any frame of the shot, Track shot / Update frame, mask versions to approve. */
+export function WhoStage({ id, project, clip, shot, gens, estimate, edit, src }: StageProps) {
+ const make = useMakeMask(id);
+ const stop = useStopJob(id);
+ const [at24, setAt24] = useState(0);
+ const [frame, setFrame] = useState<{ shot: string; f: number; image: Frame } | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [points, setPoints] = useState<PixelPoint[]>([]);
+ const [label, setLabel] = useState<"positive" | "negative">("positive");
+ const [base, setBase] = useState<string | null>(null);
+
+ if (!shot) return <Note>Pick a shot.</Note>;
+ const len = shot.end - shot.start;
+ const engine = project.engine;
+ const who = shot.who;
+ const shown = frame && frame.shot === shot.id ? frame : null;
+ const finished = (m: MaskVersion) => m.pieces.every((p) => p.url);
+ const baseVersion = shot.masks.find((m) => m.id === (base ?? shot.approvedMask)) ?? [...shot.masks].reverse().find(finished) ?? null;
+
+ const show = async (f: number) => {
+ setLoading(true);
+ try {
+ const image = await grabFrame(src, at(shot.start + f) + 0.5 / 24);
+ setFrame({ shot: shot.id, f, image });
+ setPoints([]);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ };
+ const run = (kind: "track" | "frame") => {
+ const f = shown?.f ?? at24;
+ make.mutate(
+ { clipId: clip.id, shotId: shot.id, kind, frame: f, points: shown ? points : [], ...(shown ? { size: { width: shown.image.width, height: shown.image.height } } : {}), ...(baseVersion ? { base: baseVersion.id } : {}) },
+ {
+ onSuccess: () => {
+ setPoints([]);
+ toast(kind === "track" ? `Tracking from frame ${f + 1} to the shot's end` : `Updating frame ${f + 1}`);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ },
+ );
+ };
+
+ return (
+ <div className="space-y-3">
+ <Panel title="Who to swap">
+ <div className="space-y-3">
+ <Segmented
+ label="Pick"
+ value={who.selection}
+ options={(Object.keys(WHO_LABELS) as SwapWho[]).map((v) => ({ value: v, label: WHO_LABELS[v] }))}
+ onChange={(selection) => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { who: { selection } } })}
+ />
+ <div className="grid gap-3 sm:grid-cols-[1fr_auto]">
+ <label className="flex min-w-0 flex-col gap-1 text-[12px] font-medium">
+ SAM 3.1 looks for
+ <input
+ key={who.words}
+ defaultValue={who.words}
+ maxLength={120}
+ placeholder="person"
+ onBlur={(e) => e.currentTarget.value !== who.words && void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { who: { words: e.currentTarget.value || "person" } } })}
+ onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
+ className="h-8 w-full min-w-0 rounded-md border bg-background px-2.5 text-[13px] font-normal outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ </label>
+ {who.selection === "index" && (
+ <label className="flex flex-col gap-1 text-[12px] font-medium" title={WHO_INDEX_LABEL[engine].hint}>
+ Person #
+ <input
+ key={who.index}
+ type="number"
+ min={1}
+ max={101}
+ defaultValue={who.index + 1}
+ onBlur={(e) => {
+ const n = Math.round(Number(e.currentTarget.value)) - 1;
+ if (Number.isFinite(n) && n >= 0 && n !== who.index) void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { who: { index: n } } });
+ }}
+ className="h-8 w-20 rounded-md border bg-background px-2 font-mono text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ </label>
+ )}
+ </div>
+ {engine === "cloud" ? (
+ <Note>On fal, H3 has no mask: who to swap goes into the prompt in words (“{who.selection === "index" ? `person #${who.index + 1}` : `the ${WHO_LABELS[who.selection].toLowerCase()} person`}”). SAM 3.1&apos;s masks here are for checking who it finds.</Note>
+ ) : (
+ <>
+ <ToggleRow
+ label="Masked generation"
+ hint="Only the person's mask is regenerated; the rest of the frame stays as filmed"
+ checked={shot.settings.useMask}
+ onChange={(useMask) => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { settings: { useMask } } })}
+ />
+ <div className="space-y-1.5">
+ <div className="flex items-baseline justify-between text-[12px]">
+ <span className="font-medium">Mask expansion</span>
+ <span className="font-mono text-muted-foreground tabular-nums">{shot.settings.expansion} px</span>
+ </div>
+ <Slider
+ aria-label="Mask expansion"
+ min={0}
+ max={256}
+ step={1}
+ value={[shot.settings.expansion]}
+ onValueCommit={([expansion]) => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { settings: { expansion } } })}
+ />
+ </div>
+ </>
+ )}
+ </div>
+ </Panel>
+
+ <Panel
+ title="Point at them"
+ aside={<span className="font-mono text-[11px] text-muted-foreground">Track shot · {priceText(estimate?.mask[shot.id], { demo: estimate?.demo, engine })}</span>}
+ >
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-center gap-3">
+ <div className="min-w-[12rem] flex-1">
+ <Slider aria-label="Frame of the shot" min={0} max={Math.max(0, len - 1)} step={1} value={[at24]} onValueChange={([f]) => setAt24(f)} />
+ </div>
+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">
+ Frame {at24 + 1} of {len} · {secondsLabel(at24)}
+ </span>
+ <Button size="sm" variant="outline" className="h-8 rounded-full" onClick={() => void show(at24)} disabled={loading}>
+ {loading ? <Loader2 className="size-3.5 animate-spin" /> : <Crosshair className="size-3.5" />} Show this frame
+ </Button>
+ </div>
+ {shown ? (
+ <>
+ <Segmented
+ label="A click marks"
+ value={label}
+ options={[
+ { value: "positive", label: "Include" },
+ { value: "negative", label: "Exclude" },
+ ]}
+ onChange={setLabel}
+ />
+ <FrameStage frame={shown.image} points={points} onPoints={setPoints} pointLabel={label} clickable maxPoints={SWAP_STUDIO.maxPoints} words={WORDS} />
+ {points.length > 0 && (
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => setPoints([])}>
+ <Undo2 className="size-3.5" /> Clear points
+ </Button>
+ )}
+ </>
+ ) : (
+ <Note>Show a frame to click who to swap (include) and who not (exclude) — or track with the pick and words above.</Note>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" className="h-8 rounded-full" onClick={() => run("track")} disabled={make.isPending}>
+ {make.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <ScanFace className="size-3.5" />} Track shot{(shown?.f ?? at24) > 0 ? ` from frame ${(shown?.f ?? at24) + 1}` : ""}
+ </Button>
+ <Button size="sm" variant="outline" className="h-8 rounded-full" onClick={() => run("frame")} disabled={make.isPending || !baseVersion || !shown}>
+ Update frame {(shown?.f ?? at24) + 1}
+ </Button>
+ </div>
+ {!baseVersion && <p className="text-[12px] text-muted-foreground">Update frame corrects one frame of a tracked mask: track the shot first.</p>}
+ </div>
+ </Panel>
+
+ <Panel title={`Mask versions · ${shot.masks.length}`}>
+ {!shot.masks.length ? (
+ <p className="text-[12px] text-muted-foreground">None yet.</p>
+ ) : (
+ <ol className="grid gap-3 sm:grid-cols-2">
+ {[...shot.masks].reverse().map((m) => {
+ const n = shot.masks.indexOf(m) + 1;
+ const state = jobState(m.genId, m.stepIds, gens);
+ const piece = maskPieceAt(m, shown?.f ?? at24);
+ const approved = shot.approvedMask === m.id;
+ return (
+ <li key={m.id} className={cn("min-w-0 space-y-2 rounded-xl border p-2.5", approved && "border-success")}>
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <span className="text-[13px] font-medium">v{n}</span>
+ <span className="min-w-0 truncate text-[12px] text-muted-foreground">
+ {m.kind === "track" ? `Track from frame ${m.frame + 1}` : `Frame ${m.frame + 1}`} · {m.points.length ? `${m.points.length} point${m.points.length === 1 ? "" : "s"}` : `“${m.who.words}”`}
+ {m.base ? ` · corrects v${shot.masks.findIndex((x) => x.id === m.base) + 1}` : ""}
+ </span>
+ <GenChip genId={m.genId} stepIds={m.stepIds} gens={gens} className="ml-auto" />
+ </div>
+ {piece?.url ? <video src={piece.url} muted loop playsInline controls preload="metadata" className="aspect-video w-full rounded-lg bg-media object-contain" /> : null}
+ <JobError genId={m.genId} stepIds={m.stepIds} gens={gens} />
+ <div className="flex flex-wrap gap-1.5">
+ <Button
+ size="sm"
+ variant={approved ? "secondary" : "outline"}
+ className="h-7 rounded-full px-2.5 text-[12px]"
+ disabled={!finished(m) || approved}
+ onClick={() => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { approvedMask: m.id } })}
+ >
+ <Check className="size-3.5" /> {approved ? "Approved" : "Approve"}
+ </Button>
+ {finished(m) && (
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2.5 text-[12px]" aria-pressed={baseVersion?.id === m.id} onClick={() => setBase(m.id)}>
+ {baseVersion?.id === m.id ? "Updates go here" : "Update this one"}
+ </Button>
+ )}
+ {state.status === "queued" || state.status === "running" ? (
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => stop.mutate({ kind: "mask", clipId: clip.id, shotId: shot.id, jobId: m.id })}>
+ Stop
+ </Button>
+ ) : (
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2.5 text-[12px]" aria-label={`Remove mask v${n}`} onClick={() => void edit({ type: "remove-mask", clipId: clip.id, shotId: shot.id, maskId: m.id })}>
+ <Trash2 className="size-3.5" />
+ </Button>
+ )}
+ </div>
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ {engine === "open" && shot.settings.useMask && !shot.approvedMask && <Note className="mt-3">No approved mask: each segment finds the person itself with SAM 3.1 from the pick and words above.</Note>}
+ </Panel>
+ </div>
+ );
+}
diff --git a/src/components/swap-studio/stage-words.tsx b/src/components/swap-studio/stage-words.tsx
new file mode 100644
index 00000000..335590e8
--- /dev/null
+++ b/src/components/swap-studio/stage-words.tsx
@@ -0,0 +1,145 @@
+"use client";
+
+import { Loader2, Mic, Wand2 } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Panel } from "@/components/av/tool-shell";
+import { buildShotPrompt, ROLE_LABELS, secondsLabel, shotDialogue, shotSpeaker, SWAP_STUDIO, voiceLabel, voicesOf, type SwapRole } from "@/lib/catalog/swap-studio";
+import { useTranscribe } from "./hooks";
+import { GenChip, JobError, Note, priceText, SavedText } from "./parts";
+import type { StageProps } from "./workbench";
+
+const ROLES = Object.keys(ROLE_LABELS) as SwapRole[];
+const stamp = (s: number) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`;
+
+function RoleSelect({ value, onChange, label, auto }: { value: SwapRole | null; onChange: (v: SwapRole | null) => void; label: string; auto?: SwapRole }) {
+ return (
+ <Select value={value ?? "auto"} onValueChange={(v) => onChange(v === "auto" ? null : (v as SwapRole))}>
+ <SelectTrigger className="h-8 w-full min-w-0 text-[13px] sm:w-56" aria-label={label}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {auto && <SelectItem value="auto">From the words · {ROLE_LABELS[auto].label}</SelectItem>}
+ {ROLES.map((r) => (
+ <SelectItem key={r} value={r}>
+ {ROLE_LABELS[r].label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+/** Words: the clip's transcript (both engines' speech to text), who each voice is, and each shot's speaker, words and prompt. */
+export function WordsStage({ id, project, clip, gens, estimate, edit }: StageProps) {
+ const transcribe = useTranscribe(id);
+ const t = clip.transcript;
+ const voices = voicesOf(t?.cues);
+ const busy = !!t?.genId && (gens[t.genId]?.status === "queued" || gens[t.genId]?.status === "running");
+ return (
+ <div className="space-y-3">
+ <Panel
+ title="Transcript"
+ aside={
+ <span className="flex items-center gap-2">
+ {t?.genId && <GenChip genId={t.genId} gens={gens} />}
+ <Button
+ size="sm"
+ variant={t?.cues ? "outline" : "default"}
+ className="h-8 rounded-full"
+ disabled={busy || transcribe.isPending || !clip.source.hasAudio}
+ onClick={() => transcribe.mutate({ clipId: clip.id }, { onError: (e) => toast.error((e as Error).message) })}
+ >
+ {busy || transcribe.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Mic className="size-3.5" />}
+ {t?.cues ? "Transcribe again" : "Transcribe"}
+ <span className="font-mono text-[11px] opacity-80">{priceText(estimate?.transcribe[clip.id], { demo: estimate?.demo, engine: project.engine })}</span>
+ </Button>
+ </span>
+ }
+ >
+ {!clip.source.hasAudio ? (
+ <Note>This clip has no sound: every shot is “No dialogue”.</Note>
+ ) : !t?.cues ? (
+ <Note>
+ {project.engine === "open" ? "Qwen3-ASR on your ComfyUI" : "ElevenLabs Scribe v2 (fal)"} writes the clip&apos;s words with their times{project.engine === "cloud" ? " and who says them" : ""}; each shot and segment then takes the words spoken in it.
+ </Note>
+ ) : (
+ <div className="space-y-3">
+ {voices.length > 0 && (
+ <div className="space-y-2">
+ <p className="text-[12px] font-medium">Who is each voice?</p>
+ {voices.map((v) => (
+ <div key={v} className="flex min-w-0 flex-wrap items-center gap-2">
+ <span className="w-20 shrink-0 text-[13px]">{voiceLabel(voices, v)}</span>
+ <RoleSelect label={`${voiceLabel(voices, v)} is`} value={t.voices[v] ?? "target"} onChange={(r) => void edit({ type: "voices", clipId: clip.id, voices: { [v]: r ?? "target" } })} />
+ </div>
+ ))}
+ </div>
+ )}
+ <ol className="max-h-56 space-y-1 overflow-y-auto rounded-lg bg-muted p-2 text-[12px]" aria-label="Transcript lines">
+ {t.cues.map((c, i) => (
+ <li key={i} className="flex gap-2">
+ <span className="shrink-0 font-mono text-muted-foreground tabular-nums">{stamp(c.start)}</span>
+ {voices.length > 1 && <span className="shrink-0 text-muted-foreground">{voiceLabel(voices, c.speaker || "voice")}</span>}
+ <span className="min-w-0">{c.text}</span>
+ </li>
+ ))}
+ {!t.cues.length && <li className="text-muted-foreground">No words found.</li>}
+ </ol>
+ </div>
+ )}
+ <div className="mt-2">
+ <JobError genId={t?.genId} gens={gens} />
+ </div>
+ </Panel>
+
+ <Panel
+ title="Shot prompts"
+ aside={
+ <Button size="sm" className="h-8 rounded-full" onClick={() => void edit({ type: "build-prompts", clipId: clip.id })} disabled={!clip.shots.some((s) => s.mode === "generate")}>
+ <Wand2 className="size-3.5" /> Build shot prompts
+ </Button>
+ }
+ >
+ <Note className="mb-3">H3&apos;s reference tags: &lt;Video 1&gt; is the clip, &lt;Picture 1&gt; your character, &lt;Picture 2&gt; the scene anchor, &lt;Audio 1&gt; the clip&apos;s sound. On the cloud they become Video 1, Image 1 and Image 2.</Note>
+ <ol className="space-y-3">
+ {clip.shots.map((s, i) =>
+ s.mode !== "generate" ? (
+ <li key={s.id} className="rounded-lg border border-dashed px-3 py-2 text-[12px] text-muted-foreground">
+ Shot {i + 1} · {secondsLabel(s.end - s.start)} · kept as filmed
+ </li>
+ ) : (
+ <li key={s.id} className="space-y-2 rounded-lg border px-3 py-2.5">
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <span className="text-[13px] font-medium">
+ Shot {i + 1} <span className="font-normal text-muted-foreground">· {secondsLabel(s.end - s.start)}</span>
+ </span>
+ <div className="ml-auto w-full sm:w-auto">
+ <RoleSelect label={`Shot ${i + 1}: who speaks`} value={s.speaker} auto={shotSpeaker(clip, { ...s, speaker: null })} onChange={(speaker) => void edit({ type: "shot", clipId: clip.id, shotId: s.id, patch: { speaker } })} />
+ </div>
+ </div>
+ <SavedText
+ label="Words"
+ rows={2}
+ max={SWAP_STUDIO.maxPromptChars}
+ value={shotDialogue(clip, s)}
+ hint={s.dialogue === null ? "from the transcript" : "your words"}
+ onSave={(dialogue) => void edit({ type: "shot", clipId: clip.id, shotId: s.id, patch: { dialogue } })}
+ />
+ <SavedText
+ label="Prompt"
+ rows={4}
+ max={SWAP_STUDIO.maxPromptChars}
+ value={s.prompt ?? buildShotPrompt(project, clip, s)}
+ hint={s.prompt === null ? "built from the above — edit to keep your own" : "yours"}
+ onSave={(prompt) => void edit({ type: "shot", clipId: clip.id, shotId: s.id, patch: { prompt } })}
+ />
+ </li>
+ ),
+ )}
+ </ol>
+ </Panel>
+ </div>
+ );
+}
diff --git a/src/components/swap-studio/use-scene-cuts.ts b/src/components/swap-studio/use-scene-cuts.ts
new file mode 100644
index 00000000..703d00f9
--- /dev/null
+++ b/src/components/swap-studio/use-scene-cuts.ts
@@ -0,0 +1,62 @@
+"use client";
+
+import { useCallback, useRef, useState } from "react";
+import { openVideo, releaseVideo, sampleFrames } from "@/components/av/frame-sampler";
+import { coarseTimes, coarseWindows, sceneScores, STUDIO_FPS, windowCuts, windowFrames } from "@/lib/av/scene-cuts";
+
+/**
+ * "Detect edits": FFmpeg's scene score at Akatz Labs' 0.32, read in the browser (src/lib/av/scene-cuts.ts). A coarse
+ * pass a few frames a second finds where a cut can be; a fine pass reads every 24 fps frame there. The frames are
+ * small (64 px wide) — the score is a mean over the picture, so it barely depends on the size.
+ */
+export function useSceneCuts() {
+ const [state, setState] = useState<{ busy: boolean; progress: number; error: string | null }>({ busy: false, progress: 0, error: null });
+ const stop = useRef<AbortController | null>(null);
+
+ const detect = useCallback(async (src: string, total: number): Promise<number[] | null> => {
+ stop.current?.abort();
+ const ctrl = new AbortController();
+ stop.current = ctrl;
+ setState({ busy: true, progress: 0, error: null });
+ let v: HTMLVideoElement | null = null;
+ try {
+ v = await openVideo(src);
+ const duration = v.duration;
+ const times = coarseTimes(duration);
+ const coarse = await sampleFrames(v, times, { width: 64, signal: ctrl.signal, onProgress: (p) => setState((s) => ({ ...s, progress: p * 0.6 })) });
+ if (ctrl.signal.aborted) return null;
+ const windows = coarseWindows(
+ coarse.map((f) => f.t),
+ sceneScores(coarse.map((f) => f.data.data)),
+ total,
+ );
+ const cuts = new Set<number>();
+ for (const [i, w] of windows.entries()) {
+ const frames = windowFrames(w);
+ // The middle of each 24 fps frame: whichever frame of the clip shows then.
+ const fine = await sampleFrames(
+ v,
+ frames.map((f) => Math.min(duration - 0.01, (f + 0.5) / STUDIO_FPS)),
+ { width: 64, signal: ctrl.signal },
+ );
+ if (ctrl.signal.aborted) return null;
+ for (const c of windowCuts(frames, fine.map((f) => f.data.data), total)) cuts.add(c);
+ setState((s) => ({ ...s, progress: 0.6 + (0.4 * (i + 1)) / windows.length }));
+ }
+ setState({ busy: false, progress: 1, error: null });
+ return [...cuts].sort((a, b) => a - b);
+ } catch (e) {
+ if (!ctrl.signal.aborted) setState({ busy: false, progress: 0, error: (e as Error).message || "Couldn't read this clip's frames — add the cuts by hand" });
+ return null;
+ } finally {
+ if (v) releaseVideo(v);
+ }
+ }, []);
+
+ const cancel = useCallback(() => {
+ stop.current?.abort();
+ setState({ busy: false, progress: 0, error: null });
+ }, []);
+
+ return { ...state, detect, cancel };
+}
diff --git a/src/components/swap-studio/workbench.tsx b/src/components/swap-studio/workbench.tsx
new file mode 100644
index 00000000..180ae6c8
--- /dev/null
+++ b/src/components/swap-studio/workbench.tsx
@@ -0,0 +1,477 @@
+"use client";
+
+import { ArrowLeft, Download, Film, ImagePlus, Loader2, Plus, RotateCcw, Trash2 } from "lucide-react";
+import Link from "next/link";
+import { useId, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Panel, ToolShell } from "@/components/av/tool-shell";
+import { tabKeys } from "@/components/shorts/ui";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import { uploadFile } from "@/lib/api";
+import { clipExtension, clipProblem, jobState, MODE_LABELS, secondsLabel, SWAP_STUDIO, type GenSummary, type StudioEstimate, type SwapClip, type SwapProject, type SwapShot } from "@/lib/catalog/swap-studio";
+import { cn } from "@/lib/utils";
+import { decisionsHref, useAddClip, usePrepareClip, useSwapEdit, useSwapEstimate, useSwapProject, type EditInput } from "./hooks";
+import { GenChip, JobError, Note, priceText, SavedText } from "./parts";
+import { AnchorsStage } from "./stage-anchors";
+import { AssembleStage, ReviewStage } from "./stage-review";
+import { SegmentsStage } from "./stage-segments";
+import { ShotsStage } from "./stage-shots";
+import { WhoStage } from "./stage-who";
+import { WordsStage } from "./stage-words";
+
+/** What every stage gets: the project, the clip and shot it works on, the jobs' states and prices, and the edit call. */
+export interface StageProps {
+ id: string;
+ project: SwapProject;
+ clip: SwapClip;
+ gens: Record<string, GenSummary>;
+ estimate: StudioEstimate | undefined;
+ shot: SwapShot | null;
+ setShot: (id: string) => void;
+ edit: (e: EditInput) => Promise<SwapProject | undefined>;
+ /** The clip as the page plays it (your GPU's 24 fps copy once it's made). */
+ src: string;
+}
+
+const STAGES = [
+ { id: "shots", label: "Shots" },
+ { id: "words", label: "Words" },
+ { id: "who", label: "Who to swap" },
+ { id: "anchors", label: "Scene anchors" },
+ { id: "segments", label: "Segments" },
+ { id: "review", label: "Takes & review" },
+ { id: "assemble", label: "Assemble" },
+] as const;
+type Stage = (typeof STAGES)[number]["id"];
+
+/** Upload a clip with progress (the server reads its header when it's added). */
+function uploadClip(file: File, onProgress: (p: number) => void): Promise<{ url: string; name?: string }> {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", "/api/uploads");
+ xhr.responseType = "json";
+ xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(e.loaded / e.total);
+ xhr.onload = () => {
+ const body = xhr.response as { url?: string; name?: string; error?: string } | null;
+ if (xhr.status >= 200 && xhr.status < 300 && body?.url) resolve({ url: body.url, name: body.name });
+ else reject(new Error(body?.error ?? `Upload failed (${xhr.status})`));
+ };
+ xhr.onerror = () => reject(new Error("Upload failed — check your connection"));
+ const form = new FormData();
+ form.append("file", file);
+ xhr.send(form);
+ });
+}
+
+/** What the browser reads of a clip before the server does (a format it can't play just has none of it). */
+function browserFacts(file: File): Promise<{ duration?: number; width?: number; height?: number }> {
+ return new Promise((resolve) => {
+ const v = document.createElement("video");
+ const url = URL.createObjectURL(file);
+ const done = (x: { duration?: number; width?: number; height?: number }) => {
+ URL.revokeObjectURL(url);
+ resolve(x);
+ };
+ v.preload = "metadata";
+ v.onloadedmetadata = () => done({ duration: Number.isFinite(v.duration) ? v.duration : undefined, width: v.videoWidth || undefined, height: v.videoHeight || undefined });
+ v.onerror = () => done({});
+ setTimeout(() => done({}), 6000);
+ v.src = url;
+ });
+}
+
+export function SwapWorkbench({ id }: { id: string }) {
+ const q = useSwapProject(id);
+ const v = q.data;
+ const project = v?.project;
+ const estimate = useSwapEstimate(id, project?.revision, project?.engine).data;
+ const editMutation = useSwapEdit(id);
+ const [clipId, setClipId] = useState<string | null>(null);
+ const [stage, setStage] = useState<Stage>("shots");
+ const [shotId, setShotId] = useState<string | null>(null);
+ const tabsId = useId();
+
+ const clip = project?.clips.find((c) => c.id === clipId) ?? project?.clips[0] ?? null;
+ const shot = clip?.shots.find((s) => s.id === shotId) ?? clip?.shots.find((s) => s.mode === "generate") ?? clip?.shots[0] ?? null;
+
+ const edit = async (e: EditInput) => {
+ try {
+ return await editMutation.mutateAsync(e);
+ } catch (err) {
+ toast.error((err as Error).message);
+ return undefined;
+ }
+ };
+
+ if (q.error) {
+ return (
+ <ToolShell title="Character Swap Studio" engineSwitch={false}>
+ <div className="mx-auto max-w-md pt-16 text-center">
+ <h2 className="font-heading text-[28px]">Project not found</h2>
+ <p className="mt-2 text-[14px] text-muted-foreground">{(q.error as Error).message}</p>
+ <Button asChild className="mt-6 rounded-full">
+ <Link href="/character-swap">All projects</Link>
+ </Button>
+ </div>
+ </ToolShell>
+ );
+ }
+ if (!v || !project) {
+ return (
+ <ToolShell title="Character Swap Studio" engineSwitch={false} wide>
+ <div className="mt-4 grid gap-4 lg:grid-cols-[300px_1fr]">
+ <Skeleton className="h-80 rounded-2xl" />
+ <Skeleton className="h-[480px] rounded-2xl" />
+ </div>
+ </ToolShell>
+ );
+ }
+
+ const src = clip ? (project.engine === "open" ? (clip.normalized?.url ?? clip.source.url) : clip.source.url) : "";
+ const props: StageProps | null = clip ? { id, project, clip, gens: v.gens, estimate, shot, setShot: setShotId, edit, src } : null;
+
+ return (
+ <ToolShell
+ title={project.name}
+ engineSwitch={false}
+ wide
+ header={
+ <>
+ <Button asChild variant="ghost" size="sm" className="hidden rounded-full sm:inline-flex">
+ <a href={decisionsHref(id)} download>
+ <Download className="size-4" /> Export decisions
+ </a>
+ </Button>
+ <EngineSwitch value={project.engine} onChange={(engine) => engine !== project.engine && void edit({ type: "engine", engine })} />
+ </>
+ }
+ >
+ <Link href="/character-swap" className="mt-2 inline-flex items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground">
+ <ArrowLeft className="size-4" /> All projects
+ </Link>
+ <div className="mt-3 grid min-w-0 gap-4 lg:grid-cols-[300px_minmax(0,1fr)]">
+ <div className="min-w-0 space-y-4">
+ <ProjectPanel project={project} estimate={estimate} edit={edit} />
+ <CharacterPanel project={project} edit={edit} />
+ <ClipsPanel id={id} project={project} gens={v.gens} selected={clip?.id ?? null} onSelect={(c) => {
+ setClipId(c);
+ setShotId(null);
+ }} edit={edit} />
+ </div>
+
+ <div className="min-w-0">
+ {!clip || !props ? (
+ <Panel>
+ <div className="flex flex-col items-center gap-2 py-12 text-center">
+ <Film className="size-8 text-muted-foreground" aria-hidden />
+ <p className="text-[14px] font-medium">Add a clip to start</p>
+ <p className="max-w-sm text-[12px] text-muted-foreground">MP4, MOV, MKV, WebM or AVI, up to 149.66 s and 200 MB. {project.engine === "open" ? "Your GPU works on a 24 fps copy, made as soon as it's added." : "The cloud reads it as filmed."}</p>
+ </div>
+ </Panel>
+ ) : (
+ <section aria-label={`Clip ${clip.name}`} className="min-w-0 space-y-3">
+ <ClipHeader {...props} />
+ <div role="tablist" aria-label="Stages" onKeyDown={tabKeys} className="-mx-1 flex gap-1 overflow-x-auto px-1 pb-1">
+ {STAGES.map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ role="tab"
+ id={`${tabsId}-${s.id}`}
+ aria-selected={stage === s.id}
+ aria-controls={`${tabsId}-panel`}
+ tabIndex={stage === s.id ? 0 : -1}
+ onClick={() => setStage(s.id)}
+ className={cn(
+ "h-8 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ stage === s.id ? "bg-foreground text-background" : "bg-muted text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {s.label}
+ </button>
+ ))}
+ </div>
+ {stage !== "shots" && stage !== "words" && stage !== "assemble" && <ShotStrip clip={clip} shot={shot} onPick={setShotId} gens={v.gens} />}
+ <div role="tabpanel" id={`${tabsId}-panel`} aria-labelledby={`${tabsId}-${stage}`} className="min-w-0">
+ {stage === "shots" && <ShotsStage key={clip.id} {...props} />}
+ {stage === "words" && <WordsStage {...props} />}
+ {stage === "who" && <WhoStage key={`${clip.id}-${shot?.id}`} {...props} />}
+ {stage === "anchors" && <AnchorsStage {...props} />}
+ {stage === "segments" && <SegmentsStage key={`${clip.id}-${shot?.id}`} {...props} />}
+ {stage === "review" && <ReviewStage {...props} />}
+ {stage === "assemble" && <AssembleStage {...props} />}
+ </div>
+ </section>
+ )}
+ </div>
+ </div>
+ </ToolShell>
+ );
+}
+
+function ProjectPanel({ project, estimate, edit }: { project: SwapProject; estimate: StudioEstimate | undefined; edit: StageProps["edit"] }) {
+ const nameId = useId();
+ return (
+ <Panel title="Project">
+ <label htmlFor={nameId} className="sr-only">
+ Project name
+ </label>
+ <input
+ id={nameId}
+ key={project.name}
+ defaultValue={project.name}
+ maxLength={SWAP_STUDIO.maxNameChars}
+ onBlur={(e) => e.currentTarget.value.trim() && e.currentTarget.value !== project.name && void edit({ type: "rename", name: e.currentTarget.value })}
+ onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
+ className="h-9 w-full rounded-md border bg-background px-2.5 text-[14px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ <dl className="mt-3 grid grid-cols-2 gap-2 text-[12px]">
+ <div className="rounded-lg bg-muted px-2.5 py-2">
+ <dt className="text-muted-foreground">Every shot&apos;s queue</dt>
+ <dd className="mt-0.5 font-medium">
+ {estimate ? `${estimate.project.segments} segment${estimate.project.segments === 1 ? "" : "s"}` : "…"}
+ <span className="block font-mono text-[12px]">{priceText(estimate?.project.costUsd, { demo: estimate?.demo, engine: project.engine })}</span>
+ </dd>
+ </div>
+ <div className="rounded-lg bg-muted px-2.5 py-2">
+ <dt className="text-muted-foreground">Engine</dt>
+ <dd className="mt-0.5 font-medium">{project.engine === "open" ? "Your GPU (ComfyUI)" : "Cloud (fal)"}</dd>
+ </div>
+ </dl>
+ {estimate?.demo && <Note className="mt-2">Demo mode: nothing is paid for and the takes are sample clips. Connect {project.engine === "open" ? "ComfyUI" : "fal"} in Settings to run it for real.</Note>}
+ <Button asChild variant="outline" size="sm" className="mt-3 w-full rounded-full sm:hidden">
+ <a href={decisionsHref(project.id)} download>
+ <Download className="size-4" /> Export decisions
+ </a>
+ </Button>
+ </Panel>
+ );
+}
+
+function CharacterPanel({ project, edit }: { project: SwapProject; edit: StageProps["edit"] }) {
+ const input = useRef<HTMLInputElement>(null);
+ const [busy, setBusy] = useState(false);
+ const pick = async (file: File) => {
+ if (!file.type.startsWith("image/")) return toast.error("Pick an image of your character");
+ setBusy(true);
+ try {
+ const a = await uploadFile(file);
+ await edit({ type: "character", image: a.url });
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <Panel title="Your character">
+ <div className="flex gap-3">
+ <button
+ type="button"
+ onClick={() => input.current?.click()}
+ className="relative grid size-24 shrink-0 place-items-center overflow-hidden rounded-xl border border-dashed bg-muted text-muted-foreground hover:border-border-strong focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ aria-label={project.character.image ? "Replace the character picture" : "Add a picture of your character"}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {project.character.image ? <img src={project.character.image} alt="" className="size-full object-cover" /> : <ImagePlus className="size-6" aria-hidden />}
+ {busy && (
+ <span className="absolute inset-0 grid place-items-center bg-background/70">
+ <Loader2 className="size-5 animate-spin" />
+ </span>
+ )}
+ </button>
+ <p className="min-w-0 text-[12px] leading-snug text-pretty text-muted-foreground">
+ One clear picture of who comes in (<span className="font-medium text-foreground">Picture 1</span>). A new picture un-approves the scene anchors made with the old one.
+ </p>
+ </div>
+ <input ref={input} type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files?.[0] && void pick(e.target.files[0])} />
+ <div className="mt-3">
+ <SavedText
+ label="Description"
+ value={project.character.description}
+ max={SWAP_STUDIO.maxDescriptionChars}
+ placeholder="a woman in her thirties, short black hair, yellow raincoat"
+ onSave={(description) => void edit({ type: "character", description })}
+ hint="in every prompt"
+ />
+ </div>
+ </Panel>
+ );
+}
+
+function ClipsPanel({
+ id,
+ project,
+ gens,
+ selected,
+ onSelect,
+ edit,
+}: {
+ id: string;
+ project: SwapProject;
+ gens: Record<string, GenSummary>;
+ selected: string | null;
+ onSelect: (id: string) => void;
+ edit: StageProps["edit"];
+}) {
+ const add = useAddClip(id);
+ const input = useRef<HTMLInputElement>(null);
+ const [upload, setUpload] = useState<{ name: string; progress: number } | null>(null);
+ const [remove, setRemove] = useState<SwapClip | null>(null);
+
+ const pick = async (file: File) => {
+ const problem = !clipExtension(file.name) ? "Add an MP4, MOV, MKV, WebM or AVI clip" : clipProblem({ bytes: file.size });
+ if (problem) return toast.error(problem);
+ const facts = await browserFacts(file);
+ const long = clipProblem({ duration: facts.duration });
+ if (long) return toast.error(long);
+ setUpload({ name: file.name, progress: 0 });
+ try {
+ const up = await uploadClip(file, (p) => setUpload({ name: file.name, progress: p }));
+ const p = await add.mutateAsync({ url: up.url, name: file.name, bytes: file.size, ...facts });
+ onSelect(p.clips.at(-1)!.id);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setUpload(null);
+ }
+ };
+
+ return (
+ <Panel
+ title={`Clips · ${project.clips.length}`}
+ aside={
+ <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => input.current?.click()} disabled={!!upload || project.clips.length >= SWAP_STUDIO.maxClips}>
+ <Plus className="size-3.5" /> Add clip
+ </Button>
+ }
+ >
+ <input ref={input} type="file" accept={SWAP_STUDIO.accept} className="hidden" onChange={(e) => e.target.files?.[0] && void pick(e.target.files[0])} />
+ {upload && (
+ <div className="mb-2 rounded-lg bg-muted px-2.5 py-2 text-[12px]">
+ <span className="block truncate font-medium">{upload.name}</span>
+ <div className="mt-1 h-1 overflow-hidden rounded-full bg-background" role="progressbar" aria-valuenow={Math.round(upload.progress * 100)} aria-valuemin={0} aria-valuemax={100} aria-label="Uploading">
+ <div className="h-full bg-primary transition-[width]" style={{ width: `${Math.round(upload.progress * 100)}%` }} />
+ </div>
+ </div>
+ )}
+ {!project.clips.length && !upload ? (
+ <p className="text-[12px] text-muted-foreground">No clips yet.</p>
+ ) : (
+ <ul className="space-y-1.5">
+ {project.clips.map((c) => {
+ const norm = project.engine === "open" && !c.normalized?.url ? jobState(c.normalized?.genId, undefined, gens) : null;
+ return (
+ <li key={c.id} className="flex min-w-0 items-center gap-1">
+ <button
+ type="button"
+ onClick={() => onSelect(c.id)}
+ aria-current={selected === c.id ? "true" : undefined}
+ className={cn(
+ "flex min-w-0 flex-1 flex-col rounded-lg px-2.5 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ selected === c.id ? "bg-brand-faint" : "hover:bg-muted",
+ )}
+ >
+ <span className="truncate text-[13px] font-medium">{c.name}</span>
+ <span className="truncate text-[11px] text-muted-foreground">
+ {secondsLabel(c.frames)} · {c.shots.length} shot{c.shots.length === 1 ? "" : "s"} · {c.shots.filter((s) => s.mode === "generate").length} swapped
+ {c.assembly?.genId ? " · assembled" : ""}
+ {norm ? ` · 24 fps copy: ${norm.status === "succeeded" ? "ready" : norm.status}` : ""}
+ </span>
+ </button>
+ <button
+ type="button"
+ onClick={() => setRemove(c)}
+ aria-label={`Remove ${c.name}`}
+ className="grid size-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ <AlertDialog open={!!remove} onOpenChange={(o) => !o && setRemove(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Remove “{remove?.name}”?</AlertDialogTitle>
+ <AlertDialogDescription>Its shots, masks, anchors and takes leave the project (an assembled clip stays in the Library).</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep it</AlertDialogCancel>
+ <AlertDialogAction onClick={() => remove && void edit({ type: "remove-clip", clipId: remove.id })}>Remove</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </Panel>
+ );
+}
+
+function ClipHeader({ id, project, clip, gens }: StageProps) {
+ const prepare = usePrepareClip(id);
+ const norm = jobState(clip.normalized?.genId, undefined, gens);
+ const s = clip.source;
+ return (
+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
+ <h2 className="min-w-0 truncate text-[16px] font-semibold">{clip.name}</h2>
+ <span className="text-[12px] text-muted-foreground">
+ {secondsLabel(clip.frames)} · {clip.frames} frames at 24 fps{s.fps ? ` (filmed at ${Math.round(s.fps * 100) / 100} fps)` : ""}
+ {s.width && s.height ? ` · ${s.width}×${s.height}` : ""} · {s.hasAudio ? "with sound" : "silent"}
+ </span>
+ {project.engine === "open" && !clip.normalized?.url && (
+ <span className="flex items-center gap-2">
+ <span className="text-[12px] text-muted-foreground">24 fps copy</span>
+ <GenChip genId={clip.normalized?.genId} gens={gens} />
+ {(!clip.normalized?.genId || norm.status === "failed" || norm.status === "canceled" || norm.status === "missing") && (
+ <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" disabled={prepare.isPending} onClick={() => prepare.mutate({ clipId: clip.id }, { onError: (e) => toast.error((e as Error).message) })}>
+ <RotateCcw className="size-3.5" /> Prepare at 24 fps
+ </Button>
+ )}
+ </span>
+ )}
+ <div className="w-full">
+ <JobError genId={clip.normalized?.genId} gens={gens} />
+ </div>
+ </div>
+ );
+}
+
+/** The clip's shots as a strip (widths by length): pick the shot a stage works on. */
+export function ShotStrip({ clip, shot, onPick, gens }: { clip: SwapClip; shot: SwapShot | null; onPick: (id: string) => void; gens: Record<string, GenSummary> }) {
+ const busy = useMemo(() => new Set(Object.entries(gens).filter(([, g]) => g.status === "queued" || g.status === "running").map(([k]) => k)), [gens]);
+ return (
+ <div className="flex min-w-0 gap-1 overflow-x-auto pb-1" role="radiogroup" aria-label="Shot">
+ {clip.shots.map((s, i) => {
+ const working = (s.segments ?? []).some((g) => g.takes.some((t) => t.state === "waiting" || (t.genId && busy.has(t.genId))));
+ return (
+ <button
+ key={s.id}
+ type="button"
+ role="radio"
+ aria-checked={shot?.id === s.id}
+ onClick={() => onPick(s.id)}
+ title={`${MODE_LABELS[s.mode].label} · ${secondsLabel(s.end - s.start)}`}
+ style={{ flexGrow: Math.max(1, s.end - s.start) }}
+ className={cn(
+ "flex h-12 min-w-[4.5rem] shrink-0 basis-0 flex-col justify-center rounded-lg border px-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ s.mode === "generate" ? "border-brand-text/30 bg-brand-faint" : "bg-muted",
+ shot?.id === s.id && "ring-2 ring-foreground",
+ )}
+ >
+ <span className="flex items-center gap-1 text-[12px] font-semibold">
+ Shot {i + 1}
+ {working && <Loader2 className="size-3 animate-spin text-brand-text" aria-label="making takes" />}
+ </span>
+ <span className="truncate text-[11px] text-muted-foreground">
+ {secondsLabel(s.end - s.start)} · {s.mode === "generate" ? "replace" : "keep"}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/tests/e2e/character-swap-studio.mjs b/tests/e2e/character-swap-studio.mjs
new file mode 100644
index 00000000..877cec5c
--- /dev/null
+++ b/tests/e2e/character-swap-studio.mjs
@@ -0,0 +1,229 @@
+// Character Swap Studio, browser check (o/h3-studio): the whole flow in demo mode on the cloud engine — a project, the
+// character, a clip, Detect edits, a cut at the playhead and Keep original, the transcript and Build shot prompts, a
+// click on a frame and Track shot, a mask and a scene anchor approved, two segments (the second continuing from the
+// first, waiting for it), takes made, compared and reviewed, Export decisions, the assembly with a download, and the
+// Finish stage shown as not available. Then every stage at 1440 and 390 px, light and dark, without sideways scroll;
+// a project on your GPU shows its 24 fps copy; the sidebar and Genjutsu's Character swap link here; an unknown project
+// is a 404.
+// Usage: node tests/e2e/character-swap-studio.mjs [appUrl] [--shots <dir>] (app in demo mode, ComfyUI unreachable).
+// Exits 1 on a failed check.
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { launch, root } from "./_browser.mjs";
+
+const argv = process.argv.slice(2);
+const app = (argv.find((a) => !a.startsWith("--") && argv[argv.indexOf(a) - 1] !== "--shots") ?? "http://localhost:3000").replace(/\/$/, "");
+const shots = argv.includes("--shots") ? argv[argv.indexOf("--shots") + 1] : undefined;
+if (shots) fs.mkdirSync(shots, { recursive: true });
+
+const failures = [];
+const check = (label, ok, extra = "") => {
+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(72)}${extra ? ` ${extra}` : ""}`);
+ if (!ok) failures.push(label);
+};
+// The walk clip with a hard cut at 4 s (the last 2 s mirrored and inverted), as VP9 WebM: the browser reads its frames
+// for Detect edits and the frame to click (Playwright's Chromium decodes no H.264).
+const walk = path.join(root, "scripts/eval/fixtures/walk-6s.mp4");
+const clipFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "swap-studio-e2e-")), "walk.webm");
+execFileSync("ffmpeg", [
+ "-v", "error", "-y", "-i", walk,
+ "-filter_complex", "[0:v]split[a][b];[a]trim=0:4,setpts=PTS-STARTPTS[v1];[b]trim=4:6,setpts=PTS-STARTPTS,negate,hflip[v2];[v1][v2]concat=n=2:v=1:a=0[v]",
+ "-map", "[v]", "-map", "0:a", "-c:v", "libvpx-vp9", "-b:v", "500k", "-deadline", "realtime", "-cpu-used", "8", "-c:a", "libopus", "-shortest", clipFile,
+]);
+const heroFile = path.join(root, "scripts/eval/fixtures/character/drawn-face-2.png");
+const STAGES = ["Shots", "Words", "Who to swap", "Scene anchors", "Segments", "Takes & review", "Assemble"];
+
+// A rerun starts clean: earlier runs' projects go.
+for (const p of (await (await fetch(`${app}/api/swap-studio/projects`)).json()).items ?? []) {
+ if (p.name === "Rain scene" || p.name === "GPU check") await fetch(`${app}/api/swap-studio/projects/${p.id}`, { method: "DELETE" });
+}
+
+const browser = await launch();
+let projectUrl = "";
+try {
+ // ---------------------------------------------------------------------------
+ // The flow, once (1440 light).
+ {
+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: "light" });
+ await context.addInitScript(() => {
+ try {
+ localStorage.setItem("fuobe.engine", "cloud");
+ } catch {}
+ });
+ const page = await context.newPage();
+ page.setDefaultTimeout(60_000);
+ const text = () => page.evaluate(() => document.body.innerText);
+ const shot = async (name) => shots && (await page.screenshot({ path: path.join(shots, `${name}.png`), fullPage: true }));
+
+ await page.goto(`${app}/character-swap`, { waitUntil: "load", timeout: 180_000 });
+ await page.getByRole("heading", { name: "Swap a character through whole clips" }).waitFor({ timeout: 120_000 });
+ check("projects page: hero and steps", (await text()).includes("Who and the scene"));
+ check("sidebar links the studio", (await page.locator('a[href="/character-swap"]').count()) > 0);
+ await page.getByPlaceholder(/Name the project/).fill("Rain scene");
+ await page.getByRole("button", { name: /New project · cloud/ }).click();
+ await page.waitForURL(/\/character-swap\/swap-/, { timeout: 60_000 });
+ projectUrl = page.url();
+ await page.getByRole("heading", { name: "Rain scene" }).waitFor();
+ check("project page opens", true, projectUrl.split("/").pop());
+
+ // The character and the clip.
+ await page.locator('input[type="file"][accept="image/*"]').first().setInputFiles(heroFile);
+ await page.locator('img[src^="/api/files/"]').first().waitFor();
+ const desc = page.getByLabel("Description");
+ await desc.fill("a cartoon man with round glasses and a blue scarf");
+ await desc.blur();
+ await page.locator('input[type="file"][accept^="video/"]').setInputFiles(clipFile);
+ await page.getByRole("button", { name: /^walk/ }).waitFor({ timeout: 90_000 });
+ check("clip added (6 s, 144 frames at 24 fps)", /144 frames at 24 fps/.test(await text()));
+
+ // Shots: detect, then a cut at 4 s, shot 2 kept as filmed.
+ await page.getByRole("button", { name: "Detect edits" }).click();
+ await page.getByText(/edits? detected|Detected \d+ edit/).waitFor({ timeout: 90_000 });
+ const found = await text();
+ check("Detect edits finds the cut at 4 s (frame 96)", /Detected 1 edit at frames 96 /.test(found), found.match(/Detected[^\n]*|No edits[^\n]*/)?.[0] ?? "");
+ if (/Detected 1 edit at frames 96 /.test(found)) await page.getByRole("button", { name: "Use them" }).click();
+ else {
+ // Placed by hand at the playhead instead.
+ await page.evaluate(() => {
+ const v = document.querySelector("video");
+ v.currentTime = 4.02;
+ });
+ await page.waitForFunction(() => /Frame 96 /.test(document.body.innerText), null, { timeout: 15_000 });
+ await page.getByRole("button", { name: "Cut at the playhead" }).click();
+ }
+ await page.getByRole("radiogroup", { name: "Shot 2" }).getByRole("radio", { name: /Keep original/ }).click();
+ await page.getByRole("button", { name: "Save shots" }).click();
+ await page.getByRole("button", { name: "Saved" }).waitFor();
+ check("cuts saved: two shots, the second kept", /Shot 2[\s\S]*96–144/.test(await text()));
+ await shot("01-shots");
+
+ // Words: transcript, Build shot prompts.
+ await page.getByRole("tab", { name: "Words" }).click();
+ await page.getByRole("button", { name: /^Transcribe/ }).click();
+ await page.getByText("This is a demo transcript.").first().waitFor({ timeout: 60_000 });
+ await page.getByRole("button", { name: "Build shot prompts" }).click();
+ await page.waitForFunction(() => [...document.querySelectorAll("textarea")].some((t) => t.value.includes('Current shot dialogue: "This is a demo transcript.')), null, { timeout: 20_000 });
+ check("transcript and shot prompt (H3 tags, the shot's words)", true);
+ await shot("02-words");
+
+ // Who to swap: a click on a frame, Track shot, approve.
+ await page.getByRole("tab", { name: "Who to swap" }).click();
+ await page.getByRole("button", { name: "Show this frame" }).click();
+ const stage = page.getByRole("application");
+ await stage.waitFor();
+ const box = await stage.boundingBox();
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ check("include point placed", (await page.getByRole("button", { name: /Take away point 1 \(include\)/ }).count()) === 1);
+ await page.getByRole("button", { name: /^Track shot/ }).click();
+ const approveMask = page.getByRole("button", { name: "Approve", exact: true }).first();
+ await approveMask.waitFor();
+ await page.waitForFunction(() => [...document.querySelectorAll("button")].some((b) => b.textContent?.trim() === "Approve" && !b.disabled), null, { timeout: 60_000 });
+ await approveMask.click();
+ await page.getByRole("button", { name: "Approved" }).waitFor();
+ check("mask version made and approved", true);
+ await shot("03-who");
+
+ // Scene anchor: make, approve.
+ await page.getByRole("tab", { name: "Scene anchors" }).click();
+ await page.getByRole("button", { name: "Make anchor" }).click();
+ await page.waitForFunction(() => [...document.querySelectorAll("button")].some((b) => b.textContent?.trim() === "Approve" && !b.disabled), null, { timeout: 60_000 });
+ await page.getByRole("button", { name: "Approve", exact: true }).first().click();
+ await page.getByRole("button", { name: "Approved" }).waitFor();
+ check("scene anchor made and approved", true);
+ await shot("04-anchors");
+
+ // Segments: split in two (the second continues), prices, queue all; the second waits, then both are chosen.
+ await page.getByRole("tab", { name: "Segments" }).click();
+ await page.getByRole("button", { name: "Split", exact: true }).click();
+ await page.getByRole("listitem", { name: "Segment 2" }).waitFor();
+ check("price shown before running", /Demo · free/.test(await text()));
+ await page.getByRole("button", { name: "Queue all segments" }).click();
+ await page.getByText("waits for the segment before").waitFor({ timeout: 20_000 });
+ check("the continuing segment waits for the one before", true);
+ await page.waitForFunction(() => [...document.querySelectorAll("button")].filter((b) => b.textContent?.trim() === "Chosen").length >= 2, null, { timeout: 150_000 });
+ check("both takes made and chosen", true);
+ await shot("05-segments");
+
+ // Review: compare, favourite, keep.
+ await page.getByRole("tab", { name: "Takes & review" }).click();
+ await page.getByRole("button", { name: "Play both from the start" }).waitFor();
+ check("two takes side by side", (await page.locator("video").count()) >= 2);
+ await page.getByRole("button", { name: "Favourite" }).first().click();
+ await page.getByRole("radiogroup", { name: "Take 1 decision" }).first().getByRole("radio", { name: "Keep" }).click();
+ await page.getByRole("radiogroup", { name: "Clip decision" }).getByRole("radio", { name: "Keep" }).click();
+ await page.getByRole("button", { name: "Unfavourite" }).first().waitFor();
+ const exported = await page.evaluate(async (u) => (await fetch(u)).json(), `${new URL(projectUrl).pathname.replace("/character-swap/", "/api/swap-studio/projects/")}/decisions`);
+ check("Export decisions: the clip's review and the take's", exported.clips?.[0]?.review === "keep" && exported.clips[0].shots[0].segments[0].takes[0].favourite === true);
+ await shot("06-review");
+
+ // Assemble; the Finish stage is not available.
+ await page.getByRole("tab", { name: "Assemble" }).click();
+ await page.getByRole("button", { name: "Assemble clip" }).click();
+ await page.getByRole("link", { name: "Download" }).waitFor({ timeout: 120_000 });
+ check("assembled, with a download", true);
+ check("Finish stage shown as not available", /Not available/.test(await text()) && /Raw assembly migration is pending/.test(await text()));
+ await shot("07-assemble");
+ await context.close();
+ }
+
+ // ---------------------------------------------------------------------------
+ // Every stage at both widths, light and dark: nothing scrolls sideways.
+ for (const [width, height] of [
+ [1440, 900],
+ [390, 844],
+ ]) {
+ for (const scheme of ["light", "dark"]) {
+ const tag = `${width} ${scheme}`;
+ const context = await browser.newContext({ viewport: { width, height }, colorScheme: scheme, ...(width < 500 ? { isMobile: true, hasTouch: true } : {}) });
+ const page = await context.newPage();
+ page.setDefaultTimeout(60_000);
+ const sideways = () => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
+ await page.goto(`${app}/character-swap`, { waitUntil: "load", timeout: 120_000 });
+ await page.getByRole("link", { name: "Rain scene" }).waitFor();
+ check(`${tag}: projects page, no sideways scroll`, (await sideways()) <= 0, `${await sideways()}px`);
+ if (shots) await page.screenshot({ path: path.join(shots, `home-${width}-${scheme}.png`), fullPage: true });
+ await page.goto(projectUrl, { waitUntil: "load" });
+ await page.getByRole("tab", { name: "Shots" }).waitFor();
+ for (const s of STAGES) {
+ await page.getByRole("tab", { name: s }).click();
+ await page.waitForTimeout(400);
+ const over = await sideways();
+ check(`${tag}: ${s}, no sideways scroll`, over <= 0, `${over}px`);
+ if (shots) await page.screenshot({ path: path.join(shots, `${s.replace(/\W+/g, "-").toLowerCase()}-${width}-${scheme}.png`), fullPage: true });
+ }
+ await context.close();
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Your GPU (a demo here): the 24 fps copy; Genjutsu's link; a 404.
+ {
+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
+ const page = await context.newPage();
+ page.setDefaultTimeout(60_000);
+ const created = await (await fetch(`${app}/api/swap-studio/projects`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "GPU check", engine: "open" }) })).json();
+ const form = new FormData();
+ form.append("file", new Blob([fs.readFileSync(walk)], { type: "video/mp4" }), "walk.mp4");
+ const up = await (await fetch(`${app}/api/uploads`, { method: "POST", body: form })).json();
+ await fetch(`${app}/api/swap-studio/projects/${created.id}/clips`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url: up.url, name: "walk.mp4" }) });
+ await page.goto(`${app}/character-swap/${created.id}`, { waitUntil: "load" });
+ await page.getByText("24 fps copy").first().waitFor();
+ check("your GPU: the clip's 24 fps copy is made on import", true);
+ await page.getByRole("tab", { name: "Assemble" }).click();
+ check("your GPU: where it runs (ComfyUI connection, no SSH)", /doesn't open SSH sessions/.test(await page.evaluate(() => document.body.innerText)));
+ await page.goto(`${app}/genjutsu?mode=character`, { waitUntil: "load" });
+ await page.getByRole("link", { name: /Open in Character Swap Studio/ }).waitFor({ timeout: 90_000 });
+ check("Genjutsu's Character swap links the studio", true);
+ const missing = await fetch(`${app}/character-swap/swap-nothing-here`);
+ check("an unknown project is a 404", missing.status === 404, String(missing.status));
+ await context.close();
+ }
+} catch (e) {
+ check("flow finished", false, String(e?.message ?? e).slice(0, 300));
+} finally {
+ await browser.close();
+}
+console.log(failures.length ? `\n${failures.length} failed` : "\nall ok");
+process.exit(failures.length ? 1 : 0);