fix(webui): reconcile turns after reconnect (#6211)
* fix(webui): reconcile turns after reconnect * perf(webui): bound reconnect recovery and index turn reconciliation * refactor(webui): simplify reconnect reconciliation * fix(webui): preserve turn authority during recovery * fix(webui): validate canonical completion identities
This commit is contained in:
1 parent
aeca1c0f1a
commit
fdeda8a468
18 files changed
+1741
-225
No files matched your search
@@ -270,8 +270,14 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => {
|
||||
runStatusHandlers.add(handler);
|
||||
return () => runStatusHandlers.delete(handler);
|
||||
};
|
||||
onRunCompletion = () => () => {};
|
||||
getRunStartedAt = () => null;
|
||||
getRunTurnId = () => null;
|
||||
getUnsettledRunChatIds = () => [];
|
||||
getRunGeneration = () => 0;
|
||||
hasUnsettledRun = () => false;
|
||||
canReconcileCanonicalCompletion = () => true;
|
||||
reconcileCanonicalCompletion = () => true;
|
||||
fenceCanonicalCompletedTurns = vi.fn();
|
||||
getGoalState = () => undefined;
|
||||
sendMessage = sendMessageSpy;
|
||||
@@ -2850,7 +2856,7 @@ describe("App layout", () => {
|
||||
.not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("restores sidebar run indicators after a page reload", async () => {
|
||||
it("restores sidebar runs from lifecycle replay without reviving them from stale session rows", async () => {
|
||||
mockSessions = [
|
||||
{
|
||||
key: "websocket:chat-a",
|
||||
@@ -2875,15 +2881,23 @@ describe("App layout", () => {
|
||||
JSON.stringify(["chat-b"]),
|
||||
);
|
||||
|
||||
render(<App />);
|
||||
const { rerender } = render(<App />);
|
||||
|
||||
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
|
||||
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
|
||||
await waitFor(() =>
|
||||
expect(within(sidebar).getByRole("img", { name: "Agent running" })).toBeInTheDocument(),
|
||||
);
|
||||
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);
|
||||
});
|
||||
expect(within(sidebar).getByRole("img", { name: "Agent running" })).toBeInTheDocument();
|
||||
expect(within(sidebar).getByRole("img", { name: "New activity" })).toBeInTheDocument();
|
||||
expect(attachSpy).toHaveBeenCalledWith("chat-a");
|
||||
act(() => {
|
||||
for (const handler of runStatusHandlers) handler("chat-a", null);
|
||||
});
|
||||
mockSessions = mockSessions.map((session) => ({ ...session }));
|
||||
rerender(<App />);
|
||||
expect(within(sidebar).queryByRole("img", { name: "Agent running" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("restores the active chat from the URL hash after a page reload", async () => {
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { fetchLatestWebuiThread } from "@/lib/latest-thread-request";
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import type { WebuiThreadPersistedPayload } from "@/lib/types";
|
||||
|
||||
const KEY = "websocket:shared";
|
||||
|
||||
function connectedClient(url: string): NanobotClient {
|
||||
const socket = { readyState: 1, onopen: null as (() => void) | null, send() {}, close() {} };
|
||||
const client = new NanobotClient({ url, reconnect: false, socketFactory: () => socket as unknown as WebSocket });
|
||||
client.connect();
|
||||
socket.onopen?.();
|
||||
return client;
|
||||
}
|
||||
|
||||
function cachedThread(revision = "cached"): WebuiThreadPersistedPayload {
|
||||
return { schemaVersion: 1, projection: "events", events: [], revision };
|
||||
}
|
||||
|
||||
function deferredResponse() {
|
||||
let resolve!: (response: Response) => void;
|
||||
const promise = new Promise<Response>((finish) => { resolve = finish; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
webuiThreadCache.clear();
|
||||
});
|
||||
|
||||
describe("shared latest thread requests", () => {
|
||||
it("shares a conditional read and lets one consumer cancel while another receives the owning 304 body", async () => {
|
||||
const client = connectedClient("ws://host");
|
||||
const body = cachedThread();
|
||||
webuiThreadCache.set(KEY, body);
|
||||
const read = deferredResponse();
|
||||
const fetchMock = vi.fn().mockReturnValue(read.promise);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const mounted = new AbortController();
|
||||
const first = fetchLatestWebuiThread(client, "token", KEY, mounted.signal);
|
||||
const surviving = fetchLatestWebuiThread(client, "token", KEY);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest",
|
||||
expect.objectContaining({ headers: { Authorization: "Bearer token", "If-None-Match": '"cached"' } }),
|
||||
);
|
||||
const rejected = expect(first).rejects.toMatchObject({ name: "AbortError" });
|
||||
mounted.abort();
|
||||
await rejected;
|
||||
expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(false);
|
||||
read.resolve(new Response(null, { status: 304 }));
|
||||
await expect(surviving).resolves.toBe(body);
|
||||
});
|
||||
|
||||
it("aborts the network after its final consumer cancels and starts a new read for recovery", async () => {
|
||||
const client = connectedClient("ws://host");
|
||||
const reads = [deferredResponse(), deferredResponse()];
|
||||
const fetchMock = vi.fn().mockReturnValueOnce(reads[0].promise).mockReturnValueOnce(reads[1].promise);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const controller = new AbortController();
|
||||
const cancelled = fetchLatestWebuiThread(client, "token", KEY, controller.signal);
|
||||
const rejected = expect(cancelled).rejects.toMatchObject({ name: "AbortError" });
|
||||
controller.abort();
|
||||
await rejected;
|
||||
expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(true);
|
||||
const recovered = fetchLatestWebuiThread(client, "token", KEY);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
const body = cachedThread("new");
|
||||
for (const read of reads) read.resolve(new Response(JSON.stringify(body), { status: 200 }));
|
||||
await expect(recovered).resolves.toEqual(body);
|
||||
});
|
||||
|
||||
it.each(["thread update", "turn end"] as const)("replaces surviving reads only for their own chat's %s", async (invalidation) => {
|
||||
const socket = {
|
||||
readyState: 1, onopen: null as (() => void) | null,
|
||||
onmessage: null as ((event: MessageEvent) => void) | null, send() {}, close() {},
|
||||
};
|
||||
const client = new NanobotClient({ url: "ws://host", reconnect: false, socketFactory: () => socket as unknown as WebSocket });
|
||||
client.connect();
|
||||
socket.onopen?.();
|
||||
const reads = [deferredResponse(), deferredResponse()];
|
||||
const fetchMock = vi.fn().mockReturnValueOnce(reads[0].promise).mockReturnValueOnce(reads[1].promise);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const first = fetchLatestWebuiThread(client, "token", KEY);
|
||||
const surviving = fetchLatestWebuiThread(client, "token", KEY);
|
||||
const receive = (chatId: string, scope: string) => socket.onmessage?.({
|
||||
data: JSON.stringify({ event: "session_updated", chat_id: chatId, scope }),
|
||||
} as MessageEvent);
|
||||
receive("shared", "metadata");
|
||||
receive("another-chat", "thread");
|
||||
expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(false);
|
||||
if (invalidation === "thread update") receive("shared", "thread");
|
||||
else socket.onmessage?.({
|
||||
data: JSON.stringify({ event: "turn_end", chat_id: "shared", turn_id: "turn-shared" }),
|
||||
} as MessageEvent);
|
||||
const fresh = fetchLatestWebuiThread(client, "token", KEY);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
const body = cachedThread("complete");
|
||||
reads[0].resolve(new Response(JSON.stringify(cachedThread("stale")), { status: 200 }));
|
||||
reads[1].resolve(new Response(JSON.stringify(body), { status: 200 }));
|
||||
await Promise.all([first, surviving, fresh].map((read) => expect(read).resolves.toEqual(body)));
|
||||
});
|
||||
|
||||
it("keeps host clients and renewed credentials in separate reads", async () => {
|
||||
const firstHost = connectedClient("ws://first-host");
|
||||
const secondHost = connectedClient("ws://second-host");
|
||||
const reads = [deferredResponse(), deferredResponse(), deferredResponse()];
|
||||
const fetchMock = vi.fn()
|
||||
.mockReturnValueOnce(reads[0].promise)
|
||||
.mockReturnValueOnce(reads[1].promise)
|
||||
.mockReturnValueOnce(reads[2].promise);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const requests = [
|
||||
fetchLatestWebuiThread(firstHost, "old-token", KEY),
|
||||
fetchLatestWebuiThread(firstHost, "new-token", KEY),
|
||||
fetchLatestWebuiThread(secondHost, "old-token", KEY),
|
||||
];
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
for (const read of reads) read.resolve(new Response(JSON.stringify(cachedThread()), { status: 200 }));
|
||||
await Promise.all(requests);
|
||||
});
|
||||
|
||||
it("does not join a pending read after a newer canonical page changes its cached baseline", async () => {
|
||||
const client = connectedClient("ws://host");
|
||||
const oldBody = cachedThread("old");
|
||||
const newBody = cachedThread("new");
|
||||
webuiThreadCache.set(KEY, oldBody);
|
||||
const reads = [deferredResponse(), deferredResponse()];
|
||||
const fetchMock = vi.fn().mockReturnValueOnce(reads[0].promise).mockReturnValueOnce(reads[1].promise);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const oldRead = fetchLatestWebuiThread(client, "token", KEY);
|
||||
webuiThreadCache.set(KEY, newBody);
|
||||
const newRead = fetchLatestWebuiThread(client, "token", KEY);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
for (const read of reads) read.resolve(new Response(null, { status: 304 }));
|
||||
await expect(oldRead).resolves.toBe(oldBody);
|
||||
await expect(newRead).resolves.toBe(newBody);
|
||||
});
|
||||
});
|
||||
@@ -324,6 +324,7 @@ describe("NanobotClient", () => {
|
||||
lastSocket().sent = [];
|
||||
client.onChat(chatId, vi.fn());
|
||||
client.sendMessage(chatId, "hello", undefined, { turnId: "turn-1" });
|
||||
expect(client.getUnsettledRunChatIds()).toEqual([]);
|
||||
|
||||
expect(lastSocket().sent.map((raw) => JSON.parse(raw))).toEqual([
|
||||
{
|
||||
@@ -584,7 +585,7 @@ describe("NanobotClient", () => {
|
||||
expect(handler).toHaveBeenLastCalledWith("chat-stop", null);
|
||||
});
|
||||
|
||||
it("clears stale run strip when reconnecting after a dropped socket", async () => {
|
||||
it("preserves durable run clocks and identities through transport reconnect", async () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test",
|
||||
reconnect: true,
|
||||
@@ -598,16 +599,30 @@ describe("NanobotClient", () => {
|
||||
lastSocket().fakeMessage({
|
||||
event: "goal_status",
|
||||
chat_id: "chat-strip",
|
||||
turn_id: "turn-strip",
|
||||
status: "running",
|
||||
started_at: 12_345,
|
||||
});
|
||||
|
||||
lastSocket().close();
|
||||
|
||||
expect(client.getRunStartedAt("chat-strip")).toBeNull();
|
||||
expect(handler).toHaveBeenLastCalledWith("chat-strip", null);
|
||||
expect(client.status).toBe("reconnecting");
|
||||
expect(client.getRunStartedAt("chat-strip")).toBe(12_345);
|
||||
expect(client.getRunTurnId("chat-strip")).toBe("turn-strip");
|
||||
expect(client.getUnsettledRunChatIds()).toEqual(["chat-strip"]);
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
expect(FakeSocket.instances.length).toBeGreaterThan(1);
|
||||
lastSocket().fakeOpen();
|
||||
expect(client.getRunStartedAt("chat-strip")).toBe(12_345);
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
lastSocket().fakeMessage({
|
||||
event: "turn_end", chat_id: "chat-strip", turn_id: "turn-strip",
|
||||
});
|
||||
expect(client.getRunStartedAt("chat-strip")).toBeNull();
|
||||
expect(client.getUnsettledRunChatIds()).toEqual([]);
|
||||
expect(handler).toHaveBeenLastCalledWith("chat-strip", null);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("clears run strip when a turn_end arrives without idle", () => {
|
||||
@@ -702,6 +717,12 @@ describe("NanobotClient", () => {
|
||||
"chat-guidance",
|
||||
requestGeneration,
|
||||
["turn-active"],
|
||||
{
|
||||
observedTurnIds: ["turn-active", "turn-guidance"],
|
||||
hasPendingToolCalls: false,
|
||||
activeTurnId: null,
|
||||
completionIdsProvided: true,
|
||||
},
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -1086,6 +1107,38 @@ describe("NanobotClient", () => {
|
||||
expect(client.hasUnsettledRun("chat-ack-lost")).toBe(false);
|
||||
});
|
||||
|
||||
it("requires a supplied completion identity before closing an observed lifecycle turn", () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test", reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
const received = vi.fn();
|
||||
client.onChat("chat-authority", received);
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
client.sendMessage("chat-authority", "question", undefined, { turnId: "turn-authority" });
|
||||
const requestGeneration = client.getRunGeneration("chat-authority");
|
||||
lastSocket().fakeMessage({
|
||||
event: "goal_status", chat_id: "chat-authority", turn_id: "turn-authority",
|
||||
status: "running", started_at: 123,
|
||||
});
|
||||
const snapshot = {
|
||||
observedTurnIds: ["turn-authority"], hasPendingToolCalls: false,
|
||||
activeTurnId: null, completionIdsProvided: true,
|
||||
};
|
||||
expect(client.canReconcileCanonicalCompletion("chat-authority", requestGeneration, [], snapshot)).toBe(false);
|
||||
expect(client.reconcileCanonicalCompletion("chat-authority", requestGeneration, [], snapshot)).toBe(false);
|
||||
expect(client.getRunStartedAt("chat-authority")).toBe(123);
|
||||
expect(client.hasUnsettledRun("chat-authority")).toBe(true);
|
||||
received.mockClear();
|
||||
lastSocket().fakeMessage({ event: "delta", chat_id: "chat-authority", turn_id: "turn-authority", text: "Still running" });
|
||||
expect(received).toHaveBeenCalledWith(expect.objectContaining({ event: "delta", text: "Still running" }));
|
||||
expect(client.reconcileCanonicalCompletion(
|
||||
"chat-authority", requestGeneration, ["turn-authority"], snapshot,
|
||||
)).toBe(true);
|
||||
expect(client.hasUnsettledRun("chat-authority")).toBe(false);
|
||||
});
|
||||
|
||||
it("settles an accepted turn that never reached running from canonical idle", () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test",
|
||||
|
||||
@@ -10,6 +10,7 @@ import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-dr
|
||||
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";
|
||||
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
import type {
|
||||
CliAppsPayload,
|
||||
@@ -39,6 +40,7 @@ function makeClient() {
|
||||
>();
|
||||
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>();
|
||||
@@ -73,7 +75,8 @@ function makeClient() {
|
||||
prospectiveFences.has(turnId)
|
||||
|| existingFences?.has(turnId) === true
|
||||
|| (
|
||||
snapshot?.hasPendingToolCalls === false
|
||||
snapshot?.completionIdsProvided !== true
|
||||
&& snapshot?.hasPendingToolCalls === false
|
||||
&& observedTurnIds.has(turnId)
|
||||
)
|
||||
);
|
||||
@@ -123,6 +126,10 @@ function makeClient() {
|
||||
runStatusHandlers.delete(handler);
|
||||
};
|
||||
},
|
||||
onRunCompletion: (handler: (chatId: string) => void) => {
|
||||
runCompletionHandlers.add(handler);
|
||||
return () => { runCompletionHandlers.delete(handler); };
|
||||
},
|
||||
onRuntimeModelUpdate: (
|
||||
handler: (modelName: string | null, modelPreset?: string | null) => void,
|
||||
) => {
|
||||
@@ -194,6 +201,7 @@ function makeClient() {
|
||||
) {
|
||||
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);
|
||||
@@ -2578,6 +2586,117 @@ describe("ThreadShell", () => {
|
||||
expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("adopts a completed canonical cache when reconnect revalidation returns 304", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "reconnect-not-modified";
|
||||
const turnId = "turn-cached-completion";
|
||||
let historyCalls = 0;
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (!String(input).includes(`websocket%3A${chatId}/webui-thread`)) {
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
}
|
||||
historyCalls += 1;
|
||||
if (historyCalls > 1) return { ok: false, status: 304 };
|
||||
return httpJson({
|
||||
...transcriptFromSimpleMessages([{ role: "user", content: "question", turnId }]),
|
||||
has_pending_tool_calls: true,
|
||||
});
|
||||
}));
|
||||
render(wrap(client, <ThreadShell
|
||||
session={session(chatId)} title="Cached completion"
|
||||
onToggleSidebar={() => {}} onNewChat={() => {}}
|
||||
/>));
|
||||
await screen.findByText("question");
|
||||
act(() => {
|
||||
client._emitChat(chatId, {
|
||||
event: "goal_status", chat_id: chatId, turn_id: turnId,
|
||||
status: "running", started_at: 1_700,
|
||||
});
|
||||
client._emitChat(chatId, {
|
||||
event: "delta", chat_id: chatId, turn_id: turnId, text: "cached prefix",
|
||||
});
|
||||
});
|
||||
await screen.findByText("cached prefix");
|
||||
act(() => client._emitStatus("reconnecting"));
|
||||
// The reconnect coordinator can cache this response before the mounted
|
||||
// thread's conditional request returns the same body through HTTP 304.
|
||||
act(() => webuiThreadCache.set(`websocket:${chatId}`, canonicalThreadPayload({
|
||||
schemaVersion: 3,
|
||||
revision: "completed-revision",
|
||||
has_pending_tool_calls: false,
|
||||
completed_turn_ids: [turnId],
|
||||
messages: [
|
||||
{ id: "canonical-user", role: "user", content: "question", turnId, createdAt: 1_000 },
|
||||
{ id: "canonical-answer", role: "assistant", content: "full cached answer", turnId, createdAt: 2_000 },
|
||||
],
|
||||
})!));
|
||||
act(() => client._emitStatus("open"));
|
||||
await screen.findByText("full cached answer");
|
||||
expect(historyCalls).toBe(2);
|
||||
expect(screen.queryByText("cached prefix")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows externally published completion before an older mounted reconnect read returns", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "published-completion-race";
|
||||
const turnId = "published-completed-turn";
|
||||
let historyCalls = 0;
|
||||
let finishOlderRead!: (response: ReturnType<typeof httpJson>) => void;
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
if (!String(input).includes(`websocket%3A${chatId}/webui-thread`)) {
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
|
||||
}
|
||||
historyCalls += 1;
|
||||
if (historyCalls === 1) return Promise.resolve(httpJson({
|
||||
...transcriptFromSimpleMessages([{ role: "user", content: "question", turnId }]),
|
||||
has_pending_tool_calls: true,
|
||||
}));
|
||||
return new Promise<ReturnType<typeof httpJson>>((resolve) => { finishOlderRead = resolve; });
|
||||
}));
|
||||
render(wrap(client, <ThreadShell
|
||||
session={session(chatId)} title="Published completion"
|
||||
onToggleSidebar={() => {}} onNewChat={() => {}}
|
||||
/>));
|
||||
await screen.findByText("question");
|
||||
act(() => {
|
||||
client._emitChat(chatId, {
|
||||
event: "goal_status", chat_id: chatId, turn_id: turnId,
|
||||
status: "running", started_at: 1_700,
|
||||
});
|
||||
client._emitChat(chatId, {
|
||||
event: "delta", chat_id: chatId, turn_id: turnId, text: "old active prefix",
|
||||
});
|
||||
});
|
||||
await screen.findByText("old active prefix");
|
||||
act(() => client._emitStatus("reconnecting"));
|
||||
act(() => client._emitStatus("open"));
|
||||
await waitFor(() => expect(historyCalls).toBe(2));
|
||||
const completed = canonicalThreadPayload({
|
||||
...transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "question", turnId },
|
||||
{ role: "assistant", content: "externally published final answer", turnId },
|
||||
]),
|
||||
revision: "completed-revision",
|
||||
has_pending_tool_calls: false,
|
||||
completed_turn_ids: [turnId],
|
||||
})!;
|
||||
act(() => webuiThreadCache.set(`websocket:${chatId}`, completed));
|
||||
await screen.findByText("externally published final answer");
|
||||
expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
|
||||
await act(async () => finishOlderRead(httpJson({
|
||||
...transcriptFromSimpleMessages([{ role: "user", content: "question", turnId }]),
|
||||
revision: "older-active-revision",
|
||||
has_pending_tool_calls: true,
|
||||
active_turn_id: turnId,
|
||||
completed_turn_ids: [],
|
||||
})));
|
||||
expect(screen.getByText("externally published final answer")).toBeInTheDocument();
|
||||
expect(screen.queryByText("old active prefix")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
|
||||
expect(webuiThreadCache.get(`websocket:${chatId}`)).toBe(completed);
|
||||
});
|
||||
|
||||
it("refreshes after opening when mounted while the socket is reconnecting", async () => {
|
||||
const client = makeClient();
|
||||
client._emitStatus("reconnecting");
|
||||
@@ -2700,6 +2819,7 @@ describe("ThreadShell", () => {
|
||||
observedTurnIds: [canonicalTurnId],
|
||||
hasPendingToolCalls: false,
|
||||
activeTurnId: null,
|
||||
completionIdsProvided: false,
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -2880,6 +3000,7 @@ describe("ThreadShell", () => {
|
||||
observedTurnIds: [],
|
||||
hasPendingToolCalls: false,
|
||||
activeTurnId: null,
|
||||
completionIdsProvided: false,
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -2953,7 +3074,7 @@ describe("ThreadShell", () => {
|
||||
expect(client.canReconcileCanonicalCompletion).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rolls back a committed candidate when the final lifecycle recheck loses", async () => {
|
||||
it("keeps completed content while deferring a rejected final lifecycle reconciliation", async () => {
|
||||
const client = makeClient();
|
||||
const turnId = "turn-layout-recheck";
|
||||
let historyCalls = 0;
|
||||
@@ -3023,8 +3144,8 @@ describe("ThreadShell", () => {
|
||||
await waitFor(() =>
|
||||
expect(client.reconcileCanonicalCompletion).toHaveBeenCalledTimes(1),
|
||||
);
|
||||
expect(screen.getByText("layout partial")).toBeInTheDocument();
|
||||
expect(screen.queryByText("layout canonical answer")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("layout partial")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("layout canonical answer")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
|
||||
|
||||
act(() => client._emitSessionUpdate("layout-recheck", "thread"));
|
||||
@@ -3035,7 +3156,7 @@ describe("ThreadShell", () => {
|
||||
expect(client.reconcileCanonicalCompletion).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("accepts the first reconnect refresh after switching away and back", async () => {
|
||||
it("adopts a completed equal-length history when returning after an inactive outage", async () => {
|
||||
const client = makeClient();
|
||||
const oldTurnId = "turn-old";
|
||||
let newTurnId = "";
|
||||
@@ -3121,15 +3242,10 @@ describe("ThreadShell", () => {
|
||||
|
||||
rerender(view("chat-version-b"));
|
||||
await waitFor(() => expect(screen.getByText("other chat")).toBeInTheDocument());
|
||||
rerender(view("chat-version-a"));
|
||||
await waitFor(() => expect(chatACalls).toBe(3));
|
||||
expect(screen.getByText("partial answer")).toBeInTheDocument();
|
||||
expect(screen.queryByText("partial answer completed")).not.toBeInTheDocument();
|
||||
|
||||
act(() => client._emitStatus("reconnecting"));
|
||||
act(() => client._emitStatus("open"));
|
||||
|
||||
await waitFor(() => expect(chatACalls).toBe(4));
|
||||
rerender(view("chat-version-a"));
|
||||
await waitFor(() => expect(chatACalls).toBe(3));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText("partial answer completed")).toBeInTheDocument(),
|
||||
);
|
||||
@@ -3214,6 +3330,224 @@ describe("ThreadShell", () => {
|
||||
expect(client.sendMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["both", "current", "canonical"] as const)("keeps repeated guidance order and newer live output with %s turn ids", async (guidanceTurnIds) => {
|
||||
const client = makeClient();
|
||||
const chatId = "completed-guidance-new-tail";
|
||||
const turnId = "completed-guided-turn";
|
||||
const guidanceTurnId = "guidance-input";
|
||||
const repeatedGuidanceTurnId = "repeated-guidance-input";
|
||||
let historyCalls = 0;
|
||||
let resolveRefresh!: (response: ReturnType<typeof httpJson>) => void;
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
if (!String(input).includes(`websocket%3A${chatId}/webui-thread`)) {
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
|
||||
}
|
||||
historyCalls += 1;
|
||||
if (historyCalls === 1) return Promise.resolve(httpJson({
|
||||
...transcriptFromSimpleMessages([{ role: "user", content: "guided question", turnId }]),
|
||||
has_pending_tool_calls: true,
|
||||
}));
|
||||
return new Promise<ReturnType<typeof httpJson>>((resolve) => { resolveRefresh = resolve; });
|
||||
}));
|
||||
render(wrap(client, <ThreadShell
|
||||
session={session(chatId)} title="Guided turn"
|
||||
onToggleSidebar={() => {}} onNewChat={() => {}}
|
||||
/>));
|
||||
await screen.findByText("guided question");
|
||||
act(() => {
|
||||
client._emitChat(chatId, {
|
||||
event: "goal_status", chat_id: chatId, status: "running",
|
||||
started_at: 1_700, turn_id: turnId,
|
||||
});
|
||||
client._emitChat(chatId, {
|
||||
event: "delta", chat_id: chatId, text: "first partial segment", turn_id: turnId,
|
||||
});
|
||||
});
|
||||
await screen.findByText("first partial segment");
|
||||
act(() => {
|
||||
client._emitChat(chatId, {
|
||||
event: "stream_end", chat_id: chatId, turn_id: turnId, resuming: true,
|
||||
});
|
||||
client._emitChat(chatId, {
|
||||
event: "user_message", chat_id: chatId,
|
||||
turn_id: guidanceTurnIds === "canonical" ? undefined : guidanceTurnId,
|
||||
text: "supplemental guidance", starts_turn: false, active_turn_id: turnId,
|
||||
});
|
||||
client._emitChat(chatId, {
|
||||
event: "user_message", chat_id: chatId,
|
||||
turn_id: guidanceTurnIds === "canonical" ? undefined : repeatedGuidanceTurnId,
|
||||
text: "supplemental guidance", starts_turn: false, active_turn_id: turnId,
|
||||
});
|
||||
client._emitChat(chatId, {
|
||||
event: "delta", chat_id: chatId, turn_id: turnId, text: "last partial segment",
|
||||
});
|
||||
});
|
||||
await screen.findByText("last partial segment");
|
||||
act(() => client._emitSessionUpdate(chatId, "thread"));
|
||||
await waitFor(() => expect(historyCalls).toBe(2));
|
||||
act(() => client._emitChat(chatId, {
|
||||
event: "turn_end", chat_id: chatId, turn_id: turnId,
|
||||
}));
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Message input" }), {
|
||||
target: { value: "new local question" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
const newerTurnId = client.sendMessage.mock.calls[0]?.[3]?.turnId;
|
||||
expect(newerTurnId).toBeTruthy();
|
||||
act(() => {
|
||||
client._emitChat(chatId, {
|
||||
event: "goal_status", chat_id: chatId, status: "running",
|
||||
started_at: 2_000, turn_id: newerTurnId,
|
||||
});
|
||||
client._emitChat(chatId, {
|
||||
event: "delta", chat_id: chatId, turn_id: newerTurnId, text: "newer live reply",
|
||||
});
|
||||
});
|
||||
await screen.findByText("newer live reply");
|
||||
await act(async () => resolveRefresh(httpJson({
|
||||
...transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "guided question", turnId },
|
||||
{ role: "assistant", content: "canonical first segment", turnId },
|
||||
{ role: "user", content: "supplemental guidance",
|
||||
turnId: guidanceTurnIds === "current" ? undefined : guidanceTurnId },
|
||||
{ role: "user", content: "supplemental guidance",
|
||||
turnId: guidanceTurnIds === "current" ? undefined : repeatedGuidanceTurnId },
|
||||
{ role: "assistant", content: "canonical final segment", turnId },
|
||||
]),
|
||||
has_pending_tool_calls: false,
|
||||
completed_turn_ids: [turnId],
|
||||
})));
|
||||
const first = await screen.findByText("canonical first segment");
|
||||
const guidance = screen.getAllByText("supplemental guidance");
|
||||
const final = screen.getByText("canonical final segment");
|
||||
const newer = screen.getByText("newer live reply");
|
||||
expect(guidance).toHaveLength(2);
|
||||
expect(first.compareDocumentPosition(guidance[0]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(guidance[0].compareDocumentPosition(guidance[1]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(guidance[1].compareDocumentPosition(final) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(final.compareDocumentPosition(newer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(screen.queryByText("first partial segment")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("last partial segment")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
|
||||
act(() => {
|
||||
client._emitChat(chatId, {
|
||||
event: "delta", chat_id: chatId, turn_id: turnId, text: "obsolete delayed delta",
|
||||
});
|
||||
client._emitChat(chatId, {
|
||||
event: "delta", chat_id: chatId, turn_id: newerTurnId, text: " continued",
|
||||
});
|
||||
});
|
||||
await screen.findByText("newer live reply continued");
|
||||
expect(screen.queryByText(/obsolete delayed delta/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("newer live reply")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps canonical completed turns after an older cached pagination prefix", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "completed-window-order";
|
||||
const completedTurnId = "completed-cached-turn";
|
||||
const unseenTurnId = "other-tab-completed-turn";
|
||||
const newerTurnId = "new-local-turn";
|
||||
const messageCache = new ThreadMessageCache(() => false);
|
||||
messageCache.set(chatId, [
|
||||
{ id: "older-page", role: "assistant", content: "older paginated answer", createdAt: 1 },
|
||||
{ id: "cached-user", role: "user", content: "completed question", turnId: completedTurnId, createdAt: 2 },
|
||||
{ id: "cached-prefix", role: "assistant", content: "outdated prefix", turnId: completedTurnId, createdAt: 3 },
|
||||
{ id: "new-user", role: "user", content: "new local question", turnId: newerTurnId, createdAt: 7 },
|
||||
{ id: "new-answer", role: "assistant", content: "new local stream", turnId: newerTurnId, isStreaming: true, createdAt: 8 },
|
||||
]);
|
||||
client._emitChat(chatId, {
|
||||
event: "goal_status", chat_id: chatId, turn_id: newerTurnId, status: "running", started_at: 2_000,
|
||||
});
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (!String(input).includes(`websocket%3A${chatId}/webui-thread`)) {
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
}
|
||||
return httpJson({
|
||||
...transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "completed question", turnId: completedTurnId },
|
||||
{ role: "assistant", content: "completed reply", turnId: completedTurnId },
|
||||
{ role: "user", content: "other tab question", turnId: unseenTurnId },
|
||||
{ role: "assistant", content: "other tab completed reply", turnId: unseenTurnId },
|
||||
]),
|
||||
has_pending_tool_calls: false,
|
||||
completed_turn_ids: [completedTurnId, unseenTurnId],
|
||||
page: { before_cursor: "older-page", has_more_before: true, user_message_offset: 25 },
|
||||
});
|
||||
}));
|
||||
render(wrap(client, <ThreadShell
|
||||
session={session(chatId)} title="Completed latest window" messageCache={messageCache}
|
||||
onToggleSidebar={() => {}} onNewChat={() => {}}
|
||||
/>));
|
||||
const completed = await screen.findByText("completed reply");
|
||||
const older = screen.getByText("older paginated answer");
|
||||
const other = screen.getByText("other tab completed reply");
|
||||
const newer = screen.getByText("new local stream");
|
||||
expect(older.compareDocumentPosition(completed) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(completed.compareDocumentPosition(other) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(other.compareDocumentPosition(newer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(screen.queryByText("outdated prefix")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each(["identified", "anonymous"] as const)("keeps completed guidance after a paginated prefix with %s live identity", async (guidanceIdentity) => {
|
||||
const client = makeClient();
|
||||
const chatId = "completed-guidance-paged-prefix";
|
||||
const messageCache = new ThreadMessageCache(() => false);
|
||||
messageCache.set(chatId, [
|
||||
{ id: "old-user", role: "user", content: "continue", createdAt: 1 },
|
||||
{ id: "old-answer", role: "assistant", content: "older answer", createdAt: 2 },
|
||||
{ id: "question", role: "user", content: "current question", turnId: "main", createdAt: 3 },
|
||||
{ id: "first", role: "assistant", content: "first partial", turnId: "main", createdAt: 4 },
|
||||
{ id: "guidance", role: "user", content: "continue",
|
||||
...(guidanceIdentity === "identified" ? { turnId: "guidance" } : {}), createdAt: 5 },
|
||||
{ id: "last", role: "assistant", content: "last partial", turnId: "main", createdAt: 6 },
|
||||
{ id: "new-user", role: "user", content: "new question", turnId: "new", createdAt: 7 },
|
||||
{ id: "new-answer", role: "assistant", content: "new live answer", turnId: "new", isStreaming: true, createdAt: 8 },
|
||||
]);
|
||||
client._emitChat(chatId, {
|
||||
event: "goal_status", chat_id: chatId, turn_id: "new", status: "running", started_at: 2_000,
|
||||
});
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (!String(input).includes(`websocket%3A${chatId}/webui-thread`)) {
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
}
|
||||
return httpJson({
|
||||
...transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "current question", turnId: "main" },
|
||||
{ role: "assistant", content: "completed first", turnId: "main" },
|
||||
{ role: "user", content: "continue", turnId: "guidance" },
|
||||
{ role: "assistant", content: "completed last", turnId: "main" },
|
||||
]),
|
||||
has_pending_tool_calls: false,
|
||||
completed_turn_ids: ["main"],
|
||||
page: { before_cursor: "older-page", has_more_before: true, user_message_offset: 25 },
|
||||
});
|
||||
}));
|
||||
render(wrap(client, <ThreadShell
|
||||
session={session(chatId)} title="Completed paged guidance" messageCache={messageCache}
|
||||
onToggleSidebar={() => {}} onNewChat={() => {}}
|
||||
/>));
|
||||
await screen.findByText("completed last");
|
||||
const messages = [
|
||||
...screen.getAllByText("continue"),
|
||||
...["older answer", "current question", "completed first", "completed last", "new question", "new live answer"]
|
||||
.map((text) => screen.getByText(text)),
|
||||
];
|
||||
messages.sort((a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
|
||||
expect(messages.map((message) => message.textContent)).toEqual([
|
||||
"continue", "older answer", "current question", "completed first",
|
||||
"continue", "completed last", "new question", "new live answer",
|
||||
]);
|
||||
expect(screen.queryByText("first partial")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("last partial")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
|
||||
act(() => client._emitChat(chatId, {
|
||||
event: "delta", chat_id: chatId, turn_id: "new", text: " continued",
|
||||
}));
|
||||
await screen.findByText("new live answer continued");
|
||||
});
|
||||
|
||||
it("remembers explicit completed turns on initial history load", async () => {
|
||||
const client = makeClient();
|
||||
const turnId = "turn-completed-before-load";
|
||||
|
||||
@@ -863,6 +863,31 @@ describe("useNanobotStream", () => {
|
||||
expect(result.current.isStreaming).toBe(false);
|
||||
});
|
||||
|
||||
it("restores cached tool activity according to each conversation's completed turns", () => {
|
||||
const fake = fakeClient();
|
||||
const initialMessages: UIMessage[] = [{
|
||||
id: "cached-tool-activity", role: "tool", kind: "trace", content: "exec(…)",
|
||||
traces: ["exec(…)"], turnId: "completed-tool-turn", isStreaming: true, createdAt: 1,
|
||||
}];
|
||||
const initialProps = {
|
||||
chatId: "completed-tools",
|
||||
initialMessages,
|
||||
completedTurnIds: ["completed-tool-turn"],
|
||||
};
|
||||
const { result, rerender } = renderHook((props: typeof initialProps) => useNanobotStream(
|
||||
props.chatId, props.initialMessages, false, undefined, undefined, props.completedTurnIds,
|
||||
), { wrapper: wrap(fake.client), initialProps });
|
||||
expect(result.current.isStreaming).toBe(false);
|
||||
rerender({
|
||||
chatId: "active-tools",
|
||||
initialMessages: [{ ...initialMessages[0], turnId: "active-tool-turn" }],
|
||||
completedTurnIds: [],
|
||||
});
|
||||
expect(result.current.isStreaming).toBe(true);
|
||||
rerender(initialProps);
|
||||
expect(result.current.isStreaming).toBe(false);
|
||||
});
|
||||
|
||||
it("drops pending stream work when switching chats", async () => {
|
||||
const fake = fakeClient();
|
||||
const { result, rerender } = renderHook(
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { useReconnectRuns } from "@/hooks/useReconnectRuns";
|
||||
import { useNanobotStream } from "@/hooks/useNanobotStream";
|
||||
import { useSessionHistory } from "@/hooks/useSessions";
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import type { WebuiThreadPersistedPayload } from "@/lib/types";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
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; this.onclose?.(); }
|
||||
open() { this.readyState = 1; this.onopen?.(); }
|
||||
receive(payload: unknown) {
|
||||
this.onmessage?.({ data: JSON.stringify(payload) } as MessageEvent);
|
||||
}
|
||||
}
|
||||
|
||||
function completedThread(chatId = "inactive", turnId = "turn-old"): WebuiThreadPersistedPayload {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
projection: "events",
|
||||
has_pending_tool_calls: false,
|
||||
events: [
|
||||
{ event: "user_message", chat_id: chatId, turn_id: turnId, text: "Take your time", starts_turn: true },
|
||||
{ event: "message", chat_id: chatId, turn_id: turnId, text: "The complete answer" },
|
||||
{ event: "turn_end", chat_id: chatId, turn_id: turnId },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function response(body: WebuiThreadPersistedPayload): Response {
|
||||
return new Response(JSON.stringify(body), { status: 200 });
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const sockets: TestSocket[] = [];
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test", reconnect: true, maxBackoffMs: 10,
|
||||
socketFactory: () => {
|
||||
const socket = new TestSocket();
|
||||
sockets.push(socket);
|
||||
return socket as unknown as WebSocket;
|
||||
},
|
||||
});
|
||||
client.connect();
|
||||
sockets[0].open();
|
||||
const hook = renderHook(() => useReconnectRuns(client, () => "renewed-token"));
|
||||
const running = (chatId = "inactive", turnId = "turn-old", startedAt = 123) => sockets.at(-1)!.receive({
|
||||
event: "goal_status", chat_id: chatId, turn_id: turnId,
|
||||
status: "running", started_at: startedAt,
|
||||
});
|
||||
const reopen = async () => {
|
||||
act(() => sockets.at(-1)!.close());
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10); });
|
||||
await act(async () => { sockets.at(-1)!.open(); });
|
||||
};
|
||||
const close = () => { hook.unmount(); client.close(); };
|
||||
return { client, sockets, running, reopen, close, hook };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
webuiThreadCache.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
webuiThreadCache.clear();
|
||||
});
|
||||
|
||||
describe("durable run recovery", () => {
|
||||
it("bounds recovery reads while draining all chats and preserving a newer queued turn", async () => {
|
||||
const reads: Array<{ chatId: string; resolve: (value: Response) => void }> = [];
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
const fetchMock = vi.fn().mockImplementation((url: string) => {
|
||||
active += 1;
|
||||
peak = Math.max(peak, active);
|
||||
const key = decodeURIComponent(url.split("/sessions/")[1].split("/")[0]);
|
||||
return new Promise<Response>((resolve) => { reads.push({ chatId: key.slice("websocket:".length), resolve }); })
|
||||
.finally(() => { active -= 1; });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { client, running, reopen, close } = setup();
|
||||
for (let index = 0; index < 9; index += 1) running(`chat-${index}`);
|
||||
await reopen();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
running("chat-8", "turn-new", 456);
|
||||
let answered = 0;
|
||||
for (let round = 0; round < 9 && answered < 9; round += 1) {
|
||||
const batch = reads.slice(answered);
|
||||
await act(async () => {
|
||||
for (const read of batch) read.resolve(response(completedThread(read.chatId)));
|
||||
});
|
||||
answered += batch.length;
|
||||
}
|
||||
expect(fetchMock).toHaveBeenCalledTimes(9);
|
||||
expect(peak).toBe(4);
|
||||
expect(client.getUnsettledRunChatIds()).toEqual(["chat-8"]);
|
||||
expect(client.getRunStartedAt("chat-8")).toBe(456);
|
||||
expect(webuiThreadCache.get("websocket:chat-8")).toBeUndefined();
|
||||
close();
|
||||
});
|
||||
|
||||
it("aborts outstanding recovery reads without starting queued chats after another drop", async () => {
|
||||
const reads: Array<{ signal: AbortSignal; resolve: (value: Response) => void }> = [];
|
||||
const fetchMock = vi.fn().mockImplementation((_url: string, init: RequestInit) => (
|
||||
new Promise<Response>((resolve) => { reads.push({ signal: init.signal!, resolve }); })
|
||||
));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { client, sockets, running, reopen, close } = setup();
|
||||
for (let index = 0; index < 8; index += 1) running(`chat-${index}`);
|
||||
await reopen();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
await act(async () => { sockets.at(-1)!.close(); });
|
||||
expect(reads.every((read) => read.signal.aborted)).toBe(true);
|
||||
await act(async () => {
|
||||
for (const read of reads) read.resolve(response(completedThread()));
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
expect(client.getUnsettledRunChatIds()).toHaveLength(8);
|
||||
close();
|
||||
});
|
||||
|
||||
it("shares one simultaneous recovery HTTP read with the mounted history hook", async () => {
|
||||
const cached = completedThread();
|
||||
cached.events = cached.events.slice(0, 2);
|
||||
cached.events[1] = { event: "message", chat_id: "inactive", turn_id: "turn-old", text: "Partial" };
|
||||
cached.has_pending_tool_calls = true;
|
||||
cached.active_turn_id = "turn-old";
|
||||
cached.revision = "active-page";
|
||||
webuiThreadCache.set("websocket:inactive", cached);
|
||||
let resolveRecovery!: (value: Response) => void;
|
||||
const fetchMock = vi.fn().mockResolvedValueOnce(new Response(null, { status: 304 }))
|
||||
.mockImplementation(() => new Promise<Response>((resolve) => { resolveRecovery = resolve; }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { client, running, reopen, close } = setup();
|
||||
running();
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<ClientProvider client={client} token="renewed-token">{children}</ClientProvider>
|
||||
);
|
||||
const mounted = renderHook(() => {
|
||||
const history = useSessionHistory("websocket:inactive");
|
||||
useEffect(() => {
|
||||
let refreshOnOpen = false;
|
||||
return client.onStatus((status) => {
|
||||
if (status !== "open") refreshOnOpen = true;
|
||||
else if (refreshOnOpen) {
|
||||
refreshOnOpen = false;
|
||||
history.refresh();
|
||||
}
|
||||
});
|
||||
}, [history.refresh]);
|
||||
return history;
|
||||
}, { wrapper });
|
||||
await act(async () => {});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
await reopen();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(fetchMock.mock.calls[1][1].headers["If-None-Match"]).toBe('"active-page"');
|
||||
await act(async () => { resolveRecovery(response(completedThread())); });
|
||||
expect(mounted.result.current.messages.at(-1)?.content).toBe("The complete answer");
|
||||
expect(client.getRunStartedAt("inactive")).toBeNull();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
mounted.unmount();
|
||||
close();
|
||||
});
|
||||
|
||||
it.each(["together", "separate"] as const)("starts fresh terminal history without adopting the old read when completion frames arrive %s", async (timing) => {
|
||||
const idle: WebuiThreadPersistedPayload = {
|
||||
schemaVersion: 1, projection: "events", events: [],
|
||||
completed_turn_ids: [], has_pending_tool_calls: false, active_turn_id: null,
|
||||
};
|
||||
const active = completedThread();
|
||||
active.events = active.events.slice(0, 1);
|
||||
active.completed_turn_ids = [];
|
||||
active.has_pending_tool_calls = true;
|
||||
active.active_turn_id = "turn-old";
|
||||
const reads: Array<{ signal: AbortSignal; resolve: (value: Response) => void }> = [];
|
||||
const fetchMock = vi.fn().mockResolvedValueOnce(response(idle))
|
||||
.mockImplementation((_url: string, init: RequestInit) => new Promise<Response>((resolve) => {
|
||||
reads.push({ signal: init.signal!, resolve });
|
||||
}));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { client, sockets, running, reopen, close } = setup();
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<ClientProvider client={client} token="renewed-token">{children}</ClientProvider>
|
||||
);
|
||||
const mounted = renderHook(() => {
|
||||
const history = useSessionHistory("websocket:inactive");
|
||||
const stream = useNanobotStream(
|
||||
"inactive", history.messages, history.hasPendingToolCalls,
|
||||
undefined, undefined, history.completedTurnIds,
|
||||
);
|
||||
useEffect(() => client.onSessionUpdate((chatId, scope) => {
|
||||
if (chatId === "inactive" && scope !== "metadata") history.refresh();
|
||||
}), [history.refresh]);
|
||||
useEffect(() => {
|
||||
let refreshOnOpen = false;
|
||||
return client.onStatus((status) => {
|
||||
if (status !== "open") refreshOnOpen = true;
|
||||
else if (refreshOnOpen) {
|
||||
refreshOnOpen = false;
|
||||
history.refresh();
|
||||
}
|
||||
});
|
||||
}, [history.refresh]);
|
||||
return { history, stream };
|
||||
}, { wrapper });
|
||||
await act(async () => {});
|
||||
act(() => running());
|
||||
await reopen();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
act(() => {
|
||||
sockets.at(-1)!.receive({ event: "message", chat_id: "inactive", turn_id: "turn-old", text: "The complete answer" });
|
||||
sockets.at(-1)!.receive({ event: "turn_end", chat_id: "inactive", turn_id: "turn-old" });
|
||||
if (timing === "together") {
|
||||
sockets.at(-1)!.receive({ event: "session_updated", chat_id: "inactive", scope: "thread" });
|
||||
}
|
||||
});
|
||||
await act(async () => {});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
expect(reads[0].signal.aborted).toBe(true);
|
||||
await act(async () => { reads[0].resolve(response(active)); });
|
||||
expect(mounted.result.current.history.hasPendingToolCalls).toBe(false);
|
||||
expect(mounted.result.current.stream.isStreaming).toBe(false);
|
||||
const completed = completedThread();
|
||||
completed.completed_turn_ids = ["turn-old"];
|
||||
if (timing === "separate") {
|
||||
act(() => sockets.at(-1)!.receive({ event: "session_updated", chat_id: "inactive", scope: "thread" }));
|
||||
await act(async () => {});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
await act(async () => {
|
||||
reads[1].resolve(response(completed));
|
||||
reads[2].resolve(new Response("unavailable", { status: 503 }));
|
||||
});
|
||||
expect(mounted.result.current.history.error).toBe("HTTP 503");
|
||||
expect(mounted.result.current.history.loading).toBe(false);
|
||||
expect(mounted.result.current.stream.messages.at(-1)?.content).toBe("The complete answer");
|
||||
} else {
|
||||
await act(async () => { reads[1].resolve(response(completed)); });
|
||||
expect(mounted.result.current.history.messages.at(-1)?.content).toBe("The complete answer");
|
||||
}
|
||||
expect(mounted.result.current.stream.isStreaming).toBe(false);
|
||||
expect(client.hasUnsettledRun("inactive")).toBe(false);
|
||||
mounted.unmount();
|
||||
close();
|
||||
});
|
||||
|
||||
it.each(["before", "during"] as const)("starts fresh recovery instead of sharing a mounted read from %s the outage", async (timing) => {
|
||||
const stale = completedThread();
|
||||
stale.events = stale.events.slice(0, 1);
|
||||
stale.has_pending_tool_calls = true;
|
||||
stale.active_turn_id = "turn-old";
|
||||
const reads: Array<(response: Response) => void> = [];
|
||||
const fetchMock = vi.fn().mockImplementation(() => new Promise<Response>((resolve) => { reads.push(resolve); }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { client, sockets, running, reopen, close } = setup();
|
||||
running();
|
||||
if (timing === "during") {
|
||||
act(() => sockets.at(-1)!.close());
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10); });
|
||||
expect(client.status).toBe("connecting");
|
||||
}
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<ClientProvider client={client} token="renewed-token">{children}</ClientProvider>
|
||||
);
|
||||
const mounted = renderHook(() => useSessionHistory("websocket:inactive"), { wrapper });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
if (timing === "before") await reopen();
|
||||
else await act(async () => { sockets.at(-1)!.open(); });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
await act(async () => { reads[1](response(completedThread())); });
|
||||
await act(async () => { reads[0](response(stale)); });
|
||||
expect(mounted.result.current.messages.at(-1)?.content).toBe("The complete answer");
|
||||
expect(mounted.result.current.hasPendingToolCalls).toBe(false);
|
||||
expect(client.getRunStartedAt("inactive")).toBeNull();
|
||||
mounted.unmount();
|
||||
close();
|
||||
});
|
||||
|
||||
it("settles an inactive completed chat and retains its answer before clearing the run", async () => {
|
||||
// The oldest protocol-1 host need not supply active_turn_id or completed_turn_ids.
|
||||
const body = completedThread();
|
||||
const fetchMock = vi.fn().mockResolvedValue(response(body));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { client, sockets, running, reopen, close } = setup();
|
||||
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}`)!);
|
||||
});
|
||||
|
||||
await reopen();
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest",
|
||||
expect.objectContaining({ headers: { Authorization: "Bearer renewed-token" } }),
|
||||
);
|
||||
expect(client.getRunStartedAt("inactive")).toBeNull();
|
||||
expect(client.hasUnsettledRun("inactive")).toBe(false);
|
||||
expect(cachedAtCompletion).toEqual([body]);
|
||||
expect(projectThreadEvents(cachedAtCompletion[0].events).at(-1)?.content).toBe("The complete answer");
|
||||
const delayed = vi.fn();
|
||||
client.onChat("inactive", delayed);
|
||||
expect(delayed).not.toHaveBeenCalled();
|
||||
close();
|
||||
});
|
||||
|
||||
it("checks every unsettled chat while keeping a still-running chat active", async () => {
|
||||
const body = completedThread("running", "turn-running");
|
||||
body.events = body.events.slice(0, 1);
|
||||
body.has_pending_tool_calls = true;
|
||||
body.active_turn_id = "turn-running";
|
||||
const fetchMock = vi.fn().mockImplementation((url: string) => Promise.resolve(response(
|
||||
url.includes("websocket%3Arunning") ? body : completedThread(),
|
||||
)));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { client, running, reopen, close } = setup();
|
||||
running();
|
||||
running("running", "turn-running", 456);
|
||||
const runStatus = vi.fn();
|
||||
client.onRunStatus(runStatus);
|
||||
await reopen();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(client.getRunStartedAt("inactive")).toBeNull();
|
||||
expect(client.getRunStartedAt("running")).toBe(456);
|
||||
expect(client.getRunTurnId("running")).toBe("turn-running");
|
||||
expect(client.hasUnsettledRun("running")).toBe(true);
|
||||
expect(runStatus).toHaveBeenCalledTimes(3);
|
||||
close();
|
||||
});
|
||||
|
||||
it.each(["failed read", "missing activity state"])("leaves %s unresolved", async (failure) => {
|
||||
const body = completedThread();
|
||||
delete body.has_pending_tool_calls;
|
||||
body.events = body.events.slice(0, 2);
|
||||
const fetchMock = failure === "failed read"
|
||||
? vi.fn().mockRejectedValue(new Error("offline"))
|
||||
: vi.fn().mockResolvedValue(response(body));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { client, running, reopen, close } = setup();
|
||||
running();
|
||||
await reopen();
|
||||
expect(client.getRunStartedAt("inactive")).toBe(123);
|
||||
expect(client.hasUnsettledRun("inactive")).toBe(true);
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined();
|
||||
close();
|
||||
});
|
||||
|
||||
it("does not let an in-flight old snapshot settle a newer turn", async () => {
|
||||
let resolveRead!: (value: Response) => void;
|
||||
vi.stubGlobal("fetch", vi.fn().mockImplementation(() => new Promise<Response>((resolve) => {
|
||||
resolveRead = resolve;
|
||||
})));
|
||||
const { client, running, reopen, close } = setup();
|
||||
running();
|
||||
await reopen();
|
||||
running("inactive", "turn-new", 456);
|
||||
await act(async () => { resolveRead(response(completedThread())); });
|
||||
expect(client.getRunStartedAt("inactive")).toBe(456);
|
||||
expect(client.getRunTurnId("inactive")).toBe("turn-new");
|
||||
expect(client.hasUnsettledRun("inactive")).toBe(true);
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined();
|
||||
close();
|
||||
});
|
||||
|
||||
it("keeps an ACK-lost local send unresolved when an idle snapshot does not contain it", async () => {
|
||||
const body = completedThread("inactive", "previous-turn");
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body)));
|
||||
const { client, reopen, close } = setup();
|
||||
client.sendMessage("inactive", "A newly submitted task", undefined, { turnId: "unacknowledged-turn" });
|
||||
await reopen();
|
||||
expect(client.getRunTurnId("inactive")).toBe("unacknowledged-turn");
|
||||
expect(client.hasUnsettledRun("inactive")).toBe(true);
|
||||
close();
|
||||
});
|
||||
|
||||
it("accepts an explicit completed turn when an older host omits activity metadata", async () => {
|
||||
const body = completedThread();
|
||||
delete body.has_pending_tool_calls;
|
||||
body.completed_turn_ids = ["turn-old"];
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body)));
|
||||
const { client, running, reopen, close } = setup();
|
||||
running();
|
||||
await reopen();
|
||||
expect(client.getRunStartedAt("inactive")).toBeNull();
|
||||
expect(client.hasUnsettledRun("inactive")).toBe(false);
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toEqual(body);
|
||||
close();
|
||||
});
|
||||
|
||||
it("keeps an incomplete transcript active when its completion list excludes projected turn_end", async () => {
|
||||
const body = completedThread();
|
||||
body.completed_turn_ids = [];
|
||||
body.has_pending_tool_calls = true;
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body)));
|
||||
const { client, running, reopen, close } = setup();
|
||||
running();
|
||||
await reopen();
|
||||
expect(client.getRunStartedAt("inactive")).toBe(123);
|
||||
expect(client.hasUnsettledRun("inactive")).toBe(true);
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined();
|
||||
close();
|
||||
});
|
||||
|
||||
it("keeps a queued turn and its resumed frames active when a racing idle page has no completion", async () => {
|
||||
let resolveRead!: (value: Response) => void;
|
||||
vi.stubGlobal("fetch", vi.fn().mockImplementation(() => new Promise<Response>((resolve) => {
|
||||
resolveRead = resolve;
|
||||
})));
|
||||
const { client, sockets, running, close } = setup();
|
||||
act(() => sockets[0].close());
|
||||
client.sendMessage("inactive", "A queued task", undefined, { turnId: "turn-queued" });
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10); });
|
||||
await act(async () => { sockets.at(-1)!.open(); });
|
||||
act(() => running("inactive", "turn-queued", 456));
|
||||
const body = completedThread("inactive", "turn-queued");
|
||||
body.events = body.events.slice(0, 1);
|
||||
body.completed_turn_ids = [];
|
||||
body.active_turn_id = null;
|
||||
await act(async () => { resolveRead(response(body)); });
|
||||
expect(client.getRunStartedAt("inactive")).toBe(456);
|
||||
expect(client.hasUnsettledRun("inactive")).toBe(true);
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined();
|
||||
const resumed = vi.fn();
|
||||
client.onChat("inactive", resumed);
|
||||
resumed.mockClear();
|
||||
act(() => {
|
||||
running("inactive", "turn-queued", 456);
|
||||
sockets.at(-1)!.receive({ event: "delta", chat_id: "inactive", turn_id: "turn-queued", text: "Resumed answer" });
|
||||
});
|
||||
expect(resumed).toHaveBeenCalledWith(expect.objectContaining({ event: "goal_status", status: "running" }));
|
||||
expect(resumed).toHaveBeenCalledWith(expect.objectContaining({ event: "delta", text: "Resumed answer" }));
|
||||
close();
|
||||
});
|
||||
|
||||
it("ignores a previous connection's HTTP response after another transport drop", async () => {
|
||||
let resolveRead!: (value: Response) => void;
|
||||
vi.stubGlobal("fetch", vi.fn().mockImplementation(() => new Promise<Response>((resolve) => {
|
||||
resolveRead = resolve;
|
||||
})));
|
||||
const { client, sockets, running, reopen, close } = setup();
|
||||
running();
|
||||
await reopen();
|
||||
act(() => sockets.at(-1)!.close());
|
||||
await act(async () => { resolveRead(response(completedThread())); });
|
||||
expect(client.getRunStartedAt("inactive")).toBe(123);
|
||||
expect(client.hasUnsettledRun("inactive")).toBe(true);
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined();
|
||||
close();
|
||||
});
|
||||
|
||||
it("ignores reads from a disposed host coordinator", async () => {
|
||||
let resolveRead!: (value: Response) => void;
|
||||
vi.stubGlobal("fetch", vi.fn().mockImplementation(() => new Promise<Response>((resolve) => {
|
||||
resolveRead = resolve;
|
||||
})));
|
||||
const { client, running, reopen, close, hook } = setup();
|
||||
running();
|
||||
await reopen();
|
||||
hook.unmount();
|
||||
await act(async () => { resolveRead(response(completedThread())); });
|
||||
expect(client.getRunStartedAt("inactive")).toBe(123);
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined();
|
||||
close();
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,7 @@ function fakeClient() {
|
||||
status: "open" as const,
|
||||
defaultChatId: null as string | null,
|
||||
onStatus: () => () => {},
|
||||
onRunCompletion: () => () => {},
|
||||
onError: () => () => {},
|
||||
onChat: () => () => {},
|
||||
getRunStartedAt: () => null,
|
||||
@@ -684,6 +685,78 @@ describe("useSessions", () => {
|
||||
second.unmount();
|
||||
});
|
||||
|
||||
it("reconciles a cached 304 response as a new successful latest-page observation", async () => {
|
||||
const cached = canonicalThreadPayload({
|
||||
schemaVersion: 3,
|
||||
revision: "rev-not-modified",
|
||||
has_pending_tool_calls: false,
|
||||
completed_turn_ids: ["completed-turn"],
|
||||
messages: [{
|
||||
id: "completed-answer", role: "assistant", content: "complete answer",
|
||||
createdAt: 1, turnId: "completed-turn",
|
||||
}],
|
||||
})!;
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue(cached);
|
||||
const { result, unmount } = renderHook(() => useSessionHistory("websocket:unchanged"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
const previousVersion = result.current.version;
|
||||
const lineage = result.current.lineage;
|
||||
act(() => result.current.refresh());
|
||||
await waitFor(() => expect(result.current.version).toBeGreaterThan(previousVersion));
|
||||
expect(result.current.lineage).toBe(lineage);
|
||||
expect(result.current.completedTurnIds).toEqual(["completed-turn"]);
|
||||
expect(result.current.messages[0]?.content).toBe("complete answer");
|
||||
unmount();
|
||||
});
|
||||
|
||||
it("publishes canonical reconnect history to both mounted readers and ignores their older responses", async () => {
|
||||
const requests: Array<{
|
||||
resolve: (body: Awaited<ReturnType<typeof api.fetchWebuiThread>>) => void;
|
||||
signal: AbortSignal | undefined;
|
||||
}> = [];
|
||||
vi.mocked(api.fetchWebuiThread).mockImplementation((_token, _key, options) => new Promise((resolve) => {
|
||||
requests.push({ resolve, signal: options?.signal });
|
||||
}));
|
||||
const first = renderHook(() => useSessionHistory("websocket:shared-reconnect"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
const second = renderHook(() => useSessionHistory("websocket:shared-reconnect"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
const completed = canonicalThreadPayload({
|
||||
schemaVersion: 3, revision: "completed-response", has_pending_tool_calls: false,
|
||||
completed_turn_ids: ["completed-turn"],
|
||||
messages: [{
|
||||
id: "answer", role: "assistant", content: "published complete answer",
|
||||
turnId: "completed-turn", createdAt: 1,
|
||||
}],
|
||||
})!;
|
||||
act(() => webuiThreadCache.set("websocket:shared-reconnect", completed));
|
||||
expect(first.result.current.messages[0]?.content).toBe("published complete answer");
|
||||
expect(second.result.current.messages[0]?.content).toBe("published complete answer");
|
||||
expect(requests.every((request) => request.signal?.aborted)).toBe(true);
|
||||
const active = canonicalThreadPayload({
|
||||
schemaVersion: 3, revision: "older-active-response", has_pending_tool_calls: true,
|
||||
completed_turn_ids: [], active_turn_id: "completed-turn",
|
||||
messages: [{
|
||||
id: "answer", role: "assistant", content: "older prefix", turnId: "completed-turn", createdAt: 1,
|
||||
}],
|
||||
})!;
|
||||
await act(async () => {
|
||||
for (const request of requests) request.resolve(active);
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(first.result.current.messages[0]?.content).toBe("published complete answer");
|
||||
expect(second.result.current.messages[0]?.content).toBe("published complete answer");
|
||||
expect(first.result.current.hasPendingToolCalls).toBe(false);
|
||||
expect(second.result.current.hasPendingToolCalls).toBe(false);
|
||||
expect(webuiThreadCache.get("websocket:shared-reconnect")).toBe(completed);
|
||||
first.unmount();
|
||||
second.unmount();
|
||||
});
|
||||
|
||||
it("keeps rendered history visible when its LRU entry was evicted before refresh", async () => {
|
||||
const loaded = {
|
||||
schemaVersion: 3,
|
||||
@@ -770,21 +843,18 @@ describe("useSessions", () => {
|
||||
expect(result.current.hasPendingToolCalls).toBe(false);
|
||||
});
|
||||
|
||||
it("exposes turn ids backed by persisted completion events", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
it("exposes valid completion ids from parsed persisted history", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue(api.parseWebuiThreadPayload({
|
||||
schemaVersion: 3,
|
||||
projection: "events",
|
||||
has_pending_tool_calls: false,
|
||||
completed_turn_ids: ["turn-empty", "", "turn-empty"],
|
||||
messages: [
|
||||
completed_turn_ids: ["turn-empty", "", null, "turn-empty"],
|
||||
events: [
|
||||
{
|
||||
id: "u1",
|
||||
role: "user",
|
||||
content: "stop",
|
||||
turnId: "turn-empty",
|
||||
createdAt: 1,
|
||||
event: "user_message", chat_id: "chat-empty", text: "stop", turn_id: "turn-empty", starts_turn: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
}));
|
||||
|
||||
const { result } = renderHook(() => useSessionHistory("websocket:chat-empty"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
@@ -792,10 +862,33 @@ describe("useSessions", () => {
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
expect(result.current.error).toBeNull();
|
||||
expect(result.current.messages[0]?.content).toBe("stop");
|
||||
expect(result.current.completedTurnIds).toEqual(["turn-empty"]);
|
||||
expect(result.current.hasPendingToolCalls).toBe(false);
|
||||
});
|
||||
|
||||
it("respects an explicit empty completion list for an incomplete persisted transcript", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
projection: "events",
|
||||
has_pending_tool_calls: true,
|
||||
active_turn_id: "incomplete-turn",
|
||||
completed_turn_ids: [],
|
||||
events: [
|
||||
{ event: "user_message", chat_id: "incomplete", text: "question", turn_id: "incomplete-turn" },
|
||||
{ event: "turn_end", chat_id: "incomplete", turn_id: "incomplete-turn" },
|
||||
],
|
||||
});
|
||||
const { result } = renderHook(() => useSessionHistory("websocket:incomplete"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.completedTurnIds).toEqual([]);
|
||||
expect(result.current.completionIdsProvided).toBe(true);
|
||||
expect(result.current.hasPendingToolCalls).toBe(true);
|
||||
});
|
||||
|
||||
it("does not flag transcript as pending when last row is not a trace", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
|
||||
@@ -25,10 +25,17 @@ describe("WebuiThreadCache", () => {
|
||||
expect(cache.get("c")?.revision).toBe("rev-c");
|
||||
});
|
||||
|
||||
it("does not retain a payload larger than the byte budget", () => {
|
||||
it("publishes payloads to mounted threads even when they exceed the byte budget", () => {
|
||||
const cache = new WebuiThreadCache(64, 2);
|
||||
cache.set("large", payload("x".repeat(100)));
|
||||
const published: WebuiThreadPersistedPayload[] = [];
|
||||
const unsubscribe = cache.subscribe("large", (body) => published.push(body));
|
||||
const large = payload("x".repeat(100));
|
||||
cache.set("large", large);
|
||||
|
||||
expect(cache.get("large")).toBeUndefined();
|
||||
expect(published).toEqual([large]);
|
||||
unsubscribe();
|
||||
cache.set("large", large);
|
||||
expect(published).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user