Skip to content

Commit 4248e95

Browse files
committed
fix: end failed voice calls and preserve Gemini Live transcripts
1 parent 00f8d76 commit 4248e95

31 files changed

Lines changed: 1416 additions & 387 deletions

‎docs/nodes/talk.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ their current ephemeral-token and WebRTC data-channel flow.
3838

3939
Finalized realtime user and assistant utterances are always appended live to the active agent session, so later chat and voice turns share one history. Client-owned transports report their finalized transcripts with stable entry ids; Gateway relay and Gateway-controlled WebRTC sessions append the same events server-side. Provider sessions also receive the bounded realtime profile context used by Discord voice.
4040

41+
Google Live saves complete utterances during the call, including Gemini 3.1
42+
transcriptions that omit an explicit transcription-finished flag. Partial text
43+
stays provisional until the provider's completion boundary.
44+
4145
Voice-originated consult runs require a new, exact spoken confirmation before high-impact actions such as sending messages, controlling nodes, browser/computer actions, service changes, destructive shell commands, or publication. The gate applies to runs started through `talk.client.toolCall`, the Gateway relay, and GPT-Live sideband delegations. The confirmation applies only to the canonical final execution arguments and is consumed once; if a policy or hook rewrites the approved action, OpenClaw blocks it until the rewritten action is confirmed. Unrelated concurrent runs remain unaffected. When a call closes, OpenClaw can send a compact **Voice call changes** digest for mutating tools to the session's last non-WebChat delivery target.
4246

4347
Transcription-only Talk emits the same Talk event envelope as realtime and STT/TTS sessions, but uses `mode: "transcription"` and `brain: "none"`. All Talk sessions broadcast events on the `talk.event` channel; clients subscribe to it for partial/final transcript updates (`transcript.delta`/`transcript.done`) and other session telemetry.
@@ -50,6 +54,11 @@ browser at up to one frame per second, while `describe_view` reports the
5054
camera-stream state. In both cases, camera frames bypass the Gateway, and
5155
stopping Talk releases the camera and microphone tracks.
5256

57+
If the microphone disconnects or its permission is revoked, browser Talk ends
58+
the call and shows an error. Choose an available **Microphone input**, restore
59+
permission if needed, and start Talk again. An unexpected GPT-Live connection
60+
loss also ends the call with an error; automatic reconnection is not supported.
61+
5362
## Behavior (macOS)
5463

5564
- Always-on overlay while Talk mode is enabled.

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

Lines changed: 59 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -763,7 +763,10 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
763763
const provider = buildGoogleRealtimeVoiceProvider();
764764
const onTranscript = vi.fn();
765765
const bridge = provider.createBridge({
766-
providerConfig: { apiKey: "gemini-key" },
766+
providerConfig: {
767+
model: "gemini-2.5-flash-native-audio-preview-12-2025",
768+
apiKey: "gemini-key",
769+
},
767770
onAudio: vi.fn(),
768771
onClearAudio: vi.fn(),
769772
onTranscript,
@@ -971,7 +974,10 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
971974
const onEvent = vi.fn();
972975
const onTranscript = vi.fn();
973976
const bridge = provider.createBridge({
974-
providerConfig: { apiKey: "gemini-key" },
977+
providerConfig: {
978+
model: "gemini-2.5-flash-native-audio-preview-12-2025",
979+
apiKey: "gemini-key",
980+
},
975981
onAudio: vi.fn(),
976982
onClearAudio: vi.fn(),
977983
onEvent,
@@ -1010,7 +1016,11 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
10101016
const provider = buildGoogleRealtimeVoiceProvider();
10111017
const onTranscript = vi.fn();
10121018
const bridge = provider.createBridge({
1013-
providerConfig: { apiKey: "gemini-key", sessionResumption: false },
1019+
providerConfig: {
1020+
model: "gemini-2.5-flash-native-audio-preview-12-2025",
1021+
apiKey: "gemini-key",
1022+
sessionResumption: false,
1023+
},
10141024
onAudio: vi.fn(),
10151025
onClearAudio: vi.fn(),
10161026
onTranscript,
@@ -1041,7 +1051,10 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
10411051
const onEvent = vi.fn();
10421052
const onTranscript = vi.fn();
10431053
const bridge = provider.createBridge({
1044-
providerConfig: { apiKey: "gemini-key" },
1054+
providerConfig: {
1055+
model: "gemini-2.5-flash-native-audio-preview-12-2025",
1056+
apiKey: "gemini-key",
1057+
},
10451058
onAudio: vi.fn(),
10461059
onClearAudio: vi.fn(),
10471060
onClose,
@@ -1110,7 +1123,10 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
11101123
it("does not finalize or merge a hypothesis across a fresh automatic reconnect", async () => {
11111124
vi.useFakeTimers();
11121125
const onTranscript = vi.fn();
1113-
const bridge = createGoogleLiveBridge({ onTranscript });
1126+
const bridge = createGoogleLiveBridge({
1127+
providerConfig: { model: "gemini-2.5-flash-native-audio-preview-12-2025" },
1128+
onTranscript,
1129+
});
11141130

11151131
await bridge.connect();
11161132
const firstSession = lastConnectParams().callbacks;
@@ -1144,7 +1160,6 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
11441160
sessionResumptionUpdate: { resumable: true, newHandle: "resume-1" },
11451161
serverContent: {
11461162
outputTranscription: { text: "Before " },
1147-
turnComplete: true,
11481163
},
11491164
});
11501165
await vi.advanceTimersByTimeAsync(500);
@@ -1164,7 +1179,11 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
11641179
vi.useFakeTimers();
11651180
const onClose = vi.fn();
11661181
const onTranscript = vi.fn();
1167-
const bridge = createGoogleLiveBridge({ onClose, onTranscript });
1182+
const bridge = createGoogleLiveBridge({
1183+
providerConfig: { model: "gemini-2.5-flash-native-audio-preview-12-2025" },
1184+
onClose,
1185+
onTranscript,
1186+
});
11681187

11691188
await bridge.connect();
11701189
const firstSession = lastConnectParams().callbacks;
@@ -1231,7 +1250,11 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
12311250
const onReady = vi.fn();
12321251
const onTranscript = vi.fn();
12331252
const bridge = provider.createBridge({
1234-
providerConfig: { apiKey: "gemini-key", sessionResumption: false },
1253+
providerConfig: {
1254+
model: "gemini-2.5-flash-native-audio-preview-12-2025",
1255+
apiKey: "gemini-key",
1256+
sessionResumption: false,
1257+
},
12351258
onAudio: vi.fn(),
12361259
onClearAudio: vi.fn(),
12371260
onEvent,
@@ -1772,7 +1795,10 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
17721795

17731796
it("honors a finish-only transcription message", async () => {
17741797
const onTranscript = vi.fn();
1775-
const bridge = createGoogleLiveBridge({ onTranscript });
1798+
const bridge = createGoogleLiveBridge({
1799+
providerConfig: { model: "gemini-2.5-flash-native-audio-preview-12-2025" },
1800+
onTranscript,
1801+
});
17761802

17771803
await bridge.connect();
17781804
const onmessage = lastConnectParams().callbacks.onmessage;
@@ -1789,7 +1815,10 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
17891815
const provider = buildGoogleRealtimeVoiceProvider();
17901816
const onTranscript = vi.fn();
17911817
const bridge = provider.createBridge({
1792-
providerConfig: { apiKey: "gemini-key" },
1818+
providerConfig: {
1819+
model: "gemini-2.5-flash-native-audio-preview-12-2025",
1820+
apiKey: "gemini-key",
1821+
},
17931822
onAudio: vi.fn(),
17941823
onClearAudio: vi.fn(),
17951824
onTranscript,
@@ -1826,7 +1855,10 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
18261855
const onClose = vi.fn();
18271856
const onTranscript = vi.fn();
18281857
const bridge = provider.createBridge({
1829-
providerConfig: { apiKey: "gemini-key" },
1858+
providerConfig: {
1859+
model: "gemini-2.5-flash-native-audio-preview-12-2025",
1860+
apiKey: "gemini-key",
1861+
},
18301862
onAudio: vi.fn(),
18311863
onClearAudio: vi.fn(),
18321864
onError,
@@ -1864,9 +1896,12 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
18641896
);
18651897
});
18661898

1867-
it("retains unordered transcript chunks until a protocol terminal or close", async () => {
1899+
it("finalizes assistant turns without finalizing independently ordered 2.5 input", async () => {
18681900
const onTranscript = vi.fn();
1869-
const bridge = createGoogleLiveBridge({ onTranscript });
1901+
const bridge = createGoogleLiveBridge({
1902+
providerConfig: { model: "gemini-2.5-flash-native-audio-preview-12-2025" },
1903+
onTranscript,
1904+
});
18701905

18711906
await bridge.connect();
18721907
const onmessage = lastConnectParams().callbacks.onmessage;
@@ -1882,18 +1917,25 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
18821917
},
18831918
});
18841919

1885-
expect(onTranscript.mock.calls.filter((call) => call[2] === true)).toEqual([]);
1920+
expect(onTranscript.mock.calls.filter((call) => call[2] === true)).toEqual([
1921+
["assistant", "Interrupted response", true],
1922+
["assistant", "ending", true],
1923+
]);
18861924

18871925
bridge.close();
18881926
expect(onTranscript.mock.calls.filter((call) => call[2] === true)).toEqual([
1927+
["assistant", "Interrupted response", true],
1928+
["assistant", "ending", true],
18891929
["user", "Earlier question. New question", true],
1890-
["assistant", "Interrupted response ending", true],
18911930
]);
18921931
});
18931932

18941933
it("flushes pending transcripts when the bridge closes", async () => {
18951934
const onTranscript = vi.fn();
1896-
const bridge = createGoogleLiveBridge({ onTranscript });
1935+
const bridge = createGoogleLiveBridge({
1936+
providerConfig: { model: "gemini-2.5-flash-native-audio-preview-12-2025" },
1937+
onTranscript,
1938+
});
18971939

18981940
await bridge.connect();
18991941
lastConnectParams().callbacks.onmessage({
@@ -1908,6 +1950,7 @@ describe("buildGoogleRealtimeVoiceProvider", () => {
19081950
const callbackError = new Error("transcript persistence failed");
19091951
const onError = vi.fn();
19101952
const bridge = createGoogleLiveBridge({
1953+
providerConfig: { model: "gemini-2.5-flash-native-audio-preview-12-2025" },
19111954
onError,
19121955
onTranscript: vi.fn((_role, _text, isFinal) => {
19131956
if (isFinal) {

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

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
495495
private connectionOwner: GoogleLiveConnectionAttempt | undefined;
496496
private connectAttempt: GoogleLiveConnectionAttempt | undefined;
497497
// Google can interleave independent input/output transcripts, so each role
498-
// owns its own in-progress byte budget until `finished` or terminal cleanup.
498+
// owns its own in-progress byte budget until its protocol boundary or cleanup.
499499
private readonly pendingTranscripts: Record<RealtimeVoiceRole, GoogleLiveTranscriptAccumulator> =
500500
{
501501
user: { text: "", byteCount: 0 },
@@ -941,8 +941,12 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
941941
}
942942

943943
private handleServerContent(content: LiveServerContent): void {
944+
const owner = this.connectionOwner;
944945
if (content.interrupted) {
945946
this.config.onClearAudio("barge-in");
947+
if (this.connectionOwner !== owner) {
948+
return;
949+
}
946950
}
947951

948952
if (content.inputTranscription) {
@@ -971,14 +975,28 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
971975
const audio = this.toOutputAudio(pcm, sampleRate);
972976
if (audio.length > 0) {
973977
this.config.onAudio(audio);
978+
if (this.connectionOwner !== owner) {
979+
return;
980+
}
974981
this.config.onMark?.(`audio-${randomUUID()}`);
982+
if (this.connectionOwner !== owner) {
983+
return;
984+
}
975985
}
976986
continue;
977987
}
978988
}
989+
// Output transcription precedes these model boundaries; input transcription
990+
// is independently ordered and must not be finalized by an assistant turn.
991+
if (content.generationComplete || content.interrupted || content.turnComplete) {
992+
this.flushPendingTranscript("assistant");
993+
}
979994
}
980995

981996
private appendTranscript(role: RealtimeVoiceRole, transcript: GoogleLiveTranscription): boolean {
997+
const owner = this.connectionOwner;
998+
// Live 3.1 emits complete input utterances without the optional finished flag.
999+
const completeInput = role === "user" && isGemini31LiveModel(this.model);
9821000
const text = transcript.text;
9831001
if (text) {
9841002
const pending = this.pendingTranscripts[role];
@@ -990,14 +1008,17 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
9901008
}
9911009
pending.text += text;
9921010
pending.byteCount += textBytes;
993-
this.emitTranscript(role, text, false);
1011+
if (!completeInput) {
1012+
this.emitTranscript(role, text, false);
1013+
if (this.connectionOwner !== owner) {
1014+
return false;
1015+
}
1016+
}
9941017
}
995-
// turnComplete belongs to model generation and is unordered with transcription.
996-
// Finalize only on the protocol terminal or when the bridge permanently closes.
997-
if (transcript.finished) {
1018+
if (transcript.finished || completeInput) {
9981019
this.flushPendingTranscript(role);
9991020
}
1000-
return true;
1021+
return this.connectionOwner === owner;
10011022
}
10021023

10031024
private flushPendingTranscript(role: RealtimeVoiceRole): void {
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import {
2+
LiveServerMessage,
3+
type LiveConnectParameters,
4+
type LiveServerContent,
5+
} from "@google/genai";
6+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7+
import { buildGoogleRealtimeVoiceProvider } from "./realtime-voice-provider.js";
8+
9+
const { connect, close: closeMock } = vi.hoisted(() => {
10+
const closeSession = vi.fn();
11+
return {
12+
close: closeSession,
13+
connect: vi.fn(async (_params: LiveConnectParameters) => ({ close: closeSession })),
14+
};
15+
});
16+
vi.mock("./google-genai-runtime.js", () => ({
17+
createGoogleGenAI: () => ({ live: { connect } }),
18+
}));
19+
20+
function emitContent(serverContent: LiveServerContent): void {
21+
const params = connect.mock.calls.at(-1)?.[0];
22+
if (!params) {
23+
throw new Error("Expected Google Live connection");
24+
}
25+
params.callbacks.onmessage(Object.assign(new LiveServerMessage(), { serverContent }));
26+
}
27+
28+
describe("Google Live transcript finality", () => {
29+
beforeEach(() => {
30+
connect.mockImplementation(async ({ callbacks }: LiveConnectParameters) => {
31+
callbacks.onopen?.();
32+
callbacks.onmessage(Object.assign(new LiveServerMessage(), { setupComplete: {} }));
33+
return { close: closeMock };
34+
});
35+
});
36+
afterEach(() => {
37+
vi.clearAllMocks();
38+
});
39+
40+
it("finalizes each live 3.1 spoken turn when finished is absent", async () => {
41+
const onTranscript = vi.fn();
42+
const bridge = buildGoogleRealtimeVoiceProvider().createBridge({
43+
providerConfig: { apiKey: "test-key" },
44+
onAudio: vi.fn(),
45+
onClearAudio: vi.fn(),
46+
onTranscript,
47+
});
48+
await bridge.connect();
49+
for (const [input, output] of [
50+
["Please reply with the single word glacier.", "Glacier."],
51+
["Now reply with the single word crystal.", "Crystal."],
52+
]) {
53+
emitContent({ inputTranscription: { text: input } });
54+
emitContent({ outputTranscription: { text: output } });
55+
emitContent({ generationComplete: true });
56+
emitContent({ turnComplete: true });
57+
}
58+
expect(onTranscript.mock.calls.filter((call) => call[2])).toEqual([
59+
["user", "Please reply with the single word glacier.", true],
60+
["assistant", "Glacier.", true],
61+
["user", "Now reply with the single word crystal.", true],
62+
["assistant", "Crystal.", true],
63+
]);
64+
bridge.close();
65+
expect(onTranscript.mock.calls.filter((call) => call[2])).toHaveLength(4);
66+
});
67+
68+
it("stops delivering the frame when a final transcript callback closes the bridge", async () => {
69+
const onAudio = vi.fn();
70+
const onMark = vi.fn();
71+
const onTranscript = vi.fn(() => bridge.close());
72+
const bridge = buildGoogleRealtimeVoiceProvider().createBridge({
73+
providerConfig: { apiKey: "test-key" },
74+
onAudio,
75+
onMark,
76+
onClearAudio: vi.fn(),
77+
onTranscript,
78+
});
79+
await bridge.connect();
80+
emitContent({
81+
inputTranscription: { text: "Stop" },
82+
outputTranscription: { text: "No further transcript" },
83+
modelTurn: {
84+
parts: [{ inlineData: { data: "AAAAAA==", mimeType: "audio/pcm;rate=24000" } }],
85+
},
86+
turnComplete: true,
87+
});
88+
expect(onTranscript.mock.calls).toEqual([["user", "Stop", true]]);
89+
expect(onAudio).not.toHaveBeenCalled();
90+
expect(onMark).not.toHaveBeenCalled();
91+
expect(closeMock).toHaveBeenCalledOnce();
92+
});
93+
});

0 commit comments

Comments
 (0)