fix(telegram): clear webhook state before polling startup

Co-authored-by: Peter Machona <7957943+chilu18@users.noreply.github.com>
This commit is contained in:
Peter Steinberger
2026-02-22 17:48:08 +01:00
parent 81384daeb4
commit 5069250faf
3 changed files with 79 additions and 0 deletions

View File

@@ -28,6 +28,7 @@ Docs: https://docs.openclaw.ai
- Telegram/Webhook: keep webhook monitors alive until gateway abort signals fire, preventing false channel exits and immediate webhook auto-restart loops.
- Telegram/Polling: retry recoverable setup-time network failures in monitor startup and await runner teardown before retry to avoid overlapping polling sessions.
- Telegram/Polling: clear Telegram webhooks (`deleteWebhook`) before starting long-poll `getUpdates`, including retry handling for transient cleanup failures.
- Signal/RPC: guard malformed Signal RPC JSON responses with a clear status-scoped error and add regression coverage for invalid JSON responses. (#22995) Thanks @adhitShet.
- Gateway/Subagents: guard gateway and subagent session-key/message trim paths against undefined inputs to prevent early `Cannot read properties of undefined (reading 'trim')` crashes during subagent spawn and wait flows.
- Agents/Workspace: guard `resolveUserPath` against undefined/null input to prevent `Cannot read properties of undefined (reading 'trim')` crashes when workspace paths are missing in embedded runner flows.

View File

@@ -227,6 +227,50 @@ describe("monitorTelegramProvider (grammY)", () => {
expect(runSpy).toHaveBeenCalledTimes(2);
});
it("deletes webhook before starting polling", async () => {
const order: string[] = [];
api.deleteWebhook.mockReset();
api.deleteWebhook.mockImplementationOnce(async () => {
order.push("deleteWebhook");
return true;
});
runSpy.mockImplementationOnce(() => {
order.push("run");
return {
task: () => Promise.resolve(),
stop: vi.fn(),
isRunning: () => false,
};
});
await monitorTelegramProvider({ token: "tok" });
expect(api.deleteWebhook).toHaveBeenCalledWith({ drop_pending_updates: false });
expect(order).toEqual(["deleteWebhook", "run"]);
});
it("retries recoverable deleteWebhook failures before polling", async () => {
const cleanupError = Object.assign(new TypeError("fetch failed"), {
cause: Object.assign(new Error("connect timeout"), {
code: "UND_ERR_CONNECT_TIMEOUT",
}),
});
api.deleteWebhook.mockReset();
api.deleteWebhook.mockRejectedValueOnce(cleanupError).mockResolvedValueOnce(true);
runSpy.mockImplementationOnce(() => ({
task: () => Promise.resolve(),
stop: vi.fn(),
isRunning: () => false,
}));
await monitorTelegramProvider({ token: "tok" });
expect(api.deleteWebhook).toHaveBeenCalledTimes(2);
expect(computeBackoff).toHaveBeenCalled();
expect(sleepWithAbort).toHaveBeenCalled();
expect(runSpy).toHaveBeenCalledTimes(1);
});
it("retries setup-time recoverable errors before starting polling", async () => {
const setupError = Object.assign(new TypeError("fetch failed"), {
cause: Object.assign(new Error("connect timeout"), {

View File

@@ -9,6 +9,7 @@ import { registerUnhandledRejectionHandler } from "../infra/unhandled-rejections
import type { RuntimeEnv } from "../runtime.js";
import { resolveTelegramAccount } from "./accounts.js";
import { resolveTelegramAllowedUpdates } from "./allowed-updates.js";
import { withTelegramApiErrorLogging } from "./api-logging.js";
import { createTelegramBot } from "./bot.js";
import { isRecoverableTelegramNetworkError } from "./network-errors.js";
import { makeProxyFetch } from "./proxy.js";
@@ -180,6 +181,7 @@ export async function monitorTelegramProvider(opts: MonitorTelegramOpts = {}) {
// Use grammyjs/runner for concurrent update processing
let restartAttempts = 0;
let webhookCleared = false;
const runnerOptions = createTelegramRunnerOptions(cfg);
while (!opts.abortSignal?.aborted) {
@@ -219,6 +221,38 @@ export async function monitorTelegramProvider(opts: MonitorTelegramOpts = {}) {
continue;
}
if (!webhookCleared) {
try {
await withTelegramApiErrorLogging({
operation: "deleteWebhook",
runtime: opts.runtime,
fn: () => bot.api.deleteWebhook({ drop_pending_updates: false }),
});
webhookCleared = true;
} catch (err) {
if (opts.abortSignal?.aborted) {
return;
}
if (!isRecoverableTelegramNetworkError(err, { context: "unknown" })) {
throw err;
}
restartAttempts += 1;
const delayMs = computeBackoff(TELEGRAM_POLL_RESTART_POLICY, restartAttempts);
(opts.runtime?.error ?? console.error)(
`Telegram webhook cleanup failed: ${formatErrorMessage(err)}; retrying in ${formatDurationPrecise(delayMs)}.`,
);
try {
await sleepWithAbort(delayMs, opts.abortSignal);
} catch (sleepErr) {
if (opts.abortSignal?.aborted) {
return;
}
throw sleepErr;
}
continue;
}
}
const runner = run(bot, runnerOptions);
activeRunner = runner;
const stopOnAbort = () => {