fix(webui): settle completed turns across reconnect paths
Separate named completion facts from history adoption, preserve newer and anonymous activity, and keep one mounted whole-snapshot adopter. Unify explicit-ID lifecycle/content closure without discarding uncovered content. Cover the real client/hooks reconnect and selection races, await asynchronous browser fixture startup, and retain current-policy bounded TLC models and missing-evidence limits. Archive historical/candidate verification separately.
This commit is contained in:
1 parent
9e499ad539
commit
53a556585e
34 files changed
+1891
-46
No files matched your search
@@ -544,7 +544,7 @@ export function useNanobotStream(
|
||||
}, [chatId, client]);
|
||||
const settleFragment = useCallback((owner: ThreadTranscript) => {
|
||||
if (!chatId || !owner.fragmentCompletedTurnIds.length) return;
|
||||
client.settleFragmentRunLifecycle(chatId, owner.fragmentCompletedTurnIds);
|
||||
client.settleCompletedRunLifecycle(chatId, owner.fragmentCompletedTurnIds);
|
||||
if (!client.getRunState(chatId)?.active) setRetryStatus(null);
|
||||
}, [chatId, client]);
|
||||
|
||||
@@ -575,7 +575,9 @@ export function useNanobotStream(
|
||||
if (chatId && canonical && (ownRead || !seed)) {
|
||||
if (body?.page?.record_range) {
|
||||
if (accepted) settleFragment(owner);
|
||||
} else if (ownRead && !owner.hasPendingFragmentGap) {
|
||||
} else if (!owner.hasPendingFragmentGap) {
|
||||
// A published reconnect page supersedes this owner's shared read.
|
||||
// The owner must reconcile its completion facts after that handoff too.
|
||||
reconcileCanonical(generation, canonical, accepted);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,26 +29,32 @@ export function useReconnectRuns(client: NanobotClient, getToken: () => string):
|
||||
const body = await fetchLatestWebuiThread(client, getToken(), key, signal);
|
||||
if (!body || signal.aborted) return;
|
||||
const { completedTurnIds, snapshot } = persistedCanonicalRunState(body);
|
||||
const mounted = client.hasTranscript(chatId);
|
||||
if (body.page?.record_range) {
|
||||
if (!Array.isArray(body.completed_turn_ids)) return;
|
||||
const mounted = client.hasTranscript(chatId);
|
||||
if (client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)) {
|
||||
webuiThreadCache.set(key, body);
|
||||
}
|
||||
// A mounted owner must accept (or stage) the fragment before settling.
|
||||
// Explicit completion is otherwise independent of a newer run, but the
|
||||
// fragment is not proof that its WS content is covered.
|
||||
if (!mounted) client.settleFragmentRunLifecycle(chatId, completedTurnIds);
|
||||
if (!mounted) client.settleCompletedRunLifecycle(chatId, completedTurnIds);
|
||||
return;
|
||||
}
|
||||
const explicitlyCompleted = turnId !== null && completedTurnIds.includes(turnId);
|
||||
if (!explicitlyCompleted && (snapshot.hasPendingToolCalls || snapshot.activeTurnId)) return;
|
||||
if (turnId && !explicitlyCompleted && !snapshot.observedTurnIds.includes(turnId)) return;
|
||||
if (!client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)) return;
|
||||
// Preserve the result before completion fences prune queued fragments.
|
||||
// Returning to an inactive chat can hydrate from this canonical page.
|
||||
webuiThreadCache.set(key, body);
|
||||
client.reconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot);
|
||||
const canCache = (explicitlyCompleted || (!snapshot.hasPendingToolCalls && !snapshot.activeTurnId))
|
||||
&& (!turnId || explicitlyCompleted || snapshot.observedTurnIds.includes(turnId))
|
||||
&& client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot);
|
||||
// Preserve adoptable history before notifying completion subscribers.
|
||||
if (canCache) webuiThreadCache.set(key, body);
|
||||
// Full-page completion facts belong to the ledger regardless of whether
|
||||
// a transcript can adopt this page. Retain content for its later owner.
|
||||
client.settleCompletedRunLifecycle(chatId, completedTurnIds);
|
||||
// Mounted owners alone adopt whole snapshots. Only an idle snapshot can
|
||||
// settle activity without a named identity.
|
||||
if (!mounted && canCache && !snapshot.hasPendingToolCalls && !snapshot.activeTurnId) {
|
||||
client.reconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot);
|
||||
}
|
||||
};
|
||||
let nextJob = 0;
|
||||
const worker = async () => {
|
||||
|
||||
@@ -58,7 +58,7 @@ type Command =
|
||||
| ({ kind: "written" | "reject" } & TurnRef)
|
||||
| { kind: "transport-lost" }
|
||||
| { kind: "local-stop" | "forget"; chatId: string }
|
||||
| { kind: "fence" | "settle-fragment-lifecycle"; chatId: string; completedTurnIds: readonly string[] }
|
||||
| { kind: "fence" | "settle-completed-lifecycle"; chatId: string; completedTurnIds: readonly string[] }
|
||||
| { kind: "restore-pending"; chatId: string; generation: number; turnId: string | null };
|
||||
|
||||
export type RunEffect =
|
||||
@@ -208,10 +208,9 @@ export class ClientRunLedger {
|
||||
break;
|
||||
}
|
||||
case "fence":
|
||||
this.fence(command.chatId, command.completedTurnIds, effects);
|
||||
break;
|
||||
case "settle-fragment-lifecycle":
|
||||
this.settleFragmentLifecycle(command.chatId, command.completedTurnIds, effects);
|
||||
case "settle-completed-lifecycle":
|
||||
this.completeTurns(command.chatId, command.completedTurnIds,
|
||||
command.kind === "fence" ? "content" : "lifecycle", effects);
|
||||
break;
|
||||
default: {
|
||||
const unhandled: never = command;
|
||||
@@ -348,7 +347,7 @@ export class ClientRunLedger {
|
||||
private applyCanonicalSnapshot(request: CanonicalRequest): { accepted: boolean; effects: readonly RunEffect[] } {
|
||||
const { chatId, snapshot } = request;
|
||||
const effects: RunEffect[] = [];
|
||||
this.fence(chatId, request.completedTurnIds, effects);
|
||||
this.completeTurns(chatId, request.completedTurnIds, "content", effects);
|
||||
if (!this.canApplyCanonical({ ...request, completedTurnIds: [] })) return { accepted: false, effects };
|
||||
|
||||
const chat = this.chats.get(chatId);
|
||||
@@ -466,34 +465,23 @@ export class ClientRunLedger {
|
||||
this.trimTerminalSet(chat.closed, chat.latestTurnId);
|
||||
}
|
||||
|
||||
private settleFragmentLifecycle(chatId: string, turnIds: readonly string[], effects: RunEffect[]): void {
|
||||
for (const turnId of turnIds) {
|
||||
if (!turnId) continue;
|
||||
const chat = this.ensureChat(chatId);
|
||||
this.rememberClosed(chat, turnId);
|
||||
this.settle(chatId, turnId, effects);
|
||||
if (chat.latestTurnId === turnId) {
|
||||
chat.anonymousActive = false;
|
||||
chat.effectiveStartedAt = null;
|
||||
}
|
||||
}
|
||||
effects.push({ kind: "prune-lifecycle-inbound", chatId, turnIds });
|
||||
}
|
||||
|
||||
private fence(chatId: string, turnIds: readonly string[], effects: RunEffect[]): void {
|
||||
private completeTurns(
|
||||
chatId: string, turnIds: readonly string[], coverage: "lifecycle" | "content", effects: RunEffect[],
|
||||
): void {
|
||||
let chat = this.chats.get(chatId);
|
||||
for (const turnId of turnIds) {
|
||||
if (!turnId) continue;
|
||||
chat ??= this.ensureChat(chatId);
|
||||
chat.fenced.add(turnId);
|
||||
// Explicit completion settles ownership even when the full page cannot be adopted.
|
||||
this.rememberClosed(chat, turnId);
|
||||
this.settle(chatId, turnId, effects);
|
||||
// Anonymous recovery activity is independent of this named turn.
|
||||
// Named completion never clears a different owner or anonymous recovery.
|
||||
if (chat.latestTurnId === turnId) chat.effectiveStartedAt = null;
|
||||
if (coverage === "content") chat.fenced.add(turnId);
|
||||
}
|
||||
if (chat) this.trimTerminalSet(chat.fenced);
|
||||
effects.push({ kind: "prune-inbound", chatId, turnIds: Array.from(chat?.fenced ?? []) });
|
||||
if (coverage === "content") {
|
||||
if (chat) this.trimTerminalSet(chat.fenced);
|
||||
effects.push({ kind: "prune-inbound", chatId, turnIds: Array.from(chat?.fenced ?? []) });
|
||||
} else effects.push({ kind: "prune-lifecycle-inbound", chatId, turnIds });
|
||||
}
|
||||
|
||||
private trimTerminalSet(turnIds: Set<string>, retainedTurnId?: string | null): void {
|
||||
|
||||
@@ -439,9 +439,9 @@ export class NanobotClient {
|
||||
this.applyRunEffects(this.runs.transition({ kind: "fence", chatId, completedTurnIds }));
|
||||
}
|
||||
|
||||
/** Settle explicit fragment completions without claiming coverage of live content. */
|
||||
settleFragmentRunLifecycle(chatId: string, completedTurnIds: readonly string[]): void {
|
||||
this.applyRunEffects(this.runs.transition({ kind: "settle-fragment-lifecycle", chatId, completedTurnIds }));
|
||||
/** Settle explicit completions without claiming coverage of live content. */
|
||||
settleCompletedRunLifecycle(chatId: string, completedTurnIds: readonly string[]): void {
|
||||
this.applyRunEffects(this.runs.transition({ kind: "settle-completed-lifecycle", chatId, completedTurnIds }));
|
||||
}
|
||||
|
||||
/** Whether a mounted transcript owns delivery for this chat. */
|
||||
|
||||
@@ -391,7 +391,7 @@ describe("NanobotClient", () => {
|
||||
socket.fakeOpen();
|
||||
socket.fakeMessage({ event: "recovery_state", chat_id: "chat", status: "resuming", recovery_id: "r1", attempts: 1 });
|
||||
socket.fakeMessage({ event: "goal_status", chat_id: "chat", turn_id: "recovery:r1", status: "running", started_at: 100 });
|
||||
client.settleFragmentRunLifecycle("chat", ["recovery:r1"]);
|
||||
client.settleCompletedRunLifecycle("chat", ["recovery:r1"]);
|
||||
socket.fakeMessage({ event: "attached", chat_id: "chat", recovery_state: {
|
||||
status: "awaiting_user", recovery_id: "r1", reason: "loop_guard", attempts: 1,
|
||||
} });
|
||||
@@ -2101,9 +2101,9 @@ describe("NanobotClient", () => {
|
||||
const oldContent = { event: "message", chat_id: "chat", turn_id: "history-0", text: "Unconsumed older content" };
|
||||
socket.fakeMessage(buffered);
|
||||
socket.fakeMessage(oldContent);
|
||||
client.settleFragmentRunLifecycle("chat", ["current"]);
|
||||
client.settleCompletedRunLifecycle("chat", ["current"]);
|
||||
const history = Array.from({ length: 300 }, (_, index) => `history-${index}`);
|
||||
client.settleFragmentRunLifecycle("chat", history);
|
||||
client.settleCompletedRunLifecycle("chat", history);
|
||||
|
||||
expect(history.filter((id) => client.isRunCompleted("chat", id))).toHaveLength(255);
|
||||
expect(client.isRunCompleted("chat", "history-0")).toBe(false);
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { useNanobotStream } from "@/hooks/useNanobotStream";
|
||||
import { useReconnectRuns } from "@/hooks/useReconnectRuns";
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import type { WebuiThreadPersistedPayload } from "@/lib/types";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
|
||||
class Socket {
|
||||
readyState = 0;
|
||||
onopen: (() => void) | null = null;
|
||||
onmessage: ((event: MessageEvent) => void) | null = null;
|
||||
onclose: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
send() {}
|
||||
open() { this.readyState = 1; this.onopen?.(); }
|
||||
close() { this.readyState = 3; this.onclose?.(); }
|
||||
receive(payload: unknown) { this.onmessage?.({ data: JSON.stringify(payload) } as MessageEvent); }
|
||||
}
|
||||
|
||||
interface Read {
|
||||
chat: string;
|
||||
signal: AbortSignal;
|
||||
resolve: (body: WebuiThreadPersistedPayload) => void;
|
||||
fail: (status: number) => void;
|
||||
}
|
||||
|
||||
function history(chat: string, completed: string[], active: string | null = null): WebuiThreadPersistedPayload {
|
||||
return {
|
||||
schemaVersion: 3, sessionKey: `websocket:${chat}`, projection: "events",
|
||||
completed_turn_ids: completed, has_pending_tool_calls: active !== null, active_turn_id: active,
|
||||
page: { history_generation: "real-use", before_cursor: null, has_more_before: false },
|
||||
events: [
|
||||
...completed.flatMap((turn) => [
|
||||
{ event: "user_message" as const, chat_id: chat, turn_id: turn, turn_seq: 1,
|
||||
projection_id: `${chat}-${turn}-question`, text: `${chat} question ${turn}`, starts_turn: true },
|
||||
{ event: "message" as const, chat_id: chat, turn_id: turn, turn_seq: 2,
|
||||
projection_id: `${chat}-${turn}-answer`, text: `${chat} answer ${turn}` },
|
||||
{ event: "turn_end" as const, chat_id: chat, turn_id: turn, turn_seq: 3,
|
||||
projection_id: `${chat}-${turn}-end` },
|
||||
]),
|
||||
...(active ? [{ event: "user_message" as const, chat_id: chat, turn_id: active, turn_seq: 1,
|
||||
projection_id: `${chat}-${active}-question`, text: `${chat} question ${active}`, starts_turn: true }] : []),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function harness() {
|
||||
const reads: Read[] = [];
|
||||
vi.stubGlobal("fetch", vi.fn((url: string, init: RequestInit) => {
|
||||
if (!String(url).includes("/webui-thread")) return Promise.resolve(new Response("{}", { status: 404 }));
|
||||
const key = decodeURIComponent(new URL(String(url), "http://test").pathname.split("/")[3]);
|
||||
return new Promise<Response>((resolve) => {
|
||||
reads.push({ chat: key.slice("websocket:".length), signal: init.signal as AbortSignal,
|
||||
// Deliberately allow delivery after cancellation: the consumer must reject it.
|
||||
resolve: (body) => resolve(new Response(JSON.stringify(body), { status: 200 })),
|
||||
fail: (status) => resolve(new Response("Synthetic failure", { status })) });
|
||||
});
|
||||
}));
|
||||
const sockets: Socket[] = [];
|
||||
const client = new NanobotClient({ url: "ws://test", reconnect: true, maxBackoffMs: 10,
|
||||
socketFactory: () => { const socket = new Socket(); sockets.push(socket); return socket as unknown as WebSocket; } });
|
||||
client.connect();
|
||||
sockets[0].open();
|
||||
const token = () => "synthetic-token";
|
||||
const recovery = renderHook(() => useReconnectRuns(client, token));
|
||||
const socket = () => sockets.at(-1)!;
|
||||
const running = (chat: string, turn: string, startedAt: number) => socket().receive({
|
||||
event: "goal_status", chat_id: chat, turn_id: turn, status: "running", started_at: startedAt,
|
||||
});
|
||||
const reopen = async () => {
|
||||
act(() => socket().close());
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10); });
|
||||
await act(async () => { socket().open(); });
|
||||
};
|
||||
const cache = new ThreadMessageCache(() => false);
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<ClientProvider client={client} token="synthetic-token">{children}</ClientProvider>
|
||||
);
|
||||
const mount = (initialChat: string) => renderHook(({ chat }) => {
|
||||
const stream = useNanobotStream(chat, [], false, undefined, undefined, [], { key: `websocket:${chat}`, cache });
|
||||
useEffect(() => {
|
||||
let refreshOnNextOpen = client.status !== "open";
|
||||
return client.onStatus((status) => {
|
||||
if (status !== "open") refreshOnNextOpen = true;
|
||||
else { if (refreshOnNextOpen) stream.refreshHistory(); refreshOnNextOpen = false; }
|
||||
});
|
||||
}, [stream.refreshHistory]);
|
||||
return stream;
|
||||
}, { wrapper, initialProps: { chat: initialChat } });
|
||||
return { client, reads, socket, running, reopen, mount,
|
||||
close: () => { recovery.unmount(); client.close(); } };
|
||||
}
|
||||
|
||||
beforeEach(() => { vi.useFakeTimers(); webuiThreadCache.clear(); });
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); webuiThreadCache.clear(); });
|
||||
|
||||
describe("reconnect across chat selection and transport generations", () => {
|
||||
it("gives a mounted owner sole responsibility for a shared completed page", async () => {
|
||||
const h = harness();
|
||||
act(() => h.running("alpha", "turn-1", 100));
|
||||
const selected = h.mount("alpha");
|
||||
await act(async () => { h.reads[0].resolve(history("alpha", [], "turn-1")); });
|
||||
const reconcile = vi.spyOn(h.client, "reconcileCanonicalCompletion");
|
||||
await h.reopen();
|
||||
await act(async () => { h.reads.at(-1)!.resolve(history("alpha", ["turn-1"])); });
|
||||
expect(reconcile).toHaveBeenCalledTimes(1);
|
||||
expect(selected.result.current.messages.map((message) => message.content)).toContain("alpha answer turn-1");
|
||||
expect(selected.result.current.isStreaming).toBe(false);
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
selected.unmount();
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("settles a mounted old turn when shared reconnect history precedes the newer running frame", async () => {
|
||||
const h = harness();
|
||||
act(() => h.running("alpha", "turn-1", 100));
|
||||
const selected = h.mount("alpha");
|
||||
await act(async () => { h.reads[0].resolve(history("alpha", [], "turn-1")); });
|
||||
await h.reopen();
|
||||
const read = h.reads.at(-1)!;
|
||||
expect(read.signal.aborted).toBe(false);
|
||||
await act(async () => { read.resolve(history("alpha", ["turn-1"], "turn-2")); });
|
||||
const completedFirst = h.client.isRunCompleted("alpha", "turn-1");
|
||||
act(() => {
|
||||
h.running("alpha", "turn-2", 200);
|
||||
h.socket().receive({ event: "message", chat_id: "alpha", turn_id: "turn-2", text: "alpha live answer" });
|
||||
h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "turn-2" });
|
||||
});
|
||||
const observed = { completedFirst, state: h.client.getRunState("alpha"),
|
||||
streaming: selected.result.current.isStreaming,
|
||||
contents: selected.result.current.messages.map((message) => message.content) };
|
||||
selected.unmount();
|
||||
h.close();
|
||||
expect(observed).toMatchObject({ completedFirst: true,
|
||||
state: { active: false, unsettled: false, latestTurnId: "turn-2" }, streaming: false,
|
||||
contents: expect.arrayContaining(["alpha answer turn-1", "alpha live answer"]) });
|
||||
});
|
||||
|
||||
it.each(["before", "after"] as const)("keeps two chats isolated when obsolete responses arrive %s current recovery across two outages", async (obsoleteTiming) => {
|
||||
const h = harness();
|
||||
// Turn IDs are deliberately reused across chats; ownership is a chat/turn pair.
|
||||
act(() => { h.running("alpha", "turn-1", 100); h.running("beta", "turn-1", 101); });
|
||||
const selected = h.mount("alpha");
|
||||
await act(async () => { h.reads[0].resolve(history("alpha", [], "turn-1")); });
|
||||
await h.reopen();
|
||||
const firstRecovery = h.reads.slice(1);
|
||||
expect(firstRecovery.map((read) => read.chat).sort()).toEqual(["alpha", "beta"]);
|
||||
selected.rerender({ chat: "beta" });
|
||||
expect(h.client.hasTranscript("alpha")).toBe(false);
|
||||
expect(h.client.hasTranscript("beta")).toBe(true);
|
||||
act(() => { h.running("alpha", "turn-2", 200); h.running("beta", "turn-2", 201); });
|
||||
// Cancel the whole first recovery batch before either old page returns.
|
||||
await h.reopen();
|
||||
expect(firstRecovery.every((read) => read.signal.aborted)).toBe(true);
|
||||
const secondRecovery = h.reads.slice(3);
|
||||
expect(secondRecovery.map((read) => read.chat).sort()).toEqual(["alpha", "beta"]);
|
||||
const beforeStale = [h.client.getRunState("alpha"), h.client.getRunState("beta")];
|
||||
const deliverObsolete = async () => {
|
||||
const states = [h.client.getRunState("alpha"), h.client.getRunState("beta")];
|
||||
const cached = [webuiThreadCache.get("websocket:alpha"), webuiThreadCache.get("websocket:beta")];
|
||||
await act(async () => { for (const read of firstRecovery) read.resolve(history(read.chat, ["turn-1"])); });
|
||||
expect([h.client.getRunState("alpha"), h.client.getRunState("beta")]).toEqual(states);
|
||||
expect([webuiThreadCache.get("websocket:alpha"), webuiThreadCache.get("websocket:beta")]).toEqual(cached);
|
||||
};
|
||||
if (obsoleteTiming === "before") await deliverObsolete();
|
||||
// Unmount beta while its shared current read survives in background recovery.
|
||||
selected.rerender({ chat: "alpha" });
|
||||
const secondAlpha = secondRecovery.find((read) => read.chat === "alpha")!;
|
||||
const secondBeta = secondRecovery.find((read) => read.chat === "beta")!;
|
||||
await act(async () => { secondBeta.resolve(history("beta", ["turn-1"], "turn-2")); });
|
||||
expect(h.client.isRunCompleted("beta", "turn-1")).toBe(true);
|
||||
expect(h.client.getRunState("alpha")).toEqual(beforeStale[0]);
|
||||
const betaBeforeAlpha = h.client.getRunState("beta");
|
||||
await act(async () => { secondAlpha.resolve(history("alpha", ["turn-1"], "turn-2")); });
|
||||
expect(h.client.isRunCompleted("alpha", "turn-1")).toBe(true);
|
||||
expect(h.client.getRunState("beta")).toEqual(betaBeforeAlpha);
|
||||
if (obsoleteTiming === "after") await deliverObsolete();
|
||||
for (const chat of ["alpha", "beta"]) expect(h.client.getRunState(chat)).toMatchObject({ active: true, latestTurnId: "turn-2" });
|
||||
act(() => {
|
||||
for (const chat of ["alpha", "beta"]) {
|
||||
h.socket().receive({ event: "message", chat_id: chat, turn_id: "turn-2", turn_seq: 2,
|
||||
projection_id: `${chat}-turn-2-answer`, text: `${chat} answer turn-2` });
|
||||
h.socket().receive({ event: "turn_end", chat_id: chat, turn_id: "turn-2", turn_seq: 3 });
|
||||
}
|
||||
});
|
||||
for (const chat of ["alpha", "beta"]) expect(h.client.getRunState(chat)).toMatchObject({ active: false, unsettled: false });
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
expect(selected.result.current.messages.map((message) => message.content)).toEqual(expect.arrayContaining([
|
||||
"alpha answer turn-1", "alpha answer turn-2",
|
||||
]));
|
||||
expect(selected.result.current.messages.every((message) => !message.content.includes("beta"))).toBe(true);
|
||||
// A third alpha turn starts while the user returns to the now-idle beta.
|
||||
act(() => h.running("alpha", "turn-3", 300));
|
||||
const alphaThird = h.client.getRunState("alpha");
|
||||
selected.rerender({ chat: "beta" });
|
||||
await act(async () => { h.reads.at(-1)!.resolve(history("beta", ["turn-1", "turn-2"])); });
|
||||
expect(h.client.getRunState("alpha")).toEqual(alphaThird);
|
||||
expect(selected.result.current.messages.map((message) => message.content)).toEqual(expect.arrayContaining([
|
||||
"beta answer turn-1", "beta answer turn-2",
|
||||
]));
|
||||
expect(selected.result.current.messages.every((message) => !message.content.includes("alpha"))).toBe(true);
|
||||
expect(selected.result.current.isStreaming).toBe(false);
|
||||
act(() => {
|
||||
h.socket().receive({ event: "message", chat_id: "alpha", turn_id: "turn-3", text: "alpha answer turn-3" });
|
||||
h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "turn-3" });
|
||||
});
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
expect(selected.result.current.messages.every((message) => !message.content.includes("alpha"))).toBe(true);
|
||||
selected.unmount();
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("preserves anonymous recovery through a mounted full-page cache handoff", async () => {
|
||||
const h = harness();
|
||||
act(() => h.running("alpha", "turn-1", 100));
|
||||
const selected = h.mount("alpha");
|
||||
await act(async () => { h.reads[0].resolve(history("alpha", [], "turn-1")); });
|
||||
act(() => h.socket().receive({ event: "recovery_state", chat_id: "alpha", status: "resuming",
|
||||
recovery_id: "independent", attempts: 1 }));
|
||||
await h.reopen();
|
||||
const body = { ...history("alpha", ["turn-1"]), has_pending_tool_calls: true };
|
||||
await act(async () => { h.reads.at(-1)!.resolve(body); });
|
||||
expect(h.client.isRunCompleted("alpha", "turn-1")).toBe(true);
|
||||
expect(h.client.getRunState("alpha")).toMatchObject({ active: true, unsettled: false, startedAt: null });
|
||||
expect(selected.result.current.isStreaming).toBe(true);
|
||||
act(() => h.socket().receive({ event: "recovery_state", chat_id: "alpha", status: "recovered",
|
||||
recovery_id: "independent", attempts: 1 }));
|
||||
expect(h.client.getRunState("alpha")).toMatchObject({ active: false, unsettled: false });
|
||||
expect(selected.result.current.isStreaming).toBe(false);
|
||||
selected.unmount();
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("rejects an abandoned chat's page after switching away and back without reconnecting", async () => {
|
||||
const h = harness();
|
||||
act(() => { h.running("alpha", "turn-1", 100); h.running("beta", "turn-1", 101); });
|
||||
const selected = h.mount("alpha");
|
||||
selected.rerender({ chat: "beta" });
|
||||
selected.rerender({ chat: "alpha" });
|
||||
const [abandonedAlpha, abandonedBeta, currentAlpha] = h.reads;
|
||||
expect(abandonedAlpha.signal.aborted).toBe(true);
|
||||
expect(abandonedBeta.signal.aborted).toBe(true);
|
||||
act(() => h.running("alpha", "turn-2", 200));
|
||||
await act(async () => { currentAlpha.resolve(history("alpha", ["turn-1"], "turn-2")); });
|
||||
const before = h.client.getRunState("alpha");
|
||||
await act(async () => {
|
||||
abandonedAlpha.resolve(history("alpha", [], "turn-1"));
|
||||
abandonedBeta.resolve(history("beta", ["turn-1"]));
|
||||
});
|
||||
expect(h.client.getRunState("alpha")).toEqual(before);
|
||||
expect(selected.result.current.messages.map((message) => message.content)).toContain("alpha answer turn-1");
|
||||
expect(selected.result.current.messages.every((message) => !message.content.includes("beta"))).toBe(true);
|
||||
expect(h.client.isRunCompleted("beta", "turn-1")).toBe(false);
|
||||
act(() => {
|
||||
for (const [chat, turn] of [["alpha", "turn-2"], ["beta", "turn-1"]]) {
|
||||
h.socket().receive({ event: "turn_end", chat_id: chat, turn_id: turn });
|
||||
}
|
||||
});
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
selected.unmount();
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("does not strand an older turn when selection changes before the scheduled mounted refresh", async () => {
|
||||
const h = harness();
|
||||
act(() => h.running("alpha", "turn-1", 100));
|
||||
const selected = h.mount("alpha");
|
||||
await h.reopen();
|
||||
const oldRead = h.reads.at(-1)!;
|
||||
act(() => h.socket().close());
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10); });
|
||||
const canReconcile = h.client.canReconcileCanonicalCompletion.bind(h.client);
|
||||
let pageProcessed!: () => void;
|
||||
const processed = new Promise<void>((resolve) => { pageProcessed = resolve; });
|
||||
const preflights: boolean[] = [];
|
||||
vi.spyOn(h.client, "canReconcileCanonicalCompletion").mockImplementation((...args) => {
|
||||
const accepted = canReconcile(...args);
|
||||
if (args[2].includes("turn-1") && args[3]?.activeTurnId === "turn-2") {
|
||||
preflights.push(accepted);
|
||||
pageProcessed();
|
||||
}
|
||||
return accepted;
|
||||
});
|
||||
let readsBeforeSwitch = 0;
|
||||
await act(async () => {
|
||||
h.socket().open();
|
||||
h.running("alpha", "turn-2", 200);
|
||||
h.reads.at(-1)!.resolve(history("alpha", ["turn-1"], "turn-2"));
|
||||
await processed;
|
||||
readsBeforeSwitch = h.reads.length;
|
||||
selected.rerender({ chat: "beta" });
|
||||
});
|
||||
act(() => {
|
||||
h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "turn-2" });
|
||||
h.socket().receive({ event: "session_updated", chat_id: "alpha", scope: "thread" });
|
||||
});
|
||||
const observed = { preflights, readsBeforeSwitch, oldReadAborted: oldRead.signal.aborted,
|
||||
state: h.client.getRunState("alpha"), unsettled: h.client.getUnsettledRunChatIds() };
|
||||
selected.unmount();
|
||||
h.close();
|
||||
expect(observed).toMatchObject({ preflights: [false], readsBeforeSwitch: 3, oldReadAborted: true,
|
||||
state: { active: false, unsettled: false }, unsettled: [] });
|
||||
});
|
||||
|
||||
it("recovers six chats beyond the read-concurrency limit after a failed page and repeated drops", async () => {
|
||||
const h = harness();
|
||||
const chats = Array.from({ length: 6 }, (_, index) => `chat-${index}`);
|
||||
act(() => { for (const chat of chats) h.running(chat, "turn-1", 100); });
|
||||
await h.reopen();
|
||||
const abandoned = [...h.reads];
|
||||
expect(abandoned).toHaveLength(4);
|
||||
await h.reopen();
|
||||
expect(abandoned.every((read) => read.signal.aborted)).toBe(true);
|
||||
const current = h.reads.slice(4);
|
||||
expect(current).toHaveLength(4);
|
||||
await act(async () => {
|
||||
current[0].fail(503);
|
||||
for (const read of current.slice(1)) read.resolve(history(read.chat, ["turn-1"]));
|
||||
});
|
||||
const remaining = h.reads.slice(8);
|
||||
expect(remaining.map((read) => read.chat).sort()).toEqual(["chat-4", "chat-5"]);
|
||||
await act(async () => { for (const read of remaining) read.resolve(history(read.chat, ["turn-1"])); });
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual(["chat-0"]);
|
||||
// A failed read is not success; the next real reconnect supplies its evidence.
|
||||
await h.reopen();
|
||||
expect(h.reads.slice(10).map((read) => read.chat)).toEqual(["chat-0"]);
|
||||
await act(async () => { h.reads[10].resolve(history("chat-0", ["turn-1"])); });
|
||||
await act(async () => { for (const read of abandoned) read.resolve(history(read.chat, [], "turn-1")); });
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
for (const chat of chats) {
|
||||
expect(h.client.getRunState(chat)).toMatchObject({ active: false, unsettled: false });
|
||||
expect(webuiThreadCache.get(`websocket:${chat}`)?.completed_turn_ids).toEqual(["turn-1"]);
|
||||
}
|
||||
h.close();
|
||||
});
|
||||
});
|
||||
@@ -92,7 +92,7 @@ function makeClient() {
|
||||
getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle),
|
||||
canReconcileCanonicalCompletion,
|
||||
reconcileCanonicalCompletion,
|
||||
settleFragmentRunLifecycle: vi.fn(lifecycle.settleFragmentRunLifecycle.bind(lifecycle)),
|
||||
settleCompletedRunLifecycle: vi.fn(lifecycle.settleCompletedRunLifecycle.bind(lifecycle)),
|
||||
fenceCanonicalCompletedTurns: lifecycle.fenceCanonicalCompletedTurns.bind(lifecycle),
|
||||
getGoalState: lifecycle.getGoalState.bind(lifecycle),
|
||||
onTranscript: lifecycle.onTranscript.bind(lifecycle),
|
||||
@@ -266,9 +266,8 @@ function publishReconnectCompletion(
|
||||
const generation = client.getRunGeneration(chatId);
|
||||
const { completedTurnIds, snapshot } = persistedCanonicalRunState(body);
|
||||
expect(client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)).toBe(true);
|
||||
// useReconnectRuns publishes synchronously before settling/fencing the ledger.
|
||||
// A mounted transcript takes over reconciliation from the recovery reader.
|
||||
webuiThreadCache.set(`websocket:${chatId}`, body);
|
||||
expect(client.reconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)).toBe(true);
|
||||
}
|
||||
|
||||
function httpJson(body: unknown) {
|
||||
|
||||
@@ -116,6 +116,70 @@ describe("durable run recovery", () => {
|
||||
close();
|
||||
});
|
||||
|
||||
it.each(["before", "during"] as const)("settles an unmounted old completion when a newer turn starts %s the full-page read", async (timing) => {
|
||||
let finishRead!: (value: Response) => void;
|
||||
vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((resolve) => { finishRead = resolve; })));
|
||||
const { client, sockets, running, reopen, close } = setup();
|
||||
const early = { event: "delta", chat_id: "inactive", turn_id: "turn-old", stream_id: "old", text: "Buffered A" };
|
||||
const late = { ...early, text: "Late A" };
|
||||
const live = { event: "delta", chat_id: "inactive", turn_id: "turn-new", stream_id: "new", text: "Live B" };
|
||||
running();
|
||||
sockets[0].receive(early);
|
||||
if (timing === "before") running("inactive", "turn-new", 456);
|
||||
await reopen();
|
||||
if (timing === "during") act(() => running("inactive", "turn-new", 456));
|
||||
const newer = client.getRunState("inactive");
|
||||
const body: WebuiThreadPersistedPayload = {
|
||||
...completedThread(), schemaVersion: 3, completed_turn_ids: ["turn-old"],
|
||||
has_pending_tool_calls: true, active_turn_id: "turn-new",
|
||||
};
|
||||
body.events.push({ event: "user_message", chat_id: "inactive", turn_id: "turn-new", text: "Next task", starts_turn: true });
|
||||
await act(async () => { finishRead(response(body)); });
|
||||
expect(client.isRunCompleted("inactive", "turn-old")).toBe(true);
|
||||
expect(client.getRunState("inactive")).toEqual(newer);
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined();
|
||||
act(() => {
|
||||
sockets.at(-1)!.receive(late);
|
||||
sockets.at(-1)!.receive(live);
|
||||
running("inactive", "turn-old", 999);
|
||||
sockets.at(-1)!.receive({ event: "turn_end", chat_id: "inactive", turn_id: "turn-new" });
|
||||
});
|
||||
expect(client.getRunState("inactive")).toMatchObject({
|
||||
active: false, unsettled: false, latestTurnId: "turn-new", startedAt: null, generation: newer.generation,
|
||||
});
|
||||
expect(client.getUnsettledRunChatIds()).toEqual([]);
|
||||
const replay = vi.fn();
|
||||
client.onTranscript("inactive", replay);
|
||||
for (const content of [early, late, live]) expect(replay).toHaveBeenCalledWith(content);
|
||||
expect(replay).not.toHaveBeenCalledWith(expect.objectContaining({ event: "goal_status", turn_id: "turn-old" }));
|
||||
close();
|
||||
});
|
||||
|
||||
it.each(["full page", "fragment"] as const)("preserves independent anonymous recovery when a %s completes the old named turn", async (page) => {
|
||||
const body: WebuiThreadPersistedPayload = {
|
||||
...completedThread(), schemaVersion: 3, completed_turn_ids: ["turn-old"],
|
||||
has_pending_tool_calls: true, active_turn_id: null,
|
||||
...(page === "fragment" ? {
|
||||
page: { history_generation: "generation", record_range: { turn: 0, start: 5, end: 8 },
|
||||
before_cursor: "before-5", has_more_before: true, truncated_oversized_turn: true },
|
||||
} : {}),
|
||||
};
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body)));
|
||||
const { client, sockets, running, reopen, close } = setup();
|
||||
running();
|
||||
sockets[0].receive({ event: "recovery_state", chat_id: "inactive", status: "resuming", recovery_id: "new-recovery", attempts: 1 });
|
||||
const generation = client.getRunGeneration("inactive");
|
||||
await reopen();
|
||||
expect(client.isRunCompleted("inactive", "turn-old")).toBe(true);
|
||||
expect(client.getRunState("inactive")).toMatchObject({
|
||||
active: true, unsettled: false, latestTurnId: "turn-old", startedAt: null, generation,
|
||||
});
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toEqual(body);
|
||||
act(() => sockets.at(-1)!.receive({ event: "recovery_state", chat_id: "inactive", status: "recovered", recovery_id: "new-recovery", attempts: 1 }));
|
||||
expect(client.getRunState("inactive")).toMatchObject({ active: false, unsettled: false });
|
||||
close();
|
||||
});
|
||||
|
||||
it("settles an unmounted run without losing buffered or late output absent from its completed latest fragment", async () => {
|
||||
const chatId = "inactive";
|
||||
const turnId = "turn-old";
|
||||
|
||||
Reference in new issue
Block a user