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

+2
View File
@@ -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.
+1 -1
View File
@@ -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
+37 -30
View File
@@ -214,9 +214,9 @@ export class NanobotClient {
private runStatusHandlers = new Set<RunStatusHandler>();
private runCompletionHandlers = new Set<RunCompletionHandler>();
private errorHandlers = new Set<ErrorHandler>();
// chat_id -> handlers listening on it
private chatHandlers = new Map<string, Set<EventHandler>>();
/** Inbound frames received while no subscriber is registered (e.g. user switched away). */
private transcriptHandlers = new Map<string, { handler: EventHandler }>();
/** Inbound frames received while the transcript owner is absent, regardless of observers. */
private pendingInboundByChat = new Map<string, InboundEvent[]>();
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);
+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);