Skip to content

fix(ai): stream completions text live when reasoning precedes it - #150685

Merged
steipete merged 3 commits into
openclaw:mainfrom
leapdragon:fix/completions-reasoning-first-live-text
Oct 10, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
leapdragon:fix/completions-reasoning-first-live-text

Conversation

@leapdragon

@leapdragon leapdragon commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes answers arriving in one burst at the end when an OpenAI-compatible Chat Completions model streams reasoning before visible text.

User Impact

Visible text now streams after initial or resumed reasoning wherever live streaming is enabled. A live update may briefly contain text that later becomes commentary; the final reply still excludes that commentary and delivers the confirmed answer. Content followed only by reasoning remains deliverable. No new configuration is required.

Maintainer product decision — Peter Steinberger, October 10, 2026: live interim text is deliberately allowed. This supersedes #125149's no-transient-interim delivery policy while preserving its final-answer classification. No compatibility flag or provisional-preview mechanism was added.

Why This Change Was Made

The shared completion transport no longer turns reasoning into an all-text buffer, and the subscriber no longer treats terminal-phase metadata as a live-delivery hold. The producer retains that metadata for final/error classification, preserves confirmed final boundaries, and keeps unfinished reasoning tags private. Durable unclassified block replies retain their existing terminal-resolution contract.

Thanks @leapdragon (Aron Hsiao) for the diagnosis, original implementation, and live vLLM measurements. Contributor history is preserved; current main was merged into the branch, never rebased. The maintainer revision removes the extra phase helpers and strengthens the tests to observe text before the next input chunk rather than merely counting deltas after completion.

Evidence

Real local Qwen3 4B through an isolated CLI-launched Gateway, using the same synthetic prompt and llama.cpp's reasoning_content stream:

Gateway measurement Main Candidate
First visible text from request start 15.517s 5.199s
Backend's first content from request start 8.536s 5.191s
Gateway delay after backend first content 6.981s 0.008s
Live text updates 1 35
Terminal reply 16.264s 7.897s

These are separate model generations, so total generation speed varies. The important boundary result is that main withheld content until backend completion, while the candidate forwarded it as generated.

A second real-model Gateway run inserted one synthetic INTERIM_LIVE_MARKER content chunk after the first native reasoning chunk, then forwarded the remaining real reasoning and model answer. The marker appeared live at 1.306s; streaming continued after resumed reasoning; the final reply at 4.798s excluded it. The final reply on main also excluded the marker, while main emitted no interim preview. This is synthetic interleaving over actual local inference, not a claim that the unmodified model naturally emitted that sequence. No Telegram or other live channel-server proof is claimed.

Commands used: node scripts/worktree-setup.mjs gateway, pnpm build, then pnpm openclaw --profile completions-stream gateway run --port 19371 with isolated state/config. The observer used the production Gateway client and chat.send/chat events. No operator Gateway or state was changed.

Validation:

  • Updated live-delta regression fails current main at the first content checkpoint; candidate passes, including same-packet and hidden reasoning, resumed reasoning, and unfinished tags.
  • Producer, parity, Markdown partitioner, and subscriber selection: 151 tests passed, 128.04s total wall. New streaming test body: 15ms; its unit shard took 13.07s. Updated subscriber file: 22 tests, 83.36s duration, dominated by transform/import preparation; no real sleeps or per-test Gateway boots.
  • The subscriber regression drives the real producer and real subscriber, checks live text before terminal, then checks that the final payload contains only the confirmed answer. It also preserves the content-before-reasoning case associated with [Bug]: WhatsApp reply silently dropped when openai-completions model emits visible text before reasoning_content (textPhaseRequiresTerminal seals it as commentary) #166594.
  • Parity fixture regenerated with Vitest; only a redundant empty thinking delta disappears.
  • Full build passed (617.41s), targeted lint passed, core production and package/agent test typechecks passed, formatting and diff checks passed. Build reported an advisory UI startup-size warning; no UI source is changed.
  • Max-lines, line-cap, assertion-safety, test-timeout-race, test-mock-exports, config documentation, and plugin inventory checks passed.
  • Isolated Codex review: clean through P2 on committed head 3cbae23fae46494ecb8c6345efc7ce3d57196c70. Exact-head CI passed, including openclaw/ci-gate; ClawSweeper reports no findings or Before merge items on that head. Changed-test CI jobs took 95–242s including setup; individual-file hosted times were not extracted.

Relative to the merged main baseline: production +6/-26 (net -20); tests/fixtures +133/-36 (net +97); docs +6/-2. No model-facing prompt text changed, so no prompt snapshot or token delta applies.

Gateway Chat Completions HTTP SSE retains its existing append-only correction contract; this change does not add stream retraction. Channel-specific preview settings and explicit strict-tag consumers remain supported.

Additional Telegram Test Server coverage remains unrun; the maintainer proof-only override applies. The real Gateway/local-model and producer-to-subscriber evidence above is the validation supplied for this change.

Since openclaw#125149 any OpenAI-completions stream that carries native reasoning
hides every byte of visible text until the stream ends: the first reasoning
chunk marks the message terminal-bound and arms the reasoning-tag partitioner's
strict mode, and text sharing a chunk with reasoning is routed through the
tag-aware path, which also arms strict mode. With a reasoning model on vLLM
the answer therefore arrives as one delta at the end, minutes after the
reasoning finished, even though the server streamed it token by token.

That deferral exists so text interrupted by resumed reasoning can be
classified as commentary or final answer at terminal. Reasoning that precedes
every visible byte leaves nothing to reclassify, so defer only when reasoning
resumes after visible text: mark the message terminal-bound and switch the
partitioner to strict mode only then, and route same-chunk text through the
tag-aware path only once the message is terminal-bound. Resumed-reasoning
streams behave exactly as before.

Measured against vLLM (qwen38-flash-next, reasoning low): before, one
2,924-character text delta at 16.8 s; after, 92 deltas starting 50 ms after
the last thinking delta.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clawsweeper

clawsweeper Bot commented Sep 17, 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.

@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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 17, 2026
@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Streams visible Chat Completions text after initial or resumed reasoning while preserving final-answer classification.

Example: A stream emits reasoning, “Initial text.”, more reasoning, then “Final text.”

  • Before: Visible text waits until completion.
  • After: Text appears live during generation, and the final reply contains only “Final text.”

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused shared-owner repair with supplied Gateway proof, meaningful boundary regressions, accepted product direction, and no open findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied isolated Qwen3 Gateway runs exercise the shipped CLI and production chat events, show incremental text after native reasoning, and show an injected interim marker removed from the terminal reply; Telegram coverage is expressly unclaimed.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Answers arrive in one burst despite the provider generating visible text incrementally.
Reason: The shared repair restores useful live feedback, and the recorded owner decision explicitly accepts provisional text exposure.

Merge readiness

✅ Ready for maintainer review

This PR provides a useful, maintainer-approved streaming repair that current main still needs; no introduced correctness or security defect was found.

Priority: P2
Reviewed head: 3cbae23fae46494ecb8c6345efc7ce3d57196c70

Before merge

None.

Findings

None.

Agent review details

How this fits together

The shared Chat Completions transport converts provider chunks into assistant events; the embedded-agent subscriber sends live previews and separately prepares classified final replies.

flowchart LR
  A[Provider stream] --> B[Completions transport]
  B --> C[Reasoning tag parser]
  C --> D[Assistant events]
  D --> E[Embedded subscriber]
  E --> F[Live previews]
  E --> G[Classified final reply]
Loading

Technical review

Best possible solution:

Land the shared producer and subscriber repair with the accepted live-preview tradeoff and preserved terminal filtering.

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

Current-main source shows both withholding gates, corroborated by the supplied before/after Gateway measurements; this review executed no target code.

Is this the best way to solve the issue?

The patch addresses both shared owners without adding a parallel preview API or configuration, and preserves final classification, explicit strict-tag consumers, and durable-block withholding.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Automatic strict buffering and terminal-only live delivery changes intended behavior with a stated reason (78b8f8c: Prevent transient interim text from reaching users before resumed-reasoning phase classification.)
  • Terminal commentary and final-answer classification keeps the original intent (78b8f8c: Preserve producer-owned interruption boundaries so canonical delivery selects the confirmed final answer.)
  • Unfinished reasoning privacy keeps the original intent (a96c281: Keep recognized unfinished reasoning out of visible interrupted replies; this patch also preserves privacy when removing automatic strict mode.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source -20, Tests +97, Docs +4. Total +81 across 7 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 3 6 26 -20
Tests 3 133 36 +97
Docs 1 6 2 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 145 64 +81

Review metrics

Metric Value Why it matters
Production versus tests Production +6/-26; tests and fixtures +133/-36 Production shrinks; test growth protects emission timing, unfinished-tag privacy, and final delivery through the real subscriber.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #132615
Summary: This PR repairs the documented live-text gates; the opt-in preview proposal overlaps, while the remaining WhatsApp empty-payload report has distinct unresolved behavior.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Reasoning-enabled Completions replies remain deliverable but lose incremental feedback.
  • merge-risk: 🚨 message-delivery: Live consumers can see text later classified as commentary; the recorded product decision accepts this tradeoff while final filtering remains intact.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster 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.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The changed partial-reply path reaches Telegram draft previews and is observable on the Test Server; the PR records this coverage as unrun under its maintainer proof-only override.

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 (4 earlier review cycles)
  • reviewed 2026-09-17T06:51:27.615Z sha 81efe78 :: blocked before merge. :: [P1] [P1] Preserve the hold before potentially interim text is emitted
  • reviewed 2026-09-24T22:58:36.215Z sha 81efe78 :: blocked before merge. :: [P1] Preserve the hold before potentially interim text is emitted
  • reviewed 2026-10-06T05:04:47.460Z sha 81efe78 :: blocked before merge. :: [P1] Preserve the hold before potentially interim text is emitted
  • reviewed 2026-10-10T18:44:27.601Z sha 3cbae23 :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 3:13 PM ET / 19:13 UTC (Revision 5).

steipete and others added 2 commits October 10, 2026 10:12
Stream visible Chat Completions text through initial and resumed reasoning while keeping final delivery limited to the confirmed answer. Preserve unfinished reasoning-tag privacy and content followed only by reasoning.

Co-authored-by: Aron Hsiao <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: M and removed size: S labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

Please review head 3cbae23. Peter Steinberger's product decision of October 10, 2026 explicitly permits live interim text after reasoning and supersedes #125149's no-transient-interim policy. Final reply classification is preserved: the real producer/subscriber regression and isolated Qwen3 4B Gateway interleaving proof show the interim segment live and exclude it from the final reply. The PR body records the decision, before/after timings, tests, and clean Codex review. No compatibility flag or provisional-preview mechanism was added.

@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. 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 3add6f6 into openclaw:main Oct 10, 2026
157 of 160 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

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

* fix(ai): stream completions text live when reasoning precedes it

Since openclaw#125149 any OpenAI-completions stream that carries native reasoning
hides every byte of visible text until the stream ends: the first reasoning
chunk marks the message terminal-bound and arms the reasoning-tag partitioner's
strict mode, and text sharing a chunk with reasoning is routed through the
tag-aware path, which also arms strict mode. With a reasoning model on vLLM
the answer therefore arrives as one delta at the end, minutes after the
reasoning finished, even though the server streamed it token by token.

That deferral exists so text interrupted by resumed reasoning can be
classified as commentary or final answer at terminal. Reasoning that precedes
every visible byte leaves nothing to reclassify, so defer only when reasoning
resumes after visible text: mark the message terminal-bound and switch the
partitioner to strict mode only then, and route same-chunk text through the
tag-aware path only once the message is terminal-bound. Resumed-reasoning
streams behave exactly as before.

Measured against vLLM (qwen38-flash-next, reasoning low): before, one
2,924-character text delta at 16.8 s; after, 92 deltas starting 50 ms after
the last thinking delta.

* fix(ai): stream reasoning completions before final classification

Stream visible Chat Completions text through initial and resumed reasoning while keeping final delivery limited to the confirmed answer. Preserve unfinished reasoning-tag privacy and content followed only by reasoning.

Co-authored-by: Aron Hsiao <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Aron Hsiao <[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 docs Improvements or additions to documentation 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: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M 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