Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Live calls (Gemini): keep held tool calls behind the wait for words; drop cancelled calls

Bugfixer 2c1a4561eb5ba
diff --git a/src/lib/live-call-gemini.test.ts b/src/lib/live-call-gemini.test.ts
index c5563208c7..8dfe005702 100644
--- a/src/lib/live-call-gemini.test.ts
+++ b/src/lib/live-call-gemini.test.ts
@@ -250,6 +250,60 @@ describe("a Gemini Live session", () => {
}
});
+ it("keeps a held call waiting for the rest of the words when the agent's audio comes between them", async () => {
+ vi.useFakeTimers();
+ try {
+ const t = harness();
+ await t.connect();
+ const order: string[] = [];
+ t.callbacks.onUserTranscript.mockImplementation(({ final, text }: { final: boolean; text: string }) => { if (final) order.push(text); });
+ t.delegate.mockImplementation(async () => { order.push("delegate"); return "On it."; });
+ t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_1", name: FISH_DELEGATE_TOOL, args: {} }] } });
+ t.socket().receive({ serverContent: { inputTranscription: { text: "book " } } });
+ t.socket().receive({ serverContent: { modelTurn: { parts: [{ inlineData: { mimeType: "audio/pcm", data: AUDIO } }] } } });
+ t.socket().receive({ serverContent: { outputTranscription: { text: "Sure." } } });
+ t.socket().receive({ serverContent: { inputTranscription: { text: "a table" } } });
+ expect(t.delegate).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(400);
+ expect(order).toEqual(["book a table", "delegate"]);
+ // Words made final by the agent's audio before a call came still wait a moment for more.
+ t.socket().receive({ serverContent: { turnComplete: true } });
+ t.socket().receive({ serverContent: { inputTranscription: { text: "and a " } } });
+ t.socket().receive({ serverContent: { modelTurn: { parts: [{ inlineData: { mimeType: "audio/pcm", data: AUDIO } }] } } });
+ t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_2", name: FISH_DELEGATE_TOOL, args: {} }] } });
+ t.socket().receive({ serverContent: { inputTranscription: { text: "taxi" } } });
+ expect(t.delegate).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(400);
+ expect(order).toEqual(["book a table", "delegate", "and a ", "taxi", "delegate"]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("drops a call Gemini cancels: a held one never runs, a running one's answer is not sent", async () => {
+ vi.useFakeTimers();
+ try {
+ const t = harness();
+ await t.connect();
+ t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_1", name: FISH_DELEGATE_TOOL, args: {} }] } });
+ t.socket().receive({ toolCallCancellation: { ids: ["fc_1"] } });
+ vi.advanceTimersByTime(2_000);
+ expect(t.delegate).not.toHaveBeenCalled();
+ let finish: (value: string) => void = () => undefined;
+ t.delegate.mockImplementation(() => new Promise<string>((resolve) => { finish = resolve; }));
+ t.socket().receive({ serverContent: { inputTranscription: { text: "book a table" } } });
+ t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_2", name: FISH_DELEGATE_TOOL, args: {} }] } });
+ vi.advanceTimersByTime(400);
+ expect(t.delegate).toHaveBeenCalledTimes(1);
+ t.socket().receive({ toolCallCancellation: { ids: ["fc_2"] } });
+ finish("On it.");
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.socket().sent.some((message) => "toolResponse" in message)).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("goes on over a new connection with the resumption handle when Gemini ends one", async () => {
const t = harness();
await t.connect();
diff --git a/src/lib/live-call-gemini.ts b/src/lib/live-call-gemini.ts
index a7847deacd..55dfe8a07d 100644
--- a/src/lib/live-call-gemini.ts
+++ b/src/lib/live-call-gemini.ts
@@ -48,6 +48,7 @@ type ServerMessage = {
turnComplete?: boolean;
};
toolCall?: { functionCalls?: ToolCall[] };
+ toolCallCancellation?: { ids?: string[] };
goAway?: unknown;
sessionResumptionUpdate?: { newHandle?: string; resumable?: boolean };
};
@@ -104,6 +105,8 @@ class GeminiLiveSession implements FishAgentSession {
private heldCalls: ToolCall[] = [];
private heldQuiet: ReturnType<typeof setTimeout> | null = null;
private heldLimit: ReturnType<typeof setTimeout> | null = null;
+ /** Calls Gemini cancelled, e.g. when the person talked over the agent: they do not run, or their answer is not sent. */
+ private cancelledCalls = new Set<string>();
constructor(options: FishSessionOptions<LiveGeminiSession>, deps: GeminiSessionDeps) {
this.options = options;
@@ -231,7 +234,7 @@ class GeminiLiveSession implements FishAgentSession {
}
for (const part of content.modelTurn?.parts ?? []) {
if (!part.inlineData?.data || !part.inlineData.mimeType?.startsWith("audio/")) continue;
- this.finishHeard();
+ this.finishHeardUnlessHeld();
this.turnDone = false;
this.audio?.play(decodeBase64(part.inlineData.data));
if (!this.speaking) {
@@ -241,7 +244,7 @@ class GeminiLiveSession implements FishAgentSession {
}
const said = content.outputTranscription?.text;
if (said) {
- this.finishHeard();
+ this.finishHeardUnlessHeld();
this.said += said;
this.options.callbacks.onAgentResponseDelta({ segmentId: `a${this.segment}`, text: this.said });
}
@@ -253,12 +256,14 @@ class GeminiLiveSession implements FishAgentSession {
this.playbackIdle();
}
if (content.turnComplete) {
- this.finishHeard();
+ this.finishHeardUnlessHeld();
this.heardThisTurn = false;
this.turnDone = true;
if (this.audio?.idle() !== false) this.playbackIdle();
}
}
+ const cancelled = message.toolCallCancellation?.ids ?? [];
+ if (cancelled.length) this.cancelCalls(cancelled);
const calls = message.toolCall?.functionCalls ?? [];
if (calls.length) this.onToolCalls(calls);
if (message.goAway !== undefined) this.wentAway = true;
@@ -276,7 +281,12 @@ class GeminiLiveSession implements FishAgentSession {
this.options.callbacks.onUserTranscript({ segmentId: `s${this.segment}`, text, final: true });
this.segment += 1;
this.heardThisTurn = true;
- this.releaseCalls();
+ }
+
+ /** The agent answering ends what the person said, but not while a tool call waits for it: the person's words can still
+ * come after the agent's (Gemini sends the two in no fixed order), and the call goes with all of them. */
+ private finishHeardUnlessHeld(): void {
+ if (!this.heldCalls.length) this.finishHeard();
}
private playbackIdle(): void {
@@ -291,11 +301,19 @@ class GeminiLiveSession implements FishAgentSession {
// while they are still coming.
for (const call of calls) this.callsAfterHandle.add(call.id ?? "");
this.heldCalls.push(...calls);
- if (this.heard) this.releaseWhenQuiet();
- else if (this.heardThisTurn) return this.releaseCalls();
+ if (this.heard || this.heardThisTurn) this.releaseWhenQuiet();
this.heldLimit ??= setTimeout(() => this.releaseCalls(), HEARD_WAIT_MS);
}
+ private cancelCalls(ids: string[]): void {
+ for (const id of ids) {
+ this.cancelledCalls.add(id);
+ this.callsAfterHandle.delete(id);
+ }
+ this.heldCalls = this.heldCalls.filter((call) => !this.cancelledCalls.has(call.id ?? ""));
+ if (!this.heldCalls.length) this.clearHeldTimers();
+ }
+
private releaseWhenQuiet(): void {
if (this.heldQuiet) clearTimeout(this.heldQuiet);
this.heldQuiet = setTimeout(() => this.releaseCalls(), HEARD_QUIET_MS);
@@ -326,6 +344,7 @@ class GeminiLiveSession implements FishAgentSession {
const tool = this.options.clientTools[name];
const answer = tool ? tool(call.args ?? {}, { callId: id }) : Promise.resolve(`There is no tool named ${name}.`);
void answer.then((result) => {
+ if (this.cancelledCalls.has(id)) return;
const text = String(result);
this.post({ toolResponse: { functionResponses: [{ id, name, response: { result: text, scheduling: "WHEN_IDLE" } }] }, callId: id, text });
}, () => undefined);