mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 07:38:43 +01:00
* fix(telegram): a chat that stops receiving is an alert, and a picture never vanishes silently On 2026-11-23 a screenshot of an event sent on Telegram reached nothing: no agent turn, no booking, no alert, no error. The owner's chat bot is collected by the OpenClaw gateway (long polling), and the only health check asked whether the gateway answered HTTP, which it can do while its Telegram channel collects nothing. - check-gateway also asks Telegram for the chat bot's inbox (getWebhookInfo, read-only, lib/telegram/inbox.ts): a webhook set on the polled bot, or updates waiting on two ticks in a row, raises telegram_inbox_stuck once and says so in the chat (outbound still works when inbound is dead); it clears on recovery. Skipped while the gateway itself is down. - Loki's notification bot can no longer take over the chat bot: the same token in TELEGRAM_NOTIFY_BOT_TOKEN is ignored (env.ts warns), since its setWebhook would cut the gateway off from every owner message. - ensureWebhook re-registers when Telegram reports 401/403 (a rotated AUTH_SECRET left the URL matching and every update refused), keeping the queued updates; the route logs refused calls (throttled). - A photo or image file sent to the notification bot gets a reply saying it was not read or booked and where to send it, and is recorded; a failed reply is logged instead of swallowed. Test: scripts/test/telegram-inbound.ts with a Telegram photo-update fixture. Co-Authored-By: Claude <noreply@anthropic.com> * docs(telegram): register the chat-bot inbox probe (src/lib/telegram/inbox.ts) check-telegram-registry failed on #1765: inbox.ts calls api.telegram.org but had no row in docs/telegram-notifications.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: catomean <catomean@users.noreply.github.com>
142 lines
6.1 KiB
TypeScript
142 lines
6.1 KiB
TypeScript
// Telegram inbound: a picture never vanishes without a word, and a chat bot
|
|
// whose messages stop reaching the gateway is noticed.
|
|
//
|
|
// 2026-11-23: a screenshot of an event sent on Telegram reached nothing — no
|
|
// agent turn, no booking, no alert, no error — while the gateway answered HTTP
|
|
// and every check was green. This pins the three seams that made that silent.
|
|
import assert from "node:assert/strict";
|
|
import { readFileSync } from "node:fs";
|
|
import { join, dirname } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { classifyNotifyUpdate, PICTURE_REPLY } from "../../src/lib/telegram/notify-update";
|
|
import { probeTelegramInbox, telegramInboxVerdict } from "../../src/lib/telegram/inbox";
|
|
import { notifyBotToken, webhookNeedsSet } from "../../src/lib/telegram/notify-bot";
|
|
|
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
const photoUpdate = JSON.parse(
|
|
readFileSync(join(here, "fixtures/telegram-photo-update.json"), "utf8"),
|
|
);
|
|
|
|
function telegram(result: Record<string, unknown>, ok = true): typeof fetch {
|
|
return (async () =>
|
|
new Response(
|
|
JSON.stringify(ok ? { ok, result } : { ok, description: "Unauthorized" }),
|
|
)) as typeof fetch;
|
|
}
|
|
|
|
async function main() {
|
|
// 1. A photo update (the fixture is Telegram's real shape: sizes smallest
|
|
// first, a caption) is a picture, not "other" text.
|
|
const intent = classifyNotifyUpdate(photoUpdate);
|
|
assert.deepEqual(intent, { kind: "picture", chatId: 100000001, source: "photo" });
|
|
assert.match(PICTURE_REPLY, /can't read pictures/, "the reply says it was not read");
|
|
assert.match(PICTURE_REPLY, /nothing .* saved or booked/, "and that nothing was booked");
|
|
|
|
// An image sent as a file is a picture too; a PDF is not.
|
|
const asFile = (mime: string) => ({
|
|
message: { chat: { id: 7, type: "private" }, document: { file_id: "x", mime_type: mime } },
|
|
});
|
|
assert.deepEqual(classifyNotifyUpdate(asFile("image/png")), {
|
|
kind: "picture",
|
|
chatId: 7,
|
|
source: "image-document",
|
|
});
|
|
assert.equal(classifyNotifyUpdate(asFile("application/pdf")).kind, "other");
|
|
|
|
// The existing branches are unchanged.
|
|
const text = (t: string) => ({ message: { chat: { id: 7, type: "private" }, text: t } });
|
|
assert.deepEqual(classifyNotifyUpdate(text("/start abcdefgh12")), {
|
|
kind: "start",
|
|
chatId: 7,
|
|
code: "abcdefgh12",
|
|
username: null,
|
|
});
|
|
assert.equal(classifyNotifyUpdate(text("/stop")).kind, "stop");
|
|
assert.equal(classifyNotifyUpdate(text("hello")).kind, "other");
|
|
assert.equal(
|
|
classifyNotifyUpdate({ message: { chat: { id: 7, type: "group" }, text: "hi" } }).kind,
|
|
"ignore",
|
|
"groups are not answered",
|
|
);
|
|
assert.deepEqual(
|
|
classifyNotifyUpdate({
|
|
my_chat_member: { chat: { id: 7 }, new_chat_member: { status: "kicked" } },
|
|
}),
|
|
{ kind: "left", chatId: 7 },
|
|
);
|
|
|
|
// 2. The chat bot's inbox, from Telegram's side.
|
|
const polling = await probeTelegramInbox("t", telegram({ url: "", pending_update_count: 0 }));
|
|
assert.deepEqual(polling, { known: true, webhookHost: null, pending: 0, lastError: null });
|
|
assert.equal(telegramInboxVerdict(polling, null).stuck, false, "polling, empty → fine");
|
|
|
|
// A webhook on the polled bot: the gateway gets nothing. Host only, never the path.
|
|
const hooked = await probeTelegramInbox(
|
|
"t",
|
|
telegram({
|
|
url: "https://loki.example/api/telegram/webhook?secret=abc",
|
|
pending_update_count: 3,
|
|
last_error_message: "Wrong response from the webhook: 403 Forbidden",
|
|
}),
|
|
);
|
|
const hv = telegramInboxVerdict(hooked, null);
|
|
assert.equal(hv.stuck, true, "a webhook on the chat bot is stuck at once");
|
|
assert.match(hv.detail, /loki\.example/);
|
|
assert.doesNotMatch(hv.detail, /secret=abc|\/api\//, "no path or query in the detail");
|
|
|
|
// Waiting updates: one sighting is a message in flight, two in a row is a dead poller.
|
|
const waiting = await probeTelegramInbox("t", telegram({ url: "", pending_update_count: 1 }));
|
|
assert.equal(telegramInboxVerdict(waiting, null).stuck, false, "first sighting → not yet");
|
|
assert.equal(telegramInboxVerdict(waiting, 0).stuck, false, "was empty last tick → not yet");
|
|
assert.equal(telegramInboxVerdict(waiting, 2).stuck, true, "waiting on two ticks → stuck");
|
|
|
|
// Could not ask Telegram: unknown, which changes no alert. The token never leaks.
|
|
const refused = await probeTelegramInbox("SECRET-TOKEN", telegram({}, false));
|
|
assert.equal(refused.known, false);
|
|
assert.equal(telegramInboxVerdict(refused, 5).stuck, null);
|
|
const down = await probeTelegramInbox("SECRET-TOKEN", (async () => {
|
|
throw new TypeError("fetch failed", {
|
|
cause: new Error("getaddrinfo ENOTFOUND api.telegram.org"),
|
|
});
|
|
}) as typeof fetch);
|
|
assert.equal(down.known, false);
|
|
assert.match(down.known ? "" : down.detail, /ENOTFOUND/);
|
|
assert.doesNotMatch(JSON.stringify([refused, down]), /SECRET-TOKEN/);
|
|
|
|
// 3. Loki's notification bot can never take over the chat bot.
|
|
const saved = { n: process.env.TELEGRAM_NOTIFY_BOT_TOKEN, c: process.env.TELEGRAM_BOT_TOKEN };
|
|
process.env.TELEGRAM_BOT_TOKEN = "111:chat";
|
|
process.env.TELEGRAM_NOTIFY_BOT_TOKEN = "111:chat";
|
|
assert.equal(notifyBotToken(), null, "the chat bot's token is not a notification bot");
|
|
process.env.TELEGRAM_NOTIFY_BOT_TOKEN = "222:notify";
|
|
assert.equal(notifyBotToken(), "222:notify");
|
|
for (const [k, v] of [
|
|
["TELEGRAM_NOTIFY_BOT_TOKEN", saved.n],
|
|
["TELEGRAM_BOT_TOKEN", saved.c],
|
|
] as const) {
|
|
if (v === undefined) delete process.env[k];
|
|
else process.env[k] = v;
|
|
}
|
|
|
|
// And a webhook refused for a stale secret is re-registered, not trusted.
|
|
const url = "https://loki.example/api/telegram/webhook";
|
|
assert.equal(webhookNeedsSet({ url }, url), "none");
|
|
assert.equal(webhookNeedsSet({ url: "" }, url), "register");
|
|
assert.equal(webhookNeedsSet(undefined, url), "register");
|
|
assert.equal(
|
|
webhookNeedsSet(
|
|
{ url, last_error_message: "Wrong response from the webhook: 403 Forbidden" },
|
|
url,
|
|
),
|
|
"resecret",
|
|
);
|
|
assert.equal(
|
|
webhookNeedsSet({ url, last_error_message: "Connection timed out" }, url),
|
|
"none",
|
|
"a network error is not a secret problem",
|
|
);
|
|
|
|
console.log("telegram-inbound: ok");
|
|
}
|
|
main();
|