Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9539: test(perf): benchmark big issues and Inbox switching on a large workspace (#10891)
Multica Eve61cb1f18950c
diff --git a/e2e/perf/README.md b/e2e/perf/README.mdindex 76e0cc442f..306209b2e2 100644--- a/e2e/perf/README.md+++ b/e2e/perf/README.md@@ -162,6 +162,58 @@ These are observed local measurements, not latency thresholds. Stop otherrun-owned builds/tests before measuring; the report also records system load.Destroy the API environment after the comparison with `make destroy ARGS="--yes"`.+## Core paths: big issues and Inbox switching++`core-paths.spec.ts` is the benchmark the performance work (MUL-9539) is+judged by. It measures the two paths people report as slow, on the production+UI against a real local API, with a seeded "large workspace":++- **issue**: open a big issue by URL, scroll its history to the end at a+ steady pace while the images load, then, from the middle of the history,+ toggle the left nav (⌘B) and the right sidebar ten times each. It runs on+ two issues: `large` (300 comments, 80 images, 70 runs, 40 sub-issues) and+ `p99` (54 / 54 / 36 / 38, the non-zero p99 of a production sample).+- **inbox**: click through twenty rows of the Work panel's Inbox, then go back+ and forth between the first five. `PERF_INBOX_ROWS=20` (default) uses the+ largest section limit; `PERF_INBOX_ROWS=all` first presses "Show N more".+ A switch ends when the notified comment is in view; `PERF_INBOX_UNTIL=title`+ ends it at the issue title instead, for refs older than #10872 that do not+ bring the comment into view.++Each step reports **time until the content is on screen** and **stalls**:+frames longer than 50 ms (Long Animation Frames), the longest one, and the+scripts behind the worst. Interactions start at the click event's own+timestamp and end in the frame where the target is laid out in the viewport,+so Playwright's IPC is not in the number. A step whose content never appears+fails rather than reporting a fast time.++The dataset (`lib/core-dataset.ts`) takes its sizes from production+aggregates: ~1,000 issues, ~1,800 notifications of which ~950 unread, and the+issues above. Text, structure and image bytes are deterministic; the report+carries a digest, and `scripts/perf-core-report.mjs` refuses to compare+reports from different datasets. The first run seeds a `perf-core` workspace+(about a minute) and later runs reuse it.++```bash+make up C=api ARGS="--ephemeral"+NEXT_PUBLIC_API_URL='' NEXT_PUBLIC_WS_URL='' pnpm --filter @multica/web build+(cd apps/web && REMOTE_API_URL=http://localhost:<api-port> pnpm exec next start --port 3000) &+PERF_SCENARIO=core-paths PERF_REPORT_PATH=$PWD/perf/main.json \+ make env-exec ARGS="-- pnpm exec playwright test --config=playwright.perf.config.ts core-paths.spec.ts"+node scripts/perf-core-report.mjs main=perf/main.json [other=perf/other.json ...]+```++`PERF_SCENARIO=core-issue` or `core-inbox` runs one scenario;+`PERF_ISSUES=large` narrows the issue scenario; `PERF_REPEATS` (default 5)+and `PERF_WARMUP` (default 1) set the rounds, each in a fresh browser context.+`PERF_CPU_THROTTLE=4` slows the CPU for the whole sample: an M-series Mac+absorbs work that a mid-range laptop shows as stalls, and a fix that only+helps there (#10767's left-nav toggle) is invisible unthrottled. Sidebar+toggles also report main-thread work per toggle, the most stable of the+numbers.+To compare refs, build each ref in its own worktree and run the spec from one+checkout against each server in turn, never two at once.+## When to run the typing scenariosNothing runs this automatically. The routine guard is the component test fromdiff --git a/e2e/perf/core-paths.spec.ts b/e2e/perf/core-paths.spec.tsnew file mode 100644index 0000000000..f7cbaddc30--- /dev/null+++ b/e2e/perf/core-paths.spec.ts@@ -0,0 +1,359 @@+/**+ * Core-path benchmark (MUL-9539): the two paths people report as slow, on the+ * production UI against a real local API and a "large workspace" dataset.+ *+ * 1. `issue` — open a big issue directly, scroll its history top to bottom+ * while the images load, then toggle the left nav and the right sidebar.+ * 2. `inbox` — click through twenty Inbox rows in the Work panel, then go+ * back and forth between rows already visited.+ *+ * Every step reports two things: how long until the requested content is on+ * screen, and how the page stalled on the way (Long Animation Frames). See+ * `lib/frame-metrics.ts` for the exact clock and `lib/core-dataset.ts` for the+ * data. Opt in with PERF_SCENARIO=core-paths (both) or core-issue/core-inbox.+ */+import { expect, test, type Browser, type BrowserContext, type CDPSession, type Page } from "@playwright/test";+import { mkdirSync, writeFileSync } from "node:fs";+import { cpus, loadavg } from "node:os";+import { dirname } from "node:path";+import {+ installFrameMetrics, interactionLatency, lastClick, lastInput, median, pageNow, quantile, settle, stallsBetween,+ type StallSummary,+} from "./lib/frame-metrics";+import { DETAIL_ISSUES, ensureDataset, perfApi, resetInbox, type Manifest } from "./lib/core-dataset";++const scenario = process.env.PERF_SCENARIO ?? "";+const runIssue = scenario === "core-paths" || scenario === "core-issue";+const runInbox = scenario === "core-paths" || scenario === "core-inbox";+const REPEATS = Number(process.env.PERF_REPEATS ?? 5);+/** Unmeasured rounds first: they warm the API, database and OS caches. */+const WARMUP = Number(process.env.PERF_WARMUP ?? 1);+const VIEWPORT = { width: 1440, height: 900 };+/** Idle time after content appears, so the tail of the work lands in the window. */+const LOAD_TAIL_MS = 3000;+const SWITCH_DWELL_MS = 1000;+const SIDEBAR_TOGGLES = 10;+const SCROLL_PX_PER_FRAME = 120;+/**+ * CPU slowdown for the whole sample (CDP). 1 is the machine as is; 4 stands+ * in for a mid-range laptop, where the work an M-series Mac absorbs shows.+ */+const CPU_THROTTLE = Number(process.env.PERF_CPU_THROTTLE ?? 1);+/**+ * How many Inbox rows the Work panel shows: `20`, the largest section limit+ * a user can pick, or `all`, after "Show N more" mounts every row.+ */+const INBOX_ROWS = process.env.PERF_INBOX_ROWS === "all" ? "all" : "20";+/**+ * Where an Inbox switch ends: the notified comment in view (default), or just+ * the issue's title, for refs that do not scroll to the comment (before #10872).+ */+const INBOX_UNTIL = process.env.PERF_INBOX_UNTIL === "title" ? "title" : "comment";++test.describe.configure({ mode: "serial" });++let manifest: Manifest;+let token: string;+const report: { issue: Record<string, unknown>[]; inbox: Record<string, unknown>[] } = { issue: [], inbox: [] };++test.beforeAll(async () => {+ test.skip(!runIssue && !runInbox, "set PERF_SCENARIO=core-paths (or core-issue / core-inbox)");+ test.setTimeout(900_000);+ expect(process.env.MULTICA_DEV_PROFILE, "run through `make env-exec` against an isolated environment").toMatch(/^dev-/);+ const api = await perfApi();+ token = api.getToken()!;+ manifest = await ensureDataset(api);+});++test.afterAll(async ({ browser }) => {+ if (!manifest || !process.env.PERF_REPORT_PATH) return;+ const path = process.env.PERF_REPORT_PATH;+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify({+ ref: process.env.PERF_REF ?? null,+ label: process.env.PERF_LABEL ?? null,+ dataset: { version: manifest.version, digest: manifest.digest, counts: manifest.counts },+ environment: {+ browser: browser.version(), viewport: `${VIEWPORT.width}x${VIEWPORT.height}`, cpu_throttle: CPU_THROTTLE,+ cpu: cpus()[0]?.model, cores: cpus().length, load_1m_end: loadavg()[0], repeats: REPEATS,+ inbox_rows: INBOX_ROWS, inbox_until: INBOX_UNTIL,+ },+ summary: summarize(),+ samples: report,+ }, null, 2));+});++async function openContext(browser: Browser): Promise<{ context: BrowserContext; page: Page; cdp: CDPSession; errors: string[] }> {+ const context = await browser.newContext({ viewport: VIEWPORT, locale: "en-US", colorScheme: "light" });+ const page = await context.newPage();+ await installFrameMetrics(page, token);+ const cdp = await context.newCDPSession(page);+ await cdp.send("Performance.enable");+ if (CPU_THROTTLE > 1) await cdp.send("Emulation.setCPUThrottlingRate", { rate: CPU_THROTTLE });+ const errors: string[] = [];+ page.on("pageerror", (error) => errors.push(error.message));+ return { context, page, cdp, errors };+}++/** Main-thread task time so far (ms), from the renderer's own counters. */+async function taskTime(cdp: CDPSession): Promise<number> {+ const { metrics } = await cdp.send("Performance.getMetrics");+ return (metrics.find((m) => m.name === "TaskDuration")?.value ?? 0) * 1000;+}++type Toggle = { next_paint_ms: number; task_ms: number; stalls: StallSummary; open: boolean };++function summarizeToggles(toggles: Toggle[]) {+ return {+ next_paint_median_ms: median(toggles.map((t) => t.next_paint_ms)),+ next_paint_max_ms: Math.max(...toggles.map((t) => t.next_paint_ms)),+ task_median_ms: Math.round(median(toggles.map((t) => t.task_ms))),+ stalls: toggles.reduce((sum, t) => sum + t.stalls.stalls, 0),+ stall_max_ms: Math.max(...toggles.map((t) => t.stalls.stall_max_ms)),+ top_sources: toggles.flatMap((t) => t.stalls.top_sources).slice(0, 3),+ };+}++const detailSelector = '[data-mc="issue-detail"][data-view="page"]';++/** Resolves with page-clock marks once the issue's title and the target comment are on screen. */+async function waitForIssue(page: Page, title: string, commentId: string, mode: "mounted" | "in-view" | "title") {+ const handle = await page.waitForFunction(({ title, commentId, mode, detailSelector }) => {+ const marks = window.__corePerf.marks;+ const details = [...document.querySelectorAll(detailSelector)];+ const detail = details.find((d) => d.querySelector('[data-mc="issue-title"]')?.textContent?.includes(title));+ if (!detail) return false;+ marks.title ??= performance.now();+ if (mode === "title") return { title: marks.title, content: marks.title };+ const root = detail.querySelector<HTMLElement>("[data-tab-scroll-root]");+ const target = root?.querySelector<HTMLElement>(`[data-comment-content="${commentId}"]`);+ if (!root || !target || !target.textContent?.trim()) return false;+ const row = target.closest("[data-virtual-thread-mounted]");+ if (row?.getAttribute("data-virtual-thread-mounted") === "false") return false;+ const box = target.getBoundingClientRect();+ if (box.height === 0) return false;+ if (mode === "in-view") {+ const view = root.getBoundingClientRect();+ if (!(box.bottom > view.top && box.top < view.bottom)) return false;+ }+ marks.content ??= performance.now();+ return { title: marks.title, content: marks.content };+ }, { title, commentId, mode, detailSelector }, { polling: "raf", timeout: 60_000 });+ return (await handle.jsonValue()) as { title: number; content: number };+}++test("open, scroll and toggle the sidebar on a big issue", async ({ browser }) => {+ test.skip(!runIssue, "issue scenario not selected");+ test.setTimeout(1_800_000);+ const keys = DETAIL_ISSUES.filter((key) => !process.env.PERF_ISSUES || process.env.PERF_ISSUES.split(",").includes(key));+ for (const key of keys) {+ const issue = manifest.issues[key]!;+ for (let round = -WARMUP; round < REPEATS; round++) {+ const { context, page, cdp, errors } = await openContext(browser);+ try {+ let apiRequests = 0;+ let imagesFetched = 0;+ page.on("request", (request) => { if (new URL(request.url()).pathname.startsWith("/api/")) apiRequests++; });+ page.on("requestfinished", (request) => { if (/\/api\/attachments\/[^/]+\/download/.test(request.url())) imagesFetched++; });+ await page.goto(`/${manifest.workspace.slug}/issues/${issue.id}`, { waitUntil: "commit" });+ const marks = await waitForIssue(page, issue.title, issue.firstCommentId, "mounted");+ await settle(page, LOAD_TAIL_MS);+ const load = await stallsBetween(page, 0, await pageNow(page));+ const requestsAtLoad = apiRequests;+ const imagesAtLoad = imagesFetched;++ // Scroll the history top to bottom at a steady pace; images load and decode on the way.+ const scrollStart = await pageNow(page);+ const scroll = await page.evaluate(async ({ detailSelector, step, lastId }) => {+ const root = document.querySelector<HTMLElement>(`${detailSelector} [data-tab-scroll-root]`)!;+ const start = performance.now();+ let bottomFrames = 0;+ while (performance.now() - start < 90_000 && bottomFrames < 30) {+ await new Promise((done) => requestAnimationFrame(done));+ root.scrollTop += step;+ bottomFrames = root.scrollTop + root.clientHeight >= root.scrollHeight - 2 ? bottomFrames + 1 : 0;+ }+ return {+ ms: performance.now() - start,+ height: root.scrollHeight,+ reachedEnd: !!root.querySelector(`[data-comment-content="${lastId}"]`),+ };+ }, { detailSelector, step: SCROLL_PX_PER_FRAME, lastId: issue.lastCommentId });+ await settle(page, 1000);+ const scrollStalls = await stallsBetween(page, scrollStart, await pageNow(page));+ expect(scroll.reachedEnd, "scrolling reached the last comment").toBe(true);++ // Toggle the left nav and the right sidebar with the reader in the middle of the+ // history, where the most rows are mounted; each toggle is one interaction.+ await page.evaluate((sel) => {+ const root = document.querySelector<HTMLElement>(`${sel} [data-tab-scroll-root]`)!;+ root.scrollTop = Math.round(root.scrollHeight / 2);+ }, detailSelector);+ await settle(page, 1500);+ const panels = {+ left: {+ act: () => page.keyboard.press("ControlOrMeta+b"),+ open: () => page.evaluate(() => document.querySelector('[data-slot="space-panel"][data-state]')?.getAttribute("data-state") === "expanded"),+ },+ right: {+ act: () => page.locator(detailSelector).getByRole("button", { name: "Toggle right sidebar" }).click(),+ open: () => page.evaluate(() => (document.querySelector("[data-right-sidebar-panel]")?.getBoundingClientRect().width ?? 0) > 1),+ },+ };+ const sidebar: Record<string, ReturnType<typeof summarizeToggles>> = {};+ for (const [name, panel] of Object.entries(panels)) {+ const toggles: Toggle[] = [];+ for (let i = 0; i < SIDEBAR_TOGGLES; i++) {+ const workBefore = await taskTime(cdp);+ await panel.act();+ await settle(page, 600);+ const input = await lastInput(page);+ const end = await pageNow(page);+ toggles.push({+ // Event Timing only reports interactions of 16 ms or more.+ next_paint_ms: (await interactionLatency(page, input, end)) ?? 16,+ task_ms: (await taskTime(cdp)) - workBefore,+ stalls: await stallsBetween(page, input - 1, end),+ open: await panel.open(),+ });+ }+ expect(new Set(toggles.map((t) => t.open)).size, `the ${name} sidebar both collapsed and expanded`).toBe(2);+ sidebar[name] = summarizeToggles(toggles);+ }+ expect(errors).toEqual([]);++ if (round >= 0) {+ const record = {+ issue: key, round,+ title_ms: Math.round(marks.title), content_ms: Math.round(marks.content),+ load, api_requests_at_load: requestsAtLoad,+ images_fetched_at_load: imagesAtLoad,+ scroll: { ms: Math.round(scroll.ms), height_px: scroll.height, images_fetched: imagesFetched - imagesAtLoad, ...scrollStalls },+ sidebar,+ load_1m: loadavg()[0],+ };+ report.issue.push(record);+ console.log(JSON.stringify(record));+ }+ } finally {+ await context.close();+ }+ }+ }+});++test("switch between Inbox rows in the Work panel", async ({ browser }) => {+ test.skip(!runInbox, "inbox scenario not selected");+ test.setTimeout(1_800_000);+ const sequence: { key: string; phase: "first-visit" | "revisit" }[] = manifest.inbox.slice(0, 20).map((n) => ({ key: n.key, phase: "first-visit" }));+ for (let i = 0; i < 10; i++) sequence.push({ key: manifest.inbox[i % 5]!.key, phase: "revisit" });++ for (let round = -WARMUP; round < REPEATS; round++) {+ await resetInbox(manifest);+ const { context, page, errors } = await openContext(browser);+ try {+ await page.addInitScript((slug) => {+ localStorage.setItem(`multica_sidebar_tree:${slug}`, JSON.stringify({ state: { inboxSettings: { limit: 20 } }, version: 0 }));+ }, manifest.workspace.slug);+ await page.goto(`/${manifest.workspace.slug}/issues`);+ const rows = page.locator("li[data-inbox-row]");+ await expect(rows.first()).toBeVisible({ timeout: 60_000 });+ const firstTitle = manifest.issues[manifest.inbox[0]!.key]!.title;+ await expect(rows.filter({ hasText: firstTitle })).toHaveCount(1);+ if (INBOX_ROWS === "all") {+ await page.getByRole("button", { name: /^Show \d+ more/ }).first().click();+ await expect.poll(() => rows.count()).toBeGreaterThan(500);+ }+ await expect.poll(() => rows.count(), "the Inbox section shows the twenty measured rows").toBeGreaterThanOrEqual(20);+ await settle(page, 2000);+ const mountedRows = await rows.count();++ const switches: Record<string, unknown>[] = [];+ for (const [step, { key, phase }] of sequence.entries()) {+ const issue = manifest.issues[key]!;+ await page.evaluate(() => { window.__corePerf.marks = {}; });+ await rows.filter({ hasText: issue.title }).locator("a").first().click();+ const marks = await waitForIssue(page, issue.title, issue.targetCommentId, INBOX_UNTIL === "title" ? "title" : "in-view");+ const click = await lastClick(page);+ await settle(page, SWITCH_DWELL_MS);+ const end = await pageNow(page);+ const stalls = await stallsBetween(page, click - 1, end);+ switches.push({+ step, phase, issue: key, comments: issue.comments,+ next_paint_ms: (await interactionLatency(page, click, end)) ?? 16,+ title_ms: Math.round(marks.title - click), ready_ms: Math.round(marks.content - click), ...stalls,+ });+ }+ const session = await context.newCDPSession(page);+ await session.send("HeapProfiler.collectGarbage");+ const heap = (await session.send("Performance.enable"), await session.send("Performance.getMetrics"))+ .metrics.find((m) => m.name === "JSHeapUsedSize")?.value ?? 0;+ const domNodes = await page.evaluate(() => document.getElementsByTagName("*").length);+ expect(errors).toEqual([]);+ if (round >= 0) {+ const record = { round, inbox_rows: INBOX_ROWS, mounted_rows: mountedRows, switches, heap_mb_after_gc: Math.round(heap / 1e6), dom_nodes_end: domNodes, load_1m: loadavg()[0] };+ report.inbox.push(record);+ console.log(JSON.stringify({ round, ready_ms: switches.map((s) => s.ready_ms), heap_mb_after_gc: record.heap_mb_after_gc }));+ }+ } finally {+ await context.close();+ }+ }+});++type Num = number;+const pick = (records: Record<string, unknown>[], path: string): Num[] =>+ records.map((r) => path.split(".").reduce<unknown>((v, k) => (v as Record<string, unknown>)?.[k], r) as Num).filter((v) => typeof v === "number");+const round1 = (v: number) => Math.round(v * 10) / 10;++/** Medians across samples; p95/max across individual switches. */+function summarize() {+ const issue: Record<string, unknown> = {};+ for (const key of DETAIL_ISSUES) {+ const rs = report.issue.filter((r) => r.issue === key);+ if (rs.length === 0) continue;+ issue[key] = {+ open_content_ms: median(pick(rs, "content_ms")),+ open_title_ms: median(pick(rs, "title_ms")),+ open_stalls: median(pick(rs, "load.stalls")),+ open_stall_max_ms: median(pick(rs, "load.stall_max_ms")),+ open_blocking_ms: median(pick(rs, "load.blocking_ms")),+ scroll_stalls: median(pick(rs, "scroll.stalls")),+ scroll_stall_max_ms: median(pick(rs, "scroll.stall_max_ms")),+ scroll_blocking_ms: median(pick(rs, "scroll.blocking_ms")),+ ...Object.fromEntries(["left", "right"].flatMap((side) => [+ [`${side}_toggle_next_paint_ms`, median(pick(rs, `sidebar.${side}.next_paint_median_ms`))],+ [`${side}_toggle_next_paint_max_ms`, median(pick(rs, `sidebar.${side}.next_paint_max_ms`))],+ [`${side}_toggle_task_ms`, median(pick(rs, `sidebar.${side}.task_median_ms`))],+ [`${side}_toggle_stalls`, median(pick(rs, `sidebar.${side}.stalls`))],+ [`${side}_toggle_stall_max_ms`, median(pick(rs, `sidebar.${side}.stall_max_ms`))],+ ])),+ };+ }+ const inbox: Record<string, unknown> = {};+ for (const phase of ["first-visit", "revisit"]) {+ const all = report.inbox.flatMap((r) => (r.switches as Record<string, unknown>[]).filter((s) => s.phase === phase));+ if (all.length === 0) continue;+ const ready = pick(all, "ready_ms");+ inbox[phase] = {+ switches: all.length,+ ready_median_ms: median(ready), ready_p95_ms: round1(quantile(ready, 0.95)), ready_max_ms: Math.max(...ready),+ next_paint_median_ms: median(pick(all, "next_paint_ms")), next_paint_max_ms: Math.max(...pick(all, "next_paint_ms")),+ stalls_per_switch: round1(pick(all, "stalls").reduce((a, b) => a + b, 0) / all.length),+ stall_max_ms: Math.max(...pick(all, "stall_max_ms")),+ freezes: pick(all, "freezes").reduce((a, b) => a + b, 0),+ };+ }+ if (report.inbox.length > 0) {+ inbox.heap_mb_after_gc = median(pick(report.inbox, "heap_mb_after_gc"));+ const sources = new Map<string, number>();+ for (const s of report.inbox.flatMap((r) => r.switches as { top_sources: string[] }[])) {+ for (const line of s.top_sources) {+ const [ms, ...rest] = line.split(" ");+ sources.set(rest.join(" "), (sources.get(rest.join(" ")) ?? 0) + Number.parseInt(ms!, 10));+ }+ }+ inbox.top_sources = [...sources.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([s, ms]) => `${ms}ms ${s}`);+ }+ return { issue, inbox };+}diff --git a/e2e/perf/lib/core-dataset.ts b/e2e/perf/lib/core-dataset.tsnew file mode 100644index 0000000000..864962a963--- /dev/null+++ b/e2e/perf/lib/core-dataset.ts@@ -0,0 +1,349 @@+/**+ * The "large workspace" dataset behind the core-path benchmark (MUL-9539).+ *+ * Sizes come from production aggregates (counts only, read replica,+ * 2026-11-18): the non-zero p99 per issue is 54 comments, 36 runs, 38 direct+ * sub-issues and 54 images; the p99 user has ~1,800 notifications, ~950 of+ * them unread; a p99 workspace has ~1,000 issues. `large` is the long issue+ * people actually report as slow (MUL-9538 and friends); `p99` is the 99th+ * percentile issue.+ *+ * Everything is synthetic and deterministic: the same DATASET_VERSION gives+ * the same text, structure and image bytes, and the manifest's digest proves+ * it, so two refs measured against one seeded database see identical data.+ * Rows go straight into the isolated local database (no agent ever runs);+ * images go through the real upload endpoint so their URLs, dimensions and+ * bytes are what the app normally serves.+ */+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import pg from "pg";+import { TestApiClient } from "../../fixtures";+import { mediaBytes } from "../fixtures/image-heavy-thread";++export const DATASET_VERSION = "core-2";+const API_BASE = process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;+const PERF_EMAIL = "[email protected]";+const PERF_WORKSPACE = { name: "Perf Core", slug: "perf-core" };++export interface IssueSpec {+ key: string;+ title: string;+ comments: number;+ images: number;+ runs: number;+ children: number;+ /** Where the notification points: a fraction of the way down the history. */+ target: number;+}++export interface SeededIssue extends IssueSpec {+ id: string;+ identifier: string;+ firstCommentId: string;+ lastCommentId: string;+ targetCommentId: string;+}++export interface Manifest {+ version: string;+ digest: string;+ database: string;+ workspace: { id: string; slug: string };+ token_email: string;+ issues: Record<string, SeededIssue>;+ /** The newest notifications, in Inbox order (newest first). */+ inbox: { key: string; notificationId: string }[];+ counts: Record<string, number>;+}++/** The two issues the "open a big issue" scenario measures. */+export const DETAIL_ISSUES = ["large", "p99"] as const;++function datasetSpec() {+ const issues: IssueSpec[] = [+ { key: "large", title: "Benchmark: long issue (300 comments, 80 images, 70 runs)", comments: 300, images: 80, runs: 70, children: 40, target: 0.8 },+ { key: "p99", title: "Benchmark: p99 issue (54 comments, 54 images, 36 runs)", comments: 54, images: 54, runs: 36, children: 38, target: 0.8 },+ ];+ for (let i = 0; i < 3; i++) {+ issues.push({ key: `medium-${i}`, title: `Benchmark: discussion ${i + 1} (120 comments)`, comments: 120, images: 10, runs: 15, children: 6, target: 1 });+ }+ const smallComments = [3, 8, 15, 25, 40];+ for (let i = 0; i < 45; i++) {+ issues.push({+ key: `small-${i}`,+ title: `Benchmark: inbox issue ${String(i + 1).padStart(2, "0")}`,+ comments: smallComments[i % smallComments.length]!,+ images: i % 3,+ runs: i % 4,+ children: i % 5 === 0 ? 3 : 0,+ target: i % 4 === 3 ? 0.5 : 1,+ });+ }+ // Inbox order, newest first: the big issues are spread through the first+ // twenty rows, the way they turn up among ordinary notifications.+ const order = [+ "small-0", "large", "small-1", "medium-0", "small-2", "small-3", "p99", "small-4", "medium-1", "small-5",+ "small-6", "small-7", "medium-2", "small-8", "small-9", "small-10", "small-11", "small-12", "small-13", "small-14",+ ...Array.from({ length: 30 }, (_, i) => `small-${15 + i}`),+ ];+ return { issues, order, backgroundIssues: 1000, backgroundNotifications: { unread: 900, read: 850 } };+}++/** Deterministic PRNG (mulberry32), so every seed of one version is identical. */+function rng(seed: number) {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const SENTENCES = [+ "The timeline now loads the latest page first and fetches older entries on demand.",+ "I reproduced this locally with the large fixture; the second click is where it stalls.",+ "Agreed, but we should keep the reading position stable when older comments arrive.",+ "The query plan switched to a sequential scan once the table passed a few thousand rows.",+ "Let's ship the narrow fix first and follow up with the refactor in a separate PR.",+ "Screenshots below are from the desktop build on macOS with the sidebar expanded.",+ "This only happens when the issue has more than a screenful of history.",+ "I checked the trace: most of the time goes to style recalculation after the list mounts.",+];++function commentBody(rand: () => number, n: number): string {+ const parts: string[] = [];+ const paragraphs = 1 + Math.floor(rand() * 4);+ for (let p = 0; p < paragraphs; p++) {+ const count = 2 + Math.floor(rand() * 4);+ parts.push(Array.from({ length: count }, () => SENTENCES[Math.floor(rand() * SENTENCES.length)]).join(" "));+ }+ const kind = n % 7;+ if (kind === 1) parts.push("```ts\nconst page = await api.listTimeline(issueId, { before: cursor, limit: 50 });\nfor (const entry of page.entries) render(entry);\nreturn page.next_cursor;\n```");+ if (kind === 3) parts.push("| Case | Before | After |\n| --- | --- | --- |\n| Open | 1840 ms | 420 ms |\n| Scroll | 12 stalls | 2 stalls |\n| Switch | 960 ms | 310 ms |");+ if (kind === 5) parts.push("- Keep the anchor comment in view\n- Load older pages on scroll\n- Leave the composer untouched\n - including drafts");+ if (kind === 6) parts.push(`See \`useIssueTimeline\` and [the trace](https://example.com/trace/${n}).`);+ return parts.join("\n\n");+}++function description(title: string): string {+ return [+ `## Context\n\n${title}. ${SENTENCES.slice(0, 4).join(" ")}`,+ "## Acceptance\n\n- Opening the issue shows the first comments without a visible stall\n- Scrolling to the end stays smooth while images load\n- Toggling the sidebar does not re-render the history",+ ].join("\n\n");+}++/** The structure and text of the dataset; its hash identifies what was measured. */+export function datasetDigest(): string {+ const spec = datasetSpec();+ const rand = rng(9539);+ const bodies = spec.issues.map((issue) => Array.from({ length: issue.comments }, (_, i) => commentBody(rand, i)));+ return createHash("sha256")+ .update(JSON.stringify({ version: DATASET_VERSION, spec, bodies }))+ .update(mediaBytes().original)+ .digest("hex")+ .slice(0, 16);+}++export function manifestPath(): string {+ const db = new URL(process.env.DATABASE_URL!).pathname.slice(1);+ // Outside test-results/, which Playwright empties at the start of every run.+ return process.env.PERF_MANIFEST ?? join(tmpdir(), "multica-perf-core", `${db}.manifest.json`);+}++export async function perfApi(): Promise<TestApiClient> {+ const api = new TestApiClient();+ await api.login(PERF_EMAIL, "Perf Reader");+ await api.ensureWorkspace(PERF_WORKSPACE.name, PERF_WORKSPACE.slug);+ await api.markUserOnboarded();+ return api;+}++/** Reuses the seeded dataset when the database still holds this version; seeds it otherwise. */+export async function ensureDataset(api: TestApiClient): Promise<Manifest> {+ const path = manifestPath();+ const digest = datasetDigest();+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ try {+ if (existsSync(path)) {+ const manifest = JSON.parse(readFileSync(path, "utf8")) as Manifest;+ const large = manifest.issues.large;+ const alive = large && (await db.query("SELECT 1 FROM issue WHERE id=$1", [large.id])).rowCount === 1;+ if (manifest.version === DATASET_VERSION && manifest.digest === digest && alive) return manifest;+ }+ const manifest = await seed(api, db, digest);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify(manifest, null, 2));+ return manifest;+ } finally {+ await db.end();+ }+}++async function upload(api: TestApiClient, slug: string, issueId: string, n: number): Promise<{ id: string; url: string }> {+ const form = new FormData();+ form.append("file", new Blob([new Uint8Array(mediaBytes().original)], { type: "image/png" }), `screenshot-${n}.png`);+ form.append("issue_id", issueId);+ const res = await fetch(`${API_BASE}/api/upload-file`, {+ method: "POST",+ headers: { Authorization: `Bearer ${api.getToken()}`, "X-Workspace-Slug": slug },+ body: form,+ });+ if (!res.ok) throw new Error(`upload failed: ${res.status} ${await res.text()}`);+ const body = (await res.json()) as { id: string; markdown_url?: string; url: string };+ // Production persists MULTICA_PUBLIC_URL + /api/attachments/<id>/download, the+ // app's own origin; locally that origin is the web server's, so keep the path.+ const markdown = body.markdown_url || body.url;+ return { id: body.id, url: markdown.startsWith("http") ? new URL(markdown).pathname : markdown };+}++async function seed(api: TestApiClient, db: pg.Client, digest: string): Promise<Manifest> {+ const spec = datasetSpec();+ const rand = rng(9539);+ const workspace = (await api.getWorkspaces()).find((w) => w.slug === PERF_WORKSPACE.slug)!;+ const userId = (await db.query('SELECT id FROM "user" WHERE email=$1', [PERF_EMAIL])).rows[0].id as string;++ // Start from an empty workspace so a re-seed never stacks on an older version.+ await db.query("DELETE FROM inbox_item WHERE workspace_id=$1", [workspace.id]);+ await db.query("DELETE FROM agent_task_queue WHERE issue_id IN (SELECT id FROM issue WHERE workspace_id=$1)", [workspace.id]);+ await db.query("DELETE FROM attachment WHERE workspace_id=$1", [workspace.id]);+ await db.query("DELETE FROM comment WHERE workspace_id=$1", [workspace.id]);+ await db.query("DELETE FROM issue WHERE workspace_id=$1", [workspace.id]);+ await db.query("DELETE FROM agent WHERE workspace_id=$1 AND name='Benchmark agent'", [workspace.id]);+ await db.query("DELETE FROM agent_runtime WHERE workspace_id=$1 AND name='Benchmark runtime'", [workspace.id]);++ const 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 as string;+ const 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,'workspace','private',1,$3) RETURNING id`, [workspace.id, runtimeId, userId])).rows[0].id as string;++ const statuses = ["backlog", "todo", "in_progress", "in_review", "done", "cancelled"] as const;+ const background = await api.seedTableIssues(Array.from({ length: spec.backgroundIssues }, (_, i) => ({+ title: `Background issue ${i + 1}: ${SENTENCES[i % SENTENCES.length]!.slice(0, 60)}`,+ status: statuses[i % statuses.length],+ priority: (["none", "low", "medium", "high", "urgent"] as const)[i % 5],+ })));++ const seeded: Record<string, SeededIssue> = {};+ let imageNo = 0;+ for (const issue of spec.issues) {+ const [row] = await api.seedTableIssues([{ title: issue.title, status: "in_progress", priority: "high" }]);+ const id = row!.id;+ await db.query("UPDATE issue SET description=$2, created_at=now()-interval '30 days' WHERE id=$1", [id, description(issue.title)]);+ if (issue.children > 0) {+ await api.seedTableIssues(Array.from({ length: issue.children }, (_, i) => ({+ title: `${issue.title.split(" (")[0]} · sub-issue ${i + 1}`,+ status: statuses[i % statuses.length],+ parentIssueId: id,+ })));+ }++ // Threads of 1–6 comments; every other comment by the agent.+ const commentIds: string[] = [];+ let root: string | null = null;+ let threadLeft = 0;+ const bodies = Array.from({ length: issue.comments }, (_, i) => commentBody(rand, i));+ const imageSlots = new Map<number, number>();+ for (let k = 0; k < issue.images; k++) {+ const at = Math.floor(((k % Math.max(1, Math.ceil(issue.images / 2))) * issue.comments) / Math.ceil(issue.images / 2));+ imageSlots.set(at, (imageSlots.get(at) ?? 0) + 1);+ }+ const startOffset = issue.comments + 10;+ for (let i = 0; i < issue.comments; i++) {+ if (threadLeft === 0) {+ root = null;+ threadLeft = 1 + (i % 6);+ }+ const byAgent = i % 2 === 1;+ const commentId = (await db.query(`+ INSERT INTO comment (workspace_id,issue_id,author_type,author_id,content,parent_id,created_at,updated_at)+ VALUES ($1,$2,$3,$4,$5,$6,now()-($7::int*interval '1 minute'),now()-($7::int*interval '1 minute')) RETURNING id`,+ [workspace.id, id, byAgent ? "agent" : "member", byAgent ? agentId : userId, bodies[i], root, startOffset - i])).rows[0].id as string;+ const images = imageSlots.get(i) ?? 0;+ if (images > 0) {+ const lines: string[] = [];+ for (let k = 0; k < images; k++) {+ const file = await upload(api, workspace.slug, id, imageNo++);+ await db.query("UPDATE attachment SET comment_id=$2 WHERE id=$1", [file.id, commentId]);+ lines.push(``);+ }+ await db.query("UPDATE comment SET content=content || $2 WHERE id=$1", [commentId, `\n\n${lines.join("\n\n")}`]);+ }+ commentIds.push(commentId);+ if (!root) root = commentId;+ threadLeft--;+ }++ for (let r = 0; r < issue.runs; r++) {+ await db.query(`INSERT INTO agent_task_queue+ (agent_id,runtime_id,issue_id,status,result,handoff_note,created_at,started_at,completed_at)+ VALUES ($1,$2,$3,'completed',$4,$5,now()-($6::int*interval '1 minute'),now()-($6::int*interval '1 minute'),now()-($6::int*interval '1 minute')+interval '3 minutes')`,+ [agentId, runtimeId, id, JSON.stringify({ comment: "Run summary", output: "provider output line\n".repeat(800) }), "Handoff context. ".repeat(40), startOffset - Math.floor((r * issue.comments) / Math.max(1, issue.runs))]);+ }++ const identifier = (await db.query("SELECT w.issue_prefix || '-' || i.number AS identifier FROM issue i JOIN workspace w ON w.id=i.workspace_id WHERE i.id=$1", [id])).rows[0].identifier as string;+ seeded[issue.key] = {+ ...issue,+ id,+ identifier,+ firstCommentId: commentIds[0]!,+ lastCommentId: commentIds.at(-1)!,+ targetCommentId: commentIds[Math.min(commentIds.length - 1, Math.floor((commentIds.length - 1) * issue.target))]!,+ };+ }++ // Background notifications: older than every measured row, on the background issues.+ const { unread, read } = spec.backgroundNotifications;+ await db.query(`+ INSERT INTO inbox_item (workspace_id,recipient_type,recipient_id,actor_type,actor_id,type,issue_id,title,read,created_at)+ SELECT $1,'member',$2,'agent',$3,'status_changed',issue_ids[1 + (g % array_length(issue_ids,1))],'Background notification',g >= $4,now()-interval '2 days'-(g*interval '1 minute')+ FROM generate_series(0,$5::int-1) AS g, (SELECT $6::uuid[] AS issue_ids) ids`,+ [workspace.id, userId, agentId, unread, unread + read, background.map((b) => b.id)]);++ const inbox: Manifest["inbox"] = [];+ for (const [position, key] of spec.order.entries()) {+ const issue = seeded[key]!;+ const notificationId = (await db.query(`+ INSERT INTO inbox_item (workspace_id,recipient_type,recipient_id,actor_type,actor_id,type,issue_id,title,details,created_at)+ VALUES ($1,'member',$2,'agent',$3,'new_comment',$4,$5,$6::jsonb,now()-($7::int*interval '1 minute')) RETURNING id`,+ [workspace.id, userId, agentId, issue.id, issue.title, JSON.stringify({ comment_id: issue.targetCommentId }), position + 1])).rows[0].id as string;+ inbox.push({ key, notificationId });+ }++ const counts = (await db.query(`SELECT+ (SELECT count(*) FROM issue WHERE workspace_id=$1)::int AS issues,+ (SELECT count(*) FROM comment WHERE workspace_id=$1)::int AS comments,+ (SELECT count(*) FROM attachment WHERE workspace_id=$1)::int AS images,+ (SELECT count(*) FROM agent_task_queue WHERE agent_id=$2)::int AS runs,+ (SELECT count(*) FROM inbox_item WHERE workspace_id=$1)::int AS notifications,+ (SELECT count(*) FROM inbox_item WHERE workspace_id=$1 AND NOT read)::int AS unread`, [workspace.id, agentId])).rows[0] as Record<string, number>;++ return {+ version: DATASET_VERSION,+ digest,+ database: new URL(process.env.DATABASE_URL!).pathname.slice(1),+ workspace: { id: workspace.id, slug: workspace.slug },+ token_email: PERF_EMAIL,+ issues: seeded,+ inbox,+ counts,+ };+}++/** Puts the measured notifications back to unread, so every sample starts from the same Inbox. */+export async function resetInbox(manifest: Manifest): Promise<void> {+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ try {+ await db.query("UPDATE inbox_item SET read=false, archived=false WHERE id = ANY($1::uuid[])", [manifest.inbox.map((n) => n.notificationId)]);+ } finally {+ await db.end();+ }+}diff --git a/e2e/perf/lib/frame-metrics.ts b/e2e/perf/lib/frame-metrics.tsnew file mode 100644index 0000000000..0eb51df574--- /dev/null+++ b/e2e/perf/lib/frame-metrics.ts@@ -0,0 +1,171 @@+/**+ * Shared in-page measurement for the core-path benchmark (MUL-9539).+ *+ * Two numbers matter to the people reporting slowness: how long until the+ * content they asked for is on screen, and how badly the page stalls while+ * getting there. Both are measured inside the page, against the page's own+ * clock, so Playwright's IPC never lands in a sample:+ *+ * - An interaction starts at the `click` event's `timeStamp`, captured before+ * any app handler runs. A navigation starts at the document's time origin.+ * - Content is "visible" in the animation frame in which the target is in the+ * DOM, laid out, and inside its scroll container's viewport; that frame is+ * the one painted next.+ * - Stalls come from Long Animation Frames: every frame that took longer than+ * 50 ms from the start of its work to its paint, with the scripts that ran+ * in it, so a regression points at the code that caused it.+ */+import type { Page } from "@playwright/test";++/** A frame over this long is a visible hitch (Long Animation Frames' own floor). */+export const STALL_MS = 50;+/** A frame over this long is a freeze the user notices as "stuck". */+export const FREEZE_MS = 200;++export interface FrameRecord {+ start: number;+ duration: number;+ blocking: number;+ /** The heaviest script attribution in the frame, if any. */+ source: string;+}++export interface StallSummary {+ /** Frames longer than 50 ms. */+ stalls: number;+ /** Frames longer than 200 ms. */+ freezes: number;+ stall_max_ms: number;+ /** Sum of the frames' time beyond 50 ms (Long Animation Frames' blocking duration). */+ blocking_ms: number;+ /** The scripts behind the worst frames, heaviest first. */+ top_sources: string[];+}++declare global {+ interface Window {+ __corePerf: {+ frames: FrameRecord[];+ clicks: number[];+ /** Clicks and key presses, for interactions started from the keyboard. */+ inputs: number[];+ /** Event Timing: interaction id → longest event duration (input to next paint). */+ interactions: Map<number, { start: number; duration: number }>;+ marks: Record<string, number>;+ };+ }+}++/** Installs the observers before any app script runs. Call once per context. */+export async function installFrameMetrics(page: Page, token: string): Promise<void> {+ await page.addInitScript((authToken) => {+ localStorage.setItem("multica_token", authToken);+ localStorage.setItem("multica:chat:isOpen", "false");+ const state: Window["__corePerf"] = { frames: [], clicks: [], inputs: [], interactions: new Map(), marks: {} };+ window.__corePerf = state;+ document.addEventListener("click", (event) => {+ state.clicks.push(event.timeStamp);+ state.inputs.push(event.timeStamp);+ }, { capture: true });+ document.addEventListener("keydown", (event) => state.inputs.push(event.timeStamp), { capture: true });+ new PerformanceObserver((list) => {+ for (const entry of list.getEntries() as unknown as {+ startTime: number; duration: number; blockingDuration: number;+ scripts: { duration: number; sourceURL: string; sourceFunctionName: string; invoker: string }[];+ }[]) {+ const heaviest = [...(entry.scripts ?? [])].sort((a, b) => b.duration - a.duration)[0];+ const file = heaviest?.sourceURL?.split("/").pop() ?? "";+ state.frames.push({+ start: entry.startTime,+ duration: entry.duration,+ blocking: entry.blockingDuration,+ source: heaviest+ ? `${heaviest.invoker || "script"} ${heaviest.sourceFunctionName || "(anonymous)"} @ ${file}`+ : "rendering (style/layout/paint)",+ });+ }+ }).observe({ type: "long-animation-frame", buffered: true });+ new PerformanceObserver((list) => {+ for (const entry of list.getEntries() as unknown as { interactionId: number; startTime: number; duration: number }[]) {+ if (!entry.interactionId) continue;+ // One interaction (pointerdown, pointerup, click) reports several entries.+ const prior = state.interactions.get(entry.interactionId);+ state.interactions.set(entry.interactionId, {+ start: Math.min(prior?.start ?? Infinity, entry.startTime),+ duration: Math.max(prior?.duration ?? 0, entry.duration),+ });+ }+ }).observe({ type: "event", buffered: true, durationThreshold: 16 } as PerformanceObserverInit);+ }, token);+}++/** The page clock, for bracketing a measured window. */+export function pageNow(page: Page): Promise<number> {+ return page.evaluate(() => performance.now());+}++/** The timestamp of the most recent click the page received. */+export async function lastClick(page: Page): Promise<number> {+ return page.evaluate(() => window.__corePerf.clicks.at(-1) ?? NaN);+}++/** The timestamp of the most recent click or key press. */+export async function lastInput(page: Page): Promise<number> {+ return page.evaluate(() => window.__corePerf.inputs.at(-1) ?? NaN);+}++/** Waits a few frames and a short idle period so trailing work lands in the window. */+export async function settle(page: Page, ms: number): Promise<void> {+ await page.waitForTimeout(ms);+ await page.evaluate(() => new Promise<void>((done) => requestAnimationFrame(() => requestAnimationFrame(() => done()))));+}++/** Long Animation Frames that started inside [from, to). */+export async function stallsBetween(page: Page, from: number, to: number): Promise<StallSummary> {+ const frames = await page.evaluate(+ ([a, b]) => window.__corePerf.frames.filter((f) => f.start >= a && f.start < b),+ [from, to] as const,+ );+ return summarizeFrames(frames);+}++export function summarizeFrames(frames: FrameRecord[]): StallSummary {+ const stalls = frames.filter((f) => f.duration > STALL_MS);+ const bySource = new Map<string, number>();+ for (const f of stalls) bySource.set(f.source, (bySource.get(f.source) ?? 0) + f.duration);+ return {+ stalls: stalls.length,+ freezes: stalls.filter((f) => f.duration > FREEZE_MS).length,+ stall_max_ms: Math.round(Math.max(0, ...stalls.map((f) => f.duration))),+ blocking_ms: Math.round(stalls.reduce((sum, f) => sum + f.blocking, 0)),+ top_sources: [...bySource.entries()]+ .sort((a, b) => b[1] - a[1])+ .slice(0, 3)+ .map(([source, ms]) => `${Math.round(ms)}ms ${source}`),+ };+}++/**+ * Longest Event Timing duration (input → next paint) of the interaction whose+ * click landed at `click`; its pointerdown came a few milliseconds earlier.+ */+export async function interactionLatency(page: Page, click: number, to: number): Promise<number | null> {+ return page.evaluate(([a, b]) => {+ let worst: number | null = null;+ for (const { start, duration } of window.__corePerf.interactions.values()) {+ if (start >= a - 100 && start < b) worst = Math.max(worst ?? 0, duration);+ }+ return worst;+ }, [click, to] as const);+}++export function quantile(values: number[], q: number): number {+ if (values.length === 0) return NaN;+ const sorted = [...values].sort((a, b) => a - b);+ const at = (sorted.length - 1) * q;+ const lo = Math.floor(at);+ const hi = Math.ceil(at);+ return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * (at - lo);+}++export const median = (values: number[]) => quantile(values, 0.5);diff --git a/scripts/perf-core-report.mjs b/scripts/perf-core-report.mjsnew file mode 100644index 0000000000..1f59960584--- /dev/null+++ b/scripts/perf-core-report.mjs@@ -0,0 +1,86 @@+#!/usr/bin/env node+/**+ * Turn core-path benchmark reports (e2e/perf/core-paths.spec.ts, MUL-9539)+ * into one Markdown table, one column per report:+ *+ * node scripts/perf-core-report.mjs before=perf/a.json after=perf/b.json+ *+ * Reports measured against different datasets are refused: their numbers do+ * not describe the same work.+ */+import { readFileSync } from "node:fs";++const inputs = process.argv.slice(2).map((arg) => {+ const at = arg.indexOf("=");+ const label = at > 0 ? arg.slice(0, at) : arg;+ const path = at > 0 ? arg.slice(at + 1) : arg;+ return { label, report: JSON.parse(readFileSync(path, "utf8")) };+});+if (inputs.length === 0) {+ console.error("usage: node scripts/perf-core-report.mjs <label>=<report.json> [...]");+ process.exit(2);+}+const digests = new Set(inputs.map((i) => i.report.dataset?.digest));+if (digests.size > 1) {+ console.error(`reports use different datasets: ${[...digests].join(", ")}`);+ process.exit(1);+}++const ISSUE_ROWS = [+ ["open_content_ms", "Open → first comments visible (ms)"],+ ["open_stalls", "Open: stalls >50ms"],+ ["open_stall_max_ms", "Open: longest stall (ms)"],+ ["scroll_stalls", "Scroll to end: stalls >50ms"],+ ["scroll_stall_max_ms", "Scroll to end: longest stall (ms)"],+ ...["left", "right"].flatMap((side) => [+ [`${side}_toggle_next_paint_ms`, `${side === "left" ? "Left nav" : "Right sidebar"} toggle → next paint, median (ms)`],+ [`${side}_toggle_task_ms`, "… main-thread work per toggle, median (ms)"],+ [`${side}_toggle_stalls`, "… stalls >50ms in 10 toggles"],+ [`${side}_toggle_stall_max_ms`, "… longest stall (ms)"],+ ]),+];+const INBOX_ROWS = [+ ["ready_median_ms", "Click → content visible, median (ms)"],+ ["ready_p95_ms", "… p95 (ms)"],+ ["ready_max_ms", "… worst (ms)"],+ ["next_paint_median_ms", "Click → next paint, median (ms)"],+ ["next_paint_max_ms", "Click → next paint, worst (ms)"],+ ["stalls_per_switch", "Stalls >50ms per switch"],+ ["stall_max_ms", "Longest stall (ms)"],+ ["freezes", "Freezes >200ms (all switches)"],+];++const fmt = (v) => (typeof v === "number" ? (Number.isInteger(v) ? String(v) : v.toFixed(1)) : "—");+const header = `| | ${inputs.map((i) => i.label).join(" | ")} |\n|---|${inputs.map(() => "---:").join("|")}|`;+const lines = [];++const issueKeys = [...new Set(inputs.flatMap((i) => Object.keys(i.report.summary?.issue ?? {})))];+for (const key of issueKeys) {+ lines.push(`\n**Open a big issue: \`${key}\`** (median of samples)\n`, header);+ for (const [field, name] of ISSUE_ROWS) {+ lines.push(`| ${name} | ${inputs.map((i) => fmt(i.report.summary.issue[key]?.[field])).join(" | ")} |`);+ }+}+for (const phase of ["first-visit", "revisit"]) {+ if (!inputs.some((i) => i.report.summary?.inbox?.[phase])) continue;+ lines.push(`\n**Inbox switching: ${phase}** (all switches across samples)\n`, header);+ for (const [field, name] of INBOX_ROWS) {+ lines.push(`| ${name} | ${inputs.map((i) => fmt(i.report.summary.inbox[phase]?.[field])).join(" | ")} |`);+ }+}+if (inputs.some((i) => i.report.summary?.inbox?.heap_mb_after_gc)) {+ lines.push(`| JS heap after 30 switches, after GC (MB) | ${inputs.map((i) => fmt(i.report.summary.inbox.heap_mb_after_gc)).join(" | ")} |`);+}+const env = inputs[0].report;+lines.push(+ "",+ `Dataset ${env.dataset.version} (${env.dataset.digest}): ${Object.entries(env.dataset.counts).map(([k, v]) => `${v} ${k}`).join(", ")}.`,+ `Chromium ${env.environment.browser}, ${env.environment.viewport}, ${env.environment.cpu} × ${env.environment.cores}.`,+ ...inputs.map(({ label, report }) => {+ const e = report.environment;+ const until = e.inbox_until === "title" ? "issue title is visible" : "notified comment is in view";+ return `${label}: ref ${report.ref ?? "?"}, CPU ${e.cpu_throttle}×, ${e.repeats} samples` ++ (report.summary?.inbox?.["first-visit"] ? `, ${e.inbox_rows} Inbox rows, switch ends when the ${until}` : "") + ".";+ }),+);+console.log(lines.join("\n"));