Skip to content

Commit 2d5334f

Browse files
authored
fix(tts): normalize streamed speech and report fallbacks (#125686)
* fix(tts): normalize streamed speech and report fallbacks Streamed Discord voice now strips Markdown and raw link destinations like buffered synthesis. Record the first failed streaming provider and reason code before successful file fallback. * test(ui): stabilize reconnect retry timing Drive the retry deterministically by advancing the exact 100 ms fake timer while preserving the ordering and outbox proof. Repairs CI run 32110130614 job 95627654678. * fix(discord): ignore expected TTS stream skips Address the ClawSweeper finding by retaining warning metadata only for actual failed attempts. Expected unsupported-for-streaming skips stay silent while real streaming failures still warn after successful file fallback. * test(ui): settle interaction state before assertions Repairs CI run 32117859632 by invoking the markdown table handler directly with a targeted event and waiting for durable IndexedDB composer state before navigation or page close. * test: remove incidental UI and process identities CI run 32120793258 exposed two owner-specific test assumptions. Preserve the child-session hover visibility and pointer assertions, then focus and activate its menu with Enter so an unrelated delayed hovercard cannot intercept the pointer. Assert the exact owned descendant PID is dead when QA cleanup completes instead of checking a globally reusable PGID. * test(ui): stabilize connected send retry timing CI run 32125741781 exposed the wall-clock race in the connected retry test.
1 parent 0a4e81e commit 2d5334f

14 files changed

Lines changed: 250 additions & 74 deletions

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,13 @@ export async function processDiscordVoiceSegment(params: {
169169
logger.warn(`discord voice: TTS failed: ${voiceReplyAudio.error ?? "unknown error"}`);
170170
return;
171171
}
172+
const streamFailure = voiceReplyAudio.mode === "file" ? voiceReplyAudio.streamFailure : undefined;
173+
if (streamFailure && !entry.ttsStreamFallbackWarned) {
174+
entry.ttsStreamFallbackWarned = true;
175+
logger.warn(
176+
`discord voice: streaming TTS failed provider=${streamFailure.provider} reasonCode=${streamFailure.reasonCode}; using file fallback`,
177+
);
178+
}
172179
logVoiceVerbose(
173180
`tts ok (${voiceReplyAudio.speakText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`,
174181
);

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ export type VoiceSessionEntry = {
103103
player: import("@discordjs/voice").AudioPlayer;
104104
playbackQueue: Promise<void>;
105105
processingQueue: Promise<void>;
106+
ttsStreamFallbackWarned: boolean;
106107
capture: VoiceCaptureState;
107108
realtimeLifecycle: VoiceRealtimeLifecycle;
108109
transcripts?: {

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

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,22 @@
22
import { resolveAgentDir } from "openclaw/plugin-sdk/agent-runtime";
33
import type { OpenClawConfig, TtsConfig } from "openclaw/plugin-sdk/config-contracts";
44
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
5+
import type { TtsStreamResult } from "openclaw/plugin-sdk/tts-runtime";
56
import { getDiscordRuntime } from "../runtime.js";
67
import { sanitizeVoiceReplyTextForSpeech } from "./sanitize.js";
78

9+
type VoiceStreamFailure = Pick<
10+
NonNullable<TtsStreamResult["attempts"]>[number],
11+
"provider" | "reasonCode"
12+
>;
13+
814
type VoiceReplyAudioResult =
915
| {
1016
status: "ok";
1117
mode: "file";
1218
audioPath: string;
1319
speakText: string;
20+
streamFailure?: VoiceStreamFailure;
1421
}
1522
| {
1623
status: "ok";
@@ -75,6 +82,10 @@ export async function synthesizeVoiceReplyAudio(params: {
7582
speakText,
7683
};
7784
}
85+
const streamFailure =
86+
streamResult && !streamResult.success
87+
? streamResult.attempts?.findLast((attempt) => attempt.outcome === "failed")
88+
: undefined;
7889

7990
const result = await runtime.tts.textToSpeech({
8091
text: speakText,
@@ -85,5 +96,15 @@ export async function synthesizeVoiceReplyAudio(params: {
8596
if (!result.success || !result.audioPath) {
8697
return { status: "failed", error: result.error ?? "unknown error" };
8798
}
88-
return { status: "ok", mode: "file", audioPath: result.audioPath, speakText };
99+
return {
100+
status: "ok",
101+
mode: "file",
102+
audioPath: result.audioPath,
103+
speakText,
104+
...(streamFailure
105+
? {
106+
streamFailure: { provider: streamFailure.provider, reasonCode: streamFailure.reasonCode },
107+
}
108+
: {}),
109+
};
89110
}

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

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ defineDiscordVoiceTests(
2525
textToSpeechStreamMock,
2626
textToSpeechMock,
2727
logVerboseMock,
28+
loggerWarnMock,
2829
controlRealtimeVoiceAgentRunMock,
2930
realtimeSessionMock,
3031
decodeOpusStreamMock,
@@ -39,6 +40,7 @@ defineDiscordVoiceTests(
3940
makeVoiceConfig,
4041
createFollowManager,
4142
getSessionEntry,
43+
getVoiceReceive,
4244
beginSpeakerTurn,
4345
lastAgentCommandArgs,
4446
lastAgentCommandToolNames,
@@ -227,6 +229,7 @@ defineDiscordVoiceTests(
227229
sessionLifecycle: { status: "active" },
228230
playbackQueue: Promise.resolve(),
229231
processingQueue: Promise.resolve(),
232+
ttsStreamFallbackWarned: false,
230233
capture: createVoiceCaptureState(),
231234
receiveRecovery: createVoiceReceiveRecoveryState(),
232235
isStopped: () => false,
@@ -388,6 +391,79 @@ defineDiscordVoiceTests(
388391
await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));
389392
});
390393

394+
it("logs a failed streaming provider once per session when using file fallback", async () => {
395+
const replyText = "file fallback reply";
396+
agentCommandMock.mockResolvedValue({ payloads: [{ text: replyText }] } as never);
397+
const client = createClientWithMember("u-guest", "Guest", "4321");
398+
const manager = createManager(
399+
makeVoiceConfig({}, { groupPolicy: "open", allowFrom: ["discord:u-guest"] }),
400+
client,
401+
);
402+
await manager.join({ guildId: "g1", channelId: "1001" });
403+
const entry = getSessionEntry(manager);
404+
const receive = getVoiceReceive(manager);
405+
406+
for (let index = 0; index < 2; index += 1) {
407+
await receive.processSegment({
408+
entry,
409+
wavPath: "/tmp/test.wav",
410+
userId: "u-guest",
411+
durationSeconds: 1.2,
412+
});
413+
}
414+
await entry.playbackQueue;
415+
416+
const fallbackWarnings = loggerWarnMock.mock.calls
417+
.map(([message]) => String(message))
418+
.filter((message) => message.includes("using file fallback"));
419+
expect(fallbackWarnings).toEqual([
420+
"discord voice: streaming TTS failed provider=elevenlabs reasonCode=provider_error; using file fallback",
421+
]);
422+
expect(fallbackWarnings[0]).not.toContain(replyText);
423+
});
424+
425+
it("does not warn when an unsupported streaming provider uses file fallback", async () => {
426+
textToSpeechStreamMock.mockResolvedValueOnce({
427+
success: false,
428+
error: "TTS conversion failed: buffered does not support streaming TTS",
429+
attemptedProviders: ["buffered"],
430+
attempts: [
431+
{
432+
provider: "buffered",
433+
outcome: "skipped",
434+
reasonCode: "unsupported_for_streaming",
435+
error: "buffered does not support streaming TTS",
436+
},
437+
],
438+
});
439+
agentCommandMock.mockResolvedValueOnce({
440+
payloads: [{ text: "buffered provider reply" }],
441+
} as never);
442+
const client = createClientWithMember("u-guest", "Guest", "4321");
443+
const manager = createManager(
444+
makeVoiceConfig({}, { groupPolicy: "open", allowFrom: ["discord:u-guest"] }),
445+
client,
446+
);
447+
await manager.join({ guildId: "g1", channelId: "1001" });
448+
const entry = getSessionEntry(manager);
449+
450+
await getVoiceReceive(manager).processSegment({
451+
entry,
452+
wavPath: "/tmp/test.wav",
453+
userId: "u-guest",
454+
durationSeconds: 1.2,
455+
});
456+
await entry.playbackQueue;
457+
458+
expect(textToSpeechMock).toHaveBeenCalledOnce();
459+
expect(entry.player.play).toHaveBeenCalledOnce();
460+
expect(
461+
loggerWarnMock.mock.calls
462+
.map(([message]) => String(message))
463+
.filter((message) => message.includes("streaming TTS failed")),
464+
).toEqual([]);
465+
});
466+
391467
it("releases late TTS without playback after the voice session leaves", async () => {
392468
const connection = createConnectionMock();
393469
joinVoiceChannelMock.mockReturnValueOnce(connection);

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,7 @@ export class DiscordVoiceSessions {
451451
player,
452452
playbackQueue: Promise.resolve(),
453453
processingQueue: Promise.resolve(),
454+
ttsStreamFallbackWarned: false,
454455
capture: createVoiceCaptureState(),
455456
transcripts: options?.transcripts,
456457
receiveRecovery: createVoiceReceiveRecoveryState(),

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

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ const {
3636
textToSpeechStreamMock,
3737
textToSpeechMock,
3838
logVerboseMock,
39+
loggerWarnMock,
3940
resolveConfiguredRealtimeVoiceProviderMock,
4041
createRealtimeVoiceBridgeSessionMock,
4142
controlRealtimeVoiceAgentRunMock,
@@ -86,10 +87,24 @@ function buildVoiceTestHarness() {
8687
}),
8788
);
8889
textToSpeechStreamMock.mockReset();
89-
textToSpeechStreamMock.mockResolvedValue({ success: false, error: "stream unavailable" });
90+
textToSpeechStreamMock.mockResolvedValue({
91+
success: false,
92+
error: "TTS conversion failed: elevenlabs: upstream unavailable",
93+
attemptedProviders: ["elevenlabs"],
94+
attempts: [
95+
{
96+
provider: "elevenlabs",
97+
outcome: "failed",
98+
reasonCode: "provider_error",
99+
latencyMs: 12,
100+
error: "elevenlabs: upstream unavailable",
101+
},
102+
],
103+
});
90104
textToSpeechMock.mockReset();
91105
textToSpeechMock.mockResolvedValue({ success: true, audioPath: "/tmp/voice.mp3" });
92106
logVerboseMock.mockClear();
107+
loggerWarnMock.mockClear();
93108
updateVoiceStateMock.mockClear();
94109
enqueueSystemEventMock.mockClear();
95110
enqueueSystemEventMock.mockReturnValue(true);
@@ -553,6 +568,7 @@ function buildVoiceTestHarness() {
553568
sessionLifecycle: { status: "active" },
554569
playbackQueue: Promise.resolve(),
555570
processingQueue: Promise.resolve(),
571+
ttsStreamFallbackWarned: false,
556572
capture: createVoiceCaptureState(),
557573
receiveRecovery: createVoiceReceiveRecoveryState(),
558574
},
@@ -613,6 +629,7 @@ function buildVoiceTestHarness() {
613629
textToSpeechStreamMock,
614630
textToSpeechMock,
615631
logVerboseMock,
632+
loggerWarnMock,
616633
resolveConfiguredRealtimeVoiceProviderMock,
617634
createRealtimeVoiceBridgeSessionMock,
618635
controlRealtimeVoiceAgentRunMock,

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ const {
1616
textToSpeechStreamMock,
1717
textToSpeechMock,
1818
logVerboseMock,
19+
loggerWarnMock,
1920
resolveConfiguredRealtimeVoiceProviderMock,
2021
createRealtimeVoiceBridgeSessionMock,
2122
controlRealtimeVoiceAgentRunMock,
@@ -158,6 +159,7 @@ const {
158159
),
159160
textToSpeechMock: vi.fn(async () => ({ success: true, audioPath: "/tmp/voice.mp3" })),
160161
logVerboseMock: vi.fn(),
162+
loggerWarnMock: vi.fn(),
161163
resolveConfiguredRealtimeVoiceProviderMock: vi.fn<
162164
() => {
163165
provider: {
@@ -209,6 +211,7 @@ export const voiceTestMocks = {
209211
textToSpeechStreamMock,
210212
textToSpeechMock,
211213
logVerboseMock,
214+
loggerWarnMock,
212215
resolveConfiguredRealtimeVoiceProviderMock,
213216
createRealtimeVoiceBridgeSessionMock,
214217
controlRealtimeVoiceAgentRunMock,
@@ -277,6 +280,10 @@ vi.mock("openclaw/plugin-sdk/runtime-env", async () => {
277280
);
278281
return {
279282
...actual,
283+
createSubsystemLogger: (subsystem: string) => ({
284+
...actual.createSubsystemLogger(subsystem),
285+
warn: loggerWarnMock,
286+
}),
280287
logVerbose: logVerboseMock,
281288
};
282289
});

‎extensions/qa-lab/src/test-file-scenario-command-lifecycle.test.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ vi.mock("node:child_process", async (importOriginal) => {
2929
};
3030
});
3131

32-
import { isQaPosixProcessGroupAlive } from "./posix-process-group.js";
3332
import {
3433
resetQaScenarioCommandCleanupTimings,
3534
runQaScenarioCommandLifecycle,
@@ -135,10 +134,6 @@ describe.skipIf(process.platform === "win32")("qa scenario command real POSIX li
135134
timeoutMs: 5_000,
136135
});
137136
descendantPid = await waitForPidFile(descendantPidPath);
138-
const processGroupId = (spawnMock.mock.results[0]?.value as ChildProcess | undefined)?.pid;
139-
if (!processGroupId) {
140-
throw new Error("scenario command did not expose its process group id");
141-
}
142137
const startedAt = Date.now();
143138
const deadline = new AbortController();
144139
const result = await Promise.race([
@@ -155,7 +150,10 @@ describe.skipIf(process.platform === "win32")("qa scenario command real POSIX li
155150
stdout: "Docker scheduling finished\ndelayed descendant output\n",
156151
stderr: "",
157152
});
158-
expect(isQaPosixProcessGroupAlive(processGroupId)).toBe(false);
153+
if (descendantPid === undefined) {
154+
throw new Error("scenario command descendant did not expose its pid");
155+
}
156+
expect(isProcessRunning(descendantPid)).toBe(false);
159157
} finally {
160158
if (descendantPid && isProcessRunning(descendantPid)) {
161159
process.kill(descendantPid, "SIGKILL");

‎src/tts/tts-runtime-models.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ describe("TTS runtime voice model and streaming behavior", () => {
283283
expect(streamSynthesize).toHaveBeenCalledOnce();
284284
});
285285

286-
it("classifies streaming timeouts before falling back with raw text", async () => {
286+
it("classifies streaming timeouts before falling back with normalized speech text", async () => {
287287
// Real transport timeouts arrive as "TimeoutError" (fetch-timeout.ts), not
288288
// AbortError; the classifier must catch the shape providers actually throw.
289289
const timeoutStreamSynthesize = vi.fn(async () => {
@@ -338,6 +338,8 @@ describe("TTS runtime voice model and streaming behavior", () => {
338338
outcome: "success",
339339
reasonCode: "success",
340340
});
341-
expect(fallbackStreamSynthesize).toHaveBeenCalledWith(expect.objectContaining({ text }));
341+
expect(fallbackStreamSynthesize).toHaveBeenCalledWith(
342+
expect.objectContaining({ text: "Keep streaming Markdown raw!" }),
343+
);
342344
});
343345
});

‎src/tts/tts-streaming.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { OpenClawConfig } from "../config/types.js";
22
import type { TtsDirectiveOverrides } from "./provider-types.js";
33
import { assertSpeechRuntimeAvailable } from "./runtime-availability.js";
4+
import { normalizeSpeechText } from "./speech-text.js";
45
import type { TtsStreamResult, TtsSynthesisStreamResult } from "./tts-runtime-types.js";
56
import { executeTtsProviderAttempts, resolveTtsRequestSetup } from "./tts-synthesis-support.js";
67
import { resolveTtsSynthesisTarget } from "./tts-synthesis.js";
@@ -38,7 +39,7 @@ export async function streamSpeech(params: {
3839
config,
3940
persona,
4041
providers,
41-
synthesisText: params.text,
42+
synthesisText: normalizeSpeechText(params.text),
4243
providerOverrides: params.overrides?.providerOverrides,
4344
timeoutMs: params.timeoutMs,
4445
target,

0 commit comments

Comments
 (0)