fix(webui): stabilize earlier-history loading and reclaim space (#6349)

* fix(webui): retain smoothly revealed history loading headers

* refactor(webui): simplify history loading feedback

* fix(webui): keep retained history headers clear of preceding text

* fix(webui): reclaim completed history loading space

* refactor(webui): group history projection handoff with navigation

* test(webui): synchronize history motion observations

* fix(webui): collapse history completion geometry handoff
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-21 13:10:05 +08:00
1 parent 73a55e0b2f
commit 743c51e81f
24 files changed
+1658 -356

No files matched your search

@@ -8,14 +8,16 @@ interface ThreadHistoryStatusProps {
loading: boolean;
error: string | null;
exhausted?: boolean;
preview?: boolean;
onRetry: () => void;
className?: string;
}
export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatusProps>(function ThreadHistoryStatus({ loading, error, exhausted = false, onRetry, className }, ref) {
export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatusProps>(function ThreadHistoryStatus({ loading, error, exhausted = false, preview = false, onRetry, className }, ref) {
const { t } = useTranslation();
const state = !loading && error ? "error" : !loading && exhausted ? "exhausted" : "loading";
const label = t(state === "error" ? "thread.history.retryLabel" : `thread.history.${state}`);
const state = loading ? "loading" : error ? "error" : exhausted ? "exhausted" : "ready";
const hidden = state === "ready" && !preview;
const label = state === "ready" ? undefined : t(state === "error" ? "thread.history.retryLabel" : `thread.history.${state}`);
// Blocks adapted from loading.dev (MIT); see THIRD_PARTY_NOTICES.md.
const blocks = <span aria-hidden="true" className="thread-history-blocks">
{Array.from({ length: 9 }, (_, index) => <span key={index}
@@ -25,20 +27,21 @@ export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatu
return (
<div
ref={ref}
className={cn("thread-history-status thread-message-row pointer-events-none absolute inset-x-0 top-0 z-10 flex items-center justify-center", className)}
className={cn("thread-history-status thread-message-row pointer-events-none absolute inset-x-0 top-0 z-10 flex items-center justify-center", hidden && "invisible", className)}
aria-hidden={hidden || undefined}
data-state={state}
>
<div role="status" aria-live="polite" aria-atomic="true">
{state === "exhausted" ? (
<span className="text-xs">{label}</span>
) : (
) : state === "ready" ? blocks : (
<HoverHint content={state === "error" ? error : label} side="bottom">
{loading ? (
<div tabIndex={0} aria-label={label} className="thread-history-control pointer-events-auto rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring">
{blocks}<span className="sr-only">{label}</span>
</div>
) : (
<button type="button" aria-label={state === "error" ? label : t("thread.loadEarlier")} onClick={onRetry}
<button type="button" aria-label={label} onClick={onRetry}
className="thread-history-control pointer-events-auto rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring">
{blocks}<span className="sr-only">{label}</span>
</button>
+22 -8
View File
@@ -23,6 +23,8 @@ import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage }
interface ThreadMessagesProps {
messages: UIMessage[];
beforeMessages?: ReactNode;
beforeUnit?: { key: string; content: ReactNode };
topInset?: number;
afterUserMessage?: (message: UIMessage) => ReactNode;
afterMessages?: ReactNode;
temporary?: boolean;
@@ -81,6 +83,8 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] {
export function ThreadMessages({
messages,
beforeMessages,
beforeUnit,
topInset = 0,
afterUserMessage,
afterMessages,
temporary = false,
@@ -174,6 +178,11 @@ export function ThreadMessages({
setOpenContextBlockKey((current) => open ? key : current === key ? null : current);
}, []);
let nextUserIndex = hiddenUserMessageCount;
const preludeIndex = Math.max(0, beforeUnit ? unitKeys.indexOf(beforeUnit.key) : 0);
const inset = topInset > 0 ? <div aria-hidden style={{ height: topInset }} /> : null;
const preludeInset = preludeIndex === 0 ? inset : null;
const renderPrelude = (prefix: ReactNode, marginTop?: string) => prefix || preludeInset || beforeMessages
? <div key="thread-prelude" className={cn("flow-root", marginTop)}>{prefix}{preludeInset}{beforeMessages}</div> : null;
return (
<div ref={messageListRef} className="flex w-full flex-col">
@@ -181,8 +190,10 @@ export function ThreadMessages({
containerRef={messageListRef}
onQuoteSelection={onQuoteSelection}
/>
{beforeMessages}
{units.map((unit, index) => {
{[
preludeIndex > 0 ? <Fragment key="top-inset">{inset}</Fragment> : null,
units.length === 0 ? renderPrelude(null) : null,
...units.flatMap((unit, index) => {
const next = units[index + 1];
const hasBodyBelow =
unit.type === "activity"
@@ -233,14 +244,17 @@ export function ThreadMessages({
&& unit.message.deliveryStatus !== "failed"
) nextUserIndex += 1;
return (
<Fragment key={unitKeys[index]}>
const prefix = beforeUnit?.key === unitKeys[index] ? beforeUnit.content : null;
const prelude = index === preludeIndex ? renderPrelude(prefix, marginTop) : null;
return [
prelude,
<Fragment key={`unit:${unitKeys[index]}`}>
<ThreadDisplayUnit
key={unitKeys[index]}
unitKey={unitKeys[index]}
unit={unit}
mobileActions={mobileActions}
marginTop={marginTop}
marginTop={prelude ? "" : marginTop}
userPromptId={userPromptId}
hasBodyBelow={hasBodyBelow}
suppressActivity={suppressActivity}
@@ -279,9 +293,9 @@ export function ThreadMessages({
{unit.type === "message" && unit.message.role === "user" ? (
afterUserMessage?.(unit.message)
) : null}
</Fragment>
);
})}
</Fragment>,
];
})]}
{afterMessages}
{pendingActivity ? (
<div className={cn("thread-message-row", units.length > 0 && "mt-5")}>
+31 -1
View File
@@ -900,6 +900,7 @@ export function ThreadShell({
activeHistoryKeyRef.current = historyKey;
const currentUiMessagesRef = useRef<UIMessage[] | null>(null);
const uiRevisionRef = useRef(0);
const olderPageStartRef = useRef<{ historyKey: string; client: typeof client; visibleFirstId: string | null } | null>(null);
const showTemporaryChatControl =
!hideHeader && !session && !loading && !!onTemporaryChatEnabledChange;
@@ -945,6 +946,35 @@ export function ThreadShell({
const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages);
const updateNavigationMessages = promptNavigation.updateMessages;
const olderPageProjectionPending = Boolean(
olderPageStartRef.current?.historyKey === historyKey
&& olderPageStartRef.current.client === client
&& !loadingOlder
&& !olderError
&& normalizedHistory[0]?.id !== olderPageStartRef.current.visibleFirstId
&& displayMessages[0]?.id !== normalizedHistory[0]?.id,
);
useLayoutEffect(() => {
const pending = olderPageStartRef.current;
if (pending && (pending.historyKey !== historyKey || pending.client !== client)) {
olderPageStartRef.current = null;
}
if (!historyKey) {
olderPageStartRef.current = null;
} else if (loadingOlder) {
// The request may finish before this shell commits the rendered projection.
if (!olderPageStartRef.current) {
olderPageStartRef.current = {
historyKey,
client,
visibleFirstId: normalizedHistory[0]?.id ?? null,
};
}
} else if (olderError || !olderPageProjectionPending) {
olderPageStartRef.current = null;
}
}, [client, displayMessages, historyKey, loadingOlder, olderError, olderPageProjectionPending, normalizedHistory]);
const loadTraceDetails = useCallback(async (refs: string[]) => {
const requestKey = historyKey;
if (!requestKey) return;
@@ -2101,7 +2131,7 @@ export function ThreadShell({
slashCommands={availableSlashCommands}
forkBoundaryMessageCount={forkBoundaryMessageCount}
hasMoreBefore={hasMoreBefore}
loadingOlder={loadingOlder}
loadingOlder={loadingOlder || olderPageProjectionPending}
olderError={olderError}
userMessageOffset={userMessageOffset}
onLoadOlder={loadOlder}
+133 -54
View File
@@ -18,7 +18,7 @@ import { DiagramScope } from "@/components/markdown-diagrams/context";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
import { ThreadCameraController } from "@/components/thread/thread-camera";
import { ThreadHistorySpring } from "@/components/thread/thread-history-spring";
import { HISTORY_HOLD_PX, ThreadHistorySpring, type HistoryRevealPhase } from "@/components/thread/thread-history-spring";
import {
ThreadMotionCoordinator,
type ThreadMotionGeometry,
@@ -93,7 +93,7 @@ interface HistoryScrollAnchor {
const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]";
function promptTopInset(scroller: HTMLElement): number {
const padding = Number.parseFloat(getComputedStyle(scroller).paddingTop);
const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop);
return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX;
}
@@ -236,8 +236,16 @@ function readSoftKeyboardInsetBottom(container: HTMLElement | null): number {
return inset >= SOFT_KEYBOARD_MIN_INSET_PX ? Math.ceil(inset) : 0;
}
function setHistoryStatusTravel(element: HTMLDivElement | null, distance: number): void {
element?.style.setProperty("--history-pull", `${distance}px`);
function setHistoryPresentation(
scroller: HTMLDivElement | null,
status: HTMLDivElement | null,
slot: HTMLDivElement | null,
distance: number,
): void {
// A retained inline slot replaces the same amount of presentation travel.
const travel = distance - (slot ? HISTORY_HOLD_PX : 0);
if (scroller) scroller.style.transform = travel ? `translateY(${travel}px)` : "";
status?.style.setProperty("--history-pull", `${distance}px`);
}
export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProps>(function ThreadViewport({
@@ -279,8 +287,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const activeTurnId = historyWindow ? null : liveTurnId;
const forkBoundaryMessageCount = historyWindow ? historyWindow.forkBoundaryMessageCount : latestForkBoundary;
const hasMoreBefore = historyWindow?.hasMoreBefore ?? latestHasMoreBefore;
const loadingOlder = historyWindow ? navigation!.loading : latestLoadingOlder;
const olderError = historyWindow ? navigation!.error : latestOlderError;
const loadingOlder = historyWindow ? navigation!.operation === "older" && navigation!.loading : latestLoadingOlder;
const olderError = historyWindow ? navigation!.operation === "older" ? navigation!.error : null : latestOlderError;
const userMessageOffset = historyWindow?.userMessageOffset ?? latestUserOffset;
const onLoadOlder = historyWindow ? navigation!.older : loadLatestOlder;
const scrollRef = useRef<HTMLDivElement | null>(null);
@@ -299,10 +307,17 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const restoreScrollAfterPrependRef =
useRef<{ height: number; top: number } | null>(null);
const historyScrollAnchorRef = useRef<HistoryScrollAnchor | null>(null);
const previousLoadingOlderRef = useRef(loadingOlder);
const composerDockHeightRef = useRef(0);
const [atBottom, setAtBottom] = useState(true);
const [atHistoryTop, setAtHistoryTop] = useState(false);
const [historyFeedbackActive, setHistoryFeedbackActive] = useState(false);
const [historyPhase, setHistoryPhase] = useState<HistoryRevealPhase>("hidden");
const historyPhaseRef = useRef(historyPhase);
const [historySlotKey, setHistorySlotKey] = useState<string | null>(null);
const historySlotCompleted = previousLoadingOlderRef.current && !loadingOlder && !olderError && historySlotKey !== null;
const retainedHistorySlotKey = historySlotCompleted ? null : historySlotKey;
const [showHistoryExhausted, setShowHistoryExhausted] = useState(false);
const historySlotRef = useRef<HTMLDivElement | null>(null);
const historyInputRef = useRef<"touch" | "other">("other");
const historyTouchRef = useRef<{
lastY: number; startX: number; startY: number; pulling: boolean; horizontal: boolean;
@@ -312,15 +327,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const historySpringRef = useRef<ThreadHistorySpring | null>(null);
if (historySpringRef.current === null) {
historySpringRef.current = new ThreadHistorySpring({
onFeedbackChange: setHistoryFeedbackActive,
onPhaseChange: (phase) => {
const previous = historyPhaseRef.current;
historyPhaseRef.current = phase;
setHistoryPhase(phase);
if (phase === "hidden" && previous === "feedback") setShowHistoryExhausted(false);
},
onUpdate: (distance) => {
// Presentation travel never becomes a scrollTop destination or an anchor correction.
historyDistanceRef.current = distance;
if (messageRegionRef.current) {
messageRegionRef.current.style.transform = distance > 0 ? `translateY(${distance}px)` : "";
}
// Keep animated custom properties out of the inherited message tree.
setHistoryStatusTravel(historyStatusRef.current, distance);
setHistoryPresentation(messageRegionRef.current, historyStatusRef.current, historySlotRef.current, distance);
},
});
}
@@ -329,11 +344,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
// React can reuse this div for the empty state; release imperative styles with the ref.
messageRegionRef.current?.style.removeProperty("transform");
messageRegionRef.current = element;
if (element && historyDistanceRef.current > 0) element.style.transform = `translateY(${historyDistanceRef.current}px)`;
setHistoryPresentation(element, historyStatusRef.current, historySlotRef.current, historyDistanceRef.current);
}, []);
const setHistoryStatus = useCallback((element: HTMLDivElement | null) => {
historyStatusRef.current = element;
setHistoryStatusTravel(element, historyDistanceRef.current);
setHistoryPresentation(messageRegionRef.current, element, historySlotRef.current, historyDistanceRef.current);
}, []);
const setHistorySlot = useCallback((element: HTMLDivElement | null) => {
historySlotRef.current = element;
setHistoryPresentation(messageRegionRef.current, historyStatusRef.current, element, historyDistanceRef.current);
}, []);
const [composerDockHeight, setComposerDockHeight] = useState(0);
const [keyboardInsetBottom, setKeyboardInsetBottom] = useState(0);
@@ -391,10 +410,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
? messageRegionRef.current
: viewportFrameRef.current;
}, [hasMessages]);
useLayoutEffect(() => {
const scroller = scrollRef.current;
historySpringRef.current?.setLoading(Boolean(conversationReady && scroller && loadingOlder && !olderError && scroller.scrollTop <= 1));
}, [conversationKey, conversationReady, hasMessages, loadingOlder, olderError]);
const visibleMessages = useMemo(
() => windowMessages(messages, visibleMessageCount),
[messages, visibleMessageCount],
@@ -443,7 +458,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}
historyScrollAnchorRef.current = {
key,
offsetTop: element.getBoundingClientRect().top - viewport.top,
// Normalize out the reveal lease, even when reading above its inline slot.
offsetTop: element.getBoundingClientRect().top - viewport.top
- (historySlotRef.current ? HISTORY_HOLD_PX : 0),
};
return true;
}, []);
@@ -463,7 +480,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const nextOffset =
element.getBoundingClientRect().top
- scroller.getBoundingClientRect().top;
- scroller.getBoundingClientRect().top
- (historySlotRef.current ? HISTORY_HOLD_PX : 0);
const delta = nextOffset - anchor.offsetTop;
if (Math.abs(delta) < 0.5) return true;
const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
@@ -472,8 +490,29 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
return true;
}, []);
const resetHistoryHeader = useCallback(() => {
setHistorySlotKey(null);
historySpringRef.current?.reset();
}, []);
const holdHistoryHeader = useCallback(() => {
// A request at a new boundary supersedes the old slot. Mid-page retry
// keeps its original boundary, never a hit-tested answer or activity row.
if (!historySlotRef.current || (scrollRef.current && scrollRef.current.scrollTop <= 1)) {
const unit = messageContentRef.current?.querySelector<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR);
if (unit?.dataset.threadDisplayUnit) setHistorySlotKey(unit.dataset.threadDisplayUnit);
}
historySpringRef.current?.hold();
}, []);
useLayoutEffect(() => {
// Replaced history windows cannot retain a slot for an unmounted boundary.
if (retainedHistorySlotKey && !historySlotRef.current) resetHistoryHeader();
}, [retainedHistorySlotKey, resetHistoryHeader, visibleMessages]);
const scrollToBottomNow = useCallback((smooth = false) => {
historyScrollAnchorRef.current = null;
resetHistoryHeader();
const el = scrollRef.current;
const marker = bottomRef.current;
const behavior: ScrollBehavior = smooth ? "smooth" : "auto";
@@ -488,7 +527,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
marker.scrollIntoView({ block: "end", behavior });
}
setAtBottom(true);
}, []);
}, [resetHistoryHeader]);
const scrollToBottom = useCallback(
(smooth = false, options?: { force?: boolean }) => {
@@ -501,6 +540,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
);
const loadEarlierMessages = useCallback(() => {
if (loadingOlder || navigation?.loading) return;
const el = scrollRef.current;
if (el) {
if (captureHistoryScrollAnchor()) {
@@ -520,7 +560,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
);
return;
}
if (hasMoreBefore && onLoadOlder && !loadingOlder) {
if (hasMoreBefore && onLoadOlder) {
holdHistoryHeader();
setVisibleMessageCount((count) => count + HISTORY_WINDOW_INCREMENT);
void onLoadOlder();
}
@@ -528,8 +569,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
captureHistoryScrollAnchor,
hasMoreBefore,
hiddenMessageCount,
holdHistoryHeader,
loadingOlder,
messages.length,
navigation?.loading,
onLoadOlder,
]);
@@ -548,16 +591,11 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const prompt = scrollEl ? findPromptElement(scrollEl, promptId) : null;
if (!scrollEl || !prompt) return false;
historyScrollAnchorRef.current = null;
resetHistoryHeader();
setAtBottom(false);
const maxScrollTop = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight);
threadMotionRef.current?.navigateHistoryTo(
Math.min(
maxScrollTop,
Math.max(0, promptTop(scrollEl, prompt) - promptTopInset(scrollEl)),
),
);
threadMotionRef.current?.navigateHistoryToPrompt(promptId);
return true;
}, []);
}, [resetHistoryHeader]);
const jumpToUserPrompt = useCallback((promptId: string) => {
// A local destination also supersedes an in-flight remote jump.
@@ -654,7 +692,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
lastConversationKeyRef.current = conversationKey;
historyTouchRef.current = null;
historyInputRef.current = "other";
historySpringRef.current?.reset();
resetHistoryHeader();
conversationHandoffAnimationRef.current?.cancel();
conversationHandoffAnimationRef.current = null;
conversationHandoffPendingRef.current = true;
@@ -663,6 +701,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
restoreScrollAfterPrependRef.current = null;
threadMotionRef.current?.reset();
setAtBottom(true);
setShowHistoryExhausted(false);
setVisibleMessageCount(INITIAL_HISTORY_WINDOW);
const surface = hasMessages ? messageRegionRef.current : emptyStateRef.current;
@@ -677,7 +716,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
fill: "forwards",
},
);
}, [conversationKey, hasMessages]);
}, [conversationKey, hasMessages, resetHistoryHeader]);
useLayoutEffect(() => {
if (!conversationReady) {
@@ -722,6 +761,18 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
});
}, [activeTurnId, activeTurnStartedHere, conversationReady, messages]);
useLayoutEffect(() => {
const wasLoading = previousLoadingOlderRef.current;
previousLoadingOlderRef.current = loadingOlder;
if (!wasLoading || loadingOlder || olderError || !historySlotKey) return;
// The completed render already removed the slot. Rebase the saved anchor
// by its live presentation travel before the single final-geometry read.
const anchor = historyScrollAnchorRef.current;
if (anchor) anchor.offsetTop += historyDistanceRef.current;
setShowHistoryExhausted(historyExhausted);
resetHistoryHeader();
}, [loadingOlder, olderError, historySlotKey, historyExhausted, resetHistoryHeader]);
useLayoutEffect(() => {
const pending = restoreScrollAfterPrependRef.current;
const el = scrollRef.current;
@@ -735,7 +786,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
Math.max(0, pending.top + delta),
);
threadMotionRef.current?.jumpTo(nextTop);
}, [reconcileHistoryScrollAnchor, visibleMessages.length, messages]);
}, [reconcileHistoryScrollAnchor, visibleMessages.length, messages, loadingOlder]);
useLayoutEffect(() => {
const promptId = pendingPromptJumpRef.current;
@@ -768,6 +819,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
scrollToBottom,
]);
useLayoutEffect(() => {
// A request commits temporary space; successful completion reclaims it below.
if (conversationReady && loadingOlder && scrollRef.current?.scrollTop === 0 && !historySlotRef.current) {
holdHistoryHeader();
}
}, [conversationReady, loadingOlder, holdHistoryHeader]);
useLayoutEffect(() => {
if (!conversationReady || !conversationHandoffPendingRef.current) return;
conversationHandoffPendingRef.current = false;
@@ -843,7 +901,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const onScroll = (allowHistoryLoad = true) => {
setAtHistoryTop(el.scrollTop <= 1);
if (el.scrollTop > 1) historySpringRef.current?.leaveBoundary();
else historySpringRef.current?.setLoading(conversationReady && loadingOlder && !olderError);
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
const near = distance < NEAR_BOTTOM_PX;
const owner = threadMotionRef.current?.observeScroll(near) ?? "automatic";
@@ -865,15 +922,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const handleScroll = () => onScroll(true);
const atHistoryBoundary = () => el.scrollTop <= 1 && messages.length > 0 && conversationReady
&& !pendingConversationScrollRef.current;
const canLoadAtTop = () => atHistoryBoundary() && !loadingOlder
&& (hiddenMessageCount > 0 || (hasMoreBefore && !olderError));
const canLoadAtTop = () => atHistoryBoundary() && !loadingOlder && !navigation?.loading
&& (hiddenMessageCount > 0 || hasMoreBefore);
const handleDirectionalInput = (
direction: ThreadScrollDirection | null,
) => {
if (!direction) return;
if (direction === "forward" && historyWindow?.hasMoreAfter
&& el.scrollHeight - el.scrollTop - el.clientHeight < HISTORY_PREFETCH_MIN_PX
&& !navigation?.loading && !navigation?.error) {
&& !navigation?.loading) {
captureHistoryScrollAnchor();
navigation?.newer();
}
@@ -888,6 +945,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
direction === "forward",
);
};
const prepareHistoryPull = () => {
if (loadingOlder || navigation?.loading) return;
const first = messageContentRef.current?.querySelector<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR);
// A retained header belongs to the page boundary where it was opened,
// not to a newer boundary reached by scrolling through prepended history.
if (historySlotKey && first?.dataset.threadDisplayUnit !== historySlotKey) resetHistoryHeader();
};
const handleWheel = (event: WheelEvent) => {
if (
event.defaultPrevented
@@ -901,13 +965,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? 16
: event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? el.clientHeight : 1;
if (event.deltaY < 0) {
prepareHistoryPull();
yieldCameraToUser();
setAtHistoryTop(true);
const first = historySpringRef.current?.wheel(-event.deltaY * unit);
if (first && canLoadAtTop()) loadEarlierMessages();
if ((first || olderError) && canLoadAtTop()) loadEarlierMessages();
return;
}
if (historyDistanceRef.current > 0) historySpringRef.current?.wheel(-event.deltaY * unit);
}
handleDirectionalInput(directionFromDelta(event.deltaY));
};
@@ -952,6 +1016,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
if (gesture.horizontal) return;
if (gesture.pulling || (atHistoryBoundary() && delta < 0 && hiddenMessageCount === 0)) {
if (!gesture.pulling) {
prepareHistoryPull();
historySpringRef.current?.startTouch();
gesture.pulling = true;
}
@@ -991,7 +1056,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}
if (isKeyboardControl(event.target as Element | null)) return;
historyInputRef.current = "other";
historySpringRef.current?.leaveBoundary();
handleDirectionalInput(keyboardScrollDirection(event));
};
el.addEventListener("scroll", handleScroll, { passive: true });
@@ -1024,10 +1088,27 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
messages.length,
olderError,
yieldCameraToUser,
historySlotKey,
historyWindow,
navigation,
resetHistoryHeader,
]);
const navigationStatus = navigation?.operation !== "older" && Boolean(navigation?.loading || navigation?.error);
const showHistoryStatus = !historySlotCompleted && !navigationStatus && messages.length > 0 && conversationReady
&& (atHistoryTop && (!historyExhausted || showHistoryExhausted) || historyPhase !== "hidden" || loadingOlder);
const historyStatus = showHistoryStatus ? (
<ThreadHistoryStatus
ref={setHistoryStatus}
loading={loadingOlder}
error={olderError}
exhausted={historyExhausted}
preview={historyPhase === "feedback"}
onRetry={loadEarlierMessages}
className={!retainedHistorySlotKey && !(historyExhausted && showHistoryExhausted) ? cn("thread-history-reveal", historyPhase === "feedback" && "thread-history-feedback") : undefined}
/>
) : null;
return (
<div className="thread-viewport relative flex min-h-0 flex-1 overflow-hidden">
<div
@@ -1062,7 +1143,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
data-testid="thread-message-region"
className={cn(
"thread-message-viewport thread-viewport-scrollbar row-start-1 flex min-h-0 min-w-0 flex-col",
"scroll-auto justify-start overflow-x-hidden overscroll-y-none pb-0 pt-12",
"scroll-auto justify-start overflow-x-hidden overscroll-y-none pb-0 scroll-pt-12",
"[overflow-anchor:none] [scrollbar-width:none]",
"[&::-webkit-scrollbar]:hidden",
hasVerticalOverflow ? "overflow-y-auto" : "overflow-hidden",
@@ -1072,6 +1153,12 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
<DiagramScope identity={conversationKey}>
<SubagentThreadMessages
messages={visibleMessages}
topInset={PROMPT_TOP_INSET_PX}
beforeUnit={retainedHistorySlotKey ? { key: retainedHistorySlotKey, content: (
<div ref={setHistorySlot} className="thread-history-slot relative" style={{ height: HISTORY_HOLD_PX }}>
{historyStatus}
</div>
) } : undefined}
temporary={temporary}
isStreaming={isStreaming}
activeTurnId={activeTurnId}
@@ -1147,17 +1234,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
/>
) : null}
</div>
{navigation && (navigation.loading || navigation.error) ? (
<ThreadHistoryStatus ref={setHistoryStatus} loading={navigation.loading} error={navigation.error} onRetry={navigation.retry} />
) : messages.length > 0 && conversationReady && ((atHistoryTop && (!historyExhausted || historyFeedbackActive)) || loadingOlder || olderError) ? (
<ThreadHistoryStatus
ref={setHistoryStatus}
loading={loadingOlder}
exhausted={historyExhausted}
error={olderError}
onRetry={loadEarlierMessages}
/>
) : null}
{!retainedHistorySlotKey ? historyStatus : null}
{navigationStatus && navigation ? <ThreadHistoryStatus loading={navigation.loading}
error={navigation.error} onRetry={navigation.retry} /> : null}
{!hasMessages ? <div ref={bottomRef} aria-hidden className="h-px" /> : null}
</div>
@@ -1,168 +1,170 @@
import type { ThreadCameraScheduler } from "@/components/thread/thread-camera";
import { animate, motionValue, type AnimationPlaybackControls, type MotionValue } from "motion";
export const HISTORY_PULL_LIMIT_PX = 80;
export const HISTORY_PULL_TRIGGER_PX = 42;
const LOADING_POCKET_PX = 20;
export const HISTORY_HOLD_PX = 48;
export const HISTORY_PULL_TRIGGER_PX = 56;
const RESISTANCE_LENGTH_PX = 120;
const FREQUENCY = 22;
const DAMPING_RATIO = 0.78;
export type HistoryRevealPhase = "hidden" | "feedback" | "held";
interface HistorySpringOptions {
onUpdate: (distance: number) => void;
onFeedbackChange: (active: boolean) => void;
scheduler?: ThreadCameraScheduler;
onPhaseChange: (phase: HistoryRevealPhase) => void;
prefersReducedMotion?: () => boolean;
}
/** Presentation only: the thread camera remains the sole scroll-position owner. */
/** Presentation only: Motion owns spring integration; the thread camera remains the sole scroll-position owner. */
export class ThreadHistorySpring {
private readonly options: HistorySpringOptions;
private readonly scheduler: ThreadCameraScheduler;
private readonly reducedMotion: () => boolean;
private frame: number | null = null;
private timestamp: number | null = null;
private distance = 0;
private velocity = 0;
private loading = false;
private readonly value: MotionValue<number> = motionValue(0);
private animation: AnimationPlaybackControls | null = null;
private destination: number | null = null;
private animationGeneration = 0;
private phase: HistoryRevealPhase = "hidden";
private dragging = false;
private travel = 0;
private wheelLatched = false;
private feedbackActive = false;
constructor(options: HistorySpringOptions) {
this.options = options;
this.scheduler = options.scheduler ?? {
request: (callback) => window.requestAnimationFrame(callback),
cancel: (id) => window.cancelAnimationFrame(id),
now: () => performance.now(),
};
const motionPreference = typeof window !== "undefined" && typeof window.matchMedia === "function"
const preference = typeof window !== "undefined" && typeof window.matchMedia === "function"
? window.matchMedia("(prefers-reduced-motion: reduce)") : null;
this.reducedMotion = options.prefersReducedMotion ?? (() => motionPreference?.matches ?? false);
this.reducedMotion = options.prefersReducedMotion ?? (() => preference?.matches ?? false);
this.value.on("change", this.publish);
}
setLoading(loading: boolean): void {
if (this.loading === loading) return;
this.loading = loading;
if (!this.dragging) this.animate();
hold(): void {
this.wheelLatched = true;
this.setPhase("held");
this.animateTo(HISTORY_HOLD_PX);
}
wheel(travel: number): boolean {
if (this.dragging) return false;
if (this.dragging || travel === 0) return false;
const first = !this.wheelLatched && travel > 0;
this.wheelLatched = true;
if (travel > 0) this.setFeedbackActive(true);
// Wheel packets add pressure to one live spring, without a position jump.
const speed = FREQUENCY * (travel > 0
? HISTORY_PULL_LIMIT_PX - Math.max(0, this.distance)
: -Math.max(0, this.distance));
this.velocity += (speed - this.velocity) * (1 - Math.exp(-Math.abs(travel) / RESISTANCE_LENGTH_PX));
this.animate();
if (travel > 0) {
this.wheelLatched = true;
if (this.phase !== "held") this.setPhase("feedback");
}
const pressure = 1 - Math.exp(-Math.abs(travel) / RESISTANCE_LENGTH_PX);
const current = this.boundedValue();
const pressured = current + ((travel > 0 ? HISTORY_PULL_LIMIT_PX : 0) - current) * pressure;
// Each packet retargets the same MotionValue; interruption keeps the live spring velocity.
this.animateTo(Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, pressured)));
return first;
}
startTouch(): void {
this.stopFrame();
this.stopAnimation();
const visible = this.boundedValue();
this.value.set(visible);
this.dragging = true;
this.setFeedbackActive(true);
this.velocity = 0;
this.travel = -RESISTANCE_LENGTH_PX
* Math.log(Math.max(Number.EPSILON, 1 - Math.max(0, this.distance) / HISTORY_PULL_LIMIT_PX));
if (this.phase !== "held") this.setPhase("feedback");
this.travel = -RESISTANCE_LENGTH_PX * Math.log(Math.max(Number.EPSILON, 1 - visible / HISTORY_PULL_LIMIT_PX));
}
moveTouch(travel: number): void {
if (!this.dragging) return;
this.travel = Math.max(0, this.travel + travel);
this.distance = HISTORY_PULL_LIMIT_PX * (1 - Math.exp(-this.travel / RESISTANCE_LENGTH_PX));
this.publish();
this.value.set(HISTORY_PULL_LIMIT_PX * (1 - Math.exp(-this.travel / RESISTANCE_LENGTH_PX)));
}
endTouch(cancelled = false): boolean {
const triggered = this.dragging && !cancelled && this.distance >= HISTORY_PULL_TRIGGER_PX;
if (!this.dragging) return false;
const triggered = !cancelled && this.boundedValue() >= HISTORY_PULL_TRIGGER_PX;
this.dragging = false;
this.travel = 0;
this.publish();
this.animate();
this.animateTo(this.restPosition());
return triggered;
}
/** Native scrolling releases this input round, not the committed reveal. */
leaveBoundary(): void {
this.loading = false;
this.dragging = false;
this.wheelLatched = false;
this.setFeedbackActive(false);
this.animate();
if (this.reducedMotion() && this.phase !== "held") {
this.stopAnimation();
this.value.set(0);
this.setPhase("hidden");
return;
}
this.animateTo(this.restPosition());
}
reset(): void {
this.stopFrame();
this.distance = 0;
this.velocity = 0;
this.travel = 0;
this.loading = false;
this.stopAnimation();
this.dragging = false;
this.travel = 0;
this.wheelLatched = false;
this.setFeedbackActive(false);
this.publish();
this.setPhase("hidden");
this.value.set(0);
}
private setFeedbackActive(active: boolean): void {
if (this.feedbackActive === active) return;
this.feedbackActive = active;
this.options.onFeedbackChange(active);
private readonly publish = (distance: number): void => {
const bounded = Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, distance));
this.options.onUpdate(this.phase !== "held" && this.reducedMotion() ? 0 : bounded);
};
private boundedValue(): number {
return Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, this.value.get()));
}
private publish(): void {
// Reduced motion suppresses travel, not the input/settlement lifecycle.
this.options.onUpdate(this.reducedMotion() ? 0 : Math.max(0, this.distance));
private restPosition(): number {
return this.phase === "held" ? HISTORY_HOLD_PX : 0;
}
private stopFrame(): void {
if (this.frame !== null) this.scheduler.cancel(this.frame);
this.frame = null;
this.timestamp = null;
private setPhase(phase: HistoryRevealPhase): void {
if (this.phase === phase) return;
this.phase = phase;
this.options.onPhaseChange(phase);
}
private animate(): void {
if (this.frame !== null) return;
if (this.distance === (this.loading ? LOADING_POCKET_PX : 0) && this.velocity === 0) {
if (!this.loading) {
this.wheelLatched = false;
this.setFeedbackActive(false);
}
private stopAnimation(): void {
this.animationGeneration++;
this.animation?.stop();
this.animation = null;
this.destination = null;
}
private animateTo(target: number): void {
if (this.dragging) return;
const next = Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, target));
if (this.destination === next && this.animation) return;
if (this.reducedMotion() && this.phase === "held") {
this.stopAnimation();
this.value.set(HISTORY_HOLD_PX);
return;
}
this.timestamp = this.scheduler.now();
this.frame = this.scheduler.request(this.advance);
if (Math.abs(this.value.get() - next) < 0.01) {
this.stopAnimation();
this.value.set(next);
this.finish(next, this.animationGeneration);
return;
}
const generation = ++this.animationGeneration;
this.destination = next;
this.animation = animate(this.value, next, {
type: "spring",
stiffness: 484,
damping: 34,
mass: 1,
onComplete: () => this.finish(next, generation),
});
}
private readonly advance = (timestamp: number): void => {
this.frame = null;
const seconds = Math.max(0, timestamp - (this.timestamp ?? timestamp)) / 1000;
this.timestamp = timestamp;
const target = this.loading ? LOADING_POCKET_PX : 0;
// Exact damped-oscillator solution stays stable across slow or suspended frames.
const decay = FREQUENCY * DAMPING_RATIO;
const frequency = FREQUENCY * Math.sqrt(1 - DAMPING_RATIO ** 2);
const displacement = this.distance - target;
const sine = (this.velocity + decay * displacement) / frequency;
const phase = frequency * seconds;
const envelope = Math.exp(-decay * seconds);
this.distance = target + envelope * (displacement * Math.cos(phase) + sine * Math.sin(phase));
this.velocity = envelope * (
(sine * frequency - decay * displacement) * Math.cos(phase)
- (displacement * frequency + decay * sine) * Math.sin(phase)
);
const settled = Math.abs(this.distance - target) < 0.08 && Math.abs(this.velocity) < 0.8;
if (settled) {
this.distance = target;
this.velocity = 0;
this.timestamp = null;
if (!this.loading) {
this.wheelLatched = false;
this.setFeedbackActive(false);
}
private finish(destination: number, generation: number): void {
if (generation !== this.animationGeneration) return;
this.animation = null;
this.destination = null;
this.value.set(destination);
if (destination !== this.restPosition()) {
this.animateTo(this.restPosition());
return;
}
this.publish();
if (!settled) this.frame = this.scheduler.request(this.advance);
};
if (destination === 0 && this.phase !== "held") {
this.wheelLatched = false;
this.setPhase("hidden");
}
}
}
+31 -8
View File
@@ -71,6 +71,7 @@ const THREAD_MOTION_TRANSITIONS: Readonly<
"navigation-settled": "current-automatic-mode",
"user-scroll": "browsing-history",
"boundary-scroll": "browsing-history",
"composer-input": "idle",
"resume-follow": "current-automatic-mode",
},
"navigating-history": {
@@ -79,6 +80,7 @@ const THREAD_MOTION_TRANSITIONS: Readonly<
"navigation-settled": "browsing-history",
"user-scroll": "browsing-history",
"boundary-scroll": "browsing-history",
"composer-input": "browsing-history",
"resume-follow": "current-automatic-mode",
},
"browsing-history": {
@@ -164,6 +166,7 @@ export class ThreadMotionCoordinator {
hasOutput: false,
};
private mode: ThreadMotionMode = "idle";
private historyNavigationPromptId: string | null = null;
private promptPositioned = false;
private measurementFrameId: number | null = null;
private geometryDirty = false;
@@ -309,12 +312,21 @@ export class ThreadMotionCoordinator {
}
navigateHistoryTo(top: number): ThreadCameraFollowResult | null {
this.camera.cancel();
return this.beginHistoryNavigation(top, null);
}
navigateHistoryToPrompt(promptId: string): ThreadCameraFollowResult | null {
const geometry = this.measure(promptId);
if (!geometry || geometry.promptTop === null) return null;
return this.beginHistoryNavigation(geometry.promptTop, promptId);
}
private beginHistoryNavigation(top: number, promptId: string | null): ThreadCameraFollowResult | null {
if (this.mode !== "navigating-history") this.camera.cancel();
this.transition("navigate-history");
this.historyNavigationPromptId = promptId;
const result = this.camera.navigateTo(top);
if (!result || result === "settled") {
this.transition("navigation-settled");
}
if (!result || result === "settled") this.transition("navigation-settled");
return result;
}
@@ -378,6 +390,7 @@ export class ThreadMotionCoordinator {
this.composerInputDuringTurn = false;
this.resumeFollowArmed = false;
this.mode = "idle";
this.historyNavigationPromptId = null;
this.promptPositioned = false;
}
@@ -410,6 +423,7 @@ export class ThreadMotionCoordinator {
: transition;
if (nextMode === this.mode) return false;
this.mode = nextMode;
if (nextMode !== "navigating-history") this.historyNavigationPromptId = null;
return true;
}
@@ -434,14 +448,23 @@ export class ThreadMotionCoordinator {
if (!this.geometryDirty) return;
this.geometryDirty = false;
const navigationPromptId = this.mode === "navigating-history"
? this.historyNavigationPromptId
: null;
const needsPromptGeometry =
!this.isHistoryMode()
&& this.turn.id !== null
&& !this.promptPositioned;
const geometry = this.measure(needsPromptGeometry ? this.turn.promptId : null);
navigationPromptId !== null
|| (!this.isHistoryMode() && this.turn.id !== null && !this.promptPositioned);
const geometry = this.measure(navigationPromptId ?? (needsPromptGeometry ? this.turn.promptId : null));
if (!geometry) return;
this.onGeometry?.(geometry);
if (this.mode === "navigating-history" && navigationPromptId !== null) {
if (geometry.promptTop !== null) {
const result = this.camera.navigateTo(geometry.promptTop);
if (!result || result === "settled") this.transition("navigation-settled");
}
return;
}
if (this.mode === "navigating-latest") {
const result = this.camera.navigateTo(geometry.maxScrollTop);
if (!result || result === "settled") {
+12 -3
View File
@@ -607,10 +607,16 @@
}
.thread-history-status {
height: calc(48px + var(--history-pull, 0px));
height: 48px;
background: linear-gradient(hsl(var(--background)) 35%, hsl(var(--background) / 0));
color: hsl(var(--muted-foreground));
}
.thread-history-reveal {
transform: translateY(calc(var(--history-pull, 0px) - 100%));
}
.thread-history-reveal:focus-within {
transform: none;
}
.thread-history-control {
display: flex;
width: 120px;
@@ -620,7 +626,7 @@
}
/* loading.dev Blocks, Copyright (c) 2026 Jakub Krehel (MIT); THIRD_PARTY_NOTICES.md. */
.thread-history-blocks {
color: #d35e14;
color: hsl(var(--muted-foreground));
display: grid;
width: 20px;
height: 20px;
@@ -638,7 +644,7 @@
height: 24px;
color: hsl(var(--destructive));
}
.thread-history-status[data-state="error"] .thread-history-blocks > span {
.thread-history-status:not([data-state="loading"]):not([data-state="error"]) .thread-history-blocks > span {
animation: none;
transform: none;
}
@@ -647,6 +653,9 @@
35% { transform: scale(0); }
}
@media (prefers-reduced-motion: reduce) {
.thread-history-feedback {
transform: none;
}
.thread-history-blocks > span {
animation: none;
transform: scale(0.8);
+12 -4
View File
@@ -13,6 +13,8 @@ interface HistoryPage {
body: WebuiThreadPersistedPayload;
}
const HISTORY_PAGE_LIMIT = 3;
export interface PromptHistoryNavigation {
prompts: PromptAnchor[];
window: {
@@ -23,6 +25,8 @@ export interface PromptHistoryNavigation {
forkBoundaryMessageCount: number | null;
} | null;
target: { id: string; sequence: number } | null;
/** Pending or failed page read; index errors have no page operation. */
operation: "jump" | "older" | "newer" | null;
loading: boolean;
error: string | null;
jump: (id: string) => void;
@@ -42,6 +46,7 @@ export function usePromptHistory(key: string | null, version: number, messages:
const indexSnapshot = useRef<PromptIndex>();
const [pages, setPages] = useState<HistoryPage[]>([]);
const [target, setTarget] = useState<PromptHistoryNavigation["target"]>(null);
const [operation, setOperation] = useState<PromptHistoryNavigation["operation"]>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [indexError, setIndexError] = useState<string | null>(null);
@@ -130,10 +135,12 @@ export function usePromptHistory(key: string | null, version: number, messages:
}, []);
const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string) => {
if (!key) return;
// Boundary inputs can arrive before loading renders; only a new jump supersedes a read.
if (!key || (!id && request.current)) return;
request.current?.abort();
const controller = new AbortController();
request.current = controller;
setOperation(id ? "jump" : direction === "before" ? "older" : "newer");
setLoading(true);
setError(null);
retry.current = () => { void read(cursor, direction, id); };
@@ -150,7 +157,7 @@ export function usePromptHistory(key: string | null, version: number, messages:
}
// At most three bounded server pages, even after many navigations.
setPages((previous) => id ? [page] : direction === "before"
? [page, ...previous].slice(0, 3) : [...previous, page].slice(-3));
? [page, ...previous].slice(0, HISTORY_PAGE_LIMIT) : [...previous, page].slice(-HISTORY_PAGE_LIMIT));
if (id) setTarget({ id, sequence: ++sequence.current });
} catch (cause) {
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : String(cause));
@@ -180,13 +187,14 @@ export function usePromptHistory(key: string | null, version: number, messages:
}, [currentScope, pages, first, last]);
return { prompts, window, target: currentScope ? target : null, loading: currentScope && loading,
operation: currentScope && (loading || error) ? operation : null,
error: currentScope ? error ?? indexError : null, cancel, latest, updateMessages,
retry: () => error ? retry.current() : setRefresh((value) => value + 1),
jump: (id) => {
const prompt = prompts.find((item) => item.id === id);
if (enabled && prompt?.cursor) void read(prompt.cursor, "after", id);
},
older: () => { if (!loading && first?.before_cursor) void read(first.before_cursor, "before"); },
newer: () => { if (!loading && last?.after_cursor) void read(last.after_cursor, "after"); },
older: () => { if (first?.before_cursor) void read(first.before_cursor, "before"); },
newer: () => { if (last?.after_cursor) void read(last.after_cursor, "after"); },
};
}
+8 -1
View File
@@ -381,7 +381,7 @@ describe("session-owned task UI", () => {
expect(screen.getByText("Check more").compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("keeps legacy work with an unknown origin separate from the latest request after refresh", async () => {
it("keeps legacy work separate after refresh and preserves its disclosure through local history prepends", async () => {
vi.mocked(fetch).mockImplementation(async () => response([
task({ task_id: "legacy", revision: 0, label: "Nanjing weather", state: "done", completed_at: 102,
origin_turn_id: "websocket:a:1791046873588004336", result: "## Nanjing\n\n- **Rain**" }),
@@ -402,6 +402,13 @@ describe("session-owned task UI", () => {
expect(within(detail).getByRole("heading", { name: "Nanjing" })).toBeVisible();
expect(within(detail).getByRole("list")).toHaveTextContent("Rain");
await user.keyboard("{Escape}");
view.rerender(layout({ threadMessages: [
{ id: "cached-prompt", role: "user", content: "Earlier cached prompt", createdAt: 99_000 },
...messages,
] }));
const expanded = screen.getByRole("region", { name: "Other tasks" });
expect(within(expanded).getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "true");
expect(within(expanded).getByRole("button", { name: /Nanjing weather Completed/ })).toBeVisible();
view.unmount();
render(layout());
const restored = await screen.findByRole("region", { name: "Other tasks" });
+115 -61
View File
@@ -1,32 +1,38 @@
import { describe, expect, it, vi } from "vitest";
import { HISTORY_PULL_LIMIT_PX, ThreadHistorySpring } from "@/components/thread/thread-history-spring";
import { afterEach, describe, expect, it, vi } from "vitest";
import { waitFor } from "@testing-library/react";
import {
HISTORY_HOLD_PX,
HISTORY_PULL_LIMIT_PX,
HISTORY_PULL_TRIGGER_PX,
ThreadHistorySpring,
type HistoryRevealPhase,
} from "@/components/thread/thread-history-spring";
const springs = new Set<ThreadHistorySpring>();
function harness(reduced = false) {
let now = 0;
let nextId = 0;
let distance = 0;
const frames = new Map<number, FrameRequestCallback>();
const scheduler = {
now: () => now,
request: vi.fn((callback: FrameRequestCallback) => { frames.set(++nextId, callback); return nextId; }),
cancel: (id: number) => { frames.delete(id); },
const phase = vi.fn<(phase: HistoryRevealPhase) => void>();
const update = vi.fn((next: number) => { distance = next; });
const spring = new ThreadHistorySpring({ onPhaseChange: phase, onUpdate: update, prefersReducedMotion: () => reduced });
springs.add(spring);
const expectBounded = () => {
for (const [next] of update.mock.calls) {
expect(next).toBeGreaterThanOrEqual(0);
expect(next).toBeLessThanOrEqual(HISTORY_PULL_LIMIT_PX);
}
};
const feedback = vi.fn();
const spring = new ThreadHistorySpring({ scheduler, prefersReducedMotion: () => reduced,
onFeedbackChange: feedback, onUpdate: (next) => { distance = next; } });
const advance = (milliseconds = 16) => {
now += milliseconds;
const callbacks = [...frames.values()];
frames.clear();
callbacks.forEach((callback) => callback(now));
return distance;
};
const settle = () => { for (let i = 0; i < 100 && frames.size; i++) advance(); };
return { spring, scheduler, advance, settle, frames, feedback, distance: () => distance };
return { spring, phase, update, expectBounded, distance: () => distance };
}
afterEach(() => {
for (const spring of springs) spring.reset();
springs.clear();
vi.useRealTimers();
});
describe("history boundary spring", () => {
it("resists a short touch and returns continuously without triggering a request", () => {
it("resists short touch, reverses continuously, and settles transient feedback at zero", async () => {
const h = harness();
h.spring.startTouch();
h.spring.moveTouch(40);
@@ -35,77 +41,125 @@ describe("history boundary spring", () => {
expect(pulled).toBeLessThan(40);
expect(h.spring.endTouch()).toBe(false);
expect(h.distance()).toBe(pulled);
expect(h.advance()).toBeGreaterThan(0);
h.spring.startTouch();
expect(h.distance()).toBeCloseTo(pulled);
h.spring.moveTouch(-20);
expect(h.distance()).toBeLessThan(pulled);
h.settle();
h.spring.moveTouch(2_000);
expect(h.distance()).toBeLessThanOrEqual(HISTORY_PULL_LIMIT_PX);
expect(h.spring.endTouch(true)).toBe(false);
await waitFor(() => expect(h.phase).toHaveBeenLastCalledWith("hidden"));
expect(h.distance()).toBe(0);
expect(h.frames.size).toBe(0);
expect(h.phase.mock.calls).toEqual([["feedback"], ["hidden"]]);
h.expectBounded();
});
it("holds actual loading still, lets a new touch take over, and converges immediately after long frame gaps", () => {
it("uses the 56px touch threshold and keeps a request's 48px slot after completion", async () => {
const h = harness();
h.spring.startTouch();
h.spring.moveTouch(120);
expect(h.spring.endTouch()).toBe(true);
h.spring.setLoading(true);
h.settle();
expect(h.distance()).toBe(20);
expect(h.frames.size).toBe(0);
expect(h.distance()).toBeGreaterThan(HISTORY_HOLD_PX);
expect(h.distance()).toBeLessThan(HISTORY_PULL_TRIGGER_PX);
expect(h.spring.endTouch()).toBe(false);
await waitFor(() => expect(h.distance()).toBe(0));
h.spring.startTouch();
expect(h.distance()).toBe(20);
h.spring.moveTouch(20);
expect(h.distance()).toBeGreaterThan(20);
h.spring.endTouch();
h.spring.setLoading(false);
h.advance(30_000);
expect(h.distance()).toBe(0);
expect(h.frames.size).toBe(0);
h.spring.moveTouch(160);
expect(h.spring.endTouch()).toBe(true);
h.spring.hold();
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
expect(h.spring.wheel(20)).toBe(false);
h.expectBounded();
});
it("merges decelerating wheel input into one bounded spring and one boundary request", () => {
it("rearms after leaving the boundary and restores held geometry after touch takeover/cancel", async () => {
const h = harness();
expect(h.spring.wheel(100)).toBe(true);
h.spring.hold();
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
h.spring.leaveBoundary();
expect(h.distance()).toBe(HISTORY_HOLD_PX);
expect(h.spring.wheel(100)).toBe(true);
expect(h.spring.wheel(20)).toBe(false);
await waitFor(() => expect(h.distance()).toBeGreaterThan(HISTORY_HOLD_PX));
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
h.spring.startTouch();
expect(h.distance()).toBeCloseTo(HISTORY_HOLD_PX);
h.spring.moveTouch(120);
expect(h.distance()).toBeGreaterThan(HISTORY_PULL_TRIGGER_PX);
expect(h.spring.endTouch(true)).toBe(false);
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
expect(h.phase.mock.calls.filter(([phase]) => phase === "held")).toHaveLength(1);
h.expectBounded();
});
it("decays wheel pressure without duplicate requests and is bounded under sustained reversals", async () => {
const h = harness();
let requests = 0;
for (const delta of [100, 70, 48, 32, 20, 12, 6, 2]) {
if (h.spring.wheel(delta)) requests++;
expect(h.frames.size).toBe(1);
h.advance();
}
expect(requests).toBe(1);
expect(h.feedback.mock.calls).toEqual([[true]]);
expect(h.distance()).toBeLessThan(HISTORY_PULL_LIMIT_PX);
h.settle();
await waitFor(() => expect(h.phase).toHaveBeenLastCalledWith("hidden"));
expect(h.distance()).toBe(0);
expect(h.feedback.mock.calls).toEqual([[true], [false]]);
expect(h.phase.mock.calls).toEqual([["feedback"], ["hidden"]]);
expect(h.spring.wheel(100)).toBe(true);
h.spring.hold();
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
for (const direction of [1, -1, 1, -1]) {
for (let i = 0; i < 12; i++) {
for (let packet = 0; packet < 4; packet++) expect(h.spring.wheel(direction * 2_000)).toBe(false);
await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
expect(h.distance()).toBeGreaterThanOrEqual(0);
expect(h.distance()).toBeLessThanOrEqual(HISTORY_PULL_LIMIT_PX);
}
}
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
h.expectBounded();
});
it("cancels task-owned motion on conversation changes", () => {
it("cancels stale completion on reset and supports immediate reuse", async () => {
const h = harness();
h.spring.wheel(100);
h.spring.setLoading(true);
h.spring.hold();
await waitFor(() => expect(h.distance()).toBeGreaterThan(0));
h.spring.reset();
expect(h.frames.size).toBe(0);
expect(h.distance()).toBe(0);
await new Promise((resolve) => setTimeout(resolve, 100));
expect(h.distance()).toBe(0);
expect(h.phase).toHaveBeenLastCalledWith("hidden");
expect(h.spring.wheel(100)).toBe(true);
h.spring.hold();
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
});
it("keeps the touch trigger functional with reduced motion and no display travel", () => {
it("keeps reduced-motion transient input functional and settles its lifecycle without travel", async () => {
const h = harness(true);
h.spring.startTouch();
h.spring.moveTouch(120);
h.spring.moveTouch(160);
expect(h.distance()).toBe(0);
expect(h.spring.endTouch()).toBe(true);
h.spring.setLoading(true);
await waitFor(() => expect(h.phase).toHaveBeenLastCalledWith("hidden"));
expect(h.phase.mock.calls).toEqual([["feedback"], ["hidden"]]);
expect(h.spring.wheel(100)).toBe(true);
expect(h.spring.wheel(20)).toBe(false);
expect(h.distance()).toBe(0);
h.settle();
expect(h.frames.size).toBe(0);
h.spring.setLoading(false);
h.settle();
expect(h.feedback.mock.calls).toEqual([[true], [false]]);
h.spring.wheel(100);
expect(h.feedback).toHaveBeenLastCalledWith(true);
h.settle();
h.spring.leaveBoundary();
expect(h.phase).toHaveBeenLastCalledWith("hidden");
expect(h.update.mock.calls.every(([next]) => next === 0)).toBe(true);
});
it("reveals and restores the reduced-motion committed slot immediately", () => {
const h = harness(true);
expect(h.spring.wheel(100)).toBe(true);
h.spring.hold();
expect(h.distance()).toBe(HISTORY_HOLD_PX);
h.spring.startTouch();
h.spring.moveTouch(120);
expect(h.spring.endTouch()).toBe(true);
expect(h.distance()).toBe(HISTORY_HOLD_PX);
expect(h.spring.wheel(100)).toBe(false);
h.spring.reset();
expect(h.distance()).toBe(0);
expect(h.feedback).toHaveBeenLastCalledWith(false);
h.expectBounded();
});
});
+25 -8
View File
@@ -16,17 +16,34 @@ describe("ThreadHistoryStatus", () => {
expect(container.firstElementChild).toHaveAttribute("data-state", "exhausted");
});
it("uses one loading display before and during a request while preserving keyboard activation", () => {
it("hides completed feedback without offering another loading action", () => {
const onRetry = vi.fn();
const { container, rerender } = render(<ThreadHistoryStatus loading={false} error={null} onRetry={onRetry} />);
const { container, rerender } = render(<ThreadHistoryStatus loading error={null} onRetry={onRetry} />);
expect(container.firstElementChild).toHaveAttribute("data-state", "loading");
const load = screen.getByRole("button", { name: "Load earlier messages" });
expect(load.querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
fireEvent.click(load);
expect(onRetry).toHaveBeenCalledTimes(1);
rerender(<ThreadHistoryStatus loading={false} error={null} onRetry={onRetry} />);
expect(container.firstElementChild).toHaveAttribute("data-state", "ready");
expect(container.firstElementChild).toHaveAttribute("aria-hidden", "true");
expect(container.firstElementChild).toHaveClass("invisible");
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(screen.queryByRole("button")).not.toBeInTheDocument();
expect(onRetry).not.toHaveBeenCalled();
rerender(<ThreadHistoryStatus loading error={null} onRetry={onRetry} />);
expect(container.firstElementChild).toHaveAttribute("data-state", "loading");
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
expect(container.firstElementChild).not.toHaveClass("invisible");
expect(screen.getByRole("status")).toBeInTheDocument();
});
it("shows decorative Blocks while previewing a pull without offering a loading action", () => {
const onRetry = vi.fn();
const { container } = render(<ThreadHistoryStatus loading={false} error={null} preview onRetry={onRetry} />);
expect(container.firstElementChild).toHaveAttribute("data-state", "ready");
expect(container.firstElementChild).not.toHaveClass("invisible");
const blocks = screen.getByRole("status").querySelector(".thread-history-blocks")!;
expect(blocks.children).toHaveLength(9);
expect(blocks).toHaveAttribute("aria-hidden", "true");
fireEvent.click(blocks);
expect(onRetry).not.toHaveBeenCalled();
expect(screen.queryByRole("button")).not.toBeInTheDocument();
expect(screen.getByRole("status").textContent).toBe("");
});
it("offers error Blocks with the actual failure on keyboard focus and resumes loading on retry", () => {
+60 -2
View File
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { type ThreadCameraFollowResult } from "@/components/thread/thread-camera";
import {
ThreadMotionCoordinator,
type ThreadMotionGeometry,
@@ -9,6 +10,7 @@ import {
function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
let nextFrameId = 1;
let cameraFollowing = false;
let nextNavigationResult: ThreadCameraFollowResult = "started";
const frames = new Map<number, FrameRequestCallback>();
let geometry: ThreadMotionGeometry = {
scrollTop: 400,
@@ -39,8 +41,8 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
followTo: vi.fn(() => "settled" as const),
isFollowing: vi.fn(() => cameraFollowing),
navigateTo: vi.fn(() => {
cameraFollowing = true;
return "started" as const;
cameraFollowing = nextNavigationResult === "started";
return nextNavigationResult;
}),
};
const onGeometry = vi.fn();
@@ -69,6 +71,9 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
const setCameraFollowing = (following: boolean) => {
cameraFollowing = following;
};
const setNextNavigationResult = (result: ThreadCameraFollowResult) => {
nextNavigationResult = result;
};
return {
camera,
@@ -81,6 +86,7 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
advanceFrame,
setCameraFollowing,
setGeometry,
setNextNavigationResult,
};
}
@@ -708,4 +714,56 @@ describe("ThreadMotionCoordinator", () => {
expect(camera.jumpTo.mock.calls).toEqual([[430], [458], [490]]);
});
it("retargets a prompt navigation from authoritative geometry without restarting the camera", () => {
const { camera, coordinator, measure, setGeometry } = motionHarness();
coordinator.navigateHistoryToPrompt("prompt-46");
expect(measure).toHaveBeenCalledWith("prompt-46");
expect(camera.navigateTo).toHaveBeenLastCalledWith(404);
expect(coordinator.snapshot().mode).toBe("navigating-history");
camera.cancel.mockClear();
setGeometry({ promptTop: 520 });
coordinator.reconcileObservedGeometry();
expect(camera.navigateTo).toHaveBeenLastCalledWith(520);
expect(camera.cancel).not.toHaveBeenCalled();
expect(coordinator.snapshot().mode).toBe("navigating-history");
});
it("releases prompt retarget ownership on composer input and user takeover", () => {
const { camera, coordinator, setGeometry } = motionHarness();
coordinator.navigateHistoryToPrompt("prompt-46");
camera.cancel.mockClear();
coordinator.handleComposerInput();
expect(camera.cancel).toHaveBeenCalledTimes(1);
expect(coordinator.snapshot().mode).toBe("browsing-history");
const callsAfterComposer = camera.navigateTo.mock.calls.length;
setGeometry({ promptTop: 600 });
coordinator.reconcileObservedGeometry();
expect(camera.navigateTo).toHaveBeenCalledTimes(callsAfterComposer);
coordinator.navigateHistoryToPrompt("prompt-47");
camera.cancel.mockClear();
coordinator.handleUserScrollIntent(true);
expect(camera.cancel).toHaveBeenCalledTimes(1);
expect(coordinator.snapshot().mode).toBe("browsing-history");
const callsAfterTouch = camera.navigateTo.mock.calls.length;
setGeometry({ promptTop: 700 });
coordinator.reconcileObservedGeometry();
expect(camera.navigateTo).toHaveBeenCalledTimes(callsAfterTouch);
});
it("drops prompt identity when an aligned navigation settles immediately", () => {
const { camera, coordinator, measure, setGeometry, setNextNavigationResult } = motionHarness();
setNextNavigationResult("settled");
expect(coordinator.navigateHistoryToPrompt("prompt-46")).toBe("settled");
expect(measure).toHaveBeenCalledWith("prompt-46");
expect(coordinator.snapshot().mode).toBe("browsing-history");
const callsAfterSettle = camera.navigateTo.mock.calls.length;
setGeometry({ promptTop: 720 });
coordinator.reconcileObservedGeometry();
expect(camera.navigateTo).toHaveBeenCalledTimes(callsAfterSettle);
expect(coordinator.snapshot().mode).toBe("browsing-history");
});
});
+84 -1
View File
@@ -1,5 +1,5 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { StrictMode, type ReactNode } from "react";
import { Profiler, StrictMode, type ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { preloadMarkdownText } from "@/components/MarkdownText";
@@ -4002,6 +4002,89 @@ describe("ThreadShell", () => {
},
);
it.each([
{ name: "visible rows after a hidden command prefix", rows: [
{ role: "user" as const, content: "/model hidden", turnId: "webui-system:model" },
{ role: "assistant" as const, content: "hidden model response", turnId: "webui-system:model" },
{ role: "user" as const, content: "older question", turnId: "older-turn" },
{ role: "assistant" as const, content: "older answer", turnId: "older-turn" },
], expectVisible: true },
{ name: "a page containing only hidden command rows", rows: [
{ role: "user" as const, content: "/model hidden", turnId: "webui-system:model" },
{ role: "assistant" as const, content: "hidden model response", turnId: "webui-system:model" },
], expectVisible: false },
{ name: "an empty successful page", rows: [], expectVisible: false },
{ name: "a failed page", rows: [], expectVisible: false, error: true },
])("releases older-page loading after ThreadShell handles $name", async ({ rows, expectVisible, error = false }) => {
const client = makeClient();
const chatId = `older-projection-${expectVisible ? "visible" : "hidden"}`;
let resolveOlder!: (response: Response) => void;
let olderReturned = false;
const commits: Array<{ loading: boolean; olderVisible: boolean }> = [];
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (!url.includes(`websocket%3A${chatId}/webui-thread`)) {
return { ok: false, status: 404, json: async () => ({}) };
}
if (url.includes("before=")) {
return new Promise<Response>((resolve) => { resolveOlder = resolve; });
}
return httpJson({
...transcriptFromSimpleMessages([
{ role: "user", content: "current question", turnId: "current-turn" },
]),
has_pending_tool_calls: expectVisible,
active_turn_id: expectVisible ? "current-turn" : null,
completed_turn_ids: [],
page: { before_cursor: "older-page", has_more_before: true, user_message_offset: 1 },
});
}));
const capture = () => {
if (!olderReturned) return;
commits.push({
loading: document.querySelector('.thread-history-status[data-state="loading"]') !== null,
olderVisible: document.body.textContent?.includes("older answer") ?? false,
});
};
const { container } = render(wrap(client, <Profiler id="older-history" onRender={capture}>
<ThreadShell session={session(chatId)} title="Older projection" onToggleSidebar={() => {}} />
</Profiler>));
await screen.findByText("current question");
const scroller = container.querySelector(".thread-message-viewport") as HTMLElement;
Object.defineProperties(scroller, {
scrollHeight: { configurable: true, value: 2400 },
clientHeight: { configurable: true, value: 600 },
scrollTop: { configurable: true, writable: true, value: 0 },
});
fireEvent.keyDown(scroller, { key: "Home" });
await waitFor(() => expect(resolveOlder).toBeTypeOf("function"));
await screen.findByText("Loading earlier messages…");
if (expectVisible) {
act(() => client._emitChat(chatId, {
event: "delta", chat_id: chatId, turn_id: "current-turn", text: "live during pagination",
}));
await screen.findByText("live during pagination");
}
const olderPayload = rows.length > 0
? transcriptFromSimpleMessages(rows)
: { schemaVersion: 3, projection: "events", events: [], page: { before_cursor: null, has_more_before: false } };
olderReturned = true;
await act(async () => {
resolveOlder(error
? new Response("History unavailable", { status: 503 })
: httpJson({ ...olderPayload, page: { before_cursor: null, has_more_before: false } }));
});
if (expectVisible) await screen.findByText("older answer");
await waitFor(() => expect(container.querySelector('.thread-history-status[data-state="loading"]')).toBeNull());
expect(commits.some((commit) => commit.loading && !commit.olderVisible)).toBe(expectVisible);
if (error) {
expect(container.querySelector('.thread-history-status[data-state="error"]')).toBeInTheDocument();
expect(container.querySelector(".thread-history-slot")).toBeInTheDocument();
} else {
expect(container.querySelector(".thread-history-slot")).not.toBeInTheDocument();
}
});
it("prepends earlier history while preserving the active answer cursor", async () => {
const client = makeClient();
const chatId = "running-paged-history";
+23 -12
View File
@@ -49,7 +49,7 @@ function dispatchHistoryInput(scroller: HTMLElement, input: "wheel" | "touch" |
if (input === "keyboard") fireEvent.keyDown(scroller, { key: "PageUp" });
if (input === "touch") {
fireEvent.touchStart(scroller, { touches: [{ clientX: 100, clientY: 200 }] });
fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 300 }] });
fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 380 }] });
fireEvent.touchEnd(scroller);
}
}
@@ -1517,7 +1517,6 @@ describe("ThreadViewport", () => {
expect(screen.queryByText(`message ${firstVisible - 1}`)).not.toBeInTheDocument();
expect(screen.getByText(`message ${firstVisible}`)).toBeInTheDocument();
expect(screen.getByText("message 299")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Load earlier messages" })).toBeInTheDocument();
});
it("automatically expands earlier local history near the top", () => {
@@ -1677,7 +1676,6 @@ describe("ThreadViewport", () => {
describe.each(["wheel", "touch"] as const)("%s history boundary", (input) => {
it.each([
{ loadingOlder: true },
{ olderError: "offline" },
{ conversationReady: false },
{ hasMoreBefore: false },
])("keeps history blocked: %o", (blocked) => {
@@ -1714,7 +1712,7 @@ describe("ThreadViewport", () => {
expect(onLoadOlder).toHaveBeenCalledTimes(1);
});
it("pauses automatic history requests after a failure and exposes retry", () => {
it.each(["wheel", "touch", "keyboard"] as const)("pauses automatic requests after failure but accepts another %s boundary gesture", (input) => {
const onLoadOlder = vi.fn();
const { container } = render(
@@ -1737,7 +1735,8 @@ describe("ThreadViewport", () => {
});
expect(onLoadOlder).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Loading failed. Retry" }));
expect(screen.getByRole("button", { name: "Loading failed. Retry" }).querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
dispatchHistoryInput(scroller, input);
expect(onLoadOlder).toHaveBeenCalledTimes(1);
});
@@ -1774,13 +1773,14 @@ describe("ThreadViewport", () => {
fireEvent.touchMove(scroller, touch(240));
expect(historyPull(scroller)).toBeGreaterThan(0);
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
expect(container.querySelector(".thread-history-status")).not.toHaveClass("invisible");
expect(onLoadOlder).not.toHaveBeenCalled();
fireEvent.touchEnd(scroller);
expect(historyPull(scroller)).toBeGreaterThan(0);
await waitFor(() => expect(historyPull(scroller)).toBe(0));
fireEvent.touchStart(scroller, touch(200));
fireEvent.touchMove(scroller, touch(300));
fireEvent.touchMove(scroller, touch(380));
expect(onLoadOlder).not.toHaveBeenCalled();
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
fireEvent.touchEnd(scroller);
@@ -1789,8 +1789,19 @@ describe("ThreadViewport", () => {
fireEvent.scroll(scroller);
expect(onLoadOlder).toHaveBeenCalledTimes(1);
expect(screen.getByText("Loading earlier messages…")).toBeInTheDocument();
rerender(<ThreadViewport {...props} />);
rerender(<ThreadViewport {...props} loadingOlder />);
expect(container.querySelector(".thread-history-slot")).toBeInTheDocument();
const prepended = [
{ ...messages[0], id: "older-u0", content: "Earlier message" },
...messages,
];
rerender(<ThreadViewport {...props} messages={prepended} />);
await waitFor(() => expect(historyPull(scroller)).toBe(0));
expect(container.querySelector(".thread-history-slot")).not.toBeInTheDocument();
expect(container.querySelector(".thread-history-status")).toHaveAttribute("data-state", "ready");
expect(container.querySelector(".thread-history-status")).toHaveClass("invisible");
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();
});
it("does not fetch on touch scroll alone or horizontal gestures and clears pull on session change", () => {
@@ -2009,7 +2020,7 @@ describe("ThreadViewport", () => {
const navigation = { prompts: [{ id: "u1", label: "hello", preview: "hello", answerPreview: "", createdAt: 1, index: 0 }],
window: { messages: [{ id: "old", role: "user" as const, content: "old question", createdAt: 0 }],
userMessageOffset: 0, hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },
target: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), updateMessages: vi.fn() };
target: null, operation: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), updateMessages: vi.fn() };
const view = render(<ThreadViewport ref={viewportRef} messages={messages} isStreaming={false} composer={<div />} navigation={navigation} />);
act(() => viewportRef.current?.jumpToUserPrompt("u1"));
expect(latest).toHaveBeenCalledOnce();
@@ -2025,7 +2036,7 @@ describe("ThreadViewport", () => {
render(<ThreadViewport messages={messages} isStreaming={false} composer={<div />}
navigation={{ prompts: [], window: { messages: history, userMessageOffset: 0,
hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },
target: { id: "old-user", sequence: 1 }, loading: false, error: null,
target: { id: "old-user", sequence: 1 }, operation: null, loading: false, error: null,
jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), updateMessages: vi.fn() }} />);
await waitFor(() => expect(screen.getByText("Large old turn")).toBeInTheDocument());
});
@@ -2099,17 +2110,17 @@ describe("ThreadViewport", () => {
expect(navigateTo).toHaveBeenLastCalledWith(Math.max(0, (count - 1) * 40 - 48));
});
it("keeps prompt jumps aligned when the header changes between a row and an overlay", async () => {
it("aligns prompt jumps with the scroll inset independently of message layout", async () => {
const navigateTo = vi.spyOn(ThreadCameraController.prototype, "navigateTo")
.mockReturnValue("started");
const { scroller } = await renderPromptRailViewport();
const marker = screen.getByRole("button", { name: "Jump to message: message 1" });
scroller.style.paddingTop = "16px";
scroller.style.scrollPaddingTop = "16px";
fireEvent.click(marker);
expect(navigateTo).toHaveBeenLastCalledWith(344);
scroller.style.paddingTop = "48px";
scroller.style.scrollPaddingTop = "48px";
fireEvent.click(marker);
expect(navigateTo).toHaveBeenLastCalledWith(312);
});
+46
View File
@@ -55,6 +55,27 @@ it("loads the complete index without bodies, reads bounded windows and leaves li
expect(latest).toHaveLength(1);
});
it.each(["older", "newer"] as const)("keeps one pending %s page when boundary inputs arrive before the next render", async (operation) => {
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
let finish!: (body: WebuiThreadPersistedPayload) => void;
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
const load = result.current[operation];
act(() => {
load();
load();
});
expect(api.fetchWebuiThread).toHaveBeenCalledTimes(2);
const options = vi.mocked(api.fetchWebuiThread).mock.lastCall?.[2];
if (typeof options !== "object") throw new Error("expected page options");
expect(options.signal?.aborted).toBe(false);
expect(result.current.loading).toBe(true);
await act(async () => finish(page(operation === "older" ? 9 : 11)));
expect(result.current.loading).toBe(false);
expect(result.current.window?.messages).toHaveLength(4);
});
it("keeps the current page on failure and offers retry; superseded jumps and session reads cannot win", async () => {
const { result, rerender } = renderHook(({ key }) => usePromptHistory(key, 1, latest), {
wrapper: wrapper(), initialProps: { key: "a" },
@@ -175,3 +196,28 @@ it("merges a live input by transport identity without adding an anchor or reorde
expect(result.current.window).toBeNull();
expect(result.current.target).toBeNull();
});
it("keeps the request operation with failures and retries", async () => {
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
let finish!: (body: WebuiThreadPersistedPayload) => void;
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
act(() => result.current.jump("u10"));
expect(result.current.operation).toBe("jump");
expect(result.current.loading).toBe(true);
await act(async () => finish(page(10)));
expect(result.current.operation).toBeNull();
for (const operation of ["older", "newer"] as const) {
vi.mocked(api.fetchWebuiThread).mockRejectedValueOnce(new Error("offline"));
await act(async () => result.current[operation]());
expect(result.current.operation).toBe(operation);
expect(result.current.error).toBe("offline");
await act(async () => result.current.retry());
expect(result.current.operation).toBeNull();
expect(result.current.error).toBeNull();
}
act(() => result.current.cancel());
expect(result.current.operation).toBeNull();
});