Repository navigation
fix(gateway): chat clients lose the last streamed text when a run ends in error - #119556
Conversation
…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.
|
Codex review: needs maintainer review before merge. Reviewed August 5, 2026, 6:43 AM ET / 10:43 UTC. ClawSweeper reviewWhat this changesThe 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 provenancePossible regression — probable (reviewed change; failure trace). No predecessor PR is attributed. Merge readinessKeep 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 Review scores
Verification
How this fits togetherGateway 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]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +16, Tests +95. Total +111 across 2 files. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
Merged via squash.
|
…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]>
…s, and flush the final streamed text (openclaw#99291, openclaw#119556)
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
chatchannel, and on a terminal that classified as a cancellationthe final frame carried no message text at all. Nothing in the stream signalled the loss, and the
endterminal 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
emitChatDeltawithholds a chunk that arrives inside its 150 ms window and leaves it in the runbuffer for a later event to deliver.
emitChatTerminalis meant to be that event — it flushes thebuffer before emitting the terminal frame. On the
errorbranch it could not, becauseclearBufferedChatStateran at the top of the branch, beforefinalizeLifecycleEvent, so theflush resolved empty text and no-opped.
Two changes, both inside that branch:
finalizeLifecycleEventalreadycalls
clearBufferedChatStateitself atserver-chat.ts:793, afteremitChatTerminalhasflushed 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 thedelta and left
message: undefined, becauseemitChatTerminal's ownresolveBufferedChatTextStatewould still have seen an empty buffer.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
messageinstead 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 insrc/gateway/server-chat.agent-events.test.ts, covering both branches and the terminal message.All three fail on
mainbefore the change, with exactly the symptom described:After the change, the three gateway chat suites are green:
pnpm tsgo:core,oxlint, andoxfmt --checkon 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 runon loopback with token auth, channels skipped, and a scrubbedprocess 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 asoperatorwithoperator.read/operator.write, callingsessions.messages.subscribeand then onechat.send.Every inbound frame is logged. The same client build, stub, config, and prompt drive both runs.
Trigger. The stub streams
Hello, thenworld30 ms later — inside the 150 ms delta throttlewindow, so the tail is withheld — then destroys the connection mid-stream with no
finish_reasonand 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 acold state directory, not stream latency.
Before —
26a58bcd, this branch's parent.src/gateway/server-chat.tsthere is byte-identical tomainatc02e3934. The withheldworldnever arrives on any frame:Last text the client ever sees:
Hello. The model producedHello world.After —
da5632df, this PR. The flush delta carrying the tail arrives before the terminal:Last text the client sees:
Hello world, delivered as adeltaframe ahead of the terminal, withframe ordering and the terminal itself otherwise unchanged.
Scope note: this run exercises the immediate error terminal. The cancellation-classified terminal's
messagefield is covered by the third regression test rather than by this capture.Reproduce. Build both commits, point
models.providers.<name>at a local OpenAI-compatibleserver that emits two content deltas under 150 ms apart and then destroys the socket without a
finish event, start
openclaw gateway run, connectpackages/gateway-clientas an operator, callsessions.messages.subscribethenchat.send, and log everychatframe.Run identifiers and wall-clock timestamps are redacted; frame order, relative timing, and payload
text are verbatim.