Skip to content

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

Gemini Live: request before delegation, stale-handle tool answers, no muted audio

Bugfixer 255680228159d
diff --git a/src/lib/live-call-gemini-audio.ts b/src/lib/live-call-gemini-audio.ts
index 38c350291c..ab4338e2c7 100644
--- a/src/lib/live-call-gemini-audio.ts
+++ b/src/lib/live-call-gemini-audio.ts
@@ -7,6 +7,8 @@ const MIC_CHUNK = MIC_RATE / 10;
export interface GeminiAudio {
/** Opens the microphone; rejects as getUserMedia does, e.g. with NotAllowedError. */
startMic(onChunk: (pcm: ArrayBuffer) => void): Promise<void>;
+ /** Drops microphone audio not yet sent as a chunk, e.g. what was captured while muted. */
+ dropMic(): void;
play(pcm: ArrayBuffer): void;
/** Stops what is playing and queued, when the person talks over the agent. */
flush(): void;
@@ -53,6 +55,11 @@ export class MicResampler {
}
return chunks;
}
+
+ /** Forgets the samples not yet sent as a chunk. */
+ drop(): void {
+ this.pending = [];
+ }
}
export function pcm16ToFloat(pcm: ArrayBuffer): Float32Array<ArrayBuffer> {
@@ -66,6 +73,7 @@ export function browserGeminiAudio(): GeminiAudio {
let context: AudioContext | null = new AudioContext();
let stream: MediaStream | null = null;
let node: AudioWorkletNode | null = null;
+ let resampler: MicResampler | null = null;
const playing = new Set<AudioBufferSourceNode>();
let nextAt = 0;
const audio: GeminiAudio = {
@@ -81,11 +89,15 @@ export function browserGeminiAudio(): GeminiAudio {
URL.revokeObjectURL(url);
}
if (!context) return;
- const resampler = new MicResampler(context.sampleRate);
+ const mic = new MicResampler(context.sampleRate);
+ resampler = mic;
node = new AudioWorkletNode(context, "omb-mic");
- node.port.onmessage = (event: MessageEvent<Float32Array>) => resampler.push(event.data).forEach(onChunk);
+ node.port.onmessage = (event: MessageEvent<Float32Array>) => mic.push(event.data).forEach(onChunk);
context.createMediaStreamSource(stream).connect(node);
},
+ dropMic() {
+ resampler?.drop();
+ },
play(pcm) {
if (!context) return;
const samples = pcm16ToFloat(pcm);
diff --git a/src/lib/live-call-gemini.test.ts b/src/lib/live-call-gemini.test.ts
index 291f18ea09..6234f0e849 100644
--- a/src/lib/live-call-gemini.test.ts
+++ b/src/lib/live-call-gemini.test.ts
@@ -37,7 +37,9 @@ class FakeAudio implements GeminiAudio {
flushed = 0;
closed = false;
mic: ((pcm: ArrayBuffer) => void) | null = null;
+ micDropped = 0;
constructor(readonly denied = false) {}
+ dropMic() { this.micDropped += 1; }
async startMic(onChunk: (pcm: ArrayBuffer) => void) {
if (this.denied) throw Object.assign(new Error("denied"), { name: "NotAllowedError" });
this.mic = onChunk;
@@ -184,11 +186,41 @@ describe("a Gemini Live session", () => {
const sent = t.socket().sent.length;
t.audio().mic!(new Int16Array([1]).buffer);
expect(t.socket().sent).toHaveLength(sent);
+ expect(t.audio().micDropped).toBe(0);
await session.setMicMuted(false);
+ expect(t.audio().micDropped, "audio buffered while muted is dropped on unmute").toBe(1);
t.audio().mic!(new Int16Array([1]).buffer);
expect(t.socket().sent).toHaveLength(sent + 1);
});
+ it("hands a delegate call over only after what was heard, when Gemini sends the call first", async () => {
+ vi.useFakeTimers();
+ try {
+ const t = harness();
+ await t.connect();
+ const order: string[] = [];
+ t.callbacks.onUserTranscript.mockImplementation(({ final }: { final: boolean }) => { if (final) order.push("heard"); });
+ t.delegate.mockImplementation(async () => { order.push("delegate"); return "On it."; });
+ t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_1", name: FISH_DELEGATE_TOOL, args: {} }] } });
+ expect(t.delegate).not.toHaveBeenCalled();
+ t.socket().receive({ serverContent: { inputTranscription: { text: "book " } } });
+ t.socket().receive({ serverContent: { inputTranscription: { text: "a table" } } });
+ expect(t.delegate).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(400);
+ expect(order).toEqual(["heard", "delegate"]);
+ expect(t.callbacks.onUserTranscript).toHaveBeenCalledWith({ segmentId: "s0", text: "book a table", final: true });
+ // A call with no words heard at all still goes through.
+ t.socket().receive({ serverContent: { turnComplete: true } });
+ t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_2", name: FISH_DELEGATE_TOOL, args: {} }] } });
+ vi.advanceTimersByTime(1_999);
+ expect(t.delegate).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(1);
+ expect(t.delegate).toHaveBeenCalledTimes(2);
+ } 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();
@@ -211,8 +243,9 @@ describe("a Gemini Live session", () => {
it("keeps tool answers and updates made between connections for the resumed one, in order", async () => {
const t = harness();
const session = await t.connect();
- t.socket().receive({ sessionResumptionUpdate: { newHandle: "h-2", resumable: true } });
+ t.socket().receive({ serverContent: { inputTranscription: { text: "x" } } });
t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_1", name: FISH_DELEGATE_TOOL, args: { request: "x" } }] } });
+ t.socket().receive({ sessionResumptionUpdate: { newHandle: "h-2", resumable: true } });
t.socket().drop(1000);
await settle();
session.sendUserMessage("[OpenMausBot] done", { audio: true });
@@ -222,6 +255,23 @@ describe("a Gemini Live session", () => {
expect(t.socket().sent.slice(1).map((m) => Object.keys(m)[0])).toEqual(["toolResponse", "clientContent"]);
});
+ it("answers a tool call the resumed session never saw as the bot's words, not as a tool response", async () => {
+ const t = harness();
+ await t.connect();
+ t.socket().receive({ sessionResumptionUpdate: { newHandle: "h-2", resumable: true } });
+ t.socket().receive({ serverContent: { inputTranscription: { text: "x" } } });
+ t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_1", name: FISH_DELEGATE_TOOL, args: {} }] } });
+ t.socket().receive({ sessionResumptionUpdate: { resumable: false } });
+ t.socket().drop(1000);
+ t.socket().open();
+ expect(t.socket().sent).toEqual([{ setup: { model: SESSION.model, sessionResumption: { handle: "h-2" } } }]);
+ t.socket().receive({ setupComplete: {} });
+ await settle();
+ expect(t.socket().sent.slice(1)).toEqual([
+ { clientContent: { turns: [{ role: "user", parts: [{ text: "[OpenMausBot] On it." }] }], turnComplete: true } },
+ ]);
+ });
+
it("ends the call when a resumed connection is refused instead of trying again", async () => {
const t = harness();
await t.connect();
diff --git a/src/lib/live-call-gemini.ts b/src/lib/live-call-gemini.ts
index ba2c347ab9..e1fb8c4366 100644
--- a/src/lib/live-call-gemini.ts
+++ b/src/lib/live-call-gemini.ts
@@ -3,11 +3,18 @@
// the setup sent here only names the model and the session to resume.
import type { LiveGeminiSession } from "../../shared/wire";
import { browserGeminiAudio, type GeminiAudio } from "./live-call-gemini-audio";
-import type { FishAgentSession, FishSessionOptions, FishSessionStarter } from "./live-call-fish";
+import { FISH_UPDATE_PREFIX, type FishAgentSession, type FishSessionOptions, type FishSessionStarter } from "./live-call-fish";
const MIC_MIME = "audio/pcm;rate=16000";
/** Gemini ends each connection after about 10 minutes; the call goes on over a new one, this many times at most. */
const MAX_RECONNECTS = 12;
+/** Gemini can call a tool before it sends what it heard; the call waits this long after the last words heard... */
+const HEARD_QUIET_MS = 400;
+/** ...and this long at most, since a call can come without words, e.g. on the bot's update. */
+const HEARD_WAIT_MS = 2_000;
+
+type ToolCall = { id?: string; name?: string; args?: Record<string, unknown> };
+type Outgoing = { toolResponse: unknown; callId: string; text: string } | { clientContent: unknown };
/** The part of the browser WebSocket a call uses. */
export interface GeminiSocket {
@@ -40,7 +47,7 @@ type ServerMessage = {
interrupted?: boolean;
turnComplete?: boolean;
};
- toolCall?: { functionCalls?: Array<{ id?: string; name?: string; args?: Record<string, unknown> }> };
+ toolCall?: { functionCalls?: ToolCall[] };
goAway?: unknown;
sessionResumptionUpdate?: { newHandle?: string; resumable?: boolean };
};
@@ -80,13 +87,23 @@ class GeminiLiveSession implements FishAgentSession {
private linked = false;
/** Tool answers and the bot's words, in order, held while there is no connection or, for words, while the agent speaks:
* client content interrupts what Gemini is saying. */
- private outbox: Array<{ toolResponse: unknown } | { clientContent: unknown }> = [];
+ private outbox: Outgoing[] = [];
+ /** Tool calls made since the last resumption handle: a session resumed with that handle has never seen them. */
+ private callsAfterHandle = new Set<string>();
+ /** Tool calls the session on the current connection does not know; their answers go to Gemini as the bot's words. */
+ private unknownCalls = new Set<string>();
private segment = 0;
private heard = "";
/** What the agent has said this turn: the caption shows the whole turn, Gemini sends it in pieces. */
private said = "";
private speaking = false;
private turnDone = false;
+ /** What the person said for the current turn has been captioned as final. */
+ private heardThisTurn = false;
+ /** Tool calls waiting for what the person said, so the harness gets the request before the delegation. */
+ private heldCalls: ToolCall[] = [];
+ private heldQuiet: ReturnType<typeof setTimeout> | null = null;
+ private heldLimit: ReturnType<typeof setTimeout> | null = null;
constructor(options: FishSessionOptions<LiveGeminiSession>, deps: GeminiSessionDeps) {
this.options = options;
@@ -120,6 +137,8 @@ class GeminiLiveSession implements FishAgentSession {
async setMicMuted(muted: boolean): Promise<void> {
if (muted && !this.muted) this.send({ realtimeInput: { audioStreamEnd: true } });
+ // Audio captured while muted that has not made a whole chunk yet is never sent.
+ if (!muted && this.muted) this.audio?.dropMic();
this.muted = muted;
}
@@ -129,6 +148,7 @@ class GeminiLiveSession implements FishAgentSession {
}
private shut(): void {
+ this.clearHeldTimers();
const socket = this.socket;
this.socket = null;
if (socket) {
@@ -180,6 +200,7 @@ class GeminiLiveSession implements FishAgentSession {
this.reconnects += 1;
this.resumingAfterGoAway = this.wentAway;
this.wentAway = false;
+ this.forgetCallsAfterHandle();
this.connect(() => undefined, () => undefined);
return;
}
@@ -206,6 +227,10 @@ class GeminiLiveSession implements FishAgentSession {
if (heard) {
this.heard += heard;
this.options.callbacks.onUserTranscript({ segmentId: `s${this.segment}`, text: this.heard, final: false });
+ if (this.heldCalls.length) {
+ if (this.heldQuiet) clearTimeout(this.heldQuiet);
+ this.heldQuiet = setTimeout(() => this.releaseCalls(), HEARD_QUIET_MS);
+ }
}
for (const part of content.modelTurn?.parts ?? []) {
if (!part.inlineData?.data || !part.inlineData.mimeType?.startsWith("audio/")) continue;
@@ -225,12 +250,14 @@ class GeminiLiveSession implements FishAgentSession {
}
if (content.interrupted || content.turnComplete) this.said = "";
if (content.interrupted) {
+ this.heardThisTurn = false;
this.audio?.flush();
this.turnDone = true;
this.playbackIdle();
}
if (content.turnComplete) {
this.finishHeard();
+ this.heardThisTurn = false;
this.turnDone = true;
if (this.audio?.idle() !== false) this.playbackIdle();
}
@@ -238,7 +265,10 @@ class GeminiLiveSession implements FishAgentSession {
for (const call of message.toolCall?.functionCalls ?? []) this.onToolCall(call);
if (message.goAway !== undefined) this.wentAway = true;
const update = message.sessionResumptionUpdate;
- if (update?.resumable && typeof update.newHandle === "string" && update.newHandle) this.handle = update.newHandle;
+ if (update?.resumable && typeof update.newHandle === "string" && update.newHandle) {
+ this.handle = update.newHandle;
+ this.callsAfterHandle.clear();
+ }
}
private finishHeard(): void {
@@ -247,6 +277,8 @@ class GeminiLiveSession implements FishAgentSession {
this.heard = "";
this.options.callbacks.onUserTranscript({ segmentId: `s${this.segment}`, text, final: true });
this.segment += 1;
+ this.heardThisTurn = true;
+ this.releaseCalls();
}
private playbackIdle(): void {
@@ -256,33 +288,71 @@ class GeminiLiveSession implements FishAgentSession {
this.flush();
}
- private onToolCall(call: { id?: string; name?: string; args?: Record<string, unknown> }): void {
- // The harness reads the request from what it heard, so that goes first.
+ private onToolCall(call: ToolCall): void {
+ // The harness reads the request from what it heard, so that goes first; Gemini may send it after the call.
+ this.callsAfterHandle.add(call.id ?? "");
+ this.finishHeard();
+ if (this.heardThisTurn && !this.heldCalls.length) return this.runToolCall(call);
+ this.heldCalls.push(call);
+ this.heldLimit ??= setTimeout(() => this.releaseCalls(), HEARD_WAIT_MS);
+ }
+
+ private releaseCalls(): void {
+ if (!this.heldCalls.length) return;
+ const calls = this.heldCalls;
+ this.heldCalls = [];
+ this.clearHeldTimers();
this.finishHeard();
+ calls.forEach((call) => this.runToolCall(call));
+ }
+
+ private clearHeldTimers(): void {
+ if (this.heldQuiet) clearTimeout(this.heldQuiet);
+ if (this.heldLimit) clearTimeout(this.heldLimit);
+ this.heldQuiet = null;
+ this.heldLimit = null;
+ }
+
+ private runToolCall(call: ToolCall): void {
+ if (this.ended) return;
const id = call.id ?? "";
const name = call.name ?? "";
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) => {
- this.post({ toolResponse: { functionResponses: [{ id, name, response: { result: String(result), scheduling: "WHEN_IDLE" } }] } });
+ const text = String(result);
+ this.post({ toolResponse: { functionResponses: [{ id, name, response: { result: text, scheduling: "WHEN_IDLE" } }] }, callId: id, text });
}, () => undefined);
}
+ /** On resuming with a handle older than some tool calls, their answers reach Gemini as the bot's words instead. */
+ private forgetCallsAfterHandle(): void {
+ for (const id of this.callsAfterHandle) this.unknownCalls.add(id);
+ this.callsAfterHandle.clear();
+ this.outbox = this.outbox.map((message) => this.forKnownCall(message));
+ }
+
+ private forKnownCall(message: Outgoing): Outgoing {
+ if (!("toolResponse" in message) || !this.unknownCalls.has(message.callId)) return message;
+ return { clientContent: { turns: [{ role: "user", parts: [{ text: `${FISH_UPDATE_PREFIX} ${message.text}` }] }], turnComplete: true } };
+ }
+
private sendAudio(pcm: ArrayBuffer): void {
if (!this.ready || this.muted) return;
this.send({ realtimeInput: { audio: { mimeType: MIC_MIME, data: encodeBase64(pcm) } } });
}
/** Sent now, or kept for the next connection and, for the bot's words, for when the agent stops speaking. */
- private post(message: { toolResponse: unknown } | { clientContent: unknown }): void {
+ private post(message: Outgoing): void {
if (this.ended) return;
- this.outbox.push(message);
+ this.outbox.push(this.forKnownCall(message));
this.flush();
}
private flush(): void {
while (this.linked && this.socket?.readyState === 1 && this.outbox.length && !(this.speaking && "clientContent" in this.outbox[0])) {
- this.send(this.outbox.shift());
+ const message = this.outbox.shift()!;
+ this.send("toolResponse" in message ? { toolResponse: message.toolResponse } : message);
}
}