Repository navigation
fix(acp): preserve complete answers after tool commentary - #168201
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis 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.”
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +111, Tests +505, Docs +14. Total +630 across 13 files. Added test files: 3. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (8 earlier review cycles)
Reviewed October 10, 2026, 7:48 AM ET / 11:48 UTC (Revision 9). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Yigtwxx
left a comment
There was a problem hiding this comment.
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.
| sessionUpdate: "agent_message_chunk", | ||
| content: { | ||
| type: "text", | ||
| text: preceding && delta ? `${preceding}\n\n${delta}` : preceding + delta, |
There was a problem hiding this comment.
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", ""), |
There was a problem hiding this comment.
.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` |
There was a problem hiding this comment.
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.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
…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
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]>
…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]>
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
afb4f0ff366b2003977662d1b73e58dfb5b9c897: native Ollamaqwen3:8bthrough the realpnpm openclaw --profile acp-commentary acpbridge and isolated Gateway. The model narrated “I will read the sample now.”, calledread, 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.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 bothorchidandviolet; its complete answer matches the Gateway final snapshot byte-for-byte. The captured wire carriespreamble: { retainedText: "" }. The model emitted one narration and batched the two reads; deterministic tests cover two separately narrated rounds.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).9fc2c8d13ecc015bd1d67320dfce60ca144c608bis 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.9fc2c8d13ecc015bd1d67320dfce60ca144c608bwith no findings and no Before merge items, confirming both previous findings are resolved (review).The additional failures are in
ui/src/e2e/mobile-shell-geometry.e2e.test.ts, all atexpectReachableActionline 101 (bounds.y + bounds.height <= visibleBottom):The known failures in
ui/src/e2e/chat-github-publication-guest.e2e.test.tsarepublishes an owned guest session through the shared account and recovers its receiptandwaits 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/updateframes, 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 buildpreviously 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
afe236fe89871a0adaecdfc5615dfa77e48c1bbemergesorigin/mainat0aee279a71af78b8914dced0507ddb94c0d1f5b0, 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.