Skip to content

Commit 5ae91f0

Browse files
committed
fix: speed up Discord voice wake consults
1 parent 3eb06e3 commit 5ae91f0

9 files changed

Lines changed: 99 additions & 10 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Docs: https://docs.openclaw.ai
2222
- Sessions/doctor: load large session stores without clone amplification during read-only doctor checks and reclaim stale `sessions.json.*.tmp` sidecars. Fixes #56827. Thanks @openperf.
2323
- Tests: clean successful plugin gateway gauntlet isolated temp roots while keeping an explicit preservation switch for failed/debug runs.
2424
- Plugins/perf: reuse derived plugin metadata snapshots for the lifetime of the process so reply-time skill setup no longer rescans plugin metadata on every turn.
25+
- Discord/OpenAI voice: keep wake-name master consults using the current speaker context after ignored ambient transcripts and shorten the default capture silence grace.
2526
- Gateway: keep session-only Control UI tool-start mirrors flowing during diagnostic queue pressure instead of silently dropping non-terminal tool updates.
2627
- Agents/memory: return optional not-found context for missing date-only daily memory reads instead of logging benign first-run `ENOENT` failures. Fixes #82928. Thanks @galiniliev.
2728
- Discord: merge streamed text captions into following media block replies so captions and attachments send as one message. (#86487) Thanks @neeravmakwana.
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
e8e71a715bd33405280b5a9f6b6e788abed636fba66ec5f3a4f9b9a768a1637f config-baseline.json
2-
003183db53a41905c540f37b1d30b3006ef8906915e13eac844b643cd210fdfe config-baseline.core.json
3-
859b021f65400df22c95ae55b074cf26c83d3a0bfadb3fceeaca522f6ea391ae config-baseline.channel.json
1+
5f62e1fcb1b641432dbf30213b8be9b7fd5b70d53f048c8d033a3bdc723d16f9 config-baseline.json
2+
0b75385e71e2a3aec5736b7df55e318aae81d3ad1b5794966400a2a7f01c3eca config-baseline.core.json
3+
18415d0f8a920e4d50b2bd46f10dc02bdea7c387c1f5e1f46fd4990ebca51eed config-baseline.channel.json
44
74441e331aabb3026784c148d4ee5ce3f489a15ed87ffd9b7ba0c5e2a7bc93be config-baseline.plugin.json

‎docs/channels/discord.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1252,7 +1252,7 @@ Notes:
12521252
- `voice.reconnectGraceMs` controls how long OpenClaw waits for a disconnected voice session to begin reconnecting before destroying it. Default: `15000`.
12531253
- In `stt-tts` mode, voice playback does not stop just because another user starts speaking. To avoid feedback loops, OpenClaw ignores new voice capture while TTS is playing; speak after playback finishes for the next turn. Realtime modes forward speaker starts as barge-in signals to the realtime provider.
12541254
- In realtime modes, echo from speakers into an open mic can look like barge-in and interrupt playback. For echo-heavy Discord rooms, set `voice.realtime.providers.openai.interruptResponseOnInputAudio: false` to keep OpenAI from auto-interrupting on input audio. Add `voice.realtime.bargeIn: true` if you still want Discord speaker-start events to interrupt active playback. The OpenAI realtime bridge ignores playback truncations shorter than `voice.realtime.minBargeInAudioEndMs` as likely echo/noise and logs them as skipped instead of clearing Discord playback.
1255-
- `voice.captureSilenceGraceMs` controls how long OpenClaw waits after Discord reports a speaker has stopped before finalizing that audio segment for STT. Default: `2500`; raise this if Discord splits normal pauses into choppy partial transcripts.
1255+
- `voice.captureSilenceGraceMs` controls how long OpenClaw waits after Discord reports a speaker has stopped before finalizing that audio segment for STT. Default: `2000`; raise this if Discord splits normal pauses into choppy partial transcripts.
12561256
- When ElevenLabs is the selected TTS provider, Discord voice playback uses streaming TTS and starts from the provider response stream. Providers without streaming support fall back to the synthesized temp-file path.
12571257
- OpenClaw also watches receive decrypt failures and auto-recovers by leaving/rejoining the voice channel after repeated failures in a short window.
12581258
- If receive logs repeatedly show `DecryptionFailed(UnencryptedWhenPassthroughDisabled)` after updating, collect a dependency report and logs. The bundled `@discordjs/voice` line includes the upstream padding fix from discord.js PR #11449, which closed discord.js issue #11419.

‎extensions/discord/src/config-ui-hints.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ export const discordChannelConfigUiHints = {
284284
},
285285
"voice.captureSilenceGraceMs": {
286286
label: "Discord Voice Capture Silence Grace (ms)",
287-
help: "Silence window after Discord reports a speaker ended before OpenClaw finalizes the audio segment for transcription. Default: 2500.",
287+
help: "Silence window after Discord reports a speaker ended before OpenClaw finalizes the audio segment for transcription. Default: 2000.",
288288
},
289289
"voice.tts": {
290290
label: "Discord Voice Text-to-Speech",

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

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2915,6 +2915,58 @@ describe("DiscordVoiceManager", () => {
29152915
expect(lastAgentCommandArgs().message).not.toContain("Hey");
29162916
});
29172917

2918+
it("reuses recently ignored speaker context when wake-name consult has no pending turn", async () => {
2919+
agentCommandMock.mockResolvedValueOnce({ payloads: [{ text: "wake answer" }] });
2920+
const manager = createManager(
2921+
{
2922+
groupPolicy: "open",
2923+
voice: {
2924+
enabled: true,
2925+
mode: "agent-proxy",
2926+
realtime: { provider: "openai", consultPolicy: "auto", requireWakeName: true },
2927+
},
2928+
},
2929+
undefined,
2930+
{
2931+
agents: {
2932+
list: [{ id: "agent-1", identity: { name: "Molty" } }],
2933+
},
2934+
},
2935+
);
2936+
2937+
await manager.join({ guildId: "g1", channelId: "1001" });
2938+
const entry = getSessionEntry(manager) as {
2939+
realtime?: {
2940+
beginSpeakerTurn: (
2941+
context: { extraSystemPrompt?: string; senderIsOwner: boolean; speakerLabel: string },
2942+
userId: string,
2943+
) => { close: () => void; sendInputAudio: (audio: Buffer) => void };
2944+
};
2945+
};
2946+
const bridgeParams = lastRealtimeBridgeParams() as
2947+
| {
2948+
onTranscript?: (role: "user" | "assistant", text: string, isFinal: boolean) => void;
2949+
}
2950+
| undefined;
2951+
2952+
const ownerTurn = entry.realtime?.beginSpeakerTurn(
2953+
{ extraSystemPrompt: "owner prompt", senderIsOwner: true, speakerLabel: "Owner" },
2954+
"u-owner",
2955+
);
2956+
ownerTurn?.sendInputAudio(Buffer.alloc(8));
2957+
2958+
bridgeParams?.onTranscript?.("user", "room noise", true);
2959+
bridgeParams?.onTranscript?.("user", "Molty, so", true);
2960+
bridgeParams?.onTranscript?.("user", "Malty, what do you have to say?", true);
2961+
await new Promise((resolve) => setTimeout(resolve, 260));
2962+
2963+
expect(agentCommandMock).toHaveBeenCalledTimes(1);
2964+
expect(lastAgentCommandArgs().message).toContain("what do you have to say?");
2965+
expect(lastAgentCommandArgs().message).not.toContain("Malty");
2966+
expect(lastAgentCommandArgs().extraSystemPrompt).toBe("owner prompt");
2967+
expectUserMessageIncludes("wake answer");
2968+
});
2969+
29182970
it("accepts OpenClaw as a default wake name before realtime agent-proxy consults", async () => {
29192971
agentCommandMock.mockResolvedValueOnce({ payloads: [{ text: "openclaw wake answer" }] });
29202972
const manager = createManager(

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

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ const DISCORD_REALTIME_FALLBACK_TEXT = "I hit an error while checking that. Plea
5858
const DISCORD_REALTIME_PENDING_SPEAKER_CONTEXT_LIMIT = 32;
5959
const DISCORD_REALTIME_RECENT_AGENT_PROXY_CONSULT_LIMIT = 16;
6060
const DISCORD_REALTIME_RECENT_AGENT_PROXY_CONSULT_TTL_MS = 15_000;
61+
const DISCORD_REALTIME_IGNORED_WAKE_NAME_CONTEXT_TTL_MS = 10_000;
6162
const DISCORD_REALTIME_LOG_PREVIEW_CHARS = 500;
6263
const DISCORD_REALTIME_DEFAULT_MIN_BARGE_IN_AUDIO_END_MS = 250;
6364
const DISCORD_REALTIME_FORCED_CONSULT_FALLBACK_DELAY_MS = 200;
@@ -140,6 +141,11 @@ type RecentAgentProxyConsultContext = {
140141
result?: RecentAgentProxyConsultResult;
141142
};
142143

144+
type RecentIgnoredWakeNameSpeakerContext = {
145+
context: DiscordRealtimeSpeakerContext;
146+
createdAt: number;
147+
};
148+
143149
function formatRealtimeLogPreview(text: string): string {
144150
const oneLine = text.replace(/\s+/g, " ").trim();
145151
if (oneLine.length <= DISCORD_REALTIME_LOG_PREVIEW_CHARS) {
@@ -636,6 +642,7 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
636642
private wakeNames: string[] = [];
637643
private pendingAgentProxyConsultContexts: PendingAgentProxyConsultContext[] = [];
638644
private recentAgentProxyConsultContexts: RecentAgentProxyConsultContext[] = [];
645+
private recentIgnoredWakeNameSpeakerContext: RecentIgnoredWakeNameSpeakerContext | undefined;
639646
private readonly pendingSpeakerTurns: PendingSpeakerTurn[] = [];
640647
private outputAudioTimestampMs = 0;
641648
private outputAudioDiscordBytes = 0;
@@ -832,6 +839,7 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
832839
this.clearForcedConsultTimers();
833840
this.pendingAgentProxyConsultContexts = [];
834841
this.recentAgentProxyConsultContexts = [];
842+
this.recentIgnoredWakeNameSpeakerContext = undefined;
835843
this.pendingSpeakerTurns.length = 0;
836844
this.queuedExactSpeechMessages = [];
837845
this.exactSpeechResponseActive = false;
@@ -1424,10 +1432,10 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
14241432
this.recordMeetingNotesUtterance(trimmed, meetingNotesTurn);
14251433
const wakeNameResult = this.resolveWakeNameTranscript(trimmed);
14261434
if (!wakeNameResult.allowed) {
1435+
this.rememberIgnoredWakeNameSpeakerContext(this.consumePendingSpeakerContext());
14271436
logger.info(
14281437
`discord voice: realtime wake-name gate ignored transcript chars=${trimmed.length} voiceSession=${this.params.entry.voiceSessionKey} agent=${this.params.entry.route.agentId} wakeNames=${this.wakeNames.join(",") || "none"}`,
14291438
);
1430-
this.consumePendingSpeakerContext();
14311439
return;
14321440
}
14331441
const acceptedText = wakeNameResult.text || trimmed;
@@ -1540,14 +1548,18 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
15401548
if (!question) {
15411549
return undefined;
15421550
}
1543-
const context = this.consumePendingSpeakerContext();
15441551
const skipReason = classifySkippableForcedAgentProxyTranscript(question);
15451552
if (skipReason) {
1553+
const context = this.consumePendingSpeakerContext();
15461554
logger.info(
15471555
`discord voice: realtime forced agent consult skipped reason=${skipReason} chars=${question.length} speaker=${context?.speakerLabel ?? "unknown"} transcript=${formatRealtimeLogPreview(question)}`,
15481556
);
15491557
return undefined;
15501558
}
1559+
let context = this.consumePendingSpeakerContext();
1560+
if (!context) {
1561+
context = this.consumeRecentIgnoredWakeNameSpeakerContext();
1562+
}
15511563
if (!context) {
15521564
const recent = this.findRecentAgentProxyConsultContext(question);
15531565
if (recent) {
@@ -1681,6 +1693,30 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
16811693
return turn?.context;
16821694
}
16831695

1696+
private rememberIgnoredWakeNameSpeakerContext(
1697+
context: DiscordRealtimeSpeakerContext | undefined,
1698+
): void {
1699+
if (!context) {
1700+
return;
1701+
}
1702+
this.recentIgnoredWakeNameSpeakerContext = {
1703+
context,
1704+
createdAt: Date.now(),
1705+
};
1706+
}
1707+
1708+
private consumeRecentIgnoredWakeNameSpeakerContext(): DiscordRealtimeSpeakerContext | undefined {
1709+
const recent = this.recentIgnoredWakeNameSpeakerContext;
1710+
this.recentIgnoredWakeNameSpeakerContext = undefined;
1711+
if (
1712+
!recent ||
1713+
Date.now() - recent.createdAt > DISCORD_REALTIME_IGNORED_WAKE_NAME_CONTEXT_TTL_MS
1714+
) {
1715+
return undefined;
1716+
}
1717+
return recent.context;
1718+
}
1719+
16841720
private peekPendingSpeakerTurn(): PendingSpeakerTurn | undefined {
16851721
this.prunePendingSpeakerTurns();
16861722
this.expireClosedSpeakerTurnsBeforeLaterAudio();

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type { VoiceCaptureState } from "./capture-state.js";
66
import type { VoiceReceiveRecoveryState } from "./receive-recovery.js";
77

88
export const MIN_SEGMENT_SECONDS = 0.35;
9-
export const CAPTURE_FINALIZE_GRACE_MS = 2_500;
9+
export const CAPTURE_FINALIZE_GRACE_MS = 2_000;
1010
export const VOICE_CONNECT_READY_TIMEOUT_MS = 30_000;
1111
export const VOICE_RECONNECT_GRACE_MS = 15_000;
1212
export const PLAYBACK_READY_TIMEOUT_MS = 60_000;

‎src/config/bundled-channel-config-metadata.generated.ts‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎src/config/types.discord.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ export type DiscordVoiceConfig = {
207207
connectTimeoutMs?: number;
208208
/** Grace period for Discord voice reconnect signalling after a disconnect (default: 15000). */
209209
reconnectGraceMs?: number;
210-
/** Silence grace after Discord reports a speaker ended before finalizing STT capture (default: 2500). */
210+
/** Silence grace after Discord reports a speaker ended before finalizing STT capture (default: 2000). */
211211
captureSilenceGraceMs?: number;
212212
/** Optional TTS overrides for Discord voice output. */
213213
tts?: TtsConfig;

0 commit comments

Comments
 (0)