Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(webui): stabilize earlier-history loading and reclaim space (#6349)
chengyongru743c51e81f93
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 72fb1d9a9..e92b666f5 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -205,3 +205,37 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.```+++---++## Motion — history-boundary springs (MIT)++- **Source**: https://github.com/motiondivision/motion+- **Components**: `motion`, `framer-motion`, and `motion-dom` 14.4.0; `motion-utils` 14.1.1.+- **Bundled**: `nanobot/web/dist/assets/ThreadShell-*.js`++```+The MIT License (MIT)++Copyright (c) 2024 [Motion](https://motion.dev) B.V.+Copyright (c) 2018 Framer B.V.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+```diff --git a/docs/webui.md b/docs/webui.mdindex 4a98862ab..5e3ca5aa7 100644--- a/docs/webui.md+++ b/docs/webui.md@@ -119,6 +119,8 @@ To use work from another topic, mention it with `@` and tell nanobot what you neThe message timeline shows replies and agent activity. Expand the **Worked for** section to inspect the reasoning and tool activity for a completed turn.+To load earlier messages, scroll past the oldest loaded message, or pull down far enough and release on touch devices. The muted loading indicator settles into view while the request runs. When loading succeeds, the indicator and its temporary space disappear and normal message spacing returns. If loading fails, the blocks turn red; hover for error details, then pull again or select the red blocks to retry. If there are no earlier messages, pulling at the real history boundary briefly shows **No earlier messages**.+If the connection drops, the host control shows **Reconnecting**. Tasks in persistent topics can continue during the interruption. After reconnecting, task indicators and completed replies update automatically, including topics you have switched away from. Some text generated while disconnected may appear only after the task finishes. [Temporary chats](#temporary-chats) end when their connection is lost.When the agent writes or edits files, the activity item shows the target path, status, and changed line counts. Choose **Settings → Appearance → File edit display** to control the detail: **Summary** shows the change summary, **Diff** shows available unified patches inline, and **Collapsed diff** lets you expand them with **View diff**. Large diffs may hide unchanged lines or truncate the inline preview. Select the filename in the activity row to open the read-only file preview panel.diff --git a/webui/COMPONENTS.md b/webui/COMPONENTS.mdindex 5c260e513..b9f3f3a13 100644--- a/webui/COMPONENTS.md+++ b/webui/COMPONENTS.md@@ -49,6 +49,12 @@ Supporting hooks and display-model helpers stay near the feature that owns them.`onChat` provides live events to task and model observers. `useNanobotStream` uses `onTranscript` as the single transcript owner, receiving queued events once followed by live events.+## History-boundary motion++History request hooks own loading, pagination and errors. `usePromptHistory.operation` keeps jump/newer feedback separate from an older-page slot, including failed reads and retry; index errors have no page operation. `ThreadHistorySpring` owns input resistance, gesture thresholds and transient/rest/held targets; Motion owns spring integration, frame scheduling and interruption velocity. The reduced-motion preference removes transient travel while preserving request and committed-slot behavior. The spring never writes `scrollTop`. `ThreadViewport` hands a triggered reveal to a fixed-height slot before the original boundary display unit through `ThreadMessages.beforeUnit`, subtracting that slot from the remaining transform. `ThreadMessages.topInset` remains the single normal gutter at the start of the currently rendered list and does not travel into the middle of the timeline with a loading slot; the header paints inside its own slot, not above it over earlier text. The leading content (including unlinked tasks) has its own stable keyed prelude alongside the display units, preserving identity and disclosure state across remote and local cached prepends. The scroller's `scroll-padding-top` remains the prompt-navigation inset. The preceding message margin belongs before the slot, and reading-anchor measurements exclude the slot only for following units. This keeps the handoff and later prepends continuous without a second scroll writer. The temporary loading slot stays in the message flow while a request is pending and on failure, so native scrolling carries feedback out of view; successful completion, including an exhausted result, removes the slot and its old-boundary gutter, restoring normal message spacing. `ThreadViewport` measures and compensates the active reading anchor through the existing camera when scroll bounds permit; explicit navigation and conversation changes take priority, and at a scroll bound the camera clamps rather than preserving space artificially. The leading top inset remains a single normal gutter when the historical boundary is no longer first. Explicit navigation and conversation changes reset the reveal. Boundary feedback without a real request remains transient.++Prompt navigation retains at most three server pages. Static ready Blocks appear only during an uncommitted boundary pull; a completed header is hidden and offers no second pagination entry point. Loading continues at the new boundary, where the header binds to the current first display unit for wheel, touch and keyboard alike; page eviction therefore does not remove the header or the message being read. A failure animates the same Blocks in red without visible error text; hovering shows details, and selecting the red Blocks or a fresh boundary gesture starts another request. Failed reads suppress scroll-triggered automatic requests, not explicit user input.+## TypographyUse the text roles in `tailwind.config.js` for shared metrics: `text-ui` for navigation, `text-control-label` for controls, `text-ui-label` for compact labels, `text-caption` for auxiliary text, and `text-title` / `text-ui-heading` for interface headings. These roles stay independent of reading preferences. Register new size utilities in `src/lib/utils.ts` so `cn()` distinguishes them from text colors.diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsxindex ee370d674..3c8c2e4ab 100644--- a/webui/browser/fixture.tsx+++ b/webui/browser/fixture.tsx@@ -152,7 +152,7 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>: parameters.get("case") === "typography"? <ClientProvider client={railClient} token="fixture"><TypographyFixture /></ClientProvider>: 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>+ ? <ClientProvider client={railClient} token="fixture" webuiCapabilities={["webui.prompt-navigation.v1"]}><HistoryBoundaryFixture local={parameters.has("local")} navigate={parameters.has("navigate")} tasks={parameters.has("tasks")} /></ClientProvider>: parameters.get("case") === "diagrams"? <DiagramFixture parameters={parameters} />: parameters.get("case") === "thread-loading"diff --git a/webui/browser/history-boundary-fixture.tsx b/webui/browser/history-boundary-fixture.tsxindex 307e1aa12..74c2aca66 100644--- a/webui/browser/history-boundary-fixture.tsx+++ b/webui/browser/history-boundary-fixture.tsx@@ -1,5 +1,7 @@import { Profiler, useState } from "react";import { ThreadViewport } from "@/components/thread/ThreadViewport";+import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";+import { useClient } from "@/providers/ClientProvider";import { useSessionHistory } from "@/hooks/useSessions";import { usePromptHistory } from "@/hooks/usePromptHistory";import type { UIMessage } from "@/lib/types";@@ -9,7 +11,8 @@ const localMessages: UIMessage[] = Array.from({ length: 280 }, (_, index) => ({content: `Cached message ${index}`, createdAt: index + 1,}));-export function HistoryBoundaryFixture({ local = false, navigate = false }: { local?: boolean; navigate?: boolean }) {+export function HistoryBoundaryFixture({ local = false, navigate = false, tasks = false }: { local?: boolean; navigate?: boolean; tasks?: boolean }) {+ const { client, token } = useClient();const [key, setKey] = useState("websocket:boundary-a");const history = useSessionHistory(local ? null : key);const messages = local ? localMessages : history.messages;@@ -21,11 +24,13 @@ export function HistoryBoundaryFixture({ local = false, navigate = false }: { lo<Profiler id="history-boundary" onRender={(_, phase, actualDuration) => {window.dispatchEvent(new CustomEvent("history-boundary-render", { detail: { phase, actualDuration } }));}}>+ <SubagentTasksProvider client={client} token={token} sessionKey={key} enabled={tasks} liveEvents={false}><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>} />+ </SubagentTasksProvider></Profiler></main>;}diff --git a/webui/browser/history-boundary.spec.ts b/webui/browser/history-boundary.spec.tsindex 6952a2321..18420d6df 100644--- a/webui/browser/history-boundary.spec.ts+++ b/webui/browser/history-boundary.spec.ts@@ -8,9 +8,11 @@ function historyPage(start: number, count = 12, more = start > 0) {has_more_before: more, has_more_after: start + count < 52 } };}-async function installHistory(page: Page) {+async function installHistory(page: Page, initialStart = 40, initialCount = 12) {const reads: string[] = [];const pending: Array<(value: "success" | "error") => void> = [];+ let fastResponse = false;+ let releaseFastResponse: (() => void) | null = null;await page.route("**/api/sessions/**", async (route) => {const url = new URL(route.request().url());if (url.pathname.endsWith("/prompts")) return route.fulfill({ json: {@@ -19,17 +21,26 @@ async function installHistory(page: Page) {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) });+ if (cursor === null) return route.fulfill({ json: historyPage(initialStart, initialCount) });reads.push(url.search);- const outcome = await new Promise<"success" | "error">((resolve) => pending.push(resolve));+ const outcome = fastResponse+ ? await new Promise<"success">((resolve) => { releaseFastResponse = () => resolve("success"); })+ : 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) };+ return {+ reads,+ useFastResponse: (value: boolean) => { fastResponse = value; },+ releaseFastResponse: () => { releaseFastResponse?.(); releaseFastResponse = null; },+ complete: (outcome: "success" | "error" = "success") => pending.shift()?.(outcome),+ };}+type HistoryFixture = Awaited<ReturnType<typeof installHistory>>;+async function installShortHistory(page: Page) {let reads = 0;await page.route("**/api/sessions/**", async (route) => {@@ -53,7 +64,7 @@ async function positionAtTop(body: Locator) {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;+ return first.getBoundingClientRect().top;});}@@ -63,60 +74,196 @@ async function displacement(body: Locator) {async function stableLayout(body: Locator) {await body.evaluate(async (node) => {- let previous = -1;+ const frame = node.closest<HTMLElement>(".thread-viewport-frame")!;+ const header = node.closest(".thread-viewport")!.querySelector<HTMLElement>(".thread-history-status");+ const first = node.querySelector<HTMLElement>("[data-thread-display-unit]");+ let previous: number[] | null = null;let stable = 0;- for (let i = 0; i < 120 && stable < 8; i++) {+ for (let i = 0; i < 240 && stable < 8; i++) {await new Promise(requestAnimationFrame);- const value = node.scrollHeight + node.scrollTop;- stable = value === previous ? stable + 1 : 0;+ const rect = (element: HTMLElement | null) => {+ const box = element?.getBoundingClientRect();+ return [box?.top ?? 0, box?.bottom ?? 0];+ };+ const transform = new DOMMatrix(getComputedStyle(node).transform).m42;+ const value = [node.scrollHeight, node.scrollTop, transform, ...rect(frame), ...rect(header), ...rect(first)];+ stable = previous && value.every((coordinate, index) => Math.abs(coordinate - previous![index]!) < 0.01)+ ? stable + 1 : 0;previous = value;}+ if (stable < 8) throw new Error("Thread history layout did not settle across frame and anchor geometry");});}-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;- });+async function anchorTop(body: Locator, text: string) {+ return body.getByText(text, { exact: true }).evaluate((node) =>+ node.closest("[data-thread-display-unit]")!.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");+async function openSettledHistory(page: Page, query = "") {+ await page.goto(`/browser/fixture.html?case=history-boundary${query}`);const body = page.getByTestId("thread-message-region");await expect(body).toBeVisible();await stableLayout(body);+ return { body, header: page.locator(".thread-history-status"), slot: body.locator(".thread-history-slot") };+}++async function requestOlderWithWheel(body: Locator, history: HistoryFixture, readCount: number) {+ await body.hover();+ await body.page().mouse.wheel(0, -120);+ await expect.poll(() => history.reads.length).toBe(readCount);+}++async function positionReadingAnchor(body: Locator, text: string) {+ await body.getByText(text, { exact: true }).evaluate((node) => {+ const unit = node.closest("[data-thread-display-unit]")!;+ const scroller = unit.closest<HTMLElement>(".thread-message-viewport")!;+ scroller.scrollTop += unit.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 280;+ });+ await stableLayout(body);+ return anchorTop(body, text);+}++async function completePrepend(history: HistoryFixture, body: Locator, firstText: string, anchorText: string, expectedTop: number) {+ history.complete();+ await expect(body.getByText(firstText, { exact: true })).toBeAttached();+ await expect(body.page().locator(".thread-history-status")).toHaveCount(0);+ await stableLayout(body);+ await expectAnchorCoordinate(body, anchorText, expectedTop);+}++async function themeColor(locator: Locator, token: "--muted-foreground" | "--destructive") {+ return locator.evaluate((node, variable) => {+ const probe = document.createElement("span");+ probe.style.color = `hsl(var(${variable}))`;+ node.append(probe);+ const color = getComputedStyle(probe).color;+ probe.remove();+ return color;+ }, token);+}++// Use the fixed viewport, never the transformed scroller, as the coordinate frame.+async function historyGeometry(body: Locator, text: string) {+ return body.getByText(text, { exact: true }).evaluate((node) => {+ const unit = node.closest("[data-thread-display-unit]")!.getBoundingClientRect();+ const frame = node.closest(".thread-viewport-frame")!.getBoundingClientRect();+ const scroller = node.closest<HTMLElement>(".thread-message-viewport")!;+ const header = node.closest(".thread-viewport")!.querySelector(".thread-history-status")?.getBoundingClientRect();+ const slot = scroller.querySelector(".thread-history-slot");+ return {+ headerTop: header?.top ?? 0, headerBottom: header?.bottom ?? 0, headerHeight: header?.height ?? 0,+ visibleHeight: header ? Math.max(0, Math.min(header.bottom, frame.bottom) - Math.max(header.top, frame.top)) : 0,+ anchorTop: unit.top, frameTop: frame.top, scrollTop: scroller.scrollTop,+ transformY: new DOMMatrix(getComputedStyle(scroller).transform).m42,+ slotHeight: slot ? Number.parseFloat(getComputedStyle(slot).height) : 0,+ slotBeforeKey: slot?.parentElement?.nextElementSibling?.getAttribute("data-thread-display-unit") ?? null,+ firstKey: scroller.querySelector("[data-thread-display-unit]")?.getAttribute("data-thread-display-unit"),+ };+ });+}++type HistoryGeometry = Awaited<ReturnType<typeof historyGeometry>>;++async function expectCoordinates(body: Locator, text: string, reference: HistoryGeometry) {+ let latest = reference;+ try {+ await expect.poll(async () => {+ latest = await historyGeometry(body, text);+ return Math.max(...(["headerTop", "headerBottom", "anchorTop", "frameTop"] as const)+ .map((key) => Math.abs(latest[key] - reference[key])));+ }, { message: `${text}: header and reading unit must keep their fixed viewport coordinates` }).toBeLessThan(1);+ } catch (error) {+ const diagnostic = JSON.stringify({ text, before: reference, after: latest });+ console.log("history-coordinate-failure", diagnostic);+ await test.info().attach("history-coordinate-failure", { body: diagnostic, contentType: "application/json" });+ throw error;+ }+}++async function expectHeaderInsideSlot(body: Locator) {+ const geometry = await body.locator(".thread-history-slot").evaluate((slot) => {+ const header = slot.querySelector(".thread-history-status")!.getBoundingClientRect();+ const own = slot.getBoundingClientRect();+ const before = slot.parentElement!.previousElementSibling?.getBoundingClientRect();+ const after = slot.parentElement!.nextElementSibling!.getBoundingClientRect();+ return { headerTop: header.top, headerBottom: header.bottom, slotTop: own.top, slotBottom: own.bottom,+ previousBottom: before?.bottom, nextTop: after.top };+ });+ expect(Math.abs(geometry.headerTop - geometry.slotTop)).toBeLessThan(1);+ expect(Math.abs(geometry.headerBottom - geometry.slotBottom)).toBeLessThan(1);+ if (geometry.previousBottom !== undefined) expect(geometry.previousBottom).toBeLessThanOrEqual(geometry.headerTop);+ expect(geometry.headerBottom).toBeLessThanOrEqual(geometry.nextTop);+}++async function expectHeld(body: Locator, text: string) {+ await expect(body.locator(".thread-history-slot")).toHaveCSS("height", "48px");+ await expect.poll(() => displacement(body)).toBe(0);+ await expect.poll(async () => (await historyGeometry(body, text)).visibleHeight).toBeCloseTo(48, 0);+ await expectHeaderInsideSlot(body);+ return historyGeometry(body, text);+}++function expectSameScroll(before: HistoryGeometry, after: HistoryGeometry, delta: number) {+ expect(delta).toBeGreaterThan(0);+ expect(Math.abs(after.headerTop - before.headerTop + delta)).toBeLessThan(1);+ expect(Math.abs(after.anchorTop - before.anchorTop + delta)).toBeLessThan(1);+}++async function expectNoVisibleHistoryText(header: Locator) {+ await expect.poll(() => header.evaluate((node) => {+ const content = node.cloneNode(true) as HTMLElement;+ content.querySelectorAll(".sr-only").forEach((label) => label.remove());+ return content.textContent?.trim();+ })).toBe("");+}++test("wheel loading hands off to a retained 48px slot; prepend and delayed layout keep absolute reading coordinates", async ({ page }) => {+ const history = await installHistory(page);+ const { body, header } = await openSettledHistory(page);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);+ const originalTop = await positionAtTop(body);+ await expect(header).not.toBeInViewport();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)");+ await expect(header).toHaveAttribute("data-state", "loading");+ await expect(header.locator(".thread-history-blocks")).toHaveCSS("color", "rgb(98, 98, 106)");+ await expect(header.locator(".thread-history-blocks > span").first()).not.toHaveCSS("animation-name", "none");expect(history.reads).toHaveLength(1);- await expect.poll(() => displacement(body)).toBeCloseTo(20, 1);- const still = await displacement(body);+ const held = await expectHeld(body, "Question 40");+ expect(held.anchorTop - originalTop).toBeCloseTo(48, 0);+ expect(held.headerTop).toBeCloseTo(held.frameTop, 0);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 expectCoordinates(body, "Question 40", held);+ await page.screenshot({ path: test.info().outputPath("history-loading-held.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);+ // A programmatic scroll may clip the header, but must not retract its slot or spring.+ await body.evaluate((node) => { node.scrollTop = 12; });+ await stableLayout(body);+ const programmed = await historyGeometry(body, "Question 40");+ expectSameScroll(held, programmed, 12);+ expect(programmed.visibleHeight).toBeCloseTo(36, 0);+ expect(await displacement(body)).toBe(0);+ await expect(body.locator(".thread-history-slot")).toHaveCSS("height", "48px");+ await body.evaluate((node) => { node.scrollTop = 0; });+ await stableLayout(body);+ await expectCoordinates(body, "Question 40", held);+ const preCompletionAnchorTop = await positionReadingAnchor(body, "Question 40");++ await completePrepend(history, body, "Question 28", "Question 40", preCompletionAnchorTop);+ const completedSpacing = await historyBoundarySpacing(body, "Question 40", "Question 41");+ const completedAnchorTop = await anchorTop(body, "Question 40");+ console.log("history-completion-spacing", JSON.stringify({ ...completedSpacing, readingDeltaPx: completedAnchorTop - preCompletionAnchorTop }));+ expect(Math.abs(completedSpacing.boundaryGap! - completedSpacing.referenceGap!), JSON.stringify(completedSpacing)).toBeLessThan(1);+ expect(completedSpacing.slotCount).toBe(0);expect(history.reads).toHaveLength(1);await body.getByText("Question 28", { exact: true }).evaluate((node) => {@@ -124,116 +271,337 @@ test("continuous wheel input holds real loading visible and preserves the readindelayed.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);+ await stableLayout(body);+ await expectAnchorCoordinate(body, "Question 40", preCompletionAnchorTop);+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);+ await page.screenshot({ path: test.info().outputPath("history-prepend-stable.png") });++ // The reclaimed boundary scrolls as ordinary message flow, with no retained spacer.+ const beforeScroll = await body.evaluate((node) => node.scrollTop);+ const anchorBeforeScroll = await anchorTop(body, "Question 40");+ await body.hover();+ await page.mouse.wheel(0, 16);+ await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeGreaterThan(beforeScroll);+ await stableLayout(body);+ const delta = await body.evaluate((node) => node.scrollTop) - beforeScroll;+ expect(Math.abs((await anchorTop(body, "Question 40")) - anchorBeforeScroll + delta)).toBeLessThan(1);+ expect(await displacement(body)).toBe(0);+ await page.screenshot({ path: test.info().outputPath("history-native-scroll-reclaimed.png") });+ await page.mouse.wheel(0, 96);+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);+ expect(history.reads).toHaveLength(1);+});++test("unlinked task prelude stays with the retained boundary when earlier messages load", async ({ page }) => {+ const history = await installHistory(page);+ await page.route("**/api/sessions/**/subagents", (route) => route.fulfill({ json: { tasks: [{+ task_id: "legacy", revision: 1, label: "Earlier check", task_description: "Check earlier work",+ state: "done", phase: "completed", elapsed_seconds: 2, iteration: 1,+ tool_events: [], usage: null, receipts: {}, result: "Verified", partial: false,+ stop_reason: null, error: null, origin_turn_id: "legacy-turn", origin_message_id: null,+ created_at: 100, completed_at: 102,+ }] } }));+ await page.goto("/browser/fixture.html?case=history-boundary&tasks");+ const body = page.getByTestId("thread-message-region");+ const otherTasks = body.getByRole("region", { name: "Other tasks" });+ await expect(otherTasks).toBeAttached();+ await otherTasks.getByRole("button", { name: /Other tasks/ }).click();+ await expect(otherTasks.getByRole("button", { name: /Earlier check Completed/ })).toBeVisible();+ await stableLayout(body);+ const originalTop = await positionAtTop(body);+ await body.hover();+ await page.mouse.wheel(0, -100);+ await expect(page.locator(".thread-history-status")).toHaveAttribute("data-state", "loading");+ const held = await expectHeld(body, "Question 40");+ expect(held.anchorTop - originalTop).toBeCloseTo(48, 0);+ const preCompletionAnchorTop = await positionReadingAnchor(body, "Question 40");+ history.complete();+ await expect(body.getByText("Question 28", { exact: true })).toBeAttached();+ await expect(page.locator(".thread-history-slot")).toHaveCount(0);+ await stableLayout(body);+ await expectAnchorCoordinate(body, "Question 40", preCompletionAnchorTop);+ await expect(otherTasks).toHaveCount(1);+ await expect(otherTasks.getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "true");+ expect(history.reads).toHaveLength(1);});-test("touch short-pull cancellation, armed release, loading takeover, and conversation changes converge", async ({ browser, baseURL }) => {+test("touch reveals a static partial ready header, arms only on release, and retains a stable full loading header", 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);+ const { body, header } = await openSettledHistory(page);await positionAtTop(body);+ await expect(header).not.toBeInViewport();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);+ // Leftward tests horizontal intent without Chromium's native swipe-back gesture.+ await touch("touchMove", 210, 60);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);+ const partial = await historyGeometry(body, "Question 40");expect(pulled).toBeGreaterThan(0);+ expect(pulled).toBeLessThan(80);+ expect(partial.visibleHeight).toBeGreaterThan(0);+ expect(partial.visibleHeight).toBeLessThan(partial.headerHeight);+ await expect(header).toHaveAttribute("data-state", "ready");+ await expect(header.locator(".thread-history-blocks > span").first()).toHaveCSS("animation-name", "none");+ expect(history.reads).toHaveLength(0);+ await page.screenshot({ path: test.info().outputPath("history-touch-partial-ready.png") });await touch("touchEnd");- expect(await displacement(body)).toBeGreaterThan(0);await expect.poll(() => displacement(body)).toBe(0);+ await expect(header).not.toBeInViewport();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);+ await touch("touchMove", 400);+ const armedDistance = await displacement(body);+ expect(armedDistance).toBeGreaterThanOrEqual(56);+ expect(armedDistance).toBeLessThan(80);+ await expect(header).toHaveAttribute("data-state", "ready");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 expect(header).toHaveAttribute("data-state", "loading");+ const held = await expectHeld(body, "Question 40");+ await page.waitForTimeout(150);+ await expectCoordinates(body, "Question 40", held);+ await page.screenshot({ path: test.info().outputPath("history-touch-held.png") });+await touch("touchStart");await touch("touchMove", 240);- expect(await displacement(body)).toBeGreaterThan(20);await touch("touchEnd");- await expect.poll(() => displacement(body)).toBeCloseTo(20, 1);+ await expectHeld(body, "Question 40");+ await expectCoordinates(body, "Question 40", held);expect(history.reads).toHaveLength(1);++ // Native finger-up movement must be free to scroll the retained header away.+ await touch("touchStart", 400);+ await touch("touchMove", 376);+ await touch("touchMove", 360);+ await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);+ const scrolled = await historyGeometry(body, "Question 40");+ console.log("history-touch-native-scroll", JSON.stringify({ held, scrolled }));+ expectSameScroll(held, scrolled, scrolled.scrollTop);+ expect(scrolled.visibleHeight).toBeGreaterThan(0);+ expect(scrolled.visibleHeight).toBeLessThan(48);+ await touch("touchEnd");await page.getByRole("button", { name: "Switch conversation" }).click();await expect(body.getByText("Question 1", { exact: true })).toBeVisible();expect(await displacement(body)).toBe(0);+ await expect(body.locator(".thread-history-slot")).toHaveCount(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 }) => {+test("reduced-motion failure keeps its functional 48px slot and retry until naturally scrolled away", 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");+ const header = page.locator(".thread-history-status");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; });+ const originalTop = await positionAtTop(body);+ await requestOlderWithWheel(body, history, 1);+ const held = await expectHeld(body, "Question 40");+ expect(held.anchorTop - originalTop).toBeCloseTo(48, 0);+ const block = header.locator(".thread-history-blocks > span").first();+ const normalColor = await header.locator(".thread-history-blocks").evaluate((node) => getComputedStyle(node).color);+ const mutedColor = await themeColor(header, "--muted-foreground");+ expect(normalColor).toBe(mutedColor);+ console.log(`history-colors dark loading=${normalColor}`);+ await expect(block).toHaveCSS("animation-name", "none");history.complete("error");const retry = page.getByRole("button", { name: "Loading failed. Retry", exact: true });await expect(retry).toBeInViewport();+ await page.waitForTimeout(150);+ await expectCoordinates(body, "Question 40", held);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 expectHeaderInsideSlot(body);+ await expectNoVisibleHistoryText(header);+ await expect(page.getByRole("tooltip")).toHaveCount(0);+ await failedBlocks.hover();await expect(page.getByRole("tooltip")).toHaveText("HTTP 503");- await retry.click();+ await page.screenshot({ path: test.info().outputPath("history-failure-dark.png") });+ await page.mouse.move(16, 20, { steps: 5 });+ await expect(page.getByRole("tooltip")).toHaveCount(0);++ await body.evaluate((node) => { node.scrollTop = 8; });+ await stableLayout(body);+ expectSameScroll(held, await historyGeometry(body, "Question 40"), 8);+ expect(await displacement(body)).toBe(0);+ await body.evaluate((node) => { node.scrollTop = 0; });+ await expectCoordinates(body, "Question 40", held);+ await body.hover();+ await page.mouse.wheel(0, 96);+ await expect(retry).not.toBeInViewport();+ await expect(header).toHaveAttribute("data-state", "error");+ await expect(body.locator(".thread-history-slot")).toHaveCSS("height", "48px");+ expect(history.reads).toHaveLength(1);+ await body.evaluate((node) => { node.scrollTop = 0; });+ await failedBlocks.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)");+ await expect(header).toHaveAttribute("data-state", "loading");+ await expect(header.locator(".thread-history-blocks")).toHaveCSS("width", "20px");+ await expect(block).toHaveCSS("animation-name", "none");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 expect(header).toHaveCount(0);+ await expectAnchorCoordinate(body, "Question 40", held.anchorTop);+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);++ for (const [index, start] of [16, 4, 0].entries()) {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);+ await requestOlderWithWheel(body, history, index + 3);history.complete();await expect(body.getByText(`Question ${start}`, { exact: true })).toBeAttached();}await positionAtTop(body);const exhausted = page.locator('.thread-history-status[data-state="exhausted"]');- await expect(exhausted).toHaveCount(0);await body.hover();await page.mouse.wheel(0, -120);await expect(exhausted).toBeInViewport();expect(await displacement(body)).toBe(0);expect(history.reads).toHaveLength(5);- await page.screenshot({ path: "test-results/history-boundary-exhausted-dark.png" });+ await page.screenshot({ path: test.info().outputPath("history-exhausted-dark.png") });await expect(exhausted).toHaveCount(0);});+for (const elapsedMs of [0, 80]) test(`fast responses reclaim completed slots and keep the next boundary loading${elapsedMs ? " during spring travel" : ""}`, async ({ page }) => {+ const history = await installHistory(page);+ history.useFastResponse(true);+ await page.clock.install({ time: new Date("2026-01-01T00:00:00Z") });+ const { body, header } = await openSettledHistory(page);+ await positionAtTop(body);+ await expect(header).toHaveAttribute("data-state", "ready");+ await expect(header).not.toBeInViewport();+ await body.hover();+ await page.clock.pauseAt(new Date("2026-01-01T01:00:00Z"));+ await page.mouse.wheel(0, -120);+ await expect.poll(() => history.reads.length).toBe(1);+ await expect(header).toHaveAttribute("data-state", "loading");+ if (elapsedMs > 0) await page.clock.runFor(elapsedMs);+ const beforeFastRead = await historyGeometry(body, "Question 40");+ expect(beforeFastRead.slotHeight).toBe(48);+ expect(Math.abs(beforeFastRead.transformY)).toBeGreaterThan(0);+ if (elapsedMs > 0) expect(beforeFastRead.transformY).toBeGreaterThan(-48);+ history.releaseFastResponse();+ await expect(body.getByText("Question 28", { exact: true })).toBeAttached();+ expect(history.reads).toHaveLength(1);+ await expect(header).toHaveCount(0);+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);+ const afterFastRead = await historyGeometry(body, "Question 40");+ console.log("history-fast-completion-geometry", JSON.stringify({ before: beforeFastRead, after: afterFastRead }));+ await expectAnchorCoordinate(body, "Question 40", beforeFastRead.anchorTop);+ const fastSpacing = await historyBoundarySpacing(body, "Question 40", "Question 41");+ expect(Math.abs(fastSpacing.boundaryGap! - fastSpacing.referenceGap!)).toBeLessThan(1);+ await page.clock.resume();+ await stableLayout(body);+ await expectAnchorCoordinate(body, "Question 40", beforeFastRead.anchorTop);+ const settledFastSpacing = await historyBoundarySpacing(body, "Question 40", "Question 41");+ expect(Math.abs(settledFastSpacing.boundaryGap! - settledFastSpacing.referenceGap!)).toBeLessThan(1);+ await expect(page.locator(".thread-history-slot")).toHaveCount(0);+ await page.screenshot({ path: test.info().outputPath("history-fast-ready-hidden.png") });++ history.useFastResponse(false);+ await positionAtTop(body);+ await stableLayout(body);+ const atNewHead = await historyGeometry(body, "Question 28");+ expect(atNewHead.firstKey).toBe("u28");+ expect(atNewHead.slotBeforeKey).toBeNull();+ expect(atNewHead.slotHeight).toBe(0);+ await expect(header).toBeHidden();+ expect(history.reads).toHaveLength(1);+ await requestOlderWithWheel(body, history, 2);+ await expect(header).toHaveAttribute("data-state", "loading");+ const nextHeld = await expectHeld(body, "Question 28");+ expect(nextHeld.slotBeforeKey).toBe("u28");+ expect(nextHeld.anchorTop - atNewHead.anchorTop).toBeCloseTo(48, 0);+ await completePrepend(history, body, "Question 16", "Question 28", nextHeld.anchorTop);+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);+ expect(history.reads).toEqual(["?limit=120&before=40", "?limit=120&before=28"]);+});++test("ordinary middle reading never reveals an exhausted overlay, even when the complete beginning is cached", async ({ page }) => {+ const history = await installHistory(page, 0, 52);+ await page.goto("/browser/fixture.html?case=history-boundary");+ const body = page.getByTestId("thread-message-region");+ const exhausted = page.getByText("No earlier messages", { exact: true });+ await expect(body.getByText("Question 51", { exact: true })).toBeAttached();+ await stableLayout(body);+ await expect(exhausted).toHaveCount(0);+ await body.evaluate((node) => {+ node.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));+ node.scrollTop = Math.round((node.scrollHeight - node.clientHeight) / 2);+ });+ await stableLayout(body);+ const middle = await body.evaluate((node) => node.scrollTop);+ expect(middle).toBeGreaterThan(48);+ expect(middle).toBeLessThan(await body.evaluate((node) => node.scrollHeight - node.clientHeight - 48));+ await expect(exhausted).toHaveCount(0);+ await body.hover();+ await page.mouse.wheel(0, -32);+ await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeLessThan(middle);+ await expect(exhausted).toHaveCount(0);+ await page.mouse.wheel(0, 64);+ await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeGreaterThan(middle);+ await expect(exhausted).toHaveCount(0);+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);+ expect(await displacement(body)).toBe(0);+ expect(history.reads).toHaveLength(0);+ await page.screenshot({ path: test.info().outputPath("history-middle-no-exhausted.png") });+});++test("a successful exhausted result reclaims its slot and stays at the real history boundary", async ({ page }) => {+ const history = await installHistory(page, 4);+ const { body } = await openSettledHistory(page);+ const exhausted = page.locator('.thread-history-status[data-state="exhausted"]');+ await expect(exhausted).toHaveCount(0);+ await positionAtTop(body);+ await requestOlderWithWheel(body, history, 1);+ const held = await expectHeld(body, "Question 4");+ history.complete();+ await expect(body.getByText("Question 0", { exact: true })).toBeAttached();+ await stableLayout(body);+ await expectAnchorCoordinate(body, "Question 4", held.anchorTop);+ const completionReadingDeltaPx = (await anchorTop(body, "Question 4")) - held.anchorTop;+ expect(Math.abs(completionReadingDeltaPx)).toBeLessThan(1);+ await body.evaluate((node) => { node.scrollTop = 0; node.dispatchEvent(new Event("scroll")); });+ await stableLayout(body);+ await expect(exhausted).toBeVisible();+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);+ const spacing = await historyBoundarySpacing(body, "Question 4", "Question 5");+ console.log("history-exhausted-spacing", JSON.stringify({ ...spacing, readingDeltaPx: completionReadingDeltaPx }));+ expect(Math.abs(spacing.boundaryGap! - spacing.referenceGap!)).toBeLessThan(1);+ expect(spacing.slotCount).toBe(0);+ await page.screenshot({ path: test.info().outputPath("history-exhausted-reclaimed-at-boundary.png") });+ await body.hover();+ await page.mouse.wheel(0, 600);+ await stableLayout(body);+ await expect(exhausted).toHaveCount(0);+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);+ expect(await displacement(body)).toBe(0);+ expect(history.reads).toHaveLength(1);+ await page.screenshot({ path: test.info().outputPath("history-exhausted-not-floating-in-middle.png") });+});+for (const reducedMotion of ["no-preference", "reduce"] as const) {test(`exhausted hints follow wheel and touch feedback, including settlement (${reducedMotion})`, async ({ page, browser, baseURL }) => {await page.emulateMedia({ reducedMotion });@@ -308,7 +676,7 @@ test("local cached windows expand without network loading and only the completeawait 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"),+ before: localAnchor, after: await anchorTop(body, "Cached message 160"),}), contentType: "application/json" });await expect(page.locator('.thread-history-status[data-state="exhausted"]')).toHaveCount(0);await positionAtTop(body);@@ -335,27 +703,399 @@ test("navigation-window loading and errors remain visible and retry uses the navawait 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();+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);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);+ await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);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 requestOlderWithWheel(body, history, 3);await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();+ const held = await expectHeld(body, "Question 38");+ await page.mouse.wheel(0, -80);+ await stableLayout(body);+ const afterRetryPressure = await historyGeometry(body, "Question 38");+ console.log("history-navigation-pressure-settled", JSON.stringify({ held, afterRetryPressure }));+ await expectCoordinates(body, "Question 38", held);+ expect(history.reads).toHaveLength(3);history.complete("error");await page.getByRole("button", { name: "Loading failed. Retry", exact: true }).click();await expect.poll(() => history.reads.length).toBe(4);+ const beforeRetryCompletion = await historyGeometry(body, "Question 38");history.complete();await expect(body.getByText("Question 26", { exact: true })).toBeAttached();await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);+ await expect(page.locator(".thread-history-status")).toHaveCount(0);+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);+ await stableLayout(body);+ const afterRetryCompletion = await historyGeometry(body, "Question 38");+ console.log("history-navigation-retry-completion", JSON.stringify({ beforeRetryCompletion, afterRetryCompletion }));+ await expectAnchorCoordinate(body, "Question 38", held.anchorTop);+ const navigationSpacing = await historyBoundarySpacing(body, "Question 38", "Question 39");+ expect(Math.abs(navigationSpacing.boundaryGap! - navigationSpacing.referenceGap!)).toBeLessThan(1);await positionAtTop(body);- await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();+ await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&after=50", "?limit=24&before=38", "?limit=24&before=38"]);});++async function jumpViaRail(page: Page, index: number) {+ const rail = page.getByTestId("prompt-rail-scroll");+ await expect(rail).toBeVisible();+ await rail.getByRole("button").first().focus();+ await page.keyboard.press(index < 26 ? "Home" : "End");+ await rail.getByRole("button", { name: `Jump to message: Question ${index}`, exact: true }).click();+}++test("failed Blocks animate without visible error text; pulling retries once and pending input cannot duplicate the request", async ({ page }) => {+ const history = await installHistory(page);+ const { body, header, slot } = await openSettledHistory(page);+ await positionAtTop(body);+ await requestOlderWithWheel(body, history, 1);+ const held = await expectHeld(body, "Question 40");+ expect(held.slotBeforeKey).toBe("u40");+ history.complete("error");+ await expect(header).toHaveAttribute("data-state", "error");+ const retry = page.getByRole("button", { name: "Loading failed. Retry", exact: true });+ const blocks = retry.locator(".thread-history-blocks");+ await expect(blocks).toBeInViewport();+ await expect(blocks).toHaveCSS("color", "rgb(185, 28, 28)");+ await expect(blocks.locator("span").first()).not.toHaveCSS("animation-name", "none");+ await expectHeaderInsideSlot(body);+ await expectNoVisibleHistoryText(header);+ await expect(page.getByRole("tooltip")).toHaveCount(0);+ await stableLayout(body);+ await expectCoordinates(body, "Question 40", held);+ expect(history.reads).toHaveLength(1);++ // This is a fresh pull at the failed boundary, not a ready-button-only path.+ await requestOlderWithWheel(body, history, 2);+ await expect(header).toHaveAttribute("data-state", "loading");+ await page.mouse.wheel(0, -120);+ await page.mouse.wheel(0, -80);+ await body.evaluate((node) => { node.tabIndex = 0; node.focus({ preventScroll: true }); });+ await page.keyboard.press("ArrowUp");+ await stableLayout(body);+ await expect(slot).toHaveCSS("height", "48px");+ await expect.poll(() => displacement(body)).toBe(0);+ expect((await historyGeometry(body, "Question 40")).slotBeforeKey).toBe("u40");+ await expectCoordinates(body, "Question 40", held);+ expect(history.reads).toEqual(["?limit=120&before=40", "?limit=120&before=40"]);++ history.complete();+ await expect(body.getByText("Question 28", { exact: true })).toBeAttached();+ await expect(header).toHaveCount(0);+ await expect(blocks).toHaveCount(0);+ await stableLayout(body);+ await expect(slot).toHaveCount(0);+ expect((await historyGeometry(body, "Question 40")).slotBeforeKey).toBeNull();+ await expectAnchorCoordinate(body, "Question 40", held.anchorTop);+ expect(history.reads).toHaveLength(2);+});++test("cross-path unloaded rail jump has visible navigation feedback outside a scrolled-away older slot", async ({ page }) => {+ const history = await installHistory(page);+ await page.setViewportSize({ width: 1440, height: 900 });+ const { body, slot } = await openSettledHistory(page, "&navigate=1");+ await positionAtTop(body);+ await requestOlderWithWheel(body, history, 1);+ history.complete();+ await expect(body.getByText("Question 28", { exact: true })).toBeAttached();+ await expect(slot).toHaveCount(0);+ await body.hover();+ await page.mouse.wheel(0, 128);+ // Start the replacement away from the old bottom so setup cannot prefetch newer.+ await positionAtTop(body);+ await stableLayout(body);+ await expect(slot).toHaveCount(0);++ await jumpViaRail(page, 10);+ await expect.poll(() => history.reads.length).toBe(2);+ await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();+ await expect(slot.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);+ history.complete("error");+ const retry = page.getByRole("button", { name: "Loading failed. Retry", exact: true });+ await expect(retry).toBeInViewport();+ await expect(slot.locator('.thread-history-status[data-state="error"]')).toHaveCount(0);+ await retry.click();+ await expect.poll(() => history.reads.length).toBe(3);+ await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();+ expect(history.reads).toEqual(["?limit=120&before=40", "?limit=24&after=10", "?limit=24&after=10"]);+ history.complete();+ await expect(body.getByText("Question 10", { exact: true })).toBeInViewport();+ await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);+ await expect(retry).toHaveCount(0);+});++test("cross-path newer has visible navigation feedback and forward input retries newer after its older slot scrolls away", async ({ page }) => {+ const history = await installHistory(page);+ await page.setViewportSize({ width: 1440, height: 900 });+ const { body, slot } = await openSettledHistory(page, "&navigate=1");+ await positionAtTop(body);+ await stableLayout(body);+ await jumpViaRail(page, 10);+ await expect.poll(() => history.reads.length).toBe(1);+ history.complete();+ await expect(body.getByText("Question 10", { exact: true })).toBeInViewport();+ await stableLayout(body);+ await positionAtTop(body);+ await requestOlderWithWheel(body, history, 2);+ history.complete();+ await expect(body.getByText("Question 0", { exact: true })).toBeAttached();+ await expect(slot).toHaveCount(0);+ await expect.poll(() => displacement(body)).toBe(0);+ await body.hover();+ await page.mouse.wheel(0, 128);+ await expect(slot).toHaveCount(0);+ await page.mouse.wheel(0, 10000);+ await expect.poll(() => history.reads.length).toBe(3);+ await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();+ await expect(slot.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);+ history.complete("error");+ const retry = page.getByRole("button", { name: "Loading failed. Retry", exact: true });+ await expect(retry).toBeInViewport();+ await expect(slot.locator('.thread-history-status[data-state="error"]')).toHaveCount(0);+ await stableLayout(body);+ expect(history.reads).toHaveLength(3);+ await body.hover();+ await page.mouse.wheel(0, 120);+ await expect.poll(() => history.reads.length).toBe(4);+ await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();+ expect(history.reads).toEqual(["?limit=24&after=10", "?limit=24&before=10", "?limit=24&after=22", "?limit=24&after=22"]);+ history.complete();+ await expect(body.getByText("Question 33", { exact: true })).toBeAttached();+ await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);+ await expect(retry).toHaveCount(0);+});++test("cross-path older errors never float after latest or a loaded rail jump, but boundary retry remains available", async ({ page }) => {+ const history = await installHistory(page);+ await page.setViewportSize({ width: 1440, height: 900 });+ const body = page.getByTestId("thread-message-region");+ const retry = page.getByRole("button", { name: "Loading failed. Retry", exact: true });+ for (const destination of ["latest", "loaded prompt"] as const) {+ await test.step(destination, async () => {+ const initialReads = history.reads.length;+ await openSettledHistory(page, "&navigate=1");+ await positionAtTop(body);+ await requestOlderWithWheel(body, history, initialReads + 1);+ history.complete("error");+ await expect(retry).toBeInViewport();+ await expectHeld(body, "Question 40");++ if (destination === "latest") {+ await page.getByRole("button", { name: "Scroll to bottom", exact: true }).click();+ await expect(body.getByText("Question 51", { exact: true })).toBeInViewport();+ } else {+ await jumpViaRail(page, 46);+ await expect(body.getByText("Question 46", { exact: true })).toBeInViewport();+ }+ await stableLayout(body);+ await expect.soft(page.locator('.thread-viewport-frame > .thread-history-status[data-state="error"]')).toHaveCount(0, { timeout: 1000 });+ await expect.soft(retry).not.toBeInViewport({ timeout: 1000 });+ await body.hover();+ await page.mouse.wheel(0, -64);+ await stableLayout(body);+ await expect.soft(retry).not.toBeInViewport({ timeout: 1000 });+ expect(history.reads).toHaveLength(initialReads + 1);++ await positionAtTop(body);+ await retry.focus();+ await expect(retry).toBeInViewport();+ expect(history.reads).toHaveLength(initialReads + 1);+ await retry.click();+ await expect.poll(() => history.reads.length).toBe(initialReads + 2);+ expect(history.reads.slice(initialReads)).toEqual(["?limit=120&before=40", "?limit=120&before=40"]);+ history.complete();+ await expect(body.getByText("Question 28", { exact: true })).toBeAttached();+ await expect(body.locator(".thread-history-slot")).toHaveCount(0);+ await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);+ });+ }+});+++test("bounded navigation retains three pages and reclaims each completed wheel or keyboard boundary slot", 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");+ const header = page.locator(".thread-history-status");+ const slot = body.locator(".thread-history-slot");+ const approachNextHead = async (text: string) => {+ // Real scrolling stops just short of the boundary, before it can request.+ const scrollTop = await body.evaluate((node) => node.scrollTop);+ expect(scrollTop).toBeGreaterThan(120);+ await body.hover();+ await page.mouse.wheel(0, 120 - scrollTop);+ await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeCloseTo(120, 0);+ await stableLayout(body);+ await expect(header).not.toBeInViewport();+ return historyGeometry(body, text);+ };+ await expect(body.getByText("Question 40", { exact: true })).toBeAttached();+ await expect(body.getByText("Question 38", { exact: true })).toHaveCount(0);+ await stableLayout(body);+ // Keep the replacement away from latest's bottom so setup cannot prefetch newer.+ await positionAtTop(body);+ await stableLayout(body);+ expect(history.reads).toHaveLength(0);++ // An unloaded rail destination replaces latest with P0 (38..49).+ await jumpViaRail(page, 38);+ await expect.poll(() => history.reads.length).toBe(1);+ history.complete();+ await expect(body.getByText("Question 38", { exact: true })).toBeInViewport();+ await expect(body.getByText("Question 49", { exact: true })).toBeAttached();+ await stableLayout(body);+ await positionAtTop(body);+ await requestOlderWithWheel(body, history, 2);+ await expect(header).toHaveAttribute("data-state", "loading");+ const held = await expectHeld(body, "Question 38");+ expect(held.slotBeforeKey).toBe("u38");++ await completePrepend(history, body, "Question 26", "Question 38", held.anchorTop);+ expect((await historyGeometry(body, "Question 38")).slotBeforeKey).toBeNull();+ await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(24);++ // Reach each prepended page head instead of loading from the old reading slot.+ const atSecondHead = await approachNextHead("Question 26");+ expect(atSecondHead.firstKey).toBe("u26");+ expect(atSecondHead.slotBeforeKey).toBeNull();+ expect(history.reads).toHaveLength(2);+ await page.mouse.wheel(0, -120);+ await expect.poll(() => history.reads.length).toBe(3);+ await expect(header).toHaveAttribute("data-state", "loading");+ const secondHeld = await expectHeld(body, "Question 26");+ expect(secondHeld.slotBeforeKey).toBe("u26");+ expect(secondHeld.anchorTop - atSecondHead.anchorTop - atSecondHead.scrollTop).toBeCloseTo(48, 0);+ await completePrepend(history, body, "Question 14", "Question 26", secondHeld.anchorTop);+ expect((await historyGeometry(body, "Question 26")).slotBeforeKey).toBeNull();+ await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(36);++ // Completed feedback is removed and cannot add a fourth cached page.+ await expect(header).toHaveCount(0);+ await stableLayout(body);+ await expect(page.getByText("No earlier messages", { exact: true })).toHaveCount(0);+ await expect(slot).toHaveCount(0);+ await expectAnchorCoordinate(body, "Question 26", secondHeld.anchorTop);+ expect((await historyGeometry(body, "Question 26")).slotBeforeKey).toBeNull();+ expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26"]);++ const atNewHead = await approachNextHead("Question 14");+ expect(atNewHead.firstKey).toBe("u14");+ expect(atNewHead.slotBeforeKey).toBeNull();+ expect(history.reads).toHaveLength(3);+ await page.mouse.wheel(0, -120);+ await expect.poll(() => history.reads.length).toBe(4);+ await expect(header).toHaveAttribute("data-state", "loading");+ const newHeld = await expectHeld(body, "Question 14");+ expect(newHeld.slotBeforeKey).toBe("u14");+ expect(newHeld.anchorTop - atNewHead.anchorTop - atNewHead.scrollTop).toBeCloseTo(48, 0);+ await completePrepend(history, body, "Question 2", "Question 14", newHeld.anchorTop);+ await expect(slot).toHaveCount(0);+ const completed = await historyGeometry(body, "Question 14");+ expect(completed.slotBeforeKey).toBeNull();+ expect(completed.firstKey).toBe("u2");+ await expect(body.getByText("Question 37", { exact: true })).toBeAttached();+ await expect(body.getByText("Question 38", { exact: true })).toHaveCount(0);+ await expect(body.getByText("Question 49", { exact: true })).toHaveCount(0);+ await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(36);+ await expect(header).toHaveCount(0);+ await expect(page.getByText("No earlier messages", { exact: true })).toHaveCount(0);+ expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26", "?limit=24&before=14"]);++ // A real Home key reaches the next boundary and rebinds without a wheel pull.+ const atKeyboardHead = await approachNextHead("Question 2");+ expect(atKeyboardHead.firstKey).toBe("u2");+ expect(atKeyboardHead.slotBeforeKey).toBeNull();+ await body.evaluate((node) => { node.tabIndex = 0; node.focus({ preventScroll: true }); });+ expect(history.reads).toHaveLength(4);+ await page.keyboard.press("Home");+ await expect.poll(() => history.reads.length).toBe(5);+ await expect(header).toHaveAttribute("data-state", "loading");+ const keyboardHeld = await expectHeld(body, "Question 2");+ expect(keyboardHeld.slotBeforeKey).toBe("u2");+ expect(keyboardHeld.anchorTop - atKeyboardHead.anchorTop - atKeyboardHead.scrollTop).toBeCloseTo(48, 0);+ history.complete();+ await expect(body.getByText("Question 0", { exact: true })).toBeAttached();+ await stableLayout(body);+ await expectAnchorCoordinate(body, "Question 2", keyboardHeld.anchorTop);+ await body.evaluate((node) => { node.scrollTop = 0; node.dispatchEvent(new Event("scroll")); });+ await stableLayout(body);+ await expect(header).toHaveAttribute("data-state", "exhausted");+ await expect(slot).toHaveCount(0);+ const keyboardCompleted = await historyGeometry(body, "Question 2");+ expect(keyboardCompleted.slotBeforeKey).toBeNull();+ expect(keyboardCompleted.firstKey).toBe("u0");+ await expect(body.getByText("Question 25", { exact: true })).toBeAttached();+ await expect(body.getByText("Question 26", { exact: true })).toHaveCount(0);+ await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(26);+ expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26", "?limit=24&before=14", "?limit=24&before=2"]);+});+++async function historyBoundarySpacing(body: Locator, boundaryText: string, referenceText: string) {+ return body.evaluate((node, texts) => {+ const units = Array.from(node.querySelectorAll<HTMLElement>("[data-thread-display-unit]"));+ const unitFor = (text: string) => {+ const content = Array.from(node.querySelectorAll<HTMLElement>("[data-user-prompt-id], p"))+ .find((element) => element.textContent?.trim() === text);+ return content?.closest<HTMLElement>("[data-thread-display-unit]") ?? null;+ };+ const gapBefore = (unit: HTMLElement | null) => {+ if (!unit) return null;+ const index = units.indexOf(unit);+ const previous = units[index - 1];+ return previous ? unit.getBoundingClientRect().top - previous.getBoundingClientRect().bottom : null;+ };+ return {+ boundaryGap: gapBefore(unitFor(texts.boundaryText)),+ referenceGap: gapBefore(unitFor(texts.referenceText)),+ slotCount: node.querySelectorAll(".thread-history-slot").length,+ };+ }, { boundaryText, referenceText });+}++async function expectAnchorCoordinate(body: Locator, text: string, expectedTop: number) {+ await expect.poll(async () => Math.abs(await anchorTop(body, text) - expectedTop)).toBeLessThan(1);+}+++test("history Blocks use muted loading and destructive error colors in light and dark themes", async ({ browser }) => {+ for (const colorScheme of ["light", "dark"] as const) {+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme });+ const page = await context.newPage();+ const history = await installHistory(page);+ await page.goto(`http://127.0.0.1:${process.env.NANOBOT_BROWSER_TEST_PORT ?? 4178}/browser/fixture.html?case=history-boundary`);+ if (colorScheme === "dark") await page.locator("html").evaluate((node) => node.classList.add("dark"));+ const body = page.getByTestId("thread-message-region");+ await expect(body).toBeVisible();+ await stableLayout(body);+ await positionAtTop(body);+ await requestOlderWithWheel(body, history, 1);+ const loadingBlocks = page.locator('.thread-history-status[data-state="loading"] .thread-history-blocks');+ const loadingColor = await loadingBlocks.evaluate((node) => getComputedStyle(node).color);+ const mutedColor = await themeColor(loadingBlocks, "--muted-foreground");+ expect(loadingColor).toBe(mutedColor);+ history.complete("error");+ const retry = page.getByRole("button", { name: "Loading failed. Retry", exact: true });+ const errorBlocks = retry.locator(".thread-history-blocks");+ const errorColor = await errorBlocks.evaluate((node) => getComputedStyle(node).color);+ const destructiveColor = await themeColor(errorBlocks, "--destructive");+ expect(errorColor).toBe(destructiveColor);+ expect(errorColor).not.toBe(loadingColor);+ console.log(`history-colors ${colorScheme} loading=${loadingColor} error=${errorColor}`);+ await test.info().attach(`history-colors-${colorScheme}`, {+ body: JSON.stringify({ colorScheme, loadingColor, mutedColor, errorColor, destructiveColor }),+ contentType: "application/json",+ });+ await page.close();+ }+});diff --git a/webui/bun.lock b/webui/bun.lockindex 171e138d7..aeb72bb69 100644--- a/webui/bun.lock+++ b/webui/bun.lock@@ -21,6 +21,7 @@"lucide-react": "^0.469.0","micromark-factory-space": "^2.0.1","micromark-util-decode-string": "^2.0.1",+ "motion": "^14.4.0","pele": "1.6.0","qrcode": "^1.5.4","react": "^18.3.1",@@ -628,6 +629,8 @@"fraction.js": ["[email protected]", "", {}, "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ=="],+ "framer-motion": ["[email protected]", "https://mirrors.tencent.com/npm/framer-motion/-/framer-motion-14.4.0.tgz", { "dependencies": { "motion-dom": "14.4.0", "motion-utils": "14.1.1", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-HtO1fxord2rnXYRyr1laG4uY7+OtgwDc9Szcg1wlMq/LF7BO3/S7a+KEo691U7pSi+i0ueRuRqaD1UaLEmZHuQ=="],+"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],"function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],@@ -890,6 +893,12 @@"minipass": ["[email protected]", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="],+ "motion": ["[email protected]", "https://mirrors.tencent.com/npm/motion/-/motion-14.4.0.tgz", { "dependencies": { "framer-motion": "14.4.0", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-JJTIdeNjtF2zi/py0ndRKxQF+8z2pcDUgJYXul7zqbhMvyTLRsPFR9ifE/j4cFCpCMlehQVJkTwd7BZFiPKgQg=="],++ "motion-dom": ["[email protected]", "https://mirrors.tencent.com/npm/motion-dom/-/motion-dom-14.4.0.tgz", { "dependencies": { "motion-utils": "14.1.1" } }, "sha512-1q8RyHSdr5COpzrv3JgJ9XRjOO88ZN9CwflpkGgyO/SR/SNRP/dD6EU8SEo092kcKY34IzHC5diJPKrQRMA8lQ=="],++ "motion-utils": ["[email protected]", "https://mirrors.tencent.com/npm/motion-utils/-/motion-utils-14.1.1.tgz", {}, "sha512-3VvN5Uvf8B6qG+OfOui6Nht5EWp+vLuU3IqcAj7ItZGKqtmTjCebl5sGZF7/08gEHRnEl1AP/fIwbcEyVrcQGQ=="],+"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],"mz": ["[email protected]", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="],diff --git a/webui/package-lock.json b/webui/package-lock.jsonindex 98fd545dd..a5314d770 100644--- a/webui/package-lock.json+++ b/webui/package-lock.json@@ -24,6 +24,7 @@"lucide-react": "^0.469.0","micromark-factory-space": "^2.0.1","micromark-util-decode-string": "^2.0.1",+ "motion": "^14.4.0","pele": "1.6.0","qrcode": "^1.5.4","react": "^18.3.1",@@ -4128,6 +4129,29 @@"url": "https://github.com/sponsors/rawify"}},+ "node_modules/framer-motion": {+ "version": "14.4.0",+ "resolved": "https://mirrors.tencent.com/npm/framer-motion/-/framer-motion-14.4.0.tgz",+ "integrity": "sha512-HtO1fxord2rnXYRyr1laG4uY7+OtgwDc9Szcg1wlMq/LF7BO3/S7a+KEo691U7pSi+i0ueRuRqaD1UaLEmZHuQ==",+ "license": "MIT",+ "dependencies": {+ "motion-dom": "14.4.0",+ "motion-utils": "14.1.1",+ "tslib": "^2.4.0"+ },+ "peerDependencies": {+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ }+ }+ },"node_modules/fsevents": {"version": "2.3.3","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",@@ -6083,6 +6107,43 @@"node": ">=16 || 14 >=14.17"}},+ "node_modules/motion": {+ "version": "14.4.0",+ "resolved": "https://mirrors.tencent.com/npm/motion/-/motion-14.4.0.tgz",+ "integrity": "sha512-JJTIdeNjtF2zi/py0ndRKxQF+8z2pcDUgJYXul7zqbhMvyTLRsPFR9ifE/j4cFCpCMlehQVJkTwd7BZFiPKgQg==",+ "license": "MIT",+ "dependencies": {+ "framer-motion": "14.4.0",+ "tslib": "^2.4.0"+ },+ "peerDependencies": {+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/motion-dom": {+ "version": "14.4.0",+ "resolved": "https://mirrors.tencent.com/npm/motion-dom/-/motion-dom-14.4.0.tgz",+ "integrity": "sha512-1q8RyHSdr5COpzrv3JgJ9XRjOO88ZN9CwflpkGgyO/SR/SNRP/dD6EU8SEo092kcKY34IzHC5diJPKrQRMA8lQ==",+ "license": "MIT",+ "dependencies": {+ "motion-utils": "14.1.1"+ }+ },+ "node_modules/motion-utils": {+ "version": "14.1.1",+ "resolved": "https://mirrors.tencent.com/npm/motion-utils/-/motion-utils-14.1.1.tgz",+ "integrity": "sha512-3VvN5Uvf8B6qG+OfOui6Nht5EWp+vLuU3IqcAj7ItZGKqtmTjCebl5sGZF7/08gEHRnEl1AP/fIwbcEyVrcQGQ==",+ "license": "MIT"+ },"node_modules/ms": {"version": "2.1.3","license": "MIT"diff --git a/webui/package.json b/webui/package.jsonindex e5805aa3e..8fd6eedce 100644--- a/webui/package.json+++ b/webui/package.json@@ -34,6 +34,7 @@"lucide-react": "^0.469.0","micromark-factory-space": "^2.0.1","micromark-util-decode-string": "^2.0.1",+ "motion": "^14.4.0","pele": "1.6.0","qrcode": "^1.5.4","react": "^18.3.1",diff --git a/webui/src/components/thread/ThreadHistoryStatus.tsx b/webui/src/components/thread/ThreadHistoryStatus.tsxindex 67e4c66f2..9d8e6001c 100644--- a/webui/src/components/thread/ThreadHistoryStatus.tsx+++ b/webui/src/components/thread/ThreadHistoryStatus.tsx@@ -8,14 +8,16 @@ interface ThreadHistoryStatusProps {loading: boolean;error: string | null;exhausted?: boolean;+ preview?: boolean;onRetry: () => void;className?: string;}-export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatusProps>(function ThreadHistoryStatus({ loading, error, exhausted = false, onRetry, className }, ref) {+export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatusProps>(function ThreadHistoryStatus({ loading, error, exhausted = false, preview = false, onRetry, className }, ref) {const { t } = useTranslation();- const state = !loading && error ? "error" : !loading && exhausted ? "exhausted" : "loading";- const label = t(state === "error" ? "thread.history.retryLabel" : `thread.history.${state}`);+ const state = loading ? "loading" : error ? "error" : exhausted ? "exhausted" : "ready";+ const hidden = state === "ready" && !preview;+ const label = state === "ready" ? undefined : 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}@@ -25,20 +27,21 @@ export const ThreadHistoryStatus = forwardRef<HTMLDivElement, ThreadHistoryStatureturn (<divref={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)}+ className={cn("thread-history-status thread-message-row pointer-events-none absolute inset-x-0 top-0 z-10 flex items-center justify-center", hidden && "invisible", className)}+ aria-hidden={hidden || undefined}data-state={state}><div role="status" aria-live="polite" aria-atomic="true">{state === "exhausted" ? (<span className="text-xs">{label}</span>- ) : (+ ) : state === "ready" ? blocks : (<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}+ <button type="button" aria-label={label} 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>diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsxindex 106cd6195..54fab66d0 100644--- a/webui/src/components/thread/ThreadMessages.tsx+++ b/webui/src/components/thread/ThreadMessages.tsx@@ -23,6 +23,8 @@ import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage }interface ThreadMessagesProps {messages: UIMessage[];beforeMessages?: ReactNode;+ beforeUnit?: { key: string; content: ReactNode };+ topInset?: number;afterUserMessage?: (message: UIMessage) => ReactNode;afterMessages?: ReactNode;temporary?: boolean;@@ -81,6 +83,8 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] {export function ThreadMessages({messages,beforeMessages,+ beforeUnit,+ topInset = 0,afterUserMessage,afterMessages,temporary = false,@@ -174,6 +178,11 @@ export function ThreadMessages({setOpenContextBlockKey((current) => open ? key : current === key ? null : current);}, []);let nextUserIndex = hiddenUserMessageCount;+ const preludeIndex = Math.max(0, beforeUnit ? unitKeys.indexOf(beforeUnit.key) : 0);+ const inset = topInset > 0 ? <div aria-hidden style={{ height: topInset }} /> : null;+ const preludeInset = preludeIndex === 0 ? inset : null;+ const renderPrelude = (prefix: ReactNode, marginTop?: string) => prefix || preludeInset || beforeMessages+ ? <div key="thread-prelude" className={cn("flow-root", marginTop)}>{prefix}{preludeInset}{beforeMessages}</div> : null;return (<div ref={messageListRef} className="flex w-full flex-col">@@ -181,8 +190,10 @@ export function ThreadMessages({containerRef={messageListRef}onQuoteSelection={onQuoteSelection}/>- {beforeMessages}- {units.map((unit, index) => {+ {[+ preludeIndex > 0 ? <Fragment key="top-inset">{inset}</Fragment> : null,+ units.length === 0 ? renderPrelude(null) : null,+ ...units.flatMap((unit, index) => {const next = units[index + 1];const hasBodyBelow =unit.type === "activity"@@ -233,14 +244,17 @@ export function ThreadMessages({&& unit.message.deliveryStatus !== "failed") nextUserIndex += 1;- return (- <Fragment key={unitKeys[index]}>+ const prefix = beforeUnit?.key === unitKeys[index] ? beforeUnit.content : null;+ const prelude = index === preludeIndex ? renderPrelude(prefix, marginTop) : null;+ return [+ prelude,+ <Fragment key={`unit:${unitKeys[index]}`}><ThreadDisplayUnitkey={unitKeys[index]}unitKey={unitKeys[index]}unit={unit}mobileActions={mobileActions}- marginTop={marginTop}+ marginTop={prelude ? "" : marginTop}userPromptId={userPromptId}hasBodyBelow={hasBodyBelow}suppressActivity={suppressActivity}@@ -279,9 +293,9 @@ export function ThreadMessages({{unit.type === "message" && unit.message.role === "user" ? (afterUserMessage?.(unit.message)) : null}- </Fragment>- );- })}+ </Fragment>,+ ];+ })]}{afterMessages}{pendingActivity ? (<div className={cn("thread-message-row", units.length > 0 && "mt-5")}>diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsxindex 0414ea0ec..2c2632cff 100644--- a/webui/src/components/thread/ThreadShell.tsx+++ b/webui/src/components/thread/ThreadShell.tsx@@ -900,6 +900,7 @@ export function ThreadShell({activeHistoryKeyRef.current = historyKey;const currentUiMessagesRef = useRef<UIMessage[] | null>(null);const uiRevisionRef = useRef(0);+ const olderPageStartRef = useRef<{ historyKey: string; client: typeof client; visibleFirstId: string | null } | null>(null);const showTemporaryChatControl =!hideHeader && !session && !loading && !!onTemporaryChatEnabledChange;@@ -945,6 +946,35 @@ export function ThreadShell({const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages);const updateNavigationMessages = promptNavigation.updateMessages;+ const olderPageProjectionPending = Boolean(+ olderPageStartRef.current?.historyKey === historyKey+ && olderPageStartRef.current.client === client+ && !loadingOlder+ && !olderError+ && normalizedHistory[0]?.id !== olderPageStartRef.current.visibleFirstId+ && displayMessages[0]?.id !== normalizedHistory[0]?.id,+ );+ useLayoutEffect(() => {+ const pending = olderPageStartRef.current;+ if (pending && (pending.historyKey !== historyKey || pending.client !== client)) {+ olderPageStartRef.current = null;+ }+ if (!historyKey) {+ olderPageStartRef.current = null;+ } else if (loadingOlder) {+ // The request may finish before this shell commits the rendered projection.+ if (!olderPageStartRef.current) {+ olderPageStartRef.current = {+ historyKey,+ client,+ visibleFirstId: normalizedHistory[0]?.id ?? null,+ };+ }+ } else if (olderError || !olderPageProjectionPending) {+ olderPageStartRef.current = null;+ }+ }, [client, displayMessages, historyKey, loadingOlder, olderError, olderPageProjectionPending, normalizedHistory]);+const loadTraceDetails = useCallback(async (refs: string[]) => {const requestKey = historyKey;if (!requestKey) return;@@ -2101,7 +2131,7 @@ export function ThreadShell({slashCommands={availableSlashCommands}forkBoundaryMessageCount={forkBoundaryMessageCount}hasMoreBefore={hasMoreBefore}- loadingOlder={loadingOlder}+ loadingOlder={loadingOlder || olderPageProjectionPending}olderError={olderError}userMessageOffset={userMessageOffset}onLoadOlder={loadOlder}diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsxindex e9267949e..87c20f3e5 100644--- a/webui/src/components/thread/ThreadViewport.tsx+++ b/webui/src/components/thread/ThreadViewport.tsx@@ -18,7 +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 { HISTORY_HOLD_PX, ThreadHistorySpring, type HistoryRevealPhase } from "@/components/thread/thread-history-spring";import {ThreadMotionCoordinator,type ThreadMotionGeometry,@@ -93,7 +93,7 @@ interface HistoryScrollAnchor {const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]";function promptTopInset(scroller: HTMLElement): number {- const padding = Number.parseFloat(getComputedStyle(scroller).paddingTop);+ const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop);return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX;}@@ -236,8 +236,16 @@ 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`);+function setHistoryPresentation(+ scroller: HTMLDivElement | null,+ status: HTMLDivElement | null,+ slot: HTMLDivElement | null,+ distance: number,+): void {+ // A retained inline slot replaces the same amount of presentation travel.+ const travel = distance - (slot ? HISTORY_HOLD_PX : 0);+ if (scroller) scroller.style.transform = travel ? `translateY(${travel}px)` : "";+ status?.style.setProperty("--history-pull", `${distance}px`);}export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProps>(function ThreadViewport({@@ -279,8 +287,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProconst activeTurnId = historyWindow ? null : liveTurnId;const forkBoundaryMessageCount = historyWindow ? historyWindow.forkBoundaryMessageCount : latestForkBoundary;const hasMoreBefore = historyWindow?.hasMoreBefore ?? latestHasMoreBefore;- const loadingOlder = historyWindow ? navigation!.loading : latestLoadingOlder;- const olderError = historyWindow ? navigation!.error : latestOlderError;+ const loadingOlder = historyWindow ? navigation!.operation === "older" && navigation!.loading : latestLoadingOlder;+ const olderError = historyWindow ? navigation!.operation === "older" ? navigation!.error : null : latestOlderError;const userMessageOffset = historyWindow?.userMessageOffset ?? latestUserOffset;const onLoadOlder = historyWindow ? navigation!.older : loadLatestOlder;const scrollRef = useRef<HTMLDivElement | null>(null);@@ -299,10 +307,17 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProconst restoreScrollAfterPrependRef =useRef<{ height: number; top: number } | null>(null);const historyScrollAnchorRef = useRef<HistoryScrollAnchor | null>(null);+ const previousLoadingOlderRef = useRef(loadingOlder);const composerDockHeightRef = useRef(0);const [atBottom, setAtBottom] = useState(true);const [atHistoryTop, setAtHistoryTop] = useState(false);- const [historyFeedbackActive, setHistoryFeedbackActive] = useState(false);+ const [historyPhase, setHistoryPhase] = useState<HistoryRevealPhase>("hidden");+ const historyPhaseRef = useRef(historyPhase);+ const [historySlotKey, setHistorySlotKey] = useState<string | null>(null);+ const historySlotCompleted = previousLoadingOlderRef.current && !loadingOlder && !olderError && historySlotKey !== null;+ const retainedHistorySlotKey = historySlotCompleted ? null : historySlotKey;+ const [showHistoryExhausted, setShowHistoryExhausted] = useState(false);+ const historySlotRef = useRef<HTMLDivElement | null>(null);const historyInputRef = useRef<"touch" | "other">("other");const historyTouchRef = useRef<{lastY: number; startX: number; startY: number; pulling: boolean; horizontal: boolean;@@ -312,15 +327,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProconst historySpringRef = useRef<ThreadHistorySpring | null>(null);if (historySpringRef.current === null) {historySpringRef.current = new ThreadHistorySpring({- onFeedbackChange: setHistoryFeedbackActive,+ onPhaseChange: (phase) => {+ const previous = historyPhaseRef.current;+ historyPhaseRef.current = phase;+ setHistoryPhase(phase);+ if (phase === "hidden" && previous === "feedback") setShowHistoryExhausted(false);+ },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);+ setHistoryPresentation(messageRegionRef.current, historyStatusRef.current, historySlotRef.current, distance);},});}@@ -329,11 +344,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro// 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)`;+ setHistoryPresentation(element, historyStatusRef.current, historySlotRef.current, historyDistanceRef.current);}, []);const setHistoryStatus = useCallback((element: HTMLDivElement | null) => {historyStatusRef.current = element;- setHistoryStatusTravel(element, historyDistanceRef.current);+ setHistoryPresentation(messageRegionRef.current, element, historySlotRef.current, historyDistanceRef.current);+ }, []);+ const setHistorySlot = useCallback((element: HTMLDivElement | null) => {+ historySlotRef.current = element;+ setHistoryPresentation(messageRegionRef.current, historyStatusRef.current, element, historyDistanceRef.current);}, []);const [composerDockHeight, setComposerDockHeight] = useState(0);const [keyboardInsetBottom, setKeyboardInsetBottom] = useState(0);@@ -391,10 +410,6 @@ 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],@@ -443,7 +458,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro}historyScrollAnchorRef.current = {key,- offsetTop: element.getBoundingClientRect().top - viewport.top,+ // Normalize out the reveal lease, even when reading above its inline slot.+ offsetTop: element.getBoundingClientRect().top - viewport.top+ - (historySlotRef.current ? HISTORY_HOLD_PX : 0),};return true;}, []);@@ -463,7 +480,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProconst nextOffset =element.getBoundingClientRect().top- - scroller.getBoundingClientRect().top;+ - scroller.getBoundingClientRect().top+ - (historySlotRef.current ? HISTORY_HOLD_PX : 0);const delta = nextOffset - anchor.offsetTop;if (Math.abs(delta) < 0.5) return true;const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);@@ -472,8 +490,29 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProreturn true;}, []);+ const resetHistoryHeader = useCallback(() => {+ setHistorySlotKey(null);+ historySpringRef.current?.reset();+ }, []);++ const holdHistoryHeader = useCallback(() => {+ // A request at a new boundary supersedes the old slot. Mid-page retry+ // keeps its original boundary, never a hit-tested answer or activity row.+ if (!historySlotRef.current || (scrollRef.current && scrollRef.current.scrollTop <= 1)) {+ const unit = messageContentRef.current?.querySelector<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR);+ if (unit?.dataset.threadDisplayUnit) setHistorySlotKey(unit.dataset.threadDisplayUnit);+ }+ historySpringRef.current?.hold();+ }, []);++ useLayoutEffect(() => {+ // Replaced history windows cannot retain a slot for an unmounted boundary.+ if (retainedHistorySlotKey && !historySlotRef.current) resetHistoryHeader();+ }, [retainedHistorySlotKey, resetHistoryHeader, visibleMessages]);+const scrollToBottomNow = useCallback((smooth = false) => {historyScrollAnchorRef.current = null;+ resetHistoryHeader();const el = scrollRef.current;const marker = bottomRef.current;const behavior: ScrollBehavior = smooth ? "smooth" : "auto";@@ -488,7 +527,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPromarker.scrollIntoView({ block: "end", behavior });}setAtBottom(true);- }, []);+ }, [resetHistoryHeader]);const scrollToBottom = useCallback((smooth = false, options?: { force?: boolean }) => {@@ -501,6 +540,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro);const loadEarlierMessages = useCallback(() => {+ if (loadingOlder || navigation?.loading) return;const el = scrollRef.current;if (el) {if (captureHistoryScrollAnchor()) {@@ -520,7 +560,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro);return;}- if (hasMoreBefore && onLoadOlder && !loadingOlder) {+ if (hasMoreBefore && onLoadOlder) {+ holdHistoryHeader();setVisibleMessageCount((count) => count + HISTORY_WINDOW_INCREMENT);void onLoadOlder();}@@ -528,8 +569,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProcaptureHistoryScrollAnchor,hasMoreBefore,hiddenMessageCount,+ holdHistoryHeader,loadingOlder,messages.length,+ navigation?.loading,onLoadOlder,]);@@ -548,16 +591,11 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProconst prompt = scrollEl ? findPromptElement(scrollEl, promptId) : null;if (!scrollEl || !prompt) return false;historyScrollAnchorRef.current = null;+ resetHistoryHeader();setAtBottom(false);- const maxScrollTop = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight);- threadMotionRef.current?.navigateHistoryTo(- Math.min(- maxScrollTop,- Math.max(0, promptTop(scrollEl, prompt) - promptTopInset(scrollEl)),- ),- );+ threadMotionRef.current?.navigateHistoryToPrompt(promptId);return true;- }, []);+ }, [resetHistoryHeader]);const jumpToUserPrompt = useCallback((promptId: string) => {// A local destination also supersedes an in-flight remote jump.@@ -654,7 +692,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProlastConversationKeyRef.current = conversationKey;historyTouchRef.current = null;historyInputRef.current = "other";- historySpringRef.current?.reset();+ resetHistoryHeader();conversationHandoffAnimationRef.current?.cancel();conversationHandoffAnimationRef.current = null;conversationHandoffPendingRef.current = true;@@ -663,6 +701,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProrestoreScrollAfterPrependRef.current = null;threadMotionRef.current?.reset();setAtBottom(true);+ setShowHistoryExhausted(false);setVisibleMessageCount(INITIAL_HISTORY_WINDOW);const surface = hasMessages ? messageRegionRef.current : emptyStateRef.current;@@ -677,7 +716,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProfill: "forwards",},);- }, [conversationKey, hasMessages]);+ }, [conversationKey, hasMessages, resetHistoryHeader]);useLayoutEffect(() => {if (!conversationReady) {@@ -722,6 +761,18 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro});}, [activeTurnId, activeTurnStartedHere, conversationReady, messages]);+ useLayoutEffect(() => {+ const wasLoading = previousLoadingOlderRef.current;+ previousLoadingOlderRef.current = loadingOlder;+ if (!wasLoading || loadingOlder || olderError || !historySlotKey) return;+ // The completed render already removed the slot. Rebase the saved anchor+ // by its live presentation travel before the single final-geometry read.+ const anchor = historyScrollAnchorRef.current;+ if (anchor) anchor.offsetTop += historyDistanceRef.current;+ setShowHistoryExhausted(historyExhausted);+ resetHistoryHeader();+ }, [loadingOlder, olderError, historySlotKey, historyExhausted, resetHistoryHeader]);+useLayoutEffect(() => {const pending = restoreScrollAfterPrependRef.current;const el = scrollRef.current;@@ -735,7 +786,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProMath.max(0, pending.top + delta),);threadMotionRef.current?.jumpTo(nextTop);- }, [reconcileHistoryScrollAnchor, visibleMessages.length, messages]);+ }, [reconcileHistoryScrollAnchor, visibleMessages.length, messages, loadingOlder]);useLayoutEffect(() => {const promptId = pendingPromptJumpRef.current;@@ -768,6 +819,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProscrollToBottom,]);+ useLayoutEffect(() => {+ // A request commits temporary space; successful completion reclaims it below.+ if (conversationReady && loadingOlder && scrollRef.current?.scrollTop === 0 && !historySlotRef.current) {+ holdHistoryHeader();+ }+ }, [conversationReady, loadingOlder, holdHistoryHeader]);+useLayoutEffect(() => {if (!conversationReady || !conversationHandoffPendingRef.current) return;conversationHandoffPendingRef.current = false;@@ -843,7 +901,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProconst onScroll = (allowHistoryLoad = true) => {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";@@ -865,15 +922,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProconst handleScroll = () => onScroll(true);const atHistoryBoundary = () => el.scrollTop <= 1 && messages.length > 0 && conversationReady&& !pendingConversationScrollRef.current;- const canLoadAtTop = () => atHistoryBoundary() && !loadingOlder- && (hiddenMessageCount > 0 || (hasMoreBefore && !olderError));+ const canLoadAtTop = () => atHistoryBoundary() && !loadingOlder && !navigation?.loading+ && (hiddenMessageCount > 0 || hasMoreBefore);const handleDirectionalInput = (direction: ThreadScrollDirection | null,) => {if (!direction) return;if (direction === "forward" && historyWindow?.hasMoreAfter&& el.scrollHeight - el.scrollTop - el.clientHeight < HISTORY_PREFETCH_MIN_PX- && !navigation?.loading && !navigation?.error) {+ && !navigation?.loading) {captureHistoryScrollAnchor();navigation?.newer();}@@ -888,6 +945,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProdirection === "forward",);};+ const prepareHistoryPull = () => {+ if (loadingOlder || navigation?.loading) return;+ const first = messageContentRef.current?.querySelector<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR);+ // A retained header belongs to the page boundary where it was opened,+ // not to a newer boundary reached by scrolling through prepended history.+ if (historySlotKey && first?.dataset.threadDisplayUnit !== historySlotKey) resetHistoryHeader();+ };const handleWheel = (event: WheelEvent) => {if (event.defaultPrevented@@ -901,13 +965,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProconst unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? 16: event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? el.clientHeight : 1;if (event.deltaY < 0) {+ prepareHistoryPull();yieldCameraToUser();setAtHistoryTop(true);const first = historySpringRef.current?.wheel(-event.deltaY * unit);- if (first && canLoadAtTop()) loadEarlierMessages();+ if ((first || olderError) && canLoadAtTop()) loadEarlierMessages();return;}- if (historyDistanceRef.current > 0) historySpringRef.current?.wheel(-event.deltaY * unit);}handleDirectionalInput(directionFromDelta(event.deltaY));};@@ -952,6 +1016,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProif (gesture.horizontal) return;if (gesture.pulling || (atHistoryBoundary() && delta < 0 && hiddenMessageCount === 0)) {if (!gesture.pulling) {+ prepareHistoryPull();historySpringRef.current?.startTouch();gesture.pulling = true;}@@ -991,7 +1056,6 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro}if (isKeyboardControl(event.target as Element | null)) return;historyInputRef.current = "other";- historySpringRef.current?.leaveBoundary();handleDirectionalInput(keyboardScrollDirection(event));};el.addEventListener("scroll", handleScroll, { passive: true });@@ -1024,10 +1088,27 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPromessages.length,olderError,yieldCameraToUser,+ historySlotKey,historyWindow,navigation,+ resetHistoryHeader,]);+ const navigationStatus = navigation?.operation !== "older" && Boolean(navigation?.loading || navigation?.error);+ const showHistoryStatus = !historySlotCompleted && !navigationStatus && messages.length > 0 && conversationReady+ && (atHistoryTop && (!historyExhausted || showHistoryExhausted) || historyPhase !== "hidden" || loadingOlder);+ const historyStatus = showHistoryStatus ? (+ <ThreadHistoryStatus+ ref={setHistoryStatus}+ loading={loadingOlder}+ error={olderError}+ exhausted={historyExhausted}+ preview={historyPhase === "feedback"}+ onRetry={loadEarlierMessages}+ className={!retainedHistorySlotKey && !(historyExhausted && showHistoryExhausted) ? cn("thread-history-reveal", historyPhase === "feedback" && "thread-history-feedback") : undefined}+ />+ ) : null;+return (<div className="thread-viewport relative flex min-h-0 flex-1 overflow-hidden"><div@@ -1062,7 +1143,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProdata-testid="thread-message-region"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-none pb-0 pt-12",+ "scroll-auto justify-start overflow-x-hidden overscroll-y-none pb-0 scroll-pt-12","[overflow-anchor:none] [scrollbar-width:none]","[&::-webkit-scrollbar]:hidden",hasVerticalOverflow ? "overflow-y-auto" : "overflow-hidden",@@ -1072,6 +1153,12 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro<DiagramScope identity={conversationKey}><SubagentThreadMessagesmessages={visibleMessages}+ topInset={PROMPT_TOP_INSET_PX}+ beforeUnit={retainedHistorySlotKey ? { key: retainedHistorySlotKey, content: (+ <div ref={setHistorySlot} className="thread-history-slot relative" style={{ height: HISTORY_HOLD_PX }}>+ {historyStatus}+ </div>+ ) } : undefined}temporary={temporary}isStreaming={isStreaming}activeTurnId={activeTurnId}@@ -1147,17 +1234,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro/>) : null}</div>- {navigation && (navigation.loading || navigation.error) ? (- <ThreadHistoryStatus ref={setHistoryStatus} loading={navigation.loading} error={navigation.error} onRetry={navigation.retry} />- ) : messages.length > 0 && conversationReady && ((atHistoryTop && (!historyExhausted || historyFeedbackActive)) || loadingOlder || olderError) ? (- <ThreadHistoryStatus- ref={setHistoryStatus}- loading={loadingOlder}- exhausted={historyExhausted}- error={olderError}- onRetry={loadEarlierMessages}- />- ) : null}+ {!retainedHistorySlotKey ? historyStatus : null}+ {navigationStatus && navigation ? <ThreadHistoryStatus loading={navigation.loading}+ error={navigation.error} onRetry={navigation.retry} /> : null}{!hasMessages ? <div ref={bottomRef} aria-hidden className="h-px" /> : null}</div>diff --git a/webui/src/components/thread/thread-history-spring.ts b/webui/src/components/thread/thread-history-spring.tsindex 02ffcc03c..95963879f 100644--- a/webui/src/components/thread/thread-history-spring.ts+++ b/webui/src/components/thread/thread-history-spring.ts@@ -1,168 +1,170 @@-import type { ThreadCameraScheduler } from "@/components/thread/thread-camera";+import { animate, motionValue, type AnimationPlaybackControls, type MotionValue } from "motion";export const HISTORY_PULL_LIMIT_PX = 80;-export const HISTORY_PULL_TRIGGER_PX = 42;-const LOADING_POCKET_PX = 20;+export const HISTORY_HOLD_PX = 48;+export const HISTORY_PULL_TRIGGER_PX = 56;const RESISTANCE_LENGTH_PX = 120;-const FREQUENCY = 22;-const DAMPING_RATIO = 0.78;++export type HistoryRevealPhase = "hidden" | "feedback" | "held";interface HistorySpringOptions {onUpdate: (distance: number) => void;- onFeedbackChange: (active: boolean) => void;- scheduler?: ThreadCameraScheduler;+ onPhaseChange: (phase: HistoryRevealPhase) => void;prefersReducedMotion?: () => boolean;}-/** Presentation only: the thread camera remains the sole scroll-position owner. */+/** Presentation only: Motion owns spring integration; 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 readonly value: MotionValue<number> = motionValue(0);+ private animation: AnimationPlaybackControls | null = null;+ private destination: number | null = null;+ private animationGeneration = 0;+ private phase: HistoryRevealPhase = "hidden";private dragging = false;private travel = 0;private wheelLatched = false;- private feedbackActive = 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"+ const preference = typeof window !== "undefined" && typeof window.matchMedia === "function"? window.matchMedia("(prefers-reduced-motion: reduce)") : null;- this.reducedMotion = options.prefersReducedMotion ?? (() => motionPreference?.matches ?? false);+ this.reducedMotion = options.prefersReducedMotion ?? (() => preference?.matches ?? false);+ this.value.on("change", this.publish);}- setLoading(loading: boolean): void {- if (this.loading === loading) return;- this.loading = loading;- if (!this.dragging) this.animate();+ hold(): void {+ this.wheelLatched = true;+ this.setPhase("held");+ this.animateTo(HISTORY_HOLD_PX);}wheel(travel: number): boolean {- if (this.dragging) return false;+ if (this.dragging || travel === 0) return false;const first = !this.wheelLatched && travel > 0;- this.wheelLatched = true;- if (travel > 0) this.setFeedbackActive(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();+ if (travel > 0) {+ this.wheelLatched = true;+ if (this.phase !== "held") this.setPhase("feedback");+ }+ const pressure = 1 - Math.exp(-Math.abs(travel) / RESISTANCE_LENGTH_PX);+ const current = this.boundedValue();+ const pressured = current + ((travel > 0 ? HISTORY_PULL_LIMIT_PX : 0) - current) * pressure;+ // Each packet retargets the same MotionValue; interruption keeps the live spring velocity.+ this.animateTo(Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, pressured)));return first;}startTouch(): void {- this.stopFrame();+ this.stopAnimation();+ const visible = this.boundedValue();+ this.value.set(visible);this.dragging = true;- this.setFeedbackActive(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));+ if (this.phase !== "held") this.setPhase("feedback");+ this.travel = -RESISTANCE_LENGTH_PX * Math.log(Math.max(Number.EPSILON, 1 - visible / HISTORY_PULL_LIMIT_PX));}moveTouch(travel: number): void {+ if (!this.dragging) return;this.travel = Math.max(0, this.travel + travel);- this.distance = HISTORY_PULL_LIMIT_PX * (1 - Math.exp(-this.travel / RESISTANCE_LENGTH_PX));- this.publish();+ this.value.set(HISTORY_PULL_LIMIT_PX * (1 - Math.exp(-this.travel / RESISTANCE_LENGTH_PX)));}endTouch(cancelled = false): boolean {- const triggered = this.dragging && !cancelled && this.distance >= HISTORY_PULL_TRIGGER_PX;+ if (!this.dragging) return false;+ const triggered = !cancelled && this.boundedValue() >= HISTORY_PULL_TRIGGER_PX;this.dragging = false;this.travel = 0;- this.publish();- this.animate();+ this.animateTo(this.restPosition());return triggered;}+ /** Native scrolling releases this input round, not the committed reveal. */leaveBoundary(): void {- this.loading = false;this.dragging = false;this.wheelLatched = false;- this.setFeedbackActive(false);- this.animate();+ if (this.reducedMotion() && this.phase !== "held") {+ this.stopAnimation();+ this.value.set(0);+ this.setPhase("hidden");+ return;+ }+ this.animateTo(this.restPosition());}reset(): void {- this.stopFrame();- this.distance = 0;- this.velocity = 0;- this.travel = 0;- this.loading = false;+ this.stopAnimation();this.dragging = false;+ this.travel = 0;this.wheelLatched = false;- this.setFeedbackActive(false);- this.publish();+ this.setPhase("hidden");+ this.value.set(0);+ }++ private readonly publish = (distance: number): void => {+ const bounded = Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, distance));+ this.options.onUpdate(this.phase !== "held" && this.reducedMotion() ? 0 : bounded);+ };++ private boundedValue(): number {+ return Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, this.value.get()));}- private setFeedbackActive(active: boolean): void {- if (this.feedbackActive === active) return;- this.feedbackActive = active;- this.options.onFeedbackChange(active);+ private restPosition(): number {+ return this.phase === "held" ? HISTORY_HOLD_PX : 0;}- private publish(): void {- // Reduced motion suppresses travel, not the input/settlement lifecycle.- this.options.onUpdate(this.reducedMotion() ? 0 : Math.max(0, this.distance));+ private setPhase(phase: HistoryRevealPhase): void {+ if (this.phase === phase) return;+ this.phase = phase;+ this.options.onPhaseChange(phase);}- private stopFrame(): void {- if (this.frame !== null) this.scheduler.cancel(this.frame);- this.frame = null;- this.timestamp = null;+ private stopAnimation(): void {+ this.animationGeneration++;+ this.animation?.stop();+ this.animation = null;+ this.destination = null;}- private animate(): void {- if (this.frame !== null) return;- if (this.distance === (this.loading ? LOADING_POCKET_PX : 0) && this.velocity === 0) {- if (!this.loading) {- this.wheelLatched = false;- this.setFeedbackActive(false);- }+ private animateTo(target: number): void {+ if (this.dragging) return;+ const next = Math.max(0, Math.min(HISTORY_PULL_LIMIT_PX, target));+ if (this.destination === next && this.animation) return;+ if (this.reducedMotion() && this.phase === "held") {+ this.stopAnimation();+ this.value.set(HISTORY_HOLD_PX);+ return;+ }+ if (Math.abs(this.value.get() - next) < 0.01) {+ this.stopAnimation();+ this.value.set(next);+ this.finish(next, this.animationGeneration);return;}- this.timestamp = this.scheduler.now();- this.frame = this.scheduler.request(this.advance);+ const generation = ++this.animationGeneration;+ this.destination = next;+ this.animation = animate(this.value, next, {+ type: "spring",+ stiffness: 484,+ damping: 34,+ mass: 1,+ onComplete: () => this.finish(next, generation),+ });}- private readonly advance = (timestamp: number): void => {- this.frame = null;- 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.setFeedbackActive(false);- }+ private finish(destination: number, generation: number): void {+ if (generation !== this.animationGeneration) return;+ this.animation = null;+ this.destination = null;+ this.value.set(destination);+ if (destination !== this.restPosition()) {+ this.animateTo(this.restPosition());+ return;}- this.publish();- if (!settled) this.frame = this.scheduler.request(this.advance);- };+ if (destination === 0 && this.phase !== "held") {+ this.wheelLatched = false;+ this.setPhase("hidden");+ }+ }}diff --git a/webui/src/components/thread/thread-motion.ts b/webui/src/components/thread/thread-motion.tsindex bac1b1bfc..42780b701 100644--- a/webui/src/components/thread/thread-motion.ts+++ b/webui/src/components/thread/thread-motion.ts@@ -71,6 +71,7 @@ const THREAD_MOTION_TRANSITIONS: Readonly<"navigation-settled": "current-automatic-mode","user-scroll": "browsing-history","boundary-scroll": "browsing-history",+ "composer-input": "idle","resume-follow": "current-automatic-mode",},"navigating-history": {@@ -79,6 +80,7 @@ const THREAD_MOTION_TRANSITIONS: Readonly<"navigation-settled": "browsing-history","user-scroll": "browsing-history","boundary-scroll": "browsing-history",+ "composer-input": "browsing-history","resume-follow": "current-automatic-mode",},"browsing-history": {@@ -164,6 +166,7 @@ export class ThreadMotionCoordinator {hasOutput: false,};private mode: ThreadMotionMode = "idle";+ private historyNavigationPromptId: string | null = null;private promptPositioned = false;private measurementFrameId: number | null = null;private geometryDirty = false;@@ -309,12 +312,21 @@ export class ThreadMotionCoordinator {}navigateHistoryTo(top: number): ThreadCameraFollowResult | null {- this.camera.cancel();+ return this.beginHistoryNavigation(top, null);+ }++ navigateHistoryToPrompt(promptId: string): ThreadCameraFollowResult | null {+ const geometry = this.measure(promptId);+ if (!geometry || geometry.promptTop === null) return null;+ return this.beginHistoryNavigation(geometry.promptTop, promptId);+ }++ private beginHistoryNavigation(top: number, promptId: string | null): ThreadCameraFollowResult | null {+ if (this.mode !== "navigating-history") this.camera.cancel();this.transition("navigate-history");+ this.historyNavigationPromptId = promptId;const result = this.camera.navigateTo(top);- if (!result || result === "settled") {- this.transition("navigation-settled");- }+ if (!result || result === "settled") this.transition("navigation-settled");return result;}@@ -378,6 +390,7 @@ export class ThreadMotionCoordinator {this.composerInputDuringTurn = false;this.resumeFollowArmed = false;this.mode = "idle";+ this.historyNavigationPromptId = null;this.promptPositioned = false;}@@ -410,6 +423,7 @@ export class ThreadMotionCoordinator {: transition;if (nextMode === this.mode) return false;this.mode = nextMode;+ if (nextMode !== "navigating-history") this.historyNavigationPromptId = null;return true;}@@ -434,14 +448,23 @@ export class ThreadMotionCoordinator {if (!this.geometryDirty) return;this.geometryDirty = false;+ const navigationPromptId = this.mode === "navigating-history"+ ? this.historyNavigationPromptId+ : null;const needsPromptGeometry =- !this.isHistoryMode()- && this.turn.id !== null- && !this.promptPositioned;- const geometry = this.measure(needsPromptGeometry ? this.turn.promptId : null);+ navigationPromptId !== null+ || (!this.isHistoryMode() && this.turn.id !== null && !this.promptPositioned);+ const geometry = this.measure(navigationPromptId ?? (needsPromptGeometry ? this.turn.promptId : null));if (!geometry) return;this.onGeometry?.(geometry);+ if (this.mode === "navigating-history" && navigationPromptId !== null) {+ if (geometry.promptTop !== null) {+ const result = this.camera.navigateTo(geometry.promptTop);+ if (!result || result === "settled") this.transition("navigation-settled");+ }+ return;+ }if (this.mode === "navigating-latest") {const result = this.camera.navigateTo(geometry.maxScrollTop);if (!result || result === "settled") {diff --git a/webui/src/globals.css b/webui/src/globals.cssindex 9609bdeac..bac91df17 100644--- a/webui/src/globals.css+++ b/webui/src/globals.css@@ -607,10 +607,16 @@}.thread-history-status {- height: calc(48px + var(--history-pull, 0px));+ height: 48px;background: linear-gradient(hsl(var(--background)) 35%, hsl(var(--background) / 0));color: hsl(var(--muted-foreground));}+ .thread-history-reveal {+ transform: translateY(calc(var(--history-pull, 0px) - 100%));+ }+ .thread-history-reveal:focus-within {+ transform: none;+ }.thread-history-control {display: flex;width: 120px;@@ -620,7 +626,7 @@}/* loading.dev Blocks, Copyright (c) 2026 Jakub Krehel (MIT); THIRD_PARTY_NOTICES.md. */.thread-history-blocks {- color: #d35e14;+ color: hsl(var(--muted-foreground));display: grid;width: 20px;height: 20px;@@ -638,7 +644,7 @@height: 24px;color: hsl(var(--destructive));}- .thread-history-status[data-state="error"] .thread-history-blocks > span {+ .thread-history-status:not([data-state="loading"]):not([data-state="error"]) .thread-history-blocks > span {animation: none;transform: none;}@@ -647,6 +653,9 @@35% { transform: scale(0); }}@media (prefers-reduced-motion: reduce) {+ .thread-history-feedback {+ transform: none;+ }.thread-history-blocks > span {animation: none;transform: scale(0.8);diff --git a/webui/src/hooks/usePromptHistory.ts b/webui/src/hooks/usePromptHistory.tsindex 62a57d346..db4f4ccba 100644--- a/webui/src/hooks/usePromptHistory.ts+++ b/webui/src/hooks/usePromptHistory.ts@@ -13,6 +13,8 @@ interface HistoryPage {body: WebuiThreadPersistedPayload;}+const HISTORY_PAGE_LIMIT = 3;+export interface PromptHistoryNavigation {prompts: PromptAnchor[];window: {@@ -23,6 +25,8 @@ export interface PromptHistoryNavigation {forkBoundaryMessageCount: number | null;} | null;target: { id: string; sequence: number } | null;+ /** Pending or failed page read; index errors have no page operation. */+ operation: "jump" | "older" | "newer" | null;loading: boolean;error: string | null;jump: (id: string) => void;@@ -42,6 +46,7 @@ export function usePromptHistory(key: string | null, version: number, messages:const indexSnapshot = useRef<PromptIndex>();const [pages, setPages] = useState<HistoryPage[]>([]);const [target, setTarget] = useState<PromptHistoryNavigation["target"]>(null);+ const [operation, setOperation] = useState<PromptHistoryNavigation["operation"]>(null);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const [indexError, setIndexError] = useState<string | null>(null);@@ -130,10 +135,12 @@ export function usePromptHistory(key: string | null, version: number, messages:}, []);const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string) => {- if (!key) return;+ // Boundary inputs can arrive before loading renders; only a new jump supersedes a read.+ if (!key || (!id && request.current)) return;request.current?.abort();const controller = new AbortController();request.current = controller;+ setOperation(id ? "jump" : direction === "before" ? "older" : "newer");setLoading(true);setError(null);retry.current = () => { void read(cursor, direction, id); };@@ -150,7 +157,7 @@ export function usePromptHistory(key: string | null, version: number, messages:}// At most three bounded server pages, even after many navigations.setPages((previous) => id ? [page] : direction === "before"- ? [page, ...previous].slice(0, 3) : [...previous, page].slice(-3));+ ? [page, ...previous].slice(0, HISTORY_PAGE_LIMIT) : [...previous, page].slice(-HISTORY_PAGE_LIMIT));if (id) setTarget({ id, sequence: ++sequence.current });} catch (cause) {if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : String(cause));@@ -180,13 +187,14 @@ export function usePromptHistory(key: string | null, version: number, messages:}, [currentScope, pages, first, last]);return { prompts, window, target: currentScope ? target : null, loading: currentScope && loading,+ operation: currentScope && (loading || error) ? operation : null,error: currentScope ? error ?? indexError : null, cancel, latest, updateMessages,retry: () => error ? retry.current() : setRefresh((value) => value + 1),jump: (id) => {const prompt = prompts.find((item) => item.id === id);if (enabled && prompt?.cursor) void read(prompt.cursor, "after", id);},- older: () => { if (!loading && first?.before_cursor) void read(first.before_cursor, "before"); },- newer: () => { if (!loading && last?.after_cursor) void read(last.after_cursor, "after"); },+ older: () => { if (first?.before_cursor) void read(first.before_cursor, "before"); },+ newer: () => { if (last?.after_cursor) void read(last.after_cursor, "after"); },};}diff --git a/webui/src/tests/subagent-tasks.test.tsx b/webui/src/tests/subagent-tasks.test.tsxindex 37d789eee..f068d911b 100644--- a/webui/src/tests/subagent-tasks.test.tsx+++ b/webui/src/tests/subagent-tasks.test.tsx@@ -381,7 +381,7 @@ describe("session-owned task UI", () => {expect(screen.getByText("Check more").compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();});- it("keeps legacy work with an unknown origin separate from the latest request after refresh", async () => {+ it("keeps legacy work separate after refresh and preserves its disclosure through local history prepends", async () => {vi.mocked(fetch).mockImplementation(async () => response([task({ task_id: "legacy", revision: 0, label: "Nanjing weather", state: "done", completed_at: 102,origin_turn_id: "websocket:a:1791046873588004336", result: "## Nanjing\n\n- **Rain**" }),@@ -402,6 +402,13 @@ describe("session-owned task UI", () => {expect(within(detail).getByRole("heading", { name: "Nanjing" })).toBeVisible();expect(within(detail).getByRole("list")).toHaveTextContent("Rain");await user.keyboard("{Escape}");+ view.rerender(layout({ threadMessages: [+ { id: "cached-prompt", role: "user", content: "Earlier cached prompt", createdAt: 99_000 },+ ...messages,+ ] }));+ const expanded = screen.getByRole("region", { name: "Other tasks" });+ expect(within(expanded).getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "true");+ expect(within(expanded).getByRole("button", { name: /Nanjing weather Completed/ })).toBeVisible();view.unmount();render(layout());const restored = await screen.findByRole("region", { name: "Other tasks" });diff --git a/webui/src/tests/thread-history-spring.test.ts b/webui/src/tests/thread-history-spring.test.tsindex 1c1f4dcc4..58286fe10 100644--- a/webui/src/tests/thread-history-spring.test.ts+++ b/webui/src/tests/thread-history-spring.test.ts@@ -1,32 +1,38 @@-import { describe, expect, it, vi } from "vitest";-import { HISTORY_PULL_LIMIT_PX, ThreadHistorySpring } from "@/components/thread/thread-history-spring";+import { afterEach, describe, expect, it, vi } from "vitest";+import { waitFor } from "@testing-library/react";+import {+ HISTORY_HOLD_PX,+ HISTORY_PULL_LIMIT_PX,+ HISTORY_PULL_TRIGGER_PX,+ ThreadHistorySpring,+ type HistoryRevealPhase,+} from "@/components/thread/thread-history-spring";++const springs = new Set<ThreadHistorySpring>();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 feedback = vi.fn();- const spring = new ThreadHistorySpring({ scheduler, prefersReducedMotion: () => reduced,- onFeedbackChange: feedback, onUpdate: (next) => { distance = next; } });- const advance = (milliseconds = 16) => {- now += milliseconds;- const callbacks = [...frames.values()];- frames.clear();- callbacks.forEach((callback) => callback(now));- return distance;+ const phase = vi.fn<(phase: HistoryRevealPhase) => void>();+ const update = vi.fn((next: number) => { distance = next; });+ const spring = new ThreadHistorySpring({ onPhaseChange: phase, onUpdate: update, prefersReducedMotion: () => reduced });+ springs.add(spring);+ const expectBounded = () => {+ for (const [next] of update.mock.calls) {+ expect(next).toBeGreaterThanOrEqual(0);+ expect(next).toBeLessThanOrEqual(HISTORY_PULL_LIMIT_PX);+ }};- const settle = () => { for (let i = 0; i < 100 && frames.size; i++) advance(); };- return { spring, scheduler, advance, settle, frames, feedback, distance: () => distance };+ return { spring, phase, update, expectBounded, distance: () => distance };}+afterEach(() => {+ for (const spring of springs) spring.reset();+ springs.clear();+ vi.useRealTimers();+});+describe("history boundary spring", () => {- it("resists a short touch and returns continuously without triggering a request", () => {+ it("resists short touch, reverses continuously, and settles transient feedback at zero", async () => {const h = harness();h.spring.startTouch();h.spring.moveTouch(40);@@ -35,77 +41,125 @@ describe("history boundary spring", () => {expect(pulled).toBeLessThan(40);expect(h.spring.endTouch()).toBe(false);expect(h.distance()).toBe(pulled);- expect(h.advance()).toBeGreaterThan(0);+ h.spring.startTouch();+ expect(h.distance()).toBeCloseTo(pulled);+ h.spring.moveTouch(-20);expect(h.distance()).toBeLessThan(pulled);- h.settle();+ h.spring.moveTouch(2_000);+ expect(h.distance()).toBeLessThanOrEqual(HISTORY_PULL_LIMIT_PX);+ expect(h.spring.endTouch(true)).toBe(false);+ await waitFor(() => expect(h.phase).toHaveBeenLastCalledWith("hidden"));expect(h.distance()).toBe(0);- expect(h.frames.size).toBe(0);+ expect(h.phase.mock.calls).toEqual([["feedback"], ["hidden"]]);+ h.expectBounded();});- it("holds actual loading still, lets a new touch take over, and converges immediately after long frame gaps", () => {+ it("uses the 56px touch threshold and keeps a request's 48px slot after completion", async () => {const h = harness();h.spring.startTouch();h.spring.moveTouch(120);+ expect(h.distance()).toBeGreaterThan(HISTORY_HOLD_PX);+ expect(h.distance()).toBeLessThan(HISTORY_PULL_TRIGGER_PX);+ expect(h.spring.endTouch()).toBe(false);+ await waitFor(() => expect(h.distance()).toBe(0));+ h.spring.startTouch();+ h.spring.moveTouch(160);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.hold();+ await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));+ expect(h.spring.wheel(20)).toBe(false);+ h.expectBounded();+ });++ it("rearms after leaving the boundary and restores held geometry after touch takeover/cancel", async () => {+ const h = harness();+ expect(h.spring.wheel(100)).toBe(true);+ h.spring.hold();+ await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));+ h.spring.leaveBoundary();+ expect(h.distance()).toBe(HISTORY_HOLD_PX);+ expect(h.spring.wheel(100)).toBe(true);+ expect(h.spring.wheel(20)).toBe(false);+ await waitFor(() => expect(h.distance()).toBeGreaterThan(HISTORY_HOLD_PX));+ await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));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);+ expect(h.distance()).toBeCloseTo(HISTORY_HOLD_PX);+ h.spring.moveTouch(120);+ expect(h.distance()).toBeGreaterThan(HISTORY_PULL_TRIGGER_PX);+ expect(h.spring.endTouch(true)).toBe(false);+ await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));+ expect(h.phase.mock.calls.filter(([phase]) => phase === "held")).toHaveLength(1);+ h.expectBounded();});- it("merges decelerating wheel input into one bounded spring and one boundary request", () => {+ it("decays wheel pressure without duplicate requests and is bounded under sustained reversals", async () => {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.feedback.mock.calls).toEqual([[true]]);- expect(h.distance()).toBeLessThan(HISTORY_PULL_LIMIT_PX);- h.settle();+ await waitFor(() => expect(h.phase).toHaveBeenLastCalledWith("hidden"));expect(h.distance()).toBe(0);- expect(h.feedback.mock.calls).toEqual([[true], [false]]);+ expect(h.phase.mock.calls).toEqual([["feedback"], ["hidden"]]);expect(h.spring.wheel(100)).toBe(true);+ h.spring.hold();+ await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));+ for (const direction of [1, -1, 1, -1]) {+ for (let i = 0; i < 12; i++) {+ for (let packet = 0; packet < 4; packet++) expect(h.spring.wheel(direction * 2_000)).toBe(false);+ await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));+ expect(h.distance()).toBeGreaterThanOrEqual(0);+ expect(h.distance()).toBeLessThanOrEqual(HISTORY_PULL_LIMIT_PX);+ }+ }+ await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));+ h.expectBounded();});- it("cancels task-owned motion on conversation changes", () => {+ it("cancels stale completion on reset and supports immediate reuse", async () => {const h = harness();h.spring.wheel(100);- h.spring.setLoading(true);+ h.spring.hold();+ await waitFor(() => expect(h.distance()).toBeGreaterThan(0));h.spring.reset();- expect(h.frames.size).toBe(0);expect(h.distance()).toBe(0);+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(h.distance()).toBe(0);+ expect(h.phase).toHaveBeenLastCalledWith("hidden");expect(h.spring.wheel(100)).toBe(true);+ h.spring.hold();+ await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));});- it("keeps the touch trigger functional with reduced motion and no display travel", () => {+ it("keeps reduced-motion transient input functional and settles its lifecycle without travel", async () => {const h = harness(true);h.spring.startTouch();- h.spring.moveTouch(120);+ h.spring.moveTouch(160);expect(h.distance()).toBe(0);expect(h.spring.endTouch()).toBe(true);- h.spring.setLoading(true);+ await waitFor(() => expect(h.phase).toHaveBeenLastCalledWith("hidden"));+ expect(h.phase.mock.calls).toEqual([["feedback"], ["hidden"]]);+ expect(h.spring.wheel(100)).toBe(true);+ expect(h.spring.wheel(20)).toBe(false);expect(h.distance()).toBe(0);- h.settle();- expect(h.frames.size).toBe(0);- h.spring.setLoading(false);- h.settle();- expect(h.feedback.mock.calls).toEqual([[true], [false]]);- h.spring.wheel(100);- expect(h.feedback).toHaveBeenLastCalledWith(true);- h.settle();+ h.spring.leaveBoundary();+ expect(h.phase).toHaveBeenLastCalledWith("hidden");+ expect(h.update.mock.calls.every(([next]) => next === 0)).toBe(true);+ });++ it("reveals and restores the reduced-motion committed slot immediately", () => {+ const h = harness(true);+ expect(h.spring.wheel(100)).toBe(true);+ h.spring.hold();+ expect(h.distance()).toBe(HISTORY_HOLD_PX);+ h.spring.startTouch();+ h.spring.moveTouch(120);+ expect(h.spring.endTouch()).toBe(true);+ expect(h.distance()).toBe(HISTORY_HOLD_PX);+ expect(h.spring.wheel(100)).toBe(false);+ h.spring.reset();expect(h.distance()).toBe(0);- expect(h.feedback).toHaveBeenLastCalledWith(false);+ h.expectBounded();});});diff --git a/webui/src/tests/thread-history-status.test.tsx b/webui/src/tests/thread-history-status.test.tsxindex 21a6b12e5..bf639afe6 100644--- a/webui/src/tests/thread-history-status.test.tsx+++ b/webui/src/tests/thread-history-status.test.tsx@@ -16,17 +16,34 @@ describe("ThreadHistoryStatus", () => {expect(container.firstElementChild).toHaveAttribute("data-state", "exhausted");});- it("uses one loading display before and during a request while preserving keyboard activation", () => {+ it("hides completed feedback without offering another loading action", () => {const onRetry = vi.fn();- const { container, rerender } = render(<ThreadHistoryStatus loading={false} error={null} onRetry={onRetry} />);+ const { container, rerender } = render(<ThreadHistoryStatus loading 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={false} error={null} onRetry={onRetry} />);+ expect(container.firstElementChild).toHaveAttribute("data-state", "ready");+ expect(container.firstElementChild).toHaveAttribute("aria-hidden", "true");+ expect(container.firstElementChild).toHaveClass("invisible");+ expect(screen.queryByRole("status")).not.toBeInTheDocument();+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+ expect(onRetry).not.toHaveBeenCalled();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);+ expect(container.firstElementChild).not.toHaveClass("invisible");+ expect(screen.getByRole("status")).toBeInTheDocument();+ });++ it("shows decorative Blocks while previewing a pull without offering a loading action", () => {+ const onRetry = vi.fn();+ const { container } = render(<ThreadHistoryStatus loading={false} error={null} preview onRetry={onRetry} />);+ expect(container.firstElementChild).toHaveAttribute("data-state", "ready");+ expect(container.firstElementChild).not.toHaveClass("invisible");+ const blocks = screen.getByRole("status").querySelector(".thread-history-blocks")!;+ expect(blocks.children).toHaveLength(9);+ expect(blocks).toHaveAttribute("aria-hidden", "true");+ fireEvent.click(blocks);+ expect(onRetry).not.toHaveBeenCalled();+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+ expect(screen.getByRole("status").textContent).toBe("");});it("offers error Blocks with the actual failure on keyboard focus and resumes loading on retry", () => {diff --git a/webui/src/tests/thread-motion.test.ts b/webui/src/tests/thread-motion.test.tsindex 0743a596c..d2cd7aa78 100644--- a/webui/src/tests/thread-motion.test.ts+++ b/webui/src/tests/thread-motion.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from "vitest";+import { type ThreadCameraFollowResult } from "@/components/thread/thread-camera";import {ThreadMotionCoordinator,type ThreadMotionGeometry,@@ -9,6 +10,7 @@ import {function motionHarness(initial?: Partial<ThreadMotionGeometry>) {let nextFrameId = 1;let cameraFollowing = false;+ let nextNavigationResult: ThreadCameraFollowResult = "started";const frames = new Map<number, FrameRequestCallback>();let geometry: ThreadMotionGeometry = {scrollTop: 400,@@ -39,8 +41,8 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {followTo: vi.fn(() => "settled" as const),isFollowing: vi.fn(() => cameraFollowing),navigateTo: vi.fn(() => {- cameraFollowing = true;- return "started" as const;+ cameraFollowing = nextNavigationResult === "started";+ return nextNavigationResult;}),};const onGeometry = vi.fn();@@ -69,6 +71,9 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {const setCameraFollowing = (following: boolean) => {cameraFollowing = following;};+ const setNextNavigationResult = (result: ThreadCameraFollowResult) => {+ nextNavigationResult = result;+ };return {camera,@@ -81,6 +86,7 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {advanceFrame,setCameraFollowing,setGeometry,+ setNextNavigationResult,};}@@ -708,4 +714,56 @@ describe("ThreadMotionCoordinator", () => {expect(camera.jumpTo.mock.calls).toEqual([[430], [458], [490]]);});++ it("retargets a prompt navigation from authoritative geometry without restarting the camera", () => {+ const { camera, coordinator, measure, setGeometry } = motionHarness();+ coordinator.navigateHistoryToPrompt("prompt-46");+ expect(measure).toHaveBeenCalledWith("prompt-46");+ expect(camera.navigateTo).toHaveBeenLastCalledWith(404);+ expect(coordinator.snapshot().mode).toBe("navigating-history");++ camera.cancel.mockClear();+ setGeometry({ promptTop: 520 });+ coordinator.reconcileObservedGeometry();++ expect(camera.navigateTo).toHaveBeenLastCalledWith(520);+ expect(camera.cancel).not.toHaveBeenCalled();+ expect(coordinator.snapshot().mode).toBe("navigating-history");+ });++ it("releases prompt retarget ownership on composer input and user takeover", () => {+ const { camera, coordinator, setGeometry } = motionHarness();+ coordinator.navigateHistoryToPrompt("prompt-46");+ camera.cancel.mockClear();+ coordinator.handleComposerInput();+ expect(camera.cancel).toHaveBeenCalledTimes(1);+ expect(coordinator.snapshot().mode).toBe("browsing-history");+ const callsAfterComposer = camera.navigateTo.mock.calls.length;+ setGeometry({ promptTop: 600 });+ coordinator.reconcileObservedGeometry();+ expect(camera.navigateTo).toHaveBeenCalledTimes(callsAfterComposer);++ coordinator.navigateHistoryToPrompt("prompt-47");+ camera.cancel.mockClear();+ coordinator.handleUserScrollIntent(true);+ expect(camera.cancel).toHaveBeenCalledTimes(1);+ expect(coordinator.snapshot().mode).toBe("browsing-history");+ const callsAfterTouch = camera.navigateTo.mock.calls.length;+ setGeometry({ promptTop: 700 });+ coordinator.reconcileObservedGeometry();+ expect(camera.navigateTo).toHaveBeenCalledTimes(callsAfterTouch);+ });++ it("drops prompt identity when an aligned navigation settles immediately", () => {+ const { camera, coordinator, measure, setGeometry, setNextNavigationResult } = motionHarness();+ setNextNavigationResult("settled");+ expect(coordinator.navigateHistoryToPrompt("prompt-46")).toBe("settled");+ expect(measure).toHaveBeenCalledWith("prompt-46");+ expect(coordinator.snapshot().mode).toBe("browsing-history");+ const callsAfterSettle = camera.navigateTo.mock.calls.length;+ setGeometry({ promptTop: 720 });+ coordinator.reconcileObservedGeometry();+ expect(camera.navigateTo).toHaveBeenCalledTimes(callsAfterSettle);+ expect(coordinator.snapshot().mode).toBe("browsing-history");+ });});diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsxindex 8436c8292..d8bca3274 100644--- a/webui/src/tests/thread-shell.test.tsx+++ b/webui/src/tests/thread-shell.test.tsx@@ -1,5 +1,5 @@import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";-import { StrictMode, type ReactNode } from "react";+import { Profiler, StrictMode, type ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";import { preloadMarkdownText } from "@/components/MarkdownText";@@ -4002,6 +4002,89 @@ describe("ThreadShell", () => {},);+ it.each([+ { name: "visible rows after a hidden command prefix", rows: [+ { role: "user" as const, content: "/model hidden", turnId: "webui-system:model" },+ { role: "assistant" as const, content: "hidden model response", turnId: "webui-system:model" },+ { role: "user" as const, content: "older question", turnId: "older-turn" },+ { role: "assistant" as const, content: "older answer", turnId: "older-turn" },+ ], expectVisible: true },+ { name: "a page containing only hidden command rows", rows: [+ { role: "user" as const, content: "/model hidden", turnId: "webui-system:model" },+ { role: "assistant" as const, content: "hidden model response", turnId: "webui-system:model" },+ ], expectVisible: false },+ { name: "an empty successful page", rows: [], expectVisible: false },+ { name: "a failed page", rows: [], expectVisible: false, error: true },+ ])("releases older-page loading after ThreadShell handles $name", async ({ rows, expectVisible, error = false }) => {+ const client = makeClient();+ const chatId = `older-projection-${expectVisible ? "visible" : "hidden"}`;+ let resolveOlder!: (response: Response) => void;+ let olderReturned = false;+ const commits: Array<{ loading: boolean; olderVisible: boolean }> = [];+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (!url.includes(`websocket%3A${chatId}/webui-thread`)) {+ return { ok: false, status: 404, json: async () => ({}) };+ }+ if (url.includes("before=")) {+ return new Promise<Response>((resolve) => { resolveOlder = resolve; });+ }+ return httpJson({+ ...transcriptFromSimpleMessages([+ { role: "user", content: "current question", turnId: "current-turn" },+ ]),+ has_pending_tool_calls: expectVisible,+ active_turn_id: expectVisible ? "current-turn" : null,+ completed_turn_ids: [],+ page: { before_cursor: "older-page", has_more_before: true, user_message_offset: 1 },+ });+ }));+ const capture = () => {+ if (!olderReturned) return;+ commits.push({+ loading: document.querySelector('.thread-history-status[data-state="loading"]') !== null,+ olderVisible: document.body.textContent?.includes("older answer") ?? false,+ });+ };+ const { container } = render(wrap(client, <Profiler id="older-history" onRender={capture}>+ <ThreadShell session={session(chatId)} title="Older projection" onToggleSidebar={() => {}} />+ </Profiler>));+ await screen.findByText("current question");+ const scroller = container.querySelector(".thread-message-viewport") as HTMLElement;+ Object.defineProperties(scroller, {+ scrollHeight: { configurable: true, value: 2400 },+ clientHeight: { configurable: true, value: 600 },+ scrollTop: { configurable: true, writable: true, value: 0 },+ });+ fireEvent.keyDown(scroller, { key: "Home" });+ await waitFor(() => expect(resolveOlder).toBeTypeOf("function"));+ await screen.findByText("Loading earlier messages…");+ if (expectVisible) {+ act(() => client._emitChat(chatId, {+ event: "delta", chat_id: chatId, turn_id: "current-turn", text: "live during pagination",+ }));+ await screen.findByText("live during pagination");+ }+ const olderPayload = rows.length > 0+ ? transcriptFromSimpleMessages(rows)+ : { schemaVersion: 3, projection: "events", events: [], page: { before_cursor: null, has_more_before: false } };+ olderReturned = true;+ await act(async () => {+ resolveOlder(error+ ? new Response("History unavailable", { status: 503 })+ : httpJson({ ...olderPayload, page: { before_cursor: null, has_more_before: false } }));+ });+ if (expectVisible) await screen.findByText("older answer");+ await waitFor(() => expect(container.querySelector('.thread-history-status[data-state="loading"]')).toBeNull());+ expect(commits.some((commit) => commit.loading && !commit.olderVisible)).toBe(expectVisible);+ if (error) {+ expect(container.querySelector('.thread-history-status[data-state="error"]')).toBeInTheDocument();+ expect(container.querySelector(".thread-history-slot")).toBeInTheDocument();+ } else {+ expect(container.querySelector(".thread-history-slot")).not.toBeInTheDocument();+ }+ });+it("prepends earlier history while preserving the active answer cursor", async () => {const client = makeClient();const chatId = "running-paged-history";diff --git a/webui/src/tests/thread-viewport.test.tsx b/webui/src/tests/thread-viewport.test.tsxindex b0521ee2f..90cd71208 100644--- a/webui/src/tests/thread-viewport.test.tsx+++ b/webui/src/tests/thread-viewport.test.tsx@@ -49,7 +49,7 @@ function dispatchHistoryInput(scroller: HTMLElement, input: "wheel" | "touch" |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.touchMove(scroller, { touches: [{ clientX: 100, clientY: 380 }] });fireEvent.touchEnd(scroller);}}@@ -1517,7 +1517,6 @@ describe("ThreadViewport", () => {expect(screen.queryByText(`message ${firstVisible - 1}`)).not.toBeInTheDocument();expect(screen.getByText(`message ${firstVisible}`)).toBeInTheDocument();expect(screen.getByText("message 299")).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Load earlier messages" })).toBeInTheDocument();});it("automatically expands earlier local history near the top", () => {@@ -1677,7 +1676,6 @@ describe("ThreadViewport", () => {describe.each(["wheel", "touch"] as const)("%s history boundary", (input) => {it.each([{ loadingOlder: true },- { olderError: "offline" },{ conversationReady: false },{ hasMoreBefore: false },])("keeps history blocked: %o", (blocked) => {@@ -1714,7 +1712,7 @@ describe("ThreadViewport", () => {expect(onLoadOlder).toHaveBeenCalledTimes(1);});- it("pauses automatic history requests after a failure and exposes retry", () => {+ it.each(["wheel", "touch", "keyboard"] as const)("pauses automatic requests after failure but accepts another %s boundary gesture", (input) => {const onLoadOlder = vi.fn();const { container } = render(@@ -1737,7 +1735,8 @@ describe("ThreadViewport", () => {});expect(onLoadOlder).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole("button", { name: "Loading failed. Retry" }));+ expect(screen.getByRole("button", { name: "Loading failed. Retry" }).querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);+ dispatchHistoryInput(scroller, input);expect(onLoadOlder).toHaveBeenCalledTimes(1);});@@ -1774,13 +1773,14 @@ describe("ThreadViewport", () => {fireEvent.touchMove(scroller, touch(240));expect(historyPull(scroller)).toBeGreaterThan(0);expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);+ expect(container.querySelector(".thread-history-status")).not.toHaveClass("invisible");expect(onLoadOlder).not.toHaveBeenCalled();fireEvent.touchEnd(scroller);expect(historyPull(scroller)).toBeGreaterThan(0);await waitFor(() => expect(historyPull(scroller)).toBe(0));fireEvent.touchStart(scroller, touch(200));- fireEvent.touchMove(scroller, touch(300));+ fireEvent.touchMove(scroller, touch(380));expect(onLoadOlder).not.toHaveBeenCalled();expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);fireEvent.touchEnd(scroller);@@ -1789,8 +1789,19 @@ describe("ThreadViewport", () => {fireEvent.scroll(scroller);expect(onLoadOlder).toHaveBeenCalledTimes(1);expect(screen.getByText("Loading earlier messages…")).toBeInTheDocument();- rerender(<ThreadViewport {...props} />);+ rerender(<ThreadViewport {...props} loadingOlder />);+ expect(container.querySelector(".thread-history-slot")).toBeInTheDocument();+ const prepended = [+ { ...messages[0], id: "older-u0", content: "Earlier message" },+ ...messages,+ ];+ rerender(<ThreadViewport {...props} messages={prepended} />);await waitFor(() => expect(historyPull(scroller)).toBe(0));+ expect(container.querySelector(".thread-history-slot")).not.toBeInTheDocument();+ expect(container.querySelector(".thread-history-status")).toHaveAttribute("data-state", "ready");+ expect(container.querySelector(".thread-history-status")).toHaveClass("invisible");+ expect(screen.queryByRole("status")).not.toBeInTheDocument();+ expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();});it("does not fetch on touch scroll alone or horizontal gestures and clears pull on session change", () => {@@ -2009,7 +2020,7 @@ describe("ThreadViewport", () => {const navigation = { prompts: [{ id: "u1", label: "hello", preview: "hello", answerPreview: "", createdAt: 1, index: 0 }],window: { messages: [{ id: "old", role: "user" as const, content: "old question", createdAt: 0 }],userMessageOffset: 0, hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },- target: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), updateMessages: vi.fn() };+ target: null, operation: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), updateMessages: vi.fn() };const view = render(<ThreadViewport ref={viewportRef} messages={messages} isStreaming={false} composer={<div />} navigation={navigation} />);act(() => viewportRef.current?.jumpToUserPrompt("u1"));expect(latest).toHaveBeenCalledOnce();@@ -2025,7 +2036,7 @@ describe("ThreadViewport", () => {render(<ThreadViewport messages={messages} isStreaming={false} composer={<div />}navigation={{ prompts: [], window: { messages: history, userMessageOffset: 0,hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },- target: { id: "old-user", sequence: 1 }, loading: false, error: null,+ target: { id: "old-user", sequence: 1 }, operation: null, loading: false, error: null,jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), updateMessages: vi.fn() }} />);await waitFor(() => expect(screen.getByText("Large old turn")).toBeInTheDocument());});@@ -2099,17 +2110,17 @@ describe("ThreadViewport", () => {expect(navigateTo).toHaveBeenLastCalledWith(Math.max(0, (count - 1) * 40 - 48));});- it("keeps prompt jumps aligned when the header changes between a row and an overlay", async () => {+ it("aligns prompt jumps with the scroll inset independently of message layout", async () => {const navigateTo = vi.spyOn(ThreadCameraController.prototype, "navigateTo").mockReturnValue("started");const { scroller } = await renderPromptRailViewport();const marker = screen.getByRole("button", { name: "Jump to message: message 1" });- scroller.style.paddingTop = "16px";+ scroller.style.scrollPaddingTop = "16px";fireEvent.click(marker);expect(navigateTo).toHaveBeenLastCalledWith(344);- scroller.style.paddingTop = "48px";+ scroller.style.scrollPaddingTop = "48px";fireEvent.click(marker);expect(navigateTo).toHaveBeenLastCalledWith(312);});diff --git a/webui/src/tests/usePromptHistory.test.tsx b/webui/src/tests/usePromptHistory.test.tsxindex f2fe49da9..036a17070 100644--- a/webui/src/tests/usePromptHistory.test.tsx+++ b/webui/src/tests/usePromptHistory.test.tsx@@ -55,6 +55,27 @@ it("loads the complete index without bodies, reads bounded windows and leaves liexpect(latest).toHaveLength(1);});+it.each(["older", "newer"] as const)("keeps one pending %s page when boundary inputs arrive before the next render", async (operation) => {+ const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });+ await waitFor(() => expect(result.current.prompts).toHaveLength(2000));+ await act(async () => result.current.jump("u10"));+ let finish!: (body: WebuiThreadPersistedPayload) => void;+ vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ const load = result.current[operation];+ act(() => {+ load();+ load();+ });+ expect(api.fetchWebuiThread).toHaveBeenCalledTimes(2);+ const options = vi.mocked(api.fetchWebuiThread).mock.lastCall?.[2];+ if (typeof options !== "object") throw new Error("expected page options");+ expect(options.signal?.aborted).toBe(false);+ expect(result.current.loading).toBe(true);+ await act(async () => finish(page(operation === "older" ? 9 : 11)));+ expect(result.current.loading).toBe(false);+ expect(result.current.window?.messages).toHaveLength(4);+});+it("keeps the current page on failure and offers retry; superseded jumps and session reads cannot win", async () => {const { result, rerender } = renderHook(({ key }) => usePromptHistory(key, 1, latest), {wrapper: wrapper(), initialProps: { key: "a" },@@ -175,3 +196,28 @@ it("merges a live input by transport identity without adding an anchor or reordeexpect(result.current.window).toBeNull();expect(result.current.target).toBeNull();});+++it("keeps the request operation with failures and retries", async () => {+ const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });+ await waitFor(() => expect(result.current.prompts).toHaveLength(2000));+ let finish!: (body: WebuiThreadPersistedPayload) => void;+ vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ act(() => result.current.jump("u10"));+ expect(result.current.operation).toBe("jump");+ expect(result.current.loading).toBe(true);+ await act(async () => finish(page(10)));+ expect(result.current.operation).toBeNull();++ for (const operation of ["older", "newer"] as const) {+ vi.mocked(api.fetchWebuiThread).mockRejectedValueOnce(new Error("offline"));+ await act(async () => result.current[operation]());+ expect(result.current.operation).toBe(operation);+ expect(result.current.error).toBe("offline");+ await act(async () => result.current.retry());+ expect(result.current.operation).toBeNull();+ expect(result.current.error).toBeNull();+ }+ act(() => result.current.cancel());+ expect(result.current.operation).toBeNull();+});