Skip to content

Commit 9d6d9af

Browse files
committed
merge: bound Discord realtime exact speech retention (#119250)
* commit 'c238564d2707be5527e83b112025443401e7e2fa': fix(discord): count retained speech bytes test(discord): isolate exact speech overflow test(discord): cover exact speech overflow fix(discord): bound realtime exact speech
2 parents 29f3199 + c238564 commit 9d6d9af

3 files changed

Lines changed: 133 additions & 8 deletions

File tree

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

Lines changed: 93 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -433,15 +433,18 @@ describe("DiscordVoiceManager", () => {
433433
runtime: createRuntime(),
434434
});
435435

436-
const createAgentProxyManager = () =>
437-
createManager({
438-
groupPolicy: "open",
439-
voice: {
440-
enabled: true,
441-
mode: "agent-proxy",
442-
realtime: { provider: "openai" },
436+
const createAgentProxyManager = (clientOverride?: ReturnType<typeof createClient>) =>
437+
createManager(
438+
{
439+
groupPolicy: "open",
440+
voice: {
441+
enabled: true,
442+
mode: "agent-proxy",
443+
realtime: { provider: "openai" },
444+
},
443445
},
444-
});
446+
clientOverride,
447+
);
445448

446449
const expectConnectedStatus = (
447450
manager: InstanceType<typeof managerModule.DiscordVoiceManager>,
@@ -4114,6 +4117,88 @@ describe("DiscordVoiceManager", () => {
41144117
expectUserMessageIncludes("third answer");
41154118
});
41164119

4120+
it("terminates realtime voice when retained Unicode speech exceeds the byte budget", async () => {
4121+
const client = createClient();
4122+
client.fetchChannel.mockImplementation(async (channelId: string) => {
4123+
const guildId = channelId === "2001" ? "g2" : "g1";
4124+
return {
4125+
id: channelId,
4126+
guildId,
4127+
guild: { id: guildId, name: guildId },
4128+
type: ChannelType.GuildVoice,
4129+
};
4130+
});
4131+
const manager = createAgentProxyManager(client);
4132+
4133+
await manager.join({ guildId: "g1", channelId: "1001" });
4134+
const entry = getSessionEntry(manager);
4135+
const realtime = entry.realtime as unknown as {
4136+
enqueueExactSpeechMessage: (text: string) => void;
4137+
};
4138+
const connection = (entry as unknown as { connection: { destroy: ReturnType<typeof vi.fn> } })
4139+
.connection;
4140+
const bridgeParams = lastRealtimeBridgeParams();
4141+
const accepted = "😀".repeat(8 * 1024);
4142+
expect(accepted.length).toBe(16 * 1024);
4143+
expect(Buffer.byteLength(accepted, "utf8")).toBe(32 * 1024);
4144+
4145+
await manager.join({ guildId: "g2", channelId: "2001" });
4146+
const siblingRealtime = getSessionEntry(manager, "g2").realtime as unknown as {
4147+
enqueueExactSpeechMessage: (text: string) => void;
4148+
};
4149+
4150+
realtime.enqueueExactSpeechMessage(accepted);
4151+
expectUserMessageIncludes(accepted);
4152+
expect(manager.status()).toHaveLength(2);
4153+
4154+
realtime.enqueueExactSpeechMessage("overflow");
4155+
4156+
expect(manager.status()).toEqual([
4157+
expect.objectContaining({ guildId: "g2", channelId: "2001" }),
4158+
]);
4159+
expect(connection.destroy).toHaveBeenCalledOnce();
4160+
expect(realtimeSessionMock.close).toHaveBeenCalledOnce();
4161+
expectUserMessageNotIncludes("overflow");
4162+
4163+
siblingRealtime.enqueueExactSpeechMessage("sibling remains usable");
4164+
expectUserMessageIncludes("sibling remains usable");
4165+
4166+
bridgeParams.onReady?.();
4167+
bridgeParams.onEvent?.({ direction: "server", type: "response.done" });
4168+
realtime.enqueueExactSpeechMessage("late");
4169+
entry.stop();
4170+
4171+
expect(connection.destroy).toHaveBeenCalledOnce();
4172+
expect(realtimeSessionMock.close).toHaveBeenCalledOnce();
4173+
expectUserMessageNotIncludes("late");
4174+
});
4175+
4176+
it("terminates realtime voice when retained exact speech exceeds the message budget", async () => {
4177+
const manager = createAgentProxyManager();
4178+
4179+
await manager.join({ guildId: "g1", channelId: "1001" });
4180+
const entry = getSessionEntry(manager);
4181+
const realtime = entry.realtime as unknown as {
4182+
enqueueExactSpeechMessage: (text: string) => void;
4183+
};
4184+
const connection = (entry as unknown as { connection: { destroy: ReturnType<typeof vi.fn> } })
4185+
.connection;
4186+
4187+
for (let index = 0; index < 32; index += 1) {
4188+
realtime.enqueueExactSpeechMessage(`answer-${index}`);
4189+
}
4190+
4191+
expect(manager.status()).toHaveLength(1);
4192+
expect(realtimeSessionMock.sendUserMessage).toHaveBeenCalledOnce();
4193+
4194+
realtime.enqueueExactSpeechMessage("answer-overflow");
4195+
4196+
expect(manager.status()).toStrictEqual([]);
4197+
expect(connection.destroy).toHaveBeenCalledOnce();
4198+
expect(realtimeSessionMock.close).toHaveBeenCalledOnce();
4199+
expectUserMessageNotIncludes("answer-overflow");
4200+
});
4201+
41174202
it("does not interrupt active exact speech for a later forced agent-proxy consult", async () => {
41184203
agentCommandMock
41194204
.mockResolvedValueOnce({ payloads: [{ text: "first answer" }] })

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -746,6 +746,7 @@ export class DiscordVoiceManager {
746746
receiveRecovery: createVoiceReceiveRecoveryState(),
747747
isStopped: () => stopped,
748748
stop: () => {
749+
clearSessionIfCurrent();
749750
stopEntry(entry, {
750751
destroyConnection: true,
751752
reason: `stop guild ${guildId} channel ${channelId}`,
@@ -884,6 +885,12 @@ export class DiscordVoiceManager {
884885
entry,
885886
getHumanParticipantCount: () => this.membership.countHumanParticipants(entry, this.botUserId),
886887
mode: voiceMode,
888+
onTerminalError: (error) => {
889+
logger.error(
890+
`discord voice: realtime session failed terminally guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage(error)}`,
891+
);
892+
entry.stop();
893+
},
887894
runAgentTurn: ({ context, message, toolsAllow, userId }) =>
888895
this.runDiscordRealtimeAgentTurn({ context, entry, message, toolsAllow, userId }),
889896
});

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@ const DISCORD_REALTIME_FORCED_CONSULT_FALLBACK_DELAY_MS = 200;
8989
const DISCORD_REALTIME_DUPLICATE_ERROR_SUPPRESS_MS = 60_000;
9090
const DISCORD_REALTIME_CONTROL_SPEECH_DEDUPE_MS = 5_000;
9191
const DISCORD_REALTIME_OUTPUT_PLAYBACK_WATCHDOG_MARGIN_MS = 1_500;
92+
const DISCORD_REALTIME_MAX_RETAINED_EXACT_SPEECH_MESSAGES = 32;
93+
const DISCORD_REALTIME_MAX_RETAINED_EXACT_SPEECH_BYTES = 32 * 1024;
9294
const DISCORD_REALTIME_CANCELLATION_RACE_DETAIL = "Cancellation failed: no active response found";
9395
const DISCORD_REALTIME_WAKE_ACKS = ["Yeah.", "Mm-hmm.", "Got it.", "One sec."];
9496
const discordRealtimeTalkPayload = () => ({});
@@ -388,6 +390,7 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
388390
mode: Exclude<DiscordVoiceMode, "stt-tts">;
389391
bootstrapContextInstructions?: string;
390392
getHumanParticipantCount?: () => number;
393+
onTerminalError: (error: Error) => void;
391394
runAgentTurn: (params: VoiceRealtimeAgentTurnParams) => Promise<string>;
392395
},
393396
) {
@@ -994,6 +997,36 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
994997
if (this.stopped || !text.trim()) {
995998
return;
996999
}
1000+
const retainedMessages =
1001+
this.queuedExactSpeechMessages.length + (this.activeExactSpeechMessage ? 1 : 0);
1002+
const retainedBytes =
1003+
this.queuedExactSpeechMessages.reduce(
1004+
(total, message) => total + Buffer.byteLength(message, "utf8"),
1005+
0,
1006+
) + Buffer.byteLength(this.activeExactSpeechMessage ?? "", "utf8");
1007+
const incomingBytes = Buffer.byteLength(text, "utf8");
1008+
if (
1009+
retainedMessages >= DISCORD_REALTIME_MAX_RETAINED_EXACT_SPEECH_MESSAGES ||
1010+
retainedBytes + incomingBytes > DISCORD_REALTIME_MAX_RETAINED_EXACT_SPEECH_BYTES
1011+
) {
1012+
// Completed speech cannot be silently dropped. Overflow terminally retires
1013+
// this session before late provider or playback events can drain stale work.
1014+
this.stopped = true;
1015+
this.bridgeReady = false;
1016+
this.outputBackpressure = undefined;
1017+
this.talkback.close();
1018+
this.queuedExactSpeechMessages = [];
1019+
this.exactSpeechResponseActive = false;
1020+
this.exactSpeechAudioStarted = false;
1021+
this.activeExactSpeechMessage = undefined;
1022+
this.clearOutputAudio("exact-speech-overflow");
1023+
this.params.onTerminalError(
1024+
new Error(
1025+
`Discord realtime exact speech overflow: retained=${retainedMessages} retainedBytes=${retainedBytes} incomingBytes=${incomingBytes}`,
1026+
),
1027+
);
1028+
return;
1029+
}
9971030
if (!this.bridgeReady || this.exactSpeechResponseActive || this.hasInterruptibleOutputAudio()) {
9981031
this.queuedExactSpeechMessages.push(text);
9991032
logger.info(

0 commit comments

Comments
 (0)