Skip to content

Commit 4d91d44

Browse files
authored
fix(telegram): preserve callback action ownership
Keep Telegram native and typed callback routes under their owning handlers. Expired or malformed typed buttons now clear their controls and return visible unavailable feedback while legacy raw plugin callbacks remain compatible.
1 parent d6fc4a2 commit 4d91d44

4 files changed

Lines changed: 208 additions & 25 deletions

File tree

‎extensions/telegram/src/bot-handlers.callback.runtime.ts‎

Lines changed: 48 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,10 @@ import { resolveTelegramForumFlag, withResolvedTelegramForumFlag } from "./bot/h
3030
import type { TelegramGetChat } from "./bot/types.js";
3131
import { getTelegramCallbackQueryAnswerPromise } from "./callback-query-answer-state.js";
3232
import { resolveTelegramInlineButtonsScope } from "./inline-buttons.js";
33-
import { parseTelegramOpaqueCallbackData } from "./native-command-callback-data.js";
33+
import {
34+
hasTelegramOpaqueCallbackPrefix,
35+
parseTelegramOpaqueCallbackData,
36+
} from "./native-command-callback-data.js";
3437
import { isTelegramMessageNotModifiedError } from "./network-errors.js";
3538
import {
3639
hasTelegramQuestionCallbackPrefix,
@@ -101,6 +104,7 @@ export function registerTelegramCallbackQueryHandler(
101104
const isGroup =
102105
callbackMessage.chat.type === "group" || callbackMessage.chat.type === "supergroup";
103106
const nativeCallbackCommand = parseTelegramNativeCommandCallbackData(data);
107+
const hasReservedOpaquePrefix = hasTelegramOpaqueCallbackPrefix(data);
104108
const opaqueCallbackData = parseTelegramOpaqueCallbackData(data);
105109
const genericCallbackText = data.startsWith("/") ? data : `callback_data: ${data}`;
106110
const callbackCommandText =
@@ -118,15 +122,19 @@ export function registerTelegramCallbackQueryHandler(
118122
cfg: authorizationCfg,
119123
accountId,
120124
});
125+
const inlineButtonsUnavailable =
126+
inlineButtonsScope === "off" ||
127+
(inlineButtonsScope === "dm" && isGroup) ||
128+
(inlineButtonsScope === "group" && !isGroup);
121129
// Runtime controls retain their authorization after inline-button capability changes.
122-
if (!isRuntimeControlCallback) {
123-
if (
124-
inlineButtonsScope === "off" ||
125-
(inlineButtonsScope === "dm" && isGroup) ||
126-
(inlineButtonsScope === "group" && !isGroup)
127-
) {
128-
return;
129-
}
130+
// Stale typed controls cross this gate only to render their terminal result.
131+
if (
132+
!isRuntimeControlCallback &&
133+
inlineButtonsUnavailable &&
134+
!nativeCallbackCommand &&
135+
!hasReservedOpaquePrefix
136+
) {
137+
return;
130138
}
131139

132140
const messageThreadId = callbackMessage.message_thread_id;
@@ -199,6 +207,23 @@ export function registerTelegramCallbackQueryHandler(
199207
senderUsername,
200208
context: eventAuthContext,
201209
});
210+
const clearRoutedCallbackButtons = async () => {
211+
try {
212+
await actions.clearCallbackButtons();
213+
} catch (editErr) {
214+
if (
215+
!isTelegramMessageNotModifiedError(editErr) &&
216+
!isPermanentTelegramCallbackEditError(editErr)
217+
) {
218+
throw new TelegramRetryableCallbackError(editErr);
219+
}
220+
}
221+
};
222+
const terminalizeUnavailableCallback = async () => {
223+
logVerbose("telegram: typed callback unavailable (handler missing or payload invalid)");
224+
await clearRoutedCallbackButtons();
225+
await actions.replyToCallbackChat("This action is no longer available.");
226+
};
202227

203228
if (typedApprovalCallback) {
204229
await approvalRuntime.handleCanonical(typedApprovalCallback);
@@ -226,7 +251,16 @@ export function registerTelegramCallbackQueryHandler(
226251
return;
227252
}
228253
if (
229-
await handleTelegramInteractiveCallback({
254+
inlineButtonsUnavailable &&
255+
((nativeCallbackCommand && !legacyApprovalCallback) || hasReservedOpaquePrefix)
256+
) {
257+
await terminalizeUnavailableCallback();
258+
return;
259+
}
260+
if (
261+
!nativeCallbackCommand &&
262+
!inlineButtonsUnavailable &&
263+
(await handleTelegramInteractiveCallback({
230264
accountId,
231265
callback,
232266
ctx,
@@ -243,15 +277,16 @@ export function registerTelegramCallbackQueryHandler(
243277
actions,
244278
messageRuntime,
245279
authorizeCallback,
246-
})
280+
}))
247281
) {
248282
return;
249283
}
250284
if (legacyApprovalCallback) {
251285
await approvalRuntime.handleLegacy(legacyApprovalCallback);
252286
return;
253287
}
254-
if (opaqueCallbackData) {
288+
if (hasReservedOpaquePrefix) {
289+
await terminalizeUnavailableCallback();
255290
return;
256291
}
257292
if (
@@ -277,16 +312,7 @@ export function registerTelegramCallbackQueryHandler(
277312
const hasCallbackInlineKeyboard =
278313
(callbackMessage.reply_markup?.inline_keyboard?.length ?? 0) > 0;
279314
if (hasCallbackInlineKeyboard) {
280-
try {
281-
await actions.clearCallbackButtons();
282-
} catch (editErr) {
283-
if (
284-
!isTelegramMessageNotModifiedError(editErr) &&
285-
!isPermanentTelegramCallbackEditError(editErr)
286-
) {
287-
throw new TelegramRetryableCallbackError(editErr);
288-
}
289-
}
315+
await clearRoutedCallbackButtons();
290316
}
291317
const syntheticMessage = buildSyntheticTextMessage({
292318
base: withResolvedTelegramForumFlag(callbackMessage, isForum),

‎extensions/telegram/src/bot.create-telegram-bot.test.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1853,6 +1853,38 @@ describe("createTelegramBot", () => {
18531853
expect(answerCallbackQuerySpy).toHaveBeenCalledWith("cbq-plugin-1");
18541854
});
18551855

1856+
it("preserves raw tgcb1 callbacks emitted before the prefix became reserved", async () => {
1857+
const pluginHandler = vi.fn(async (ctx) => {
1858+
expect(ctx.callback.namespace).toBe("tgcb1");
1859+
expect(ctx.callback.payload).toBe("inspect:123");
1860+
return { handled: true };
1861+
});
1862+
expect(
1863+
registerPluginInteractiveHandler("legacy-tgcb1", {
1864+
channel: "telegram",
1865+
namespace: "tgcb1",
1866+
handler: pluginHandler,
1867+
}),
1868+
).toEqual({ ok: true });
1869+
1870+
createTelegramBot({ token: "tok" });
1871+
await getCallbackHandler()(
1872+
makeCallbackRetryContext({
1873+
id: "cbq-legacy-tgcb1",
1874+
data: "tgcb1:inspect:123",
1875+
messageId: 10,
1876+
}),
1877+
);
1878+
1879+
expect(pluginHandler).toHaveBeenCalledOnce();
1880+
expect(replySpy).not.toHaveBeenCalled();
1881+
expect(sendMessageSpy).not.toHaveBeenCalledWith(
1882+
1234,
1883+
"This action is no longer available.",
1884+
undefined,
1885+
);
1886+
});
1887+
18561888
it("preserves raw slash callback_query payloads as command text", async () => {
18571889
createTelegramBot({ token: "tok" });
18581890
const callbackHandler = getCallbackHandler();
@@ -2033,6 +2065,120 @@ describe("createTelegramBot", () => {
20332065
expect(payload.CommandSource).toBe("native");
20342066
expect(answerCallbackQuerySpy).toHaveBeenCalledWith("cbq-native-1");
20352067
});
2068+
2069+
it("keeps tgcmd native when a plugin registers the same namespace", async () => {
2070+
const pluginHandler = vi.fn(async () => ({ handled: true }));
2071+
expect(
2072+
registerPluginInteractiveHandler("namespace-collision", {
2073+
channel: "telegram",
2074+
namespace: "tgcmd",
2075+
handler: pluginHandler,
2076+
}),
2077+
).toEqual({ ok: true });
2078+
2079+
createTelegramBot({ token: "tok" });
2080+
await getCallbackHandler()(
2081+
makeCallbackRetryContext({
2082+
id: "cbq-native-collision",
2083+
data: "tgcmd:/fast status",
2084+
messageId: 10,
2085+
}),
2086+
);
2087+
2088+
expect(pluginHandler).not.toHaveBeenCalled();
2089+
expect(replySpy).toHaveBeenCalledTimes(1);
2090+
expect(requireValue(replySpy.mock.calls.at(0), "replySpy call")[0]).toMatchObject({
2091+
CommandBody: "/fast status",
2092+
CommandSource: "native",
2093+
});
2094+
});
2095+
2096+
it("terminalizes native callbacks after inline buttons are disabled", async () => {
2097+
const pluginHandler = vi.fn(async () => ({ handled: true }));
2098+
registerPluginInteractiveHandler("disabled-native-collision", {
2099+
channel: "telegram",
2100+
namespace: "tgcmd",
2101+
handler: pluginHandler,
2102+
});
2103+
loadConfig.mockReturnValue({
2104+
channels: {
2105+
telegram: {
2106+
dmPolicy: "open",
2107+
allowFrom: ["*"],
2108+
capabilities: { inlineButtons: "off" },
2109+
},
2110+
},
2111+
});
2112+
2113+
createTelegramBot({ token: "tok" });
2114+
await getCallbackHandler()(
2115+
makeCallbackRetryContext({
2116+
id: "cbq-disabled-native",
2117+
data: "tgcmd:/fast status",
2118+
messageId: 10,
2119+
message: {
2120+
reply_markup: {
2121+
inline_keyboard: [[{ text: "Status", callback_data: "tgcmd:/fast status" }]],
2122+
},
2123+
},
2124+
}),
2125+
);
2126+
2127+
expect(pluginHandler).not.toHaveBeenCalled();
2128+
expect(replySpy).not.toHaveBeenCalled();
2129+
expect(editMessageReplyMarkupSpy).toHaveBeenCalledWith(1234, 10, {
2130+
reply_markup: { inline_keyboard: [] },
2131+
});
2132+
expect(sendMessageSpy).toHaveBeenCalledWith(
2133+
1234,
2134+
"This action is no longer available.",
2135+
undefined,
2136+
);
2137+
});
2138+
2139+
it.each([
2140+
["stale", buildTelegramOpaqueCallbackData("missing-plugin:approve-1")],
2141+
["malformed", "tgcb1:invalid"],
2142+
])("terminalizes %s typed callbacks without raw-text fallthrough", async (_name, data) => {
2143+
const pluginHandler = vi.fn(async () => ({ handled: true }));
2144+
registerPluginInteractiveHandler("disabled-typed-owner", {
2145+
channel: "telegram",
2146+
namespace: "missing-plugin",
2147+
handler: pluginHandler,
2148+
});
2149+
loadConfig.mockReturnValue({
2150+
channels: {
2151+
telegram: {
2152+
dmPolicy: "open",
2153+
allowFrom: ["*"],
2154+
capabilities: { inlineButtons: "off" },
2155+
},
2156+
},
2157+
});
2158+
createTelegramBot({ token: "tok" });
2159+
await getCallbackHandler()(
2160+
makeCallbackRetryContext({
2161+
id: `cbq-opaque-${_name}`,
2162+
data,
2163+
messageId: 10,
2164+
message: {
2165+
reply_markup: { inline_keyboard: [[{ text: "Approve", callback_data: data }]] },
2166+
},
2167+
}),
2168+
);
2169+
2170+
expect(pluginHandler).not.toHaveBeenCalled();
2171+
expect(replySpy).not.toHaveBeenCalled();
2172+
expect(editMessageReplyMarkupSpy).toHaveBeenCalledWith(1234, 10, {
2173+
reply_markup: { inline_keyboard: [] },
2174+
});
2175+
expect(sendMessageSpy).toHaveBeenCalledWith(
2176+
1234,
2177+
"This action is no longer available.",
2178+
undefined,
2179+
);
2180+
});
2181+
20362182
it("reloads callback model routing bindings without recreating the bot", async () => {
20372183
const buildModelsProviderDataMock =
20382184
telegramBotDepsForTest.buildModelsProviderData as unknown as BuildModelsProviderDataMock;

‎extensions/telegram/src/bot.test.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2176,7 +2176,7 @@ describe("createTelegramBot", () => {
21762176
expect(answerCallbackQuerySpy).toHaveBeenCalledWith("cbq-plugin-approve");
21772177
});
21782178

2179-
it("does not resolve opaque approval-shaped plugin callbacks", async () => {
2179+
it("terminalizes unowned opaque approval-shaped plugin callbacks", async () => {
21802180
mockTelegramConfig({
21812181
dmPolicy: "open",
21822182
allowFrom: ["*"],
@@ -2194,7 +2194,14 @@ describe("createTelegramBot", () => {
21942194
);
21952195

21962196
expect(resolveExecApprovalSpy).not.toHaveBeenCalled();
2197-
expect(editMessageReplyMarkupSpy).not.toHaveBeenCalled();
2197+
expect(editMessageReplyMarkupSpy).toHaveBeenCalledWith(1234, 25, {
2198+
reply_markup: { inline_keyboard: [] },
2199+
});
2200+
expect(sendMessageSpy).toHaveBeenCalledWith(
2201+
1234,
2202+
"This action is no longer available.",
2203+
undefined,
2204+
);
21982205
expect(answerCallbackQuerySpy).toHaveBeenCalledWith("cbq-opaque-plugin-approve");
21992206
});
22002207

‎extensions/telegram/src/native-command-callback-data.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,15 @@ export function buildTelegramOpaqueCallbackData(value: string): string {
2222
return `${TELEGRAM_OPAQUE_CALLBACK_PREFIX}${checksumTelegramOpaqueCallbackValue(value)}:${value}`;
2323
}
2424

25+
export function hasTelegramOpaqueCallbackPrefix(data?: string | null): boolean {
26+
return data?.startsWith(TELEGRAM_OPAQUE_CALLBACK_PREFIX) === true;
27+
}
28+
2529
export function parseTelegramOpaqueCallbackData(data?: string | null): string | null {
2630
if (!data) {
2731
return null;
2832
}
29-
if (!data.startsWith(TELEGRAM_OPAQUE_CALLBACK_PREFIX)) {
33+
if (!hasTelegramOpaqueCallbackPrefix(data)) {
3034
return null;
3135
}
3236
const encoded = data.slice(TELEGRAM_OPAQUE_CALLBACK_PREFIX.length);

0 commit comments

Comments
 (0)