Skip to content

Commit 3f7c852

Browse files
authored
fix(discord): stop stale voice playback after leave (#124030)
Discard TTS that settles after a Discord voice session stops, release queued streams, and remove file-backed playback artifacts after use.
1 parent f8fcc7f commit 3f7c852

3 files changed

Lines changed: 93 additions & 25 deletions

File tree

‎extensions/discord/src/voice/segment.ts‎

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Discord plugin module implements segment behavior.
2-
import path from "node:path";
32
import { Readable } from "node:stream";
43
import type { DiscordAccountConfig, OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
4+
import { unlinkIfExists } from "openclaw/plugin-sdk/media-runtime";
55
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
66
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
77
import { formatErrorMessage } from "openclaw/plugin-sdk/ssrf-runtime";
@@ -171,32 +171,35 @@ export async function processDiscordVoiceSegment(params: {
171171
`tts ok (${voiceReplyAudio.speakText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`,
172172
);
173173

174+
const releaseAudio =
175+
voiceReplyAudio.mode === "stream"
176+
? voiceReplyAudio.release
177+
: () => unlinkIfExists(voiceReplyAudio.audioPath);
178+
// Synthesis can settle after leave; release before the playback queue gets ownership.
179+
if (entry.sessionLifecycle.status === "stopped") {
180+
await releaseAudio?.();
181+
return;
182+
}
174183
params.enqueuePlayback(entry, async () => {
175184
const voiceSdk = loadDiscordVoiceSdk();
176-
const releaseAudioStream =
177-
voiceReplyAudio.mode === "stream" ? voiceReplyAudio.release : undefined;
178185
try {
179-
if (voiceReplyAudio.mode === "stream") {
180-
logVoiceVerbose(`playback start: guild ${entry.guildId} channel ${entry.channelId} stream`);
181-
const nodeStream = Readable.fromWeb(
182-
voiceReplyAudio.audioStream as import("node:stream/web").ReadableStream<Uint8Array>,
183-
);
184-
const resource = voiceSdk.createAudioResource(createDiscordOpusPlaybackStream(nodeStream), {
185-
inputType: voiceSdk.StreamType.Opus,
186-
});
187-
entry.player.play(resource);
188-
} else {
189-
logVoiceVerbose(
190-
`playback start: guild ${entry.guildId} channel ${entry.channelId} file ${path.basename(voiceReplyAudio.audioPath)}`,
191-
);
192-
const resource = voiceSdk.createAudioResource(
193-
createDiscordOpusPlaybackStream(voiceReplyAudio.audioPath),
194-
{
195-
inputType: voiceSdk.StreamType.Opus,
196-
},
197-
);
198-
entry.player.play(resource);
186+
// Queued playback can outlive its session; a stopped player is reusable by the SDK.
187+
if (entry.sessionLifecycle.status === "stopped") {
188+
return;
199189
}
190+
const input =
191+
voiceReplyAudio.mode === "stream"
192+
? Readable.fromWeb(
193+
voiceReplyAudio.audioStream as import("node:stream/web").ReadableStream<Uint8Array>,
194+
)
195+
: voiceReplyAudio.audioPath;
196+
logVoiceVerbose(
197+
`playback start: guild ${entry.guildId} channel ${entry.channelId} ${voiceReplyAudio.mode}`,
198+
);
199+
const resource = voiceSdk.createAudioResource(createDiscordOpusPlaybackStream(input), {
200+
inputType: voiceSdk.StreamType.Opus,
201+
});
202+
entry.player.play(resource);
200203
await voiceSdk
201204
.entersState(entry.player, voiceSdk.AudioPlayerStatus.Playing, PLAYBACK_READY_TIMEOUT_MS)
202205
.catch(() => undefined);
@@ -205,7 +208,7 @@ export async function processDiscordVoiceSegment(params: {
205208
.catch(() => undefined);
206209
logVoiceVerbose(`playback done: guild ${entry.guildId} channel ${entry.channelId}`);
207210
} finally {
208-
await releaseAudioStream?.();
211+
await releaseAudio?.();
209212
}
210213
});
211214
}

‎extensions/discord/src/voice/voice-runtime.e2e.test.ts‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
14
import type { MockCallSource } from "./manager.e2e.test-support.js";
25
import { defineDiscordVoiceTests } from "./voice-test-harness.test-support.js";
36

@@ -220,6 +223,7 @@ defineDiscordVoiceTests(
220223
route: { sessionKey: "discord:g1:1001", agentId: "agent-1" },
221224
connection: createConnectionMock(),
222225
player: createAudioPlayerMock(),
226+
sessionLifecycle: { status: "active" },
223227
playbackQueue: Promise.resolve(),
224228
processingQueue: Promise.resolve(),
225229
capture: createVoiceCaptureState(),
@@ -282,6 +286,10 @@ defineDiscordVoiceTests(
282286
});
283287

284288
it("runs voice replies under Discord voice output policy", async () => {
289+
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-discord-voice-"));
290+
const audioPath = path.join(tempDir, "reply.mp3");
291+
await fs.writeFile(audioPath, "voice");
292+
textToSpeechMock.mockResolvedValueOnce({ success: true, audioPath });
285293
agentCommandMock.mockResolvedValueOnce({
286294
payloads: [{ text: "hello back" }],
287295
} as never);
@@ -292,7 +300,18 @@ defineDiscordVoiceTests(
292300
client,
293301
{},
294302
);
295-
await processVoiceSegment(manager, "u-guest");
303+
try {
304+
await processVoiceSegment(manager, "u-guest");
305+
await vi.waitFor(async () => {
306+
const exists = await fs.access(audioPath).then(
307+
() => true,
308+
() => false,
309+
);
310+
expect(exists).toBe(false);
311+
});
312+
} finally {
313+
await fs.rm(tempDir, { recursive: true, force: true });
314+
}
296315

297316
const commandArgs = lastAgentCommandArgs() as
298317
| { message?: string; messageChannel?: string; messageProvider?: string }
@@ -368,6 +387,51 @@ defineDiscordVoiceTests(
368387
await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));
369388
});
370389

390+
it("releases late TTS without playback after the voice session leaves", async () => {
391+
const connection = createConnectionMock();
392+
joinVoiceChannelMock.mockReturnValueOnce(connection);
393+
decodeOpusStreamMock.mockResolvedValueOnce(Buffer.alloc(96_000));
394+
agentCommandMock.mockResolvedValueOnce({ payloads: [{ text: "late voice reply" }] });
395+
const release = vi.fn(async () => undefined);
396+
let resolveStream!: (value: unknown) => void;
397+
textToSpeechStreamMock.mockReturnValueOnce(
398+
new Promise((resolve) => {
399+
resolveStream = resolve;
400+
}),
401+
);
402+
connection.receiver.subscribe.mockReturnValueOnce({
403+
on: vi.fn(),
404+
off: vi.fn(),
405+
destroy: vi.fn(),
406+
destroyed: false,
407+
async *[Symbol.asyncIterator]() {},
408+
});
409+
const manager = createManager(
410+
makeVoiceConfig({}, { groupPolicy: "open", allowFrom: ["discord:u-speaker"] }),
411+
);
412+
await manager.join({ guildId: "g1", channelId: "1001" });
413+
const entry = getSessionEntry(manager);
414+
415+
const speaking = handleSpeakingStart(manager, entry, "u-speaker");
416+
await vi.waitFor(() => expect(textToSpeechStreamMock).toHaveBeenCalledOnce());
417+
await manager.leave({ guildId: "g1" });
418+
resolveStream({
419+
success: true,
420+
audioStream: new ReadableStream<Uint8Array>({
421+
start(controller) {
422+
controller.close();
423+
},
424+
}),
425+
release,
426+
});
427+
await speaking;
428+
await entry.processingQueue;
429+
await entry.playbackQueue;
430+
431+
expect(entry.player.play).not.toHaveBeenCalled();
432+
expect(release).toHaveBeenCalledOnce();
433+
});
434+
371435
it("passes per-channel system prompt context to voice agent runs", async () => {
372436
const client = createClientWithMember("u-guest", "Guest", "4321");
373437
const manager = createManager(

‎extensions/discord/src/voice/voice-test-harness.test-support.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,7 @@ function buildVoiceTestHarness() {
550550
route: { sessionKey: "discord:g1:1001", agentId: "agent-1" },
551551
connection: createConnectionMock(),
552552
player: createAudioPlayerMock(),
553+
sessionLifecycle: { status: "active" },
553554
playbackQueue: Promise.resolve(),
554555
processingQueue: Promise.resolve(),
555556
capture: createVoiceCaptureState(),

0 commit comments

Comments
 (0)