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:
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,
|
loading,
|
||||||
error: historyError,
|
error: historyError,
|
||||||
loadingOlder,
|
loadingOlder,
|
||||||
|
olderError,
|
||||||
loadOlder,
|
loadOlder,
|
||||||
hasMoreBefore,
|
hasMoreBefore,
|
||||||
userMessageOffset,
|
userMessageOffset,
|
||||||
@@ -1922,6 +1923,7 @@ export function ThreadShell({
|
|||||||
forkBoundaryMessageCount={forkBoundaryMessageCount}
|
forkBoundaryMessageCount={forkBoundaryMessageCount}
|
||||||
hasMoreBefore={hasMoreBefore}
|
hasMoreBefore={hasMoreBefore}
|
||||||
loadingOlder={loadingOlder}
|
loadingOlder={loadingOlder}
|
||||||
|
olderError={olderError}
|
||||||
userMessageOffset={userMessageOffset}
|
userMessageOffset={userMessageOffset}
|
||||||
onLoadOlder={loadOlder}
|
onLoadOlder={loadOlder}
|
||||||
traceDetailScope={historyKey}
|
traceDetailScope={historyKey}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { useTranslation } from "react-i18next";
|
|||||||
|
|
||||||
import { PromptRail } from "@/components/thread/PromptRail";
|
import { PromptRail } from "@/components/thread/PromptRail";
|
||||||
import { ThreadMessages } from "@/components/thread/ThreadMessages";
|
import { ThreadMessages } from "@/components/thread/ThreadMessages";
|
||||||
|
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
|
||||||
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
|
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
|
||||||
import { ThreadCameraController } from "@/components/thread/thread-camera";
|
import { ThreadCameraController } from "@/components/thread/thread-camera";
|
||||||
import {
|
import {
|
||||||
@@ -54,6 +55,7 @@ interface ThreadViewportProps {
|
|||||||
forkBoundaryMessageCount?: number | null;
|
forkBoundaryMessageCount?: number | null;
|
||||||
hasMoreBefore?: boolean;
|
hasMoreBefore?: boolean;
|
||||||
loadingOlder?: boolean;
|
loadingOlder?: boolean;
|
||||||
|
olderError?: string | null;
|
||||||
userMessageOffset?: number;
|
userMessageOffset?: number;
|
||||||
onLoadOlder?: () => Promise<void> | void;
|
onLoadOlder?: () => Promise<void> | void;
|
||||||
traceDetailScope?: string | null;
|
traceDetailScope?: string | null;
|
||||||
@@ -63,6 +65,7 @@ interface ThreadViewportProps {
|
|||||||
onQuoteSelection?: (text: string) => void;
|
onQuoteSelection?: (text: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const HISTORY_PULL_THRESHOLD_PX = 48;
|
||||||
const NEAR_BOTTOM_PX = 48;
|
const NEAR_BOTTOM_PX = 48;
|
||||||
const PROMPT_TOP_INSET_PX = 48;
|
const PROMPT_TOP_INSET_PX = 48;
|
||||||
const HISTORY_PREFETCH_MIN_PX = 160;
|
const HISTORY_PREFETCH_MIN_PX = 160;
|
||||||
@@ -245,6 +248,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
forkBoundaryMessageCount = null,
|
forkBoundaryMessageCount = null,
|
||||||
hasMoreBefore = false,
|
hasMoreBefore = false,
|
||||||
loadingOlder = false,
|
loadingOlder = false,
|
||||||
|
olderError = null,
|
||||||
userMessageOffset = 0,
|
userMessageOffset = 0,
|
||||||
onLoadOlder,
|
onLoadOlder,
|
||||||
traceDetailScope = null,
|
traceDetailScope = null,
|
||||||
@@ -273,6 +277,22 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
const composerInputScrollTopRef = useRef<number | null>(null);
|
const composerInputScrollTopRef = useRef<number | null>(null);
|
||||||
const composerDockHeightRef = useRef(0);
|
const composerDockHeightRef = useRef(0);
|
||||||
const [atBottom, setAtBottom] = useState(true);
|
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 [composerDockHeight, setComposerDockHeight] = useState(0);
|
||||||
const [keyboardInsetBottom, setKeyboardInsetBottom] = useState(0);
|
const [keyboardInsetBottom, setKeyboardInsetBottom] = useState(0);
|
||||||
const [hasVerticalOverflow, setHasVerticalOverflow] = useState(false);
|
const [hasVerticalOverflow, setHasVerticalOverflow] = useState(false);
|
||||||
@@ -469,9 +489,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
if (!el || !hasMessages || pendingConversationScrollRef.current) return;
|
if (!el || !hasMessages || pendingConversationScrollRef.current) return;
|
||||||
if (!threadMotionRef.current?.isBrowsingHistory()) return;
|
if (!threadMotionRef.current?.isBrowsingHistory()) return;
|
||||||
if (el.scrollTop > historyPrefetchDistance(el)) 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();
|
loadEarlierMessages();
|
||||||
}, [hasMessages, hasMoreBefore, hiddenMessageCount, loadEarlierMessages]);
|
}, [hasMessages, hasMoreBefore, hiddenMessageCount, loadEarlierMessages, olderError]);
|
||||||
|
|
||||||
const navigateToVisiblePrompt = useCallback((promptId: string) => {
|
const navigateToVisiblePrompt = useCallback((promptId: string) => {
|
||||||
const scrollEl = scrollRef.current;
|
const scrollEl = scrollRef.current;
|
||||||
@@ -738,6 +759,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
if (!el) return;
|
if (!el) return;
|
||||||
|
|
||||||
const onScroll = (allowHistoryLoad = true) => {
|
const onScroll = (allowHistoryLoad = true) => {
|
||||||
|
setNearHistoryTop(el.scrollTop <= historyPrefetchDistance(el));
|
||||||
|
if (el.scrollTop > 1) setHistoryPull(0);
|
||||||
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
|
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
|
||||||
const near = distance < NEAR_BOTTOM_PX;
|
const near = distance < NEAR_BOTTOM_PX;
|
||||||
const owner = threadMotionRef.current?.observeScroll(near) ?? "automatic";
|
const owner = threadMotionRef.current?.observeScroll(near) ?? "automatic";
|
||||||
@@ -755,10 +778,19 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
|
|
||||||
onScroll(false);
|
onScroll(false);
|
||||||
const handleScroll = () => onScroll(true);
|
const handleScroll = () => onScroll(true);
|
||||||
|
const canLoadAtTop = () => el.scrollTop <= 0 && hasMessages && conversationReady
|
||||||
|
&& !pendingConversationScrollRef.current && !loadingOlder
|
||||||
|
&& (hiddenMessageCount > 0 || (hasMoreBefore && !olderError));
|
||||||
const handleDirectionalInput = (
|
const handleDirectionalInput = (
|
||||||
direction: ThreadScrollDirection | null,
|
direction: ThreadScrollDirection | null,
|
||||||
) => {
|
) => {
|
||||||
if (!direction) return;
|
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(
|
threadMotionRef.current?.handleUserScrollIntent(
|
||||||
canScrollInDirection(el, direction),
|
canScrollInDirection(el, direction),
|
||||||
direction === "forward",
|
direction === "forward",
|
||||||
@@ -772,6 +804,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
historyInputRef.current = "other";
|
||||||
|
setHistoryPull(0);
|
||||||
handleDirectionalInput(directionFromDelta(event.deltaY));
|
handleDirectionalInput(directionFromDelta(event.deltaY));
|
||||||
};
|
};
|
||||||
const handlePointerDown = (event: PointerEvent) => {
|
const handlePointerDown = (event: PointerEvent) => {
|
||||||
@@ -782,21 +816,64 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
yieldCameraToUser();
|
yieldCameraToUser();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let lastTouchY: number | null = null;
|
const handleTouchCancel = () => {
|
||||||
|
historyTouchRef.current = null;
|
||||||
|
setHistoryPull(0);
|
||||||
|
};
|
||||||
const handleTouchStart = (event: TouchEvent) => {
|
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 handleTouchMove = (event: TouchEvent) => {
|
||||||
const currentY = event.touches[0]?.clientY;
|
const gesture = historyTouchRef.current;
|
||||||
const scrollDeltaY =
|
const touch = event.touches[0];
|
||||||
lastTouchY !== null && currentY !== undefined
|
if (event.touches.length !== 1) {
|
||||||
? lastTouchY - currentY
|
handleTouchCancel();
|
||||||
: 0;
|
return;
|
||||||
lastTouchY = currentY ?? null;
|
}
|
||||||
handleDirectionalInput(directionFromDelta(scrollDeltaY));
|
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 = () => {
|
const handleTouchEnd = () => {
|
||||||
lastTouchY = null;
|
historyTouchRef.current = null;
|
||||||
|
if (!loadingOlder) setHistoryPull(0);
|
||||||
};
|
};
|
||||||
const handleKeyDown = (event: KeyboardEvent) => {
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
if (
|
if (
|
||||||
@@ -816,14 +893,16 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (isKeyboardControl(event.target as Element | null)) return;
|
if (isKeyboardControl(event.target as Element | null)) return;
|
||||||
|
historyInputRef.current = "other";
|
||||||
|
setHistoryPull(0);
|
||||||
handleDirectionalInput(keyboardScrollDirection(event));
|
handleDirectionalInput(keyboardScrollDirection(event));
|
||||||
};
|
};
|
||||||
el.addEventListener("scroll", handleScroll, { passive: true });
|
el.addEventListener("scroll", handleScroll, { passive: true });
|
||||||
el.addEventListener("wheel", handleWheel, { passive: true });
|
el.addEventListener("wheel", handleWheel, { passive: true });
|
||||||
el.addEventListener("touchstart", handleTouchStart, { 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("touchend", handleTouchEnd, { passive: true });
|
||||||
el.addEventListener("touchcancel", handleTouchEnd, { passive: true });
|
el.addEventListener("touchcancel", handleTouchCancel, { passive: true });
|
||||||
el.addEventListener("pointerdown", handlePointerDown);
|
el.addEventListener("pointerdown", handlePointerDown);
|
||||||
el.addEventListener("keydown", handleKeyDown);
|
el.addEventListener("keydown", handleKeyDown);
|
||||||
return () => {
|
return () => {
|
||||||
@@ -832,14 +911,20 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
el.removeEventListener("touchstart", handleTouchStart);
|
el.removeEventListener("touchstart", handleTouchStart);
|
||||||
el.removeEventListener("touchmove", handleTouchMove);
|
el.removeEventListener("touchmove", handleTouchMove);
|
||||||
el.removeEventListener("touchend", handleTouchEnd);
|
el.removeEventListener("touchend", handleTouchEnd);
|
||||||
el.removeEventListener("touchcancel", handleTouchEnd);
|
el.removeEventListener("touchcancel", handleTouchCancel);
|
||||||
el.removeEventListener("pointerdown", handlePointerDown);
|
el.removeEventListener("pointerdown", handlePointerDown);
|
||||||
el.removeEventListener("keydown", handleKeyDown);
|
el.removeEventListener("keydown", handleKeyDown);
|
||||||
};
|
};
|
||||||
}, [
|
}, [
|
||||||
captureHistoryScrollAnchor,
|
captureHistoryScrollAnchor,
|
||||||
|
conversationReady,
|
||||||
hasMessages,
|
hasMessages,
|
||||||
|
hasMoreBefore,
|
||||||
|
hiddenMessageCount,
|
||||||
|
loadingOlder,
|
||||||
|
loadEarlierMessages,
|
||||||
maybeLoadEarlierFromScroll,
|
maybeLoadEarlierFromScroll,
|
||||||
|
olderError,
|
||||||
yieldCameraToUser,
|
yieldCameraToUser,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -875,9 +960,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
<div
|
<div
|
||||||
ref={messageRegionRef}
|
ref={messageRegionRef}
|
||||||
data-testid="thread-message-region"
|
data-testid="thread-message-region"
|
||||||
|
style={{ transform: historyPull > 0 ? `translateY(${historyPull}px)` : undefined }}
|
||||||
className={cn(
|
className={cn(
|
||||||
"thread-message-viewport thread-viewport-scrollbar row-start-1 flex min-h-0 min-w-0 flex-col",
|
"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]",
|
"[overflow-anchor:none] [scrollbar-width:none]",
|
||||||
"[&::-webkit-scrollbar]:hidden",
|
"[&::-webkit-scrollbar]:hidden",
|
||||||
hasVerticalOverflow ? "overflow-y-auto" : "overflow-hidden",
|
hasVerticalOverflow ? "overflow-y-auto" : "overflow-hidden",
|
||||||
@@ -972,6 +1058,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</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}
|
{!hasMessages ? <div ref={bottomRef} aria-hidden className="h-px" /> : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -138,6 +138,7 @@ interface SessionHistoryState {
|
|||||||
messages: UIMessage[];
|
messages: UIMessage[];
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
loadingOlder: boolean;
|
loadingOlder: boolean;
|
||||||
|
olderError: string | null;
|
||||||
error: string | null;
|
error: string | null;
|
||||||
hasPendingToolCalls: boolean;
|
hasPendingToolCalls: boolean;
|
||||||
completedTurnIds: string[];
|
completedTurnIds: string[];
|
||||||
@@ -157,6 +158,7 @@ function emptyHistoryState(key: string | null, loading = false): SessionHistoryS
|
|||||||
messages: [],
|
messages: [],
|
||||||
loading,
|
loading,
|
||||||
loadingOlder: false,
|
loadingOlder: false,
|
||||||
|
olderError: null,
|
||||||
error: null,
|
error: null,
|
||||||
hasPendingToolCalls: false,
|
hasPendingToolCalls: false,
|
||||||
completedTurnIds: [],
|
completedTurnIds: [],
|
||||||
@@ -183,6 +185,7 @@ function cachedHistoryState(
|
|||||||
messages,
|
messages,
|
||||||
loading: false,
|
loading: false,
|
||||||
loadingOlder: false,
|
loadingOlder: false,
|
||||||
|
olderError: null,
|
||||||
error: null,
|
error: null,
|
||||||
hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages),
|
hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages),
|
||||||
completedTurnIds: completedTurnIdsFromThread(body),
|
completedTurnIds: completedTurnIdsFromThread(body),
|
||||||
@@ -384,6 +387,7 @@ export function useSessionHistory(key: string | null): {
|
|||||||
messages: UIMessage[];
|
messages: UIMessage[];
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
loadingOlder: boolean;
|
loadingOlder: boolean;
|
||||||
|
olderError: string | null;
|
||||||
error: string | null;
|
error: string | null;
|
||||||
refresh: () => void;
|
refresh: () => void;
|
||||||
loadOlder: () => Promise<void>;
|
loadOlder: () => Promise<void>;
|
||||||
@@ -492,6 +496,10 @@ export function useSessionHistory(key: string | null): {
|
|||||||
messages: merged.messages,
|
messages: merged.messages,
|
||||||
loading: false,
|
loading: false,
|
||||||
loadingOlder: false,
|
loadingOlder: false,
|
||||||
|
olderError: merged.continuity === "overlap"
|
||||||
|
&& (retainedPrefix || prev.beforeCursor === body?.page?.before_cursor)
|
||||||
|
? prev.olderError
|
||||||
|
: null,
|
||||||
error: null,
|
error: null,
|
||||||
hasPendingToolCalls: hasPending,
|
hasPendingToolCalls: hasPending,
|
||||||
completedTurnIds,
|
completedTurnIds,
|
||||||
@@ -532,6 +540,7 @@ export function useSessionHistory(key: string | null): {
|
|||||||
messages: [],
|
messages: [],
|
||||||
loading: false,
|
loading: false,
|
||||||
loadingOlder: false,
|
loadingOlder: false,
|
||||||
|
olderError: null,
|
||||||
error: null,
|
error: null,
|
||||||
hasPendingToolCalls: false,
|
hasPendingToolCalls: false,
|
||||||
completedTurnIds: [],
|
completedTurnIds: [],
|
||||||
@@ -573,7 +582,7 @@ export function useSessionHistory(key: string | null): {
|
|||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
olderRequestAbortRef.current = controller;
|
olderRequestAbortRef.current = controller;
|
||||||
setState((prev) => matchesRequest(prev)
|
setState((prev) => matchesRequest(prev)
|
||||||
? { ...prev, loadingOlder: true, error: null }
|
? { ...prev, loadingOlder: true, olderError: null }
|
||||||
: prev);
|
: prev);
|
||||||
try {
|
try {
|
||||||
const body = await fetchWebuiThread(getToken(), requestKey, {
|
const body = await fetchWebuiThread(getToken(), requestKey, {
|
||||||
@@ -604,7 +613,7 @@ export function useSessionHistory(key: string | null): {
|
|||||||
...prev,
|
...prev,
|
||||||
messages: nextMessages,
|
messages: nextMessages,
|
||||||
loadingOlder: false,
|
loadingOlder: false,
|
||||||
error: null,
|
olderError: null,
|
||||||
forkBoundaryMessageCount: olderBoundary ?? shiftedBoundary,
|
forkBoundaryMessageCount: olderBoundary ?? shiftedBoundary,
|
||||||
beforeCursor: body.page?.before_cursor ?? null,
|
beforeCursor: body.page?.before_cursor ?? null,
|
||||||
hasMoreBefore: body.page?.has_more_before === true,
|
hasMoreBefore: body.page?.has_more_before === true,
|
||||||
@@ -617,7 +626,7 @@ export function useSessionHistory(key: string | null): {
|
|||||||
? {
|
? {
|
||||||
...prev,
|
...prev,
|
||||||
loadingOlder: false,
|
loadingOlder: false,
|
||||||
error: (e as Error).message,
|
olderError: (e as Error).message || "Could not load earlier messages",
|
||||||
}
|
}
|
||||||
: prev);
|
: prev);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -640,6 +649,7 @@ export function useSessionHistory(key: string | null): {
|
|||||||
messages: EMPTY_MESSAGES,
|
messages: EMPTY_MESSAGES,
|
||||||
loading: false,
|
loading: false,
|
||||||
loadingOlder: false,
|
loadingOlder: false,
|
||||||
|
olderError: null,
|
||||||
error: null,
|
error: null,
|
||||||
refresh,
|
refresh,
|
||||||
loadOlder,
|
loadOlder,
|
||||||
@@ -662,6 +672,7 @@ export function useSessionHistory(key: string | null): {
|
|||||||
messages: EMPTY_MESSAGES,
|
messages: EMPTY_MESSAGES,
|
||||||
loading: true,
|
loading: true,
|
||||||
loadingOlder: false,
|
loadingOlder: false,
|
||||||
|
olderError: null,
|
||||||
error: null,
|
error: null,
|
||||||
refresh,
|
refresh,
|
||||||
loadOlder,
|
loadOlder,
|
||||||
@@ -681,6 +692,7 @@ export function useSessionHistory(key: string | null): {
|
|||||||
messages: state.messages,
|
messages: state.messages,
|
||||||
loading: state.loading,
|
loading: state.loading,
|
||||||
loadingOlder: state.loadingOlder,
|
loadingOlder: state.loadingOlder,
|
||||||
|
olderError: state.olderError,
|
||||||
error: state.error,
|
error: state.error,
|
||||||
refresh,
|
refresh,
|
||||||
loadOlder,
|
loadOlder,
|
||||||
|
|||||||
@@ -1815,6 +1815,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "Scroll to bottom",
|
"scrollToBottom": "Scroll to bottom",
|
||||||
"loadEarlier": "Load earlier messages",
|
"loadEarlier": "Load earlier messages",
|
||||||
|
"history": {
|
||||||
|
"loading": "Loading earlier messages…",
|
||||||
|
"error": "Loading failed.",
|
||||||
|
"retry": "Retry"
|
||||||
|
},
|
||||||
"forkedFromHistory": "Forked from history",
|
"forkedFromHistory": "Forked from history",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "Open prompt navigator",
|
"open": "Open prompt navigator",
|
||||||
|
|||||||
@@ -1616,6 +1616,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "Desplazarse al final",
|
"scrollToBottom": "Desplazarse al final",
|
||||||
"loadEarlier": "Cargar mensajes anteriores",
|
"loadEarlier": "Cargar mensajes anteriores",
|
||||||
|
"history": {
|
||||||
|
"loading": "Cargando mensajes anteriores…",
|
||||||
|
"error": "Error al cargar.",
|
||||||
|
"retry": "Reintentar"
|
||||||
|
},
|
||||||
"forkedFromHistory": "Bifurcado desde el historial",
|
"forkedFromHistory": "Bifurcado desde el historial",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "Abrir el navegador de instrucciones",
|
"open": "Abrir el navegador de instrucciones",
|
||||||
|
|||||||
@@ -1615,6 +1615,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "Faire défiler vers le bas",
|
"scrollToBottom": "Faire défiler vers le bas",
|
||||||
"loadEarlier": "Charger les messages précédents",
|
"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",
|
"forkedFromHistory": "Bifurqué depuis l'historique",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "Ouvrir le navigateur d’instructions",
|
"open": "Ouvrir le navigateur d’instructions",
|
||||||
|
|||||||
@@ -1615,6 +1615,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "Gulir ke bawah",
|
"scrollToBottom": "Gulir ke bawah",
|
||||||
"loadEarlier": "Muat pesan sebelumnya",
|
"loadEarlier": "Muat pesan sebelumnya",
|
||||||
|
"history": {
|
||||||
|
"loading": "Memuat pesan sebelumnya…",
|
||||||
|
"error": "Gagal memuat.",
|
||||||
|
"retry": "Coba lagi"
|
||||||
|
},
|
||||||
"forkedFromHistory": "Cabang dari riwayat",
|
"forkedFromHistory": "Cabang dari riwayat",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "Buka navigasi instruksi",
|
"open": "Buka navigasi instruksi",
|
||||||
|
|||||||
@@ -1615,6 +1615,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "一番下へスクロール",
|
"scrollToBottom": "一番下へスクロール",
|
||||||
"loadEarlier": "以前のメッセージを読み込む",
|
"loadEarlier": "以前のメッセージを読み込む",
|
||||||
|
"history": {
|
||||||
|
"loading": "以前のメッセージを読み込み中…",
|
||||||
|
"error": "読み込みに失敗しました。",
|
||||||
|
"retry": "再試行"
|
||||||
|
},
|
||||||
"forkedFromHistory": "履歴から分岐",
|
"forkedFromHistory": "履歴から分岐",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "プロンプトナビゲーターを開く",
|
"open": "プロンプトナビゲーターを開く",
|
||||||
|
|||||||
@@ -1615,6 +1615,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "맨 아래로 스크롤",
|
"scrollToBottom": "맨 아래로 스크롤",
|
||||||
"loadEarlier": "이전 메시지 불러오기",
|
"loadEarlier": "이전 메시지 불러오기",
|
||||||
|
"history": {
|
||||||
|
"loading": "이전 메시지를 불러오는 중…",
|
||||||
|
"error": "불러오지 못했습니다.",
|
||||||
|
"retry": "다시 시도"
|
||||||
|
},
|
||||||
"forkedFromHistory": "기록에서 분기됨",
|
"forkedFromHistory": "기록에서 분기됨",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "프롬프트 탐색기 열기",
|
"open": "프롬프트 탐색기 열기",
|
||||||
|
|||||||
@@ -1629,6 +1629,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "Rolar para o final",
|
"scrollToBottom": "Rolar para o final",
|
||||||
"loadEarlier": "Carregar mensagens anteriores",
|
"loadEarlier": "Carregar mensagens anteriores",
|
||||||
|
"history": {
|
||||||
|
"loading": "Carregando mensagens anteriores…",
|
||||||
|
"error": "Falha ao carregar.",
|
||||||
|
"retry": "Tentar novamente"
|
||||||
|
},
|
||||||
"forkedFromHistory": "Bifurcado a partir do histórico",
|
"forkedFromHistory": "Bifurcado a partir do histórico",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "Abrir navegador de instruções",
|
"open": "Abrir navegador de instruções",
|
||||||
|
|||||||
@@ -1615,6 +1615,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "Cuộn xuống cuối",
|
"scrollToBottom": "Cuộn xuống cuối",
|
||||||
"loadEarlier": "Tải tin nhắn trước đó",
|
"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ử",
|
"forkedFromHistory": "Tách nhánh từ lịch sử",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "Mở trình điều hướng lời nhắc",
|
"open": "Mở trình điều hướng lời nhắc",
|
||||||
|
|||||||
@@ -1815,6 +1815,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "滚动到底部",
|
"scrollToBottom": "滚动到底部",
|
||||||
"loadEarlier": "加载更早消息",
|
"loadEarlier": "加载更早消息",
|
||||||
|
"history": {
|
||||||
|
"loading": "正在加载更早的消息…",
|
||||||
|
"error": "加载失败",
|
||||||
|
"retry": "重试"
|
||||||
|
},
|
||||||
"forkedFromHistory": "从历史消息分叉",
|
"forkedFromHistory": "从历史消息分叉",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "打开提示词导航",
|
"open": "打开提示词导航",
|
||||||
|
|||||||
@@ -1615,6 +1615,11 @@
|
|||||||
},
|
},
|
||||||
"scrollToBottom": "捲動到底部",
|
"scrollToBottom": "捲動到底部",
|
||||||
"loadEarlier": "載入更早訊息",
|
"loadEarlier": "載入更早訊息",
|
||||||
|
"history": {
|
||||||
|
"loading": "正在載入更早的訊息…",
|
||||||
|
"error": "載入失敗",
|
||||||
|
"retry": "重試"
|
||||||
|
},
|
||||||
"forkedFromHistory": "從歷史訊息建立分支",
|
"forkedFromHistory": "從歷史訊息建立分支",
|
||||||
"promptNavigator": {
|
"promptNavigator": {
|
||||||
"open": "開啟提示詞導覽",
|
"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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -40,6 +40,23 @@ function dispatchUserScroll(scroller: HTMLElement): void {
|
|||||||
scroller.dispatchEvent(new Event("scroll"));
|
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 {
|
interface ResizeObserverInstance {
|
||||||
elements: Element[];
|
elements: Element[];
|
||||||
callback: ResizeObserverCallback;
|
callback: ResizeObserverCallback;
|
||||||
@@ -920,7 +937,7 @@ describe("ThreadViewport", () => {
|
|||||||
|
|
||||||
followTo.mockClear();
|
followTo.mockClear();
|
||||||
act(() => {
|
act(() => {
|
||||||
fireEvent.touchStart(scroller, { touches: [{ clientY: 300 }] });
|
fireEvent.touchStart(scroller, { touches: [{ clientX: 100, clientY: 300 }] });
|
||||||
fireEvent.touchMove(scroller, { touches: [{ clientY: 324 }] });
|
fireEvent.touchMove(scroller, { touches: [{ clientY: 324 }] });
|
||||||
scroller.scrollTop = 1_380;
|
scroller.scrollTop = 1_380;
|
||||||
scroller.dispatchEvent(new Event("scroll"));
|
scroller.dispatchEvent(new Event("scroll"));
|
||||||
@@ -931,7 +948,7 @@ describe("ThreadViewport", () => {
|
|||||||
expect(screen.getByRole("button", { name: "Scroll to bottom" })).toBeInTheDocument();
|
expect(screen.getByRole("button", { name: "Scroll to bottom" })).toBeInTheDocument();
|
||||||
|
|
||||||
act(() => {
|
act(() => {
|
||||||
fireEvent.touchMove(scroller, { touches: [{ clientY: 300 }] });
|
fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 300 }] });
|
||||||
scroller.scrollTop = 1_404;
|
scroller.scrollTop = 1_404;
|
||||||
scroller.dispatchEvent(new Event("scroll"));
|
scroller.dispatchEvent(new Event("scroll"));
|
||||||
fireEvent.touchEnd(scroller);
|
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", () => {
|
it("automatically requests older transcript pages near the top", () => {
|
||||||
const onLoadOlder = vi.fn();
|
const onLoadOlder = vi.fn();
|
||||||
|
|
||||||
@@ -1653,11 +1703,7 @@ describe("ThreadViewport", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const scroller = getScroller(container);
|
const scroller = getScroller(container);
|
||||||
Object.defineProperties(scroller, {
|
mockScrollGeometry(scroller, 1800, 600);
|
||||||
scrollHeight: { configurable: true, value: 1800 },
|
|
||||||
clientHeight: { configurable: true, value: 600 },
|
|
||||||
scrollTop: { configurable: true, writable: true, value: 0 },
|
|
||||||
});
|
|
||||||
|
|
||||||
act(() => {
|
act(() => {
|
||||||
dispatchUserScroll(scroller);
|
dispatchUserScroll(scroller);
|
||||||
@@ -1666,6 +1712,112 @@ describe("ThreadViewport", () => {
|
|||||||
expect(onLoadOlder).toHaveBeenCalledTimes(1);
|
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 () => {
|
it("renders a prompt rail that jumps to user messages", async () => {
|
||||||
const navigateTo = vi.spyOn(ThreadCameraController.prototype, "navigateTo")
|
const navigateTo = vi.spyOn(ThreadCameraController.prototype, "navigateTo")
|
||||||
.mockReturnValue("started");
|
.mockReturnValue("started");
|
||||||
@@ -1753,8 +1905,8 @@ describe("ThreadViewport", () => {
|
|||||||
expect(cancel).toHaveBeenCalledTimes(1);
|
expect(cancel).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
restartNavigation();
|
restartNavigation();
|
||||||
fireEvent.touchStart(scroller, { touches: [{ clientY: 300 }] });
|
fireEvent.touchStart(scroller, { touches: [{ clientX: 100, clientY: 300 }] });
|
||||||
fireEvent.touchMove(scroller, { touches: [{ clientY: 200 }] });
|
fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 200 }] });
|
||||||
expect(cancel).toHaveBeenCalledTimes(1);
|
expect(cancel).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
restartNavigation();
|
restartNavigation();
|
||||||
|
|||||||
@@ -990,6 +990,88 @@ describe("useSessions", () => {
|
|||||||
expect(result.current.continuity).toBe("initial");
|
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 () => {
|
it("aborts an older-history request when the consumer unmounts", async () => {
|
||||||
let olderSignal: AbortSignal | undefined;
|
let olderSignal: AbortSignal | undefined;
|
||||||
vi.mocked(api.fetchWebuiThread)
|
vi.mocked(api.fetchWebuiThread)
|
||||||
|
|||||||
Reference in new issue
Block a user