Skip to content

Commit 53d2279

Browse files
committed
fix(google): bound native realtime audio queue
1 parent b82dd01 commit 53d2279

2 files changed

Lines changed: 128 additions & 5 deletions

File tree

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

Lines changed: 104 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// Google tests cover realtime voice provider plugin behavior.
2-
import { REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ } from "openclaw/plugin-sdk/realtime-voice";
2+
import {
3+
REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
4+
resamplePcm,
5+
} from "openclaw/plugin-sdk/realtime-voice";
36
import type { RealtimeVoiceTool } from "openclaw/plugin-sdk/realtime-voice";
47
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
58
import { buildGoogleRealtimeVoiceProvider } from "./realtime-voice-provider.js";
@@ -1213,6 +1216,106 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
12131216
expect(connectedSession.sendRealtimeInput).toHaveBeenCalledTimes(1);
12141217
});
12151218

1219+
it("copies and bounds pending audio by aggregate bytes before activation", async () => {
1220+
const connectedSession = createMockGoogleLiveSession();
1221+
connectMock.mockResolvedValueOnce(connectedSession);
1222+
const provider = buildGoogleRealtimeVoiceProvider();
1223+
const bridge = provider.createBridge({
1224+
providerConfig: { apiKey: "gemini-key" },
1225+
audioFormat: REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
1226+
onAudio: vi.fn(),
1227+
onClearAudio: vi.fn(),
1228+
});
1229+
const backing = Buffer.alloc(2 * 1024 * 1024);
1230+
const firstChunk = backing.subarray(0, 512 * 1024);
1231+
firstChunk.writeInt16LE(513);
1232+
const expectedFirstSample = resamplePcm(Buffer.from(firstChunk), 24_000, 16_000).readInt16LE(0);
1233+
1234+
bridge.sendAudio(firstChunk);
1235+
bridge.sendAudio(Buffer.alloc(512 * 1024, 0x7f));
1236+
bridge.sendAudio(Buffer.from([0x01]));
1237+
firstChunk.fill(0);
1238+
1239+
await bridge.connect();
1240+
lastConnectParams().callbacks.onopen();
1241+
lastConnectParams().callbacks.onmessage({ setupComplete: { sessionId: "session-1" } });
1242+
1243+
expect(connectedSession.sendRealtimeInput).toHaveBeenCalledTimes(2);
1244+
const firstAudio = connectedSession.sendRealtimeInput.mock.calls[0]?.[0]?.audio as
1245+
| { data?: unknown }
1246+
| undefined;
1247+
expect(Buffer.from(String(firstAudio?.data), "base64").readInt16LE(0)).toBe(
1248+
expectedFirstSample,
1249+
);
1250+
});
1251+
1252+
it("bounds pending audio by chunk count before activation", async () => {
1253+
const connectedSession = createMockGoogleLiveSession();
1254+
connectMock.mockResolvedValueOnce(connectedSession);
1255+
const provider = buildGoogleRealtimeVoiceProvider();
1256+
const bridge = provider.createBridge({
1257+
providerConfig: { apiKey: "gemini-key" },
1258+
audioFormat: REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
1259+
onAudio: vi.fn(),
1260+
onClearAudio: vi.fn(),
1261+
});
1262+
1263+
for (let index = 0; index < 321; index += 1) {
1264+
bridge.sendAudio(Buffer.alloc(2, index & 0xff));
1265+
}
1266+
1267+
await bridge.connect();
1268+
lastConnectParams().callbacks.onopen();
1269+
lastConnectParams().callbacks.onmessage({ setupComplete: { sessionId: "session-1" } });
1270+
1271+
expect(connectedSession.sendRealtimeInput).toHaveBeenCalledTimes(320);
1272+
});
1273+
1274+
it("drops reconnect audio on terminal exhaustion until an explicit reconnect owns admission", async () => {
1275+
vi.useFakeTimers();
1276+
const reconnectedSession = createMockGoogleLiveSession();
1277+
const provider = buildGoogleRealtimeVoiceProvider();
1278+
const onClose = vi.fn();
1279+
const bridge = provider.createBridge({
1280+
providerConfig: { apiKey: "gemini-key" },
1281+
audioFormat: REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
1282+
onAudio: vi.fn(),
1283+
onClearAudio: vi.fn(),
1284+
onClose,
1285+
});
1286+
1287+
await bridge.connect();
1288+
const firstSession = lastConnectParams().callbacks;
1289+
firstSession.onopen();
1290+
firstSession.onmessage({ setupComplete: { sessionId: "session-1" } });
1291+
connectMock
1292+
.mockRejectedValueOnce(new Error("connect failed 1"))
1293+
.mockRejectedValueOnce(new Error("connect failed 2"))
1294+
.mockRejectedValueOnce(new Error("connect failed 3"))
1295+
.mockResolvedValueOnce(reconnectedSession);
1296+
firstSession.onclose({ code: 1011, reason: "temporary" });
1297+
bridge.sendAudio(Buffer.from([0x01, 0x00]));
1298+
1299+
await vi.advanceTimersByTimeAsync(1_750);
1300+
bridge.sendAudio(Buffer.from([0x02, 0x00]));
1301+
1302+
expect(onClose).toHaveBeenCalledOnce();
1303+
expect(onClose).toHaveBeenCalledWith("error");
1304+
1305+
await bridge.connect();
1306+
const reconnected = lastConnectParams().callbacks;
1307+
reconnected.onopen();
1308+
reconnected.onmessage({ setupComplete: { sessionId: "session-2" } });
1309+
bridge.sendAudio(Buffer.alloc(480, 0x03));
1310+
1311+
expect(reconnectedSession.sendRealtimeInput).toHaveBeenCalledOnce();
1312+
const sent = reconnectedSession.sendRealtimeInput.mock.calls[0]?.[0]?.audio as
1313+
| { data?: unknown }
1314+
| undefined;
1315+
expect(sent?.data).toBeTypeOf("string");
1316+
bridge.close();
1317+
});
1318+
12161319
it("does not activate a late session after close during setup", async () => {
12171320
const pendingSession = createDeferred<MockGoogleLiveSession>();
12181321
const lateSession = createMockGoogleLiveSession();

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

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ const GOOGLE_REALTIME_BROWSER_API_VERSION = "v1alpha";
6262
const GOOGLE_REALTIME_BROWSER_WEBSOCKET_URL =
6363
"wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained";
6464
const MAX_PENDING_AUDIO_CHUNKS = 320;
65+
const MAX_PENDING_AUDIO_BYTES = 1024 * 1024;
6566
const DEFAULT_AUDIO_STREAM_END_SILENCE_MS = 500;
6667
const GOOGLE_REALTIME_BROWSER_SESSION_TTL_MS = 30 * 60 * 1000;
6768
const GOOGLE_REALTIME_BROWSER_NEW_SESSION_TTL_MS = 60 * 1000;
@@ -472,6 +473,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
472473
private sessionConfigured = false;
473474
private intentionallyClosed = false;
474475
private pendingAudio: Buffer[] = [];
476+
private pendingAudioBytes = 0;
475477
private sessionReadyFired = false;
476478
private consecutiveSilenceMs = 0;
477479
private audioStreamEnded = false;
@@ -641,10 +643,19 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
641643
}
642644

643645
sendAudio(audio: Buffer): void {
646+
if (this.terminalError || this.intentionallyClosed || this.closeNotified) {
647+
return;
648+
}
644649
if (!this.session || !this.connected || !this.sessionConfigured) {
645-
if (this.pendingAudio.length < MAX_PENDING_AUDIO_CHUNKS) {
646-
this.pendingAudio.push(audio);
650+
if (
651+
this.pendingAudio.length >= MAX_PENDING_AUDIO_CHUNKS ||
652+
this.pendingAudioBytes + audio.byteLength > MAX_PENDING_AUDIO_BYTES
653+
) {
654+
return;
647655
}
656+
const queuedAudio = Buffer.from(audio);
657+
this.pendingAudio.push(queuedAudio);
658+
this.pendingAudioBytes += queuedAudio.byteLength;
648659
return;
649660
}
650661
const silent = this.isSilence(audio);
@@ -778,7 +789,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
778789
clearTimeout(this.reconnectTimer);
779790
this.reconnectTimer = undefined;
780791
}
781-
this.pendingAudio = [];
792+
this.clearPendingAudio();
782793
this.consecutiveSilenceMs = 0;
783794
this.audioStreamEnded = false;
784795
this.pendingFunctionNames.clear();
@@ -877,7 +888,10 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
877888
}
878889
this.sessionConfigured = true;
879890
this.reconnectAttempts = 0;
880-
for (const chunk of this.pendingAudio.splice(0)) {
891+
const pendingAudio = this.pendingAudio;
892+
this.pendingAudio = [];
893+
this.pendingAudioBytes = 0;
894+
for (const chunk of pendingAudio) {
881895
this.sendAudio(chunk);
882896
}
883897
if (!this.sessionReadyFired) {
@@ -1015,10 +1029,16 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
10151029
if (this.closeNotified) {
10161030
return;
10171031
}
1032+
this.clearPendingAudio();
10181033
this.closeNotified = true;
10191034
this.config.onClose?.(reason);
10201035
}
10211036

1037+
private clearPendingAudio(): void {
1038+
this.pendingAudio = [];
1039+
this.pendingAudioBytes = 0;
1040+
}
1041+
10221042
private cancelConnectAttempt(attempt: GoogleLiveConnectionAttempt | undefined): void {
10231043
if (!attempt) {
10241044
return;

0 commit comments

Comments
 (0)