fix(webui): share sidebar and Composer run state (#6337)
This commit is contained in:
1 parent
3d0f8feb77
commit
5ae49a43e7
13 files changed
+378
-374
No files matched your search
@@ -6,6 +6,7 @@ import type { Window as HappyWindow } from "happy-dom";
|
||||
import i18n from "@/i18n";
|
||||
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
|
||||
import { useSessions } from "@/hooks/useSessions";
|
||||
import type { RunState } from "@/lib/nanobot-client";
|
||||
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
|
||||
import type {
|
||||
ChatSummary,
|
||||
@@ -33,7 +34,10 @@ const sendMessageSpy = vi.fn();
|
||||
const sendSystemCommandSpy = vi.fn().mockResolvedValue(undefined);
|
||||
let mockDefaultChatId: string | null = null;
|
||||
const statusHandlers = new Set<(status: ConnectionStatus) => void>();
|
||||
const runStatusHandlers = new Set<(chatId: string, startedAt: number | null) => void>();
|
||||
const runStatusHandlers = new Set<(chatId: string, state: RunState) => void>();
|
||||
const runState = (startedAt: number | null): RunState => ({
|
||||
active: startedAt !== null, startedAt, latestTurnId: null, generation: 0, unsettled: false,
|
||||
});
|
||||
const sessionUpdateHandlers = new Set<(
|
||||
chatId: string,
|
||||
scope?: string,
|
||||
@@ -272,11 +276,13 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => {
|
||||
sidebarStateUpdateHandlers.add(handler);
|
||||
return () => sidebarStateUpdateHandlers.delete(handler);
|
||||
};
|
||||
onRunStatus = (handler: (chatId: string, startedAt: number | null) => void) => {
|
||||
onRunStatus = (handler: (chatId: string, state: RunState) => void) => {
|
||||
runStatusHandlers.add(handler);
|
||||
return () => runStatusHandlers.delete(handler);
|
||||
};
|
||||
onRunCompletion = () => () => {};
|
||||
getRunState = () => runState(null);
|
||||
restorePendingRun = vi.fn();
|
||||
getRunStartedAt = () => null;
|
||||
getRunTurnId = () => null;
|
||||
getUnsettledRunChatIds = () => [];
|
||||
@@ -2915,12 +2921,12 @@ describe("App layout", () => {
|
||||
);
|
||||
|
||||
act(() => {
|
||||
for (const handler of runStatusHandlers) handler("chat-a", 12_345);
|
||||
for (const handler of runStatusHandlers) handler("chat-a", runState(12_345));
|
||||
});
|
||||
expect(within(sidebar).getByRole("img", { name: "Agent running" })).toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
for (const handler of runStatusHandlers) handler("chat-a", null);
|
||||
for (const handler of runStatusHandlers) handler("chat-a", runState(null));
|
||||
});
|
||||
expect(within(sidebar).queryByRole("img", { name: "Agent running" }))
|
||||
.not.toBeInTheDocument();
|
||||
@@ -2969,12 +2975,12 @@ describe("App layout", () => {
|
||||
await waitFor(() => expect(document.title).toContain("Active work"));
|
||||
|
||||
act(() => {
|
||||
for (const handler of runStatusHandlers) handler("chat-a", 12_345);
|
||||
for (const handler of runStatusHandlers) handler("chat-a", runState(12_345));
|
||||
});
|
||||
expect(within(sidebar).getByRole("img", { name: "Agent running" })).toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
for (const handler of runStatusHandlers) handler("chat-a", null);
|
||||
for (const handler of runStatusHandlers) handler("chat-a", runState(null));
|
||||
});
|
||||
expect(within(sidebar).queryByRole("img", { name: "Agent running" }))
|
||||
.not.toBeInTheDocument();
|
||||
@@ -3062,12 +3068,12 @@ describe("App layout", () => {
|
||||
await waitFor(() => expect(attachSpy).toHaveBeenCalledWith("chat-a"));
|
||||
expect(within(sidebar).queryByRole("img", { name: "Agent running" })).not.toBeInTheDocument();
|
||||
act(() => {
|
||||
for (const handler of runStatusHandlers) handler("chat-a", 12_345);
|
||||
for (const handler of runStatusHandlers) handler("chat-a", runState(12_345));
|
||||
});
|
||||
expect(within(sidebar).getByRole("img", { name: "Agent running" })).toBeInTheDocument();
|
||||
expect(within(sidebar).getByRole("img", { name: "New activity" })).toBeInTheDocument();
|
||||
act(() => {
|
||||
for (const handler of runStatusHandlers) handler("chat-a", null);
|
||||
for (const handler of runStatusHandlers) handler("chat-a", runState(null));
|
||||
});
|
||||
mockSessions = mockSessions.map((session) => ({ ...session }));
|
||||
rerender(<App />);
|
||||
|
||||
@@ -630,7 +630,7 @@ describe("NanobotClient", () => {
|
||||
expect(client.getRunStartedAt("chat-stop")).toBeNull();
|
||||
expect(client.hasUnsettledRun("chat-stop")).toBe(false);
|
||||
expect(client.isRunCompleted("chat-stop", "turn-stop")).toBe(true);
|
||||
expect(handler).toHaveBeenLastCalledWith("chat-stop", null);
|
||||
expect(handler).toHaveBeenLastCalledWith("chat-stop", expect.objectContaining({ active: false, startedAt: null }));
|
||||
});
|
||||
|
||||
it("preserves durable run clocks and identities through transport reconnect", async () => {
|
||||
@@ -672,7 +672,7 @@ describe("NanobotClient", () => {
|
||||
expect(client.getUnsettledRunChatIds()).toEqual([]);
|
||||
expect(client.isRunCompleted("chat-strip", "turn-strip")).toBe(true);
|
||||
expect(client.isRunCompleted("another-chat", "turn-strip")).toBe(false);
|
||||
expect(handler).toHaveBeenLastCalledWith("chat-strip", null);
|
||||
expect(handler).toHaveBeenLastCalledWith("chat-strip", expect.objectContaining({ active: false, startedAt: null }));
|
||||
client.close();
|
||||
});
|
||||
|
||||
@@ -697,7 +697,7 @@ describe("NanobotClient", () => {
|
||||
chat_id: "chat-strip",
|
||||
});
|
||||
expect(client.getRunStartedAt("chat-strip")).toBeNull();
|
||||
expect(handler).toHaveBeenLastCalledWith("chat-strip", null);
|
||||
expect(handler).toHaveBeenLastCalledWith("chat-strip", expect.objectContaining({ active: false, startedAt: null }));
|
||||
});
|
||||
|
||||
it("rejects a completed snapshot when a newer run is not represented", () => {
|
||||
@@ -1752,7 +1752,7 @@ describe("NanobotClient", () => {
|
||||
),
|
||||
).toBe(true);
|
||||
expect(client.getRunStartedAt("chat-canonical")).toBeNull();
|
||||
expect(runHandler).toHaveBeenLastCalledWith("chat-canonical", null);
|
||||
expect(runHandler).toHaveBeenLastCalledWith("chat-canonical", expect.objectContaining({ active: false, startedAt: null }));
|
||||
const deliveredBeforeLateFrames = chatHandler.mock.calls.length;
|
||||
|
||||
lastSocket().fakeMessage({
|
||||
@@ -1805,19 +1805,22 @@ describe("NanobotClient", () => {
|
||||
status: "running",
|
||||
started_at: 12_345,
|
||||
});
|
||||
expect(handler).toHaveBeenCalledWith("chat-status", 12_345);
|
||||
expect(handler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: true, startedAt: 12_345 }));
|
||||
|
||||
const lateHandler = vi.fn();
|
||||
client.onRunStatus(lateHandler);
|
||||
expect(lateHandler).toHaveBeenCalledWith("chat-status", 12_345);
|
||||
expect(lateHandler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: true, startedAt: 12_345 }));
|
||||
|
||||
lastSocket().fakeMessage({
|
||||
event: "goal_status",
|
||||
chat_id: "chat-status",
|
||||
status: "idle",
|
||||
});
|
||||
expect(handler).toHaveBeenCalledWith("chat-status", null);
|
||||
expect(lateHandler).toHaveBeenCalledWith("chat-status", null);
|
||||
expect(handler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: false, startedAt: null }));
|
||||
expect(lateHandler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: false, startedAt: null }));
|
||||
const idleSubscriber = vi.fn();
|
||||
client.onRunStatus(idleSubscriber);
|
||||
expect(idleSubscriber).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: false, startedAt: null }));
|
||||
});
|
||||
|
||||
it("records goal_state per chat_id without an onChat subscriber", () => {
|
||||
@@ -2567,6 +2570,7 @@ describe("binary attachment transport", () => {
|
||||
const delivery = client.sendAttachments("chat", "look", [
|
||||
{ data_url: "data:text/plain;base64,eA==", name: "note.txt" },
|
||||
], { turnId: "slow-upload" });
|
||||
expect(client.getRunState("chat")).toMatchObject({ active: true, startedAt: null });
|
||||
await vi.advanceTimersByTimeAsync(80_000);
|
||||
expect(socket.sent.some((frame) => frame.includes("slow-ref"))).toBe(true);
|
||||
socket.fakeMessage({ event: "message_accepted", chat_id: "chat", turn_id: "slow-upload" });
|
||||
@@ -2637,6 +2641,7 @@ describe("binary attachment transport", () => {
|
||||
upload: { path: "/api/attachments", token: "cap" } });
|
||||
const draft = [{ data_url: "data:text/plain;base64,eA==", name: "note.txt" }];
|
||||
await expect(client.sendAttachments("chat", "look", draft)).rejects.toThrow("401");
|
||||
expect(client.getRunState("chat").active).toBe(false);
|
||||
expect(socket.sent.filter((frame) => JSON.parse(frame).type === "message")).toHaveLength(0);
|
||||
expect(draft[0].data_url).toBe("data:text/plain;base64,eA==");
|
||||
fetchMock.mockImplementation(async () => {
|
||||
@@ -2644,6 +2649,7 @@ describe("binary attachment transport", () => {
|
||||
return Response.json({ reference: "old-connection-ref" });
|
||||
});
|
||||
await expect(client.sendAttachments("chat", "look", draft)).rejects.toThrow("Connection changed");
|
||||
expect(client.getRunState("chat").active).toBe(false);
|
||||
expect(socket.sent.filter((frame) => JSON.parse(frame).type === "message")).toHaveLength(0);
|
||||
} finally { client.close(); vi.unstubAllGlobals(); }
|
||||
});
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import type { InboundEvent } from "@/lib/types";
|
||||
|
||||
/** Real lifecycle and dispatch with an in-memory transport. */
|
||||
export function createStreamClient() {
|
||||
const socket = {
|
||||
readyState: 1,
|
||||
onopen: null as (() => void) | null,
|
||||
onmessage: null as ((event: MessageEvent) => void) | null,
|
||||
send() {},
|
||||
close() {},
|
||||
};
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test", reconnect: false,
|
||||
socketFactory: () => socket as unknown as WebSocket,
|
||||
});
|
||||
client.connect();
|
||||
socket.onopen?.();
|
||||
return {
|
||||
client,
|
||||
receive(event: InboundEvent) {
|
||||
socket.onmessage?.({ data: JSON.stringify(event) } as MessageEvent);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import type {
|
||||
WebuiThreadPersistedPayload,
|
||||
} from "@/lib/types";
|
||||
import { canonicalThreadPayload } from "./thread-test-payload";
|
||||
import { createStreamClient } from "./stream-client";
|
||||
|
||||
const HERO_GREETING_PATTERN =
|
||||
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
|
||||
@@ -35,65 +36,16 @@ async function openMessageActions(text: string): Promise<HTMLElement> {
|
||||
}
|
||||
|
||||
function makeClient() {
|
||||
const { client: lifecycle, receive } = createStreamClient();
|
||||
const errorHandlers = new Set<(err: StreamError) => void>();
|
||||
const statusHandlers = new Set<(status: ConnectionStatus) => void>();
|
||||
const chatHandlers = new Map<string, Set<(ev: import("@/lib/types").InboundEvent) => void>>();
|
||||
const runtimeModelHandlers = new Set<
|
||||
(modelName: string | null, modelPreset?: string | null) => void
|
||||
>();
|
||||
const sessionUpdateHandlers = new Set<(chatId: string, scope?: string) => void>();
|
||||
const runStatusHandlers = new Set<(chatId: string, startedAt: number | null) => void>();
|
||||
const runCompletionHandlers = new Set<(chatId: string) => void>();
|
||||
const runStartedAtByChatId = new Map<string, number>();
|
||||
const runGenerationByChatId = new Map<string, number>();
|
||||
const latestRunTurnIdByChatId = new Map<string, string>();
|
||||
const closedRunTurnIdsByChatId = new Map<string, Set<string>>();
|
||||
const completedTurnIdsByChatId = new Map<string, Set<string>>();
|
||||
const goalStateByChatId = new Map<string, import("@/lib/types").GoalStateWsPayload>();
|
||||
let status: ConnectionStatus = "open";
|
||||
const advanceRunGeneration = (chatId: string, turnId?: string) => {
|
||||
runGenerationByChatId.set(chatId, (runGenerationByChatId.get(chatId) ?? 0) + 1);
|
||||
if (turnId) latestRunTurnIdByChatId.set(chatId, turnId);
|
||||
else latestRunTurnIdByChatId.delete(chatId);
|
||||
};
|
||||
const sendMessage = vi.fn((
|
||||
chatId: string,
|
||||
_content: string,
|
||||
_media?: unknown,
|
||||
options?: { turnId?: string; startsNewRun?: boolean },
|
||||
) => {
|
||||
if (options?.turnId && options.startsNewRun !== false) {
|
||||
advanceRunGeneration(chatId, options.turnId);
|
||||
}
|
||||
});
|
||||
const canReconcileCanonicalCompletion = vi.fn((
|
||||
chatId: string,
|
||||
expectedRunGeneration: number,
|
||||
completedTurnIds: readonly string[],
|
||||
snapshot?: CanonicalRunSnapshot,
|
||||
) => {
|
||||
const existingFences = completedTurnIdsByChatId.get(chatId);
|
||||
const prospectiveFences = new Set(completedTurnIds);
|
||||
const observedTurnIds = new Set(snapshot?.observedTurnIds ?? []);
|
||||
const isRepresented = (turnId: string) => (
|
||||
prospectiveFences.has(turnId)
|
||||
|| existingFences?.has(turnId) === true
|
||||
|| (
|
||||
snapshot?.completionIdsProvided !== true
|
||||
&& snapshot?.hasPendingToolCalls === false
|
||||
&& snapshot?.activeTurnId !== turnId
|
||||
&& observedTurnIds.has(turnId)
|
||||
)
|
||||
);
|
||||
const currentGeneration = runGenerationByChatId.get(chatId) ?? 0;
|
||||
const latestTurnId = latestRunTurnIdByChatId.get(chatId);
|
||||
if (latestTurnId && !closedRunTurnIdsByChatId.get(chatId)?.has(latestTurnId)
|
||||
&& !isRepresented(latestTurnId)) return false;
|
||||
return (
|
||||
currentGeneration === expectedRunGeneration
|
||||
|| (typeof latestTurnId === "string" && isRepresented(latestTurnId))
|
||||
);
|
||||
});
|
||||
const sendMessage = vi.fn(lifecycle.sendMessage.bind(lifecycle));
|
||||
const canReconcileCanonicalCompletion = vi.fn(lifecycle.canReconcileCanonicalCompletion.bind(lifecycle));
|
||||
const reconcileCanonicalCompletion = vi.fn((
|
||||
chatId: string,
|
||||
expectedRunGeneration: number,
|
||||
@@ -108,12 +60,7 @@ function makeClient() {
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
const fences = completedTurnIdsByChatId.get(chatId) ?? new Set<string>();
|
||||
for (const turnId of completedTurnIds) fences.add(turnId);
|
||||
completedTurnIdsByChatId.set(chatId, fences);
|
||||
const hadClock = runStartedAtByChatId.delete(chatId);
|
||||
if (hadClock) for (const h of runStatusHandlers) h(chatId, null);
|
||||
return true;
|
||||
return lifecycle.reconcileCanonicalCompletion(chatId, expectedRunGeneration, completedTurnIds, snapshot);
|
||||
});
|
||||
return {
|
||||
get status() {
|
||||
@@ -127,17 +74,8 @@ function makeClient() {
|
||||
statusHandlers.delete(handler);
|
||||
};
|
||||
},
|
||||
onRunStatus: (handler: (chatId: string, startedAt: number | null) => void) => {
|
||||
runStatusHandlers.add(handler);
|
||||
for (const [chatId, startedAt] of runStartedAtByChatId) handler(chatId, startedAt);
|
||||
return () => {
|
||||
runStatusHandlers.delete(handler);
|
||||
};
|
||||
},
|
||||
onRunCompletion: (handler: (chatId: string) => void) => {
|
||||
runCompletionHandlers.add(handler);
|
||||
return () => { runCompletionHandlers.delete(handler); };
|
||||
},
|
||||
onRunStatus: lifecycle.onRunStatus.bind(lifecycle),
|
||||
onRunCompletion: lifecycle.onRunCompletion.bind(lifecycle),
|
||||
onRuntimeModelUpdate: (
|
||||
handler: (modelName: string | null, modelPreset?: string | null) => void,
|
||||
) => {
|
||||
@@ -146,40 +84,20 @@ function makeClient() {
|
||||
runtimeModelHandlers.delete(handler);
|
||||
};
|
||||
},
|
||||
getRunStartedAt: (chatId: string) => runStartedAtByChatId.get(chatId) ?? null,
|
||||
getRunTurnId: (chatId: string) => latestRunTurnIdByChatId.get(chatId) ?? null,
|
||||
isRunCompleted: (chatId: string, turnId: string) => (
|
||||
closedRunTurnIdsByChatId.get(chatId)?.has(turnId) === true
|
||||
|| completedTurnIdsByChatId.get(chatId)?.has(turnId) === true
|
||||
),
|
||||
finishRunLocally: vi.fn((chatId: string) => {
|
||||
runStartedAtByChatId.delete(chatId);
|
||||
latestRunTurnIdByChatId.delete(chatId);
|
||||
}),
|
||||
hasUnsettledRun: () => false,
|
||||
getRunGeneration: (chatId: string) => runGenerationByChatId.get(chatId) ?? 0,
|
||||
getRunState: lifecycle.getRunState.bind(lifecycle),
|
||||
restorePendingRun: lifecycle.restorePendingRun.bind(lifecycle),
|
||||
getRunStartedAt: lifecycle.getRunStartedAt.bind(lifecycle),
|
||||
getRunTurnId: lifecycle.getRunTurnId.bind(lifecycle),
|
||||
isRunCompleted: lifecycle.isRunCompleted.bind(lifecycle),
|
||||
finishRunLocally: vi.fn(lifecycle.finishRunLocally.bind(lifecycle)),
|
||||
hasUnsettledRun: lifecycle.hasUnsettledRun.bind(lifecycle),
|
||||
getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle),
|
||||
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),
|
||||
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) {
|
||||
handlers = new Set();
|
||||
chatHandlers.set(chatId, handlers);
|
||||
}
|
||||
handlers.add(handler);
|
||||
return () => {
|
||||
handlers?.delete(handler);
|
||||
};
|
||||
},
|
||||
fenceCanonicalCompletedTurns: lifecycle.fenceCanonicalCompletedTurns.bind(lifecycle),
|
||||
getGoalState: lifecycle.getGoalState.bind(lifecycle),
|
||||
onTranscript: lifecycle.onTranscript.bind(lifecycle),
|
||||
onChat: lifecycle.onChat.bind(lifecycle),
|
||||
onError: (handler: (err: StreamError) => void) => {
|
||||
errorHandlers.add(handler);
|
||||
return () => {
|
||||
@@ -193,48 +111,16 @@ function makeClient() {
|
||||
};
|
||||
},
|
||||
_emitError(err: StreamError) {
|
||||
if (err.kind !== "model_request_failed" && err.chatId && err.turnId) {
|
||||
if (latestRunTurnIdByChatId.get(err.chatId) === err.turnId) {
|
||||
latestRunTurnIdByChatId.delete(err.chatId);
|
||||
const hadClock = runStartedAtByChatId.delete(err.chatId);
|
||||
if (hadClock) for (const h of runStatusHandlers) h(err.chatId, null);
|
||||
}
|
||||
}
|
||||
if (err.chatId && err.turnId) receive({
|
||||
event: "error", chat_id: err.chatId, turn_id: err.turnId, detail: err.kind,
|
||||
});
|
||||
for (const h of errorHandlers) h(err);
|
||||
},
|
||||
_emitStatus(nextStatus: ConnectionStatus) {
|
||||
status = nextStatus;
|
||||
for (const h of statusHandlers) h(status);
|
||||
},
|
||||
_emitChat(chatId: string, ev: import("@/lib/types").InboundEvent) {
|
||||
const turnId = "turn_id" in ev && typeof ev.turn_id === "string" ? ev.turn_id : null;
|
||||
if (turnId && completedTurnIdsByChatId.get(chatId)?.has(turnId)) return;
|
||||
if (
|
||||
ev.event === "goal_status"
|
||||
&& ev.status === "running"
|
||||
&& typeof ev.started_at === "number"
|
||||
) {
|
||||
advanceRunGeneration(chatId, ev.turn_id);
|
||||
runStartedAtByChatId.set(chatId, ev.started_at);
|
||||
for (const h of runStatusHandlers) h(chatId, ev.started_at);
|
||||
} else if (
|
||||
(ev.event === "goal_status" && ev.status === "idle")
|
||||
|| ev.event === "turn_end"
|
||||
) {
|
||||
if (turnId) {
|
||||
const closed = closedRunTurnIdsByChatId.get(chatId) ?? new Set<string>();
|
||||
closed.add(turnId);
|
||||
closedRunTurnIdsByChatId.set(chatId, closed);
|
||||
}
|
||||
runStartedAtByChatId.delete(chatId);
|
||||
for (const h of runStatusHandlers) h(chatId, null);
|
||||
for (const h of runCompletionHandlers) h(chatId);
|
||||
}
|
||||
if (ev.event === "goal_state") {
|
||||
goalStateByChatId.set(chatId, ev.goal_state);
|
||||
}
|
||||
for (const h of chatHandlers.get(chatId) ?? []) h(ev);
|
||||
},
|
||||
_emitChat(_chatId: string, ev: import("@/lib/types").InboundEvent) { receive(ev); },
|
||||
_emitRuntimeModelUpdate(modelName: string | null, modelPreset?: string | null) {
|
||||
for (const h of runtimeModelHandlers) h(modelName, modelPreset);
|
||||
},
|
||||
@@ -3300,7 +3186,13 @@ describe("ThreadShell", () => {
|
||||
detail: "message_rejected",
|
||||
}));
|
||||
|
||||
act(() => client._emitSessionUpdate("empty-reset-chat", "thread"));
|
||||
act(() => {
|
||||
client._emitError({
|
||||
kind: "turn_rejected", chatId: "empty-reset-chat",
|
||||
turnId: client.sendMessage.mock.calls[0][3]!.turnId!,
|
||||
});
|
||||
client._emitSessionUpdate("empty-reset-chat", "thread");
|
||||
});
|
||||
|
||||
await waitFor(() => expect(historyCalls).toBe(2));
|
||||
await waitFor(() =>
|
||||
@@ -5357,6 +5249,24 @@ describe("ThreadShell", () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByRole("button", { name: "停止响应" })).toBeInTheDocument();
|
||||
const nextTurnId = client.getRunTurnId("chat-model-failure")!;
|
||||
act(() => {
|
||||
client._emitChat("chat-model-failure", {
|
||||
event: "goal_status", chat_id: "chat-model-failure", turn_id: nextTurnId,
|
||||
status: "running", started_at: 1_700_000_000,
|
||||
});
|
||||
client._emitChat("chat-model-failure", {
|
||||
event: "delta", chat_id: "chat-model-failure", turn_id: nextTurnId,
|
||||
text: "New request is running",
|
||||
});
|
||||
});
|
||||
expect(await screen.findByText("New request is running")).toBeVisible();
|
||||
expect(client.getRunState("chat-model-failure")).toMatchObject({ active: true, startedAt: 1_700_000_000 });
|
||||
act(() => client._emitChat("chat-model-failure", {
|
||||
event: "turn_end", chat_id: "chat-model-failure", turn_id: nextTurnId,
|
||||
}));
|
||||
expect(screen.queryByRole("button", { name: "停止响应" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("moves a correlated delivery error from the banner into the failed message tooltip", async () => {
|
||||
@@ -5881,7 +5791,7 @@ describe("ThreadShell", () => {
|
||||
expect(client.sendMessage).toHaveBeenCalledWith("resuming-chat", "/stop");
|
||||
});
|
||||
|
||||
it("allows a new turn after a completed recovery state", async () => {
|
||||
it.each(["awaiting_user", "failed", "recovered"] as const)("allows a new turn after a %s recovery state", async (status) => {
|
||||
const client = makeClient();
|
||||
render(wrap(
|
||||
client,
|
||||
@@ -5898,7 +5808,7 @@ describe("ThreadShell", () => {
|
||||
event: "recovery_state",
|
||||
chat_id: "recovered-chat",
|
||||
recovery_id: "recovery-1",
|
||||
status: "recovered",
|
||||
status,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -45,6 +45,75 @@ function setup() {
|
||||
}
|
||||
|
||||
describe("completed turn event ordering", () => {
|
||||
it("does not restore busy state from pending history delivered after completion", () => {
|
||||
const { socket, client, wrapper, running } = setup();
|
||||
const staleHistory: UIMessage[] = [{
|
||||
id: "persisted-user", role: "user", content: "original request", turnId: TURN_ID, createdAt: 0,
|
||||
}];
|
||||
const { result, rerender, unmount } = renderHook(
|
||||
({ pending, history, active }: { pending: boolean; history: UIMessage[]; active: string | null }) =>
|
||||
useNanobotStream(CHAT_ID, history, pending, undefined, undefined, [], undefined, active),
|
||||
{ wrapper, initialProps: { pending: false, history: EMPTY_MESSAGES, active: null as string | null } },
|
||||
);
|
||||
act(() => {
|
||||
socket.receive(running);
|
||||
socket.receive({ event: "stream_end", chat_id: CHAT_ID, turn_id: TURN_ID, text: "done" });
|
||||
socket.receive({ event: "turn_end", chat_id: CHAT_ID, turn_id: TURN_ID });
|
||||
});
|
||||
expect(result.current.isStreaming).toBe(false);
|
||||
rerender({ pending: true, history: staleHistory, active: TURN_ID });
|
||||
expect(result.current.isStreaming).toBe(false);
|
||||
expect(client.hasUnsettledRun(CHAT_ID)).toBe(false);
|
||||
act(() => socket.receive({
|
||||
...running, turn_id: "next-turn", started_at: 1_700_000_100,
|
||||
}));
|
||||
rerender({ pending: false, history: staleHistory, active: null });
|
||||
expect(result.current.isStreaming).toBe(true);
|
||||
expect(client.getRunTurnId(CHAT_ID)).toBe("next-turn");
|
||||
unmount();
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("shares optimistic activity before a gateway start clock exists", () => {
|
||||
const { socket, client, wrapper } = setup();
|
||||
const status = vi.fn();
|
||||
client.onRunStatus(status);
|
||||
const { result, unmount } = renderHook(
|
||||
() => useNanobotStream(CHAT_ID, EMPTY_MESSAGES), { wrapper },
|
||||
);
|
||||
act(() => { result.current.send("new request"); });
|
||||
expect(result.current.isStreaming).toBe(true);
|
||||
expect(result.current.runStartedAt).toBeNull();
|
||||
expect(status).toHaveBeenLastCalledWith(CHAT_ID,
|
||||
expect.objectContaining({ active: true, startedAt: null }));
|
||||
const turnId = client.getRunTurnId(CHAT_ID)!;
|
||||
act(() => socket.receive({
|
||||
event: "turn_end", chat_id: CHAT_ID, turn_id: turnId,
|
||||
}));
|
||||
expect(result.current.isStreaming).toBe(false);
|
||||
expect(status).toHaveBeenLastCalledWith(CHAT_ID,
|
||||
expect.objectContaining({ active: false, startedAt: null }));
|
||||
unmount();
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("restores the canonical owner rather than a steering input at the history tail", () => {
|
||||
const { socket, client, wrapper } = setup();
|
||||
const initial: UIMessage[] = [{
|
||||
id: "steering", role: "user", content: "additional guidance", turnId: "input-2", createdAt: Date.now(),
|
||||
}];
|
||||
const { result, unmount } = renderHook(
|
||||
() => useNanobotStream(CHAT_ID, initial, true, undefined, undefined, [], undefined, TURN_ID), { wrapper },
|
||||
);
|
||||
expect(result.current.isStreaming).toBe(true);
|
||||
expect(client.getRunTurnId(CHAT_ID)).toBe(TURN_ID);
|
||||
act(() => socket.receive({ event: "turn_end", chat_id: CHAT_ID, turn_id: TURN_ID }));
|
||||
expect(result.current.isStreaming).toBe(false);
|
||||
expect(client.hasUnsettledRun(CHAT_ID)).toBe(false);
|
||||
unmount();
|
||||
client.close();
|
||||
});
|
||||
|
||||
it.each(["turn_end", "idle", "stop", "snapshot", "idle snapshot"] as const)(
|
||||
"keeps %s terminal despite late lifecycle and ownership frames",
|
||||
(terminal) => {
|
||||
|
||||
@@ -6,16 +6,16 @@ import { useNanobotStream } from "@/hooks/useNanobotStream";
|
||||
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
|
||||
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import type { StreamError } from "@/lib/nanobot-client";
|
||||
import type { NanobotClient, StreamError } from "@/lib/nanobot-client";
|
||||
import type {
|
||||
ConnectionStatus,
|
||||
GoalStateWsPayload,
|
||||
InboundEvent,
|
||||
UIMediaAttachment,
|
||||
UIMessage,
|
||||
} from "@/lib/types";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
import projectionFixture from "./fixtures/live-replay-event-projection.json";
|
||||
import { createStreamClient } from "./stream-client";
|
||||
|
||||
const EMPTY_MESSAGES: UIMessage[] = [];
|
||||
|
||||
@@ -72,112 +72,64 @@ function normalizeProjection(messages: UIMessage[]): Array<Record<string, unknow
|
||||
}
|
||||
|
||||
function fakeClient() {
|
||||
const handlers = new Map<string, Set<(ev: InboundEvent) => void>>();
|
||||
const { client: lifecycle, receive } = createStreamClient();
|
||||
const statusHandlers = new Set<(status: ConnectionStatus) => void>();
|
||||
const runStatusHandlers = new Set<(chatId: string, startedAt: number | null) => void>();
|
||||
const errorHandlers = new Set<(error: StreamError) => void>();
|
||||
const runStartedAtByChatId = new Map<string, number>();
|
||||
const unsettledRunByChatId = new Map<string, boolean>();
|
||||
const goalStateByChatId = new Map<string, GoalStateWsPayload>();
|
||||
const requestMutation = vi.fn().mockResolvedValue({});
|
||||
let status: ConnectionStatus = "open";
|
||||
|
||||
function recordGoalStatusForRunStrip(chatId: string, ev: InboundEvent) {
|
||||
if (ev.event === "turn_end") {
|
||||
runStartedAtByChatId.delete(chatId);
|
||||
return;
|
||||
}
|
||||
if (ev.event !== "goal_status") return;
|
||||
if (ev.status === "running" && typeof ev.started_at === "number") {
|
||||
runStartedAtByChatId.set(chatId, ev.started_at);
|
||||
} else {
|
||||
runStartedAtByChatId.delete(chatId);
|
||||
}
|
||||
}
|
||||
|
||||
function recordGoalStateSnapshot(chatId: string, ev: InboundEvent) {
|
||||
if (ev.event === "goal_state") {
|
||||
goalStateByChatId.set(chatId, ev.goal_state);
|
||||
return;
|
||||
}
|
||||
if (ev.event === "turn_end" && ev.goal_state != null && typeof ev.goal_state === "object") {
|
||||
goalStateByChatId.set(chatId, ev.goal_state);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
client: {
|
||||
get status() {
|
||||
return status;
|
||||
},
|
||||
get status() { return status; },
|
||||
defaultChatId: null as string | null,
|
||||
onStatus(handler: (nextStatus: ConnectionStatus) => void) {
|
||||
statusHandlers.add(handler);
|
||||
handler(status);
|
||||
return () => statusHandlers.delete(handler);
|
||||
},
|
||||
onRunStatus(handler: (chatId: string, startedAt: number | null) => void) {
|
||||
runStatusHandlers.add(handler);
|
||||
for (const [chatId, startedAt] of runStartedAtByChatId) handler(chatId, startedAt);
|
||||
return () => runStatusHandlers.delete(handler);
|
||||
},
|
||||
onRunStatus: lifecycle.onRunStatus.bind(lifecycle),
|
||||
getRunState: lifecycle.getRunState.bind(lifecycle),
|
||||
getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle),
|
||||
restorePendingRun: lifecycle.restorePendingRun.bind(lifecycle),
|
||||
getRunStartedAt: lifecycle.getRunStartedAt.bind(lifecycle),
|
||||
getRunTurnId: lifecycle.getRunTurnId.bind(lifecycle),
|
||||
getGoalState: lifecycle.getGoalState.bind(lifecycle),
|
||||
hasUnsettledRun: lifecycle.hasUnsettledRun.bind(lifecycle),
|
||||
onTranscript: lifecycle.onTranscript.bind(lifecycle),
|
||||
onError(handler: (error: StreamError) => void) {
|
||||
errorHandlers.add(handler);
|
||||
return () => errorHandlers.delete(handler);
|
||||
},
|
||||
getRunStartedAt(chatId: string) {
|
||||
const v = runStartedAtByChatId.get(chatId);
|
||||
return v === undefined ? null : v;
|
||||
},
|
||||
getRunTurnId() {
|
||||
return null;
|
||||
},
|
||||
getGoalState(chatId: string) {
|
||||
return goalStateByChatId.get(chatId);
|
||||
},
|
||||
hasUnsettledRun(chatId: string) {
|
||||
return unsettledRunByChatId.get(chatId) === true;
|
||||
},
|
||||
onTranscript(chatId: string, h: (ev: InboundEvent) => void) {
|
||||
let set = handlers.get(chatId);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
handlers.set(chatId, set);
|
||||
}
|
||||
set.add(h);
|
||||
return () => set!.delete(h);
|
||||
},
|
||||
sendMessage: vi.fn(),
|
||||
sendAttachments: vi.fn().mockResolvedValue(undefined),
|
||||
sendMessage: vi.fn(lifecycle.sendMessage.bind(lifecycle)),
|
||||
sendAttachments: vi.fn(async (...args: Parameters<NanobotClient["sendAttachments"]>) => {
|
||||
lifecycle.sendMessage(args[0], args[1], undefined, args[3]);
|
||||
}),
|
||||
requestMutation,
|
||||
finishRunLocally: vi.fn(),
|
||||
newChat: vi.fn(),
|
||||
forkChat: vi.fn(),
|
||||
attach: vi.fn(),
|
||||
connect: vi.fn(),
|
||||
close: vi.fn(),
|
||||
updateUrl: vi.fn(),
|
||||
},
|
||||
emit(chatId: string, ev: InboundEvent) {
|
||||
recordGoalStatusForRunStrip(chatId, ev);
|
||||
recordGoalStateSnapshot(chatId, ev);
|
||||
const set = handlers.get(chatId);
|
||||
set?.forEach((h) => h(ev));
|
||||
finishRunLocally: vi.fn(lifecycle.finishRunLocally.bind(lifecycle)),
|
||||
newChat: vi.fn(), forkChat: vi.fn(), attach: vi.fn(),
|
||||
connect: vi.fn(), close: vi.fn(), updateUrl: vi.fn(),
|
||||
},
|
||||
emit(_chatId: string, event: InboundEvent) { receive(event); },
|
||||
emitStatus(nextStatus: ConnectionStatus) {
|
||||
status = nextStatus;
|
||||
statusHandlers.forEach((handler) => handler(status));
|
||||
},
|
||||
emitRunStatus(chatId: string, startedAt: number | null) {
|
||||
if (startedAt === null) runStartedAtByChatId.delete(chatId);
|
||||
else runStartedAtByChatId.set(chatId, startedAt);
|
||||
runStatusHandlers.forEach((handler) => handler(chatId, startedAt));
|
||||
receive({ event: "goal_status", chat_id: chatId,
|
||||
status: startedAt === null ? "idle" : "running",
|
||||
...(startedAt !== null ? { started_at: startedAt } : {}),
|
||||
});
|
||||
},
|
||||
emitError(error: StreamError) {
|
||||
if (error.chatId && error.turnId) receive({
|
||||
event: "error", chat_id: error.chatId, turn_id: error.turnId,
|
||||
detail: error.kind,
|
||||
});
|
||||
errorHandlers.forEach((handler) => handler(error));
|
||||
},
|
||||
setUnsettled(chatId: string, unsettled: boolean) {
|
||||
unsettledRunByChatId.set(chatId, unsettled);
|
||||
if (unsettled) lifecycle.sendMessage(chatId, "pending", undefined, { turnId: "pending-fixture" });
|
||||
else lifecycle.finishRunLocally(chatId);
|
||||
},
|
||||
requestMutation,
|
||||
};
|
||||
@@ -295,7 +247,7 @@ describe("useNanobotStream", () => {
|
||||
});
|
||||
await flushStreamFrame();
|
||||
act(() => { first.result.current.send("/model", undefined, { sideChannel: true }); });
|
||||
const commandTurn = fake.client.sendMessage.mock.calls.at(-1)![3]?.turnId;
|
||||
const commandTurn = fake.client.sendMessage.mock.calls.at(-1)![3]!.turnId!;
|
||||
first.unmount();
|
||||
const snapshot = cache.get("checkpoint")!;
|
||||
expect(snapshot.sideChannelTurnIds.has(commandTurn)).toBe(true);
|
||||
@@ -808,7 +760,7 @@ describe("useNanobotStream", () => {
|
||||
});
|
||||
expect(result.current.isStreaming).toBe(false);
|
||||
expect(result.current.runStartedAt).toBeNull();
|
||||
expect(fake.client.finishRunLocally).toHaveBeenCalledWith("chat-recovery");
|
||||
expect(fake.client.getRunState("chat-recovery").active).toBe(false);
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-recovery", {
|
||||
@@ -836,7 +788,7 @@ describe("useNanobotStream", () => {
|
||||
});
|
||||
});
|
||||
expect(result.current.isStreaming).toBe(false);
|
||||
expect(fake.client.finishRunLocally).toHaveBeenCalledWith("chat-recovery");
|
||||
expect(fake.client.getRunState("chat-recovery").active).toBe(false);
|
||||
});
|
||||
|
||||
it.each(["awaiting_user", "resuming"] as const)(
|
||||
@@ -3787,6 +3739,14 @@ describe("live canonical event projection", () => {
|
||||
|
||||
for (const event of fixtureCase.live_events) {
|
||||
act(() => {
|
||||
// Projection fixtures omit lifecycle admission between their turns.
|
||||
if ("turn_id" in event && event.turn_id
|
||||
&& fake.client.getRunTurnId(fixtureCase.chat_id) !== event.turn_id) {
|
||||
fake.emit(fixtureCase.chat_id, {
|
||||
event: "goal_status", chat_id: fixtureCase.chat_id,
|
||||
turn_id: event.turn_id, status: "running", started_at: 0,
|
||||
});
|
||||
}
|
||||
fake.emit(fixtureCase.chat_id, event);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -299,8 +299,8 @@ describe("durable run recovery", () => {
|
||||
running();
|
||||
sockets[0].receive({ event: "delta", chat_id: "inactive", turn_id: "turn-old", text: "The" });
|
||||
const cachedAtCompletion: WebuiThreadPersistedPayload[] = [];
|
||||
client.onRunStatus((chatId, startedAt) => {
|
||||
if (startedAt === null) cachedAtCompletion.push(webuiThreadCache.get(`websocket:${chatId}`)!);
|
||||
client.onRunStatus((chatId, state) => {
|
||||
if (!state.active) cachedAtCompletion.push(webuiThreadCache.get(`websocket:${chatId}`)!);
|
||||
});
|
||||
|
||||
await reopen();
|
||||
|
||||
Reference in new issue
Block a user