Repository navigation
fix(telegram): use per-message sequential key to unblock steer-mode message injection - #60604
kiranight75 wants to merge 12 commits into
Conversation
Greptile SummaryThis PR fixes steer-mode message injection on Telegram by appending Confidence Score: 4/5Safe to merge after fixing the incorrect test expectation — the implementation change itself is correct. The production code change in sequential-key.ts is well-reasoned and correct. The one blocking issue is a newly added test case that asserts "telegram:unknown" for { chat: { id: 999 } }, when the function actually returns "telegram:999" — this will cause the test suite to fail. extensions/telegram/src/sequential-key.test.ts — the chat-only context fallback test case has a wrong expected value. Prompt To Fix All With AIThis is a comment left during a code review.
Path: extensions/telegram/src/sequential-key.test.ts
Line: 112-113
Comment:
**Wrong expected value — test will fail**
The expected output `"telegram:unknown"` is incorrect for the input `{ chat: { id: 999 } }`. In the function, `chatId` is resolved as `msg?.chat?.id ?? ctx.chat?.id`, so with `msg = undefined` and `ctx.chat = { id: 999 }`, `chatId` evaluates to `999`. Since `typeof 999 === "number"` is `true`, the function enters the `if` branch and returns `"telegram:999"` (no `messageId` suffix because `msg` is `undefined`), never reaching the `return "telegram:unknown"` fallback. The test expectation should be `"telegram:999"`.
```suggestion
// fallback when no message is present (chat-only context)
[{ chat: { id: 999 } }, "telegram:999"],
```
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix(telegram): use per-message sequentia..." | Re-trigger Greptile |
| // fallback when no message is present (chat-only context) | ||
| [{ chat: { id: 999 } }, "telegram:unknown"], |
There was a problem hiding this comment.
Wrong expected value — test will fail
The expected output "telegram:unknown" is incorrect for the input { chat: { id: 999 } }. In the function, chatId is resolved as msg?.chat?.id ?? ctx.chat?.id, so with msg = undefined and ctx.chat = { id: 999 }, chatId evaluates to 999. Since typeof 999 === "number" is true, the function enters the if branch and returns "telegram:999" (no messageId suffix because msg is undefined), never reaching the return "telegram:unknown" fallback. The test expectation should be "telegram:999".
| // fallback when no message is present (chat-only context) | |
| [{ chat: { id: 999 } }, "telegram:unknown"], | |
| // fallback when no message is present (chat-only context) | |
| [{ chat: { id: 999 } }, "telegram:999"], |
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/sequential-key.test.ts
Line: 112-113
Comment:
**Wrong expected value — test will fail**
The expected output `"telegram:unknown"` is incorrect for the input `{ chat: { id: 999 } }`. In the function, `chatId` is resolved as `msg?.chat?.id ?? ctx.chat?.id`, so with `msg = undefined` and `ctx.chat = { id: 999 }`, `chatId` evaluates to `999`. Since `typeof 999 === "number"` is `true`, the function enters the `if` branch and returns `"telegram:999"` (no `messageId` suffix because `msg` is `undefined`), never reaching the `return "telegram:unknown"` fallback. The test expectation should be `"telegram:999"`.
```suggestion
// fallback when no message is present (chat-only context)
[{ chat: { id: 999 } }, "telegram:999"],
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Fixed — the test now correctly expects "telegram:999" for chat-only context, and per-message keys are only applied when isRunActiveForChat returns true.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4c55c5d3aa
ℹ️ 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".
| if (typeof chatId === "number") { | ||
| return threadId != null ? `telegram:${chatId}:topic:${threadId}` : `telegram:${chatId}`; | ||
| const base = threadId != null ? `telegram:${chatId}:topic:${threadId}` : `telegram:${chatId}`; | ||
| return typeof messageId === "number" ? `${base}:${messageId}` : base; |
There was a problem hiding this comment.
Preserve per-chat ordering for normal inbound messages
Appending message_id to the default sequentialization key removes grammY's per-chat FIFO for ordinary messages, so two updates from the same chat now run concurrently. That breaks ordering assumptions in downstream async preprocessing (for example processInboundMessage does await resolveMedia(...) before enqueueing dispatch in extensions/telegram/src/bot-handlers.runtime.ts), which lets a later lightweight text overtake an earlier media message and be processed first in the session lane. This changes conversation order, not just steer injection behavior.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed — per-message keys are now conditional: only when isRunActiveForChat(chatId, threadId) returns true. Normal inbound messages keep per-chat FIFO ordering.
| "telegram:123:43", | ||
| ], | ||
| // fallback when no message is present (chat-only context) | ||
| [{ chat: { id: 999 } }, "telegram:unknown"], |
There was a problem hiding this comment.
Correct chat-only fallback expectation in key test
The new case expects telegram:unknown for { chat: { id: 999 } }, but getTelegramSequentialKey still falls back to ctx.chat?.id and returns telegram:999 when no message object exists. This makes the added unit test inconsistent with the implementation and will fail as soon as this test file is run.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed — test expectation corrected to "telegram:999".
f3e1228 to
b181e56
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b181e56a17
ℹ️ 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".
| const base = threadId != null ? `telegram:${chatId}:topic:${threadId}` : `telegram:${chatId}`; | ||
| return typeof messageId === "number" ? `${base}:${messageId}` : base; |
There was a problem hiding this comment.
Keep chat-level sequential key for normal inbound messages
Appending message_id to the default key removes grammY FIFO for ordinary same-chat updates, so two messages from one chat now run concurrently. In this path, work happens before the session lane (resolveMedia(...) and then inboundDebouncer.enqueue(...) in extensions/telegram/src/bot-handlers.runtime.ts), and debounce flush consumes entries in arrival order (entries.map(...) / entries.at(-1)), so a later lightweight text can overtake an earlier media message and even be combined in reversed order; this is a user-visible ordering regression whenever close-together messages have different preprocessing latency.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fair point — appending messageId unconditionally does break per-chat ordering for normal inbound messages. Rethinking the approach: the fix should only bypass sequentialization for steer/mid-run messages, not all messages. Will update.
|
Good catch on the ordering regression — addressed in ebc8ab01d4. Per-message sequential keys are now conditional: The callback is currently wired as |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ebc8ab01d4
ℹ️ 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".
| getTelegramSequentialKey(ctx, { | ||
| isRunActiveForChat: undefined, // placeholder — replace with runtime check | ||
| }), |
There was a problem hiding this comment.
Wire active-run predicate into sequential key middleware
createTelegramBot now wraps getTelegramSequentialKey, but it hardcodes isRunActiveForChat: undefined, so runActive is always falsy and the key never includes message_id. In practice this leaves grammY sequentialization at the same chat-level behavior as before, so steer-mode messages are still blocked behind an in-progress run instead of being injected mid-run.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c177b5a — isRunActiveForChat is now wired to the embedded Pi run state via chatSessionCache + isEmbeddedPiRunActive.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c177b5a863
ℹ️ 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".
| // Keep the chatId → sessionKey cache current so the sequential key | ||
| // middleware can check whether an embedded run is active for this chat. | ||
| if (chatSessionCache && typeof params.chatId === "number") { | ||
| chatSessionCache.set(params.chatId, sessionKey); |
There was a problem hiding this comment.
Cache sessionId instead of sessionKey for run-active checks
chatSessionCache is populated with sessionKey, but the sequentializer consults isRunActiveForSession, which is backed by isEmbeddedPiRunActive(sessionId) and tracks active runs by sessionId. Because session keys (for example agent:...) differ from session IDs (UUID-style IDs stored on session entries), this lookup usually returns false even when a run is active, so the per-message key path is never activated and steer messages remain blocked behind the in-flight run.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3d7917f — switched to sessionKey-based lookup instead of sessionId.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3d7917ff16
ℹ️ 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".
| if (chatSessionCache && typeof params.chatId === "number") { | ||
| chatSessionCache.set(params.chatId, sessionKey); |
There was a problem hiding this comment.
Populate run-active cache on normal inbound message path
This cache update is inside resolveTelegramSessionState, but that helper is only used in the model-selection callback_query branches in this file, not in the normal inbound flow (message/channel_post → handleInboundMessageLike → processInboundMessage → processMessage). As a result, chatSessionCache is usually empty during real message handling, isRunActiveForChat in bot.ts returns false, and steer-mode messages still stay on chat-level sequential keys and remain blocked behind the active run. Fresh evidence: in this commit the only resolveTelegramSessionState callsites are around lines 1445 and 1520 in this file.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in dae45b5 — cache is now populated on the normal inbound message path, not just callback_query.
| const sessionKey = chatSessionCache.get(chatId); | ||
| return sessionKey ? telegramDeps.isRunActiveForSessionKey!(sessionKey) : false; |
There was a problem hiding this comment.
Key run-active sequentialization by topic/thread, not chat
The run-active predicate reads from a cache keyed only by chatId, but Telegram routing/session keys are topic/thread-specific (for example forum topics and DM topic threads). If one topic in a chat has an active run, this chat-level lookup makes other topics in the same chat appear active too, so they get per-message sequential keys and can process concurrently even without an active run in that topic, which can reorder messages there. The activity lookup needs to include thread/topic scope, not just chat scope.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f70feec — run-active check is now scoped to topic/thread, not just chatId.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f70feec370
ℹ️ 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".
| const runActive = typeof chatId === "number" && opts?.isRunActiveForChat?.(chatId, threadId ?? undefined); | ||
| if (typeof chatId === "number") { | ||
| return threadId != null ? `telegram:${chatId}:topic:${threadId}` : `telegram:${chatId}`; | ||
| const base = threadId != null ? `telegram:${chatId}:topic:${threadId}` : `telegram:${chatId}`; | ||
| return runActive && typeof messageId === "number" ? `${base}:${messageId}` : base; |
There was a problem hiding this comment.
Keep chat FIFO when queue mode cannot steer
This branch switches to a per-message key for any active run, but steer injection only happens when the run is streaming (shouldSteer && isStreaming), and Telegram defaults to collect queue mode. In non-steer or non-streaming-active windows, this removes grammY's per-chat FIFO without any steering benefit; because inbound handling does async media work before enqueue, a later lightweight message can overtake an earlier media message and get queued first, reversing user message order during active runs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good point — currently the per-message key activates for any active run, but steer only works when streaming. Will check if the queue mode / streaming state should also be factored into the predicate.
| const cacheKey = threadId != null ? `${chatId}:${threadId}` : `${chatId}`; | ||
| const sessionKey = chatSessionCache.get(cacheKey); |
There was a problem hiding this comment.
Include sender in run-active cache key for DM routes
The run-active cache lookup key is only chatId[:threadId], but Telegram DM session routing can be sender-specific (the route/session key can be built from senderId in business/chat-bridge flows). When multiple senders map to the same chat/thread key, this cache is overwritten by the last sender, so active-run checks can point at the wrong session and incorrectly enable/disable per-message sequentialization for other senders.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Noted — for the current use case (single-user DM bot), chatId+threadId is sufficient. But for multi-user scenarios this would need the sender dimension. Keeping as-is for now, can extend if needed.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b182f5c3c5
ℹ️ 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".
| const telegramQueueMode = | ||
| (queueCfg?.byChannel as Record<string, string | undefined> | undefined)?.telegram ?? | ||
| queueCfg?.mode; | ||
| const isSteerMode = | ||
| telegramQueueMode === "steer" || telegramQueueMode === "steer-backlog" || |
There was a problem hiding this comment.
Enable steer keying for session-level queue overrides
This gate only checks cfg.messages.queue at bot startup, so per-session queue changes (for example /queue steer or inline queue directives) never enable the run-active sequentialization path. runReplyAgent still resolves queue mode from sessionEntry and can try to steer, but the middleware key remains chat-scoped here, so inbound messages are still blocked behind the active run and cannot inject mid-run unless Telegram is globally configured to steer.
Useful? React with 👍 / 👎.
| getTelegramSequentialKey(ctx, { | ||
| isRunActiveForChat: isSteerMode && telegramDeps.isRunActiveForSessionKey | ||
| ? (chatId, threadId, senderId) => { | ||
| const cacheKey = buildChatSessionCacheKey(chatId, threadId, senderId); |
There was a problem hiding this comment.
Remove sender dimension from group run-active cache keys
The run-active lookup key includes senderId, but Telegram group session routing is group/topic scoped rather than sender scoped (group routes resolve to the same session key regardless of author). If user A starts a run and user B sends a first message during that run, B's cache lookup misses and falls back to the shared chat key, so the message is serialized behind the active run instead of being steer-eligible. This makes steer behavior inconsistent across participants in the same group/topic.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 296cb3269c
ℹ️ 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".
| const effectiveMode = entry?.queueMode ?? channelMode; | ||
| const isSteer = effectiveMode === "steer" || effectiveMode === "steer-backlog" | ||
| || effectiveMode === "steer+backlog"; | ||
| chatSessionCache.set(cacheKey, { sessionKey, isSteerMode: isSteer }); |
There was a problem hiding this comment.
Refresh steer-mode cache after queue directive updates
isSteerMode is cached from entry?.queueMode before the message is processed, but inline /queue ... directives can change the effective queue mode for the same turn later in processing. If a turn flips collect→steer or steer→collect and starts a long run, the next inbound message still uses this stale cache entry in createTelegramBot and gets the wrong sequentialization policy (either blocked when steer should inject, or concurrent when collect should stay FIFO).
Useful? React with 👍 / 👎.
| /** Reverse index: sessionKey → sessionId for active runs. */ | ||
| sessionKeyToId: new Map<string, string>(), |
There was a problem hiding this comment.
Reset sessionKey reverse index with embedded-run test state
The new sessionKeyToId reverse index is added to global run state, but __testing.resetActiveEmbeddedRuns() does not clear it. After a reset, stale sessionKey -> sessionId mappings can survive and later report a different run as active when that sessionId is reused, causing cross-test leakage and incorrect isEmbeddedPiRunActiveForSessionKey results.
Useful? React with 👍 / 👎.
|
Re: steer-mode cache refresh after Moving session resolution into the sequential key middleware would require |
…essage injection The grammY sequentialize middleware serializes all updates that share the same key. Until now, every message in a chat/topic shared a single key (e.g. telegram:123:topic:456), which meant inbound messages were blocked behind the active agent run. This made steer-mode ineffective: the steering message could never reach queueEmbeddedPiMessage() while a run was in progress. Append message_id to the sequential key so each message is processed independently by grammY. Run-level serialization is still guaranteed by the session lane queue (enqueueCommandInLane, maxConcurrent=1), so there is no risk of concurrent agent runs on the same session. Control messages (/stop, abort phrases) and reactions retain their existing key scheme and are unaffected. Fixes openclaw#50880 Fixes openclaw#48003
Greptile review correctly identified that { chat: { id: 999 } } resolves
chatId via ctx.chat?.id (999), so the function returns 'telegram:999'
rather than 'telegram:unknown'.
Per-message sequential keys are now only used when isRunActiveForChat returns true, preserving grammY FIFO ordering for normal messages. When no run is active, falls back to per-chat key. This addresses the ordering regression where a lightweight text message could overtake an earlier media message due to parallel processing in resolveMedia/inboundDebouncer. The isRunActiveForChat callback is currently a placeholder (undefined); wiring to the actual session/lane runtime is left as a TODO.
- Export isEmbeddedPiRunActive via plugin-sdk/reply-runtime - Add isRunActiveForSession to TelegramBotDeps (defaults to isEmbeddedPiRunActive) - Maintain chatId→sessionKey cache in createTelegramBot, populated by resolveTelegramSessionState on each message - Sequential key middleware now checks the real run state: per-message keys (steer bypass) only when an embedded run is active for the chat
- Add sessionKeyToId reverse index in embedded run state - setActiveEmbeddedRun/clearActiveEmbeddedRun maintain the index - New isEmbeddedPiRunActiveForSessionKey checks by sessionKey - Wire through plugin-sdk and bot-deps so the sequential key middleware correctly detects active runs via the chatId→sessionKey cache populated by bot-handlers
Call resolveTelegramSessionState in handleInboundMessageLike to keep the chatId→sessionKey cache warm for the sequential key middleware. Previously the cache was only populated in callback_query branches.
- isRunActiveForChat callback now receives (chatId, threadId?) - chatSessionCache keyed by chatId:threadId instead of just chatId - Prevents one active topic from making other topics in the same forum chat appear active
…ache P1: Per-message sequential keys are now only enabled when the Telegram queue mode is steer or steer-backlog. In collect/followup modes (the default), per-chat FIFO is always preserved since steer injection is not used. P2: The chatSessionCache key now includes senderId so DM routes with multiple senders (business/chat-bridge flows) resolve to distinct session keys.
- chatSessionCache now stores {sessionKey, isSteerMode} per entry
- isSteerMode resolved from session queueMode override, falling back
to channel/global config — respects /queue steer inline directives
- buildChatSessionCacheKey excludes senderId for groups (group sessions
are topic-scoped, not sender-scoped)
- Removed static queue mode check at bot startup
8494f6d to
7c88f24
Compare
|
Closing this as duplicate or superseded after Codex automated review. Close #60604 as superseded by #65222. Current main still does not implement the Telegram per-message sequential-key bypass, but later related discussion showed this PR is only a partial fix: the inbound debouncer can re-serialize steer messages, and the core steer path still has the Best possible solution: Close #60604 as superseded and continue the remaining work in #65222, or in a fresh maintainer-scoped replacement if #65222 is split. The canonical fix should cover Telegram active-run keying plus debouncer bypass and align with the core What I checked:
So I’m closing this here and keeping the remaining discussion on the canonical linked item. Codex Review notes: model gpt-5.5, reasoning high; reviewed against e29d3516bf05. |
Summary
The grammY
sequentializemiddleware serializes all updates sharing the same key. Until now, every message in a chat/topic shared a single key (e.g.telegram:123:topic:456), which meant inbound messages were blocked behind the active agent run. This madesteerqueue mode completely ineffective on Telegram: the steering message could never reachqueueEmbeddedPiMessage()while a run was in progress.Root Cause
getTelegramSequentialKey()returned keys scoped to chat/topic but not to individual messages. grammY'ssequentializeholds the second message until the first one's handler (which includes the entire agent run) completes. By the time the steering message reaches the steer check inrunReplyAgent, the run has already finished — there is nothing to steer into.Fix
Append
message_idto the sequential key so each inbound message is processed independently by grammY. This allows steering messages to flow throughprocessMessage → getReplyFromConfig → runReplyAgentin parallel with an active run and reachqueueEmbeddedPiMessage().Safety
Run-level serialization is still guaranteed by the session lane queue (
enqueueCommandInLane,maxConcurrent=1), so there is no risk of concurrent agent runs on the same session. The steer path inrunReplyAgentchecksisActive && isStreamingbefore injecting viaqueueEmbeddedPiMessage()and returns early without creating a new run.Unaffected:
/stop, abort phrases) — already use:controlkey/btwmessages — already use per-message keydebounceMsTesting
sequential-key.test.ts— all existing tests updated for per-message keysmessage_idvalues producing different keysAI Disclosure
Fixes #50880
Fixes #48003