Skip to content

Commit 533319b

Browse files
authored
fix(discord): retire voice sessions after realtime provider closure (#131548)
* 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. * test(discord): prove terminal closure retires transcript captures * test(discord): split terminal lifecycle coverage
1 parent 1e17830 commit 533319b

9 files changed

Lines changed: 482 additions & 191 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.startup.test.ts‎

Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ defineDiscordVoiceTests(
77
createConnectionMock,
88
joinVoiceChannelMock,
99
realtimeSessionMock,
10+
createRealtimeVoiceBridgeSessionMock,
1011
createAgentProxyManager,
1112
getLastAudioPlayer,
1213
lastRealtimeBridgeParams,
@@ -87,31 +88,50 @@ defineDiscordVoiceTests(
8788
expect(connection.destroy).not.toHaveBeenCalled();
8889
});
8990

90-
it("handles terminal provider output before the initial realtime connect finishes", async () => {
91-
const connection = createConnectionMock();
92-
joinVoiceChannelMock.mockReturnValueOnce(connection);
93-
const manager = createAgentProxyManager();
94-
realtimeSessionMock.connect.mockImplementationOnce(async () => {
95-
// Provider output can arrive while connect is pending; exceed the two-minute PCM cap.
96-
lastRealtimeBridgeParams().audioSink.sendAudio(Buffer.alloc(24_000 * 2 * 121));
97-
});
91+
it.each(["output overflow", "completed", "error", "synchronous close"] as const)(
92+
"handles terminal provider %s before the initial realtime connect finishes",
93+
async (terminal) => {
94+
const connection = createConnectionMock();
95+
joinVoiceChannelMock.mockReturnValueOnce(connection);
96+
const manager = createAgentProxyManager();
97+
if (terminal === "synchronous close") {
98+
createRealtimeVoiceBridgeSessionMock.mockImplementationOnce(() => {
99+
lastRealtimeBridgeParams().onClose?.("error");
100+
return realtimeSessionMock;
101+
});
102+
} else {
103+
realtimeSessionMock.connect.mockImplementationOnce(async () => {
104+
const provider = lastRealtimeBridgeParams();
105+
if (terminal === "output overflow") {
106+
// Provider output can arrive while connect is pending; exceed the two-minute PCM cap.
107+
provider.audioSink.sendAudio(Buffer.alloc(24_000 * 2 * 121));
108+
} else {
109+
provider.onClose?.(terminal);
110+
}
111+
});
112+
}
98113

99-
try {
100-
await expect(manager.join({ guildId: "g1", channelId: "1001" })).resolves.toEqual({
101-
ok: false,
102-
message: "Discord realtime voice session stopped before startup completed.",
103-
guildId: "g1",
104-
channelId: "1001",
105-
});
114+
try {
115+
await expect(manager.join({ guildId: "g1", channelId: "1001" })).resolves.toEqual({
116+
ok: false,
117+
message: "Discord realtime voice session stopped before startup completed.",
118+
guildId: "g1",
119+
channelId: "1001",
120+
});
106121

107-
expect(manager.status()).toEqual([]);
108-
expect(realtimeSessionMock.close).toHaveBeenCalled();
122+
expect(manager.status()).toEqual([]);
123+
expect(connection.receiver.speaking.on).not.toHaveBeenCalled();
124+
expect(realtimeSessionMock.close).toHaveBeenCalledOnce();
125+
expect(connection.destroy).toHaveBeenCalledTimes(1);
126+
expect(getLastAudioPlayer().stop).toHaveBeenCalledWith(true);
127+
if (terminal === "synchronous close") {
128+
expect(realtimeSessionMock.connect).not.toHaveBeenCalled();
129+
}
130+
} finally {
131+
await manager.destroy();
132+
}
109133
expect(connection.destroy).toHaveBeenCalledTimes(1);
110-
expect(getLastAudioPlayer().stop).toHaveBeenCalledWith(true);
111-
} finally {
112-
await manager.destroy();
113-
}
114-
expect(connection.destroy).toHaveBeenCalledTimes(1);
115-
});
134+
},
135+
);
116136
},
117137
);

0 commit comments

Comments
 (0)