Skip to content

Commit 47bd1bb

Browse files
authored
fix(telegram): report degraded inline controls
Preserve readable fallbacks and tell the model when Telegram drops unencodable controls, including recovery guidance.\n\nCo-authored-by: Guoji-XYDT <[email protected]>
1 parent c1a2f4d commit 47bd1bb

5 files changed

Lines changed: 324 additions & 20 deletions

File tree

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

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1761,6 +1761,22 @@ describe("handleTelegramAction", () => {
17611761
).rejects.toThrow(/cannot be combined/i);
17621762
});
17631763

1764+
it("rejects location sends mixed with presentation text", async () => {
1765+
await expect(
1766+
handleTelegramAction(
1767+
{
1768+
action: "sendMessage",
1769+
to: "123456",
1770+
location: { latitude: 1, longitude: 2 },
1771+
presentation: {
1772+
blocks: [{ type: "text", text: "caption" }],
1773+
},
1774+
},
1775+
telegramConfig(),
1776+
),
1777+
).rejects.toThrow(/cannot be combined/i);
1778+
});
1779+
17641780
it("renders presentation text when message content is omitted", async () => {
17651781
await handleTelegramAction(
17661782
{
@@ -1872,6 +1888,95 @@ describe("handleTelegramAction", () => {
18721888
]);
18731889
});
18741890

1891+
it("reports dropped controls and delivers their readable fallback", async () => {
1892+
const result = await handleTelegramAction(
1893+
{
1894+
action: "sendMessage",
1895+
to: "123456",
1896+
content: "Choose",
1897+
presentation: {
1898+
blocks: [
1899+
{
1900+
type: "buttons",
1901+
buttons: [
1902+
{ label: "Retry", value: "retry" },
1903+
{ label: "Copy manually", value: "x".repeat(65) },
1904+
],
1905+
},
1906+
],
1907+
},
1908+
},
1909+
telegramConfig({ capabilities: { inlineButtons: "all" } }),
1910+
);
1911+
1912+
const call = mockCall(sendMessageTelegram, 0, "degraded controls");
1913+
expect(call[1]).toBe("Choose\n\n- Copy manually");
1914+
expect(requireRecord(call[2], "degraded controls options").buttons).toEqual([
1915+
[{ text: "Retry", callback_data: "retry" }],
1916+
]);
1917+
expect(resultDetails(result)).toMatchObject({
1918+
ok: true,
1919+
warning: "Telegram delivered 1 unencodable control as readable text.",
1920+
degradedDelivery: {
1921+
droppedControls: 1,
1922+
fallback: "text",
1923+
reasons: ["callback_data_too_long"],
1924+
callbackDataLimitBytes: 64,
1925+
},
1926+
});
1927+
});
1928+
1929+
it("keeps a 64-byte Unicode callback native without a degradation warning", async () => {
1930+
const callbackData = "😀".repeat(16);
1931+
const result = await handleTelegramAction(
1932+
{
1933+
action: "sendMessage",
1934+
to: "123456",
1935+
content: "Choose",
1936+
presentation: {
1937+
blocks: [{ type: "buttons", buttons: [{ label: "Exact", value: callbackData }] }],
1938+
},
1939+
},
1940+
telegramConfig({ capabilities: { inlineButtons: "all" } }),
1941+
);
1942+
1943+
const call = mockCall(sendMessageTelegram, 0, "64-byte callback");
1944+
expect(requireRecord(call[2], "64-byte callback options").buttons).toEqual([
1945+
[{ text: "Exact", callback_data: callbackData }],
1946+
]);
1947+
expect(resultDetails(result)).not.toHaveProperty("degradedDelivery");
1948+
});
1949+
1950+
it("delivers control fallback text before a standalone location", async () => {
1951+
const result = await handleTelegramAction(
1952+
{
1953+
action: "sendMessage",
1954+
to: "123456",
1955+
location: { latitude: 48.858844, longitude: 2.294351 },
1956+
presentation: {
1957+
blocks: [
1958+
{ type: "buttons", buttons: [{ label: "Copy manually", value: "x".repeat(65) }] },
1959+
],
1960+
},
1961+
},
1962+
telegramConfig({ capabilities: { inlineButtons: "all" } }),
1963+
);
1964+
1965+
const durableCall = mockCall(sendDurableMessageBatch, 0, "degraded location");
1966+
expect(requireRecord(durableCall[0], "degraded location params")).toMatchObject({
1967+
payloads: [
1968+
{
1969+
text: "- Copy manually",
1970+
location: { latitude: 48.858844, longitude: 2.294351 },
1971+
},
1972+
],
1973+
});
1974+
expect(resultDetails(result)).toMatchObject({
1975+
ok: true,
1976+
degradedDelivery: { droppedControls: 1, fallback: "text" },
1977+
});
1978+
});
1979+
18751980
it("edits reply markup when editMessage only changes buttons", async () => {
18761981
await handleTelegramAction(
18771982
{
@@ -1898,6 +2003,60 @@ describe("handleTelegramAction", () => {
18982003
expect(requireRecord(call[3], "reply markup edit options").token).toBe("tok");
18992004
});
19002005

2006+
it("reports controls dropped from a reply-markup edit", async () => {
2007+
const result = await handleTelegramAction(
2008+
{
2009+
action: "editMessage",
2010+
chatId: "123456",
2011+
messageId: 321,
2012+
presentation: {
2013+
blocks: [
2014+
{
2015+
type: "buttons",
2016+
buttons: [
2017+
{ label: "Open", value: "open" },
2018+
{ label: "Copy manually", value: "x".repeat(65) },
2019+
],
2020+
},
2021+
],
2022+
},
2023+
},
2024+
telegramConfig({ capabilities: { inlineButtons: "all" } }),
2025+
);
2026+
2027+
const call = mockCall(editMessageReplyMarkupTelegram, 0, "degraded reply markup edit");
2028+
expect(call[2]).toEqual([[{ text: "Open", callback_data: "open" }]]);
2029+
expect(resultDetails(result)).toMatchObject({
2030+
ok: true,
2031+
warning: "Telegram could not deliver 1 control.",
2032+
degradedDelivery: { droppedControls: 1, fallback: "not_delivered" },
2033+
});
2034+
});
2035+
2036+
it("returns a recoverable result when every edited control is unencodable", async () => {
2037+
const result = await handleTelegramAction(
2038+
{
2039+
action: "editMessage",
2040+
chatId: "123456",
2041+
messageId: 321,
2042+
presentation: {
2043+
blocks: [
2044+
{ type: "buttons", buttons: [{ label: "Copy manually", value: "x".repeat(65) }] },
2045+
],
2046+
},
2047+
},
2048+
telegramConfig({ capabilities: { inlineButtons: "all" } }),
2049+
);
2050+
2051+
expect(editMessageTelegram).not.toHaveBeenCalled();
2052+
expect(editMessageReplyMarkupTelegram).not.toHaveBeenCalled();
2053+
expect(resultDetails(result)).toMatchObject({
2054+
ok: false,
2055+
warning: "Telegram could not deliver 1 control.",
2056+
degradedDelivery: { droppedControls: 1, fallback: "not_delivered" },
2057+
});
2058+
});
2059+
19012060
it.each([
19022061
{ description: "non-empty", caption: "Updated caption", richMessages: false },
19032062
{ description: "empty", caption: "", richMessages: false },

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

Lines changed: 95 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,12 @@ import {
3131
resolveDefaultTelegramAccountId,
3232
resolveTelegramPollActionGateState,
3333
} from "./accounts.js";
34-
import { resolveTelegramInlineButtons } from "./button-types.js";
34+
import { TELEGRAM_CALLBACK_DATA_MAX_BYTES } from "./approval-callback-data.js";
35+
import {
36+
resolveTelegramInlineButtons,
37+
type TelegramButtonBuildOptions,
38+
type TelegramDroppedControl,
39+
} from "./button-types.js";
3540
import { telegramInboundEventDelivery } from "./inbound-event-delivery.js";
3641
import {
3742
resolveTelegramInlineButtonsScope,
@@ -219,7 +224,7 @@ function readTelegramSendMediaUrls(params: Record<string, unknown>) {
219224
function resolveTelegramButtonsFromParams(
220225
params: Record<string, unknown>,
221226
presentation = normalizeMessagePresentation(params.presentation),
222-
options?: { allowWebAppButtons?: boolean },
227+
options?: TelegramButtonBuildOptions,
223228
) {
224229
return resolveTelegramInlineButtons(
225230
{
@@ -272,7 +277,59 @@ function readTelegramSendContent(params: {
272277
if (content == null && !params.mediaUrl && !params.hasButtons && !params.hasLocation) {
273278
throw new Error("content required.");
274279
}
275-
return content ?? "";
280+
return {
281+
content: content ?? "",
282+
hasExplicitContent: explicitContent != null,
283+
};
284+
}
285+
286+
function renderTelegramDroppedControlFallback(controls: readonly TelegramDroppedControl[]): string {
287+
return renderMessagePresentationFallbackText({
288+
presentation: {
289+
blocks: [
290+
{
291+
type: "buttons",
292+
buttons: controls.map((control) => ({ label: control.label, value: "unavailable" })),
293+
},
294+
],
295+
},
296+
});
297+
}
298+
299+
function appendTelegramDroppedControlFallback(
300+
text: string,
301+
controls: readonly TelegramDroppedControl[],
302+
): string {
303+
const fallback = renderTelegramDroppedControlFallback(controls);
304+
if (!fallback || text === fallback || text.endsWith(`\n\n${fallback}`)) {
305+
return text;
306+
}
307+
return [text, fallback].filter(Boolean).join("\n\n");
308+
}
309+
310+
function buildTelegramControlDegradation(
311+
controls: readonly TelegramDroppedControl[],
312+
fallbackDelivered: boolean,
313+
) {
314+
if (controls.length === 0) {
315+
return undefined;
316+
}
317+
const reasons = [...new Set(controls.map((control) => control.reason))];
318+
const hasOverflow = reasons.includes("callback_data_too_long");
319+
return {
320+
warning: fallbackDelivered
321+
? `Telegram delivered ${controls.length} unencodable control${controls.length === 1 ? "" : "s"} as readable text.`
322+
: `Telegram could not deliver ${controls.length} control${controls.length === 1 ? "" : "s"}.`,
323+
degradedDelivery: {
324+
droppedControls: controls.length,
325+
fallback: fallbackDelivered ? "text" : "not_delivered",
326+
reasons,
327+
...(hasOverflow ? { callbackDataLimitBytes: TELEGRAM_CALLBACK_DATA_MAX_BYTES } : {}),
328+
guidance: hasOverflow
329+
? `Shorten callback data to at most ${TELEGRAM_CALLBACK_DATA_MAX_BYTES} UTF-8 bytes and retry if clickable controls are required.`
330+
: "Retry with a supported control action if clickable controls are required.",
331+
},
332+
};
276333
}
277334

278335
function normalizeTelegramDeliveryPin(params: Record<string, unknown>) {
@@ -482,19 +539,34 @@ export async function handleTelegramAction(
482539
const firstMediaUrl = mediaUrls[0];
483540
const location = normalizeOutboundLocation(params.location);
484541
const presentation = normalizeMessagePresentation(params.presentation);
542+
const droppedControls: TelegramDroppedControl[] = [];
485543
const buttons = resolveTelegramButtonsFromParams(params, presentation, {
486544
allowWebAppButtons: resolveTelegramTargetChatType(to) === "direct",
545+
onDroppedControl: (control) => droppedControls.push(control),
487546
});
488-
const content = readTelegramSendContent({
547+
const resolvedContent = readTelegramSendContent({
489548
args: params,
490549
mediaUrl: firstMediaUrl,
491550
hasButtons: Array.isArray(buttons) && buttons.length > 0,
492551
hasLocation: Boolean(location),
493552
interactive: params.interactive,
494553
presentation,
495554
});
555+
const content =
556+
droppedControls.length > 0 && resolvedContent.hasExplicitContent
557+
? appendTelegramDroppedControlFallback(resolvedContent.content, droppedControls)
558+
: resolvedContent.content;
559+
const droppedControlFallback =
560+
droppedControls.length > 0 ? renderTelegramDroppedControlFallback(droppedControls) : "";
561+
const hasOnlyDroppedControlFallback =
562+
!resolvedContent.hasExplicitContent &&
563+
droppedControlFallback.length > 0 &&
564+
content.trim() === droppedControlFallback.trim();
496565
const asVideoNote = readBooleanParam(params, "asVideoNote") ?? false;
497-
if (location && (content.trim() || mediaUrls.length > 0 || asVideoNote)) {
566+
if (
567+
location &&
568+
((content.trim() && !hasOnlyDroppedControlFallback) || mediaUrls.length > 0 || asVideoNote)
569+
) {
498570
throw new Error("Telegram location sends cannot be combined with message text or media.");
499571
}
500572
if (asVideoNote && mediaUrls.length !== 1) {
@@ -602,6 +674,7 @@ export async function handleTelegramAction(
602674
ok: true,
603675
messageId: result.messageId,
604676
chatId: result.chatId,
677+
...buildTelegramControlDegradation(droppedControls, Boolean(content.trim())),
605678
});
606679
}
607680

@@ -738,15 +811,28 @@ export async function handleTelegramAction(
738811
accountId,
739812
context: options,
740813
});
741-
const content =
814+
let content =
742815
readStringParam(params, "content", { allowEmpty: false }) ??
743816
readStringParam(params, "message", { allowEmpty: false });
744817
// Telegram treats an explicit empty caption as a request to remove it.
745-
const caption = readStringParam(params, "caption", { allowEmpty: true });
818+
let caption = readStringParam(params, "caption", { allowEmpty: true });
819+
const droppedControls: TelegramDroppedControl[] = [];
746820
const buttons = resolveTelegramButtonsFromParams(params, undefined, {
747821
allowWebAppButtons: resolveTelegramTargetChatType(chatId ?? "") === "direct",
822+
onDroppedControl: (control) => droppedControls.push(control),
748823
});
824+
if (droppedControls.length > 0) {
825+
if (caption != null) {
826+
caption = appendTelegramDroppedControlFallback(caption, droppedControls);
827+
} else if (content != null) {
828+
content = appendTelegramDroppedControlFallback(content, droppedControls);
829+
}
830+
}
749831
if (content == null && caption == null && buttons === undefined) {
832+
const degradation = buildTelegramControlDegradation(droppedControls, false);
833+
if (degradation) {
834+
return jsonResult({ ok: false, ...degradation });
835+
}
750836
throw new Error("content required.");
751837
}
752838
if (buttons !== undefined) {
@@ -782,6 +868,7 @@ export async function handleTelegramAction(
782868
ok: true,
783869
messageId: result.messageId,
784870
chatId: result.chatId,
871+
...buildTelegramControlDegradation(droppedControls, false),
785872
});
786873
}
787874
const result = await telegramActionRuntime.editMessageTelegram(
@@ -801,6 +888,7 @@ export async function handleTelegramAction(
801888
ok: true,
802889
messageId: result.messageId,
803890
chatId: result.chatId,
891+
...buildTelegramControlDegradation(droppedControls, true),
804892
});
805893
}
806894

‎extensions/telegram/src/approval-callback-data.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { buildApprovalResolutionRef } from "openclaw/plugin-sdk/approval-reference-runtime";
33
import type { MessagePresentationAction } from "openclaw/plugin-sdk/interactive-runtime";
44

5-
const TELEGRAM_CALLBACK_DATA_MAX_BYTES = 64;
5+
export const TELEGRAM_CALLBACK_DATA_MAX_BYTES = 64;
66
const TELEGRAM_APPROVAL_CALLBACK_PREFIX = "tga1:";
77

88
export type TelegramApprovalCallback = Extract<MessagePresentationAction, { type: "approval" }>;

‎extensions/telegram/src/button-types.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -647,6 +647,25 @@ describe("buildTelegramPresentationButtons", () => {
647647
).toBeUndefined();
648648
});
649649

650+
it("records Web App gating separately from callback overflow", () => {
651+
const dropped: Array<{ reason: string; callbackDataBytes?: number }> = [];
652+
buildTelegramPresentationButtons(
653+
{
654+
blocks: [
655+
{
656+
type: "buttons",
657+
buttons: [
658+
{ label: "App", action: { type: "web-app", url: "https://example.com/app" } },
659+
],
660+
},
661+
],
662+
},
663+
{ onDroppedControl: (control) => dropped.push(control) },
664+
);
665+
666+
expect(dropped).toEqual([{ label: "App", reason: "web_app_unavailable" }]);
667+
});
668+
650669
it("skips hosted widget actions without a Telegram web app URL", () => {
651670
expect(
652671
buildTelegramPresentationButtons({

0 commit comments

Comments
 (0)