Skip to content

fix(agents): recover final replies after terminated streams - #142168

Merged
obviyus merged 3 commits into
openclaw:mainfrom
LiuwqGit:feat/issue-142149-terminated-settled-turn-recovery
Sep 9, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
LiuwqGit:feat/issue-142149-terminated-settled-turn-recovery

Conversation

@LiuwqGit

@LiuwqGit LiuwqGit commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

AI-assisted: yes

Related: #142149

What Problem This Solves

Fixes an issue where a completed tool-driven turn loses its final reply when the provider stream ends with bare terminated after the ordinary retry window has elapsed. The turn reports LLM request timed out even though its run timeout did not fire.

Why This Change Was Made

Reuse the existing anchored transport-message pattern when capturing settled-turn context. Preserve the caller's lifecycle callback and terminal deferral through the built-in finalizer, so the recovered answer ends the run successfully instead of retaining the prior attempt's error.

The normal transcript-continuation path, timeout-family classification, exact tool-settlement checks, cancellation, refusal and permanent-error guards remain unchanged. The finalizer still has no callable tools.

User Impact

Eligible completed turns retain their final summary without repeating tool effects. Asynchronous or unfinished work, previously visible answers and unsettled delivery remain excluded.

Evidence

The real authenticated Gateway proof uses chat.send and agent.wait, the built-in file tool, an actual interrupted HTTP response body and the built-in finalizer. An initial transient failure starts the existing retry window; the later post-tool stream closes after that window expires. The fixture does not disable retries or change timeout policy.

  • Baseline 82d4e9a: one completed write, persisted terminated, no final answer, and the existing timeout-family error.
  • The ordinary single-cut continuation control still answers with one write.
  • All three new context/transport regressions failed at the intended boundary before the fix; 834 focused checks passed after the context repair.
  • The connected lifecycle regression failed because the callback was dropped; 35 lifecycle, cancellation and harness checks passed after forwarding the existing caller fields.

Candidate 96d2cfe4 passes the real late-cut Gateway flow: the existing finalizer sends one request with no callable tools, agent.wait returns success, history contains one final answer, the original message prefix is unchanged, and the only added message is the final answer. Normal cache bookkeeping remains separate from messages. The completed write is not repeated.

Fresh source-blind native acceptance independently passed both the late-cut recovery and ordinary-continuation controls on 96d2cfe4. The full negative-state and source-mechanism gates are covered separately by focused tests and source review. Exact-head hosted CI and the final review gate remain required before landing.

Limits: the provider is a deterministic loopback service. This does not certify a live Windows llama.cpp/llama-swap deployment or make every background-download run eligible. Private internal flags/context are supported by source and observed lifecycle evidence, not claimed as directly exported fields.

@clawsweeper

clawsweeper Bot commented Sep 8, 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 agents Agent runtime and tooling size: S labels Sep 8, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 8, 2026
@clawsweeper

clawsweeper Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 9, 2026, 8:07 AM ET / 12:07 UTC (Revision 4).

ClawSweeper review

What this changes

Recover final answers after an exact terminated-stream error by retaining completed tool results and preserving lifecycle notifications through the existing tool-free finalizer.

Merge readiness

✅ Ready for maintainer review

This remains a useful, focused fix: current main still misses the reported recovery path. No blocking patch defect was found, and the supplied real-transport and Gateway observations satisfy the behavior-proof requirement.

Priority: P2
Reviewed head: 96d2cfe4a62abb5cedb2427da009fb7644d65e05

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful before/after transport evidence, reported Gateway acceptance, and no actionable correctness finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured evidence connects the exact-error context repair to an actual interrupted HTTP body and reports the built-in finalizer’s late-cut Gateway recovery on 96d2cfe: agent.wait succeeds, one final answer is appended, and the completed write is not repeated. The original Windows llama.cpp deployment is outside this bounded proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured evidence connects the exact-error context repair to an actual interrupted HTTP body and reports the built-in finalizer’s late-cut Gateway recovery on 96d2cfe: agent.wait succeeds, one final answer is appended, and the completed write is not repeated. The original Windows llama.cpp deployment is outside this bounded proof.
Evidence reviewed 9 items Recovery repaired at its producer: The introduced predicate accepts only the exact trimmed terminated message in addition to existing transient failures. Abort, timeout, visible-answer, and tool-result checks remain in place.
Existing settlement and terminal safeguards: The consumer still requires matching completed tool calls and excludes asynchronous work, cancellation, existing delivery, client tool calls, and yielded work. The terminal-resolution guard continues rejecting structured terminal errors and refusals.
Lifecycle ownership remains with the caller: The built-in finalizer forwards the existing callback and terminal deferral while retaining disableTools=true. The stream preparation maps deferral to finishing, matching the outer orchestrator’s ownership of final publication.
Findings None None.
Security None None.

How this fits together

The embedded agent runner turns provider responses and completed tool results into an assistant reply. Its finalizer can recover a missing answer without repeating tools, while the outer execution owner publishes the run’s final outcome.

flowchart TD
  A[Provider stream and tool results] --> B[Attempt result projection]
  B --> C{Tools settled and recovery eligible?}
  C -->|Yes| D[Tool-free finalizer]
  C -->|No| E[Preserve existing outcome]
  D --> F[Final answer and lifecycle notification]
  F --> G[Outer owner publishes completion]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +13, Tests +73. Total +86 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 3 16 3 +13
Tests 4 76 3 +73
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 92 6 +86

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #142149
Summary: This PR is the candidate repair for the open settled-turn recovery report; the older failover-classification report concerns a distinct boundary.

Members:

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

Technical review

Best possible solution:

Keep recovery in the existing context producer and tool-free finalizer, preserving completed effects and caller-owned terminal publication.

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

Yes: current source excludes bare terminated without a recognized transport code from recovery context, and the supplied before/after transport and late-cut Gateway observations exercise that gap. This read-only review did not execute the reproduction.

Is this the best way to solve the issue?

Yes: repairing the context producer and forwarding existing lifecycle fields reuses the established recovery mechanism without weakening terminal-error guards or adding another retry policy.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: A bounded provider-stream failure can suppress the final answer after useful tool work has completed.
  • 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 (live_output): The captured evidence connects the exact-error context repair to an actual interrupted HTTP body and reports the built-in finalizer’s late-cut Gateway recovery on 96d2cfe: agent.wait succeeds, one final answer is appended, and the completed write is not repeated. The original Windows llama.cpp deployment is outside this bounded proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured evidence connects the exact-error context repair to an actual interrupted HTTP body and reports the built-in finalizer’s late-cut Gateway recovery on 96d2cfe: agent.wait succeeds, one final answer is appended, and the completed write is not repeated. The original Windows llama.cpp deployment is outside this bounded proof.

Evidence

What I checked:

  • Recovery repaired at its producer: The introduced predicate accepts only the exact trimmed terminated message in addition to existing transient failures. Abort, timeout, visible-answer, and tool-result checks remain in place. (src/agents/embedded-agent-runner/run/attempt-result.ts:123, 96d2cfe4a62a)
  • Existing settlement and terminal safeguards: The consumer still requires matching completed tool calls and excludes asynchronous work, cancellation, existing delivery, client tool calls, and yielded work. The terminal-resolution guard continues rejecting structured terminal errors and refusals. (src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts:348, 96d2cfe4a62a)
  • Lifecycle ownership remains with the caller: The built-in finalizer forwards the existing callback and terminal deferral while retaining disableTools=true. The stream preparation maps deferral to finishing, matching the outer orchestrator’s ownership of final publication. (src/agents/harness/builtin-openclaw.ts:49, 96d2cfe4a62a)
  • Current main still needs the fix: At fetched main, the transient predicate still checks only network classification and incomplete-stream wording; the restricted finalizer also lacks the two lifecycle fields. Existing recovery therefore does not duplicate this repair. (src/agents/embedded-agent-runner/run/attempt-result.ts:112, 87ade599b623)
  • Latest supplied release lacks the exact-message repair: The v2026.9.3 source also returns only INCOMPLETE_ASSISTANT_STREAM_RE.test(message) after network classification. (src/agents/embedded-agent-runner/run/attempt-result.ts, 1391f7cd2d40)
  • Real transport regression and reported Gateway acceptance: The inspected transport test cuts an actual SSE response body and checks bare terminated, one tool execution, request tool counts [1,1,0], preserved transcript prefix, and a recovered answer. The supplied comment reports its before/after failure and success. Separately, the captured PR body reports authenticated chat.send/agent.wait acceptance on 96d2cfe, using the built-in finalizer after the ordinary retry window, with successful completion and one unchanged write. These are contributor-reported executions, not tests run during this review. (src/agents/embedded-agent-runner/run/settled-turn-finalization.transport.test.ts:129, 96d2cfe4a62a)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • VACInc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: 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 (3 earlier review cycles)
  • reviewed 2026-09-08T13:02:45.404Z sha d5df6104a62c5e8ae0df5b27f2e3854283d780a0 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-08T13:59:34.376Z sha 4512562 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-09T11:58:28.509Z sha 96d2cfe :: needs maintainer review before merge. :: none

…h "terminated"

A bare `terminated` transport failure on the final post-tool provider call
carries no retryable code, so the settled-turn finalization context producer
treated it as non-transient and the whole run failed as "LLM request timed
out" even though no run timeout had fired and all tool work had settled.
Reuse the failover timeout family anchored `^terminated$` pattern in the
transient predicate so the existing tool-free finalization path recovers the
final visible reply.

Fixes openclaw#142149
@LiuwqGit
LiuwqGit force-pushed the feat/issue-142149-terminated-settled-turn-recovery branch from d5df610 to 4512562 Compare September 8, 2026 13:54
@LiuwqGit

LiuwqGit commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

Added the missing real-behavior proof for the exact bare terminated path (follow-up to the review's proof ask): a new end-to-end case finalizes after terminated failure in settled-turn-finalization.transport.test.ts, pushed in 4512562.

What it proves (real transport, no fixtures for the failure itself):

  • A loopback HTTP server speaks the real OpenAI Responses SSE protocol; on the final post-tool stream it writes a valid response.output_item.added event and then destroys the socket mid-body — Node/undici surfaces exactly TypeError: terminated, which reaches the transcript as stopReason="error" / errorMessage="terminated" with no retryable code (isTransientNetworkError returns false, confirming this is the previously-unclassified path — the failure is produced by the real transport, not injected).
  • The production projector captures settledTurnFinalizationContext and the isolated tool-free finalizer issues the recovery request with tools: [], producing the visible final reply "Note saved once.".
  • Completed side effects execute exactly once: execute called once, tool lifecycle {startedCount: 1, completedCount: 1, activeCount: 0}, note file contains a single saved line, provider request tool counts are [1, 1, 0], and the failed-turn transcript prefix is preserved with the finalization answer as the only addition.

Evidence after fix:

✓ finalizes after HTTP failure 1329ms
✓ finalizes after WebSocket failure 215ms
✓ finalizes after terminated failure 438ms
Test Files  1 passed (1)   Tests  3 passed (3)

Evidence before fix (same test with only the fix files reverted to main — the already-recognized HTTP/WebSocket cases still pass, the bare terminated case fails exactly at the classification gap):

✓ finalizes after HTTP failure 1253ms
✓ finalizes after WebSocket failure 230ms
FAIL finalizes after terminated failure
AssertionError: expected { terminal: { kind: 'ok' }, …(48) } to match object
  { settledTurnFinalizationContext: { source: 'openclaw-transcript' } }
Test Files  1 failed (1)   Tests  1 failed | 2 passed (3)

The PR body Evidence section has been updated accordingly. Note on the earlier red checks at d5df610: checks-node-compact-small-51/-52 were runner-infra failures (exactly 10-minute runs with zero recorded steps and no retrievable logs), and checks-node-compact-large-17 failed in ui/src/app/settings.preferences.node.test.ts with a Vitest EnvironmentTeardownError — none touch this PR's src/agents/** files; the new push re-runs them.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 8, 2026
@obviyus obviyus self-assigned this Sep 9, 2026
Reuse the existing exact transport-message pattern when capturing settled-turn context. Preserve ordinary transcript continuation, timeout classification, and the tool-free finalizer safeguards.
Forward the existing caller lifecycle callback and deferral setting into built-in finalization so the recovered turn replaces its prior attempt error and the outer caller publishes its final outcome.
@obviyus obviyus changed the title fix(agents): settled tool turns lose the final reply when the provider stream ends with "terminated" fix(agents): recover final replies after terminated streams Sep 9, 2026
@obviyus
obviyus requested review from a team as code owners September 9, 2026 11:51
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams labels Sep 9, 2026
@obviyus

obviyus commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

landpr-approve-unrelated-red
pr: 142168
head: 96d2cfe
run: 34347762454 attempt: 1
failed: checks-node-changed-extensions-bundle-27 job=102453618170 conclusion=failure
check: openclaw/ci-gate

@obviyus

obviyus commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

Thanks @LiuwqGit! Landed as 5614557 with your authorship preserved.

Proof: The real Gateway baseline lost the final reply after a completed write and an interrupted HTTP response once the ordinary retry window had elapsed. The repaired run uses the existing tool-free finalizer, stores one answer, preserves the original messages, and completes successfully without repeating the write. Independent native acceptance confirmed both that recovery and the unchanged ordinary-continuation path. Focused checks and the exact-head security-aware review passed.

CI disposition: Run 34347762454 completed with 139 successful jobs, 17 skipped jobs, and one failed child plus its aggregate. The failed child reports a Telegram loopback model-confirmation editMessageText network error. That callback path uses grammY's HTTP client and does not execute this PR's embedded-attempt or finalizer changes. Main-side controls at 82d4e9a passed in both standalone and canonical runner modes; they did not reproduce the failure. Its underlying fetch cause and introducing commit remain unknown. The failed shard's remaining selected tests are not claimed as passed. Landing used the guarded completed-run exception, not a green-CI claim or an unchanged rerun.

Scope: Existing asynchronous-work, unfinished-tool, cancellation, refusal, delivery and timeout safeguards remain. The proof uses a loopback provider; it does not certify the original Windows/background-download scenario. #142149 remains open for that broader reproduction.

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

Labels

agents Agent runtime and tooling app: android App: android app: ios App: ios app: linux app: macos App: macos app: wearos App: wearos app: web-ui App: web-ui channel: a2a channel: buzz channel: discord Channel integration: discord channel: feishu Channel integration: feishu channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: irc channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: qa-channel Channel integration: qa-channel channel: raft Channel integration: Raft channel: reef Channel integration: reef channel: signal Channel integration: signal channel: slack Channel integration: slack channel: sms Channel integration: sms channel: synology-chat channel: telegram Channel integration: telegram channel: tlon Channel integration: tlon channel: twitch Channel integration: twitch channel: voice-call Channel integration: voice-call channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo channel: zalouser Channel integration: zalouser deploy: cloudflare Cloudflare deployment template and docs docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: acpx extensions: active-memory extensions: admin-http-rpc extensions: arcee extensions: baseten Extension: baseten extensions: byteplus extensions: cerebras extensions: clawrouter Extension: clawrouter extensions: clickclack extensions: copilot-proxy Extension: copilot-proxy extensions: crabbox extensions: deepgram extensions: deepinfra extensions: deepseek extensions: diagnostics-otel Extension: diagnostics-otel extensions: diagnostics-prometheus extensions: document-extract extensions: duckduckgo extensions: featherless extensions: gmi extensions: llama-cpp extensions: llm-task Extension: llm-task extensions: lobster Extension: lobster extensions: memory-core Extension: memory-core extensions: memory-lancedb Extension: memory-lancedb extensions: memory-wiki extensions: oc-path extensions: onepassword 1Password plugin extensions: policy extensions: qa-lab extensions: stepfun extensions: tencent extensions: tokenjuice Changes to the bundled tokenjuice extension extensions: vault Extension: vault extensions: web-readability extensions: webhooks gateway Gateway runtime P2 Normal backlog priority with limited blast radius. plugin: azure-speech Azure Speech plugin plugin: beam Beam session sharing plugin plugin: bonjour Plugin integration: bonjour plugin: cua-computer plugin: file-transfer plugin: geolocation Geolocation plugin (IP to coarse city) plugin: google-meet plugin: imap plugin: linux-node plugin: logbook Logbook automatic work journal plugin plugin: migrate-claude plugin: migrate-hermes plugin: mxc plugin: pixverse plugin: team-reports plugin: teams-meetings Teams Meetings plugin plugin: visitor-access plugin: workboard plugin: zoom Zoom plugin proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts security Security documentation size: S 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