Skip to content

fix(telegram): use per-message sequential key to unblock steer-mode message injection - #60604

Closed
kiranight75 wants to merge 12 commits into
openclaw:mainfrom
kiranight75:fix/telegram-steer-sequential-key
Closed

kiranight75 wants to merge 12 commits into
openclaw:mainfrom
kiranight75:fix/telegram-steer-sequential-key

Conversation

@kiranight75

Copy link
Copy Markdown

Summary

The grammY sequentialize middleware 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 made steer queue mode completely ineffective on Telegram: the steering message could never reach queueEmbeddedPiMessage() while a run was in progress.

Root Cause

getTelegramSequentialKey() returned keys scoped to chat/topic but not to individual messages. grammY's sequentialize holds 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 in runReplyAgent, the run has already finished — there is nothing to steer into.

Fix

Append message_id to the sequential key so each inbound message is processed independently by grammY. This allows steering messages to flow through processMessage → getReplyFromConfig → runReplyAgent in parallel with an active run and reach queueEmbeddedPiMessage().

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 in runReplyAgent checks isActive && isStreaming before injecting via queueEmbeddedPiMessage() and returns early without creating a new run.

Unaffected:

  • Control messages (/stop, abort phrases) — already use :control key
  • /btw messages — already use per-message key
  • Reactions — remain on chat-level key
  • Inbound debouncer — still coalesces rapid messages within debounceMs

Testing

  • Updated sequential-key.test.ts — all existing tests updated for per-message keys
  • Added tests for different message_id values producing different keys
  • Manually verified on live Telegram setup: steer messages now inject mid-run during tool call chains

AI Disclosure

  • AI-assisted (Claude Opus via OpenClaw)
  • Fully tested (unit tests + manual live verification)
  • I understand what the code does

Fixes #50880
Fixes #48003

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: XS labels Apr 4, 2026
@greptile-apps

greptile-apps Bot commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes steer-mode message injection on Telegram by appending message_id to the grammY sequentialize key, allowing inbound messages to be processed independently rather than being serialized behind an active agent run. The implementation change is sound — run-level serialization is correctly delegated to the session lane queue — but one newly added test case has an incorrect expected value that will cause the test suite to fail.

Confidence Score: 4/5

Safe 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 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.

Reviews (1): Last reviewed commit: "fix(telegram): use per-message sequentia..." | Re-trigger Greptile

Comment on lines +112 to +113
// fallback when no message is present (chat-only context)
[{ chat: { id: 999 } }, "telegram:unknown"],

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 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".

Suggested change
// 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.

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 — the test now correctly expects "telegram:999" for chat-only context, and per-message keys are only applied when isRunActiveForChat returns true.

@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: 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;

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 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 👍 / 👎.

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.

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"],

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.

P2 Badge 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 👍 / 👎.

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 — test expectation corrected to "telegram:999".

@kiranight75
kiranight75 force-pushed the fix/telegram-steer-sequential-key branch 2 times, most recently from f3e1228 to b181e56 Compare April 4, 2026 11:44

@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: 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".

Comment on lines +68 to +69
const base = threadId != null ? `telegram:${chatId}:topic:${threadId}` : `telegram:${chatId}`;
return typeof messageId === "number" ? `${base}:${messageId}` : base;

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 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 👍 / 👎.

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.

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.

@kiranight75

Copy link
Copy Markdown
Author

Good catch on the ordering regression — addressed in ebc8ab01d4.

Per-message sequential keys are now conditional: getTelegramSequentialKey accepts an optional isRunActiveForChat?: (chatId: number) => boolean callback. Per-message keys (which allow steer-mode bypass) are only used when the callback reports an active run for that chat. Otherwise, the per-chat key is used, preserving grammY FIFO ordering.

The callback is currently wired as undefined (effectively per-chat keys everywhere), which is safe. Wiring it to the actual session/lane runtime (e.g. isEmbeddedPiRunActive via a chatId→sessionId map) is left as a TODO — would appreciate guidance on the best place to maintain that mapping in the telegram extension lifecycle.

@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: 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".

Comment on lines +354 to +356
getTelegramSequentialKey(ctx, {
isRunActiveForChat: undefined, // placeholder — replace with runtime check
}),

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 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 👍 / 👎.

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 c177b5a — isRunActiveForChat is now wired to the embedded Pi run state via chatSessionCache + isEmbeddedPiRunActive.

@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: 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);

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 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 👍 / 👎.

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 3d7917f — switched to sessionKey-based lookup instead of sessionId.

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Apr 4, 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: 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".

Comment on lines +348 to +349
if (chatSessionCache && typeof params.chatId === "number") {
chatSessionCache.set(params.chatId, sessionKey);

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 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 👍 / 👎.

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 dae45b5 — cache is now populated on the normal inbound message path, not just callback_query.

Comment thread extensions/telegram/src/bot.ts Outdated
Comment on lines +359 to +360
const sessionKey = chatSessionCache.get(chatId);
return sessionKey ? telegramDeps.isRunActiveForSessionKey!(sessionKey) : false;

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.

P2 Badge 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 👍 / 👎.

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 f70feec — run-active check is now scoped to topic/thread, not just chatId.

@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: 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".

Comment on lines +74 to +77
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;

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 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 👍 / 👎.

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.

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.

Comment thread extensions/telegram/src/bot.ts Outdated
Comment on lines +359 to +360
const cacheKey = threadId != null ? `${chatId}:${threadId}` : `${chatId}`;
const sessionKey = chatSessionCache.get(cacheKey);

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.

P2 Badge 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 👍 / 👎.

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.

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.

@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: 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".

Comment thread extensions/telegram/src/bot.ts Outdated
Comment on lines +353 to +357
const telegramQueueMode =
(queueCfg?.byChannel as Record<string, string | undefined> | undefined)?.telegram ??
queueCfg?.mode;
const isSteerMode =
telegramQueueMode === "steer" || telegramQueueMode === "steer-backlog" ||

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 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);

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.

P2 Badge 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 👍 / 👎.

@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: 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".

Comment on lines +383 to +386
const effectiveMode = entry?.queueMode ?? channelMode;
const isSteer = effectiveMode === "steer" || effectiveMode === "steer-backlog"
|| effectiveMode === "steer+backlog";
chatSessionCache.set(cacheKey, { sessionKey, isSteerMode: isSteer });

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 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 👍 / 👎.

Comment on lines +44 to +45
/** Reverse index: sessionKey → sessionId for active runs. */
sessionKeyToId: new Map<string, string>(),

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.

P2 Badge 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 👍 / 👎.

@kiranight75

Copy link
Copy Markdown
Author

Re: steer-mode cache refresh after /queue steer — this is by design. The chatSessionCache is updated on every inbound message via resolveTelegramSessionState, which reads the current entry.queueMode (with fallback to channel/global config). After a /queue steer directive updates the session entry, the very next inbound message refreshes the cache. The only "stale" message is the /queue steer command itself, which is a control command and not a steer candidate anyway.

Moving session resolution into the sequential key middleware would require loadConfig() + loadSessionStore() on every Telegram update, which is too expensive for a middleware that must be synchronous and fast.

…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
@clawsweeper

clawsweeper Bot commented Apr 26, 2026

Copy link
Copy Markdown
Contributor

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 isStreaming gate. The newer open #65222 is the better canonical PR for the remaining Telegram steer/interrupt delivery work.

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 isActive/isStopped steer semantics tracked by #65010, instead of merging this older partial branch.

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.

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: S

Projects

None yet

1 participant