Skip to content

fix(telegram): enable interrupt/steer message delivery during active runs - #65021

Closed
jetd1 wants to merge 2 commits into
openclaw:mainfrom
jetd1:fix/telegram-interrupt-debouncer-clean
Closed

jetd1 wants to merge 2 commits into
openclaw:mainfrom
jetd1:fix/telegram-interrupt-debouncer-clean

Conversation

@jetd1

@jetd1 jetd1 commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Enable Telegram interrupt/steer message delivery during active agent runs, and fix ReplyOperation registry races that can lose user messages or cause overlapping runs.

Problem

When a Telegram user sends a message while an agent run is active and queue mode is steer, steer-backlog, or interrupt, the message gets serialized behind the debouncer — even though steer/interrupt modes are supposed to deliver immediately. Additionally, the ReplyOperation registry has several race conditions around force-supersede:

  1. notifyReplyRunEnded fires during the gap between clearing the old operation and registering the replacement, causing waiters to incorrectly see "idle".
  2. Queued operation abort clears state synchronously — abortByUser() calls clearState() inline for queued ops, which triggers notifyReplyRunEnded before the replacement is registered.
  3. clearWaitSessionIds deletes replacement mappings — when a stale operation's finally block runs after a replacement is registered, it can delete the replacement's wait-key entries.
  4. Stale waitKeysBySessionId aliases after updateSessionId rotation — only currentSessionId was removed on normal completion, leaving orphaned aliases that could attach waitForReplyRunEndBySessionId(oldId) to future unrelated runs.

Changes

Telegram sequential key bypass:

  • Add isRunActiveForChat callback to getTelegramSequentialKey. When an embedded Pi run is active and the queue mode needs immediate delivery, return a per-message sequential key so grammY dispatches in parallel.
  • chatSessionCache keyed by conversation (chatId:threadId) for groups, and by chatId:threadId:senderId for DMs.
  • Cache lookup tries conversation key first, then sender key.
  • Cap at 500 entries with FIFO eviction.
  • Use live config (loadConfig()) for queue-mode resolution so runtime changes take effect without restart.

Session key lookup for active runs:

  • Add isEmbeddedPiRunActiveForSessionKey() that resolves sessionKey → sessionId → active run registry check.
  • Export through pi-embedded barrel and plugin-sdk/reply-runtime.

Interrupt-mode forceDetach: trust scheduling decision:

  • After forceDetachEmbeddedRun succeeds in interrupt mode, return { kind: "continue" } immediately without re-checking isActive. The residual ReplyOperation is handled downstream by createReplyOperation({ force: true }).
  • forceDetachEmbeddedRun now resolves sessionKey from the reverse map and logs the session state transition to "idle".

ReplyOperation registry race fixes:

  • abortByUser accepts { skipNotify } option; the force-supersede path passes it so that queued operations (which clear state synchronously) also suppress the idle notification.
  • clearReplyRunState accepts skipNotify option; the force path uses it to avoid resolving waiters in the gap between clearing the old operation and registering the new one.
  • clearReplyRunState accepts expectedOperation for strict object-identity comparison in the isReplaced guard. The sessionId fallback is documented as unsafe when a replacement shares the same sessionId.
  • In the isReplaced branch: zero map mutations — the replacement owns all registry entries and may have inherited sessionIds via updateSessionId rotation.
  • Normal clear path: clean up all waitKeysBySessionId aliases for the sessionKey (not just currentSessionId), preventing stale aliases from attaching to future runs after updateSessionId rotation.
  • Force-supersede path: skip alias cleanup — aliases are preserved for the replacement operation. They will be cleaned up when the replacement finishes normally.

waitForEmbeddedPiRunEnd enhancement:

  • Now waits for both the embedded run map AND the ReplyOperation registry via waitForReplyRunEndBySessionId.
  • waitForEmbeddedPiRunEnd caps at 15s; waitForReplyRunEndBySessionId caps at 500ms within the remaining budget.

Retry guard scoping:

  • Force-supersede retry in agent-runner.ts only fires in interrupt mode (force: isInterruptMode). In collect/followup modes, aborting an in-flight run would violate queue semantics, so the retry falls through to the shutdown message.

Known Limitations

  • Rapid burst: When two interrupt messages arrive concurrently for the same chat (enabled by per-message sequential keys), only the first to reach createReplyOperation({ force: true }) wins the slot. The second receives the "still shutting down" reply. This is intentional — only one replacement can be in-flight at a time.
  • isReplaced sessionId fallback: The fallback path (currentEntry.sessionId !== params.sessionId) is unsafe when replacement and old operation share the same sessionId. All internal callers pass expectedOperation for strict identity comparison.

Testing

  • 37/37 unit tests passing (reply-run-registry + get-reply-run-queue + agent-runner.steer-guard + runs)
  • pnpm lint clean on changed files

🤖 AI-assisted (Cha via OpenClaw)

Replace the overly restrictive isStreaming() guard in
queueEmbeddedPiMessage 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 message delivery.

Changes:
- 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 now checks 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.
- 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
@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram agents Agent runtime and tooling size: L labels Apr 11, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4d4b10c7b7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/agents/pi-embedded-runner/runs.ts Resolved
@greptile-apps

greptile-apps Bot commented Apr 11, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds interrupt/steer message delivery bypass for the Telegram integration, consisting of three coordinated pieces: a chatSessionCache (Map capped at 500 entries with FIFO eviction) that records session state, a getTelegramSequentialKey extension that returns a per-message key to let grammY dispatch in parallel when a run is active, and a waitForReplyRunEndBySessionId call before retrying createReplyOperation to mitigate "Previous run is still shutting down" errors from the abort+recreate race. The new isEmbeddedPiRunActiveForSessionKey helper correctly resolves sessionKey → sessionId → isActive and is exported through the appropriate barrel and plugin-sdk surfaces.

Confidence Score: 5/5

This PR is safe to merge; all findings are minor style/documentation suggestions.

The implementation is carefully designed with appropriate race condition handling, consistent cache key construction between the sequentializer and the handler, and correct fallthrough behavior for edge cases. Both "steer-backlog" and "steer+backlog" are valid config schema values. The timeout overshoot in waitForEmbeddedPiRunEnd is documented inline. No P0 or P1 issues found.

No files require special attention.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/runs.ts
Line: 367-368

Comment:
**`waitForEmbeddedPiRunEnd` can exceed its stated `timeoutMs`**

When the embedded run waiter consumes nearly the full budget, `Math.max(100, timeoutMs - elapsed)` floors at 100ms, so the total wall time for this call can be `timeoutMs + up to 100ms`. This is documented via the inline comment and is negligible for the default 15s timeout, but callers that pass a tight budget (e.g. 500ms) should be aware the function may return slightly late. Consider surfacing this in the JSDoc so callers don't assume a strict deadline.

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

---

This is a comment left during a code review.
Path: extensions/telegram/src/sequential-key.ts
Line: 99-108

Comment:
**Bypass silently skips when `message_id` is absent**

When `isRunActiveForChat` returns `true` (a run is active and immediate delivery was intended) but `msg?.message_id` is not a number, the function falls through and returns the normal shared sequential key — so the message is serialized behind the active handler instead of bypassing it. In practice `message_id` is always present for regular messages, but a brief comment here would clarify this is an intentional safe-fallback rather than a silent no-op.

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

Reviews (1): Last reviewed commit: "fix(telegram): enable interrupt/steer me..." | Re-trigger Greptile

Comment thread src/agents/pi-embedded-runner/runs.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e674fad2ad

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@jetd1
jetd1 force-pushed the fix/telegram-interrupt-debouncer-clean branch 2 times, most recently from fb50456 to 30c6dde Compare April 12, 2026 02:48

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 30c6ddea69

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/agents/pi-embedded-runner/runs.ts Resolved
@jetd1
jetd1 force-pushed the fix/telegram-interrupt-debouncer-clean branch from 30c6dde to aabe2ee Compare April 12, 2026 03:06

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: aabe2ee931

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@jetd1
jetd1 force-pushed the fix/telegram-interrupt-debouncer-clean branch from aabe2ee to 02e9d78 Compare April 12, 2026 04:35

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 02e9d78f93

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@jetd1
jetd1 force-pushed the fix/telegram-interrupt-debouncer-clean branch from 02e9d78 to af6ebef Compare April 12, 2026 04:52

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: af6ebef936

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@jetd1
jetd1 force-pushed the fix/telegram-interrupt-debouncer-clean branch from af6ebef to 492944d Compare April 12, 2026 05:05

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 492944dde2

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@jetd1
jetd1 force-pushed the fix/telegram-interrupt-debouncer-clean branch from 492944d to 7439765 Compare April 12, 2026 05:18

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 743976552f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/auto-reply/reply/agent-runner.ts Resolved
@jetd1
jetd1 force-pushed the fix/telegram-interrupt-debouncer-clean branch from 7439765 to 8dada37 Compare April 12, 2026 05:46

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8dada37b4a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@jetd1
jetd1 force-pushed the fix/telegram-interrupt-debouncer-clean branch from 8dada37 to 0293552 Compare April 12, 2026 06:02
…runs

When Telegram queue mode is set to steer, steer-backlog, or interrupt,
messages arriving while an agent run is active need immediate delivery
rather than being serialized behind the debouncer.

Telegram sequential key bypass:
- Add isRunActiveForChat callback to getTelegramSequentialKey. When an
  embedded Pi run is active and the queue mode needs immediate delivery,
  return a per-message sequential key so grammY dispatches in parallel.
- chatSessionCache keyed by conversation (chatId:threadId) for groups,
  and by chatId:threadId:senderId for DMs.
- Cache lookup tries conversation key first, then sender key.
- Cap at 500 entries with FIFO eviction.
- Use live config (loadConfig) for queue-mode resolution so runtime
  changes take effect without restart.

Session key lookup for active runs:
- Add isEmbeddedPiRunActiveForSessionKey() that resolves sessionKey to
  sessionId then checks the active run registry.
- Export through pi-embedded barrel and plugin-sdk/reply-runtime.

Interrupt-mode forceDetach: trust scheduling decision:
- After forceDetachEmbeddedRun succeeds in interrupt mode, return
  { kind: "continue" } immediately without re-checking isActive.
- forceDetachEmbeddedRun now resolves sessionKey from the reverse map
  and logs the session state transition to "idle".

ReplyOperation registry race fixes:
- abortByUser accepts { skipNotify } option; the force-supersede path
  passes it so queued operations suppress the idle notification.
- clearReplyRunState accepts expectedOperation for strict identity
  comparison in the isReplaced guard. The sessionId fallback is
  documented as unsafe when replacement shares the same sessionId.
- In the isReplaced branch: zero map mutations.
- Normal clear path: clean up ALL waitKeysBySessionId aliases for the
  sessionKey, preventing stale aliases after updateSessionId rotation.

Retry guard: force-supersede retry only fires in interrupt mode. In
collect/followup modes, aborting an in-flight run would violate queue
semantics, so the retry falls through to the shutdown message instead.

Known limitation: under rapid burst (2+ concurrent interrupt messages
for the same chat), only one message wins the force-supersede race.

Co-Authored-By: Cha <[email protected]> via OpenClaw
@jetd1
jetd1 force-pushed the fix/telegram-interrupt-debouncer-clean branch from 0293552 to 04b9a86 Compare April 12, 2026 06:07
@jetd1

jetd1 commented Apr 12, 2026

Copy link
Copy Markdown
Contributor Author

Re: comment — Fixed. Alias cleanup loop now gated behind !skipNotify. Force-supersede always passes skipNotify: true, so aliases are preserved for the replacement. Cleaned up when replacement finishes normally. Added test covering rotated alias preservation across force-supersede.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 04b9a8652f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

export type { FinalizedMsgContext, MsgContext } from "../auto-reply/templating.js";
export { generateConversationLabel } from "../auto-reply/reply/conversation-label-generator.js";
export type { ConversationLabelParams } from "../auto-reply/reply/conversation-label-generator.js";
export { isEmbeddedPiRunActiveForSessionKey } from "../agents/pi-embedded.js";

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.

P1 Badge Keep reply-runtime from eagerly importing embedded agent stack

src/plugin-sdk/reply-runtime.ts now re-exports isEmbeddedPiRunActiveForSessionKey from ../agents/pi-embedded.js, which makes every runtime import of openclaw/plugin-sdk/reply-runtime instantiate the embedded-agent module graph (through src/agents/pi-embedded.ts and src/agents/pi-embedded-runner.ts). I checked this path because many channel runtimes import reply-runtime for lightweight helpers only, so this change can regress startup latency/memory and pull in heavy optional runtime surfaces even when embedded runs are unused; it also violates the Plugin SDK boundary guidance in src/plugin-sdk/AGENTS.md to keep broad SDK entrypoints cheap at module load.

Useful? React with 👍 / 👎.

@jetd1

jetd1 commented Apr 12, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by split into independent PRs:

  • PR B (core): fix/interrupt-scheduling-race — interrupt scheduling race fix
  • PR C (telegram): fix/telegram-interrupt-delivery — Telegram delivery bypass

The original PR mixed core and channel-specific fixes. Split for cleaner review.

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: telegram Channel integration: telegram size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant