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:
chengyongru authored and GitHub committed 2026-10-16 11:38:05 +08:00
1 parent aeca1c0f1a
commit fdeda8a468
18 files changed
+1741 -225

No files matched your search

+2 -19
View File
@@ -49,6 +49,7 @@ import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surf
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { useSessions } from "@/hooks/useSessions";
import { useReconnectRuns } from "@/hooks/useReconnectRuns";
import { useDeferredTitleRefresh } from "@/hooks/useDeferredTitleRefresh";
import { useSidebarState } from "@/hooks/useSidebarState";
import { useSkills } from "@/hooks/useSkills";
@@ -1194,6 +1195,7 @@ function Shell({
const remoteConnectionsRef = useRef(remoteConnections);
remoteConnectionsRef.current = remoteConnections;
const { client, getToken } = useClient();
useReconnectRuns(client, getToken);
const {
sessions,
loading,
@@ -1700,25 +1702,6 @@ function Shell({
for (const chatId of activeRunIds) {
client.attach(chatId);
}
setRunningChatIds((current) => {
let changed = false;
const next = new Set(current);
for (const chatId of activeRunIds) {
if (!next.has(chatId)) changed = true;
next.add(chatId);
}
if (!changed) return current;
runningChatIdsRef.current = next;
return next;
});
setUpdatedChatIds((current) => {
let changed = false;
const next = new Set(current);
for (const chatId of activeRunIds) {
if (next.delete(chatId)) changed = true;
}
return changed ? next : current;
});
}, [client, loading, sessions]);
const openHostSidebar = useCallback(() => {
+190 -72
View File
@@ -73,6 +73,7 @@ import type {
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { canonicalRunSnapshot, completedAssistantTurnIds } from "@/lib/canonical-run-snapshot";
import { providerDisplayLabel } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
@@ -80,6 +81,7 @@ import { useClient } from "@/providers/ClientProvider";
type MessageShape = Pick<UIMessage, "role" | "kind" | "content" | "isStreaming" | "turnId">;
interface PendingCanonicalHydrate {
source: "initial" | "refresh";
historyLineage: number;
historyVersion: number;
runGeneration: number;
@@ -358,28 +360,120 @@ function hasInlineDeliveryError(
));
}
function completedAssistantTurnIds(messages: UIMessage[]): string[] {
return Array.from(new Set(
messages
.filter((message) => message.role === "assistant" && !!message.turnId)
.map((message) => message.turnId as string),
));
}
function canonicalRunSnapshot(
messages: UIMessage[],
hasPendingToolCalls: boolean,
activeTurnId: string | null,
): CanonicalRunSnapshot {
return {
observedTurnIds: Array.from(new Set(
messages
.filter((message) => message.role === "user" && !!message.turnId)
.map((message) => message.turnId as string),
)),
hasPendingToolCalls,
activeTurnId,
function replaceCanonicalCompletedTurns(
current: UIMessage[],
canonical: UIMessage[],
completedTurnIds: readonly string[],
): UIMessage[] {
const completed = new Set(completedTurnIds);
const represented = new Set(canonical.flatMap((message) => (
message.turnId && completed.has(message.turnId) ? [message.turnId] : []
)));
if (!current.some((message) => message.turnId && represented.has(message.turnId))) {
return current;
}
const retained: UIMessage[] = [];
const originalPositions = new Map<string, number>();
for (const message of current) {
if (message.turnId && represented.has(message.turnId)) {
if (!originalPositions.has(message.turnId)) {
originalPositions.set(message.turnId, retained.length);
}
} else {
retained.push(message);
}
}
// Supplemental inputs may have their own turn identity between two answer
// segments. Match those retained rows as anchors so completed rows keep the
// canonical chronology instead of being grouped at the first turn row.
type AnchorQueue = { indices: number[]; offset: number };
type ShapeAnchors = {
all: AnchorQueue;
byTurnId: Map<string | undefined, AnchorQueue>;
};
const anchorIndex = new Map<string, Map<string, ShapeAnchors>>();
for (let index = 0; index < retained.length; index += 1) {
const message = retained[index];
const shape = JSON.stringify([message.role, message.kind ?? ""]);
let byContent = anchorIndex.get(shape);
if (!byContent) {
byContent = new Map();
anchorIndex.set(shape, byContent);
}
let positions = byContent.get(message.content);
if (!positions) {
positions = {
all: { indices: [], offset: 0 },
byTurnId: new Map(),
};
byContent.set(message.content, positions);
}
positions.all.indices.push(index);
const turnId = message.turnId || undefined;
const queue = positions.byTurnId.get(turnId) ?? { indices: [], offset: 0 };
queue.indices.push(index);
positions.byTurnId.set(turnId, queue);
}
let cursor = 0;
let fallbackBoundary = 0;
const firstAnchor = (queue: AnchorQueue | undefined, minimumIndex: number): number => {
if (!queue) return retained.length;
while (queue.offset < queue.indices.length && queue.indices[queue.offset] < minimumIndex) {
queue.offset += 1;
}
return queue.indices[queue.offset] ?? retained.length;
};
const anchors = canonical.map((message) => {
if (message.turnId && represented.has(message.turnId)) {
// Keep anonymous matches after this turn's retained pagination prefix.
fallbackBoundary = Math.max(fallbackBoundary, originalPositions.get(message.turnId) ?? 0);
return -1;
}
const positions = anchorIndex
.get(JSON.stringify([message.role, message.kind ?? ""]))
?.get(message.content);
const exactIndex = message.turnId
? firstAnchor(positions?.byTurnId.get(message.turnId), cursor)
: retained.length;
const index = exactIndex < retained.length
? exactIndex
: firstAnchor(
message.turnId ? positions?.byTurnId.get(undefined) : positions?.all,
Math.max(cursor, fallbackBoundary),
);
if (index === retained.length) return -1;
cursor = index + 1;
return index;
});
const nextAnchors = new Array<number | undefined>(anchors.length);
let nextAnchor: number | undefined;
for (let index = anchors.length - 1; index >= 0; index -= 1) {
nextAnchors[index] = nextAnchor;
if (anchors[index] >= 0) nextAnchor = anchors[index];
}
const insertions = new Map<number, UIMessage[]>();
let precedingAnchor = 0;
let previousInsertionPosition = 0;
for (let index = 0; index < canonical.length; index += 1) {
if (anchors[index] >= 0) precedingAnchor = anchors[index] + 1;
const message = canonical[index];
if (!message.turnId || !represented.has(message.turnId)) continue;
const position = Math.max(
previousInsertionPosition,
nextAnchors[index] ?? Math.max(
precedingAnchor,
originalPositions.get(message.turnId) ?? precedingAnchor,
),
);
previousInsertionPosition = position;
const rows = insertions.get(position) ?? [];
rows.push(message);
insertions.set(position, rows);
}
return retained.flatMap((message, index) => [
...insertions.get(index) ?? [],
message,
]).concat(insertions.get(retained.length) ?? []);
}
const FILE_PREVIEW_DEFAULT_WIDTH = 544;
@@ -694,6 +788,7 @@ export function ThreadShell({
userMessageOffset,
hasPendingToolCalls,
completedTurnIds,
completionIdsProvided,
continuity: historyContinuity,
lineage: historyLineage,
activeTurnId: historyActiveTurnId,
@@ -806,8 +901,11 @@ export function ThreadShell({
const initial = useMemo(() => {
if (!chatId) return historical;
return messageCacheRef.current.get(chatId) ?? historical;
}, [chatId, historical]);
const cached = messageCacheRef.current.get(chatId);
return cached
? replaceCanonicalCompletedTurns(cached, historical, completedTurnIds)
: historical;
}, [chatId, completedTurnIds, historical]);
const handleTurnEnd = useCallback(() => {
if (chatId) activeViewportTurnByChatIdRef.current.delete(chatId);
setSubmittedViewportTurnId(null);
@@ -833,7 +931,9 @@ export function ThreadShell({
setMessages,
streamError,
dismissStreamError,
} = useNanobotStream(chatId, initial, hasPendingToolCalls, handleTurnEnd, handleStreamDetach);
} = useNanobotStream(
chatId, initial, hasPendingToolCalls, handleTurnEnd, handleStreamDetach, completedTurnIds,
);
const loadTraceDetails = useCallback(async (refs: string[]) => {
const requestKey = historyKey;
@@ -1144,23 +1244,49 @@ export function ThreadShell({
});
}, [client, refreshModelSettings]);
useEffect(() => {
if (!historyKey || !chatId) return;
pendingCanonicalHydrateRef.current.set(chatId, {
source: "initial",
historyLineage,
historyVersion,
runGeneration: client.getRunGeneration(chatId),
uiBaseline: durableMessageShapes(initial),
uiLineage: committedHistoryLineageRef.current.get(chatId) ?? null,
uiRevision: uiRevisionRef.current,
});
// Capture the request's run generation when entering a conversation, before
// its history response can race with another send or running event.
}, [chatId, client, historyKey]);
useEffect(() => {
if (!historyKey || !chatId || loading) return;
client.fenceCanonicalCompletedTurns(chatId, completedTurnIds);
const cached = messageCacheRef.current.get(chatId);
const pendingCanonicalHydrate = pendingCanonicalHydrateRef.current.get(chatId);
const hasNewCanonicalHistory = (
const shouldReconcileRun = (
pendingCanonicalHydrate !== undefined
&& historyVersion > pendingCanonicalHydrate.historyVersion
&& (
pendingCanonicalHydrate.source === "refresh"
|| (
(historical.length > 0 || completedTurnIds.length > 0)
&& (isStreaming || runStartedAt !== null || client.hasUnsettledRun(chatId))
)
)
);
// When the user switches away and back, keep the local in-memory thread
// state (including not-yet-persisted messages) instead of replacing it with
// whatever the history endpoint currently knows about. Once a fresh
// canonical replay arrives (e.g. after ``session_updated`` refresh), prefer it
// so rendering converges to the same shape as a manual refresh.
const normalizedHistory = projectWebuiThreadMessages(historical);
const keepLiveMessages = (current: UIMessage[]) => projectWebuiThreadMessages(current);
if (hasNewCanonicalHistory && pendingCanonicalHydrate) {
const canonicalCompletedTurnIds = Array.from(new Set([
...completedTurnIds,
...(!completionIdsProvided && !hasPendingToolCalls && historyActiveTurnId === null
? completedAssistantTurnIds(normalizedHistory)
: []),
]));
// Completion is a fact about a turn, even when a newer local turn prevents
// this snapshot from settling the conversation's current run.
client.fenceCanonicalCompletedTurns(chatId, canonicalCompletedTurnIds);
const keepLiveMessages = (current: UIMessage[]) => projectWebuiThreadMessages(
replaceCanonicalCompletedTurns(current, normalizedHistory, canonicalCompletedTurnIds),
);
if (shouldReconcileRun && pendingCanonicalHydrate) {
// Transcript replay strips streaming metadata and uses persisted ids.
// Never adopt it while the turn is active: even if no assistant delta
// arrived locally yet, the next resumed delta must create/continue the
@@ -1175,7 +1301,8 @@ export function ThreadShell({
&& (
historyContinuity === "reset"
|| (
historyContinuity === "overlap"
pendingCanonicalHydrate.source === "refresh"
&& historyContinuity === "overlap"
&& historyLineage === pendingCanonicalHydrate.historyLineage
)
)
@@ -1198,14 +1325,11 @@ export function ThreadShell({
setMessages((current) => keepLiveMessages(current));
return;
}
const canonicalCompletedTurnIds = Array.from(new Set([
...completedTurnIds,
...completedAssistantTurnIds(normalizedHistory),
]));
const canonicalSnapshot = canonicalRunSnapshot(
normalizedHistory,
hasPendingToolCalls,
historyActiveTurnId,
completionIdsProvided,
);
if (!client.canReconcileCanonicalCompletion(
chatId,
@@ -1224,7 +1348,7 @@ export function ThreadShell({
historyVersion,
hydrate: pendingCanonicalHydrate,
messages: normalizedHistory,
previousMessages: messages,
previousMessages: keepLiveMessages(messages),
});
setMessages((current) => {
if (current !== messages) return current;
@@ -1239,12 +1363,11 @@ export function ThreadShell({
});
return;
}
const adoptsNormalizedHistory = cached && cached.length > 0
? (
normalizedHistory.length > cached.length
&& !isStaleThreadSnapshot(messages, normalizedHistory)
)
: !isStaleThreadSnapshot(messages, normalizedHistory);
const reconciledMessages = keepLiveMessages(messages);
const adoptsNormalizedHistory = (
(!hasPendingToolCalls || messages.length === 0)
&& !isStaleThreadSnapshot(reconciledMessages, normalizedHistory, true)
);
if (adoptsNormalizedHistory) {
pendingHistoryLineageCommitRef.current.set(chatId, {
lineage: historyLineage,
@@ -1252,24 +1375,18 @@ export function ThreadShell({
});
}
setMessages((current) => {
if (cached && cached.length > 0) {
if (
normalizedHistory.length > cached.length
&& !isStaleThreadSnapshot(current, normalizedHistory)
) {
return normalizedHistory;
}
return isStaleThreadSnapshot(current, cached) ? keepLiveMessages(current) : cached;
}
return isStaleThreadSnapshot(current, normalizedHistory)
? keepLiveMessages(current)
: normalizedHistory;
const reconciled = keepLiveMessages(current);
return (hasPendingToolCalls && current.length > 0)
|| isStaleThreadSnapshot(reconciled, normalizedHistory, true)
? reconciled
: normalizedHistory;
});
}, [
loading,
chatId,
client,
completedTurnIds,
completionIdsProvided,
historical,
historyVersion,
historyContinuity,
@@ -1295,21 +1412,21 @@ export function ThreadShell({
pendingCanonicalCommitRef.current.delete(chatId);
return;
}
if (uiRevisionRef.current !== commit.expectedUiRevision) {
if (
uiRevisionRef.current !== commit.expectedUiRevision
|| !client.reconcileCanonicalCompletion(
chatId,
commit.hydrate.runGeneration,
commit.completedTurnIds,
commit.canonicalSnapshot,
)
) {
pendingCanonicalCommitRef.current.delete(chatId);
const fallback = messageCacheRef.current.get(chatId) ?? commit.previousMessages;
messageCacheRef.current.set(chatId, fallback);
setMessages((current) => current === commit.messages ? fallback : current);
return;
}
if (!client.reconcileCanonicalCompletion(
chatId,
commit.hydrate.runGeneration,
commit.completedTurnIds,
commit.canonicalSnapshot,
)) {
pendingCanonicalCommitRef.current.delete(chatId);
const fallback = messageCacheRef.current.get(chatId) ?? commit.previousMessages;
const fallback = replaceCanonicalCompletedTurns(
messageCacheRef.current.get(chatId) ?? commit.previousMessages,
commit.messages,
commit.completedTurnIds,
);
messageCacheRef.current.set(chatId, fallback);
setMessages((current) => current === commit.messages ? fallback : current);
return;
@@ -1330,6 +1447,7 @@ export function ThreadShell({
const refreshCanonicalHistory = useCallback(() => {
if (!historyKey || !chatId) return;
pendingCanonicalHydrateRef.current.set(chatId, {
source: "refresh",
historyLineage,
historyVersion,
runGeneration: client.getRunGeneration(chatId),
+14 -5
View File
@@ -1,5 +1,5 @@
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
@@ -46,6 +46,8 @@ type PendingStreamEvent =
const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000;
// Markdown and layout work must leave room for input between visible updates.
const VISIBLE_STREAM_FLUSH_INTERVAL_MS = 50;
const EMPTY_INITIAL_MESSAGES: UIMessage[] = [];
const EMPTY_COMPLETED_TURN_IDS: readonly string[] = [];
/**
* Subscribe to a chat by ID. Returns the in-memory message list for the chat,
@@ -134,10 +136,11 @@ function appendProjectedSessionInput(
export function useNanobotStream(
chatId: string | null,
initialMessages: UIMessage[] = [],
initialMessages: UIMessage[] = EMPTY_INITIAL_MESSAGES,
hasPendingToolCalls = false,
onTurnEnd?: () => void,
onStreamDetach?: (messages: UIMessage[]) => void,
completedTurnIds: readonly string[] = EMPTY_COMPLETED_TURN_IDS,
): {
messages: UIMessage[];
/** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */
@@ -186,7 +189,13 @@ export function useNanobotStream(
}, []);
const [messageOwnerChatId, setMessageOwnerChatId] = useState(chatId);
/** If history ends in unfinished agent activity, keep the loading spinner alive. */
const initialStreaming = hasPendingAgentActivity(initialMessages);
const initialStreaming = useMemo(() => {
if (completedTurnIds.length === 0) return hasPendingAgentActivity(initialMessages);
const completedInitialTurns = new Set(completedTurnIds);
return hasPendingAgentActivity(initialMessages.filter((message) => (
!message.turnId || !completedInitialTurns.has(message.turnId)
)));
}, [completedTurnIds, initialMessages]);
const [isStreaming, setIsStreaming] = useState(
initialStreaming || hasPendingToolCalls || initialRunStartedAt !== null,
);
@@ -518,7 +527,7 @@ export function useNanobotStream(
setMessages(initialMessages);
setMessageOwnerChatId(chatId);
setIsStreaming(
hasPendingAgentActivity(initialMessages)
initialStreaming
|| hasPendingToolCalls
|| restoredRunStartedAt !== null,
);
@@ -1023,7 +1032,7 @@ export function useNanobotStream(
const reconcileTurnComplete = useCallback(() => {
clearPendingStreamWork();
projectionRef.current = resetThreadProjectionCursor(projectionRef.current);
projectionRef.current = resetThreadProjectionCursor(projectionRef.current, messagesRef.current);
setRunStartedAt(null);
setRetryStatus(null);
setIsStreaming(false);
+60
View File
@@ -0,0 +1,60 @@
import { useEffect } from "react";
import { persistedCanonicalRunState } from "@/lib/canonical-run-snapshot";
import { fetchLatestWebuiThread } from "@/lib/latest-thread-request";
import type { NanobotClient } from "@/lib/nanobot-client";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
const RECONNECT_READ_CONCURRENCY = 4;
/** Reconcile durable runs even when their threads are not mounted. */
export function useReconnectRuns(client: NanobotClient, getToken: () => string): void {
useEffect(() => {
let controller: AbortController | null = null;
const unsubscribe = client.onStatus((status) => {
controller?.abort();
controller = null;
if (status !== "open") return;
const chats = client.getUnsettledRunChatIds();
if (chats.length === 0) return;
controller = new AbortController();
const signal = controller.signal;
const jobs = chats.map((chatId) => ({
chatId,
generation: client.getRunGeneration(chatId),
turnId: client.getRunTurnId(chatId),
}));
const recover = async ({ chatId, generation, turnId }: typeof jobs[number]) => {
const key = `websocket:${chatId}`;
const body = await fetchLatestWebuiThread(client, getToken(), key, signal);
if (!body || signal.aborted) return;
const { completedTurnIds, snapshot } = persistedCanonicalRunState(body);
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);
};
let nextJob = 0;
const worker = async () => {
while (!signal.aborted) {
const job = jobs[nextJob++];
if (!job) return;
try {
await recover(job);
} catch {
// A failed read leaves this run unresolved; other chats can recover.
}
}
};
void Promise.allSettled(Array.from({ length: Math.min(RECONNECT_READ_CONCURRENCY, jobs.length) }, worker));
});
return () => {
controller?.abort();
unsubscribe();
};
}, [client, getToken]);
}
+95 -86
View File
@@ -11,6 +11,7 @@ import {
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { fetchLatestWebuiThread } from "@/lib/latest-thread-request";
import { readReloadSessions, writeReloadCache } from "@/lib/reload-cache";
import type {
ChatSummary,
@@ -22,7 +23,6 @@ import type {
} from "@/lib/types";
const EMPTY_MESSAGES: UIMessage[] = [];
const INITIAL_HISTORY_PAGE_LIMIT = 40;
const OLDER_HISTORY_PAGE_LIMIT = 120;
const CHAT_CREATE_TIMEOUT_MS = 60_000;
@@ -123,11 +123,16 @@ function hasPendingToolCallsFromThread(
function completedTurnIdsFromThread(
body: Awaited<ReturnType<typeof fetchWebuiThread>>,
): string[] {
if (!Array.isArray(body?.completed_turn_ids)) return [];
if (Array.isArray(body?.completed_turn_ids)) {
return Array.from(new Set(body.completed_turn_ids.filter(
(turnId) => typeof turnId === "string" && turnId.length > 0,
)));
}
if (body?.has_pending_tool_calls !== false || body.active_turn_id) return [];
return Array.from(new Set(
body.completed_turn_ids.filter(
(turnId): turnId is string => typeof turnId === "string" && turnId.length > 0,
),
body.events.flatMap((event) => (
event.event === "turn_end" && event.turn_id ? [event.turn_id] : []
)),
));
}
@@ -140,6 +145,7 @@ interface SessionHistoryState {
error: string | null;
hasPendingToolCalls: boolean;
completedTurnIds: string[];
completionIdsProvided: boolean;
forkBoundaryMessageCount: number | null;
beforeCursor: string | null;
hasMoreBefore: boolean;
@@ -160,6 +166,7 @@ function emptyHistoryState(key: string | null, loading = false): SessionHistoryS
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
completionIdsProvided: false,
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
@@ -187,6 +194,7 @@ function cachedHistoryState(
error: null,
hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages),
completedTurnIds: completedTurnIdsFromThread(body),
completionIdsProvided: Array.isArray(body.completed_turn_ids),
forkBoundaryMessageCount: projected.forkBoundaryMessageCount,
beforeCursor: body.page?.before_cursor ?? null,
hasMoreBefore: body.page?.has_more_before === true,
@@ -397,6 +405,8 @@ export function useSessionHistory(key: string | null): {
hasPendingToolCalls: boolean;
/** Turn identities backed by explicit persisted completion events. */
completedTurnIds: string[];
/** A supplied list is authoritative even when empty (unfinished transcripts). */
completionIdsProvided: boolean;
/** Relationship between the latest canonical page and its predecessor. */
continuity: SessionHistoryContinuity;
/** Stable across overlapping latest pages; changes on initial load or reset. */
@@ -404,7 +414,7 @@ export function useSessionHistory(key: string | null): {
/** Exact active turn when supplied by a current gateway. */
activeTurnId: string | null;
} {
const { getToken } = useClient();
const { client, getToken } = useClient();
const loadingOlderRef = useRef(false);
const olderRequestAbortRef = useRef<AbortController | null>(null);
const historyVersionRef = useRef(0);
@@ -452,77 +462,84 @@ export function useSessionHistory(key: string | null): {
: cachedBody
? cachedHistoryState(key, cachedBody, cachedVersion)
: emptyHistoryState(key, true));
const adoptBody = (body: WebuiThreadPersistedPayload | null) => {
historyVersionRef.current += 1;
const responseVersion = historyVersionRef.current;
const completedTurnIds = completedTurnIdsFromThread(body);
const projected = projectPersistedThread(body);
const ui = projected.messages;
const hasPending = hasPendingToolCallsFromThread(body, ui);
const forkBoundary = projected.forkBoundaryMessageCount;
setState((prev) => {
const merged = prev.key === key
? mergeLatestHistory(prev.messages, ui, prev.lineage === 0)
: mergeLatestHistory([], ui, true);
const retainedPrefix = merged.retainedPrefixLength > 0;
const retainedForkBoundary = (
retainedPrefix
&& prev.forkBoundaryMessageCount !== null
&& prev.forkBoundaryMessageCount <= merged.retainedPrefixLength
)
? prev.forkBoundaryMessageCount
: null;
return {
key,
messages: merged.messages,
loading: false,
loadingOlder: false,
olderError: merged.continuity === "overlap"
&& (retainedPrefix || prev.beforeCursor === body?.page?.before_cursor)
? prev.olderError
: null,
error: null,
hasPendingToolCalls: hasPending,
completedTurnIds,
completionIdsProvided: Array.isArray(body?.completed_turn_ids),
forkBoundaryMessageCount: forkBoundary === null
? retainedForkBoundary
: forkBoundary + merged.retainedPrefixLength,
beforeCursor: retainedPrefix
? prev.beforeCursor
: body?.page?.before_cursor ?? null,
hasMoreBefore: retainedPrefix
? prev.hasMoreBefore
: body?.page?.has_more_before === true,
userMessageOffset: retainedPrefix
? prev.userMessageOffset
: Math.max(0, body?.page?.user_message_offset ?? 0),
version: responseVersion,
continuity: merged.continuity,
lineage: merged.continuity === "overlap"
? prev.lineage
: responseVersion,
activeTurnId: typeof body?.active_turn_id === "string"
? body.active_turn_id
: null,
};
});
};
let publishingBody = false;
const unsubscribeCache = webuiThreadCache.subscribe(key, (body) => {
if (publishingBody) return;
// A reconnect read can finish before this thread's older HTTP request.
// Adopt that published page now and prevent the older response from
// overwriting its completed content or lifecycle facts.
cancelled = true;
controller.abort();
olderRequestAbortRef.current?.abort();
olderRequestAbortRef.current = null;
loadingOlderRef.current = false;
adoptBody(body);
});
(async () => {
try {
const body = await fetchWebuiThread(getToken(), key, {
limit: INITIAL_HISTORY_PAGE_LIMIT,
direction: "latest",
signal: controller.signal,
revision: cachedBody?.revision,
cached: cachedBody,
});
const body = await fetchLatestWebuiThread(client, getToken(), key, controller.signal);
if (cancelled) return;
if (body === cachedBody && cachedBody !== undefined) {
setState((prev) => prev.key === key
? { ...prev, loading: false, error: null }
: prev);
return;
}
publishingBody = true;
if (body) webuiThreadCache.set(key, body);
else webuiThreadCache.delete(key);
historyVersionRef.current += 1;
const responseVersion = historyVersionRef.current;
const completedTurnIds = completedTurnIdsFromThread(body);
const projected = projectPersistedThread(body);
const ui = projected.messages;
const hasPending = hasPendingToolCallsFromThread(body, ui);
const forkBoundary = projected.forkBoundaryMessageCount;
setState((prev) => {
const merged = prev.key === key
? mergeLatestHistory(prev.messages, ui, prev.lineage === 0)
: mergeLatestHistory([], ui, true);
const retainedPrefix = merged.retainedPrefixLength > 0;
const retainedForkBoundary = (
retainedPrefix
&& prev.forkBoundaryMessageCount !== null
&& prev.forkBoundaryMessageCount <= merged.retainedPrefixLength
)
? prev.forkBoundaryMessageCount
: null;
return {
key,
messages: merged.messages,
loading: false,
loadingOlder: false,
olderError: merged.continuity === "overlap"
&& (retainedPrefix || prev.beforeCursor === body?.page?.before_cursor)
? prev.olderError
: null,
error: null,
hasPendingToolCalls: hasPending,
completedTurnIds,
forkBoundaryMessageCount: forkBoundary === null
? retainedForkBoundary
: forkBoundary + merged.retainedPrefixLength,
beforeCursor: retainedPrefix
? prev.beforeCursor
: body?.page?.before_cursor ?? null,
hasMoreBefore: retainedPrefix
? prev.hasMoreBefore
: body?.page?.has_more_before === true,
userMessageOffset: retainedPrefix
? prev.userMessageOffset
: Math.max(0, body?.page?.user_message_offset ?? 0),
version: responseVersion,
continuity: merged.continuity,
lineage: merged.continuity === "overlap"
? prev.lineage
: responseVersion,
activeTurnId: typeof body?.active_turn_id === "string"
? body.active_turn_id
: null,
};
});
publishingBody = false;
adoptBody(body);
} catch (e) {
if (cancelled || isAbortError(e)) return;
if (e instanceof ApiError && e.status === 404) {
@@ -534,22 +551,10 @@ export function useSessionHistory(key: string | null): {
? "reset"
: "initial";
return {
key,
messages: [],
loading: false,
loadingOlder: false,
olderError: null,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
...emptyHistoryState(key),
version: responseVersion,
continuity,
lineage: responseVersion,
activeTurnId: null,
};
});
} else {
@@ -562,8 +567,9 @@ export function useSessionHistory(key: string | null): {
return () => {
cancelled = true;
controller.abort();
unsubscribeCache();
};
}, [getToken, key, refreshSeq]);
}, [client, getToken, key, refreshSeq]);
const loadOlder = useCallback(async () => {
if (!key || loadingOlderRef.current) return;
@@ -657,6 +663,7 @@ export function useSessionHistory(key: string | null): {
forkBoundaryMessageCount: null,
hasPendingToolCalls: false,
completedTurnIds: [],
completionIdsProvided: false,
continuity: "initial",
lineage: 0,
activeTurnId: null,
@@ -680,6 +687,7 @@ export function useSessionHistory(key: string | null): {
forkBoundaryMessageCount: null,
hasPendingToolCalls: false,
completedTurnIds: [],
completionIdsProvided: false,
continuity: "initial",
lineage: 0,
activeTurnId: null,
@@ -700,6 +708,7 @@ export function useSessionHistory(key: string | null): {
forkBoundaryMessageCount: state.forkBoundaryMessageCount,
hasPendingToolCalls: state.hasPendingToolCalls,
completedTurnIds: state.completedTurnIds,
completionIdsProvided: state.completionIdsProvided,
continuity: state.continuity,
lineage: state.lineage,
activeTurnId: state.activeTurnId,
+53
View File
@@ -0,0 +1,53 @@
import type { CanonicalRunSnapshot } from "./nanobot-client";
import { projectThreadEvents } from "./thread-event-projection";
import type { UIMessage, WebuiThreadPersistedPayload } from "./types";
export function completedAssistantTurnIds(messages: UIMessage[]): string[] {
return Array.from(new Set(messages.flatMap((message) => (
message.role === "assistant" && message.turnId ? [message.turnId] : []
))));
}
export function canonicalRunSnapshot(
messages: UIMessage[],
hasPendingToolCalls: boolean,
activeTurnId: string | null,
completionIdsProvided = false,
): CanonicalRunSnapshot {
return {
observedTurnIds: Array.from(new Set(messages.flatMap((message) => (
message.role === "user" && message.turnId ? [message.turnId] : []
)))),
hasPendingToolCalls,
activeTurnId,
completionIdsProvided,
};
}
export function persistedCanonicalRunState(body: WebuiThreadPersistedPayload): {
completedTurnIds: string[];
snapshot: CanonicalRunSnapshot;
} {
const messages = projectThreadEvents(body.events);
const suppliedCompletionIds = Array.isArray(body.completed_turn_ids) ? body.completed_turn_ids : null;
// The older protocol-1 host may omit active_turn_id. Its explicit pending
// flag still confirms idle; a missing flag cannot establish completion.
const snapshot = canonicalRunSnapshot(
messages,
body.has_pending_tool_calls !== false,
typeof body.active_turn_id === "string" ? body.active_turn_id : null,
suppliedCompletionIds !== null,
);
const completedTurnIds = suppliedCompletionIds?.filter(
(turnId) => typeof turnId === "string" && turnId.length > 0,
) ?? [];
// The gateway excludes incomplete transcript turns even when their display
// projection contains turn_end. Only older hosts need idle-state inference.
if (suppliedCompletionIds === null && !snapshot.hasPendingToolCalls && !snapshot.activeTurnId) {
completedTurnIds.push(...body.events.flatMap((event) => (
event.event === "turn_end" && event.turn_id ? [event.turn_id] : []
)));
completedTurnIds.push(...completedAssistantTurnIds(messages));
}
return { completedTurnIds: Array.from(new Set(completedTurnIds)), snapshot };
}
+111
View File
@@ -0,0 +1,111 @@
import { fetchWebuiThread } from "./api";
import type { NanobotClient } from "./nanobot-client";
import type { WebuiThreadPersistedPayload } from "./types";
import { webuiThreadCache } from "./webui-thread-cache";
interface LatestThreadRequest {
cached: WebuiThreadPersistedPayload | undefined;
controller: AbortController;
promise: Promise<WebuiThreadPersistedPayload | null>;
consumers: number;
settled: boolean;
shareable: boolean;
}
const requestsByClient = new WeakMap<NanobotClient, Map<string, LatestThreadRequest>>();
const INVALIDATED_THREAD_READ = Symbol("invalidated thread read");
function abortedRequest(): DOMException {
return new DOMException("The request was aborted", "AbortError");
}
/** Share only the canonical latest 40-event page within one authenticated host. */
export function fetchLatestWebuiThread(
client: NanobotClient,
token: string,
key: string,
signal?: AbortSignal,
): Promise<WebuiThreadPersistedPayload | null> {
if (signal?.aborted) return Promise.reject(abortedRequest());
const requests = requestsByClient.get(client) ?? new Map<string, LatestThreadRequest>();
requestsByClient.set(client, requests);
const requestKey = JSON.stringify([token, key]);
const cached = webuiThreadCache.get(key);
let request = requests.get(requestKey);
if (!request || !request.shareable || request.controller.signal.aborted || request.cached !== cached) {
const controller = new AbortController();
request = {
cached,
controller,
consumers: 0,
settled: false,
shareable: client.status === "open",
promise: fetchWebuiThread(token, key, {
limit: 40,
direction: "latest",
signal: controller.signal,
revision: cached?.revision,
cached,
}),
};
requests.set(requestKey, request);
const current = request;
const unsubscribeStatus = client.onStatus((status) => {
// Recovery must not join a read started before or during an outage.
if (status !== "open") current.shareable = false;
});
const unsubscribeSessionUpdate = client.onSessionUpdate((chatId, scope) => {
if (key === `websocket:${chatId}` && scope !== "metadata") {
current.controller.abort(INVALIDATED_THREAD_READ);
}
});
const unsubscribeRunCompletion = client.onRunCompletion((chatId) => {
if (key === `websocket:${chatId}`) current.controller.abort(INVALIDATED_THREAD_READ);
});
const finish = () => {
if (current.settled) return;
current.settled = true;
unsubscribeStatus();
unsubscribeSessionUpdate();
unsubscribeRunCompletion();
current.controller.signal.removeEventListener("abort", finish);
if (requests.get(requestKey) === current) requests.delete(requestKey);
};
current.controller.signal.addEventListener("abort", finish, { once: true });
void current.promise.then(finish, finish);
}
const current = request;
return new Promise((resolve, reject) => {
current.consumers += 1;
let active = true;
const release = () => {
if (!active) return;
active = false;
signal?.removeEventListener("abort", abort);
current.controller.signal.removeEventListener("abort", abort);
current.consumers -= 1;
if (current.consumers === 0 && !current.settled) current.controller.abort();
};
const abort = () => {
release();
if (current.controller.signal.reason === INVALIDATED_THREAD_READ) {
// Replace the stale page after the current notification finishes so
// all surviving consumers can join one read of its updated thread.
resolve(Promise.resolve().then(() => fetchLatestWebuiThread(client, token, key, signal)));
return;
}
reject(abortedRequest());
};
signal?.addEventListener("abort", abort, { once: true });
current.controller.signal.addEventListener("abort", abort, { once: true });
void current.promise.then((body) => {
if (!active) return;
release();
resolve(body);
}, (error: unknown) => {
if (!active) return;
release();
reject(error);
});
});
}
+21 -10
View File
@@ -70,6 +70,7 @@ function summarizeInboundWsPayload(ev: InboundEvent): unknown {
type Unsubscribe = () => void;
type EventHandler = (ev: InboundEvent) => void;
type StatusHandler = (status: ConnectionStatus) => void;
type RunCompletionHandler = (chatId: string) => void;
type RuntimeModelHandler = (modelName: string | null, modelPreset?: string | null) => void;
type SessionUpdateScope = "metadata" | "thread" | string;
type SessionUpdateHandler = (
@@ -171,6 +172,8 @@ export interface CanonicalRunSnapshot {
hasPendingToolCalls: boolean;
/** Exact active turn when supplied by a current gateway. */
activeTurnId?: string | null;
/** Supplied completion identities are authoritative for lifecycle turns. */
completionIdsProvided?: boolean;
}
type PendingMessageState = "queued" | "sent" | "unknown" | "accepted";
@@ -198,6 +201,7 @@ export class NanobotClient {
private sessionUpdateHandlers = new Set<SessionUpdateHandler>();
private sidebarStateUpdateHandlers = new Set<SidebarStateUpdateHandler>();
private runStatusHandlers = new Set<RunStatusHandler>();
private runCompletionHandlers = new Set<RunCompletionHandler>();
private errorHandlers = new Set<ErrorHandler>();
// chat_id -> handlers listening on it
private chatHandlers = new Map<string, Set<EventHandler>>();
@@ -360,6 +364,20 @@ export class NanobotClient {
return (this.unsettledRunTurnIdsByChatId.get(chatId)?.size ?? 0) > 0;
}
/** Observe terminal wire facts without subscribing to or attaching a chat. */
onRunCompletion(handler: RunCompletionHandler): Unsubscribe {
this.runCompletionHandlers.add(handler);
return () => this.runCompletionHandlers.delete(handler);
}
/** Durable runs that need a canonical disposition after transport recovery. */
getUnsettledRunChatIds(): string[] {
return Array.from(new Set([
...this.unsettledRunTurnIdsByChatId.keys(),
...this.runStartedAtByChatId.keys(),
])).filter((chatId) => !this.temporaryChatIds.has(chatId));
}
private normalizeMaxFrameBytes(value: number | undefined): number | undefined {
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
return undefined;
@@ -375,10 +393,11 @@ export class NanobotClient {
snapshot?: CanonicalRunSnapshot,
): boolean {
if (completed.has(turnId)) return true;
const pending = this.pendingMessageSends.get(this.runSendKey(chatId, turnId));
if (snapshot?.completionIdsProvided && pending?.startsNewRun !== false) return false;
if (!snapshot || snapshot.activeTurnId === turnId) return false;
if (snapshot.hasPendingToolCalls) return false;
if (observed.has(turnId)) return true;
const pending = this.pendingMessageSends.get(this.runSendKey(chatId, turnId));
return pending?.state === "unknown" || pending?.state === "accepted";
}
@@ -770,6 +789,7 @@ export class NanobotClient {
if (closesCurrentRun && this.runStartedAtByChatId.delete(chatId)) {
this.emitRunStatus(chatId, null);
}
for (const handler of this.runCompletionHandlers) handler(chatId);
}
private recordGoalStatusForRunStrip(chatId: string, ev: InboundEvent): void {
@@ -1132,14 +1152,6 @@ export class NanobotClient {
for (const handler of this.statusHandlers) handler(status);
}
private clearRunStatusesForReconnect(): void {
if (this.runStartedAtByChatId.size === 0) return;
const chatIds = [...this.runStartedAtByChatId.keys()];
this.runStartedAtByChatId.clear();
this.runStartedAtByTurnKey.clear();
for (const chatId of chatIds) this.emitRunStatus(chatId, null);
}
private handleOpen(): void {
this.setStatus("open");
this.reconnectAttempts = 0;
@@ -1530,7 +1542,6 @@ export class NanobotClient {
}
private scheduleReconnect(): void {
this.clearRunStatusesForReconnect();
this.setStatus("reconnecting");
const attempt = this.reconnectAttempts++;
// Exponential backoff: 0.5s, 1s, 2s, 4s, capped.
+13
View File
@@ -5,6 +5,8 @@ import type { WebuiThreadPersistedPayload } from "./types";
/** Bounded canonical replay cache; the most recent snapshot also survives tab reloads. */
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
private readonly listeners = new Map<string, Set<(body: WebuiThreadPersistedPayload) => void>>();
constructor(
maxBytes = 16 * 1024 * 1024,
maxEntries = 12,
@@ -31,6 +33,17 @@ export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload
override set(key: string, body: WebuiThreadPersistedPayload): void {
super.set(key, body);
if (super.get(key)) writeReloadCache("thread", { key, body });
for (const listener of this.listeners.get(key) ?? []) listener(body);
}
subscribe(key: string, listener: (body: WebuiThreadPersistedPayload) => void): () => void {
const listeners = this.listeners.get(key) ?? new Set();
listeners.add(listener);
this.listeners.set(key, listeners);
return () => {
listeners.delete(listener);
if (listeners.size === 0) this.listeners.delete(key);
};
}
override delete(key: string): void {
+20 -6
View File
@@ -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);
});
});
+56 -3
View File
@@ -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",
+346 -12
View File
@@ -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";
+25
View File
@@ -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(
+480
View File
@@ -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();
});
});
+103 -10
View File
@@ -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,
+9 -2
View File
@@ -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);
});
});