fix(webui): unblock earlier-history pagination and show retry states (#5934)

* fix(webui): show history pagination loading and retry states

* fix(webui): load earlier history on backward input at top

* fix(webui): use pull gestures and spinners for history loading

* fix(webui): shorten history loading failure messages

* refactor(webui): simplify history pagination guards and tests
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-27 21:06:59 +08:00
1 parent db6ef4d674
commit 33dddaaa46
17 files changed
+533 -28

No files matched your search

@@ -0,0 +1,61 @@
import { useEffect, useState } from "react";
import { Loader2, RotateCcw } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
interface ThreadHistoryStatusProps {
loading: boolean;
error: string | null;
pullDistance?: number;
onRetry: () => void;
}
export function ThreadHistoryStatus({ loading, error, onRetry, pullDistance = 0 }: ThreadHistoryStatusProps) {
const { t } = useTranslation();
const [showLoading, setShowLoading] = useState(false);
useEffect(() => {
if (!loading) {
setShowLoading(false);
return;
}
const timer = window.setTimeout(() => setShowLoading(true), 180);
return () => window.clearTimeout(timer);
}, [loading]);
return (
<div
className="thread-message-row pointer-events-none absolute inset-x-0 top-0 z-10 flex items-center justify-center"
style={{ height: 48 + pullDistance }}
>
<div role="status" aria-live="polite" aria-atomic="true">
{(loading && showLoading) || pullDistance > 0 ? (
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-background/95 text-muted-foreground">
<Loader2
aria-hidden="true"
className={`h-4 w-4 ${loading ? "animate-spin motion-reduce:animate-none" : ""}`}
style={!loading ? { transform: `rotate(${pullDistance * 6}deg)`, opacity: Math.min(1, pullDistance / 24) } : undefined}
/>
{loading ? <span className="sr-only">{t("thread.history.loading")}</span> : null}
</div>
) : !loading && error ? (
<div className="pointer-events-auto flex items-center gap-1 rounded-control bg-background/95 pl-3 text-xs text-muted-foreground">
<span>{t("thread.history.error")}</span>
<Button
type="button"
variant="ghost"
size="sm"
className="h-11 w-11 shrink-0 p-0 sm:h-8 sm:w-8"
aria-label={t("thread.history.retry")}
title={t("thread.history.retry")}
onClick={onRetry}
>
<RotateCcw aria-hidden="true" className="h-4 w-4" />
</Button>
</div>
) : null}
</div>
</div>
);
}
@@ -683,6 +683,7 @@ export function ThreadShell({
loading,
error: historyError,
loadingOlder,
olderError,
loadOlder,
hasMoreBefore,
userMessageOffset,
@@ -1922,6 +1923,7 @@ export function ThreadShell({
forkBoundaryMessageCount={forkBoundaryMessageCount}
hasMoreBefore={hasMoreBefore}
loadingOlder={loadingOlder}
olderError={olderError}
userMessageOffset={userMessageOffset}
onLoadOlder={loadOlder}
traceDetailScope={historyKey}
+111 -16
View File
@@ -14,6 +14,7 @@ import { useTranslation } from "react-i18next";
import { PromptRail } from "@/components/thread/PromptRail";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
import { ThreadCameraController } from "@/components/thread/thread-camera";
import {
@@ -54,6 +55,7 @@ interface ThreadViewportProps {
forkBoundaryMessageCount?: number | null;
hasMoreBefore?: boolean;
loadingOlder?: boolean;
olderError?: string | null;
userMessageOffset?: number;
onLoadOlder?: () => Promise<void> | void;
traceDetailScope?: string | null;
@@ -63,6 +65,7 @@ interface ThreadViewportProps {
onQuoteSelection?: (text: string) => void;
}
const HISTORY_PULL_THRESHOLD_PX = 48;
const NEAR_BOTTOM_PX = 48;
const PROMPT_TOP_INSET_PX = 48;
const HISTORY_PREFETCH_MIN_PX = 160;
@@ -245,6 +248,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
forkBoundaryMessageCount = null,
hasMoreBefore = false,
loadingOlder = false,
olderError = null,
userMessageOffset = 0,
onLoadOlder,
traceDetailScope = null,
@@ -273,6 +277,22 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const composerInputScrollTopRef = useRef<number | null>(null);
const composerDockHeightRef = useRef(0);
const [atBottom, setAtBottom] = useState(true);
const [nearHistoryTop, setNearHistoryTop] = useState(false);
const [historyPull, setHistoryPull] = useState(0);
const historyInputRef = useRef<"touch" | "other">("other");
const historyTouchRef = useRef<{
lastY: number; startX: number; startY: number | null; triggered: boolean;
} | null>(null);
useEffect(() => {
if (!loadingOlder || olderError || !hasMoreBefore) setHistoryPull(0);
}, [loadingOlder, olderError, hasMoreBefore]);
useEffect(() => {
historyTouchRef.current = null;
historyInputRef.current = "other";
setHistoryPull(0);
}, [conversationKey]);
const [composerDockHeight, setComposerDockHeight] = useState(0);
const [keyboardInsetBottom, setKeyboardInsetBottom] = useState(0);
const [hasVerticalOverflow, setHasVerticalOverflow] = useState(false);
@@ -469,9 +489,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
if (!el || !hasMessages || pendingConversationScrollRef.current) return;
if (!threadMotionRef.current?.isBrowsingHistory()) return;
if (el.scrollTop > historyPrefetchDistance(el)) return;
if (hiddenMessageCount <= 0 && !hasMoreBefore) return;
if (hiddenMessageCount <= 0 && (historyInputRef.current === "touch" || el.scrollTop > 1)) return;
if (hiddenMessageCount <= 0 && (!hasMoreBefore || olderError)) return;
loadEarlierMessages();
}, [hasMessages, hasMoreBefore, hiddenMessageCount, loadEarlierMessages]);
}, [hasMessages, hasMoreBefore, hiddenMessageCount, loadEarlierMessages, olderError]);
const navigateToVisiblePrompt = useCallback((promptId: string) => {
const scrollEl = scrollRef.current;
@@ -738,6 +759,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
if (!el) return;
const onScroll = (allowHistoryLoad = true) => {
setNearHistoryTop(el.scrollTop <= historyPrefetchDistance(el));
if (el.scrollTop > 1) setHistoryPull(0);
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
const near = distance < NEAR_BOTTOM_PX;
const owner = threadMotionRef.current?.observeScroll(near) ?? "automatic";
@@ -755,10 +778,19 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
onScroll(false);
const handleScroll = () => onScroll(true);
const canLoadAtTop = () => el.scrollTop <= 0 && hasMessages && conversationReady
&& !pendingConversationScrollRef.current && !loadingOlder
&& (hiddenMessageCount > 0 || (hasMoreBefore && !olderError));
const handleDirectionalInput = (
direction: ThreadScrollDirection | null,
) => {
if (!direction) return;
// At the top (including a page too short to scroll), backward intent
// produces no scroll event. It must still be able to reveal history.
if (direction === "backward" && canLoadAtTop()) {
loadEarlierMessages();
return;
}
threadMotionRef.current?.handleUserScrollIntent(
canScrollInDirection(el, direction),
direction === "forward",
@@ -772,6 +804,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
) {
return;
}
historyInputRef.current = "other";
setHistoryPull(0);
handleDirectionalInput(directionFromDelta(event.deltaY));
};
const handlePointerDown = (event: PointerEvent) => {
@@ -782,21 +816,64 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
yieldCameraToUser();
}
};
let lastTouchY: number | null = null;
const handleTouchCancel = () => {
historyTouchRef.current = null;
setHistoryPull(0);
};
const handleTouchStart = (event: TouchEvent) => {
lastTouchY = event.touches[0]?.clientY ?? null;
historyInputRef.current = "touch";
const touch = event.touches[0];
historyTouchRef.current = event.touches.length === 1 && touch
? {
lastY: touch.clientY,
startX: touch.clientX,
startY: el.scrollTop <= 0 ? touch.clientY : null,
triggered: false,
}
: null;
};
const handleTouchMove = (event: TouchEvent) => {
const currentY = event.touches[0]?.clientY;
const scrollDeltaY =
lastTouchY !== null && currentY !== undefined
? lastTouchY - currentY
: 0;
lastTouchY = currentY ?? null;
handleDirectionalInput(directionFromDelta(scrollDeltaY));
const gesture = historyTouchRef.current;
const touch = event.touches[0];
if (event.touches.length !== 1) {
handleTouchCancel();
return;
}
if (!gesture || !touch || event.defaultPrevented) return;
const delta = gesture.lastY - touch.clientY;
gesture.lastY = touch.clientY;
if (gesture.triggered) {
if (el.scrollTop <= 0 && delta < 0 && event.cancelable) event.preventDefault();
return;
}
if (el.scrollTop > 0) gesture.startY = null;
if (canLoadAtTop() && hiddenMessageCount === 0) {
gesture.startY ??= touch.clientY;
const distance = touch.clientY - gesture.startY;
if (distance > 0 && distance > Math.abs(touch.clientX - gesture.startX)) {
if (event.cancelable) event.preventDefault();
yieldCameraToUser();
// Resistance exposes a small loading pocket without stretching the transcript.
const pull = Math.min(HISTORY_PULL_THRESHOLD_PX, distance * 0.5);
setHistoryPull(pull);
setNearHistoryTop(true);
if (pull >= HISTORY_PULL_THRESHOLD_PX) {
gesture.triggered = true;
loadEarlierMessages();
}
return;
}
}
setHistoryPull(0);
// Locally windowed messages need no network gesture or loading feedback.
if (hiddenMessageCount > 0) handleDirectionalInput(directionFromDelta(delta));
else threadMotionRef.current?.handleUserScrollIntent(
canScrollInDirection(el, directionFromDelta(delta)), delta > 0,
);
};
const handleTouchEnd = () => {
lastTouchY = null;
historyTouchRef.current = null;
if (!loadingOlder) setHistoryPull(0);
};
const handleKeyDown = (event: KeyboardEvent) => {
if (
@@ -816,14 +893,16 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
return;
}
if (isKeyboardControl(event.target as Element | null)) return;
historyInputRef.current = "other";
setHistoryPull(0);
handleDirectionalInput(keyboardScrollDirection(event));
};
el.addEventListener("scroll", handleScroll, { passive: true });
el.addEventListener("wheel", handleWheel, { passive: true });
el.addEventListener("touchstart", handleTouchStart, { passive: true });
el.addEventListener("touchmove", handleTouchMove, { passive: true });
el.addEventListener("touchmove", handleTouchMove, { passive: false });
el.addEventListener("touchend", handleTouchEnd, { passive: true });
el.addEventListener("touchcancel", handleTouchEnd, { passive: true });
el.addEventListener("touchcancel", handleTouchCancel, { passive: true });
el.addEventListener("pointerdown", handlePointerDown);
el.addEventListener("keydown", handleKeyDown);
return () => {
@@ -832,14 +911,20 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
el.removeEventListener("touchstart", handleTouchStart);
el.removeEventListener("touchmove", handleTouchMove);
el.removeEventListener("touchend", handleTouchEnd);
el.removeEventListener("touchcancel", handleTouchEnd);
el.removeEventListener("touchcancel", handleTouchCancel);
el.removeEventListener("pointerdown", handlePointerDown);
el.removeEventListener("keydown", handleKeyDown);
};
}, [
captureHistoryScrollAnchor,
conversationReady,
hasMessages,
hasMoreBefore,
hiddenMessageCount,
loadingOlder,
loadEarlierMessages,
maybeLoadEarlierFromScroll,
olderError,
yieldCameraToUser,
]);
@@ -875,9 +960,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
<div
ref={messageRegionRef}
data-testid="thread-message-region"
style={{ transform: historyPull > 0 ? `translateY(${historyPull}px)` : undefined }}
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 pb-0 pt-[var(--thread-prompt-inset,3rem)]",
"scroll-auto justify-start overflow-x-hidden overscroll-y-contain pb-0 pt-12",
"[overflow-anchor:none] [scrollbar-width:none]",
"[&::-webkit-scrollbar]:hidden",
hasVerticalOverflow ? "overflow-y-auto" : "overflow-hidden",
@@ -972,6 +1058,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
/>
) : null}
</div>
{hasMessages && conversationReady && nearHistoryTop && hasMoreBefore ? (
<ThreadHistoryStatus
key={conversationKey}
loading={loadingOlder}
pullDistance={historyPull}
error={olderError}
onRetry={loadEarlierMessages}
/>
) : null}
{!hasMessages ? <div ref={bottomRef} aria-hidden className="h-px" /> : null}
</div>
+15 -3
View File
@@ -138,6 +138,7 @@ interface SessionHistoryState {
messages: UIMessage[];
loading: boolean;
loadingOlder: boolean;
olderError: string | null;
error: string | null;
hasPendingToolCalls: boolean;
completedTurnIds: string[];
@@ -157,6 +158,7 @@ function emptyHistoryState(key: string | null, loading = false): SessionHistoryS
messages: [],
loading,
loadingOlder: false,
olderError: null,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
@@ -183,6 +185,7 @@ function cachedHistoryState(
messages,
loading: false,
loadingOlder: false,
olderError: null,
error: null,
hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages),
completedTurnIds: completedTurnIdsFromThread(body),
@@ -384,6 +387,7 @@ export function useSessionHistory(key: string | null): {
messages: UIMessage[];
loading: boolean;
loadingOlder: boolean;
olderError: string | null;
error: string | null;
refresh: () => void;
loadOlder: () => Promise<void>;
@@ -492,6 +496,10 @@ export function useSessionHistory(key: string | null): {
messages: merged.messages,
loading: false,
loadingOlder: false,
olderError: merged.continuity === "overlap"
&& (retainedPrefix || prev.beforeCursor === body?.page?.before_cursor)
? prev.olderError
: null,
error: null,
hasPendingToolCalls: hasPending,
completedTurnIds,
@@ -532,6 +540,7 @@ export function useSessionHistory(key: string | null): {
messages: [],
loading: false,
loadingOlder: false,
olderError: null,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
@@ -573,7 +582,7 @@ export function useSessionHistory(key: string | null): {
const controller = new AbortController();
olderRequestAbortRef.current = controller;
setState((prev) => matchesRequest(prev)
? { ...prev, loadingOlder: true, error: null }
? { ...prev, loadingOlder: true, olderError: null }
: prev);
try {
const body = await fetchWebuiThread(getToken(), requestKey, {
@@ -604,7 +613,7 @@ export function useSessionHistory(key: string | null): {
...prev,
messages: nextMessages,
loadingOlder: false,
error: null,
olderError: null,
forkBoundaryMessageCount: olderBoundary ?? shiftedBoundary,
beforeCursor: body.page?.before_cursor ?? null,
hasMoreBefore: body.page?.has_more_before === true,
@@ -617,7 +626,7 @@ export function useSessionHistory(key: string | null): {
? {
...prev,
loadingOlder: false,
error: (e as Error).message,
olderError: (e as Error).message || "Could not load earlier messages",
}
: prev);
} finally {
@@ -640,6 +649,7 @@ export function useSessionHistory(key: string | null): {
messages: EMPTY_MESSAGES,
loading: false,
loadingOlder: false,
olderError: null,
error: null,
refresh,
loadOlder,
@@ -662,6 +672,7 @@ export function useSessionHistory(key: string | null): {
messages: EMPTY_MESSAGES,
loading: true,
loadingOlder: false,
olderError: null,
error: null,
refresh,
loadOlder,
@@ -681,6 +692,7 @@ export function useSessionHistory(key: string | null): {
messages: state.messages,
loading: state.loading,
loadingOlder: state.loadingOlder,
olderError: state.olderError,
error: state.error,
refresh,
loadOlder,
+5
View File
@@ -1815,6 +1815,11 @@
},
"scrollToBottom": "Scroll to bottom",
"loadEarlier": "Load earlier messages",
"history": {
"loading": "Loading earlier messages…",
"error": "Loading failed.",
"retry": "Retry"
},
"forkedFromHistory": "Forked from history",
"promptNavigator": {
"open": "Open prompt navigator",
+5
View File
@@ -1616,6 +1616,11 @@
},
"scrollToBottom": "Desplazarse al final",
"loadEarlier": "Cargar mensajes anteriores",
"history": {
"loading": "Cargando mensajes anteriores…",
"error": "Error al cargar.",
"retry": "Reintentar"
},
"forkedFromHistory": "Bifurcado desde el historial",
"promptNavigator": {
"open": "Abrir el navegador de instrucciones",
+5
View File
@@ -1615,6 +1615,11 @@
},
"scrollToBottom": "Faire défiler vers le bas",
"loadEarlier": "Charger les messages précédents",
"history": {
"loading": "Chargement des messages précédents…",
"error": "Échec du chargement.",
"retry": "Réessayer"
},
"forkedFromHistory": "Bifurqué depuis l'historique",
"promptNavigator": {
"open": "Ouvrir le navigateur d’instructions",
+5
View File
@@ -1615,6 +1615,11 @@
},
"scrollToBottom": "Gulir ke bawah",
"loadEarlier": "Muat pesan sebelumnya",
"history": {
"loading": "Memuat pesan sebelumnya…",
"error": "Gagal memuat.",
"retry": "Coba lagi"
},
"forkedFromHistory": "Cabang dari riwayat",
"promptNavigator": {
"open": "Buka navigasi instruksi",
+5
View File
@@ -1615,6 +1615,11 @@
},
"scrollToBottom": "一番下へスクロール",
"loadEarlier": "以前のメッセージを読み込む",
"history": {
"loading": "以前のメッセージを読み込み中…",
"error": "読み込みに失敗しました。",
"retry": "再試行"
},
"forkedFromHistory": "履歴から分岐",
"promptNavigator": {
"open": "プロンプトナビゲーターを開く",
+5
View File
@@ -1615,6 +1615,11 @@
},
"scrollToBottom": "맨 아래로 스크롤",
"loadEarlier": "이전 메시지 불러오기",
"history": {
"loading": "이전 메시지를 불러오는 중…",
"error": "불러오지 못했습니다.",
"retry": "다시 시도"
},
"forkedFromHistory": "기록에서 분기됨",
"promptNavigator": {
"open": "프롬프트 탐색기 열기",
+5
View File
@@ -1629,6 +1629,11 @@
},
"scrollToBottom": "Rolar para o final",
"loadEarlier": "Carregar mensagens anteriores",
"history": {
"loading": "Carregando mensagens anteriores…",
"error": "Falha ao carregar.",
"retry": "Tentar novamente"
},
"forkedFromHistory": "Bifurcado a partir do histórico",
"promptNavigator": {
"open": "Abrir navegador de instruções",
+5
View File
@@ -1615,6 +1615,11 @@
},
"scrollToBottom": "Cuộn xuống cuối",
"loadEarlier": "Tải tin nhắn trước đó",
"history": {
"loading": "Đang tải tin nhắn trước đó…",
"error": "Tải thất bại.",
"retry": "Thử lại"
},
"forkedFromHistory": "Tách nhánh từ lịch sử",
"promptNavigator": {
"open": "Mở trình điều hướng lời nhắc",
+5
View File
@@ -1815,6 +1815,11 @@
},
"scrollToBottom": "滚动到底部",
"loadEarlier": "加载更早消息",
"history": {
"loading": "正在加载更早的消息…",
"error": "加载失败",
"retry": "重试"
},
"forkedFromHistory": "从历史消息分叉",
"promptNavigator": {
"open": "打开提示词导航",
+5
View File
@@ -1615,6 +1615,11 @@
},
"scrollToBottom": "捲動到底部",
"loadEarlier": "載入更早訊息",
"history": {
"loading": "正在載入更早的訊息…",
"error": "載入失敗",
"retry": "重試"
},
"forkedFromHistory": "從歷史訊息建立分支",
"promptNavigator": {
"open": "開啟提示詞導覽",
@@ -0,0 +1,51 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
afterEach(() => {
vi.useRealTimers();
});
describe("ThreadHistoryStatus", () => {
it("delays the loading indicator so fast history requests do not flash", () => {
vi.useFakeTimers();
render(<ThreadHistoryStatus loading error={null} onRetry={vi.fn()} />);
expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();
act(() => vi.advanceTimersByTime(179));
expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();
act(() => vi.advanceTimersByTime(1));
expect(screen.getByText("Loading earlier messages…")).toHaveClass("sr-only");
expect(screen.getByRole("status").querySelector("svg")).toHaveClass("animate-spin");
});
it("cancels the delay on completion and starts a fresh delay for the next request", () => {
vi.useFakeTimers();
const props = { error: null, onRetry: vi.fn() };
const { rerender } = render(<ThreadHistoryStatus {...props} loading />);
act(() => vi.advanceTimersByTime(100));
rerender(<ThreadHistoryStatus {...props} loading={false} />);
act(() => vi.advanceTimersByTime(500));
expect(screen.getByRole("status")).toBeEmptyDOMElement();
rerender(<ThreadHistoryStatus {...props} loading />);
act(() => vi.advanceTimersByTime(180));
expect(screen.getByText("Loading earlier messages…")).toHaveClass("sr-only");
expect(screen.getByRole("status").querySelector("svg")).toHaveClass("animate-spin");
rerender(<ThreadHistoryStatus {...props} loading={false} />);
expect(screen.getByRole("status")).toBeEmptyDOMElement();
rerender(<ThreadHistoryStatus {...props} loading />);
expect(screen.getByRole("status")).toBeEmptyDOMElement();
});
it("offers an explicit retry after loading earlier history fails", () => {
const onRetry = vi.fn();
render(<ThreadHistoryStatus loading={false} error="offline" onRetry={onRetry} />);
expect(screen.getByText("Loading failed.")).toBeVisible();
expect(screen.getByRole("status").parentElement).toHaveClass("thread-message-row");
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(onRetry).toHaveBeenCalledTimes(1);
});
});
+161 -9
View File
@@ -40,6 +40,23 @@ function dispatchUserScroll(scroller: HTMLElement): void {
scroller.dispatchEvent(new Event("scroll"));
}
function dispatchHistoryInput(scroller: HTMLElement, input: "wheel" | "touch" | "keyboard") {
if (input === "wheel") fireEvent.wheel(scroller, { deltaY: -100 });
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 }] });
}
}
function mockScrollGeometry(scroller: HTMLElement, height: number, viewport: number, top = 0) {
Object.defineProperties(scroller, {
scrollHeight: { configurable: true, value: height },
clientHeight: { configurable: true, value: viewport },
scrollTop: { configurable: true, writable: true, value: top },
});
}
interface ResizeObserverInstance {
elements: Element[];
callback: ResizeObserverCallback;
@@ -920,7 +937,7 @@ describe("ThreadViewport", () => {
followTo.mockClear();
act(() => {
fireEvent.touchStart(scroller, { touches: [{ clientY: 300 }] });
fireEvent.touchStart(scroller, { touches: [{ clientX: 100, clientY: 300 }] });
fireEvent.touchMove(scroller, { touches: [{ clientY: 324 }] });
scroller.scrollTop = 1_380;
scroller.dispatchEvent(new Event("scroll"));
@@ -931,7 +948,7 @@ describe("ThreadViewport", () => {
expect(screen.getByRole("button", { name: "Scroll to bottom" })).toBeInTheDocument();
act(() => {
fireEvent.touchMove(scroller, { touches: [{ clientY: 300 }] });
fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 300 }] });
scroller.scrollTop = 1_404;
scroller.dispatchEvent(new Event("scroll"));
fireEvent.touchEnd(scroller);
@@ -1639,6 +1656,39 @@ describe("ThreadViewport", () => {
}
});
it.each(["wheel", "touch", "keyboard"] as const)(
"requests older history on %s intent when the initial page does not overflow",
(input) => {
const onLoadOlder = vi.fn();
const { container } = render(
<ThreadViewport messages={messages} isStreaming={false}
hasMoreBefore onLoadOlder={onLoadOlder} />,
);
const scroller = getScroller(container);
mockScrollGeometry(scroller, 746, 746);
expect(onLoadOlder).not.toHaveBeenCalled();
dispatchHistoryInput(scroller, input);
expect(onLoadOlder).toHaveBeenCalledTimes(1);
},
);
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) => {
const onLoadOlder = vi.fn();
const { container } = render(<ThreadViewport messages={messages} isStreaming={false}
hasMoreBefore onLoadOlder={onLoadOlder} {...blocked} />);
const scroller = getScroller(container);
dispatchHistoryInput(scroller, input);
expect(onLoadOlder).not.toHaveBeenCalled();
expect(scroller.style.transform).toBe("");
});
});
it("automatically requests older transcript pages near the top", () => {
const onLoadOlder = vi.fn();
@@ -1653,11 +1703,7 @@ describe("ThreadViewport", () => {
);
const scroller = getScroller(container);
Object.defineProperties(scroller, {
scrollHeight: { configurable: true, value: 1800 },
clientHeight: { configurable: true, value: 600 },
scrollTop: { configurable: true, writable: true, value: 0 },
});
mockScrollGeometry(scroller, 1800, 600);
act(() => {
dispatchUserScroll(scroller);
@@ -1666,6 +1712,112 @@ describe("ThreadViewport", () => {
expect(onLoadOlder).toHaveBeenCalledTimes(1);
});
it("pauses automatic history requests after a failure and exposes retry", () => {
const onLoadOlder = vi.fn();
const { container } = render(
<ThreadViewport
messages={makeLongMessages(20)}
isStreaming={false}
composer={<div />}
hasMoreBefore
olderError="offline"
onLoadOlder={onLoadOlder}
/>,
);
const scroller = getScroller(container);
mockScrollGeometry(scroller, 1800, 600);
act(() => {
dispatchUserScroll(scroller);
scroller.dispatchEvent(new Event("scroll"));
});
expect(onLoadOlder).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(onLoadOlder).toHaveBeenCalledTimes(1);
});
it("hides history feedback away from the top without fetching again", async () => {
const onLoadOlder = vi.fn();
const { container, rerender } = render(
<ThreadViewport messages={messages} isStreaming={false}
hasMoreBefore loadingOlder onLoadOlder={onLoadOlder} />,
);
const scroller = getScroller(container);
mockScrollGeometry(scroller, 1800, 600, 200);
act(() => dispatchUserScroll(scroller));
expect(await screen.findByText("Loading earlier messages…")).toBeVisible();
expect(scroller.scrollTop).toBe(200);
expect(onLoadOlder).not.toHaveBeenCalled();
act(() => {
scroller.scrollTop = 800;
dispatchUserScroll(scroller);
});
expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();
rerender(<ThreadViewport messages={messages} isStreaming={false}
conversationKey="another" hasMoreBefore onLoadOlder={onLoadOlder} />);
expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();
});
it("reveals touch feedback before fetching, cancels short pulls, and fetches once per gesture", () => {
const onLoadOlder = vi.fn();
const props = { messages, isStreaming: false, hasMoreBefore: true, onLoadOlder };
const { container, rerender } = render(<ThreadViewport {...props} />);
const scroller = getScroller(container);
const touch = (y: number) => ({ touches: [{ clientX: 100, clientY: y }] });
fireEvent.touchStart(scroller, touch(200));
fireEvent.touchMove(scroller, touch(240));
expect(scroller).toHaveStyle({ transform: "translateY(20px)" });
expect(screen.getByRole("status").querySelector("svg")).not.toBeNull();
expect(onLoadOlder).not.toHaveBeenCalled();
fireEvent.touchEnd(scroller);
expect(scroller.style.transform).toBe("");
fireEvent.touchStart(scroller, touch(200));
fireEvent.touchMove(scroller, touch(300));
expect(onLoadOlder).toHaveBeenCalledTimes(1);
rerender(<ThreadViewport {...props} loadingOlder />);
fireEvent.touchMove(scroller, touch(350));
fireEvent.scroll(scroller);
expect(onLoadOlder).toHaveBeenCalledTimes(1);
expect(screen.getByRole("status").querySelector("svg")).toHaveClass("animate-spin");
fireEvent.touchEnd(scroller);
expect(scroller).toHaveStyle({ transform: "translateY(48px)" });
rerender(<ThreadViewport {...props} />);
expect(scroller.style.transform).toBe("");
});
it("does not fetch on touch scroll alone or horizontal gestures and clears pull on session change", () => {
const onLoadOlder = vi.fn();
const props = { messages, isStreaming: false, hasMoreBefore: true, onLoadOlder };
const { container, rerender } = render(<ThreadViewport {...props} conversationKey="a" />);
const scroller = getScroller(container);
fireEvent.touchStart(scroller, { touches: [{ clientX: 100, clientY: 200 }] });
fireEvent.touchMove(scroller, { touches: [{ clientX: 300, clientY: 220 }] });
fireEvent.scroll(scroller);
expect(scroller.style.transform).toBe("");
expect(onLoadOlder).not.toHaveBeenCalled();
fireEvent.touchEnd(scroller);
fireEvent.touchStart(scroller, { touches: [{ clientX: 100, clientY: 200 }] });
fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 240 }] });
rerender(<ThreadViewport {...props} conversationKey="b" />);
expect(scroller.style.transform).toBe("");
expect(onLoadOlder).not.toHaveBeenCalled();
});
it("leaves completed history quiet", () => {
const onLoadOlder = vi.fn();
const { container } = render(<ThreadViewport messages={messages} isStreaming={false}
onLoadOlder={onLoadOlder} />);
fireEvent.wheel(getScroller(container), { deltaY: -100 });
expect(screen.getByText("hello")).toBeVisible();
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(onLoadOlder).not.toHaveBeenCalled();
});
it("renders a prompt rail that jumps to user messages", async () => {
const navigateTo = vi.spyOn(ThreadCameraController.prototype, "navigateTo")
.mockReturnValue("started");
@@ -1753,8 +1905,8 @@ describe("ThreadViewport", () => {
expect(cancel).toHaveBeenCalledTimes(1);
restartNavigation();
fireEvent.touchStart(scroller, { touches: [{ clientY: 300 }] });
fireEvent.touchMove(scroller, { touches: [{ clientY: 200 }] });
fireEvent.touchStart(scroller, { touches: [{ clientX: 100, clientY: 300 }] });
fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 200 }] });
expect(cancel).toHaveBeenCalledTimes(1);
restartNavigation();
+82
View File
@@ -990,6 +990,88 @@ describe("useSessions", () => {
expect(result.current.continuity).toBe("initial");
});
it("keeps older-history failures separate and retries them explicitly", async () => {
vi.mocked(api.fetchWebuiThread)
.mockResolvedValueOnce({
schemaVersion: 3,
messages: [
{ id: "u2", role: "user", content: "latest question", createdAt: 2 },
],
page: {
before_cursor: "cursor-2",
has_more_before: true,
loaded_message_count: 1,
user_message_offset: 1,
},
})
.mockRejectedValueOnce(new Error("offline"))
.mockResolvedValueOnce({
schemaVersion: 3,
messages: [
{ id: "u1", role: "user", content: "earliest question", createdAt: 1 },
],
page: {
before_cursor: null,
has_more_before: false,
loaded_message_count: 1,
user_message_offset: 0,
},
});
const { result } = renderHook(() => useSessionHistory("websocket:retry-older"), {
wrapper: wrap(fakeClient()),
});
await waitFor(() => expect(result.current.loading).toBe(false));
await act(async () => {
await result.current.loadOlder();
});
expect(result.current.error).toBeNull();
expect(result.current.olderError).toBe("offline");
expect(result.current.hasMoreBefore).toBe(true);
await act(async () => {
await result.current.loadOlder();
});
expect(result.current.olderError).toBeNull();
expect(result.current.hasMoreBefore).toBe(false);
expect(result.current.messages.map((message) => message.id)).toEqual(["u1", "u2"]);
});
it("preserves a failed history cursor on refresh but clears it for another session", async () => {
const latest = {
schemaVersion: 3 as const,
messages: [{ id: "u2", role: "user" as const, content: "question", createdAt: 2 }],
page: {
before_cursor: "cursor-2", has_more_before: true,
loaded_message_count: 1, user_message_offset: 1,
},
};
vi.mocked(api.fetchWebuiThread)
.mockResolvedValueOnce(latest)
.mockRejectedValueOnce(new Error("offline"))
.mockResolvedValueOnce({ ...latest })
.mockResolvedValueOnce({ schemaVersion: 3, messages: [] });
const { result, rerender } = renderHook(({ sessionKey }) => useSessionHistory(sessionKey), {
initialProps: { sessionKey: "websocket:failed-prefix" },
wrapper: wrap(fakeClient()),
});
await waitFor(() => expect(result.current.loading).toBe(false));
await act(async () => { await result.current.loadOlder(); });
expect(result.current.olderError).toBe("offline");
const previousVersion = result.current.version;
act(() => result.current.refresh());
await waitFor(() => expect(result.current.version).toBeGreaterThan(previousVersion));
expect(result.current.olderError).toBe("offline");
expect(result.current.error).toBeNull();
rerender({ sessionKey: "websocket:other-history" });
expect(result.current.olderError).toBeNull();
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.messages).toEqual([]);
});
it("aborts an older-history request when the consumer unmounts", async () => {
let olderSignal: AbortSignal | undefined;
vi.mocked(api.fetchWebuiThread)