Skip to content

fix: stalled chat turns ask users to retry instead of answering from gathered context - #161069

Merged
obviyus merged 9 commits into
mainfrom
fix/stalled-turn-recover
Sep 30, 2026
Merged

obviyus merged 9 commits into
mainfrom
fix/stalled-turn-recover

Conversation

@obviyus

@obviyus obviyus commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: a chat turn that stalls (slow model or tools, then aborted by stuck-session recovery) posts "⚠️ This turn was interrupted because it stopped making progress. Please try again." and leaves the user to re-ask, even though the transcript already holds most of what's needed to answer.

User Impact

When an interactive turn stalls before sending any output, and its request is already saved in the transcript:

  • Nothing from that sender is waiting in the follow-up queue (the normal channel case): no notice. OpenClaw starts one recovery turn on the stalled turn's route and authority. It answers from the existing transcript, keeps tool use minimal, doesn't repeat actions and says what it couldn't verify. Channel messages that arrived during the stall, from this sender or another one sharing the session, run afterwards as their own turns.
  • The same sender already has a follow-up in the queue (for example chat.send with queueMode: "followup"): no notice. That follow-up runs next with a runtime note that the stalled turn's request is still unanswered, so it answers that request together with the new message. Follow-ups from other senders or routes sharing the session are never given the stalled request. They get a separate recovery turn instead.
  • The recovery turn, or the follow-up that took over the request, also stalls: the existing notice is sent as a last resort. There is never a second recovery.
  • A Web UI (chat.send) or group-thread participant turn with no queued follow-up from the same sender: the existing notice is sent. These turns reply only through their own source-bound delivery, which a separate recovery turn can't use, so its answer would be dropped.
  • The turn stalls before its request is saved (for example during preflight compaction): the existing notice is sent, because a transcript-only recovery couldn't see the request.

Cron, heartbeat, optional-reply turns and stalls after output are unchanged.

It also fixes a custody bug in dispatch that is already on main. A channel message queued as a follow-up behind a busy session could get "⚠️ OpenClaw couldn't produce or deliver a reply. Please try again." while that follow-up was still waiting to run. This happened when the busy turn ended just before the message's dispatch took the session back for final delivery. Dispatch now keeps the queue's accepted custody instead of overwriting it with the late owned admission.

Why This Change Was Made

On a live Telegram gateway in our setup, a user asked a simple restaurant question while the network was throttled. The turn spent 15 minutes researching, was aborted, and the user got "Please try again". The very next queued message answered correctly from the same transcript within a minute.

The recovery reuses the existing session follow-up lane (enqueueFollowupRun plus drain after the reply operation clears), so there is no new queue. The recovery run is replay-safe: the inbound message isn't replayed or re-persisted, and inbound dedupe and turn adoption are unchanged. When the queue hands the request to an existing follow-up, it matches on the queue's existing route key plus the collect-batching authorization key (sender, operator authority, owner and exec overrides). If the stalled turn's operator authority is no longer current, nothing is continued and the notice path runs as before. A recovery turn is otherwise an ordinary queued follow-up under the queue's existing admission, abort and authority checks (maintainer decision in the PR thread).

Accepted tradeoffs

  • Cancelling a follow-up that took over a stalled request stays silent. A targeted chat.abort of that queued follow-up is a deliberate cancel. No retry notice is sent afterwards (maintainer decision).
  • No extra send-time authority fence. The recovery turn is an ordinary queued follow-up under the queue's existing admission, abort and authority checks. Authority is checked when the continuation is queued and again at follow-up admission, the same as any queued follow-up (maintainer decision).
  • Web UI and group-thread participant turns without a queued same-sender follow-up keep the notice. Giving a standalone recovery turn a live source-bound delivery owner would need new machinery, so this PR scopes recovery to channel turns and the same-sender follow-up handoff (maintainer decision).

Evidence

  • Telegram Test Server with a live OpenAI model, head 0eca7a4 (Recovery) and e0b05c5 (the other cases) (telegram-e2e-userbot skill, Convex-leased credential, real QA user in a DM, QA_DIAGNOSTIC_STUCK_SESSION_ABORT_MS=30000, diagnostics.enabled, a fallback model, and provider timeoutSeconds: 30 so the stuck detector's model allowance matches the QA abort bound). A live model can't be made to stall on demand, so a proof-only local proxy sits in front of the real OpenAI API. For a stalled turn it reproduces the QA mock's stall shape: 4 main-model requests that fail after 8 s, then 1 held open until the abort. Everything else goes to the API unchanged. The question is "What is 17*23? Reply with just the number.":

    • Recovery: the QA user's message lands at +0.2 s. Stuck recovery aborts the turn at 54 s (stuck session recovery … action=abort_embedded_run, then cause=skipped:reply_operation_aborted). One recovery request carrying the stall guidance goes to the live model, which returns 391. The only SUT message is 391 at +61.3 s, with no retry notice. Main-model requests: 5 stalled, 1 forwarded. The same result held at e0b05c5 (+61.1 s).
    • The recovery also stalls (the proxy stalls the guided request the same way): there are two stuck aborts (ages 53 s and 59 s). The only SUT message is the existing notice "⚠️ This turn was interrupted because it stopped making progress. Please try again." at +118.3 s. Main-model requests: 5 stalled plus 5 recovery requests stalled, none forwarded, and no second recovery.
    • Queued same-sender follow-up (messages.queue.mode: followup): the QA user asks 1723 at +0.2 s and "Also, what is 1921? Reply with just the number." at +20.2 s, while the first turn is stalling. After the abort, the queued follow-up runs once with the stall guidance and the live model returns 391 and 399. There's one SUT message at +60.4 s, no notice, no "couldn't produce or deliver a reply" fallback and no separate recovery turn.
    • The queued follow-up also stalls: same two messages, and the proxy also stalls the follow-up's guided requests. There are two stuck aborts (ages 53 s and 60 s). The only SUT message is the notice at +117.9 s.
    • Defect this found on c8a2682: with the old guidance ("Answer the user's outstanding request now"), the live model took the newer message as the outstanding request and replied only 399. The stalled question went unanswered, with no notice. The guidance now says the stalled turn's request is still unanswered and asks for an answer to it together with any newer message. The same scenario then answered both questions, at 313f58a and again at e0b05c5. The QA mock needle ("previous turn stopped making progress") is unchanged.
    • Runner wall times: 170 s, 202 s, 222 s and 224 s.
  • Real Gateway chat.send (Web UI path) with a live OpenAI model: a standalone Gateway from the built head, the same stall proxy, and an operator WebSocket client (the TUI's GatewayClient) that sends the question with chat.send and records the chat broadcasts:

    • Head 0eca7a4: the turn stalls (5 stalled main-model requests) and stuck recovery aborts it at 50 s. The client receives state: "error" with "⚠️ This turn was interrupted because it stopped making progress. Please try again." for its run at +57.9 s, then aborted. No recovery request is sent.
    • Head e0b05c5 (before this fix): same stall and abort. The client only receives aborted for its run. The recovery turn's result is dropped by the chat.send reply owner (webchat late reply disposition … outcome: late-and-dropped, reason: terminal-not-recorded). The user gets neither an answer nor the stall notice.
  • Telegram Test Server (telegram-e2e-userbot skill, Convex-leased credential, real QA user in a DM, --backend qa-mock, QA_DIAGNOSTIC_STUCK_SESSION_ABORT_MS=30000, E2E_ROOT_CONFIG_PATCH enabling diagnostics plus a fallback model so the turn keeps retrying, 180 s recording window). Head c8a2682:

    • The QA user sends one message at +0.2 s. The only SUT message is STALLED-TURN-RECOVERED-OK at +59.9 s, after typing rows. There's no "Please try again" or any other SUT message in the window.
    • Provider requests from the QA mock: 5 stalled requests (4 on the primary model, then 1 held on the fallback model until the abort), then exactly 1 recovery request carrying the stall guidance, which succeeded. The mock only returns the marker for a request that carries the guidance.
    • Gateway log: stuck session recovery outcome: status=aborted, then visible channel turn dispatched with no queued reply payloads … cause=skipped:reply_operation_aborted, then a single telegram outbound send ok.
    • Runner wall time: 203 s.
    • The runner drops *_SESSION_* env keys from child processes as secret-shaped, so for this run a NODE_OPTIONS preload set the QA stuck-session bound on the gateway process only. The harness isn't changed in this PR.
  • qa-lab stalled-turn-auto-recovery (real gateway, qa-channel, mock-openai, session.dmScope: main, messages.queue.mode: followup). Sender A's turn loops on failing model requests until QA-tuned stuck recovery aborts it. Sender B DMs the same main session while A's turn is running. Isolated profile, state dir, config path and gateway port per run, with gateway logs kept (OPENCLAW_QA_KEEP_TEMP=1), 6 runs in parallel:

    • Head c8a2682: 18/18 passed. Earlier head dbc5955 (same runtime code): 12/12 passed. Every run: A's DM gets exactly ["STALLED-TURN-RECOVERED-OK"], B's DM gets exactly ["GATEWAY_REPEATED_REQUEST_QUEUED_OK"], and the mock logs stalledRequests=5 recoveryRequests=1 bystanderRequests=1 with the recovery request before B's. Suite wall time at head under 6-way load: median 132 s, range 81–156 s. A single unloaded run took 70 s.
    • Same build with only the custody fix reverted: 10/15 failed. 8 failed because B got the generic "couldn't produce or deliver a reply" fallback while its queued follow-up was still pending. This is the intermittent failure reported on the previous head. 2 more timed out after B's dispatch failed with restart recovery claim changed before agent adoption. That failure also didn't occur in any run with the fix.
  • gateway-repeated-request-recovery gateway e2e (same-operator chat.send follow-up): passes in 102 s (file wall 173 s). The queued follow-up carries the stall guidance, and no extra recovery turn runs.

  • Unit tests (real runReplyAgent with the real follow-up queue):

    • One transcript-only recovery run when nothing is queued.
    • The same sender's next queued follow-up gets the guidance and is protected from overflow eviction.
    • Another sender's queued follow-up on another route is left untouched, even when a same-sender follow-up sits behind it. A separate recovery run bound to the stalled sender's route and sender drains first.
    • Revoked stalled-turn authority: no continuation and no exception.
    • Heartbeat: no continuation is set up.
    • Dispatch: the notice is sent only when nothing continues the turn. A stall after output continues nothing. A queued channel turn stays accepted when the busy session frees before final admission. This test fails without the custody fix: queuedFinal is true and the fallback is sent.
    • Follow-up delivery: the last-resort notice when the recovery run itself stalls, silence in the other aborted cases.
    • Wall times: agent-runner.stalled-turn.test.ts (new file, 5 tests) takes 26.6 s wall on its own, and its tests run for 2.8 s. The changed dispatch-from-config.terminal-recovery.test.ts, followup-delivery.test.ts and agent-runner.stalled-turn.test.ts together take 36 s wall (93 tests). extensions/qa-lab/src/suite-planning.test.ts takes 14 s wall (28 tests).

LOC vs origin/main: production +252/−25 (core reply +213/−24, qa-lab harness/mock +39/−1). Tests/QA +680/−9 (including the 170-line qa-lab scenario). Docs +1. The qa-lab, gateway e2e and older Telegram evidence above ran at c8a2682. agent-runner.stalled-turn.test.ts passes at 0eca7a4 (8 tests, 31 s wall). Its new Web UI test uses the Gateway's real chat.send reply owner and fails at e0b05c5 (continuation returns true). With the production files reverted to 313f58a, the claimed-follow-up double-stall (followup and collect) and pre-persistence stall tests fail.

@clawsweeper

clawsweeper Bot commented Sep 29, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: qa-lab size: L labels Sep 29, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. 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 29, 2026
@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 30, 2026, 6:50 AM ET / 10:50 UTC (Revision 13).

ClawSweeper review

What this changes

The branch lets OpenClaw continue an eligible stalled chat request once through its existing reply queue, preserves queued reply custody and last-resort notices, and adds tests, a QA scenario, and queue documentation.

Merge readiness

✅ Ready for maintainer review

Current main still sends a retry notice for the central stalled-turn case. The branch remains useful, and the reviewed code and real behavior evidence establish no blocking introduced defect. The scoped delivery and authority tradeoffs were stated by an account with maintain permission.

Priority: P1
Reviewed head: e0cb1fbfe583316ce3fda9eaeafff6c30cfabd58

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong real-path evidence and focused boundary coverage support a useful patch with a deliberately scoped behavior change.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The changed reply and queue owners are exercised by captured Telegram Test Server runs with a live model behind a controlled stall proxy: the original DM receives one answer, a second stall yields one notice, and a same-sender follow-up answers both requests. A real Gateway chat.send trace shows the accepted notice exception. The runs name earlier runtime heads; current-head source inspection supports their claimed paths. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The changed reply and queue owners are exercised by captured Telegram Test Server runs with a live model behind a controlled stall proxy: the original DM receives one answer, a second stall yields one notice, and a same-sender follow-up answers both requests. A real Gateway chat.send trace shows the accepted notice exception. The runs name earlier runtime heads; current-head source inspection supports their claimed paths. No stored-data contract changes.
Evidence reviewed 8 items Current-main behavior: Current main sends the stalled-turn retry notice after a pre-output run_stalled result; it has no stalled-turn continuation symbols.
Continuation owner: The introduced path requires persisted input, checks current operator authority, claims only an eligible queued request, and otherwise schedules one recovery through the existing follow-up queue.
Sender and route boundary: The queue compares route identity and the existing authorization key before handing an unanswered request to the next queued user turn.
Findings None None.
Security None None.

How this fits together

Channel and Web UI requests enter a per-session reply turn. If the stuck-session detector aborts that turn, dispatch and the follow-up queue determine whether the original route receives a continued answer or a retry notice.

flowchart LR
 A[Inbound chat request] --> B[Session reply turn]
 B --> C[Stall detector]
 C --> D{Saved request and eligible route?}
 D -->|Yes| E[Follow-up queue]
 D -->|No| F[Retry notice]
 E --> G[Answer or final notice]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +227, Tests +501, Docs +1, Other +170. Total +899 across 23 files.

View PR surface stats
Area Files Added Removed Net
Source 17 252 25 +227
Tests 4 510 9 +501
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 1 170 0 +170
Total 23 933 34 +899

Review metrics

Metric Value Why it matters
Production versus proof growth production +252/−25; tests and QA +680/−9 The production growth uses the existing queue owner and is accompanied by distinct delivery, lifecycle, and cross-sender scenarios.

Technical review

Best possible solution:

Keep the continuation in the existing session follow-up owner, with one attempt, route-bound delivery, and a truthful final notice when it cannot answer.

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

Yes. Current-main source has a clear path to the retry notice, and the captured Telegram and Gateway traces exercise that stalled-turn scenario; I did not execute this checkout.

Is this the best way to solve the issue?

Yes. The branch uses the existing follow-up queue, guards transcript-only recovery on persisted input, and keeps source-bound delivery exceptions supported by the Gateway trace.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 7db6ea365a62.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: A stalled interactive channel turn can leave a real user with only a retry request after lengthy work.
  • merge-risk: 🚨 compatibility: Default-on continuation changes the former retry-notice outcome; the maintain-role author explicitly accepted that behavior.
  • merge-risk: 🚨 message-delivery: Queue handoff changes answer ordering and routing, with cross-sender separation covered by the QA scenario.
  • merge-risk: 🚨 security-boundary: The continuation carries operator authority through the existing queue checks, and the maintain-role author explicitly accepted no additional send-time fence.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The changed reply and queue owners are exercised by captured Telegram Test Server runs with a live model behind a controlled stall proxy: the original DM receives one answer, a second stall yields one notice, and a same-sender follow-up answers both requests. A real Gateway chat.send trace shows the accepted notice exception. The runs name earlier runtime heads; current-head source inspection supports their claimed paths. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed reply and queue owners are exercised by captured Telegram Test Server runs with a live model behind a controlled stall proxy: the original DM receives one answer, a second stall yields one notice, and a same-sender follow-up answers both requests. A real Gateway chat.send trace shows the accepted notice exception. The runs name earlier runtime heads; current-head source inspection supports their claimed paths. No stored-data contract changes.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Telegram users visibly receive either a recovered answer or the final retry notice, and the PR body reports Test Server proof of both.

Evidence

What I checked:

  • Current-main behavior: Current main sends the stalled-turn retry notice after a pre-output run_stalled result; it has no stalled-turn continuation symbols. (src/auto-reply/reply/dispatch-from-config.prepare-context.ts:453, 7db6ea365a62)
  • Continuation owner: The introduced path requires persisted input, checks current operator authority, claims only an eligible queued request, and otherwise schedules one recovery through the existing follow-up queue. (src/auto-reply/reply/agent-runner-execute.ts:41, e0cb1fbfe583)
  • Sender and route boundary: The queue compares route identity and the existing authorization key before handing an unanswered request to the next queued user turn. (src/auto-reply/reply/queue/enqueue.ts:284, e0cb1fbfe583)
  • Last-resort delivery: A marked recovery that also stalls produces the notice; other aborted follow-ups remain suppressed. (src/auto-reply/reply/followup-delivery.ts:144, e0cb1fbfe583)
  • Real behavior proof: The captured PR body hash matched the live REST body. Its earlier runtime-head Telegram Test Server traces show one recovered answer, a notice when recovery also stalls, and a same-sender follow-up answering both requests; a real Gateway chat.send trace shows the source-bound notice. These runs are attributed to their stated heads, not represented as an exact-final-head rerun.
  • Maintainer tradeoff: The author account has maintain permission and identifies as Ayaan Zaidi. Its PR comments explicitly accept default-on recovery, the existing queued-follow-up authority checks without an extra send-time fence, silent deliberate cancellation, and the standalone Web UI exception.

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • shakkernerd: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-30T06:25:41.744Z sha e0b05c5 :: needs changes before merge. :: none
  • reviewed 2026-09-30T07:36:37.351Z sha e0b05c5 :: blocked before merge. :: [P2] Keep the stalled request owned if its claimed follow-up is canceled
  • reviewed 2026-09-30T07:44:07.890Z sha e0b05c5 :: needs changes before merge. :: none
  • reviewed 2026-09-30T08:50:59.645Z sha e0b05c5 :: blocked before merge. :: [P1] Preserve Web UI delivery for standalone recovery
  • reviewed 2026-09-30T09:17:23.516Z sha 0eca7a4 :: blocked before merge. :: none
  • reviewed 2026-09-30T09:27:47.044Z sha 0eca7a4 :: needs changes before merge. :: none
  • reviewed 2026-09-30T10:16:15.946Z sha 0eca7a4 :: needs changes before merge. :: [P2] Document the group-thread retry-notice exception
  • reviewed 2026-09-30T10:23:56.271Z sha fd0e7dddbbfc60f069c21da8c3bf1345612d3efc :: needs maintainer review before merge. :: none

@obviyus
obviyus force-pushed the fix/stalled-turn-recover branch from aa90f18 to 8a21d26 Compare September 29, 2026 13:20
@obviyus

obviyus commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator Author

Owner decision (maintainer): we want automatic recovery on by default. Security is a product tradeoff here. We accept bounded risk within the existing trust model instead of adding new fences for hypothetical cases.

  • Cross-sender handoff (P1): fixed. Only the same sender and route, with the same authorization key, can take over the stalled request. Anyone else's queued follow-up is left untouched, and a separate recovery turn runs on the stalled turn's own route and authority. This is covered by a unit test and by the two-sender qa-channel scenario.
  • Revoked authority: we're adding no new machinery. The recovery run carries the stalled turn's existing operator authority, so the queue's existing enqueue/admission checks gate it. If that authority is already stale at the stall, the turn isn't continued and the existing notice is sent.
  • Repeating completed actions: the recovery turn runs over the persisted transcript under the same tool policy. The inbound message isn't replayed, and the model is told not to repeat actions that already ran. That matches how any follow-up turn in the session already behaves, and it's the tradeoff we accept for not asking users to retry.
  • Fixed 3 s QA sleep: replaced. The scenario now asserts only after diagnostics.stability reports the session idle with an empty queue.

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

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 29, 2026
@obviyus

obviyus commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator Author

Revision 2 findings:

  • [P1] Protect the selected follow-up: fixed. A claimed follow-up is now exempt from drop: old and summarize eviction, using the same protectFromQueueOverflow custody as the front-queued recovery run.
  • [P2] Recovery order: fixed. The handoff now takes only the next pending user request, and only when that request comes from the same route and authorization key. If another sender's request is ahead, a separate recovery run is queued at the front instead. There's a unit test for this ordering.
  • [P1/high] Recheck authority before the final channel send: owner decision, no change. The recovery turn is an ordinary follow-up that carries the stalled turn's operator authority. The queue's existing enqueue/admission fences and abort signal gate it exactly as they gate every other queued follow-up. Adding a new final-send fence only for this path is outside the existing trust model, and we accept that bounded risk for simplicity.

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper Maintainer decision (Ayaan, repository maintainer): both remaining Revision 3 items are accepted as they are.

  • Default-on recovery: accepted. Recovery is on by default. Without it, a stalled turn ends in a retry notice and the user has to repeat themselves. A recovery turn is an ordinary follow-up that runs under the queue's existing admission, abort and authority checks, so it has the same exposure as any queued follow-up. It doesn't replay the inbound message and runs over the persisted transcript. The model sees its own tool calls and results there and is told not to repeat actions that already ran, which limits repeated side effects.
  • Revalidate operator authority before the recovery's final channel send: declined, same as Revision 2. There's no extra send-time fence. Queued follow-ups don't have one either, and the recovery turn's authority is checked at enqueue and at follow-up admission the same way theirs is. If the stalled turn's authority is already stale at the stall, nothing is continued and the existing notice is sent.

@clawsweeper

clawsweeper Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper assist is taking a look at your question.

I queued a lightweight read-only assist pass. It will post a separate answer comment and will not edit the durable ClawSweeper review comment or trigger close, merge, repair, label, or branch changes.

Request: Maintainer decision (Ayaan, repository maintainer): both remaining Revision 3 items are accepted as they are. - Default-on recovery: accepted. Recovery is on by default. Without it, a stalled turn ends in a retry notice and the user has to repeat themselves. A recovery turn is an ordinary follow-up that runs under the queue's existing admission, abort and authority checks, so it has the same exposure as any queued follow-up. It doesn't replay the inbound message and runs over the persisted t...

@obviyus

obviyus commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper assist: Ayaan’s decision accepts default-on recovery and declines an extra authority check before the final channel send. Whether the current implementation and proof satisfy that decision needs a full review.

Evidence:

  • The maintainer decision states both choices.
  • Revision 3 reviewed ea2b498; the PR is now at c8a2682 and its body reports Telegram Test Server and gateway proof.

Suggested next action: Request @clawsweeper review for the current head and PR body.


Source: #161069 (comment)
Assist reasoning: medium.

@obviyus

obviyus commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. 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 30, 2026
obviyus and others added 4 commits September 30, 2026 16:12
Keep the claimed follow-up responsible for last-resort feedback and require persisted input before transcript-only continuation. Move the existing continuation block into the execution owner; cover real queue delivery and early preflight cancellation.

Co-authored-by: obviyus <[email protected]>
@obviyus
obviyus force-pushed the fix/stalled-turn-recover branch from fd0e7dd to e0cb1fb Compare September 30, 2026 10:43
@obviyus
obviyus merged commit 872c9ba into main Sep 30, 2026
294 of 362 checks passed
@obviyus
obviyus deleted the fix/stalled-turn-recover branch September 30, 2026 11:30
@obviyus

obviyus commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 872c9ba (squash of head e0cb1fb).

Bug: when an interactive chat turn stalled and stuck-session recovery aborted it, the user got "⚠️ This turn was interrupted because it stopped making progress. Please try again." and had to ask again, even though the transcript already had enough to answer. A queued channel follow-up could also get the generic "couldn't produce or deliver a reply" fallback while it was still waiting to run.

Fix: a stalled channel turn now gets one recovery turn on its own route and authority. If the same sender already has a follow-up queued, that follow-up takes over the stalled request instead. The notice is sent only when that continuation also stalls, when the request was never saved, or when the turn is a Web UI or group-thread turn with no same-sender follow-up. Dispatch also keeps the queue's accepted custody for a queued follow-up.

Proof: on the Telegram Test Server with a live OpenAI model and a fault proxy:

  • A stalled question got the real answer (391) with no notice.
  • When the recovery also stalled, the user got exactly one notice.
  • A queued same-sender follow-up answered both questions.
  • A real Gateway chat.send shows the scoped Web UI notice.
  • Two-sender qa-lab runs showed the bystander's reply stays separate.

Hosted review: ready at e0cb1fb (Revision 13). Ayaan (repository maintainer) reviewed this PR and approved landing. Accepted tradeoffs are recorded in the PR body and in the maintainer-decision comments.

CI bypass: merged with admin bypass for a flake shared with unrelated PRs, which this PR doesn't touch: src/gateway/server-runtime-subscriptions.shutdown.test.ts > cancels auxiliary model work before inherited connection drain. It failed in both attempts of run https://github.com/openclaw/openclaw/actions/runs/36704163151 (every other job was green or cancelled by the gate). It passes locally at the head, alone (3/3) and together with its shard's other files (2/2). The same test failed today on 5 unrelated branches:

CI on the earlier head 0eca7a4, before the rebase that picked up main's registry build fix, was fully green: https://github.com/openclaw/openclaw/actions/runs/36694377070.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 1, 2026
…gathered context (openclaw#161069)

## What Problem This Solves

Fixes: a chat turn that stalls (slow model or tools, then aborted by stuck-session recovery) posts "⚠️ This turn was interrupted because it stopped making progress. Please try again." and leaves the user to re-ask, even though the transcript already holds most of what's needed to answer.

## User Impact

When an interactive turn stalls before sending any output, and its request is already saved in the transcript:

- **Nothing from that sender is waiting in the follow-up queue (the normal channel case):** no notice. OpenClaw starts one recovery turn on the stalled turn's route and authority. It answers from the existing transcript, keeps tool use minimal, doesn't repeat actions and says what it couldn't verify. Channel messages that arrived during the stall, from this sender or another one sharing the session, run afterwards as their own turns.
- **The same sender already has a follow-up in the queue (for example `chat.send` with `queueMode: "followup"`):** no notice. That follow-up runs next with a runtime note that the stalled turn's request is still unanswered, so it answers that request together with the new message. Follow-ups from other senders or routes sharing the session are never given the stalled request. They get a separate recovery turn instead.
- **The recovery turn, or the follow-up that took over the request, also stalls:** the existing notice is sent as a last resort. There is never a second recovery.
- **A Web UI (`chat.send`) or group-thread participant turn with no queued follow-up from the same sender:** the existing notice is sent. These turns reply only through their own source-bound delivery, which a separate recovery turn can't use, so its answer would be dropped.
- **The turn stalls before its request is saved** (for example during preflight compaction): the existing notice is sent, because a transcript-only recovery couldn't see the request.

Cron, heartbeat, optional-reply turns and stalls after output are unchanged.

It also fixes a custody bug in dispatch that is already on `main`. A channel message queued as a follow-up behind a busy session could get "⚠️ OpenClaw couldn't produce or deliver a reply. Please try again." while that follow-up was still waiting to run. This happened when the busy turn ended just before the message's dispatch took the session back for final delivery. Dispatch now keeps the queue's `accepted` custody instead of overwriting it with the late `owned` admission.

## Why This Change Was Made

On a live Telegram gateway in our setup, a user asked a simple restaurant question while the network was throttled. The turn spent 15 minutes researching, was aborted, and the user got "Please try again". The very next queued message answered correctly from the same transcript within a minute.

The recovery reuses the existing session follow-up lane (`enqueueFollowupRun` plus drain after the reply operation clears), so there is no new queue. The recovery run is replay-safe: the inbound message isn't replayed or re-persisted, and inbound dedupe and turn adoption are unchanged. When the queue hands the request to an existing follow-up, it matches on the queue's existing route key plus the collect-batching authorization key (sender, operator authority, owner and exec overrides). If the stalled turn's operator authority is no longer current, nothing is continued and the notice path runs as before. A recovery turn is otherwise an ordinary queued follow-up under the queue's existing admission, abort and authority checks (maintainer decision in the PR thread).

## Accepted tradeoffs

- **Cancelling a follow-up that took over a stalled request stays silent.** A targeted `chat.abort` of that queued follow-up is a deliberate cancel. No retry notice is sent afterwards ([maintainer decision](openclaw#161069 (comment))).
- **No extra send-time authority fence.** The recovery turn is an ordinary queued follow-up under the queue's existing admission, abort and authority checks. Authority is checked when the continuation is queued and again at follow-up admission, the same as any queued follow-up ([maintainer decision](openclaw#161069 (comment))).
- **Web UI and group-thread participant turns without a queued same-sender follow-up keep the notice.** Giving a standalone recovery turn a live source-bound delivery owner would need new machinery, so this PR scopes recovery to channel turns and the same-sender follow-up handoff ([maintainer decision](openclaw#161069 (comment))).

## Evidence

- **Telegram Test Server with a live OpenAI model**, head `0eca7a4` (Recovery) and `e0b05c5` (the other cases) (`telegram-e2e-userbot` skill, Convex-leased credential, real QA user in a DM, `QA_DIAGNOSTIC_STUCK_SESSION_ABORT_MS=30000`, `diagnostics.enabled`, a fallback model, and provider `timeoutSeconds: 30` so the stuck detector's model allowance matches the QA abort bound). A live model can't be made to stall on demand, so a proof-only local proxy sits in front of the real OpenAI API. For a stalled turn it reproduces the QA mock's stall shape: 4 main-model requests that fail after 8 s, then 1 held open until the abort. Everything else goes to the API unchanged. The question is "What is 17*23? Reply with just the number.":
  - **Recovery:** the QA user's message lands at +0.2 s. Stuck recovery aborts the turn at 54 s (`stuck session recovery … action=abort_embedded_run`, then `cause=skipped:reply_operation_aborted`). One recovery request carrying the stall guidance goes to the live model, which returns `391`. The only SUT message is `391` at +61.3 s, with no retry notice. Main-model requests: 5 stalled, 1 forwarded. The same result held at `e0b05c5` (+61.1 s).
  - **The recovery also stalls** (the proxy stalls the guided request the same way): there are two stuck aborts (ages 53 s and 59 s). The only SUT message is the existing notice "⚠️ This turn was interrupted because it stopped making progress. Please try again." at +118.3 s. Main-model requests: 5 stalled plus 5 recovery requests stalled, none forwarded, and no second recovery.
  - **Queued same-sender follow-up** (`messages.queue.mode: followup`): the QA user asks 17*23 at +0.2 s and "Also, what is 19*21? Reply with just the number." at +20.2 s, while the first turn is stalling. After the abort, the queued follow-up runs once with the stall guidance and the live model returns `391` and `399`. There's one SUT message at +60.4 s, no notice, no "couldn't produce or deliver a reply" fallback and no separate recovery turn.
  - **The queued follow-up also stalls:** same two messages, and the proxy also stalls the follow-up's guided requests. There are two stuck aborts (ages 53 s and 60 s). The only SUT message is the notice at +117.9 s.
  - **Defect this found on `c8a2682`:** with the old guidance ("Answer the user's outstanding request now"), the live model took the newer message as the outstanding request and replied only `399`. The stalled question went unanswered, with no notice. The guidance now says the stalled turn's request is still unanswered and asks for an answer to it together with any newer message. The same scenario then answered both questions, at `313f58a` and again at `e0b05c5`. The QA mock needle ("previous turn stopped making progress") is unchanged.
  - Runner wall times: 170 s, 202 s, 222 s and 224 s.
- **Real Gateway `chat.send` (Web UI path) with a live OpenAI model**: a standalone Gateway from the built head, the same stall proxy, and an operator WebSocket client (the TUI's `GatewayClient`) that sends the question with `chat.send` and records the `chat` broadcasts:
  - Head `0eca7a4`: the turn stalls (5 stalled main-model requests) and stuck recovery aborts it at 50 s. The client receives `state: "error"` with "⚠️ This turn was interrupted because it stopped making progress. Please try again." for its run at +57.9 s, then `aborted`. No recovery request is sent.
  - Head `e0b05c5` (before this fix): same stall and abort. The client only receives `aborted` for its run. The recovery turn's result is dropped by the chat.send reply owner (`webchat late reply disposition … outcome: late-and-dropped, reason: terminal-not-recorded`). The user gets neither an answer nor the stall notice.

- **Telegram Test Server** (`telegram-e2e-userbot` skill, Convex-leased credential, real QA user in a DM, `--backend qa-mock`, `QA_DIAGNOSTIC_STUCK_SESSION_ABORT_MS=30000`, `E2E_ROOT_CONFIG_PATCH` enabling `diagnostics` plus a fallback model so the turn keeps retrying, 180 s recording window). Head `c8a2682`:
  - The QA user sends one message at +0.2 s. The only SUT message is `STALLED-TURN-RECOVERED-OK` at +59.9 s, after typing rows. There's no "Please try again" or any other SUT message in the window.
  - Provider requests from the QA mock: 5 stalled requests (4 on the primary model, then 1 held on the fallback model until the abort), then exactly 1 recovery request carrying the stall guidance, which succeeded. The mock only returns the marker for a request that carries the guidance.
  - Gateway log: `stuck session recovery outcome: status=aborted`, then `visible channel turn dispatched with no queued reply payloads … cause=skipped:reply_operation_aborted`, then a single `telegram outbound send ok`.
  - Runner wall time: 203 s.
  - The runner drops `*_SESSION_*` env keys from child processes as secret-shaped, so for this run a `NODE_OPTIONS` preload set the QA stuck-session bound on the gateway process only. The harness isn't changed in this PR.
- **qa-lab `stalled-turn-auto-recovery`** (real gateway, qa-channel, mock-openai, `session.dmScope: main`, `messages.queue.mode: followup`). Sender A's turn loops on failing model requests until QA-tuned stuck recovery aborts it. Sender B DMs the same main session while A's turn is running. Isolated profile, state dir, config path and gateway port per run, with gateway logs kept (`OPENCLAW_QA_KEEP_TEMP=1`), 6 runs in parallel:
  - Head `c8a2682`: **18/18 passed**. Earlier head `dbc5955` (same runtime code): 12/12 passed. Every run: A's DM gets exactly `["STALLED-TURN-RECOVERED-OK"]`, B's DM gets exactly `["GATEWAY_REPEATED_REQUEST_QUEUED_OK"]`, and the mock logs `stalledRequests=5 recoveryRequests=1 bystanderRequests=1` with the recovery request before B's. Suite wall time at head under 6-way load: median 132 s, range 81–156 s. A single unloaded run took 70 s.
  - Same build with only the custody fix reverted: **10/15 failed**. 8 failed because B got the generic "couldn't produce or deliver a reply" fallback while its queued follow-up was still pending. This is the intermittent failure reported on the previous head. 2 more timed out after B's dispatch failed with `restart recovery claim changed before agent adoption`. That failure also didn't occur in any run with the fix.
- **`gateway-repeated-request-recovery` gateway e2e** (same-operator `chat.send` follow-up): passes in 102 s (file wall 173 s). The queued follow-up carries the stall guidance, and no extra recovery turn runs.
- **Unit tests** (real `runReplyAgent` with the real follow-up queue):
  - One transcript-only recovery run when nothing is queued.
  - The same sender's next queued follow-up gets the guidance and is protected from overflow eviction.
  - Another sender's queued follow-up on another route is left untouched, even when a same-sender follow-up sits behind it. A separate recovery run bound to the stalled sender's route and sender drains first.
  - Revoked stalled-turn authority: no continuation and no exception.
  - Heartbeat: no continuation is set up.
  - Dispatch: the notice is sent only when nothing continues the turn. A stall after output continues nothing. A queued channel turn stays `accepted` when the busy session frees before final admission. This test fails without the custody fix: `queuedFinal` is `true` and the fallback is sent.
  - Follow-up delivery: the last-resort notice when the recovery run itself stalls, silence in the other aborted cases.
  - Wall times: `agent-runner.stalled-turn.test.ts` (new file, 5 tests) takes 26.6 s wall on its own, and its tests run for 2.8 s. The changed `dispatch-from-config.terminal-recovery.test.ts`, `followup-delivery.test.ts` and `agent-runner.stalled-turn.test.ts` together take 36 s wall (93 tests). `extensions/qa-lab/src/suite-planning.test.ts` takes 14 s wall (28 tests).

LOC vs `origin/main`: production +252/−25 (core reply +213/−24, qa-lab harness/mock +39/−1). Tests/QA +680/−9 (including the 170-line qa-lab scenario). Docs +1. The qa-lab, gateway e2e and older Telegram evidence above ran at `c8a2682`. `agent-runner.stalled-turn.test.ts` passes at `0eca7a4` (8 tests, 31 s wall). Its new Web UI test uses the Gateway's real chat.send reply owner and fails at `e0b05c5` (continuation returns `true`). With the production files reverted to `313f58a`, the claimed-follow-up double-stall (followup and collect) and pre-persistence stall tests fail.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
## What Problem This Solves

Fixes: Web UI (`chat.send`) turns that stall before replying still end with "⚠️ This turn was interrupted because it stopped making progress. Please try again." instead of the automatic recovery that channel DMs get since #161069.

## User Impact

- When a Web UI turn stalls before replying, the user now gets the recovered answer instead of the retry notice. The stalled run ends as aborted, and the answer arrives as its own run in the same chat, the same way any queued Web UI follow-up arrives. If the recovery also stalls, the existing notice is sent once.
- The recovery keeps its normal tools, except that Skill Workshop can't write to the skill library during a recovery. It answers "send a fresh message" instead.
- Group-thread participant turns keep the notice. That is now the only exception, and it's stated in the docs.

## Why This Change Was Made

#161069 kept the notice for Web UI turns because the recovery run had no owner that would deliver its answer ([maintainer decision](#161069 (comment))). Provenance of that owner:

- #116649 binds every queued `chat.send` reply to its originating Gateway admission, so a late answer never goes out through a later same-session dispatcher.
- #129001 added `createSourceRetry`, which gives a front-requeued run of the same source a fresh owner, and the `pending` state: a source that never handed its request to the queue keeps its own terminal, so a finished run gets no duplicate or late reply.
- The recovery run inherited the stalled turn's still-`pending` owner, so its answer was dropped (`terminal-not-recorded`).

The fix:

- **The stalled turn hands its request to the recovery through the source's existing `createSourceRetry`.** A `pending` source that hands off is settled, so the original can never deliver once the retry exists, and the recovery owns the only delivery. The relaxed `pending` case is reachable only through the stall continuation, which runs after the stale watchdog aborted the source before any output. `createSourceRetry` has two callers:
  - the follow-up source retry in `followup-delivery.ts`, which only sees owners that already queued (`deliver`/`drop`);
  - the stall continuation.
- **The #161069 early return is narrowed.** Only a source that explicitly declares no owner (`drop`) keeps the notice.
- **Library authoring is not carried into the recovery.** Every authenticated Web UI human turn mints a library-authoring grant (`prepareGatewaySkillAuthoring`), and every run binds it at admission. By design (#134068) the grant refuses a replacement run, and the recovery is a new run, so it doesn't inherit the grant. Before this change the recovery failed with "Personal authoring cannot move to a replacement run" instead of answering.
  - Rule: a recovery run never inherits skill-library authoring. Whatever the original grant's target, the recovery gets an expired personal grant. The Workshop tool can't fall back to the workspace tool (`createSkillWorkshopTool`), and every call returns `AUTHORITY_EXPIRED` asking for a fresh message. All other tools stay available, and no access is widened.
  - Alternatives considered:
    - The existing per-run `conversationToolPolicy` replaces the configured group policy instead of adding to it, so using it as a deny list could widen access in group sessions.
    - Minting a fresh grant would relax #134068's replacement-run guard.

Hermes (sibling framework) returns its timeout result through each turn's own reply path on every surface. This PR follows that idea of one reply owner per source. Hermes has no auto-continuation to borrow.

### Group threads: left for a follow-up

Group-thread participant turns keep the notice. Participant reply options set `onQueuedFollowupReplyBatch: undefined` (#141411), which #116649's `in` check turns into a `drop` owner, so every queued participant reply is dropped. Omitting that key makes the recovery reach the group: in a qa-channel run the group got `STALLED-TURN-RECOVERED-OK` instead of the notice. The same run showed a second group message, arriving while the recovery ran, ending `skipped:reply-operation-active` with no reply. Participant reply options also clear `turnAdoptionLifecycle`, so a participant turn on a busy session never reaches queue policy (`allowGatewayQueueResolution` in `dispatch-from-config.lifecycle.ts`). Fixing that needs its own change to participant admission, so this PR doesn't enable group recovery.

## Bounded cost

- **Recovery runs at most once per stalled turn.** `continueStalledTurn` is armed only for direct turns and called once from the aborted-dispatch finisher. The recovery runs on the follow-up runner, which never arms it, so if the recovery also stalls the existing notice is sent and nothing else starts. Tested: "sends the Web UI notice, not a second recovery, when the recovery also stalls" (2 model turns total, empty queue).
- **One delivery per handed-off source.** After `createSourceRetry` from `pending`, the original owner is settled and refuses both delivery and further retries. Tested: "gives a pending source's only delivery to the retry it hands off to".
- **No recovery where its answer would be dropped.** Tested: "leaves the notice with a group-thread participant whose source declares no reply owner".
- **No wider tool access.** Tested: "never lets a personal/workspace-target recovery author skills while keeping its other tools". No tools are disabled.

## Evidence

- **Real Gateway `chat.send`.** A QA Gateway child, mock-openai with the stalled-turn fixture, `QA_DIAGNOSTIC_STUCK_SESSION_ABORT_MS=30000`, and an operator `GatewayClient` (TUI pattern) recording `chat` broadcasts:
  - Before (`f525f46`): `+56.4s state=error "⚠️ This turn was interrupted because it stopped making progress. Please try again."`, then `aborted`. 5 mock requests, none guided.
  - After: `+58.6s aborted` for the stalled run, then `+59.5s state=final` under the recovery's own run id with the recovered answer. 6 mock requests: 5 stalled, 1 guided success. The answer is persisted in `chat.history`.
  - An intermediate run without the authoring change: the recovery was delivered through the new owner but failed with the authoring error. That run is what found the issue.
- **Unit tests:**
  - The two Web UI tests in `agent-runner.stalled-turn.test.ts` fail on `main` (`continueStalledTurn` returned `false`) and pass now.
  - The owner, drop and authoring tests pass.
  - Wall times: `agent-runner.stalled-turn.test.ts` + `followup-delivery.test.ts`: 51 s (75 tests; plus `skill-workshop-tool.test.ts` 19 tests). `chat-send-late-followup.test.ts`: 2 s (6 tests).
- `node scripts/check-changed.mjs` passes (typecheck, lint, guards).
- **Head `c1bca05` (delivery path unchanged since):** the stalled run ends `aborted` at +59.1s, then `state=final` with the recovered answer under the recovery's run id at +60.1s. 6 mock requests, 1 guided. The answer is persisted in `chat.history`.

LOC vs `origin/main`: production +36/−6, tests +130/−5, docs +1/−1.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
…t failed (#162439)

## What Problem This Solves

Fixes: with the default `steer` queue mode, a message sent while the first message's model request is failing replaces the first message. The chat shows `⚠️ <model> request failed.` and then only the answer to the second message. The first question is never retried or answered.

## User Impact

When a model request fails while a newer message is waiting to steer into that turn, OpenClaw retries or falls back for the first message as usual. The newer message then runs as its own turn. Both questions get answered in order. The failure notice only appears if the first message's retries and fallbacks are all exhausted, the same as when nothing was steered.

## Why This Change Was Made

Root cause: after a model request failed, `AgentSession.handlePostAgentRun` still continued the session with the queued steer. The embedded runner owns retries for a failed request (`agent-project-settings.ts` turns session auto-retry off, #73781), so the failed message was never retried. The steered message ran in its place, against a transcript where the failed message looked handled. Per-input answer segments (#149925) then correctly reported the first segment's failure, so the user got `⚠️ request failed` plus the second answer.

Provenance:
- `steer` became the default in `4a6e10ece842` ("feat: default queueing to steer") and #77023, to keep the active turn responsive without starting a second run.
- The post-run `hasQueuedMessages() ? "continue"` came from #109709 so that messages queued by `agent_end` handlers are not stranded. That reason still holds after successful turns. This PR only excludes failed requests, where continuing skips the run owner's retry and fallback.
- Steered channel input already waits for its transcript commit (`agent-runner-steer-adoption.ts`, `waitForTranscriptCommit: true`). When the session settles without committing it, the steer is withdrawn from the runtime queue and the parked reservation falls back to the ordinary follow-up queue. That path runs after the reply operation clears. No new queue or retry logic is added.

Fix: one condition. After a failed request, queued input no longer continues the session (`agent-session-prompting.ts`). Docs: `docs/concepts/queue-steering.md`.

Hermes comparison: Hermes injects a steer only at a role-safe boundary after a tool result. With no tool row yet, or when the request fails, it requeues the steer as the next turn's user message, and each queued message gets its own turn. This change gives OpenClaw the same outcome by reusing its existing follow-up fallback.

Relation to #161069 (stalled-turn recovery): that PR covers turns aborted by stuck-session recovery. This one covers a provider failure while a steer is pending. The two don't overlap.

## Bounded cost

- Fewer model calls: before, a pending steer triggered one extra model call inside the failed run. Now it doesn't.
- The first message keeps its existing retry budget (`MAX_EMPTY_ERROR_RETRIES = 3`, plus the configured fallback chain). Nothing new is retried.
- A handed-back steer is queued at most once. The fallback drops its `steerPending` marker, so it drains as an ordinary follow-up turn and is never steered again. If that turn also fails, it ends with the normal failure notice and is not requeued. The worst case is one follow-up turn per inbound message.
- Tested: the session regression test asserts exactly one model request after the failure, with no continuation. The requeue-once path is existing behavior covered by `src/auto-reply/reply/queue/enqueue.steering.test.ts` (6/6 on this head).

## Evidence

**Telegram Test Server** (`telegram-e2e-userbot`, Convex-leased credential, real QA user in a DM, default queue mode). A deterministic mock provider fails agent-turn requests whose newest question is `17*23` three times (`response.failed` after 8 s). Like the live model in our earlier proof, it answers only the newest user question. The QA user sends `What is 17*23?` at +0.2 s and `Also, what is 19*21?` at +8.2 s, so the second message arrives during the first failing request.

- Before (built head with only this line reverted): the SUT sends `⚠️ openai/gpt-5.5 request failed.` at +13.1 s, then `399` at +14.1 s. The request after the failure carries both questions (`developer,user,user,user`). The first request is never retried, and `391` is never sent.
- After: three failing first-question requests (`[empty-error-retry]` attempts 1/3 to 3/3), none carrying the second question. The fourth request answers `391` at +30.5 s. The second message then runs as its own turn (`developer,user,user,assistant,user,user`) and answers `399` at +31.5 s. No failure notice is sent.

**Unit test:** `agent-session-loop-next-turn.test.ts` "does not answer a steer in place of a failed request". On `main` the steer is committed into the failed turn (`promise resolved instead of rejecting`). With this change there is one request, the steer's commit wait rejects so its caller requeues it, and nothing is left queued. File: 24/24 pass. Related suites pass: `sdk`, `agent-session-loop-correctness`, `attempt-prompt-submit` (+ steering, retention), `attempt-stream-prepare`, `attempt-session-replay` and `provider-review-continuation`, 231 tests.

**Telegram with a live OpenAI model** (same Telegram Test Server DM; a small local proxy in front of the real OpenAI API fails only the first two agent requests that carry 17*23 without 19*21, and forwards everything else to the live model):
- Before (this line reverted in the build): one failing request, then the next request carries both questions and goes to the live model, which answers `399`. The bot sends `⚠️ openai/gpt-6-astra request failed.` (+20.4 s), then `399` (+21.0 s). 17*23 is never answered.
- After: two failing requests for the first question alone, then the live model answers the retry with `391` (+24.1 s). The second message's own turn gets `399` (+26.0 s). No notice.
- Both runs used the fix build, before the branch was rebased onto newer main; the production change is the same. For the before run, only the fix line was reverted.

**Telegram, when the first question fails on every retry and fallback** (same harness; the mock fails every agent request whose newest question is 17*23, and the agent has a fallback model configured): 8 requests for the first question, 4 on `gpt-5.5` and 4 on `gpt-5.5-fallback`. None of them carries the second question. The model-fallback log shows `gpt-5.5` failing over to `gpt-5.5-fallback`, then nothing left to try. The SUT sends exactly two messages: one `⚠️ openai/gpt-5.5-fallback request failed.` at +70.9 s, then `399` at +71.9 s from the second message's own turn. No other notices.

**Web UI `chat.send` (real Gateway, operator WebSocket client of the kind the TUI uses, same mock):** the client sends `What is 17*23?`, then `Also, what is 19*21?` 8 s later, during the first failing request.
- Before (this line reverted in the build): the client's only answer is `399`. The request after the failure carries both questions (`developer,user,user,user`). `chat.history` ends `user 17*23, user 19*21, assistant 399`, so the first question is unanswered.
- After: the steer is withdrawn when the failed attempt settles. Its `chat.send` run closes with an empty final (+17.1 s), and `chat-send-agent-dispatch.ts` dispatches it again; it runs as a follow-up and is not steered into the retry. The first run retries three times, with no retried request carrying the second question, and answers `391` (+33.7 s). The second message's own run answers `399` (+34.0 s). `chat.history`: `user 17*23, assistant 391, user 19*21, assistant 399`.

Why a withdrawn Web UI steer can't be re-steered into the retry: with explicit `queueMode: "steer"`, chat.send's fallback dispatch passes `messageInjectionDisposition: "rejected"` (`src/gateway/server-methods/chat-send-agent-dispatch.ts:388-390`). `runReplyAgent` steers only when the disposition is `"none"` (`src/auto-reply/reply/agent-runner-run.ts:341-346`), so the message is queued as a follow-up instead (`:389`). With the default mode, chat.send makes no injection attempt of its own (`chat-send-admission.ts:272-275`) and the message takes the channel path: its parked reservation falls back with its steer marker removed (`queue/enqueue.ts:307-318`), and the queue drains only after the reply operation clears (`agent-runner-steer-adoption.ts:110-122`).

**Wall times** (`pnpm test <file>`, shared, heavily loaded host):
- `agent-session-loop-next-turn.test.ts`: 24/24, 121 s wall (vitest 106 s). The new test signals request start and steer acceptance with deferreds; it no longer polls.
- `enqueue.steering`: 6/6, 78 s.
- `attempt.queue-message`: 16/16, 98 s.
- `agent-session-handoff-adoption.integration`: 1/1, 63 s.
- `agent-runner-steer-adoption.question-recovery`: 25/25, 97 s.
- `chat-send-steering-custody`: 17/17, 90 s.
- `agent-runner.runreplyagent.e2e`: 223/224 under load. The one failure, "keeps the replacement source when retired admission completes", passes alone (60 s wall). That file mocks the embedded agent, so it never reaches the changed session code.

qa-lab note: the qa-channel serializes inbound per account, so the same-sender steer couldn't be reproduced there. The proof uses the Telegram Test Server instead.

LOC vs `origin/main`: production +3/−1, test +46, docs +1 (changed line).

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
…retry notice (#162756)

## What Problem This Solves

Fixes: when a chat turn has already answered through the message tool and then stalls on a later model request, stuck-session recovery treats it as unanswered. It starts a recovery turn, which posts a second, redundant answer, or, if that also stalls, the "Please try again" notice.

## User Impact

After a turn's final message-tool answer reaches the chat, a later stall stays quiet: no recovery turn, no second message, no retry notice. Progress messages (`final: false`) don't count as an answer, so a turn that only said "working on it" still recovers as before. In message-tool-only mode (Slack quiet mode), where every visible reply is a message-tool send, this keeps a stall after the answer from posting the last-resort notice, which bypasses quiet-mode suppression.

## Why This Change Was Made

#161069 decides between recovery and the notice with `isReplyOperationStalledBeforeOutput(operation)`, which checked only the stall reason. An adversarial review of #161069 found that this ignores source delivery that already happened.

The run result does carry the delivery evidence, but dispatch makes the notice/recovery decision as soon as the watchdog expires the reply operation, before the aborted run returns its result. A live run confirmed that ordering (`cause=skipped:reply_operation_aborted` before the fallback chain settles).

So the reply operation, which owns the turn's lifecycle, now owns the fact as well. A successful final message-tool send to the turn's exact source (the existing `messageDelivery.sourceReplyDelivered` condition: settled, not partial, not dry-run, `final` not `false`, current source) marks the active operation `sourceReplyDelivered`. The single predicate reads it, so dispatch, follow-up delivery and any future caller share one rule.

A user message steered into the same operation after that answer reopens it. Steer acceptance has one owner on the operation (`markSteeredInputAccepted`, which replaces the audio-only `markAcceptedSteeredInboundAudio` from #95596; its audio flag is unchanged). It clears the fact, so the newer request still recovers if the turn then stalls.

Hermes (sibling framework) keeps one per-turn reply owner and never re-answers after a delivered reply. Its inactivity timeout only reports through that owner.

## Bounded cost

This only removes work. No new model calls, runs or messages. A stalled turn that already answered starts no recovery turn (one model run fewer). Recovery stays at most once per stalled turn on every surface, unchanged.

## Evidence

- **Telegram Test Server, live model.** `telegram-e2e-userbot` skill, Convex-leased credential, real QA user in a DM, `openai/gpt-6-astra` through a proof-only local proxy in front of the real OpenAI API, QA stuck-session bound 30 s. A live model can't be made to stall, so the proxy holds open the first model request that follows a completed `message` tool call. Everything else reaches the live API unchanged. The QA user sends: "Use the message tool to send me the answer to 17*23 as just the number. After that message is sent, you are done: send nothing else."
  - **Before (`origin/main` d06974d):** the model sends `391` through the message tool. The next request is held, and stuck recovery aborts the turn at age 47 s. A recovery request carrying the stall guidance then goes to the live model, and the chat gets a second message, "Already sent: 391.". SUT messages: `391`, `Already sent: 391.`
  - **After (exact head `50a09f1`):** the model sends `391` through the message tool, the next request is held, and stuck recovery aborts the turn at age 49 s. There's no recovery request, and the chat shows only `391`. No second message and no notice. The earlier run on `fe6eed9` matched it: same `391` send, held request, and stuck abort (age 48 s). There's no recovery request, and the chat shows only `391`. No second message and no notice.
  - Both runs also show the existing "Working" progress row, which is unchanged.
  - **Second message during the stall (exact head `50a09f1`):** the scenario sends the 17*23 request, then "Also, what is 19*21? Reply with just the number." 30 s later, while the post-answer request is held.
    - Live, the second message was queued as its own turn rather than steered (`queueDepth=1`), because the active run doesn't take steering after its answer.
    - The first turn's stall (age 75 s) started no recovery. The queued turn then ran and stalled too (age 58 s), and its recovery answered it.
    - Chat: `391`, then `399`. One guided recovery request, for the unanswered second message only.
    - The steered-into-the-same-operation variant isn't reachable in this flow, so it's covered by the real `runReplyAgent` steer test.
- **Regression tests:**
  - `dispatch-from-config.terminal-recovery.test.ts`: a new case marks the active operation answered, then lets the watchdog expire it while the run is still pending, which is the real order. It expects no notice and no continuation. It fails on `main`.
  - `message-tool-execution.test.ts`: the existing eligibility table now also asserts that only an eligible final source send marks the operation. Failures, partial sends, dry runs, `final: false` and other targets don't mark it.
  - The same table has a case where an answer is followed by a steered input. It expects one continuation.
  - `agent-runner.media-paths.test.ts`: the real steer path through `runReplyAgent` clears an earlier answer.
  - Focused suites pass, including `reply-run-registry`, `dispatch-from-config` and `message-tool-execution`.
- One-worker wall times (`pnpm test <file> --maxWorkers=1`, real / Vitest duration): `dispatch-from-config.terminal-recovery.test.ts` 27 s / 23.8 s (27 tests); `message-tool-execution.test.ts` 23 s / 20.3 s (76 tests); `agent-runner.media-paths.test.ts` 27 s / 23.3 s (21 tests). Transform dominates (75–80%); each is under 30 s.
- `node scripts/check-changed.mjs` passes.

LOC vs `origin/main`: production +25/−7, tests +33/−6.

No new user-visible messages. This only removes a redundant answer and an incorrect notice.

No overlap with Pash/Sarah changes on the touched files.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
## What Problem This Solves

Fixes: when a Web UI (`chat.send`) turn stalls, and the automatic recovery from #162490 also stalls, the user gets neither an answer nor the "stopped making progress" notice. The chat just shows the run as aborted.

## User Impact

In that double-stall case, Web UI users see the same "⚠️ This turn was interrupted because it stopped making progress. Please try again." error they got before #162490. A user's own cancel stays silent, and channel delivery is unchanged.

## Why This Change Was Made

#161069 and #162490 promise one last-resort notice if the recovery run also stalls. `followup-delivery.ts` builds that notice payload. The follow-up runner, though, reported the watchdog-aborted run to its source owner as `completion: aborted`, the same as a user cancel. The `chat.send` finalizer (`chat-send-source-finalization.ts`) correctly hides final payloads for aborted runs and emits a bare `aborted` event, so the notice was dropped. The #162490 test missed this because it mocked the finalizer as "delivered".

The follow-up runner owns the completion it reports, so the fix is there. A stall-recovery run whose operation the watchdog stalled before any output now completes as `failed`, with the notice as its error. The Gateway already sends that through its terminal error contract (`state: "error"`), the same way the original stalled turn did before #162490. Other aborted follow-ups, including user cancels (`aborted_by_user`), still classify as `aborted` and stay silent. This change adds no new message: it restores the existing notice on the one surface that lost it.

Hermes (sibling framework) handles an inactivity timeout the same way: it returns a failed run result with diagnostic text through the turn's own reply path, never a silent cancel.

## Bounded cost

No new model calls or runs. This only changes how an already-finished recovery run is classified. Recovery still happens at most once per stalled turn; the existing test covers this (2 model turns, empty queue).

## Evidence

- `agent-runner.stalled-turn.test.ts` "sends the Web UI notice, not a second recovery, when the recovery also stalls" now drives the real `createChatSendLateReplyFinalizer`, with a real Gateway request context, and asserts the `chat` event it broadcasts.
  - On `main` it fails: `state: "aborted"`, no notice.
  - With the fix it passes: one `state: "error"` event whose `errorMessage` is the notice.
- **Live model, real Gateway `chat.send` client.** A local proxy sits in front of the real OpenAI API (`gpt-6-astra`), and an operator WebSocket client (the TUI's `GatewayClient`) sends "What is 17*23? Reply with just the number." and records the `chat` events. A live model can't be made to stall, so the proxy reproduces the stall shape for the question's requests (4 failing requests, then held open until the abort) for both the original turn and its recovery. QA stuck-session bound: 30 s.
  - **Before (`origin/main` d06974d):** two stuck aborts (ages 48 s and 59 s). The client receives `aborted` for the original run at +56.7 s, then `aborted` for the recovery run at +116.8 s. No notice and no answer.
  - **After (head `823a966`):** same two stuck aborts (ages 49 s and 59 s). The client receives `aborted` for the original run at +56.7 s, then `state: "error"` with "⚠️ This turn was interrupted because it stopped making progress. Please try again." for the recovery run at +116.7 s.
  - Telegram isn't affected: channel follow-ups route the notice payload directly, and this change only alters the completion reported to a source owner.
- Wall time: `pnpm test src/auto-reply/reply/agent-runner.stalled-turn.test.ts --maxWorkers=1` takes 39.6 s real, 36.0 s Vitest duration (60% transform, 30% tests) for 12 tests. The file's whole suite runs the real `runReplyAgent` with a SQLite transcript. This defect only shows at the boundary between the follow-up runner's completion and the chat.send finalizer, so a cheaper unit test of either side alone (the old mocked finalizer) missed it.
- Sibling suites pass: `followup-runner`, `followup-delivery`, `chat-send-late-followup`, and `server.chat-queued-followup` (real Gateway WebSocket), 104 tests.
- `node scripts/check-changed.mjs` passes.

Optional cleanup of the expired-personal-grant stub was skipped; it would grow the diff.

No new user-visible messages: this restores the existing notice on the one surface that lost it, and user cancels stay silent.

LOC vs `origin/main`: production +11/−1, tests +26/−10.

No overlap with Pash/Sarah changes on the touched files.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
## What Problem This Solves

Fixes: Web UI (`chat.send`) turns that stall before replying still end with "⚠️ This turn was interrupted because it stopped making progress. Please try again." instead of the automatic recovery that channel DMs get since openclaw#161069.

## User Impact

- When a Web UI turn stalls before replying, the user now gets the recovered answer instead of the retry notice. The stalled run ends as aborted, and the answer arrives as its own run in the same chat, the same way any queued Web UI follow-up arrives. If the recovery also stalls, the existing notice is sent once.
- The recovery keeps its normal tools, except that Skill Workshop can't write to the skill library during a recovery. It answers "send a fresh message" instead.
- Group-thread participant turns keep the notice. That is now the only exception, and it's stated in the docs.

## Why This Change Was Made

openclaw#161069 kept the notice for Web UI turns because the recovery run had no owner that would deliver its answer ([maintainer decision](openclaw#161069 (comment))). Provenance of that owner:

- openclaw#116649 binds every queued `chat.send` reply to its originating Gateway admission, so a late answer never goes out through a later same-session dispatcher.
- openclaw#129001 added `createSourceRetry`, which gives a front-requeued run of the same source a fresh owner, and the `pending` state: a source that never handed its request to the queue keeps its own terminal, so a finished run gets no duplicate or late reply.
- The recovery run inherited the stalled turn's still-`pending` owner, so its answer was dropped (`terminal-not-recorded`).

The fix:

- **The stalled turn hands its request to the recovery through the source's existing `createSourceRetry`.** A `pending` source that hands off is settled, so the original can never deliver once the retry exists, and the recovery owns the only delivery. The relaxed `pending` case is reachable only through the stall continuation, which runs after the stale watchdog aborted the source before any output. `createSourceRetry` has two callers:
  - the follow-up source retry in `followup-delivery.ts`, which only sees owners that already queued (`deliver`/`drop`);
  - the stall continuation.
- **The openclaw#161069 early return is narrowed.** Only a source that explicitly declares no owner (`drop`) keeps the notice.
- **Library authoring is not carried into the recovery.** Every authenticated Web UI human turn mints a library-authoring grant (`prepareGatewaySkillAuthoring`), and every run binds it at admission. By design (openclaw#134068) the grant refuses a replacement run, and the recovery is a new run, so it doesn't inherit the grant. Before this change the recovery failed with "Personal authoring cannot move to a replacement run" instead of answering.
  - Rule: a recovery run never inherits skill-library authoring. Whatever the original grant's target, the recovery gets an expired personal grant. The Workshop tool can't fall back to the workspace tool (`createSkillWorkshopTool`), and every call returns `AUTHORITY_EXPIRED` asking for a fresh message. All other tools stay available, and no access is widened.
  - Alternatives considered:
    - The existing per-run `conversationToolPolicy` replaces the configured group policy instead of adding to it, so using it as a deny list could widen access in group sessions.
    - Minting a fresh grant would relax openclaw#134068's replacement-run guard.

Hermes (sibling framework) returns its timeout result through each turn's own reply path on every surface. This PR follows that idea of one reply owner per source. Hermes has no auto-continuation to borrow.

### Group threads: left for a follow-up

Group-thread participant turns keep the notice. Participant reply options set `onQueuedFollowupReplyBatch: undefined` (openclaw#141411), which openclaw#116649's `in` check turns into a `drop` owner, so every queued participant reply is dropped. Omitting that key makes the recovery reach the group: in a qa-channel run the group got `STALLED-TURN-RECOVERED-OK` instead of the notice. The same run showed a second group message, arriving while the recovery ran, ending `skipped:reply-operation-active` with no reply. Participant reply options also clear `turnAdoptionLifecycle`, so a participant turn on a busy session never reaches queue policy (`allowGatewayQueueResolution` in `dispatch-from-config.lifecycle.ts`). Fixing that needs its own change to participant admission, so this PR doesn't enable group recovery.

## Bounded cost

- **Recovery runs at most once per stalled turn.** `continueStalledTurn` is armed only for direct turns and called once from the aborted-dispatch finisher. The recovery runs on the follow-up runner, which never arms it, so if the recovery also stalls the existing notice is sent and nothing else starts. Tested: "sends the Web UI notice, not a second recovery, when the recovery also stalls" (2 model turns total, empty queue).
- **One delivery per handed-off source.** After `createSourceRetry` from `pending`, the original owner is settled and refuses both delivery and further retries. Tested: "gives a pending source's only delivery to the retry it hands off to".
- **No recovery where its answer would be dropped.** Tested: "leaves the notice with a group-thread participant whose source declares no reply owner".
- **No wider tool access.** Tested: "never lets a personal/workspace-target recovery author skills while keeping its other tools". No tools are disabled.

## Evidence

- **Real Gateway `chat.send`.** A QA Gateway child, mock-openai with the stalled-turn fixture, `QA_DIAGNOSTIC_STUCK_SESSION_ABORT_MS=30000`, and an operator `GatewayClient` (TUI pattern) recording `chat` broadcasts:
  - Before (`80290b4`): `+56.4s state=error "⚠️ This turn was interrupted because it stopped making progress. Please try again."`, then `aborted`. 5 mock requests, none guided.
  - After: `+58.6s aborted` for the stalled run, then `+59.5s state=final` under the recovery's own run id with the recovered answer. 6 mock requests: 5 stalled, 1 guided success. The answer is persisted in `chat.history`.
  - An intermediate run without the authoring change: the recovery was delivered through the new owner but failed with the authoring error. That run is what found the issue.
- **Unit tests:**
  - The two Web UI tests in `agent-runner.stalled-turn.test.ts` fail on `main` (`continueStalledTurn` returned `false`) and pass now.
  - The owner, drop and authoring tests pass.
  - Wall times: `agent-runner.stalled-turn.test.ts` + `followup-delivery.test.ts`: 51 s (75 tests; plus `skill-workshop-tool.test.ts` 19 tests). `chat-send-late-followup.test.ts`: 2 s (6 tests).
- `node scripts/check-changed.mjs` passes (typecheck, lint, guards).
- **Head `c1bca05` (delivery path unchanged since):** the stalled run ends `aborted` at +59.1s, then `state=final` with the recovered answer under the recovery's run id at +60.1s. 6 mock requests, 1 guided. The answer is persisted in `chat.history`.

LOC vs `origin/main`: production +36/−6, tests +130/−5, docs +1/−1.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…t failed (openclaw#162439)

## What Problem This Solves

Fixes: with the default `steer` queue mode, a message sent while the first message's model request is failing replaces the first message. The chat shows `⚠️ <model> request failed.` and then only the answer to the second message. The first question is never retried or answered.

## User Impact

When a model request fails while a newer message is waiting to steer into that turn, OpenClaw retries or falls back for the first message as usual. The newer message then runs as its own turn. Both questions get answered in order. The failure notice only appears if the first message's retries and fallbacks are all exhausted, the same as when nothing was steered.

## Why This Change Was Made

Root cause: after a model request failed, `AgentSession.handlePostAgentRun` still continued the session with the queued steer. The embedded runner owns retries for a failed request (`agent-project-settings.ts` turns session auto-retry off, openclaw#73781), so the failed message was never retried. The steered message ran in its place, against a transcript where the failed message looked handled. Per-input answer segments (openclaw#149925) then correctly reported the first segment's failure, so the user got `⚠️ request failed` plus the second answer.

Provenance:
- `steer` became the default in `6ba8981e46cd` ("feat: default queueing to steer") and openclaw#77023, to keep the active turn responsive without starting a second run.
- The post-run `hasQueuedMessages() ? "continue"` came from openclaw#109709 so that messages queued by `agent_end` handlers are not stranded. That reason still holds after successful turns. This PR only excludes failed requests, where continuing skips the run owner's retry and fallback.
- Steered channel input already waits for its transcript commit (`agent-runner-steer-adoption.ts`, `waitForTranscriptCommit: true`). When the session settles without committing it, the steer is withdrawn from the runtime queue and the parked reservation falls back to the ordinary follow-up queue. That path runs after the reply operation clears. No new queue or retry logic is added.

Fix: one condition. After a failed request, queued input no longer continues the session (`agent-session-prompting.ts`). Docs: `docs/concepts/queue-steering.md`.

Hermes comparison: Hermes injects a steer only at a role-safe boundary after a tool result. With no tool row yet, or when the request fails, it requeues the steer as the next turn's user message, and each queued message gets its own turn. This change gives OpenClaw the same outcome by reusing its existing follow-up fallback.

Relation to openclaw#161069 (stalled-turn recovery): that PR covers turns aborted by stuck-session recovery. This one covers a provider failure while a steer is pending. The two don't overlap.

## Bounded cost

- Fewer model calls: before, a pending steer triggered one extra model call inside the failed run. Now it doesn't.
- The first message keeps its existing retry budget (`MAX_EMPTY_ERROR_RETRIES = 3`, plus the configured fallback chain). Nothing new is retried.
- A handed-back steer is queued at most once. The fallback drops its `steerPending` marker, so it drains as an ordinary follow-up turn and is never steered again. If that turn also fails, it ends with the normal failure notice and is not requeued. The worst case is one follow-up turn per inbound message.
- Tested: the session regression test asserts exactly one model request after the failure, with no continuation. The requeue-once path is existing behavior covered by `src/auto-reply/reply/queue/enqueue.steering.test.ts` (6/6 on this head).

## Evidence

**Telegram Test Server** (`telegram-e2e-userbot`, Convex-leased credential, real QA user in a DM, default queue mode). A deterministic mock provider fails agent-turn requests whose newest question is `17*23` three times (`response.failed` after 8 s). Like the live model in our earlier proof, it answers only the newest user question. The QA user sends `What is 17*23?` at +0.2 s and `Also, what is 19*21?` at +8.2 s, so the second message arrives during the first failing request.

- Before (built head with only this line reverted): the SUT sends `⚠️ openai/gpt-5.5 request failed.` at +13.1 s, then `399` at +14.1 s. The request after the failure carries both questions (`developer,user,user,user`). The first request is never retried, and `391` is never sent.
- After: three failing first-question requests (`[empty-error-retry]` attempts 1/3 to 3/3), none carrying the second question. The fourth request answers `391` at +30.5 s. The second message then runs as its own turn (`developer,user,user,assistant,user,user`) and answers `399` at +31.5 s. No failure notice is sent.

**Unit test:** `agent-session-loop-next-turn.test.ts` "does not answer a steer in place of a failed request". On `main` the steer is committed into the failed turn (`promise resolved instead of rejecting`). With this change there is one request, the steer's commit wait rejects so its caller requeues it, and nothing is left queued. File: 24/24 pass. Related suites pass: `sdk`, `agent-session-loop-correctness`, `attempt-prompt-submit` (+ steering, retention), `attempt-stream-prepare`, `attempt-session-replay` and `provider-review-continuation`, 231 tests.

**Telegram with a live OpenAI model** (same Telegram Test Server DM; a small local proxy in front of the real OpenAI API fails only the first two agent requests that carry 17*23 without 19*21, and forwards everything else to the live model):
- Before (this line reverted in the build): one failing request, then the next request carries both questions and goes to the live model, which answers `399`. The bot sends `⚠️ openai/gpt-6-astra request failed.` (+20.4 s), then `399` (+21.0 s). 17*23 is never answered.
- After: two failing requests for the first question alone, then the live model answers the retry with `391` (+24.1 s). The second message's own turn gets `399` (+26.0 s). No notice.
- Both runs used the fix build, before the branch was rebased onto newer main; the production change is the same. For the before run, only the fix line was reverted.

**Telegram, when the first question fails on every retry and fallback** (same harness; the mock fails every agent request whose newest question is 17*23, and the agent has a fallback model configured): 8 requests for the first question, 4 on `gpt-5.5` and 4 on `gpt-5.5-fallback`. None of them carries the second question. The model-fallback log shows `gpt-5.5` failing over to `gpt-5.5-fallback`, then nothing left to try. The SUT sends exactly two messages: one `⚠️ openai/gpt-5.5-fallback request failed.` at +70.9 s, then `399` at +71.9 s from the second message's own turn. No other notices.

**Web UI `chat.send` (real Gateway, operator WebSocket client of the kind the TUI uses, same mock):** the client sends `What is 17*23?`, then `Also, what is 19*21?` 8 s later, during the first failing request.
- Before (this line reverted in the build): the client's only answer is `399`. The request after the failure carries both questions (`developer,user,user,user`). `chat.history` ends `user 17*23, user 19*21, assistant 399`, so the first question is unanswered.
- After: the steer is withdrawn when the failed attempt settles. Its `chat.send` run closes with an empty final (+17.1 s), and `chat-send-agent-dispatch.ts` dispatches it again; it runs as a follow-up and is not steered into the retry. The first run retries three times, with no retried request carrying the second question, and answers `391` (+33.7 s). The second message's own run answers `399` (+34.0 s). `chat.history`: `user 17*23, assistant 391, user 19*21, assistant 399`.

Why a withdrawn Web UI steer can't be re-steered into the retry: with explicit `queueMode: "steer"`, chat.send's fallback dispatch passes `messageInjectionDisposition: "rejected"` (`src/gateway/server-methods/chat-send-agent-dispatch.ts:388-390`). `runReplyAgent` steers only when the disposition is `"none"` (`src/auto-reply/reply/agent-runner-run.ts:341-346`), so the message is queued as a follow-up instead (`:389`). With the default mode, chat.send makes no injection attempt of its own (`chat-send-admission.ts:272-275`) and the message takes the channel path: its parked reservation falls back with its steer marker removed (`queue/enqueue.ts:307-318`), and the queue drains only after the reply operation clears (`agent-runner-steer-adoption.ts:110-122`).

**Wall times** (`pnpm test <file>`, shared, heavily loaded host):
- `agent-session-loop-next-turn.test.ts`: 24/24, 121 s wall (vitest 106 s). The new test signals request start and steer acceptance with deferreds; it no longer polls.
- `enqueue.steering`: 6/6, 78 s.
- `attempt.queue-message`: 16/16, 98 s.
- `agent-session-handoff-adoption.integration`: 1/1, 63 s.
- `agent-runner-steer-adoption.question-recovery`: 25/25, 97 s.
- `chat-send-steering-custody`: 17/17, 90 s.
- `agent-runner.runreplyagent.e2e`: 223/224 under load. The one failure, "keeps the replacement source when retired admission completes", passes alone (60 s wall). That file mocks the embedded agent, so it never reaches the changed session code.

qa-lab note: the qa-channel serializes inbound per account, so the same-sender steer couldn't be reproduced there. The proof uses the Telegram Test Server instead.

LOC vs `origin/main`: production +3/−1, test +46, docs +1 (changed line).

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…retry notice (openclaw#162756)

## What Problem This Solves

Fixes: when a chat turn has already answered through the message tool and then stalls on a later model request, stuck-session recovery treats it as unanswered. It starts a recovery turn, which posts a second, redundant answer, or, if that also stalls, the "Please try again" notice.

## User Impact

After a turn's final message-tool answer reaches the chat, a later stall stays quiet: no recovery turn, no second message, no retry notice. Progress messages (`final: false`) don't count as an answer, so a turn that only said "working on it" still recovers as before. In message-tool-only mode (Slack quiet mode), where every visible reply is a message-tool send, this keeps a stall after the answer from posting the last-resort notice, which bypasses quiet-mode suppression.

## Why This Change Was Made

openclaw#161069 decides between recovery and the notice with `isReplyOperationStalledBeforeOutput(operation)`, which checked only the stall reason. An adversarial review of openclaw#161069 found that this ignores source delivery that already happened.

The run result does carry the delivery evidence, but dispatch makes the notice/recovery decision as soon as the watchdog expires the reply operation, before the aborted run returns its result. A live run confirmed that ordering (`cause=skipped:reply_operation_aborted` before the fallback chain settles).

So the reply operation, which owns the turn's lifecycle, now owns the fact as well. A successful final message-tool send to the turn's exact source (the existing `messageDelivery.sourceReplyDelivered` condition: settled, not partial, not dry-run, `final` not `false`, current source) marks the active operation `sourceReplyDelivered`. The single predicate reads it, so dispatch, follow-up delivery and any future caller share one rule.

A user message steered into the same operation after that answer reopens it. Steer acceptance has one owner on the operation (`markSteeredInputAccepted`, which replaces the audio-only `markAcceptedSteeredInboundAudio` from openclaw#95596; its audio flag is unchanged). It clears the fact, so the newer request still recovers if the turn then stalls.

Hermes (sibling framework) keeps one per-turn reply owner and never re-answers after a delivered reply. Its inactivity timeout only reports through that owner.

## Bounded cost

This only removes work. No new model calls, runs or messages. A stalled turn that already answered starts no recovery turn (one model run fewer). Recovery stays at most once per stalled turn on every surface, unchanged.

## Evidence

- **Telegram Test Server, live model.** `telegram-e2e-userbot` skill, Convex-leased credential, real QA user in a DM, `openai/gpt-6-astra` through a proof-only local proxy in front of the real OpenAI API, QA stuck-session bound 30 s. A live model can't be made to stall, so the proxy holds open the first model request that follows a completed `message` tool call. Everything else reaches the live API unchanged. The QA user sends: "Use the message tool to send me the answer to 17*23 as just the number. After that message is sent, you are done: send nothing else."
  - **Before (`origin/main` 02f46a6):** the model sends `391` through the message tool. The next request is held, and stuck recovery aborts the turn at age 47 s. A recovery request carrying the stall guidance then goes to the live model, and the chat gets a second message, "Already sent: 391.". SUT messages: `391`, `Already sent: 391.`
  - **After (exact head `50a09f1`):** the model sends `391` through the message tool, the next request is held, and stuck recovery aborts the turn at age 49 s. There's no recovery request, and the chat shows only `391`. No second message and no notice. The earlier run on `fe6eed9` matched it: same `391` send, held request, and stuck abort (age 48 s). There's no recovery request, and the chat shows only `391`. No second message and no notice.
  - Both runs also show the existing "Working" progress row, which is unchanged.
  - **Second message during the stall (exact head `50a09f1`):** the scenario sends the 17*23 request, then "Also, what is 19*21? Reply with just the number." 30 s later, while the post-answer request is held.
    - Live, the second message was queued as its own turn rather than steered (`queueDepth=1`), because the active run doesn't take steering after its answer.
    - The first turn's stall (age 75 s) started no recovery. The queued turn then ran and stalled too (age 58 s), and its recovery answered it.
    - Chat: `391`, then `399`. One guided recovery request, for the unanswered second message only.
    - The steered-into-the-same-operation variant isn't reachable in this flow, so it's covered by the real `runReplyAgent` steer test.
- **Regression tests:**
  - `dispatch-from-config.terminal-recovery.test.ts`: a new case marks the active operation answered, then lets the watchdog expire it while the run is still pending, which is the real order. It expects no notice and no continuation. It fails on `main`.
  - `message-tool-execution.test.ts`: the existing eligibility table now also asserts that only an eligible final source send marks the operation. Failures, partial sends, dry runs, `final: false` and other targets don't mark it.
  - The same table has a case where an answer is followed by a steered input. It expects one continuation.
  - `agent-runner.media-paths.test.ts`: the real steer path through `runReplyAgent` clears an earlier answer.
  - Focused suites pass, including `reply-run-registry`, `dispatch-from-config` and `message-tool-execution`.
- One-worker wall times (`pnpm test <file> --maxWorkers=1`, real / Vitest duration): `dispatch-from-config.terminal-recovery.test.ts` 27 s / 23.8 s (27 tests); `message-tool-execution.test.ts` 23 s / 20.3 s (76 tests); `agent-runner.media-paths.test.ts` 27 s / 23.3 s (21 tests). Transform dominates (75–80%); each is under 30 s.
- `node scripts/check-changed.mjs` passes.

LOC vs `origin/main`: production +25/−7, tests +33/−6.

No new user-visible messages. This only removes a redundant answer and an incorrect notice.

No overlap with Pash/Sarah changes on the touched files.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…#162713)

## What Problem This Solves

Fixes: when a Web UI (`chat.send`) turn stalls, and the automatic recovery from openclaw#162490 also stalls, the user gets neither an answer nor the "stopped making progress" notice. The chat just shows the run as aborted.

## User Impact

In that double-stall case, Web UI users see the same "⚠️ This turn was interrupted because it stopped making progress. Please try again." error they got before openclaw#162490. A user's own cancel stays silent, and channel delivery is unchanged.

## Why This Change Was Made

openclaw#161069 and openclaw#162490 promise one last-resort notice if the recovery run also stalls. `followup-delivery.ts` builds that notice payload. The follow-up runner, though, reported the watchdog-aborted run to its source owner as `completion: aborted`, the same as a user cancel. The `chat.send` finalizer (`chat-send-source-finalization.ts`) correctly hides final payloads for aborted runs and emits a bare `aborted` event, so the notice was dropped. The openclaw#162490 test missed this because it mocked the finalizer as "delivered".

The follow-up runner owns the completion it reports, so the fix is there. A stall-recovery run whose operation the watchdog stalled before any output now completes as `failed`, with the notice as its error. The Gateway already sends that through its terminal error contract (`state: "error"`), the same way the original stalled turn did before openclaw#162490. Other aborted follow-ups, including user cancels (`aborted_by_user`), still classify as `aborted` and stay silent. This change adds no new message: it restores the existing notice on the one surface that lost it.

Hermes (sibling framework) handles an inactivity timeout the same way: it returns a failed run result with diagnostic text through the turn's own reply path, never a silent cancel.

## Bounded cost

No new model calls or runs. This only changes how an already-finished recovery run is classified. Recovery still happens at most once per stalled turn; the existing test covers this (2 model turns, empty queue).

## Evidence

- `agent-runner.stalled-turn.test.ts` "sends the Web UI notice, not a second recovery, when the recovery also stalls" now drives the real `createChatSendLateReplyFinalizer`, with a real Gateway request context, and asserts the `chat` event it broadcasts.
  - On `main` it fails: `state: "aborted"`, no notice.
  - With the fix it passes: one `state: "error"` event whose `errorMessage` is the notice.
- **Live model, real Gateway `chat.send` client.** A local proxy sits in front of the real OpenAI API (`gpt-6-astra`), and an operator WebSocket client (the TUI's `GatewayClient`) sends "What is 17*23? Reply with just the number." and records the `chat` events. A live model can't be made to stall, so the proxy reproduces the stall shape for the question's requests (4 failing requests, then held open until the abort) for both the original turn and its recovery. QA stuck-session bound: 30 s.
  - **Before (`origin/main` 02f46a6):** two stuck aborts (ages 48 s and 59 s). The client receives `aborted` for the original run at +56.7 s, then `aborted` for the recovery run at +116.8 s. No notice and no answer.
  - **After (head `823a966`):** same two stuck aborts (ages 49 s and 59 s). The client receives `aborted` for the original run at +56.7 s, then `state: "error"` with "⚠️ This turn was interrupted because it stopped making progress. Please try again." for the recovery run at +116.7 s.
  - Telegram isn't affected: channel follow-ups route the notice payload directly, and this change only alters the completion reported to a source owner.
- Wall time: `pnpm test src/auto-reply/reply/agent-runner.stalled-turn.test.ts --maxWorkers=1` takes 39.6 s real, 36.0 s Vitest duration (60% transform, 30% tests) for 12 tests. The file's whole suite runs the real `runReplyAgent` with a SQLite transcript. This defect only shows at the boundary between the follow-up runner's completion and the chat.send finalizer, so a cheaper unit test of either side alone (the old mocked finalizer) missed it.
- Sibling suites pass: `followup-runner`, `followup-delivery`, `chat-send-late-followup`, and `server.chat-queued-followup` (real Gateway WebSocket), 104 tests.
- `node scripts/check-changed.mjs` passes.

Optional cleanup of the expired-personal-grant stub was skipped; it would grow the diff.

No new user-visible messages: this restores the existing notice on the one surface that lost it, and user cancels stay silent.

LOC vs `origin/main`: production +11/−1, tests +26/−10.

No overlap with Pash/Sarah changes on the touched files.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Oct 2, 2026
* fix: preserve plugin settings through update recovery (#160344)

Keep incompatible local plugin configuration intact and complete deferred migration confirmation after unchanged package convergence. Use completion receipts to clear obsolete retry warnings without rewriting update history.

Fixes #159477. Thanks @EndeavorPioneer for the recovery report.

(cherry picked from commit 8e66b0b6c8d1e8022f3f1ebaee532f405897549d)

* fix: prevent duplicate Gateways during container onboarding (#160193)

* fix: prevent duplicate Gateways during container onboarding

* fix: keep QA cron controls scoped to the child

Drop inherited parent cron suppression while preserving explicit child runtime
settings. Cover the failing inheritance contract at the environment owner.

Await node-list RPC responses after acknowledged rename and reconnect events
without racing the existing RPC deadline against a separate polling timeout.

(cherry picked from commit 54b1b1b63e2149074cd5e0a965834afd31d172df)

* fix: deeply nested MCP tool results crash result projection (#160825)

Handle deeply nested MCP structuredContent as an actionable tool error instead of letting a serialization RangeError escape result projection. Preserve server content and report the same failure to Code Mode guest callers, without retaining the unprojectable value for downstream serialization.

Preserves ordinary shallow results and adds focused regression coverage.

Co-authored-by: wangmiao0668000666 <[email protected]>
Co-authored-by: Tak Hoffman <[email protected]>
Co-authored-by: Takhoffman <[email protected]>
(cherry picked from commit 452c808d5b1bab8bfb2f929035db422e6f71acf3)

* feat(openai): support GPT-6.1 Sol (#161400)

* feat(openai): support GPT-6.1 Sol

Co-authored-by: steipete <[email protected]>

* feat(openai): support GPT-6.1 Sol

Worked on by:
- @steipete

Co-authored-by: steipete <[email protected]>
OpenClaw-Publication: 970e2aab-1efa-4534-be78-7b6ec08717b5

* fix(openai): preserve GPT-6.1 Sol request capabilities

Preserve mandatory reasoning through subscription discovery and configured Responses requests. Extract existing catalog readers and discovery coverage to respect file-size ratchets.

Co-authored-by: steipete <[email protected]>

* test(openai): narrow discovered model request fixture

Require the discovered row before converting catalog modalities and optional context metadata to the typed chat runtime model.

Co-authored-by: steipete <[email protected]>

---------

Co-authored-by: steipete <[email protected]>
(cherry picked from commit 858993c1a41c180da5743c110b5d8cc38bc74007)

* fix(logging): redaction stalls for seconds on long plus-joined text (#161089)

* fix(logging): stop redaction stalling on long plus-joined text

The seven vendor-token patterns built on BASE64_SAFE_TOKEN_BOUNDARY ran
their data-URL negative lookbehind at every `+`, `/`, or `=` boundary of a
base64-class run, rescanning the whole run each time. On two-byte subjects
(any character above U+00FF) V8 no longer rejects those boundaries early,
so 100 KB of `+`-joined text took seconds; JSC shows it on more shapes.

Check the token with a lookahead first so the lookbehind runs only where a
complete token starts. The matched language and capture groups are
unchanged.

* refactor(logging): inline single-use redaction helpers

Compact the base64-safe token helper (identical pattern strings) and fold the naming-only readEnvAssignmentKey wrapper into its only caller, keeping the fix production-LOC negative.

(cherry picked from commit ff21cc82ce5ffe7a1587b96a1636488956b26b9c)

* fix(gmail): recover watcher after transient restart bind conflicts (#161503)

The Gmail watcher stayed down for good when a Gateway restart briefly found its port still in use (EADDRINUSE). It now retries the bind a few times with bounded backoff and recovers once the port frees. If the port stays taken, it reports a clear error and stops retrying.

Fixes #161467. Reported by @kazuyuki-eguchi.

Proof: a real isolated Gateway, with the Gmail watcher on local fakes.
- Before the fix, the watcher stayed down after a transient port conflict. After it, the watcher recovered and answered.
- With the port held for the whole run, the watcher stopped after the initial attempt plus three retries, with a clear error.
- The regression test fails before the fix and passes after, and 31 focused tests pass.
- Updating from the published 2026.9.6 build to this build succeeded in two fresh runs (102 s and 97 s), and the installed build passed both the transient and the persistent control. The first updater run failed at service activation and didn't recur. The watcher can't reach that step: rehearsal disables hooks, and this diff doesn't touch activation or lease code.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 8095304914588d01c552977744595ceed8da985f)

* fix(sessions): reject missing and malformed session targets (#161533)

* fix(sessions): reject compaction of missing sessions

Return an actionable INVALID_REQUEST instead of a successful no-op for missing targets in both compaction modes. Preserve explicit no-op outcomes for existing empty sessions.

* fix(sessions): reject malformed reset agent selectors

Use strict session agent input validation before lifecycle cleanup so an invalid explicit selector cannot reset the default agent. Extract reset-target resolution from the oversized lifecycle service while retaining selected-global targeting.

Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit 670c2d0d6a0566e8e29191d70540f4aab8ff48a9)

* fix(agents): honor captured subagent announce skips (#161542)

Authoritative terminal snapshots bypassed ANNOUNCE_SKIP filtering and woke
the requester unnecessarily. Apply the existing completion selector before
expanding retained history, then suppress the successful announce while
preserving child cleanup. Keep global terminal snapshots, legacy fallback
behavior, and failed or timed-out child outcomes unchanged.

The real Gateway reproduction made three parent model requests instead of
two; five fixed repetitions avoid the extra turn. Three pre-fix regression
failures now pass. Blacksmith Testbox proof: 634 related unit cases, 87
announce E2E cases, 15 stub-provider operator scenarios repeated five times,
and the full changed-code gate. Streaming/reconnect/timeout-compaction
baseline flows passed once; their five-repeat rerun and process-restart
proof were not completed within the campaign time box. No live credentials.

Changed-test wall costs (pnpm test <file> --maxWorkers=1):
T2 COST FILE src/agents/subagents/announce/subagent-announce.test.ts
T2 TEST WALL 47.63 seconds
T2 COST FILE src/agents/subagents/announce/subagent-announce-output.test.ts
T2 TEST WALL 43.91 seconds
T2 COST FILE src/agents/subagents/announce/subagent-announce-result.test.ts
T2 TEST WALL 29.28 seconds
T2 COST FILE src/agents/subagents/completion/subagent-completion-result.test.ts
T2 TEST WALL 1.33 seconds

Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit 806f961301f9b0f4bc12fd6991cac6fac29597c5)

* fix(auto-reply): release canceled thinking-catalog waits (#161319)

* fix(auto-reply): release canceled thinking-catalog waits

Race the canceled reply's model-level and status waits against its own
AbortSignal without canceling shared catalog discovery.

Refs #161310

* fix(ci): keep database-worker test routes unique

The duplicate pdf-tool.resources.test.ts entry introduced in #161270
causes preflight to fail while splitting core-runtime-infra-storage-state.
Retain its original route once so PR test plans can be built.

* fix(auto-reply): keep abort assertion outside preprocessing import cycle

Move the existing AbortError assertion into a small reply leaf module so
model-level resolution can use it without importing the preprocessing graph.
The reply assertion behavior remains unchanged.

* test(ui): wait for shell viewport sync before splash geometry check

* fix(auto-reply): cancel earlier directive catalog waits

* chore: keep catalog cancellation PR scoped to reply handling

* test(auto-reply): avoid returning timer handle from executor

---------

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit f18202c76b68a01841466c6dc94cc65d21fbf023)

* fix(tts): pass the responding agent to summary model acquisition (#161454)

* fix(tts): pass the responding agent to summary model acquisition

summarizeText acquired its model without an agent id, so it fell back to the default agent and threw the no-explicit-owner error in multi-agent configs. Forward the reply's agent id from maybeApplyTtsToPayloadCore. The injected-deps path is unchanged.

Fixes #161431

* test(tts): cover multi-agent summary through real model selection

Drives summarizeText for agent 'work' in a two-agent config through the
real acquisition and selection path, stubbing only the completion call.
Asserts the ownership error is gone and the summary keeps using the
documented agents.defaults.model.primary fallback.

* test(tts): retain behavioral owner regression and document auth scope

---------

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 5073ee41abfbe2cab02c0e58a12d4dcc27bcba18)

* fix(imap): bound backlog message retention during sweeps (#160413)

The IMAP watcher collected every unseen message into memory before processing any of them, so a large backlog held every message body at once. Sweeps now fetch and process unseen messages in bounded batches, in UID order, with the existing cursor, retry and sender-gate behavior unchanged.

Fixes #160353. Thanks @Ayushdevo for the fix and @addyCooks for the report.

Proof: a real ImapFlow TCP connection to an in-process IMAP server holding 2,000 messages, run in a container.
- On main, the sweep held all 2,000 bodies at once. With this change it held at most 20, and every message was admitted exactly once in UID order.
- A rejection injected at UID 25 resumed from cursor 24.
- A sender-gated message (UID 30) was skipped once.
- The regression test fails before the fix and passes after, and the watcher suite passes 21/21.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit ecbe1861efd51fd1987315baf7b4cff797181a7c)

* fix(cron): isolated setup times out while the thinking catalog hydrates (#161132)

Isolated cron turns spent their whole 60-second setup budget waiting for the native thinking catalog to load, so the setup watchdog killed runs whose catalog was slow (measured at 13–65 s on 2026.9.6). The cron path now bounds that wait the same way `loadFullModelCatalog` already does and falls back to the published catalog facts. The shared `loadNativeModelCatalog` stays unbounded for the other callers that depend on it returning the complete catalog.

Fixes #161112. Thanks @jayzhou2309 for the fix and @Flakedict for the report and the measurements.

Proof: a real isolated Gateway in a container, with the mock provider's native catalog publication held open.
- On main, cron setup hit the watchdog at 60,012 ms. With this change, the cron turn replied in 11,756 ms while the publication was still held.
- When the catalog is fast, the turn replied in 1,683 ms using the full catalog.
- The regression test fails before the fix and passes after, and the scoped tests pass 7/7.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 786ed6b566080f48f57410a3c7334406db8e2da2)

* fix(matrix): preserve direct mappings when account-data reads fail (#161727)

Preserve existing Matrix peer mappings when an account-data read fails. Keep best-effort fallback on read-only inspection and propagate read errors before writes.

The regression failed on the original code and passes after the fix. Direct-room, sibling sender/FIFO, changed-file and zero-cycle checks passed; repair documentation explains the failure behavior.

(cherry picked from commit 78d75e9350c2b19cbec5c783d2b2a4d78932bad3)

* fix(agents): detached runs keep their transcript when a settled turn is finalized (#161091)

* fix(agents): preserve detached finalization history without internal prompts

Keep the host-owned session manager and persistence mode during settled-turn finalization. Refresh one-shot user persistence suppression when reusing the guard so empty-answer retries do not retain internal recovery prompts. Preserve completed tool receipts and subsequent genuine user turns.

Regression fails before the guard repair with two retained internal prompts and passes afterward. Focused proof: 126 tests, core tsgo, scoped lint, formatting, and whitespace checks pass. Independent Codex review found no actionable P0-P2 findings. Both native-live cases remain enabled on main.

* test(agents): reuse a caller-owned admission without growing the attempt runner

* test(agents): pass the caller-owned admission from the typed override

(cherry picked from commit 8f924bff5d680ef80e96ae960245847c782f2ff4)

* fix(worker): stop durable session retries from freezing node hosts (#160812)

* fix(worker): stop durable session retries from freezing node hosts

* test(worker): name closing window harness as repro

* test(worker): fix loopback harness checks

* test(worker): adapt closing-window regression to Gateway tools

---------

Co-authored-by: Altay <[email protected]>
(cherry picked from commit 1de9a42f114e4bdbb8c8be3331b02a9a807efb5f)

* fix: preserve plugin install records during legacy updates (#161485)

The v13 wide-row state migration conflated a missing installed_plugin_index row with a row whose JSON was unparseable or shape-drifted, and dropped the table in both cases. An invalid row is now preserved in full in the existing diagnostic_events quarantine with repair guidance recorded, valid install records are retained independently of damaged metadata, and a preservation failure rolls the step back to v12. No schema change.

Closes #161329.

Landed under the pre-existing-red rule: the remaining CI failures were current main reds at this base (Codex app-server settlement fixture drift, fixed on main by 52e60fb42bc3; the subagent kill-tombstone / descendant-cancellation intermittent first seen on main hourly 36619831492).

(cherry picked from commit e1ea50caf762bf5b09d2016fcdcf6e126f0c29e5)

* fix(gateway): restore CLI-backed exec with secret egress proxy (#160760)

* fix(gateway): pass admitted run instance to loopback-mediated exec

* test(gateway): cover egress-enabled MCP exec grants

Prove the real MCP HTTP grant, cached tool construction, egress-enabled process launch, retired-grant rejection, and a later run in the same session. Route the fixture through the existing native database-worker test group.

Co-authored-by: VACInc <[email protected]>

* test(ui): wait for transcript resize before measuring centering

The real layout owner publishes viewport width asynchronously after resize. Wait for rendered width readiness, then sample all centers atomically while retaining visible-box and one-pixel assertions. The focused catalog E2E now passes in secretless AWS; the real-browser mechanism reproduces the prior 160px phase and still rejects a 2px displacement.

Co-authored-by: VACInc <[email protected]>

* fix(ci): restore Doctor plugin repair lint budget (#160715)

Co-authored-by: VACInc <[email protected]>

* fix(ci): restore config and node adapter lint budgets (#160843)

* fix(ci): keep config env and worker tests within lint budgets

* test(gateway): share node capacity and rejection fixtures

Co-authored-by: VACInc <[email protected]>

* refactor(talk): combine transcript early-return guards

Preserve echo-first short-circuit evaluation while restoring the existing relay file-length budget. No runtime behavior or lint limit changes.

Co-authored-by: VACInc <[email protected]>

* refactor(ui): share model setup activation payloads

Reuse the same discovery-to-activation projection for prepared and directly selected candidates, retaining optional-field omission and excluding discovery metadata. Restore the existing model setup page line budget without changing UI behavior or lint limits.

Co-authored-by: VACInc <[email protected]>

* test(gateway): join chat execution before metadata assertions

The operator.write verbose-level fixture asserted agent.wait success after a one-second observation window without joining its detached run. Reuse the existing execution observer before the same scoped RPC, preserving the timeout and every metadata/permission assertion.

Verified the complete chat file on CI's Node 24.19.0 in network-isolated execution: 41 tests passed. Independent P0-P3 review and targeted lint passed.

Co-authored-by: VACInc <[email protected]>

* test(gateway): join recap producer lifecycle events

Wait for actual model entry before inherited connection drain and for the relocated recap post-commit publication before inspecting persisted state. Preserve model cancellation, old-owner fencing, exact target/store checks and existing persistence assertions. New waits follow test cancellation rather than timing a cold worker through an observation poll.

Verified both edited files (25 tests), the original receiving-merge peer groups (377 and 164 tests), focused lint, both owning type graphs and independent P0-P3 review.

Co-authored-by: VACInc <[email protected]>

* fix(infra): retain explicit SQLite launch paths when cwd is unavailable

Keep supplied launch and transport facts, resolve relative arguments only against a genuine captured cwd, and anchor native inspections to selected absolute operation paths when ambient cwd is gone. Refuse unresolved cwd-dependent inputs rather than redirecting them. Prove both native transports after real directory removal; cold Node Worker bootstrap remains a separate lifecycle limitation.

Co-authored-by: VACInc <[email protected]>

* test(gateway): coordinate monitor fault injection with worker admission

Use the existing managed state write transaction for persistent trigger creation and removal. Controlled scheduleUnowned interleaving reproduces both raw-DDL lock failures and passes both managed-DDL variants without changing reload assertions or timeouts. Ensure final trigger cleanup cannot skip service cleanup.

Co-authored-by: VACInc <[email protected]>

* test(gateway): keep monitor fault injection in fixture support

Preserve the exact managed DDL statements and cleanup lifecycle while shrinking the over-cap reload test. Line-cap, suppression, assertion and import-cycle guards pass; the 115-case file, focused lint, owning types and independent P0-P3 review pass.

Co-authored-by: VACInc <[email protected]>

* test(update): select host runtime for Homebrew guidance

Keep the Homebrew-specific guidance fixture independent of the container used for isolated proof. Container cases and all guidance assertions remain unchanged.

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: VACInc <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit 6daee6e4bd58a525ac6c958ad885d1431bda26e3)

* fix(sandbox): sessions fail with EACCES after skills refresh on read-only installs (#162304)

* fix(sandbox): keep synced skill copies removable on read-only installs

Sandbox skill sync copied bundled skills with fs.cp, which keeps source
modes. From a read-only install every copied directory became 0555, so the
next full re-sync (skills version bump or Gateway restart) failed with
EACCES unlinking skills/<skill>/SKILL.md, and library-pinned sessions
failed every turn.

Copied directories are now made owner-writable (file modes unchanged), and
removal repairs legacy read-only trees inside the synced child before one
retry. The repair stays inside the skills root and never follows symlinks.
The Claude CLI skills-plugin copy fallback uses the same helper.

* fix(sandbox): classify skill removal errors without a type assertion

(cherry picked from commit be93e8595555889d6ddc895989da9971d76de462)

* fix(agents): cron fallback delivers a truncated reply when history caps a long message (#160520)

When a run's final message was longer than the chat history display cap, the run-wait reply reader fell back to the capped history copy and delivered it with an internal `...(truncated)...` marker, cutting off the user's reply. The reader now recovers the full message instead of the display-capped projection. The capped display history keeps its provenance, and text the model writes itself, including a literal marker, is left alone.

Also addresses #82121 at the producer, without global stripping in the sanitizer. Thanks @jayzhou2309.

Proof: real isolated Gateways in a secretless container, with a scripted mock model, over the Gateway WebSocket and the actual run-wait reply reader.
- On main (`f57a952ab0aa`), a 14,329-character report came back as an 8,018-character copy ending in the truncation marker. With this change, it comes back complete and exact.
- Display-cap provenance is kept in history on both builds.
- Normal prose and an intentional standalone marker are unchanged.
- Three recovery cases fail on main and pass here, and the regression suite passes 63 tests.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit ebf4bd70ca7ae5c9db4858424e0b9f124114ef85)

* fix(update): avoid terminal errors during pnpm updates (#161920)

The updater spawned the package-manager install with inherited terminal stdin but captured stdout/stderr; pnpm 12.1.0's global build-approval prompt then failed with "IO error: not a terminal" and aborted the install. The pnpm package-install step now receives EOF on stdin (pnpm skips the prompt when stdin is not a terminal; no --yes, so consent is unchanged); npm and Bun installs and every other bounded command keep their stdin behavior. docs/install/updating.md gains the first-hop recovery for already-installed updaters.

Closes #161866

Thanks @alkor2000 for the diagnosis and fix.

Co-authored-by: alkor2000 <[email protected]>
(cherry picked from commit bbe0d114e4e06678a65a49479c6e9c8e920b500f)

* fix(agents): preserve spawned session cwd at ingress (#162308)

Visible child sessions persist lineage and a managed cwd without an inherited workspace. Keep that cwd for subsequent runs while preserving explicit inherited workspace precedence and sandbox ownership checks. Existing session rows require no migration.

(cherry picked from commit 43d29bbdb1198dcaa277bf020101d54aef349f32)

* fix: finished subagents keep child slots occupied after delivery expires (#162368)

* fix: release child slots when descendant delivery is suspended

* test: wait for collector completion publication

* ci: install ripgrep for baseline ratchets

* Revert "ci: install ripgrep for baseline ratchets"

This reverts commit 616d5cc3e04e77cf97c5cc6b7a201fb02e966a84.

* Revert "test: wait for collector completion publication"

This reverts commit a9902f4633b12fddccfe4780b3f08ed5ca52cda7.

---------

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit c03ee95e109d671ed7f4d918346a7cdc0f419d69)

* fix(skills): sandboxed turns fail with EACCES when refreshing read-only skill copies (#162295)

* fix(skills): refresh read-only sandbox skill copies

Repair owner access through confined directory descriptors before removing stale materialized skill trees. Preserve read-only sandbox mounts and source permissions. Cover prior read-only copies, nested cleanup, symlink confinement, and mount identity.

* fix(skills): unlink stale top-level skill symlinks

(cherry picked from commit 81d89fb43bbcb82f03b622dd994ac7e11228e5b5)

* fix: steered message no longer replaces a question whose model request failed (#162439)

Fixes: with the default `steer` queue mode, a message sent while the first message's model request is failing replaces the first message. The chat shows `⚠️ <model> request failed.` and then only the answer to the second message. The first question is never retried or answered.

When a model request fails while a newer message is waiting to steer into that turn, OpenClaw retries or falls back for the first message as usual. The newer message then runs as its own turn. Both questions get answered in order. The failure notice only appears if the first message's retries and fallbacks are all exhausted, the same as when nothing was steered.

Root cause: after a model request failed, `AgentSession.handlePostAgentRun` still continued the session with the queued steer. The embedded runner owns retries for a failed request (`agent-project-settings.ts` turns session auto-retry off, #73781), so the failed message was never retried. The steered message ran in its place, against a transcript where the failed message looked handled. Per-input answer segments (#149925) then correctly reported the first segment's failure, so the user got `⚠️ request failed` plus the second answer.

Provenance:
- `steer` became the default in `4a6e10ece842` ("feat: default queueing to steer") and #77023, to keep the active turn responsive without starting a second run.
- The post-run `hasQueuedMessages() ? "continue"` came from #109709 so that messages queued by `agent_end` handlers are not stranded. That reason still holds after successful turns. This PR only excludes failed requests, where continuing skips the run owner's retry and fallback.
- Steered channel input already waits for its transcript commit (`agent-runner-steer-adoption.ts`, `waitForTranscriptCommit: true`). When the session settles without committing it, the steer is withdrawn from the runtime queue and the parked reservation falls back to the ordinary follow-up queue. That path runs after the reply operation clears. No new queue or retry logic is added.

Fix: one condition. After a failed request, queued input no longer continues the session (`agent-session-prompting.ts`). Docs: `docs/concepts/queue-steering.md`.

Hermes comparison: Hermes injects a steer only at a role-safe boundary after a tool result. With no tool row yet, or when the request fails, it requeues the steer as the next turn's user message, and each queued message gets its own turn. This change gives OpenClaw the same outcome by reusing its existing follow-up fallback.

Relation to #161069 (stalled-turn recovery): that PR covers turns aborted by stuck-session recovery. This one covers a provider failure while a steer is pending. The two don't overlap.

- Fewer model calls: before, a pending steer triggered one extra model call inside the failed run. Now it doesn't.
- The first message keeps its existing retry budget (`MAX_EMPTY_ERROR_RETRIES = 3`, plus the configured fallback chain). Nothing new is retried.
- A handed-back steer is queued at most once. The fallback drops its `steerPending` marker, so it drains as an ordinary follow-up turn and is never steered again. If that turn also fails, it ends with the normal failure notice and is not requeued. The worst case is one follow-up turn per inbound message.
- Tested: the session regression test asserts exactly one model request after the failure, with no continuation. The requeue-once path is existing behavior covered by `src/auto-reply/reply/queue/enqueue.steering.test.ts` (6/6 on this head).

**Telegram Test Server** (`telegram-e2e-userbot`, Convex-leased credential, real QA user in a DM, default queue mode). A deterministic mock provider fails agent-turn requests whose newest question is `17*23` three times (`response.failed` after 8 s). Like the live model in our earlier proof, it answers only the newest user question. The QA user sends `What is 17*23?` at +0.2 s and `Also, what is 19*21?` at +8.2 s, so the second message arrives during the first failing request.

- Before (built head with only this line reverted): the SUT sends `⚠️ openai/gpt-5.5 request failed.` at +13.1 s, then `399` at +14.1 s. The request after the failure carries both questions (`developer,user,user,user`). The first request is never retried, and `391` is never sent.
- After: three failing first-question requests (`[empty-error-retry]` attempts 1/3 to 3/3), none carrying the second question. The fourth request answers `391` at +30.5 s. The second message then runs as its own turn (`developer,user,user,assistant,user,user`) and answers `399` at +31.5 s. No failure notice is sent.

**Unit test:** `agent-session-loop-next-turn.test.ts` "does not answer a steer in place of a failed request". On `main` the steer is committed into the failed turn (`promise resolved instead of rejecting`). With this change there is one request, the steer's commit wait rejects so its caller requeues it, and nothing is left queued. File: 24/24 pass. Related suites pass: `sdk`, `agent-session-loop-correctness`, `attempt-prompt-submit` (+ steering, retention), `attempt-stream-prepare`, `attempt-session-replay` and `provider-review-continuation`, 231 tests.

**Telegram with a live OpenAI model** (same Telegram Test Server DM; a small local proxy in front of the real OpenAI API fails only the first two agent requests that carry 17*23 without 19*21, and forwards everything else to the live model):
- Before (this line reverted in the build): one failing request, then the next request carries both questions and goes to the live model, which answers `399`. The bot sends `⚠️ openai/gpt-6-astra request failed.` (+20.4 s), then `399` (+21.0 s). 17*23 is never answered.
- After: two failing requests for the first question alone, then the live model answers the retry with `391` (+24.1 s). The second message's own turn gets `399` (+26.0 s). No notice.
- Both runs used the fix build, before the branch was rebased onto newer main; the production change is the same. For the before run, only the fix line was reverted.

**Telegram, when the first question fails on every retry and fallback** (same harness; the mock fails every agent request whose newest question is 17*23, and the agent has a fallback model configured): 8 requests for the first question, 4 on `gpt-5.5` and 4 on `gpt-5.5-fallback`. None of them carries the second question. The model-fallback log shows `gpt-5.5` failing over to `gpt-5.5-fallback`, then nothing left to try. The SUT sends exactly two messages: one `⚠️ openai/gpt-5.5-fallback request failed.` at +70.9 s, then `399` at +71.9 s from the second message's own turn. No other notices.

**Web UI `chat.send` (real Gateway, operator WebSocket client of the kind the TUI uses, same mock):** the client sends `What is 17*23?`, then `Also, what is 19*21?` 8 s later, during the first failing request.
- Before (this line reverted in the build): the client's only answer is `399`. The request after the failure carries both questions (`developer,user,user,user`). `chat.history` ends `user 17*23, user 19*21, assistant 399`, so the first question is unanswered.
- After: the steer is withdrawn when the failed attempt settles. Its `chat.send` run closes with an empty final (+17.1 s), and `chat-send-agent-dispatch.ts` dispatches it again; it runs as a follow-up and is not steered into the retry. The first run retries three times, with no retried request carrying the second question, and answers `391` (+33.7 s). The second message's own run answers `399` (+34.0 s). `chat.history`: `user 17*23, assistant 391, user 19*21, assistant 399`.

Why a withdrawn Web UI steer can't be re-steered into the retry: with explicit `queueMode: "steer"`, chat.send's fallback dispatch passes `messageInjectionDisposition: "rejected"` (`src/gateway/server-methods/chat-send-agent-dispatch.ts:388-390`). `runReplyAgent` steers only when the disposition is `"none"` (`src/auto-reply/reply/agent-runner-run.ts:341-346`), so the message is queued as a follow-up instead (`:389`). With the default mode, chat.send makes no injection attempt of its own (`chat-send-admission.ts:272-275`) and the message takes the channel path: its parked reservation falls back with its steer marker removed (`queue/enqueue.ts:307-318`), and the queue drains only after the reply operation clears (`agent-runner-steer-adoption.ts:110-122`).

**Wall times** (`pnpm test <file>`, shared, heavily loaded host):
- `agent-session-loop-next-turn.test.ts`: 24/24, 121 s wall (vitest 106 s). The new test signals request start and steer acceptance with deferreds; it no longer polls.
- `enqueue.steering`: 6/6, 78 s.
- `attempt.queue-message`: 16/16, 98 s.
- `agent-session-handoff-adoption.integration`: 1/1, 63 s.
- `agent-runner-steer-adoption.question-recovery`: 25/25, 97 s.
- `chat-send-steering-custody`: 17/17, 90 s.
- `agent-runner.runreplyagent.e2e`: 223/224 under load. The one failure, "keeps the replacement source when retired admission completes", passes alone (60 s wall). That file mocks the embedded agent, so it never reaches the changed session code.

qa-lab note: the qa-channel serializes inbound per account, so the same-sender steer couldn't be reproduced there. The proof uses the Telegram Test Server instead.

LOC vs `origin/main`: production +3/−1, test +46, docs +1 (changed line).

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 4d755295bc37cf910e168578697528af1753b98b)

* fix(telegram): restore progress when reply hooks suppress previews (#161546)

* fix(telegram): deliver progress when reply hooks suppress previews

Co-authored-by: VACInc <[email protected]>

* fix(telegram): honor global block-streaming opt-out

Preserve the explicit global off preference when reply hooks suppress previews, and cover both hook contracts through Telegram HTTP delivery.

Co-authored-by: VACInc <[email protected]>

* docs(telegram): clarify hooked fallback for multi-agent turns

Clarify that configured GroupThread turns retain their existing block policy: their previews are disabled independently of reply-modifying hooks. The new forced fallback applies to ordinary single-agent turns. No delivery-policy or test changes.

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: VACInc <[email protected]>
(cherry picked from commit 54a614954928e718f97c5aade26a7a94fdc4f45f)

* fix(webchat): keep saved replies visible during history refresh (#162763)

* fix(webchat): keep saved replies visible during history refresh

Fence pre-commit history snapshots at transcript publication before run settlement. Reuse the existing queued refresh so both active and late background replies survive history races.

Co-authored-by: VACInc <[email protected]>

* fix(webchat): keep saved replies visible during history refresh

Worked on by:
- @VACInc

Co-authored-by: VACInc <[email protected]>
OpenClaw-Publication: 18964aa1-fac1-42b9-8777-682b1d10ef09

---------

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: VACInc <[email protected]>
(cherry picked from commit e42c52b7d83ede656c778337b46c0a25cb279625)

* fix(cron): stale automatic tool lists block scheduled jobs from tools their owner has (#162432)

Related: #130753, #137832, #147969

Fixes: some scheduled jobs created by an agent fail for months because a tool list saved by an older OpenClaw build is missing tools the creator actually had, such as the native shell. In our setup, a monthly group job that runs `node <script>` delivered nothing in August, delivered nothing in September (the run still reported `ok`), and posted a blocker in October. Its saved list had 31 tools and no `exec`.

User impact: an agent-created agent-turn job that does not name specific tools now gets the same tools as its owner conversation at run time, like a job an operator creates without `--tools`. Existing jobs with an automatically saved creator snapshot behave the same way from their next run. Nothing stored is rewritten: no migration and no backups. Explicit tool lists, script payloads, condition triggers, and jobs bound to captured Codex app authority keep their stored list.

Tradeoff, approved by the maintainer (Ayaan): a per-sender tool policy on the creating owner, or a plugin hook that narrowed the creating turn, no longer limits these default jobs. Only owners can create automations from chat, and subagents cannot create them.

**History of the saved list.**
- #91499 introduced it so a delayed run cannot do more than its creator could.
- #112483 made every agent-created job store one, because runs have no sender.
- #112661 made scheduled runs re-apply the owner session's group policy and every non-sender limit, keeping the stored list as the upper bound.
- #137832 fixed native tool capture for new jobs only, and deliberately did not widen stored lists.
- #147969 added a Doctor advisory. It only fires for claude-cli, so it never covered Codex-harness or built-in OpenAI jobs like ours.

**Root cause.** When no tool list was given, OpenClaw saved a frozen copy of the creating turn's tools instead of treating the job like an operator `*` job. Every capture bug (missing native tools, late configured MCP, renamed tools) then stayed in the job permanently.

**Fix.** This follows Hermes, which keeps no creator snapshot: `cron/scheduler.py` `_resolve_cron_enabled_toolsets` reads toolsets from config at run time.
- **New jobs.** An agent-turn create or update with no list, or `*`, stores `["*"]`. That is the same value operator jobs store, so the job's tools match a normal turn in its owner conversation. Script payloads and condition triggers still store the creator's concrete tools, because a script reaches MCP only through servers its list names. Jobs whose creator captured Codex app authority also keep the concrete list, because that authority is bound to it.
- **Existing jobs.** One helper, `resolveCronRunToolsAllow` in `src/cron/tools-allow.ts`: a stored automatic snapshot (`toolsAllowIsDefault`) runs as `*` when it has a valid scheduled owner policy, no condition trigger, and no Codex app authority. Otherwise it keeps its stored list. Every execution consumer of the stored list uses it: the run payload, the command-prompt preflight, and the scheduled message authority.
- **Script transitions.** A `*` job that becomes a script, or gains a condition trigger, captures the creator's concrete tools.
- **Exec pin.** A `*` list keeps the creator's exec host pin.
- **No new noise:** automatic snapshots stay excluded from the `web_search` provider warning, as on main.
- **Deleted, now pointless:** both Doctor advisories about incomplete automatic snapshots, the run warning about pre-MCP snapshots, and two exports nothing uses anymore.

Review note: on claude-cli, a `*` job runs without a CLI tool cap, so Claude's native tools behave exactly as in a normal chat turn in that conversation. This PR introduces no new path around `tools.deny` that a chat turn doesn't already have.

Live-model Telegram proof (Telegram Test Server DM, leased team credential, live `openai/gpt-6-astra` reached through a forwarding proxy that stands in for the runner's mock provider; the runner harness itself is unchanged). This reproduces the shape of the original incident:
- The tester DMs the bot, which creates the owner conversation.
- A job owned by that conversation is added. Its stored list is an old-style automatic snapshot `["automations","message","read"]` plus `toolsAllowIsDefault: true`, with no `exec`.
- The payload is `Run: node scripts/split-report.mjs and post its output line verbatim`. The workspace script prints a random nonce.
- The job is run once (`cron run --wait`), with announce delivery to the DM.

| Build | `exec` offered | Model action | What arrived in the DM | Run |
|---|---|---|---|---|
| base 94f5a8d (main before this PR) | no | `tool_search` ×2, then gave up | "Could not run node scripts/split-report.mjs: no command-execution tool is available…" | error |
| **this PR, head 5b78cb7** | **yes** | `exec {"command":"node scripts/split-report.mjs"}` | "**SPLIT-REPORT 93C53909**: general 41, design 17, ops 9" (the exact script output, with this run's random nonce) | ok, delivered |
| head 5b78cb7 with `tools.deny: ["exec"]` | no | `tool_search`, `read`, then gave up | "Could not run node scripts/split-report.mjs: no command-execution tool or paired node is available…" | error |

In every run, the stored job kept `["automations","message","read"]` plus the marker. Before and after use the same scenario and driver; only the checkout differs.

Update and live proof: published `[email protected]`, then this branch at the exact head (2f5099d), on the same state directory. Mock provider. Every process ran under a temporary `HOME` and state directory. Each job's message makes the model call `exec` with `touch <effects>/<job>`.

1. 2026.9.7 created both jobs through `cron.add` (scheduled policy `trusted`). With the Gateway stopped, the "stale" job was given the old automatic-snapshot shape `["automations","message","read"]` plus `toolsAllowIsDefault: true`. sha256 of both stored rows: `609358837…`.
2. Runs:

| Build / config | Job | `exec` offered | Side effect | Run |
|---|---|---|---|---|
| 2026.9.7 | stale automatic snapshot | no | absent | error |
| 2026.9.7 | explicit `["read","message"]` | no | absent | error |
| this branch | stale automatic snapshot | **yes** | **created** | ok |
| this branch | explicit `["read","message"]` | no | absent | error |
| this branch, owner policy narrowed to `tools.deny: ["exec"]` | stale automatic snapshot | no | **absent** | error |
| this branch, `tools.deny: ["exec"]` | explicit `["read","message"]` | no | absent | error |

3. After the branch runs, the stored rows were byte-identical (same sha256 `609358837…`), and job ids and lists were unchanged. Nothing was migrated.

An earlier run at e151ea3, with the same harness, also covered a snapshot bound to Codex app authority: `exec` was not offered, the file stayed absent, and the stored row was unchanged.

Tests:
- `run.tools-allow.test.ts`: a stored automatic snapshot `["message","read"]` reaches the embedded run as `["*"]`, with the owner's scheduled policy intact. It fails on main with `["message","read"]`.
- `cron-tool-creator-cap.test.ts`: a default agent turn stores `["*"]`, while a trigger script and a Codex-app creator keep the concrete snapshot.
- `run.tools-allow.test.ts`: snapshots without a valid owner policy, or behind a condition trigger, keep their list. Both cases fail on the previous head.
- `run.tools-allow.test.ts`: no `web_search` warning for an automatic snapshot that kept its list. This fails without the exclusion.
- `run.message-tool-policy.test.ts`: a self-edited automatic snapshot runs on CLI with no cap.
- `run.tools-allow.test.ts`: a legacy `Command to run:` prompt from an automatic snapshot without shell tools now runs instead of being rejected.
- `jobs-tool-policy.test.ts`: scheduled message authority is admitted for an automatic snapshot that lacked `message`.
- `cron-tool-creator-cap.test.ts`: a `*` agent turn converted to a script captures the creator's concrete tools.
- These three regressions fail on the previous head. `node scripts/check-changed.mjs` passes.
- Explicit-list, exec-pin and gateway creator-transport suites pass. `pnpm tsgo:core` passes.

No new path triggers a model call or a job run. The change only selects which tool list an already scheduled run uses.

LOC vs main: production +98/-250 (net -152), tests +140/-373, docs +19/-11.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 08498ec40de5803d77eafb728ef675d0034c13c1)

* fix(cron): deliver manual runs started from an agent turn after that turn ends (#162780)

Fixes: when an agent turn starts an automation with `automations` `run` (for example the owner says "run my report now"), the run fails with `attempt disposed before transcript write` once that turn ends. For a `sessionTarget: "current"` job the report is never delivered. For other jobs the report is still sent, but its copy in the conversation transcript is lost (a WARN).

User impact: "Run it now" from a chat delivers the report, the same as a scheduled run. No new settings, messages or warnings.

Root cause: the `automations` tool calls `cron.run` through the in-process gateway, so `enqueueRun` runs inside the calling turn's AsyncLocalStorage, including its owned transcript-write context (`withOwnedSessionTranscriptWrites`). The queued run inherits that context. When the run writes into the caller's session (the current-session report or the delivery mirror), `runWithOwnedSessionTranscriptWrite` matches the session and routes the write through the caller's attempt lifecycle. By then that turn has ended and its lifecycle is disposed, so the write is rejected.

Provenance:
- #104595 (`b6e95201f8b`, "retain detached manual run admission") made the queued manual run its own gateway root (`runWithGatewayIndependentRootWorkContinuation(..., "cron:manual-run")`), so it no longer depends on the caller's request. That helper resets only gateway work admission, not other per-turn context.
- Later, #115404 (`d16e33e08e4`) and #121113 (`ce53f7e82e2`) carried the turn's transcript lifecycle and writer fence in an AsyncLocalStorage, so nested writes stay serialized and fenced to the running attempt. #115404 also added `runWithoutOwnedSessionTranscriptWrites` for work that outlives its turn. Subagent completion (`b3d3f860e4a`), `sessions_send` follow-ups, media-generation completions, and session event wakes all use it. The manual-run detach point from #104595 never got it.

Fix: `enqueueRun` starts the queued run outside the caller's owned transcript context (`runWithoutOwnedSessionTranscriptWrites` around the existing independent root continuation). It reuses the helper the sibling detached paths use; no new mechanism. The invariants of those PRs still hold: the run is still a tracked independent gateway root (#104595); the caller's activation and commit guards still run before acceptance, and they don't touch transcripts; writes made during the turn are still fenced to its attempt (#115404/#121113). The queued run gets its own lifecycle when its attempt starts, the same as a scheduled run.

Hermes: `trigger_job` doesn't run the job inside the caller. It marks the job for the scheduler's next tick, so a manual run always starts from scheduler-owned context. This change does the same for OpenClaw's queued manual run, at the point where it detaches.

- **Live, Telegram Test Server DM, live OpenAI model** (`telegram-e2e-userbot`, Convex-leased credential, fresh isolated gateway built from each ref, ports 19951/19952, provider slot = pass-through proxy to the OpenAI API; the tester is the configured owner, `session.dmScope: "main"`). The owner creates `current-check` (`sessionTarget: "current"`, `payload: agentTurn "Reply with exactly CURRENT-REPORT"`, `delivery: announce`, disabled), then sends: "Use the automations tool to run the automation named current-check now (action run, runMode force …). When the run call returns, reply with exactly RUN-DONE".
  - Command (secrets omitted): `E2E_MOCK_SERVER_PATH=<live proxy> node .agents/skills/telegram-e2e-userbot/scripts/run-mock-sut-user-e2e.mjs --gateway-port 19951 --mock-port 19952 --dm --timeout-ms 420000 --scenario <scenario> --record events.ndjson --output summary.json` → exit 0 on both refs. The scenario waits 90 s after the last reply.
  - **Before, `origin/main` `26bcc94353c`:** DM shows `SETUP-DONE` (20.8 s) and `RUN-DONE` (87.7 s), then nothing more. The run receipt is `error: attempt disposed before transcript write`. The gateway logs it at the cron run session (`outcome=error`).
  - **After, this branch:** DM shows `SETUP-DONE` (24.2 s), `RUN-DONE` (94.4 s), **`CURRENT-REPORT` (96.4 s)**. The run receipt is `ok`, and the gateway log has no `attempt disposed` lines. The WARN/ERROR lines are the same harness startup lines as in the before run.
- **Regression test** (`src/cron/service/ops.regression.test.ts`, "runs a manual run queued from an agent turn outside that turn's transcript lifecycle"): `enqueueRun` is called inside a real attempt transcript lifecycle (`createEmbeddedAttemptTranscriptLifecycle` + `withOwnedSessionTranscriptWrites`). The calling turn disposes, then the run writes into the caller session through the real `runWithOwnedSessionTranscriptWrite`. On `origin/main` the run finishes `error`; with this change it finishes `ok` and the write lands.
- `pnpm exec vitest run src/cron/service/ops.regression.test.ts src/cron/service/ops.run-admission-cleanup.test.ts src/cron/service/ops.run-admission.test.ts src/cron/service/manual-ack-durability.test.ts` → 4 files, 46 tests passed.
- `node scripts/check-changed.mjs` on `997394f3a3a` → exit 0 (format, lint, core and test typecheck, line-cap and dead-export ratchets).
- Test cost: `pnpm test src/cron/service/ops.regression.test.ts --maxWorkers=1` → 15 tests passed, 33.9 s wall (vitest 30.7 s, mostly transform; the new test itself takes about 40 ms).
- Size vs `origin/main`: production +6/−2 ignoring whitespace (+75/−71 raw, because the existing callback is re-indented one level); test +58.

Not changed here: in both runs the `current` run waits behind the caller turn, and the tool's run wait returns "Not finished yet" after about 60 s before the turn replies. That wait is a separate issue.

One AsyncLocalStorage `exit` per queued manual run. No new state, timers, retries or queues. The run's own transcript writes go through its own attempt lifecycle, as for any scheduled run.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 510beb8d52bd6be9fea27513b9008a50c92a1d2d)

* fix(codex): prevent Gateway heap exhaustion with large agent fleets (#162912)

Closes #162802

Fixes Gateway heap exhaustion during Codex session discovery on large agent fleets. Thanks to @609NFT for the report and allocation profiles.

Large fleets can finish startup and retain their native Codex session catalog without retaining a whole fleet configuration for every agent/home pair. No schema, stored-data, configuration, or catalog-output changes are required.

The existing config-identity cache now owns one captured configuration per generation. Agent/home entries keep their separate directories and cloned connection options, but share that captured configuration. Config reload isolation and source-specific backoff remain unchanged.

No overlap with Pash/Sarah changes.

Codex source inspection: `codex-rs/app-server/src/request_processors/thread_processor.rs:2524–2608` in the sibling Codex checkout confirms that `thread/list` consumes pagination and filter parameters; the fleet configuration capture being repaired belongs to OpenClaw, not the native listing protocol.

Compared baseline `7ef388bac8f607eb03510189922d1c6a4d786b52` with candidate `f0ae922f60922f2b357bc3d5af22a2142799fbe0` in isolated Linux arm64 Docker containers, Node 24.21.0. The synthetic profile contained 739 agents, eight explicit Codex homes, and three native sessions (380,439 bytes of configuration).

| Check | Baseline | Candidate |
| --- | --- | --- |
| Real Gateway, 2,560 MiB heap | Heap OOM at 100.3 s | Survived the six-minute window; clean shutdown |
| Sampled catalog allocations under `resolveRequestOptions` → `structuredClone` | 2.248 GB | 5.48 MB |
| Post-startup heap, 150–360 s | Process already terminated | Bounded at 377–566 MiB |
| Complete startup, separate 6,144 MiB control without profiling | 98.34 s | 93.83 s |
| HTTP listening, same startup control | 50.52 s | 49.56 s |

The larger-heap startup control lets the baseline complete startup rather than comparing a successful candidate against an OOM.

- Real `sessions.catalog.list` Gateway RPCs returned exactly the three expected native session IDs for agents `agent000`, `agent001`, and `agent738`.
- Exact-head live gate: a real OpenAI `gpt-5.4-mini` turn through the candidate Gateway's Codex harness returned `CATALOG_LIVE_OK` on the 739-agent profile (5.449 s). Its temporary read-only credential file and container were removed.
- Regression failed on baseline: four fleet config clones instead of one across multiple agents/homes. It passes on the candidate and also checks reload allocation isolation; the regression itself took 5 ms.
- All 38 focused tests passed across `session-catalog-listing-cache.test.ts`, `session-catalog-request-lifetime.test.ts`, `session-catalog-homes.test.ts`, and `session-catalog-backoff.test.ts` (38.67 s wall).
- Standalone `pnpm test extensions/codex/src/session-catalog-listing-cache.test.ts --maxWorkers=1` passed (32.61 s wall, including runner preparation).
- Built and exercised the real candidate runtime with `pnpm build`. Broader static and project-wide validation is left to CI.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit fd0124688db63ef6801ed5008551cf7db9e1a433)

* fix(agents): preserve complete CLI subagent answers (#162843)

Fixes #162777.

The claude-cli transcript writer now records `__openclaw.runId` on the terminal assistant row, matching the field other writers set and the completion reader expects. CLI-backed subagents now deliver their complete final answer instead of the truncated-by-retention fallback.

Proof: real isolated Gateway with a fake claude-cli backend. main delivered the fallback and dropped the tail of a 14,025-character child answer; with this change the parent received all 400 lines including the tail marker. A failed CLI child still reports its error with no fabricated final. Live control: one real OpenAI embedded subagent turn delivered its exact answer. Regression tests fail before and pass after.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit d7cea26df24dac303a77f0e6149654a685e55323)

* fix(reef): admit gpt-6.1-sol as a documented immutable guard model (#162955)

OpenAI's gpt-6.1 generation publishes no dated snapshots either, so the Reef
guard rejected the Team configuration that pinned gpt-6.1-sol and the channel
could not start. Admit the exact id beside the gpt-5.6 ids, with the same
documented residual risk; bare family aliases stay rejected.

(cherry picked from commit d77cdd2af6bbcc238b38c99a0b0d54fe35b3359e)

* fix: remote MCP plugins fail to start in native agent sessions (#162376)

* fix: remote MCP plugins fail to start in native agent sessions

* test: align remote MCP assertions with normalized transports

(cherry picked from commit 4587ef903ca6afa6ca58b4c02a656e59a6ca0656)

* fix(llama-cpp): managed server fails on clean Windows installs (#163093)

* fix(llama-cpp): ship Windows VC runtime app-local

* fix(llama-cpp): make Windows runtime staging fallback-only

(cherry picked from commit 45762faaa842ffc797086417ad7b75c1ff588799)

* fix(secrets): keep store entry kind when rotating a value (#158968) (#160926)

* fix(secrets): keep store entry kind when rotating a value

`secrets store set <NAME> --value-file <path>` resolved the entry kind
from the name heuristic whenever no host-policy flag was passed, so
rotating the value of an entry created with `--kind secret` under a name
the heuristic does not classify as sensitive silently converted it into a
readable `env` entry and deleted its `--allow-host` allowlist. `import`
classified every entry from its name for the same reason.

Both paths now inherit the stored kind, and that inheritance is resolved
inside the authoritative store write transaction rather than captured
before the CLI awaits its value or its confirmation. A protection change
committed while one of those waits is pending is therefore no longer
overwritten by the pending write, and the value it carries lands under
the newer policy instead of reaching agent subprocesses as plaintext.

Because a kind resolved at write time can invalidate a value the CLI
already accepted, `import` now hands its whole batch to a single
store-owned write. `writeSecretStoreEntries` resolves every live kind and
validates every resulting entry inside one transaction before it writes
any of them, so an entry that a concurrent protection change turns into
an empty secret still fails the command with nothing committed, matching
the existing no-write-on-validation-failure contract.

An explicit `--kind` still overrides both the stored kind and the name
heuristic in either direction.

(cherry picked from commit 66a8c01c8db76bf63ab79c506880f462856b2d1e)

* fix(secrets): satisfy CI pools, formatters, and assertion ratchet

- Run the kind-inheritance purge through the expiry kernel directly so it
  does not require the host-broker state worker (the CLI project executes
  test files off the main thread).
- Replace uncommented kind casts with runtime narrowing for the assertion
  SAFETY ratchet; reformat to oxfmt.

Co-authored-by: yetval <[email protected]>

* chore(ci): rerun checks

* ci: retrigger checks for flaky shard reruns

* ci: retrigger checks (flaky infra shards)

* test(ci): dedupe pdf-tool.resources in database worker core paths

670e3fb4ea2 (#161270) re-added src/agents/tools/pdf-tool.resources.test.ts
to databaseWorkerCoreTestFiles, which already listed it (16b17b22ebc). The
changed-node shard planner now rejects repeated files in a split timing
generation, so preflight threw 'split timing generation repeats files for
core-runtime-infra-storage-state' for every PR touching any non-README path.

* fix(secrets): enforce literal input safety at commit

Carry argv provenance to the store transaction and refuse literal values when
kind inheritance resolves to a secret. Preserve explicit env reclassification,
cover concurrent protection, and clarify the set/import kind rules.

Strengthen rotation-value, committed-kind output, and redacted batch no-write
regressions. Existing Gateway writer paths remain unchanged.

Co-authored-by: zachisfine <[email protected]>
Co-authored-by: yetval <[email protected]>

---------

Co-authored-by: yetval <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: zachisfine <[email protected]>
(cherry picked from commit 0ae13a56209a1e4eea646e1869bd81367b38d3c0)

* chore(release): prepare 2026.8.35

* fix(release): adapt backports for 2026.8

* docs(changelog): refresh 2026.8.35 ledger

* fix: repair extended-stable backport integration

* fix: preserve cleanup failures on 2026.8

* test: complete worker cleanup before gateway close

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: wangmiao0668000666 <[email protected]>
Co-authored-by: Tak Hoffman <[email protected]>
Co-authored-by: RoboClaw <[email protected]>
Co-authored-by: steipete <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: Baumus <[email protected]>
Co-authored-by: Y.B. <[email protected]>
Co-authored-by: Ayush Tiwari <[email protected]>
Co-authored-by: Jay Zhou <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: RileyJJY <[email protected]>
Co-authored-by: Altay <[email protected]>
Co-authored-by: Vito Cappello <[email protected]>
Co-authored-by: VACInc <[email protected]>
Co-authored-by: alkor2000 <[email protected]>
Co-authored-by: alkor2000 <[email protected]>
Co-authored-by: Sam Armstrong <[email protected]>
Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: Jony <[email protected]>
Co-authored-by: Patrick Erichsen <[email protected]>
Co-authored-by: zachisfine <[email protected]>
Co-authored-by: yetval <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: qa-lab merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

2 participants