Skip to content

fix(acp): preserve complete answers after tool commentary - #168201

Merged
steipete merged 9 commits into
mainfrom
fix/acp-pre-tool-commentary
Oct 10, 2026
Merged

steipete merged 9 commits into
mainfrom
fix/acp-pre-tool-commentary

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #167837

What Problem This Solves

Fixes missing or truncated final answers in ACP clients after assistant narration is reclassified as pre-tool commentary.

User Impact

ACP clients retain commentary once, in order, and receive the complete final answer after that reclassification. This requires an updated Gateway and bridge. Existing clients can ignore the optional metadata; channel reply policy, configuration, storage, and the protocol version are unchanged.

Why This Change Was Made

The Gateway already owns the retained-answer projection. It now carries that fact in optional preamble metadata, preserving it through transport coalescing. ACP uses it to retire narration from its answer baseline and deduplicates preambles by item ID. Generic provider snapshots are scoped to their original commentary IDs; when several items share an already displayed preview, ACP carries that preview credit across the identities. Ordinary final retirement keeps its existing behavior. Distinct preamble items receive a separator while incremental updates and already delivered preview bytes remain intact.

Production +177/-66 (net +111); tests +505/-0; docs +14/-0. The production growth carries the protocol fact and necessary item/preview accounting; redundant callback plumbing and timing-based reconstruction were removed. No model-facing prompt or tool text changed.

Evidence

  • Live before, baseline afb4f0ff366b2003977662d1b73e58dfb5b9c897: native Ollama qwen3:8b through the real pnpm openclaw --profile acp-commentary acp bridge and isolated Gateway. The model narrated “I will read the sample now.”, called read, then answered “The sample value is orchid.” ACP dropped the final answer. A two-read run lost the first 26 characters of a longer answer.
  • Live after, head 33e53e953149046d9d6304158d3d63efa5b856a6: the one-read run delivers that narration once, the real tool start/result, and the complete “The sample value is orchid.” answer. A thinking-enabled two-read run returns both orchid and violet; its complete answer matches the Gateway final snapshot byte-for-byte. The captured wire carries preamble: { retainedText: "" }. The model emitted one narration and batched the two reads; deterministic tests cover two separately narrated rounds.
  • Regressions: shorter/longer finals, multiple narrated rounds, either chat/raw arrival order, delayed projections, retained answer prefixes, item echoes, identical text under distinct IDs, legacy events, and Gateway pacing/coalescing. Original cases failed on main. ClawSweeper's cumulative generic-commentary finding failed through the producer → Gateway → ACP composition before repair; a second failing composition caught batched preview replay.
  • Final focused run: 29 tests passed across both ACP commentary files and both agent commentary/stream-phase siblings, in 1,027.73 s wall time with one worker and isolation. Test execution: new producer composition file 4.16 s, ACP commentary file 19.66 s; shared worker preparation and collection dominate wall time. The tests use existing in-process fixtures and fake clocks, with no per-test Gateway boots or sleeps. Final-snapshot, replay, approval, and Gateway projection/schema/coalescing suites also passed during validation.
  • Checks: full final check:changed, production/test typechecks, touched-file lint, required ratchets/inventories, formatting, and diff sanity passed. Protocol JSON/Swift/Kotlin outputs were regenerated and compatibility checks passed; generated files are ignored build artifacts. The final Gateway/QA runtime build passed in 868.77 s wall time (10m40s measured build phases).
  • Current follow-up: exact-output separator regression failed before repair; 15 ACP tests passed in 159.23 s wall time after repair. Targeted lint/format, production types (88.47 s), ACP test types (25.58 s), and all seven required ratchets/inventories passed. Fresh Codex autoreview of committed head 9fc2c8d13ecc015bd1d67320dfce60ca144c608b is scoped-clean through P2 (confidence 0.83). The follow-up also clarifies that empty preamble metadata carries no new retirement projection on that event; earlier credit may still apply.
  • Review: ClawSweeper reviewed exact head 9fc2c8d13ecc015bd1d67320dfce60ca144c608b with no findings and no Before merge items, confirming both previous findings are resolved (review).
  • CI: Exact-head run 38047971532 completed with 47 passed, 21 skipped, 3 failed, 0 cancelled. The failed jobs are UI E2E shards 2/4 and 3/4 plus the aggregate gate. Failed logs were fetched once. In addition to the known guest-publication failures, four mobile-shell geometry tests failed; these additional failures block readiness under the current scoped CI exception. No UI files are changed by this PR.

The additional failures are in ui/src/e2e/mobile-shell-geometry.e2e.test.ts, all at expectReachableAction line 101 (bounds.y + bounds.height <= visibleBottom):

Test Expected maximum Actual
keeps desktop-zero routes and controls in one usable canvas 142 159
keeps landscape-zero routes and controls in one usable canvas 150 173
keeps compact-landscape routes and controls in one usable canvas 150 175
keeps standalone-landscape-contract routes and controls in one usable canvas 150 173

The known failures in ui/src/e2e/chat-github-publication-guest.e2e.test.ts are publishes an owned guest session through the shared account and recovers its receipt and waits for an available publication target (managed workspace: true). Both expected one Publish PR button and found zero (lines 142 and 211).

The live proof client initializes ACP over stdio, creates a session, sends a prompt, records session/update frames, and compares text after the final tool result with the real Gateway final snapshot. It uses isolated state and port 19267 with supported Node 24.19.0.

Known limitation: an additional no-thinking two-file attempt made only one real tool call, then the Gateway replaced ordinary answer text without a preamble event. ACP still lost that replacement tail. This PR fixes commentary reclassification; general non-preamble answer replacement remains a follow-up and is not counted as passing proof.

Validation tooling notes: the full local pnpm build previously stalled at package declarations, so the supported Gateway/QA runtime build supplied the live executable. One combined agent test run stalled without completed cases. A diagnostic attempt failed before collection when concurrent lint created a temporary root config; the final serialized isolated run passed. The final typecheck also caught a test mock typing mismatch, which was corrected before publication.

Main integration follow-up

Head afe236fe89871a0adaecdfc5615dfa77e48c1bbe merges origin/main at 0aee279a71af78b8914dced0507ddb94c0d1f5b0, including the Kysely guard fix (db6449d3f609) and recovery/fallback-fixture fix (#167814). No ACP patch changes or manual conflict resolutions were needed. Dependency/Gateway profile setup passed. Fresh targeted formatting, lint, ratchets, config-doc and plugin-inventory checks passed (247.51 seconds combined); all 47 focused tests across eight ACP/Gateway/agent files passed in 209.11 seconds wall time. Tests used one worker and isolation. Prior live proof remains evidence for the unchanged ACP patch at the explicitly recorded earlier head.

@clawsweeper

clawsweeper Bot commented Oct 10, 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 app: web-ui App: web-ui gateway Gateway runtime size: L labels Oct 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR preserves commentary once and delivers complete ACP answers when the Gateway reclassifies streamed narration before tool calls.

Example: The assistant says “I will read the sample now.”, calls read, and answers “The sample value is orchid.”

  • Before: ACP can retain the narration as its answer cursor and drop the shorter final answer.
  • After: ACP retains the narration once and delivers the complete orchid answer after the tool result.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, coherent repair with supplied shipped-entry-point evidence, meaningful boundary coverage, and no actionable findings; live evidence predates the small separator follow-up.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Supplied native Ollama runs exercise the real ACP stdio bridge and isolated Gateway, showing complete final answers after commentary retirement at 33e53e9; the later separator change is covered by exact-output production-composition regressions, and no new live run is claimed.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: ACP users can miss narration and receive missing or truncated final answers after tool commentary.
Reason: The patch repairs demonstrated existing behavior using the established projection owner and introduces no configuration or policy choice.

Merge readiness

✅ Ready for maintainer review

Keep this PR: it repairs a demonstrated ACP delivery bug still present on current main, and the earlier findings are resolved; failed exact-head CI still prevents a clean landing verdict.

Priority: P2
Reviewed head: 9fc2c8d13ecc015bd1d67320dfce60ca144c608b

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded subscriber identifies commentary, the Gateway publishes its retained-answer projection, and the ACP bridge translates those events into append-only client updates.

flowchart TD
  A[Provider assistant output] --> B[Embedded subscriber]
  B --> C[Gateway answer projection]
  C --> D[Paced agent and chat events]
  D --> E[ACP commentary accounting]
  E --> F[ACP client updates]
Loading

Technical review

Best possible solution:

Land the Gateway-owned projection and ACP accounting repair through the native CI workflow while keeping general non-preamble answer replacement separate.

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

Current-main source exposes the ignored preamble stream and length-based answer cursor, consistent with the supplied live before/after reproduction; this review executed no target code.

Is this the best way to solve the issue?

The repair uses the existing Gateway projection owner, preserves commentary identities at the producer, and maintains ACP's append-only contract without changing configuration or channel reply policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • ACP event translation and answer cursor changes intended behavior with a stated reason (7cf4f9a: This commit mechanically split the translator while preserving behavior; it does not establish the filter's original introduction. Reading its parent translator blob failed with bad object.)
  • Generic commentary identity and completion keeps the original intent (fb598bd: Preserve one stable identity per commentary segment so live and durable output reconcile without duplication; completion delivery was subsequently retained by a2bbcbf.)
  • Prepared generic commentary extraction changes intended behavior with a stated reason (93ad954: Reuse cumulative commentary extraction within an update; this PR explains why independently identified commentary items now require scoped extraction.)
  • Gateway paced text delivery keeps the original intent (2f58ead: Coalesce append deltas while retaining recovery snapshots and ordering; the patch preserves the new retirement fact through that existing transport owner.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 0320297 adds src/agents/embedded-agent-subscribe.handlers.messages.stream.ts:190 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0320297d7a15; files: src/agents/embedded-agent-subscribe.handlers.messages.stream.ts)
  • pash-openai: Raw commit a2bbcbf adds src/agents/embedded-agent-subscribe.handlers.messages.stream.ts:238 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: a2bbcbf40684; files: src/agents/embedded-agent-subscribe.handlers.messages.stream.ts)

PR surface

Source +111, Tests +505, Docs +14. Total +630 across 13 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 8 177 66 +111
Tests 3 505 0 +505
Docs 2 14 0 +14
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 696 66 +630

Review metrics

Metric Value Why it matters
Production versus test LOC Production +177/-66; tests +505/-0. Production growth carries the wire projection and per-item preview accounting; tests protect distinct producer, transport-coalescing, and ACP delivery contracts.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The bug loses or truncates ACP text during tool-heavy turns, with a bounded client-delivery scope.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

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

Workflow

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

History

Review history (8 earlier review cycles)
  • reviewed 2026-10-10T04:51:55.320Z sha 0c2795e :: needs changes before merge. :: [P2] Scope generic commentary before deduplicating by item ID
  • reviewed 2026-10-10T05:21:33.697Z sha 0c2795e :: needs changes before merge. :: [P2] Scope generic commentary before deduplicating by item ID
  • reviewed 2026-10-10T08:08:53.288Z sha 33e53e9 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T08:34:42.379Z sha 33e53e9 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T10:09:41.541Z sha 33e53e9 :: needs changes before merge. :: [P2] [P2] Preserve separators between consecutive narration items | [P3] [P3] Describe empty preamble metadata without denying prior preview coverage
  • reviewed 2026-10-10T10:40:44.114Z sha afe236f :: needs changes before merge. :: [P2] Preserve separators between consecutive narration items | [P3] Describe empty metadata without denying prior preview coverage
  • reviewed 2026-10-10T10:45:14.842Z sha afe236f :: needs changes before merge. :: [P2] Preserve separators between consecutive narration items | [P3] Describe empty metadata without denying prior preview coverage
  • reviewed 2026-10-10T11:23:34.884Z sha 9fc2c8d :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 7:48 AM ET / 11:48 UTC (Revision 9).

@steipete
steipete marked this pull request as ready for review October 10, 2026 05:15
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Oct 10, 2026
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor 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. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The retained-answer rebase reads correctly to me; I walked the held-replacement and paced-chat orderings and couldn't make the answer cursor drift. The notes below are all about several commentary items inside one assistant message.

Comment thread src/acp/translator.agent-events.ts Outdated
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: preceding && delta ? `${preceding}\n\n${delta}` : preceding + delta,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When one assistant message carries several narration blocks (text, tool_use, text, tool_use), each block arrives here as a new item with no retirement, and since tools only start after message_end, no tool_call update lands between them. Each delta goes out raw, so the client gets "Checking files.", "Reading config.", "Checking files." as consecutive chunks and renders Checking files.Reading config.Checking files.. The batched-preview path doesn't glue them because those separators come from the chat preview, so the two paths render differently. Could a fresh item's first delta get a \n\n prefix when a message chunk was already emitted since the last tool_call? A flag on pending, set on any message chunk and cleared on tool start, would mirror how preceding is joined here.

update.sessionUpdate === "agent_message_chunk" ? [update.content.text] : [],
)
.join("")
.replaceAll("\n", ""),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.replaceAll("\n", "") makes this pass whether or not the narration items are separated. In the non-batched case the real chunks have no newlines at all, and the batched case only differs by newlines. Asserting the exact chunk list for both cases would pin the separator behavior down instead of hiding it.

Canonical `agent` events with `stream: "item"` and `data.kind: "preamble"`
include optional `preamble` metadata. When the item replaces a live preview,
`preamble.retainedText` supplies the producer's remaining answer projection,
including an empty string when no answer prefix remains. An empty `preamble`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't quite match the producer. Only the first commentary emission that retires the preview gets assistantProjection; later items from the same retired preview, and repeated end snapshots, go out with preamble: {}. An append-only client following this sentence would treat items 2..n of a batched preview as never previewed and print them twice (ACP avoids it only via its preamblePreview credit). Maybe: "an empty object means this event carries no retirement; items already covered by an earlier retirement also arrive with an empty object", plus a line on how clients should credit them.

@steipete steipete added the ci:no-fail-fast Keep all selected CI matrix jobs running after failures on the next PR run. label Oct 10, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@steipete steipete self-assigned this Oct 10, 2026
@steipete
steipete merged commit 34128f1 into main Oct 10, 2026
140 of 145 checks passed
@steipete
steipete deleted the fix/acp-pre-tool-commentary branch October 10, 2026 11:50
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…68201)

* fix(acp): preserve complete answers after tool commentary

* fix(acp): reconcile deferred commentary projections

* fix(acp): preserve retained prefixes in deferred commentary

* fix(acp): consume Gateway-owned preamble projections

* fix(acp): retain preamble projections during coalescing

* fix(acp): preserve commentary identities across cumulative snapshots

* test(acp): align commentary request mock with prompt harness

* fix(acp): preserve boundaries between narration items
steipete added a commit that referenced this pull request Oct 11, 2026
Related: #167888, #168201

Remove heuristic retroactive commentary/final phase inference so streamed answer text stays append-only across tools and reasoning. Preserve explicit OpenAI Responses phases and Harmony channels, canonical empty replies, and the shipped optional SDK field. Final channel reply selection remains with the existing payload owner.

Intentional terminal-tool completion now derives from settled successful tool-batch evidence independently of payload count, preserving pre-tool narration instead of returning an incomplete-turn error.

Thanks to @laulopezreal for the same-item rewrite regression from #167888, adapted with current preamble metadata and credited in the commit.

Thanks to @Yigtwxx for identifying narrated terminating tools becoming incomplete turns.

Validation: fresh isolated autoreview and exact-head ClawSweeper found no actionable issues; CI run 38164947634 passed all 54 successful jobs and openclaw/ci-gate. Five provider regressions failed before the terminal repair and pass afterward; 105 focused and 45 settlement/finalization tests passed. Recorded live ACP/Ollama and QA-channel runs preserve complete replies, with current-head native Ollama ACP proof preserving terminal-tool narration and returning end_turn. Telegram Test Server was not exercised.

Co-authored-by: Laura López Real <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…69020)

Related: openclaw#167888, openclaw#168201

Remove heuristic retroactive commentary/final phase inference so streamed answer text stays append-only across tools and reasoning. Preserve explicit OpenAI Responses phases and Harmony channels, canonical empty replies, and the shipped optional SDK field. Final channel reply selection remains with the existing payload owner.

Intentional terminal-tool completion now derives from settled successful tool-batch evidence independently of payload count, preserving pre-tool narration instead of returning an incomplete-turn error.

Thanks to @laulopezreal for the same-item rewrite regression from openclaw#167888, adapted with current preamble metadata and credited in the commit.

Thanks to @Yigtwxx for identifying narrated terminating tools becoming incomplete turns.

Validation: fresh isolated autoreview and exact-head ClawSweeper found no actionable issues; CI run 38164947634 passed all 54 successful jobs and openclaw/ci-gate. Five provider regressions failed before the terminal repair and pass afterward; 105 focused and 45 settlement/finalization tests passed. Recorded live ACP/Ollama and QA-channel runs preserve complete replies, with current-head native Ollama ACP proof preserving terminal-tool narration and returning end_turn. Telegram Test Server was not exercised.

Co-authored-by: Laura López Real <[email protected]>
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: web-ui App: web-ui ci:no-fail-fast Keep all selected CI matrix jobs running after failures on the next PR run. docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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