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.

Remove a person: window previews kept from your ComfyUI, and earlier removals redone after a reload

Claude4a1813ef3e1a
diff --git a/src/components/remove-object/remove-object-tool.tsx b/src/components/remove-object/remove-object-tool.tsx
index 6abe3ec9..ceca880f 100644
--- a/src/components/remove-object/remove-object-tool.tsx
+++ b/src/components/remove-object/remove-object-tool.tsx
@@ -27,6 +27,7 @@ import {
REMOVE,
REMOVE_EXAMPLES,
REMOVE_MODES,
+ rerollProblem,
reviewOfOutput,
type Eraser,
type RemoveMode,
@@ -112,6 +113,9 @@ export function RemoveObjectTool({ tabs, person = false }: { tabs?: React.ReactN
const runGuard = useSubmitGuard();
const previewGuard = useSubmitGuard();
const history = useGenerations({ features: [REMOVE.feature], limit: 24 });
+ // Earlier H3 person removals whose windows can still be redone (the step that made them carries the review).
+ const reviewable = useGenerations({ features: [REMOVE.feature, REMOVE.stepFeature], models: [PERSON_ERASER], statuses: ["succeeded"], limit: 12 });
+ const earlier = (reviewable.data ?? []).filter((g) => !run?.ids.includes(g.id) && reviewOfOutput(g.outputs.find((o) => o.kind === "video")?.meta));
// Hand-off: /video-tools/remove-object?video=/api/files/… (a result's menu in the Library, the feed or Cinema).
useEffect(() => {
@@ -137,6 +141,8 @@ export function RemoveObjectTool({ tabs, person = false }: { tabs?: React.ReactN
const h3 = !!eraser?.cleanFrame;
// Removing a person with H3 runs on your GPU only (nothing hosted fills the person green for it): said on the cloud.
const personOnCloud = personAsked && engine === "cloud";
+ // H3 Person Removal switched off in Settings → Models & licences: said, so the fallback isn't a surprise.
+ const personOff = personAsked && engine === "open" && mode === "type" && !isOn(PERSON_ERASER);
// The selection's first frame, grabbed by the browser: what points and paint are made on.
const startAt = range ? Math.round(range.startTime * 100) / 100 : null;
@@ -491,6 +497,13 @@ export function RemoveObjectTool({ tabs, person = false }: { tabs?: React.ReactN
</div>
)}
+ {personOff && (
+ <p className="flex gap-1.5 rounded-xl bg-muted/60 p-3 text-[13px]" role="status">
+ <Cpu className="mt-0.5 size-3.5 shrink-0" />
+ <span>Person removal with MiniMax H3 is turned off here{eraser ? `, so ${eraser.label} is used instead` : ""}.</span>
+ </p>
+ )}
+
{h3 && (
<Field label="Mask expansion" htmlFor="remove-grow" hint={`${REMOVE.maskGrow.min}–${REMOVE.maskGrow.max} px`}>
<div className="flex items-center gap-2">
@@ -561,6 +574,26 @@ export function RemoveObjectTool({ tabs, person = false }: { tabs?: React.ReactN
{run && <RunPanel run={run} onAgain={start} onRedo={(r) => setRun({ ...run, final: r.final.id, ids: r.items.map((g) => g.id) })} />}
+ {earlier.length > 0 && (
+ <section className="mt-10" aria-labelledby="earlier-windows">
+ <h3 id="earlier-windows" className="mb-1 font-heading text-[22px]">
+ Redo a window
+ </h3>
+ <p className="mb-3 text-[13px] text-muted-foreground">Your earlier person removals, window by window. Open one to redo a weak part.</p>
+ <div className="space-y-2">
+ {earlier.map((g) => (
+ <details key={g.id} className="group rounded-xl border px-3 py-2">
+ <summary className="cursor-pointer truncate text-[13px] font-medium">{g.request.batchTitle ?? g.request.title ?? "Remove a person"}</summary>
+ <WindowReview
+ g={g}
+ onRedo={(r) => setRun({ final: r.final.id, ids: r.items.map((x) => x.id), before: g.request.inputs?.video ?? g.outputs.find((o) => o.kind === "video")?.url ?? "", start: 0 })}
+ />
+ </details>
+ ))}
+ </div>
+ </section>
+ )}
+
{(history.data?.length ?? 0) > 0 && (
<section className="mt-10" aria-labelledby="removals">
<h3 id="removals" className="mb-3 font-heading text-[22px]">
@@ -734,6 +767,7 @@ function WindowReview({ g, onRedo }: { g: Generation; onRedo: (r: { final: Gener
.finally(() => setBusy(null));
};
const fps = 24;
+ const why = (index: number) => rerollProblem(review, index);
return (
<div className="mt-4 space-y-2">
<div className="flex flex-wrap items-baseline justify-between gap-2">
@@ -759,7 +793,15 @@ function WindowReview({ g, onRedo }: { g: Generation; onRedo: (r: { final: Gener
<span className="min-w-0 truncate text-[12px] text-muted-foreground">
{w.index + 1} · {from} s{w.reused ? " · kept" : ""}
</span>
- <Button size="sm" variant="ghost" className="h-7 shrink-0 rounded-full px-2 text-[12px]" disabled={busy !== null} onClick={() => redo(w.index)} aria-label={`Redo from window ${w.index + 1}`}>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-7 shrink-0 rounded-full px-2 text-[12px]"
+ disabled={busy !== null || !!why(w.index)}
+ title={why(w.index) ?? undefined}
+ onClick={() => redo(w.index)}
+ aria-label={`Redo from here, window ${w.index + 1}`}
+ >
{busy === w.index ? <Loader2 className="size-3 animate-spin" /> : <Dices className="size-3" />} Redo from here
</Button>
</div>
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index cb60c725..02e24b38 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -700,7 +700,7 @@ How you work:
- Call generate (or create_storyboard) directly. The app shows the user a plan card with the cost and runs it when they approve — never ask "shall I go ahead?" in text.
- For multi-step work (an image, then animate it; transcribe, translate, then voice it), put the steps in one generate call and set "after" on each later job: it starts by itself when the earlier job finishes and gets its result as input. When you need to judge a result before deciding the next step, wait with check_generations instead (look=true to see images) and pass the output URL into the next call.
- Besides images, video and audio, models can transcribe speech, translate or write text (scripts, captions, ad copy), split images into layers, separate voice from background, trim, caption or re-sound clips, and turn an image into a 3D model: search_models with kind "text" or "model3d" finds the text and 3D ones.
-- Whole studio jobs have their own tools, and each job opens in its studio, where the user can carry on: split_layers (a Layers project), restyle_footage (a Shorts Studio session), dub_video (a dub the user reviews line by line in Translate & dub), faceless_episode (a Faceless Studio episode), create_ads (an Ads Studio batch), add_captions (the Captions editor), restore_video (old or black-and-white footage restored and colourised, in Restore & colourise), blockout_film (a grey-box 3D blockout from Blender or any 3D app filmed from reference stills and timed beats, as Cinema's Blockout does; in the Library) and katana (a reference edit — a 1–30 s video — rebuilt shot for shot with the user's own subject from 1–5 photos, when they want "this edit, but with me / my product"). Use them instead of chaining those steps by hand; once one starts, say which studio it's in (the chat links to it).
+- Whole studio jobs have their own tools, and each job opens in its studio, where the user can carry on: split_layers (a Layers project), restyle_footage (a Shorts Studio session), dub_video (a dub the user reviews line by line in Translate & dub), faceless_episode (a Faceless Studio episode), create_ads (an Ads Studio batch), add_captions (the Captions editor), restore_video (old or black-and-white footage restored and colourised, in Restore & colourise), remove_person (a person removed from a video and the scene rebuilt behind them, on the user's own GPU, in Remove a person), blockout_film (a grey-box 3D blockout from Blender or any 3D app filmed from reference stills and timed beats, as Cinema's Blockout does; in the Library) and katana (a reference edit — a 1–30 s video — rebuilt shot for shot with the user's own subject from 1–5 photos, when they want "this edit, but with me / my product"). Use them instead of chaining those steps by hand; once one starts, say which studio it's in (the chat links to it).
- Use the user's files by the URLs listed in their message. Earlier outputs are found with list_recent. Saved characters and products are Elements: check list_elements and write their @handle in prompts.
- Results show up in the chat by themselves, so don't repeat URLs back. After starting jobs, say briefly what's coming; after they finish, give a short take and suggest a next step.
- Be brief and friendly. Plain sentences, no headings. Prices are estimates in USD; open-source models run free on the user's own GPU.
diff --git a/src/server/assist/studio-routes.ts b/src/server/assist/studio-routes.ts
index af8a947a..d0680063 100644
--- a/src/server/assist/studio-routes.ts
+++ b/src/server/assist/studio-routes.ts
@@ -745,7 +745,7 @@ const removePersonRoute: StudioRoute<RemovePersonToolInput> = {
return {
ids: [r.final.id],
href: modeHref("video-tools", "remove-person"),
- info: { note: "The removal is listed under Your removals in Remove a person, beside the original with a Before/After wipe; each window there can be redone." },
+ info: { note: "The removal is listed under Your removals in Remove a person. When it finishes, Redo a window on that page shows each of its windows, and any weak one can be drawn again with the windows before it kept." },
};
},
};
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index c2e56bfc..0ba2d765 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -72,7 +72,7 @@ import { getSetting, isCandidate, savedSetting } from "../settings";
import { decodePng, encodePng } from "../png";
import { probeAvi } from "../avi-probe";
import { probeWebm } from "../webm-probe";
-import { adoptFile, readRef, scratchDir } from "../storage";
+import { adoptFile, contentTypeFor, readRef, saveFile, scratchDir } from "../storage";
import { CONNECT_GPU_MESSAGE } from "@/lib/guest-access";
import { discardBody, fetchPublic, RemoteFetchError } from "../remote-fetch";
import { zipToFile } from "../zip";
@@ -447,7 +447,7 @@ function forget(promptId: string) {
// Outputs
type HistoryFile = { filename: string; subfolder: string; type: string };
-type HistoryEntry = {
+export type HistoryEntry = {
prompt?: [number, string, ComfyWorkflow, ...unknown[]];
status?: { status_str?: string; completed?: boolean; messages?: [string, Record<string, unknown>][] };
outputs?: Record<string, Record<string, unknown>>;
@@ -1668,7 +1668,8 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
if (controls !== undefined && (typeof controls !== "string" || controls.length > 131_072)) delete extra[REVIEW_EXTRA.controls];
const own = !ownGpu() && !computerScope() && !tenantAccount();
if (reuse && own) Object.assign(values, { video: reuse.video, image: reuse.image, filenamePrefix: reuse.prefix });
- if (typeof values.video === "string" && typeof values.image === "string" && typeof values.filenamePrefix === "string") {
+ // Only the studio's own ComfyUI keeps a review (its previews are fetched from there; nothing else can be redone).
+ if (own && typeof values.video === "string" && typeof values.image === "string" && typeof values.filenamePrefix === "string") {
reviewInputs = { video: values.video, image: values.image, prefix: values.filenamePrefix };
}
}
@@ -1942,12 +1943,18 @@ async function followMetaBatch(prefix: string, manifest: ManifestWorkflow | unde
return null;
}
+/** A window preview H3 Relay writes (a 512 px clip or still): anything bigger isn't kept. */
+const WINDOW_PREVIEW_MAX_BYTES = 64 * 2 ** 20;
+
/**
* H3 Person Removal: H3 Relay's review of the run (each window's checkpoint, seed and preview) on the video it made, as
- * meta.review plus the previews as meta.artifacts (kept with the result), so the page shows every window and can redo
- * from one. Nothing when the Relay didn't report a run (an older pack) or the inputs can't be sent again.
+ * meta.review plus the previews as meta.artifacts. The previews are copied from ComfyUI here, with its token, into the
+ * generation's files (a local or LAN ComfyUI isn't fetched by link later, and raw ComfyUI links never reach a page). A
+ * preview that can't be copied is left out; the window can still be redone. Nothing when the Relay didn't report a run
+ * (an older pack), the inputs can't be sent again, or the run wasn't on the studio's own ComfyUI.
*/
-async function withRemovalReview(entry: HistoryEntry, outputs: ComfyOutput[], reuseMeta: unknown, worker: ComfyWorker): Promise<ComfyOutput[]> {
+export async function withRemovalReview(entry: HistoryEntry, outputs: ComfyOutput[], reuseMeta: unknown, worker: ComfyWorker, generationId: string): Promise<ComfyOutput[]> {
+ if (ownGpu() || computerScope() || tenantAccount()) return outputs;
const reuse = reuseOf(reuseMeta);
const runs = Object.values(entry.outputs ?? {}).flatMap((ui) => (Array.isArray(ui?.h3_removal_run) ? ui.h3_removal_run : []));
const runId = runs.find((r): r is string => typeof r === "string" && /^[0-9a-f]{32}$/.test(r));
@@ -1955,12 +1962,31 @@ async function withRemovalReview(entry: HistoryEntry, outputs: ComfyOutput[], re
if (!reuse || !runId || at < 0) return outputs;
try {
const run = await comfyJson<unknown>(`/h3_relay/removal/previews?${new URLSearchParams({ workflow_id: "", node_id: "review", run_id: runId })}`, worker);
- const base = baseUrl(worker);
- const read = reviewOfRun(run, reuse, (f) => `${base}/view?${new URLSearchParams(f)}`);
+ const read = reviewOfRun(run, reuse, (f) => `/view?${new URLSearchParams(f)}`);
if (!read) return outputs;
+ const kept: Record<string, string> = {};
+ for (const [key, view] of Object.entries(read.artifacts)) {
+ try {
+ const res = await comfyFetch(view, {}, worker);
+ const size = Number(res.headers.get("content-length") ?? 0);
+ if (!res.ok || size > WINDOW_PREVIEW_MAX_BYTES) {
+ discardBody(res);
+ continue;
+ }
+ const data = Buffer.from(await res.arrayBuffer());
+ if (!data.length || data.length > WINDOW_PREVIEW_MAX_BYTES) continue;
+ const name = new URLSearchParams(view.split("?")[1]).get("filename") ?? undefined;
+ const type = res.headers.get("content-type");
+ const contentType = type && type !== "application/octet-stream" ? type.split(";")[0] : contentTypeFor(name ?? "", "application/octet-stream");
+ kept[key] = saveFile({ data, contentType, name, source: "generation", generationId: generationId || undefined }).url;
+ } catch {
+ // this window shows no preview
+ }
+ }
+ const review = { ...read.review, windows: read.review.windows.map((w) => ({ ...w, video: w.video && kept[w.video] ? w.video : undefined, poster: w.poster && kept[w.poster] ? w.poster : undefined })) };
const o = outputs[at];
- const artifacts = { ...((o.meta?.artifacts as Record<string, string> | undefined) ?? {}), ...read.artifacts };
- return outputs.map((x, i) => (i === at ? { ...x, meta: { ...x.meta, review: read.review, artifacts } } : x));
+ const artifacts = { ...((o.meta?.artifacts as Record<string, string> | undefined) ?? {}), ...kept };
+ return outputs.map((x, i) => (i === at ? { ...x, meta: { ...x.meta, review, artifacts } } : x));
} catch {
return outputs;
}
@@ -2294,7 +2320,7 @@ export const comfyProvider: ProviderAdapter = {
}
const seed = typeof meta.seed === "number" ? meta.seed : undefined;
if (seed !== undefined) outputs = outputs.map((o) => (o.kind === "image" ? { ...o, meta: { ...o.meta, seed } } : o));
- if (manifest?.id === H3_REMOVAL_WORKFLOW) outputs = await withRemovalReview(entry, outputs, meta.reviewInputs, worker);
+ if (manifest?.id === H3_REMOVAL_WORKFLOW) outputs = await withRemovalReview(entry, outputs, meta.reviewInputs, worker, String(meta.generationId ?? String(meta.prefix ?? "").replace(/^fuobe\//, "")));
return { state: "succeeded" as const, outputs: await withLayerBoxes(outputs) };
};
const isDone = (e: HistoryEntry | undefined): e is HistoryEntry => !!e && (!!e.status?.completed || e.status?.status_str === "success" || e.status?.status_str === "error");
diff --git a/src/server/remove-object.ts b/src/server/remove-object.ts
index 8d5f04ff..52c406ae 100644
--- a/src/server/remove-object.ts
+++ b/src/server/remove-object.ts
@@ -383,6 +383,23 @@ function soundStepAfter(g: Generation): Generation | null {
return null;
}
+/** The step that cut the clip's original sound for a removal's mux (when the part isn't the whole clip). */
+function soundCutOf(mux: Generation): Generation | null {
+ const rows = db().prepare("SELECT id FROM generations WHERE batch_id IS ? AND op = 'trim' ORDER BY created_at").all(mux.batchId) as { id: string }[];
+ for (const r of rows) {
+ const g = getGeneration(r.id);
+ if (g && g.id !== mux.id && g.request.step?.label === "Original sound") return g;
+ }
+ return null;
+}
+
+/** A step's request as it was asked, without what belonged to that run only. */
+function askedAgain<T extends object>(request: T): T {
+ const req = { ...request } as T & Record<string, unknown>;
+ for (const k of ["asked", "chainFilled", "chainSkipped", "notice", "chain"]) delete req[k];
+ return req;
+}
+
/**
* Redo an H3 person removal from one window: the same graph sent to the same ComfyUI with H3 Relay's window controls,
* so the windows before it come back from their checkpoints exactly, the window is drawn with a new seed and the ones
@@ -403,10 +420,13 @@ export async function createRemovalReroll(body: RerollBody): Promise<{ final: Ge
if (!controls) throw new ShortsError("The windows before this one weren't saved — redo from the first window", 422);
// The step as it ran (its chained inputs filled in), without what belongs to that run only.
- const req = { ...erase.request } as typeof erase.request & Record<string, unknown>;
- for (const k of ["asked", "chainFilled", "chainSkipped", "notice", "chain"]) delete req[k];
+ const req = askedAgain(erase.request);
const masterSeed = Number(review.seed);
const mux = soundStepAfter(erase);
+ // The sound goes back as before: the mux's own audio, or (when that mux never started) the original sound cut again.
+ const audio = mux?.request.inputs?.audio;
+ const cut = mux && !audio ? soundCutOf(mux) : null;
+ if (mux && !audio && !cut) throw new ShortsError("This removal's sound wasn't ready — run the removal again", 409);
const was = (erase.request.batchTitle ?? erase.request.title ?? "Remove a person").replace(/ · from window \d+$/, "");
const title = `${was} · from window ${body.window + 1}`;
const steps: PlanStep[] = [
@@ -426,6 +446,7 @@ export async function createRemovalReroll(body: RerollBody): Promise<{ final: Ge
},
},
];
+ if (cut) steps.push({ key: "sound", request: { ...askedAgain(cut.request), batchTitle: title } });
if (mux) {
steps.push({
key: "final",
@@ -435,11 +456,11 @@ export async function createRemovalReroll(body: RerollBody): Promise<{ final: Ge
title,
modelId: mux.modelId,
op: "mux",
- ...(mux.request.inputs?.audio ? { inputs: { audio: mux.request.inputs.audio } } : {}),
+ ...(audio ? { inputs: { audio } } : {}),
step: { label: "Put the sound back", index: 1, of: 2 },
},
- after: ["erase0"],
- chain: [{ slot: "video" }],
+ after: cut ? ["erase0", "sound"] : ["erase0"],
+ chain: cut ? [{ slot: "video" }, { slot: "audio" }] : [{ slot: "video" }],
});
}
const p = run(steps);
diff --git a/tests/e2e/remove-person-flows.mjs b/tests/e2e/remove-person-flows.mjs
index 5ee63f1b..de37d971 100644
--- a/tests/e2e/remove-person-flows.mjs
+++ b/tests/e2e/remove-person-flows.mjs
@@ -66,12 +66,21 @@ try {
if (shots) await page.screenshot({ path: path.join(shots, "remove-person-open-1440.png"), fullPage: true });
await page.getByRole("button", { name: /Remove it/ }).click();
await page.getByRole("heading", { name: "Windows" }).waitFor({ timeout: 120_000 });
- const redo = page.getByRole("button", { name: "Redo from window 2" });
- check("each window with Redo from here", (await page.getByRole("button", { name: /Redo from window/ }).count()) === 3);
+ const redo = page.getByRole("button", { name: "Redo from here, window 2" });
+ check("each window with Redo from here", (await page.getByRole("button", { name: /^Redo from here, window/ }).count()) === 3);
await redo.click();
await page.getByText(/Redoing from window 2/).first().waitFor({ timeout: 30_000 });
check("Redo from here starts a new run", true);
if (shots) await page.screenshot({ path: path.join(shots, "remove-person-result-1440.png"), fullPage: true });
+ // After a reload the earlier removal's windows are still there to redo.
+ await page.reload({ waitUntil: "load" });
+ await page.getByRole("heading", { name: "Redo a window" }).waitFor({ timeout: 60_000 });
+ await page.locator("#earlier-windows ~ div details summary").first().click();
+ const again = page.getByRole("button", { name: "Redo from here, window 1" }).first();
+ await again.waitFor({ timeout: 30_000 });
+ await again.click();
+ await page.getByText(/Redoing from window 1/).first().waitFor({ timeout: 30_000 });
+ check("after a reload: an earlier removal's windows can be redone", true);
await context.close();
}
{
diff --git a/tests/person-remover-plus.test.ts b/tests/person-remover-plus.test.ts
index 1ca5ef27..9f4644fb 100644
--- a/tests/person-remover-plus.test.ts
+++ b/tests/person-remover-plus.test.ts
@@ -1,7 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
-import { afterAll, describe, expect, it } from "vitest";
+import { afterAll, describe, expect, it, vi } from "vitest";
import { getModel, getPreset } from "@/lib/catalog";
import { h3Canvas, H3_REMOVAL_WORKFLOW } from "@/lib/catalog/character-swap";
import { planGeneration } from "@/lib/catalog/plan";
@@ -30,8 +30,8 @@ import type { ManifestWorkflow } from "@/lib/comfy";
// H3 Person Remover, everywhere (o/person-remover-plus): mask first, window review and "Redo from here".
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-person-remover-plus-"));
process.env.FUOBE_DATA_DIR = tmp;
-process.env.COMFYUI_URL = "http://comfy.test:8188";
-const { prepareWorkflow } = await import("@/server/providers/comfyui");
+process.env.COMFYUI_URL = "http://127.0.0.1:8199";
+const { prepareWorkflow, withRemovalReview } = await import("@/server/providers/comfyui");
const { runAsTenant } = await import("@/server/tenant");
afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));
@@ -168,5 +168,51 @@ describe("Redo from here", () => {
// Never another run's files for an account's run.
const account = await runAsTenant({ kind: "account", id: "acc1" }, () => prep({ [REVIEW_EXTRA.reuse]: reuse }));
expect((account.workflow as Record<string, { inputs: Record<string, unknown> }>).source.inputs.file).toBe("new_fit.mp4");
+ // ...and an account's run keeps no review (nothing on its GPU is fetched for it, and it can't be redone).
+ expect(account.meta.reviewInputs).toBeUndefined();
+ });
+});
+
+describe("window previews from the studio's ComfyUI", () => {
+ it("are copied into the result's files from a local ComfyUI, with its token, never left as ComfyUI links", async () => {
+ const asked: { url: string; auth?: string }[] = [];
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ asked.push({ url, auth: (init?.headers as Record<string, string> | undefined)?.Authorization });
+ if (url.includes("/h3_relay/removal/previews")) return Response.json(run);
+ if (url.includes("window-002.mp4")) return new Response(Buffer.from("mp4-bytes"), { headers: { "content-type": "video/mp4" } });
+ if (url.includes("window-001.jpg")) return new Response(Buffer.from("jpg-bytes"), { headers: { "content-type": "image/jpeg" } });
+ return new Response("no", { status: 404 });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const { setSetting } = await import("@/server/settings");
+ setSetting("comfyToken", "tok-123");
+ try {
+ const entry = { outputs: { review: { h3_removal_run: [run.run_id] } } };
+ const outputs = [{ url: "http://127.0.0.1:8199/view?filename=out.mp4", kind: "video" as const, contentType: "video/mp4" }];
+ const [out] = await withRemovalReview(entry, outputs, reuse, "main", "gen1");
+ const meta = out.meta as { review: RemovalReview; artifacts: Record<string, string> };
+ expect(asked[0].url).toBe(`http://127.0.0.1:8199/h3_relay/removal/previews?workflow_id=&node_id=review&run_id=${run.run_id}`);
+ expect(asked.every((a) => a.auth === "Bearer tok-123")).toBe(true);
+ expect(Object.keys(meta.artifacts).sort()).toEqual(["window-001-poster", "window-002"]);
+ for (const link of Object.values(meta.artifacts)) expect(link).toMatch(/^\/api\/files\//);
+ expect(meta.review.windows.map((w) => [w.index, w.poster, w.video])).toEqual([
+ [0, "window-001-poster", undefined],
+ [1, undefined, "window-002"],
+ [2, undefined, undefined],
+ ]);
+ // An account's run (its own GPU, or the hosted pool): no review is read.
+ const n = asked.length;
+ const acc = await runAsTenant({ kind: "account", id: "acc1" }, () => withRemovalReview(entry, outputs, reuse, "main", "gen2"));
+ expect(acc[0].meta).toBeUndefined();
+ expect(asked.length).toBe(n);
+ // A preview ComfyUI won't give is left out; the window can still be redone.
+ fetchMock.mockImplementation(async (url: string) => (url.includes("/previews") ? Response.json(run) : new Response("no", { status: 403 })));
+ const [bare] = await withRemovalReview(entry, outputs, reuse, "main", "gen3");
+ expect((bare.meta as { artifacts: Record<string, string> }).artifacts).toEqual({});
+ expect((bare.meta as { review: RemovalReview }).review.windows.every((w) => !w.video && !w.poster && w.recordId)).toBe(true);
+ } finally {
+ setSetting("comfyToken", "");
+ vi.unstubAllGlobals();
+ }
});
});
diff --git a/tests/person-remover-reroll.test.ts b/tests/person-remover-reroll.test.ts
new file mode 100644
index 00000000..90144e27
--- /dev/null
+++ b/tests/person-remover-reroll.test.ts
@@ -0,0 +1,120 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+
+vi.setConfig({ testTimeout: 120_000 });
+
+// "Redo from here" end to end in demo mode: an H3 person removal runs through the mock provider (which reports three
+// windows), then POST /api/remove-object/reroll draws it again from one window and puts the sound back as before.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-person-reroll-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const { saveFile } = await import("@/server/storage");
+const { db } = await import("@/server/db");
+const createRoute = await import("@/app/api/remove-object/route");
+const rerollRoute = await import("@/app/api/remove-object/reroll/route");
+const { REMOVE, REVIEW_EXTRA } = await import("@/lib/catalog/remove-object");
+
+const json = (body?: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+
+let clip = "";
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "skate.mp4" }).url;
+});
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+async function settle(id: string, ms = 90_000): Promise<Generation> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 300));
+ }
+}
+
+const batchOf = (id: string) => {
+ const b = (db().prepare("SELECT batch_id FROM generations WHERE id = ?").get(id) as { batch_id: string }).batch_id;
+ return db().prepare("SELECT id, model_id, op FROM generations WHERE batch_id = ? ORDER BY created_at, id").all(b) as { id: string; model_id: string; op: string }[];
+};
+
+/** An H3 person removal of part of the clip (so its sound is cut from the clip and chained into the mux). */
+async function removal(): Promise<{ erase: Generation; mux: Generation; cut: Generation }> {
+ const res = await createRoute.POST(json({ engine: "open", mode: "type", modelId: "oss-h3-person-remove", prompt: "the skater", source: { url: clip, name: "skate.mp4" }, range: { start: 1, end: 7 } }));
+ expect(res.status).toBe(201);
+ const out = (await res.json()) as { final: Generation };
+ expect((await settle(out.final.id)).status).toBe("succeeded");
+ const rows = batchOf(out.final.id);
+ const erase = gens.getGeneration(rows.find((r) => r.model_id === "oss-h3-person-remove")!.id)!;
+ const cut = rows.map((r) => gens.getGeneration(r.id)!).find((g) => g.op === "trim" && g.request.step?.label === "Original sound")!;
+ return { erase, mux: gens.getGeneration(out.final.id)!, cut };
+}
+
+describe("Redo from here", () => {
+ let first: Generation | undefined;
+
+ it("sends the removal again with the window controls and the original inputs, then puts the sound back", async () => {
+ const { erase, mux } = await removal();
+ first = erase;
+ const review = erase.outputs.find((o) => o.kind === "video")?.meta?.review as { windows: unknown[]; reuse: unknown; seed: string };
+ expect(review.windows).toHaveLength(3);
+ const res = await rerollRoute.POST(json({ id: erase.id, window: 1, seed: 42, requestId: "reroll-req-0001" }));
+ expect(res.status).toBe(201);
+ const made = (await res.json()) as { final: Generation; items: Generation[] };
+ expect(made.items.map((g) => g.op)).toEqual(["remove-object", "mux"]);
+ const [again, final] = made.items;
+ expect(again).toMatchObject({ modelId: "oss-h3-person-remove", feature: REMOVE.stepFeature });
+ const extra = again.request.params?.extra as Record<string, unknown>;
+ expect(JSON.parse(String(extra[REVIEW_EXTRA.controls])).windows).toMatchObject({ "0": { locked: true }, "1": { seed: "42", locked: false } });
+ expect(extra[REVIEW_EXTRA.reuse]).toEqual(review.reuse);
+ expect(again.request.params?.seed).toBe(Number(review.seed));
+ expect(again.request.inputs?.video).toBe(erase.request.inputs?.video);
+ expect(final).toMatchObject({ op: "mux", feature: REMOVE.feature, modelId: mux.modelId });
+ expect(final.request.inputs?.audio).toBe(mux.request.inputs?.audio);
+ expect(final.request.title).toMatch(/ · from window 2$/);
+ // The same press twice is one redo.
+ const twice = (await (await rerollRoute.POST(json({ id: erase.id, window: 1, seed: 42, requestId: "reroll-req-0001" }))).json()) as { final: Generation };
+ expect(twice.final.id).toBe(made.final.id);
+ expect((await settle(made.final.id)).status).toBe("succeeded");
+ // A redo of a redo keeps one window in the title.
+ const redo = gens.getGeneration(again.id)!;
+ const third = (await (await rerollRoute.POST(json({ id: redo.id, window: 2 }))).json()) as { final: Generation };
+ expect(third.final.request.title).toMatch(/ · from window 3$/);
+ expect(third.final.request.title).not.toMatch(/window 2/);
+ });
+
+ it("cuts the sound again when the first mux never got it", async () => {
+ const { erase, mux, cut } = await removal();
+ const req = { ...mux.request, inputs: {} };
+ db().prepare("UPDATE generations SET request_json = ? WHERE id = ?").run(JSON.stringify(req), mux.id);
+ const res = await rerollRoute.POST(json({ id: erase.id, window: 0 }));
+ expect(res.status).toBe(201);
+ const made = (await res.json()) as { final: Generation; items: Generation[] };
+ expect(made.items.map((g) => g.op)).toEqual(["remove-object", "trim", "mux"]);
+ expect(made.items[1].request).toMatchObject({ modelId: cut.modelId, inputs: { video: cut.request.inputs?.video }, params: { startTime: cut.request.params?.startTime, endTime: cut.request.params?.endTime } });
+ const final = await settle(made.final.id);
+ expect(final.status).toBe("succeeded");
+ expect(final.request.inputs?.audio).toBeTruthy();
+ });
+
+ it("refuses what it can't redo", async () => {
+ const erase = first!;
+ const code = async (b: unknown) => (await rerollRoute.POST(json(b))).status;
+ expect(await code({ id: "nope", window: 0 })).toBe(404);
+ expect(await code({ id: erase.id, window: 3 })).toBe(422);
+ expect(await code({ id: erase.id })).toBe(400);
+ // Another step of the removal: not an H3 removal.
+ const fit = batchOf(erase.id).find((r) => r.model_id === "oss-fit-clip")!;
+ expect(await code({ id: fit.id, window: 0 })).toBe(422);
+ // Still running.
+ db().prepare("UPDATE generations SET status = 'running' WHERE id = ?").run(erase.id);
+ expect(await code({ id: erase.id, window: 0 })).toBe(409);
+ });
+});