fix(webui): reconcile turns after reconnect (#6211)
* fix(webui): reconcile turns after reconnect * perf(webui): bound reconnect recovery and index turn reconciliation * refactor(webui): simplify reconnect reconciliation * fix(webui): preserve turn authority during recovery * fix(webui): validate canonical completion identities
This commit is contained in:
1 parent
aeca1c0f1a
commit
fdeda8a468
18 files changed
+1741
-225
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user