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.

Assist: generate is no longer strict, voice-change re-voices the earlier audio, quiet offline note

Claudef68a6f474439
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index 38a6bc5d..9c767189 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -3,7 +3,7 @@ import Anthropic from "@anthropic-ai/sdk";
import { nanoid } from "nanoid";
import { AUDIO_STUDIO, EDIT_STUDIO, IMAGE_STUDIO, MUSIC_STUDIO, VIDEO_STUDIO } from "@/lib/studios";
import { type AssistItem, type AssistThread, type AssistThreadSummary, type AssistThreadView, threadTitle } from "@/lib/assist";
-import type { Engine, Generation } from "@/lib/catalog/types";
+import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";
import { db } from "../db";
import { getGeneration } from "../generations";
import { engineMode, getSetting } from "../settings";
@@ -391,12 +391,13 @@ export const offline: ModelCall = async ({ messages, ctx }) => {
if (results.length && !said.trim()) {
const body = results.map((r) => (typeof r.content === "string" ? r.content : "")).join(" ");
if (results.some((r) => r.is_error)) return reply([text(/declined/i.test(body) ? "Okay, I won't run that. Tell me what to change." : `That didn't start: ${body.replace(/^.*"error":"([^"]+)".*$/, "$1")}`)], "end_turn");
- return reply([text("On it — the results will appear here as they finish. Want variations, a different look, or to animate one?")], "end_turn");
+ return reply([text(`On it — the results will appear here as they finish. ${FOLLOW_UP[startedKind(body)]}`)], "end_turn");
}
const plan = offlinePlan(said, ctx.engine);
if (!plan) return reply([text("Tell me what to make — an image, a video, a voice-over or a storyboard — and attach any photos to use.")], "end_turn");
+ // step() adds OFFLINE_NOTE as a quiet line under the plan card.
return reply(
- [text(`${plan.say}\n\n${OFFLINE_NOTE}`), { type: "tool_use", id: `toolu_offline_${nanoid(10)}`, name: plan.tool, input: plan.input, caller: { type: "direct" } } as unknown as Anthropic.Beta.BetaToolUseBlock],
+ [text(plan.say), { type: "tool_use", id: `toolu_offline_${nanoid(10)}`, name: plan.tool, input: plan.input, caller: { type: "direct" } } as unknown as Anthropic.Beta.BetaToolUseBlock],
"tool_use",
);
};
@@ -404,6 +405,25 @@ export const offline: ModelCall = async ({ messages, ctx }) => {
/** Under every offline plan: the rule-based planner is a fallback, not the assistant. */
export const OFFLINE_NOTE = "Offline planner — connect Claude or Ollama in Settings for better plans.";
+/** What to offer next, by what was just started. */
+const FOLLOW_UP: Record<MediaKind, string> = {
+ image: "Want variations, a different look, or to animate one?",
+ video: "Want another take, a different camera move, or a longer cut?",
+ audio: "Want another voice, a different pace, or to put it on a video?",
+ text: "Want it shorter, in another tone, or voiced?",
+ model3d: "Want another take, or a model from a different photo?",
+};
+
+/** The kind of the last generation a tool result started (the end of a chain), image when unknown. */
+function startedKind(body: string): MediaKind {
+ const ids = [...body.matchAll(/"(?:started|id)":\s*\[?\s*"([\w-]+)"/g)].map((m) => m[1]);
+ for (const id of ids.reverse()) {
+ const g = getGeneration(id);
+ if (g) return g.kind;
+ }
+ return "image";
+}
+
const NUMBER_WORDS: Record<string, number> = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8 };
const NUM = "(\\d|one|two|three|four|five|six|seven|eight)";
const num = (s: string) => NUMBER_WORDS[s] ?? Number(s);
@@ -567,6 +587,10 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
const results: ToolResult[] = [];
const gated: Pending["gated"] = [];
+ // The rule-based planner says so in a quiet line under its plan (or under the jobs it started).
+ const offlineNote = () => {
+ if (model === offline) push(s, { role: "notice", tone: "info", text: OFFLINE_NOTE });
+ };
for (const u of uses) {
if (getTool(u.name)?.gated && !s.thread.autoApprove) {
// Malformed arguments (common from small local models) go straight back as an error the model can fix, not onto an approval card.
@@ -589,10 +613,12 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
const summaries = gated.map((g) => (g.input as { summary?: string }).summary).filter(Boolean);
const total = plans.some((p) => p.total === null) ? null : plans.reduce((n, p) => n + (p.total ?? 0), 0);
const item = push(s, { role: "approval", summary: summaries.join(" · ") || (gated[0].name === "create_storyboard" ? "Storyboard" : "Generate"), jobs, totalUsd: total, status: "pending" });
+ offlineNote();
s.pending = { approvalItemId: item.id, results, gated, order };
s.thread.status = "waiting";
return "stop";
}
+ offlineNote();
s.messages.push({ role: "user", content: ordered(results, order) });
return "continue";
}
diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.ts
index 23cb5af9..90cba97a 100644
--- a/src/server/assist/tools.ts
+++ b/src/server/assist/tools.ts
@@ -244,8 +244,9 @@ const Job = z.object({
images: z.array(ref).optional().describe("Input images: the image to edit, the start frame, or references, in order."),
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)."),
- voice_audio: ref.optional().describe("A recording of the voice to speak with (voice-cloning text to speech)."),
+ 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."),
+ voice_audio: ref.optional().describe("A recording of the voice to speak with (voice-cloning text to speech) or to change into (voice-change)."),
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."),
@@ -264,7 +265,7 @@ const Job = z.object({
.int()
.optional()
.describe(
- "Index (0-based) of an earlier job in this same call whose result this job uses: it starts by itself when that job finishes. An image becomes the start frame or the image to edit, a video the input video, audio the soundtrack (or the voice to clone, for tts), text the prompt.",
+ "Index (0-based) of an earlier job in this same call whose result this job uses: it starts by itself when that job finishes. An image becomes the start frame or the image to edit, a video the input video, audio the soundtrack or the recording to re-voice (the voice to clone, for tts), text the prompt.",
),
negative_prompt: z.string().optional(),
});
@@ -292,6 +293,7 @@ function toRequest(j: JobInput): GenerationRequest {
...(j.end_image && { endImage: j.end_image }),
...(j.video && { video: j.video }),
...(j.audio && { audio: j.audio }),
+ ...(j.background_audio && { audio2: j.background_audio }),
...(j.voice_audio && { voiceAudio: j.voice_audio }),
};
const shots = j.shots && j.shots > 1 ? shotList(getModel(j.model_id), j.shots) : undefined;
@@ -324,7 +326,8 @@ function toRequest(j: JobInput): GenerationRequest {
function slotFor(kind: MediaKind, op: Operation | undefined): ChainSlot {
if (kind === "text") return { slot: "prompt" };
if (kind === "video") return { slot: op === "concat" ? "videos" : "video" };
- if (kind === "audio") return { slot: op === "tts" || op === "voice-change" ? "voiceAudio" : "audio" };
+ // tts clones the earlier audio's voice; voice-change re-voices the earlier audio (its target voice is voice_audio).
+ if (kind === "audio") return { slot: op === "tts" ? "voiceAudio" : "audio" };
return { slot: "images", position: "first" };
}
@@ -392,7 +395,9 @@ const generate = defineTool({
"Start image, video, audio, text (transcribe, translate, write) or 3D generations, alone or chained with \"after\". The app shows the user the plan with its cost and runs it once they approve, so call this directly instead of asking for confirmation in text. Returns generation ids; their results appear in the chat by themselves.",
schema: GenerateInput,
gated: true,
- strict: true,
+ // Not strict: the API allows 24 optional parameters across all strict tools in a request, and a
+ // job has more. Calls are validated with zod (validateInput / planFor / executeTool) instead, and
+ // a malformed one goes back to the model as an error it can fix.
plan: ({ jobs }) => chainJobs(jobs.slice(0, 6)).map(plannedJob),
async run({ jobs }) {
const list = jobs.slice(0, 6);
diff --git a/tests/assist-runtime.test.ts b/tests/assist-runtime.test.ts
index e3ec1ac5..0c6704e3 100644
--- a/tests/assist-runtime.test.ts
+++ b/tests/assist-runtime.test.ts
@@ -78,7 +78,10 @@ describe("offline planner (U18)", () => {
let v = agent.getThread(t.id)!;
expect(v.thread.status).toBe("waiting");
const said = v.thread.items.find((i) => i.role === "assistant") as { text: string };
- expect(said.text).toContain(agent.OFFLINE_NOTE);
+ // A quiet line right under the plan card, not part of the reply.
+ expect(said.text).not.toContain(agent.OFFLINE_NOTE);
+ const at = v.thread.items.findIndex((i) => i.role === "approval");
+ expect(v.thread.items[at + 1]).toMatchObject({ role: "notice", tone: "info", text: agent.OFFLINE_NOTE });
expect(agent.OFFLINE_NOTE).toBe("Offline planner — connect Claude or Ollama in Settings for better plans.");
const card = v.thread.items.find((i) => i.role === "approval") as { jobs: { kind: string; op: string; error?: string }[] };
expect(card.jobs.map((j) => [j.kind, j.op, j.error])).toEqual([
@@ -93,6 +96,20 @@ describe("offline planner (U18)", () => {
expect(dependsOn(clip.id)).toBe(still.id);
expect(clip.request.chain).toEqual([{ slot: "images", position: "first" }]);
expect(clip.request.params?.shots).toHaveLength(3);
+ // The follow-up fits what ran: the chain ends in a video, which needs no animating.
+ const last = v.thread.items.filter((i) => i.role === "assistant").at(-1) as { text: string };
+ expect(last.text).toMatch(/another take/);
+ expect(last.text).not.toMatch(/animate/);
+ });
+
+ it("offers a text follow-up after a script, and notes itself under jobs it starts right away", async () => {
+ const t = agent.createThread({ agent: "offline", engine: "cloud", autoApprove: true });
+ agent.addMessage(t.id, "Write a 30-second voice-over script about cold brew");
+ await agent.run(t.id, agent.offline);
+ const v = agent.getThread(t.id)!;
+ const roles = v.thread.items.map((i) => i.role);
+ expect(roles.indexOf("notice")).toBe(roles.indexOf("generations") + 1);
+ expect((v.thread.items.at(-1) as { text: string }).text).toMatch(/shorter, in another tone, or voiced/);
});
});
@@ -179,6 +196,63 @@ describe("new kinds and operations in the tools", () => {
expect(summary[0].outputs[0]).toMatchObject({ kind: "text", text: expect.stringMatching(/Demo/), meta: { demo: true } });
});
+ it("re-voices an earlier recording: voice-change takes it as the audio, tts clones it", () => {
+ const plan = tools.planFor(
+ "generate",
+ {
+ summary: "Voice-over, then another voice",
+ jobs: [
+ { model_id: "elevenlabs-v4", prompt: "Welcome to the studio" },
+ { model_id: "elevenlabs-voice-changer", op: "voice-change", prompt: "Same words, Roger's voice", voice: "CwhRBWXzGAHq8TQ4Fs17", after: 0 },
+ { model_id: "chatterbox-cloud", op: "tts", prompt: "And now in that voice", after: 0 },
+ ],
+ },
+ { engine: "cloud" },
+ );
+ expect(plan.jobs.map((j) => [j.op, j.error])).toEqual([
+ ["tts", undefined],
+ ["voice-change", undefined],
+ ["tts", undefined],
+ ]);
+ });
+
+ it("passes a background track to mux", async () => {
+ const out = await tools.executeTool(
+ "generate",
+ { summary: "Soundtrack", jobs: [{ model_id: "oss-mux", op: "mux", prompt: "Mix", video: "/api/files/a.mp4", audio: "/api/files/voice.wav", background_audio: "/api/files/bg.wav" }] },
+ { engine: "open" },
+ );
+ expect(out.isError, String(out.content)).toBeFalsy();
+ const [r] = JSON.parse(out.content as string) as { started: string[] }[];
+ expect(gens.getGeneration(r.started[0])!.request.inputs).toEqual({ video: "/api/files/a.mp4", audio: "/api/files/voice.wav", audio2: "/api/files/bg.wav" });
+ });
+
+ it("keeps strict tools within the API's limits for one request", () => {
+ // platform.claude.com structured outputs: ≤ 20 strict tools, ≤ 24 optional parameters and
+ // ≤ 16 union-typed parameters across all strict schemas in a request, nested ones included.
+ const strict = tools.apiTools().filter((t) => t.strict);
+ let optional = 0;
+ let unions = 0;
+ const walk = (node: unknown): void => {
+ if (Array.isArray(node)) return node.forEach(walk);
+ if (!node || typeof node !== "object") return;
+ const n = node as { type?: unknown; properties?: Record<string, unknown>; required?: string[]; anyOf?: unknown; items?: unknown };
+ if (n.anyOf || Array.isArray(n.type)) unions++;
+ if (n.properties) {
+ optional += Object.keys(n.properties).filter((k) => !n.required?.includes(k)).length;
+ Object.values(n.properties).forEach(walk);
+ }
+ walk(n.items);
+ walk(n.anyOf);
+ };
+ strict.forEach((t) => walk(t.input_schema));
+ expect(strict.length).toBeLessThanOrEqual(20);
+ expect(optional).toBeLessThanOrEqual(24);
+ expect(unions).toBeLessThanOrEqual(16);
+ // generate is validated by zod instead (its jobs have more optional fields than the budget).
+ expect(strict.map((t) => t.name)).not.toContain("generate");
+ });
+
it("prices a chained plan and points out a bad 'after'", () => {
const plan = tools.planFor(
"generate",
diff --git a/tests/assist.test.ts b/tests/assist.test.ts
index 48800a94..7568798e 100644
--- a/tests/assist.test.ts
+++ b/tests/assist.test.ts
@@ -40,7 +40,7 @@ const history = (id: string) => JSON.parse((db().prepare("SELECT messages_json F
const job = { model_id: "nano-banana-pro", prompt: "a red fox in snow, golden hour" };
describe("assist tools", () => {
- it("sends closed, constraint-free schemas and strict gated tools", () => {
+ it("sends closed, constraint-free schemas, strict only where the API's strict budget allows", () => {
const tools = apiTools();
const json = JSON.stringify(tools);
expect(json).not.toMatch(/"(maximum|minimum|maxItems|minLength|\$schema)"/);
@@ -54,7 +54,9 @@ describe("assist tools", () => {
};
tools.forEach((t) => walk(t.input_schema));
expect(objects.every((o) => o.additionalProperties === false)).toBe(true);
- expect(tools.find((t) => t.name === "generate")?.strict).toBe(true);
+ // generate has more optional fields than strict mode allows per request (zod validates it instead).
+ expect(tools.find((t) => t.name === "generate")?.strict).toBeUndefined();
+ expect(tools.find((t) => t.name === "create_storyboard")?.strict).toBe(true);
expect(tools.find((t) => t.name === "search_models")?.strict).toBeUndefined();
});
});