From da5f2bea68b933b1389802f7dca5273cb9563748 Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:28:50 +0800 Subject: [PATCH] fix(agents): extend the chat scrollbar to the composer --- e2e/agentMarkdown.spec.ts | 3 +- e2e/agentScroll.spec.ts | 32 ++++- src/features/agents/Session.module.css | 18 ++- src/features/agents/session/Stream.tsx | 164 +++++++++++++--------- src/features/agents/sessionState.test.tsx | 18 +-- src/ui/Scrollbar.module.css | 4 + src/ui/Scrollbar.tsx | 68 ++++++--- 7 files changed, 199 insertions(+), 108 deletions(-) diff --git a/e2e/agentMarkdown.spec.ts b/e2e/agentMarkdown.spec.ts index cd09673a4..dc172cfab 100644 --- a/e2e/agentMarkdown.spec.ts +++ b/e2e/agentMarkdown.spec.ts @@ -504,6 +504,7 @@ test("fits conversation stream, composer, question card and off-screen rows live Number.parseFloat(getComputedStyle(root).paddingLeft) + Number.parseFloat(getComputedStyle(root).paddingRight); return { conversationWidth: conversation.clientWidth, + streamWidth: root.clientWidth, streamInnerWidth: root.clientWidth - padding, columnWidth: column.width, bubbleWidth: bubble.width, @@ -538,7 +539,7 @@ test("fits conversation stream, composer, question card and off-screen rows live expect(Math.abs(fitted.columnWidth - fitted.streamInnerWidth)).toBeLessThan(1); expect(fitted.bubbleWidth).toBeGreaterThan(720); expect(Math.abs(fitted.bubbleWidth - fitted.streamInnerWidth * 0.8)).toBeLessThan(1); - expect(Math.abs(fitted.composerWidth - fitted.conversationWidth)).toBeLessThan(1); + expect(Math.abs(fitted.composerWidth - fitted.streamWidth)).toBeLessThan(1); expect(Math.abs(fitted.questionWidth - fitted.streamInnerWidth)).toBeLessThan(1); expect(fitted.offscreenRowHeight).toBeLessThan(capped.offscreenRowHeight); expect(fitted.scrollHeight).toBeLessThan(capped.scrollHeight); diff --git a/e2e/agentScroll.spec.ts b/e2e/agentScroll.spec.ts index aa2929ef5..2a9b28636 100644 --- a/e2e/agentScroll.spec.ts +++ b/e2e/agentScroll.spec.ts @@ -61,7 +61,7 @@ async function openHistory(page: Page) { { task, entries }, ); const stream = page.locator("[class*='_stream_']:visible"); - await expect(stream.locator(":scope > *")).toHaveCount(80 * 3); + await expect(stream.locator("[class*='_streamContent_'] > *")).toHaveCount(80 * 3); await page.evaluate(() => document.fonts.ready); return stream; } @@ -85,7 +85,7 @@ for (const placement of ["editor", "toolWindow"] as const) { ); // The working indicator ends the conversation, after its rows; the turn ends with a reply. await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible(); - await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1); + await expect(stream.locator("[class*='_streamContent_'] > *")).toHaveCount(80 * 3 + 1); await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2); const timer = await page.evaluate(async (id) => { const path = "/src/features/agents/store.ts"; @@ -139,6 +139,34 @@ for (const placement of ["editor", "toolWindow"] as const) { }); } +test("drags the conversation thumb through the full chat column", async ({ page }) => { + const stream = await openHistory(page); + const conversation = page.locator("[class*='_conversation_']:visible"); + const track = conversation.locator(":scope > [class*='_track_']"); + const thumb = track.locator(":scope > [class*='_thumb_']"); + const column = (await conversation.boundingBox())!; + const viewport = (await stream.boundingBox())!; + const rail = (await track.boundingBox())!; + const handle = (await thumb.boundingBox())!; + expect(handle.height).toBeGreaterThanOrEqual(64); + expect(rail.y).toBeCloseTo(column.y, 0); + expect(rail.y + rail.height).toBeCloseTo(column.y + column.height, 0); + expect(rail.y + rail.height).toBeGreaterThan(viewport.y + viewport.height); + expect(handle.y + handle.height).toBeCloseTo(rail.y + rail.height, 0); + + const x = handle.x + handle.width / 2; + await page.mouse.move(x, handle.y + handle.height / 2); + await page.mouse.down(); + await page.mouse.move(x, rail.y + 1, { steps: 5 }); + await expect.poll(() => stream.evaluate((el) => el.scrollTop)).toBeLessThan(2); + await page.mouse.move(x, rail.y + rail.height - 1, { steps: 5 }); + await page.mouse.up(); + await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2); + + await page.mouse.wheel(0, -100); + await expect(page.getByRole("button", { name: "Jump to Latest" })).toBeVisible(); +}); + for (const selected of [false, true]) { test(`keeps long-chat scroll geometry stable while jumping through history (selected: ${selected})`, async ({ page, diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css index f186d77a2..ffed7e30a 100644 --- a/src/features/agents/Session.module.css +++ b/src/features/agents/Session.module.css @@ -15,11 +15,13 @@ } .conversation { + position: relative; container-type: inline-size; display: flex; flex-direction: column; min-width: 0; min-height: 0; + padding-right: var(--space-3); border-right: 1px solid var(--border); } @@ -38,7 +40,7 @@ .withChanges { grid-template-columns: minmax(min(240px, 50%), 1fr) minmax(0, var(--agent-changes-width, 280px)); } -.fitWidth .stream > * { +.fitWidth .streamContent > * { width: 100%; } .fitWidth .userMessage > .user { @@ -204,12 +206,14 @@ padding: var(--space-3); /* Room below the end that keeps the header of a section folded there in place (`Stream`). */ padding-bottom: calc(var(--space-3) + var(--stream-slack, 0px)); - display: flex; - flex-direction: column; font-size: var(--agent-fs-ui, var(--fs-ui)); } -/* Actual row heights keep WebKit's scrollbar and cross-message selections anchored. */ -.stream > * { +.streamContent { + display: flex; + flex-direction: column; +} +/* Actual row heights keep the scrollbar and cross-message selections anchored. */ +.streamContent > * { flex: none; min-width: 0; width: min(100%, var(--session-content-width)); @@ -237,10 +241,10 @@ /* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a universal adjacent-sibling rule makes Chromium restyle whole sibling subtrees on every DOM insertion anywhere in the window, which costs every editor scroll frame. */ -.stream > :where(:not(:first-child)) { +.streamContent > :where(:not(:first-child)) { margin-top: var(--space-4); } -.stream > [data-process] + [data-process] { +.streamContent > [data-process] + [data-process] { margin-top: var(--space-2); } .stream:focus { diff --git a/src/features/agents/session/Stream.tsx b/src/features/agents/session/Stream.tsx index c3d5ec9d0..0b5dbe972 100644 --- a/src/features/agents/session/Stream.tsx +++ b/src/features/agents/session/Stream.tsx @@ -5,8 +5,10 @@ import { Button, copyMenuFor, EmptyState, + hideNativeScrollbar, Icon, IconButton, + Scrollbar, selectableText, showContextMenu, Spinner, @@ -138,7 +140,7 @@ function useOffscreenRows( mark(); }, 200); }); - resize.observe(el); + if (el.parentElement) resize.observe(el.parentElement); return () => { cancelAnimationFrame(frame); window.clearTimeout(timer); @@ -176,6 +178,7 @@ interface StreamProps { /** Entries rendered at a time when a conversation opens at its end. */ const ENTRY_BATCH = 40; +const MIN_THUMB_SIZE = 64; /** How long a conversation stays behind other tabs before it drops the entries painted above its tail. */ const HIDDEN_TRIM_MS = 30_000; @@ -217,6 +220,8 @@ export function Stream({ drafts, }: StreamProps) { const ref = useRef(null); + const content = useRef(null); + const track = useRef(null); // Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again. const visible = useEditorShown(); useSelectionBoundary(ref); @@ -273,7 +278,7 @@ export function Stream({ const loadEarlier = useCallback(() => { const el = ref.current; if (!visible || !el || start <= 0 || dragging.current || anchor.current) return; - const first = el.firstElementChild; + const first = content.current?.firstElementChild; if (!position.current.stick && first) anchor.current = { el: first, top: first.getBoundingClientRect().top }; startTransition(() => setShown((n) => n + ENTRY_BATCH)); }, [start, visible]); @@ -288,8 +293,11 @@ export function Stream({ }, [loadEarlier]); useEffect(() => { const down = (event: PointerEvent) => { - if (!ref.current?.contains(event.target as Node)) return; + const target = event.target as Node; + if (!ref.current?.contains(target) && !(event.button === 0 && track.current?.contains(target))) return; dragging.current = true; + markUserScroll(); + scrollingUp.current = false; if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); }; const up = () => { @@ -308,7 +316,7 @@ export function Stream({ window.removeEventListener("blur", up); if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); }; - }, [loadWhenStill]); + }, [loadWhenStill, markUserScroll]); useEffect(() => { // Following the end, paint the rest in the background. A user who scrolled away // gets them only after stopping near the top (`loadWhenStill`), so the scrollbar @@ -336,7 +344,7 @@ export function Stream({ return () => window.clearTimeout(timer); }, [visible]); const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings(); - useOffscreenRows(ref, visible, !finding, fitWindowWidth, fontZoom); + useOffscreenRows(content, visible, !finding, fitWindowWidth, fontZoom); /** * Blank space after the conversation that lets a section folded near the end keep its header * in place. It is only ever what the view shows below the content: scrolling up or new rows @@ -426,14 +434,16 @@ export function Stream({ */ useEffect(() => { const el = ref.current; - if (!el) return; + const scrollbar = track.current; + if (!el || !scrollbar) return; let gesture: { owner: HTMLElement; at: number } | null = null; const onWheel = (e: WheelEvent) => { if (e.defaultPrevented || e.ctrlKey || e.metaKey) return; if (e.shiftKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return; + const overTrack = e.currentTarget === scrollbar; const now = performance.now(); const latched = gesture && now - gesture.at < WHEEL_GESTURE_MS && gesture.owner.isConnected; - const owner = latched ? gesture!.owner : scrollOwner(e.target, el); + const owner = overTrack ? el : latched ? gesture!.owner : scrollOwner(e.target, el); gesture = { owner, at: now }; if (owner !== el) { const room = e.deltaY < 0 ? owner.scrollTop : owner.scrollHeight - owner.clientHeight - owner.scrollTop; @@ -441,11 +451,25 @@ export function Stream({ return; } markUserScroll(); - if (e.deltaY < 0) stopFollowing(e.target); + if (e.deltaY < 0) stopFollowing(overTrack ? el : e.target); else if (e.deltaY > 0) scrollingUp.current = false; + if (overTrack) { + e.preventDefault(); + const unit = + e.deltaMode === WheelEvent.DOM_DELTA_PAGE + ? el.clientHeight + : e.deltaMode === WheelEvent.DOM_DELTA_LINE + ? 16 + : 1; + el.scrollTop += e.deltaY * unit; + } }; el.addEventListener("wheel", onWheel, { passive: false }); - return () => el.removeEventListener("wheel", onWheel); + scrollbar.addEventListener("wheel", onWheel, { passive: false }); + return () => { + el.removeEventListener("wheel", onWheel); + scrollbar.removeEventListener("wheel", onWheel); + }; }, [markUserScroll, stopFollowing]); /** * The reader opened or closed a section: put its header back where it was, in the run or @@ -559,7 +583,7 @@ export function Stream({
{ touchY.current = e.touches.length === 1 ? e.touches[0]!.clientY : null; @@ -584,10 +608,6 @@ export function Stream({ ) scrollingUp.current = false; }} - onPointerDown={() => { - markUserScroll(); - scrollingUp.current = false; - }} onScroll={(e) => { const el = e.currentTarget; trimSlack(); @@ -630,66 +650,70 @@ export function Stream({ showContextMenu(e, items); }} > - {loadError && ( -
- - void executeAction("agents.retryConversation", { - task: task.id, - subagent: subagent?.id ?? null, - }) - } - > - Retry - - } - /> -
- )} - {entries === null ? ( - !loadError && - ) : entries.length === 0 && !busy && !loadError ? ( - - ) : ( - - {rows.map((row) => { - const images = toolImages(row); - return ( -
- {authorHeaders.has(row.index) && ( -
-
- - {providerName(task.provider)} +
+ {loadError && ( +
+ + void executeAction("agents.retryConversation", { + task: task.id, + subagent: subagent?.id ?? null, + }) + } + > + Retry + + } + /> +
+ )} + {entries === null ? ( + !loadError && + ) : entries.length === 0 && !busy && !loadError ? ( + + ) : ( + + {rows.map((row) => { + const images = toolImages(row); + return ( +
+ {authorHeaders.has(row.index) && ( +
+
+ + {providerName(task.provider)} +
-
- )} - {renderConversationRow(row)} - {images.length > 0 && ( -
- -
- )} -
- ); - })} - - )} - + )} + {renderConversationRow(row)} + {images.length > 0 && ( +
+ +
+ )} +
+ ); + })} + + )} + +
{away && !!entries?.length && }
+ ); diff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsx index d3841e8c2..dddd4f9c6 100644 --- a/src/features/agents/sessionState.test.tsx +++ b/src/features/agents/sessionState.test.tsx @@ -218,6 +218,7 @@ const input = (id: string) => ({ data: { task: id }, }); const stream = () => document.querySelector(`.${styles.stream}`)!; +const streamContent = () => stream().querySelector(`.${styles.streamContent}`)!; const tool = (id: string, overrides: Partial> = {}): AgentEntry => ({ type: "tool", id, @@ -363,7 +364,7 @@ describe("conversation rows", () => { render(); await screen.findByText("Done"); expect(stream().querySelectorAll(`.${styles.agentAuthor}`)).toHaveLength(1); - expect(stream().firstElementChild?.firstElementChild).toHaveClass(styles.agentAuthor!); + expect(streamContent().firstElementChild?.firstElementChild).toHaveClass(styles.agentAuthor!); }); it.each([subagent, { type: "message", incoming: true, text: "Parent request" }])( @@ -381,7 +382,7 @@ describe("conversation rows", () => { await screen.findByText("After the work"); const authors = stream().querySelectorAll(`.${styles.agentAuthor}`); expect(authors).toHaveLength(2); - expect(stream().children[1]?.querySelector(`.${styles.agentAuthor}`)).toBeNull(); + expect(streamContent().children[1]?.querySelector(`.${styles.agentAuthor}`)).toBeNull(); expect(authors[1]?.nextElementSibling).toHaveClass(styles.processRun!); expect(authors[1]?.parentElement?.nextElementSibling?.firstElementChild).toHaveClass(styles.agentMessage!); }, @@ -548,7 +549,7 @@ describe("turn folding", () => { // What the agent is doing ends the conversation, below its latest output. const working = stream().querySelector(`.${styles.working}`); expect(working).toHaveRole("status"); - expect(stream().lastElementChild).toBe(working); + expect(streamContent().lastElementChild).toBe(working); }); }); @@ -1144,18 +1145,19 @@ describe("scrolling", () => { ); el.scrollTop = 20; fireEvent.scroll(el); - const count = el.children.length; - const first = el.firstElementChild!; + const content = streamContent(); + const count = content.children.length; + const first = content.firstElementChild!; const top = vi.spyOn(first, "getBoundingClientRect"); top.mockReturnValue({ top: 100 } as DOMRect); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 180)); }); - expect(el.children.length).toBe(count); + expect(content.children.length).toBe(count); // Its old top is measured at release, then shifts down when rows are inserted. top.mockReturnValueOnce({ top: 100 } as DOMRect).mockReturnValue({ top: 500 } as DOMRect); fireEvent.pointerUp(window); - await waitFor(() => expect(el.children.length).toBeGreaterThan(count)); + await waitFor(() => expect(content.children.length).toBeGreaterThan(count)); expect(el.scrollTop).toBe(420); view.unmount(); }); @@ -2006,7 +2008,7 @@ describe("session state across tasks and hosts", () => { render(); expect(screen.getByText("Reply 149")).toBeInTheDocument(); expect(await screen.findByText("Reply 0")).toBeInTheDocument(); - expect(stream().children).toHaveLength(150); + expect(streamContent().children).toHaveLength(150); }); it("returns to the task conversation when the docked task changes after opening a subagent", async () => { diff --git a/src/ui/Scrollbar.module.css b/src/ui/Scrollbar.module.css index 7fb7a97be..ba46205e0 100644 --- a/src/ui/Scrollbar.module.css +++ b/src/ui/Scrollbar.module.css @@ -6,6 +6,10 @@ width: 10px; z-index: 1; } +.fullHeight { + bottom: 0; + touch-action: none; +} .thumb { position: absolute; left: 0; diff --git a/src/ui/Scrollbar.tsx b/src/ui/Scrollbar.tsx index aa5fd3f4c..72010052c 100644 --- a/src/ui/Scrollbar.tsx +++ b/src/ui/Scrollbar.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from "react"; +import clsx from "clsx"; import { lockScrollbarCursor } from "./dragCursor"; import styles from "./Scrollbar.module.css"; @@ -14,18 +15,30 @@ export const hideNativeScrollbar = styles.hideNative; * native one scrolls asynchronously in WebKit and shows blank rows until the * page catches up. * - * `contentHeight` re-measures when the scroller's content grows. + * Pass `content` to observe its size or `contentHeight` to re-measure on demand. + * `fullHeight` uses the height of the scrollbar's positioned parent. */ export function Scrollbar({ target, + content, contentHeight, + fullHeight = false, + minThumbSize = MIN_THUMB, + trackRef, }: { target: RefObject; + content?: RefObject; contentHeight?: number; + fullHeight?: boolean; + minThumbSize?: number; + trackRef?: RefObject; }) { - const track = useRef(null); + const ownTrack = useRef(null); + const track = trackRef ?? ownTrack; const thumb = useRef(null); - const drag = useRef<{ pointerId: number; y: number; top: number; unlock: () => void } | null>(null); + const drag = useRef<{ el: HTMLDivElement; pointerId: number; y: number; top: number; unlock: () => void } | null>( + null, + ); const geometry = useRef(null); const endDrag = useCallback(() => { const current = drag.current; @@ -33,22 +46,23 @@ export function Scrollbar({ drag.current = null; current.unlock(); delete thumb.current?.dataset.dragging; - const el = track.current; - if (el?.hasPointerCapture(current.pointerId)) el.releasePointerCapture(current.pointerId); + if (current.el.hasPointerCapture(current.pointerId)) current.el.releasePointerCapture(current.pointerId); }, []); useLayoutEffect(() => { - geometry.current = layout(target.current, track.current, thumb.current); - }, [target, contentHeight]); + geometry.current = layout(target.current, track.current, thumb.current, fullHeight, minThumbSize); + }, [target, track, fullHeight, minThumbSize, contentHeight]); useEffect(() => { const el = target.current; if (!el) return; const sync = () => { - geometry.current = layout(el, track.current, thumb.current); + geometry.current = layout(el, track.current, thumb.current, fullHeight, minThumbSize); }; el.addEventListener("scroll", sync, { passive: true }); const observer = new ResizeObserver(sync); observer.observe(el); + if (content?.current) observer.observe(content.current); + if (fullHeight && track.current?.parentElement) observer.observe(track.current.parentElement); window.addEventListener("blur", endDrag); return () => { endDrag(); @@ -56,12 +70,12 @@ export function Scrollbar({ el.removeEventListener("scroll", sync); observer.disconnect(); }; - }, [target, endDrag]); + }, [target, track, content, fullHeight, minThumbSize, endDrag]); return (
{ const el = target.current; @@ -75,7 +89,13 @@ export function Scrollbar({ return; } e.currentTarget.setPointerCapture(e.pointerId); - drag.current = { pointerId: e.pointerId, y: e.clientY, top: el.scrollTop, unlock: lockScrollbarCursor() }; + drag.current = { + el: e.currentTarget, + pointerId: e.pointerId, + y: e.clientY, + top: el.scrollTop, + unlock: lockScrollbarCursor(), + }; thumb.current!.dataset.dragging = ""; }} onPointerMove={(e) => { @@ -96,22 +116,30 @@ export function Scrollbar({ type Geometry = { range: number; max: number }; /** Positions the track over `el` and the thumb at its scroll offset; null when nothing scrolls. */ -function layout(el: HTMLElement | null, t: HTMLElement | null, th: HTMLElement | null): Geometry | null { +function layout( + el: HTMLElement | null, + t: HTMLElement | null, + th: HTMLElement | null, + fullHeight: boolean, + minThumbSize: number, +): Geometry | null { if (!el || !t || !th) return null; - const height = el.clientHeight; - const max = el.scrollHeight - height; + const viewport = el.clientHeight; + const height = fullHeight ? (t.parentElement?.clientHeight ?? 0) : viewport; + const content = el.scrollHeight; + const max = content - viewport; // WebKit can report scrollHeight a pixel over clientHeight after the scroller is resized to a // fractional height (dragging a splitter), with nothing overflowing: that is no scroll range. - const scrolls = max > 1; - t.style.top = `${el.offsetTop}px`; - t.style.height = `${height}px`; + const scrolls = viewport > 0 && height > 1 && max > 1; + t.style.top = fullHeight ? "" : `${el.offsetTop}px`; + t.style.height = fullHeight ? "" : `${height}px`; t.style.display = scrolls ? "" : "none"; if (!scrolls) return null; - const size = Math.max(MIN_THUMB, (height * height) / el.scrollHeight); + const size = Math.min(height - 1, Math.max(minThumbSize, (height * viewport) / content)); const range = height - size; th.style.height = `${size}px`; - th.style.transform = `translateY(${(Math.min(max, el.scrollTop) / max) * range}px)`; - return range > 0 ? { range, max } : null; + th.style.transform = `translateY(${(Math.max(0, Math.min(max, el.scrollTop)) / max) * range}px)`; + return { range, max }; } /**