From cf0e57e5dfed4b2d907ca31a5b79997cdd549343 Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Thu, 26 Nov 2026 15:20:55 -0800 Subject: [PATCH] fix(agents): advance history batching past long folded process runs (#6278) A session's history paints from the end in batches of ENTRY_BATCH, and the first painted entry moves back over a leading run of tool calls so a folded process row is never split. Since all consecutive tool calls fold into one run, a run longer than a batch made the next batch end inside the same run, so start never moved: the background batches and loading earlier messages at the top both stalled, and earlier turns never appeared (also after a hidden tab trimmed its history). The next batch now steps past what is actually painted. A conversation scrolled away from the end also keeps loading while its rows don't fill the viewport or it sits near the top. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- e2e/agentScroll.spec.ts | 45 ++++++++++++ src/features/agents/hiddenWindow.test.tsx | 85 +++++++++++++++++++++++ src/features/agents/session/Stream.tsx | 67 ++++++++++++++---- 3 files changed, 182 insertions(+), 15 deletions(-) diff --git a/e2e/agentScroll.spec.ts b/e2e/agentScroll.spec.ts index 005b35a9dd..f994d352f4 100644 --- a/e2e/agentScroll.spec.ts +++ b/e2e/agentScroll.spec.ts @@ -209,3 +209,48 @@ test("opens a folded process run with the keyboard and jumps back to the latest await expect(jump).toBeHidden(); await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(40); }); + +test("paints earlier turns past folded process runs longer than ENTRY_BATCH", async ({ page }) => { + const longRun = (prefix: string, count: number): AgentEntry[] => + Array.from({ length: count }, (_, i): AgentEntry => ({ + type: "tool", + id: `${prefix}-${i}`, + kind: i % 3 === 0 ? "edit" : i % 2 === 0 ? "execute" : "read", + title: `tool ${prefix}-${i}`, + status: "completed", + locations: [], + output: null, + diffs: [], + })); + const longProcessEntries: AgentEntry[] = [ + { type: "user", text: "Earliest request before long runs", attachments: [], steered: false }, + { type: "agent", text: "Initial reply" }, + { type: "user", text: "Split PR into three focused PRs", attachments: [], steered: false }, + ...longRun("batch-a", 75), + { type: "agent", text: "Interim status update" }, + ...longRun("batch-b", 75), + ]; + await page.goto("/"); + await page.getByRole("tree", { name: "Project" }).waitFor(); + await page.evaluate( + async ({ task, entries }) => { + const path = "/src/features/agents/store.ts"; + const store = await import(path); + store.useAgents.setState({ + loaded: true, + error: null, + providers: [], + tasks: new Map([[task.id, { ...task, status: "running" }]]), + entries: new Map([[task.id, entries]]), + unread: new Set(), + docked: null, + }); + store.openTaskInEditorLocation(task.id); + }, + { task, entries: longProcessEntries }, + ); + const stream = page.locator("[class*='_stream_']:visible"); + await expect(stream.getByText("Earliest request before long runs")).toBeVisible(); + await expect(stream.getByText("Split PR into three focused PRs")).toBeVisible(); + await expect(stream.getByText("Interim status update")).toBeVisible(); +}); diff --git a/src/features/agents/hiddenWindow.test.tsx b/src/features/agents/hiddenWindow.test.tsx index be92d0738a..b25c6c9852 100644 --- a/src/features/agents/hiddenWindow.test.tsx +++ b/src/features/agents/hiddenWindow.test.tsx @@ -255,4 +255,89 @@ describe("a kept-alive session tab that stays hidden", { timeout: 30_000 }, () = // The one request in the trimmed part of the history is found. expect(await screen.findByText("1/1", {}, { timeout: 10_000 })).toBeInTheDocument(); }); + + it("paints earlier messages past folded process runs longer than ENTRY_BATCH on open and after hiding", async () => { + const toolCalls = (prefix: string, count: number): AgentEntry[] => + Array.from({ length: count }, (_, k): AgentEntry => ({ + type: "tool", + id: `${prefix}-${k}`, + title: `Read src/file${k}.ts`, + kind: "read", + status: "completed", + locations: [], + output: null, + diffs: [], + })); + const longRuns: AgentEntry[] = [ + ...history(5), + { type: "user", text: "Split the PR", attachments: [], sentMs: null }, + ...toolCalls("first-run", 75), + { type: "agent", text: "Interim update" }, + ...toolCalls("second-run", 75), + ]; + useAgents.setState({ + tasks: new Map([[task("A").id, { ...task("A"), status: "running" }]]), + entries: new Map([["A", longRuns]]), + }); + + const view = render(session(true)); + expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument(); + expect(screen.getByText("Split the PR")).toBeInTheDocument(); + + vi.useFakeTimers(); + view.rerender(session(false)); + await act(async () => { + await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS); + }); + expect(screen.queryByText("Request 0")).toBeNull(); + + vi.useRealTimers(); + view.rerender(session(true)); + expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument(); + expect(screen.getByText("Split the PR")).toBeInTheDocument(); + }); + + it("loads earlier messages past a long process run when scrolled to the top with stick disabled", async () => { + const longRun: AgentEntry[] = [ + ...history(3), + { type: "user", text: "Prompt before long run", attachments: [], sentMs: null }, + ...Array.from({ length: 75 }, (_, k): AgentEntry => ({ + type: "tool", + id: `top-run-${k}`, + title: `Read src/mod${k}.ts`, + kind: "read", + status: "completed", + locations: [], + output: null, + diffs: [], + })), + { type: "agent", text: "Tail reply" }, + ]; + useAgents.setState({ entries: new Map([["A", longRun]]) }); + // Suppress background auto-follow after initial render by scrolling away before history finishes. + const view = render(session(true)); + await settle("Tail reply"); + vi.useFakeTimers(); + view.rerender(session(false)); + await act(async () => { + await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS); + }); + expect(screen.queryByText("Request 0")).toBeNull(); + + // User switches back while holding pointer down, then scrolls to the top (`stick: false`). + fireEvent.pointerDown(stream()); + view.rerender(session(true)); + const el = stream(); + layOut(el); + fireEvent.wheel(el, { deltaY: -120 }); + el.scrollTop = 0; + fireEvent.scroll(el); + fireEvent.pointerUp(window); + await act(async () => { + await vi.advanceTimersByTimeAsync(2_000); + }); + vi.useRealTimers(); + expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument(); + expect(screen.getByText("Prompt before long run")).toBeInTheDocument(); + }); }); diff --git a/src/features/agents/session/Stream.tsx b/src/features/agents/session/Stream.tsx index 5e25a0925f..8e85630534 100644 --- a/src/features/agents/session/Stream.tsx +++ b/src/features/agents/session/Stream.tsx @@ -212,6 +212,24 @@ function clampMultiClick(target: EventTarget) { if (row) clampSelectionToRow(document.getSelection(), row); } +/** First entry index painted for a `shown` tail cap, keeping a leading process run intact. */ +function historyStart(entries: readonly AgentEntry[], shown: number): number { + let start = Math.max(0, entries.length - shown); + // Keep a process run intact so prepending never replaces the anchored row. + while (start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--; + return start; +} + +/** + * Next `shown` cap after one batch. Keeping a process run intact can already paint more than + * `shown` entries, so step past what is actually painted (`entries.length - start`) rather than + * `shown`; otherwise a process run longer than `ENTRY_BATCH` leaves `start` unchanged and stalls. + */ +function nextShownBatch(entries: readonly AgentEntry[] | null, shown: number): number { + if (!entries) return shown + ENTRY_BATCH; + return Math.max(shown, entries.length - historyStart(entries, shown)) + ENTRY_BATCH; +} + export function Stream({ loadError, task, @@ -239,9 +257,11 @@ export function Stream({ // Opened at the end, the last entries come first and the earlier ones follow in batches: // reopening a long conversation paints at once. A kept offset needs them all. const [shown, setShown] = useState(() => (positions.get(key)?.stick === false ? Infinity : ENTRY_BATCH)); - let start = finding || !entries ? 0 : Math.max(0, entries.length - shown); - // Keep a process run intact so prepending never replaces the anchored row. - while (entries && start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--; + const start = finding || !entries ? 0 : historyStart(entries, shown); + const latest = useRef({ entries, start, visible }); + useLayoutEffect(() => { + latest.current = { entries, start, visible }; + }); 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, @@ -280,11 +300,12 @@ export function Stream({ const anchor = useRef<{ el: Element; top: number } | null>(null); const loadEarlier = useCallback(() => { const el = ref.current; - if (!visible || !el || start <= 0 || dragging.current || anchor.current) return; + const { start: currentStart, visible: isVisible } = latest.current; + if (!isVisible || !el || currentStart <= 0 || dragging.current || anchor.current) return; const first = el.firstElementChild; if (!position.current.stick && first) anchor.current = { el: first, top: first.getBoundingClientRect().top }; - startTransition(() => setShown((n) => n + ENTRY_BATCH)); - }, [start, visible]); + startTransition(() => setShown((n) => nextShownBatch(latest.current.entries, n))); + }, []); const loadTimer = useRef(null); /** Load the next batch once the user stops scrolling near the top. */ const loadWhenStill = useCallback(() => { @@ -298,12 +319,19 @@ export function Stream({ const down = (event: PointerEvent) => { if (!ref.current?.contains(event.target as Node)) return; dragging.current = true; - if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); + if (loadTimer.current !== null) { + window.clearTimeout(loadTimer.current); + loadTimer.current = null; + } }; const up = () => { if (!dragging.current) return; dragging.current = false; - if (ref.current && (position.current.stick || ref.current.scrollTop < 120)) loadWhenStill(); + if ( + ref.current && + (position.current.stick || ref.current.scrollHeight <= ref.current.clientHeight || ref.current.scrollTop < 120) + ) + loadWhenStill(); }; window.addEventListener("pointerdown", down, true); window.addEventListener("pointerup", up, true); @@ -314,16 +342,24 @@ export function Stream({ window.removeEventListener("pointerup", up, true); window.removeEventListener("pointercancel", up, true); window.removeEventListener("blur", up); - if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); + if (loadTimer.current !== null) { + window.clearTimeout(loadTimer.current); + loadTimer.current = null; + } }; }, [loadWhenStill]); 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 - // is not resized mid-drag. A hidden tab paints nothing more. - if (visible && start > 0 && position.current.stick && !dragging.current) - startTransition(() => setShown((n) => n + ENTRY_BATCH)); - }, [start, visible]); + // gets them only after stopping near the top (`loadWhenStill`), or when folded rows + // do not yet fill the viewport, so the scrollbar is not resized mid-drag. A hidden + // tab paints nothing more. + if (!visible || start <= 0 || dragging.current) return; + if (position.current.stick) { + startTransition(() => setShown((n) => nextShownBatch(latest.current.entries, n))); + } else if (ref.current && (ref.current.scrollHeight <= ref.current.clientHeight || ref.current.scrollTop < 120)) { + loadWhenStill(); + } + }, [loadWhenStill, start, visible]); useEffect(() => { // A conversation read to its end gives back the history painted above its recent entries // once it stays behind other tabs: a few kept-alive tabs would otherwise hold every turn @@ -418,6 +454,7 @@ export function Stream({ const observer = new ResizeObserver(() => { trimSlack(); if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight; + else if (!position.current.stick && el.scrollHeight <= el.clientHeight && !dragging.current) loadWhenStill(); updateJumpVisibility(el); }); observer.observe(el); @@ -425,7 +462,7 @@ export function Stream({ observer.disconnect(); if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop }); }; - }, [key, positions, trimSlack, updateJumpVisibility]); + }, [key, loadWhenStill, positions, trimSlack, updateJumpVisibility]); /** * The wheel scrolls the innermost container under the pointer, and only that one: a run of * calls from its headers, a tool output from its text, the conversation elsewhere. A container