fix(webui): isolate transcript replay from live observers (#6306)

* fix(webui): isolate transcript replay from live observers

* docs(webui): shorten chat subscription ownership notes
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-19 17:13:12 +08:00
1 parent dca49c258a
commit 0f3b47bc3a
9 files changed
+193 -43

No files matched your search

+1
View File
@@ -257,6 +257,7 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => {
onRuntimeModelUpdate = () => () => {};
onError = () => () => {};
onChat = () => () => {};
onTranscript = () => () => {};
onSessionUpdate = (handler: (
chatId: string,
scope?: string,
@@ -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 <><output data-testid="messages">{JSON.stringify(messages)}</output>{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) => (
<ClientProvider client={client} token="test">
<SubagentTasksProvider client={client} sessionKey={`websocket:${CHAT_ID}`}
token="test" enabled liveEvents>{showThread && <Thread />}</SubagentTasksProvider>
</ClientProvider>
);
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) => (
<SubagentTasksProvider client={client} sessionKey={`websocket:${CHAT_ID}`}
token="test" enabled liveEvents>{children}</SubagentTasksProvider>
);
const view = render(
<ClientProvider client={client} token="test">
{order === "tasks first" ? <Thread>{tasks()}</Thread> : tasks(<Thread />)}
</ClientProvider>,
);
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();
}
},
);
});
+27 -9
View File
@@ -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", () => {
+3
View File
@@ -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) {
+1 -1
View File
@@ -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();
+2 -2
View File
@@ -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);