Skip to content

Commit e3d553b

Browse files
authored
fix(channels): surface Discord voice failures and preserve Telegram controls (#125152)
* fix(channels): surface degraded Discord and Telegram sends * fix(telegram): preserve legacy slash callbacks * fix(ci): correct env-var count after version define removal
1 parent 0e7f8c9 commit e3d553b

11 files changed

Lines changed: 228 additions & 70 deletions

‎config/env-var-count-budget.txt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Distinct OPENCLAW_* names in production source under src, packages, and extensions.
22
# Ratchet: lower this number when cleanup removes names; never raise it without owner approval.
33
# Worker bundle installation no longer injects OPENCLAW_STATE_DIR into a remote npm process.
4-
# The retired compile-time version define no longer contributes OPENCLAW_VERSION.
5-
501
4+
# OPENCLAW_VERSION remains a supported runtime override after compile-time define retirement.
5+
502

‎extensions/discord/src/outbound-adapter.test.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,8 @@ describe("discordOutbound", () => {
495495
expectedText: "spoken answer",
496496
},
497497
])("falls back to $name when audioAsVoice delivery fails", async ({ payload, expectedText }) => {
498-
hoisted.sendVoiceMessageDiscordMock.mockRejectedValueOnce(new Error("ffmpeg unavailable"));
498+
const voiceError = new Error("ffmpeg unavailable");
499+
hoisted.sendVoiceMessageDiscordMock.mockRejectedValueOnce(voiceError);
499500

500501
const result = await discordOutbound.sendPayload?.({
501502
cfg: {},
@@ -520,10 +521,15 @@ describe("discordOutbound", () => {
520521
messageId: "msg-1",
521522
target: { kind: "channel", id: "ch-1" },
522523
});
524+
expect(outboundWarnSpy).toHaveBeenCalledWith(
525+
"discord voice send failed; continuing without voice",
526+
{ error: voiceError },
527+
);
523528
});
524529

525530
it("does not duplicate already-delivered TTS supplement text when audioAsVoice delivery fails", async () => {
526-
hoisted.sendVoiceMessageDiscordMock.mockRejectedValueOnce(new Error("ffmpeg unavailable"));
531+
const voiceError = new Error("ffmpeg unavailable");
532+
hoisted.sendVoiceMessageDiscordMock.mockRejectedValueOnce(voiceError);
527533

528534
const result = await discordOutbound.sendPayload?.({
529535
cfg: {},
@@ -553,6 +559,10 @@ describe("discordOutbound", () => {
553559
parts: [],
554560
},
555561
});
562+
expect(outboundWarnSpy).toHaveBeenCalledWith(
563+
"discord voice send failed; continuing without voice",
564+
{ error: voiceError },
565+
);
556566
});
557567

558568
it("does not treat delivery progress failures as voice delivery failures", async () => {

‎extensions/discord/src/outbound-payload.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
sendPayloadMediaSequenceOrFallback,
1111
sendTextMediaPayload,
1212
} from "openclaw/plugin-sdk/reply-payload";
13+
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
1314
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
1415
import { normalizeDiscordApprovalPayload } from "./outbound-approval.js";
1516
import {
@@ -31,6 +32,8 @@ type DiscordOutboundPayloadContext = Parameters<
3132
>[0];
3233
type DiscordPayloadSendContext = Awaited<ReturnType<typeof createDiscordPayloadSendContext>>;
3334

35+
const log = createSubsystemLogger("discord/outbound");
36+
3437
function resolveDiscordDeliveryProgress(ctx: DiscordOutboundPayloadContext) {
3538
return ctx.onDeliveryResult
3639
? async (result: Awaited<ReturnType<DiscordPayloadSendContext["send"]>>) => {
@@ -130,12 +133,12 @@ export async function sendDiscordOutboundPayload(params: {
130133
? undefined
131134
: supplement?.spokenText;
132135
const fallbackText = visibleFallbackText ?? hiddenFallbackText;
136+
if (!fallbackText && !supplement?.visibleTextAlreadyDelivered) {
137+
throw err;
138+
}
139+
log.warn("discord voice send failed; continuing without voice", { error: err });
133140
if (!fallbackText) {
134-
if (supplement?.visibleTextAlreadyDelivered) {
135-
lastResult = createDiscordUnknownPayloadResult(sendContext.target);
136-
} else {
137-
throw err;
138-
}
141+
lastResult = createDiscordUnknownPayloadResult(sendContext.target);
139142
} else {
140143
lastResult = await sendContext.send(sendContext.target, fallbackText, {
141144
verbose: false,

‎extensions/telegram/src/action-runtime.ts‎

Lines changed: 2 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
} from "./accounts.js";
3535
import { TELEGRAM_CALLBACK_DATA_MAX_BYTES } from "./approval-callback-data.js";
3636
import {
37+
appendTelegramDroppedControlFallback,
3738
resolveTelegramInlineButtons,
3839
type TelegramButtonBuildOptions,
3940
type TelegramDroppedControl,
@@ -290,30 +291,6 @@ function readTelegramSendContent(params: {
290291
};
291292
}
292293

293-
function renderTelegramDroppedControlFallback(controls: readonly TelegramDroppedControl[]): string {
294-
return renderMessagePresentationFallbackText({
295-
presentation: {
296-
blocks: [
297-
{
298-
type: "buttons",
299-
buttons: controls.map((control) => ({ label: control.label, value: "unavailable" })),
300-
},
301-
],
302-
},
303-
});
304-
}
305-
306-
function appendTelegramDroppedControlFallback(
307-
text: string,
308-
controls: readonly TelegramDroppedControl[],
309-
): string {
310-
const fallback = renderTelegramDroppedControlFallback(controls);
311-
if (!fallback || text === fallback || text.endsWith(`\n\n${fallback}`)) {
312-
return text;
313-
}
314-
return [text, fallback].filter(Boolean).join("\n\n");
315-
}
316-
317294
function buildTelegramControlDegradation(
318295
controls: readonly TelegramDroppedControl[],
319296
fallbackDelivered: boolean,
@@ -564,8 +541,7 @@ export async function handleTelegramAction(
564541
droppedControls.length > 0 && resolvedContent.hasExplicitContent
565542
? appendTelegramDroppedControlFallback(resolvedContent.content, droppedControls)
566543
: resolvedContent.content;
567-
const droppedControlFallback =
568-
droppedControls.length > 0 ? renderTelegramDroppedControlFallback(droppedControls) : "";
544+
const droppedControlFallback = appendTelegramDroppedControlFallback("", droppedControls);
569545
const hasOnlyDroppedControlFallback =
570546
!resolvedContent.hasExplicitContent &&
571547
droppedControlFallback.length > 0 &&

‎extensions/telegram/src/bot-message-dispatch-reply.ts‎

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,10 @@ import type {
4141
TelegramReplyStateSlice,
4242
} from "./bot-message-dispatch.types.js";
4343
import {
44+
appendTelegramDroppedControlFallback,
4445
resolveTelegramInlineButtons,
4546
resolveTelegramQuestionOptionIndices,
47+
type TelegramDroppedControl,
4648
type TelegramInlineButtons,
4749
} from "./button-types.js";
4850
import {
@@ -53,6 +55,7 @@ import {
5355
} from "./error-policy.js";
5456
import { shouldSuppressLocalTelegramExecApprovalPrompt } from "./exec-approvals.js";
5557
import { createTelegramReasoningStepState } from "./reasoning-lane-coordinator.js";
58+
import { resolveTelegramTargetChatType } from "./targets.js";
5659

5760
type BufferedDispatchParams = Parameters<
5861
TelegramBotDeps["dispatchReplyWithBufferedBlockDispatcher"]
@@ -87,20 +90,31 @@ function toTelegramVisiblePartialDeliveryError(error: unknown): unknown {
8790
: createChannelPartialDeliveryError(error, { visibleReplySent: true });
8891
}
8992

90-
function resolvePayloadTelegramInlineButtons(
93+
function resolvePayloadTelegramControls(
94+
turn: Turn,
9195
payload: ReplyPayload,
92-
): TelegramInlineButtons | undefined {
96+
): { payload: ReplyPayload; buttons: TelegramInlineButtons | undefined } {
9397
const telegramData = payload.channelData?.telegram as
9498
| { buttons?: TelegramInlineButtons }
9599
| undefined;
96-
return resolveTelegramInlineButtons(
100+
const droppedControls: TelegramDroppedControl[] = [];
101+
const buttons = resolveTelegramInlineButtons(
97102
{
98103
buttons: telegramData?.buttons,
99104
presentation: normalizeMessagePresentation(payload.presentation),
100105
interactive: payload.interactive,
101106
},
102-
{ questionOptionIndices: resolveTelegramQuestionOptionIndices(payload) },
107+
{
108+
allowWebAppButtons: resolveTelegramTargetChatType(String(turn.context.chatId)) === "direct",
109+
onDroppedControl: (control) => droppedControls.push(control),
110+
questionOptionIndices: resolveTelegramQuestionOptionIndices(payload),
111+
},
103112
);
113+
const text = appendTelegramDroppedControlFallback(payload.text ?? "", droppedControls);
114+
return {
115+
payload: text === (payload.text ?? "") ? payload : { ...payload, text },
116+
buttons,
117+
};
104118
}
105119

106120
function hasExecApprovalPayload(payload: ReplyPayload): boolean {
@@ -140,11 +154,12 @@ async function flushBufferedFinalAnswer(turn: Turn, currentPayloadVisible = fals
140154
return;
141155
}
142156
try {
157+
const controls = resolvePayloadTelegramControls(turn, buffered);
143158
const result = await deliverFinalAnswerText(
144159
turn,
145-
buffered.payload,
146-
buffered.text,
147-
resolvePayloadTelegramInlineButtons(buffered.payload),
160+
controls.payload,
161+
controls.payload.text ?? "",
162+
controls.buttons,
148163
settlement?.onPlatformSendDispatch,
149164
settlement?.bindPendingFinalDelivery,
150165
);
@@ -218,7 +233,8 @@ export async function deliverReply(
218233
if (!deduped) {
219234
return await settleTerminalNoVisibleDelivery(turn, info);
220235
}
221-
const effectivePayload = deduped;
236+
const controls = resolvePayloadTelegramControls(turn, deduped);
237+
const effectivePayload = controls.payload;
222238
if (
223239
shouldSuppressLocalTelegramExecApprovalPrompt({
224240
cfg: turn.cfg,
@@ -229,7 +245,7 @@ export async function deliverReply(
229245
turn.queuedFinal = true;
230246
return await settleTerminalNoVisibleDelivery(turn, info);
231247
}
232-
const telegramButtons = resolvePayloadTelegramInlineButtons(effectivePayload);
248+
const telegramButtons = controls.buttons;
233249
const lanePayload =
234250
info.kind === "block" &&
235251
typeof payload.text === "string" &&
@@ -294,10 +310,9 @@ export async function deliverReply(
294310
resolve: resolveFinalization,
295311
reject: rejectFinalization,
296312
};
297-
turn.reasoningStepState.bufferFinalAnswer({
298-
payload: effectivePayload,
299-
text: segment.update.text,
300-
});
313+
turn.reasoningStepState.bufferFinalAnswer(
314+
applyTextToPayload(effectivePayload, segment.update.text),
315+
);
301316
continue;
302317
}
303318
if (segment.lane === "reasoning") {

‎extensions/telegram/src/bot-message-dispatch.draft-finalization.test.ts‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
emitTelegramMessageSentHooks,
1414
expectDeliverRepliesParams,
1515
expectRecordFields,
16+
loadSessionStore,
1617
mockCallArg,
1718
mockDefaultSessionEntry,
1819
readLatestAssistantTextByIdentity,
@@ -114,6 +115,141 @@ describeTelegramDispatch("dispatchTelegramMessage draft-finalization", () => {
114115
expectRecordFields(mockCallArg(editMessageTelegram, 0, 3), { buttons });
115116
});
116117

118+
it("keeps DM Web App buttons when finalizing the streamed preview", async () => {
119+
const { answerDraftStream } = setupDraftStreams({ answerMessageId: 2001 });
120+
dispatchReplyWithBufferedBlockDispatcher.mockImplementation(
121+
async ({ dispatcherOptions, replyOptions }) => {
122+
await replyOptions?.onPartialReply?.({ text: "Opening the app" });
123+
await dispatcherOptions.deliver(
124+
{
125+
text: "Open the app",
126+
presentation: {
127+
blocks: [
128+
{
129+
type: "buttons",
130+
buttons: [
131+
{
132+
label: "Launch",
133+
action: { type: "web-app", url: "https://example.com/app" },
134+
},
135+
],
136+
},
137+
],
138+
},
139+
},
140+
{ kind: "final" },
141+
);
142+
return { queuedFinal: true };
143+
},
144+
);
145+
146+
await dispatchWithContext({
147+
context: createContext(),
148+
streamMode: "partial",
149+
telegramCfg: { richMessages: true, streaming: { mode: "partial" } },
150+
});
151+
152+
expect(answerDraftStream.update).toHaveBeenLastCalledWith(
153+
"Open the app",
154+
expect.objectContaining({ onPlatformSendDispatch: expect.any(Function) }),
155+
);
156+
expectRecordFields(mockCallArg(editMessageTelegram, 0, 3), {
157+
buttons: [[{ text: "Launch", web_app: { url: "https://example.com/app" } }]],
158+
});
159+
expect(deliverReplies).not.toHaveBeenCalled();
160+
});
161+
162+
it("renders dropped controls in the finalized streamed preview", async () => {
163+
const { answerDraftStream } = setupDraftStreams({ answerMessageId: 2001 });
164+
dispatchReplyWithBufferedBlockDispatcher.mockImplementation(
165+
async ({ dispatcherOptions, replyOptions }) => {
166+
await replyOptions?.onPartialReply?.({ text: "Preparing controls" });
167+
await dispatcherOptions.deliver(
168+
{
169+
text: "Choose",
170+
presentation: {
171+
blocks: [
172+
{
173+
type: "buttons",
174+
buttons: [{ label: "Copy manually", value: "x".repeat(65) }],
175+
},
176+
],
177+
},
178+
},
179+
{ kind: "final" },
180+
);
181+
return { queuedFinal: true };
182+
},
183+
);
184+
185+
await dispatchWithContext({
186+
context: createContext(),
187+
streamMode: "partial",
188+
telegramCfg: { richMessages: true, streaming: { mode: "partial" } },
189+
});
190+
191+
expect(answerDraftStream.update).toHaveBeenLastCalledWith(
192+
"Choose\n\n- Copy manually",
193+
expect.objectContaining({ onPlatformSendDispatch: expect.any(Function) }),
194+
);
195+
expect(deliverReplies).not.toHaveBeenCalled();
196+
});
197+
198+
it("keeps mixed controls intact through buffered finalization", async () => {
199+
const { answerDraftStream } = setupDraftStreams({ answerMessageId: 2001 });
200+
loadSessionStore.mockReturnValue({ s1: { reasoningLevel: "stream" } });
201+
deliverReplies
202+
.mockResolvedValueOnce({ delivered: false })
203+
.mockResolvedValueOnce({ delivered: true });
204+
dispatchReplyWithBufferedBlockDispatcher.mockImplementation(async ({ dispatcherOptions }) => {
205+
await dispatcherOptions.deliver(
206+
{ text: "<think>first attempt</think>", isReasoning: true },
207+
{ kind: "block" },
208+
);
209+
await dispatcherOptions.deliver(
210+
{
211+
presentation: {
212+
blocks: [
213+
{
214+
type: "buttons",
215+
buttons: [
216+
{ label: "Retry", value: "retry" },
217+
{ label: "Copy manually", value: "x".repeat(65) },
218+
],
219+
},
220+
],
221+
},
222+
},
223+
{ kind: "final" },
224+
);
225+
await dispatcherOptions.deliver(
226+
{ text: "<think>second attempt</think>", isReasoning: true },
227+
{ kind: "block" },
228+
);
229+
return { queuedFinal: true };
230+
});
231+
232+
await dispatchWithContext({
233+
context: createContext({
234+
ctxPayload: { SessionKey: "s1" } as TelegramMessageContext["ctxPayload"],
235+
}),
236+
});
237+
238+
expect(answerDraftStream.update).toHaveBeenCalledWith(
239+
"- Copy manually",
240+
expect.objectContaining({ onPlatformSendDispatch: expect.any(Function) }),
241+
);
242+
expectRecordFields(mockCallArg(editMessageTelegram, 0, 3), {
243+
buttons: [[{ text: "Retry", callback_data: "retry" }]],
244+
});
245+
const fallbackReplies = deliverReplies.mock.calls.flatMap((call) =>
246+
((call[0] as { replies?: Array<{ text?: string }> }).replies ?? []).map(
247+
(reply) => reply.text,
248+
),
249+
);
250+
expect(fallbackReplies).not.toContain("- Copy manually");
251+
});
252+
117253
it("finalizes an ordinary block-only draft when no final follows", async () => {
118254
const { answerDraftStream } = setupDraftStreams({ answerMessageId: 2001 });
119255
dispatchReplyWithBufferedBlockDispatcher.mockImplementation(async ({ dispatcherOptions }) => {

0 commit comments

Comments
 (0)