Repository navigation
fix(agents): deliver token-limited partial replies instead of discarding them - #123546
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 15, 2026, 3:31 PM ET / 19:31 UTC. ClawSweeper reviewWhat this changesThe PR delivers visible embedded-agent text stopped by a model output limit, adds a truncation notice, and records the partial reply as replayable success. Regression provenancePossible regression — probable (reviewed change; failure trace). No predecessor PR is attributed. Merge readinessKeep this PR open for normal maintainer merge handling: current main and the latest release still discard this class of reply, while the exact head resolves the delivery, replay, and trajectory disagreement with no remaining code finding. Priority: P1 Review scores
Verification
How this fits togetherEmbedded-agent runs convert terminal model messages into reply payloads, lifecycle events, and durable trajectory state. A token-limit stop passes through classification before payload delivery, with its result later used for session replay and diagnostics. flowchart LR
A[Model reaches output limit] --> B[Terminal turn classification]
B --> C[Payload preparation]
C --> D[Partial reply and notice]
B --> E[Lifecycle replay state]
E --> F[Trajectory record]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +54, Tests +233. Total +287 across 11 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Merge the narrow phase-local repair after exact-head CI is green; keep the separate checks because a shared post-payload predicate would misclassify the earlier lifecycle and trajectory phases. Do we have a high-confidence way to reproduce the issue? Yes in source: current main classifies a length-stopped reply as incomplete even after visible text exists, and the PR body supplies matching redacted before/after runtime logs. Is this the best way to solve the issue? Yes: the repair updates the owning classification, delivery, lifecycle, and trajectory boundaries rather than adding a downstream fallback; tool-use semantics remain unchanged. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against ab5b8b9a02c8. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (10 earlier review cycles; latest 8 shown)
|
5a951b8 to
4a21c99
Compare
|
Thanks — both findings were correct and both are now fixed in [P2] Restrict the truncation notice to partial text — agreed, this was a real overreach. The notice keyed only on [P2] Align trajectory status with delivered length replies — agreed, and folded in rather than left out of scope. One note on how I aligned it, in case you'd have chosen differently. Rather than keying the trajectory branch on assistant text, I keyed it on Real behavior proof — added to the PR body under Evidence, with the redacted before/after runtime output: the pre-fix I've disclosed the limit of that proof in the body rather than overstating it: the deployment runs a published build, so the observation came from applying the same two edits to the installed bundle of that version, not from running this branch in production. The branch is the source-level port, and the tests are what verify the port. Acceptance criteria — On the earlier red CI: those failures were not from this change. On the +13 net production lines: the predicate is now centralized in the sense that matters — all three boundaries key on the same signals — but they are three separate owners (classification, terminal delivery, trajectory finalization) that receive their evidence from different params, and finalization runs before terminal resolution. Extracting a shared helper would mean threading |
|
CI status after the rebase, for the record: 87 checks pass, 0 test failures. The pre-rebase test failures were the stale base and are gone. One extra commit was needed, The one remaining red check is |
|
@clawsweeper re-review — both findings are addressed ( |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
You were right and my previous fix was wrong — fixed in I keyed the trajectory guard on It now keys on visible assistant text, which is the canonical fact and is already resolved at that boundary via const hasVisibleAssistantOutput =
hasNonEmptyAssistantText(params.assistantTexts) || params.synthesizedPayloadCount > 0;
Test changes, all in
The old "marks length-limited visible text as non-deliverable without terminal output" expectation is replaced by the first of those, which is what you asked for in the original finding. Verified: 12 files / 352 tests pass across |
|
Addressed the remaining finding in f7f6522e3c. You were right that the two boundaries disagreed.
Tool-use behaviour is unchanged: Verified locally: all 59 @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
ddd475b to
c01017f
Compare
|
Rebased onto current main ( Agreed on the net-line reading: the phase-local checks are deliberate, because a shared helper would have to couple the pre-payload lifecycle and trajectory decisions to post-payload delivery facts — which is what caused the original contradiction. |
|
CI on The one red check,
|
|
Maintainer note: all review findings have been addressed. I am updating this PR from c01017f6a614816b06e20f95bd54bb33dc3dc8fd onto current origin/main (8668aeb) to pick up the latest base fixes and prepare exact-head CI for merge. No other action is needed for now. |
c01017f to
21902fd
Compare
…ing them `isIncompleteTerminalAssistantTurn` accepted `hasAssistantVisibleText` but the `length` branch never read it, so a turn that stopped at the output token limit after emitting visible text was classified incomplete. The whole reply was then replaced with "Agent couldn't generate a response" and the run was marked abandoned. Respect the flag: a `length` stop is incomplete only when there is no visible text and no terminal tool output. A length stop that did produce text now delivers that text with a truncation notice appended, so a cut-off answer is not mistaken for a complete one.
Review follow-up on the token-limited partial reply fix. The truncation notice keyed only on stopReason, so a length stop that also produced terminal output (tool media, a committed source reply) gained an extra text reply telling the user to ask for a continuation. Those turns were already complete before this fix, so the notice now uses the same predicate as the classifier: a length stop with no terminal output. resolveAttemptTrajectoryTerminal() also still recorded a delivered partial reply as non_deliverable_terminal_turn, so durable trajectory state contradicted what the user received. It now uses the same payload-count evidence the terminal owner uses, so a length stop is only non-deliverable when nothing was delivered. A length stop with visible text but no synthesized payload stays an error.
…tials handleAgentEnd() no longer marks a length stop with visible text as abandoned and replay-invalid, because that turn is now delivered as a partial reply. The lifecycle test still pinned the old outcome. The sibling case that has pending tool media is unchanged: it still has terminal output, so it stays abandoned.
…d count The previous guard used synthesizedPayloadCount, which does not include ordinary final assistant text: attempt-result.ts computes it from block replies, tool media, source-reply payloads, and silent-tool payloads, and finalization runs before terminal-preparation.ts turns assistant text into payloads. So an ordinary text-only truncated reply — the case this PR exists to fix — still recorded non_deliverable_terminal_turn while the reply was delivered. Key on visible assistant text instead, which is the fact the delivery owner also keys on and is already resolved at finalization. A length stop with nothing visible to show stays non-deliverable, whitespace-only text included.
…gth partials The attempt-finalize table row for a length stop expected finalStatus "error". Its fixture assistant carries visible text, which resolveTerminalAssistantTexts() promotes to terminal assistant text for a length stop, so that row is a delivered partial reply and must now record success. Renamed to say so.
…lity The lifecycle handler derived assistant-visible text only from streamed assistant texts, while terminal payload building falls back to the completed assistant message's visible text when the streamed texts are empty. A non-streamed length stop was therefore delivered to the user and, at the same time, recorded as an abandoned, replay-invalid turn. Give the classifier call site the same canonical fact, keeping the streamed-only view for error and abort stop reasons whose raw text can describe an interrupted generation rather than a reply.
A cron turn can end with a length stop whose only payload is the synthesized silent result of a successful tool. Gating the notice on terminal-state absence alone appended a visible truncation message to that intentionally silent result. Require nonblank assistant text — streamed or from the terminal assistant message — so the notice only labels prose the user actually received. Also drops .rev3.md, a review transcript committed by accident.
21902fd to
9fe47b6
Compare
|
Merge-ready at source HEAD 9fe47b621c275b0f6d87dd6d50eb916cbc987504. Best-fix verdict: this repair sits at the correct classification, delivery, lifecycle, and trajectory owner boundaries. All ClawSweeper findings are addressed; current-head ClawSweeper and local autoreview are clean; the required exact-head CI gate is green after the transient lint-runner shutdown cleared on rerun. Compatibility: no public API, config, environment, plugin SDK, protocol, schema, persistence, dependency, or migration changes. The only intentional behavior change is that token-limited replies containing visible text are delivered with a truncation notice and remain replayable instead of being discarded as an error. Merged as db0d133ec9521edffe9f722551762dce3d1d5783. |
|
Merged via squash.
|
…ing them (openclaw#123546) * fix(agents): deliver token-limited partial replies instead of discarding them `isIncompleteTerminalAssistantTurn` accepted `hasAssistantVisibleText` but the `length` branch never read it, so a turn that stopped at the output token limit after emitting visible text was classified incomplete. The whole reply was then replaced with "Agent couldn't generate a response" and the run was marked abandoned. Respect the flag: a `length` stop is incomplete only when there is no visible text and no terminal tool output. A length stop that did produce text now delivers that text with a truncation notice appended, so a cut-off answer is not mistaken for a complete one. * fix(agents): scope the truncation notice and align trajectory status Review follow-up on the token-limited partial reply fix. The truncation notice keyed only on stopReason, so a length stop that also produced terminal output (tool media, a committed source reply) gained an extra text reply telling the user to ask for a continuation. Those turns were already complete before this fix, so the notice now uses the same predicate as the classifier: a length stop with no terminal output. resolveAttemptTrajectoryTerminal() also still recorded a delivered partial reply as non_deliverable_terminal_turn, so durable trajectory state contradicted what the user received. It now uses the same payload-count evidence the terminal owner uses, so a length stop is only non-deliverable when nothing was delivered. A length stop with visible text but no synthesized payload stays an error. * test(agents): flip the lifecycle expectation for delivered length partials handleAgentEnd() no longer marks a length stop with visible text as abandoned and replay-invalid, because that turn is now delivered as a partial reply. The lifecycle test still pinned the old outcome. The sibling case that has pending tool media is unchanged: it still has terminal output, so it stays abandoned. * fix(agents): key length trajectory status on visible text, not payload count The previous guard used synthesizedPayloadCount, which does not include ordinary final assistant text: attempt-result.ts computes it from block replies, tool media, source-reply payloads, and silent-tool payloads, and finalization runs before terminal-preparation.ts turns assistant text into payloads. So an ordinary text-only truncated reply — the case this PR exists to fix — still recorded non_deliverable_terminal_turn while the reply was delivered. Key on visible assistant text instead, which is the fact the delivery owner also keys on and is already resolved at finalization. A length stop with nothing visible to show stays non-deliverable, whitespace-only text included. * test(agents): flip the finalization trajectory case for delivered length partials The attempt-finalize table row for a length stop expected finalStatus "error". Its fixture assistant carries visible text, which resolveTerminalAssistantTexts() promotes to terminal assistant text for a length stop, so that row is a delivered partial reply and must now record success. Renamed to say so. * fix(agents): use the completed assistant message for lifecycle visibility The lifecycle handler derived assistant-visible text only from streamed assistant texts, while terminal payload building falls back to the completed assistant message's visible text when the streamed texts are empty. A non-streamed length stop was therefore delivered to the user and, at the same time, recorded as an abandoned, replay-invalid turn. Give the classifier call site the same canonical fact, keeping the streamed-only view for error and abort stop reasons whose raw text can describe an interrupted generation rather than a reply. * fix(agents): require partial text before appending the truncation notice A cron turn can end with a length stop whose only payload is the synthesized silent result of a successful tool. Gating the notice on terminal-state absence alone appended a visible truncation message to that intentionally silent result. Require nonblank assistant text — streamed or from the terminal assistant message — so the notice only labels prose the user actually received. Also drops .rev3.md, a review transcript committed by accident.
Related: #94176
Related: #63188
Related: #63210
Related: #119259
What Problem This Solves
Fixes an issue where users whose reply hits the model's output token limit see
⚠️ Agent couldn't generate a response. Please try again.instead of the answerthe model already wrote. Everything the assistant produced in that turn is
thrown away, the run is recorded as
abandoned, and the transcript is markedreplay-invalid — so retrying restarts the work rather than continuing it.
This is worse the more useful the answer was: long answers are exactly the ones
that hit the limit, and they are the ones that get deleted.
Why This Change Was Made
isIncompleteTerminalAssistantTurn()already accepted ahasAssistantVisibleTextparameter and callers already passed it, but the
lengthbranch never read it:So a
lengthstop with visible text and no terminal tool output was classifiedas an incomplete turn, and
resolveIncompleteTurnPayloadText()replaced thepayloads with the failure notice.
A
lengthstop is genuinely different fromtoolUse: no continuation ispending, and whatever text the model emitted is the answer so far. The fix
respects the parameter, so a
lengthstop is incomplete only when there isnothing to show, and
completeEmbeddedRun()appends a one-line truncationnotice to the partial payloads so a cut-off answer is not mistaken for a
complete one.
One predicate now governs all three boundaries — a
lengthstop with noterminal output and nothing delivered:
isIncompleteTerminalAssistantTurn()— classification.completeEmbeddedRun()— the truncation notice.resolveAttemptTrajectoryTerminal()— the durable trajectory record.Scope is deliberately narrow. The only behavior that changes is
stopReason === "length"and visible text and no terminal tool output.toolUseturns are untouched. Turns that already had terminal toolmedia/output were already treated as complete, and they stay complete and
notice-free: the notice is gated on
!hasAttemptTerminalState(attempt), so alength stop that also produced tool media or a committed source reply does not
gain an extra text reply telling the user to ask for a continuation. The notice
additionally requires nonblank assistant text (streamed, or from the terminal
assistant message), so a cron turn whose only payload is the synthesized silent
result of a successful tool stays silent.
The classifier has four call sites. Two of them
(
isEmptyResponseAssistantTurn,isNonVisibleAssistantTurnEligibleForSilentReplyin the same file) hardcode
hasAssistantVisibleText: false, so they areunaffected. The other two pass the real value and both change for that single
case, consistently:
resolveIncompleteTurnPayloadText()stops replacing thepayloads, and
handleAgentEnd()inembedded-agent-subscribe.handlers.lifecycle.tsstops marking the turn
replayInvalid/abandoned— which is what makes thedelivered partial answer replayable instead of a dead end.
resolveAttemptTrajectoryTerminal()is included so durable state cannotcontradict what the user received. It previously recorded
terminalError: "non_deliverable_terminal_turn"for everylengthturn withoutterminal output, including the ones this PR now delivers. It now keys on visible
assistant text, the same fact the delivery owner keys on.
Visible text rather than payload count, deliberately: attempt finalization runs
before
terminal-preparation.tsturns assistant text into payloads, sosynthesizedPayloadCountis still0for an ordinary text-only truncated reply(it counts block replies, tool media, source-reply payloads, and silent-tool
payloads). Keying on it would have left the headline case still recorded as an
error while the reply was delivered. A
lengthstop with nothing visible to show— whitespace-only text included — stays non-deliverable.
Files changed:
src/agents/embedded-agent-runner/run/incomplete-turn-classification.ts—the classifier respects
hasAssistantVisibleText.src/agents/embedded-agent-runner/run/incomplete-turn-resolution.ts—adds
TRUNCATED_REPLY_NOTICE_TEXT.src/agents/embedded-agent-runner/run/terminal-resolution.ts— appends thenotice on the success path when the turn stopped at the output limit and has
no terminal output.
src/agents/embedded-agent-runner/run/attempt-trajectory-status.ts— thetrajectory record agrees with the delivered result.
Related history: #76544 introduced the
hasAssistantVisibleTextparameter forthe
toolUsecase and left it unread by thelengthcase; #112022 is theprecedent for emitting a notice instead of discarding output. #119259 was closed
as already-implemented on reasoning this bug invalidates.
User Impact
A reply that runs out of output budget now arrives, followed by:
The run stays
workingrather thanabandoned, the transcript staysreplayable, and trajectory data records the turn as a success, so "continue
that" works instead of starting over. Turns that stopped at the limit with
nothing to show still surface the existing incomplete-turn warning, unchanged.
Evidence
Runtime behavior, before and after
Observed on a live deployment running this OpenClaw version, before the fix —
gateway log, redacted:
The user saw only:
hasLastAssistant=yeswithpayloads=1is the defect in one line: the replyexisted and was discarded anyway. 20 occurrences in 21 hours on that deployment.
After the fix, same deployment. A
lengthstop was forced cheaply instead ofgenerating a 128K reply, using a temporary provider route with
maxTokens: 400and reasoning disabled, then prompting for a 4,000-word essay:Two such runs, both identical in shape, and zero
incomplete turn detectedlines for them — previously one per occurrence. The delivered payload shape is
byte-for-byte the same as a normal successful reply, checked against a control
run.
Disclosure on how that observation was produced: the deployment runs a published
build, so the two edits were applied to the installed bundle of the same version
rather than to a source checkout. This branch is the source-level port of those
same two edits, plus the notice gating and trajectory alignment added in review;
the tests below are what verify the port itself.
Focused tests
New coverage:
terminal-resolution.test.ts— end-to-end: alengthstop with visible textresolves to
completewith the partial payload plus the notice, nometa.error,livenessState: "working".terminal-resolution.test.ts— alengthstop that already has terminal toolmedia delivers its payloads with no notice appended.
terminal-resolution.test.ts— alengthstop with no visible text stillyields
meta.error.kind === "incomplete_turn"andlivenessState: "abandoned".terminal-resolution.test.ts— alength-stopped cron turn whose only payloadis the synthesized silent tool result keeps that single
NO_REPLYpayload withno notice appended.
embedded-agent-subscribe.handlers.lifecycle.test.ts— alengthstop whosevisible text was never streamed (empty
assistantTexts, text on the completedassistant message) stays
workingrather thanabandoned, matching thecompleted-assistant fallback that payload building already applies; one with
neither stays
abandoned/replayInvalid.attempt-trajectory-status.test.ts— a deliveredlengthpartial recordsstatus: "success"even withsynthesizedPayloadCount: 0, which is the realfinalization-time state for a text-only reply; a
lengthstop with no visibletext, and one with whitespace-only text, both still record
non_deliverable_terminal_turn.settled-tool-evidence.test.ts— the classifier matrix now pins bothlengthoutcomes.run.incomplete-turn.delivery-resolution.test.ts— the existingtoken-limited-partial-answer case now asserts the answer is deliverable, and a
new case pins the no-visible-text path.
Every new assertion was checked against pre-fix
mainand fails there.Also run:
pnpm tsgo:coreclean; targetedoxlint --type-awareclean on allchanged files. Rebased onto current
main— the earlier red CI on this PR was aknown
mainfailure at the old base(
replyOperation.bindToolAuthorityFingerprint is not a functioninauto-reply/replyandgateway/server-methods, unrelated to these files), whichreproduces at the old base commit and passes on current
main.AI-assisted: written with Claude, from a production incident report. The full
diff and reasoning have been reviewed by hand.