Skip to content

fix(agents): deliver final answers that end a response before more same-input work - #164803

Closed
obviyus wants to merge 7 commits into
mainfrom
draft/seal-tail-answers
Closed

obviyus wants to merge 7 commits into
mainfrom
draft/seal-tail-answers

Conversation

@obviyus

@obviyus obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

Draft for discussion, stacked on #164774. Not for landing. The commit is a minimal sketch so the trade-off can be read against real code; it needs a maintainer decision before any review or CI work.

Question

When one model response ends in a completed final_answer and the model then keeps working on the same input (async tool results arrive, it calls more tools, and it writes a new answer), should OpenClaw deliver the earlier answer as well?

Two real occurrences (our setup, openai/gpt-6-astra over openai-responses, Telegram)

  1. Follow-up is NO_REPLY. One response: async web_search, commentary + sessions_yield, async web_fetch, then final_answer with the full answer. The follow-up after the async results was NO_REPLY. On main the answer is lost and the user gets "⚠️ Agent couldn't generate a response". fix(agents): Astra answer dropped for a generic warning when its follow-up is NO_REPLY #164774 fixes this one.
  2. Follow-up does more work and answers again. One response: async view_image, async process, then final_answer with the main answer and a link to an official document. The follow-up response polled again, read an image (async), and produced an empty final_answer tail. The next response wrote a short new answer that reads as if the first had been seen ("Here's the official close-up…"). Only the second answer reached the user; the link was lost. fix(agents): Astra answer dropped for a generic warning when its follow-up is NO_REPLY #164774 does not change this; it is listed there under "Not changed".

Both have the same transcript shape: a call-free tail fragment of a split async response whose text is phase: final_answer.

Why the current behavior exists (#141444)

Fixes an issue where users received a burst of obsolete intermediate answers at the end of a tool-using conversation when a before_agent_finalize hook deferred delivery. Earlier answers could still be sent after a newer accepted answer or terminal NO_REPLY.

It records which message blocks belong to tool continuations, including normal-stop tails of async responses, and supersedes only their older text.

docs/concepts/streaming.md (from #141444): "A later answer supersedes deferred text from earlier tool turns, including when the final answer is NO_REPLY." Related: #149925 ("Final answers still replace progress within one input; silent answers do not leak progress"), #150539, and #152786 (text written beside the last tool call is not promoted; recovery uses the tool-free finalizer).

The trade-off

Supersede (today) Deliver sealed answers (this draft)
Model corrects itself after the async results User sees only the correction. User sees the first answer, then the correction as a second message.
Model builds on its earlier answer (occurrence 2) User loses context the model believes they saw. Later replies refer to things the user never got. User gets both, in order. This matches what the model wrote.
Exact repeat Once. Once (the earlier seal is dropped and the repeat is delivered at its later position).
NO_REPLY follow-up (occurrence 1) Fixed by #164774. Same outcome without the payload special case: the sealed answer is delivered and NO_REPLY adds nothing.

Codex (../codex c248f6d48b) does the second. A non-commentary message item is finalized and shown when it completes (codex-rs/core/src/stream_events_utils.rs:383-397). Any tool call still sets needs_follow_up and the turn samples again (:356; session/turn.rs:2780, :566, :653), so nothing the model said is retracted. Codex's next-turn deferral (stream_events_utils.rs:122-135, session/input_queue.rs:275-296) applies only to inter-agent mailbox mail, not to tool results.

#141444's scenarios under this draft

  • Answers written beside an async call (text + toolCall in one message, with stop toolUse or stop), followed by a terminal answer or NO_REPLY: unchanged, still superseded. Only a call-free phase: final_answer message with stopReason: stop is sealed. Text in a message that carries a call is progress.
  • Completed answers to earlier user inputs: unchanged (user-boundary segments).
  • Deferred media with an obsolete caption (a call-free final_answer with media, then commentary, then the final answer): intended change for real async tails. After fix(agents): Astra answer dropped for a generic warning when its follow-up is NO_REPLY #164774 that message has stopReason: stop, so its caption is a completed answer and is delivered with the media. The model wrote it as the answer. fix(agents): stop replaying obsolete replies after tool continuations #141444's fixture uses stopReason: toolUse, which is not sealed.
  • Deferred prefix extended by the final text: unchanged (the prefix message is toolUse and has no phase).
  • Commentary before a call: unchanged, never delivered.

Sketch (this commit)

  • At the next assistant message_start, a previous message that is stop, phase: final_answer, call-free, with visible non-silent text is pushed as a fix(agents): deliver one answer per steered user input #149925 answer segment marked continued (no new state store). An exact repeat at a later message_end pops the seal.
  • payloads.ts keeps one rule: segments are answers. continued segments do not get precedingInputAnswer, so voice consult and transcript-truncation recovery treat them as the current input's answer. fix(agents): Astra answer dropped for a generic warning when its follow-up is NO_REPLY #164774's inputAnswer/answerStands special case goes away.
  • settled-turn-finalization.ts keeps the current input's delivery floor at the last user-boundary segment.
  • Deferred release (reply-delivery.ts) is unchanged: segment boundaries already protect sealed answers from supersession.

Sketch-level evidence only. Through the real Responses → runAgentLoop → subscriber → block pipeline → payload path, both occurrence shapes deliver both answers once, an exact repeat is delivered once, commentary or text beside a call is not delivered, and #141444's beside-a-call cases are still superseded. A live Telegram Test Server run with real gpt-6-astra for occurrence 2's shape (fetch, answer without waiting, then fetch again and write a new message) showed a progress draft, then the first answer, then the second answer, with the draft deleted and no warning.

Decision needed

Should a completed final_answer that ended its model response be delivered when the model keeps working on the same input? If yes, this replaces #164774's payload special case and partly reverses #141444 for call-free async tails. If no, close this draft and keep #164774 as is.

@clawsweeper

clawsweeper Bot commented Oct 4, 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: M labels Oct 4, 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. 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: 🦐 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 4, 2026
@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 5, 2026, 2:31 AM ET / 06:31 UTC (Revision 2).

ClawSweeper review

What this changes

The branch preserves completed answers across further work on the same input and changes streamed-answer matching so those answers can reach channels in order.

Merge readiness

⛔ Blocked before merge - 5 items remain

Keep this draft open for the requested delivery-policy decision. Its distinct behavior remains absent from main, and the unchanged head still contains the prior cross-input defect plus another concrete delivery-suppression defect.

Priority: P2
Reviewed head: 6df0fb46a268e3f9f4e5f2390dff7ed2701b8310
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The live delivery evidence is useful, but two concrete boundary defects limit implementation readiness.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured body records a real-provider Telegram Test Server run through the changed answer-segmentation and delivery path, observing both answers in order and draft cleanup without a warning. That proves the intended visible scenario, while steering and failed-delivery cases remain correctness gaps. No stored-data contract changes.
Patch quality 🦐 gold shrimp (3/6) 2 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured body records a real-provider Telegram Test Server run through the changed answer-segmentation and delivery path, observing both answers in order and draft cleanup without a warning. That proves the intended visible scenario, while steering and failed-delivery cases remain correctness gaps. No stored-data contract changes.
Evidence reviewed 9 items Pinned introduced change: Reviewed the merge-base-to-head delta, including production changes and the Responses-to-delivery regression table. The checkout is the original head, not a synthetic merge; no pinned test merge is available.
Prior blocker remains: The prior review assessed this exact head. Continued segments permanently skip preceding-input metadata, while the user-message handler appends a boundary without reclassifying them. Voice consult filters by that metadata, and channel transcript recovery also consumes it.
Cross-message matching defect: The introduced backward scan crosses physical assistant-message boundaries. Filtering its combined groups to delivered attempts can let an earlier delivered message cover a later failed message. Current main has an explicit regression for retrying a later unsent answer with matching earlier text.
Findings 2 actionable findings [P2] Reclassify continued answers after a new user input
[P2] Bound streamed-item matching to its physical message
Security None None.

How this fits together

The agent runtime turns model responses and asynchronous tool results into answer segments. Reply construction and channel delivery consume those segments to select, order, and deduplicate outgoing answers.

flowchart TD
  A[User input] --> B[Model response and tools]
  B --> C[Assistant message subscriber]
  C --> D[Answer segments]
  D --> E[Reply payload selection]
  E --> F[Streamed reply matching]
  F --> G[Channel messages]
Loading

Decision needed

Question Recommendation
Should completed call-free final answers remain deliverable when subsequent work on the same input produces a different answer? Retain current supersession: Keep the merged silent-continuation repair and let a later substantive answer replace the earlier answer.

Why: The draft intentionally changes an established delivery policy, trading suppression of obsolete answers for preservation of context the model assumes was delivered.

Before merge

  • Reclassify continued answers after a new user input (P2) - When input A seals an answer and continues before input B arrives, the user-message handler adds a normal boundary but leaves A's earlier segments marked continued. This loop therefore omits precedingInputAnswer from A's answer even though B is current. Voice consult filters earlier answers using that metadata, so it can speak A's answer as part of B's result; transcript-backed channel recovery also loses its earlier-input protection. Classify segments relative to the latest user boundary. This prior finding remains unchanged at the reviewed head.
  • Bound streamed-item matching to its physical message (P2) - The backward scan can include attempts from an earlier assistant message. If index 0 delivered Done. and a separate index 1 attempt for Done. failed before delivery, hasSentPayload filters the combined group to the delivered index 0 attempt and incorrectly treats index 1's final payload as sent, suppressing its retry. Preserve physical-message start boundaries when combining item attempts. This is a late discovery on code unchanged since the prior reviewed head.
  • Resolve merge risk (P1) - Delivering sealed same-input answers changes the existing supersession policy: users may receive an answer and then its correction, including an earlier caption alongside retained media. This tradeoff has not been approved.
  • Complete next step (P2) - Obtain the sealed-answer policy decision; if approved, resolve both findings, align the documentation, and reconcile the current merge conflicts before landing.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P2] Reclassify continued answers after a new user input — src/agents/embedded-agent-runner/run/payloads.ts:353-355
  • [P2] Bound streamed-item matching to its physical message — src/auto-reply/reply/block-reply-pipeline.ts:361-367
Agent review details

Security

None.

PR surface

Source +63, Tests +342. Total +405 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 6 69 6 +63
Tests 1 342 0 +342
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 411 6 +405

Review metrics

Metric Value Why it matters
Production and regression growth production +63 net lines; tests +342 lines The production growth reuses answer segments rather than adding a state owner, while the regression table exercises the composed Responses-to-delivery path.

Merge-risk options

Maintainer options:

  1. Keep the existing delivery contract (recommended)
    Pause this sketch while retaining main's merged silent-follow-up repair and current supersession behavior.
  2. Approve and complete the policy change
    Explicitly accept delivering superseded completed answers, then repair input classification and message-bounded matching before landing.

Technical review

Best possible solution:

Preserve main's supersession contract unless maintainers approve delivering both answers; an approved implementation should retain user-input identity and physical-message delivery boundaries.

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

Yes, source establishes both patch defects: continue input A before steering input B, or fail delivery of a later answer whose text matches an earlier delivered message. No target code or tests were executed during this read-only review.

Is this the best way to solve the issue?

No, the sketch is not ready as written: it conflates continuation history with current-input identity and matches delivery across physical messages. Main already provides the narrower silent-follow-up fix.

Full review comments:

  • [P2] Reclassify continued answers after a new user input — src/agents/embedded-agent-runner/run/payloads.ts:353-355
    When input A seals an answer and continues before input B arrives, the user-message handler adds a normal boundary but leaves A's earlier segments marked continued. This loop therefore omits precedingInputAnswer from A's answer even though B is current. Voice consult filters earlier answers using that metadata, so it can speak A's answer as part of B's result; transcript-backed channel recovery also loses its earlier-input protection. Classify segments relative to the latest user boundary. This prior finding remains unchanged at the reviewed head.
    Confidence: 0.99
  • [P2] Bound streamed-item matching to its physical message — src/auto-reply/reply/block-reply-pipeline.ts:361-367
    The backward scan can include attempts from an earlier assistant message. If index 0 delivered Done. and a separate index 1 attempt for Done. failed before delivery, hasSentPayload filters the combined group to the delivered index 0 attempt and incorrectly treats index 1's final payload as sent, suppressing its retry. Preserve physical-message start boundaries when combining item attempts. This is a late discovery on code unchanged since the prior reviewed head.
    Confidence: 0.99
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded delivery-policy proposal with concrete boundary defects, without evidence of an urgent current-main regression.
  • merge-risk: 🚨 message-delivery: The proposed policy can expose superseded answers, and the introduced matching logic can suppress a later unsent answer.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The captured body records a real-provider Telegram Test Server run through the changed answer-segmentation and delivery path, observing both answers in order and draft cleanup without a warning. That proves the intended visible scenario, while steering and failed-delivery cases remain correctness gaps. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured body records a real-provider Telegram Test Server run through the changed answer-segmentation and delivery path, observing both answers in order and draft cleanup without a warning. That proves the intended visible scenario, while steering and failed-delivery cases remain correctness gaps. No stored-data contract changes.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The policy changes how many persistent Telegram answers users receive; the recorded Test Server run demonstrates the basic two-answer scenario.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head delta, including production changes and the Responses-to-delivery regression table. The checkout is the original head, not a synthetic merge; no pinned test merge is available. (6df0fb46a268)
  • Prior blocker remains: The prior review assessed this exact head. Continued segments permanently skip preceding-input metadata, while the user-message handler appends a boundary without reclassifying them. Voice consult filters by that metadata, and channel transcript recovery also consumes it. (src/agents/embedded-agent-runner/run/payloads.ts:354, 6df0fb46a268)
  • Cross-message matching defect: The introduced backward scan crosses physical assistant-message boundaries. Filtering its combined groups to delivered attempts can let an earlier delivered message cover a later failed message. Current main has an explicit regression for retrying a later unsent answer with matching earlier text. (src/auto-reply/reply/block-reply-pipeline.ts:363, 6df0fb46a268)
  • Current-main sibling fix: fix(agents): Astra answer dropped for a generic warning when its follow-up is NO_REPLY #164774 merged as 83e6cb9. Main preserves completed answers before silent continuations but still supersedes them when a later answer arrives. It also bounds streamed-item matching by physical message start. This fixes overlapping cases, not this draft's central policy proposal. (src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts:117, d7f9ebd8de66)
  • Existing delivery contract: Streaming documentation describes superseding deferred text from earlier tool turns while preserving completed answers to earlier user inputs. The draft explicitly proposes changing that contract for call-free completed tails; no approving human discussion or review is present. Public docs: docs/concepts/streaming.md. (docs/concepts/streaming.md:83, d7f9ebd8de66)
  • Recorded real behavior: The captured PR body, sourceRevision ebe8c943d37a2330108645b11510440e7dd03df6d0ee4546e77a1d8ae73c2d84, reports a real-provider Telegram Test Server run through an isolated setup: asynchronous fetch, completed answer, further fetch, then a second answer. It records both persistent answers in order, progress-draft deletion, and no warning. The three downloaded screenshots were inspected; they belong to the related recovery PR and do not demonstrate this draft's two-answer scenario.

Likely related people:

  • obviyus: 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)

Rank-up moves

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

  • Preserve earlier-input metadata for all segments before the latest user boundary and add the continued-answer-then-steered-input regression.
  • Bound streamed-item matching by physical message and cover a failed later send matching an earlier delivered answer.
  • If the policy is approved, align streaming documentation with that decision.

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 (1 earlier review cycle)
  • reviewed 2026-10-04T06:35:27.280Z sha 6df0fb4 :: blocked before merge. :: [P2] [P2] Reclassify continued answers when a new user input begins

@obviyus
obviyus force-pushed the fix/dropped-final-answer branch from 25dc7e4 to 69b4a7b Compare October 4, 2026 13:14
Base automatically changed from fix/dropped-final-answer to main October 5, 2026 06:25
@obviyus

obviyus commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: design C (deliver every response-ending answer) was not pursued. #164774 covers the dropped-answer case that motivated it.

@obviyus obviyus closed this Oct 6, 2026
@RomneyDa
RomneyDa deleted the draft/seal-tail-answers branch October 22, 2026 03:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant