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;
|
||||
|
||||
Reference in new issue
Block a user