From 2afd6363145aa2cc7c2a99ecbd2a4acc8f37cb65 Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:06:38 +0200 Subject: [PATCH] perf(agents): drop a hidden session tab's painted history (#5494) A kept-alive session tab (up to 5, `KEPT_TABS`) painted its whole conversation and never gave any of it back: `Stream` opens at the last `ENTRY_BATCH` (40) entries, then the "following the end" effect (`Stream.tsx`, the `useEffect` on `[start]`) keeps adding batches until the full history is DOM, hidden or not. Five long tabs therefore held every turn as DOM nodes (WebKit keeps layout/style/render-tree memory for all of it). Now a tab that was left at the end of its conversation and stays hidden for 30 s drops back to its recent tail, and a hidden tab no longer paints more batches. When it is shown again it is at the end as before and re-paints the earlier entries in the background exactly as when it first opened. Independent of #5462 (hidden tabs stop rendering), #5467 (per-chunk re-render) and the Rust PRs. Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- perf/scenarios.ts | 16 +- src/features/agents/hiddenWindow.test.tsx | 256 ++++++++++++++++++++++ src/features/agents/session/Stream.tsx | 35 ++- 3 files changed, 287 insertions(+), 20 deletions(-) create mode 100644 src/features/agents/hiddenWindow.test.tsx diff --git a/perf/scenarios.ts b/perf/scenarios.ts index 37b358e6a..d2dec1043 100644 --- a/perf/scenarios.ts +++ b/perf/scenarios.ts @@ -567,24 +567,14 @@ const agentTabs: Scenario = { // The conversation shown: its requests end with its task's title. const SHOWN = "[data-editor-focus] [data-message]"; const title = (n: number) => `(Sample task ${n})`; - // Both conversations get their earlier entries painted in background batches, also the - // first one, hidden behind the second as soon as it opened. - await h.page.waitForFunction( - () => - [...document.querySelectorAll("[data-message]")] - .map((m) => m.parentElement!) - .filter((stream, i, all) => all.indexOf(stream) === i && stream.textContent!.includes("Turn 0:")).length === - 2, - undefined, - { timeout: 30_000, polling: 200 }, - ); - // Rows painted while hidden are laid out the first time their conversation shows. + // Visit each conversation to let it finish painting and laying out its history. for (const n of [1, 2]) { await h.page.getByRole("tab", { name: `Sample task ${n}` }).click(); await h.page .locator(SHOWN, { hasText: title(n) }) + .filter({ hasText: "Turn 0:" }) .first() - .waitFor(); + .waitFor({ state: "attached", timeout: 30_000 }); await h.page.waitForTimeout(300); } // WebKit restyles a hidden conversation in full when it is shown again (Chromium keeps its diff --git a/src/features/agents/hiddenWindow.test.tsx b/src/features/agents/hiddenWindow.test.tsx new file mode 100644 index 000000000..3c07cb16e --- /dev/null +++ b/src/features/agents/hiddenWindow.test.tsx @@ -0,0 +1,256 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen, within } from "@testing-library/react"; +import type { AgentEntry, AgentTask } from "@/bindings"; +import { useProject } from "@/platform/project"; +import { EditorShownProvider } from "@/workbench/contributions"; +import { SessionEditor } from "./SessionEditor"; +import { SESSION_KIND, sessionKey } from "./model"; +import { focusedSession } from "./sessionFocus"; +import { disconnect, useAgents } from "./store"; +import styles from "./Session.module.css"; + +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original()), + commands: { + fsProbe: async () => ({ status: "ok", data: { size: 1, binary: false, tooLarge: false } }), + agentChanges: async () => ({ status: "ok", data: [] }), + agentGroupedChanges: async () => ({ status: "ok", data: { uncommitted: [], commits: [] } }), + vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }), + agentEntries: async () => ({ status: "ok", data: [] }), + }, +})); +vi.mock("@tauri-apps/api/webview", () => ({ + getCurrentWebview: () => ({ onDragDropEvent: () => Promise.resolve(() => {}) }), +})); +vi.mock("@/workbench/contributions", async (original) => ({ + ...(await original()), + editorService: () => ({ closeInput: vi.fn(), openInput: vi.fn() }), + toolWindowService: () => ({ show: vi.fn() }), +})); + +const TURNS = 60; +/** Hidden for longer than any plausible "a while". */ +const LONG_HIDDEN_MS = 10 * 60_000; + +const task = (id: string): AgentTask => ({ + id, + title: id, + provider: "codex", + status: "ready", + isolation: "local", + model: null, + cwd: "/project", + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: 0, + updatedMs: 0, + config: [], + capabilities: { rollback: true }, + commands: [], + usage: null, + queue: [], +}); + +/** A request, a run of calls and a reply: what a turn looks like in a real session. */ +const history = (turns: number): AgentEntry[] => + Array.from({ length: turns }, (_, i): AgentEntry[] => [ + { type: "user", text: `Request ${i}`, attachments: [], sentMs: null }, + ...Array.from({ length: 3 }, (_, k): AgentEntry => ({ + type: "tool", + id: `tool-${i}-${k}`, + title: `Read src/file${k}.ts`, + kind: "read", + status: "completed", + locations: [], + output: null, + diffs: [], + })), + { type: "agent", text: `Reply ${i}` }, + ]).flat(); + +const input = (id: string) => ({ kind: SESSION_KIND, key: sessionKey(id), data: { task: id } }); +const session = (shown: boolean, id = "A") => ( + + + +); +const stream = () => document.querySelector(`.${styles.stream}`)!; +/** Conversation rows in the DOM, whatever their kind. */ +const rows = () => stream().querySelectorAll(`.${styles.conversationRow}`).length; +const nodes = () => stream().getElementsByTagName("*").length; + +/** The scroll geometry jsdom lacks: a conversation as tall as its rows. */ +function layOut(el: HTMLElement, viewport = 400) { + Object.defineProperty(el, "clientHeight", { configurable: true, value: viewport }); + Object.defineProperty(el, "scrollHeight", { + configurable: true, + get: () => viewport + el.querySelectorAll(`.${styles.conversationRow}`).length * 20, + }); +} + +/** Lets the opening batch and every background batch after it paint. */ +async function settle(last: string) { + await screen.findByText("Request 0", {}, { timeout: 10_000 }); + await screen.findByText(last); +} + +beforeEach(() => { + useProject.setState({ settings: null }); + disconnect(); + useAgents.setState({ + loaded: true, + sessionLocation: "editor", + homeOpen: false, + tasks: new Map([task("A")].map((t) => [t.id, t])), + entries: new Map([["A", history(TURNS)]]), + external: [], + externalError: null, + }); +}); +afterEach(() => { + vi.useRealTimers(); +}); + +describe("a kept-alive session tab that stays hidden", () => { + it("keeps an unsent edit to an earlier message even after returning to the end", async () => { + const view = render(session(true)); + await settle("Reply 59"); + layOut(stream()); + const edit = screen.getAllByRole("button", { name: "Edit" })[0]!; + fireEvent.click(edit); + const draft = within(stream()).getByRole("textbox", { name: "Message" }); + fireEvent.change(draft, { target: { value: "Unsent revision" } }); + draft.blur(); + stream().scrollTop = stream().scrollHeight - stream().clientHeight; + fireEvent.scroll(stream()); + + vi.useFakeTimers(); + view.rerender(session(false)); + await act(async () => { + await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS); + }); + view.rerender(session(true)); + expect(within(stream()).getByRole("textbox", { name: "Message" })).toHaveValue("Unsent revision"); + }); + + it("keeps a text selection in the earlier rows while hidden", async () => { + const view = render(session(true)); + await settle("Reply 59"); + const selection = window.getSelection()!; + selection.selectAllChildren(screen.getByText("Request 0")); + + vi.useFakeTimers(); + view.rerender(session(false)); + await act(async () => { + await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS); + }); + view.rerender(session(true)); + expect(selection.toString()).toBe("Request 0"); + selection.removeAllRanges(); + }); + + it("gives back the history it painted behind the tail and is at the latest message when shown again", async () => { + const view = render(session(true)); + await settle("Reply 59"); + layOut(stream()); + const full = nodes(); + expect(rows()).toBeGreaterThan(150); + + vi.useFakeTimers(); + view.rerender(session(false)); + await act(async () => { + await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS); + }); + // The recent tail stays; the earlier turns leave the DOM. + expect(rows()).toBeLessThan(60); + expect(nodes()).toBeLessThan(full / 4); + expect(screen.getByText("Reply 59")).toBeInTheDocument(); + expect(screen.queryByText("Request 0")).toBeNull(); + + vi.useRealTimers(); + view.rerender(session(true)); + expect(screen.getByText("Reply 59")).toBeInTheDocument(); + expect(stream().scrollTop).toBe(stream().scrollHeight); + // Shown again, it paints the history behind the tail again, as when it opened. + await screen.findByText("Request 0", {}, { timeout: 10_000 }); + expect(stream().scrollTop).toBe(stream().scrollHeight); + expect(rows()).toBeGreaterThan(150); + }); + + it("keeps the whole window of a tab scrolled up, so its position survives", async () => { + const view = render(session(true)); + await settle("Reply 59"); + const el = stream(); + layOut(el); + fireEvent.wheel(el, { deltaY: -200 }); + el.scrollTop = 1000; + fireEvent.scroll(el); + const before = rows(); + + vi.useFakeTimers(); + view.rerender(session(false)); + await act(async () => { + await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS); + }); + expect(rows()).toBe(before); + expect(screen.getByText("Request 0")).toBeInTheDocument(); + + vi.useRealTimers(); + view.rerender(session(true)); + expect(stream().scrollTop).toBe(1000); + }); + + it("stays trimmed while a reply streams in, and shows the reply once shown", async () => { + const view = render(session(true)); + await settle("Reply 59"); + layOut(stream()); + vi.useFakeTimers(); + view.rerender(session(false)); + await act(async () => { + await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS); + }); + const trimmed = rows(); + expect(trimmed).toBeLessThan(60); + + act(() => + useAgents.setState({ + entries: new Map([["A", [...history(TURNS), { type: "agent", text: "A late reply" } as AgentEntry]]]), + }), + ); + await act(async () => { + await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS); + }); + expect(rows()).toBeLessThanOrEqual(trimmed + 1); + + vi.useRealTimers(); + view.rerender(session(true)); + expect(screen.getByText("A late reply")).toBeInTheDocument(); + expect(stream().scrollTop).toBe(stream().scrollHeight); + }); + + it("lets Find in Conversation search the whole history once shown again", async () => { + const view = render(session(true)); + await settle("Reply 59"); + layOut(stream()); + vi.useFakeTimers(); + view.rerender(session(false)); + await act(async () => { + await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS); + }); + expect(screen.queryByText("Request 0")).toBeNull(); + + vi.useRealTimers(); + // jsdom has no layout: every range counts as painted. + vi.spyOn(Range.prototype, "getClientRects").mockImplementation( + () => [new DOMRect(0, 0, 20, 12)] as unknown as DOMRectList, + ); + view.rerender(session(true)); + fireEvent.focusIn(stream()); + act(() => focusedSession()!.openFind()); + fireEvent.change(await screen.findByLabelText("Find in Conversation"), { target: { value: "Request 0" } }); + // The one request in the trimmed part of the history is found. + expect(await screen.findByText("1/1", {}, { timeout: 10_000 })).toBeInTheDocument(); + }); +}); diff --git a/src/features/agents/session/Stream.tsx b/src/features/agents/session/Stream.tsx index b975d3848..99aac0fb3 100644 --- a/src/features/agents/session/Stream.tsx +++ b/src/features/agents/session/Stream.tsx @@ -176,6 +176,8 @@ interface StreamProps { /** Entries rendered at a time when a conversation opens at its end. */ const ENTRY_BATCH = 40; +/** How long a conversation stays behind other tabs before it drops the entries painted above its tail. */ +const HIDDEN_TRIM_MS = 30_000; function scrollsY(el: Element): boolean { if (el.scrollHeight - el.clientHeight <= 1) return false; @@ -215,6 +217,8 @@ export function Stream({ drafts, }: StreamProps) { const ref = useRef(null); + // Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again. + const visible = useEditorShown(); useSelectionBoundary(ref); const [openFolds] = useState(() => new Map()); const key = entriesKey(task.id, subagent?.id ?? null); @@ -268,11 +272,11 @@ export function Stream({ const anchor = useRef<{ el: Element; top: number } | null>(null); const loadEarlier = useCallback(() => { const el = ref.current; - if (!el || start <= 0 || dragging.current || anchor.current) return; + if (!visible || !el || start <= 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]); + }, [start, visible]); const loadTimer = useRef(null); /** Load the next batch once the user stops scrolling near the top. */ const loadWhenStill = useCallback(() => { @@ -308,12 +312,29 @@ export function Stream({ 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. - if (start > 0 && position.current.stick && !dragging.current) + // 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]); - // Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again. - const visible = useEditorShown(); + }, [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 + // as DOM. One scrolled away keeps them, its offset needs the rows above. + if (visible) return; + const timer = window.setTimeout(() => { + const stream = ref.current; + if (!stream || !position.current.stick) return; + // A row can still hold an unsent edit or a selection after scrolling to the end. + if ( + stream.querySelector(`.${styles.editMessage}`) || + stream.contains(stream.ownerDocument.activeElement) || + selectionIn(stream) + ) + return; + setShown(ENTRY_BATCH); + }, HIDDEN_TRIM_MS); + return () => window.clearTimeout(timer); + }, [visible]); const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings(); useOffscreenRows(ref, visible, !finding, fitWindowWidth, fontZoom); /**