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.

Merge origin/claude/fuobe-parity-4 into o/dbs-d9

Claudec4e6a9d4c91b
diff --cc src/lib/av/split.ts
index 32af3b51,2f70ae7f..9101e2f8
--- a/src/lib/av/split.ts
+++ b/src/lib/av/split.ts
@@@ -15,6 -15,6 +15,8 @@@ import { clock, type ToolPlan } from ".
export const SPLIT_FEATURE = "audio-split";
export const SPLIT_MODEL = "oss-dbs-separate";
++/** originals (o/dbs-d9): graph C's model (soundtrack-remix-dbs), the one Clean up dialogue runs on (src/lib/av/clean-dialogue.ts OPEN_MODEL): a split with levels. */
++export const REMIX_MODEL = "oss-dbs-remix";
/** Putting a mix back on its video: the open stream-copy mux, or fal's merge on the cloud. */
export const REMUX_FEATURE = "audio-split-remux";
export const REMUX_MODELS: Record<Engine, string> = {
@@@ -263,16 -209,14 +265,17 @@@ const STEP_LABEL: Record<DbsChannels, s
export function planSplit(i: SplitInput): SplitPlan {
if (i.engine === "cloud") throw new Error(CLOUD_SPLIT_PROBLEM);
if (!i.media) throw new Error(`Add the ${i.kind === "video" ? "video" : "audio"} to split`);
- const mode = dbsChannelsFor(i.stereo ? "each channel" : "mono", i.channels);
+ // A remix is one file: in mono it would lose a stereo source's image, so it splits every channel unless told otherwise.
+ const remix = i.remix;
+ const mode = dbsChannelsFor((i.stereo ?? !!remix) ? "each channel" : "mono", i.channels);
const name = i.name?.trim();
- const title = `Split · ${name || (i.kind === "video" ? "video soundtrack" : "soundtrack")}`;
- const extra: Record<string, unknown> = { channels: mode };
+ const title = `${remix ? `Mix (${remixWords(remix)})` : "Split"} · ${name || (i.kind === "video" ? "video soundtrack" : "soundtrack")}`;
- const extra: Record<string, unknown> = { channels: mode, ...(remix && { remix: true, ...remix }) };
++ // Graph C's levels are always all three, given (its own defaults keep the music and effects at -18 dB).
++ const extra: Record<string, unknown> = { channels: mode, ...(remix && { voiceDb: remix.voiceDb, musicDb: remix.musicDb, effectsDb: remix.effectsDb }) };
if (i.quality) extra.separationModel = DBS_MODELS[i.quality];
if (i.channels && i.channels > 0) extra.sourceChannels = Math.round(i.channels);
const request: GenerationRequest = {
-- modelId: SPLIT_MODEL,
++ modelId: remix ? REMIX_MODEL : SPLIT_MODEL,
op: "separate-audio",
feature: SPLIT_FEATURE,
batchTitle: title,
diff --cc src/server/assist/agent.ts
index 802ff69d,da95cf27..2ac4bfc3
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@@ -705,8 -705,7 +705,8 @@@ 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), fly_around (a still filmed along an exact camera path: an orbit by its degrees, direction, tilt and pulse, or a ready move; 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).
+- Soundtracks: split_soundtrack splits audio or a video's sound into dialogue, music and effects (all stems, one stem such as "just the music", or one remix at given levels), and remove_dialogue takes the talking out of a video, keeps only it, or lowers the music under it, with the picture untouched. Both run on the user's GPU (free); the cloud engine can't do them.
- 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 --cc src/server/assist/studio-tools.ts
index e5c700b0,b0f3e786..d1900d98
--- a/src/server/assist/studio-tools.ts
+++ b/src/server/assist/studio-tools.ts
@@@ -777,221 -819,70 +825,284 @@@ const blockoutFilm = defineTool(
},
});
- export const STUDIO_TOOLS = [splitLayers, restyleFootage, dubVideo, facelessEpisode, createAds, addCaptions, restoreVideo, blockoutFilm];
+ // ---------------------------------------------------------------------------
+ // Fly around (build plan N7-7): a still filmed along an exact camera path
+
+ export const FlyAroundToolInput = z.object({
+ image: ref.describe("The still to film: the clip's first frame (a character, a product, a scene)."),
+ views: z.array(ref).max(FLY_VIEWS_MAX).optional().describe("Cloud only: other pictures of the same subject from other sides; MiniMax H3 Max takes them as references (the path then goes in words)."),
+ preset: z
+ .enum(PATH_PRESETS.map((p) => p.id) as [string, ...string[]])
+ .optional()
+ .describe(`A ready move: ${PATH_PRESETS.map((p) => `${p.id} (${p.name})`).join(", ")}. Leave it out to give the orbit's numbers instead.`),
+ degrees: z.number().min(30).max(360).optional().describe("An exact orbit: how far round the subject, 30–360° (default 360)."),
+ direction: z.enum(["cw", "ccw"]).optional().describe("An exact orbit's direction seen from above: cw moves the camera round to the left, ccw to the right (default ccw)."),
+ tilt: z.number().min(0).max(20).optional().describe("An exact orbit's height tilt, 0–20°: the ring rises over the first half turn and dips below eye level over the second."),
+ pulse: z.boolean().optional().describe("An exact orbit moves 25% in and out twice on the way round."),
+ prompt: z.string().max(1500).optional().describe("Motion words: what the subject does while the camera moves (the camera's own move is set by the path)."),
+ duration: z.number().min(1).max(15).optional().describe("Cloud only: seconds (default 5). Your GPU always films about 5 s."),
+ });
+ export type FlyAroundToolInput = z.infer<typeof FlyAroundToolInput>;
+
+ /** The fly-around's steps as a pipeline in the Library (src/lib/catalog/fly-around.ts). */
+ function flyAroundSteps(i: FlyAroundToolInput, ctx: ToolContext): PipelineStep[] {
+ const engine = engineOf(ctx);
+ const exact = !i.preset || i.degrees !== undefined || i.direction !== undefined || i.tilt !== undefined || i.pulse !== undefined;
+ const plan = planFlyAround({
+ engine,
+ image: i.image,
+ views: i.views,
+ ...(exact ? { orbit: { degrees: i.degrees ?? 360, direction: i.direction ?? "ccw", tilt: i.tilt ?? 0, pulse: i.pulse ? 0.25 : 0 } } : { preset: i.preset }),
+ prompt: i.prompt,
+ duration: i.duration,
+ feature: "fly-around",
+ });
+ if (plan.blocker) throw new Error(plan.blocker);
+ return plan.steps.map((s) => ({ key: s.key, request: s.request, ...(s.after?.length && { after: s.after }) }));
+ }
+
+ const flyAround = defineTool({
+ name: "fly_around",
+ description:
+ "Film a still along an exact camera path: an orbit set by numbers (degrees, direction seen from above, a height tilt, a radius pulse) or a ready move (Orbit 360°, arcs, a tilted ring, a figure of eight, dollies, trucks) — Fuobe's Fly around. " +
+ "In the cloud MiniMax H3 Max camera controls follows the path as keyframes from the still (5 s at 768P is $0.40 at list price); with other views of the subject, MiniMax H3 Max takes them as references and the path goes in words. " +
+ "On your GPU MoGe 2 measures the still's depth, the studio renders the path through it, and Wan 2.1 with Uni3C films the still along that render: free, about 5 s, a large GPU (about 48 GB). Gated by the same approval card as generate.",
+ schema: FlyAroundToolInput,
+ gated: true,
+ title: (i) => (i.preset ? `Fly around: ${PATH_PRESETS.find((p) => p.id === i.preset)?.name ?? i.preset}` : `Fly around: ${i.degrees ?? 360}°`),
+ plan: (i, ctx) => {
+ try {
+ return planSteps("fly_around", flyAroundSteps(i, ctx));
+ } catch (e) {
+ return [{ tool: "fly_around", modelId: "fly-around", modelName: "Fly around", kind: "video", op: "camera-path", prompt: "Fly around", count: 0, costUsd: 0, demo: false, atomic: true, error: (e as Error).message }];
+ }
+ },
+ async run(i, ctx) {
+ let steps: PipelineStep[];
+ try {
+ steps = flyAroundSteps(i, ctx);
+ } catch (e) {
+ return { content: JSON.stringify({ error: (e as Error).message }), isError: true };
+ }
+ return startPipeline("Fly around", steps, "Fly around");
+ },
+ });
+
+ export const STUDIO_TOOLS = [splitLayers, restyleFootage, dubVideo, facelessEpisode, createAds, addCaptions, restoreVideo, removePerson, blockoutFilm, flyAround];
/** For tests: the fallback pipelines, as they would be created. */
- export const fallbackSteps = { restore: restoreSteps, layers: layerSteps, restyle: restyleSteps, dub: dubSteps, faceless: facelessSteps, captions: captionSteps, ads: adRequests, blockout: blockoutSteps };
+ export const fallbackSteps = { restore: restoreSteps, layers: layerSteps, restyle: restyleSteps, dub: dubSteps, faceless: facelessSteps, captions: captionSteps, ads: adRequests, blockout: blockoutSteps, flyAround: flyAroundSteps };
+
+// ---------------------------------------------------------------------------
+// originals (o/dbs-d9): Split soundtrack and Remove dialogue in one call (docs/research/dbs-separation-7.md §8 and §9 D9).
+// Both run the Audio hub's and Video tools' own plans (src/lib/av/split.ts, src/lib/av/remove-dialogue.ts through
+// src/server/audio-tools.ts), so a call reads the file's header, picks the stems and the mux exactly as the pages do, and
+// its results land in the Library. Open engine only: DBS is hosted nowhere, and SAM Audio in the cloud is the owner's call,
+// not taken (docs/handoff/owner-decisions.json samAudioCloud: false); the cloud engine refuses in words.
+
+const SoundtrackEngine = z
+ .enum(["open", "cloud"])
+ .optional()
+ .describe("Leave it out: it runs on the open engine (the user's GPU, free). 'cloud' is refused: DBS isn't hosted on fal or Replicate, and there is no cloud stand-in.");
+
+const SplitSoundtrackInput = z.object({
+ media: ref.describe("The audio file or the video whose soundtrack to split."),
+ keep: z
+ .array(z.enum(KEEP_STEMS as [KeepStem, ...KeepStem[]]))
+ .optional()
+ .describe(
+ "The stems to keep. Left out: all four stems come back (voice = dialogue, music, effects, background = music & effects). One stem (['music']): that stem alone. ['music','effects']: the background stem. Dialogue with music or with effects: one mixed file of those.",
+ ),
+ levels_db: z
+ .object({
+ dialogue: z.number().min(REMIX_MIN_DB).max(REMIX_MAX_DB).optional(),
+ music: z.number().min(REMIX_MIN_DB).max(REMIX_MAX_DB).optional(),
+ effects: z.number().min(REMIX_MIN_DB).max(REMIX_MAX_DB).optional(),
+ })
+ .optional()
+ .describe(`Mix the kept stems back into ONE file at these levels (whole dB, ${REMIX_MIN_DB} to +${REMIX_MAX_DB}; a kept stem with no level stays at 0 dB), e.g. { music: -12 } for the music 12 dB under the dialogue and effects.`),
+ quality: z.enum(["fast", "best"]).optional().describe("fast = DBS-BSRNN, best = DBS-TIGER (about 3x slower on a CPU). Left out: the GPU's pick (best on CUDA, fast on a CPU)."),
+ engine: SoundtrackEngine,
+});
+const RemoveDialogueInput = z.object({
+ video: ref.describe("The video to take the dialogue out of (it must have sound)."),
+ keep: z
+ .enum(["bed", "dialogue"])
+ .optional()
+ .describe("bed (default): the music and sound effects stay, the talking goes. dialogue: only the talking stays. With music_db: the talking stays and the music and effects go quieter under it."),
+ music_db: z.number().min(LOWER_MIN_DB).max(LOWER_MAX_DB).optional().describe(`Keep the dialogue and lower the music and effects to this level under it (dB, ${LOWER_MIN_DB} to 0; ${LOWER_DEFAULT_DB} is a good start).`),
+ quality: z.enum(["fast", "best"]).optional().describe("fast = DBS-BSRNN, best = DBS-TIGER. Left out: the GPU's pick."),
+ engine: SoundtrackEngine,
+});
+export type SplitSoundtrackToolInput = z.infer<typeof SplitSoundtrackInput>;
+export type RemoveDialogueToolInput = z.infer<typeof RemoveDialogueInput>;
+
+/** The engine a soundtrack tool runs on: the open engine unless asked otherwise (Engine mode wins). */
+const soundtrackEngine = (asked?: Engine): Engine => (engineMode() === "both" ? (asked ?? "open") : (engineMode() as Engine));
+
+/** audio / video from the file's name, or why the file can't be split. */
+function mediaKind(url: string): "audio" | "video" {
+ const rel = filesRel(url);
+ const kind = rel ? kindFor(contentTypeFor(rel)) : null;
+ if (kind === "audio" || kind === "video") return kind;
+ throw new Error("Pass an audio file or a video with sound (a file URL from the chat, /api/files/…)");
+}
+
+const levelOf = (l: SplitSoundtrackToolInput["levels_db"]) => l && { dialogue: l.dialogue, music: l.music, effects: l.effects };
+
+/** The Audio hub's Split soundtrack request for a call, and what it returns. Throws what's in the way. */
+export function splitSoundtrackBody(i: SplitSoundtrackToolInput): { body: AudioToolRequest; outcome: SplitOutcome } {
+ const outcome = splitOutcome(i.keep, levelOf(i.levels_db));
+ const kind = mediaKind(i.media);
+ const parsed = AudioToolBody.safeParse({
+ tool: "split",
+ engine: soundtrackEngine(i.engine),
+ media: i.media,
+ kind,
+ ...(i.quality && { quality: i.quality }),
+ ...(outcome.kind === "mix" && { remix: outcome.levels }),
+ });
+ if (!parsed.success) throw new Error("Pass a file URL from the chat (/api/files/…)");
+ return { body: parsed.data, outcome };
+}
+
+/** Video tools → Remove dialogue's request for a call. Throws what's in the way. */
+export function removeDialogueBody(i: RemoveDialogueToolInput): { body: AudioToolRequest; outcome: DialogueOutcome } {
+ if (i.keep === "bed" && i.music_db !== undefined) throw new Error("music_db lowers the music under the dialogue: leave keep out (or set it to 'dialogue') to use it");
+ if (mediaKind(i.video) !== "video") throw new Error("remove_dialogue takes a video: use split_soundtrack for an audio file");
+ const outcome: DialogueOutcome = i.music_db !== undefined ? "lower-music" : i.keep === "dialogue" ? "dialogue-only" : "no-dialogue";
+ const parsed = AudioToolBody.safeParse({
+ tool: "remove-dialogue",
+ engine: soundtrackEngine(i.engine),
+ video: i.video,
+ outcome,
+ ...(outcome === "lower-music" && { musicDb: Math.round(i.music_db!) }),
+ ...(i.quality && { quality: i.quality }),
+ });
+ if (!parsed.success) throw new Error("Pass a video URL from the chat (/api/files/…)");
+ return { body: parsed.data, outcome };
+}
+
+/**
+ * "about 1–2 min on your GPU" for the card, from the GPU's last known device. Before the device has been read the card
+ * leaves the time out (a CUDA card and a CPU differ about 80x) and asks the GPU in the background, so the next card has it.
+ */
+export function soundtrackTime(p: AudioToolPlan, body: AudioToolRequest): string | null {
+ const seconds = p.split?.duration;
+ if (!seconds || (body.tool !== "split" && body.tool !== "remove-dialogue")) return null;
+ const device = comfyDeviceSeen();
+ if (!device) {
+ void comfyDevice().catch(() => undefined);
+ return null;
+ }
+ const quality = body.quality ?? hostPick(device);
+ const mode = dbsChannelsFor(body.tool === "split" && (body.stereo ?? !!body.remix) ? "each channel" : "mono", p.split?.channels);
+ const t = (body.tool === "split" ? splitTime : removeDialogueTime)({ seconds, quality, mode, channels: p.split?.channels, device });
+ return `${durationWords(t)} ${device === "cpu" ? "on your computer" : "on your GPU"}`;
+}
+
+/** Price (and time) the call the way the page does; never throws: what's in the way is the card's error. */
+function planSoundtrack(tool: string, name: string, kind: "audio" | "video", build: () => { body: AudioToolRequest }): PlannedJob[] {
+ let body: AudioToolRequest;
+ let p: AudioToolPlan;
+ try {
+ body = build().body;
+ p = planAudioTool(body);
+ } catch (e) {
+ return [{ tool, modelId: SPLIT_MODEL, modelName: name, kind, op: "separate-audio", prompt: name, count: 0, costUsd: 0, demo: false, atomic: true, error: (e as Error).message }];
+ }
+ const jobs = planSteps(tool, p.steps.map((s) => ({ key: s.key, request: s.request, ...(s.after && { after: s.after }), ...(s.chain && { chain: s.chain }) })));
+ const time = jobs.some((j) => j.demo) ? null : soundtrackTime(p, body);
+ // The card's first line says what the whole call does (the steps' own labels are their notes).
+ if (jobs[0]) jobs[0] = { ...jobs[0], prompt: p.summary };
+ if (time && jobs[0] && !jobs[0].error) jobs[0] = { ...jobs[0], note: `${jobs[0].note ?? name} · ${time}` };
+ return jobs;
+}
+
+/** Start the call: the host's check first (a DBS model it doesn't have is refused before anything is queued), then one batch. */
+async function runSoundtrack(name: string, href: string, build: () => { body: AudioToolRequest; returns: string }): Promise<ToolOutcome> {
+ let body: AudioToolRequest;
+ let returns: string;
+ try {
+ ({ body, returns } = build());
+ } catch (e) {
+ return { content: JSON.stringify({ error: (e as Error).message }), isError: true };
+ }
+ try {
+ const preview = await previewAudioTool(body);
+ const run = await runAudioTool(body);
+ return {
+ content: JSON.stringify({
+ tool: name,
+ href,
+ engine: body.engine,
+ steps: run.items.map((g) => ({ step: g.request.step?.label, id: g.id })),
+ result: run.result.id,
+ returns,
+ costUsd: preview.costUsd,
+ ...(preview.estimate && !preview.demo && { takes: `${durationWords(preview.estimate)} on your GPU` }),
+ demo: preview.demo || undefined,
- note: "It runs in the background: check_generations on the result gives the output URLs (a split's audio outputs carry meta.stem: voice, music, effects or background; a mix is the one audio output).",
++ note: "It runs in the background: check_generations on the result gives the output URLs (a split's audio outputs carry meta.stem: voice, music, effects or background; a mix is the one audio output, tagged meta.stem voice whatever levels it has, with a short text report beside it).",
+ }),
+ items: [
+ { id: "", role: "tool", text: `${name}: started${preview.estimate && !preview.demo ? ` (${durationWords(preview.estimate)})` : ""}`, href },
+ { id: "", role: "generations", ids: [run.result.id] },
+ ],
+ };
+ } catch (e) {
+ return { content: JSON.stringify({ error: (e as Error).message }), isError: true };
+ }
+}
+
+const STEM_WORDS: Record<string, string> = { voice: "voice (the dialogue)", music: "music", effects: "effects", background: "background (music & effects)" };
+
+function splitReturns(o: SplitOutcome): string {
+ if (o.kind === "stems") return "four stems on the result: voice (the dialogue), music, effects, background (music & effects)";
+ if (o.kind === "stem") return `the ${STEM_WORDS[o.stem]} stem of the result (it holds all four stems; pick meta.stem ${o.stem})`;
- return `one mixed file: ${remixWords(o.levels)}`;
++ return `one mixed file: ${remixWords(o.levels)} (the result's audio output; it carries meta.stem voice whatever it holds, and a text report comes with it)`;
+}
+
+const splitSoundtrack = defineTool({
+ name: "split_soundtrack",
+ description:
+ "Split a soundtrack (an audio file or a video) into dialogue, music and effects with DBS — Fuobe's Split soundtrack (Audio → Split soundtrack): " +
+ "four stems (voice, music, effects, background = music & effects), one stem ('give me just the music': keep ['music']), or one file remixed at your levels (levels_db). " +
+ "Runs on the user's GPU (open source, free; a CPU works too, at about a quarter of real time); there is no hosted DBS, so the cloud engine refuses it. " +
+ "Dialogue separates cleanly; music and effects can bleed into each other. A mix that would clip is turned down as a whole. Gated by the same approval card as generate.",
+ schema: SplitSoundtrackInput,
+ gated: true,
+ title: (i) => (i.levels_db ? "Remix the soundtrack" : i.keep?.length === 1 ? `Split soundtrack: just the ${i.keep[0]}` : "Split soundtrack"),
+ place: () => ({ studio: "Split soundtrack", href: "/audio/split" }),
+ plan: (i) => planSoundtrack("split_soundtrack", "Split soundtrack", "audio", () => splitSoundtrackBody(i)),
+ run: (i) =>
+ runSoundtrack("Split soundtrack", "/audio/split", () => {
+ const b = splitSoundtrackBody(i);
+ return { body: b.body, returns: splitReturns(b.outcome) };
+ }),
+});
+
+const REMOVE_RETURNS: Record<DialogueOutcome, string> = {
+ "no-dialogue": "a new video with the music and effects only (the picture copied untouched); the dialogue it took out is a stem of the split step",
+ "dialogue-only": "a new video with the dialogue only (the picture copied untouched); the music & effects it took out are a stem of the split step",
+ "lower-music": "a new video with the dialogue over the lowered music and effects (the picture copied untouched)",
+};
+
+const removeDialogue = defineTool({
+ name: "remove_dialogue",
+ description:
+ "Take the dialogue out of a video, keep only the dialogue, or keep it with the music lowered (music_db) — Fuobe's Remove dialogue (Video tools → Remove dialogue): DBS splits the soundtrack, then the chosen sound goes back on the video with the picture copied untouched. " +
+ "Runs on the user's GPU (open source, free); there is no hosted DBS, so the cloud engine refuses it. Gated by the same approval card as generate.",
+ schema: RemoveDialogueInput,
+ gated: true,
+ title: (i) => (i.music_db !== undefined ? `Lower the music (${Math.round(i.music_db)} dB)` : i.keep === "dialogue" ? "Keep only the dialogue" : "Remove the dialogue"),
+ place: () => ({ studio: "Remove dialogue", href: "/video-tools/remove-dialogue" }),
+ plan: (i) => planSoundtrack("remove_dialogue", "Remove dialogue", "video", () => removeDialogueBody(i)),
+ run: (i) =>
+ runSoundtrack("Remove dialogue", "/video-tools/remove-dialogue", () => {
+ const b = removeDialogueBody(i);
+ return { body: b.body, returns: REMOVE_RETURNS[b.outcome] };
+ }),
+});
+
+/** originals (o/dbs-d9): Split soundtrack and Remove dialogue (registered after the studio tools in ./tools.ts). */
+export const SOUNDTRACK_TOOLS = [splitSoundtrack, removeDialogue];
diff --cc src/server/assist/tools.ts
index d06d31e1,97a7a983..86f8391c
--- a/src/server/assist/tools.ts
+++ b/src/server/assist/tools.ts
@@@ -99,7 -102,7 +104,7 @@@ const searchModels = defineTool(
.string()
.optional()
.describe(
- "Operation id to filter by, e.g. t2i, edit, t2v, i2v, flf2v, ref2v, extend, lipsync, avatar, tts, upscale-image, layers, text-layers, trim, transcribe, captions, mux, separate-audio, translate, write, image-to-3d. separate-audio models return audio stems (meta.stem): voice (the dialogue) and background (everything else); DBS also returns music and effects (background = music & effects). For a whole split or a remix in one call use split_soundtrack, for a video without its dialogue remove_dialogue.",
- "Operation id to filter by, e.g. t2i, edit, t2v, i2v, flf2v, ref2v, extend, lipsync, avatar, tts, upscale-image, layers, text-layers, trim, transcribe, captions, mux, separate-audio, translate, write, image-to-3d, refine-3d, splat.",
++ "Operation id to filter by, e.g. t2i, edit, t2v, i2v, flf2v, ref2v, extend, lipsync, avatar, tts, upscale-image, layers, text-layers, trim, transcribe, captions, mux, separate-audio, translate, write, image-to-3d, refine-3d, splat. separate-audio models return audio stems (meta.stem): voice (the dialogue) and background (everything else); DBS also returns music and effects (background = music & effects). For a whole split or a remix in one call use split_soundtrack, for a video without its dialogue remove_dialogue.",
),
query: z.string().optional().describe("Words to match in the model name, vendor or description, e.g. 'kling', 'cheap', 'photoreal'."),
}),
@@@ -266,8 -269,15 +271,15 @@@ const Job = z.object(
end_image: ref.optional().describe("End frame (first-and-last-frame video)."),
video: ref.optional().describe("Input video (extend, edit, lipsync, upscale, trim, captions, transcribe…)."),
audio: ref.optional().describe("Input audio (lipsync, avatar, transcribe, separate-audio, mux; for voice-change the recording to re-voice)."),
- background_audio: ref.optional().describe("Mux: a second track mixed under the audio — the background stem from separate-audio, or a music bed."),
+ background_audio: ref.optional().describe("Mux: a second track mixed under the audio — the background stem (music & effects) from separate-audio, DBS's music or effects stem alone, or a music bed."),
voice_audio: ref.optional().describe("A recording of the voice to speak with (voice-cloning text to speech) or to change into (voice-change)."),
+ model3d: ref
+ .optional()
+ .describe("A 3D model (.glb) to work on: rig-3d rigs it; refine-3d (oss-hi3d-refine, Hi3D 1.0, the user's GPU only) refines its geometry from the photo in images (the photo it was made from)."),
+ mesh_resolution: z
+ .union([z.literal(512), z.literal(1024), z.literal(1536)])
+ .optional()
+ .describe("refine-3d: Hi3D's detail, 512 (one pass), 1024 (two, the default) or 1536 (three). On an open image-to-3d model, setting it also refines the model after it is built. The result is geometry only."),
aspect_ratio: z.string().optional().describe("e.g. 16:9, 9:16, 1:1 — one the model lists."),
resolution: z.string().optional().describe("e.g. 1080p, 2K — one the model lists."),
duration: z.number().optional().describe("Seconds, for video and music — one the model lists."),
diff --cc src/server/audio-tools.ts
index 0d906876,31a0a055..e79c9369
--- a/src/server/audio-tools.ts
+++ b/src/server/audio-tools.ts
@@@ -1,8 -1,9 +1,9 @@@
import "server-only";
import { z } from "zod";
import { planJoin, planLoop, CROSSFADE_MAX, JOIN_MAX_CLIPS, LOOP_MAX_SECONDS, type AudioToolPreview, type ToolPlan } from "@/lib/av/audio-tools";
-import { CLOUD_ONLY_PROBLEM, DBS_MODELS, dbsChannelsFor, hostPick, missingDbs, planRemux, planSplit, splitTime } from "@/lib/av/split";
+import { CLOUD_ONLY_PROBLEM, DBS_MODELS, dbsChannelsFor, hostPick, missingDbs, planRemux, planSplit, REMIX_MAX_DB, splitTime } from "@/lib/av/split";
import { CLOUD_ONLY_REMOVE_PROBLEM, LOWER_MAX_DB, LOWER_MIN_DB, NO_SOUND_PROBLEM, planRemoveDialogue, removeDialogueTime } from "@/lib/av/remove-dialogue";
+ import { planCleanDialogue } from "@/lib/av/clean-dialogue";
import { CLOUD_ONLY_CLEAN_PROBLEM, missingReuse, NO_REUSE_PACK, planClean, planTime, tooLongProblem } from "@/lib/av/clean-voice";
import type { Engine, Generation } from "@/lib/catalog/types";
import { lastGpuDevice } from "./account-gpu";
@@@ -230,8 -249,8 +256,9 @@@ export async function previewAudioTool(
if (installed && !installed.includes(DBS_MODELS[quality])) throw new AudioToolError(missingDbs(DBS_MODELS[quality], installed));
const { duration: seconds, channels } = p.split ?? {};
Object.assign(out, { hostPick: pick, ...(device && { device }), ...(installed && { installed: installed.map((m) => (m === DBS_MODELS.best ? "best" : "fast")) }), ...(p.headerChannels && { channels: p.headerChannels }) });
- const mode = dbsChannelsFor(body.tool === "split" && (body.stereo ?? !!body.remix) ? "each channel" : "mono", channels);
- if (seconds) out.estimate = (body.tool === "split" ? splitTime : removeDialogueTime)({ seconds, quality, mode, channels, device });
- const mode = dbsChannelsFor((body.tool === "split" || body.tool === "clean-dialogue") && body.stereo ? "each channel" : "mono", channels);
++ const stereo = body.tool === "split" ? (body.stereo ?? !!body.remix) : body.tool === "clean-dialogue" && body.stereo;
++ const mode = dbsChannelsFor(stereo ? "each channel" : "mono", channels);
+ if (seconds) out.estimate = (body.tool === "remove-dialogue" ? removeDialogueTime : splitTime)({ seconds, quality, mode, channels, device });
}
if (body.tool === "clean") {
// As Split: the host's device and its RE-USE files (and DBS's, to keep music & effects), asked live for the owner;
diff --cc tests/assist-soundtrack-tools.test.ts
index 35a0d1fe,00000000..69b27966
mode 100644,000000..100644
--- a/tests/assist-soundtrack-tools.test.ts
+++ b/tests/assist-soundtrack-tools.test.ts
@@@ -1,359 -1,0 +1,373 @@@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import type { Engine, Generation, GenInput } from "@/lib/catalog/types";
+
+// DBS D9 (docs/research/dbs-separation-7.md §8 and §9 D9): Assist's and MCP's split_soundtrack and remove_dialogue. What
- // a call returns (stems, one stem, one remix), graph C (soundtrack-remix-dbs) as the remix's variant, the open engine
++// a call returns (stems, one stem, one remix), graph C (soundtrack-remix-dbs, Clean up dialogue's oss-dbs-remix) for a remix, the open engine
+// only (the cloud refuses: samAudioCloud is false), price first (estimate_job), and the offline planner's suggestions.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-soundtrack-tools-"));
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing listens: the open models run on the demo provider.
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { getSetting, setSetting } = await import("@/server/settings");
+const { saveFile } = await import("@/server/storage");
+const tools = await import("@/server/assist/tools");
+const studio = await import("@/server/assist/studio-tools");
+const agent = await import("@/server/assist/agent");
+const { handleMcp } = await import("@/server/mcp");
+const gens = await import("@/server/generations");
+const { prepareWorkflow } = await import("@/server/providers/comfyui");
+const { resolveWorkflowId } = await import("@/lib/comfy-variants");
+const split = await import("@/lib/av/split");
++const { getModel } = await import("@/lib/catalog");
+const { CLOUD_ONLY_REMOVE_PROBLEM, CLOUD_REMOVE_PROBLEM } = await import("@/lib/av/remove-dialogue");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const plan = (name: string, input: unknown, engine: Engine = "cloud") => tools.planFor(name, input, { engine });
+const run = (name: string, input: unknown, engine: Engine = "cloud") => tools.executeTool(name, input, { engine });
+const rpc = (method: string, params?: unknown) => handleMcp({ jsonrpc: "2.0", id: 1, method, params });
+
+/** A two-second 16-bit stereo WAV. */
+function wav(name = "film.wav"): string {
+ const rate = 8000;
+ const n = rate * 2;
+ const buf = Buffer.alloc(44 + n * 4);
+ buf.write("RIFF", 0);
+ buf.writeUInt32LE(36 + n * 4, 4);
+ buf.write("WAVEfmt ", 8);
+ buf.writeUInt32LE(16, 16);
+ buf.writeUInt16LE(1, 20);
+ buf.writeUInt16LE(2, 22);
+ buf.writeUInt32LE(rate, 24);
+ buf.writeUInt32LE(rate * 4, 28);
+ buf.writeUInt16LE(4, 32);
+ buf.writeUInt16LE(16, 34);
+ buf.write("data", 36);
+ buf.writeUInt32LE(n * 4, 40);
+ return saveFile({ data: buf, contentType: "audio/wav", name, source: "upload" }).url;
+}
+
+/** A small MP4 with a video track and (unless null) a stereo AAC track, 2 s each. */
+function mp4(channels: number | null = 2, name = "interview.mp4"): string {
+ const u32 = (...v: number[]) => Buffer.concat(v.map((x) => Buffer.from([x >>> 24, (x >>> 16) & 255, (x >>> 8) & 255, x & 255])));
+ const box = (type: string, ...parts: Buffer[]) => {
+ const body = Buffer.concat(parts);
+ return Buffer.concat([u32(8 + body.length), Buffer.from(type), body]);
+ };
+ const trak = (handler: string, ...stbl: Buffer[]) =>
+ box("trak", box("mdia", box("mdhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(4)), box("hdlr", u32(0, 0), Buffer.from(handler), Buffer.alloc(12)), box("minf", box("stbl", ...stbl))));
+ const entry = Buffer.alloc(28);
+ entry.writeUInt16BE(1, 6);
+ entry.writeUInt16BE(channels ?? 2, 16);
+ entry.writeUInt16BE(16, 18);
+ const sound = channels === null ? [] : [trak("soun", box("stsd", u32(0, 1), box("mp4a", entry)))];
+ const data = Buffer.concat([box("ftyp", Buffer.from("isom"), u32(0)), box("moov", box("mvhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(80)), trak("vide", box("stts", u32(0, 1, 50, 40))), ...sound)]);
+ return saveFile({ data, contentType: "video/mp4", name, source: "upload" }).url;
+}
+
+async function finished(id: string): Promise<Generation> {
+ const deadline = Date.now() + 15_000;
+ let g = gens.getGeneration(id)!;
+ while (g.status !== "succeeded" && g.status !== "failed" && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 200));
+ g = gens.getGeneration(id)!;
+ }
+ return g;
+}
+
+describe("what split_soundtrack returns (splitOutcome)", () => {
+ it("all four stems, one stem, music & effects as the background stem, or a mix", () => {
+ expect(split.splitOutcome()).toEqual({ kind: "stems" });
+ expect(split.splitOutcome(["dialogue", "music", "effects"])).toEqual({ kind: "stems" });
+ expect(split.splitOutcome(["music"])).toEqual({ kind: "stem", stem: "music" });
+ expect(split.splitOutcome(["dialogue"])).toEqual({ kind: "stem", stem: "voice" });
+ expect(split.splitOutcome(["effects", "music"])).toEqual({ kind: "stem", stem: "background" });
+ // Dialogue with one of the others isn't one stem: one mix, the rest left out.
+ expect(split.splitOutcome(["dialogue", "effects"])).toEqual({ kind: "mix", levels: { voiceDb: 0, musicDb: split.REMIX_OUT_DB, effectsDb: 0 } });
+ });
+
+ it("levels make one mix: whole dB, clamped, a stem not kept left out", () => {
+ expect(split.splitOutcome(undefined, { music: -12.4 })).toEqual({ kind: "mix", levels: { voiceDb: 0, musicDb: -12, effectsDb: 0 } });
+ expect(split.splitOutcome(["dialogue", "music"], { dialogue: 40, music: -90, effects: 3 })).toEqual({
+ kind: "mix",
+ levels: { voiceDb: split.REMIX_MAX_DB, musicDb: split.REMIX_MIN_DB, effectsDb: split.REMIX_OUT_DB },
+ });
+ // A level only for a stem that isn't kept changes nothing: the music stem.
+ expect(split.splitOutcome(["music"], { dialogue: -6 })).toEqual({ kind: "stem", stem: "music" });
+ expect(() => split.splitOutcome([])).toThrow("Keep at least one of dialogue, music or effects");
+ expect(split.remixWords({ voiceDb: 0, musicDb: -12, effectsDb: split.REMIX_OUT_DB })).toBe("Dialogue + Music −12 dB");
+ });
+
+ it("a remix plan: one job with the levels, every channel of a stereo source", () => {
+ const p = split.planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", channels: 2, seconds: 10, remix: { voiceDb: 0, musicDb: -12, effectsDb: -100 } });
+ expect(p.mode).toBe("each channel");
- expect(p.steps[0].request.params?.extra).toMatchObject({ remix: true, voiceDb: 0, musicDb: -12, effectsDb: -100, channels: "each channel" });
++ // Graph C's model (Clean up dialogue's), with all three levels given (the graph's own defaults are -18 dB under the dialogue).
++ expect(p.steps[0].request.modelId).toBe("oss-dbs-remix");
++ expect(p.steps[0].request.params?.extra).toEqual({ voiceDb: 0, musicDb: -12, effectsDb: -100, channels: "each channel", sourceChannels: 2 });
+ expect(p.steps[0].request.title).toBe("Mix (Dialogue + Music −12 dB) · soundtrack");
+ // A mono source stays one pass; asked for mono, a stereo one too.
+ expect(split.planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", channels: 1, remix: { voiceDb: 0, musicDb: 0, effectsDb: 0 } }).mode).toBe("mono");
+ expect(split.planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", channels: 2, stereo: false, remix: { voiceDb: 0, musicDb: 0, effectsDb: 0 } }).mode).toBe("mono");
+ // Without levels: as the Audio hub's plan (mono, four stems).
- expect(split.planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", channels: 2 }).steps[0].request.params?.extra).toEqual({ channels: "mono", sourceChannels: 2 });
++ const plain = split.planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", channels: 2 }).steps[0].request;
++ expect(plain.params?.extra).toEqual({ channels: "mono", sourceChannels: 2 });
++ expect(plain.modelId).toBe(split.SPLIT_MODEL);
+ });
+});
+
+describe("graph C runs for a remix (soundtrack-remix-dbs)", () => {
+ const has = () => true;
+ const req = (extra: Record<string, unknown>) => ({ op: "separate-audio", clips: 0, images: 0, audio2: false, extra, has });
+
- it("is separate-soundtrack-dbs's variant for params.extra.remix", () => {
- expect(resolveWorkflowId("separate-soundtrack-dbs", req({ remix: true }))).toBe("soundtrack-remix-dbs");
- expect(resolveWorkflowId("separate-soundtrack-dbs", req({}))).toBe("separate-soundtrack-dbs");
- expect(resolveWorkflowId("separate-soundtrack-dbs", { ...req({ remix: true }), has: () => false })).toBe("separate-soundtrack-dbs");
++ it("runs on graph C's own model (oss-dbs-remix), not as a variant of the four-stem split", () => {
++ expect(getModel("oss-dbs-remix")?.routes.find((r) => r.provider === "comfyui")?.endpoint).toBe("soundtrack-remix-dbs");
++ expect(resolveWorkflowId("separate-soundtrack-dbs", req({ voiceDb: 0, musicDb: -12, effectsDb: -100 }))).toBe("separate-soundtrack-dbs");
+ });
+
+ it("binds the levels to Adjust Audio Volume and the DBS rules to the loader and the split", async () => {
- const input: GenInput = { seed: 1, audio: "film.wav", extra: { remix: true, voiceDb: -6, musicDb: -100, effectsDb: 3, channels: "each channel", separationModel: "DBS-TIGER-DnR" } };
++ const input: GenInput = { seed: 1, audio: "film.wav", extra: { voiceDb: -6, musicDb: -100, effectsDb: 3, channels: "each channel", separationModel: "DBS-TIGER-DnR" } };
+ const { workflow } = await prepareWorkflow("soundtrack-remix-dbs", input, {
+ generationId: "gen1",
+ op: "separate-audio",
+ upload: async (_d: unknown, _t: unknown, name: string) => `up_${name}`,
+ media: () => ({ container: "wav", channels: 2 }),
+ device: async () => "cpu",
+ dbsModels: async () => undefined,
+ } as never);
+ expect(workflow["1"].inputs.audio).toBe("film.wav");
+ expect(workflow["2"].inputs.model).toBe("DBS-TIGER-DnR");
+ expect(workflow["3"].inputs.channels).toBe("each channel");
+ expect([workflow["4"].inputs.volume, workflow["5"].inputs.volume, workflow["6"].inputs.volume]).toEqual([-6, -100, 3]);
- expect(workflow["9"]).toMatchObject({ class_type: "SaveAudioAdvanced", inputs: { format: "flac" } });
++ expect(workflow["9"]).toMatchObject({ class_type: "SaveAudioAdvanced", inputs: { format: "flac", filename_prefix: "fuobe/gen1" } });
++ expect(workflow["10"]).toMatchObject({ class_type: "PreviewAny" });
+ });
+
+ it("is in the manifest, validated, with its pack and the four DBS files on the GPU pre-flight's index", () => {
+ const manifest = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/manifest.json"), "utf8"));
+ const w = manifest.workflows.find((x: { id: string }) => x.id === "soundtrack-remix-dbs");
- expect(w).toMatchObject({ capability: "separate-audio", validated: true, outputs: [{ node: "9", kind: "audio" }] });
++ expect(w).toMatchObject({ capability: "separate-audio", validated: true, outputs: [
++ { node: "9", kind: "audio", stem: "voice" },
++ { node: "10", kind: "text", role: "report" },
++ ],
++ });
++ expect(w.defaults).toMatchObject({ voiceDb: 0, musicDb: -18, effectsDb: -18 });
+ const reqs = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/requirements.json"), "utf8"));
+ const r = reqs.workflows?.["soundtrack-remix-dbs"] ?? reqs["soundtrack-remix-dbs"];
+ expect(r.packs).toEqual({ "ComfyUI-DBS": ["DBSLoader", "DBSSeparate"] });
+ expect(r.files).toHaveLength(4);
+ });
+});
+
+describe("split_soundtrack and remove_dialogue as tools", () => {
+ it("are gated studio tools, listed for Assist and over MCP, priced by estimate_job", async () => {
+ for (const name of ["split_soundtrack", "remove_dialogue"]) {
+ const t = tools.getTool(name)!;
+ expect(t.gated).toBe(true);
+ expect(t.description).toMatch(/there is no hosted DBS, so the cloud engine refuses it/);
+ }
+ const list = (await rpc("tools/list")) as { result: { tools: { name: string; inputSchema: { properties?: Record<string, unknown>; enum?: string[] } }[] } };
+ const names = list.result.tools.map((t) => t.name);
+ expect(names).toEqual(expect.arrayContaining(["split_soundtrack", "remove_dialogue", "estimate_job"]));
+ const est = list.result.tools.find((t) => t.name === "estimate_job")!;
+ expect((est.inputSchema.properties!.tool as { enum: string[] }).enum).toEqual(expect.arrayContaining(["split_soundtrack", "remove_dialogue"]));
+ const init = (await rpc("initialize", { protocolVersion: "2025-11-25" })) as { result: { instructions: string; serverInfo: { version: string } } };
+ expect(init.result.serverInfo.version).toBe("1.4.0");
+ expect(init.result.instructions).toMatch(/split_soundtrack/);
+ expect(init.result.instructions).toMatch(/remove_dialogue/);
+ });
+
+ it("validates its arguments: levels in range, keep from the three stems, music_db 0 to −30", () => {
+ expect(plan("split_soundtrack", { media: "/api/files/x.wav", keep: ["voice"] }).error).toBeTruthy();
+ expect(plan("split_soundtrack", { media: "/api/files/x.wav", levels_db: { music: -80 } }).error).toBeTruthy();
+ expect(plan("remove_dialogue", { video: "/api/files/x.mp4", music_db: -40 }).error).toBeTruthy();
+ expect(plan("remove_dialogue", { video: "/api/files/x.mp4", keep: "music" }).error).toBeTruthy();
+ });
+
+ it("prices a split first: free on the open engine (demo here), one step, the studio's page", () => {
+ const media = wav("song.wav");
+ // The chat's engine is the cloud: the tool still runs on the open engine unless asked otherwise.
+ const p = plan("split_soundtrack", { media, keep: ["music"] });
+ expect(p.error).toBeUndefined();
+ expect(p.jobs).toHaveLength(1);
+ expect(p.jobs[0]).toMatchObject({ tool: "split_soundtrack", modelId: "oss-dbs-separate", op: "separate-audio", costUsd: 0, demo: true, atomic: true });
+ expect(p.jobs[0].error).toBeUndefined();
+ expect(p.total).toBe(0);
+ expect(p).toMatchObject({ studio: "Split soundtrack", href: "/audio/split" });
+ });
+
+ it("leaves the card's time out until the GPU's device is known, and says where it runs", async () => {
+ const { planAudioTool } = await import("@/server/audio-tools");
+ const body = studio.splitSoundtrackBody({ media: wav("time.wav") }).body;
+ const time = () => studio.soundtrackTime(planAudioTool(body), body);
+ const cache = (globalThis.__fuobeComfyDevice ??= new Map());
+ const url = getSetting("comfyUrl").replace(/\/+$/, "");
+ const before = cache.get(url);
+ try {
+ cache.delete(url);
+ expect(time()).toBeNull();
+ cache.set(url, { type: "cpu", at: Date.now() });
+ expect(time()).toMatch(/ on your computer$/);
+ cache.set(url, { type: "cuda", at: Date.now() });
+ expect(time()).toMatch(/ on your GPU$/);
+ } finally {
+ if (before) cache.set(url, before);
+ else cache.delete(url);
+ }
+ });
+
+ it("prices Remove dialogue as the page's two steps (the split, then the stream-copy mux)", () => {
+ const video = mp4();
+ const p = plan("remove_dialogue", { video, music_db: -18 });
+ expect(p.jobs.map((j) => [j.modelId, j.op, j.costUsd, !!j.error])).toEqual([
+ ["oss-dbs-separate", "separate-audio", 0, false],
+ ["oss-mux", "mux", 0, false],
+ ]);
+ expect(p).toMatchObject({ studio: "Remove dialogue", href: "/video-tools/remove-dialogue" });
+ });
+
+ it("refuses the cloud engine and a paid-APIs-only install in words, before anything is queued", async () => {
+ const media = wav("cloud.wav");
+ const video = mp4(2, "cloud.mp4");
+ expect(plan("split_soundtrack", { media, engine: "cloud" }).jobs[0].error).toBe(split.CLOUD_SPLIT_PROBLEM);
+ expect(plan("remove_dialogue", { video, engine: "cloud" }).jobs[0].error).toBe(CLOUD_REMOVE_PROBLEM);
+ const before = gens.listGenerations({ limit: 500 }).length;
+ const out = await run("split_soundtrack", { media, engine: "cloud" });
+ expect(out.isError).toBe(true);
+ expect(JSON.parse(out.content as string).error).toBe(split.CLOUD_SPLIT_PROBLEM);
+ setSetting("engineMode", "cloud");
+ try {
+ expect(plan("split_soundtrack", { media }).jobs[0].error).toBe(split.CLOUD_ONLY_PROBLEM);
+ expect(plan("remove_dialogue", { video }).jobs[0].error).toBe(CLOUD_ONLY_REMOVE_PROBLEM);
+ expect((await run("remove_dialogue", { video })).isError).toBe(true);
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ expect(gens.listGenerations({ limit: 500 }).length).toBe(before);
+ });
+
+ it("refuses what the pages refuse: a silent video, an image, keep 'bed' with music_db, a file that is gone", () => {
+ expect(plan("remove_dialogue", { video: mp4(null, "silent.mp4") }).jobs[0].error).toBe("This clip has no sound");
+ expect(plan("split_soundtrack", { media: "/api/files/uploads/still.png" }).jobs[0].error).toMatch(/Pass an audio file or a video/);
+ expect(plan("remove_dialogue", { video: wav("speech.wav") }).jobs[0].error).toMatch(/use split_soundtrack for an audio file/);
+ expect(plan("remove_dialogue", { video: mp4(2, "bed.mp4"), keep: "bed", music_db: -12 }).jobs[0].error).toMatch(/music_db lowers the music/);
+ expect(plan("split_soundtrack", { media: "/api/files/uploads/gone.wav" }).jobs[0].error).toBe("That audio file is gone — add it again");
+ expect(plan("split_soundtrack", { media: wav("none.wav"), keep: [] }).jobs[0].error).toBe("Keep at least one of dialogue, music or effects");
+ });
+
+ it("runs a split into the Library and says which stem to pick", async () => {
+ const out = await run("split_soundtrack", { media: wav("run.wav"), keep: ["music"] });
+ expect(out.isError).toBeFalsy();
+ const body = JSON.parse(out.content as string);
+ expect(body).toMatchObject({ tool: "Split soundtrack", href: "/audio/split", engine: "open", costUsd: 0, demo: true });
+ expect(body.returns).toMatch(/music stem/);
+ expect(out.items).toEqual([expect.objectContaining({ role: "tool", href: "/audio/split" }), { id: "", role: "generations", ids: [body.result] }]);
+ const g = await finished(body.result);
+ expect(g.status).toBe("succeeded");
+ expect(g.outputs.map((o) => o.meta?.stem)).toEqual(["voice", "music", "effects", "background"]);
+ }, 30_000);
+
+ it("runs a remix as one mixed file (graph C)", async () => {
+ const out = await run("split_soundtrack", { media: wav("remix.wav"), levels_db: { music: -12 }, keep: ["dialogue", "music"] });
+ const body = JSON.parse(out.content as string);
- expect(body.returns).toBe("one mixed file: Dialogue + Music −12 dB");
++ expect(body.returns).toMatch(/^one mixed file: Dialogue \+ Music −12 dB /);
++ expect(body.returns).toMatch(/meta\.stem voice/);
+ const g = await finished(body.result);
- expect(g.request.params?.extra).toMatchObject({ remix: true, voiceDb: 0, musicDb: -12, effectsDb: -100 });
- expect(g.outputs).toHaveLength(1);
- expect(g.outputs[0]).toMatchObject({ kind: "audio" });
- expect(g.outputs[0].meta?.stem).toBeUndefined();
++ expect(g.modelId).toBe("oss-dbs-remix");
++ expect(g.request.params?.extra).toMatchObject({ voiceDb: 0, musicDb: -12, effectsDb: -100 });
++ expect(g.request.params?.extra).not.toHaveProperty("remix");
++ // Graph C tags its one audio output as the voice stem, whatever the levels.
++ const audio = g.outputs.filter((o) => o.kind === "audio");
++ expect(audio).toHaveLength(1);
++ expect(audio[0].meta?.stem).toBe("voice");
+ }, 30_000);
+
+ it("runs Remove dialogue as the page does: the split, then the mux with the background stem", async () => {
+ const out = await run("remove_dialogue", { video: mp4(2, "run.mp4") });
+ const body = JSON.parse(out.content as string);
+ expect(body.steps).toHaveLength(2);
+ expect(body.returns).toMatch(/music and effects only/);
+ const g = await finished(body.result);
+ expect(g).toMatchObject({ modelId: "oss-mux", op: "mux", status: "succeeded" });
+ expect(g.request.chain).toEqual([{ slot: "audio", stem: "background" }]);
+ }, 30_000);
+
+ it("builds the pages' own requests (the exported builders)", () => {
+ const v = mp4(2, "b.mp4");
+ expect(studio.removeDialogueBody({ video: v, keep: "dialogue" }).body).toMatchObject({ tool: "remove-dialogue", engine: "open", outcome: "dialogue-only" });
+ expect(studio.removeDialogueBody({ video: v, music_db: -9.6 }).body).toMatchObject({ outcome: "lower-music", musicDb: -10 });
+ expect(studio.splitSoundtrackBody({ media: v, quality: "best" }).body).toMatchObject({ tool: "split", kind: "video", quality: "best" });
+ });
+});
+
+describe("the offline planner", () => {
+ const attached = (kind: string, url: string) => `\n\nAttached files (use these URLs):\n- ${kind} 1: ${url}`;
+
+ it("'Remove the dialogue from this video' with a video attached: remove_dialogue", () => {
+ const v = "/api/files/uploads/clip.mp4";
+ expect(agent.offlinePlan(`Remove the dialogue from this video${attached("video", v)}`, "cloud")).toMatchObject({ tool: "remove_dialogue", input: { video: v } });
+ expect(agent.offlinePlan(`keep just the dialogue${attached("video", v)}`, "open")).toMatchObject({ tool: "remove_dialogue", input: { video: v, keep: "dialogue" } });
+ expect(agent.offlinePlan(`lower the music under the talking by 18 dB${attached("video", v)}`, "open")).toMatchObject({ tool: "remove_dialogue", input: { video: v, music_db: -18 } });
+ });
+
+ it("'just the music' with a file attached: split_soundtrack", () => {
+ const a = "/api/files/uploads/song.wav";
+ expect(agent.offlinePlan(`give me just the music${attached("audio", a)}`, "open")).toMatchObject({ tool: "split_soundtrack", input: { media: a, keep: ["music"] } });
+ expect(agent.offlinePlan(`remove the vocals${attached("audio", a)}`, "open")).toMatchObject({ tool: "split_soundtrack", input: { media: a, keep: ["music", "effects"] } });
+ expect(agent.offlinePlan(`split the soundtrack into stems${attached("video", "/api/files/v.mp4")}`, "open")).toMatchObject({ tool: "split_soundtrack", input: { media: "/api/files/v.mp4" } });
+ });
+
+ it("asks for the file when none is attached, and leaves new pieces alone", () => {
+ expect(agent.offlineSoundtrack("Remove the dialogue from this video")).toEqual({ say: expect.stringMatching(/Attach the video/) });
+ expect(agent.offlineSoundtrack("write a song with no vocals")).toBeNull();
+ expect(agent.offlineSoundtrack("a cinematic video of a lighthouse, no dialogue")).toBeNull();
+ expect(agent.offlinePlan("a cinematic video of a lighthouse, no dialogue", "cloud")?.tool).toBe("generate");
+ expect(agent.offlineSoundtrack("a red fox in the snow")).toBeNull();
+ });
+
+ it("leaves other jobs that mention the voice, the music or vocals to their own plans", () => {
+ const v = attached("video", "/api/files/uploads/clip.mp4");
+ const a = attached("audio", "/api/files/uploads/take.wav");
+ const others = [
+ `Remove the background noise from my voice${a}`,
+ `Translate this video to French and keep the voice${v}`,
+ `Dub this video into Spanish but keep the music${v}`,
+ `Extend this video and keep the music${v}`,
+ `Upscale this video, no voice changes${v}`,
+ `Add captions to this video, keep the voice${v}`,
+ `Lip sync this video to the audio, keep the voice${v}`,
+ `Make a music video for this song with no vocals${a}`,
+ `Write a song like this, no vocals${a}`,
+ `Generate a video with this audio, no talking${a}`,
+ `Keep the voice and make it 9:16${v}`,
+ ];
+ for (const m of others) {
+ expect(agent.offlineSoundtrack(m), m).toBeNull();
+ expect(["split_soundtrack", "remove_dialogue"], m).not.toContain(agent.offlinePlan(m, "open")?.tool);
+ }
+ // "keep only …" , "make it just the music" and "turn down the music" are still soundtrack requests.
+ expect(agent.offlinePlan(`keep only the music${a}`, "open")).toMatchObject({ tool: "split_soundtrack", input: { keep: ["music"] } });
+ expect(agent.offlinePlan(`make it just the music${a}`, "open")).toMatchObject({ tool: "split_soundtrack", input: { keep: ["music"] } });
+ expect(agent.offlinePlan(`turn down the music under the dialogue${v}`, "open")).toMatchObject({ tool: "remove_dialogue", input: { music_db: -12 } });
+ });
+});
+
+describe("public sign-up: the tools are the owner's (docs/public-signup.md)", () => {
+ it("a visitor's change to an Assist chat (where the tools run) is refused, and MCP is owner-only, so a visitor never runs them", async () => {
+ const access = await import("@/lib/guest-access");
+ // Approving a split_soundtrack / remove_dialogue card is a change to the chat: assist-owner for guests and accounts.
+ expect(access.isAssistChange("POST", "/api/assist/abc123/approval")).toBe(true);
+ expect(access.isAssistChange("POST", "/api/assist/abc123/messages")).toBe(true);
+ expect(access.ownerOnly("POST", "/api/mcp")).toBe(true);
+ expect(access.ownerOnly("GET", "/api/mcp")).toBe(true);
+ });
+});