diff --git a/webui/src/components/thread/ThreadHistoryStatus.tsx b/webui/src/components/thread/ThreadHistoryStatus.tsx new file mode 100644 index 000000000..fcfb07e25 --- /dev/null +++ b/webui/src/components/thread/ThreadHistoryStatus.tsx @@ -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 ( +
+
+ {(loading && showLoading) || pullDistance > 0 ? ( +
+
+ ) : !loading && error ? ( +
+ {t("thread.history.error")} + +
+ ) : null} +
+
+ ); +} diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index 1688c6040..cc64bf0d2 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -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} diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx index 8e86472ea..56c2ade5d 100644 --- a/webui/src/components/thread/ThreadViewport.tsx +++ b/webui/src/components/thread/ThreadViewport.tsx @@ -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; 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(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 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 { + 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 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 { @@ -782,21 +816,64 @@ export const ThreadViewport = forwardRef { + 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 { @@ -832,14 +911,20 @@ export const ThreadViewport = forwardRef 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 ) : null} + {hasMessages && conversationReady && nearHistoryTop && hasMoreBefore ? ( + + ) : null} {!hasMessages ?
: null}
diff --git a/webui/src/hooks/useSessions.ts b/webui/src/hooks/useSessions.ts index c197ab1bb..f6bc3a821 100644 --- a/webui/src/hooks/useSessions.ts +++ b/webui/src/hooks/useSessions.ts @@ -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; @@ -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, diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 3526c7ec9..296cc2f0c 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -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", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index cfeea6d83..c35aa3197 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -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", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index 1d4dedbe8..32ad52b79 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -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", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index d99c2ae4c..82e3ad843 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -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", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 3eb500b90..fd7525345 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -1615,6 +1615,11 @@ }, "scrollToBottom": "一番下へスクロール", "loadEarlier": "以前のメッセージを読み込む", + "history": { + "loading": "以前のメッセージを読み込み中…", + "error": "読み込みに失敗しました。", + "retry": "再試行" + }, "forkedFromHistory": "履歴から分岐", "promptNavigator": { "open": "プロンプトナビゲーターを開く", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 7f761188a..8206f5e8c 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -1615,6 +1615,11 @@ }, "scrollToBottom": "맨 아래로 스크롤", "loadEarlier": "이전 메시지 불러오기", + "history": { + "loading": "이전 메시지를 불러오는 중…", + "error": "불러오지 못했습니다.", + "retry": "다시 시도" + }, "forkedFromHistory": "기록에서 분기됨", "promptNavigator": { "open": "프롬프트 탐색기 열기", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 854bd173d..c47daeb3b 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -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", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index aace12e94..320ed2e36 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -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", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index dc1ab85f4..a05b724ed 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1815,6 +1815,11 @@ }, "scrollToBottom": "滚动到底部", "loadEarlier": "加载更早消息", + "history": { + "loading": "正在加载更早的消息…", + "error": "加载失败", + "retry": "重试" + }, "forkedFromHistory": "从历史消息分叉", "promptNavigator": { "open": "打开提示词导航", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index c26794719..c658d0c7f 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -1615,6 +1615,11 @@ }, "scrollToBottom": "捲動到底部", "loadEarlier": "載入更早訊息", + "history": { + "loading": "正在載入更早的訊息…", + "error": "載入失敗", + "retry": "重試" + }, "forkedFromHistory": "從歷史訊息建立分支", "promptNavigator": { "open": "開啟提示詞導覽", diff --git a/webui/src/tests/thread-history-status.test.tsx b/webui/src/tests/thread-history-status.test.tsx new file mode 100644 index 000000000..cb3ff468e --- /dev/null +++ b/webui/src/tests/thread-history-status.test.tsx @@ -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(); + + 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(); + act(() => vi.advanceTimersByTime(100)); + rerender(); + act(() => vi.advanceTimersByTime(500)); + expect(screen.getByRole("status")).toBeEmptyDOMElement(); + + rerender(); + act(() => vi.advanceTimersByTime(180)); + expect(screen.getByText("Loading earlier messages…")).toHaveClass("sr-only"); + expect(screen.getByRole("status").querySelector("svg")).toHaveClass("animate-spin"); + rerender(); + expect(screen.getByRole("status")).toBeEmptyDOMElement(); + rerender(); + expect(screen.getByRole("status")).toBeEmptyDOMElement(); + }); + + it("offers an explicit retry after loading earlier history fails", () => { + const onRetry = vi.fn(); + render(); + + 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); + }); +}); diff --git a/webui/src/tests/thread-viewport.test.tsx b/webui/src/tests/thread-viewport.test.tsx index e6f7abdf5..c10954848 100644 --- a/webui/src/tests/thread-viewport.test.tsx +++ b/webui/src/tests/thread-viewport.test.tsx @@ -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( + , + ); + 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(); + 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( + } + 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( + , + ); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + expect(scroller.style.transform).toBe(""); + expect(onLoadOlder).not.toHaveBeenCalled(); + }); + + it("leaves completed history quiet", () => { + const onLoadOlder = vi.fn(); + const { container } = render(); + 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(); diff --git a/webui/src/tests/useSessions.test.tsx b/webui/src/tests/useSessions.test.tsx index b57cff6d5..3c9357c45 100644 --- a/webui/src/tests/useSessions.test.tsx +++ b/webui/src/tests/useSessions.test.tsx @@ -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)