From 0f3b47bc3ab5b60a6154675333e19e373d567853 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:13:12 +0800 Subject: [PATCH] fix(webui): isolate transcript replay from live observers (#6306) * fix(webui): isolate transcript replay from live observers * docs(webui): shorten chat subscription ownership notes --- webui/COMPONENTS.md | 2 + webui/src/hooks/useNanobotStream.ts | 2 +- webui/src/lib/nanobot-client.ts | 67 +++++----- webui/src/tests/app-layout.test.tsx | 1 + .../src/tests/chat-replay-ownership.test.tsx | 119 ++++++++++++++++++ webui/src/tests/nanobot-client.test.ts | 36 ++++-- webui/src/tests/thread-shell.test.tsx | 3 + webui/src/tests/useNanobotStream.test.tsx | 2 +- webui/src/tests/useReconnectRuns.test.tsx | 4 +- 9 files changed, 193 insertions(+), 43 deletions(-) create mode 100644 webui/src/tests/chat-replay-ownership.test.tsx diff --git a/webui/COMPONENTS.md b/webui/COMPONENTS.md index d3426a1bc..00e304016 100644 --- a/webui/COMPONENTS.md +++ b/webui/COMPONENTS.md @@ -47,6 +47,8 @@ Supporting hooks and display-model helpers stay near the feature that owns them. `NanobotClient` adapts WebSocket frames into observations for its `ClientRunLedger`. The ledger owns each chat's message delivery, run identities, clocks, and completion records, and returns effects for the client to apply to its queues and subscribers. A dropped connection makes unconfirmed delivery unknown while durable runs remain unresolved. Wire completion still permits late final messages; canonical completion records suppress matching top-level turn events. `useNanobotStream` owns message projection and render batching, while `ThreadShell` adopts canonical history and confirms completion after the messages commit. +`onChat` provides live events to task and model observers. `useNanobotStream` uses `onTranscript` as the single transcript owner, receiving queued events once followed by live events. + ## Choose an existing component - Check the gallery and current callers before creating a control. Different labels, colors, or sizes usually call for an existing component's options. `Button` already has appearance and size variants; `Input` and `SearchInput` share the input implementation. diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 0599c3dd5..e2cf21318 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -902,7 +902,7 @@ export function useNanobotStream( } }; - const unsub = client.onChat(chatId, handle); + const unsub = client.onTranscript(chatId, handle); return () => { unsub(); // Navigation may happen before the throttled paint. Snapshot the pending diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts index c0eb059c4..76499b85d 100644 --- a/webui/src/lib/nanobot-client.ts +++ b/webui/src/lib/nanobot-client.ts @@ -214,9 +214,9 @@ export class NanobotClient { private runStatusHandlers = new Set(); private runCompletionHandlers = new Set(); private errorHandlers = new Set(); - // chat_id -> handlers listening on it private chatHandlers = new Map>(); - /** Inbound frames received while no subscriber is registered (e.g. user switched away). */ + private transcriptHandlers = new Map(); + /** Inbound frames received while the transcript owner is absent, regardless of observers. */ private pendingInboundByChat = new Map(); private static readonly PENDING_INBOUND_MAX = 2000; // chat_ids we've attached to since connect; re-attached after reconnects @@ -460,7 +460,7 @@ export class NanobotClient { } } - /** Subscribe to events for a given chat_id. Auto-attaches on the next open. */ + /** Observe live chat events without consuming transcript replay. Auto-attaches. */ onChat(chatId: string, handler: EventHandler): Unsubscribe { let handlers = this.chatHandlers.get(chatId); if (!handlers) { @@ -468,14 +468,6 @@ export class NanobotClient { this.chatHandlers.set(chatId, handlers); } handlers.add(handler); - const pending = this.pendingInboundByChat.get(chatId); - if (pending !== undefined && pending.length > 0) { - const flushed = pending.splice(0); - this.pendingInboundByChat.delete(chatId); - for (const ev of flushed) { - handler(ev); - } - } this.attach(chatId); return () => { const current = this.chatHandlers.get(chatId); @@ -485,6 +477,24 @@ export class NanobotClient { }; } + /** Own transcript delivery: consume the pending tail once, then receive live events. */ + onTranscript(chatId: string, handler: EventHandler): Unsubscribe { + if (this.transcriptHandlers.has(chatId)) { + throw new Error(`Transcript already subscribed: ${chatId}`); + } + const subscription = { handler }; + this.transcriptHandlers.set(chatId, subscription); + const pending = this.pendingInboundByChat.get(chatId); + this.pendingInboundByChat.delete(chatId); + for (const event of pending ?? []) handler(event); + this.attach(chatId); + return () => { + if (this.transcriptHandlers.get(chatId) === subscription) { + this.transcriptHandlers.delete(chatId); + } + }; + } + connect(): void { if (this.socket && this.socket.readyState < WS_CLOSING) return; this.intentionallyClosed = false; @@ -1015,27 +1025,23 @@ export class NanobotClient { } private dispatch(chatId: string, ev: InboundEvent): void { - const handlers = this.chatHandlers.get(chatId); - if (handlers !== undefined && handlers.size > 0) { - for (const h of handlers) { - h(ev); + const transcript = this.transcriptHandlers.get(chatId); + if (transcript) { + transcript.handler(ev); + } else { + let pending = this.pendingInboundByChat.get(chatId); + if (!pending) { + pending = []; + this.pendingInboundByChat.set(chatId, pending); + } + pending.push(ev); + // Temporary chats have no canonical history to recover evicted events from. + if (!this.temporaryChatIds.has(chatId)) { + const over = pending.length - NanobotClient.PENDING_INBOUND_MAX; + if (over > 0) pending.splice(0, over); } - return; - } - let q = this.pendingInboundByChat.get(chatId); - if (!q) { - q = []; - this.pendingInboundByChat.set(chatId, q); - } - q.push(ev); - // Temporary chats have no canonical history to recover evicted events from. - // Like their pinned message snapshots, retain them until resubscribe, close - // or disconnect. Disk-backed chats keep the bounded replay tail below. - if (this.temporaryChatIds.has(chatId)) return; - const over = q.length - NanobotClient.PENDING_INBOUND_MAX; - if (over > 0) { - q.splice(0, over); } + for (const handler of this.chatHandlers.get(chatId) ?? []) handler(ev); } private handleClose(event?: { code?: number }): void { @@ -1188,6 +1194,7 @@ export class NanobotClient { this.temporaryChatIds.delete(chatId); this.knownChats.delete(chatId); this.chatHandlers.delete(chatId); + this.transcriptHandlers.delete(chatId); this.pendingInboundByChat.delete(chatId); const effects = this.runs.transition({ kind: "forget", chatId }); this.goalStateByChatId.delete(chatId); diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index 0fc889f98..c7008add9 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -257,6 +257,7 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => { onRuntimeModelUpdate = () => () => {}; onError = () => () => {}; onChat = () => () => {}; + onTranscript = () => () => {}; onSessionUpdate = (handler: ( chatId: string, scope?: string, diff --git a/webui/src/tests/chat-replay-ownership.test.tsx b/webui/src/tests/chat-replay-ownership.test.tsx new file mode 100644 index 000000000..3796414d7 --- /dev/null +++ b/webui/src/tests/chat-replay-ownership.test.tsx @@ -0,0 +1,119 @@ +import { act, render, screen } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { SubagentTasksProvider } from "@/components/thread/SubagentTasks"; +import { useNanobotStream } from "@/hooks/useNanobotStream"; +import { NanobotClient } from "@/lib/nanobot-client"; +import type { InboundEvent, UIMessage } from "@/lib/types"; +import { ClientProvider } from "@/providers/ClientProvider"; + +class TestSocket { + readyState = 0; + onopen: (() => void) | null = null; + onmessage: ((event: MessageEvent) => void) | null = null; + onclose: (() => void) | null = null; + onerror: (() => void) | null = null; + send() {} + close() { this.readyState = 3; } + open() { this.readyState = 1; this.onopen?.(); } + receive(event: InboundEvent) { + this.onmessage?.({ data: JSON.stringify(event) } as MessageEvent); + } +} + +const CHAT_ID = "replay-ownership"; +const TURN_ID = "running-turn"; +const INITIAL_MESSAGES: UIMessage[] = [ + { id: "prompt", role: "user", content: "Read the fixtures", turnId: TURN_ID }, +]; + +function toolMessage(callId: string): InboundEvent { + return { + event: "message", chat_id: CHAT_ID, turn_id: TURN_ID, + kind: "tool_hint", text: `read_file(${callId}.txt)`, + tool_events: [{ + call_id: callId, name: "read_file", phase: "end", + arguments: { path: `${callId}.txt` }, result: `Contents of ${callId}`, + }], + }; +} + +function Thread({ children }: { children?: ReactNode }) { + const { messages } = useNanobotStream(CHAT_ID, INITIAL_MESSAGES); + return <>{JSON.stringify(messages)}{children}; +} + +function displayedCalls(): string[] { + const messages: UIMessage[] = JSON.parse(screen.getByTestId("messages").textContent!); + return messages.flatMap((message) => message.toolEvents?.map((event) => event.call_id) ?? []); +} + +afterEach(() => { vi.unstubAllGlobals(); }); + +describe("transcript replay with real task and stream subscriptions", () => { + it("retains transcript events while only the task observer is mounted", async () => { + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({ tasks: [] })))); + const socket = new TestSocket(); + const client = new NanobotClient({ + url: "ws://test", reconnect: false, + socketFactory: () => socket as unknown as WebSocket, + }); + client.connect(); + socket.open(); + const tree = (showThread: boolean) => ( + + {showThread && } + + ); + const view = render(tree(false)); + try { + await act(async () => { + socket.receive(toolMessage("while-away-b")); + socket.receive(toolMessage("while-away-c")); + }); + view.rerender(tree(true)); + expect(displayedCalls()).toEqual(["while-away-b", "while-away-c"]); + } finally { + view.unmount(); + client.close(); + } + }); + + it.each(["tasks first", "transcript first"])( + "retains queued tools when %s subscribes on topic return", + async (order) => { + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({ tasks: [] })))); + const socket = new TestSocket(); + const client = new NanobotClient({ + url: "ws://test", reconnect: false, + socketFactory: () => socket as unknown as WebSocket, + }); + client.connect(); + socket.open(); + socket.receive({ + event: "goal_status", chat_id: CHAT_ID, turn_id: TURN_ID, + status: "running", started_at: 1_700_000_000, + }); + socket.receive(toolMessage("while-away-b")); + socket.receive(toolMessage("while-away-c")); + const tasks = (children?: ReactNode) => ( + {children} + ); + const view = render( + + {order === "tasks first" ? {tasks()} : tasks()} + , + ); + try { + await act(async () => { socket.receive(toolMessage("after-return-d")); }); + expect(displayedCalls()).toEqual(["while-away-b", "while-away-c", "after-return-d"]); + } finally { + view.unmount(); + client.close(); + } + }, + ); +}); diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts index dcc977bf2..1ad4ae4fb 100644 --- a/webui/src/tests/nanobot-client.test.ts +++ b/webui/src/tests/nanobot-client.test.ts @@ -89,8 +89,8 @@ describe("NanobotClient", () => { } const regular = vi.fn(); const temporary = vi.fn(); - client.onChat("regular", regular); - const unsubscribe = client.onChat("temporary", temporary); + client.onTranscript("regular", regular); + const unsubscribe = client.onTranscript("temporary", temporary); expect(regular).toHaveBeenCalledTimes(2_000); expect(regular.mock.calls[0][0].text).toBe("10"); expect(temporary.mock.calls.filter(([event]) => event.event === "delta")).toHaveLength(2_010); @@ -98,7 +98,7 @@ describe("NanobotClient", () => { socket.fakeMessage({ event: "delta", chat_id: "temporary", text: "discard me" }); client.discardTemporaryChat("temporary"); const discarded = vi.fn(); - client.onChat("temporary", discarded); + client.onTranscript("temporary", discarded); expect(discarded).not.toHaveBeenCalled(); client.close(); }); @@ -393,7 +393,7 @@ describe("NanobotClient", () => { }); await secondCreation; lastSocket().sent = []; - client.onChat("temp-drop-a", firstHandler); + client.onTranscript("temp-drop-a", firstHandler); client.onChat("temp-drop-b", secondHandler); firstHandler.mockClear(); secondHandler.mockClear(); @@ -517,7 +517,7 @@ describe("NanobotClient", () => { expect(status).toHaveBeenLastCalledWith("open"); }); - it("buffers chat events while no chat handler is registered and replays on subscribe", () => { + it("buffers transcript events independently of live observers", () => { const client = new NanobotClient({ url: "ws://test", reconnect: false, @@ -525,16 +525,24 @@ describe("NanobotClient", () => { }); client.connect(); lastSocket().fakeOpen(); - // Nobody listening yet — deltas must not be dropped (user switched away). lastSocket().fakeMessage({ event: "delta", chat_id: "chat-queue", text: "a" }); + const observer = vi.fn(); + const secondObserver = vi.fn(); + client.onChat("chat-queue", observer); + client.onChat("chat-queue", secondObserver); + expect(observer).not.toHaveBeenCalled(); + expect(secondObserver).not.toHaveBeenCalled(); lastSocket().fakeMessage({ event: "delta", chat_id: "chat-queue", text: "b" }); const handler = vi.fn(); - client.onChat("chat-queue", handler); + client.onTranscript("chat-queue", handler); expect(handler).toHaveBeenCalledTimes(2); expect(handler.mock.calls[0][0]).toMatchObject({ event: "delta", text: "a" }); expect(handler.mock.calls[1][0]).toMatchObject({ event: "delta", text: "b" }); lastSocket().fakeMessage({ event: "delta", chat_id: "chat-queue", text: "c" }); expect(handler).toHaveBeenCalledTimes(3); + for (const listener of [observer, secondObserver]) { + expect(listener.mock.calls.map(([event]) => event.text)).toEqual(["b", "c"]); + } }); it("records goal_status run strip without an onChat subscriber", () => { @@ -1824,8 +1832,10 @@ describe("NanobotClient", () => { reconnect: false, socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket, }); + const observer = vi.fn(); + client.onChat("chat-rejoin", observer); const h1 = vi.fn(); - const unsub = client.onChat("chat-rejoin", h1); + const unsub = client.onTranscript("chat-rejoin", h1); client.connect(); lastSocket().fakeOpen(); lastSocket().fakeMessage({ event: "delta", chat_id: "chat-rejoin", text: "live" }); @@ -1834,9 +1844,17 @@ describe("NanobotClient", () => { lastSocket().fakeMessage({ event: "delta", chat_id: "chat-rejoin", text: "queued" }); expect(h1).toHaveBeenCalledTimes(1); const h2 = vi.fn(); - client.onChat("chat-rejoin", h2); + const unsub2 = client.onTranscript("chat-rejoin", h2); expect(h2).toHaveBeenCalledTimes(1); expect(h2.mock.calls[0][0]).toMatchObject({ event: "delta", text: "queued" }); + unsub(); + lastSocket().fakeMessage({ event: "delta", chat_id: "chat-rejoin", text: "next" }); + expect(h2).toHaveBeenCalledTimes(2); + unsub2(); + const h3 = vi.fn(); + client.onTranscript("chat-rejoin", h3); + expect(h3).not.toHaveBeenCalled(); + expect(observer.mock.calls.map(([event]) => event.text)).toEqual(["live", "queued", "next"]); }); it("dispatches runtime model updates globally", () => { diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index 6ad5b7f09..e1f1fe5d5 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -159,6 +159,9 @@ function makeClient() { completedTurnIdsByChatId.set(chatId, fences); }, getGoalState: (chatId: string) => goalStateByChatId.get(chatId), + onTranscript(chatId: string, handler: (ev: import("@/lib/types").InboundEvent) => void) { + return this.onChat(chatId, handler); + }, onChat: (chatId: string, handler: (ev: import("@/lib/types").InboundEvent) => void) => { let handlers = chatHandlers.get(chatId); if (!handlers) { diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index ec52fcdcb..81727d522 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -136,7 +136,7 @@ function fakeClient() { hasUnsettledRun(chatId: string) { return unsettledRunByChatId.get(chatId) === true; }, - onChat(chatId: string, h: (ev: InboundEvent) => void) { + onTranscript(chatId: string, h: (ev: InboundEvent) => void) { let set = handlers.get(chatId); if (!set) { set = new Set(); diff --git a/webui/src/tests/useReconnectRuns.test.tsx b/webui/src/tests/useReconnectRuns.test.tsx index 5fe71c5e3..c96980718 100644 --- a/webui/src/tests/useReconnectRuns.test.tsx +++ b/webui/src/tests/useReconnectRuns.test.tsx @@ -314,7 +314,7 @@ describe("durable run recovery", () => { expect(cachedAtCompletion).toEqual([body]); expect(projectThreadEvents(cachedAtCompletion[0].events).at(-1)?.content).toBe("The complete answer"); const delayed = vi.fn(); - client.onChat("inactive", delayed); + client.onTranscript("inactive", delayed); expect(delayed).not.toHaveBeenCalled(); close(); }); @@ -436,7 +436,7 @@ describe("durable run recovery", () => { expect(client.hasUnsettledRun("inactive")).toBe(true); expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined(); const resumed = vi.fn(); - client.onChat("inactive", resumed); + client.onTranscript("inactive", resumed); resumed.mockClear(); act(() => { running("inactive", "turn-queued", 456);