Skip to content

fix(telegram): report lastEventAt to channel health monitor - #37850

Closed
jakozloski wants to merge 5 commits into
openclaw:mainfrom
jakozloski:jakozloski/fix-telegram-health-status
Closed

jakozloski wants to merge 5 commits into
openclaw:mainfrom
jakozloski:jakozloski/fix-telegram-health-status

Conversation

@jakozloski

Copy link
Copy Markdown

Summary

  • The Telegram provider never updated lastEventAt in the channel health snapshot, causing the health monitor to declare "stale-socket" and restart the bot every 30 minutes — even when the connection was healthy
  • Thread setStatus from the channel plugin through monitorTelegramProvider → createTelegramBot → startTelegramWebhook
  • Add grammY middleware for lastEventAt on all inbound updates and lastInboundAt only for message/channel_post
  • Add transport-level heartbeat via getUpdates API transformer (polling) and periodic getWebhookInfo ping (webhook) for idle-channel liveness

Test plan

  • Verify Telegram bot responds to messages after deploy
  • Check gateway logs show lastEventAt updates, no more "stale-socket" restarts
  • Wait >30 min idle — confirm transport heartbeat keeps channel healthy
  • Failure drill: block Telegram API → verify health monitor detects staleness → unblock → verify recovery
  • Run pnpm test -- --grep telegram

🤖 Generated with Claude Code

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: S labels Mar 6, 2026
@greptile-apps

greptile-apps Bot commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes the Telegram channel health monitor's "stale-socket" false-positive by threading a setStatus callback through to update lastEventAt on all inbound updates (via grammY middleware) and on transport-level liveness signals (polling: getUpdates API transformer; webhook: periodic getWebhookInfo ping). The core approach is sound and will resolve the stale-socket restarts.

However, there are two issues:

  1. lastInboundAt middleware is unreachable: The middleware registered at lines 421–428 to track message/channel_post activity is registered after registerTelegramHandlers(), which installs terminal handlers (lines 1468/1493) that don't call next(). In grammY's middleware chain, this prevents the downstream middleware from ever running. Moving the lastInboundAt block to before registerTelegramHandlers will fix this.

  2. Webhook heartbeat has no immediate startup ping: setInterval doesn't run until 10 minutes have elapsed. A freshly started idle webhook will have stale lastEventAt for up to 10 minutes. Adding void ping() immediately after the interval creation closes this window.

Confidence Score: 3/5

  • The core lastEventAt fix is correct but lastInboundAt tracking is broken due to middleware ordering, and webhook startup liveness has a 10-minute gap.
  • The primary objective—preventing false "stale-socket" restarts by stamping lastEventAt on every update and on transport heartbeats—is implemented correctly. However, lastInboundAt tracking (used for distinguishing transport liveness from actual user message activity) will never fire in practice because its middleware is registered after terminal message handlers. The webhook heartbeat's 10-minute startup delay is a secondary concern but still worth closing. Both issues are concrete and actionable.
  • src/telegram/bot.ts requires moving the lastInboundAt middleware block before registerTelegramHandlers(). src/telegram/webhook.ts requires adding an immediate ping() call at startup.

Last reviewed commit: 4f63343

Comment thread src/telegram/bot.ts Outdated
Comment on lines +421 to +428
// Track lastInboundAt only for message-bearing updates (not reactions/callbacks).
if (opts.setStatus) {
const setStatus = opts.setStatus;
bot.on(["message", "channel_post"], async (_ctx, next) => {
setStatus({ lastInboundAt: Date.now() });
await next();
});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bot.on(["message", "channel_post"], ...) middleware for lastInboundAt is registered after registerTelegramHandlers(), which at lines 1468 and 1493 of bot-handlers.ts registers terminal bot.on("message", ...) and bot.on("channel_post", ...) handlers that never call next().

In grammY, middleware registered after a terminal filter handler is never reached for updates that were consumed by that handler. Because registerTelegramHandlers registers handlers with signatures like async (ctx) => { ... } (no next parameter), the chain stops there. The lastInboundAt middleware at line 424 will therefore never fire for real messages or channel posts.

Move this block to immediately after the lastEventAt middleware (around line 135), before any message-processing handlers are registered:

Suggested change
// Track lastInboundAt only for message-bearing updates (not reactions/callbacks).
if (opts.setStatus) {
const setStatus = opts.setStatus;
bot.on(["message", "channel_post"], async (_ctx, next) => {
setStatus({ lastInboundAt: Date.now() });
await next();
});
}
// Track lastInboundAt only for message-bearing updates (not reactions/callbacks).
if (opts.setStatus) {
const setStatus = opts.setStatus;
bot.on(["message", "channel_post"], async (_ctx, next) => {
setStatus({ lastInboundAt: Date.now() });
await next();
});
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/telegram/bot.ts
Line: 421-428

Comment:
The `bot.on(["message", "channel_post"], ...)` middleware for `lastInboundAt` is registered **after** `registerTelegramHandlers()`, which at lines 1468 and 1493 of `bot-handlers.ts` registers terminal `bot.on("message", ...)` and `bot.on("channel_post", ...)` handlers that never call `next()`.

In grammY, middleware registered after a terminal filter handler is never reached for updates that were consumed by that handler. Because `registerTelegramHandlers` registers handlers with signatures like `async (ctx) => { ... }` (no `next` parameter), the chain stops there. The `lastInboundAt` middleware at line 424 will therefore **never fire** for real messages or channel posts.

Move this block to immediately after the `lastEventAt` middleware (around line 135), before any message-processing handlers are registered:

```suggestion
  // Track lastInboundAt only for message-bearing updates (not reactions/callbacks).
  if (opts.setStatus) {
    const setStatus = opts.setStatus;
    bot.on(["message", "channel_post"], async (_ctx, next) => {
      setStatus({ lastInboundAt: Date.now() });
      await next();
    });
  }
```

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0721511 — moved the lastInboundAt middleware block to before registerTelegramHandlers() so it runs before the terminal handlers.

// API unreachable — don't update, let health monitor detect staleness
}
};
webhookHeartbeat = setInterval(ping, 10 * 60_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setInterval(ping, 10 * 60_000) only fires after the first full 10-minute interval elapses. For an idle webhook channel (no inbound updates after startup), the health monitor will see a stale lastEventAt for up to 10 minutes before the first heartbeat runs.

Adding an immediate call to ping() after the interval is created would close this window and ensure the transport heartbeat activates on startup:

Suggested change
webhookHeartbeat = setInterval(ping, 10 * 60_000);
webhookHeartbeat = setInterval(ping, 10 * 60_000);
void ping();
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/telegram/webhook.ts
Line: 274

Comment:
`setInterval(ping, 10 * 60_000)` only fires after the first full 10-minute interval elapses. For an idle webhook channel (no inbound updates after startup), the health monitor will see a stale `lastEventAt` for up to 10 minutes before the first heartbeat runs.

Adding an immediate call to `ping()` after the interval is created would close this window and ensure the transport heartbeat activates on startup:

```suggestion
    webhookHeartbeat = setInterval(ping, 10 * 60_000);
    void ping();
```

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0721511 — added void ping() immediately after setInterval creation so the first heartbeat fires at startup.

@jakozloski

Copy link
Copy Markdown
Author

Both issues from the Greptile review are fixed in 0721511:

  1. lastInboundAt middleware unreachable — Moved the bot.on(["message", "channel_post"]) block to before registerTelegramHandlers(), so it runs before terminal handlers that don't call next().

  2. Webhook heartbeat startup gap — Added immediate void ping() after setInterval creation, so lastEventAt is stamped at startup instead of waiting 10 minutes.

Also fixed the TypeScript error (TS2322) — cast ctx.setStatus at the call site in channel.ts to bridge the ChannelAccountSnapshot → Record<string, unknown> parameter type mismatch.

jakozloski and others added 4 commits March 20, 2026 07:37
The Telegram provider never updated lastEventAt in the channel health
snapshot, causing the health monitor to declare "stale-socket" and
restart the connection every 30 minutes — even when the bot was healthy.

Thread setStatus from the channel plugin through monitorTelegramProvider
and createTelegramBot. Add:

- grammY middleware to stamp lastEventAt on every inbound update
- Separate lastInboundAt tracking only for message/channel_post
- API transformer on getUpdates for transport-level heartbeat (proves
  polling is alive during idle periods without masking real failures)
- Webhook mode: periodic getWebhookInfo ping with cleanup on shutdown

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tup gap

- Cast ctx.setStatus in channel.ts to fix TS2322 type mismatch
- Move lastInboundAt middleware before registerTelegramHandlers so it
  actually runs (terminal handlers don't call next())
- Add immediate ping() at webhook startup to close 10-minute liveness gap

Co-Authored-By: Claude Opus 4.6 <[email protected]>
setInterval already returns NodeJS.Timeout — no need for typeof guard
or `as NodeJS.Timeout` cast.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…fter module move

The original PR targeted src/telegram/monitor.ts which was deleted on main
and moved to extensions/telegram/src/monitor.ts. Thread setStatus through
the new monitor and polling-session to complete the health monitoring plumbing.
@jakozloski
jakozloski force-pushed the jakozloski/fix-telegram-health-status branch from bfcbcf4 to 343e773 Compare March 20, 2026 11:40
@jakozloski
jakozloski force-pushed the jakozloski/fix-telegram-health-status branch from 5daea5e to 15151f8 Compare March 20, 2026 12:12
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Apr 20, 2026
@steipete

Copy link
Copy Markdown
Contributor

Closing as superseded by #51931. The newer PR threads a typed status sink into Telegram polling and updates the gateway health-policy tests around explicit polling mode, which is the safer shape for this liveness surface. Thanks for pushing the original direction here; it helped identify the right seam.

@steipete steipete closed this Apr 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram size: S stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants