diff --git a/e2e/agentScroll.spec.ts b/e2e/agentScroll.spec.ts index f994d352f4..e7de05d5d6 100644 --- a/e2e/agentScroll.spec.ts +++ b/e2e/agentScroll.spec.ts @@ -1,5 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; import type { AgentEntry, AgentTask } from "../src/bindings"; +import type * as AgentStore from "../src/features/agents/store"; +import type * as Ipc from "../src/platform/ipc"; const task: AgentTask = { id: "long-chat", @@ -254,3 +256,141 @@ test("paints earlier turns past folded process runs longer than ENTRY_BATCH", as await expect(stream.getByText("Split PR into three focused PRs")).toBeVisible(); await expect(stream.getByText("Interim status update")).toBeVisible(); }); + +test("keeps earlier messages visible and upward wheel scrolling working after a tall row collapses", async ({ + page, +}) => { + await page.setViewportSize({ width: 980, height: 640 }); + await page.goto("/"); + await page.getByRole("tree", { name: "Project" }).waitFor(); + await page.evaluate(async () => { + const storePath = "/src/features/agents/store.ts"; + const themePath = "/src/workbench/theme.ts"; + const ipcPath = "/src/platform/ipc.ts"; + const store: typeof AgentStore = await import(storePath); + const { previewTheme } = await import(themePath); + const { commands }: typeof Ipc = await import(ipcPath); + previewTheme("light"); + const taskId = "collapse-scroll"; + commands.agentRespond = async (_id: string, permId: number, _answer: string | null) => { + const current = store.useAgents.getState().entries.get(taskId) ?? []; + store.useAgents.setState({ + entries: new Map([ + [ + taskId, + [ + ...current.map((entry) => + entry.type === "permission" && entry.id === permId + ? { ...entry, chosen: "Layered architecture diagram" } + : entry, + ), + { type: "thought", text: "Planning the layered architecture diagram…", startedMs: Date.now() }, + ], + ], + ]), + }); + return { status: "ok", data: null }; + }; + const priorTurns: AgentEntry[] = Array.from({ length: 8 }, (_, turn): AgentEntry[] => [ + { type: "user", text: `Earlier request ${turn}`, attachments: [], steered: false }, + { type: "agent", text: `Earlier reply ${turn} with context from the repository.` }, + ]).flat(); + const history: AgentEntry[] = [ + ...priorTurns, + { + type: "user", + text: "Can you review the architecture design and convert Section 2.1 into a diagram?", + attachments: ["architecture_design.md"], + sentMs: Date.now() - 180_000, + steered: false, + }, + { + type: "agent", + text: "I reviewed `architecture_design.md` against the codebase. Before generating the diagram, please confirm the layout preferences below.", + }, + { + type: "permission", + id: 1, + title: "Choose diagram options", + command: null, + options: [ + { id: "submit", name: "Submit", kind: "allow_once" }, + { id: "cancel", name: "Cancel", kind: "reject_once" }, + ], + questions: [ + { + header: "Style", + question: "Which visual style should Section 2.1 use?", + multiSelect: false, + options: Array.from({ length: 8 }, (_, i) => ({ + label: i === 0 ? "Layered architecture diagram (Recommended)" : `Alternative layout style ${i + 1}`, + description: + "Horizontal pipeline tiers with a dedicated right-hand artifact rail so connectors never cross.", + preview: null, + })), + }, + ], + chosen: null, + }, + ]; + store.useAgents.setState({ + loaded: true, + error: null, + providers: [], + tasks: new Map([ + [ + taskId, + { + id: taskId, + title: "Can you review the architecture design", + status: "running", + isolation: "local", + provider: "copilot", + model: null, + cwd: "/dev/acme-api", + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: Date.now() - 180_000, + updatedMs: Date.now(), + config: [], + commands: [], + usage: null, + queue: [], + }, + ], + ]), + entries: new Map([[taskId, history]]), + unread: new Set(), + docked: null, + }); + store.openTaskInEditorLocation(taskId); + }); + + const stream = page.locator("[class*='_stream_']:visible"); + const card = page.getByRole("form", { name: "Choose diagram options" }); + await expect(card).toBeVisible(); + + // Scroll slightly away so the tall card's header sits above `.stream` while Submit stays in view, then submit. + await card.getByRole("radio", { name: /^Layered architecture diagram/ }).check(); + await stream.hover(); + await page.mouse.wheel(0, -10); + await stream.evaluate((el) => { + el.scrollTop = el.scrollHeight - el.clientHeight - 4; + el.dispatchEvent(new Event("scroll")); + }); + await card.getByRole("button", { name: "Submit", exact: true }).click(); + await expect(card).toHaveCount(0); + + // Immediately after collapsing, the preceding reply stays visible in the viewport with no blank slack lockup. + await expect(stream.getByText("I reviewed")).toBeInViewport(); + + // Scrolling upward with the wheel reaches the earliest turns without snapping scrollTop back. + await stream.hover(); + for (let i = 0; i < 12; i++) { + await page.mouse.wheel(0, -120); + await page.waitForTimeout(20); + } + await expect(stream.getByText("Earlier reply 0 with context from the repository.")).toBeInViewport(); +}); diff --git a/src/features/agents/session/Stream.tsx b/src/features/agents/session/Stream.tsx index 81e9aab404..75b627244f 100644 --- a/src/features/agents/session/Stream.tsx +++ b/src/features/agents/session/Stream.tsx @@ -217,8 +217,8 @@ 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 { +/** The first row the view shows and its box in the view; the rows are laid out in order. */ +function firstShownRow(el: HTMLElement): { row: Element; top: number; height: number } | null { const rows = el.querySelectorAll(`:scope > .${styles.conversationRow}`); if (!rows.length) return null; const view = el.getBoundingClientRect().top; @@ -230,7 +230,9 @@ function firstShownRow(el: HTMLElement): { row: Element; top: number } | null { else lo = mid + 1; } const row = rows[lo]!; - return { row, top: row.getBoundingClientRect().top - view }; + const box = row.getBoundingClientRect(); + if (box.bottom <= view) return null; + return { row, top: box.top - view, height: box.height }; } /** Images remain visible beside the work's folded summary, without duplicating them when it opens. */ @@ -290,6 +292,14 @@ function clampMultiClick(target: EventTarget) { if (row) clampSelectionToRow(document.getSelection(), row); } +/** Interactive controls inside a row handle clicks of their own, not a scrollbar or selection drag. */ +function isInteractiveTarget(target: EventTarget | null): boolean { + return ( + target instanceof Element && + target.closest("button, input, textarea, select, label, summary, a, [role='button'], [contenteditable]") !== null + ); +} + /** 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); @@ -403,7 +413,7 @@ export function Stream({ }, [loadEarlier]); useEffect(() => { const down = (event: PointerEvent) => { - if (!ref.current?.contains(event.target as Node)) return; + if (!ref.current?.contains(event.target as Node) || isInteractiveTarget(event.target)) return; dragging.current = true; if (loadTimer.current !== null) { window.clearTimeout(loadTimer.current); @@ -488,6 +498,7 @@ export function Stream({ const shownRow = useRef<{ row: Element; top: number; + height: number; scrollTop: number; } | null>(null); const holdShownRow = useCallback(() => { @@ -496,24 +507,35 @@ export function Stream({ 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; + // Content that got shorter below clamps the offset to the new end; check before `trimSlack` + // shrinks `scrollHeight` on an upward user scroll. + const preTrimMaxScroll = el.scrollHeight - el.clientHeight; + const clamped = + preTrimMaxScroll < held.scrollTop - 0.5 && + el.scrollTop < held.scrollTop && + el.scrollTop >= preTrimMaxScroll - 1; if (el.scrollTop === held.scrollTop || clamped) { - const moved = held.row.getBoundingClientRect().top - el.getBoundingClientRect().top - held.top; + const box = held.row.getBoundingClientRect(); + const padTop = parseFloat(getComputedStyle(el).paddingTop) || 0; + const collapsedPastTop = held.top < 0 && box.height < held.height - 0.5 && held.top + box.height <= padTop; + const desiredTop = collapsedPastTop ? padTop : held.top; + const moved = box.top - el.getBoundingClientRect().top - desiredTop; if (Math.abs(moved) >= 1) { - const target = Math.max(0, el.scrollTop + moved); + const maxContentScroll = Math.max(0, el.scrollHeight - slack.current - el.clientHeight); + const rawTarget = Math.max(0, el.scrollTop + moved); + const target = collapsedPastTop ? Math.min(rawTarget, maxContentScroll) : rawTarget; 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); } } } + // Rows that grew back below, or an upward scroll, take the room left for them. + trimSlack(); + updateJumpVisibility(el); const shown = firstShownRow(el); shownRow.current = shown && { ...shown, scrollTop: el.scrollTop }; }, [key, positions, setSlack, trimSlack, updateJumpVisibility]); @@ -526,7 +548,10 @@ export function Stream({ const onDiagramDrawn = useCallback(() => { const el = ref.current; if (!el) return; - if (position.current.stick && !dragging.current) scrollStreamTo(el, el.scrollHeight); + if (position.current.stick && !dragging.current && slack.current === 0) { + scrollStreamTo(el, el.scrollHeight); + position.current = { top: el.scrollTop, stick: true }; + } updateJumpVisibility(el); }, [updateJumpVisibility]); useLayoutEffect(() => { @@ -536,27 +561,43 @@ export function Stream({ // A message the user just sent: back to the end, where it shows, wherever they had scrolled. const sent = previousLength.current > 0 && entries.slice(previousLength.current).some((e) => e.type === "user"); previousLength.current = entries.length; - if (sent && !position.current.stick) { + if (sent) { scrollingUp.current = false; - position.current = { top: el.scrollTop, stick: true }; - positions.set(key, position.current); - setAway(false); + if (slack.current !== 0) setSlack(0); + if (!position.current.stick) { + position.current = { top: el.scrollTop, stick: true }; + positions.set(key, position.current); + setAway(false); + } return; } if ((truncated || entries.length === 0) && el.scrollHeight - el.scrollTop - el.clientHeight < 40) { scrollingUp.current = false; + if (slack.current !== 0) setSlack(0); position.current = { top: el.scrollTop, stick: true }; positions.set(key, position.current); setAway(false); } - }, [entries, visible, key, positions]); + }, [entries, visible, key, positions, setSlack]); useLayoutEffect(() => { const el = ref.current; if (!el || entries === null || !visible) return; - trimSlack(); if (position.current.stick) { - if (!dragging.current) scrollStreamTo(el, el.scrollHeight); - } else if (!restored.current) scrollStreamTo(el, position.current.top); + if (!dragging.current) { + const content = el.scrollHeight - slack.current; + if (slack.current === 0 || content - el.clientHeight > el.scrollTop) { + if (slack.current !== 0) setSlack(0); + scrollStreamTo(el, el.scrollHeight); + position.current = { top: el.scrollTop, stick: true }; + positions.set(key, position.current); + } else { + trimSlack(); + } + } + } else { + trimSlack(); + if (!restored.current) scrollStreamTo(el, position.current.top); + } restored.current = true; updateJumpVisibility(el); }); @@ -596,8 +637,10 @@ export function Stream({ if (!el) return; const observer = new ResizeObserver(() => { trimSlack(); - if (position.current.stick && !dragging.current) scrollStreamTo(el, el.scrollHeight); - else if (!position.current.stick && el.scrollHeight <= el.clientHeight && !dragging.current) loadWhenStill(); + if (position.current.stick && !dragging.current && slack.current === 0) { + scrollStreamTo(el, el.scrollHeight); + position.current = { top: el.scrollTop, stick: true }; + } else if (!position.current.stick && el.scrollHeight <= el.clientHeight && !dragging.current) loadWhenStill(); updateJumpVisibility(el); }); observer.observe(el); @@ -661,6 +704,7 @@ export function Stream({ position.current = { top: el.scrollTop, stick: false }; positions.set(key, position.current); } + seenHeight.current = { content: el.scrollHeight - slack.current, view: el.clientHeight }; updateJumpVisibility(el); takeShownRow(); }, @@ -671,13 +715,15 @@ export function Stream({ const el = ref.current; if (!el) return; scrollingUp.current = false; + if (slack.current !== 0) setSlack(0); + shownRow.current = null; position.current = { top: el.scrollTop, stick: true }; revealRowsAt(el, el.scrollHeight); if (typeof el.scrollTo === "function") el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); else el.scrollTop = el.scrollHeight; setAway(false); el.focus({ preventScroll: true }); - }, []); + }, [setSlack]); // Forks and undo apply to the task's own turns, not a subagent's conversation. const turns = useMemo(() => (entries && !subagent ? turnNumbers(entries) : null), [entries, subagent]); const replies = useMemo(() => (entries && !subagent ? replyTurns(entries) : null), [entries, subagent]); @@ -806,7 +852,8 @@ export function Stream({ ) scrollingUp.current = false; }} - onPointerDown={() => { + onPointerDown={(e) => { + if (isInteractiveTarget(e.target)) return; markUserScroll(); scrollingUp.current = false; }} @@ -819,21 +866,24 @@ export function Stream({ }} onScroll={(e) => { const el = e.currentTarget; - trimSlack(); - const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40; + const contentHeight = el.scrollHeight - slack.current; const laidOut = - el.scrollHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view; + contentHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view; seenHeight.current = { - content: el.scrollHeight, + content: contentHeight, 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; + if (!position.current.stick) holdShownRow(); + trimSlack(); + const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40; 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) scrollStreamTo(el, el.scrollHeight); + if (stick && !atEnd && !dragging.current && slack.current === 0) scrollStreamTo(el, el.scrollHeight); + if (stick) shownRow.current = null; position.current = { top: el.scrollTop, stick }; positions.set(key, position.current); updateJumpVisibility(el); @@ -841,7 +891,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(); + if (!position.current.stick && shownRow.current === null) takeShownRow(); }} // 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 index 0d8a067d33..82cfc3f448 100644 --- a/src/features/agents/session/holdShownRow.test.tsx +++ b/src/features/agents/session/holdShownRow.test.tsx @@ -1,4 +1,4 @@ -import { act, fireEvent, render, waitFor } from "@testing-library/react"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import type { AgentEntry, AgentTask } from "@/bindings"; @@ -14,6 +14,20 @@ vi.mock("@/platform/ipc", async (original) => ({ status: "ok", data: { uncommitted: [], commits: [] }, }), + agentRespond: async (_taskId: string, id: number, chosen: string | null) => { + const current = useAgents.getState().entries.get(task.id) ?? []; + useAgents.setState({ + entries: new Map([ + [ + task.id, + current.map((entry) => + entry.type === "permission" && entry.id === id ? { ...entry, chosen: chosen ?? "Cancelled" } : entry, + ), + ], + ]), + }); + return { status: "ok", data: null }; + }, vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }), }, })); @@ -51,26 +65,58 @@ const task: AgentTask = { 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); +/** Rows stack from the top of the stream: a row with a form or "tall" is 500px/300px, "compact" is 30px, any other 100px. */ +const height = (row: Element) => { + if (row.querySelector("form")) return 500; + if (row.textContent?.includes("huge")) return 600; + if (row.textContent?.includes("tall")) return 300; + if (row.textContent?.includes("compact") || row.classList.contains(styles.working!)) return 30; + return 100; +}; const rowsOf = (el: HTMLElement) => [...el.querySelectorAll(`:scope > .${styles.conversationRow}`)]; +const childrenOf = (el: HTMLElement) => + [...el.children].filter( + (child) => child.classList.contains(styles.conversationRow!) || child.classList.contains(styles.working!), + ); +const slackOf = (el: HTMLElement) => parseFloat(el.style.getPropertyValue("--stream-slack")) || 0; const original = Element.prototype.getBoundingClientRect; +function attachScrollGeometry(el: HTMLElement, viewport = 400) { + scroller = el; + let top = el.scrollTop; + const totalHeight = () => childrenOf(el).reduce((sum, child) => sum + height(child), 0) + slackOf(el); + Object.defineProperty(el, "clientHeight", { value: viewport, configurable: true }); + Object.defineProperty(el, "scrollHeight", { + get: totalHeight, + configurable: true, + }); + Object.defineProperty(el, "scrollTop", { + get: () => Math.max(0, Math.min(top, Math.max(0, totalHeight() - viewport))), + set: (next: number) => { + top = Math.max(0, Math.min(next, Math.max(0, totalHeight() - viewport))); + }, + configurable: true, + }); +} + 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")]]]), + entries: new Map([ + [task.id, [agent("tall one"), agent("two"), agent("three"), agent("four"), agent("five"), agent("six")]], + ]), composers: new Map(), + scrollPositions: 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); + for (const child of childrenOf(scroller)) { + if (child === this) return new DOMRect(0, top, 600, height(child)); + top += height(child); } } return original.call(this); @@ -91,12 +137,7 @@ it("keeps the row at the top of the view in place when a row above it gets short 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, - }); + attachScrollGeometry(el); // 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; @@ -105,10 +146,172 @@ it("keeps the row at the top of the view in place when a row above it gets short // 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")]]]), + entries: new Map([ + [task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("five"), agent("six")]], + ]), }); }); expect(el.scrollTop).toBe(150); const two = rowsOf(el).find((row) => row.textContent?.includes("two"))!; expect(two.getBoundingClientRect().top).toBe(-50); }); + +it("lets upward scrolling consume --stream-slack without snapping scrollTop back", async () => { + useAgents.setState({ + entries: new Map([[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("huge five")]]]), + }); + const { container } = render( + , + ); + const el = await waitFor(() => { + const found = container.querySelector(`.${styles.conversationRow}`)?.parentElement; + expect(found).toBeTruthy(); + return found!; + }); + attachScrollGeometry(el); + // Content is 400 + 600 = 1000px; scroll to 550 (away from the end). + el.scrollTop = 600; + fireEvent.scroll(el); + fireEvent.wheel(el, { deltaY: -50 }); + el.scrollTop = 550; + fireEvent.scroll(el); + + // Even a 1px upward trackpad step from the end is not swallowed as browser clamping. + el.scrollTop = 600; + fireEvent.wheel(el, { deltaY: 50 }); + fireEvent.scroll(el); + fireEvent.wheel(el, { deltaY: -1 }); + el.scrollTop = 599; + fireEvent.scroll(el); + expect(el.scrollTop).toBe(599); + + // Scroll to 450 ("huge five" at -50px), then "huge five" shrinks from 600px to 100px below. + el.scrollTop = 450; + fireEvent.scroll(el); + act(() => { + useAgents.setState({ + entries: new Map([[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("five")]]]), + }); + }); + expect(el.scrollTop).toBe(450); + expect(slackOf(el)).toBe(350); + + // Scrolling back up consumes slack step by step instead of getting stuck at 450. + fireEvent.wheel(el, { deltaY: -60 }); + el.scrollTop = 390; + fireEvent.scroll(el); + expect(el.scrollTop).toBe(390); + expect(slackOf(el)).toBe(290); + + fireEvent.wheel(el, { deltaY: -300 }); + el.scrollTop = 90; + fireEvent.scroll(el); + expect(el.scrollTop).toBe(90); + expect(slackOf(el)).toBe(0); +}); + +it("keeps a collapsing tall row in view instead of pushing all rows above WorkingRow", async () => { + useAgents.setState({ + tasks: new Map([[task.id, { ...task, status: "running" }]]), + entries: new Map([[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("huge thought")]]]), + }); + const { container } = render( + , + ); + const el = await waitFor(() => { + const found = container.querySelector(`.${styles.conversationRow}`)?.parentElement; + expect(found).toBeTruthy(); + return found!; + }); + attachScrollGeometry(el); + // Content is 400 + 600 + 30 (WorkingRow) = 1030px. Scroll to 550 so "huge thought" starts at -150px. + el.scrollTop = 630; + fireEvent.scroll(el); + fireEvent.wheel(el, { deltaY: -80 }); + el.scrollTop = 550; + fireEvent.scroll(el); + + // "huge thought" (600px, top = -150px) collapses into "compact thought" (30px). + act(() => { + useAgents.setState({ + entries: new Map([ + [task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("compact thought")]], + ]), + }); + }); + const collapsed = rowsOf(el).at(-1)!; + expect(collapsed.getBoundingClientRect().bottom).toBeGreaterThan(0); + expect(collapsed.getBoundingClientRect().top).toBeGreaterThanOrEqual(0); +}); + +it("keeps following the end with zero slack after submitting an inline QuestionForm", async () => { + const entries: AgentEntry[] = [ + agent("one"), + agent("two"), + agent("three"), + agent("four"), + { + type: "permission", + id: 1, + title: "Which visual style?", + command: null, + options: [ + { id: "submit", name: "Submit", kind: "allow_once" }, + { id: "cancel", name: "Cancel", kind: "reject_once" }, + ], + questions: [ + { + header: "Question", + question: "Which visual style?", + multiSelect: false, + options: [ + { label: "Layered SVG (Recommended)", description: "Crisp vector layout", preview: null }, + { label: "Hand-drawn", description: "Sketchy strokes", preview: null }, + ], + }, + ], + chosen: null, + }, + ]; + useAgents.setState({ + tasks: new Map([[task.id, { ...task, status: "running" }]]), + entries: new Map([[task.id, entries]]), + }); + const { container } = render( + , + ); + const el = await waitFor(() => { + const found = container.querySelector(`.${styles.conversationRow}`)?.parentElement; + expect(found).toBeTruthy(); + return found!; + }); + attachScrollGeometry(el); + // At the bottom of the 400 + 500 + 30 = 930px stream (scrollTop = 530). + el.scrollTop = 530; + fireEvent.scroll(el); + + const form = await screen.findByRole("form", { name: "Which visual style?" }); + const radio = within(form).getByRole("radio", { name: /^Layered SVG/ }); + fireEvent.pointerDown(radio); + fireEvent.click(radio); + fireEvent.pointerUp(window); + + const submit = within(form).getByRole("button", { name: "Submit" }); + fireEvent.pointerDown(submit); + await act(async () => { + fireEvent.click(submit); + }); + fireEvent.pointerUp(window); + // Browser dispatches the clamped scroll event after the 500px form shrinks to a compact record. + fireEvent.scroll(el); + + expect(slackOf(el)).toBe(0); + // Next streamed reply still follows the end automatically. + act(() => { + const current = useAgents.getState().entries.get(task.id)!; + useAgents.setState({ + entries: new Map([[task.id, [...current, agent("huge follow-up reply")]]]), + }); + }); + expect(el.scrollTop).toBe(el.scrollHeight - el.clientHeight); +});