Skip to content

fix(gateway): chat clients lose the last streamed text when a run ends in error - #119556

Merged
Takhoffman merged 1 commit into
openclaw:mainfrom
xyrolle:fix/gateway-error-terminal-flush
Aug 5, 2026
Merged

Takhoffman merged 1 commit into
openclaw:mainfrom
xyrolle:fix/gateway-error-terminal-flush

Conversation

@xyrolle

@xyrolle xyrolle commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #119554

What Problem This Solves

Fixes an issue where users watching a streamed answer would see the assistant message truncated
when the run ended in an error instead of completing normally. The last chunk of text the model
produced never arrived on the chat channel, and on a terminal that classified as a cancellation
the final frame carried no message text at all. Nothing in the stream signalled the loss, and the
end terminal behaved correctly, so the gap only showed up on failed runs.

Full mechanism, version verification, and scope analysis are in #119554.

Why This Change Was Made

emitChatDelta withholds a chunk that arrives inside its 150 ms window and leaves it in the run
buffer for a later event to deliver. emitChatTerminal is meant to be that event — it flushes the
buffer before emitting the terminal frame. On the error branch it could not, because
clearBufferedChatState ran at the top of the branch, before finalizeLifecycleEvent, so the
flush resolved empty text and no-opped.

Two changes, both inside that branch:

  • Immediate branch — removed the clear. It was redundant: finalizeLifecycleEvent already
    calls clearBufferedChatState itself at server-chat.ts:793, after emitChatTerminal has
    flushed and resolved the terminal message. Removing it is what fixes the cancellation-classified
    terminal's missing message; merely adding a flush ahead of the clear would have fixed the
    delta and left message: undefined, because emitChatTerminal's own
    resolveBufferedChatTextState would still have seen an empty buffer.
  • Deferred retry-grace branch — kept the clear, so a fallback attempt still cannot merge onto
    the failed attempt's text, but flushed before it. This matches the shape already used at the
    pre-tool-broadcast and pre-item-broadcast flush sites in the same function (:1470, :1547).

Non-goals: this does not change the 150 ms throttle itself. The throttle's lack of a trailing
flush is a separate cadence/latency question and is not touched here.

User Impact

Streaming clients now receive the complete assistant text on runs that end in an error, not just
on runs that end normally. Cancellation-classified terminals carry the partial text in message
instead of dropping it. Retry and fallback behavior is unchanged — the buffer is still isolated
before any fallback attempt can reuse the runId.

Evidence

Three regression tests added next to the existing end-terminal test in
src/gateway/server-chat.agent-events.test.ts, covering both branches and the terminal message.

All three fail on main before the change, with exactly the symptom described:

 × flushes buffered text as delta before the error terminal
   → AssertionError: expected 'Hello' to be 'Hello world'
 × flushes buffered text as delta before deferring a retryable error terminal
   → AssertionError: expected 'Hello' to be 'Hello world'
 × carries buffered text in the terminal message when an error classifies as cancellation
   → AssertionError: expected undefined to be 'Hello world'

 Test Files  1 failed (1)
      Tests  3 failed | 134 passed (137)

After the change, the three gateway chat suites are green:

node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway.config.ts \
  src/gateway/server-chat.agent-events.test.ts \
  src/gateway/server.chat.gateway-server-chat.test.ts \
  src/gateway/server.chat.gateway-server-chat-b.test.ts

 Test Files  3 passed (3)
      Tests  284 passed (284)

pnpm tsgo:core, oxlint, and oxfmt --check on the two changed files are all clean.

Runtime proof (running Gateway + subscribed client)

Frames below come from a Gateway process started from this checkout and a real Gateway Protocol v4
client subscribed to the session, not from a handler harness.

Rig. openclaw gateway run on loopback with token auth, channels skipped, and a scrubbed
process environment so no ambient provider credential can be picked up. One model provider points
at a local OpenAI-compatible stub server; its API key is a literal placeholder string. The client is
this repository's own reference client (packages/gateway-client), connecting as operator with
operator.read/operator.write, calling sessions.messages.subscribe and then one chat.send.
Every inbound frame is logged. The same client build, stub, config, and prompt drive both runs.

Trigger. The stub streams Hello, then world 30 ms later — inside the 150 ms delta throttle
window, so the tail is withheld — then destroys the connection mid-stream with no finish_reason
and no [DONE]:

[stub] chat.completions request received {"stream":true}
[stub] sent first content delta {"text":"Hello"}
[stub] sent second content delta {"text":" world","gapMs":30}
[stub] destroying connection mid-stream (no finish_reason, no [DONE])

The runtime classifies the drop, retries once, the retry is refused by the provider-failure
cooldown, and the run ends on the lifecycle error path — the branch this PR changes.

Client subscribe transcript (abridged). Identical on both runs; timestamps below are relative to
chat.send. The ~20-30 s before the first frame is first-turn workspace/context preparation on a
cold state directory, not stream latency.

[+    27ms] hello-ok {"protocol":4,"role":"operator","scopes":["operator.read","operator.write"]}
[+    41ms] sessions.messages.subscribe {"subscribed":true,"key":"agent:main:proof-session"}
[+     0ms] chat.send {"sessionKey":"proof-session","message":"Reply with a short greeting."}
[+   105ms] chat.send-ack {"runId":"<run-id>","status":"started"}

Before — 26a58bcd, this branch's parent. src/gateway/server-chat.ts there is byte-identical to
main at c02e3934. The withheld world never arrives on any frame:

[+ 34747ms] chat {"runId":"<run-id>","sessionKey":"agent:main:proof-session","agentId":"main","seq":5,"state":"delta","deltaText":"Hello","message":{"role":"assistant","content":[{"type":"text","text":"Hello"}],"timestamp":<ts>}}
[+ 37478ms] chat {"runId":"<run-id>","sessionKey":"agent:main:proof-session","agentId":"main","seq":9,"state":"status","phase":"preparing_workspace"}
[+ 37657ms] chat {"runId":"<run-id>","sessionKey":"agent:main:proof-session","agentId":"main","seq":10,"state":"status","phase":"preparing_context"}
[+ 37673ms] chat {"runId":"<run-id>","sessionKey":"agent:main:proof-session","agentId":"main","seq":11,"state":"error","errorMessage":"Inline API key for provider \"stubprovider\" is temporarily disabled after a provider auth/billing failure. Retry after about 1 minute, or switch to a different auth profile/API key."}

Last text the client ever sees: Hello. The model produced Hello world.

After — da5632df, this PR. The flush delta carrying the tail arrives before the terminal:

[+ 23000ms] chat {"runId":"<run-id>","sessionKey":"agent:main:proof-session","agentId":"main","seq":5,"state":"delta","deltaText":"Hello","message":{"role":"assistant","content":[{"type":"text","text":"Hello"}],"timestamp":<ts>}}
[+ 25665ms] chat {"runId":"<run-id>","sessionKey":"agent:main:proof-session","agentId":"main","seq":9,"state":"status","phase":"preparing_workspace"}
[+ 25788ms] chat {"runId":"<run-id>","sessionKey":"agent:main:proof-session","agentId":"main","seq":10,"state":"status","phase":"preparing_context"}
[+ 25804ms] chat {"runId":"<run-id>","sessionKey":"agent:main:proof-session","agentId":"main","seq":11,"state":"delta","deltaText":" world","message":{"role":"assistant","content":[{"type":"text","text":"Hello world"}],"timestamp":<ts>}}
[+ 25804ms] chat {"runId":"<run-id>","sessionKey":"agent:main:proof-session","agentId":"main","seq":11,"state":"error","errorMessage":"Inline API key for provider \"stubprovider\" is temporarily disabled after a provider auth/billing failure. Retry after about 1 minute, or switch to a different auth profile/API key."}

Last text the client sees: Hello world, delivered as a delta frame ahead of the terminal, with
frame ordering and the terminal itself otherwise unchanged.

Scope note: this run exercises the immediate error terminal. The cancellation-classified terminal's
message field is covered by the third regression test rather than by this capture.

Reproduce. Build both commits, point models.providers.<name> at a local OpenAI-compatible
server that emits two content deltas under 150 ms apart and then destroys the socket without a
finish event, start openclaw gateway run, connect packages/gateway-client as an operator, call
sessions.messages.subscribe then chat.send, and log every chat frame.

Run identifiers and wall-clock timestamps are redacted; frame order, relative timing, and payload
text are verbatim.

…s in error

The 150 ms delta throttle in emitChatDelta withholds the most recent chunk
without scheduling it, leaving it in the run buffer for a later event to
deliver. emitChatTerminal exists to be that event: it flushes the buffer
before emitting the terminal frame.

On the error terminal it cannot, because the buffer is cleared at the top of
the branch, before finalizeLifecycleEvent runs. The flush then resolves empty
text and no-ops, so the withheld tail never reaches the chat channel, and a
terminal that classifies as a cancellation resolves its message to undefined.

The clear is redundant on the immediate branch: finalizeLifecycleEvent already
clears the buffer itself, after emitChatTerminal has flushed and resolved the
terminal message. Removing it there fixes both the missing delta and the
missing message. The deferred retry-grace branch still needs the clear so a
fallback attempt cannot merge onto the failed attempt's text, so flush before
clearing there, matching the pre-tool and pre-item flush sites in the same
function.

The end terminal was already correct, which is why this stayed invisible.
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Aug 5, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. labels Aug 5, 2026
@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 5, 2026, 6:43 AM ET / 10:43 UTC.

ClawSweeper review

What this changes

The PR preserves throttled streamed chat text through lifecycle-error handling so subscribed clients receive it before the terminal frame, while retaining retry-attempt isolation.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

Keep open: the patch correctly repairs a current-main Gateway ordering bug, with focused regression coverage and a before/after running-Gateway client transcript.

Priority: P1
Reviewed head: da5632dfbca007fa3da5d91d6a232c83261fe730

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused repair with direct runtime evidence, branch-specific regression coverage, and no identified correctness or security finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The updated PR body includes redacted before/after terminal output from a running Gateway and subscribed reference client on the exact head.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The updated PR body includes redacted before/after terminal output from a running Gateway and subscribed reference client on the exact head.
Evidence reviewed 5 items Current-main failure mechanism: Current main clears the client run before the terminal finalizer, while the finalizer's terminal emitter flushes buffered text only afterward; the flush therefore sees an empty buffer.
Terminal lifecycle owner: The terminal emitter resolves and flushes buffered text before it clears run state, proving the pre-clear in the error path defeats its intended ordering.
Narrow repair and regression coverage: The head removes the premature clear for immediate finalization and flushes before clearing only on the retry-grace branch; tests cover immediate errors, deferred errors, and cancellation-classified terminals.
Findings None None.
Security None None.

How this fits together

Gateway converts agent stream events into chat frames for subscribed clients. Buffered assistant text is normally flushed at terminal and tool/item boundaries before lifecycle cleanup removes the run state.

flowchart LR
  A[Model stream] --> B[Gateway agent events]
  B --> C[Buffered chat text]
  C --> D{Lifecycle error}
  D --> E[Flush before cleanup]
  E --> F[Subscribed chat clients]
Loading

Before merge

  • Complete next step (P2) - No mechanical repair remains; this PR is ready for normal maintainer merge review against its current head.
Agent review details

Security

None.

PR surface

Source +16, Tests +95. Total +111 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 17 1 +16
Tests 1 95 0 +95
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 112 1 +111

Review metrics

Metric Value Why it matters
Production vs regression LOC production +17/-1; tests +95/-0 The small production increase documents the lifecycle-ordering invariant, and the added tests cover each repaired error-terminal outcome.

Technical review

Best possible solution:

Land the narrow lifecycle-ordering repair independently; the separate trailing-flush work remains a distinct, composable improvement.

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

Yes. The PR body shows a running Gateway plus subscribed protocol-client before/after transcript, and current main has the exact pre-clear path that the focused regression tests exercise.

Is this the best way to solve the issue?

Yes. Keeping the buffer until immediate terminal emission, while explicitly flushing then clearing only before deferred retry grace, repairs the owner boundary without changing throttle policy or fallback semantics.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against a52b336f260f.

Labels

Label justifications:

  • P1: A common Gateway error path can silently omit already-produced streamed text from active chat clients.
  • 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. Sufficient (terminal): The updated PR body includes redacted before/after terminal output from a running Gateway and subscribed reference client on the exact head.
  • proof: sufficient: Contributor real behavior proof is sufficient. The updated PR body includes redacted before/after terminal output from a running Gateway and subscribed reference client on the exact head.

Evidence

What I checked:

  • Current-main failure mechanism: Current main clears the client run before the terminal finalizer, while the finalizer's terminal emitter flushes buffered text only afterward; the flush therefore sees an empty buffer. (src/gateway/server-chat.ts:1638, a52b336f260f)
  • Terminal lifecycle owner: The terminal emitter resolves and flushes buffered text before it clears run state, proving the pre-clear in the error path defeats its intended ordering. (src/gateway/server-chat.ts:1066, a52b336f260f)
  • Narrow repair and regression coverage: The head removes the premature clear for immediate finalization and flushes before clearing only on the retry-grace branch; tests cover immediate errors, deferred errors, and cancellation-classified terminals. (src/gateway/server-chat.agent-events.test.ts:1236, da5632dfbca0)
  • Real behavior proof: The PR body provides before/after output from a running Gateway and subscribed protocol client: the exact head emits the withheld world delta before the error terminal, unlike its parent. (src/gateway/server-chat.ts:1644, da5632dfbca0)
  • History provenance: Blame attributes the current pre-clear error block to this commit; its shallow history does not support a reliable predecessor PR attribution. (src/gateway/server-chat.ts:1639, b316c9cacf69)

Likely related people:

  • Peter Steinberger: Unified the Gateway chat-run state used by buffering, lifecycle finalization, and these regression tests. (role: chat-run state architecture owner; confidence: high; commits: 7cbd24771fc9, de8b78781263; files: src/gateway/server-chat.ts, src/gateway/server-chat-state.ts, src/gateway/server-chat.agent-events.test.ts)
  • Ayaan Zaidi: Recent error and timeout classification changes touched the same Gateway lifecycle and test surface. (role: recent terminal-classification contributor; confidence: medium; commits: 5ffa6db0dee5, a303ca607ca5; files: src/gateway/server-chat.ts, src/gateway/server-chat.agent-events.test.ts)
  • Syu: Current-main blame assigns the premature pre-clear error block to this commit. (role: current affected-block author; confidence: medium; commits: b316c9cacf69; files: src/gateway/server-chat.ts)

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-08-05T09:37:39.743Z sha da5632d :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 5, 2026
@Takhoffman Takhoffman self-assigned this Aug 5, 2026
@Takhoffman
Takhoffman merged commit 9b2328d into openclaw:main Aug 5, 2026
141 of 153 checks passed
@Takhoffman

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 6, 2026
…s in error (openclaw#119556)

…s in error

The 150 ms delta throttle in emitChatDelta withholds the most recent chunk
without scheduling it, leaving it in the run buffer for a later event to
deliver. emitChatTerminal exists to be that event: it flushes the buffer
before emitting the terminal frame.

On the error terminal it cannot, because the buffer is cleared at the top of
the branch, before finalizeLifecycleEvent runs. The flush then resolves empty
text and no-ops, so the withheld tail never reaches the chat channel, and a
terminal that classifies as a cancellation resolves its message to undefined.

The clear is redundant on the immediate branch: finalizeLifecycleEvent already
clears the buffer itself, after emitChatTerminal has flushed and resolved the
terminal message. Removing it there fixes both the missing delta and the
missing message. The deferred retry-grace branch still needs the clear so a
fallback attempt cannot merge onto the failed attempt's text, so flush before
clearing there, matching the pre-tool and pre-item flush sites in the same
function.

The end terminal was already correct, which is why this stayed invisible.

Co-authored-by: Tak Hoffman <[email protected]>
chovizzz added a commit to chovizzz/openclaw that referenced this pull request Sep 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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.

[Bug]: chat clients lose the tail of streamed assistant text when a run ends in error

2 participants