fix(webui): add spring feedback at the history boundary (#6322)

* fix(webui): add spring feedback at the history boundary

Refs NAN-287.

* fix(webui): refine history boundary states and retry feedback

* fix(webui): share history loading states with subagents
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-20 15:32:21 +08:00
1 parent a1bca7dc50
commit 816c9221a0
27 files changed
+910 -209

No files matched your search

@@ -11,7 +11,7 @@ interface SubagentThreadProps {
}
export function SubagentThread({ token, sessionKey, task, historyEnabled, isStreaming }: SubagentThreadProps) {
const { messages, loading, failed, activeTurnId, retry } = useSubagentThread({ token, sessionKey, task, historyEnabled });
return <SubagentThreadView messages={messages} loading={loading} failed={failed} isStreaming={isStreaming}
const { messages, loading, error, activeTurnId, retry } = useSubagentThread({ token, sessionKey, task, historyEnabled });
return <SubagentThreadView messages={messages} loading={loading} error={error} isStreaming={isStreaming}
activeTurnId={activeTurnId} runStartedAt={task.created_at} onRetry={retry} />;
}
@@ -1,27 +1,18 @@
import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { Button } from "@/components/ui/button";
import type { UIMessage } from "@/lib/types";
export function SubagentThreadView({ messages, loading, failed, isStreaming, activeTurnId, runStartedAt, onRetry }: {
export function SubagentThreadView({ messages, loading, error, isStreaming, activeTurnId, runStartedAt, onRetry }: {
messages: UIMessage[];
loading: boolean;
failed: boolean;
error: string | null;
isStreaming: boolean;
activeTurnId?: string | null;
runStartedAt: number;
onRetry: () => void;
}) {
const { t } = useTranslation();
return <>
{failed ? <div role="alert" className="mb-4 flex items-center gap-2 px-5 text-sm text-destructive">
<span>{t("thread.history.error")}</span>
<Button type="button" variant="ghost" size="sm" onClick={onRetry}>{t("thread.history.retry")}</Button>
</div> : loading ? <p role="status" className="flex items-center gap-2 px-5 text-sm text-muted-foreground">
<LoaderCircle className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />{t("chat.loading")}
</p> : null}
{loading || error ? <ThreadHistoryStatus className="relative" loading={loading} error={error} onRetry={onRetry} /> : null}
<ThreadMessages messages={messages} isStreaming={isStreaming} activeTurnId={activeTurnId} runStartedAt={runStartedAt} />
</>;
}
@@ -1,61 +1,51 @@
import { useEffect, useState } from "react";
import { Loader2, RotateCcw } from "lucide-react";
import { forwardRef } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { HoverHint } from "@/components/ui/hover-hint";
import { cn } from "@/lib/utils";
interface ThreadHistoryStatusProps {
loading: boolean;
error: string | null;
pullDistance?: number;
exhausted?: boolean;
onRetry: () => void;
className?: string;
}
export function ThreadHistoryStatus({ loading, error, onRetry, pullDistance = 0 }: ThreadHistoryStatusProps) {
export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatusProps>(function ThreadHistoryStatus({ loading, error, exhausted = false, onRetry, className }, ref) {
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]);
const state = !loading && error ? "error" : !loading && exhausted ? "exhausted" : "loading";
const label = t(state === "error" ? "thread.history.retryLabel" : `thread.history.${state}`);
// Blocks adapted from loading.dev (MIT); see THIRD_PARTY_NOTICES.md.
const blocks = <span aria-hidden="true" className="thread-history-blocks">
{Array.from({ length: 9 }, (_, index) => <span key={index}
style={{ animationDelay: `${(index % 3 + Math.floor(index / 3) - 5) * 260}ms` }} />)}
</span>;
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 }}
ref={ref}
className={cn("thread-history-status thread-message-row pointer-events-none absolute inset-x-0 top-0 z-10 flex items-center justify-center", className)}
data-state={state}
>
<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}
{state === "exhausted" ? (
<span className="text-xs">{label}</span>
) : (
<HoverHint content={state === "error" ? error : label} side="bottom">
{loading ? (
<div tabIndex={0} aria-label={label} className="thread-history-control pointer-events-auto rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring">
{blocks}<span className="sr-only">{label}</span>
</div>
) : (
<button type="button" aria-label={state === "error" ? label : t("thread.loadEarlier")} onClick={onRetry}
className="thread-history-control pointer-events-auto rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring">
{blocks}<span className="sr-only">{label}</span>
</button>
)}
</HoverHint>
)}
</div>
</div>
);
}
});
+87 -52
View File
@@ -18,6 +18,7 @@ import { DiagramScope } from "@/components/markdown-diagrams/context";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
import { ThreadCameraController } from "@/components/thread/thread-camera";
import { ThreadHistorySpring } from "@/components/thread/thread-history-spring";
import {
ThreadMotionCoordinator,
type ThreadMotionGeometry,
@@ -69,7 +70,6 @@ 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;
@@ -235,6 +235,10 @@ function readSoftKeyboardInsetBottom(container: HTMLElement | null): number {
return inset >= SOFT_KEYBOARD_MIN_INSET_PX ? Math.ceil(inset) : 0;
}
function setHistoryStatusTravel(element: HTMLDivElement | null, distance: number): void {
element?.style.setProperty("--history-pull", `${distance}px`);
}
export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProps>(function ThreadViewport({
messages: latestMessages,
navigation,
@@ -280,7 +284,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const scrollRef = useRef<HTMLDivElement | null>(null);
const viewportFrameRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const messageRegionRef = useRef<HTMLDivElement>(null);
const messageRegionRef = useRef<HTMLDivElement | null>(null);
const messageContentRef = useRef<HTMLDivElement>(null);
const emptyStateRef = useRef<HTMLDivElement>(null);
const composerDockRef = useRef<HTMLDivElement>(null);
@@ -296,22 +300,38 @@ 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 [atHistoryTop, setAtHistoryTop] = useState(false);
const historyInputRef = useRef<"touch" | "other">("other");
const historyTouchRef = useRef<{
lastY: number; startX: number; startY: number | null; triggered: boolean;
lastY: number; startX: number; startY: number; pulling: boolean; horizontal: boolean;
} | null>(null);
const historyDistanceRef = useRef(0);
const historyStatusRef = useRef<HTMLDivElement | null>(null);
const historySpringRef = useRef<ThreadHistorySpring | null>(null);
if (historySpringRef.current === null) {
historySpringRef.current = new ThreadHistorySpring({
onUpdate: (distance) => {
// Presentation travel never becomes a scrollTop destination or an anchor correction.
historyDistanceRef.current = distance;
if (messageRegionRef.current) {
messageRegionRef.current.style.transform = distance > 0 ? `translateY(${distance}px)` : "";
}
// Keep animated custom properties out of the inherited message tree.
setHistoryStatusTravel(historyStatusRef.current, distance);
},
});
}
useEffect(() => {
if (!loadingOlder || olderError || !hasMoreBefore) setHistoryPull(0);
}, [loadingOlder, olderError, hasMoreBefore]);
useEffect(() => {
historyTouchRef.current = null;
historyInputRef.current = "other";
setHistoryPull(0);
}, [conversationKey]);
const setMessageRegion = useCallback((element: HTMLDivElement | null) => {
// React can reuse this div for the empty state; release imperative styles with the ref.
messageRegionRef.current?.style.removeProperty("transform");
messageRegionRef.current = element;
if (element && historyDistanceRef.current > 0) element.style.transform = `translateY(${historyDistanceRef.current}px)`;
}, []);
const setHistoryStatus = useCallback((element: HTMLDivElement | null) => {
historyStatusRef.current = element;
setHistoryStatusTravel(element, historyDistanceRef.current);
}, []);
const [composerDockHeight, setComposerDockHeight] = useState(0);
const [keyboardInsetBottom, setKeyboardInsetBottom] = useState(0);
const [hasVerticalOverflow, setHasVerticalOverflow] = useState(false);
@@ -367,6 +387,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
? messageRegionRef.current
: viewportFrameRef.current;
}, [hasMessages]);
useLayoutEffect(() => {
const scroller = scrollRef.current;
historySpringRef.current?.setLoading(Boolean(conversationReady && scroller && loadingOlder && !olderError && scroller.scrollTop <= 1));
}, [conversationKey, conversationReady, hasMessages, loadingOlder, olderError]);
const visibleMessages = useMemo(
() => windowMessages(messages, visibleMessageCount),
[messages, visibleMessageCount],
@@ -623,6 +647,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
useLayoutEffect(() => {
if (lastConversationKeyRef.current === conversationKey) return;
lastConversationKeyRef.current = conversationKey;
historyTouchRef.current = null;
historyInputRef.current = "other";
historySpringRef.current?.reset();
conversationHandoffAnimationRef.current?.cancel();
conversationHandoffAnimationRef.current = null;
conversationHandoffPendingRef.current = true;
@@ -769,6 +796,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
useEffect(() => () => {
conversationHandoffAnimationRef.current?.cancel();
historySpringRef.current?.reset();
threadMotionRef.current?.dispose();
}, []);
@@ -808,8 +836,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
if (!el) return;
const onScroll = (allowHistoryLoad = true) => {
setNearHistoryTop(el.scrollTop <= historyPrefetchDistance(el));
if (el.scrollTop > 1) setHistoryPull(0);
setAtHistoryTop(el.scrollTop <= 1);
if (el.scrollTop > 1) historySpringRef.current?.leaveBoundary();
else historySpringRef.current?.setLoading(conversationReady && loadingOlder && !olderError);
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
const near = distance < NEAR_BOTTOM_PX;
const owner = threadMotionRef.current?.observeScroll(near) ?? "automatic";
@@ -829,8 +858,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
onScroll(false);
const handleScroll = () => onScroll(true);
const canLoadAtTop = () => el.scrollTop <= 0 && hasMessages && conversationReady
&& !pendingConversationScrollRef.current && !loadingOlder
const atHistoryBoundary = () => el.scrollTop <= 1 && messages.length > 0 && conversationReady
&& !pendingConversationScrollRef.current;
const canLoadAtTop = () => atHistoryBoundary() && !loadingOlder
&& (hiddenMessageCount > 0 || (hasMoreBefore && !olderError));
const handleDirectionalInput = (
direction: ThreadScrollDirection | null,
@@ -862,7 +892,18 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
return;
}
historyInputRef.current = "other";
setHistoryPull(0);
if (atHistoryBoundary()) {
const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? 16
: event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? el.clientHeight : 1;
if (event.deltaY < 0) {
yieldCameraToUser();
setAtHistoryTop(true);
const first = historySpringRef.current?.wheel(-event.deltaY * unit);
if (first && canLoadAtTop()) loadEarlierMessages();
return;
}
if (historyDistanceRef.current > 0) historySpringRef.current?.wheel(-event.deltaY * unit);
}
handleDirectionalInput(directionFromDelta(event.deltaY));
};
const handlePointerDown = (event: PointerEvent) => {
@@ -875,7 +916,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
};
const handleTouchCancel = () => {
historyTouchRef.current = null;
setHistoryPull(0);
historySpringRef.current?.endTouch(true);
};
const handleTouchStart = (event: TouchEvent) => {
historyInputRef.current = "touch";
@@ -884,8 +925,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
? {
lastY: touch.clientY,
startX: touch.clientX,
startY: el.scrollTop <= 0 ? touch.clientY : null,
triggered: false,
startY: touch.clientY,
pulling: false,
horizontal: false,
}
: null;
};
@@ -899,29 +941,21 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
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();
const horizontalTravel = Math.abs(touch.clientX - gesture.startX);
const verticalTravel = Math.abs(touch.clientY - gesture.startY);
if (!gesture.pulling && horizontalTravel > verticalTravel) gesture.horizontal = true;
if (gesture.horizontal) return;
if (gesture.pulling || (atHistoryBoundary() && delta < 0 && hiddenMessageCount === 0)) {
if (!gesture.pulling) {
historySpringRef.current?.startTouch();
gesture.pulling = true;
}
if (event.cancelable) event.preventDefault();
yieldCameraToUser();
historySpringRef.current?.moveTouch(-delta);
setAtHistoryTop(true);
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(
@@ -929,8 +963,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
);
};
const handleTouchEnd = () => {
const pulling = historyTouchRef.current?.pulling;
historyTouchRef.current = null;
if (!loadingOlder) setHistoryPull(0);
if (historySpringRef.current?.endTouch() && pulling && canLoadAtTop()) loadEarlierMessages();
};
const handleKeyDown = (event: KeyboardEvent) => {
if (
@@ -951,7 +986,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}
if (isKeyboardControl(event.target as Element | null)) return;
historyInputRef.current = "other";
setHistoryPull(0);
historySpringRef.current?.leaveBoundary();
handleDirectionalInput(keyboardScrollDirection(event));
};
el.addEventListener("scroll", handleScroll, { passive: true });
@@ -981,6 +1016,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
loadingOlder,
loadEarlierMessages,
maybeLoadEarlierFromScroll,
messages.length,
olderError,
yieldCameraToUser,
historyWindow,
@@ -1017,12 +1053,11 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
>
{hasMessages ? (
<div
ref={messageRegionRef}
ref={setMessageRegion}
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 overscroll-y-contain pb-0 pt-12",
"scroll-auto justify-start overflow-x-hidden overscroll-y-none pb-0 pt-12",
"[overflow-anchor:none] [scrollbar-width:none]",
"[&::-webkit-scrollbar]:hidden",
hasVerticalOverflow ? "overflow-y-auto" : "overflow-hidden",
@@ -1120,12 +1155,12 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
) : null}
</div>
{navigation && (navigation.loading || navigation.error) ? (
<ThreadHistoryStatus loading={navigation.loading} error={navigation.error} onRetry={navigation.retry} />
) : hasMessages && conversationReady && nearHistoryTop && hasMoreBefore ? (
<ThreadHistoryStatus ref={setHistoryStatus} loading={navigation.loading} error={navigation.error} onRetry={navigation.retry} />
) : messages.length > 0 && conversationReady && (atHistoryTop || loadingOlder || olderError) ? (
<ThreadHistoryStatus
key={conversationKey}
ref={setHistoryStatus}
loading={loadingOlder}
pullDistance={historyPull}
exhausted={!hasMoreBefore && hiddenMessageCount === 0}
error={olderError}
onRetry={loadEarlierMessages}
/>
@@ -0,0 +1,163 @@
import type { ThreadCameraScheduler } from "@/components/thread/thread-camera";
export const HISTORY_PULL_LIMIT_PX = 80;
export const HISTORY_PULL_TRIGGER_PX = 42;
const LOADING_POCKET_PX = 20;
const RESISTANCE_LENGTH_PX = 120;
const FREQUENCY = 22;
const DAMPING_RATIO = 0.78;
interface HistorySpringOptions {
onUpdate: (distance: number) => void;
scheduler?: ThreadCameraScheduler;
prefersReducedMotion?: () => boolean;
}
/** Presentation only: the thread camera remains the sole scroll-position owner. */
export class ThreadHistorySpring {
private readonly options: HistorySpringOptions;
private readonly scheduler: ThreadCameraScheduler;
private readonly reducedMotion: () => boolean;
private frame: number | null = null;
private timestamp: number | null = null;
private distance = 0;
private velocity = 0;
private loading = false;
private dragging = false;
private travel = 0;
private wheelLatched = false;
constructor(options: HistorySpringOptions) {
this.options = options;
this.scheduler = options.scheduler ?? {
request: (callback) => window.requestAnimationFrame(callback),
cancel: (id) => window.cancelAnimationFrame(id),
now: () => performance.now(),
};
const motionPreference = typeof window !== "undefined" && typeof window.matchMedia === "function"
? window.matchMedia("(prefers-reduced-motion: reduce)") : null;
this.reducedMotion = options.prefersReducedMotion ?? (() => motionPreference?.matches ?? false);
}
setLoading(loading: boolean): void {
if (this.loading === loading) return;
this.loading = loading;
if (!this.dragging) this.animate();
}
wheel(travel: number): boolean {
if (this.dragging) return false;
const first = !this.wheelLatched && travel > 0;
this.wheelLatched = true;
// Wheel packets add pressure to one live spring, without a position jump.
const speed = FREQUENCY * (travel > 0
? HISTORY_PULL_LIMIT_PX - Math.max(0, this.distance)
: -Math.max(0, this.distance));
this.velocity += (speed - this.velocity) * (1 - Math.exp(-Math.abs(travel) / RESISTANCE_LENGTH_PX));
this.animate();
return first;
}
startTouch(): void {
this.stopFrame();
this.dragging = true;
this.velocity = 0;
this.travel = -RESISTANCE_LENGTH_PX
* Math.log(Math.max(Number.EPSILON, 1 - Math.max(0, this.distance) / HISTORY_PULL_LIMIT_PX));
}
moveTouch(travel: number): void {
this.travel = Math.max(0, this.travel + travel);
this.distance = HISTORY_PULL_LIMIT_PX * (1 - Math.exp(-this.travel / RESISTANCE_LENGTH_PX));
this.publish();
}
endTouch(cancelled = false): boolean {
const triggered = this.dragging && !cancelled && this.distance >= HISTORY_PULL_TRIGGER_PX;
this.dragging = false;
this.travel = 0;
this.publish();
this.animate();
return triggered;
}
leaveBoundary(): void {
this.loading = false;
this.dragging = false;
this.wheelLatched = false;
this.animate();
}
reset(): void {
this.stopFrame();
this.distance = 0;
this.velocity = 0;
this.travel = 0;
this.loading = false;
this.dragging = false;
this.wheelLatched = false;
this.publish();
}
private publish(): void {
this.options.onUpdate(this.reducedMotion() ? 0 : Math.max(0, this.distance));
}
private stopFrame(): void {
if (this.frame !== null) this.scheduler.cancel(this.frame);
this.frame = null;
this.timestamp = null;
}
private animate(): void {
if (this.reducedMotion()) {
this.distance = 0;
this.velocity = 0;
this.stopFrame();
this.publish();
return;
}
if (this.frame !== null) return;
if (this.distance === (this.loading ? LOADING_POCKET_PX : 0) && this.velocity === 0) {
if (!this.loading) this.wheelLatched = false;
return;
}
this.timestamp = this.scheduler.now();
this.frame = this.scheduler.request(this.advance);
}
private readonly advance = (timestamp: number): void => {
this.frame = null;
if (this.reducedMotion()) {
this.distance = 0;
this.velocity = 0;
this.timestamp = null;
this.publish();
return;
}
const seconds = Math.max(0, timestamp - (this.timestamp ?? timestamp)) / 1000;
this.timestamp = timestamp;
const target = this.loading ? LOADING_POCKET_PX : 0;
// Exact damped-oscillator solution stays stable across slow or suspended frames.
const decay = FREQUENCY * DAMPING_RATIO;
const frequency = FREQUENCY * Math.sqrt(1 - DAMPING_RATIO ** 2);
const displacement = this.distance - target;
const sine = (this.velocity + decay * displacement) / frequency;
const phase = frequency * seconds;
const envelope = Math.exp(-decay * seconds);
this.distance = target + envelope * (displacement * Math.cos(phase) + sine * Math.sin(phase));
this.velocity = envelope * (
(sine * frequency - decay * displacement) * Math.cos(phase)
- (displacement * frequency + decay * sine) * Math.sin(phase)
);
const settled = Math.abs(this.distance - target) < 0.08 && Math.abs(this.velocity) < 0.8;
if (settled) {
this.distance = target;
this.velocity = 0;
this.timestamp = null;
if (!this.loading) this.wheelLatched = false;
}
this.publish();
if (!settled) this.frame = this.scheduler.request(this.advance);
};
}
@@ -14,7 +14,8 @@ export function useSubagentThread({ token, sessionKey, task, historyEnabled }: {
}) {
const pageVisible = usePageVisibility();
const [thread, setThread] = useState<WebuiThreadPersistedPayload | null>(null);
const [failed, setFailed] = useState(false);
const [loading, setLoading] = useState(historyEnabled);
const [error, setError] = useState<string | null>(null);
const refreshRef = useRef<(() => void) | null>(null);
const taskId = task.task_id;
@@ -27,12 +28,15 @@ export function useSubagentThread({ token, sessionKey, task, historyEnabled }: {
const refresh = async () => {
if (refreshing) { pending = true; return; }
refreshing = true;
setLoading(true);
setError(null);
try {
const payload = await fetchSubagentThread(token, sessionKey, taskId, controller.signal);
if (!cancelled) { setThread(payload); setFailed(false); }
} catch {
if (!cancelled) setFailed(true);
if (!cancelled) setThread(payload);
} catch (reason) {
if (!cancelled) setError(reason instanceof Error ? reason.message : String(reason));
} finally {
if (!cancelled) setLoading(false);
refreshing = false;
if (pending && !cancelled) { pending = false; void refresh(); }
}
@@ -56,5 +60,5 @@ export function useSubagentThread({ token, sessionKey, task, historyEnabled }: {
}, [historyEnabled, taskId, task.task_description, task.created_at, task.completed_at, task.result, thread]);
const retry = useCallback(() => refreshRef.current?.(), []);
return { messages, failed, loading: historyEnabled && thread === null, activeTurnId: thread?.active_turn_id, retry };
return { messages, loading, error, activeTurnId: thread?.active_turn_id, retry };
}