Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
perf(issues): bound long-history work and keep images complete (MUL-8830) (#10173)
shaojieMikef4dc21c2babe
diff --git a/e2e/fixtures.ts b/e2e/fixtures.tsindex bfb7c4a191..c558b74297 100644--- a/e2e/fixtures.ts+++ b/e2e/fixtures.ts@@ -350,10 +350,10 @@ export class TestApiClient {await this.authedFetch(`/api/issues/${id}`, { method: "DELETE" });}- async createComment(issueId: string, content: string) {+ async createComment(issueId: string, content: string, parentId?: string) {const res = await this.authedFetch(`/api/issues/${issueId}/comments`, {method: "POST",- body: JSON.stringify({ content }),+ body: JSON.stringify({ content, ...(parentId ? { parent_id: parentId } : {}) }),});if (!res.ok) {throw new Error(`create comment failed: ${res.status} ${await res.text()}`);@@ -361,6 +361,21 @@ export class TestApiClient {return (await res.json()) as { id: string };}+ async seedCommentNotification(issueId: string, commentId: string, title: string) {+ if (!this.workspaceId || !this.email) throw new Error("Select a workspace before seeding a notification");+ const client = new pg.Client(DATABASE_URL);+ await client.connect();+ try {+ await client.query(+ `INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, actor_type, actor_id, type, issue_id, title, details)+ SELECT $1, 'member', id, 'member', id, 'new_comment', $2, $3, $4::jsonb FROM "user" WHERE email = $5`,+ [this.workspaceId, issueId, title, JSON.stringify({ comment_id: commentId }), this.email],+ );+ } finally {+ await client.end();+ }+ }+/** Seed an owned runtime without launching an actual agent tool. */async seedRuntime(name: string): Promise<string> {if (!this.workspaceId || !this.email) throw new Error("Select a workspace before seeding a runtime");diff --git a/e2e/issue-task-history.spec.ts b/e2e/issue-task-history.spec.tsnew file mode 100644index 0000000000..145f9f1469--- /dev/null+++ b/e2e/issue-task-history.spec.ts@@ -0,0 +1,92 @@+import { test, expect } from "@playwright/test";+import pg from "pg";+import { createTestApi } from "./helpers";++test("issue loads compact runs until Runs requests full own or subtree history", async ({ page }) => {+ const api = await createTestApi();+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ let runtimeId = "";+ let agentId = "";+ try {+ const workspace = (await api.getWorkspaces())[0]!;+ const userId = (await db.query('SELECT id FROM "user" WHERE email=$1', [api.getEmail()])).rows[0].id;+ const issue = await api.createIssue("On-demand run history");+ const child = await api.createIssue("Child run history", { parent_issue_id: issue.id });++ // Seed finished runs without dispatching any work to a real runtime.+ runtimeId = (await db.query(`+ INSERT INTO agent_runtime (workspace_id,name,runtime_mode,provider,status,device_info,metadata,owner_id)+ VALUES ($1,'History test runtime','cloud','test','offline','Test','{}',$2) RETURNING id+ `, [workspace.id, userId])).rows[0].id;+ agentId = (await db.query(`+ INSERT INTO agent (workspace_id,name,description,instructions,runtime_mode,runtime_config,runtime_id,visibility,permission_mode,max_concurrent_tasks,owner_id)+ VALUES ($1,'History test agent','','','cloud','{}',$2,'private','private',1,$3) RETURNING id+ `, [workspace.id, runtimeId, userId])).rows[0].id;+ for (const issueId of [issue.id, child.id]) {+ await db.query(`+ INSERT INTO agent_task_queue (agent_id,runtime_id,issue_id,status,result,handoff_note,started_at,completed_at)+ VALUES ($1,$2,$3,'completed',$4,'Full handoff details',now()-interval '1 minute',now())+ `, [agentId, runtimeId, issueId, JSON.stringify({+ comment: "Inline run summary",+ output: `Full provider output for ${issueId}`,+ session_id: "history-test-session",+ })]);+ }++ await page.setViewportSize({ width: 1440, height: 900 });+ await page.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, api.getToken());+ const isIssueTasks = (url: URL) => url.pathname.endsWith(`/issues/${issue.id}/task-runs`);+ const requests: URL[] = [];+ page.on("request", (request) => {+ const url = new URL(request.url());+ if (isIssueTasks(url)) requests.push(url);+ });+ const compactResponse = page.waitForResponse((response) => {+ const url = new URL(response.url());+ return isIssueTasks(url) && url.searchParams.get("view") === "timeline";+ });+ await page.goto(`/${workspace.slug}/issues/${issue.id}`);+ const compact = await (await compactResponse).json();+ expect(compact).toHaveLength(1);+ expect(compact[0].result).toEqual({ comment: "Inline run summary" });+ expect(compact[0].handoff_note).toBeFalsy();+ const openRuns = page.getByRole("button", { name: /^Open timeline/ });+ await expect(openRuns).toBeVisible();+ expect(requests.length).toBeGreaterThan(0);+ expect(requests.every((url) => url.searchParams.get("view") === "timeline")).toBe(true);++ const ownHistory = page.waitForResponse((response) => {+ const url = new URL(response.url());+ return isIssueTasks(url) && !url.searchParams.has("view") && !url.searchParams.has("scope");+ });+ await openRuns.click();+ const own = await (await ownHistory).json();+ expect(own).toHaveLength(1);+ expect(own[0].result.output).toBe(`Full provider output for ${issue.id}`);+ expect(own[0].handoff_note).toBe("Full handoff details");++ const subtreeHistory = page.waitForResponse((response) => {+ const url = new URL(response.url());+ return isIssueTasks(url) && !url.searchParams.has("view") && url.searchParams.get("scope") === "subtree";+ });+ const includeChildren = page.getByRole("dialog").getByRole("checkbox", { name: "Include sub-issues" });+ await includeChildren.check();+ const subtree = await (await subtreeHistory).json();+ expect(subtree).toHaveLength(2);+ expect(subtree.map((task: { result: { output: string } }) => task.result.output).sort()).toEqual(+ [issue.id, child.id].map((id) => `Full provider output for ${id}`).sort(),+ );+ expect(subtree.every((task: { handoff_note: string }) => task.handoff_note === "Full handoff details")).toBe(true);+ await expect(includeChildren).toBeChecked();+ } finally {+ await api.cleanup();+ if (agentId) await db.query("DELETE FROM agent_task_queue WHERE agent_id=$1", [agentId]);+ if (agentId) await db.query("DELETE FROM agent WHERE id=$1", [agentId]);+ if (runtimeId) await db.query("DELETE FROM agent_runtime WHERE id=$1", [runtimeId]);+ await db.end();+ }+});diff --git a/e2e/issue-timeline-scroll.spec.ts b/e2e/issue-timeline-scroll.spec.tsnew file mode 100644index 0000000000..712f37445d--- /dev/null+++ b/e2e/issue-timeline-scroll.spec.ts@@ -0,0 +1,184 @@+import { test, expect, type Page } from "@playwright/test";+import { createTestApi, loginAsDefault } from "./helpers";++async function readingPosition(page: Page, commentId?: string) {+ return page.evaluate((id) => {+ const container = document.querySelector<HTMLElement>('[data-tab-scroll-root^="main:"]')!;+ const c = container.getBoundingClientRect();+ const comment = id+ ? container.querySelector<HTMLElement>(`#comment-${id}`)+ : document.elementFromPoint(c.left + c.width / 2, c.top + c.height / 2)?.closest<HTMLElement>('[id^="comment-"]');+ if (!comment || !container.contains(comment)) return null;+ const e = comment.getBoundingClientRect();+ return {+ id: comment.id.slice("comment-".length),+ offset: e.top - c.top,+ visible: e.bottom > c.top && e.top < c.bottom,+ mounted: comment.dataset.virtualThreadMounted !== "false",+ };+ }, commentId);+}++test("Inbox restores the current reply after leaving a virtualized long thread", async ({ page }, testInfo) => {+ test.setTimeout(120_000);+ await page.setViewportSize({ width: 1440, height: 900 });+ const api = await createTestApi();+ try {+ const slug = await loginAsDefault(page);+ const title = "Inbox long-thread scroll restoration";+ const issue = await api.createIssue(title, {+ description: Array.from({ length: 45 }, (_, i) => `Description paragraph ${i}. A long description precedes the timeline.`).join("\n\n"),+ });+ for (let i = 0; i < 24; i++) {+ await api.createComment(issue.id, `Outer comment ${i}\n\n${"Before the long thread. ".repeat(5 + i % 8)}`);+ }+ const root = await api.createComment(issue.id, "Long discussion root");+ let targetId = "";+ for (let i = 0; i < 80; i++) {+ const reply = await api.createComment(issue.id, i === 61+ ? "Notification reply 61\n\nThe notification should land here."+ : `Reply ${i}\n\n${Array.from({ length: 2 + i % 11 }, (_, j) => `Paragraph ${j}. ${"Variable-height Markdown content. ".repeat(3)}`).join("\n\n")}`, root.id);+ if (i === 61) targetId = reply.id;+ }+ for (let i = 0; i < 4; i++) await api.createComment(issue.id, `After thread ${i}`);+ await api.seedCommentNotification(issue.id, targetId, title);+ await page.goto(`/${slug}/inbox`);+ const notification = page.getByText(title, { exact: true }).first();+ await notification.click();+ const target = page.locator(`#comment-${targetId}`);+ await expect(target).toBeVisible();+ await expect.poll(() => readingPosition(page, targetId).then((p) => p?.mounted)).toBe(true);+ await expect.poll(() => readingPosition(page, targetId).then((p) => p?.visible)).toBe(true);+ const before = (await readingPosition(page, targetId))!;++ const leaveAndReturn = async () => {+ await page.locator(`a[href="/${slug}/issues"]`).first().click();+ await expect(page).toHaveURL(new RegExp(`/${slug}/issues`));+ await page.goBack();+ };+ const expectRestored = async (position: { id: string; offset: number }) => {+ let stable = 0;+ await expect.poll(async () => {+ const current = await readingPosition(page, position.id);+ stable = current?.mounted && current.visible && Math.abs(current.offset - position.offset) < 4 ? stable + 1 : 0;+ return stable;+ }, { timeout: 10_000, intervals: [100] }).toBeGreaterThanOrEqual(3);+ };++ await page.screenshot({ path: testInfo.outputPath("before-leaving.png"), animations: "disabled" });+ await leaveAndReturn();+ await expectRestored(before);+ await page.screenshot({ path: testInfo.outputPath("restored-notification.png"), animations: "disabled" });++ // Reading farther up must restore that reply, rather than replay the notification.+ const container = page.locator(`[data-tab-scroll-root="main:${issue.id}"]`);+ await container.hover();+ await page.mouse.wheel(0, -1800);+ await expect.poll(async () => (await readingPosition(page))?.id).not.toBe(targetId);+ const reading = (await readingPosition(page))!;+ expect(reading).not.toBeNull();+ await leaveAndReturn();+ await expectRestored(reading);+ await page.locator(`a[href="/${slug}/issues"]`).first().click();+ await expect(page).toHaveURL(new RegExp(`/${slug}/issues`));+ await page.setViewportSize({ width: 1200, height: 900 });+ await page.goBack();+ await expectRestored(reading);+ expect(await page.locator('[data-virtual-thread-mounted="true"]').count()).toBeLessThan(20);+ await page.screenshot({ path: testInfo.outputPath("restored-reading-position.png"), animations: "disabled" });++ // An explicit click still replays the original notification after a restore.+ await notification.click();+ await expect.poll(() => readingPosition(page, targetId).then((p) => p?.visible)).toBe(true);+ } finally {+ await api.cleanup();+ }+});++// Scroll the timeline up in fixed steps and record how far a visible reply+// moved beyond the step itself. Anything but ~0 is content jumping under the+// reader: an offscreen reply above the viewport swapped its placeholder+// height for its real one without the scroll position following it.+async function scrollUpShifts(page: Page, steps: number, delta = 150) {+ const shifts: number[] = [];+ for (let i = 0; i < steps; i++) {+ const shift = await page.evaluate(async (d) => {+ const container = document.querySelector<HTMLElement>('[data-tab-scroll-root^="main:"]')!;+ const c = container.getBoundingClientRect();+ // The first comment whose top edge is on screen. Its own resize cannot+ // move its top, so only layout changes above it show up as a shift.+ const ref = [...container.querySelectorAll<HTMLElement>('[id^="comment-"]')]+ .find((el) => { const r = el.getBoundingClientRect(); return r.top > c.top + 80 && r.top < c.bottom - 80; });+ if (!ref) return null;+ const before = ref.getBoundingClientRect().top;+ const scrollBefore = container.scrollTop;+ container.scrollTop = scrollBefore - d;+ const applied = scrollBefore - container.scrollTop;+ for (let f = 0; f < 10; f++) await new Promise((r) => requestAnimationFrame(r));+ await new Promise((r) => setTimeout(r, 60));+ return ref.isConnected ? ref.getBoundingClientRect().top - before - applied : null;+ }, delta);+ if (shift !== null) shifts.push(Math.round(shift));+ }+ return shifts;+}++test("scrolling up a virtualized long thread keeps the reading position steady", async ({ page }) => {+ test.setTimeout(180_000);+ await page.setViewportSize({ width: 1440, height: 900 });+ const api = await createTestApi();+ try {+ const slug = await loginAsDefault(page);+ const title = "Long-thread upward scroll stability";+ // Two shapes that trip Virtuoso's own compensation differently: one-line+ // replies ending the timeline, and mixed heights followed by more comments.+ // Both are mostly far shorter than an unmeasured row's estimate.+ const seedThread = async (issueTitle: string, mixed: boolean) => {+ const issue = await api.createIssue(issueTitle, { description: "Short description." });+ for (let i = 0; i < 5; i++) await api.createComment(issue.id, `Outer comment ${i}`);+ const root = await api.createComment(issue.id, "Long discussion root");+ let targetId = "";+ for (let i = 0; i < 120; i++) {+ const body = mixed && i % 17 === 0+ ? Array.from({ length: 12 }, (_, j) => `Paragraph ${j}. ${"Long reply content. ".repeat(6)}`).join("\n\n")+ : `Reply ${i}. Short answer.`;+ const reply = await api.createComment(issue.id, i === 100 ? "Notification reply 100" : body, root.id);+ if (i === 100) targetId = reply.id;+ }+ if (mixed) for (let i = 0; i < 4; i++) await api.createComment(issue.id, `After thread ${i}`);+ return { issue, targetId };+ };+ const short = await seedThread(title, false);+ const mixed = await seedThread("Long-thread mixed heights", true);+ const targetId = short.targetId;+ await api.seedCommentNotification(short.issue.id, targetId, title);++ // 1. Land on a reply deep in the thread from Inbox, then read upward.+ await page.goto(`/${slug}/inbox`);+ await page.getByText(title, { exact: true }).first().click();+ await expect(page.locator(`#comment-${targetId}`)).toBeVisible();+ await expect.poll(() => readingPosition(page, targetId).then((p) => p?.mounted && p.visible)).toBe(true);+ await page.waitForTimeout(1000);+ const fromInbox = await scrollUpShifts(page, 40);+ expect(fromInbox.length).toBeGreaterThan(30);+ expect.soft(fromInbox.filter((s) => Math.abs(s) > 2), `Inbox landing shifts: ${fromInbox}`).toEqual([]);++ // 2. Open the issue normally, go to the end of the discussion, read upward.+ await page.goto(`/${slug}/issues/${mixed.issue.id}`);+ await expect(page.getByText("Long discussion root")).toBeVisible();+ const toEnd = () => page.evaluate(() => {+ const c = document.querySelector<HTMLElement>('[data-tab-scroll-root^="main:"]')!;+ c.scrollTop = c.scrollHeight;+ });+ await toEnd();+ await page.waitForTimeout(800);+ await toEnd();+ await page.waitForTimeout(800);+ const fromEnd = await scrollUpShifts(page, 40);+ expect(fromEnd.length).toBeGreaterThan(30);+ expect.soft(fromEnd.filter((s) => Math.abs(s) > 2), `End-of-thread shifts: ${fromEnd}`).toEqual([]);+ expect(await page.locator('[data-virtual-thread-mounted="true"]').count()).toBeLessThan(60);+ } finally {+ await api.cleanup();+ }+});diff --git a/e2e/perf/README.md b/e2e/perf/README.mdindex ce2aceda87..76e0cc442f 100644--- a/e2e/perf/README.md+++ b/e2e/perf/README.md@@ -124,7 +124,45 @@ survives an interrupted exit. It also checks that the message list's ancestoris never scaled, and that a reopened window never paints before its messagelist does. HTTP and WebSocket traffic is synthetic; no backend is needed.-## When to run it+## Issue history with a real local API++`issue-history.spec.ts` measures direct issue entry and Inbox selection on the+production UI against an isolated, migrated local API/database. It seeds and+cleans up its own issues through `TestApiClient`; completed execution rows are+inserted locally without dispatching agents. It never mocks HTTP or WebSocket+responses. Run it explicitly with `PERF_SCENARIO=issue-history`.++Start the API with `make up C=api ARGS="--ephemeral"`. Build each compared ref+with `NEXT_PUBLIC_API_URL='' NEXT_PUBLIC_WS_URL='' pnpm --filter @multica/web build`,+then run its production server with `REMOTE_API_URL` pointing at that API.+Run the **same spec from the head checkout** against each server:++```bash+PERF_SCENARIO=issue-history PERF_REPEATS=5 \+ PLAYWRIGHT_BASE_URL=http://localhost:<production-web-port> \+ PERF_REPORT_PATH=<absolute-report-path> \+ make env-exec ARGS="-- pnpm exec playwright test --config=playwright.perf.config.ts issue-history.spec.ts"+```++Each scenario gets one warmup and five fresh-browser-context samples. The+default datasets have 120 or 716 Markdown replies and 20 completed runs with+64 KiB outputs. An optional `PERF_ISSUE_SOURCE` JSON array of `{content}` adds+a local discussion-text workload; keep private content outside Git and do not+publish its screenshots. Reports contain only counts, byte sizes and a content+digest. Compare digests before comparing samples.++Reports include entry-to-visible-target time, main-thread task duration, long+tasks, live heap after explicit GC, mounted comment bodies, DOM nodes and actual+task-response body bytes (decompressed). CPU is unthrottled. Direct entry+includes application boot; Inbox entry starts with the shell already loaded.+Long tasks are snapshotted before the instrumentation's forced GC. Set+`PERF_DATASET` to dataset names separated by commas or `PERF_ENTRY=direct|inbox` to+repeat a focused case in alternating product order.+These are observed local measurements, not latency thresholds. Stop other+run-owned builds/tests before measuring; the report also records system load.+Destroy the API environment after the comparison with `make destroy ARGS="--yes"`.++## When to run the typing scenariosNothing runs this automatically. The routine guard is the component test from#8260, which pins the exact failure mode behind MUL-7227 — a streamed messagediff --git a/e2e/perf/issue-history.spec.ts b/e2e/perf/issue-history.spec.tsnew file mode 100644index 0000000000..75b032b424--- /dev/null+++ b/e2e/perf/issue-history.spec.ts@@ -0,0 +1,159 @@+/** Real API/database and production UI; opt in with PERF_SCENARIO=issue-history. */+import { test, expect } from "@playwright/test";+import { createHash } from "node:crypto";+import { readFileSync, writeFileSync } from "node:fs";+import { loadavg } from "node:os";+import pg from "pg";+import { createTestApi } from "../helpers";++test("measure issue history entry against the local API", async ({ browser }) => {+ test.skip(process.env.PERF_SCENARIO !== "issue-history", "Requires an isolated local API and production build");+ test.setTimeout(600_000);+ expect(process.env.MULTICA_DEV_PROFILE).toMatch(/^dev-/);+ expect(process.env.DATABASE_URL).toBeTruthy();+ const api = await createTestApi();+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ const samples: Record<string, unknown>[] = [];+ const repeats = Number(process.env.PERF_REPEATS ?? 5);+ const datasets = [120, 716].map((count) => ({+ name: `generated-${count}-replies`,+ bodies: ["Performance discussion", ...Array.from({ length: count }, (_, i) =>+ `Reply ${i}\n\n${"A measured discussion about implementation, validation and tradeoffs. ".repeat(3 + i % 8)}\n\n` ++ (i % 5 === 0 ? "```ts\nconst result = await query({ issueId, view: 'timeline' });\nreturn result.map(task => task.status);\n```" : "- Verify the result\n- Preserve the reading position"))],+ runs: false,+ }));+ if (process.env.PERF_ISSUE_SOURCE) {+ const comments = JSON.parse(readFileSync(process.env.PERF_ISSUE_SOURCE, "utf8")) as { content?: string }[];+ datasets.unshift({ name: "local-discussion-text", bodies: comments.map((c) => c.content ?? "").filter(Boolean), runs: false });+ }+ datasets.push({ name: "20-runs-64KiB-output", bodies: ["Execution history benchmark"], runs: true });+ let runtimeId = "";+ let agentId = "";+ try {+ const workspace = (await api.getWorkspaces())[0]!;+ const userId = (await db.query('SELECT id FROM "user" WHERE email=$1', [api.getEmail()])).rows[0].id;+ for (const dataset of datasets.filter((item) => !process.env.PERF_DATASET || process.env.PERF_DATASET.split(",").includes(item.name))) {+ const title = `History benchmark ${dataset.name}`;+ const issue = await api.createIssue(title, { description: "Local performance comparison." });+ let rootId = "";+ let targetId = "";+ for (const [i, body] of dataset.bodies.entries()) {+ const comment = (await db.query(`+ INSERT INTO comment (workspace_id,issue_id,author_type,author_id,content,parent_id,created_at)+ VALUES ($1,$2,'member',$3,$4,$5,now()-interval '1 day'+$6::int*interval '1 second') RETURNING id+ `, [workspace.id, issue.id, userId, body, rootId || null, i])).rows[0].id;+ if (!rootId) rootId = comment;+ if (i === Math.floor((dataset.bodies.length - 1) * 0.8)) targetId = comment;+ }+ await api.seedCommentNotification(issue.id, targetId, title);+ if (dataset.runs) {+ runtimeId = (await db.query(`INSERT INTO agent_runtime+ (workspace_id,name,runtime_mode,provider,status,device_info,metadata,owner_id)+ VALUES ($1,'Benchmark runtime','cloud','test','offline','Test','{}',$2) RETURNING id`, [workspace.id, userId])).rows[0].id;+ agentId = (await db.query(`INSERT INTO agent+ (workspace_id,name,description,instructions,runtime_mode,runtime_config,runtime_id,visibility,permission_mode,max_concurrent_tasks,owner_id)+ VALUES ($1,'Benchmark agent','','','cloud','{}',$2,'private','private',1,$3) RETURNING id`, [workspace.id, runtimeId, userId])).rows[0].id;+ for (let i = 0; i < 20; i++) await db.query(`INSERT INTO agent_task_queue+ (agent_id,runtime_id,issue_id,status,result,handoff_note,started_at,completed_at)+ VALUES ($1,$2,$3,'completed',$4,$5,now()-interval '2 minutes',now()-interval '1 minute')`,+ [agentId, runtimeId, issue.id, JSON.stringify({ comment: "Inline summary", output: "provider output ".repeat(4096) }), "Handoff context. ".repeat(100)]);+ }++ for (const entry of ["direct", "inbox"] as const) {+ if (process.env.PERF_ENTRY && entry !== process.env.PERF_ENTRY) continue;+ // One warmup primes server/OS caches; each measured sample gets a fresh browser context.+ for (let round = -1; round < repeats; round++) {+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });+ try {+ await context.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ const state = { longTasks: [] as number[] };+ (window as unknown as { __historyPerf: typeof state }).__historyPerf = state;+ new PerformanceObserver((entries) => {+ for (const item of entries.getEntries()) state.longTasks.push(item.duration);+ }).observe({ type: "longtask", buffered: false });+ }, api.getToken());+ const page = await context.newPage();+ const errors: string[] = [];+ page.on("pageerror", (error) => errors.push(error.message));+ const responses: Promise<{ path: string; bytes: number }>[] = [];+ page.on("response", (response) => {+ const path = new URL(response.url()).pathname;+ if (path.includes(`/issues/${issue.id}/`) && /\/(timeline|task-runs|deliverables)$/.test(path)) {+ responses.push(response.body().then((body) => ({ path, bytes: body.length })));+ }+ });+ const session = await context.newCDPSession(page);+ await session.send("Performance.enable");+ if (entry === "inbox") {+ await page.goto(`/${workspace.slug}/inbox`);+ await expect(page.getByText(title, { exact: true }).first()).toBeVisible();+ await page.evaluate(() => { (window as unknown as { __historyPerf: { longTasks: number[] } }).__historyPerf.longTasks.length = 0; });+ }+ const before = await session.send("Performance.getMetrics");+ const start = performance.now();+ if (entry === "direct") await page.goto(`/${workspace.slug}/issues/${issue.id}`);+ else await page.getByText(title, { exact: true }).first().click();+ await page.waitForFunction(({ targetId, rootId, entry }) => {+ const container = document.querySelector<HTMLElement>('[data-tab-scroll-root^="main:"]');+ const target = entry === "inbox"+ ? document.getElementById(`comment-${targetId}`)+ : container?.querySelector(`[data-comment-content="${rootId}"]`);+ if (!container || !target || target.getAttribute("data-virtual-thread-mounted") === "false") return false;+ const c = container.getBoundingClientRect();+ const r = target.getBoundingClientRect();+ return r.bottom > c.top && r.top < c.bottom;+ }, { targetId, rootId, entry }, { timeout: 45_000 });+ await page.evaluate(async () => {+ for (let i = 0; i < 4; i++) await new Promise((done) => requestAnimationFrame(done));+ });+ const readyMs = performance.now() - start;+ await page.waitForTimeout(350);+ const after = await session.send("Performance.getMetrics");+ const metric = (record: typeof after, name: string) => record.metrics.find((m) => m.name === name)?.value ?? 0;+ const taskMs = (metric(after, "TaskDuration") - metric(before, "TaskDuration")) * 1000;+ // Snapshot interaction work before the instrumentation's forced GC.+ const dom = await page.evaluate(() => ({+ nodes: document.getElementsByTagName("*").length,+ bodies: document.querySelectorAll('[data-comment-content]:not([data-comment-content^="description:"])').length,+ longTasks: [...(window as unknown as { __historyPerf: { longTasks: number[] } }).__historyPerf.longTasks],+ }));+ await session.send("HeapProfiler.collectGarbage");+ const memory = await session.send("Performance.getMetrics");+ const network = await Promise.all(responses);+ expect(errors).toEqual([]);+ if (round >= 0) {+ const record = {+ dataset: dataset.name, entry, round, ready_ms: readyMs, task_ms: taskMs,+ system_load_1m: loadavg()[0],+ heap_mb: metric(memory, "JSHeapUsedSize") / 1e6,+ dom_nodes: dom.nodes, mounted_bodies: dom.bodies,+ long_task_count: dom.longTasks.length,+ long_task_max_ms: Math.max(0, ...dom.longTasks),+ long_task_total_ms: dom.longTasks.reduce((sum, value) => sum + value, 0),+ task_response_bytes: network.filter((r) => r.path.endsWith("/task-runs")).reduce((sum, r) => sum + r.bytes, 0),+ dataset_comments: dataset.bodies.length,+ dataset_utf8_bytes: Buffer.byteLength(dataset.bodies.join("\n")),+ dataset_sha256: createHash("sha256").update(JSON.stringify(dataset.bodies)).digest("hex"),+ };+ samples.push(record);+ console.log(JSON.stringify(record));+ }+ } finally { await context.close(); }+ }+ }+ }+ if (process.env.PERF_REPORT_PATH) writeFileSync(process.env.PERF_REPORT_PATH, JSON.stringify({+ ref: process.env.PERF_REF, browser: browser.version(), cpu_throttle: 1, viewport: "1440x900",+ samples, status: "ok",+ }, null, 2));+ } finally {+ await api.cleanup();+ if (agentId) await db.query("DELETE FROM agent_task_queue WHERE agent_id=$1", [agentId]);+ if (agentId) await db.query("DELETE FROM agent WHERE id=$1", [agentId]);+ if (runtimeId) await db.query("DELETE FROM agent_runtime WHERE id=$1", [runtimeId]);+ await db.end();+ }+});diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 5a22a73cf6..3314a27457 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1078,6 +1078,20 @@ describe("ApiClient", () => {}});+ it("requests the timeline run view without changing full-history requests", async () => {+ const fetch = vi.fn().mockImplementation(() => Promise.resolve(new Response(JSON.stringify([+ { id: "task-1", result: { comment: "Inline reply" }, coalesced_comment_ids: "malformed", can_supplement: "malformed" },+ ]), { status: 200, headers: { "Content-Type": "application/json" } })));+ vi.stubGlobal("fetch", fetch);+ const client = new ApiClient("https://api.example.test");+ const tasks = await client.listTasksByIssue("issue-1", false, { view: "timeline" });+ expect(String(fetch.mock.calls[0]?.[0])).toContain("/api/issues/issue-1/task-runs?view=timeline");+ expect(tasks[0]?.result).toEqual({ comment: "Inline reply" });+ expect(tasks[0]?.coalesced_comment_ids).toBeUndefined();+ await client.listTasksByIssue("issue-1");+ expect(String(fetch.mock.calls[1]?.[0])).toBe("https://api.example.test/api/issues/issue-1/task-runs");+ });+it("preserves planned and delivered comment coverage from issue task runs", async () => {vi.stubGlobal("fetch",@@ -3410,3 +3424,23 @@ describe("ApiClient shared credential across windows", () => {expect(onUnauthorized).toHaveBeenCalledTimes(1);});});++describe("ApiClient complete issue deliverables", () => {+ it("loads a posting comment's thread and validates the comment response", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ invalid: true }), { status: 200 }));+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");+ expect(await client.listComments("issue", { thread: "historical/comment" })).toEqual([]);+ expect(fetchMock.mock.calls[0]?.[0]).toBe("https://api.example.test/api/issues/issue/comments?thread=historical%2Fcomment");+ });++ it("loads lightweight origins independently of timeline and tolerates malformed responses", async () => {+ const fetchMock = vi.fn().mockResolvedValueOnce(new Response(JSON.stringify([{ id:"old",type:"comment",actor_type:"agent",actor_id:"a",created_at:"2026-01-01T00:00:00Z",attachments:[] }]),{status:200}))+ .mockResolvedValueOnce(new Response(JSON.stringify({invalid:true}),{status:200}));+ vi.stubGlobal("fetch",fetchMock);+ const client = new ApiClient("https://api.example.test");+ expect((await client.listIssueDeliverables("issue"))[0]?.id).toBe("old");+ expect(fetchMock.mock.calls[0]?.[0]).toBe("https://api.example.test/api/issues/issue/deliverables");+ expect(await client.listIssueDeliverables("issue")).toEqual([]);+ });+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 88c212c258..f9f9dd1e09 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1749,8 +1749,16 @@ export class ApiClient {}// Comments- async listComments(issueId: string): Promise<Comment[]> {- const raw = await this.fetch<unknown>(`/api/issues/${issueId}/comments`);+ async listIssueDeliverables(issueId: string): Promise<TimelineEntry[]> {+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/deliverables`);+ return parseWithFallback(raw, TimelineEntriesSchema, [], {+ endpoint: "GET /api/issues/:id/deliverables",+ });+ }++ async listComments(issueId: string, options?: { thread: string }): Promise<Comment[]> {+ const query = options ? `?${new URLSearchParams({ thread: options.thread })}` : "";+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/comments${query}`);return parseWithFallback(raw, CommentsListSchema, [], {endpoint: "GET /api/issues/:id/comments",});@@ -2969,10 +2977,12 @@ export class ApiClient {});}- async listTasksByIssue(issueId: string, includeDescendants = false): Promise<AgentTask[]> {- const raw = await this.fetch<unknown>(- `/api/issues/${issueId}/task-runs${includeDescendants ? "?scope=subtree" : ""}`,- );+ async listTasksByIssue(issueId: string, includeDescendants = false, options?: { view: "timeline" }): Promise<AgentTask[]> {+ const search = new URLSearchParams();+ if (includeDescendants) search.set("scope", "subtree");+ if (options?.view) search.set("view", options.view);+ const query = search.size ? `?${search}` : "";+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/task-runs${query}`);return parseWithFallback<AgentTask[]>(raw, AgentTaskListSchema, [], {endpoint: "GET /api/issues/:id/task-runs",});diff --git a/packages/core/attachments/deliverables.test.ts b/packages/core/attachments/deliverables.test.tsindex bab7e7f7a4..f62584d358 100644--- a/packages/core/attachments/deliverables.test.ts+++ b/packages/core/attachments/deliverables.test.ts@@ -6,6 +6,7 @@ import {deliverableKey,findDeliverableByName,findDeliverableVersion,+ mergeDeliverableSources,} from "./deliverables";function attachment(over: Partial<Attachment> & { id: string }): Attachment {@@ -115,6 +116,16 @@ describe("findDeliverableVersion", () => {});});+describe("mergeDeliverableSources", () => {+ it("retains older image inventory, overlays live changes and excludes tombstones", () => {+ const old = { id: "old", type: "comment" as const, actor_type: "agent", actor_id: "a", created_at: "2026-01-01", attachments: [attachment({id:"image",filename:"chart.png",content_type:"image/png"})] };+ const gone = { ...old, id: "gone" };+ const sources = mergeDeliverableSources([old, gone], [{...gone, deleted_at:"2026-02-01"}]);+ expect(sources.map((entry) => entry.id)).toEqual(["old"]);+ expect(collectDeliverableFiles(sources)[0]?.latest.id).toBe("image");+ });+});+describe("findDeliverableByName", () => {it("returns the file whose latest upload is the newest version", () => {const v1 = attachment({ id: "a1", filename: "report.html", content_type: "text/html", created_at: "2026-09-20T10:00:00Z" });diff --git a/packages/core/attachments/deliverables.ts b/packages/core/attachments/deliverables.tsindex e18be3a109..7d47614b94 100644--- a/packages/core/attachments/deliverables.ts+++ b/packages/core/attachments/deliverables.ts@@ -10,14 +10,13 @@* across runs, and the reader wants the latest one with its history behind* it, not five near-identical rows.*- * Built from comment entries rather than the issue-wide attachment list: the- * list is fetched before the upload is bound to its comment and is not- * refreshed when that bind lands, while the timeline is patched live and- * already carries each comment's attachments.+ * The complete attachment inventory supplies older origins; loaded timeline+ * comments overlay it so new uploads and tombstones remain current.** Pure — no React, no DOM, no platform APIs.*/+import type { TimelineEntry } from "../types";import type { Attachment } from "../types/attachment";/** The part of a timeline comment this module reads. */@@ -126,3 +125,16 @@ export function findDeliverableVersion(}return undefined;}++/** Live comments override inventory metadata, including tombstones. */+export function mergeDeliverableSources(+ inventory: readonly TimelineEntry[],+ timeline: readonly TimelineEntry[],+): TimelineEntry[] {+ const comments = new Map(inventory.map((entry) => [entry.id, entry]));+ for (const entry of timeline) {+ if (entry.type === "comment") comments.set(entry.id, entry);+ }+ return [...comments.values()].filter((entry) => !entry.deleted_at)+ .sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id));+}diff --git a/packages/core/issues/comment-thread.test.ts b/packages/core/issues/comment-thread.test.tsnew file mode 100644index 0000000000..5d6fa3516d--- /dev/null+++ b/packages/core/issues/comment-thread.test.ts@@ -0,0 +1,25 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { Comment } from "../types";+import { commentToTimelineEntry, mergeCommentThread } from "./comment-thread";++const comment: Comment = {+ id: "old", issue_id: "issue", author_type: "member", author_id: "member",+ content: "Historical chart", parent_id: null, type: "comment", reactions: [], attachments: [],+ created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", revision: 1,+ resolved_at: null, resolved_by_type: null, resolved_by_id: null,+};++describe("requested comment thread", () => {+ it("retains a historical target across bounded refetches without duplicating loaded comments", () => {+ const recent = commentToTimelineEntry({ ...comment, id: "recent", created_at: "2026-02-01T00:00:00Z" });+ expect(mergeCommentThread([recent], [comment]).map((entry) => entry.id)).toEqual(["old", "recent"]);+ expect(mergeCommentThread([recent, commentToTimelineEntry(comment)], [comment])).toHaveLength(2);+ });++ it("keeps the newest revision and deletion state when live events and thread reads overlap", () => {+ const live = commentToTimelineEntry({ ...comment, revision: 3, content: "", deleted_at: "2026-02-01T00:00:00Z" });+ expect(mergeCommentThread([live], [comment])[0]).toEqual(live);+ expect(mergeCommentThread([commentToTimelineEntry(comment)], [{ ...comment, revision: 4, content: "Updated chart" }])[0]?.content).toBe("Updated chart");+ });+});diff --git a/packages/core/issues/comment-thread.ts b/packages/core/issues/comment-thread.tsnew file mode 100644index 0000000000..26998e0fc9--- /dev/null+++ b/packages/core/issues/comment-thread.ts@@ -0,0 +1,45 @@+import type { Comment, TimelineEntry } from "../types";+import { sortTimelineEntriesAsc } from "./timeline-sort";++export function commentToTimelineEntry(c: Comment): TimelineEntry {+ return {+ type: "comment",+ id: c.id,+ actor_type: c.author_type,+ actor_id: c.author_id,+ content: c.content,+ parent_id: c.parent_id,+ created_at: c.created_at,+ updated_at: c.updated_at,+ revision: c.revision,+ comment_type: c.type,+ reactions: c.reactions ?? [],+ attachments: c.attachments ?? [],+ resolved_at: c.resolved_at,+ resolved_by_type: c.resolved_by_type,+ resolved_by_id: c.resolved_by_id,+ source_task_id: c.source_task_id,+ supplements: c.supplements,+ supplement_task_id: c.supplement_task_id,+ supplement_status: c.supplement_status,+ supplement_failure_reason: c.supplement_failure_reason,+ supplement_delivered_at: c.supplement_delivered_at,+ deleted_at: c.deleted_at,+ };+}++/** Keep a requested historical thread available across bounded timeline refetches. */+export function mergeCommentThread(timeline: TimelineEntry[], comments: Comment[]): TimelineEntry[] {+ if (comments.length === 0) return timeline;+ const entries = new Map(comments.map((comment) => [comment.id, commentToTimelineEntry(comment)]));+ for (const entry of timeline) {+ const focused = entries.get(entry.id);+ entries.set(+ entry.id,+ focused?.revision !== undefined && entry.revision !== undefined && focused.revision > entry.revision+ ? { ...focused, actor_name: entry.actor_name, actor_avatar_url: entry.actor_avatar_url }+ : entry,+ );+ }+ return sortTimelineEntriesAsc([...entries.values()]);+}diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex 4bd12a40c7..aca5f28534 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -23,10 +23,13 @@ import type { SidebarIssuesRequest } from "./sidebar-list";import { ALL_STATUSES } from "./config";import { issueColumnCategory } from "./status-category";-export function issueTasksOptions(issueId: string, includeDescendants = false) {+export function issueTasksOptions(issueId: string, includeDescendants = false, view: "timeline" | "history" = "timeline") {+ const key = includeDescendants ? issueKeys.subtreeTasks(issueId) : issueKeys.tasks(issueId);return queryOptions({- queryKey: includeDescendants ? issueKeys.subtreeTasks(issueId) : issueKeys.tasks(issueId),- queryFn: () => api.listTasksByIssue(issueId, includeDescendants),+ queryKey: view === "history" ? [...key, "history"] : key,+ queryFn: () => view === "timeline"+ ? api.listTasksByIssue(issueId, includeDescendants, { view })+ : api.listTasksByIssue(issueId, includeDescendants),enabled: !!issueId,staleTime: 30_000,refetchOnWindowFocus: true,@@ -173,6 +176,8 @@ export const issueKeys = {/** Full-issue timeline (single TanStack Query, no cursor). */timeline: (issueId: string) =>[...issueKeys.timelineAll(), issueId] as const,+ commentThread: (issueId: string, commentId: string) =>+ [...issueKeys.timeline(issueId), "thread", commentId] as const,/** Prefix across all issues — WS task lifecycle events invalidate here so* an open composer's trigger preview refreshes when an agent's queue* state changes (the dedup guard makes the answer queue-dependent). */@@ -202,9 +207,9 @@ export const issueKeys = {* click time. */attachments: (issueId: string) =>[...issueKeys.attachmentsAll(), issueId] as const,- /** Prefix-match key for invalidating tasks across all issues — used by- * the global WS task: prefix path so any task lifecycle event refreshes- * every per-issue list, regardless of which issue is currently mounted. */+ deliverables: (issueId: string) =>+ [...issueKeys.attachments(issueId), "deliverables"] as const,+ /** Prefix for reconnects and task events without an issue scope. */tasksAll: () => ["issues", "tasks"] as const,/** Per-issue task list (issue-detail Execution log section). */tasks: (issueId: string) => [...issueKeys.tasksAll(), issueId] as const,@@ -689,6 +694,19 @@ export function issueTimelineOptions(issueId: string) {});}+export function issueCommentThreadOptions(issueId: string, commentId: string) {+ return queryOptions({+ queryKey: issueKeys.commentThread(issueId, commentId),+ queryFn: async () => {+ const comments = await api.listComments(issueId, { thread: commentId });+ if (!comments.some((comment) => comment.id === commentId)) {+ throw new Error("Comment not found in thread");+ }+ return comments;+ },+ });+}+export function issueReactionsOptions(issueId: string) {return queryOptions({queryKey: issueKeys.reactions(issueId),@@ -734,3 +752,11 @@ export function issueAttachmentsOptions(issueId: string) {queryFn: () => api.listAttachments(issueId),});}++/** Complete attachment inventory; independent of the bounded discussion feed. */+export function issueDeliverablesOptions(issueId: string) {+ return queryOptions({+ queryKey: issueKeys.deliverables(issueId),+ queryFn: () => api.listIssueDeliverables(issueId),+ });+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex d5fe9116c4..bc87a74961 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -48,6 +48,7 @@"./issues/wakeups": "./issues/wakeups.ts","./issues/mutations": "./issues/mutations.ts","./issues/timeline-sort": "./issues/timeline-sort.ts",+ "./issues/comment-thread": "./issues/comment-thread.ts","./issues/comment-deletion": "./issues/comment-deletion.ts","./issues/comment-trigger-outcomes": "./issues/comment-trigger-outcomes.ts","./issues/run-steering": "./issues/run-steering.ts",diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex 2002d6c651..8b2319b7da 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -588,6 +588,8 @@ describe("useRealtimeSync — comment folded into a queued run", () => {renderHook(() => useRealtimeSync(ws, createStores()), { wrapper: createWrapper(qc) });const onAny = vi.mocked(ws.onAny).mock.calls[0]![0];qc.setQueryData(issueKeys.tasks("issue-1"), []);+ qc.setQueryData(issueKeys.tasks("unrelated-issue"), []);+ qc.setQueryData(issueKeys.subtreeTasks("parent"), []);onAny({type: "task:coalesced",@@ -596,6 +598,8 @@ describe("useRealtimeSync — comment folded into a queued run", () => {await vi.advanceTimersByTimeAsync(1_000);expect(qc.getQueryState(issueKeys.tasks("issue-1"))?.isInvalidated).toBe(true);+ expect(qc.getQueryState(issueKeys.tasks("unrelated-issue"))?.isInvalidated).toBe(false);+ expect(qc.getQueryState(issueKeys.subtreeTasks("parent"))?.isInvalidated).toBe(true);});});@@ -912,3 +916,18 @@ describe("useRealtimeSync — member:removed", () => {await waitFor(() => expect(qc.getQueryData(workspaceKeys.list())).toEqual([]));});});++describe("deliverable inventory freshness", () => {+ it.each(["comment:created", "comment:updated", "comment:deleted"])("refreshes only the affected issue on %s", (event) => {+ const qc = new QueryClient({ defaultOptions: {queries:{retry:false,staleTime:Infinity}} });+ const ws=createMockWs();+ renderHook(()=>useRealtimeSync(ws,createStores()),{wrapper:createWrapper(qc)});+ qc.setQueryData(issueKeys.deliverables("affected"),[]);+ qc.setQueryData(issueKeys.deliverables("unrelated"),[]);+ const listener=vi.mocked(ws.on).mock.calls.find(([name])=>name===event)?.[1];+ act(()=>listener?.({comment:{issue_id:"affected"},issue_id:"affected"} as never));+ expect(qc.getQueryState(issueKeys.deliverables("affected"))?.isInvalidated).toBe(true);+ expect(qc.getQueryState(issueKeys.deliverables("unrelated"))?.isInvalidated).toBe(false);+ qc.clear();+ });+});diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex f988878025..c34578683c 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -1029,15 +1029,6 @@ export function useRealtimeSync(// catches every agent's list — the per-agent detail key sits// under agentTasks/<wsId>/<agentId>.qc.invalidateQueries({ queryKey: agentTasksKeys.all(wsId) });- // Per-issue task list (issue-detail Execution log). Prefix match- // across all issues — keeps the contract "any task: event makes- // every list-of-tasks query stale" so cache stays fresh even- // when the relevant component isn't currently mounted.- qc.invalidateQueries({ queryKey: ["issues", "tasks"] });- // Per-issue token usage card (issue-detail right rail). Same- // shape as the tasks invalidation above — any task lifecycle- // event shifts the aggregated usage numbers.- qc.invalidateQueries({ queryKey: ["issues", "usage"] });// Squad members-status reads the same task lifecycle to flip// working ↔ idle for each agent member.invalidateSquadMemberStatusQueries(qc, wsId);@@ -1128,6 +1119,17 @@ export function useRealtimeSync(const unsubAny = ws.onAny((msg) => {if (specificEvents.has(msg.type)) return;const prefix = msg.type.split(":")[0] ?? "";+ if (prefix === "task" && msg.type !== "task:progress") {+ const payload = msg.payload as { issue_id?: unknown };+ const issueId = typeof payload?.issue_id === "string" && payload.issue_id ? payload.issue_id : null;+ // Debounce per issue so simultaneous runs cannot erase each other's refresh.+ debouncedRefresh(`issue-task:${issueId ?? "all"}`, () => {+ qc.invalidateQueries({ queryKey: issueId ? issueKeys.tasks(issueId) : issueKeys.tasksAll() });+ // Events don't carry the ancestor chain needed to scope subtree projections.+ if (issueId) qc.invalidateQueries({ queryKey: issueKeys.tasksAll(), predicate: (q) => q.queryKey[3] === "subtree" });+ qc.invalidateQueries({ queryKey: issueId ? issueKeys.usage(issueId) : issueKeys.usageAll() });+ });+ }if (prefix === "agent" || (prefix === "task" && msg.type !== "task:progress")) {const wsId = getCurrentWsId();if (wsId) scheduleWorkingAgentRefresh(wsId);@@ -1281,6 +1283,7 @@ export function useRealtimeSync(// through `refetchOnMount`. Active observers stay fresh via the// granular setQueryData handlers in `useIssueTimeline`.const invalidateTimeline = (issueId: string) => {+ qc.invalidateQueries({ queryKey: issueKeys.deliverables(issueId) });qc.invalidateQueries({queryKey: issueKeys.timeline(issueId),refetchType: "none",diff --git a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsxindex abeb989f1a..a5dd3c4732 100644--- a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx+++ b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx@@ -468,7 +468,7 @@ describe("IssueActionsDropdown", () => {fireEvent.click(screen.getByTestId("trigger"));await waitFor(() => {- expect(listTasksByIssueMock).toHaveBeenCalledWith("issue-1");+ expect(listTasksByIssueMock).toHaveBeenCalledWith("issue-1", false, { view: "timeline" });});fireEvent.click(await screen.findByText("Copy local workdir path"));diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsxindex cbb406748e..ded90dd516 100644--- a/packages/views/issues/actions/issue-actions-menu-items.tsx+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx@@ -31,7 +31,6 @@ import { useIssueDeletion } from "@multica/core/issues/use-issue-deletion";import type { AgentTask, Issue } from "@multica/core/types";import { resolveWorkdirCopyTarget } from "@multica/core/issues";import { todayDateOnly, addDaysDateOnly } from "@multica/core/issues/date";-import { api } from "@multica/core/api";import { agentTaskSnapshotOptions } from "@multica/core/agents";import {PRIORITY_DISPLAY_ORDER,@@ -45,7 +44,7 @@ import { stepHandsOff, workflowAllowsStatus, workflowStep } from "@multica/core/import { useModalStore } from "@multica/core/modals";import { useIssueStatusOptions } from "../utils/status-options";import { useStatusLabel } from "../utils/status-label";-import { issueKeys } from "@multica/core/issues/queries";+import { issueTasksOptions } from "@multica/core/issues/queries";import { StatusIcon } from "../components/status-icon";import { PriorityIcon } from "../components/priority-icon";import { selectIssueTasks } from "../surface/activity";@@ -182,9 +181,7 @@ export function IssueActionsMenuItems({// The query shares its key with ExecutionLogSection, so navigating from// the issue detail page is a free cache hit.const { data: tasks } = useQuery({- queryKey: issueKeys.tasks(issue.id),- queryFn: () => api.listTasksByIssue(issue.id),- staleTime: 30_000,+ ...issueTasksOptions(issue.id),enabled: !sidebar,});const workdirCopyTarget = useMemo(diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex dcdbf14f25..a75cbe0c52 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -36,6 +36,7 @@ import { useCommentUploads } from "./use-comment-uploads";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { api, dispatchReasonCode, errorCode } from "@multica/core/api";import { ReplyInput } from "./reply-input";+import { VirtualThreadRow } from "./virtual-thread-row";import { CommentTriggerChips } from "./comment-trigger-chips";import { AppCallChips } from "./app-call-chips";import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";@@ -113,6 +114,7 @@ function StickyHeaderShell({interface CommentCardProps {issueId: string;+ replyScrollParent?: HTMLElement | null;runs?: CommentRun[];runViewState?: InlineCommentRunState;enteringRunIds?: ReadonlySet<string>;@@ -956,8 +958,9 @@ function ReplyToQuote({ entry, onJump }: { entry: TimelineEntry; onJump?: (comme}/** A run without a persisted reply still belongs to the agent, never its trigger author. */-export function AgentRunComment({ run, standalone = false, commentProps, entering = false, replyTo, highlightedId }: {+export function AgentRunComment({ run, standalone = false, commentProps, entering = false, replyTo, highlightedId, managedAnchor = false }: {run: CommentRun;+ managedAnchor?: boolean;standalone?: boolean;entering?: boolean;commentProps?: CommentCardProps;@@ -987,7 +990,7 @@ export function AgentRunComment({ run, standalone = false, commentProps, enterinreturn (<div ref={motionRef} data-run-slot-id={run.task.id}data-run-comment-id={!reply ? run.task.id : undefined}- id={!standalone ? `comment-${slotEntry?.id ?? run.task.id}` : undefined}+ id={!standalone && !managedAnchor ? `comment-${slotEntry?.id ?? run.task.id}` : undefined}className={cn("transition-colors duration-700", standalone ? !reply && "rounded-xl border" : "border-t border-border/50", !reply && "py-1.5",highlighted ? highlightedCommentBackgroundClass : standalone && !reply && "bg-card")}>{commentProps && reply ? standalone ? (@@ -1017,6 +1020,7 @@ export function AgentRunComment({ run, standalone = false, commentProps, enterinfunction CommentCardImpl({issueId,+ replyScrollParent,runs = EMPTY_COMMENT_RUNS,runViewState,enteringRunIds,@@ -1094,17 +1098,17 @@ function CommentCardImpl({// A run slot renders the run's latest comment, or its activity until it// posts one.- const renderThreadRow = (row: TimelineEntry | ThreadRunSlot) => "run" in row ? (- <AgentRunComment key={row.run.task.id} run={row.run} entering={enteringRunIds?.has(row.run.task.id)}+ const renderThreadRow = (row: TimelineEntry | ThreadRunSlot, managedAnchor = false) => "run" in row ? (+ <AgentRunComment key={row.run.task.id} run={row.run} managedAnchor={managedAnchor} entering={enteringRunIds?.has(row.run.task.id)}highlightedId={highlightedCommentId}replyTo={row.replyTo && <ReplyToQuote entry={row.replyTo} onJump={onJumpToComment} />}commentProps={row.reply ? {issueId, entry: row.reply, replies: [], currentUserId, canModerate, onReply, onEdit, onDelete,onToggleReaction, onCreateSubIssue, onResolveToggle, onCopyLink, highlightedCommentId, enteringRunIds,} : undefined} />- ) : renderReply(row);+ ) : renderReply(row, managedAnchor);- const renderReply = (reply: TimelineEntry) => (+ const renderReply = (reply: TimelineEntry, managedAnchor: boolean) => (<Fragment key={reply.id}>{/* A tombstone keeps its place in the thread but contributes no rowof its own. */}@@ -1112,7 +1116,7 @@ function CommentCardImpl({<divdata-mc="comment-reply"data-author-type={reply.actor_type}- id={`comment-${reply.id}`}+ id={managedAnchor ? undefined : `comment-${reply.id}`}className={cn("border-t border-border/50 transition-colors duration-700",highlightedCommentId === reply.id && highlightedCommentBackgroundClass,@@ -1170,6 +1174,18 @@ function CommentCardImpl({&& (run.anchorCommentId === entry.id || run.anchorCommentId === replyResolutionId))): orderThreadWithRuns(entry, allNestedReplies, runs);+ const renderRows = () => threadRows.map((row) => {+ if (!replyScrollParent || threadRows.length < 30) return renderThreadRow(row);+ if (!("run" in row) && isDeletedComment(row)) return null;+ const anchorId = "run" in row+ ? (row.reply && !isDeletedComment(row.reply) ? row.reply.id : row.run.task.id)+ : row.id;+ return <VirtualThreadRow key={anchorId} id={`comment-${anchorId}`}+ taskId={"run" in row ? row.run.task.id : undefined} scrollParent={replyScrollParent}>+ {() => renderThreadRow(row, true)}+ </VirtualThreadRow>;+ });+// Pin the root comment's header to the timeline's scroll parent while the// thread is open, so a LONG root comment keeps its author + actions visible// as you scroll its body (overflow-clip on the Card anchors this to the@@ -1511,7 +1527,7 @@ function CommentCardImpl({/></div>)}- {threadRows.map(renderThreadRow)}+ {renderRows()}</>) : (<>@@ -1529,7 +1545,7 @@ function CommentCardImpl({</button>)}{/* Replies — chronological; the resolution keeps its place with a badge */}- {threadRows.map(renderThreadRow)}+ {renderRows()}{/* Reply input */}<div className="border-t border-border/50 px-4 max-md:px-3 py-2.5">diff --git a/packages/views/issues/components/deliverables/deliverable-kind.ts b/packages/views/issues/components/deliverables/deliverable-kind.tsindex 74c123efab..eb9dba9896 100644--- a/packages/views/issues/components/deliverables/deliverable-kind.ts+++ b/packages/views/issues/components/deliverables/deliverable-kind.ts@@ -1,3 +1,4 @@+import type { DeliverableFile } from "@multica/core/attachments/deliverables";import { getPreviewKind } from "../../../editor/utils/preview";import { isDocumentFile } from "../../../editor/utils/file-icon";@@ -22,3 +23,18 @@ export function deliverableCategory(if (kind === "video") return "video";return isDocumentFile(contentType, filename) ? "document" : "other";}++/** Images are individually visible even when their filenames match. */+export function displayDeliverableFiles(files: readonly DeliverableFile[]): DeliverableFile[] {+ return files.flatMap((file) => {+ if (deliverableCategory(file.latest.content_type, file.latest.filename) !== "image") return [file];+ return file.versions.map((attachment) => ({+ ...file,+ key: `${file.key}\u0000${attachment.id}`,+ latest: attachment,+ }));+ }).sort((a, b) => b.latest.created_at.localeCompare(a.latest.created_at) || b.latest.id.localeCompare(a.latest.id));+}+export function displayedVersion(file: DeliverableFile): number {+ return file.versions.findIndex((version) => version.id === file.latest.id) + 1;+}diff --git a/packages/views/issues/components/deliverables/deliverables-overview.tsx b/packages/views/issues/components/deliverables/deliverables-overview.tsxindex 57644f2bce..279df2e815 100644--- a/packages/views/issues/components/deliverables/deliverables-overview.tsx+++ b/packages/views/issues/components/deliverables/deliverables-overview.tsx@@ -19,6 +19,8 @@ import type { DeliverableOrigin } from "./deliverable-details";import {DELIVERABLE_CATEGORIES,deliverableCategory,+ displayDeliverableFiles,+ displayedVersion,type DeliverableCategory,} from "./deliverable-kind";import { DeliverableThumbnail } from "./deliverable-thumbnail";@@ -44,8 +46,8 @@ interface FileGroup {* the sidebar's "view all" and from the viewer's grid button (`G`).** Files grouped by the comment that posted them, in page order, each group- * one click from that comment. Files show their latest version only, so the- * count here always equals the sidebar's.+ * one click from a loaded comment. Every image upload stays visible; other+ * files show their latest version, matching the sidebar count.** A full-window Dialog: the primitive owns focus (moved in on open, trapped* while open, returned to the opener on close) and Escape; this only restyles@@ -136,7 +138,7 @@ export function DeliverablesOverview({function OverviewBody({identifier,- files,+ files: groupedFiles,commentById,onClose,onOpenFile,@@ -152,6 +154,7 @@ function OverviewBody({onCopyLink?: (filename: string) => void;}) {const { t } = useT("issues");+ const files = useMemo(() => displayDeliverableFiles(groupedFiles), [groupedFiles]);const [filter, setFilter] = useState<Filter>("all");const count = files.length;@@ -410,7 +413,7 @@ function FileTileButton({<span className="mt-2 flex min-w-0 items-center gap-1.5"><span className="truncate text-body">{latest.filename}</span>{file.versions.length > 1 && (- <VersionBadge version={file.versions.length} className="bg-secondary" />+ <VersionBadge version={displayedVersion(file)} className="bg-secondary" />)}</span>{meta.length > 0 && (diff --git a/packages/views/issues/components/deliverables/deliverables-section.tsx b/packages/views/issues/components/deliverables/deliverables-section.tsxindex 4bd2c40050..5f5ae41781 100644--- a/packages/views/issues/components/deliverables/deliverables-section.tsx+++ b/packages/views/issues/components/deliverables/deliverables-section.tsx@@ -2,7 +2,7 @@import { IssueSidebarSectionHeader } from "../issue-sidebar-section";-import { useState } from "react";+import { useMemo, useState } from "react";import { LayoutGrid, Link2 } from "@multica/ui/icons";import type { DeliverableFile } from "@multica/core/attachments/deliverables";import { IconButton } from "@multica/ui/components/common/icon-button";@@ -13,6 +13,7 @@ import { fileIcon } from "../../../editor/utils/file-icon";import { getPreviewKind } from "../../../editor/utils/preview";import { DeliverableThumbnail } from "./deliverable-thumbnail";import { useOpenAttachment } from "./use-open-attachment";+import { displayDeliverableFiles, displayedVersion } from "./deliverable-kind";import { VersionBadge } from "./version-badge";// The sidebar is a summary, not the list: the newest few of each, and the@@ -28,7 +29,7 @@ const RECENT_FILES = 4;* until a comment delivers a file.*/export function DeliverablesSection({- files,+ files: groupedFiles,onOpenOverview,onCopyLink,}: {@@ -38,6 +39,7 @@ export function DeliverablesSection({onCopyLink?: (filename: string) => void;}) {const { t } = useT("issues");+ const files = useMemo(() => displayDeliverableFiles(groupedFiles), [groupedFiles]);const [open, setOpen] = useState(true);const { open: openAttachment, modal } = useOpenAttachment();@@ -101,7 +103,7 @@ function versionedName(file: DeliverableFile, t: IssuesT): string {return file.versions.length > 1? t(($) => $.deliverables.name_with_version, {name: file.latest.filename,- version: file.versions.length,+ version: displayedVersion(file),}): file.latest.filename;}@@ -131,7 +133,7 @@ function FileRow({><Icon className="size-3.5 shrink-0 text-muted-foreground" /><span className="min-w-0 truncate">{latest.filename}</span>- {file.versions.length > 1 && <VersionBadge version={file.versions.length} />}+ {file.versions.length > 1 && <VersionBadge version={displayedVersion(file)} />}<spanclassName={onCopyLinkdiff --git a/packages/views/issues/components/deliverables/deliverables.test.tsx b/packages/views/issues/components/deliverables/deliverables.test.tsxindex abedd61796..013dea8b6e 100644--- a/packages/views/issues/components/deliverables/deliverables.test.tsx+++ b/packages/views/issues/components/deliverables/deliverables.test.tsx@@ -212,6 +212,25 @@ describe("DeliverablesOverview", () => {return { onClose, onLocate };}+ it("shows every uploaded image version as a separate selectable thumbnail", () => {+ const older = { ...SHOT, id: "shot-old", created_at: "2026-09-19T10:00:00Z" };+ const files = collectDeliverableFiles([comment("older-comment", [older]), ...TIMELINE]);+ renderOverview({ files });+ expect(screen.getAllByTitle("settings.png")).toHaveLength(2);+ fireEvent.click(screen.getByRole("button", { name: /^Images\s*2$/ }));+ expect(screen.getAllByTitle("settings.png")).toHaveLength(2);+ fireEvent.click(screen.getAllByTitle("settings.png")[0]!);+ expect(openAtMock).toHaveBeenCalledWith("shot-old");+ });++ it("offers a jump for every known posting comment", () => {+ const { onLocate } = renderOverview();+ const buttons = screen.getAllByRole("button", { name: "Show in comments" });+ expect(buttons).toHaveLength(2);+ fireEvent.click(buttons[0]!);+ expect(onLocate).toHaveBeenCalledWith({ kind: "comment", commentId: "c-1" });+ });+it("counts exactly what the sidebar counts", () => {renderOverview();const dialog = screen.getByRole("dialog", { name: "MUL-7588 deliverables" });diff --git a/packages/views/issues/components/execution-log-section.test.tsx b/packages/views/issues/components/execution-log-section.test.tsxindex 7e8f436308..755523717a 100644--- a/packages/views/issues/components/execution-log-section.test.tsx+++ b/packages/views/issues/components/execution-log-section.test.tsx@@ -85,6 +85,8 @@ describe("subtree execution log", () => {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });queryClient.setQueryData(issueKeys.tasks("issue-1"), own);queryClient.setQueryData(issueKeys.subtreeTasks("issue-1"), subtree);+ queryClient.setQueryData([...issueKeys.tasks("issue-1"), "history"], own);+ queryClient.setQueryData([...issueKeys.subtreeTasks("issue-1"), "history"], subtree);return renderWithI18n(<QueryClientProvider client={queryClient}><ExecutionLogSection issueId="issue-1" identifier="MUL-1" hasChildren />@@ -275,7 +277,7 @@ describe("subtree execution log", () => {fireEvent.click(screen.getByRole("checkbox", { name: "Include sub-issues" }));expect(screen.getByRole("status", { name: "Loading runs..." })).toBeInTheDocument();expect(screen.queryByRole("button", { name: "Execution log 1" })).not.toBeInTheDocument();- expect(list).toHaveBeenCalledWith("issue-1", true);+ expect(list).toHaveBeenCalledWith("issue-1", true, { view: "timeline" });await act(async () => { rejectRequest(new Error("unavailable")); });const retry = await screen.findByRole("button", { name: "Could not load runs. Retry" });list.mockResolvedValue([makeTask({ id: "deep", issue_id: "deep-issue" })]);@@ -543,7 +545,7 @@ describe("per-run token usage", () => {// Header figures stay readable at every supported sidebar width.describe("execution log header geometry", () => {- function renderSection(tasks: AgentTask[]) {+ function renderSection(tasks: AgentTask[], seedHistory = true) {// Seed the cache instead of mocking the API: the query is fresh for 30s,// so `listTasksByIssue` is never reached and the section renders its real// header markup.@@ -551,6 +553,7 @@ describe("execution log header geometry", () => {defaultOptions: { queries: { retry: false } },});queryClient.setQueryData(issueKeys.tasks("issue-1"), tasks);+ if (seedHistory) queryClient.setQueryData([...issueKeys.tasks("issue-1"), "history"], tasks);return renderWithI18n(<QueryClientProvider client={queryClient}><ExecutionLogSection issueId="issue-1" identifier="MUL-1" />@@ -558,6 +561,18 @@ describe("execution log header geometry", () => {);}+ it("requests complete run history only when its dialog opens", async () => {+ const client = new ApiClient("http://localhost");+ setApiInstance(client);+ const request = vi.spyOn(client, "listTasksByIssue").mockResolvedValue([]);+ try {+ renderSection([makeTask({ status: "completed", completed_at: "2026-06-08T08:01:00Z" })], false);+ expect(request).not.toHaveBeenCalled();+ await act(async () => fireEvent.click(screen.getByRole("button", { name: "Open timeline" })));+ expect(request).toHaveBeenCalledWith("issue-1", false);+ } finally { request.mockRestore(); }+ });+it("shows the running task before pending tasks in queue order", () => {renderSection([makeTask({ id: "new", status: "queued", trigger_summary: "Order: second", created_at: "2026-09-08T03:02:00Z" }),diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsxindex 552b512691..09e0663429 100644--- a/packages/views/issues/components/execution-log-section.tsx+++ b/packages/views/issues/components/execution-log-section.tsx@@ -59,10 +59,8 @@ import { WakeupRunLabel } from "./wakeup-source-chip";// Left text keeps flex-1 so the row never shows a mid-row gap. Do// not use masks/padding gymnastics here.//-// One query (`listTasksByIssue`) drives both buckets — the back-end-// returns every status, the front-end filters into active vs past on the-// client. WS task:* events for this issue trigger an invalidate so the-// list updates without polling.+// The timeline index supplies every status and usage without provider output.+// Full run history and charts load only while the Runs dialog is open.interface ExecutionLogSectionProps {issueId: string;diff --git a/packages/views/issues/components/issue-agent-header-chip.tsx b/packages/views/issues/components/issue-agent-header-chip.tsxindex d82e276cc7..7d64386a6b 100644--- a/packages/views/issues/components/issue-agent-header-chip.tsx+++ b/packages/views/issues/components/issue-agent-header-chip.tsx@@ -10,8 +10,7 @@ import {import { useActorName } from "@multica/core/workspace/hooks";import { cn } from "@multica/ui/lib/utils";import { BorderBeam } from "@multica/ui/components/common/border-beam";-import { api } from "@multica/core/api";-import { issueKeys } from "@multica/core/issues/queries";+import { issueTasksOptions } from "@multica/core/issues/queries";import type { AgentTask } from "@multica/core/types";import { TranscriptButton } from "../../common/task-transcript";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";@@ -54,12 +53,7 @@ export const IssueAgentHeaderChip = memo(function IssueAgentHeaderChip({}: IssueAgentHeaderChipProps) {const { t } = useT("issues");// Same query options as ExecutionLogSection so both observe one cache entry.- const { data: tasks = [] } = useQuery({- queryKey: issueKeys.tasks(issueId),- queryFn: () => api.listTasksByIssue(issueId),- staleTime: 30_000,- refetchOnWindowFocus: true,- });+ const { data: tasks = [] } = useQuery(issueTasksOptions(issueId));const { running, queued } = useMemo(() => {const running: AgentTask[] = [];diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 962f104481..3ef76bd2cc 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -316,6 +316,7 @@ vi.mock("../../projects/components/project-picker", () => ({// Mock apiconst mockApiObj = vi.hoisted(() => ({+ getBaseUrl: () => "",getIssue: vi.fn(),listTimeline: vi.fn().mockResolvedValue([]),listComments: vi.fn().mockResolvedValue([]),@@ -344,6 +345,7 @@ const mockApiObj = vi.hoisted(() => ({addIssueReaction: vi.fn(),removeIssueReaction: vi.fn(),listAttachments: vi.fn().mockResolvedValue([]),+ listIssueDeliverables: vi.fn().mockResolvedValue([]),addCommentReaction: vi.fn(),removeCommentReaction: vi.fn(),listMembers: vi.fn().mockResolvedValue([{ user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" }]),@@ -470,10 +472,8 @@ vi.mock("@multica/core/issues/stores", async () => ({}));// Mock react-virtuoso: jsdom has no real layout, so the real Virtuoso would-// compute a 0-height viewport and render nothing. The mock renders every item-// inline so id="comment-..." nodes are always present in the DOM — this-// matches the production cold-path where `initialItemCount` force-mounts-// items[0..targetIdx], giving the deep-link effect a real target node.+// compute a 0-height viewport and render nothing. Most tests render every item;+// the windowed regression requires index navigation to mount an offscreen row.//// scrollIntoViewSpy: the deep-link effect no longer calls native// scrollIntoView (it drives the timeline container's scrollTop directly to@@ -484,27 +484,86 @@ vi.mock("@multica/core/issues/stores", async () => ({// layout.const scrollIntoViewSpy = vi.hoisted(() => vi.fn());const scrollToIndexSpy = vi.hoisted(() => vi.fn());+const scrollIntoViewIndexSpy = vi.hoisted(() => vi.fn());+const mockVirtualWindow = vi.hoisted(() => ({+ enabled: false, delayedViewport: false, lateScrollReset: false, offscreenViewport: false, pendingSizeCorrection: false, holdAtIndex: false,+ targetId: "", targetHeight: 100, scrollParent: null as HTMLElement | null,+}));vi.mock("react-virtuoso", () => ({Virtuoso: forwardRef(function MockVirtuoso(- { data, itemContent, computeItemKey }: {+ { data, itemContent, computeItemKey, customScrollParent, totalListHeightChanged }: {data: unknown[];itemContent: (i: number, item: unknown) => unknown;computeItemKey: (i: number, item: unknown) => React.Key;+ customScrollParent?: HTMLElement;+ totalListHeightChanged?: (height: number) => void;},ref: any,) {+ const [windowStart, setWindowStart] = useState(0);+ const correctionTimer = useRef<ReturnType<typeof setInterval> | null>(null);+ useEffect(() => {+ if (!mockVirtualWindow.holdAtIndex || !customScrollParent) return;+ correctionTimer.current = setInterval(() => { customScrollParent.scrollTop = 0; }, 10);+ return () => { if (correctionTimer.current) clearInterval(correctionTimer.current); };+ }, [customScrollParent]);+ const viewportMeasured = useRef(!mockVirtualWindow.delayedViewport && !mockVirtualWindow.offscreenViewport);+ useEffect(() => {+ const measured = () => {+ viewportMeasured.current = true;+ totalListHeightChanged?.(1000);+ };+ if (mockVirtualWindow.offscreenViewport && customScrollParent) {+ const list = document.querySelector('[data-testid="virtuoso-mock"]')?.parentElement;+ if (list) list.getBoundingClientRect = () => new DOMRect(0, 1000 - customScrollParent.scrollTop, 400, 100);+ const timer = window.setInterval(() => {+ if (customScrollParent.scrollTop > 0) { window.clearInterval(timer); measured(); }+ }, 10);+ return () => window.clearInterval(timer);+ }+ if (!mockVirtualWindow.delayedViewport) { measured(); return; }+ const timer = window.setTimeout(measured, 100);+ return () => window.clearTimeout(timer);+ }, [totalListHeightChanged, customScrollParent]);+ useEffect(() => {+ if ((!mockVirtualWindow.lateScrollReset && !mockVirtualWindow.holdAtIndex) || !customScrollParent) return;+ mockVirtualWindow.scrollParent = customScrollParent;+ Object.defineProperty(customScrollParent, "clientHeight", { configurable: true, value: 200 });+ customScrollParent.getBoundingClientRect = () => new DOMRect(0, 0, 400, 200);+ const target = document.getElementById(`comment-${mockVirtualWindow.targetId}`);+ if (target) {+ target.getBoundingClientRect = () => new DOMRect(0, 250 - customScrollParent.scrollTop, 400, mockVirtualWindow.targetHeight);+ const row = target.closest<HTMLElement>("[data-item-index]");+ if (row) row.getBoundingClientRect = () => new DOMRect(0, -customScrollParent.scrollTop, 400, 500);+ }+ }, [customScrollParent, windowStart, data]);+ const jump = (location: { index: number; offset?: number; done?: () => void }) => {+ if (location.offset !== undefined && customScrollParent && mockVirtualWindow.holdAtIndex) {+ if (correctionTimer.current) clearInterval(correctionTimer.current);+ customScrollParent.scrollTop = location.offset;+ }+ if (mockVirtualWindow.enabled && viewportMeasured.current) setWindowStart(Math.max(0, location.index - 2));+ if (mockVirtualWindow.lateScrollReset && customScrollParent) {+ window.setTimeout(() => { customScrollParent.scrollTop = location.offset ?? 0; location.done?.(); }, 80);+ } else if (!mockVirtualWindow.pendingSizeCorrection && !mockVirtualWindow.holdAtIndex) location.done?.();+ };useImperativeHandle(ref, () => ({- // Real Virtuoso ref methods are not exercised by tests in this file- // since the deep-link cold-path drives the container's scrollTop on the- // real DOM node, not Virtuoso's imperative API.- scrollIntoView: vi.fn(),- scrollToIndex: scrollToIndexSpy,+ scrollIntoView: (location: { index: number; done?: () => void }) => {+ scrollIntoViewIndexSpy(location);+ jump(location);+ },+ scrollToIndex: (location: { index: number }) => {+ scrollToIndexSpy(location);+ jump(location);+ },}));+ const start = mockVirtualWindow.enabled ? windowStart : 0;+ const visible = mockVirtualWindow.enabled ? data.slice(start, start + 8) : data;return (<div data-testid="virtuoso-mock">- {data.map((item, i) => (- <div key={computeItemKey(i, item)}>{itemContent(i, item) as React.ReactElement}</div>+ {visible.map((item, i) => (+ <div key={computeItemKey(start + i, item)} data-item-index={start + i}>{itemContent(start + i, item) as React.ReactElement}</div>))}</div>);@@ -514,6 +573,16 @@ vi.mock("react-virtuoso", () => ({// jsdom's HTMLElement.prototype.scrollIntoView is a no-op stub; replace it// with a spy so the deep-link effect's call can be observed.beforeEach(() => {+ mockVirtualWindow.enabled = false;+ mockVirtualWindow.pendingSizeCorrection = false;+ mockVirtualWindow.holdAtIndex = false;+ mockVirtualWindow.delayedViewport = false;+ mockVirtualWindow.offscreenViewport = false;+ mockVirtualWindow.lateScrollReset = false;+ mockVirtualWindow.targetId = "";+ mockVirtualWindow.targetHeight = 100;+ mockVirtualWindow.scrollParent = null;+ scrollIntoViewIndexSpy.mockClear();scrollIntoViewSpy.mockClear();scrollToIndexSpy.mockClear();Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {@@ -736,6 +805,8 @@ describe("IssueDetail (shared)", () => {mockApiObj.listPins.mockResolvedValue([]);// /timeline returns the entries flat in chronological order (oldest first).mockApiObj.listTimeline.mockResolvedValue(mockTimeline);+ mockApiObj.listIssueDeliverables.mockResolvedValue([]);+ mockApiObj.listComments.mockResolvedValue([]);mockApiObj.listIssueReactions.mockResolvedValue([]);mockApiObj.listIssueSubscribers.mockResolvedValue([]);mockApiObj.listChildIssues.mockResolvedValue({ issues: [] });@@ -814,6 +885,75 @@ describe("IssueDetail (shared)", () => {expect(screen.queryByRole("button", { name: "brief.pdf" })).toBeNull();});+ it("keeps images from comments outside the loaded history in deliverables", async () => {+ const image: Attachment = { id: "historical-chart", workspace_id: "ws-1", issue_id: "issue-1", comment_id: "older-comment",+ chat_session_id: null, chat_message_id: null, uploader_type: "agent", uploader_id: "agent-1",+ filename: "historical-chart.png", content_type: "image/png", size_bytes: 100,+ url: "/chart.png", download_url: "/chart.png", markdown_url: "/chart.png", created_at: "2026-01-01T00:00:00Z" };+ mockApiObj.listTimeline.mockResolvedValue([]);+ mockApiObj.listIssueDeliverables.mockResolvedValue([{ id: "older-comment", type: "comment", actor_type: "agent",+ actor_id: "agent-1", created_at: image.created_at, attachments: [image] }]);+ const root = {+ id: "older-root", issue_id: "issue-1", author_type: "agent", author_id: "agent-1",+ content: "Historical image discussion", type: "comment", parent_id: null,+ created_at: image.created_at, updated_at: image.created_at, reactions: [], attachments: [],+ resolved_at: null, resolved_by_type: null, resolved_by_id: null,+ };+ mockApiObj.listComments.mockResolvedValue([root, {+ ...root, id: "older-comment", parent_id: root.id,+ content: "Historical chart explanation", attachments: [image],+ }]);+ renderIssueDetail();+ expect(await screen.findByRole("button", { name: "historical-chart.png" })).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "View all 1 deliverable" }));+ expect(await screen.findByTitle("historical-chart.png")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Show in comments" })).toBeInTheDocument();+ expect(mockApiObj.listComments).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Show in comments" }));+ await waitFor(() => expect(hasHighlightedCommentBackground(+ document.getElementById("comment-older-comment"),+ )).toBe(true));+ expect(mockApiObj.listComments).toHaveBeenCalledWith("issue-1", { thread: "older-comment" });+ expect(screen.getByText("Historical chart explanation")).toBeInTheDocument();+ expect(screen.queryByRole("dialog", { name: /deliverables$/ })).toBeNull();+ });++ it.each([100, 1200])("keeps a %i-pixel deliverable reply visible while the virtual list corrects its size", async (height) => {+ mockVirtualWindow.enabled = true;+ mockVirtualWindow.holdAtIndex = true;+ mockVirtualWindow.targetId = "image-reply";+ mockVirtualWindow.targetHeight = height;+ const history = Array.from({ length: 120 }, (_, index) => ({+ ...mockTimeline[0]!, id: `history-${index}`, parent_id: null, source_task_id: undefined,+ content: `Historical comment ${index}`,+ created_at: new Date(Date.UTC(2026, 0, 1, 0, index)).toISOString(),+ }));+ const root = history[115]!;+ const image: Attachment = { id: "deep-image", workspace_id: "ws-1", issue_id: "issue-1",+ comment_id: "image-reply", chat_session_id: null, chat_message_id: null,+ uploader_type: "agent", uploader_id: "agent-1", filename: "deep-image.png",+ content_type: "image/png", size_bytes: 100, url: "/image.png", download_url: "/image.png",+ markdown_url: "/image.png", created_at: root.created_at };+ mockApiObj.listTimeline.mockResolvedValue([...history, {+ ...root, id: "image-reply", parent_id: root.id, content: "Deep image explanation", attachments: [image],+ }]);+ mockApiObj.listTasksByIssue.mockResolvedValue([]);+ renderIssueDetail();+ fireEvent.click(await screen.findByRole("button", { name: "View all 1 deliverable" }));+ fireEvent.click(screen.getByRole("button", { name: "Show in comments" }));+ await waitFor(() => expect(hasHighlightedCommentBackground(+ document.getElementById("comment-image-reply"),+ )).toBe(true));+ await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 150)); });+ expect(mockVirtualWindow.scrollParent?.scrollTop).toBe(height === 100 ? 200 : 234);+ expect(document.querySelectorAll('[id^="comment-history-"]').length).toBeLessThanOrEqual(8);+ expect(mockApiObj.listComments).not.toHaveBeenCalled();+ const jumps = scrollIntoViewIndexSpy.mock.calls.length;+ fireEvent.click(screen.getByRole("button", { name: "View all 1 deliverable" }));+ fireEvent.click(screen.getByRole("button", { name: "Show in comments" }));+ await waitFor(() => expect(scrollIntoViewIndexSpy.mock.calls.length).toBeGreaterThan(jumps));+ });+it("opens source-context creation from both a root comment and a reply", async () => {mockApiObj.listTimeline.mockResolvedValue([{ ...mockTimeline[0], id: "source-root", parent_id: null },@@ -2485,7 +2625,86 @@ describe("IssueDetail (shared)", () => {expect(screen.queryByText(/Show \d+ more activit/i)).not.toBeInTheDocument();});+ it("does not mount offscreen reply bodies in a long discussion", async () => {+ vi.stubGlobal("IntersectionObserver", class {+ observe() {} unobserve() {} disconnect() {}+ });+ const root = { ...mockTimeline[0]!, id: "long-thread-root", parent_id: null, content: "Long discussion root" };+ const replies = Array.from({ length: 200 }, (_, index) => ({+ ...root, id: `offscreen-reply-${index}`, parent_id: root.id, content: `Offscreen body ${index}`,+ }));+ mockApiObj.listTimeline.mockResolvedValue([root, ...replies]);+ mockApiObj.listTasksByIssue.mockResolvedValue([]);+ try {+ renderIssueDetail();+ await screen.findByText("Long discussion root");+ expect(document.getElementById("comment-offscreen-reply-199")).not.toBeNull();+ expect(screen.queryByText("Offscreen body 199")).toBeNull();+ expect(readonlyContentRenders.filter((body) => body.startsWith("Offscreen body"))).toHaveLength(0);+ } finally { vi.unstubAllGlobals(); }+ });+describe("highlightCommentId scroll-to-comment", () => {+ it.each([+ { kind: "root", delayedViewport: false, lateScrollReset: false },+ { kind: "reply", delayedViewport: false, lateScrollReset: false },+ { kind: "root", delayedViewport: true, lateScrollReset: false },+ { kind: "reply", delayedViewport: false, lateScrollReset: true },+ { kind: "reply", delayedViewport: false, lateScrollReset: false, offscreenViewport: true },+ { kind: "reply", delayedViewport: false, lateScrollReset: false, pendingSizeCorrection: true },+ { kind: "reply", delayedViewport: false, lateScrollReset: false, holdAtIndex: true },+ ])("keeps long history virtualized for a $kind (late viewport: $delayedViewport, late scroll: $lateScrollReset, below fold: $offscreenViewport)", async ({ kind, delayedViewport, lateScrollReset, offscreenViewport, pendingSizeCorrection, holdAtIndex }) => {+ mockVirtualWindow.holdAtIndex = !!holdAtIndex;+ mockVirtualWindow.pendingSizeCorrection = !!pendingSizeCorrection;+ mockVirtualWindow.enabled = true;+ mockVirtualWindow.delayedViewport = delayedViewport;+ mockVirtualWindow.offscreenViewport = !!offscreenViewport;+ mockVirtualWindow.lateScrollReset = lateScrollReset;+ const history = Array.from({ length: 120 }, (_, index) => ({+ ...mockTimeline[0]!,+ id: `history-${index}`,+ parent_id: null,+ source_task_id: undefined,+ content: `Historical comment ${index}`,+ created_at: new Date(Date.UTC(2026, 0, 1, 0, index)).toISOString(),+ }));+ const root = history[115]!;+ const target = kind === "root" ? root : {+ ...root,+ id: "deep-reply",+ parent_id: root.id,+ content: "Offscreen reply target",+ };+ mockVirtualWindow.targetId = target.id;+ mockApiObj.listTimeline.mockResolvedValue(kind === "root" ? history : [...history, target]);+ mockApiObj.listTasksByIssue.mockResolvedValue([]);+ renderIssueDetailWithHighlight(target.id);++ await waitFor(() => expect(hasHighlightedCommentBackground(+ document.getElementById(`comment-${target.id}`),+ )).toBe(true));+ if (lateScrollReset || holdAtIndex) {+ await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 150)); });+ expect(mockVirtualWindow.scrollParent?.scrollTop).toBe(200);+ }+ expect(screen.queryByTestId("virtuoso-mock")).not.toBeNull();+ expect(document.querySelectorAll('[id^="comment-history-"]').length).toBeLessThanOrEqual(8);+ expect(document.getElementById("comment-history-0")).toBeNull();+ expect(scrollIntoViewIndexSpy).toHaveBeenCalledWith(expect.objectContaining({ index: 115 }));+ });++ it("waits for run grouping before consuming the comment landing", async () => {+ let finishTasks!: (tasks: AgentTask[]) => void;+ mockApiObj.listTasksByIssue.mockReturnValue(new Promise<AgentTask[]>((resolve) => { finishTasks = resolve; }));+ renderIssueDetailWithHighlight("comment-2");+ await waitFor(() => expect(document.getElementById("comment-comment-2")).not.toBeNull());+ await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 60)); });+ const landedBeforeGrouping = hasHighlightedCommentBackground(document.getElementById("comment-comment-2"));+ await act(async () => { finishTasks([]); });+ await waitFor(() => expect(hasHighlightedCommentBackground(document.getElementById("comment-comment-2"))).toBe(true));+ expect(landedBeforeGrouping).toBe(false);+ });+it("folds an assignment reply with its resolved parent and unfolds that thread for a notification", async () => {const run: AgentTask = { id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",kind: "direct", status: "completed", priority: 0, created_at: "2026-01-16T00:00:00Z", started_at: null, dispatched_at: null,@@ -2559,10 +2778,7 @@ describe("IssueDetail (shared)", () => {it("scrolls to the highlighted comment after both issue and timeline finish loading", async () => {renderIssueDetailWithHighlight("comment-2");- // Wait for the comment row to mount. With initialItemCount in- // production, items[0..targetIdx] are force-mounted on first commit;- // the mock unconditionally inline-renders every item, so this just- // waits for the regular render pass.+ // Wait for the requested row to mount before checking its highlight.await waitFor(() => {expect(document.getElementById("comment-comment-2"),diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 4bacd6fe07..3ed330e649 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -132,7 +132,7 @@ import {useDeliverableDetails,type DeliverableOrigin,} from "./deliverables/deliverable-details";-import { collectDeliverableFiles } from "@multica/core/attachments/deliverables";+import { collectDeliverableFiles, mergeDeliverableSources } from "@multica/core/attachments/deliverables";import { AttachmentVersionsProvider } from "./deliverables/attachment-versions";import {OpenDeliverableOnLoad,@@ -152,7 +152,7 @@ import {import { useRecentContextStore } from "@multica/core/chat";import { useRegisterCommandBarContext } from "../../search/register-context";import { useModalStore } from "@multica/core/modals";-import { issueListOptions, issueDetailOptions, childIssuesOptions, childIssueProgressOptions, issueAttachmentsOptions } from "@multica/core/issues/queries";+import { issueListOptions, issueDetailOptions, childIssuesOptions, childIssueProgressOptions, issueAttachmentsOptions, issueDeliverablesOptions } from "@multica/core/issues/queries";import { projectDetailOptions } from "@multica/core/projects/queries";import { ProjectIcon } from "../../projects/components/project-icon";import { issueLabelsOptions } from "@multica/core/labels";@@ -201,6 +201,8 @@ import { MetadataSection } from "./metadata-section";import { IssueSidebarSectionHeader, IssueSidebarStack, IssueSidebarPropertyGrid } from "./issue-sidebar-section";import { useT } from "../../i18n";import { useIssueDetailScrollRestore } from "../hooks/use-issue-detail-scroll-restore";+import { useIssueTimelineAnchor } from "../hooks/use-issue-timeline-anchor";+import { scrollToTimelineComment } from "../utils/scroll-to-timeline-comment";import { useJumpToLatest } from "../hooks/use-jump-to-latest";import { useInPageFind } from "../hooks/use-in-page-find";import { useStickyComposer } from "../hooks/use-sticky-composer";@@ -1418,13 +1420,28 @@ export function IssueDetailSkeleton({// IssueDetail-export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, highlightAppRequestId, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false, openDeliverable, onDeliverableLinkDone }: IssueDetailProps) {+export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId: linkedCommentId, highlightRequestToken: linkedRequestToken, highlightAppRequestId, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false, openDeliverable, onDeliverableLinkDone }: IssueDetailProps) {const isPeek = variant === "peek";const { t } = useT("issues");const { t: tCommon } = useT("common");const locale = useLocale();const timeAgo = useTimeAgo();const id = issueId;+ const [deliverableJump, setDeliverableJump] = useState<{+ issueId: string;+ linkedCommentId: string | undefined;+ linkedRequestToken: number | undefined;+ commentId: string;+ token: number;+ } | null>(null);+ const activeDeliverableJump = deliverableJump?.issueId === id &&+ deliverableJump.linkedCommentId === linkedCommentId &&+ deliverableJump.linkedRequestToken === linkedRequestToken ? deliverableJump : null;+ const highlightCommentId = activeDeliverableJump?.commentId ?? linkedCommentId;+ const highlightRequestToken = activeDeliverableJump?.token ?? linkedRequestToken;+ useEffect(() => {+ setDeliverableJump(null);+ }, [id, linkedCommentId, linkedRequestToken]);const user = useAuthStore((s) => s.user);const paths = useWorkspacePaths();const openModal = useModalStore((state) => state.open);@@ -1737,9 +1754,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trtimeline, loading: timelineLoading, dataUpdatedAt: timelineUpdatedAt,submitComment, submitReply,editComment, deleteComment, toggleResolveComment, toggleReaction: handleToggleReaction,- } = useIssueTimeline(id, user?.id);+ } = useIssueTimeline(id, user?.id, activeDeliverableJump?.commentId);- const { data: commentTasks } = useQuery(issueTasksOptions(id));+ const { data: commentTasks, isLoading: commentTasksLoading } = useQuery(issueTasksOptions(id));const enteringRunIds = useNewRunIds(id, commentTasks);const previousCommentRuns = useRef(new Map<string, CommentRun[]>());const { runs: commentRuns, timeline: displayTimeline, standaloneRuns } = useMemo(() => {@@ -1977,10 +1994,42 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr[items, timelineView.threadReplies],);- // When the timeline renders flat (deep-link or in-page find), there is no+ // When in-page find renders the timeline flat, there is no// Virtuoso instance — minimap jumps drive the scroll container directly.- const isFlatTimeline = !!highlightCommentId || find.open;+ const isFlatTimeline = find.open;const virtuosoRef = useRef<VirtuosoHandle>(null);+ const virtualTimelineRef = useRef<HTMLDivElement>(null);+ const [measuredTimelineId, setMeasuredTimelineId] = useState<string | null>(null);+ const handleTimelineHeightChange = useCallback((height: number) => {+ if (height > 0) setMeasuredTimelineId(id);+ }, [id]);+ const pendingHighlight = !!highlightCommentId && consumedHighlightId !== highlightCommentId;+ const { pending: readingAnchor, complete: completeAnchorRestore } = useIssueTimelineAnchor({+ containerKey: scrollContainerKey,+ container: scrollContainerEl,+ ready: !issueLoading && !timelineLoading && !commentTasksLoading,+ skipRestore: isPeek || pendingHighlight,+ });+ useEffect(() => {+ const container = scrollContainerEl;+ if (!readingAnchor || !container || issueLoading || timelineLoading || commentTasksLoading) return;+ let rootId = replyToRoot.get(readingAnchor.commentId) ?? readingAnchor.commentId;+ for (const [threadId, runs] of commentRuns) {+ if (runs.some((run) => run.task.id === readingAnchor.commentId)) { rootId = threadId; break; }+ }+ const index = items.findIndex((item) => item.id === rootId);+ if (index < 0) { completeAnchorRestore(); return; }+ if (!isFlatTimeline && measuredTimelineId !== id) {+ const list = virtualTimelineRef.current;+ if (list) container.scrollTop += list.getBoundingClientRect().top - container.getBoundingClientRect().top;+ return;+ }+ return scrollToTimelineComment({+ container, virtualizer: isFlatTimeline ? null : virtuosoRef.current, index,+ commentId: commentLandingTarget(readingAnchor.commentId, rootId, timelineView.threadReplies.get(rootId) ?? EMPTY_REPLIES),+ offset: readingAnchor.offset, onComplete: completeAnchorRestore,+ });+ }, [readingAnchor, scrollContainerEl, issueLoading, timelineLoading, commentTasksLoading, replyToRoot, commentRuns, items, isFlatTimeline, measuredTimelineId, id, timelineView.threadReplies, completeAnchorRestore]);// Scroll a freshly posted comment into view, aligned so its bottom sits just// above the sticky composer (never behind it). A reply lives inside its root// CommentCard, so the containing top-level row is the scroll target. Flat and@@ -2016,7 +2065,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr};}, [pendingPostedCommentId, items, replyToRoot, isFlatTimeline]);- // Flat mode (find bar / deep link) has no Virtuoso, so drive scrollTop by+ // Flat mode (find bar) has no Virtuoso, so drive scrollTop by// hand: align the row's bottom to the composer's top edge. The comment's// async layout (markdown, code highlight, images) keeps shifting its height,// so re-align each frame until it settles (within 1px) or ~0.5s elapses — the@@ -2256,6 +2305,10 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// `src`/`href` against this list to resolve an attachment id before// calling `/api/attachments/{id}`.const { data: issueAttachments } = useQuery(issueAttachmentsOptions(id));+ const { data: deliverableInventory = EMPTY_REPLIES, error: deliverablesError } = useQuery(issueDeliverablesOptions(id));+ useEffect(() => {+ if (deliverablesError) toast.error(deliverablesError.message);+ }, [deliverablesError]);// Sub-issue queriesconst parentIssueId = issue?.parent_issue_id;@@ -2372,11 +2425,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trconst loading = issueLoading;- // Deep-link landing. Semantically equivalent to navigating to- // `#comment-${id}`: find the element with that id, scrollIntoView it.- // When `highlightCommentId` is set the timeline below renders flat (no- // virtualization), so every comment id is in the DOM by the time this- // effect runs after commit.+ // Deep links keep the timeline virtualized. Mount the enclosing row by+ // index, then center and highlight the exact comment once its anchor exists.//// For a reply or threaded run inside a folded resolved thread, the target// is not in items (only the resolved-bar root is). Auto-expand the thread@@ -2387,7 +2437,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// ref populates only on the post-loading render, so it's the signal that// the timeline (and the deep-link target id) has actually rendered.useEffect(() => {- if (!highlightCommentId || items.length === 0) return;+ if (!highlightCommentId || items.length === 0 || timelineLoading || commentTasksLoading) return;// An explicit replay request (re-click on the already-open notification// row): the host cleared the memento entry and bumped the token, so// re-arm the landing guard and fall through to the jump.@@ -2400,13 +2450,15 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// switch back or an in-tab return). The restored scroll offset is the// state the user left, and the jump must not fight it. A fresh selection// clears the entry, so this only ever suppresses a *repeat* landing.- if (consumedHighlightRef.current === highlightCommentId) {+ if (!activeDeliverableJump && consumedHighlightRef.current === highlightCommentId) {didHighlightRef.current = highlightCommentId;return;}- const rootId = highlightRootId;- if (rootId && rootId !== highlightCommentId) {+ const rootId = highlightRootId ?? highlightCommentId;+ const collapse = useCommentCollapseStore.getState();+ if (collapse.isCollapsed(id, rootId)) collapse.toggle(id, rootId);+ if (rootId) {// Root resolved → the whole thread is a folded bar.const rootItem = items[targetIdx];if (rootItem?.kind === "resolved-bar" || (rootItem?.kind === "run" && rootItem.entry?.resolved_at && !expandedResolved.has(rootId))) {@@ -2437,54 +2489,35 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trthreadRootId,timelineView.threadReplies.get(threadRootId) ?? EMPTY_REPLIES,);- const el = document.getElementById(`comment-${landingId}`);const container = scrollContainerEl;- if (!el || !container) return;-- didHighlightRef.current = highlightCommentId;- // Record the landing in the memento so a remount that merely restores- // this view (tab switch back) skips the jump instead of replaying it- // over the restored scroll position.- writeViewState(issueHighlightMementoKey(id), highlightCommentId);-- // Center the target comment WITHIN its own scroll container by driving the- // container's scrollTop directly — never native scrollIntoView. Native- // scrollIntoView is spec'd to scroll EVERY scrollable ancestor: on a cold- // mount where the timeline is still growing (streaming agent), the inner- // scroller can't satisfy centering on its own, so the scroll propagates up- // and moves the desktop shell's `overflow:hidden` wrapper — shoving the- // whole page, header included, off the top with no scrollbar to recover,- // until a resize reflows it (#3929). Scoping the scroll to `container`- // keeps it contained; re-centering across frames lands the comment- // precisely once async heights (markdown, code highlight, streamed replies)- // settle, instead of leaning on the ancestor scroll the way native did.- let rafId = 0;- let frames = 0;- let last = -1;- const center = () => {- const c = container.getBoundingClientRect();- const e = el.getBoundingClientRect();- const target = Math.max(- 0,- container.scrollTop + (e.top - c.top) - (container.clientHeight - e.height) / 2,- );- container.scrollTop = target;- // Content is still laying out → the centered offset keeps shifting; keep- // re-centering until it stabilizes (within 1px) or we hit ~0.5s of frames.- if (Math.abs(target - last) > 1 && ++frames < 30) {- last = target;- rafId = requestAnimationFrame(center);+ if (!container) return;+ if (!isFlatTimeline) {+ if (targetIdx < 0) return;+ if (measuredTimelineId !== id) {+ // A long description can put the whole list below the scroll viewport.+ // Bring its probe row into view so Virtuoso can measure before jumping.+ const list = virtualTimelineRef.current;+ if (list) container.scrollTop += list.getBoundingClientRect().top - container.getBoundingClientRect().top;+ return;}- };- rafId = requestAnimationFrame(center);+ }- setHighlightedId(landingId);- const fade = window.setTimeout(() => setHighlightedId(null), 2500);+ let fade: number | undefined;+ const cancel = scrollToTimelineComment({+ container, virtualizer: isFlatTimeline ? null : virtuosoRef.current,+ index: targetIdx, commentId: landingId,+ onMounted: () => {+ didHighlightRef.current = highlightCommentId;+ writeViewState(issueHighlightMementoKey(id), highlightCommentId);+ setHighlightedId(landingId);+ fade = window.setTimeout(() => setHighlightedId(null), 2500);+ },+ });return () => {- cancelAnimationFrame(rafId);- clearTimeout(fade);+ cancel();+ if (fade !== undefined) clearTimeout(fade);};- }, [highlightCommentId, highlightRequestToken, id, writeViewState, items, targetIdx, scrollContainerEl, highlightRootId, expandedResolved, timelineView, toggleResolvedExpand]);+ }, [highlightCommentId, highlightRequestToken, activeDeliverableJump, id, writeViewState, items, targetIdx, scrollContainerEl, highlightRootId, expandedResolved, timelineView, toggleResolvedExpand, isFlatTimeline, measuredTimelineId, timelineLoading, commentTasksLoading]);const descEditorRef = useRef<ContentEditorRef>(null);const descriptionEditingRef = useRef(false);@@ -2551,6 +2584,10 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// the whole issue's (comment uploads keep `issue_id`) — it only resolves the// description's own references, or every comment file would be counted at// the description's position.+ const deliverableSources = useMemo(+ () => mergeDeliverableSources(deliverableInventory, timeline),+ [deliverableInventory, timeline],+ );const previewSequence = useMemo(() => {const blocks: ImageSequenceBlock[] = [{@@ -2560,73 +2597,44 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trstandalone: false,},];- for (const item of items) {- if (item.kind === "activity-group" || !item.entry) continue;- blocks.push({- id: item.entry.id,- content: item.entry.content,- attachments: item.entry.attachments,- });- for (const reply of timelineView.threadReplies.get(item.entry.id) ?? []) {- blocks.push({ id: reply.id, content: reply.content, attachments: reply.attachments });- }+ for (const entry of deliverableSources) {+ blocks.push({ id: entry.id, content: entry.content, attachments: entry.attachments });}return collectPreviewSequence(blocks);- }, [issue?.description, descEditorAttachments, items, timelineView.threadReplies]);+ }, [issue?.description, descEditorAttachments, deliverableSources]);// The files this issue has delivered as a whole: the sidebar section, the// overview grid, the viewer's info panel and the comments' version badges// all read this (MUL-7649).- const deliverableFiles = useMemo(() => collectDeliverableFiles(timeline), [timeline]);+ const deliverableFiles = useMemo(() => collectDeliverableFiles(deliverableSources), [deliverableSources]);const commentById = useMemo(() =>new Map(- timeline+ deliverableSources.filter((entry) => entry.type === "comment").map((entry) => [entry.id, entry] as const),),- [timeline],+ [deliverableSources],);- // "Show in comments" from the viewer and the overview. A reply goes through- // the quick-jump rail's path, which already undoes everything that hides one- // (the reader's collapse, a resolution folding the thread) and waits for the- // reply to mount. A root is visible unless its own thread is collapsed or- // folded into a resolved bar: open that, then jump once the open thread has- // rendered, so the flash lands on the comment and not on the bar.- const [locateRootRequest, setLocateRootRequest] = useState<string | null>(null);+ // File origins use the deep-link landing path: load missing thread context,+ // unfold it and wait for virtual rows and their measured heights to settle.const locateOrigin = useCallback((origin: DeliverableOrigin) => {if (origin.kind === "description") {scrollContainerEl?.scrollTo({ top: 0, behavior: "smooth" });return;}- const { commentId } = origin;- if (replyToRoot.has(commentId)) {- jumpToReply(commentId);- return;- }- const rootItem = items.find((it) => it.id === commentId);- const root = rootItem && rootItem.kind !== "activity-group" ? rootItem.entry : undefined;- if (!root) return;- const collapse = useCommentCollapseStore.getState();- if (collapse.isCollapsed(id, commentId)) collapse.toggle(id, commentId);- if (- !expandedResolved.has(commentId) &&- deriveThreadResolution(root, timelineView.threadReplies.get(commentId) ?? EMPTY_REPLIES)- .kind === "root"- ) {- toggleResolvedExpand(commentId, true);- }- setLocateRootRequest(commentId);+ setDeliverableJump((previous) => ({+ issueId: id,+ linkedCommentId,+ linkedRequestToken,+ commentId: origin.commentId,+ token: Math.max(previous?.token ?? 0, linkedRequestToken ?? 0) + 1,+ }));},- [scrollContainerEl, replyToRoot, jumpToReply, items, id, expandedResolved, timelineView.threadReplies, toggleResolvedExpand],+ [scrollContainerEl, id, linkedCommentId, linkedRequestToken],);- useEffect(() => {- if (!locateRootRequest) return;- setLocateRootRequest(null);- jumpToThread(locateRootRequest);- }, [locateRootRequest, jumpToThread]);// Identifier form, like the issue's own copy link: a pasted link should say// which issue it points at.@@ -2837,13 +2845,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trrestoreKey: `${wsId}:${id}`,scrollContainerEl,ready: !!issue && !loading && !timelineLoading,- // Disabled only while the comment deep link still has a landing to run —- // the jump owns the scroll then. Once the landing is consumed (a tab- // switch back), this hook's retry loop IS the restore: the one-shot- // ref-attach assignment clamps against a container whose async content- // (markdown, images) hasn't reached its captured height yet.+ // Comment landings and semantic reading anchors own their scroll. Pixel+ // restoration still covers positions outside the discussion (description,+ // sub-issues) and adapters without a saved timeline anchor.// A peek always opens at the top: it is a glance, not a place to return to.- disabled: isPeek || (!!highlightCommentId && consumedHighlightId !== highlightCommentId),+ disabled: isPeek || pendingHighlight || !!readingAnchor,// The tab memento's offset, when the platform serves one. It must win// over this hook's module-level map — see the parameter doc.overrideTop: restoredScrollTop,@@ -3248,7 +3254,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tronExpand={() => toggleResolvedExpand(reply.id, true)} /> : <AgentRunComment run={item.run} entering={enteringRunIds.has(item.run.task.id)} standalonehighlightedId={highlightedId}commentProps={reply ? {- issueId: id, entry: reply, replies: timelineView.threadReplies.get(reply.id) ?? EMPTY_REPLIES,+ issueId: id, replyScrollParent: isFlatTimeline ? null : scrollContainerEl, entry: reply, replies: timelineView.threadReplies.get(reply.id) ?? EMPTY_REPLIES,currentUserId: user?.id, canModerate: canModerateComments, onReply: submitReply,onReplyAccepted: scrollToTimelineBottom, onEdit: editComment, onDelete: deleteComment,onToggleReaction: handleToggleReaction, onCreateSubIssue: openCommentSubIssue,@@ -3278,6 +3284,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr<div className="pb-3" id={`comment-${item.id}`}><CommentCardissueId={id}+ replyScrollParent={isFlatTimeline ? null : scrollContainerEl}runs={commentRuns.get(item.id) ?? EMPTY_COMMENT_RUNS}enteringRunIds={enteringRunIds}entry={item.entry}@@ -4008,41 +4015,27 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr{timelineLoading && timelineView.groups.length === 0 ? (<TimelineSkeleton />) : (- // Two render modes:- // - `highlightCommentId` set (came from inbox deep-link) →- // render flat. Every comment mounts, every height is real,- // the target id is in the DOM the instant the useEffect- // above runs `scrollIntoView`. No virtualization estimate- // errors, no spacer reflow drift. Pays cold-mount cost- // proportional to items.length (markdown + lowlight per- // comment), which is acceptable in the deep-link case —- // the user has explicit intent to land on a specific item.- // - `find.open` (in-page Cmd/Ctrl+F) → also render flat, so- // every comment is in the DOM for the find walk to match- // and highlight. Same explicit-intent cold-mount trade-off.- // - otherwise → Virtuoso. Browsing mode, virtualization- // wins on first-paint perf for long timelines.- //- // The split is deliberate: virtualization and "land precisely- // on a target" have fundamentally opposed contracts (estimated- // heights vs real heights). Trying to satisfy both in one- // path is what produced the bug history this PR closes.- !highlightCommentId && !find.open ? (+ // Only in-page find needs every row mounted for DOM text search.+ // Browsing and comment deep links keep viewport-sized rendering.+ !isFlatTimeline ? (!scrollContainerEl ? (// Skeleton while the callback ref populates so the gap// between IssueDetail mount and Virtuoso mount doesn't// flash empty.<TimelineSkeleton />) : (- <div className="mt-4">+ <div ref={virtualTimelineRef} className="mt-4"><Virtuosokey={`${wsId}:${id}`}ref={virtuosoRef}customScrollParent={scrollContainerEl}data={items}- initialScrollTop={restoredScrollTop}+ initialScrollTop={readingAnchor ? undefined : restoredScrollTop}increaseViewportBy={{ top: 800, bottom: 800 }}+ totalListHeightChanged={handleTimelineHeightChange}computeItemKey={(_i, item) => `${item.kind}:${item.kind === "run" ? item.run.task.id : item.id}`}+ // Also load-bearing for long threads: keepThreadRowAnchored+ // corrects after Virtuoso's resize handling in the same frame.skipAnimationFrameInResizeObserver// followOutput intentionally NOT set. Virtuoso treats// it as a sticky "is at bottom" flag and resetsdiff --git a/packages/views/issues/components/issue-runs-dialog.test.tsx b/packages/views/issues/components/issue-runs-dialog.test.tsxindex 4908a77a77..999a4db9fc 100644--- a/packages/views/issues/components/issue-runs-dialog.test.tsx+++ b/packages/views/issues/components/issue-runs-dialog.test.tsx@@ -64,7 +64,7 @@ function usage(overrides: Partial<TaskUsage> = {}): TaskUsage {function open(tasks: AgentTask[], locale?: "zh-Hans") {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });- queryClient.setQueryData(issueKeys.tasks("issue-1"), tasks);+ queryClient.setQueryData([...issueKeys.tasks("issue-1"), "history"], tasks);return renderWithI18n(<QueryClientProvider client={queryClient}><IssueRunsDialogdiff --git a/packages/views/issues/components/issue-runs-dialog.tsx b/packages/views/issues/components/issue-runs-dialog.tsxindex 8561a6f9aa..899f8ac53a 100644--- a/packages/views/issues/components/issue-runs-dialog.tsx+++ b/packages/views/issues/components/issue-runs-dialog.tsx@@ -141,7 +141,7 @@ function IssueRunsDialogContent({const [includeChildren, setIncludeChildren] = useState(includeDescendants);const scopeLabelId = useId();const { data: tasks = [], isPending, isError, refetch } = useQuery(- issueTasksOptions(issueId, includeChildren),+ issueTasksOptions(issueId, includeChildren, "history"),);// `estimateCost` reads custom rates imperatively out of the Zustand store,// so nothing re-renders this dialog when the user saves a new rate. Subscribediff --git a/packages/views/issues/components/virtual-thread-row.test.tsx b/packages/views/issues/components/virtual-thread-row.test.tsxnew file mode 100644index 0000000000..940f618686--- /dev/null+++ b/packages/views/issues/components/virtual-thread-row.test.tsx@@ -0,0 +1,48 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, render, screen } from "@testing-library/react";+import { VirtualThreadRow } from "./virtual-thread-row";++let notify: IntersectionObserverCallback;+let observed: Element;+beforeEach(() => {+ vi.stubGlobal("IntersectionObserver", class {+ constructor(callback: IntersectionObserverCallback) { notify = callback; }+ observe(node: Element) { observed = node; }+ disconnect() {}+ });+});+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });+const intersect = (visible: boolean) => act(() => notify([+ { target: observed, isIntersecting: visible } as IntersectionObserverEntry,+], {} as IntersectionObserver));++describe("VirtualThreadRow", () => {+ it("keeps an anchor and measured height while unmounting offscreen content", () => {+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 400, 640));+ const body = vi.fn(() => <p>Expensive Markdown</p>);+ const { container } = render(<VirtualThreadRow id="comment-target" scrollParent={document.body}>{body}</VirtualThreadRow>);+ expect(body).not.toHaveBeenCalled();+ expect(container.querySelector("#comment-target")).toHaveStyle({ height: "320px" });+ intersect(true);+ expect(screen.getByText("Expensive Markdown")).toBeInTheDocument();+ intersect(false);+ expect(screen.queryByText("Expensive Markdown")).toBeNull();+ expect(container.querySelector("#comment-target")).toHaveStyle({ height: "640px" });+ intersect(true);+ expect(screen.getByText("Expensive Markdown")).toBeInTheDocument();+ });++ it("retains an offscreen edit instead of unmounting its draft", () => {+ render(<VirtualThreadRow id="comment-edit" scrollParent={document.body}>+ {() => <div contentEditable suppressContentEditableWarning>Unsaved draft</div>}+ </VirtualThreadRow>);+ intersect(true);+ intersect(false);+ expect(screen.getByText("Unsaved draft")).toBeInTheDocument();+ });++ it("renders all content without a scroll parent for in-page find", () => {+ render(<VirtualThreadRow id="comment-find">{() => <p>Findable history</p>}</VirtualThreadRow>);+ expect(screen.getByText("Findable history")).toBeInTheDocument();+ });+});diff --git a/packages/views/issues/components/virtual-thread-row.tsx b/packages/views/issues/components/virtual-thread-row.tsxnew file mode 100644index 0000000000..8b1a9c0224--- /dev/null+++ b/packages/views/issues/components/virtual-thread-row.tsx@@ -0,0 +1,63 @@+"use client";++import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";+import { keepThreadRowAnchored } from "../utils/keep-thread-rows-anchored";++/** Keep anchors addressable without parsing every offscreen Markdown reply. */+export function VirtualThreadRow({ id, taskId, scrollParent, children }: {+ id: string;+ taskId?: string;+ scrollParent?: HTMLElement | null;+ children: () => ReactNode;+}) {+ const ref = useRef<HTMLDivElement>(null);+ const height = useRef(320);+ const [visible, setVisible] = useState(false);+ const mounted = !scrollParent || visible;++ useEffect(() => {+ const node = ref.current;+ if (!node || !scrollParent) return;+ if (typeof IntersectionObserver !== "function") {+ setVisible(true);+ return;+ }+ const observer = new IntersectionObserver((entries) => {+ const intersecting = entries.at(-1)?.isIntersecting ?? false;+ // Editing and open controls own transient state; don't discard it on scroll.+ const engaged = node.contains(document.activeElement)+ || !!node.querySelector('[contenteditable="true"], [aria-expanded="true"]');+ setVisible(intersecting || engaged);+ }, { root: scrollParent, rootMargin: "800px 0px" });+ observer.observe(node);+ return () => observer.disconnect();+ }, [scrollParent]);++ // The placeholder's height becomes the real one in this commit. Keep the+ // content below a row above the viewport from moving (see the helper).+ useLayoutEffect(() => {+ const node = ref.current;+ if (!node || !visible || !scrollParent) return;+ keepThreadRowAnchored(scrollParent, node, height.current);+ }, [visible, scrollParent]);++ useEffect(() => {+ const node = ref.current;+ if (!node || !mounted) return;+ const measure = () => {+ const next = node.getBoundingClientRect().height;+ if (next > 0) height.current = next;+ };+ measure();+ if (typeof ResizeObserver !== "function") return;+ const observer = new ResizeObserver(measure);+ observer.observe(node);+ return () => observer.disconnect();+ }, [mounted]);++ return <div ref={ref} id={id} data-run-slot-id={taskId}+ data-virtual-thread-row data-virtual-thread-mounted={mounted}+ style={mounted ? undefined : { height: height.current }}>+ {mounted ? children() : null}+ </div>;+}diff --git a/packages/views/issues/hooks/use-issue-timeline-anchor.ts b/packages/views/issues/hooks/use-issue-timeline-anchor.tsnew file mode 100644index 0000000000..e11d4620ce--- /dev/null+++ b/packages/views/issues/hooks/use-issue-timeline-anchor.ts@@ -0,0 +1,73 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useRestoredViewState, useViewStateWriter } from "../../platform";++interface TimelineAnchor { commentId: string; offset: number }+interface AnchorSnapshot { key: string; anchor: TimelineAnchor | null }++function readAnchor(value: string | undefined): TimelineAnchor | null {+ if (!value) return null;+ try {+ const anchor: unknown = JSON.parse(value);+ if (typeof anchor !== "object" || !anchor || !("commentId" in anchor) || !("offset" in anchor)) return null;+ return typeof anchor.commentId === "string" && /^[A-Za-z0-9_-]+$/.test(anchor.commentId)+ && typeof anchor.offset === "number" && Number.isFinite(anchor.offset)+ ? { commentId: anchor.commentId, offset: anchor.offset } : null;+ } catch { return null; }+}++/** Keep reading position in the platform's route/tab memento, not in pixel estimates. */+export function useIssueTimelineAnchor({+ containerKey, container, ready, skipRestore,+}: {+ containerKey: string;+ container: HTMLElement | null;+ ready: boolean;+ skipRestore: boolean;+}) {+ const key = `timeline-anchor:${containerKey}`;+ const saved = useRestoredViewState(key);+ const write = useViewStateWriter();+ const snapshotRef = useRef<AnchorSnapshot | null>(null);+ if (snapshotRef.current?.key !== key) snapshotRef.current = { key, anchor: readAnchor(saved) };+ const snapshot = snapshotRef.current;+ // A fresh notification selection owns the landing, even after it marks its+ // highlight consumed. It must not revive the previous reading position.+ if (skipRestore) snapshot.anchor = null;+ const [completed, setCompleted] = useState<AnchorSnapshot | null>(null);+ const pending = completed !== snapshot ? snapshot.anchor : null;+ const complete = useCallback(() => setCompleted(snapshot), [snapshot]);++ useEffect(() => {+ if (!container || !ready || skipRestore || pending) return;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const capture = () => {+ const c = container.getBoundingClientRect();+ if (!c.width || !c.height || typeof document.elementFromPoint !== "function") return;+ // Hit testing finds the visible reply without measuring every offscreen+ // placeholder on each scroll of a long thread.+ const el = document.elementFromPoint(c.left + c.width / 2, c.top + c.height / 2)+ ?.closest<HTMLElement>('[id^="comment-"]');+ const anchor = el && container.contains(el)+ ? { commentId: el.id.slice("comment-".length), offset: el.getBoundingClientRect().top - c.top }+ : null;+ write(key, anchor ? JSON.stringify(anchor) : undefined);+ };+ // Desktop commits view state through its tab store. Save after scrolling+ // settles, and before navigation input, instead of updating that store on+ // every animation frame.+ const schedule = () => { clearTimeout(timer); timer = setTimeout(capture, 100); };+ container.addEventListener("scroll", schedule, { passive: true });+ document.addEventListener("pointerdown", capture, true);+ document.addEventListener("keydown", capture, true);+ const frame = requestAnimationFrame(capture);+ return () => {+ clearTimeout(timer);+ cancelAnimationFrame(frame);+ container.removeEventListener("scroll", schedule);+ document.removeEventListener("pointerdown", capture, true);+ document.removeEventListener("keydown", capture, true);+ };+ }, [container, ready, skipRestore, pending, key, write]);++ return { pending, complete };+}diff --git a/packages/views/issues/hooks/use-issue-timeline.test.tsx b/packages/views/issues/hooks/use-issue-timeline.test.tsxindex 73be2991e3..3c75731325 100644--- a/packages/views/issues/hooks/use-issue-timeline.test.tsx+++ b/packages/views/issues/hooks/use-issue-timeline.test.tsx@@ -48,6 +48,10 @@ vi.mock("@multica/core/issues/mutations", () => ({}));vi.mock("@multica/core/issues/queries", () => ({+ issueCommentThreadOptions: (id: string, commentId: string) => ({+ queryKey: ["issues", "timeline", id, "thread", commentId],+ queryFn: () => Promise.resolve([]),+ }),issueTimelineOptions: (id: string) => ({queryKey: ["issues", "timeline", id],queryFn: () => Promise.resolve([]),@@ -77,9 +81,9 @@ vi.mock("@tanstack/react-query", async () => {);return {...actual,- useQuery: () => ({- data: queryState.data,- isLoading: queryState.isLoading,+ useQuery: (options: { queryKey: string[] }) => ({+ data: options.queryKey.includes("thread") ? undefined : queryState.data,+ isLoading: options.queryKey.includes("thread") ? false : queryState.isLoading,}),useQueryClient: () => ({invalidateQueries: vi.fn(() => {diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.tsindex d2ced295b2..84b88d5e1b 100644--- a/packages/views/issues/hooks/use-issue-timeline.ts+++ b/packages/views/issues/hooks/use-issue-timeline.ts@@ -24,6 +24,7 @@ import type {} from "@multica/core/types";import {issueTimelineOptions,+ issueCommentThreadOptions,issueKeys,} from "@multica/core/issues/queries";import {@@ -34,6 +35,7 @@ import {useToggleCommentReaction,type ToggleCommentReactionVars,} from "@multica/core/issues/mutations";+import { commentToTimelineEntry, mergeCommentThread } from "@multica/core/issues/comment-thread";import { sortTimelineEntriesAsc } from "@multica/core/issues/timeline-sort";import {unhandledCommentTriggerOutcomes,@@ -47,32 +49,6 @@ import { blockedShortReasonLabel } from "../blocked-trigger-copy";type TLCache = TimelineEntry[];-function commentToTimelineEntry(c: Comment): TimelineEntry {- return {- type: "comment",- id: c.id,- actor_type: c.author_type,- actor_id: c.author_id,- content: c.content,- parent_id: c.parent_id,- created_at: c.created_at,- updated_at: c.updated_at,- revision: c.revision,- comment_type: c.type,- reactions: c.reactions ?? [],- attachments: c.attachments ?? [],- resolved_at: c.resolved_at,- resolved_by_type: c.resolved_by_type,- resolved_by_id: c.resolved_by_id,- source_task_id: c.source_task_id,- supplements: c.supplements,- supplement_task_id: c.supplement_task_id,- supplement_status: c.supplement_status,- supplement_failure_reason: c.supplement_failure_reason,- supplement_delivered_at: c.supplement_delivered_at,- deleted_at: c.deleted_at,- };-}function acceptsCommentRevision(current: TimelineEntry,@@ -114,14 +90,25 @@ function applyCommentSnapshot(}}-export function useIssueTimeline(issueId: string, userId?: string) {+export function useIssueTimeline(issueId: string, userId?: string, focusCommentId?: string) {const { t } = useT("issues");const qc = useQueryClient();const query = useQuery(issueTimelineOptions(issueId));const { data, isLoading: loading, dataUpdatedAt } = query;- const timeline = useMemo<TimelineEntry[]>(() => data ?? [], [data]);+ const needsThread = !!focusCommentId && !loading && !data?.some((entry) => entry.id === focusCommentId);+ const threadQuery = useQuery({+ ...issueCommentThreadOptions(issueId, focusCommentId ?? ""),+ enabled: needsThread,+ });+ useEffect(() => {+ if (threadQuery.error && needsThread) toast.error(t(($) => $.detail.load_failed));+ }, [threadQuery.error, needsThread, t]);+ const timeline = useMemo<TimelineEntry[]>(+ () => mergeCommentThread(data ?? [], threadQuery.data ?? []),+ [data, threadQuery.data],+ );// Stable mutation handles. TanStack v5 returns a fresh result wrapper from// useMutation per render, but the inner mutateAsync / mutate functions are@@ -524,7 +511,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {return {timeline: optimisticTimeline,- loading,+ loading: loading || (needsThread && threadQuery.isPending),/*** When the cached timeline was last written (Query's `dataUpdatedAt`).* Lets a caller tell whether `timeline` already reflects a read itdiff --git a/packages/views/issues/utils/keep-thread-rows-anchored.test.ts b/packages/views/issues/utils/keep-thread-rows-anchored.test.tsnew file mode 100644index 0000000000..2ebfd3469d--- /dev/null+++ b/packages/views/issues/utils/keep-thread-rows-anchored.test.ts@@ -0,0 +1,82 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { keepThreadRowAnchored } from "./keep-thread-rows-anchored";++// Geometry lives in content coordinates; the viewport is [scrollTop, scrollTop + 500].+let observers: { callback: ResizeObserverCallback; disconnected: boolean }[] = [];+beforeEach(() => {+ observers = [];+ vi.stubGlobal("ResizeObserver", class {+ entry: { callback: ResizeObserverCallback; disconnected: boolean };+ constructor(callback: ResizeObserverCallback) { this.entry = { callback, disconnected: false }; observers.push(this.entry); }+ observe() {}+ disconnect() { this.entry.disconnected = true; }+ });+});+afterEach(() => { vi.unstubAllGlobals(); document.body.innerHTML = ""; });++function thread(heights: number[], scrollTop: number) {+ const container = document.createElement("div");+ const rows = heights.map(() => {+ const row = document.createElement("div");+ row.setAttribute("data-virtual-thread-row", "");+ container.append(row);+ return row;+ });+ document.body.append(container);+ let top = scrollTop;+ Object.defineProperty(container, "scrollTop", { get: () => top, set: (v: number) => { top = v; } });+ container.getBoundingClientRect = () => new DOMRect(0, 0, 400, 500);+ rows.forEach((row, i) => {+ row.getBoundingClientRect = () => {+ const offset = heights.slice(0, i).reduce((a, b) => a + b, 0);+ return new DOMRect(0, offset - top, 400, heights[i]);+ };+ });+ return { container, rows, heights, scroll: () => top };+}++async function frame() {+ await Promise.resolve();+ for (const o of observers.filter((o) => !o.disconnected)) o.callback([], {} as ResizeObserver);+}++describe("keepThreadRowAnchored", () => {+ it("follows a reply above the viewport that mounts shorter than its estimate", async () => {+ const t = thread([84, 320, 84, 84], 600);+ t.heights[1] = 84; // mounted: 320 → 84, wholly above the viewport (offset 84..404)+ keepThreadRowAnchored(t.container, t.rows[1]!, 320);+ await frame();+ expect(t.scroll()).toBe(364);+ });++ it("leaves the position alone when the list already compensated", async () => {+ const t = thread([84, 320, 84, 84], 600);+ t.heights[1] = 84;+ keepThreadRowAnchored(t.container, t.rows[1]!, 320);+ await Promise.resolve();+ t.container.scrollTop = 364; // Virtuoso's own compensation in its earlier observer+ for (const o of observers) o.callback([], {} as ResizeObserver);+ expect(t.scroll()).toBe(364);+ });++ it("undoes a list compensation for a reply that mounted in or below the viewport", async () => {+ const t = thread([400, 84, 320, 84], 300);+ t.heights[2] = 84; // offset 484, inside the viewport+ keepThreadRowAnchored(t.container, t.rows[2]!, 320);+ await Promise.resolve();+ t.container.scrollTop = 64; // a whole-item compensation the reader must not see+ for (const o of observers) o.callback([], {} as ResizeObserver);+ expect(t.scroll()).toBe(300);+ });++ it("batches rows mounted in one commit", async () => {+ const t = thread([320, 320, 84, 84], 700);+ t.heights[0] = 84;+ t.heights[1] = 84;+ keepThreadRowAnchored(t.container, t.rows[0]!, 320);+ keepThreadRowAnchored(t.container, t.rows[1]!, 320);+ await frame();+ expect(t.scroll()).toBe(228);+ expect(observers).toHaveLength(1);+ });+});diff --git a/packages/views/issues/utils/keep-thread-rows-anchored.ts b/packages/views/issues/utils/keep-thread-rows-anchored.tsnew file mode 100644index 0000000000..67062d7528--- /dev/null+++ b/packages/views/issues/utils/keep-thread-rows-anchored.ts@@ -0,0 +1,77 @@+/**+ * Keep the reader's content still when thread replies swap their placeholder+ * height for their real one.+ *+ * Virtuoso sees a long thread as ONE item, so it cannot tell where inside the+ * thread a size change happened. Its upward-scroll compensation shifts by the+ * whole item's change, and only on some frames (scrolling up, not at the+ * bottom, no scroll in progress); its list also opts out of native scroll+ * anchoring. A reply above the viewport that mounts shorter than its estimate+ * therefore sometimes moves everything below it, and a reply below the+ * viewport sometimes moves the content it should not touch.+ *+ * So the outcome is measured instead of predicting Virtuoso:+ *+ * 1. After React commits the newly mounted rows (a microtask, before the frame+ * renders), pick the row or item the reading position hangs on and record+ * where it must stay: shifted only by the rows that lay wholly above the+ * viewport, never by rows inside or below it.+ * 2. A one-shot ResizeObserver, created after Virtuoso's, runs after its+ * synchronous resize handling (`skipAnimationFrameInResizeObserver`) in the+ * same frame, and applies whatever residual remains to `scrollTop` — before+ * the frame paints, whether Virtuoso compensated, skipped or overshot.+ */++interface PendingRow { row: HTMLElement; previousHeight: number }++const batches = new WeakMap<HTMLElement, PendingRow[]>();+const ANCHOR_CANDIDATES = "[data-virtual-thread-row], [data-item-index]";++/** Called from a row's layout effect when its real content first replaces its placeholder. */+export function keepThreadRowAnchored(container: HTMLElement, row: HTMLElement, previousHeight: number) {+ if (typeof ResizeObserver !== "function") return;+ const pending = batches.get(container);+ if (pending) { pending.push({ row, previousHeight }); return; }+ batches.set(container, [{ row, previousHeight }]);+ queueMicrotask(() => {+ const rows = batches.get(container) ?? [];+ batches.delete(container);+ settle(container, rows);+ });+}++function settle(container: HTMLElement, pending: PendingRow[]) {+ const viewportTop = container.getBoundingClientRect().top;+ const ordered = pending+ .filter(({ row }) => row.isConnected && container.contains(row))+ .sort((a, b) => (a.row.compareDocumentPosition(b.row) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1));+ // Positions are read after the commit; undo the earlier rows' changes to+ // recover each row's pre-change box.+ let shiftAbove = 0;+ let lastAbove: HTMLElement | null = null;+ for (const { row, previousHeight } of ordered) {+ const rect = row.getBoundingClientRect();+ const previousBottom = rect.top - shiftAbove + previousHeight;+ const delta = rect.height - previousHeight;+ if (previousBottom > viewportTop) break;+ shiftAbove += delta;+ lastAbove = row;+ }+ // The row or timeline item the reader's position hangs on: the first one after+ // the last changed row above the viewport (every change before it was above+ // the viewport, so it must not move on screen), else the first one in view.+ const candidates = [...container.querySelectorAll<HTMLElement>(ANCHOR_CANDIDATES)];+ const anchor = lastAbove+ ? candidates.find((el) => !el.contains(lastAbove!) && !!(lastAbove!.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING))+ : candidates.find((el) => el.getBoundingClientRect().top >= viewportTop);+ if (!anchor) return;+ const expectedTop = anchor.getBoundingClientRect().top - shiftAbove;++ const observer = new ResizeObserver(() => {+ observer.disconnect();+ if (!anchor.isConnected) return;+ const residual = anchor.getBoundingClientRect().top - expectedTop;+ if (Math.abs(residual) >= 1) container.scrollTop += residual;+ });+ observer.observe(anchor);+}diff --git a/packages/views/issues/utils/scroll-to-timeline-comment.ts b/packages/views/issues/utils/scroll-to-timeline-comment.tsnew file mode 100644index 0000000000..46ac656991--- /dev/null+++ b/packages/views/issues/utils/scroll-to-timeline-comment.ts@@ -0,0 +1,72 @@+import type { VirtuosoHandle } from "react-virtuoso";++/** Reveal a nested anchor before aligning it against measured reply content. */+export function scrollToTimelineComment({+ container, virtualizer, index, commentId, offset, onMounted, onComplete,+}: {+ container: HTMLElement;+ virtualizer: VirtuosoHandle | null;+ index: number;+ commentId: string;+ /** Comment top relative to the viewport; omitted to center comments that fit. */+ offset?: number;+ onMounted?: () => void;+ onComplete?: () => void;+}) {+ let rafId = 0;+ let mountFrames = 0;+ let frames = 0;+ let last = -1;+ let cancelled = false;+ let mounted = false;+ const alignTarget = (el: HTMLElement, reveal = false) => {+ const c = container.getBoundingClientRect();+ const e = el.getBoundingClientRect();+ const thread = el.closest<HTMLElement>("[data-item-index]") ?? el.parentElement?.closest<HTMLElement>('[id^="comment-"]');+ const stickyBar = thread?.querySelector<HTMLElement>("[data-thread-sticky-bar]");+ const headerHeight = stickyBar && !el.contains(stickyBar) ? stickyBar.offsetHeight : 0;+ // Keep a tall comment's beginning visible below its enclosing sticky bar.+ // Centering its full height would put its header above the viewport.+ const centeredOffset = Math.max(16 + headerHeight, (container.clientHeight - e.height) / 2);+ const viewportOffset = reveal || offset === undefined ? centeredOffset : offset;+ const target = Math.max(0, container.scrollTop + e.top - c.top - viewportOffset);+ const row = virtualizer ? el.closest<HTMLElement>("[data-item-index]") : null;+ if (row) {+ // Redirect the list's pending size corrections to the nested reply.+ virtualizer?.scrollToIndex({+ index, align: "start", offset: e.top - row.getBoundingClientRect().top - viewportOffset,+ });+ }+ // Native scrollIntoView also scrolls ancestors and can move the desktop+ // shell offscreen (#3929). Only the timeline owns this scroll.+ container.scrollTop = target;+ return target;+ };+ const land = () => {+ const el = container.querySelector<HTMLElement>(`[id="comment-${commentId}"]`);+ if (!el || el.dataset.virtualThreadMounted === "false") {+ if (el) alignTarget(el, true);+ if (++mountFrames < 60) rafId = requestAnimationFrame(land);+ else onComplete?.();+ return;+ }+ if (!mounted) { mounted = true; onMounted?.(); }+ const align = () => {+ const target = alignTarget(el);+ if (Math.abs(target - last) > 1 && ++frames < 30) {+ last = target;+ rafId = requestAnimationFrame(align);+ } else onComplete?.();+ };+ rafId = requestAnimationFrame(align);+ };+ const queueLanding = () => {+ if (cancelled) return;+ cancelAnimationFrame(rafId);+ rafId = requestAnimationFrame(land);+ };+ virtualizer?.scrollIntoView({ index, align: "start", done: queueLanding });+ // Reply bodies can resize the thread before Virtuoso calls done.+ queueLanding();+ return () => { cancelled = true; cancelAnimationFrame(rafId); };+}diff --git a/packages/views/modals/create-project-local-mode.test.tsx b/packages/views/modals/create-project-local-mode.test.tsxindex 88b1e38300..4bd5646230 100644--- a/packages/views/modals/create-project-local-mode.test.tsx+++ b/packages/views/modals/create-project-local-mode.test.tsx@@ -62,6 +62,12 @@ vi.mock("@tanstack/react-query", () => ({queryOptions: (options: unknown) => options,}));+// The access picker needs the signed-in creator when deriving draft members.+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (selector: (state: { user: { id: string } }) => unknown) =>+ selector({ user: { id: "user-1" } }),+}));+vi.mock("@multica/core/projects/mutations", () => ({useCreateProject: () => ({ mutateAsync: createProjectMock }),}));diff --git a/packages/views/modals/create-project.test.tsx b/packages/views/modals/create-project.test.tsxindex c07d9cd48a..a3085fdab9 100644--- a/packages/views/modals/create-project.test.tsx+++ b/packages/views/modals/create-project.test.tsx@@ -19,6 +19,12 @@ vi.mock("@tanstack/react-query", () => ({const createProjectMock = vi.hoisted(() => vi.fn().mockResolvedValue({ id: "p1" }));+// The access picker needs the signed-in creator when deriving draft members.+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (selector: (state: { user: { id: string } }) => unknown) =>+ selector({ user: { id: "user-1" } }),+}));+vi.mock("@multica/core/projects/mutations", () => ({useCreateProject: () => ({ mutateAsync: createProjectMock }),}));diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 361b099486..68d44ea3d1 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2170,6 +2170,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/reactions", h.AddIssueReaction)r.Delete("/reactions", h.RemoveIssueReaction)r.Get("/attachments", h.ListAttachments)+ r.Get("/deliverables", h.ListIssueDeliverables)r.Get("/children", h.ListChildIssues)r.Get("/duplicates", h.ListIssueDuplicates)r.Get("/labels", h.ListLabelsForIssue)diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex c90161d461..4977409cdc 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -6319,6 +6319,12 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {return}+ view := r.URL.Query().Get("view")+ if view != "" && view != "timeline" {+ writeError(w, http.StatusBadRequest, "view must be 'timeline' when specified")+ return+ }+scope := r.URL.Query().Get("scope")if scope != "" && scope != "issue" && scope != "family" && scope != "subtree" {writeError(w, http.StatusBadRequest, "scope must be 'issue', 'family', or 'subtree'")@@ -6447,6 +6453,11 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {return}}+ if view == "timeline" {+ for i := range resp {+ resp[i] = issueTimelineTaskResponse(resp[i])+ }+ }writeJSON(w, http.StatusOK, resp)}@@ -6473,6 +6484,18 @@ func (h *Handler) hydrateSubtreeTaskUsage(ctx context.Context, tasks []db.AgentTattachTaskUsage(resp, byTask)}+// issueTimelineTaskResponse keeps inline replies, lineage, controls and pricing.+// Provider output and daemon handoff instructions belong to on-demand history.+func issueTimelineTaskResponse(task AgentTaskResponse) AgentTaskResponse {+ task.HandoffNote = ""+ result, _ := task.Result.(map[string]any)+ task.Result = nil+ if comment, ok := result["comment"].(string); ok {+ task.Result = map[string]any{"comment": comment}+ }+ return task+}+// hydrateTaskUsage attaches each run's own token usage to the execution-log// rows. One query for the whole issue, then a map join — not one query per// task, which would be an N+1 over a list the UI always renders in full.diff --git a/server/internal/handler/issue_deliverables.go b/server/internal/handler/issue_deliverables.gonew file mode 100644index 0000000000..2a00810f2c--- /dev/null+++ b/server/internal/handler/issue_deliverables.go@@ -0,0 +1,68 @@+package handler++import (+ "log/slog"+ "net/http"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// ListIssueDeliverables returns every live comment's attachments independently+// of the bounded timeline, without transferring historical comment bodies.+func (h *Handler) ListIssueDeliverables(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ attachments, err := h.Queries.ListAttachmentsByIssue(r.Context(), db.ListAttachmentsByIssueParams{IssueID: issue.ID, WorkspaceID: issue.WorkspaceID})+ if err != nil {+ slog.Error("failed to list deliverables", "error", err)+ writeError(w, http.StatusInternalServerError, "failed to list deliverables")+ return+ }+ ids := make([]pgtype.UUID, 0)+ seen := make(map[pgtype.UUID]bool)+ byComment := make(map[string][]AttachmentResponse)+ mode := attachmentURLModeFromRequest(r)+ for _, a := range attachments {+ if !a.CommentID.Valid {+ continue+ }+ if !seen[a.CommentID] {+ ids = append(ids, a.CommentID)+ seen[a.CommentID] = true+ }+ key := uuidToString(a.CommentID)+ byComment[key] = append(byComment[key], h.attachmentToResponse(a, mode))+ }+ if len(ids) == 0 {+ writeJSON(w, http.StatusOK, []TimelineEntry{})+ return+ }+ comments, err := h.Queries.ListCommentsByIDsForIssue(r.Context(), db.ListCommentsByIDsForIssueParams{Ids: ids, IssueID: issue.ID, WorkspaceID: issue.WorkspaceID})+ if err != nil {+ slog.Error("failed to load deliverable origins", "error", err)+ writeError(w, http.StatusInternalServerError, "failed to list deliverables")+ return+ }+ writeJSON(w, http.StatusOK, issueDeliverableEntries(comments, byComment))+}++func issueDeliverableEntries(comments []db.Comment, attachments map[string][]AttachmentResponse) []TimelineEntry {+ entries := make([]TimelineEntry, 0, len(comments))+ for _, c := range comments {+ id := uuidToString(c.ID)+ if c.DeletedAt.Valid || len(attachments[id]) == 0 {+ continue+ }+ entry := TimelineEntry{Type: "comment", ID: id, ActorType: c.AuthorType, ActorID: uuidToString(c.AuthorID), CreatedAt: c.CreatedAt.Time.Format("2006-01-02T15:04:05Z07:00"), Attachments: attachments[id]}+ if c.ParentID.Valid {+ parent := uuidToString(c.ParentID)+ entry.ParentID = &parent+ }+ entries = append(entries, entry)+ }+ return entries+}diff --git a/server/internal/handler/issue_deliverables_test.go b/server/internal/handler/issue_deliverables_test.gonew file mode 100644index 0000000000..bf7a5e78b8--- /dev/null+++ b/server/internal/handler/issue_deliverables_test.go@@ -0,0 +1,29 @@+package handler++import (+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "testing"+ "time"+)++func TestIssueDeliverableEntries(t *testing.T) {+ id := parseUUID("00000000-0000-0000-0000-000000000001")+ gone := parseUUID("00000000-0000-0000-0000-000000000002")+ parent := parseUUID("00000000-0000-0000-0000-000000000003")+ comments := []db.Comment{+ {ID: id, AuthorType: "agent", AuthorID: parent, ParentID: parent, Content: "large historical body", CreatedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true}},+ {ID: gone, DeletedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true}},+ }+ files := map[string][]AttachmentResponse{uuidToString(id): {{ID: "old-chart", ContentType: "image/png"}, {ID: "same-name-new-version", ContentType: "image/png"}}, uuidToString(gone): {{ID: "deleted-image"}}, "orphan": {{ID: "orphan-image"}}}+ out := issueDeliverableEntries(comments, files)+ if len(out) != 1 || len(out[0].Attachments) != 2 {+ t.Fatalf("must retain all live uploads, omit deleted/orphan sources: %#v", out)+ }+ if out[0].Content != nil || out[0].ActorID != uuidToString(parent) || out[0].ParentID == nil {+ t.Fatal("return lightweight origin metadata without comment bodies")+ }+ if len(issueDeliverableEntries(nil, files)) != 0 {+ t.Fatal("an unbound attachment is not an output")+ }+}diff --git a/server/internal/handler/issue_timeline_task_test.go b/server/internal/handler/issue_timeline_task_test.gonew file mode 100644index 0000000000..3738c7cfe1--- /dev/null+++ b/server/internal/handler/issue_timeline_task_test.go@@ -0,0 +1,30 @@+package handler++import "testing"++func TestIssueTimelineTaskResponse(t *testing.T) {+ full := AgentTaskResponse{+ ID: "task", AgentID: "agent", Status: "completed", HandoffNote: "private handoff",+ Result: map[string]any{"comment": "inline reply", "output": "large provider output", "session_id": "session"},+ DeliveredCommentIDs: []string{"input"},+ Usage: []TaskUsageData{{Provider: "codex"}},+ }+ index := issueTimelineTaskResponse(full)+ if index.ID != full.ID || index.Status != full.Status || index.AgentID != full.AgentID {+ t.Fatal("timeline view must preserve run identity and status")+ }+ result, ok := index.Result.(map[string]any)+ if !ok || len(result) != 1 || result["comment"] != "inline reply" {+ t.Fatalf("inline reply must remain available, got %#v", index.Result)+ }+ if index.HandoffNote != "" || len(index.DeliveredCommentIDs) != 1 || len(index.Usage) != 1 {+ t.Fatal("omit handoff instructions, preserve delivery and usage")+ }+ if full.HandoffNote == "" || len(full.Result.(map[string]any)) != 3 {+ t.Fatal("projection must not mutate full history")+ }+ full.Result = map[string]any{"output": "provider-only output"}+ if issueTimelineTaskResponse(full).Result != nil {+ t.Fatal("provider-only output must not enter the timeline index")+ }+}diff --git a/server/internal/handler/private_project_test.go b/server/internal/handler/private_project_test.goindex 008fc16515..b4cebfb5c0 100644--- a/server/internal/handler/private_project_test.go+++ b/server/internal/handler/private_project_test.go@@ -202,22 +202,25 @@ func TestPrivateProjectSubtreeRunsAreRedacted(t *testing.T) {agentID := dbfx.Agent(t, f.marker+" subtree agent", testRuntimeID, testutil.Cols{"owner_id": f.insider})taskID := dbfx.Task(t, agentID, testutil.Cols{"issue_id": f.secretIssue, "runtime_id": testRuntimeID, "status": "completed",- "result": testutil.Raw(`'{"output":"private subtree result"}'::jsonb`),+ "result": testutil.Raw(`'{"output":"private subtree result","comment":"private inline result"}'::jsonb`),+ "handoff_note": "private handoff",})- for _, userID := range []string{f.outsider, f.insider, testUserID} {- req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+f.publicIssue+"/task-runs?scope=subtree", nil), userID), "id", f.publicIssue)- var runs []AgentTaskResponse- testutil.Call(t, testHandler.ListTasksByIssue, req).Want(http.StatusOK).JSON(&runs)- if len(runs) != 1 || runs[0].ID != taskID {- t.Fatalf("subtree runs = %+v, want descendant run %s", runs, taskID)- }- run := runs[0]- if userID == f.outsider {- if !run.Restricted || run.IssueID != "" || run.IssueTitle != "" || run.IssueIdentifier != "" || run.Result != nil {- t.Fatalf("private descendant run exposed to outsider: %+v", run)+ for _, view := range []string{"", "&view=timeline"} {+ for _, userID := range []string{f.outsider, f.insider, testUserID} {+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+f.publicIssue+"/task-runs?scope=subtree"+view, nil), userID), "id", f.publicIssue)+ var runs []AgentTaskResponse+ testutil.Call(t, testHandler.ListTasksByIssue, req).Want(http.StatusOK).JSON(&runs)+ if len(runs) != 1 || runs[0].ID != taskID {+ t.Fatalf("subtree runs = %+v, want descendant run %s", runs, taskID)+ }+ run := runs[0]+ if userID == f.outsider {+ if !run.Restricted || run.IssueID != "" || run.IssueTitle != "" || run.IssueIdentifier != "" || run.Result != nil || run.HandoffNote != "" {+ t.Fatalf("private descendant run exposed to outsider: %+v", run)+ }+ } else if run.Restricted || run.IssueID != f.secretIssue || run.IssueTitle == "" || run.Result == nil {+ t.Fatalf("authorized viewer lost descendant run content: %+v", run)}- } else if run.Restricted || run.IssueID != f.secretIssue || run.IssueTitle == "" || run.Result == nil {- t.Fatalf("authorized viewer lost descendant run content: %+v", run)}}}