From e52cb2e42664719f80c2a69b1ac33213f73fb024 Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:12:27 +0800 Subject: [PATCH] fix(agents): keep the conversation at its end after a send or an opened section (#2975) After a send the composer shrank and the conversation view grew; the resulting scroll was taken for a user scroll, so following the end stopped and the reply arrived below the view. A change of the view height now counts as layout. Opening a folded section (reasoning, tool call, turn) keeps the view at the end when the end was in view, else scrolls the section into view. --- src/features/agents/SessionEditor.tsx | 295 +++++++++++++--------- src/features/agents/sessionState.test.tsx | 65 +++++ 2 files changed, 241 insertions(+), 119 deletions(-) diff --git a/src/features/agents/SessionEditor.tsx b/src/features/agents/SessionEditor.tsx index a38828d97..3038c6a89 100644 --- a/src/features/agents/SessionEditor.tsx +++ b/src/features/agents/SessionEditor.tsx @@ -640,10 +640,11 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f const dragging = useRef(false); // When the user last scrolled the conversation (wheel, touch, keys, the scrollbar, Find): // that leaves the end. WebKit also moves the offset back on its own while rows lay out, - // which comes with a change of the content height; a scroll without one is meant too (the + // which comes with a change of the content height, and pulls it back to the end when the view + // grows taller (the composer shrinks after a send); a scroll without either is meant too (the // scrollbar thumb, a jump), whatever moved it. const userScrolled = useRef(-Infinity); - const seenHeight = useRef(0); + const seenHeight = useRef({ content: 0, view: 0 }); const markUserScroll = useCallback(() => { userScrolled.current = performance.now(); }, []); @@ -770,6 +771,40 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop }); }; }, [key, positions]); + // How far the end was below the view when a section was toggled, before its content renders. + const gapAtToggle = useRef(Infinity); + useEffect(() => { + const el = ref.current; + if (!el) return; + const toggled = () => { + gapAtToggle.current = el.scrollHeight - el.scrollTop - el.clientHeight; + }; + el.addEventListener("toggle", toggled, true); + return () => el.removeEventListener("toggle", toggled, true); + }, []); + /** + * An opened section grew the conversation below its header: with the end in view, stay at + * it; otherwise bring what it shows into view. Either way its header stays on screen, and + * following stops when that leaves the end out of view. + */ + const revealFold = useCallback( + (fold: HTMLElement) => { + const el = ref.current; + if (!el || dragging.current) return; + const view = el.getBoundingClientRect(); + const box = fold.getBoundingClientRect(); + const atEnd = position.current.stick || gapAtToggle.current < 40; + gapAtToggle.current = Infinity; + const below = atEnd ? el.scrollHeight - el.scrollTop - el.clientHeight : box.bottom - view.bottom; + if (below > 0) el.scrollTop += Math.max(0, Math.min(below, box.top - view.top)); + if (atEnd && el.scrollHeight - el.scrollTop - el.clientHeight >= 40) { + position.current = { top: el.scrollTop, stick: false }; + positions.set(key, position.current); + setAway(true); + } + }, + [key, positions], + ); /** Back to the end of the stream; following resumes from there. */ const jumpToLatest = useCallback(() => { const el = ref.current; @@ -840,126 +875,134 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f ); return ( -
- {finding && } -
{ - markUserScroll(); - if (e.deltaY < 0 && !e.ctrlKey && !e.defaultPrevented) stopFollowing(e.target); - else if (e.deltaY > 0 && !e.ctrlKey && !e.defaultPrevented) scrollingUp.current = false; - }} - onTouchStart={(e) => { - touchY.current = e.touches.length === 1 ? e.touches[0]!.clientY : null; - }} - onTouchMove={(e) => { - markUserScroll(); - const y = e.touches.length === 1 ? e.touches[0]!.clientY : null; - if (y !== null && touchY.current !== null && y > touchY.current) stopFollowing(e.target); - else if (y !== null && touchY.current !== null && y < touchY.current) scrollingUp.current = false; - touchY.current = y; - }} - onKeyDown={(e) => { - markUserScroll(); - if (e.defaultPrevented || (e.target as Element).closest("input, textarea, [contenteditable]")) return; - if (e.key === "ArrowUp" || e.key === "PageUp" || e.key === "Home" || (e.key === " " && e.shiftKey)) - stopFollowing(e.target); - else if (e.key === "ArrowDown" || e.key === "PageDown" || e.key === "End" || (e.key === " " && !e.shiftKey)) + +
+ {finding && } +
{ + markUserScroll(); + if (e.deltaY < 0 && !e.ctrlKey && !e.defaultPrevented) stopFollowing(e.target); + else if (e.deltaY > 0 && !e.ctrlKey && !e.defaultPrevented) scrollingUp.current = false; + }} + onTouchStart={(e) => { + touchY.current = e.touches.length === 1 ? e.touches[0]!.clientY : null; + }} + onTouchMove={(e) => { + markUserScroll(); + const y = e.touches.length === 1 ? e.touches[0]!.clientY : null; + if (y !== null && touchY.current !== null && y > touchY.current) stopFollowing(e.target); + else if (y !== null && touchY.current !== null && y < touchY.current) scrollingUp.current = false; + touchY.current = y; + }} + onKeyDown={(e) => { + markUserScroll(); + if (e.defaultPrevented || (e.target as Element).closest("input, textarea, [contenteditable]")) return; + if (e.key === "ArrowUp" || e.key === "PageUp" || e.key === "Home" || (e.key === " " && e.shiftKey)) + stopFollowing(e.target); + else if ( + e.key === "ArrowDown" || + e.key === "PageDown" || + e.key === "End" || + (e.key === " " && !e.shiftKey) + ) + scrollingUp.current = false; + }} + onPointerDown={() => { + markUserScroll(); scrollingUp.current = false; - }} - onPointerDown={() => { - markUserScroll(); - scrollingUp.current = false; - }} - onScroll={(e) => { - const el = e.currentTarget; - const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40; - const laidOut = el.scrollHeight !== seenHeight.current; - seenHeight.current = el.scrollHeight; - const byUser = dragging.current || performance.now() - userScrolled.current < 500 || !laidOut; - const movedDown = el.scrollTop > position.current.top; - const stayedAtEnd = position.current.stick && el.scrollTop === position.current.top; - const stick = - (atEnd && !scrollingUp.current && (movedDown || stayedAtEnd)) || (position.current.stick && !byUser); - // Still following: back to the end the offset was moved away from. - if (stick && !atEnd && !dragging.current) el.scrollTop = el.scrollHeight; - position.current = { top: el.scrollTop, stick }; - positions.set(key, position.current); - setAway(!position.current.stick); - // Reached the top of what is painted: fetch the earlier entries, but only - // once the drag has settled. - if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); - if (!position.current.stick && el.scrollTop < 120 && !dragging.current) loadWhenStill(); - }} - // Copy, plus Quote for a selection: replies to it in the composer. - onContextMenu={(e) => { - const text = selectionIn(e.currentTarget); - const items = copyMenuFor(e.target) ?? []; - if (text.trim() && task.status !== "archived") { - items.push({ - kind: "action", - action: "agents.quoteReply", - label: "Quote", - arg: { task: task.id, text }, - }); - } - if (!items.length) return; - e.preventDefault(); - 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) => ( -
- {authorHeaders.has(row.index) && ( -
-
- - {providerName(task.provider)} -
-
- )} - {renderConversationRow(row)} + }} + onScroll={(e) => { + const el = e.currentTarget; + const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40; + const laidOut = + el.scrollHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view; + seenHeight.current = { content: el.scrollHeight, view: el.clientHeight }; + const byUser = dragging.current || performance.now() - userScrolled.current < 500 || !laidOut; + const movedDown = el.scrollTop > position.current.top; + const stayedAtEnd = position.current.stick && el.scrollTop === position.current.top; + const stick = + (atEnd && !scrollingUp.current && (movedDown || stayedAtEnd)) || (position.current.stick && !byUser); + // Still following: back to the end the offset was moved away from. + if (stick && !atEnd && !dragging.current) el.scrollTop = el.scrollHeight; + position.current = { top: el.scrollTop, stick }; + positions.set(key, position.current); + setAway(!position.current.stick); + // Reached the top of what is painted: fetch the earlier entries, but only + // once the drag has settled. + if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); + if (!position.current.stick && el.scrollTop < 120 && !dragging.current) loadWhenStill(); + }} + // Copy, plus Quote for a selection: replies to it in the composer. + onContextMenu={(e) => { + const text = selectionIn(e.currentTarget); + const items = copyMenuFor(e.target) ?? []; + if (text.trim() && task.status !== "archived") { + items.push({ + kind: "action", + action: "agents.quoteReply", + label: "Quote", + arg: { task: task.id, text }, + }); + } + if (!items.length) return; + e.preventDefault(); + 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) => ( +
+ {authorHeaders.has(row.index) && ( +
+
+ + {providerName(task.provider)} +
+
+ )} + {renderConversationRow(row)} +
+ )) + )} + +
+ {away && !!entries?.length && }
- {away && !!entries?.length && } -
+
); } @@ -1839,6 +1882,9 @@ const FoldedContent = createContext(false); */ const OpenFolds = createContext | null>(null); +/** Scrolls a section the reader just opened into view (`Stream`). */ +const RevealFold = createContext<((el: HTMLElement) => void) | null>(null); + /** * A collapsed section that renders its content only once opened: most of a long conversation * stays folded, and keeping it out of the DOM keeps showing and restyling the tab cheap. @@ -1859,13 +1905,24 @@ function Fold({ }) { const always = useContext(FoldedContent); const remembered = useContext(OpenFolds); + const reveal = useContext(RevealFold); const [expanded, setExpanded] = useState(() => !!open || (!!id && !!remembered?.get(id))); + const ref = useRef(null); + const opened = useRef(false); + // Once its content is laid out, so its height is known. + useLayoutEffect(() => { + if (!expanded || !opened.current) return; + opened.current = false; + if (ref.current) reveal?.(ref.current); + }, [expanded, reveal]); return (
{ const now = e.currentTarget.open; + opened.current = now; setExpanded(now); if (id && remembered) { if (now) remembered.set(id, true); diff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsx index 6c1036201..c83a4788c 100644 --- a/src/features/agents/sessionState.test.tsx +++ b/src/features/agents/sessionState.test.tsx @@ -529,6 +529,71 @@ describe("scrolling", () => { expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull(); }); + it.each([ + { name: "stays at the end below it", top: 300, bottom: 360, scrolled: 60, away: false }, + { name: "keeps its header on screen", top: 50, bottom: 900, scrolled: 50, away: true }, + { name: "back at the end without following", top: 300, bottom: 360, scrolled: 60, away: false, released: true }, + ])("scrolls a section opened at the end into view: $name", async ({ top, bottom, scrolled, away, released }) => { + backend.entries.set("A", [ + { type: "thought", text: "Weighing it" }, + { type: "agent", text: "Answer A" }, + ]); + useAgents.setState({ entries: new Map(backend.entries) }); + render(); + await screen.findByText("Answer A"); + const el = stream(); + Object.defineProperty(el, "scrollHeight", { configurable: true, value: 1000 }); + Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 }); + el.getBoundingClientRect = () => ({ top: 0, bottom: 400 }) as DOMRect; + el.scrollTop = 600; + fireEvent.scroll(el); + if (released) { + fireEvent.wheel(el, { deltaY: -50 }); + el.scrollTop = 550; + fireEvent.scroll(el); + el.scrollTop = 600; + fireEvent.scroll(el); + expect(screen.getByRole("button", { name: "Jump to Latest" })).toBeInTheDocument(); + } + const fold = stream().querySelector("details")!; + fold.getBoundingClientRect = () => ({ top, bottom }) as DOMRect; + // It grows once its content renders. + Object.defineProperty(el, "scrollHeight", { + configurable: true, + get: () => (fold.children.length > 1 ? 1000 + bottom - top : 1000), + }); + fireEvent.pointerDown(fold); + fireEvent.pointerUp(fold); + fold.open = true; + act(() => { + fireEvent(fold, new Event("toggle")); + }); + expect(el.scrollTop).toBe(600 + scrolled); + fireEvent.scroll(el); + // With the end out of view, the next chunk doesn't pull the reader away from the section. + expect(screen.queryByRole("button", { name: "Jump to Latest" }) !== null).toBe(away); + }); + + it("keeps following when the view grows taller and the browser pulls the offset back", () => { + useAgents.setState({ entries: new Map([["A", [{ type: "agent", text: "Initial reply" }]]]) }); + render(); + const el = stream(); + let height = 1000; + let viewport = 400; + Object.defineProperty(el, "scrollHeight", { configurable: true, get: () => height }); + Object.defineProperty(el, "clientHeight", { configurable: true, get: () => viewport }); + el.scrollTop = 600; + fireEvent.scroll(el); + // The composer shrank after sending: the end moved up and the offset was clamped to it. + viewport = 500; + el.scrollTop = 500; + fireEvent.scroll(el); + expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull(); + height = 1200; + act(() => useAgents.setState({ entries: new Map([["A", [{ type: "agent", text: "Streaming" }]]]) })); + expect(el.scrollTop).toBe(1200); + }); + it.each(["wheel", "touch", "ArrowUp", "PageUp", "Home", "Shift+Space"])( "releases following before an upward %s scroll, even within the bottom threshold", async (method) => {