diff options
| author | Kenneth Lien <kenneth@anthropic.com> | 2026-03-20 10:55:27 -0700 |
|---|---|---|
| committer | Kenneth Lien <kenneth@anthropic.com> | 2026-03-20 10:55:27 -0700 |
| commit | 1daff5f2242e93a31fe734475caba9d19770ec43 (patch) | |
| tree | ab53b2b695d376fdcacddcb254a13fd5bfc9cac2 /external_plugins | |
| parent | 90accf6fd2008fe0ee9578ebc088740c3a754d58 (diff) | |
telegram: retry on 409 Conflict instead of crashing
During /mcp reload or when a zombie from a previous session still holds
the polling slot, the new process gets 409 Conflict on its first
getUpdates and dies immediately. Retry with backoff until the slot
frees — typically within a second or two.
Also handles the two-sessions case: the second Claude Code instance
keeps retrying (with a clear message about what's happening) and takes
over when the first one exits.
Fixes #804 #794, partial #788 (issue 4)
Diffstat (limited to 'external_plugins')
| -rw-r--r-- | external_plugins/telegram/server.ts | 38 |
1 files changed, 31 insertions, 7 deletions
diff --git a/external_plugins/telegram/server.ts b/external_plugins/telegram/server.ts index 8acd52a2..977c2060 100644 --- a/external_plugins/telegram/server.ts +++ b/external_plugins/telegram/server.ts @@ -15,7 +15,7 @@ import { ListToolsRequestSchema, CallToolRequestSchema, } from '@modelcontextprotocol/sdk/types.js' -import { Bot, InputFile, type Context } from 'grammy' +import { Bot, GrammyError, InputFile, type Context } from 'grammy' import type { ReactionTypeEmoji } from 'grammy/types' import { randomBytes } from 'crypto' import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, statSync, renameSync, realpathSync, chmodSync } from 'fs' @@ -593,9 +593,33 @@ async function handleInbound( }) } -void bot.start({ - onStart: info => { - botUsername = info.username - process.stderr.write(`telegram channel: polling as @${info.username}\n`) - }, -}) +// 409 Conflict = another getUpdates consumer is still active (zombie from a +// previous session, or a second Claude Code instance). Retry with backoff +// until the slot frees up instead of crashing on the first rejection. +void (async () => { + for (let attempt = 1; ; attempt++) { + try { + await bot.start({ + onStart: info => { + botUsername = info.username + process.stderr.write(`telegram channel: polling as @${info.username}\n`) + }, + }) + return // bot.stop() was called — clean exit from the loop + } catch (err) { + if (err instanceof GrammyError && err.error_code === 409) { + const delay = Math.min(1000 * attempt, 15000) + const detail = attempt === 1 + ? ' — another instance is polling (zombie session, or a second Claude Code running?)' + : '' + process.stderr.write( + `telegram channel: 409 Conflict${detail}, retrying in ${delay / 1000}s\n`, + ) + await new Promise(r => setTimeout(r, delay)) + continue + } + process.stderr.write(`telegram channel: polling failed: ${err}\n`) + return + } + } +})() |
