fix(webui): keep completed turns terminal across late events (#5991)

* fix(webui): keep completed turns terminal across late events

* test(webui): align app layout client mock with completion API
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-30 17:40:11 +08:00
1 parent 450a85fe0e
commit 678cd8f4a7
5 files changed
+307 -27

No files matched your search

@@ -1131,6 +1131,7 @@ export function ThreadShell({
useEffect(() => {
if (!historyKey || !chatId || loading) return;
client.fenceCanonicalCompletedTurns(chatId, completedTurnIds);
const cached = messageCacheRef.current.get(chatId);
const pendingCanonicalHydrate = pendingCanonicalHydrateRef.current.get(chatId);
const hasNewCanonicalHistory = (
+78 -27
View File
@@ -221,6 +221,8 @@ export class NanobotClient {
private lastSocketMessageSendKey: string | null = null;
/** Canonically completed turns whose delayed websocket frames must be ignored. */
private canonicalCompletedTurnIdsByChatId = new Map<string, Set<string>>();
/** Closed run identities; output/ACKs can still arrive after idle or local stop. */
private closedRunTurnIdsByChatId = new Map<string, Set<string>>();
private static readonly COMPLETED_TURN_FENCE_MAX = 256;
/** Latest ``goal_state`` snapshot per ``chat_id`` (multi-session isolation). */
private goalStateByChatId = new Map<string, GoalStateWsPayload>();
@@ -328,6 +330,9 @@ export class NanobotClient {
/** Clear the optimistic run state immediately after the user stops a turn. */
finishRunLocally(chatId: string): void {
const unsettled = [...(this.unsettledRunTurnIdsByChatId.get(chatId) ?? [])];
const latestTurnId = this.latestRunTurnIdByChatId.get(chatId);
if (latestTurnId) this.rememberRunCompletion(chatId, latestTurnId);
for (const turnId of unsettled) this.rememberRunCompletion(chatId, turnId);
for (const turnId of unsettled) this.settleRunTurn(chatId, turnId);
this.latestRunTurnIdByChatId.delete(chatId);
if (this.runStartedAtByChatId.delete(chatId)) {
@@ -469,28 +474,8 @@ export class NanobotClient {
completedTurnIds: readonly string[],
snapshot?: CanonicalRunSnapshot,
): boolean {
this.fenceCanonicalCompletedTurns(chatId, completedTurnIds);
const fences = this.canonicalCompletedTurnIdsByChatId.get(chatId) ?? new Set<string>();
for (const turnId of completedTurnIds) {
if (!turnId) continue;
fences.add(turnId);
}
while (fences.size > NanobotClient.COMPLETED_TURN_FENCE_MAX) {
const oldest = fences.values().next().value;
if (typeof oldest !== "string") break;
fences.delete(oldest);
}
if (fences.size > 0) this.canonicalCompletedTurnIdsByChatId.set(chatId, fences);
const pendingInbound = this.pendingInboundByChat.get(chatId);
if (pendingInbound) {
const remaining = pendingInbound.filter((event) => {
const turnId = "turn_id" in event && typeof event.turn_id === "string"
? event.turn_id
: null;
return turnId === null || !fences.has(turnId);
});
if (remaining.length > 0) this.pendingInboundByChat.set(chatId, remaining);
else this.pendingInboundByChat.delete(chatId);
}
if (!this.canReconcileCanonicalCompletion(
chatId,
@@ -515,6 +500,7 @@ export class NanobotClient {
observed,
snapshot,
)) continue;
this.rememberRunCompletion(chatId, turnId);
unsettledTurnIds.delete(turnId);
this.clearPendingMessageSend(chatId, turnId);
this.runStartedAtByTurnKey.delete(this.runSendKey(chatId, turnId));
@@ -528,6 +514,32 @@ export class NanobotClient {
return true;
}
/** Remember explicit terminal facts even when a history snapshot cannot replace live UI. */
fenceCanonicalCompletedTurns(chatId: string, completedTurnIds: readonly string[]): void {
const fences = this.canonicalCompletedTurnIdsByChatId.get(chatId) ?? new Set<string>();
for (const turnId of completedTurnIds) {
if (!turnId) continue;
fences.add(turnId);
}
while (fences.size > NanobotClient.COMPLETED_TURN_FENCE_MAX) {
const oldest = fences.values().next().value;
if (typeof oldest !== "string") break;
fences.delete(oldest);
}
if (fences.size > 0) this.canonicalCompletedTurnIdsByChatId.set(chatId, fences);
const pendingInbound = this.pendingInboundByChat.get(chatId);
if (pendingInbound) {
const remaining = pendingInbound.filter((event) => {
const turnId = "turn_id" in event && typeof event.turn_id === "string"
? event.turn_id
: null;
return turnId === null || !fences.has(turnId);
});
if (remaining.length > 0) this.pendingInboundByChat.set(chatId, remaining);
else this.pendingInboundByChat.delete(chatId);
}
}
/** Last ``goal_state`` payload for *chatId*, if any frame has arrived this connection. */
getGoalState(chatId: string): GoalStateWsPayload | undefined {
return this.goalStateByChatId.get(chatId);
@@ -599,9 +611,22 @@ export class NanobotClient {
private recordCanonicalTurnOwnership(
ev: Extract<InboundEvent, { event: "message_accepted" | "user_message" }>,
): void {
const activeTurnId = ev.active_turn_id;
if (!activeTurnId) return;
): Extract<InboundEvent, { event: "message_accepted" | "user_message" }> {
const activeTurnId = ev.active_turn_id ?? (ev.starts_turn ? ev.turn_id : undefined);
if (!activeTurnId) return ev;
if (this.isRunCompleted(ev.chat_id, activeTurnId)) {
// The input is still valid, but its admission-time owner is already closed.
// Undo a local new-run guess when this input was actually steering that owner.
const pending = ev.turn_id
? this.pendingMessageSends.get(this.runSendKey(ev.chat_id, ev.turn_id))
: undefined;
if (pending?.startsNewRun && ev.turn_id !== activeTurnId) {
this.recordRunRejection(ev.chat_id, ev.turn_id);
if (!this.hasUnsettledRun(ev.chat_id)) this.emitRunStatus(ev.chat_id, null);
}
return { ...ev, active_turn_id: undefined, started_at: undefined, starts_turn: false };
}
// Two clients can optimistically submit while the chat still looks idle.
// The gateway admits exactly one owner and classifies the other message as
@@ -623,6 +648,7 @@ export class NanobotClient {
this.runStartedAtByChatId.set(ev.chat_id, ev.started_at);
if (previous !== ev.started_at) this.emitRunStatus(ev.chat_id, ev.started_at);
}
return ev;
}
private recordRunRejection(chatId: string, turnId?: string): void {
@@ -698,6 +724,22 @@ export class NanobotClient {
);
}
private isRunCompleted(chatId: string, turnId: string): boolean {
return this.closedRunTurnIdsByChatId.get(chatId)?.has(turnId) === true
|| this.canonicalCompletedTurnIdsByChatId.get(chatId)?.has(turnId) === true;
}
private rememberRunCompletion(chatId: string, turnId: string): void {
const closed = this.closedRunTurnIdsByChatId.get(chatId) ?? new Set<string>();
closed.add(turnId);
while (closed.size > NanobotClient.COMPLETED_TURN_FENCE_MAX) {
const oldest = closed.values().next().value;
if (typeof oldest !== "string") break;
closed.delete(oldest);
}
this.closedRunTurnIdsByChatId.set(chatId, closed);
}
private isSupersededRunCompletion(chatId: string, ev: InboundEvent): boolean {
if (
ev.event !== "turn_end"
@@ -716,6 +758,7 @@ export class NanobotClient {
}
private recordRunCompletion(chatId: string, turnId?: string): void {
if (turnId) this.rememberRunCompletion(chatId, turnId);
this.settleRunTurn(chatId, turnId);
const latestRunTurnId = this.latestRunTurnIdByChatId.get(chatId);
const closesCurrentRun = latestRunTurnId === undefined || turnId === latestRunTurnId;
@@ -1136,8 +1179,17 @@ export class NanobotClient {
const turnId = "turn_id" in parsed && typeof parsed.turn_id === "string"
? parsed.turn_id
: null;
const correlatedChatId = (parsed as { chat_id?: string }).chat_id;
// Fence before ownership, clocks, acceptance, or subscribers can mutate state.
if (correlatedChatId && this.isCanonicalCompletedTurnEvent(correlatedChatId, parsed)) return;
if (
correlatedChatId && turnId && this.isRunCompleted(correlatedChatId, turnId)
&& parsed.event !== "message_accepted" && parsed.event !== "user_message"
&& parsed.event !== "message" && parsed.event !== "turn_end"
&& !(parsed.event === "goal_status" && parsed.status === "idle")
) return;
if (parsed.event === "message_accepted" || parsed.event === "user_message") {
this.recordCanonicalTurnOwnership(parsed);
parsed = this.recordCanonicalTurnOwnership(parsed);
}
if (parsed.event === "message_accepted") {
this.recordRunAcceptance(parsed.chat_id, parsed.turn_id);
@@ -1158,7 +1210,6 @@ export class NanobotClient {
return;
}
const correlatedChatId = (parsed as { chat_id?: string }).chat_id;
if (parsed.event === "error" && correlatedChatId && turnId) {
this.recordRunRejection(correlatedChatId, turnId);
if (parsed.detail !== "workspace_scope_rejected") {
@@ -1249,7 +1300,6 @@ export class NanobotClient {
const chatId = (parsed as { chat_id?: string }).chat_id;
if (chatId) {
if (this.isCanonicalCompletedTurnEvent(chatId, parsed)) return;
const supersededRunCompletion = this.isSupersededRunCompletion(chatId, parsed);
this.recordGoalStatusForRunStrip(chatId, parsed);
if (supersededRunCompletion) return;
@@ -1485,6 +1535,7 @@ export class NanobotClient {
this.latestRunTurnIdByChatId.delete(chatId);
this.unsettledRunTurnIdsByChatId.delete(chatId);
this.canonicalCompletedTurnIdsByChatId.delete(chatId);
this.closedRunTurnIdsByChatId.delete(chatId);
this.goalStateByChatId.delete(chatId);
for (const key of [...this.runStartedAtByTurnKey.keys()]) {
if (key.startsWith(`${chatId}\u0000`)) this.runStartedAtByTurnKey.delete(key);
+1
View File
@@ -265,6 +265,7 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => {
};
getRunStartedAt = () => null;
getRunTurnId = () => null;
fenceCanonicalCompletedTurns = vi.fn();
getGoalState = () => undefined;
sendMessage = sendMessageSpy;
newChat = vi.fn();
+39
View File
@@ -141,6 +141,11 @@ function makeClient() {
getRunGeneration: (chatId: string) => runGenerationByChatId.get(chatId) ?? 0,
canReconcileCanonicalCompletion,
reconcileCanonicalCompletion,
fenceCanonicalCompletedTurns: (chatId: string, turnIds: readonly string[]) => {
const fences = completedTurnIdsByChatId.get(chatId) ?? new Set<string>();
for (const turnId of turnIds) fences.add(turnId);
completedTurnIdsByChatId.set(chatId, fences);
},
getGoalState: (chatId: string) => goalStateByChatId.get(chatId),
onChat: (chatId: string, handler: (ev: import("@/lib/types").InboundEvent) => void) => {
let handlers = chatHandlers.get(chatId);
@@ -3173,6 +3178,40 @@ describe("ThreadShell", () => {
expect(client.sendMessage).not.toHaveBeenCalled();
});
it("remembers explicit completed turns on initial history load", async () => {
const client = makeClient();
const turnId = "turn-completed-before-load";
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
if (String(input).includes("websocket%3Ainitial-completion/webui-thread")) {
return httpJson({
...transcriptFromSimpleMessages([
{ role: "user", content: "previous question", turnId },
]),
has_pending_tool_calls: false,
completed_turn_ids: [turnId],
});
}
return { ok: false, status: 404, json: async () => ({}) };
}));
render(wrap(client, <ThreadShell
session={session("initial-completion")}
title="Initial completion"
onToggleSidebar={() => {}}
onNewChat={() => {}}
/>));
await screen.findByText("previous question");
act(() => client._emitChat("initial-completion", {
event: "goal_status", chat_id: "initial-completion", turn_id: turnId,
status: "running", started_at: 4_000,
}));
expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
act(() => client._emitChat("initial-completion", {
event: "goal_status", chat_id: "initial-completion", turn_id: "new-turn",
status: "running", started_at: 5_000,
}));
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
});
it("fences websocket frames that arrive after canonical completion", async () => {
const client = makeClient();
const turnId = "turn-http-won";
+188
View File
@@ -0,0 +1,188 @@
import { act, fireEvent, render, renderHook, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { describe, expect, it, vi } from "vitest";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
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 EMPTY_MESSAGES: UIMessage[] = [];
const CHAT_ID = "completed-turn";
const TURN_ID = "turn-1";
function setup() {
const socket = new TestSocket();
const client = new NanobotClient({
url: "ws://test", reconnect: false,
socketFactory: () => socket as unknown as WebSocket,
});
client.connect();
socket.open();
const wrapper = ({ children }: { children: ReactNode }) => (
<ClientProvider client={client} token="test">{children}</ClientProvider>
);
const running: InboundEvent = {
event: "goal_status", chat_id: CHAT_ID, turn_id: TURN_ID,
status: "running", started_at: 1_700_000_000,
};
return { socket, client, wrapper, running };
}
describe("completed turn event ordering", () => {
it.each(["turn_end", "idle", "stop", "snapshot", "idle snapshot"] as const)(
"keeps %s terminal despite late lifecycle and ownership frames",
(terminal) => {
const { socket, client, wrapper, running } = setup();
const { result, unmount } = renderHook(
() => useNanobotStream(CHAT_ID, EMPTY_MESSAGES), { wrapper },
);
act(() => socket.receive(running));
act(() => {
if (terminal === "stop") result.current.stop();
else if (terminal === "snapshot") {
client.reconcileCanonicalCompletion(CHAT_ID, client.getRunGeneration(CHAT_ID), [TURN_ID]);
} else if (terminal === "idle snapshot") {
expect(client.reconcileCanonicalCompletion(CHAT_ID, client.getRunGeneration(CHAT_ID), [], {
observedTurnIds: [TURN_ID], hasPendingToolCalls: false, activeTurnId: null,
})).toBe(true);
} else socket.receive(terminal === "idle"
? { event: "goal_status", chat_id: CHAT_ID, turn_id: TURN_ID, status: "idle" }
: { event: "turn_end", chat_id: CHAT_ID, turn_id: TURN_ID });
});
expect(result.current.isStreaming).toBe(false);
act(() => {
socket.receive(running);
socket.receive({
event: "user_message", chat_id: CHAT_ID, turn_id: TURN_ID,
text: "late original task", starts_turn: true,
});
socket.receive({
event: "user_message", chat_id: CHAT_ID, turn_id: "input-2",
text: "additional context", starts_turn: false,
active_turn_id: TURN_ID, started_at: 1_700_000_000,
});
socket.receive({
event: "message_accepted", chat_id: CHAT_ID, turn_id: "input-2",
starts_turn: false, active_turn_id: TURN_ID, started_at: 1_700_000_000,
});
socket.receive({ event: "stream_end", chat_id: CHAT_ID, turn_id: TURN_ID, text: "late" });
});
expect(result.current.isStreaming).toBe(false);
expect(result.current.runStartedAt).toBeNull();
expect(client.getRunStartedAt(CHAT_ID)).toBeNull();
expect(client.hasUnsettledRun(CHAT_ID)).toBe(false);
expect(result.current.messages.some((message) => message.content === "additional context")).toBe(true);
act(() => socket.receive({
event: "goal_status", chat_id: CHAT_ID, turn_id: "turn-3",
status: "running", started_at: 1_700_000_100,
}));
act(() => {
socket.receive(running);
socket.receive({
event: "message_accepted", chat_id: CHAT_ID, turn_id: "input-2",
starts_turn: false, active_turn_id: TURN_ID, started_at: 1_700_000_000,
});
});
expect(result.current.isStreaming).toBe(true);
expect(client.getRunTurnId(CHAT_ID)).toBe("turn-3");
expect(result.current.runStartedAt).toBe(1_700_000_100);
unmount();
client.close();
},
);
it("settles a local new-run guess admitted as steering of an already completed owner", () => {
const { socket, client, wrapper, running } = setup();
const { result, unmount } = renderHook(
() => useNanobotStream(CHAT_ID, EMPTY_MESSAGES), { wrapper },
);
act(() => {
socket.receive(running);
socket.receive({ event: "turn_end", chat_id: CHAT_ID, turn_id: TURN_ID });
});
act(() => result.current.send("additional context"));
const inputTurnId = client.getRunTurnId(CHAT_ID)!;
expect(result.current.isStreaming).toBe(true);
act(() => socket.receive({
event: "message_accepted", chat_id: CHAT_ID, turn_id: inputTurnId,
active_turn_id: TURN_ID, starts_turn: false, started_at: 1_700_000_000,
}));
expect(result.current.isStreaming).toBe(false);
expect(client.hasUnsettledRun(CHAT_ID)).toBe(false);
expect(result.current.messages.find((message) => message.content === "additional context"))
.toMatchObject({ deliveryStatus: "accepted" });
unmount();
client.close();
});
it("preserves a final answer and turn outcome arriving after idle", () => {
const { socket, client, wrapper, running } = setup();
const onTurnEnd = vi.fn();
const { result, unmount } = renderHook(
() => useNanobotStream(CHAT_ID, EMPTY_MESSAGES, false, onTurnEnd), { wrapper },
);
act(() => {
socket.receive(running);
socket.receive({ event: "goal_status", chat_id: CHAT_ID, turn_id: TURN_ID, status: "idle" });
socket.receive({ event: "message", chat_id: CHAT_ID, turn_id: TURN_ID, text: "final answer" });
socket.receive({ event: "turn_end", chat_id: CHAT_ID, turn_id: TURN_ID, latency_ms: 42 });
});
expect(result.current.isStreaming).toBe(false);
expect(result.current.messages.find((message) => message.content === "final answer"))
.toMatchObject({ latencyMs: 42 });
expect(onTurnEnd).toHaveBeenCalledOnce();
unmount();
client.close();
});
it("sends queued guidance once when completion and an old broadcast are batched", () => {
const { socket, client, running } = setup();
const onSend = vi.fn();
function Composer() {
const stream = useNanobotStream(CHAT_ID, EMPTY_MESSAGES);
return <ThreadComposer onSend={onSend} onStop={stream.stop}
isStreaming={stream.isStreaming || stream.runStartedAt !== null} />;
}
const { unmount } = render(
<ClientProvider client={client} token="test"><Composer /></ClientProvider>,
);
act(() => socket.receive(running));
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "follow-up" } });
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend).not.toHaveBeenCalled();
act(() => {
socket.receive({ event: "turn_end", chat_id: CHAT_ID, turn_id: TURN_ID });
socket.receive({ event: "goal_status", chat_id: CHAT_ID, turn_id: TURN_ID, status: "idle" });
socket.receive({
event: "user_message", chat_id: CHAT_ID, turn_id: TURN_ID, text: "original task",
starts_turn: true, active_turn_id: TURN_ID, started_at: 1_700_000_000,
});
});
expect(onSend).toHaveBeenCalledOnce();
expect(onSend).toHaveBeenCalledWith("follow-up");
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
act(() => socket.receive({ event: "turn_end", chat_id: CHAT_ID, turn_id: TURN_ID }));
expect(onSend).toHaveBeenCalledOnce();
unmount();
client.close();
});
});