From 97598641be4e32803c53357070db49eceffbd074 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 01:25:34 +0800 Subject: [PATCH] fix(agents): keep the reader's place when streamed content reflows above or below (#6863) Scrolled away from the end while a reply streams, the view jumped when rows changed height (a reasoning folding once the next tool call arrives, a lone call joining a folded run): WebKit has no scroll anchoring. Away from the end, Stream now keeps the row at the top of the view in place after every render, row resize and scroll; content that gets shorter below leaves blank room (now an ::after spacer) instead of pulling the view down. Following the end is unchanged. --- src/features/agents/Session.module.css | 10 +- src/features/agents/session/Stream.tsx | 99 +++++++++++++-- .../agents/session/holdShownRow.test.tsx | 114 ++++++++++++++++++ 3 files changed, 213 insertions(+), 10 deletions(-) create mode 100644 src/features/agents/session/holdShownRow.test.tsx diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css index 06cbe9a80..10bc2d8e6 100644 --- a/src/features/agents/Session.module.css +++ b/src/features/agents/Session.module.css @@ -229,12 +229,18 @@ overflow-x: hidden; overflow-anchor: none; 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)); } +/* Room below the end that keeps the reader's place when the content above it gets shorter + (`Stream`). Not padding: a flex item is never shorter than its padding, so room taller than + the view would make the stream taller than its area. */ +.stream::after { + content: ""; + flex: none; + height: var(--stream-slack, 0px); +} /* Actual row heights keep WebKit's scrollbar and cross-message selections anchored. */ .stream > * { flex: none; diff --git a/src/features/agents/session/Stream.tsx b/src/features/agents/session/Stream.tsx index fcf7641a5..81e9aab40 100644 --- a/src/features/agents/session/Stream.tsx +++ b/src/features/agents/session/Stream.tsx @@ -217,6 +217,22 @@ export function revealRowsAt(el: HTMLElement, top: number) { } } +/** The first row the view shows and its top in the view; the rows are laid out in order. */ +function firstShownRow(el: HTMLElement): { row: Element; top: number } | null { + const rows = el.querySelectorAll(`:scope > .${styles.conversationRow}`); + if (!rows.length) return null; + const view = el.getBoundingClientRect().top; + let lo = 0; + let hi = rows.length - 1; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (rows[mid]!.getBoundingClientRect().bottom > view) hi = mid; + else lo = mid + 1; + } + const row = rows[lo]!; + return { row, top: row.getBoundingClientRect().top - view }; +} + /** Images remain visible beside the work's folded summary, without duplicating them when it opens. */ function toolImages(row: ConversationRow): AgentImage[] { return rowEntries(row).flatMap((entry) => (entry.type === "tool" ? (entry.images ?? []) : [])); @@ -349,12 +365,20 @@ export function Stream({ }, [key, positions], ); + /** + * Blank space after the conversation that keeps the reader's place: the header of a section + * folded near the end, or the row at the top of the view when the content below it gets + * shorter. It is only ever what the view shows below the content: scrolling up or new rows + * take it back without moving anything. + */ + const slack = useRef(0); const updateJumpVisibility = useCallback((el: HTMLElement) => { // An upward gesture releases following before anything moves. Only offer a jump // when there is actual content below the viewport, excluding the fold spacer. setAway( !position.current.stick && - el.scrollHeight - el.clientHeight - el.scrollTop > (parseFloat(getComputedStyle(el).paddingBottom) || 0) + 1, + el.scrollHeight - el.clientHeight - el.scrollTop > + (parseFloat(getComputedStyle(el).paddingBottom) || 0) + slack.current + 1, ); }, []); // Earlier entries are prepended above the view: remember where the first painted row is @@ -443,12 +467,6 @@ export function Stream({ }, [visible]); const { toolCalls, fitWindowWidth } = useAgentSettings(); useOffscreenRows(ref, 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 - * take it back without moving anything. - */ - const slack = useRef(0); const setSlack = useCallback((px: number) => { slack.current = px; if (px) ref.current?.style.setProperty("--stream-slack", `${px}px`); @@ -461,6 +479,49 @@ export function Stream({ const next = Math.max(0, Math.min(slack.current, Math.ceil(el.scrollTop + el.clientHeight - content))); if (next !== slack.current) setSlack(next); }, [setSlack]); + /** + * Away from the end, the row at the top of the view stays where it is when rows change height + * (WebKit has no scroll anchoring): a reasoning that folds once the next call arrives, a lone + * call joining a run. Content that gets shorter below leaves blank room rather than pulling + * the view down. A scroll by anything else since the row was taken just takes the row again. + */ + const shownRow = useRef<{ + row: Element; + top: number; + scrollTop: number; + } | null>(null); + const holdShownRow = useCallback(() => { + const el = ref.current; + if (!el) return; + const held = shownRow.current; + shownRow.current = null; + if (position.current.stick || !latest.current.visible) return; + // Rows that grew back below take the room left for them. + trimSlack(); + if (held?.row.isConnected && !dragging.current) { + // Content that got shorter below clamps the offset to the new end. + const clamped = el.scrollTop < held.scrollTop && el.scrollTop >= el.scrollHeight - el.clientHeight - 1; + if (el.scrollTop === held.scrollTop || clamped) { + const moved = held.row.getBoundingClientRect().top - el.getBoundingClientRect().top - held.top; + if (Math.abs(moved) >= 1) { + const target = Math.max(0, el.scrollTop + moved); + const short = Math.ceil(target + el.clientHeight - el.scrollHeight); + if (short > 0) setSlack(slack.current + short); + el.scrollTop = target; + position.current = { top: el.scrollTop, stick: false }; + positions.set(key, position.current); + updateJumpVisibility(el); + } + } + } + const shown = firstShownRow(el); + shownRow.current = shown && { ...shown, scrollTop: el.scrollTop }; + }, [key, positions, setSlack, trimSlack, updateJumpVisibility]); + /** Take the row at the top of the view again, after a scroll that is meant. */ + const takeShownRow = useCallback(() => { + shownRow.current = null; + holdShownRow(); + }, [holdShownRow]); /** A diagram that drew after the last streamed chunk grows the conversation: keep following. */ const onDiagramDrawn = useCallback(() => { const el = ref.current; @@ -510,6 +571,26 @@ export function Stream({ scroller.scrollTop += from.el.getBoundingClientRect().top - from.top; updateJumpVisibility(scroller); }); + useLayoutEffect(() => { + holdShownRow(); + }); + useEffect(() => { + // A row also changes height on its own (a reasoning folding when its turn moves on, text + // revealed at a pace, an image loading): before it paints. + const el = ref.current; + if (!el || typeof ResizeObserver === "undefined") return; + const resize = new ResizeObserver(() => holdShownRow()); + const watch = () => { + for (const row of el.querySelectorAll(`:scope > .${styles.conversationRow}`)) resize.observe(row); + }; + watch(); + const rows = new MutationObserver(watch); + rows.observe(el, { childList: true }); + return () => { + rows.disconnect(); + resize.disconnect(); + }; + }, [holdShownRow]); useLayoutEffect(() => { const el = ref.current; if (!el) return; @@ -581,8 +662,9 @@ export function Stream({ positions.set(key, position.current); } updateJumpVisibility(el); + takeShownRow(); }, - [key, positions, setSlack, trimSlack, updateJumpVisibility], + [key, positions, setSlack, takeShownRow, trimSlack, updateJumpVisibility], ); /** Back to the end of the stream; following resumes from there. */ const jumpToLatest = useCallback(() => { @@ -759,6 +841,7 @@ export function Stream({ // once the drag has settled. if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); if (!position.current.stick && el.scrollTop < 120 && !dragging.current) loadWhenStill(); + holdShownRow(); }} // Copy, plus Quote for a selection: replies to it in the composer. onContextMenu={(e) => { diff --git a/src/features/agents/session/holdShownRow.test.tsx b/src/features/agents/session/holdShownRow.test.tsx new file mode 100644 index 000000000..0d8a067d3 --- /dev/null +++ b/src/features/agents/session/holdShownRow.test.tsx @@ -0,0 +1,114 @@ +import { act, fireEvent, render, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import type { AgentEntry, AgentTask } from "@/bindings"; + +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original()), + commands: { + agentEntries: async () => ({ + status: "ok", + data: useAgents.getState().entries.get(task.id) ?? [], + }), + agentChanges: async () => ({ status: "ok", data: [] }), + agentGroupedChanges: async () => ({ + status: "ok", + data: { uncommitted: [], commits: [] }, + }), + vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }), + }, +})); +vi.mock("@tauri-apps/api/webview", () => ({ + getCurrentWebview: () => ({ + onDragDropEvent: () => Promise.resolve(() => {}), + }), +})); + +import styles from "../Session.module.css"; +import { SessionEditor } from "../SessionEditor"; +import { useAgents } from "../store"; + +const task: AgentTask = { + id: "anchor", + title: "Test task", + provider: "codex", + status: "ready", + isolation: "local", + model: null, + cwd: "/project", + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: 0, + updatedMs: 0, + config: [], + commands: [], + usage: null, + queue: [], + capabilities: { fork: true, rollback: true, steer: true, images: true }, +}; + +const agent = (text: string): AgentEntry => ({ type: "agent", text }); + +let scroller: HTMLElement | null = null; +/** Rows stack from the top of the stream: a row whose text says "tall" is 300px, any other 100px. */ +const height = (row: Element) => (row.textContent?.includes("tall") ? 300 : 100); +const rowsOf = (el: HTMLElement) => [...el.querySelectorAll(`:scope > .${styles.conversationRow}`)]; +const original = Element.prototype.getBoundingClientRect; + +beforeEach(() => { + useAgents.setState({ + loaded: true, + tasks: new Map([[task.id, task]]), + entries: new Map([[task.id, [agent("tall one"), agent("two"), agent("three"), agent("four"), agent("five")]]]), + composers: new Map(), + focus: null, + }); + Element.prototype.getBoundingClientRect = function (this: Element) { + if (scroller && this === scroller) return new DOMRect(0, 0, 600, 400); + if (scroller && this.parentElement === scroller) { + let top = -scroller.scrollTop; + for (const row of rowsOf(scroller)) { + if (row === this) return new DOMRect(0, top, 600, height(row)); + top += height(row); + } + } + return original.call(this); + }; +}); + +afterEach(() => { + Element.prototype.getBoundingClientRect = original; + scroller = null; +}); + +it("keeps the row at the top of the view in place when a row above it gets shorter", async () => { + const { container } = render( + , + ); + const el = await waitFor(() => { + const found = container.querySelector(`.${styles.conversationRow}`)?.parentElement; + expect(found).toBeTruthy(); + return found!; + }); + scroller = el; + Object.defineProperty(el, "clientHeight", { value: 400, configurable: true }); + Object.defineProperty(el, "scrollHeight", { + get: () => rowsOf(el).reduce((sum, row) => sum + height(row), 0), + configurable: true, + }); + // Scrolled up from the end: "two" is at the top of the view, 50px of it above. + fireEvent.wheel(el, { deltaY: -4 }); + el.scrollTop = 350; + fireEvent.scroll(el); + + // The first row gets 200px shorter above the view. + act(() => { + useAgents.setState({ + entries: new Map([[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("five")]]]), + }); + }); + expect(el.scrollTop).toBe(150); + const two = rowsOf(el).find((row) => row.textContent?.includes("two"))!; + expect(two.getBoundingClientRect().top).toBe(-50); +});