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

+4 -1
View File
@@ -22,6 +22,7 @@ import { installSkeletonPreviewApi, SkeletonAdditionsFixture } from "./skeleton-
import { NewChatSkeletonFixture } from "./new-chat-skeleton-fixture";
import "../src/globals.css";
import { DiagramFixture } from "./diagram-fixture";
import { HistoryBoundaryFixture } from "./history-boundary-fixture";
const history: UIMessage[] = [
{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },
@@ -143,7 +144,9 @@ function AppsFixture() {
if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();
await initializeI18n();
createRoot(document.getElementById("root")!).render(<TooltipProvider>
{parameters.get("case") === "diagrams"
{parameters.get("case") === "history-boundary"
? <ClientProvider client={railClient} token="fixture" webuiCapabilities={["webui.prompt-navigation.v1"]}><HistoryBoundaryFixture local={parameters.has("local")} navigate={parameters.has("navigate")} /></ClientProvider>
: parameters.get("case") === "diagrams"
? <DiagramFixture parameters={parameters} />
: parameters.get("case") === "new-chat-skeleton"
? <ClientProvider client={railClient} token="fixture"><NewChatSkeletonFixture /></ClientProvider>
@@ -0,0 +1,31 @@
import { Profiler, useState } from "react";
import { ThreadViewport } from "@/components/thread/ThreadViewport";
import { useSessionHistory } from "@/hooks/useSessions";
import { usePromptHistory } from "@/hooks/usePromptHistory";
import type { UIMessage } from "@/lib/types";
const localMessages: UIMessage[] = Array.from({ length: 280 }, (_, index) => ({
id: `local-${index}`, role: index % 2 ? "assistant" : "user",
content: `Cached message ${index}`, createdAt: index + 1,
}));
export function HistoryBoundaryFixture({ local = false, navigate = false }: { local?: boolean; navigate?: boolean }) {
const [key, setKey] = useState("websocket:boundary-a");
const history = useSessionHistory(local ? null : key);
const messages = local ? localMessages : history.messages;
const navigation = usePromptHistory(local ? null : key, history.version, messages);
return <main className="bg-background text-foreground" style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
<div className="flex h-10 shrink-0 items-center gap-4 px-4 text-sm">
<button onClick={() => setKey((current) => current.endsWith("-a") ? "websocket:boundary-b" : "websocket:boundary-a")}>Switch conversation</button>
</div>
<Profiler id="history-boundary" onRender={(_, phase, actualDuration) => {
window.dispatchEvent(new CustomEvent("history-boundary-render", { detail: { phase, actualDuration } }));
}}>
<ThreadViewport messages={messages} isStreaming={false} conversationKey={key}
conversationReady={local || !history.loading} hasMoreBefore={history.hasMoreBefore}
loadingOlder={history.loadingOlder} olderError={history.olderError} onLoadOlder={history.loadOlder}
navigation={navigate ? navigation : undefined} userMessageOffset={history.userMessageOffset}
composer={<div className="border-t px-4 py-6" style={{ height: 96 }}>History boundary fixture</div>} />
</Profiler>
</main>;
}
+274
View File
@@ -0,0 +1,274 @@
import { expect, test, type Locator, type Page } from "@playwright/test";
function historyPage(start: number, count = 12, more = start > 0) {
return { schemaVersion: 3, projection: "events", events: Array.from({ length: Math.min(count, 52 - start) }, (_, offset) => [
{ event: "user_message", chat_id: "boundary-a", projection_id: `u${start + offset}`, text: `Question ${start + offset}`, starts_turn: true },
{ event: "message", chat_id: "boundary-a", projection_id: `a${start + offset}`, text: "Historical answer.\n\n".repeat(8) },
]).flat(), page: { before_cursor: String(start), after_cursor: String(start + count), user_message_offset: start,
has_more_before: more, has_more_after: start + count < 52 } };
}
async function installHistory(page: Page) {
const reads: string[] = [];
const pending: Array<(value: "success" | "error") => void> = [];
await page.route("**/api/sessions/**", async (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/prompts")) return route.fulfill({ json: {
prompts: Array.from({ length: 52 }, (_, i) => ({ id: `u${i}`, preview: `Question ${i}`, answerPreview: "Historical answer", turnId: `turn${i}`, cursor: String(i), createdAt: i + 1 })),
} });
if (!url.pathname.endsWith("/webui-thread")) return route.fulfill({ json: {} });
if (url.pathname.includes("boundary-b")) return route.fulfill({ json: historyPage(0, 2, false) });
const cursor = url.searchParams.get("before") ?? url.searchParams.get("after");
if (cursor === null) return route.fulfill({ json: historyPage(40) });
reads.push(url.search);
const outcome = await new Promise<"success" | "error">((resolve) => pending.push(resolve));
if (outcome === "error") return route.fulfill({ status: 503, body: "History unavailable" });
const start = url.searchParams.has("after") ? Number(cursor) : Math.max(0, Number(cursor) - 12);
const count = url.searchParams.has("after") ? 12 : Number(cursor) - start;
await route.fulfill({ json: historyPage(start, count, start > 0) });
});
return { reads, complete: (outcome: "success" | "error" = "success") => pending.shift()?.(outcome) };
}
// Positioning is synthetic; gesture assertions below use browser wheel / CDP touch input.
async function positionAtTop(body: Locator) {
return body.evaluate((node) => {
node.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
node.scrollTop = 0;
node.dispatchEvent(new TouchEvent("touchstart", { bubbles: true, touches: [new Touch({ identifier: 1, target: node, clientX: 180, clientY: 200 })] }));
node.dispatchEvent(new TouchEvent("touchend", { bubbles: true }));
const first = node.querySelector("[data-thread-display-unit]")!;
return first.getBoundingClientRect().top - node.getBoundingClientRect().top;
});
}
async function displacement(body: Locator) {
return body.evaluate((node) => new DOMMatrix(getComputedStyle(node).transform).m42);
}
async function stableLayout(body: Locator) {
await body.evaluate(async (node) => {
let previous = -1;
let stable = 0;
for (let i = 0; i < 120 && stable < 8; i++) {
await new Promise(requestAnimationFrame);
const value = node.scrollHeight + node.scrollTop;
stable = value === previous ? stable + 1 : 0;
previous = value;
}
});
}
async function anchorOffset(body: Locator, text: string) {
return body.getByText(text, { exact: true }).evaluate((node) => {
const unit = node.closest("[data-thread-display-unit]")!;
const scroller = node.closest(".thread-message-viewport")!;
return unit.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
});
}
test("continuous wheel input holds real loading visible and preserves the reading anchor through prepend and delayed layout", async ({ page }) => {
const history = await installHistory(page);
await page.goto("/browser/fixture.html?case=history-boundary");
const body = page.getByTestId("thread-message-region");
await expect(body).toBeVisible();
await stableLayout(body);
const nativeTop = await body.evaluate((node) => node.scrollTop);
await body.hover();
await page.mouse.wheel(0, -100);
await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeLessThan(nativeTop);
expect(await displacement(body)).toBe(0);
expect(history.reads).toHaveLength(0);
await positionAtTop(body);
await body.hover();
await page.mouse.wheel(80, 0);
expect(await displacement(body)).toBe(0);
expect(history.reads).toHaveLength(0);
await body.hover();
for (const delta of [-100, -70, -45, -28, -16, -8, -3]) await page.mouse.wheel(0, delta);
await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();
await expect(page.locator(".thread-history-blocks")).toHaveCSS("color", "rgb(211, 94, 20)");
expect(history.reads).toHaveLength(1);
await expect.poll(() => displacement(body)).toBeCloseTo(20, 1);
const still = await displacement(body);
await page.waitForTimeout(150);
expect(Math.abs(await displacement(body) - still)).toBeLessThan(0.1);
await page.screenshot({ path: "test-results/history-boundary-loading.png" });
await body.evaluate((node) => { node.scrollTop = 500; });
await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();
await expect.poll(() => displacement(body)).toBe(0);
const reading = await anchorOffset(body, "Question 40");
history.complete();
await expect(body.getByText("Question 28", { exact: true })).toBeAttached();
expect(Math.abs(await anchorOffset(body, "Question 40") - reading)).toBeLessThan(1);
expect(history.reads).toHaveLength(1);
await body.getByText("Question 28", { exact: true }).evaluate((node) => {
const delayed = document.createElement("div");
delayed.style.height = "160px";
node.closest("[data-thread-display-unit]")!.prepend(delayed);
});
await page.waitForTimeout(100);
expect(Math.abs(await anchorOffset(body, "Question 40") - reading)).toBeLessThan(1);
});
test("touch short-pull cancellation, armed release, loading takeover, and conversation changes converge", async ({ browser, baseURL }) => {
const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, baseURL });
const page = await context.newPage();
const history = await installHistory(page);
try {
await page.goto("/browser/fixture.html?case=history-boundary");
const body = page.getByTestId("thread-message-region");
await expect(body).toBeVisible();
await stableLayout(body);
await positionAtTop(body);
const cdp = await context.newCDPSession(page);
const touch = async (type: "touchStart" | "touchMove" | "touchEnd", y = 200, x = 180) => cdp.send("Input.dispatchTouchEvent", {
type, touchPoints: type === "touchEnd" ? [] : [{ x, y, id: 1 }],
});
await touch("touchStart");
await touch("touchMove", 210, 300);
await touch("touchEnd");
expect(await displacement(body)).toBe(0);
expect(history.reads).toHaveLength(0);
await touch("touchStart");
await touch("touchMove", 240);
const pulled = await displacement(body);
expect(pulled).toBeGreaterThan(0);
await touch("touchEnd");
expect(await displacement(body)).toBeGreaterThan(0);
await expect.poll(() => displacement(body)).toBe(0);
expect(history.reads).toHaveLength(0);
await touch("touchStart");
await touch("touchMove", 330);
await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeVisible();
expect(await displacement(body)).toBeGreaterThanOrEqual(42);
expect(history.reads).toHaveLength(0);
await touch("touchEnd");
await expect.poll(() => history.reads.length).toBe(1);
await expect.poll(() => displacement(body)).toBeCloseTo(20, 1);
await touch("touchStart");
await touch("touchMove", 240);
expect(await displacement(body)).toBeGreaterThan(20);
await touch("touchEnd");
await expect.poll(() => displacement(body)).toBeCloseTo(20, 1);
expect(history.reads).toHaveLength(1);
await page.getByRole("button", { name: "Switch conversation" }).click();
await expect(body.getByText("Question 1", { exact: true })).toBeVisible();
expect(await displacement(body)).toBe(0);
history.complete();
await page.waitForTimeout(100);
await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);
} finally { await context.close(); }
});
test("failure stays actionable away from the top; retry, fast completion and exhausted reduced-motion state remain truthful", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce", colorScheme: "dark" });
const history = await installHistory(page);
await page.goto("/browser/fixture.html?case=history-boundary");
await page.locator("html").evaluate((node) => node.classList.add("dark"));
await expect(page.locator("main")).toHaveCSS("background-color", "rgb(48, 48, 48)");
const body = page.getByTestId("thread-message-region");
await expect(body).toBeVisible();
await stableLayout(body);
await positionAtTop(body);
await page.getByRole("button", { name: "Load earlier messages", exact: true }).click();
await expect.poll(() => history.reads.length).toBe(1);
expect(await displacement(body)).toBe(0);
const block = page.locator(".thread-history-blocks > span").first();
await expect(block).toHaveCSS("background-color", "rgb(211, 94, 20)");
expect(await block.evaluate((node) => getComputedStyle(node).animationName)).toBe("none");
await body.evaluate((node) => { node.scrollTop = 600; });
history.complete("error");
const retry = page.getByRole("button", { name: "Loading failed. Retry", exact: true });
await expect(retry).toBeInViewport();
const failedBlocks = retry.locator(".thread-history-blocks");
await expect(failedBlocks).toHaveCSS("width", "24px");
await expect(failedBlocks).toHaveCSS("height", "24px");
await expect(failedBlocks).toHaveCSS("color", "rgb(252, 165, 165)");
await expect(failedBlocks.locator("span").first()).toHaveCSS("animation-name", "none");
await expect(failedBlocks.locator("span").first()).toHaveCSS("transform", "none");
await retry.focus();
await expect(page.getByRole("tooltip")).toHaveText("HTTP 503");
await retry.click();
await expect.poll(() => history.reads.length).toBe(2);
await expect(page.locator(".thread-history-blocks")).toHaveCSS("width", "20px");
await expect(page.locator(".thread-history-blocks")).toHaveCSS("color", "rgb(211, 94, 20)");
history.complete();
await expect(body.getByText("Question 28", { exact: true })).toBeAttached();
await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);
await expect(page.locator('.thread-history-status[data-state="exhausted"]')).toHaveCount(0);
for (const start of [16, 4, 0]) {
await positionAtTop(body);
await page.getByRole("button", { name: "Load earlier messages", exact: true }).click();
await expect.poll(() => history.reads.length).toBe(start === 16 ? 3 : start === 4 ? 4 : 5);
history.complete();
await expect(body.getByText(`Question ${start}`, { exact: true })).toBeAttached();
}
await positionAtTop(body);
await expect(page.locator('.thread-history-status[data-state="exhausted"]')).toBeInViewport();
await body.hover();
await page.mouse.wheel(0, -120);
expect(await displacement(body)).toBe(0);
expect(history.reads).toHaveLength(5);
await page.screenshot({ path: "test-results/history-boundary-exhausted-dark.png" });
});
test("local cached windows expand without network loading and only the complete beginning is exhausted", async ({ page }) => {
const history = await installHistory(page);
await page.goto("/browser/fixture.html?case=history-boundary&local=1");
const body = page.getByTestId("thread-message-region");
await expect(body.getByText("Cached message 160", { exact: true })).toBeAttached();
await stableLayout(body);
const localAnchor = await positionAtTop(body);
await expect(body.getByText("Cached message 40", { exact: true })).toBeAttached();
await stableLayout(body);
await test.info().attach("local-window-anchor", { body: JSON.stringify({
before: localAnchor, after: await anchorOffset(body, "Cached message 160"),
}), contentType: "application/json" });
await expect(page.locator('.thread-history-status[data-state="exhausted"]')).toHaveCount(0);
await positionAtTop(body);
await expect(body.getByText("Cached message 0", { exact: true })).toBeAttached();
await positionAtTop(body);
await expect(page.locator('.thread-history-status[data-state="exhausted"]')).toBeInViewport();
expect(history.reads).toHaveLength(0);
await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);
});
test("navigation-window loading and errors remain visible and retry uses the navigation request owner", async ({ page }) => {
const history = await installHistory(page);
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto("/browser/fixture.html?case=history-boundary&navigate=1");
const body = page.getByTestId("thread-message-region");
await expect(body).toBeVisible();
const rail = page.getByTestId("prompt-rail-scroll");
await rail.getByRole("button").first().focus();
await page.keyboard.press("Home");
await page.getByRole("button", { name: "Jump to message: Question 38", exact: true }).click();
await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();
history.complete();
await expect(body.getByText("Question 38", { exact: true })).toBeInViewport();
await stableLayout(body);
await body.hover();
await page.mouse.wheel(0, 10000);
await expect.poll(() => history.reads.length).toBe(2);
history.complete();
await expect(body.getByText("Question 51", { exact: true })).toBeAttached();
await stableLayout(body);
await positionAtTop(body);
await body.hover();
await page.mouse.wheel(0, -120);
await expect.poll(() => history.reads.length).toBe(3);
await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();
history.complete("error");
await page.getByRole("button", { name: "Loading failed. Retry", exact: true }).click();
await expect.poll(() => history.reads.length).toBe(4);
history.complete();
await expect(body.getByText("Question 26", { exact: true })).toBeAttached();
await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);
await positionAtTop(body);
await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();
expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&after=50", "?limit=24&before=38", "?limit=24&before=38"]);
});
@@ -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 };
}
+3 -3
View File
@@ -105,7 +105,7 @@ function SubagentPreview() {
return <div className="space-y-4">
<StatePicker label="子任务会话状态" value={mode} options={["ready", "running", "loading", "error"]} onChange={setMode} />
<div className="max-h-96 overflow-y-auto rounded-control border py-4">
<SubagentThreadView messages={messages} loading={mode === "loading"} failed={mode === "error"} isStreaming={mode === "running"}
<SubagentThreadView messages={messages} loading={mode === "loading"} error={mode === "error" ? "示例历史加载失败。" : null} isStreaming={mode === "running"}
activeTurnId={mode === "running" ? "gallery-child-turn" : null} runStartedAt={startedAt / 1000}
onRetry={() => { setRetries((value) => value + 1); setMode("ready"); }} />
</div>
@@ -124,6 +124,6 @@ export const contentExamples: ComponentExample[] = [
description: "查看任务列表,编辑、停用和删除任务,并切换加载和错误状态。", options: "jobs、loading、loadFailed 和 now 来自调用方;onAction 与 onEdit 返回更新后的任务快照;界面负责弹窗衔接、焦点恢复和操作反馈。",
code: '<SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={failed} now={now} onAction={act} onEdit={edit} onOpenCalendar={openCalendar} />' },
{ title: "SubagentThreadView · 子任务消息", files: ["webui/src/components/thread/SubagentThreadView.tsx"], Preview: SubagentPreview,
description: "查看子任务消息、推理活动、加载和失败状态,试用重试回调。", options: "messages 已由运行时投影;loading 和 failed 控制提示;isStreaming 与 activeTurnId 决定当前活动。界面不获取任务历史。",
code: '<SubagentThreadView messages={messages} loading={loading} failed={failed} isStreaming={running} runStartedAt={startedAt} onRetry={retry} />' },
description: "查看子任务消息、推理活动、加载和失败状态,试用重试回调。", options: "messages 已由运行时投影;loading 和 error 复用历史加载组件;isStreaming 与 activeTurnId 决定当前活动。界面不获取任务历史。",
code: '<SubagentThreadView messages={messages} loading={loading} error={error} isStreaming={running} runStartedAt={startedAt} onRetry={retry} />' },
];
+5 -5
View File
@@ -173,13 +173,13 @@ function ViewportPreview() {
}
function HistoryPreview() {
const [mode, setMode] = useState<"loading" | "error" | "pulling">("error");
const [mode, setMode] = useState<"loading" | "error" | "exhausted">("loading");
const [retries, setRetries] = useState(0);
return <div className="space-y-4">
<StatePicker label="历史加载状态" value={mode} options={["loading", "error", "pulling"]} onChange={setMode} />
<StatePicker label="历史状态" value={mode} options={["loading", "exhausted", "error"]} onChange={setMode} />
<div className="relative h-20 rounded-control border">
<ThreadHistoryStatus loading={mode === "loading"} error={mode === "error" ? "Example history unavailable" : null}
pullDistance={mode === "pulling" ? 32 : 0} onRetry={() => { setRetries((value) => value + 1); setMode("loading"); }} />
exhausted={mode === "exhausted"} onRetry={() => { setRetries((value) => value + 1); setMode("loading"); }} />
</div>
<p role="status" className="text-sm text-muted-foreground">重试次数:{retries}</p>
</div>;
@@ -298,8 +298,8 @@ export const conversationExamples: ComponentExample[] = [
{ title: "ThreadViewport · 会话滚动", files: ["thread/ThreadViewport", "thread/PromptRail"], Preview: ViewportPreview,
description: "真实长会话滚动区,包含问题标记、导航跳转和返回底部。", options: "固定预览容器高度;messages 驱动历史显示,ref.jumpToUserPrompt 执行定位;emptyState 提供空会话内容。",
code: '<div className="flex h-96 flex-col"><ThreadViewport ref={viewport} messages={messages} isStreaming={false} /></div>' },
{ title: "ThreadHistoryStatus · 历史加载", files: ["thread/ThreadHistoryStatus"], Preview: HistoryPreview,
description: "切换加载、失败和下拉状态,并试用重试按钮。", options: "loading 控制加载指示,error 控制错误提示,pullDistance 控制下拉位置,onRetry 由调用方提供。",
{ title: "ThreadHistoryStatus · 历史状态", files: ["thread/ThreadHistoryStatus"], Preview: HistoryPreview,
description: "显示加载、历史起点与失败重试状态。", options: "loading 表示正在请求,exhausted 表示没有更早消息,error 提供报错信息,onRetry 重试加载。",
code: '<ThreadHistoryStatus loading={loading} error={error} onRetry={retry} />' },
{ title: "RecoveryNotice · 任务恢复", files: ["thread/RecoveryNotice"], Preview: RecoveryPreview,
description: "切换中断、恢复、失败和无法继续状态,试用继续与关闭。", options: "state 为已有恢复快照;onContinue 与 onDismiss 返回 Promise。示例回调只更新当前预览。",
+47
View File
@@ -535,6 +535,53 @@
.thread-message-end-gap {
height: var(--thread-composer-fade-height);
}
.thread-history-status {
height: calc(48px + var(--history-pull, 0px));
background: linear-gradient(hsl(var(--background)) 35%, hsl(var(--background) / 0));
color: hsl(var(--muted-foreground));
}
.thread-history-control {
display: flex;
width: 120px;
height: 44px;
align-items: center;
justify-content: center;
}
/* loading.dev Blocks, Copyright (c) 2026 Jakub Krehel (MIT); THIRD_PARTY_NOTICES.md. */
.thread-history-blocks {
color: #d35e14;
display: grid;
width: 20px;
height: 20px;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 2px;
}
.thread-history-blocks > span {
background: currentColor;
border-radius: 1.25px;
animation: thread-history-blocks 1300ms ease-in-out infinite;
}
.thread-history-status[data-state="error"] .thread-history-blocks {
width: 24px;
height: 24px;
color: hsl(var(--destructive));
}
.thread-history-status[data-state="error"] .thread-history-blocks > span {
animation: none;
transform: none;
}
@keyframes thread-history-blocks {
0%, 70%, 100% { transform: scale(1); }
35% { transform: scale(0); }
}
@media (prefers-reduced-motion: reduce) {
.thread-history-blocks > span {
animation: none;
transform: scale(0.8);
}
}
.thread-composer-dock {
background: hsl(var(--background));
}
+2 -2
View File
@@ -2192,8 +2192,8 @@
"loadEarlier": "Load earlier messages",
"history": {
"loading": "Loading earlier messages…",
"error": "Loading failed.",
"retry": "Retry"
"exhausted": "No earlier messages",
"retryLabel": "Loading failed. Retry"
},
"forkedFromHistory": "Forked from history",
"promptNavigator": {
+2 -2
View File
@@ -1993,8 +1993,8 @@
"loadEarlier": "Cargar mensajes anteriores",
"history": {
"loading": "Cargando mensajes anteriores…",
"error": "Error al cargar.",
"retry": "Reintentar"
"exhausted": "No hay mensajes anteriores",
"retryLabel": "Error al cargar. Reintentar"
},
"forkedFromHistory": "Bifurcado desde el historial",
"promptNavigator": {
+2 -2
View File
@@ -1992,8 +1992,8 @@
"loadEarlier": "Charger les messages précédents",
"history": {
"loading": "Chargement des messages précédents…",
"error": "Échec du chargement.",
"retry": "Réessayer"
"exhausted": "Aucun message plus ancien",
"retryLabel": "Échec du chargement. Réessayer"
},
"forkedFromHistory": "Bifurqué depuis l'historique",
"promptNavigator": {
+2 -2
View File
@@ -1992,8 +1992,8 @@
"loadEarlier": "Muat pesan sebelumnya",
"history": {
"loading": "Memuat pesan sebelumnya…",
"error": "Gagal memuat.",
"retry": "Coba lagi"
"exhausted": "Tidak ada pesan sebelumnya",
"retryLabel": "Gagal memuat. Coba lagi"
},
"forkedFromHistory": "Cabang dari riwayat",
"promptNavigator": {
+2 -2
View File
@@ -1992,8 +1992,8 @@
"loadEarlier": "以前のメッセージを読み込む",
"history": {
"loading": "以前のメッセージを読み込み中…",
"error": "読み込みに失敗しました。",
"retry": "再試行"
"exhausted": "これより前のメッセージはありません",
"retryLabel": "読み込みに失敗しました。再試行"
},
"forkedFromHistory": "履歴から分岐",
"promptNavigator": {
+2 -2
View File
@@ -1992,8 +1992,8 @@
"loadEarlier": "이전 메시지 불러오기",
"history": {
"loading": "이전 메시지를 불러오는 중…",
"error": "불러오지 못했습니다.",
"retry": "다시 시도"
"exhausted": "이전 메시지가 없습니다",
"retryLabel": "불러오지 못했습니다. 다시 시도"
},
"forkedFromHistory": "기록에서 분기됨",
"promptNavigator": {
+2 -2
View File
@@ -2006,8 +2006,8 @@
"loadEarlier": "Carregar mensagens anteriores",
"history": {
"loading": "Carregando mensagens anteriores…",
"error": "Falha ao carregar.",
"retry": "Tentar novamente"
"exhausted": "Não há mensagens anteriores",
"retryLabel": "Falha ao carregar. Tentar novamente"
},
"forkedFromHistory": "Bifurcado a partir do histórico",
"promptNavigator": {
+2 -2
View File
@@ -1992,8 +1992,8 @@
"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"
"exhausted": "Không có tin nhắn trước đó",
"retryLabel": "Tải thất bại. Thử lại"
},
"forkedFromHistory": "Tách nhánh từ lịch sử",
"promptNavigator": {
+2 -2
View File
@@ -2192,8 +2192,8 @@
"loadEarlier": "加载更早消息",
"history": {
"loading": "正在加载更早的消息…",
"error": "加载失败",
"retry": "重试"
"exhausted": "没有更早的消息",
"retryLabel": "加载失败,重试"
},
"forkedFromHistory": "从历史消息分叉",
"promptNavigator": {
+2 -2
View File
@@ -1992,8 +1992,8 @@
"loadEarlier": "載入更早訊息",
"history": {
"loading": "正在載入更早的訊息…",
"error": "載入失敗",
"retry": "重試"
"exhausted": "沒有更早的訊息",
"retryLabel": "載入失敗,重試"
},
"forkedFromHistory": "從歷史訊息建立分支",
"promptNavigator": {
+20 -7
View File
@@ -174,21 +174,34 @@ describe("session-owned task UI", () => {
expect(await within(screen.getByRole("dialog")).findByText("Latest child response")).toBeVisible();
});
it("retries a failed history read through the shared history controls", async () => {
let offline = true;
it("shares history loading, actual failure details and keyboard retry with the main thread", async () => {
let rejectRead!: (reason: Error) => void;
let resolveRead!: (value: Response) => void;
let reads = 0;
vi.stubGlobal("fetch", vi.fn(async (url: string) => {
if (!url.endsWith("/webui-thread")) return response([task()]);
if (offline) throw new Error("offline");
return childThread("Recovered child response");
reads += 1;
return new Promise<Response>((resolve, reject) => { resolveRead = resolve; rejectRead = reject; });
}));
const user = userEvent.setup();
render(layout({ historyEnabled: true }));
await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
const detail = screen.getByRole("dialog");
expect(await within(detail).findByRole("alert")).toHaveTextContent("Loading failed.");
offline = false;
await user.click(within(detail).getByRole("button", { name: "Retry" }));
const loading = within(detail).getByRole("status");
expect(loading.querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
expect(loading.closest(".thread-history-status")).toHaveAttribute("data-state", "loading");
await act(async () => { rejectRead(new Error("offline")); });
const retry = await within(detail).findByRole("button", { name: "Loading failed. Retry" });
expect(retry.closest(".thread-history-status")).toHaveAttribute("data-state", "error");
expect(retry.querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
act(() => { retry.focus(); });
expect(screen.getByRole("tooltip")).toHaveTextContent("offline");
await user.keyboard("{Enter}");
expect(reads).toBe(2);
expect(within(detail).getByRole("status").closest(".thread-history-status")).toHaveAttribute("data-state", "loading");
await act(async () => { resolveRead(childThread("Recovered child response")); });
expect(await within(detail).findByText("Recovered child response")).toBeVisible();
expect(within(detail).queryByRole("status")).not.toBeInTheDocument();
});
it("keeps the same work block under its prompt, folds completed work and restores it after refresh", async () => {
@@ -0,0 +1,99 @@
import { describe, expect, it, vi } from "vitest";
import { HISTORY_PULL_LIMIT_PX, ThreadHistorySpring } from "@/components/thread/thread-history-spring";
function harness(reduced = false) {
let now = 0;
let nextId = 0;
let distance = 0;
const frames = new Map<number, FrameRequestCallback>();
const scheduler = {
now: () => now,
request: vi.fn((callback: FrameRequestCallback) => { frames.set(++nextId, callback); return nextId; }),
cancel: (id: number) => { frames.delete(id); },
};
const spring = new ThreadHistorySpring({ scheduler, prefersReducedMotion: () => reduced,
onUpdate: (next) => { distance = next; } });
const advance = (milliseconds = 16) => {
now += milliseconds;
const callbacks = [...frames.values()];
frames.clear();
callbacks.forEach((callback) => callback(now));
return distance;
};
const settle = () => { for (let i = 0; i < 100 && frames.size; i++) advance(); };
return { spring, scheduler, advance, settle, frames, distance: () => distance };
}
describe("history boundary spring", () => {
it("resists a short touch and returns continuously without triggering a request", () => {
const h = harness();
h.spring.startTouch();
h.spring.moveTouch(40);
const pulled = h.distance();
expect(pulled).toBeGreaterThan(0);
expect(pulled).toBeLessThan(40);
expect(h.spring.endTouch()).toBe(false);
expect(h.distance()).toBe(pulled);
expect(h.advance()).toBeGreaterThan(0);
expect(h.distance()).toBeLessThan(pulled);
h.settle();
expect(h.distance()).toBe(0);
expect(h.frames.size).toBe(0);
});
it("holds actual loading still, lets a new touch take over, and converges immediately after long frame gaps", () => {
const h = harness();
h.spring.startTouch();
h.spring.moveTouch(120);
expect(h.spring.endTouch()).toBe(true);
h.spring.setLoading(true);
h.settle();
expect(h.distance()).toBe(20);
expect(h.frames.size).toBe(0);
h.spring.startTouch();
expect(h.distance()).toBe(20);
h.spring.moveTouch(20);
expect(h.distance()).toBeGreaterThan(20);
h.spring.endTouch();
h.spring.setLoading(false);
h.advance(30_000);
expect(h.distance()).toBe(0);
expect(h.frames.size).toBe(0);
});
it("merges decelerating wheel input into one bounded spring and one boundary request", () => {
const h = harness();
let requests = 0;
for (const delta of [100, 70, 48, 32, 20, 12, 6, 2]) {
if (h.spring.wheel(delta)) requests++;
expect(h.frames.size).toBe(1);
h.advance();
}
expect(requests).toBe(1);
expect(h.distance()).toBeLessThan(HISTORY_PULL_LIMIT_PX);
h.settle();
expect(h.distance()).toBe(0);
expect(h.spring.wheel(100)).toBe(true);
});
it("cancels task-owned motion on conversation changes", () => {
const h = harness();
h.spring.wheel(100);
h.spring.setLoading(true);
h.spring.reset();
expect(h.frames.size).toBe(0);
expect(h.distance()).toBe(0);
expect(h.spring.wheel(100)).toBe(true);
});
it("keeps the touch trigger functional with reduced motion and no display travel", () => {
const h = harness(true);
h.spring.startTouch();
h.spring.moveTouch(120);
expect(h.distance()).toBe(0);
expect(h.spring.endTouch()).toBe(true);
h.spring.setLoading(true);
expect(h.frames.size).toBe(0);
expect(h.distance()).toBe(0);
});
});
+34 -39
View File
@@ -1,51 +1,46 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { 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();
it("exposes real loading immediately and switches to a distinct exhausted state on completion", () => {
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));
const { container, rerender } = render(<ThreadHistoryStatus {...props} loading />);
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();
expect(container.firstElementChild).toHaveAttribute("data-state", "loading");
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
rerender(<ThreadHistoryStatus {...props} loading={false} exhausted />);
expect(screen.getByText("No earlier messages")).toHaveClass("text-xs");
expect(container.firstElementChild).toHaveAttribute("data-state", "exhausted");
});
it("offers an explicit retry after loading earlier history fails", () => {
it("uses one loading display before and during a request while preserving keyboard activation", () => {
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" }));
const { container, rerender } = render(<ThreadHistoryStatus loading={false} error={null} onRetry={onRetry} />);
expect(container.firstElementChild).toHaveAttribute("data-state", "loading");
const load = screen.getByRole("button", { name: "Load earlier messages" });
expect(load.querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
fireEvent.click(load);
expect(onRetry).toHaveBeenCalledTimes(1);
rerender(<ThreadHistoryStatus loading error={null} onRetry={onRetry} />);
expect(container.firstElementChild).toHaveAttribute("data-state", "loading");
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
});
it("offers error Blocks with the actual failure on keyboard focus and resumes loading on retry", () => {
const onRetry = vi.fn();
const { container, rerender } = render(<ThreadHistoryStatus loading={false} error="offline" onRetry={onRetry} />);
const retry = screen.getByRole("button", { name: "Loading failed. Retry" });
expect(retry.querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
expect(screen.getByText("Loading failed. Retry")).toHaveClass("sr-only");
fireEvent.focus(retry);
expect(screen.getByRole("tooltip")).toHaveTextContent("offline");
fireEvent.click(retry);
expect(onRetry).toHaveBeenCalledTimes(1);
rerender(<ThreadHistoryStatus loading error={null} onRetry={onRetry} />);
expect(container.firstElementChild).toHaveAttribute("data-state", "loading");
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
});
});
+42 -19
View File
@@ -1,4 +1,4 @@
import { createRef, useRef } from "react";
import { createRef, Profiler, useRef } from "react";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -40,12 +40,17 @@ function dispatchUserScroll(scroller: HTMLElement): void {
scroller.dispatchEvent(new Event("scroll"));
}
function historyPull(scroller: HTMLElement): number {
return Number.parseFloat(/translateY\(([-.\d]+)px\)/.exec(scroller.style.transform)?.[1] ?? "0");
}
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 }] });
fireEvent.touchEnd(scroller);
}
}
@@ -1542,7 +1547,7 @@ describe("ThreadViewport", () => {
expect(screen.queryByText(`message ${firstVisible - 1}`)).not.toBeInTheDocument();
expect(screen.getByText(`message ${firstVisible}`)).toBeInTheDocument();
expect(screen.getByText("message 299")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Load earlier messages" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Load earlier messages" })).toBeInTheDocument();
});
it("automatically expands earlier local history near the top", () => {
@@ -1712,7 +1717,7 @@ describe("ThreadViewport", () => {
const scroller = getScroller(container);
dispatchHistoryInput(scroller, input);
expect(onLoadOlder).not.toHaveBeenCalled();
expect(scroller.style.transform).toBe("");
if ("conversationReady" in blocked && blocked.conversationReady === false) expect(historyPull(scroller)).toBe(0);
});
});
@@ -1762,11 +1767,11 @@ describe("ThreadViewport", () => {
});
expect(onLoadOlder).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
fireEvent.click(screen.getByRole("button", { name: "Loading failed. Retry" }));
expect(onLoadOlder).toHaveBeenCalledTimes(1);
});
it("hides history feedback away from the top without fetching again", async () => {
it("keeps real loading visible after leaving the top without fetching again", async () => {
const onLoadOlder = vi.fn();
const { container, rerender } = render(
<ThreadViewport messages={messages} isStreaming={false}
@@ -1783,13 +1788,13 @@ describe("ThreadViewport", () => {
scroller.scrollTop = 800;
dispatchUserScroll(scroller);
});
expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();
expect(screen.getByText("Loading earlier messages…")).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", () => {
it("reveals touch feedback, springs back on cancellation, and requests only on an armed release", async () => {
const onLoadOlder = vi.fn();
const props = { messages, isStreaming: false, hasMoreBefore: true, onLoadOlder };
const { container, rerender } = render(<ThreadViewport {...props} />);
@@ -1797,24 +1802,25 @@ describe("ThreadViewport", () => {
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(historyPull(scroller)).toBeGreaterThan(0);
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
expect(onLoadOlder).not.toHaveBeenCalled();
fireEvent.touchEnd(scroller);
expect(scroller.style.transform).toBe("");
expect(historyPull(scroller)).toBeGreaterThan(0);
await waitFor(() => expect(historyPull(scroller)).toBe(0));
fireEvent.touchStart(scroller, touch(200));
fireEvent.touchMove(scroller, touch(300));
expect(onLoadOlder).not.toHaveBeenCalled();
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
fireEvent.touchEnd(scroller);
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)" });
expect(screen.getByText("Loading earlier messages…")).toBeInTheDocument();
rerender(<ThreadViewport {...props} />);
expect(scroller.style.transform).toBe("");
await waitFor(() => expect(historyPull(scroller)).toBe(0));
});
it("does not fetch on touch scroll alone or horizontal gestures and clears pull on session change", () => {
@@ -1825,23 +1831,40 @@ describe("ThreadViewport", () => {
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(historyPull(scroller)).toBe(0);
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(historyPull(scroller)).toBe(0);
expect(onLoadOlder).not.toHaveBeenCalled();
});
it("leaves completed history quiet", () => {
it("animates boundary frames without rerendering the message tree", async () => {
const onRender = vi.fn();
const { container } = render(<Profiler id="history" onRender={onRender}>
<ThreadViewport messages={messages} isStreaming={false} />
</Profiler>);
await flushAnimationFrame();
await flushAnimationFrame();
fireEvent.wheel(getScroller(container), { deltaY: -100 });
await flushAnimationFrame();
onRender.mockClear();
await flushAnimationFrame();
await flushAnimationFrame();
expect(historyPull(getScroller(container))).toBeGreaterThan(0);
expect(onRender).not.toHaveBeenCalled();
});
it("shows the confirmed start of conversation with boundary feedback", async () => {
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(screen.getByText("No earlier messages")).toBeVisible();
await waitFor(() => expect(historyPull(getScroller(container))).toBeGreaterThan(0));
expect(onLoadOlder).not.toHaveBeenCalled();
});