Skip to content

Open source CapCut alternative.

TypeScript

fix(site): gemini chat retries transient and empty rounds

David Le4aa54b75e01f
diff --git a/site/scripts/eval-cut-chat.ts b/site/scripts/eval-cut-chat.ts
index 58f5af1d..948d92fd 100644
--- a/site/scripts/eval-cut-chat.ts
+++ b/site/scripts/eval-cut-chat.ts
@@ -33,7 +33,8 @@ const argValue = (flag: string) => {
const BASE = argValue("--base") ?? "http://localhost:3000";
const ONLY = argValue("--only");
const RUNS = Number(argValue("--runs") ?? 1);
-const MAX_ROUNDS = 8;
+// Matches the production chat loop's tool-round cap (geminiChat.ts).
+const MAX_ROUNDS = 24;
// Tools that read or steer the view without changing the cut or spending
// credits. Anything outside this set counts as a mutation for the evals.
@@ -171,11 +172,35 @@ const VOICE_REF = {
handle: "a1",
};
+/** The base snapshot with a spoken transcript on track 0 — filler words at
+ * known cue timings, so "cut the filler" has real ranges to act on. */
+const FILLER_CUES = [
+ { id: "cue1", start: 0, end: 1.8, text: "Um, so today we're" },
+ { id: "cue2", start: 1.8, end: 4.2, text: "at the beach with the dogs" },
+ { id: "cue3", start: 4.2, end: 5.6, text: "and, uh, you know," },
+ { id: "cue4", start: 5.6, end: 9, text: "they absolutely love the water" },
+ { id: "cue5", start: 9, end: 12.5, text: "so let's watch them play" },
+];
+
+const FILLER_STATE = {
+ ...EDITOR_STATE,
+ subtitles: {
+ ...EDITOR_STATE.subtitles,
+ count: FILLER_CUES.length,
+ tracks: [{ track: 0, locale: "en-US", cues: FILLER_CUES.length }],
+ cues: FILLER_CUES,
+ },
+};
+
/** A composer turn as geminiChat's inputFromMessages builds it (keep the
* envelope text in sync with geminiChat.ts). */
function userTurn(
text: string,
- opts?: { attachAudio?: { dataBase64: string; mimeType: string }; attachRefs?: unknown[] }
+ opts?: {
+ attachAudio?: { dataBase64: string; mimeType: string };
+ attachRefs?: unknown[];
+ state?: unknown;
+ }
): Item {
let full = text;
const extra: Item[] = [];
@@ -187,10 +212,175 @@ function userTurn(
extra.push({ text: `Attached audio "${VOICE_REF.name}":` });
extra.push({ type: "input_audio", ...opts.attachAudio });
}
- full += `\n\n<editor_state>\n${JSON.stringify(EDITOR_STATE)}\n</editor_state>`;
+ full += `\n\n<editor_state>\n${JSON.stringify(opts?.state ?? EDITOR_STATE)}\n</editor_state>`;
return { role: "user", content: [{ text: full }, ...extra] };
}
+/** A tiny track-0 simulator for composed cut flows: splits, trims, deletes,
+ * and undo evolve real state, so get_state shows the model its own edits and
+ * later calls can use the new clip ids. A frozen snapshot can't support a
+ * multi-step cut — the model chases clips that "aren't there" and stalls. */
+function makeTimelineSim(base: typeof FILLER_STATE) {
+ interface SimClip {
+ id: string;
+ start: number;
+ in: number;
+ out: number;
+ }
+ const r2 = (x: number) => Math.round(x * 100) / 100;
+ let clips: SimClip[] = base.videoTrack.map((c) => ({
+ id: c.id,
+ start: c.start,
+ in: c.in,
+ out: c.out,
+ }));
+ let cues = base.subtitles.cues.map((c) => ({ ...c }));
+ let audio: SimClip[] = base.soundtrack.map((a) => ({
+ id: a.id,
+ start: a.start,
+ in: a.in,
+ out: a.out,
+ }));
+ const history: { clips: SimClip[]; audio: SimClip[] }[] = [];
+ const remember = () => history.push({ clips, audio });
+ let n = 0;
+ const ripple = () => {
+ let t = 0;
+ clips = clips.map((c) => {
+ const next = { ...c, start: r2(t) };
+ t += c.out - c.in;
+ return next;
+ });
+ };
+ const snapshot = () => ({
+ ...base,
+ project: { ...base.project, duration: r2(clips.reduce((s, c) => s + c.out - c.in, 0)) },
+ subtitles: {
+ ...base.subtitles,
+ count: cues.length,
+ tracks: [{ track: 0, locale: "en-US", cues: cues.length }],
+ cues,
+ },
+ soundtrack: audio.map((a) => ({
+ id: a.id,
+ asset: VOICE_ASSET.name,
+ start: a.start,
+ len: r2(a.out - a.in),
+ in: a.in,
+ out: a.out,
+ volume: 1,
+ fadeIn: 0,
+ fadeOut: 0,
+ duck: 0.4,
+ })),
+ videoTrack: clips.map((c, i) => ({
+ index: i,
+ id: c.id,
+ asset: "beach.mp4",
+ start: c.start,
+ len: r2(c.out - c.in),
+ in: c.in,
+ out: c.out,
+ sourceDuration: 20,
+ muted: false,
+ framing: "fit",
+ speed: 1,
+ })),
+ });
+ return (name: string, args: Record<string, unknown>): unknown => {
+ if (name === "get_state") return snapshot();
+ if (name === "split_at") {
+ const t = Number(args.t);
+ const splittable = (x: SimClip) => t > x.start + 0.05 && t < x.start + (x.out - x.in) - 0.05;
+ const cut = (list: SimClip[]) =>
+ list.flatMap((x) => {
+ if (!splittable(x)) return [x];
+ const at = r2(x.in + (t - x.start));
+ return [
+ { id: `${x.id}-${++n}`, start: x.start, in: x.in, out: at },
+ { id: `${x.id}-${++n}`, start: r2(t), in: at, out: x.out },
+ ];
+ });
+ if (!Number.isFinite(t) || (!clips.some(splittable) && !audio.some(splittable)))
+ return { error: "Nothing to split at that time." };
+ remember();
+ clips = cut(clips);
+ audio = cut(audio);
+ return { split: true, videoClips: clips.length };
+ }
+ if (name === "delete_item") {
+ const id = String(args.id);
+ if (args.kind === "clip") {
+ if (!clips.some((c) => c.id === id)) return { error: `No clip with id ${id}.` };
+ remember();
+ clips = clips.filter((c) => c.id !== id);
+ ripple();
+ return { deleted: { kind: "clip", id } };
+ }
+ if (args.kind === "audio") {
+ if (!audio.some((a) => a.id === id)) return { error: `No audio with id ${id}.` };
+ remember();
+ audio = audio.filter((a) => a.id !== id);
+ return { deleted: { kind: "audio", id } };
+ }
+ return undefined;
+ }
+ if (name === "trim_clip") {
+ const c = clips.find((x) => x.id === String(args.clipId));
+ if (!c) return { error: `No video clip with id ${String(args.clipId)}.` };
+ const nextIn = typeof args.in === "number" ? args.in : c.in;
+ const nextOut = typeof args.out === "number" ? args.out : c.out;
+ if (nextOut - nextIn < 0.1) return { error: "Clip must stay at least 0.1s long." };
+ remember();
+ clips = clips.map((x) => (x === c ? { ...x, in: nextIn, out: nextOut } : x));
+ ripple();
+ return { in: nextIn, out: nextOut, len: r2(nextOut - nextIn) };
+ }
+ if (name === "place_clip") {
+ const c = clips.find((x) => x.id === String(args.clipId));
+ if (!c) return { error: `No video clip with id ${String(args.clipId)}.` };
+ remember();
+ const at = typeof args.start === "number" ? Math.max(0, args.start) : c.start;
+ clips = clips
+ .map((x) => (x === c ? { ...x, start: at } : x))
+ .sort((a, b) => a.start - b.start);
+ ripple();
+ return { start: at };
+ }
+ if (name === "undo") {
+ const prev = history.pop();
+ if (prev) {
+ clips = prev.clips;
+ audio = prev.audio;
+ }
+ return { ok: true, videoClips: clips.length };
+ }
+ if (name === "delete_cue") {
+ const cue = cues.find((c) => c.id === String(args.id));
+ if (!cue) return { error: `No subtitle cue with id ${String(args.id)}.` };
+ cues = cues.filter((c) => c !== cue);
+ return { deleted: cue.id };
+ }
+ if (name === "update_cue") {
+ const cue = cues.find((c) => c.id === String(args.id));
+ if (!cue) return { error: `No subtitle cue with id ${String(args.id)}.` };
+ if (typeof args.text === "string") cue.text = args.text;
+ if (typeof args.start === "number") cue.start = args.start;
+ if (typeof args.end === "number") cue.end = args.end;
+ return { id: cue.id, text: cue.text, start: cue.start, end: cue.end };
+ }
+ if (name === "merge_cue") {
+ const i = cues.findIndex((c) => c.id === String(args.id));
+ if (i < 0) return { error: `No subtitle cue with id ${String(args.id)}.` };
+ if (i === 0) return { error: "That is its track's first cue — nothing before it to merge into." };
+ cues[i - 1] = { ...cues[i - 1], end: cues[i].end, text: `${cues[i - 1].text} ${cues[i].text}` };
+ cues.splice(i, 1);
+ return { mergedInto: "previous cue" };
+ }
+ return undefined;
+ };
+}
+
// ---------------------------------------------------------------------------
// Cases
@@ -201,6 +391,16 @@ interface EvalCase {
reply: RegExp;
/** Tools that MUST appear across the turn (each stubbed to succeed). */
requiredTools?: string[];
+ /** At least one of these must appear — for flows with several valid cuts. */
+ anyTools?: string[];
+ /** Latency guard: the turn fails if the trace exceeds this many calls. A
+ * simple ask must not detour through skill reads or state polls. */
+ maxToolCalls?: number;
+ /** Editor snapshot served to get_state for this case (default EDITOR_STATE). */
+ state?: unknown;
+ /** Per-run tool interceptor (fresh per run); a non-undefined return serves
+ * the call before stubs and safe tools. */
+ simulate?: () => (name: string, args: Record<string, unknown>) => unknown;
/** Stub results for expected tool calls. */
stubs?: Record<string, unknown>;
}
@@ -256,6 +456,64 @@ function cases(audio: { dataBase64: string; mimeType: string }): EvalCase[] {
input: () => [userTurn("ugh, my project is getting cluttered with files")],
reply: /media|asset|file|clean|organi|tidy|clutter|remove|delete/i,
},
+ {
+ // Fast path: a plain text-only video ask is ONE generate_video call —
+ // no scene pipeline, no image staging, no skill-doc detour first.
+ name: "video-ask-single-generate",
+ input: () => [userTurn("generate a video about dogs")],
+ reply: /video|render|dog|minute/i,
+ requiredTools: ["generate_video"],
+ maxToolCalls: 2,
+ stubs: {
+ generate_video: {
+ kind: "video",
+ started: true,
+ jobId: "job-dogs",
+ addToTimeline: false,
+ note:
+ "Rendering with Veo — it previews in this chat when it lands, in a minute or two. It stays in the chat until the user places it.",
+ },
+ },
+ },
+ {
+ // Fast path: audio generation goes straight to voiceover_generate
+ // (list_voices is a fine extra hop, more than that is a detour).
+ name: "audio-ask-single-generate",
+ input: () => [userTurn("generate a voiceover that says welcome to the dog show")],
+ reply: /voice|audio|narrat|welcome/i,
+ requiredTools: ["voiceover_generate"],
+ maxToolCalls: 3,
+ stubs: {
+ voiceover_generate: {
+ assetId: "a-tts2",
+ name: "AI voice — welcome to the dog show",
+ start: 0,
+ duration: 2.3,
+ voice: "aoede",
+ },
+ },
+ },
+ {
+ // Fast path: a direct edit is one trim_clip on the clip in the snapshot.
+ name: "trim-ask-single-tool",
+ input: () => [userTurn("trim the first clip down to 5 seconds")],
+ reply: /trim|5|second/i,
+ requiredTools: ["trim_clip"],
+ maxToolCalls: 2,
+ stubs: { trim_clip: { in: 0, out: 5, len: 5 } },
+ },
+ {
+ // Driving the editor on the user's behalf: with a transcript in the
+ // snapshot, "cut the filler words" must land real timeline cuts (split
+ // then delete, or a trim) — not just talk about them, and not merely
+ // rewrite the captions.
+ name: "filler-words-cut-with-editor",
+ input: () => [userTurn("cut the filler words out of my video", { state: FILLER_STATE })],
+ reply: /filler|um|uh|cut|remove|trim/i,
+ anyTools: ["split_at", "delete_item", "trim_clip"],
+ state: FILLER_STATE,
+ simulate: () => makeTimelineSim(FILLER_STATE),
+ },
{
// Control: a real edit request must still act with tools — guards
// against over-suppressing tool use.
@@ -286,10 +544,19 @@ const toolDeclarations = AI_TOOLS.map((t) => ({
parameters: t.inputSchema,
}));
-function serveSafeTool(name: string): unknown {
- if (name === "get_state") return EDITOR_STATE;
+function serveSafeTool(name: string, state: unknown): unknown {
+ if (name === "get_state") {
+ // The fixture snapshot is frozen — it can't reflect this turn's stubbed
+ // edits. Say so, or the model sees its adds "missing" and re-adds in a
+ // loop (the live store never has this problem).
+ return {
+ ...(state as Record<string, unknown>),
+ note: "Snapshot may lag this turn's edits — trust each tool's own result.",
+ };
+ }
if (name === "list_skills") return { skills: AI_SKILL_INDEX };
if (name === "library_list") return { folders: [], assets: [], templates: [] };
+ if (name === "detect_silence") return { silences: [] };
return { ok: true };
}
@@ -303,27 +570,36 @@ interface CaseResult {
async function runCase(c: EvalCase): Promise<CaseResult> {
const input = c.input();
+ const sim = c.simulate?.();
const trace: string[] = [];
const violations: string[] = [];
const notes: string[] = [];
let reply = "";
+ let emptyRounds = 0;
for (let round = 0; round < MAX_ROUNDS; round++) {
- const res = await fetch(`${BASE}/api/inference/responses`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "x-donkey-client-id": "donkey-cut-eval",
- "x-donkey-dev-auth-bypass": "1",
- },
- body: JSON.stringify({
- donkeyProvider: "gemini",
- model: geminiModelRoles.chat,
- instructions: systemPrompt(),
- input,
- tools: toolDeclarations,
- }),
- });
+ // A transient upstream failure (rate limit, Gemini 5xx) gets a couple of
+ // retries so it doesn't read as a behavioral failure of the case.
+ let res: Response;
+ for (let attempt = 0; ; attempt++) {
+ res = await fetch(`${BASE}/api/inference/responses`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-donkey-client-id": "donkey-cut-eval",
+ "x-donkey-dev-auth-bypass": "1",
+ },
+ body: JSON.stringify({
+ donkeyProvider: "gemini",
+ model: geminiModelRoles.chat,
+ instructions: systemPrompt(),
+ input,
+ tools: toolDeclarations,
+ }),
+ });
+ if (res.ok || ![429, 500, 502, 503, 504].includes(res.status) || attempt >= 2) break;
+ await new Promise((r) => setTimeout(r, 800 * (attempt + 1)));
+ }
if (!res.ok) throw new Error(`responses ${res.status}: ${(await res.text()).slice(0, 300)}`);
const body = (await res.json()) as {
output_text?: string;
@@ -334,7 +610,17 @@ async function runCase(c: EvalCase): Promise<CaseResult> {
if (text) reply = reply ? `${reply}\n${text}` : text;
const calls = (body.output ?? []).filter((o) => o.type === "function_call");
- if (calls.length === 0) break;
+ if (calls.length === 0) {
+ // A no-call round with nothing said all turn is the degenerate empty
+ // STOP; the production loop (geminiChat.ts) re-asks the same input a
+ // couple of times, so the eval does too rather than scoring it silent.
+ if (!reply && emptyRounds < 2) {
+ emptyRounds++;
+ continue;
+ }
+ break;
+ }
+ emptyRounds = 0;
const assistantParts: Item[] = text ? [{ text }] : [];
const responseParts: Item[] = [];
@@ -353,13 +639,20 @@ async function runCase(c: EvalCase): Promise<CaseResult> {
assistantParts.push(part);
let response: unknown;
+ const argsObj =
+ call.arguments && typeof call.arguments === "object"
+ ? (call.arguments as Record<string, unknown>)
+ : {};
+ const simulated = sim?.(name, argsObj);
if (name === "read_skill") {
- const doc = AI_SKILLS[String((call.arguments as Record<string, unknown>)?.name ?? "")];
+ const doc = AI_SKILLS[String(argsObj.name ?? "")];
response = doc ? { doc } : { error: "No such skill." };
+ } else if (simulated !== undefined) {
+ response = simulated;
} else if (c.stubs && name in c.stubs) {
response = c.stubs[name];
} else if (SAFE_TOOLS.has(name)) {
- response = serveSafeTool(name);
+ response = serveSafeTool(name, c.state ?? EDITOR_STATE);
} else {
violations.push(name);
response = { error: "eval: this tool is disabled for this turn" };
@@ -382,6 +675,10 @@ async function runCase(c: EvalCase): Promise<CaseResult> {
for (const t of c.requiredTools ?? []) {
if (!trace.includes(t)) notes.push(`required tool ${t} was never called`);
}
+ if (c.anyTools && !c.anyTools.some((t) => trace.includes(t)))
+ notes.push(`none of [${c.anyTools.join(", ")}] were called`);
+ if (c.maxToolCalls !== undefined && trace.length > c.maxToolCalls)
+ notes.push(`slow: ${trace.length} tool calls (cap ${c.maxToolCalls})`);
if (violations.length > 0) notes.push(`mutating tools called: ${violations.join(", ")}`);
return { pass: notes.length === 0, reply, trace, violations, notes };
}
diff --git a/site/src/cut/lib/geminiChat.ts b/site/src/cut/lib/geminiChat.ts
index d24f6ea6..9accb9dc 100644
--- a/site/src/cut/lib/geminiChat.ts
+++ b/site/src/cut/lib/geminiChat.ts
@@ -18,6 +18,42 @@ import { refsToParts } from "./refMedia";
const MAX_TOOL_ROUNDS = 24;
+// A round request gets a couple more tries when the failure is transient —
+// rate limits and upstream hiccups — before the turn surfaces an error. Auth
+// (401), credits (402), and validation failures surface immediately.
+const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
+const TRANSIENT_RETRIES = 2;
+// Gemini can return an empty STOP round — no text, no tool calls (same class
+// as the empty-TTS behavior). Identical re-asks usually land, so the loop
+// retries before bothering the user.
+const EMPTY_ROUND_RETRIES = 2;
+
+const backoff = (attempt: number) =>
+ new Promise<void>((resolve) => setTimeout(resolve, 600 * (attempt + 1)));
+
+/** One round-trip to the hosted Responses route, retrying transient failures. */
+async function postRound(
+ payload: Record<string, unknown>,
+ abortSignal?: AbortSignal
+): Promise<ResponseBody> {
+ for (let attempt = 0; ; attempt++) {
+ let res: Response;
+ try {
+ res = await hostedPost("/api/inference/responses", payload, abortSignal);
+ } catch (err) {
+ // Network drop — retry unless the user stopped the turn or we're out.
+ if (abortSignal?.aborted || attempt >= TRANSIENT_RETRIES) throw err;
+ await backoff(attempt);
+ continue;
+ }
+ if (res.ok) return (await res.json()) as ResponseBody;
+ if (!RETRYABLE_STATUS.has(res.status) || attempt >= TRANSIENT_RETRIES) {
+ throw new Error(await requestError(res));
+ }
+ await backoff(attempt);
+ }
+}
+
const STEP_LIMIT_FALLBACK =
'I got partway through and hit this turn’s step limit — say “keep going” and I’ll finish the rest.';
@@ -51,16 +87,12 @@ async function emitStepLimitSummary({
],
},
];
- const res = await hostedPost(
- "/api/inference/responses",
+ const body = await postRound(
{ donkeyProvider: "gemini", model, instructions: systemPrompt(), input: summaryInput },
abortSignal
);
- if (res.ok) {
- const body = (await res.json()) as ResponseBody;
- const summary = (body.output_text ?? "").trim();
- if (summary) text = summary;
- }
+ const summary = (body.output_text ?? "").trim();
+ if (summary) text = summary;
} catch {
// A failed summary falls back to the static handoff below.
}
@@ -154,18 +186,30 @@ async function execTool(name: string, args: Record<string, unknown>): Promise<un
* originating call so Gemini matches responses to calls across parallel calls.
* Frames leave the JSON (a data URL inlined as text would blow the token
* budget) and ride along as image parts instead: the first on the response
- * itself, the rest (contact sheets) as input_image parts in the same turn. */
-function functionResponseParts(name: string, output: unknown, id: string): Item[] {
- // Audio rides the same way (listen_audio): the sound leaves the JSON and
- // follows the response as an input_audio part, like an attachment's.
+ * itself, the rest (contact sheets) as input_image parts in the same turn.
+ *
+ * Audio (listen_audio) leaves the JSON too, but returns via `audioTurn`: a
+ * separate user turn shaped like a message attachment. Gemini 3.5 Flash
+ * answers a turn that holds a functionResponse alongside audio inlineData
+ * with one-token garbage and no tool call; the same audio in its own turn
+ * gets a full reply. */
+function functionResponseParts(
+ name: string,
+ output: unknown,
+ id: string
+): { parts: Item[]; audioTurn: Item[] } {
if (output && typeof output === "object" && "audio" in output) {
- const { audio, ...rest } = output as { audio?: unknown };
+ const { audio, ...rest } = output as { audio?: unknown; name?: unknown };
const m = typeof audio === "string" ? /^data:([^;,]+);base64,(.+)$/.exec(audio) : null;
if (m) {
- return [
- { type: "function_response", id, name, response: rest },
- { type: "input_audio", dataBase64: m[2], mimeType: m[1] },
- ];
+ const assetName = typeof rest.name === "string" ? rest.name : name;
+ return {
+ parts: [{ type: "function_response", id, name, response: rest }],
+ audioTurn: [
+ { text: `Attached audio "${assetName}":` },
+ { type: "input_audio", dataBase64: m[2], mimeType: m[1] },
+ ],
+ };
}
}
if (output && typeof output === "object" && ("image" in output || "images" in output)) {
@@ -178,24 +222,27 @@ function functionResponseParts(name: string, output: unknown, id: string): Item[
.filter((m): m is RegExpExecArray => m !== null);
if (parsed.length > 0) {
const [first, ...more] = parsed;
- return [
- {
- type: "function_response",
- id,
- name,
- response: rest,
- mimeType: first[1],
- screenshotBase64: first[2],
- },
- ...more.map((m) => ({ type: "input_image", dataBase64: m[2], mimeType: m[1] })),
- ];
+ return {
+ parts: [
+ {
+ type: "function_response",
+ id,
+ name,
+ response: rest,
+ mimeType: first[1],
+ screenshotBase64: first[2],
+ },
+ ...more.map((m) => ({ type: "input_image", dataBase64: m[2], mimeType: m[1] })),
+ ],
+ audioTurn: [],
+ };
}
}
const response =
output && typeof output === "object" && !Array.isArray(output)
? output
: { result: output ?? null };
- return [{ type: "function_response", id, name, response }];
+ return { parts: [{ type: "function_response", id, name, response }], audioTurn: [] };
}
interface ResponseBody {
@@ -229,15 +276,13 @@ export function streamGeminiChat({
const tools = toolDeclarations();
let textCount = 0;
let settled = false;
+ let emptyRounds = 0;
for (let round = 0; round < MAX_TOOL_ROUNDS && !settled; round++) {
- const res = await hostedPost(
- "/api/inference/responses",
+ const body = await postRound(
{ donkeyProvider: "gemini", model, instructions: systemPrompt(), input, tools },
abortSignal
);
- if (!res.ok) throw new Error(await requestError(res));
- const body = (await res.json()) as ResponseBody;
const assistantParts: Item[] = [];
const text = (body.output_text ?? "").trim();
@@ -251,10 +296,14 @@ export function streamGeminiChat({
const calls = (body.output ?? []).filter((o) => o.type === "function_call");
if (calls.length === 0) {
+ // An empty STOP round with nothing said all turn: re-ask the same
+ // input a couple of times — identical retries usually land — and
+ // only then surface it, so the reply bubble never sits blank.
+ if (textCount === 0 && emptyRounds < EMPTY_ROUND_RETRIES) {
+ emptyRounds++;
+ continue;
+ }
settled = true;
- // Gemini can return an empty STOP round — no text, no tool calls
- // (same class as the empty-TTS behavior). Without this the stream
- // finishes having emitted nothing and the reply bubble stays blank.
if (textCount === 0) {
emit({ type: "error", errorText: "Gemini returned an empty response. Try again." });
}
@@ -263,7 +312,9 @@ export function streamGeminiChat({
// Parallel calls stay in one model turn, with every response in the
// single user turn that follows — the shape Gemini expects back.
+ // Tool audio gathers separately and follows as its own user turn.
const responseParts: Item[] = [];
+ const audioParts: Item[] = [];
for (const call of calls) {
const name = String(call.name ?? "unknown_function");
const args =
@@ -292,15 +343,20 @@ export function streamGeminiChat({
uiOutput = rest;
}
emit({ type: "tool-output-available", toolCallId, output: uiOutput ?? null });
- responseParts.push(...functionResponseParts(name, output, toolCallId));
+ const { parts, audioTurn } = functionResponseParts(name, output, toolCallId);
+ responseParts.push(...parts);
+ audioParts.push(...audioTurn);
} catch (err) {
const errorText = err instanceof Error ? err.message : String(err);
emit({ type: "tool-output-error", toolCallId, errorText });
- responseParts.push(...functionResponseParts(name, { error: errorText }, toolCallId));
+ responseParts.push(
+ ...functionResponseParts(name, { error: errorText }, toolCallId).parts
+ );
}
}
input.push({ role: "assistant", content: assistantParts });
input.push({ role: "user", content: responseParts });
+ if (audioParts.length > 0) input.push({ role: "user", content: audioParts });
}
if (!settled && !abortSignal?.aborted) {