Skip to content

Commit e14fbd7

Browse files
committed
fix(discord): retire voice sessions after realtime provider closure
Route terminal provider closure through the existing voice entry teardown owner and resume queued speech after reconnect readiness. Closes #131397.
1 parent b70945a commit e14fbd7

8 files changed

Lines changed: 267 additions & 76 deletions

‎docs/channels/discord.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1273,6 +1273,7 @@ Notes:
12731273
- `voice.followUsers` lets the bot join, move, and leave Discord voice with selected users. See [Follow users in voice](#follow-users-in-voice).
12741274
- `agent-proxy` routes speech through `discord-voice`, which preserves normal owner/tool authorization for the speaker and target session but hides the agent `tts` tool because Discord voice owns playback. By default, `agent-proxy` gives the consult full owner-equivalent tool access for owner speakers (`voice.realtime.toolPolicy: "owner"`) and strongly prefers consulting the OpenClaw agent before substantive answers (`voice.realtime.consultPolicy: "always"`). In that default `always` mode, the realtime layer does not auto-speak filler before the consult answer; it captures and transcribes speech, then speaks the routed OpenClaw answer. If multiple forced consult answers finish while Discord is still playing the first answer, later exact-speech answers are queued until playback idles instead of replacing speech mid-sentence.
12751275
- Realtime voice buffers generated audio when Discord playback temporarily falls behind and tolerates brief provider or network gaps. Normal backpressure does not cancel the response, and queued answers wait until Discord finishes playing the previous answer, even if its provider response or audio encoder has already finished.
1276+
- If the realtime provider ends the session, OpenClaw leaves the voice channel and clears its connected status. Check the `realtime session failed terminally` log, then use `/vc join` to reconnect. Temporary provider reconnects do not end the Discord voice session.
12761277
- In `stt-tts` mode, STT uses `tools.media.audio`; `voice.model` does not affect transcription.
12771278
- `stt-tts` replies remain active until Discord finishes playing them; long responses are not cut off by a fixed one-minute playback deadline.
12781279
- In realtime modes, `voice.realtime.provider`, `voice.realtime.model`, and `voice.realtime.speakerVoice` configure the realtime audio session. For OpenAI Realtime 2.1 plus the Codex brain, use `voice.realtime.model: "gpt-realtime-2.1"` and `voice.model: "openai/gpt-5.6-sol"`.

‎extensions/discord/src/voice/manager.e2e.test-support.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type {
22
RealtimeVoiceBridgeEvent,
3+
RealtimeVoiceBridgeCreateRequest,
34
RealtimeVoiceResponseOutcome,
45
} from "openclaw/plugin-sdk/realtime-voice";
56
import { vi } from "vitest";
@@ -51,6 +52,7 @@ export type TestRealtimeBridgeParams = {
5152
instructions?: string;
5253
interruptResponseOnInputAudio?: boolean;
5354
onEvent?: (event: RealtimeVoiceBridgeEvent) => void;
55+
onClose?: RealtimeVoiceBridgeCreateRequest["onClose"];
5456
onReady?: () => void;
5557
onResponseDone?: (outcome: RealtimeVoiceResponseOutcome) => void;
5658
onToolCall?: (

‎extensions/discord/src/voice/realtime-session.runtime.ts‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,12 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
322322
toolPolicy,
323323
consultPolicy,
324324
});
325+
const onReady = () => {
326+
this.markProviderGenerationObserved();
327+
if (this.markLifecycleReady(lifecycleGeneration)) {
328+
this.playback.drainQueuedExactSpeechMessages("provider-ready");
329+
}
330+
};
325331
this.bridge = this.harness.createBridge({
326332
provider: resolved.provider,
327333
cfg: this.params.cfg,
@@ -369,13 +375,14 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
369375
this.markProviderGenerationObserved();
370376
return this.consults.handleToolCall(event, session);
371377
},
372-
onReady: () => {
373-
this.markProviderGenerationObserved();
374-
if (this.markLifecycleReady(lifecycleGeneration)) {
375-
this.playback.drainQueuedExactSpeechMessages("provider-ready");
378+
onReady,
379+
onEvent: (event) => {
380+
this.handleBridgeEvent(event);
381+
// Some providers report recovered readiness without repeating onReady.
382+
if (event.direction === "client" && event.type === "session.reconnect.ready") {
383+
onReady();
376384
}
377385
},
378-
onEvent: (event) => this.handleBridgeEvent(event),
379386
onResponseDone: (outcome) => {
380387
this.markProviderGenerationObserved();
381388
this.playback.handleResponseDone(outcome);
@@ -389,10 +396,20 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
389396
},
390397
onError: (error) => this.logRealtimeError(formatErrorMessage(error)),
391398
onClose: (reason) => {
392-
this.flushSuppressedRealtimeErrors();
393-
logVoiceVerbose(`realtime closed: ${reason}`);
399+
// Reconnects stay provider-owned. A close is terminal unless local teardown started it.
400+
if (!this.isStopped()) {
401+
this.stopLifecycle(`provider closed: ${reason}`);
402+
this.params.onTerminalError(
403+
new Error(`Realtime provider closed unexpectedly: ${reason}`),
404+
);
405+
}
394406
},
395407
});
408+
// createBridge may close synchronously, before its returned bridge can be disposed.
409+
if (this.isStopped()) {
410+
this.close();
411+
return;
412+
}
396413
const resolvedModel =
397414
readProviderConfigString(resolved.providerConfig, "model") ?? resolved.provider.defaultModel;
398415
const resolvedVoice = readProviderConfigString(resolved.providerConfig, "voice");

‎extensions/discord/src/voice/realtime-turns.test.ts‎

Lines changed: 73 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ defineDiscordVoiceTests(
494494
expect(wakeAckCount()).toBe(2);
495495
});
496496

497-
it("replays zero-audio exact speech once after provider continuity reset", async () => {
497+
it("replays zero-audio exact speech once after provider reconnect readiness", async () => {
498498
agentCommandMock
499499
.mockResolvedValueOnce({ payloads: [{ text: "first answer" }] })
500500
.mockResolvedValueOnce({ payloads: [{ text: "second answer" }] });
@@ -515,7 +515,8 @@ defineDiscordVoiceTests(
515515
expect(realtimeSessionMock.handleBargeIn).not.toHaveBeenCalled();
516516
expect(realtimeSessionMock.close).not.toHaveBeenCalled();
517517

518-
bridgeParams?.onReady?.();
518+
// OpenAI's onReady fires once; automatic recovery reports this event instead.
519+
bridgeParams.onEvent?.({ direction: "client", type: "session.reconnect.ready" });
519520
expect(sentUserMessages().filter((message) => message.includes("first answer"))).toHaveLength(
520521
2,
521522
);
@@ -584,50 +585,76 @@ defineDiscordVoiceTests(
584585
).toHaveLength(1);
585586
});
586587

587-
it("drops stale native consult delivery after provider continuity reset", async () => {
588-
let resolveOld: ((result: { payloads: Array<{ text: string }> }) => void) | undefined;
589-
agentCommandMock
590-
.mockReturnValueOnce(
591-
new Promise((resolve) => {
592-
resolveOld = resolve;
593-
}),
594-
)
595-
.mockResolvedValueOnce({ payloads: [{ text: "fresh answer" }] });
596-
const { bridgeParams, entry } = await createJoinedAgentProxyFixture();
597-
beginSpeakerTurn(entry);
598-
const oldSubmission = bridgeParams?.onToolCall?.(
599-
{
600-
itemId: "item-old",
601-
callId: "call-old",
602-
name: "openclaw_agent_consult",
603-
args: { question: "same question" },
604-
},
605-
realtimeSessionMock,
606-
);
607-
await Promise.resolve();
608-
609-
bridgeParams?.onEvent?.({ direction: "client", type: "session.continuity.reset" });
610-
resolveOld?.({ payloads: [{ text: "stale answer" }] });
611-
await oldSubmission;
612-
expect(
613-
realtimeSessionMock.submitToolResult.mock.calls.some(([callId]) => callId === "call-old"),
614-
).toBe(false);
615-
616-
bridgeParams?.onReady?.();
617-
beginSpeakerTurn(entry);
618-
await bridgeParams?.onToolCall?.(
619-
{
620-
itemId: "item-fresh",
621-
callId: "call-fresh",
622-
name: "openclaw_agent_consult",
623-
args: { question: "same question" },
624-
},
625-
realtimeSessionMock,
626-
);
627-
expect(realtimeSessionMock.submitToolResult).toHaveBeenCalledWith("call-fresh", {
628-
text: "fresh answer",
629-
});
630-
});
588+
it.each(["continuity reset", "terminal close"] as const)(
589+
"drops stale native consult delivery after provider %s",
590+
async (transition) => {
591+
let resolveOld: ((result: { payloads: Array<{ text: string }> }) => void) | undefined;
592+
agentCommandMock
593+
.mockReturnValueOnce(
594+
new Promise((resolve) => {
595+
resolveOld = resolve;
596+
}),
597+
)
598+
.mockResolvedValueOnce({ payloads: [{ text: "fresh answer" }] });
599+
const fixture = await createJoinedAgentProxyFixture();
600+
const { manager } = fixture;
601+
let { bridgeParams, entry } = fixture;
602+
try {
603+
beginSpeakerTurn(entry);
604+
const oldSubmission = bridgeParams?.onToolCall?.(
605+
{
606+
itemId: "item-old",
607+
callId: "call-old",
608+
name: "openclaw_agent_consult",
609+
args: { question: "same question" },
610+
},
611+
realtimeSessionMock,
612+
);
613+
await Promise.resolve();
614+
615+
if (transition === "terminal close") {
616+
bridgeParams.onClose?.("error");
617+
} else {
618+
bridgeParams.onEvent?.({ direction: "client", type: "session.continuity.reset" });
619+
bridgeParams.onEvent?.({ direction: "client", type: "session.reconnect.scheduled" });
620+
}
621+
resolveOld?.({ payloads: [{ text: "stale answer" }] });
622+
await oldSubmission;
623+
expect(
624+
realtimeSessionMock.submitToolResult.mock.calls.some(
625+
([callId]) => callId === "call-old",
626+
),
627+
).toBe(false);
628+
629+
if (transition === "terminal close") {
630+
expect(manager.status()).toEqual([]);
631+
await manager.join({ guildId: "g1", channelId: "1001" });
632+
entry = getSessionEntry(manager);
633+
bridgeParams = lastRealtimeBridgeParams();
634+
} else {
635+
expect(manager.status()).toHaveLength(1);
636+
expect(realtimeSessionMock.close).not.toHaveBeenCalled();
637+
expect(getSessionEntry(manager)).toBe(entry);
638+
}
639+
bridgeParams?.onReady?.();
640+
beginSpeakerTurn(entry);
641+
await bridgeParams?.onToolCall?.(
642+
{
643+
itemId: "item-fresh",
644+
callId: "call-fresh",
645+
name: "openclaw_agent_consult",
646+
args: { question: "same question" },
647+
},
648+
realtimeSessionMock,
649+
);
650+
expect(realtimeSessionMock.submitToolResult).toHaveBeenCalledWith("call-fresh", {
651+
text: "fresh answer",
652+
});
653+
} finally {
654+
await manager.destroy();
655+
}
656+
},
657+
);
631658

632659
it("treats a bare wake name as an activation for the next realtime transcript", async () => {
633660
agentCommandMock.mockResolvedValueOnce({ payloads: [{ text: "follow-up answer" }] });

‎extensions/discord/src/voice/voice-session.lifecycle.test.ts‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ defineDiscordVoiceTests(
2020
resolveRealtimeBootstrapContextInstructionsMock,
2121
createRealtimeVoiceBridgeSessionMock,
2222
realtimeSessionMock,
23+
decodeOpusStreamChunksMock,
2324
managerModule,
2425
createClient,
2526
createManager,
@@ -28,6 +29,9 @@ defineDiscordVoiceTests(
2829
getSessionEntry,
2930
getVoiceReceive,
3031
getLastAudioPlayer,
32+
loggerErrorMock,
33+
lastRealtimeBridgeParams,
34+
beginSpeakerTurn,
3135
expectOffEventWithFunction,
3236
createJoinedAgentProxyFixture,
3337
createJoinedBidiFixture,
@@ -130,6 +134,118 @@ defineDiscordVoiceTests(
130134
expect(newStopped).toHaveBeenCalledOnce();
131135
});
132136

137+
it.each([
138+
["agent-proxy", "completed"],
139+
["agent-proxy", "error"],
140+
["bidi", "completed"],
141+
["bidi", "error"],
142+
] as const)(
143+
"retires %s voice on provider %s without affecting its replacement",
144+
async (mode, reason) => {
145+
const oldConnection = createConnectionMock();
146+
const newConnection = createConnectionMock();
147+
joinVoiceChannelMock.mockReturnValueOnce(oldConnection).mockReturnValueOnce(newConnection);
148+
const manager = createAgentProxyManager(undefined, {
149+
allowFrom: ["discord:u-owner"],
150+
voice: { mode },
151+
});
152+
const transcripts = { sessionId: "notes-1", onUtterance: vi.fn() };
153+
let finishDecoding!: () => void;
154+
const decoding = new Promise<void>((resolve) => {
155+
finishDecoding = resolve;
156+
});
157+
let receive: Promise<void> | undefined;
158+
try {
159+
await manager.join({ guildId: "g1", channelId: "1001" });
160+
await manager.join({ guildId: "g1", channelId: "1001" }, { transcripts });
161+
const entry = getSessionEntry(manager);
162+
decodeOpusStreamChunksMock.mockReturnValueOnce(decoding);
163+
receive = handleSpeakingStart(manager, entry, "u-owner");
164+
await vi.waitFor(() => expect(decodeOpusStreamChunksMock).toHaveBeenCalledOnce());
165+
const captureStream = expectDefined(
166+
oldConnection.receiver.subscribe.mock.results[0]?.value,
167+
"voice capture stream",
168+
);
169+
getVoiceReceive(manager).scheduleCaptureFinalize(entry, "u-owner", "speaker end");
170+
expect(entry.capture.captureFinalizeTimers.size).toBe(1);
171+
const turn = beginSpeakerTurn(entry);
172+
const provider = lastRealtimeBridgeParams();
173+
const player = getLastAudioPlayer();
174+
provider.audioSink.sendAudio(Buffer.alloc(24_000));
175+
expect(player.play).toHaveBeenCalledOnce();
176+
177+
provider.onClose?.(reason);
178+
179+
expect(manager.status()).toEqual([]);
180+
expect(entry.realtime).toBeUndefined();
181+
expect(entry.transcripts).toBe(transcripts);
182+
expect(captureStream.destroy).toHaveBeenCalledOnce();
183+
expect(entry.capture.activeCaptureStreams.size).toBe(0);
184+
expect(entry.capture.captureFinalizeTimers.size).toBe(0);
185+
expect(oldConnection.destroy).toHaveBeenCalledOnce();
186+
expect(realtimeSessionMock.close).toHaveBeenCalledOnce();
187+
expect(loggerErrorMock).toHaveBeenCalledExactlyOnceWith(
188+
expect.stringContaining(`Realtime provider closed unexpectedly: ${reason}`),
189+
);
190+
expect(player.stop).toHaveBeenCalledWith(true);
191+
expectOffEventWithFunction(oldConnection.receiver.speaking.off, "start");
192+
expectOffEventWithFunction(oldConnection.receiver.speaking.off, "end");
193+
const audioPlayer = expectDefined(
194+
createAudioPlayerMock.mock.results[0]?.value,
195+
"audio player",
196+
);
197+
expectOffEventWithFunction(audioPlayer.off, "idle");
198+
199+
await manager.join({ guildId: "g1", channelId: "1001" });
200+
const replacement = getSessionEntry(manager);
201+
const replacementTranscripts = { sessionId: "notes-2", onUtterance: vi.fn() };
202+
await manager.join(
203+
{ guildId: "g1", channelId: "1001" },
204+
{ transcripts: replacementTranscripts },
205+
);
206+
const inputCalls = realtimeSessionMock.sendAudio.mock.calls.length;
207+
turn?.sendInputAudio(Buffer.alloc(3840));
208+
turn?.close();
209+
provider.onClose?.(reason);
210+
provider.onReady?.();
211+
provider.onEvent?.({ direction: "client", type: "session.reconnect.ready" });
212+
provider.audioSink.sendAudio(Buffer.alloc(24_000));
213+
provider.onTranscript?.("user", "stale transcript", true);
214+
provider.onEvent?.({ direction: "server", type: "response.done" });
215+
await Promise.resolve();
216+
217+
expectConnectedStatus(manager, "1001");
218+
expect(getSessionEntry(manager)).toBe(replacement);
219+
expect(newConnection.destroy).not.toHaveBeenCalled();
220+
expect(realtimeSessionMock.close).toHaveBeenCalledOnce();
221+
expect(loggerErrorMock).toHaveBeenCalledOnce();
222+
expect(realtimeSessionMock.sendAudio).toHaveBeenCalledTimes(inputCalls);
223+
expect(player.play).toHaveBeenCalledOnce();
224+
expect(transcripts.onUtterance).not.toHaveBeenCalled();
225+
expect(replacementTranscripts.onUtterance).not.toHaveBeenCalled();
226+
beginSpeakerTurn(replacement);
227+
expect(realtimeSessionMock.sendAudio).toHaveBeenCalledTimes(inputCalls + 1);
228+
} finally {
229+
finishDecoding();
230+
await receive;
231+
await manager.destroy();
232+
}
233+
},
234+
);
235+
236+
it("does not report a terminal error when local close synchronously closes the provider", async () => {
237+
const { bridgeParams, manager } = await createJoinedAgentProxyFixture();
238+
realtimeSessionMock.close.mockImplementationOnce(() => bridgeParams.onClose?.("completed"));
239+
try {
240+
await manager.leave({ guildId: "g1" });
241+
expect(manager.status()).toEqual([]);
242+
expect(realtimeSessionMock.close).toHaveBeenCalledOnce();
243+
expect(loggerErrorMock).not.toHaveBeenCalled();
244+
} finally {
245+
await manager.destroy();
246+
}
247+
});
248+
133249
it("attaches transcripts capture to an existing voice session", async () => {
134250
const manager = createManager();
135251

0 commit comments

Comments
 (0)