Skip to content

fix(telegram): bypass grammY sequential key for interrupt/steer message delivery - #65222

Closed
jetd1 wants to merge 30 commits into
openclaw:mainfrom
jetd1:fix/telegram-interrupt-delivery
Closed

jetd1 wants to merge 30 commits into
openclaw:mainfrom
jetd1:fix/telegram-interrupt-delivery

Conversation

@jetd1

@jetd1 jetd1 commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor

Problem

In Telegram, grammY's sequentialize middleware serializes all updates for the same chat. When a run is active (e.g., executing a tool call), new messages queue behind it. This prevents:

  • Interrupt mode: user message cannot reach the scheduling layer to trigger abort
  • Steer mode: user message cannot be injected into the active run's steering queue

Changes

1. Chat-session cache (chatSessionCache)

Maps Telegram chat IDs → OpenClaw session keys. Capped at 500 entries with LRU eviction. Populated when session state is resolved during message processing.

2. Per-message sequential key

When a run is active for the cached session key AND the queue mode is interrupt or steer/steer-backlog/steer+backlog, generate a unique per-message key instead of the per-chat key. This lets grammY process the new message concurrently with the running update.

3. Lightweight run-active-check module

New re-export path (pi-embedded-runner/run-active-check.ts) avoids pulling the full embedded-agent module graph into reply-runtime.ts → channel plugins. Addresses module boundary concern where reply-runtime is a lightweight SDK entry.

4. Live config for queue mode decisions

The sequential key bypass reads live config via loadConfig() instead of the outer config snapshot, so queue mode changes take effect without restart.

Dependencies

Clean 3-commit stack on top of the latest prerequisite commits; will rebase away once both merge:

Tests

  • Telegram scoped tests (sequential-key.test.ts, bot.create-telegram-bot.test.ts, etc.): pass
  • Full Telegram suite: 1281/1281 pass
  • Auto-reply scoped (runs.test.ts, get-reply-run-queue.test.ts, reply-run-registry.test.ts, agent-runner.steer-guard.test.ts): 52/52 pass
  • oxlint: 0 errors (previously failing on unused isStreaming/isInterruptMode)

Known Limitations

  • chatSessionCache maps chat ID → session key; group chats with multiple senders sharing one chat ID work correctly (cache is per-chat, not per-sender)
  • The bypass only activates when isRunActiveForSessionKey returns true; if the cache misses (first message in a chat), the fallback is normal per-chat serialization

Related

Part of a 3-PR fix set for interrupt/steer message delivery:

AI Disclosure

  • AI-assisted (OpenClaw agent + Codex review)
  • Fully tested (see Tests section above)
  • Author understands all changes

@greptile-apps

greptile-apps Bot commented Apr 12, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a two-layer bypass for grammY's sequential update processing so that interrupt and steer mode messages can be delivered immediately instead of queuing behind an active handler. The first layer assigns a per-message sequential key (bypassing per-chat serialization), and the second layer skips the inbound debouncer when an active run is detected. A lightweight run-active-check.ts re-export path avoids pulling the full embedded-runner module graph into reply-runtime.ts.

Confidence Score: 5/5

Safe to merge — no correctness or reliability issues found; all edge cases are documented.

No P0 or P1 issues found. The two-layer bypass design (sequential key + debouncer skip) is sound, cache key symmetry between population and lookup is correct for both DMs and groups, and the force-detach path for interrupt timeouts is well-tested. All remaining findings are P2 style notes.

No files require special attention.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/telegram/src/sequential-key.ts
Line: 101

Comment:
**Redundant nullish coalescing**

`threadId` is already typed as `number | undefined`, so `threadId ?? undefined` is equivalent to just `threadId`.

```suggestion
      if (options.isRunActiveForChat(chatId, threadId, senderId)) {
```

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

Reviews (1): Last reviewed commit: "fix(telegram): bypass grammY sequential ..." | Re-trigger Greptile

@jetd1
jetd1 force-pushed the fix/telegram-interrupt-delivery branch from 8e07c01 to 820f10c Compare April 12, 2026 07:15
@jetd1
jetd1 force-pushed the fix/telegram-interrupt-delivery branch 2 times, most recently from 57cfb94 to 4f1b1d8 Compare April 12, 2026 07:56
@jetd1
jetd1 force-pushed the fix/telegram-interrupt-delivery branch 9 times, most recently from 167877c to d40b634 Compare April 12, 2026 12:46
@jetd1
jetd1 force-pushed the fix/telegram-interrupt-delivery branch from d40b634 to 2f1bbdc Compare April 12, 2026 14:25
@jetd1
jetd1 force-pushed the fix/telegram-interrupt-delivery branch 2 times, most recently from 31e0c71 to 58f756c Compare April 18, 2026 08:59
@steipete

Copy link
Copy Markdown
Contributor

Maintainer triage: this is mergeable, but it is a perceived-latency fix rather than the polling-stall fix.

The two-layer design looks sound: per-message sequential keys for active steer/interrupt cases, plus debouncer bypass when a run is active. The cache is bounded, the cache key covers chat/thread/sender, and CI is green.

Recommendation: merge after a normal rebase/check, but do not treat it as closing #69147/#64288/#66885. It fixes "Telegram feels slow to interrupt/steer while a handler is busy"; the active getUpdates socket hangs still need the transport fixes.

steipete and others added 7 commits April 21, 2026 16:27
…dit (openclaw#69581)

* fix(codex): exclude codex-app-server synthetic apiKey from secrets audit

The Codex extension uses the literal string "codex-app-server" as a
hardcoded placeholder apiKey in provider.ts, since the real
authentication is managed by the app-server transport itself.

The secrets audit currently reports this as a real plaintext leak
(PLAINTEXT_FOUND), producing a false positive for any user who has
configured the Codex harness.

Declare it as a plugin-owned non-secret marker in the Codex plugin
manifest, so it flows through the standard
`listKnownNonSecretApiKeyMarkers()` path alongside `ollama-local`,
`lmstudio-local`, `gcp-vertex-credentials`, and `minimax-oauth`.

Also extends the existing `model auth markers` unit tests to lock
in the behavior.

Fixes openclaw#69511

* ci: retrigger checks (no-op)

(cherry picked from commit 081da17)
openclaw#69338)

When ingestDelta returns null (first empty/commentary delta or unchanged
content), the handler returned early, skipping setActivityStatus and
armStreamingWatchdog. If all subsequent deltas were also null (e.g.
due to phase filtering), the watchdog was never armed and the status bar
stayed stale as "idle" while a run was live.

Move setActivityStatus("streaming") and armStreamingWatchdog before
the null-displayText guard so they fire on every received delta event.

Fixes openclaw#34513, openclaw#40824

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
(cherry picked from commit 89b6d02)
@jetd1
jetd1 force-pushed the fix/telegram-interrupt-delivery branch from 58f756c to 4070807 Compare April 22, 2026 15:44
jet added 3 commits April 23, 2026 01:11
…injection

Replace the overly restrictive isStreaming() guard in
queueEmbeddedPiMessage and queueReplyRunMessage with a precise
agent-loop lifecycle check. The old guard blocked steer messages
during tool execution (when isStreaming is false but the agent loop
is still running), preventing legitimate steer/interrupt delivery.

- Add isStopped() method to EmbeddedPiQueueHandle that returns true
  when the agent loop is not actively running (before first prompt or
  after prompt end). During these windows the steering queue is not
  drained, so messages would be silently dropped.
- In attempt.ts, track agentLoopStarted (set immediately before
  activeSession.prompt()) and agentLoopStopped (set in the prompt
  finally block). isStopped = !started || stopped.
- queueEmbeddedPiMessage and queueReplyRunMessage now check isStopped()
  instead of isStreaming(), correctly allowing steer during tool
  execution while rejecting during startup and teardown windows.
- In agent-runner.ts, the steer guard uses isActive (run handle exists)
  instead of isStreaming, matching the broader acceptance window.
- Add isStopped?() to ReplyBackendHandle interface.
- Remove the now-dead isStreaming param from runReplyAgent and its
  destructuring in runPreparedReply.
- 6 new/updated tests covering: not-streaming+running (tool exec),
  stopped (teardown), not-yet-started (startup), compacting, and
  streaming cases.

Fixes openclaw#48003

Co-Authored-By: Cha <[email protected]> via OpenClaw
…Operation registries

- Rename forceDetached → waitInterrupted for clarity: the flag indicates
  whether the waitForActiveRunEnd was forcefully interrupted, not whether
  a detach operation succeeded.
- Two-phase abort: interrupt → waitForEmbeddedPiRunEnd → refreshPreparedState
  → check isActive; if still active, attempt forceDetachActiveRun.
- forceDetachActiveRun return value is advisory — scheduling layer commits
  to superseding regardless; createReplyOperation handles residual
  ReplyOperation state.
- Stale waiter cleanup: forceDetachActiveRun resolves waiters with false
  immediately to prevent leakage.
- Identity-gated force-supersede: createReplyOperation's force now accepts
  `{ ifStale: ReplyOperation }`. At the interrupt-retry site in
  agent-runner, the stale ReplyOperation is captured synchronously in the
  ReplyRunAlreadyActiveError catch, then the retry passes the ref so the
  force only fires when the registered op is object-identical to the
  original stale one. If a newer request registered during the 500ms wait
  window, the retry throws and we return "try again" instead of
  preempting the legitimate newer run.
- Creation sequence counter: reply-run-registry tracks a monotonic per-
  sessionKey createSeq incremented on every successful createReplyOperation.
  The interrupt-retry path captures staleSeq alongside staleReplyOperation
  and rejects the retry when seq advanced during its wait. Closes the
  window where a newer request supersedes the stale run AND completes
  before the older retry wakes — identity-gate alone can't detect that
  case because the registry is empty again by retry time.
…ge delivery

- Per-message sequential keys for steer/interrupt so they bypass the
  debouncer and are delivered immediately without waiting for the
  previous message's response.
- Extract resolveEffectiveQueueMode helper (shared with queue/settings.ts)
  to avoid duplicating the session → channel → global cascade in the
  Telegram hot path.
- Fix stale steer+backlog comparison (normalized to steer-backlog).
@jetd1
jetd1 force-pushed the fix/telegram-interrupt-delivery branch from 4070807 to 4f699be Compare April 22, 2026 17:26
@jetd1
jetd1 requested review from a team as code owners April 22, 2026 17:26
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord gateway Gateway runtime cli CLI command changes scripts Repository scripts docker Docker and sandbox tooling extensions: qa-lab extensions: codex labels Apr 22, 2026
@vincentkoc vincentkoc added the triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup. label Apr 26, 2026
@clawsweeper

clawsweeper Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

Summary
The PR adds active-run-aware Telegram sequential keys, a chat-session cache, debouncer bypass, and supporting queue/runtime helpers and tests, while also touching unrelated docs, Discord, QA, scripts, media, TUI, and release surfaces.

Reproducibility: yes. Static current-main proof is high-confidence: ordinary Telegram messages in the same chat/topic share one grammY key, and the same debounce key can keep the second handler behind the first active run before it reaches steer or interrupt scheduling.

Next step before merge
A focused automated replacement is appropriate because the bug is source-backed and the remaining repair is a narrow rebase/scope cleanup plus coordination with the core prerequisite.

Security
Cleared: No concrete security or supply-chain regression was found in the intended Telegram bypass; the unrelated script/postinstall/release churn should be dropped as a scoping issue.

Review findings

  • [P2] Drop unrelated changes before merge — docs/.generated/config-baseline.sha256:1-4
Review details

Best possible solution:

Land a narrow replacement or clean rebase that contains only the Telegram delivery bypass, its required active-run seam, focused tests, and a changelog entry, with unrelated branch churn dropped.

Do we have a high-confidence way to reproduce the issue?

Yes. Static current-main proof is high-confidence: ordinary Telegram messages in the same chat/topic share one grammY key, and the same debounce key can keep the second handler behind the first active run before it reaches steer or interrupt scheduling.

Is this the best way to solve the issue?

Yes for the two-layer design, no for this branch as the merge vehicle. The maintainable path is the active-run-aware sequential key plus debouncer bypass, delivered as a focused PR coordinated with the core active-run prerequisite.

Full review comments:

  • [P2] Drop unrelated changes before merge — docs/.generated/config-baseline.sha256:1-4
    This PR is billed as a Telegram delivery fix, but the diff also changes generated baselines, Discord UI, QA scenarios, install/release scripts, postinstall behavior, media handling, and TUI behavior. Merging from this line would ship unrelated work under the Telegram fix, so please rebase or replace it with a narrow branch containing only the Telegram bypass and required core seam/tests.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.88

Acceptance criteria:

  • pnpm test extensions/telegram/src/sequential-key.test.ts extensions/telegram/src/bot.create-telegram-bot.test.ts extensions/telegram/src/bot-handlers.runtime.test.ts
  • pnpm test src/agents/pi-embedded-runner/runs.test.ts src/auto-reply/reply/agent-runner.steer-guard.test.ts src/auto-reply/reply/get-reply-run-queue.test.ts if core active-run behavior is touched
  • pnpm exec oxfmt --check --threads=1 extensions/telegram/src/sequential-key.ts extensions/telegram/src/bot-core.ts extensions/telegram/src/bot-handlers.runtime.ts
  • pnpm check:changed in Testbox before handoff

What I checked:

Likely related people:

  • steipete: Current blame and short history for the Telegram sequential key, bot wiring, handler debounce path, and inbound debouncer point to Peter Steinberger's recent refactor/maintenance commits, and he also provided maintainer triage on this PR. (role: recent maintainer and current-file owner; confidence: high; commits: 2baa07f62be3, e497681dea, 7db255150c; files: extensions/telegram/src/sequential-key.ts, extensions/telegram/src/bot-core.ts, extensions/telegram/src/bot-handlers.runtime.ts)
  • vincentkoc: The provided timeline shows vincentkoc applying the dirty-candidate label and cross-referencing open core follow-up fix: allow steer messages during active non-streaming runs #73365, which is directly adjacent to the active-run prerequisite this Telegram fix depends on. (role: adjacent follow-up owner; confidence: medium; files: src/agents/pi-embedded-runner/runs.ts, src/auto-reply/reply/agent-runner.ts)

Remaining risk / open question:

  • The branch mixes the Telegram fix with unrelated generated docs, script/postinstall, release, QA, Discord, media, and TUI changes, so merging it as-is would ship unrelated behavior.
  • The Telegram bypass depends on core active-run behavior that current main still lacks; it should be coordinated with fix: allow steer messages during active non-streaming runs #73365 or a narrow prerequisite change.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 76861364197f.

@obviyus

obviyus commented May 9, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the PR. This branch carries release/config churn around the Telegram delivery change, so it is not reviewable as a focused Telegram PR. Please reopen as a narrow PR with only the intended fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling channel: discord Channel integration: discord channel: telegram Channel integration: telegram cli CLI command changes docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: codex extensions: qa-lab gateway Gateway runtime scripts Repository scripts size: XL triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants