fix(webui): preserve oversized turn history with record pagination (#6586)
This commit is contained in:
1 parent
5c1083df7f
commit
3c61bcfdf0
34 files changed
+3466
-380
No files matched your search
@@ -107,8 +107,8 @@ function transitionTurnDelivery(
|
||||
return changed ? next : messages;
|
||||
}
|
||||
|
||||
function createTranscript(messages: UIMessage[], saved: ThreadTranscriptSnapshot | undefined, historyKey: string | null) {
|
||||
const owner = new ThreadTranscript(messages, saved);
|
||||
function createTranscript(messages: UIMessage[], saved: ThreadTranscriptSnapshot | undefined, historyKey: string | null, temporary: boolean) {
|
||||
const owner = new ThreadTranscript(messages, saved, { recordLiveContributions: !temporary });
|
||||
// The first paint must not enter the welcome layout while history is pending.
|
||||
owner.paging = { ...owner.paging, loading: !!historyKey && owner.paging.version === 0,
|
||||
hasMoreBefore: historyKey ? owner.paging.hasMoreBefore : false };
|
||||
@@ -122,7 +122,7 @@ export function useNanobotStream(
|
||||
onTurnEnd?: () => void,
|
||||
onStreamDetach?: (messages: UIMessage[]) => void,
|
||||
completedTurnIds: readonly string[] = EMPTY_COMPLETED_TURN_IDS,
|
||||
history?: { key: string | null; cache?: ThreadMessageCache },
|
||||
history?: { key: string | null; cache?: ThreadMessageCache; temporary?: boolean },
|
||||
historyActiveTurnId: string | null = null,
|
||||
): {
|
||||
messages: UIMessage[];
|
||||
@@ -158,9 +158,10 @@ export function useNanobotStream(
|
||||
} {
|
||||
const { client, getToken } = useClient();
|
||||
const historyKey = history?.key ?? null;
|
||||
const temporary = history?.temporary === true;
|
||||
const messageCache = history?.cache;
|
||||
const [initialTranscript] = useState(() => createTranscript(initialMessages,
|
||||
chatId ? messageCache?.get(chatId) : undefined, historyKey));
|
||||
chatId ? messageCache?.get(chatId) : undefined, historyKey, temporary));
|
||||
const transcriptRef = useRef(initialTranscript);
|
||||
const [historyState, setHistoryState] = useState(initialTranscript.paging);
|
||||
const publishHistory = useCallback(() => setHistoryState(transcriptRef.current.paging), []);
|
||||
@@ -310,6 +311,7 @@ export function useNanobotStream(
|
||||
for (let index = 0; index < events.length; index++) {
|
||||
const event = events[index];
|
||||
const chunks = [event.text];
|
||||
const parts = [event];
|
||||
const members = event.turn.turnSeq === undefined ? [] : [event.turn.turnSeq];
|
||||
let turn = event.turn;
|
||||
while (index + 1 < events.length) {
|
||||
@@ -323,6 +325,7 @@ export function useNanobotStream(
|
||||
|| JSON.stringify(nextEvent.responseSources) !== JSON.stringify(event.responseSources)
|
||||
|| JSON.stringify(nextEvent.responseInputIds) !== JSON.stringify(event.responseInputIds)))) break;
|
||||
chunks.push(nextEvent.text);
|
||||
parts.push(nextEvent);
|
||||
if (nextEvent.turn.turnSeq !== undefined) members.push(nextEvent.turn.turnSeq);
|
||||
turn = { ...turn, ...nextEvent.turn };
|
||||
index++;
|
||||
@@ -359,8 +362,12 @@ export function useNanobotStream(
|
||||
}
|
||||
projectedEvent.projection_receipts = [{ turn_id: turn.turnId, ranges }];
|
||||
}
|
||||
const contributions = parts.map((part) => ({
|
||||
...projectedEvent, text: part.text, turn_id: part.turn.turnId, turn_phase: part.turn.turnPhase,
|
||||
turn_seq: part.turn.turnSeq, stream_id: part.streamId, projection_receipts: undefined,
|
||||
}));
|
||||
transcriptRef.current.project(projectedEvent, {
|
||||
createId: () => crypto.randomUUID(), now: Date.now(), startSeq: event.turn.turnSeq,
|
||||
createId: () => crypto.randomUUID(), now: Date.now(), startSeq: event.turn.turnSeq, contributions,
|
||||
});
|
||||
}
|
||||
return transcriptRef.current.messages;
|
||||
@@ -475,7 +482,7 @@ export function useNanobotStream(
|
||||
// ``initialMessages`` update: a brand-new chat can receive an empty/404
|
||||
// history response after the optimistic first message has already rendered.
|
||||
useEffect(() => {
|
||||
transcriptRef.current = createTranscript(initialMessages, chatId ? messageCache?.get(chatId) : undefined, historyKey);
|
||||
transcriptRef.current = createTranscript(initialMessages, chatId ? messageCache?.get(chatId) : undefined, historyKey, temporary);
|
||||
setMessages(transcriptRef.current.messages);
|
||||
setMessageScope({ chatId, historyKey, client });
|
||||
setRunState(chatId ? client.getRunState(chatId) : null);
|
||||
@@ -484,7 +491,7 @@ export function useNanobotStream(
|
||||
setGoalState(chatId ? client.getGoalState(chatId) : undefined);
|
||||
setRecoveryState(null);
|
||||
clearPendingStreamWork();
|
||||
}, [chatId, client, historyKey, clearActivitySegment, clearPendingStreamWork, setMessages]);
|
||||
}, [chatId, client, historyKey, temporary, clearActivitySegment, clearPendingStreamWork, setMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!chatId || (!hasPendingToolCalls && !initialStreaming)) return;
|
||||
@@ -515,6 +522,20 @@ export function useNanobotStream(
|
||||
}, [publishHistory]);
|
||||
const latestReadOwnerRef = useRef<ThreadTranscript>();
|
||||
const detailRequestsRef = useRef(new Map<string, Promise<{ ref: string; events: ThreadProjectionEvent[] } | null>>());
|
||||
const reconcileCanonical = useCallback((generation: number, canonical: ReturnType<typeof persistedCanonicalRunState>, accepted: boolean) => {
|
||||
if (!chatId) return;
|
||||
const settle = !canonical.snapshot.hasPendingToolCalls
|
||||
&& client.canReconcileCanonicalCompletion(chatId, generation, canonical.completedTurnIds, canonical.snapshot);
|
||||
if (accepted && settle && client.reconcileCanonicalCompletion(chatId, generation,
|
||||
canonical.completedTurnIds, canonical.snapshot)) {
|
||||
setRetryStatus(null);
|
||||
} else client.fenceCanonicalCompletedTurns(chatId, canonical.completedTurnIds);
|
||||
}, [chatId, client]);
|
||||
const settleFragment = useCallback((owner: ThreadTranscript) => {
|
||||
if (!chatId || !owner.fragmentCompletedTurnIds.length) return;
|
||||
client.settleFragmentRunLifecycle(chatId, owner.fragmentCompletedTurnIds);
|
||||
if (!client.getRunState(chatId)?.active) setRetryStatus(null);
|
||||
}, [chatId, client]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!historyKey) return;
|
||||
@@ -532,8 +553,6 @@ export function useNanobotStream(
|
||||
flushPendingStreamEvents();
|
||||
const decision = ownRead ? read : owner.begin(seed ? "initial" : "latest");
|
||||
const canonical = body ? persistedCanonicalRunState(body) : null;
|
||||
const settle = chatId && canonical && !canonical.snapshot.hasPendingToolCalls
|
||||
&& client.canReconcileCanonicalCompletion(chatId, generation, canonical.completedTurnIds, canonical.snapshot);
|
||||
const accepted = owner.accept(body, decision);
|
||||
// Commit the received owner before cache listeners/ledger callbacks can reenter.
|
||||
setMessages(owner.messages);
|
||||
@@ -544,11 +563,12 @@ export function useNanobotStream(
|
||||
else webuiThreadCache.delete(historyKey);
|
||||
publishing = false;
|
||||
}
|
||||
if (ownRead && chatId && canonical) {
|
||||
if (accepted && settle && client.reconcileCanonicalCompletion(chatId, generation,
|
||||
canonical.completedTurnIds, canonical.snapshot)) {
|
||||
setRetryStatus(null);
|
||||
} else client.fenceCanonicalCompletedTurns(chatId, canonical.completedTurnIds);
|
||||
if (chatId && canonical && (ownRead || !seed)) {
|
||||
if (body?.page?.record_range) {
|
||||
if (accepted) settleFragment(owner);
|
||||
} else if (ownRead && !owner.hasPendingFragmentGap) {
|
||||
reconcileCanonical(generation, canonical, accepted);
|
||||
}
|
||||
}
|
||||
};
|
||||
const cached = webuiThreadCache.get(historyKey);
|
||||
@@ -568,7 +588,7 @@ export function useNanobotStream(
|
||||
else { owner.finishRead(read, (error as Error).message); publishHistory(); }
|
||||
});
|
||||
return () => { disposed = true; controller.abort(); cancelOlderRead(); unsubscribe(); };
|
||||
}, [cancelOlderRead, chatId, client, flushPendingStreamEvents, getToken, historyKey, messageCache, publishHistory, refreshSeq, setMessages]);
|
||||
}, [cancelOlderRead, chatId, client, flushPendingStreamEvents, getToken, historyKey, messageCache, publishHistory, reconcileCanonical, refreshSeq, setMessages, settleFragment]);
|
||||
|
||||
const loadOlder = useCallback(async () => {
|
||||
const owner = transcriptRef.current;
|
||||
@@ -583,8 +603,12 @@ export function useNanobotStream(
|
||||
const body = await fetchWebuiThread(getToken(), historyKey, { before, limit: 120, signal: controller.signal });
|
||||
if (olderReadRef.current !== operation || transcriptRef.current !== owner) return;
|
||||
flushPendingStreamEvents();
|
||||
owner.accept(body, read);
|
||||
const accepted = owner.accept(body, read);
|
||||
setMessages(owner.messages);
|
||||
if (accepted) {
|
||||
if (chatId) messageCache?.set(chatId, owner.save());
|
||||
settleFragment(owner);
|
||||
}
|
||||
} catch (error) {
|
||||
if (olderReadRef.current === operation && transcriptRef.current === owner) {
|
||||
owner.finishRead(read, (error as Error).message);
|
||||
@@ -593,7 +617,14 @@ export function useNanobotStream(
|
||||
} finally {
|
||||
if (olderReadRef.current === operation) olderReadRef.current = null;
|
||||
}
|
||||
}, [flushPendingStreamEvents, getToken, historyKey, publishHistory, setMessages]);
|
||||
}, [chatId, client, flushPendingStreamEvents, getToken, historyKey, messageCache, publishHistory, setMessages, settleFragment]);
|
||||
|
||||
useEffect(() => {
|
||||
const bridging = transcriptRef.current.hasPendingFragmentGap;
|
||||
if (historyKey && historyState.version > 0 && historyState.hasMoreBefore
|
||||
&& !historyState.loading && !historyState.loadingOlder && !historyState.olderError
|
||||
&& (bridging || (messages.length === 0 && !historyState.error))) void loadOlder();
|
||||
}, [historyKey, historyState, loadOlder, messages.length]);
|
||||
|
||||
const loadTraceDetails = useCallback(async (refs: string[]) => {
|
||||
const owner = transcriptRef.current;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useClient } from "@/providers/ClientProvider";
|
||||
import { fetchPromptIndex, fetchWebuiThread } from "@/lib/api";
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
|
||||
import { joinThreadFragments } from "@/lib/thread-page-fragments";
|
||||
import { isModelCommandText } from "@/lib/format";
|
||||
import { isSystemCommandTurnId } from "@/lib/nanobot-client";
|
||||
import type { PromptIndex, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
|
||||
@@ -45,6 +46,8 @@ export function usePromptHistory(key: string | null, version: number, messages:
|
||||
const [index, setIndex] = useState<{ key: string; prompts: PromptAnchor[] } | null>(null);
|
||||
const indexSnapshot = useRef<PromptIndex>();
|
||||
const [pages, setPages] = useState<HistoryPage[]>([]);
|
||||
const pagesRef = useRef(pages);
|
||||
pagesRef.current = pages;
|
||||
const [target, setTarget] = useState<PromptHistoryNavigation["target"]>(null);
|
||||
const [operation, setOperation] = useState<PromptHistoryNavigation["operation"]>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -54,6 +57,7 @@ export function usePromptHistory(key: string | null, version: number, messages:
|
||||
const request = useRef<AbortController | null>(null);
|
||||
const sequence = useRef(0);
|
||||
const retry = useRef<() => void>(() => setRefresh((value) => value + 1));
|
||||
const emptyScan = useRef<{ direction: "before" | "after"; reversed: boolean }>({ direction: "after", reversed: false });
|
||||
const scope = useRef({ key, client });
|
||||
const currentScope = scope.current.key === key && scope.current.client === client;
|
||||
|
||||
@@ -140,9 +144,10 @@ export function usePromptHistory(key: string | null, version: number, messages:
|
||||
setPages((current) => current.map((page) => ({ ...page, messages: update(page.messages) })));
|
||||
}, []);
|
||||
|
||||
const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string) => {
|
||||
const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string, automatic = false) => {
|
||||
// Boundary inputs can arrive before loading renders; only a new jump supersedes a read.
|
||||
if (!key || (!id && request.current)) return;
|
||||
if (!automatic) emptyScan.current = { direction, reversed: false };
|
||||
request.current?.abort();
|
||||
const controller = new AbortController();
|
||||
request.current = controller;
|
||||
@@ -156,6 +161,11 @@ export function usePromptHistory(key: string | null, version: number, messages:
|
||||
});
|
||||
if (controller.signal.aborted) return;
|
||||
if (!body) throw new Error("History is no longer available");
|
||||
const generation = body.page?.history_generation;
|
||||
const previousGeneration = pagesRef.current[0]?.body.page?.history_generation;
|
||||
if (!id && generation && previousGeneration && generation !== previousGeneration) {
|
||||
throw new Error("History changed; select the message again");
|
||||
}
|
||||
const page = { body, messages: projectWebuiThreadMessages(projectThreadEvents(body.events)) };
|
||||
if (id && !page.messages.some((message) => message.id === id)) {
|
||||
setRefresh((value) => value + 1);
|
||||
@@ -179,19 +189,43 @@ export function usePromptHistory(key: string | null, version: number, messages:
|
||||
const last = pages[pages.length - 1]?.body.page;
|
||||
const window = useMemo(() => {
|
||||
if (!currentScope || !pages.length) return null;
|
||||
let count = 0;
|
||||
const messages: UIMessage[] = [];
|
||||
let boundary: number | null = null;
|
||||
for (const page of pages) {
|
||||
const eventIndex = page.body.fork_boundary_event_index;
|
||||
if (eventIndex !== undefined) boundary = count + projectWebuiThreadMessages(projectThreadEvents(page.body.events.slice(0, eventIndex))).length;
|
||||
count += page.messages.length;
|
||||
for (let index = 0; index < pages.length; index++) {
|
||||
const page = pages[index];
|
||||
let body = page.body;
|
||||
let rows = page.messages;
|
||||
const range = body.page?.record_range;
|
||||
if (range) {
|
||||
let joined = joinThreadFragments([], body);
|
||||
while (pages[index + 1]?.body.page?.record_range?.turn === range.turn) {
|
||||
joined = joinThreadFragments(joined.pages, pages[++index].body);
|
||||
}
|
||||
body = joined.body;
|
||||
rows = projectWebuiThreadMessages(projectThreadEvents(body.events));
|
||||
}
|
||||
const eventIndex = body.fork_boundary_event_index;
|
||||
if (eventIndex !== undefined) boundary = messages.length + projectWebuiThreadMessages(projectThreadEvents(body.events.slice(0, eventIndex))).length;
|
||||
messages.push(...rows);
|
||||
}
|
||||
return { messages: pages.flatMap((page) => page.messages),
|
||||
return { messages,
|
||||
userMessageOffset: first?.user_message_offset ?? 0,
|
||||
hasMoreBefore: first?.has_more_before === true, hasMoreAfter: last?.has_more_after === true,
|
||||
forkBoundaryMessageCount: boundary };
|
||||
}, [currentScope, pages, first, last]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!window || window.messages.length || loading || error) return;
|
||||
let direction = emptyScan.current.direction;
|
||||
let cursor = direction === "after" ? last?.after_cursor : first?.before_cursor;
|
||||
if (!cursor && !emptyScan.current.reversed) {
|
||||
direction = direction === "after" ? "before" : "after";
|
||||
emptyScan.current = { direction, reversed: true };
|
||||
cursor = direction === "after" ? last?.after_cursor : first?.before_cursor;
|
||||
}
|
||||
if (cursor) void read(cursor, direction, undefined, true);
|
||||
}, [error, first?.before_cursor, last?.after_cursor, loading, read, window]);
|
||||
|
||||
return { prompts, window, target: currentScope ? target : null, loading: currentScope && loading,
|
||||
operation: currentScope && (loading || error) ? operation : null,
|
||||
error: currentScope ? error ?? indexError : null, cancel, latest, updateMessages,
|
||||
|
||||
@@ -29,6 +29,18 @@ export function useReconnectRuns(client: NanobotClient, getToken: () => string):
|
||||
const body = await fetchLatestWebuiThread(client, getToken(), key, signal);
|
||||
if (!body || signal.aborted) return;
|
||||
const { completedTurnIds, snapshot } = persistedCanonicalRunState(body);
|
||||
if (body.page?.record_range) {
|
||||
if (!Array.isArray(body.completed_turn_ids)) return;
|
||||
const mounted = client.hasTranscript(chatId);
|
||||
if (client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)) {
|
||||
webuiThreadCache.set(key, body);
|
||||
}
|
||||
// A mounted owner must accept (or stage) the fragment before settling.
|
||||
// Explicit completion is otherwise independent of a newer run, but the
|
||||
// fragment is not proof that its WS content is covered.
|
||||
if (!mounted) client.settleFragmentRunLifecycle(chatId, completedTurnIds);
|
||||
return;
|
||||
}
|
||||
const explicitlyCompleted = turnId !== null && completedTurnIds.includes(turnId);
|
||||
if (!explicitlyCompleted && (snapshot.hasPendingToolCalls || snapshot.activeTurnId)) return;
|
||||
if (turnId && !explicitlyCompleted && !snapshot.observedTurnIds.includes(turnId)) return;
|
||||
|
||||
Reference in new issue
Block a user