fix(webui): preserve oversized turn history with record pagination (#6586)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-11 17:32:47 +08:00
1 parent 5c1083df7f
commit 3c61bcfdf0
34 files changed
+3466 -380

No files matched your search

@@ -136,6 +136,7 @@ export function ThreadMessages({
? activeTurnStartIndex(units, activeTurnId)
: units.length;
const unitKeys = useMemo(() => unitKeysForDisplay(units), [units]);
const scrollAnchors = useMemo(() => scrollAnchorsForUnits(units), [units]);
const messageBlocks = useMemo(
() => completedMessageBlocks(
units,
@@ -251,6 +252,7 @@ export function ThreadMessages({
<ThreadDisplayUnit
key={unitKeys[index]}
unitKey={unitKeys[index]}
scrollAnchor={scrollAnchors[index]}
unit={unit}
mobileActions={mobileActions}
marginTop={prelude ? "" : marginTop}
@@ -361,6 +363,7 @@ function pendingTurnProjection(
interface ThreadDisplayUnitProps {
mobileActions: boolean;
unitKey: string;
scrollAnchor: ScrollAnchorIdentity;
unit: DisplayUnit;
marginTop: string;
userPromptId?: string;
@@ -562,6 +565,7 @@ function MessageBlockMenu({
const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
mobileActions,
unitKey,
scrollAnchor,
unit,
marginTop,
userPromptId,
@@ -686,6 +690,8 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
onContextBlockActiveChange(contextBlockKey ?? null);
}}
data-thread-display-unit={unitKey}
data-thread-scroll-sources={scrollAnchor.sources}
data-thread-scroll-fallback={scrollAnchor.fallback}
data-user-prompt-id={userPromptId}
data-message-context-block={contextBlockKey}
data-context-block-active={contextBlockActive || undefined}
@@ -778,6 +784,8 @@ function threadDisplayUnitPropsEqual(
): boolean {
return (
displayUnitsEqual(previous.unit, next.unit)
&& previous.scrollAnchor.sources === next.scrollAnchor.sources
&& previous.scrollAnchor.fallback === next.scrollAnchor.fallback
&& previous.mobileActions === next.mobileActions
&& previous.marginTop === next.marginTop
&& previous.userPromptId === next.userPromptId
@@ -935,6 +943,46 @@ export function unitKeysForDisplay(units: DisplayUnit[]): string[] {
});
}
interface ScrollAnchorIdentity {
sources: string;
fallback?: string;
}
function scrollAnchorsForUnits(units: DisplayUnit[]): ScrollAnchorIdentity[] {
const sourceKeys = units.map((unit) => {
const messages = unit.type === "message" ? [unit.message] : unit.messages;
// Either edge of an activity cluster can survive when the other grows.
const edges = messages.length > 1 ? [messages[0], messages[messages.length - 1]] : messages;
const streams: string[] = [];
const sequences: string[] = [];
const ids: string[] = [];
for (const message of edges) {
const stream = unit.type === "message" ? message.streamId : message.reasoningStreamId;
if (message.turnId && stream) streams.push(JSON.stringify([unit.type, "stream", message.turnId, stream]));
const sequence = message.projectionStartSeq ?? message.turnSeq;
if (message.turnId && Number.isFinite(sequence)) {
sequences.push(JSON.stringify([unit.type, "sequence", message.turnId, sequence]));
}
ids.push(JSON.stringify([unit.type, "id", message.id]));
}
return [...new Set([...streams, ...sequences, ...ids])];
});
const sourceCounts = new Map<string, number>();
const bases = units.map(unitKeyBase);
const baseCounts = new Map<string, number>();
for (const sources of sourceKeys) for (const source of sources) {
sourceCounts.set(source, (sourceCounts.get(source) ?? 0) + 1);
}
for (const base of bases) baseCounts.set(base, (baseCounts.get(base) ?? 0) + 1);
return sourceKeys.map((sources, index) => ({
sources: JSON.stringify(sources.filter((source) => sourceCounts.get(source) === 1)),
// A sole turn/phase row can keep its live identity when replay replaces
// both its source id and sequence. Occurrence keys are unsafe otherwise.
...(bases[index].startsWith("turn-") && baseCounts.get(bases[index]) === 1
? { fallback: bases[index] } : {}),
}));
}
function unitKeyBase(unit: DisplayUnit, index: number): string {
if (unit.type === "activity") {
const anchor = unit.messages[0];
+1 -1
View File
@@ -663,7 +663,7 @@ export function ThreadShell({
dismissStreamError,
} = useNanobotStream(
chatId, undefined, false, handleTurnEnd, undefined, undefined,
{ key: historyKey, cache: messageCacheRef.current },
{ key: historyKey, cache: messageCacheRef.current, temporary },
);
const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]);
const initialHistoryLoading = loading;
+42 -7
View File
@@ -92,13 +92,25 @@ export const INITIAL_HISTORY_WINDOW = 120;
export const HISTORY_WINDOW_INCREMENT = 120;
interface HistoryScrollAnchor {
key: string;
sources: string[];
fallback?: string;
offsetTop: number;
scrollTop: number;
}
const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]";
function scrollSourceKind(source: string): string {
return (JSON.parse(source) as string[])[1];
}
function scrollSourcesDisagree(left: string[], right: string[], kind: string): boolean {
const leftKeys = left.filter((source) => scrollSourceKind(source) === kind);
const rightKeys = right.filter((source) => scrollSourceKind(source) === kind);
return leftKeys.length > 0 && rightKeys.length > 0
&& !leftKeys.some((source) => rightKeys.includes(source));
}
function promptTopInset(scroller: HTMLElement): number {
const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop);
return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX;
@@ -500,13 +512,19 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}
const viewport = scroller.getBoundingClientRect();
const element = visibleHistoryUnit(content, viewport);
const key = element?.dataset.threadDisplayUnit;
if (!element || !key) {
if (!element?.dataset.threadScrollSources) {
historyScrollAnchorRef.current = null;
return false;
}
const sources = JSON.parse(element.dataset.threadScrollSources) as string[];
const fallback = element.dataset.threadScrollFallback;
if (sources.length === 0 && !fallback) {
historyScrollAnchorRef.current = null;
return false;
}
historyScrollAnchorRef.current = {
key,
sources,
fallback,
scrollTop: scroller.scrollTop,
// Normalize out the reveal lease, even when reading above its inline slot.
offsetTop: element.getBoundingClientRect().top - viewport.top
@@ -524,9 +542,26 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
if (Math.abs(scroller.scrollTop - Math.min(anchor.scrollTop, maxScrollTop)) >= 0.5) {
return captureHistoryScrollAnchor();
}
const element = Array.from(
content.querySelectorAll<HTMLElement>("[data-thread-display-unit]"),
).find((candidate) => candidate.dataset.threadDisplayUnit === anchor.key);
const candidates = Array.from(content.querySelectorAll<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR));
const bySource = new Map<string, { element: HTMLElement; sources: string[] }>();
for (const candidate of candidates) {
const sources = JSON.parse(candidate.dataset.threadScrollSources ?? "[]") as string[];
for (const source of sources) bySource.set(source, { element: candidate, sources });
}
let element: HTMLElement | undefined;
for (const source of anchor.sources) {
const candidate = bySource.get(source);
if (!candidate) continue;
const kind = scrollSourceKind(source);
// An index-generated replay id can be reused by a different message.
if (kind !== "stream" && scrollSourcesDisagree(anchor.sources, candidate.sources, "stream")) continue;
if (kind === "id" && scrollSourcesDisagree(anchor.sources, candidate.sources, "sequence")) continue;
element = candidate.element;
break;
}
if (!element && anchor.fallback) {
element = candidates.find((candidate) => candidate.dataset.threadScrollFallback === anchor.fallback);
}
if (!element) {
historyScrollAnchorRef.current = null;
return false;