Skip to content

Commit bac7d6b

Browse files
authored
fix(tts): preserve hidden speech answers when synthesis fails (#118690)
* fix(tts): preserve hidden speech answers when synthesis fails * fix(tts): preserve visible Slack fallback before channel activation * test(tts): respect plugin ownership boundaries
1 parent 317320a commit bac7d6b

2 files changed

Lines changed: 309 additions & 2 deletions

File tree

‎src/tts/tts-payload.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import { markReplyPayloadAsTtsSupplement, type ReplyPayload } from "../auto-reply/reply-payload.js";
2+
import { getChannelPlugin } from "../channels/plugins/registry.js";
23
import type { OpenClawConfig } from "../config/types.js";
34
import { isVerbose, logVerbose } from "../globals.js";
45
import { resolveSendableOutboundReplyParts } from "../infra/outbound/reply-payload-parts.js";
6+
import { hasReplyPayloadContent } from "../interactive/payload.js";
57
import { truncateUtf16Safe } from "../utils.js";
8+
import { normalizeMessageChannel } from "../utils/message-channel-core.js";
69
import { parseTtsDirectives } from "./directives.js";
710
import { canonicalizeSpeechProviderId, getSpeechProvider } from "./provider-registry.js";
811
import type { SpeechVoiceOption } from "./provider-types.js";
@@ -266,5 +269,13 @@ export async function maybeApplyTtsToPayload(
266269

267270
const latency = Date.now() - ttsStart;
268271
logVerbose(`TTS: conversion failed after ${latency}ms (${result.error ?? "unknown"}).`);
269-
return nextPayload;
272+
const channelId =
273+
explicitTtsText && nextPayload.channelData ? normalizeMessageChannel(params.channel) : null;
274+
const hasChannelData = channelId
275+
? getChannelPlugin(channelId)?.messaging?.hasStructuredReplyPayload?.({ payload: nextPayload })
276+
: undefined;
277+
// Channel-owned content checks keep transport-only metadata from silently dropping the answer.
278+
return explicitTtsText && !hasReplyPayloadContent(nextPayload, { hasChannelData })
279+
? { ...nextPayload, text: explicitTtsText }
280+
: nextPayload;
270281
}

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

Lines changed: 297 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,17 @@
11
import { rmSync } from "node:fs";
22
import path from "node:path";
3-
import { afterEach, describe, expect, it } from "vitest";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { createReplyDispatcher } from "../auto-reply/reply/reply-dispatcher.js";
5+
import { routeReply } from "../auto-reply/reply/route-reply.js";
6+
import * as bundledChannelPlugins from "../channels/plugins/bundled.js";
7+
import { getChannelPlugin } from "../channels/plugins/registry.js";
8+
import {
9+
captureActivePluginRegistrySnapshot,
10+
getActivePluginRegistry,
11+
restoreActivePluginRegistrySnapshot,
12+
setActivePluginRegistry,
13+
} from "../plugins/runtime.js";
14+
import { createChannelTestPluginBase, createTestRegistry } from "../test-utils/channel-plugins.js";
415
import {
516
clearRuntimeConfigSnapshot,
617
createMockSpeechProvider,
@@ -21,8 +32,58 @@ import {
2132
testApi,
2233
transcodeAudioBufferMock,
2334
type OpenClawConfig,
35+
type ReplyPayload,
2436
} from "./tts-runtime.test-support.js";
2537

38+
const routedPayloads = vi.hoisted(() => [] as ReplyPayload[]);
39+
40+
vi.mock("../channels/message/runtime.js", () => ({
41+
sendDurableMessageBatch: async ({ payloads }: { payloads: ReplyPayload[] }) => {
42+
routedPayloads.push(...payloads);
43+
return { status: "sent", results: [{ messageId: "tts-route-1" }] };
44+
},
45+
}));
46+
47+
function installStructuredReplyTestChannel(loaded: boolean): () => void {
48+
const previousRegistry = captureActivePluginRegistrySnapshot();
49+
const channelPlugin = {
50+
...createChannelTestPluginBase({ id: "slack" }),
51+
messaging: {
52+
hasStructuredReplyPayload: ({ payload }: { payload: ReplyPayload }) => {
53+
const blocks = (payload.channelData?.slack as { blocks?: unknown } | undefined)?.blocks;
54+
return Array.isArray(blocks) && blocks.length > 0;
55+
},
56+
},
57+
};
58+
const originalGetBundledChannelPlugin = bundledChannelPlugins.getBundledChannelPlugin;
59+
const bundledPluginOverride = loaded
60+
? undefined
61+
: vi
62+
.spyOn(bundledChannelPlugins, "getBundledChannelPlugin")
63+
.mockImplementation((channelId) =>
64+
channelId === channelPlugin.id
65+
? channelPlugin
66+
: originalGetBundledChannelPlugin(channelId),
67+
);
68+
setActivePluginRegistry(
69+
createTestRegistry(
70+
loaded
71+
? [
72+
{
73+
pluginId: "slack",
74+
source: "tts-runtime-fallback-test",
75+
plugin: channelPlugin,
76+
},
77+
]
78+
: [],
79+
),
80+
);
81+
return () => {
82+
bundledPluginOverride?.mockRestore();
83+
restoreActivePluginRegistrySnapshot(previousRegistry);
84+
};
85+
}
86+
2687
describe("TTS runtime provider fallback and delivery behavior", () => {
2788
afterEach(() => {
2889
setTtsMachinePrefsPathResolver();
@@ -31,6 +92,7 @@ describe("TTS runtime provider fallback and delivery behavior", () => {
3192
synthesizeMock.mockClear();
3293
prepareSynthesisMock.mockClear();
3394
transcodeAudioBufferMock.mockClear();
95+
routedPayloads.length = 0;
3496
installSpeechProviders([createMockSpeechProvider()]);
3597
});
3698

@@ -257,6 +319,240 @@ describe("TTS runtime provider fallback and delivery behavior", () => {
257319
expect(result).toBe(payload);
258320
});
259321

322+
it.each([
323+
{ failure: "speech provider fails", failProvider: true },
324+
{ failure: "audio persistence fails", failProvider: false },
325+
])("delivers audio-only TTS text when the $failure", async ({ failProvider }) => {
326+
const answer = "Your important answer is ready.";
327+
if (failProvider) {
328+
synthesizeMock.mockRejectedValueOnce(new Error("Speech provider unavailable"));
329+
}
330+
331+
const result = await maybeApplyTtsToPayloadCore(
332+
{
333+
payload: {
334+
text: `[[tts:text]] ${answer} [[/tts:text]]`,
335+
audioAsVoice: true,
336+
},
337+
cfg: createTtsConfig(`openclaw-speech-core-hidden-tts-failure-${failProvider}`),
338+
channel: "telegram",
339+
kind: "final",
340+
},
341+
async () => {
342+
throw new Error("Media exceeds configured limit");
343+
},
344+
);
345+
346+
expect(result).toEqual({ text: answer, audioAsVoice: true });
347+
expect((await import("./runtime-api.js")).getLastTtsAttempt()).toMatchObject({
348+
success: false,
349+
attemptedProviders: ["mock"],
350+
});
351+
});
352+
353+
it.each([
354+
{ failure: "speech provider fails", failProvider: true, structured: false, loaded: true },
355+
{ failure: "audio persistence fails", failProvider: false, structured: false, loaded: true },
356+
{
357+
failure: "speech provider fails with visible blocks",
358+
failProvider: true,
359+
structured: true,
360+
loaded: true,
361+
},
362+
{
363+
failure: "audio persistence fails with visible blocks",
364+
failProvider: false,
365+
structured: true,
366+
loaded: true,
367+
},
368+
{
369+
failure: "speech provider fails before channel activation",
370+
failProvider: true,
371+
structured: false,
372+
loaded: false,
373+
},
374+
{
375+
failure: "audio persistence fails before channel activation",
376+
failProvider: false,
377+
structured: false,
378+
loaded: false,
379+
},
380+
{
381+
failure: "speech provider fails with visible blocks before channel activation",
382+
failProvider: true,
383+
structured: true,
384+
loaded: false,
385+
},
386+
{
387+
failure: "audio persistence fails with visible blocks before channel activation",
388+
failProvider: false,
389+
structured: true,
390+
loaded: false,
391+
},
392+
])(
393+
"routes hidden speech through the actual dispatcher and channel router when $failure",
394+
async ({ failProvider, structured, loaded }) => {
395+
const restoreRegistry = installStructuredReplyTestChannel(loaded);
396+
try {
397+
const answer = "Your important answer is ready.";
398+
const cfg = createTtsConfig(
399+
`openclaw-speech-core-hidden-tts-router-${failProvider}-${structured}-${loaded}`,
400+
);
401+
const channelData = structured
402+
? {
403+
slack: {
404+
blocks: [
405+
{ type: "section", text: { type: "mrkdwn", text: "Visible channel card" } },
406+
],
407+
},
408+
}
409+
: { slack: { unfurl: false } };
410+
if (!loaded) {
411+
expect(getActivePluginRegistry()?.channels).toEqual([]);
412+
expect(
413+
getChannelPlugin("slack")?.messaging?.hasStructuredReplyPayload?.({
414+
payload: { channelData },
415+
}),
416+
).toBe(structured);
417+
}
418+
const routingResults: Array<Awaited<ReturnType<typeof routeReply>>> = [];
419+
if (failProvider) {
420+
synthesizeMock.mockRejectedValueOnce(new Error("Speech provider unavailable"));
421+
}
422+
423+
const dispatcher = createReplyDispatcher({
424+
beforeDeliver: (payload, info) =>
425+
maybeApplyTtsToPayloadCore(
426+
{
427+
payload,
428+
cfg,
429+
channel: "slack",
430+
kind: info.kind,
431+
},
432+
async () => {
433+
throw new Error("Media exceeds configured limit");
434+
},
435+
),
436+
deliver: async (payload, info) => {
437+
routingResults.push(
438+
await routeReply({
439+
payload,
440+
channel: "slack",
441+
to: "channel:C123",
442+
cfg,
443+
replyKind: info.kind,
444+
}),
445+
);
446+
},
447+
});
448+
449+
expect(
450+
dispatcher.sendFinalReply({
451+
text: `[[tts:text]]${answer}[[/tts:text]]`,
452+
channelData,
453+
}),
454+
).toBe(true);
455+
dispatcher.markComplete();
456+
await dispatcher.waitForIdle();
457+
458+
expect(routingResults).toEqual([{ ok: true, delivered: true, messageId: "tts-route-1" }]);
459+
expect(routedPayloads).toHaveLength(1);
460+
expect(routedPayloads[0]).toMatchObject({
461+
text: structured ? undefined : answer,
462+
channelData,
463+
});
464+
expect(dispatcher.getFailedCounts().final).toBe(0);
465+
expect((await import("./runtime-api.js")).getLastTtsAttempt()).toMatchObject({
466+
success: false,
467+
attemptedProviders: ["mock"],
468+
});
469+
} finally {
470+
restoreRegistry();
471+
}
472+
},
473+
);
474+
475+
it("keeps existing visible text when hidden TTS synthesis fails", async () => {
476+
synthesizeMock.mockRejectedValueOnce(new Error("Speech provider unavailable"));
477+
478+
const result = await maybeApplyTtsToPayloadCore(
479+
{
480+
payload: {
481+
text: "Visible answer [[tts:text]]Hidden expressive answer[[/tts:text]]",
482+
},
483+
cfg: createTtsConfig("openclaw-speech-core-visible-hidden-tts-provider-failure"),
484+
channel: "telegram",
485+
kind: "final",
486+
},
487+
async () => "/unused.ogg",
488+
);
489+
490+
expect(result).toEqual({ text: "Visible answer" });
491+
});
492+
493+
it("keeps hidden TTS text private when the reply already contains an attachment", async () => {
494+
const result = await maybeApplyTtsToPayloadCore(
495+
{
496+
payload: {
497+
text: "[[tts:text]]This must remain audio-only.[[/tts:text]]",
498+
mediaUrl: "https://example.invalid/already-attached.png",
499+
},
500+
cfg: createTtsConfig("openclaw-speech-core-hidden-tts-existing-attachment"),
501+
channel: "telegram",
502+
kind: "final",
503+
},
504+
async () => {
505+
throw new Error("Media storage must not be called");
506+
},
507+
);
508+
509+
expect(result).toEqual({
510+
text: undefined,
511+
mediaUrl: "https://example.invalid/already-attached.png",
512+
});
513+
expect(synthesizeMock).not.toHaveBeenCalled();
514+
});
515+
516+
it.each([
517+
{
518+
surface: "a presentation",
519+
content: { presentation: { blocks: [{ type: "text", text: "Visible presentation" }] } },
520+
},
521+
{
522+
surface: "an interactive reply",
523+
content: { interactive: { blocks: [{ type: "text", text: "Visible interactive reply" }] } },
524+
},
525+
{
526+
surface: "a location",
527+
content: { location: { latitude: 48.858844, longitude: 2.294351 } },
528+
},
529+
{
530+
surface: "channel data",
531+
content: { channelData: { visibleAction: { label: "Approve" } } },
532+
},
533+
] satisfies Array<{ surface: string; content: Partial<ReplyPayload> }>)(
534+
"keeps hidden TTS text private when $surface is already deliverable",
535+
async ({ content }) => {
536+
synthesizeMock.mockRejectedValueOnce(new Error("Speech provider unavailable"));
537+
538+
const result = await maybeApplyTtsToPayloadCore(
539+
{
540+
payload: {
541+
text: "[[tts:text]]This detail must remain audio-only.[[/tts:text]]",
542+
...content,
543+
},
544+
cfg: createTtsConfig("openclaw-speech-core-hidden-tts-existing-rich-content"),
545+
channel: "telegram",
546+
kind: "final",
547+
},
548+
async () => "/unused.ogg",
549+
);
550+
551+
expect(result).toEqual({ text: undefined, ...content });
552+
expect(synthesizeMock).toHaveBeenCalledOnce();
553+
},
554+
);
555+
260556
it("normalizes voice-note Markdown once before synthesis", async () => {
261557
const text =
262558
'This short explanation keeps the fenced literal below from becoming code-heavy.\n\n```md\nconst literal = "[x](y)";\n```';

0 commit comments

Comments
 (0)