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", title: "Long conversation", status: "ready", isolation: "local", provider: "codex", model: null, cwd: "/dev/acme-api", branch: null, base: null, baseCommit: null, error: null, createdMs: 0, updatedMs: 0, config: [], commands: [], usage: null, queue: [], }; const entries: AgentEntry[] = Array.from({ length: 80 }, (_, turn): AgentEntry[] => [ { type: "user", text: `Request ${turn}`, attachments: [], steered: false }, ...["read", "execute", "edit"].map((kind): AgentEntry => ({ type: "tool", id: `${turn}-${kind}`, kind, title: `${kind} src/module-${turn}.ts`, status: "completed", locations: [], output: Array.from({ length: 80 }, (_, line) => `output ${turn}:${line}`).join("\n"), diffs: [], })), { type: "thought", text: `Checking module ${turn}.\n\n${"Details of the investigation. ".repeat(30)}` }, { type: "agent", text: `Reply ${turn}\n\n- Checked the module.\n- Updated the implementation.\n\n\`\`\`text\nmodule-${turn}\n src/\n tests/\n\`\`\``, }, ]).flat(); /** Opens the 80-turn chat; each turn's consecutive tool calls and reasoning fold into one row. */ async function openHistory(page: Page) { 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]]), entries: new Map([[task.id, entries]]), unread: new Set(), docked: null, }); store.openTaskInEditorLocation(task.id); }, { task, entries }, ); const stream = page.locator("[class*='_stream_']:visible"); // Each turn shows its request, its folded process run and its reply. await expect(stream.locator(":scope > *")).toHaveCount(80 * 3); await page.evaluate(() => document.fonts.ready); return stream; } // Selecting words in a long conversation must not move the reader away from the clicked text. test("keeps the conversation position on double-click", async ({ page }) => { const stream = await openHistory(page); await stream.evaluate((el) => { el.scrollTop = el.scrollHeight / 2; }); const target = stream.locator("[class*='_conversationRow_']").filter({ hasText: "Reply 40" }).last(); await target.scrollIntoViewIfNeeded(); const before = await stream.evaluate((el) => el.scrollTop); await target.getByText("Reply 40", { exact: true }).dblclick(); await expect.poll(() => stream.evaluate((el, top) => Math.abs(el.scrollTop - top), before)).toBeLessThanOrEqual(1); }); for (const placement of ["editor", "toolWindow"] as const) { test(`lets small upward wheel steps leave the end while replies stream in the ${placement}`, async ({ page }) => { // Streams into an 80-turn conversation for several seconds: close to 30 s on CI runners. test.slow(); const stream = await openHistory(page); await page.evaluate( async ({ id, placement }) => { const path = "/src/features/agents/store.ts"; const store = await import(path); const state = store.useAgents.getState(); store.useAgents.setState({ tasks: new Map(state.tasks).set(id, { ...state.tasks.get(id)!, status: "running" }), }); if (placement === "toolWindow") store.dockTask(id); }, { id: task.id, placement }, ); // The working indicator ends the conversation, after its rows; the turn ends with a reply. await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible(); await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1); await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2); const timer = await page.evaluate(async (id) => { const path = "/src/features/agents/store.ts"; const store = await import(path); const el = [...document.querySelectorAll("[class*='_stream_']")].find((el) => el.offsetHeight)!; el.addEventListener( "wheel", () => { el.dataset.streamWheelStart = String(el.scrollTop); }, { capture: true, once: true }, ); let chunks = 0; return window.setInterval(() => { const state = store.useAgents.getState(); const entries = state.entries.get(id)!.slice(); const last = entries.at(-1)!; if (last.type !== "agent") throw new Error("Expected a streaming reply"); entries[entries.length - 1] = { ...last, text: `${last.text}\n\nStreaming chunk ${++chunks}` }; store.useAgents.setState({ entries: new Map(state.entries).set(id, entries) }); el.dataset.streamChunks = String(chunks); }, 40); }, task.id); const chunks = async () => Number(await stream.getAttribute("data-stream-chunks")); try { await stream.hover(); for (let i = 0; i < 8; i++) { const previous = await chunks(); await page.mouse.wheel(0, -12); await expect.poll(chunks).toBeGreaterThan(previous); } const top = await stream.evaluate((el) => el.scrollTop); expect(Number(await stream.getAttribute("data-stream-wheel-start")) - top).toBeGreaterThan(80); const previous = await chunks(); await expect.poll(chunks).toBeGreaterThan(previous + 3); expect(Math.abs((await stream.evaluate((el) => el.scrollTop)) - top)).toBeLessThanOrEqual(1); const jump = page.getByRole("button", { name: "Jump to Latest" }); await expect(jump).toBeVisible(); await jump.click(); await expect .poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)) .toBeLessThan(2); const resumed = await chunks(); await expect.poll(chunks).toBeGreaterThan(resumed + 3); await expect .poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)) .toBeLessThan(2); } finally { await page.evaluate((timer) => window.clearInterval(timer), timer); } }); } for (const selected of [false, true]) { test(`keeps long-chat scroll geometry stable while jumping through history (selected: ${selected})`, async ({ page, context, }) => { await context.grantPermissions(["clipboard-read", "clipboard-write"]); const stream = await openHistory(page); const result = await stream.evaluate(async (el, selected) => { let text = ""; if (selected) { const range = document.createRange(); range.selectNodeContents(el); window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range); text = window.getSelection()!.toString(); } await new Promise(requestAnimationFrame); const initialHeight = el.scrollHeight; const samples: Array<{ height: number; drift: number }> = []; // A thumb can jump into previously unvisited rows in either direction. for (const fraction of [0, 0.75, 0.25, 1, 0.5, 0.1, 0.9, 0]) { el.scrollTop = fraction * (initialHeight - el.clientHeight); const target = el.scrollTop; await new Promise(requestAnimationFrame); await new Promise(requestAnimationFrame); samples.push({ height: el.scrollHeight, drift: Math.abs(el.scrollTop - target) }); } return { initialHeight, samples, text, after: window.getSelection()!.toString() }; }, selected); expect(result.initialHeight).toBeGreaterThan(10_000); for (const sample of result.samples) { expect(Math.abs(sample.height - result.initialHeight)).toBeLessThanOrEqual(1); expect(sample.drift).toBeLessThanOrEqual(1); } if (selected) { expect(result.text).toContain("Request 0"); expect(result.text).toContain("Reply 79"); expect(result.after).toBe(result.text); await stream.focus(); await page.keyboard.press("ControlOrMeta+c"); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(result.text); await page.evaluate(() => window.getSelection()!.removeAllRanges()); } }); } test("opens a folded process run with the keyboard and jumps back to the latest reply", async ({ page }) => { const stream = await openHistory(page); await stream.evaluate((el) => { el.scrollTop = 0; }); const jump = page.getByRole("button", { name: "Jump to Latest" }); await expect(jump).toBeVisible(); const fold = stream.locator("[class*='_processRun_']").first(); const summary = fold.locator(":scope > summary"); await summary.focus(); await page.keyboard.press("Enter"); await expect(fold).toHaveAttribute("open", ""); await expect(fold.getByText("read src/module-0.ts", { exact: true })).toBeVisible(); await expect(fold.getByText("execute src/module-0.ts", { exact: true })).toBeVisible(); await summary.focus(); await page.keyboard.press("Space"); await expect(fold).not.toHaveAttribute("open", ""); await jump.focus(); await page.keyboard.press("Enter"); 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(); }); 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(); });