From f62dfe0ee85215b22e10fc2e93b45ad2839b803f Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:56:26 +0800 Subject: [PATCH] fix(webui): show latest button for hidden content (#6605) * fix(webui): show latest button for hidden content * fix(webui): preserve latest navigation after focus scroll --- webui/browser/fixture.tsx | 8 +- webui/browser/mobile-chat-layout.spec.ts | 90 ++++++++++++++++++- .../src/components/thread/ThreadViewport.tsx | 76 +++++++++++----- webui/src/components/thread/thread-camera.ts | 4 + webui/src/components/thread/thread-motion.ts | 11 +++ webui/src/tests/thread-motion.test.ts | 28 ++++++ webui/src/tests/thread-viewport.test.tsx | 49 ++++++++++ 7 files changed, 243 insertions(+), 23 deletions(-) diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index b94bef670..15e72555b 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -110,7 +110,9 @@ const parameters = new URLSearchParams(location.search); const railClient = new NanobotClient({ url: "ws://127.0.0.1:8765", reconnect: false }); const railHistory: UIMessage[] = Array.from({ length: 5 }, (_, index) => [ { id: `u${1995 + index}`, role: "user" as const, content: `Question ${1995 + index}`, createdAt: index + 1 }, - { id: `a${1995 + index}`, role: "assistant" as const, content: "A synthetic answer.\n\n".repeat(8), createdAt: index + 1 }, + { id: `a${1995 + index}`, role: "assistant" as const, content: parameters.has("focus-links") && index === 4 + ? Array.from({ length: 45 }, (_, i) => `[Reference ${i}](https://example.test/ref${i})`).join("\n") + : "A synthetic answer.\n\n".repeat(8), createdAt: index + 1 }, ]).flat(); function RailFixture() { const [messages, setMessages] = useState(parameters.has("real") ? [] : railHistory); @@ -148,7 +150,9 @@ function RailFixture() { } {parameters.has("workbench") ? {}} onAddPane={() => {}} onLayoutChange={() => {}} onPaneOrderChange={() => {}} renderPane={(_pane, context) => <> {viewport(context.composerPortalTarget !== undefined, context.navigationFrame)} diff --git a/webui/browser/mobile-chat-layout.spec.ts b/webui/browser/mobile-chat-layout.spec.ts index 6cc7832b4..847b81597 100644 --- a/webui/browser/mobile-chat-layout.spec.ts +++ b/webui/browser/mobile-chat-layout.spec.ts @@ -1,4 +1,21 @@ -import { expect, test } from "@playwright/test"; +import { expect, test, type Page } from "@playwright/test"; + +async function recordBottomButtonFrames(page: Page) { + await page.evaluate(() => { + (window as unknown as { bottomButtonFrames: boolean[] }).bottomButtonFrames = []; + let start = 0; + const sample = () => { + (window as unknown as { bottomButtonFrames: boolean[] }).bottomButtonFrames.push( + Boolean(document.querySelector('button[aria-label="Scroll to bottom"]')), + ); + if (performance.now() - start < 300) requestAnimationFrame(sample); + }; + document.querySelector('button[aria-label="Scroll to bottom"]')!.addEventListener("click", () => { + start = performance.now(); + requestAnimationFrame(sample); + }, { once: true }); + }); +} for (const { width, dark } of [{ width: 360, dark: false }, { width: 314, dark: true }, { width: 600, dark: false }]) { test.describe(`mobile transcript at ${width}px`, () => { @@ -68,3 +85,74 @@ test.describe("desktop transcript spacing", () => { expect(await scroller.evaluate(node => getComputedStyle(node).maskImage)).toContain("calc(100% - 36px)"); }); }); + +test("bottom button stays hidden throughout smooth navigation", async ({ page }) => { + await page.setViewportSize({ width: 360, height: 740 }); + await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en")); + await page.route("**/api/**", route => route.fulfill({ json: {} })); + await page.goto("/browser/fixture.html?case=mobile-chat-layout&project"); + const scroller = page.locator(".thread-message-viewport"); + const button = page.getByRole("button", { name: "Scroll to bottom" }); + await expect.poll(() => scroller.evaluate(el => el.scrollHeight - el.clientHeight)).toBeGreaterThan(100); + await expect(button).toBeHidden(); + const readableDistance = () => scroller.evaluate(el => { + const rows = [...el.querySelectorAll(".thread-message-row")]; + const row = rows.reverse().find(item => item.getBoundingClientRect().height > 0)!; + const gap = el.querySelector(".thread-message-end-gap")!; + return row.getBoundingClientRect().bottom - (el.getBoundingClientRect().bottom - gap.getBoundingClientRect().height); + }); + expect(await readableDistance()).toBeLessThanOrEqual(1); + await scroller.hover(); + await page.mouse.wheel(0, -120); + await expect(button).toBeVisible(); + expect(await readableDistance()).toBeGreaterThan(0); + await expect(button).toBeVisible(); + await recordBottomButtonFrames(page); + await button.click(); + await expect(button).toBeHidden(); + await expect.poll(() => scroller.evaluate(el => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(1); + await page.waitForTimeout(320); + const frames = await page.evaluate(() => (window as unknown as { bottomButtonFrames: boolean[] }).bottomButtonFrames); + expect(frames.length).toBeGreaterThan(1); + expect(frames).not.toContain(true); + await expect(button).toBeHidden(); +}); + +test("bottom button stays hidden after focus scrolls a following thread", async ({ page }) => { + await page.setViewportSize({ width: 360, height: 740 }); + await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en")); + await page.route("**/api/sessions/**", route => route.fulfill({ json: { prompts: [] } })); + await page.goto("/browser/fixture.html?case=rail&workbench=1&focus-links=1"); + const scroller = page.locator(".thread-message-viewport"); + const links = scroller.locator("a"); + const button = page.getByRole("button", { name: "Scroll to bottom" }); + await expect(links).toHaveCount(45); + await expect.poll(() => scroller.evaluate(el => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(1); + await expect(button).toBeHidden(); + + const index = await scroller.evaluate(el => { + const top = el.getBoundingClientRect().top; + return [...el.querySelectorAll("a")].findIndex(link => { + const offset = link.getBoundingClientRect().top - top; + return offset > 48 && offset < 100; + }); + }); + expect(index).toBeGreaterThan(0); + await links.nth(index).focus(); + const initialTop = await scroller.evaluate(el => el.scrollTop); + await page.keyboard.press("Shift+Tab"); + await expect(links.nth(index - 1)).toBeFocused(); + await expect(button).toBeVisible(); + const distance = initialTop - await scroller.evaluate(el => el.scrollTop); + expect(distance).toBeGreaterThan(0); + expect(distance).toBeLessThan(48); + + await recordBottomButtonFrames(page); + await button.click(); + await expect.poll(() => scroller.evaluate(el => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(1); + await page.waitForTimeout(320); + const frames = await page.evaluate(() => (window as unknown as { bottomButtonFrames: boolean[] }).bottomButtonFrames); + expect(frames.length).toBeGreaterThan(1); + expect(frames).not.toContain(true); + await expect(button).toBeHidden(); +}); diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx index 71d6afb3c..efce5af52 100644 --- a/webui/src/components/thread/ThreadViewport.tsx +++ b/webui/src/components/thread/ThreadViewport.tsx @@ -313,6 +313,7 @@ export const ThreadViewport = forwardRef(null); + const endGapRef = useRef(null); const lastConversationKeyRef = useRef(conversationKey); const conversationHandoffPendingRef = useRef(false); const conversationHandoffAnimationRef = useRef(null); @@ -323,7 +324,27 @@ export const ThreadViewport = forwardRef(null); const previousLoadingOlderRef = useRef(loadingOlder); const composerDockHeightRef = useRef(0); - const [atBottom, setAtBottom] = useState(true); + const [contentBelowViewport, setContentBelowViewport] = useState(false); + const [navigatingToBottom, setNavigatingToBottom] = useState(false); + const lastMessageRowRef = useRef(null); + const refreshLastMessageRow = useCallback(() => { + const rows = messageContentRef.current?.querySelectorAll(".thread-message-row"); + lastMessageRowRef.current = null; + if (!rows) return; + for (let index = rows.length - 1; index >= 0; index--) { + if (rows[index].getBoundingClientRect().height > 0) { + lastMessageRowRef.current = rows[index]; + break; + } + } + }, []); + const updateContentVisibility = useCallback(() => { + const viewport = messageRegionRef.current; + const lastRow = lastMessageRowRef.current; + setContentBelowViewport(Boolean(viewport && lastRow + && lastRow.getBoundingClientRect().bottom > viewport.getBoundingClientRect().bottom + - (endGapRef.current?.getBoundingClientRect().height ?? 0))); + }, []); const [atHistoryTop, setAtHistoryTop] = useState(false); const [historyPhase, setHistoryPhase] = useState("hidden"); const historyPhaseRef = useRef(historyPhase); @@ -380,7 +401,9 @@ export const ThreadViewport = forwardRef(null); if (threadMotionRef.current === null) { - const camera = new ThreadCameraController(() => scrollRef.current); + const camera = new ThreadCameraController(() => scrollRef.current, { + onSettled: () => threadMotionRef.current?.cameraSettled(), + }); threadMotionRef.current = new ThreadMotionCoordinator({ camera, measure: (promptId) => { @@ -408,6 +431,10 @@ export const ThreadViewport = forwardRef { + setNavigatingToBottom(false); + updateContentVisibility(); + }, onGeometry: (geometry: ThreadMotionGeometry) => { composerLayoutChangeRef.current?.(); if (Math.abs(composerDockHeightRef.current - geometry.composerHeight) >= 1) { @@ -419,7 +446,6 @@ export const ThreadViewport = forwardRef setAtBottom(true), }); } const hasTaskResults = useHasSubagentResults(); @@ -461,7 +487,9 @@ export const ThreadViewport = forwardRef { threadMotionRef.current?.takeUserControl(); - }, []); + setNavigatingToBottom(false); + updateContentVisibility(); + }, [updateContentVisibility]); const captureHistoryScrollAnchor = useCallback(() => { const scroller = scrollRef.current; @@ -542,14 +570,14 @@ export const ThreadViewport = forwardRef 0) { setVisibleMessageCount((count) => Math.min(messages.length, count + HISTORY_WINDOW_INCREMENT), @@ -615,7 +642,6 @@ export const ThreadViewport = forwardRef Math.max(count, localMessages.length - index)); }, [historyWindow, latestMessages, messages, navigateToVisiblePrompt, navigation]); @@ -647,7 +672,6 @@ export const ThreadViewport = forwardRef message.id === navigation.target!.id); setVisibleMessageCount(Math.max(INITIAL_HISTORY_WINDOW, messages.length - Math.max(0, index))); }, [navigation?.target]); @@ -658,7 +682,9 @@ export const ThreadViewport = forwardRef { threadMotionRef.current?.takeUserControl(); - }, []); + setNavigatingToBottom(false); + updateContentVisibility(); + }, [updateContentVisibility]); useImperativeHandle( ref, @@ -724,7 +750,7 @@ export const ThreadViewport = forwardRef { + refreshLastMessageRow(); + updateContentVisibility(); threadMotionRef.current?.invalidateGeometry(); - }, [composer, hasMessages, visibleMessages.length]); + }, [composer, hasMessages, visibleMessages, refreshLastMessageRow, updateContentVisibility]); useEffect(() => () => { conversationHandoffAnimationRef.current?.cancel(); @@ -897,11 +925,15 @@ export const ThreadViewport = forwardRef { + refreshLastMessageRow(); threadMotionRef.current?.invalidateGeometry(); + updateContentVisibility(); }; const reconcileObservedGeometry = () => { + refreshLastMessageRow(); reconcileHistoryScrollAnchor(); threadMotionRef.current?.reconcileObservedGeometry(); + updateContentVisibility(); }; reconcileObservedGeometry(); const observer = typeof ResizeObserver === "undefined" @@ -911,29 +943,28 @@ export const ThreadViewport = forwardRef { observer?.disconnect(); window.removeEventListener("resize", invalidateGeometry); }; - }, [hasMessages, reconcileHistoryScrollAnchor]); + }, [hasMessages, reconcileHistoryScrollAnchor, refreshLastMessageRow, updateContentVisibility]); useEffect(() => { const el = scrollRef.current; if (!el) return; const onScroll = (allowHistoryLoad = true) => { + updateContentVisibility(); setAtHistoryTop(el.scrollTop <= 1); if (el.scrollTop > 1) historySpringRef.current?.leaveBoundary(); const distance = el.scrollHeight - el.scrollTop - el.clientHeight; const near = distance < NEAR_BOTTOM_PX; // A detached history page's bottom is not the live tail. const owner = threadMotionRef.current?.observeScroll(near && !historyWindow) ?? "automatic"; - const logicallyAtBottom = !historyWindow && (owner === "automatic" || (owner === "navigation" && near)); - setAtBottom((current) => - current === logicallyAtBottom ? current : logicallyAtBottom, - ); + if (threadMotionRef.current?.snapshot().mode !== "navigating-latest") setNavigatingToBottom(false); if (owner === "user") { // Restoring the anchor also emits scroll. Keep that reading position // through lazy content resizing instead of selecting a prepended row. @@ -978,6 +1009,10 @@ export const ThreadViewport = forwardRef { if (loadingOlder || navigation?.loading) return; @@ -1149,6 +1184,7 @@ export const ThreadViewport = forwardRef -
+
) : ( @@ -1319,7 +1355,7 @@ export const ThreadViewport = forwardRef ) : null} - {showScrollToBottomButton && (!atBottom || historyWindow) && ( + {showScrollToBottomButton && (historyWindow || (contentBelowViewport && !navigatingToBottom)) && (
boolean; + onSettled?: () => void; } function defaultScheduler(): ThreadCameraScheduler { @@ -38,6 +39,7 @@ export class ThreadCameraController { private readonly getViewport: () => ThreadCameraViewport | null; private readonly scheduler: ThreadCameraScheduler; private readonly prefersReducedMotion: () => boolean; + private readonly onSettled?: () => void; private frameId: number | null = null; private phase: "idle" | "following" = "idle"; private target = 0; @@ -50,6 +52,7 @@ export class ThreadCameraController { ) { this.getViewport = getViewport; this.scheduler = options.scheduler ?? defaultScheduler(); + this.onSettled = options.onSettled; this.prefersReducedMotion = options.prefersReducedMotion ?? defaultPrefersReducedMotion; } @@ -132,6 +135,7 @@ export class ThreadCameraController { if (remainingMs === 0) { this.write(viewport, this.target); this.cancel(); + this.onSettled?.(); return; } diff --git a/webui/src/components/thread/thread-motion.ts b/webui/src/components/thread/thread-motion.ts index 3a99fc119..fb8dd3f04 100644 --- a/webui/src/components/thread/thread-motion.ts +++ b/webui/src/components/thread/thread-motion.ts @@ -44,6 +44,7 @@ const THREAD_MOTION_TRANSITIONS: Readonly< "resume-follow": "current-automatic-mode", }, "follow-latest": { + "navigate-latest": "navigating-latest", "navigate-history": "navigating-history", "user-scroll": "browsing-history", }, @@ -134,6 +135,7 @@ interface ThreadMotionCoordinatorOptions { measure: (promptId: string | null) => ThreadMotionGeometry | null; onGeometry?: (geometry: ThreadMotionGeometry) => void; onAutoFollow?: () => void; + onLatestNavigationSettled?: () => void; scheduler?: ThreadMotionScheduler; } @@ -159,6 +161,7 @@ export class ThreadMotionCoordinator { private readonly measure: ThreadMotionCoordinatorOptions["measure"]; private readonly onGeometry?: ThreadMotionCoordinatorOptions["onGeometry"]; private readonly onAutoFollow?: ThreadMotionCoordinatorOptions["onAutoFollow"]; + private readonly onLatestNavigationSettled?: () => void; private readonly scheduler: ThreadMotionScheduler; private turn: ThreadMotionTurn = { id: null, @@ -180,6 +183,7 @@ export class ThreadMotionCoordinator { this.measure = options.measure; this.onGeometry = options.onGeometry; this.onAutoFollow = options.onAutoFollow; + this.onLatestNavigationSettled = options.onLatestNavigationSettled; this.scheduler = options.scheduler ?? defaultScheduler(); } @@ -330,6 +334,13 @@ export class ThreadMotionCoordinator { return result; } + cameraSettled(): void { + if (this.mode === "navigating-latest") { + this.settleLatestNavigation(); + this.onLatestNavigationSettled?.(); + } + } + isAutoFollowPaused(): boolean { return this.isHistoryMode(); } diff --git a/webui/src/tests/thread-motion.test.ts b/webui/src/tests/thread-motion.test.ts index d2cd7aa78..ff5c886ea 100644 --- a/webui/src/tests/thread-motion.test.ts +++ b/webui/src/tests/thread-motion.test.ts @@ -587,6 +587,34 @@ describe("ThreadMotionCoordinator", () => { expect(coordinator.snapshot().mode).toBe("browsing-history"); }); + it("settles camera navigation without relying on a scroll event", () => { + const { coordinator } = motionHarness(); + coordinator.takeUserControl(); + coordinator.navigateLatestTo(1_400); + coordinator.cameraSettled(); + expect(coordinator.snapshot().mode).toBe("follow-latest"); + + coordinator.navigateHistoryTo(200); + coordinator.cameraSettled(); + expect(coordinator.snapshot().mode).toBe("navigating-history"); + }); + + it("keeps explicit latest navigation in control when already following the tail", () => { + const { camera, coordinator, advanceFrame, setCameraFollowing } = motionHarness(); + coordinator.resumeAutoFollow(); + advanceFrame(); + + expect(coordinator.snapshot().mode).toBe("follow-latest"); + expect(coordinator.navigateLatestTo(1_400)).toBe("started"); + expect(coordinator.snapshot().mode).toBe("navigating-latest"); + expect(coordinator.observeScroll(true)).toBe("navigation"); + expect(camera.isFollowing()).toBe(true); + + setCameraFollowing(false); + coordinator.cameraSettled(); + expect(coordinator.snapshot().mode).toBe("follow-latest"); + }); + it("retargets smooth latest navigation before resuming automatic follow", () => { const { camera, diff --git a/webui/src/tests/thread-viewport.test.tsx b/webui/src/tests/thread-viewport.test.tsx index 55a5b98db..4716b74d7 100644 --- a/webui/src/tests/thread-viewport.test.tsx +++ b/webui/src/tests/thread-viewport.test.tsx @@ -201,6 +201,14 @@ function getScroller(container: HTMLElement): HTMLElement { return scroller; } +function mockMessageEnd(scroller: HTMLElement) { + const rows = scroller.querySelectorAll(".thread-message-row"); + const row = rows[rows.length - 1]; + scroller.getBoundingClientRect = () => ({ bottom: scroller.clientHeight } as DOMRect); + row.getBoundingClientRect = () => ({ height: 100, bottom: scroller.scrollHeight - scroller.scrollTop } as DOMRect); + act(() => window.dispatchEvent(new Event("resize"))); +} + async function renderPromptRailViewport({ scrollTo, messages: promptMessages = makePromptExchangeMessages(5), @@ -922,6 +930,7 @@ describe("ThreadViewport", () => { await flushAnimationFrame(); followTo.mockClear(); + mockMessageEnd(scroller); act(() => { fireEvent.wheel(scroller, { deltaY: -24 }); scroller.scrollTop = 1_380; @@ -970,6 +979,43 @@ describe("ThreadViewport", () => { .not.toBeInTheDocument(); }); + it("tracks the message content edge independently of trailing space and motion ownership", () => { + const resizeObserver = stubResizeObserver(); + try { + const { container } = render(composer
} />); + const scroller = getScroller(container); + const content = scroller.firstElementChild as HTMLElement; + const row = scroller.querySelector(".thread-message-row:last-child")!; + const gap = scroller.querySelector(".thread-message-end-gap")!; + let contentBottom = 565; + scroller.getBoundingClientRect = () => ({ bottom: 600 } as DOMRect); + gap.getBoundingClientRect = () => ({ height: 36 } as DOMRect); + row.getBoundingClientRect = () => ({ bottom: contentBottom, height: 100 } as DOMRect); + act(() => window.dispatchEvent(new Event("resize"))); + Object.defineProperties(scroller, { + scrollHeight: { configurable: true, value: 1000 }, + clientHeight: { configurable: true, value: 600 }, + scrollTop: { configurable: true, writable: true, value: 300 }, + }); + act(() => { scroller.dispatchEvent(new Event("scroll")); }); + expect(screen.getByRole("button", { name: "Scroll to bottom" })).toBeInTheDocument(); + contentBottom = 564; + act(() => { scroller.dispatchEvent(new Event("scroll")); }); + expect(screen.queryByRole("button", { name: "Scroll to bottom" })).not.toBeInTheDocument(); + contentBottom = 570; + const observer = resizeObserver.observers.find((item) => item.elements.includes(content))!; + act(() => { observer.callback([], observer); }); + expect(screen.getByRole("button", { name: "Scroll to bottom" })).toBeInTheDocument(); + vi.spyOn(ThreadMotionCoordinator.prototype, "navigateLatestTo").mockReturnValue("started"); + fireEvent.click(screen.getByRole("button", { name: "Scroll to bottom" })); + expect(screen.queryByRole("button", { name: "Scroll to bottom" })).not.toBeInTheDocument(); + fireEvent.wheel(scroller, { deltaY: -20 }); + expect(screen.getByRole("button", { name: "Scroll to bottom" })).toBeInTheDocument(); + } finally { + resizeObserver.restore(); + } + }); + it("keeps the scroll-to-bottom button above a growing composer", async () => { const resizeObserver = stubResizeObserver(); @@ -988,6 +1034,7 @@ describe("ThreadViewport", () => { scrollTop: { configurable: true, value: 0 }, }); + mockMessageEnd(scroller); act(() => { dispatchUserScroll(scroller); }); @@ -1046,6 +1093,7 @@ describe("ThreadViewport", () => { scrollTop: { configurable: true, writable: true, value: 0 }, }); + mockMessageEnd(scroller); act(() => { dispatchUserScroll(scroller); }); @@ -2379,6 +2427,7 @@ describe("ThreadViewport", () => { clientHeight: { configurable: true, value: 600 }, scrollTop: { configurable: true, writable: true, value: 300 }, }); + mockMessageEnd(scroller); act(() => { dispatchUserScroll(scroller); });