Skip to content

Commit 1731908

Browse files
committed
fix(ui): restore in-flight streaming assistant reply on Control UI reconnect (#90755)
1 parent 462c076 commit 1731908

3 files changed

Lines changed: 184 additions & 1 deletion

File tree

‎ui/src/ui/controllers/chat.test.ts‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3382,3 +3382,86 @@ describe("loadChatHistory retry handling", () => {
33823382
expect(state.chatThinkingLevel).toBeNull();
33833383
});
33843384
});
3385+
3386+
describe("loadChatHistory in-flight run adoption", () => {
3387+
it("restores a buffered in-flight assistant stream on reconnect", async () => {
3388+
// Reconnect after switching away: only the committed user turn is persisted,
3389+
// and the gateway reports the still-streaming assistant run as inFlightRun.
3390+
const request = vi.fn().mockResolvedValue({
3391+
messages: [{ role: "user", content: [{ type: "text", text: "Do the thing" }] }],
3392+
inFlightRun: { runId: "run-live", text: "Partial assistant repl" },
3393+
});
3394+
const state = createState({
3395+
client: { request } as unknown as ChatState["client"],
3396+
connected: true,
3397+
chatRunId: null,
3398+
chatStream: null,
3399+
chatStreamStartedAt: null,
3400+
});
3401+
3402+
await loadChatHistory(state);
3403+
3404+
expect(state.chatRunId).toBe("run-live");
3405+
expect(state.chatStream).toBe("Partial assistant repl");
3406+
expect(state.chatStreamStartedAt).toEqual(expect.any(Number));
3407+
expect(state.chatMessages).toHaveLength(1);
3408+
});
3409+
3410+
it("adopts an empty-text in-flight run so the thread shows streaming, not idle", async () => {
3411+
// Runtimes that only deliver assistant text at completion (e.g. Codex) report
3412+
// an inFlightRun with no buffered text; the client must still adopt the run so
3413+
// the status is streaming and a reading indicator renders (chatStream === "").
3414+
const request = vi.fn().mockResolvedValue({
3415+
messages: [{ role: "user", content: [{ type: "text", text: "Run it" }] }],
3416+
inFlightRun: { runId: "run-codex", text: "" },
3417+
});
3418+
const state = createState({
3419+
client: { request } as unknown as ChatState["client"],
3420+
connected: true,
3421+
});
3422+
3423+
await loadChatHistory(state);
3424+
3425+
expect(state.chatRunId).toBe("run-codex");
3426+
expect(state.chatStream).toBe("");
3427+
expect(state.chatStreamStartedAt).toEqual(expect.any(Number));
3428+
});
3429+
3430+
it("ignores inFlightRun without a run id", async () => {
3431+
const request = vi.fn().mockResolvedValue({
3432+
messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
3433+
inFlightRun: { text: "orphan partial" },
3434+
});
3435+
const state = createState({
3436+
client: { request } as unknown as ChatState["client"],
3437+
connected: true,
3438+
});
3439+
3440+
await loadChatHistory(state);
3441+
3442+
expect(state.chatRunId).toBeNull();
3443+
expect(state.chatStream).toBeNull();
3444+
});
3445+
3446+
it("does not adopt inFlightRun when a fresher local run is already streaming", async () => {
3447+
// A live local run started/continued during the reload must win over a stale
3448+
// history snapshot's inFlightRun; reconciliation keeps the local run id, so
3449+
// adoption must be skipped.
3450+
const request = vi.fn().mockResolvedValue({
3451+
messages: [{ role: "user", content: [{ type: "text", text: "newer turn" }] }],
3452+
inFlightRun: { runId: "run-stale", text: "stale partial" },
3453+
});
3454+
const state = createState({
3455+
client: { request } as unknown as ChatState["client"],
3456+
connected: true,
3457+
chatRunId: "run-fresh",
3458+
chatStream: "fresh live text",
3459+
chatStreamStartedAt: 999,
3460+
});
3461+
3462+
await loadChatHistory(state);
3463+
3464+
expect(state.chatRunId).toBe("run-fresh");
3465+
expect(state.chatStream).toBe("fresh live text");
3466+
});
3467+
});

‎ui/src/ui/controllers/chat.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,13 @@ export type ChatHistoryResult = {
425425
sessionInfo?: GatewaySessionRow;
426426
agentsList?: AgentsListResult;
427427
metadata?: ChatMetadataResult;
428+
// A run still streaming for this session+agent that the gateway reports as
429+
// in-flight (already bounded; `text` may be empty when no partial is buffered
430+
// or for runtimes that only deliver assistant text at completion). A client
431+
// that switched away stopped receiving this run's per-agent-delivered deltas,
432+
// so the persisted `messages` above do not include it; the loader re-adopts
433+
// the run on switch-back so the partial renders and further deltas continue.
434+
inFlightRun?: { runId?: string; text?: string };
428435
};
429436

430437
export type ChatMetadataResult = CommandsListResult & {
@@ -568,7 +575,7 @@ const inFlightChatHistoryRequests = new WeakMap<ChatState, InFlightChatHistoryRe
568575

569576
function recordChatHistoryTiming(
570577
state: ChatState,
571-
phase: "start" | "applied" | "stream-reset" | "stale" | "error",
578+
phase: "start" | "applied" | "stream-reset" | "in-flight-run-adopted" | "stale" | "error",
572579
startedAtMs: number,
573580
extra: Record<string, unknown> = {},
574581
) {
@@ -807,6 +814,33 @@ async function loadChatHistoryUncached(
807814
prunePersistedToolStreamMessages(state, persistedToolStreamIds);
808815
}
809816
}
817+
// Restore a run still streaming for this session+agent that the gateway
818+
// reports as in-flight. Its live deltas were delivered to a per-agent key
819+
// this client stopped watching after switching away, so the persisted
820+
// history above does not contain it; re-adopt the run so its partial renders
821+
// and further deltas (now that this session is active again) continue it.
822+
// Mirrors the TUI history loader (src/tui/tui-session-actions.ts). Only adopt
823+
// when no run survived stream reconciliation above, so a fresher live stream
824+
// is never clobbered by a slightly stale history snapshot.
825+
if (resetStream && !state.chatRunId) {
826+
const inFlightRunId =
827+
typeof res.inFlightRun?.runId === "string" ? res.inFlightRun.runId.trim() : "";
828+
if (inFlightRunId) {
829+
const inFlightText = typeof res.inFlightRun?.text === "string" ? res.inFlightRun.text : "";
830+
// Adopt the run so its status shows `streaming` (not idle) and its
831+
// completion is owned here. Render any buffered partial; an empty string
832+
// (Codex-style runtimes, or text dropped by the history budget) still
833+
// shows a reading indicator instead of an idle thread.
834+
state.chatRunId = inFlightRunId;
835+
state.chatStream = inFlightText;
836+
state.chatStreamStartedAt = Date.now();
837+
recordChatHistoryTiming(state, "in-flight-run-adopted", startedAtMs, {
838+
requestSessionKey: sessionKey,
839+
requestAgentId,
840+
previousRunId,
841+
});
842+
}
843+
}
810844
recordChatHistoryTiming(state, "applied", startedAtMs, {
811845
requestSessionKey: sessionKey,
812846
requestAgentId,

‎ui/src/ui/e2e/chat-flow.e2e.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -934,4 +934,70 @@ describeControlUiE2e("Control UI mocked Gateway E2E", () => {
934934
await context.close();
935935
}
936936
});
937+
938+
it("restores the in-flight streaming assistant reply on reconnect (#90755)", async () => {
939+
const context = await browser.newContext({
940+
locale: "en-US",
941+
serviceWorkers: "block",
942+
viewport: { height: 900, width: 1280 },
943+
});
944+
const page = await context.newPage();
945+
// Reconnect snapshot: the committed history holds only the user turn, while
946+
// the gateway reports the still-streaming assistant run via inFlightRun
947+
// (the existing chat.history/chat.startup contract). Before this fix the
948+
// Control UI ignored inFlightRun and the partial reply was lost on reload.
949+
const userTurn = {
950+
content: [{ text: "Summarize the design doc.", type: "text" }],
951+
role: "user",
952+
timestamp: Date.now(),
953+
};
954+
const inFlightRun = { runId: "run-in-flight-90755", text: "Streaming the summary so" };
955+
const gateway = await installMockGateway(page, {
956+
historyMessages: [userTurn],
957+
methodResponses: {
958+
"chat.startup": {
959+
agentsList: {
960+
agents: [{ id: "main", identity: { name: "OpenClaw" }, name: "OpenClaw" }],
961+
defaultId: "main",
962+
mainKey: "main",
963+
scope: "agent",
964+
},
965+
inFlightRun,
966+
messages: [userTurn],
967+
metadata: { models: [{ id: "gpt-5.5", name: "gpt-5.5", provider: "openai" }] },
968+
sessionId: "control-ui-e2e-session",
969+
thinkingLevel: null,
970+
},
971+
"chat.history": {
972+
inFlightRun,
973+
messages: [userTurn],
974+
sessionId: "control-ui-e2e-session",
975+
thinkingLevel: null,
976+
},
977+
},
978+
});
979+
980+
try {
981+
await page.goto(`${server.baseUrl}chat`);
982+
// The committed user turn is present (baseline reconnect behavior).
983+
await page.locator(".chat-thread").getByText("Summarize the design doc.").waitFor({
984+
timeout: 10_000,
985+
});
986+
// The in-flight assistant partial is restored from inFlightRun — the bug fix.
987+
await page.locator(".chat-thread").getByText("Streaming the summary so").waitFor({
988+
timeout: 10_000,
989+
});
990+
991+
// The adopted run still owns subsequent live deltas/final after reconnect.
992+
await gateway.emitChatFinal({
993+
runId: inFlightRun.runId,
994+
text: "Streaming the summary so the reconnect keeps it.",
995+
});
996+
await page.getByText("Streaming the summary so the reconnect keeps it.").waitFor({
997+
timeout: 10_000,
998+
});
999+
} finally {
1000+
await context.close();
1001+
}
1002+
});
9371003
});

0 commit comments

Comments
 (0)