Skip to content

Commit 213c051

Browse files
committed
refactor(google): centralize realtime audio queue bounds
1 parent 24e6354 commit 213c051

4 files changed

Lines changed: 97 additions & 49 deletions

File tree

‎extensions/google/index.ts‎

Lines changed: 8 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
} from "./generation-provider-metadata.js";
2121
import { geminiMemoryEmbeddingProviderAdapter } from "./memory-embedding-adapter.js";
2222
import { registerGoogleProvider } from "./provider-registration.js";
23+
import { createGoogleRealtimeAudioQueue } from "./realtime-audio-queue.js";
2324
import { buildGoogleSpeechProvider } from "./speech-provider.js";
2425
import { createGeminiWebSearchProvider } from "./src/gemini-web-search-provider.js";
2526

@@ -201,8 +202,6 @@ function resolveGoogleRealtimeEnvApiKey(): string | undefined {
201202
);
202203
}
203204

204-
const GOOGLE_REALTIME_LAZY_MAX_PENDING_AUDIO_CHUNKS = 320;
205-
const GOOGLE_REALTIME_LAZY_MAX_PENDING_AUDIO_BYTES = 1024 * 1024;
206205
const GOOGLE_REALTIME_LAZY_MAX_PENDING_USER_MESSAGES = 128;
207206
const GOOGLE_REALTIME_LAZY_MAX_PENDING_USER_MESSAGE_BYTES = 256 * 1024;
208207

@@ -219,14 +218,10 @@ function createLazyGoogleRealtimeVoiceBridge(
219218
let providerTerminated = false;
220219
let latestMediaTimestamp: number | undefined;
221220
let pendingGreeting: string | undefined;
222-
const pendingAudio: Buffer[] = [];
223-
let pendingAudioBytes = 0;
221+
// Lazy startup keeps the newest microphone tail when loading stalls.
222+
const pendingAudio = createGoogleRealtimeAudioQueue("drop-oldest");
224223
const pendingUserMessages: string[] = [];
225224
let pendingUserMessageBytes = 0;
226-
const clearPendingAudio = () => {
227-
pendingAudio.length = 0;
228-
pendingAudioBytes = 0;
229-
};
230225
// Loading and connecting finish on separate async boundaries. Keep close ownership
231226
// here so either late completion closes the provider bridge exactly once.
232227
const closeBridge = (loadedBridge = bridge) => {
@@ -257,7 +252,7 @@ function createLazyGoogleRealtimeVoiceBridge(
257252
onClose: (reason) => {
258253
bridgeReady = false;
259254
providerTerminated = true;
260-
clearPendingAudio();
255+
pendingAudio.clear();
261256
req.onClose?.(reason);
262257
},
263258
}),
@@ -282,9 +277,7 @@ function createLazyGoogleRealtimeVoiceBridge(
282277
if (typeof latestMediaTimestamp === "number") {
283278
loadedBridge.setMediaTimestamp(latestMediaTimestamp);
284279
}
285-
const audioChunks = pendingAudio.splice(0);
286-
pendingAudioBytes = 0;
287-
for (const audio of audioChunks) {
280+
for (const audio of pendingAudio.drain()) {
288281
loadedBridge.sendAudio(audio);
289282
}
290283
const userMessages = pendingUserMessages.splice(0);
@@ -315,7 +308,7 @@ function createLazyGoogleRealtimeVoiceBridge(
315308
} catch (error) {
316309
bridgeReady = false;
317310
providerTerminated = true;
318-
clearPendingAudio();
311+
pendingAudio.clear();
319312
throw error;
320313
}
321314
if (closed) {
@@ -330,22 +323,7 @@ function createLazyGoogleRealtimeVoiceBridge(
330323
bridge.sendAudio(audio);
331324
return;
332325
}
333-
if (audio.byteLength > GOOGLE_REALTIME_LAZY_MAX_PENDING_AUDIO_BYTES) {
334-
return;
335-
}
336-
const queuedAudio = Buffer.from(audio);
337-
while (
338-
pendingAudio.length >= GOOGLE_REALTIME_LAZY_MAX_PENDING_AUDIO_CHUNKS ||
339-
pendingAudioBytes + queuedAudio.byteLength > GOOGLE_REALTIME_LAZY_MAX_PENDING_AUDIO_BYTES
340-
) {
341-
const droppedAudio = pendingAudio.shift();
342-
if (!droppedAudio) {
343-
return;
344-
}
345-
pendingAudioBytes -= droppedAudio.byteLength;
346-
}
347-
pendingAudio.push(queuedAudio);
348-
pendingAudioBytes += queuedAudio.byteLength;
326+
pendingAudio.enqueue(audio);
349327
},
350328
setMediaTimestamp: (ts) => {
351329
if (closed) {
@@ -393,7 +371,7 @@ function createLazyGoogleRealtimeVoiceBridge(
393371
closed = true;
394372
bridgeReady = false;
395373
providerTerminated = true;
396-
clearPendingAudio();
374+
pendingAudio.clear();
397375
pendingUserMessages.length = 0;
398376
pendingUserMessageBytes = 0;
399377
pendingGreeting = undefined;
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { describe, expect, it } from "vitest";
2+
import { createGoogleRealtimeAudioQueue } from "./realtime-audio-queue.js";
3+
4+
describe("Google realtime audio queue", () => {
5+
it("rejects newest audio without retaining caller-owned buffers", () => {
6+
const queue = createGoogleRealtimeAudioQueue("reject-newest");
7+
const backing = Buffer.alloc(2 * 1024 * 1024, 0x01);
8+
const retainedView = backing.subarray(0, 512 * 1024);
9+
10+
expect(queue.enqueue(retainedView)).toBe(true);
11+
retainedView.fill(0);
12+
expect(queue.enqueue(Buffer.alloc(512 * 1024, 0x02))).toBe(true);
13+
expect(queue.enqueue(Buffer.from([0x03]))).toBe(false);
14+
15+
expect(queue.drain()).toEqual([Buffer.alloc(512 * 1024, 0x01), Buffer.alloc(512 * 1024, 0x02)]);
16+
});
17+
18+
it("drops oldest audio and resets accounting on clear", () => {
19+
const queue = createGoogleRealtimeAudioQueue("drop-oldest");
20+
for (let index = 0; index < 322; index += 1) {
21+
expect(queue.enqueue(Buffer.from([index & 0xff]))).toBe(true);
22+
}
23+
24+
const drained = queue.drain();
25+
expect(drained).toHaveLength(320);
26+
expect(drained[0]).toEqual(Buffer.from([2]));
27+
expect(drained.at(-1)).toEqual(Buffer.from([65]));
28+
29+
expect(queue.enqueue(Buffer.alloc(1024 * 1024, 0x04))).toBe(true);
30+
queue.clear();
31+
expect(queue.enqueue(Buffer.from([0x05]))).toBe(true);
32+
expect(queue.drain()).toEqual([Buffer.from([0x05])]);
33+
});
34+
});
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const GOOGLE_REALTIME_MAX_PENDING_AUDIO_CHUNKS = 320;
2+
const GOOGLE_REALTIME_MAX_PENDING_AUDIO_BYTES = 1024 * 1024;
3+
4+
export type GoogleRealtimeAudioOverflowPolicy = "drop-oldest" | "reject-newest";
5+
6+
export function createGoogleRealtimeAudioQueue(overflowPolicy: GoogleRealtimeAudioOverflowPolicy) {
7+
let chunks: Buffer[] = [];
8+
let bytes = 0;
9+
10+
const clear = () => {
11+
chunks = [];
12+
bytes = 0;
13+
};
14+
15+
return {
16+
clear,
17+
drain: (): Buffer[] => {
18+
const drained = chunks;
19+
clear();
20+
return drained;
21+
},
22+
enqueue: (audio: Buffer): boolean => {
23+
if (audio.byteLength > GOOGLE_REALTIME_MAX_PENDING_AUDIO_BYTES) {
24+
return false;
25+
}
26+
const chunk = Buffer.from(audio);
27+
if (
28+
overflowPolicy === "reject-newest" &&
29+
(chunks.length >= GOOGLE_REALTIME_MAX_PENDING_AUDIO_CHUNKS ||
30+
bytes + chunk.byteLength > GOOGLE_REALTIME_MAX_PENDING_AUDIO_BYTES)
31+
) {
32+
return false;
33+
}
34+
while (
35+
chunks.length >= GOOGLE_REALTIME_MAX_PENDING_AUDIO_CHUNKS ||
36+
bytes + chunk.byteLength > GOOGLE_REALTIME_MAX_PENDING_AUDIO_BYTES
37+
) {
38+
const dropped = chunks.shift();
39+
if (!dropped) {
40+
return false;
41+
}
42+
bytes -= dropped.byteLength;
43+
}
44+
chunks.push(chunk);
45+
bytes += chunk.byteLength;
46+
return true;
47+
},
48+
};
49+
}

‎extensions/google/realtime-voice-provider.ts‎

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import {
5252
normalizeOptionalString,
5353
} from "openclaw/plugin-sdk/string-coerce-runtime";
5454
import { createGoogleGenAI } from "./google-genai-runtime.js";
55+
import { createGoogleRealtimeAudioQueue } from "./realtime-audio-queue.js";
5556
import { resolveGoogleGemini3ThinkingLevel } from "./thinking.js";
5657

5758
const GOOGLE_REALTIME_DEFAULT_MODEL = "gemini-3.1-flash-live-preview";
@@ -61,8 +62,6 @@ const GOOGLE_REALTIME_INPUT_SAMPLE_RATE = 16_000;
6162
const GOOGLE_REALTIME_BROWSER_API_VERSION = "v1alpha";
6263
const GOOGLE_REALTIME_BROWSER_WEBSOCKET_URL =
6364
"wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained";
64-
const MAX_PENDING_AUDIO_CHUNKS = 320;
65-
const MAX_PENDING_AUDIO_BYTES = 1024 * 1024;
6665
const DEFAULT_AUDIO_STREAM_END_SILENCE_MS = 500;
6766
const GOOGLE_REALTIME_BROWSER_SESSION_TTL_MS = 30 * 60 * 1000;
6867
const GOOGLE_REALTIME_BROWSER_NEW_SESSION_TTL_MS = 60 * 1000;
@@ -472,8 +471,8 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
472471
private setupCompleteReceived = false;
473472
private sessionConfigured = false;
474473
private intentionallyClosed = false;
475-
private pendingAudio: Buffer[] = [];
476-
private pendingAudioBytes = 0;
474+
// Native reconnect keeps the already accepted FIFO prefix stable.
475+
private readonly pendingAudio = createGoogleRealtimeAudioQueue("reject-newest");
477476
private sessionReadyFired = false;
478477
private consecutiveSilenceMs = 0;
479478
private audioStreamEnded = false;
@@ -647,15 +646,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
647646
return;
648647
}
649648
if (!this.session || !this.connected || !this.sessionConfigured) {
650-
if (
651-
this.pendingAudio.length >= MAX_PENDING_AUDIO_CHUNKS ||
652-
this.pendingAudioBytes + audio.byteLength > MAX_PENDING_AUDIO_BYTES
653-
) {
654-
return;
655-
}
656-
const queuedAudio = Buffer.from(audio);
657-
this.pendingAudio.push(queuedAudio);
658-
this.pendingAudioBytes += queuedAudio.byteLength;
649+
this.pendingAudio.enqueue(audio);
659650
return;
660651
}
661652
const silent = this.isSilence(audio);
@@ -888,10 +879,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
888879
}
889880
this.sessionConfigured = true;
890881
this.reconnectAttempts = 0;
891-
const pendingAudio = this.pendingAudio;
892-
this.pendingAudio = [];
893-
this.pendingAudioBytes = 0;
894-
for (const chunk of pendingAudio) {
882+
for (const chunk of this.pendingAudio.drain()) {
895883
this.sendAudio(chunk);
896884
}
897885
if (!this.sessionReadyFired) {
@@ -1035,8 +1023,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
10351023
}
10361024

10371025
private clearPendingAudio(): void {
1038-
this.pendingAudio = [];
1039-
this.pendingAudioBytes = 0;
1026+
this.pendingAudio.clear();
10401027
}
10411028

10421029
private cancelConnectAttempt(attempt: GoogleLiveConnectionAttempt | undefined): void {

0 commit comments

Comments
 (0)