Skip to content

Commit da5632d

Browse files
committed
fix(gateway): chat clients lose the last streamed text when a run ends 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.
1 parent 26a58bc commit da5632d

2 files changed

Lines changed: 112 additions & 1 deletion

File tree

‎src/gateway/server-chat.agent-events.test.ts‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1233,6 +1233,101 @@ describe("agent event handler", () => {
12331233
nowSpy.mockRestore();
12341234
});
12351235

1236+
it("flushes buffered text as delta before the error terminal", () => {
1237+
let now = 10_000;
1238+
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
1239+
const { broadcast, chatRunState, handler } = createHarness({ lifecycleErrorRetryGraceMs: 0 });
1240+
registerNamedChatRun(chatRunState, "err-flush");
1241+
1242+
emitAgentEvent(handler, "run-err-flush", "assistant", { text: "Hello" });
1243+
1244+
now = 10_100;
1245+
emitAgentEvent(handler, "run-err-flush", "assistant", { text: "Hello world" });
1246+
1247+
emitAgentEvent(
1248+
handler,
1249+
"run-err-flush",
1250+
"lifecycle",
1251+
{ phase: "error", error: "provider failed" },
1252+
{ seq: 2 },
1253+
);
1254+
1255+
const chatPayloads = chatBroadcastCalls(broadcast).map(
1256+
([, payload]) => payload as { state?: string; deltaText?: string },
1257+
);
1258+
expect(
1259+
chatPayloads
1260+
.filter((payload) => payload.state === "delta")
1261+
.map((payload) => payload.deltaText)
1262+
.join(""),
1263+
).toBe("Hello world");
1264+
expect(chatPayloads.at(-1)?.state).toBe("error");
1265+
nowSpy.mockRestore();
1266+
});
1267+
1268+
it("flushes buffered text as delta before deferring a retryable error terminal", () => {
1269+
vi.useFakeTimers();
1270+
let now = 10_000;
1271+
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
1272+
const { broadcast, chatRunState, handler } = createHarness({
1273+
lifecycleErrorRetryGraceMs: 100,
1274+
});
1275+
registerNamedChatRun(chatRunState, "err-grace");
1276+
1277+
emitAgentEvent(handler, "run-err-grace", "assistant", { text: "Hello" });
1278+
1279+
now = 10_100;
1280+
emitAgentEvent(handler, "run-err-grace", "assistant", { text: "Hello world" });
1281+
1282+
emitAgentEvent(
1283+
handler,
1284+
"run-err-grace",
1285+
"lifecycle",
1286+
{ phase: "error", error: "retryable provider failure" },
1287+
{ seq: 2 },
1288+
);
1289+
1290+
// The terminal is still deferred behind the retry grace, but the tail the
1291+
// throttle withheld has already been delivered.
1292+
expect(vi.getTimerCount()).toBe(1);
1293+
expect(
1294+
chatBroadcastCalls(broadcast)
1295+
.map(([, payload]) => payload as { state?: string; deltaText?: string })
1296+
.filter((payload) => payload.state === "delta")
1297+
.map((payload) => payload.deltaText)
1298+
.join(""),
1299+
).toBe("Hello world");
1300+
nowSpy.mockRestore();
1301+
});
1302+
1303+
it("carries buffered text in the terminal message when an error classifies as cancellation", () => {
1304+
let now = 10_000;
1305+
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
1306+
const { broadcast, chatRunState, handler } = createHarness({ lifecycleErrorRetryGraceMs: 0 });
1307+
registerNamedChatRun(chatRunState, "err-cancel");
1308+
1309+
emitAgentEvent(handler, "run-err-cancel", "assistant", { text: "Hello" });
1310+
1311+
now = 10_100;
1312+
emitAgentEvent(handler, "run-err-cancel", "assistant", { text: "Hello world" });
1313+
1314+
emitAgentEvent(
1315+
handler,
1316+
"run-err-cancel",
1317+
"lifecycle",
1318+
{ phase: "error", aborted: true },
1319+
{ seq: 2 },
1320+
);
1321+
1322+
const terminal = chatBroadcastCalls(broadcast).at(-1)?.[1] as {
1323+
state?: string;
1324+
message?: { content?: Array<{ text?: string }> };
1325+
};
1326+
expect(terminal?.state).toBe("aborted");
1327+
expect(terminal?.message?.content?.[0]?.text).toBe("Hello world");
1328+
nowSpy.mockRestore();
1329+
});
1330+
12361331
it("preserves pre-tool assistant text when later segments stream as non-prefix snapshots", () => {
12371332
let now = 10_500;
12381333
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);

‎src/gateway/server-chat.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1636,15 +1636,31 @@ export function createAgentEventHandler({
16361636
}
16371637

16381638
if (lifecyclePhase === "error") {
1639-
clearBufferedChatState(clientRunId);
16401639
const skipChatErrorFinal = isChatSendRunActive(evt.runId) && !chatLink;
16411640
const isFallbackExhaustedFailure = evt.data?.fallbackExhaustedFailure === true;
16421641
// Per-attempt provider errors keep the retry grace so fallback can reuse
16431642
// the runId. Once the runner marks fallback as exhausted, clear chat state
16441643
// immediately so webchat sessions do not stay in progress until the timer.
16451644
if (isAborted || isFallbackExhaustedFailure || lifecycleErrorRetryGraceMs <= 0) {
1645+
// finalizeLifecycleEvent clears the buffer itself, after emitChatTerminal
1646+
// has flushed the throttled tail and resolved the terminal message.
16461647
finalizeLifecycleEvent(evt, { skipChatErrorFinal, restartRecoveryState });
16471648
} else {
1649+
// Deliver the throttled tail before isolating the buffer so a fallback
1650+
// attempt cannot merge onto the failed attempt's text.
1651+
if (sessionKey) {
1652+
flushBufferedChatDeltaIfNeeded(
1653+
sessionKey,
1654+
sessionAgentId,
1655+
clientRunId,
1656+
evt.runId,
1657+
evt.seq,
1658+
{
1659+
controlUiVisible: isControlUiVisible,
1660+
},
1661+
);
1662+
}
1663+
clearBufferedChatState(clientRunId);
16481664
scheduleTerminalLifecycleError(evt, { skipChatErrorFinal, restartRecoveryState });
16491665
}
16501666
return;

0 commit comments

Comments
 (0)