Skip to content

fix(auto-reply): queued follow-up messages fail with "no active tool authority snapshot" - #139929

Closed
ylcn91 wants to merge 3 commits into
openclaw:mainfrom
ylcn91:fix/queued-followup-tool-authority
Closed

ylcn91 wants to merge 3 commits into
openclaw:mainfrom
ylcn91:fix/queued-followup-tool-authority

Conversation

@ylcn91

@ylcn91 ylcn91 commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Closes #139847

What Problem This Solves

Fixes an issue where users who sent a chat message while the agent was still working on their previous message would, on 2026.9.2, get ⚠️ Something went wrong while processing your request. as soon as the queued message started, and the message was lost rather than requeued. Gateway logs showed:

Embedded agent failed before reply: Reply operation has no active tool authority snapshot

The failure fired at model-route binding, before any provider request, so every fallback candidate that runs through a CLI backend died the same way. Reported on Telegram direct chats; the queued path is shared by every channel and by chat.send.

Why This Change Was Made

Root cause. #134003 (commit e3ce08c, shipped in v2026.9.2) introduced bindToolAuthoritySnapshot / bindToolAuthorityRoute on the reply operation and bound the snapshot for foreground runs right after admission (src/auto-reply/reply/agent-runner-run.ts:543). Queued follow-up admission (admitFollowupTurn in src/auto-reply/reply/followup-turn-admission.ts) obtains its own fresh operation from admitReplyTurn and was never given the same binding. Two consumers then see an operation with no snapshot:

  • src/auto-reply/reply/agent-runner-cli-candidate.ts:141 calls bindToolAuthorityRoute unconditionally, and the registry throws the reported error for every CLI-backed candidate. This is the user-visible drop.
  • src/auto-reply/reply/agent-runner-embedded-candidate.ts:220 passes replyOperation.toolAuthorityFingerprint, which is undefined, so embedded candidates fall back to direct attempt authority and still run (which matches the reporter's log, where one hosted fallback made a real request).

Fix. In admitFollowupTurn, bind prepareReplyToolAuthority(queued) to the admitted operation immediately after the admitted run facts (session id, session file, model lock, fallback probe) are final and before the turn object is built. This is the same call and the same point in the lifecycle as foreground admission. The operation is fresh per admitted queued turn, so the once-only binding contract holds; session rotation after binding (preflight compaction, role-ordering reset) behaves exactly as it already does for foreground runs.

Relation to #139925. That PR (opened while this one was being validated) binds the same snapshot one stage later, in executeFollowupTurn right before executeAgentTurn. Binding at admission instead keeps the queued operation's authority known for its whole active lifetime, including preflight compaction, mirrors the foreground runner one-to-one, and is the repair boundary the ClawSweeper review identified.

Non-goals. No change to the guard itself, no retry of failed turns, no change to the embedded direct-authority fallback, no config or store changes. Production delta: +5 lines in one file.

User Impact

Typing a follow-up while the agent is still working now behaves as documented in docs/concepts/queue.md: the queued message runs after the active turn finishes, on CLI and embedded backends alike, instead of being dropped with a generic error.

Evidence

Live Claude CLI backend proof, before and after (RED/GREEN)

New extensions/qa-lab/src/gateway-queued-followup-send.claude-cli.live.test.ts (live-gated: OPENCLAW_LIVE_TEST=1 OPENCLAW_LIVE_CLI_BACKEND=1, needs a logged-in Claude Code executable) boots a child Gateway with the bundled claude-cli backend (claude-cli/claude-opus-5, subscription login, queue mode: "followup"). It sends message 1 over chat.send, waits until the Gateway log shows the CLI process launched (cli exec: provider=claude-cli), sends message 2 to the same session while that CLI turn is still running, and asserts both replies arrive as two separate CLI executions with no snapshot error.

Why chat.send and not a qa-channel message: the qa-channel poller hands inbound messages to the Gateway one at a time and waits for each reply (extensions/qa-channel/src/gateway.ts, enqueueInbound), so a channel message can never reach the reply pipeline mid-run in this harness. chat.send enters the same pipeline (dispatchInboundMessage -> reply runner -> enqueueFollowupRun -> admitFollowupTurn) without that serialization. The Gateway log confirms the overlap directly (queueDepth=2 sessionState=processing while the first cli exec is in flight).

Before (RED). Same test against a dist built from the unmodified origin/main copy of followup-turn-admission.ts. Message 2 was admitted mid-run, and the moment the first turn completed, the queued turn died at route binding and the user got the generic error:

bus (outbound only; both sends went through chat.send):
  + 0.0s outbound QA-CLI-QUEUED-FOLLOWUP-FIRST-OK
  + 0.1s outbound ⚠️ Something went wrong while processing your request. Please try again, or use /new to start a
gateway log:
  2026-09-06T10:04:39.234Z message received: channel=webchat chatId=unknown messageId=… sessionId=unknown sessionKey=agent:qa:main source=dispatchInboundMessage
  2026-09-06T10:04:39.260Z message queued: sessionId=unknown sessionKey=agent:qa:main source=dispatch queueDepth=1 sessionState=idle
  2026-09-06T10:04:40.195Z session state: sessionId=… sessionKey=agent:qa:main prev=processing new=processing reason="run_started" queueDepth=1
  2026-09-06T10:04:40.574Z [agent/cli-backend] cli exec: provider=claude-cli model=claude-opus-5 promptChars=252 trigger=user useResume=false session=none resumeSession=none reu
  2026-09-06T10:04:40.643Z message received: channel=webchat chatId=unknown messageId=… sessionId=unknown sessionKey=agent:qa:main source=dispatchInboundMessage
  2026-09-06T10:04:40.653Z message queued: sessionId=… sessionKey=agent:qa:main source=dispatch queueDepth=2 sessionState=processing
  2026-09-06T10:04:43.800Z [agent/cli-backend] cli turn: provider=claude-cli model=claude-opus-5 durationMs=3227 outBytes=31 outHash=62ffd8440fb2
  2026-09-06T10:04:44.120Z session state: sessionId=… sessionKey=agent:qa:main prev=idle new=idle reason="run_completed" queueDepth=0
  2026-09-06T10:04:44.336Z Embedded agent failed before reply: Reply operation has no active tool authority snapshot

Test result: 1 failed (Error: ⚠️ Something went wrong while processing your request…).

After (GREEN). Same test on this branch. Message 2 was admitted mid-run, and after the first turn completed, the queued turn ran as its own CLI execution (second cli exec, useResume=true) and its reply was delivered:

bus (outbound only; both sends went through chat.send):
  + 0.0s outbound QA-CLI-QUEUED-FOLLOWUP-FIRST-OK
  + 2.1s outbound QA-CLI-QUEUED-FOLLOWUP-SECOND-OK
gateway log:
  2026-09-06T09:54:42.615Z message received: channel=webchat chatId=unknown messageId=… sessionId=unknown sessionKey=agent:qa:main source=dispatchInboundMessag
  2026-09-06T09:54:42.637Z message queued: sessionId=unknown sessionKey=agent:qa:main source=dispatch queueDepth=1 sessionState=idle
  2026-09-06T09:54:43.194Z session state: sessionId=… sessionKey=agent:qa:main prev=processing new=processing reason="run_started" queueDepth=1
  2026-09-06T09:54:43.659Z [agent/cli-backend] cli exec: provider=claude-cli model=claude-opus-5 promptChars=252 trigger=user useResume=false session=none resumeSession=non
  2026-09-06T09:54:43.713Z message received: channel=webchat chatId=unknown messageId=… sessionId=unknown sessionKey=agent:qa:main source=dispatchInboundMessag
  2026-09-06T09:54:43.719Z message queued: sessionId=… sessionKey=agent:qa:main source=dispatch queueDepth=2 sessionState=processing
  2026-09-06T09:54:46.224Z [agent/cli-backend] cli turn: provider=claude-cli model=claude-opus-5 durationMs=2567 outBytes=31 outHash=62ffd8440fb2
  2026-09-06T09:54:46.512Z lane task done: lane=session:agent:qa:main durationMs=3326 active=0 queued=0
  2026-09-06T09:54:46.529Z session state: sessionId=… sessionKey=agent:qa:main prev=idle new=idle reason="run_completed" queueDepth=0
  2026-09-06T09:54:46.730Z session state: sessionId=… sessionKey=agent:qa:main prev=idle new=processing reason="run_started" queueDepth=0
  2026-09-06T09:54:47.090Z [agent/cli-backend] cli exec: provider=claude-cli model=claude-opus-5 promptChars=253 trigger=user useResume=true session=present resumeSession=…
  2026-09-06T09:54:48.459Z [agent/cli-backend] cli turn: provider=claude-cli model=claude-opus-5 durationMs=1370 outBytes=32 outHash=02c025cecf7d
  2026-09-06T09:54:48.741Z lane task done: lane=session:agent:qa:main durationMs=2014 active=0 queued=0
  2026-09-06T09:54:48.752Z session state: sessionId=… sessionKey=agent:qa:main prev=processing new=idle reason="run_completed" queueDepth=0

Test result: Test Files 1 passed (1) · Tests 1 passed (1) (~22s per run; final run on the rebuilt branch dist 54.6s including Gateway boot). grep "no active tool authority snapshot" on the Gateway log: 0 matches.

Boundary regression (RED/GREEN, unit)

src/auto-reply/reply/followup-turn-admission.queued-handoff.test.ts replays the issue's sequence through the unmocked admission path and reply-run registry: message 1 admitted as a visible run with its authority bound, message 2 admitted as queued_followup while message 1 is active, message 1 completes, message 2 admitted with a fresh operation, and bindToolAuthorityRoute on that operation succeeds. followup-turn-admission.test.ts also asserts the snapshot is bound once and fingerprints the admitted generation.

Before (tests on unmodified origin/main):

× followup-turn-admission.test.ts > binds the admitted turn's tool authority snapshot to the reply operation
   → expected "vi.fn()" to be called once, but got 0 times
× followup-turn-admission.queued-handoff.test.ts > lets the queued turn bind its concrete route once the active run completes
   → Reply operation has no active tool authority snapshot

After (this branch): followup-turn-admission*.test.ts 39 passed; owner and sibling suites (followup-turn-execution, followup-runner, reply-run-registry, reply-turn-admission) 240 passed.

Mock-provider Gateway e2e (embedded runtime)

extensions/qa-lab/src/gateway-queued-followup-send.e2e.test.ts boots a child Gateway with the mock provider and queue mode: "followup", holds the first reply for ~15s, sends a second message mid-run, and asserts both replies are delivered in order. This revision switches its two sends from qa-channel inbound messages to chat.send for the reason above; the earlier revision's second message was only delivered to the Gateway after the first turn had finished, so it did not exercise the queued path. The embedded runtime tolerates a missing snapshot (direct attempt authority), so this test is a regression guard for the queued flow itself, not the RED/GREEN boundary; the CLI live test above is.

Result: Test Files 1 passed (1) · Tests 1 passed (1) (47.2s), run against a dist rebuilt from this branch.

Checks

  • followup-turn-admission*.test.ts: 39 passed (rebased head). Owner/sibling suites: 240 passed (previous head; production file unchanged since).
  • extensions/qa-lab/src/gateway-queued-followup-send.e2e.test.ts (chat.send revision): 1 passed (47.2s).
  • extensions/qa-lab/src/gateway-queued-followup-send.claude-cli.live.test.ts: RED on main-built dist (fails with the reported error), GREEN on this branch (1 passed, 54.6s).
  • tsgo extensions lane (tsconfig.extensions.json): clean. oxfmt --check and oxlint on both touched test files: clean. git diff --check: clean.
  • node scripts/check-changed.mjs: 40 of its lanes green at push time (tsgo core/ui/test shards, dead-export scan, ratchets); the type-aware lint lane was still running and will be reported in a follow-up comment if it flags anything.

Rebase onto main (427abe8)

#140018 landed, so the two cherry-picked CI commits are dropped and the branch is the three fix/proof commits rebased as d6d1cdd, with no conflicts and no content changes. Locally on the rebased head: followup-turn-admission and followup-turn-admission.queued-handoff pass (39 tests); the qa-lab Gateway e2e and the live CLI proof run in CI.

@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@ylcn91
ylcn91 marked this pull request as ready for review September 6, 2026 08:13
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 6, 2026
@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 7, 2026, 11:41 PM ET / October 8, 2026, 03:41 UTC (Revision 8).

ClawSweeper review

What this changes

The branch binds each queued reply’s immutable tool-permission snapshot during admission and adds Gateway, real Claude CLI, and admission regression coverage.

Example: Send a second chat message while a Claude CLI reply is running

  • Before: On the pinned base, the queued message fails with “Reply operation has no active tool authority snapshot.”
  • After: The queued turn launches a second CLI execution and delivers QA-CLI-QUEUED-FOLLOWUP-SECOND-OK.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong historical runtime proof and useful regression coverage remain, but main has repaired the original defect and the remaining capture-timing proposal needs reconciliation.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The supplied real child-Gateway chat.send trace exercises queued admission and a logged-in Claude CLI after the fix: the second message arrives during the first execution, then launches separately and delivers its marker. Historical proof remains sufficient for the unchanged pinned head; current-main integration still requires reconciliation. No stored-data contract changes.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A message typed while the agent is working can fail before execution and receive only a generic error.
Reason: The branch repairs the stated defect on its pinned base and provides valuable CLI evidence. Main now supplies the missing binding, so changing capture timing requires a distinct owner decision.

Merge readiness

⛔ Blocked before merge - 4 items remain

The original missing-snapshot failure is repaired on current main, but this PR retains useful real-CLI regression coverage and proposes a different snapshot-capture boundary. The historical proof remains valid; the conflicting branch needs reconciliation with main’s existing binding before merge.

Priority: P2
Reviewed head: 066b764143fdab5a73715144ab193ba7c1040ec4
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should the remaining contribution preserve main’s execution-time snapshot capture, or deliberately move the single capture to queued admission?
  • Recommendation: Preserve execution ownership: Remove the redundant admission binding and adapt the useful CLI regression coverage to current main.
  • Why: The original crash is already repaired, while admission-time capture changes the permission lifecycle before compaction; the supplied historical proof does not settle that remaining choice.

Before merge

  • Resolve merge risk (P1) - The branch conflicts with current main; a resolved revision must account for main’s execution-time snapshot binding and preserve exactly one binding, since the reported newer-main carry otherwise prevented queued replies from executing.
  • Resolve merge risk (P1) - Capturing permissions before preflight is now a separate lifecycle change: if retained, demonstrate that compaction/session rotation and current authority preparation remain correct through execution.
  • Complete next step (P2) - Select the snapshot-capture boundary, resolve the conflicts with current main, and validate the reconciled queued CLI path with exactly one binding.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied RED/GREEN CLI run covers the pinned historical base and head; it does not validate a conflict-resolved integration with current main’s existing snapshot binding.
Agent review details

How this fits together

OpenClaw queues messages that arrive while their conversation is busy, then admits each follow-up into the shared agent execution pipeline. A turn-owned permission snapshot controls model-route binding and whether later input may steer that turn.

flowchart TD
  A[Message arrives during a reply] --> B[Conversation follow-up queue]
  B --> C[Admit a fresh reply turn]
  C --> D[Capture immutable tool permissions]
  D --> E[Prepare conversation and compaction]
  E --> F[Bind model route and execute]
  F --> G[Deliver queued reply]
Loading

Technical review

Best possible solution:

Preserve main’s single execution-owned snapshot binding and adapt the useful real-CLI regression coverage; pursue earlier capture only for a demonstrated remaining preflight defect.

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

No current-main reproduction of the original missing-bind defect was established: main now binds before execution. The supplied real Gateway/CLI trace establishes the failure and recovery on the pinned older base.

Is this the best way to solve the issue?

No for current main as written: another snapshot binding already exists. Keeping its owner and porting the useful runtime coverage is the narrower path unless earlier capture solves a demonstrated remaining defect.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against f0fff3ce7b88.

Merge-risk options

Maintainer options:

  1. Keep the runtime regression coverage (recommended)
    Reconcile with main while retaining its existing snapshot owner and port the real-CLI queued-message test.
  2. Make admission the sole owner
    If earlier capture is selected, remove the execution rebind and prove queued delivery across preflight and session rotation.

Provenance checked

Testing

Proof path: shipped entry point. Added test files: 4.

Security

None.

Evidence

What I checked:

  • Pinned production change: The introduced production hunk adds snapshot binding after admitted session facts are resolved and before preflight; it does not change the registry guards. (src/auto-reply/reply/followup-turn-admission.ts:260, 066b764143fd)
  • Current main already binds queued authority: Current main awaits snapshot binding immediately before marking the queued operation running and invoking canonical execution. (src/auto-reply/reply/followup-turn-execution.ts:427, f0fff3ce7b88)
  • Merged queued-binding repair: GitHub verifies Keep Slack threads responsive during queued turns #143661 merged on September 10. Its recorded patch adds queued snapshot binding before execution, and its description explicitly preserves immutable permissions, FIFO ordering, and different-permission queueing. No formal fixing link from that PR to this PR was established. (src/auto-reply/reply/followup-turn-execution.ts, bffda1f94521)
  • Merged-fix history and release containment: The raw commit records a parent, author, and the queued-authority repair. Branch containment includes main; tag containment includes v2026.9.7 and v2026.9.8. GitHub confirms v2026.9.8 was published, but the first shipping release was not established. (bffda1f94521)
  • Single-snapshot invariant: Both synchronous and asynchronous binding reject a second distinct snapshot with “Reply operation cannot change tool authority after admission”; preparing another snapshot object does not make rebinding safe. (src/auto-reply/reply/reply-run-registry.tool-authority.ts:222, f0fff3ce7b88)
  • Real Gateway and Claude CLI proof: The complete PR body was retrieved through REST, including the previously omitted ending. Its September 6 before/after logs show a second chat.send arriving during the first CLI execution: the base throws before launch, while the branch launches a second CLI process and delivers both markers. The inspected live test matches this scenario. Captured body identity: da3c8eef67588e61c4ab83048ef232473d9f95a1b041cc6c1e5a1e4cc61b2a32. (extensions/qa-lab/src/gateway-queued-followup-send.claude-cli.live.test.ts:120, 066b764143fd)

Likely related people:

  • Peter Steinberger: Raw commit f8cc39c adds src/auto-reply/reply/followup-turn-admission.ts:392 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f8cc39ce6213; files: src/auto-reply/reply/followup-turn-admission.ts)
  • pash-openai: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

PR surface

Source +15, Tests +499. Total +514 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 3 15 0 +15
Tests 4 499 0 +499
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 514 0 +514

Root-cause cluster

Relationship: partial_overlap
Canonical: #143661
Summary: The merged queued-binding repair covers the original missing-snapshot failure; this PR additionally proposes earlier capture and real-CLI regression coverage.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P2: The original queued-message failure is repaired on main; the remaining work is bounded integration and regression coverage.
  • add merge-risk: 🚨 message-delivery: The reported newer-main carry rejected a second snapshot and left queued messages unanswered, making single-binding reconciliation essential.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • remove P1: Current review triage priority is P2, so this older priority label is no longer current.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P2: The original queued-message failure is repaired on main; the remaining work is bounded integration and regression coverage.
  • merge-risk: 🚨 message-delivery: The reported newer-main carry rejected a second snapshot and left queued messages unanswered, making single-binding reconciliation essential.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Resolve current-main conflicts while preserving exactly one queued snapshot binding.
  • Adapt the CLI regression coverage to the selected owner boundary and verify queued delivery after preflight.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (7 earlier review cycles)
  • reviewed 2026-09-06T08:20:29.353Z sha 2f42382c868244183fbde0519f961c0f15aa85fa :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-06T09:17:20.654Z sha d45a6380e9c5330a905f4ae2b13f3bb6a932045d :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-06T09:30:41.418Z sha c06860b816273929a6d99395115e5b61c88a0895 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-06T10:46:54.251Z sha 193b0d1d22c10b6dc2da5c556b946212056e181b :: needs maintainer review before merge. :: none
  • reviewed 2026-09-06T11:03:11.674Z sha a39e4b2774581abdfd586f12bed0a37b36d2a393 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-06T13:21:42.874Z sha d6d1cdd73357dae97f62d5d87aebcc5fd5947147 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-06T13:39:37.699Z sha 066b764 :: needs maintainer review before merge. :: none

@ylcn91

ylcn91 commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review — Added the requested runtime proof: a live Gateway e2e test (extensions/qa-lab/src/gateway-queued-followup-send.e2e.test.ts) that sends a message mid-run and confirms the queued follow-up executes as its own turn and its reply is delivered, with zero "no active tool authority snapshot" errors. Before/after evidence and a runtime-scope note are in the updated PR body.

@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 6, 2026
@ylcn91
ylcn91 force-pushed the fix/queued-followup-tool-authority branch from d45a638 to c06860b Compare September 6, 2026 09:25
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 6, 2026
vincentkoc added a commit that referenced this pull request Sep 6, 2026
#140018)

* fix(ci): keep preflight job outputs under GitHub's 1 MiB cap

Pull requests that need the full canonical Node test plan failed preflight
with "Job outputs exceed 1,048,576 bytes", which made ci-gate report every
lane as selected=missing. The compact plan lists 7,749 striped test files
explicitly, and GitHub measures job outputs in UTF-16, so the effective cap
for all preflight outputs is 524,288 characters. The manifest reached ~522K
characters on the github profile as the tracked test inventory grew.

Emit each Node matrix row's groups as gzip+base64 JSON at the manifest
boundary and unpack them in the shard runner. On current main this takes the
github-profile manifest from 522,522 to 195,410 characters and the blacksmith
profile from 450,639 to 158,571, with identical jobs and group membership.
The manifest imports the codec through the existing target-plan seam, the
trusted runner checkout lists it, and plain OPENCLAW_NODE_TEST_GROUPS_JSON
remains for the Vitest cache warmer.

Related to #139929 and #136820.

* fix(ci): load the Node test groups codec only for grouped rows

The manifest imported scripts/lib/ci-node-test-groups-codec.mts
unconditionally through importTargetPlan. An ordinary manual
workflow_dispatch whose target_ref predates the codec is not a
compatibility target, so the import threw before planning even though
such targets emit an ungrouped plan and never call the encoder.

Import the codec only when the emitted Node rows carry groups, and keep
the clear failure when a grouped plan comes from a target without it.
The workflow-guard fixture can now omit the codec so a codec-free manual
target runs the real manifest step.

* fix(ci): preserve grouped historical test plans

Negotiate the packed group codec against the selected target and fall back to the same five-field legacy projection when the codec is unavailable.

Five-field projection adapted from #140036.

Co-authored-by: Peter Steinberger <[email protected]>

---------

Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
@ylcn91
ylcn91 force-pushed the fix/queued-followup-tool-authority branch from a39e4b2 to d6d1cdd Compare September 6, 2026 13:15
@ylcn91

ylcn91 commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

#140018 is on main, so the two cherry-picked CI commits are gone: rebased onto main (427abe8) as d6d1cdd, three commits kept, no conflicts, no content changes. The body's "CI note" is replaced by "Rebase onto main (427abe8)". followup-turn-admission suites pass locally (39 tests).

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 6, 2026
…authority snapshot"

A chat message that arrives while a reply run is active is queued and,
once the active run ends, starts as its own run. Since 2026.9.2 that
queued run failed before any provider request with "Reply operation has
no active tool authority snapshot" and the message was lost.

Foreground admission binds the reply operation's tool authority snapshot
(agent-runner-run.ts), but queued follow-up admission obtains its own
operation and never did. CLI backends bind the concrete route through
that snapshot and threw; embedded runs fell back to direct authority and
could not be steered while the queued turn ran.

Bind the admitted queued turn's snapshot at the same point foreground
admission does, after the admitted session facts are final and before
any backend can consume the operation.

Closes openclaw#139847
…tive run

Boots a child Gateway with the mock provider, sends a message that starts a
held reply run, then sends a second message while that run is active. Proves
the queued follow-up runs as its own turn and its reply is delivered, with no
"no active tool authority snapshot" error.

Adds a dedicated stall prompt to the QA mock so the first turn stays active
while the follow-up is admitted.

Refs openclaw#139847
…kend

Add a live-gated Gateway test that runs the reported sequence on the
bundled claude-cli backend: a second chat.send arrives while the first
CLI turn is running, is admitted as a queued follow-up, and after the
first turn completes runs as its own CLI execution with its reply
delivered. Against a dist built from main the queued turn dies at route
binding with "Reply operation has no active tool authority snapshot".

Switch the mock-provider e2e test to chat.send as well: the qa-channel
poller hands inbound messages to the Gateway one at a time and waits for
each reply, so its second message never reached the reply pipeline
mid-run and the queued path was not exercised.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 7, 2026
openclaw#140018)

* fix(ci): keep preflight job outputs under GitHub's 1 MiB cap

Pull requests that need the full canonical Node test plan failed preflight
with "Job outputs exceed 1,048,576 bytes", which made ci-gate report every
lane as selected=missing. The compact plan lists 7,749 striped test files
explicitly, and GitHub measures job outputs in UTF-16, so the effective cap
for all preflight outputs is 524,288 characters. The manifest reached ~522K
characters on the github profile as the tracked test inventory grew.

Emit each Node matrix row's groups as gzip+base64 JSON at the manifest
boundary and unpack them in the shard runner. On current main this takes the
github-profile manifest from 522,522 to 195,410 characters and the blacksmith
profile from 450,639 to 158,571, with identical jobs and group membership.
The manifest imports the codec through the existing target-plan seam, the
trusted runner checkout lists it, and plain OPENCLAW_NODE_TEST_GROUPS_JSON
remains for the Vitest cache warmer.

Related to openclaw#139929 and openclaw#136820.

* fix(ci): load the Node test groups codec only for grouped rows

The manifest imported scripts/lib/ci-node-test-groups-codec.mts
unconditionally through importTargetPlan. An ordinary manual
workflow_dispatch whose target_ref predates the codec is not a
compatibility target, so the import threw before planning even though
such targets emit an ungrouped plan and never call the encoder.

Import the codec only when the emitted Node rows carry groups, and keep
the clear failure when a grouped plan comes from a target without it.
The workflow-guard fixture can now omit the codec so a codec-free manual
target runs the real manifest step.

* fix(ci): preserve grouped historical test plans

Negotiate the packed group codec against the selected target and fall back to the same five-field legacy projection when the codec is unavailable.

Five-field projection adapted from openclaw#140036.

Co-authored-by: Peter Steinberger <[email protected]>

---------

Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
@aspalagin

Copy link
Copy Markdown
Contributor

Field validation on 2026.9.4: this one-line change fixes the lost-message case in production

Environment. OpenClaw 2026.9.4 (3a9d69d), npm global install, Ubuntu / Linux 6.8.0-139-generic x64, Node 26.9.0, single gateway, single agent. Runtime claude-cli (primary anthropic/claude-fable-5-1). Telegram direct chat with DM topics. messages.queue not configured (default mode).

Before the patch (natural trigger, 2026-09-19). Run A was a 5.5-minute claude-cli turn (cli exec … reuse=reusable-drift:system-prompt,prompt-tools at 22:27:46Z, cli turn … durationMs=327259 at 22:33:13Z; its reply was delivered). Three user messages sent during that turn (22:30:59Z, 22:31:14Z, 22:31:26Z) each died ~1.3 s after arrival with the generic error card, and none was requeued. No cli exec was logged for any of them, i.e. the throw happened at route binding before the CLI launched:

22:30:59.230 Inbound message telegram:… (direct, 15 chars)
22:31:00.511 ERROR Embedded agent failed before reply: Reply operation has no active tool authority snapshot
22:31:14.618 Inbound message telegram:… (direct, 15 chars)
22:31:16.065 ERROR Embedded agent failed before reply: Reply operation has no active tool authority snapshot
22:31:26.478 Inbound message telegram:… (direct, 5 chars)
22:31:27.713 ERROR Embedded agent failed before reply: Reply operation has no active tool authority snapshot

Same shape on this host on Sep 12, 13 and 18.

Which clause. In the published 2026.9.4 dist/agent-runner.runtime-*.mjs, bindToolAuthoritySnapshot(prepareReplyToolAuthority(…)) occurs exactly once, on the foreground path (runReplyAgent). The operation created in admitFollowupTurn is never given a snapshot, so the first bindToolAuthorityRoute call on the CLI turn path throws on !toolAuthoritySnapshot. This matches the instrumented measurement in #139847 (comment) and the reviewer summary above.

What we applied. The PR's single line, verbatim, into the 2026.9.4 dist chunk: operation.bindToolAuthoritySnapshot(prepareReplyToolAuthority(queued)); right after const queued = { ...params.queued, run }; in admitFollowupTurn (prepareReplyToolAuthority is already imported there).

Offline RED/GREEN against the real dist modules (createReplyOperation, admitReplyTurn, admitFollowupTurn from the bundle): foreground operation admitted with a snapshot; queued follow-up waits for idle and is admitted after the foreground complete(); then bindToolAuthorityRoute({ provider, model }) on the follow-up operation.

  • vanilla 2026.9.4: throws Reply operation has no active tool authority snapshot (6/7 steps pass)
  • patched: returns a fingerprint equal to resolveFollowupRunToolAuthorityFingerprint(queued.run, route) (7/7)

Live after gateway restart (2026-09-19T23:35Z).

  • Controlled: run A executed exec sleep 75 on claude-cli; message B was injected 16 s into A via sessions_send. B waited in the session lane (lane wait exceeded … waitedMs=62859 activeAhead=1), then ran as its own turn (cli exec 23:41:22Z) and its reply was delivered (23:41:29Z).
  • Natural: a user message arrived 8 s after a run started in a Telegram DM topic, waited 143.8 s in the lane, ran as its own turn and was answered.
  • 3.6 h of traffic since restart: 7 claude-cli turns, 3 queued follow-ups admitted after an active run, 0 occurrences of authority snapshot / failed before reply. Small sample; will report if it recurs.

Not done here. We did not run the PR's vitest suites (no monorepo checkout with node_modules on the host); validation is the dist-level harness plus the live checks above. One thing we could not reconstruct from logs is how the follow-up admission overlapped with the still-active run A (same overlap the PR's e2e test reproduces with sessionState=processing); the fix does not depend on that mechanism.

+1 for merging. Prepared with AI assistance (the OpenClaw agent on this host did the analysis and testing); reviewed and posted by the operator.

@kiranvk-2011

Copy link
Copy Markdown
Contributor

Runtime data point: on a main-based build this change loses the queued follow-up (double bind with #143661)

We carried this PR's head (066b764143) on a canary built from upstream main 20eebbd5c (2026-09-21) and ran the queued-follow-up scenario on the claude-cli backend. The follow-up is lost, and the mechanism is the same one #142306 hit on 2026-09-12: main already binds the queued turn's tool authority at execution time, so the admission-time bind added here is a second, different snapshot and the registry refuses it.

Environment

Test

  1. /queue collect
  2. Message A: an exec turn that runs python3 -c "import time; time.sleep(50)" and then replies DONE-A (Claude Code refuses a bare sleep, so A really runs ~55 s).
  3. Message B, sent 18 s (run 1) and 25 s (run 2) into A: "reply with exactly DONE-B".

Result

image A B gateway
with this PR (:49cc56d) DONE-A after 55223 / 54949 ms never answered, both runs followup queue drain failed for agent:opus46:<session>: Error: Reply operation cannot change tool authority after admission every ~500 ms, 1,202 lines in 6.5 min (768 + 434 across the two test sessions; first failure 371 ms after A's turn ended), until the container is restarted
without this PR (control) DONE-A after 54992 / 54982 ms delivered as [Queued messages while agent was busy] → DONE-B, its own claude-cli turn (1303 / 1288 ms), both runs 0 lines matching tool authority, 0 drain failures

Gateway log, with this PR (run 1):

11:22:02.614 [agent/cli-backend] cli exec: provider=claude-cli model=claude-opus-5 promptChars=189 trigger=user useResume=false session=none   <- A
11:22:57.836 [agent/cli-backend] cli turn: provider=claude-cli model=claude-opus-5 durationMs=55223 outBytes=30
11:22:58.207 followup queue drain failed for agent:opus46:<session>: Error: Reply operation cannot change tool authority after admission
11:22:58.714 followup queue drain failed for agent:opus46:<session>: Error: Reply operation cannot change tool authority after admission
11:22:59.229 followup queue drain failed for agent:opus46:<session>: Error: Reply operation cannot change tool authority after admission
... (every ~500 ms; no `cli exec` for B ever appears)

Control, same shape (run 1):

11:33:54.540 [agent/cli-backend] cli exec: provider=claude-cli model=claude-opus-5 promptChars=189 trigger=user useResume=false session=none   <- A
11:34:49.532 [agent/cli-backend] cli turn: provider=claude-cli model=claude-opus-5 durationMs=54992 outBytes=34
11:34:50.343 [agent/cli-backend] cli exec: provider=claude-cli model=claude-opus-5 promptChars=101 trigger=user useResume=true session=present  <- B, queued, runs as its own turn
11:34:51.643 [agent/cli-backend] cli turn: provider=claude-cli model=claude-opus-5 durationMs=1303 outBytes=6

Why

bindToolAuthoritySnapshot refuses a second, different snapshot object once one is bound. The built runtime bundle shows the call sites (grep -o 'bindToolAuthoritySnapshot(prepareReplyToolAuthority([a-zA-Z.]*))' agent-runner.runtime-*.mjs | sort | uniq -c):

image (followupRun) direct-send (queued) this PR, admission (turn.queued) main #143661, execution
control 1 – 1
with this PR 1 1 1

On main today the execution-time bind is src/auto-reply/reply/followup-turn-execution.ts:376 (turn.operation.bindToolAuthoritySnapshot(prepareReplyToolAuthority(turn.queued)), from #143661, merged 2026-09-10). With this PR, admission binds first, execution then tries to bind again with a fresh prepareReplyToolAuthority(turn.queued) object, the registry throws, and the drain retries forever.

Why the field validations above still saw a fix

They are on the 2026.9.4 release, which does not contain #143661 (git merge-base --is-ancestor bffda1f9452 v2026.9.4 → false; same for v2026.9.3), so on those builds the queued path has no bind at all and this PR's single line is the only one. v2026.9.5 (tagged 2026-09-18) does contain #143661, so on 2026.9.5 and on main this PR as written turns a fixed path back into a lost message, with a different error string than the one in the title.

Suggestion

Bind at admission only when the operation has no snapshot yet, or take the approach #142306's current head uses (move the bind to admission and remove the execution-time call) so there is exactly one production bind on the follow-up path. I can re-run the same red/green on a revised head.

@gregb100

Copy link
Copy Markdown

Independent field validation on 2026.9.4 (production, Telegram lane) — repro confirmed + timeline data

Adding independent production data from a second deployment, since the thread currently has conflicting field results (aspalagin's 9.4 validation vs kiranvk-2011's main-build loss via #143661).

Environment: OpenClaw 2026.9.4 (3a9d69d), npm global, Ubuntu (kernel 7.0.0-34), Node 24.21.0, single gateway, single agent, Telegram direct chat with topics. No companion app / no browser Control UI session involved.

Repro (deterministic on our install): send a Telegram message while an active turn is >1 min into tool work. When the first turn completes, the queued turn dies in 10–56 ms, before any model call:

[diagnostic] lane task error: lane=session:... error="Reply operation has no active tool authority snapshot"
[model-fallback/decision] candidate_failed ... reason=unknown detail=Reply operation has no active tool authority snapshot  (x4: glm-5.3 → grok-4.7 → qwen3.7-plus → auto)
Embedded agent failed before reply: Reply operation has no active tool authority snapshot

Two user instructions were eaten this way 16 minutes apart today (each as a 12-line journal burst). Recovery practice we now use: the inbound survives in session history and is re-run on a fresh turn.

Timeline data point (latent race, not a version-change trigger): 2026.9.4 installed 2026-09-11; zero occurrences Sep 11–26; first occurrence Sep 27 21:02; then 48 lines Sep 28, 30 lines Sep 29. Gateway process and install unchanged throughout — the race sat dormant until our traffic pattern shifted to long multi-minute tool turns with mid-turn follow-ups. Worth noting for triage: this can look like "it started yesterday" to users without any config or version change.

Static check on 2026.9.6 (latest, 2026-09-23): the bindToolAuthorityRoute guard + throw string is byte-identical to 2026.9.4 in the ±4000-char window around the throw site in dist/worker/worker.mjs. Not claiming 9.6 still misbehaves (the bind-timing fix may live elsewhere), just pinning that the guard itself is unchanged — the 8.x line (2026.8.33 extended-stable) contains no bindToolAuthorityRoute at all.

Stacked defect worth keeping in scope (cross-link #148789): in the same burst, this pre-model invariant failure is classified as a model-candidate failure and burns the entire fallback chain (4 candidates, $0 tokens, identical deterministic failure each time). Whatever lands for the bind race, invariant/operational errors of this class should be non-retryable so the fallback chain isn't wasted re-running an operation that cannot succeed.

Happy to provide raw journal excerpts if useful.

@gregb100

Copy link
Copy Markdown

Trigger refinement (follow-up to our field validation above): the race correlates with primary-model meter exhaustion.

Journal from the same deployment shows every "no active tool authority snapshot" burst is immediately preceded by the primary model returning a billing/meter failure:

05:03:24 [model-fallback/decision] candidate_failed requested=xai/grok-4.7 reason=billing next=openrouter/z-ai/glm-5.3 detail=402 "Grok Build usage balance exhausted"
05:08:43.744 lane task error: "⚠️ xai (grok-4.7) returned a billing error — check your account for subscription or usage limits"
05:08:43.746 candidate_failed requested=xai/grok-4.7 candidate=xai/grok-4.7 reason=billing next=glm-5.3 detail=402 "Grok Build usage balance exhausted"
05:08:43.809 candidate_failed candidate=glm-5.3 reason=unknown detail=Reply operation has no active tool authority snapshot   ← the race, now misclassified as a model failure

Timeline correlation: our 2026.9.4 install ran error-free Sep 11–26 and the Grok meter (Build usage balance) exhausted around Sep 27 21:02 — the exact timestamp of our first-ever occurrence of this error. Every burst since has a preceding 402.

Suggested handling that falls out of this: (1) billing/meter 402 on the primary already forces the fallback path — the queued-turn bind race appears to be reachable chiefly on that path, so it's a good repro wedge; (2) again cross-linking #148789 — when the authority throw fires mid-chain, it poisons the remaining candidates, and a user with an exhausted primary meter loses the message entirely instead of cleanly falling back.

@gregb100

Copy link
Copy Markdown

Design invariant this bug violates: model fallback must never be destructive to active or queued work.

A meter/billing limit on the primary model is a routine, expected runtime event — any user on any metered plan will hit it. The correct degradation is boring: queued messages continue on the fallback model, unaffected.

Current behavior on 2026.9.4 is the opposite: the 402 triggers the fallback path, the authority-bind race fires there, and the result is maximally destructive — the queued user message is lost, the remaining fallback candidates are burned retrying a deterministic operational failure (cross-link #148789), and the user is told to start a new session when the lane is healthy.

Two concrete acceptance criteria that would close this class:

  1. No path from a billing/meter failure to message loss. A queued inbound that cannot bind must be re-queued for a fresh turn (or executed with a re-minted snapshot) — never dropped. Message delivery and model selection are separate concerns; the failure of one must not consume the other.
  2. Operational errors are non-retryable and unlabeled as model failures. An invariant throw is not a candidate failure; it should short-circuit the chain, not burn the remaining models — otherwise the user loses the message and the diagnosis is obscured (everything looks like model flakiness).

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Oct 8, 2026
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @ylcn91 for investigating this and providing the detailed CLI reproduction. Closing as already fixed by #143661 (bffda1f).

On current main, executeFollowupTurn binds a fresh snapshot from the queued input through bindToolAuthoritySnapshotAsync(prepareReplyRunToolAuthority(...)) before agent execution. The missing-snapshot guard remains enforced; adding a second admission-time binding would conflict with the existing binding.

Verified on main 1a2eb9f: 38 queued-execution/tool-authority tests passed, including rejection of changed operator/tool permissions. The real Gateway product regression also passed: a second chat.send queues during a held first turn, then completes with tool execution after its predecessor finishes. Main subsequently advanced by one unrelated test-only commit; the relevant production paths are unchanged. The original CLI reproduction remains useful evidence for the older releases. Thank you!

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

Labels

extensions: qa-lab merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: message sent while a reply run is active is dropped — "Reply operation has no active tool authority snapshot" (regression in 2026.9.2)

5 participants