Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9612: test(perf): run the core-path benchmark on Desktop, with idle CPU and memory growth (#10930)
Multica Evee67937b15bdc
diff --git a/e2e/perf/README.md b/e2e/perf/README.mdindex 5498174c3a..cd3f2d2521 100644--- a/e2e/perf/README.md+++ b/e2e/perf/README.md@@ -264,6 +264,69 @@ checkout's `apps/desktop/out`); `PERF_REPEATS`, `PERF_WARMUP` andwrites a Chrome trace and CPU profile of the last round's last tab cycle.The renderer bundle is not minified, so profiles carry real function names.+## Core paths on Desktop, idle CPU and memory growth++The same core paths run in the Electron app, plus two scenarios only Desktop+has (MUL-9612). `scripts/perf-desktop.mjs` builds Desktop for production+against the environment's API, starts that build with a DevTools port, runs+the specs over CDP with `PERF_PLATFORM=desktop`, and stops the app:++```bash+make up C=api ARGS="--ephemeral"+make env-exec ARGS="-- node scripts/perf-desktop.mjs --out $PWD/perf/desktop"+node scripts/perf-core-report.mjs web=perf/main.json \+ desktop=perf/desktop/core-paths.json desktop=perf/desktop/desktop-resources.json+```++It writes `core-paths.json`, `desktop-resources.json`, `desktop.log` (the+app's output) and `report.md`. `--scenarios` picks a subset (`core-issue`,+`core-inbox`, `desktop-idle`, `desktop-memory`); `--skip-build` reuses+`apps/desktop/out`, which must have been built against the same API port.+`PERF_*` variables pass through. A full run takes about 35 minutes.++- **Core paths** are the steps above, on the same dataset, with the same+ clock and the same report. Each sample clears the renderer's storage and+ HTTP cache, writes a tab layout holding only the measured route and+ reloads: the app boots onto that tab as it does on launch. That is the+ Desktop counterpart of opening a URL in a fresh browser context.+ Every boot also writes English as the language choice, as the web+ context's `locale: "en-US"` does; the specs match English labels, and+ Desktop would otherwise follow the OS language.+- **`desktop-idle`** opens the big issue (300 comments, 70 runs), waits 15 s,+ then touches nothing for `PERF_IDLE_SECONDS` (300). CPU is sampled every+ second per process role: main, renderer, GPU, utility (network, storage).+ 100% is one core. The renderer's own main-thread busy time and any stalls+ are reported beside it.+- **`desktop-memory`** clicks through the Work panel's twenty Inbox rows,+ round and round, for `PERF_MEMORY_SECONDS` (600), sampling resident memory+ every 5 s. It reports the growth slope over the whole window and over its+ second half (the first minutes include caches filling), the first and last+ minute, the JS heap at the end before and after GC, and whether switches+ got slower.++CPU and memory come from `ps` (`lib/process-tree.ts`): cumulative CPU time+and RSS of the Electron main process and its descendants, read from outside+the app. Processes without an Electron `--type` under it (the local daemon+Desktop starts, and its agents) are reported as `other` and left out of the+app total. Memory is RSS, not macOS's "memory footprint" in Activity Monitor;+compare it run to run, not with that number.++The app runs unpackaged from `apps/desktop/out` with a production renderer+bundle; packaging, signing and auto-update are not part of it. It gets its own+userData directory (`Multica Canary Perf <env>`) and starts signed out; the+specs sign in as the dataset's user. Keep its window visible: Chromium+throttles a hidden window, so `desktop-idle` fails rather than report one.++`--attach` measures the development Desktop of `make up C=desktop+ARGS="--cdp"` instead and leaves it running. Its React is the development+build: slower, and it records profiling data, so use it only for problems+that exist only there, such as the User Timing leak of MUL-8781:++```bash+make up C=api,desktop ARGS="--ephemeral --cdp"+make env-exec ARGS="-- node scripts/perf-desktop.mjs --attach --scenarios desktop-memory --out $PWD/perf/dev"+```+## Inbox jump`inbox-jump.spec.ts` opens a notification about a reply deep in a long issuediff --git a/e2e/perf/core-paths.spec.ts b/e2e/perf/core-paths.spec.tsindex e56d3f5b03..24d6c38d77 100644--- a/e2e/perf/core-paths.spec.ts+++ b/e2e/perf/core-paths.spec.ts@@ -11,16 +11,20 @@* 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.+ * PERF_PLATFORM=desktop runs the same steps in the Electron renderer+ * (`lib/perf-target.ts`, launched by `scripts/perf-desktop.mjs`).*/-import { expect, test, type Browser, type BrowserContext, type CDPSession, type Page } from "@playwright/test";+import { expect, test, type CDPSession, type Request } 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,+ 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";+import { perfTarget, PLATFORM, type Sample, type Target } from "./lib/perf-target";+import { detailSelector, inboxStorage, openInbox, switchTo, waitForIssue } from "./lib/core-steps";const scenario = process.env.PERF_SCENARIO ?? "";const runIssue = scenario === "core-paths" || scenario === "core-issue";@@ -54,6 +58,7 @@ test.describe.configure({ mode: "serial" });let manifest: Manifest;let token: string;+let target: Target;const report: { issue: Record<string, unknown>[]; inbox: Record<string, unknown>[] } = { issue: [], inbox: [] };test.beforeAll(async () => {@@ -65,16 +70,18 @@ test.beforeAll(async () => {manifest = await ensureDataset(api);});-test.afterAll(async ({ browser }) => {- if (!manifest || !process.env.PERF_REPORT_PATH) return;+test.afterAll(async () => {+ if (!manifest || !target || !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,+ kind: "core-paths",+ platform: PLATFORM,dataset: { version: manifest.version, digest: manifest.digest, counts: manifest.counts },environment: {- browser: browser.version(), viewport: `${VIEWPORT.width}x${VIEWPORT.height}`, cpu_throttle: CPU_THROTTLE,+ browser: await target.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,},@@ -83,16 +90,9 @@ test.afterAll(async ({ browser }) => {}, 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 };+/** A fresh sample: a new browser context on the web, a cleared and reloaded renderer on desktop. */+async function newSample(storage?: Record<string, string>): Promise<Sample> {+ return target.newSample({ token, viewport: VIEWPORT, cpuThrottle: CPU_THROTTLE, storage });}/** Main-thread task time so far (ms), from the renderer's own counters. */@@ -114,61 +114,24 @@ function summarizeToggles(toggles: Toggle[]) {};}-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. */-/**- * `first-screen`: the first comment is mounted, or the history starts below- * the first screen (a long description or sub-issue list above it). Virtuoso- * renders no rows out of view, so a comment below the fold mounts only when- * the reader scrolls to it — that is the scroll step's job, not the open's.- */-async function waitForIssue(page: Page, title: string, commentId: string, mode: "first-screen" | "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 (mode === "first-screen" && root && !target) {- const activity = detail.querySelector<HTMLElement>('[data-mc="issue-activity"]');- if (activity && activity.getBoundingClientRect().top >= root.getBoundingClientRect().bottom) {- marks.content ??= performance.now();- return { title: marks.title, content: marks.content };- }- }- 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);+ target ??= await perfTarget(browser, token);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);+ const sample = await newSample();+ const { page, cdp, errors } = sample;+ let apiRequests = 0;+ let imagesFetched = 0;+ const onRequest = (request: Request) => { if (new URL(request.url()).pathname.startsWith("/api/")) apiRequests++; };+ const onFinished = (request: Request) => { if (/\/api\/attachments\/[^/]+\/download/.test(request.url())) imagesFetched++; };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" });+ page.on("request", onRequest);+ page.on("requestfinished", onFinished);+ await sample.open(`/${manifest.workspace.slug}/issues/${issue.id}`);const marks = await waitForIssue(page, issue.title, issue.firstCommentId, "first-screen");await settle(page, LOAD_TAIL_MS);const load = await stallsBetween(page, 0, await pageNow(page));@@ -249,7 +212,9 @@ test("open, scroll and toggle the sidebar on a big issue", async ({ browser }) =console.log(JSON.stringify(record));}} finally {- await context.close();+ page.off("request", onRequest);+ page.off("requestfinished", onFinished);+ await sample.close();}}}@@ -258,40 +223,22 @@ test("open, scroll and toggle the sidebar on a big issue", async ({ browser }) =test("switch between Inbox rows in the Work panel", async ({ browser }) => {test.skip(!runInbox, "inbox scenario not selected");test.setTimeout(1_800_000);+ target ??= await perfTarget(browser, token);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);+ const sample = await newSample(inboxStorage(manifest.workspace.slug));+ const { page, cdp, errors } = sample;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") {- const showMore = page.getByRole("button", { name: /^Show \d+ more/ }).first();- const hidden = Number((await showMore.textContent())?.match(/\d+/)?.[0] ?? 0);- expect(hidden, "the Inbox section hides hundreds of rows").toBeGreaterThan(500);- await showMore.click();- // A virtualized list mounts only the rows near the viewport, so the- // expansion is read from the toggle rather than from the row count.- await expect(page.getByRole("button", { name: "Show fewer" }).first()).toHaveAttribute("aria-expanded", "true");- }- await expect.poll(() => rows.count(), "the Inbox section shows the twenty measured rows").toBeGreaterThanOrEqual(20);- await settle(page, 2000);+ const rows = await openInbox(sample, manifest, INBOX_ROWS);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 marks = await switchTo(page, rows, issue, INBOX_UNTIL === "title" ? "title" : "in-view");const click = await lastClick(page);await settle(page, SWITCH_DWELL_MS);const end = await pageNow(page);@@ -302,10 +249,8 @@ test("switch between Inbox rows in the Work panel", async ({ browser }) => {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;+ await cdp.send("HeapProfiler.collectGarbage");+ const heap = (await cdp.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) {@@ -314,7 +259,7 @@ test("switch between Inbox rows in the Work panel", async ({ browser }) => {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();+ await sample.close();}}});diff --git a/e2e/perf/desktop-resources.spec.ts b/e2e/perf/desktop-resources.spec.tsnew file mode 100644index 0000000000..8e79840b8c--- /dev/null+++ b/e2e/perf/desktop-resources.spec.ts@@ -0,0 +1,193 @@+/**+ * Desktop-only resource scenarios (MUL-9612): what the Electron app costs the+ * machine while someone reads, and whether its memory keeps growing while+ * someone works through their Inbox.+ *+ * 1. `desktop-idle` — open the big issue (300 comments, 70 runs), let it+ * settle, then touch nothing for PERF_IDLE_SECONDS (300) and sample the+ * app's CPU every second.+ * 2. `desktop-memory` — click through the Work panel's twenty Inbox rows,+ * round and round, for PERF_MEMORY_SECONDS (600), sampling resident memory+ * every five seconds, and report how fast it grows.+ *+ * CPU and memory come from `ps`, per process role (`lib/process-tree.ts`):+ * nothing in the app measures itself. The scenarios drive the same Desktop+ * renderer as `core-paths.spec.ts` with PERF_PLATFORM=desktop; run them+ * through `scripts/perf-desktop.mjs`. Opt in with PERF_SCENARIO=+ * desktop-resources (both), desktop-idle or desktop-memory.+ */+import { expect, test } from "@playwright/test";+import { mkdirSync, writeFileSync } from "node:fs";+import { cpus, loadavg, totalmem } from "node:os";+import { dirname } from "node:path";+import { median, pageNow, quantile, settle, stallsBetween } from "./lib/frame-metrics";+import { ensureDataset, perfApi, resetInbox, type Manifest } from "./lib/core-dataset";+import { inboxStorage, openInbox, switchTo, waitForIssue } from "./lib/core-steps";+import { perfTarget, PLATFORM, type Target } from "./lib/perf-target";+import {+ cdpOwnerPid, cpuByRole, rssByRole, ROLES, slopePerMinute, snapshotTree, type TreeSnapshot,+} from "./lib/process-tree";++const scenario = process.env.PERF_SCENARIO ?? "";+const runIdle = scenario === "desktop-resources" || scenario === "desktop-idle";+const runMemory = scenario === "desktop-resources" || scenario === "desktop-memory";+const IDLE_SECONDS = Number(process.env.PERF_IDLE_SECONDS ?? 300);+/** Untouched time between the content appearing and the idle window, so the tail of loading is not counted as idle. */+const IDLE_SETTLE_MS = 15_000;+const MEMORY_SECONDS = Number(process.env.PERF_MEMORY_SECONDS ?? 600);+const MEMORY_SAMPLE_MS = 5000;+const SWITCH_DWELL_MS = 1000;+const VIEWPORT = { width: 1440, height: 900 };++test.describe.configure({ mode: "serial" });++let manifest: Manifest;+let token: string;+let target: Target;+let appPid: number;+const report: Record<string, unknown> = {};++test.beforeAll(async ({ browser }) => {+ test.skip(!runIdle && !runMemory, "set PERF_SCENARIO=desktop-resources (or desktop-idle / desktop-memory)");+ expect(PLATFORM, "these scenarios measure the Electron app: set PERF_PLATFORM=desktop").toBe("desktop");+ expect(process.env.MULTICA_DEV_PROFILE, "run through `make env-exec` against an isolated environment").toMatch(/^dev-/);+ test.setTimeout(900_000);+ const api = await perfApi();+ token = api.getToken()!;+ manifest = await ensureDataset(api);+ target = await perfTarget(browser, token);+ appPid = Number(process.env.PERF_DESKTOP_PID) || cdpOwnerPid(process.env.PERF_DESKTOP_CDP_URL || process.env.MULTICA_DEV_DESKTOP_CDP_URL!);+ snapshotTree(appPid);+});++test.afterAll(async () => {+ if (!manifest || !target || !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,+ kind: "desktop-resources",+ platform: PLATFORM,+ build: process.env.PERF_DESKTOP_BUILD ?? null,+ dataset: { version: manifest.version, digest: manifest.digest, counts: manifest.counts },+ environment: {+ browser: await target.version(), viewport: `${VIEWPORT.width}x${VIEWPORT.height}`,+ cpu: cpus()[0]?.model, cores: cpus().length, memory_gb: Math.round(totalmem() / 2 ** 30), load_1m_end: loadavg()[0],+ },+ ...report,+ }, null, 2));+});++const r1 = (v: number) => Math.round(v * 10) / 10;+const byRole = <T>(f: (role: (typeof ROLES)[number] | "app") => T) =>+ Object.fromEntries([...ROLES, "app" as const].map((role) => [role, f(role)]));++test("idle on a big issue", async () => {+ test.skip(!runIdle, "idle scenario not selected");+ test.setTimeout(IDLE_SECONDS * 1000 + 300_000);+ const issue = manifest.issues.large!;+ const sample = await target.newSample({ token, viewport: VIEWPORT, cpuThrottle: 1 });+ const { page, cdp, errors } = sample;+ try {+ await sample.open(`/${manifest.workspace.slug}/issues/${issue.id}`);+ await waitForIssue(page, issue.title, issue.firstCommentId, "first-screen");+ await settle(page, IDLE_SETTLE_MS);+ // A hidden or occluded window is throttled by Chromium and would read as idle.+ expect(await page.evaluate(() => document.visibilityState), "the Desktop window is visible").toBe("visible");++ const taskBefore = (await cdp.send("Performance.getMetrics")).metrics.find((m) => m.name === "TaskDuration")?.value ?? 0;+ const pageStart = await pageNow(page);+ const snapshots: TreeSnapshot[] = [snapshotTree(appPid)];+ const until = snapshots[0]!.at + IDLE_SECONDS * 1000;+ while (Date.now() < until) {+ await new Promise((done) => setTimeout(done, Math.min(1000, until - Date.now())));+ snapshots.push(snapshotTree(appPid));+ }+ const taskAfter = (await cdp.send("Performance.getMetrics")).metrics.find((m) => m.name === "TaskDuration")?.value ?? 0;+ const stalls = await stallsBetween(page, pageStart, await pageNow(page));+ expect(errors).toEqual([]);++ const first = snapshots[0]!;+ const last = snapshots.at(-1)!;+ const seconds = (last.at - first.at) / 1000;+ const perSecond = snapshots.slice(1).map((s, i) => cpuByRole(snapshots[i]!, s));+ const whole = cpuByRole(first, last);+ report.idle = {+ issue: "large",+ seconds: Math.round(seconds),+ cpu_pct: byRole((role) => ({+ mean: r1(whole[role]),+ p95: r1(quantile(perSecond.map((c) => c[role]), 0.95)),+ max: r1(Math.max(...perSecond.map((c) => c[role]))),+ })),+ renderer_main_thread_busy_pct: r1(((taskAfter - taskBefore) / seconds) * 100),+ rss_mb: byRole((role) => ({ start: Math.round(rssByRole(first)[role]), end: Math.round(rssByRole(last)[role]) })),+ processes: Object.fromEntries(ROLES.map((role) => [role, last.processes.filter((p) => p.role === role).length])),+ stalls,+ series: perSecond.map((c) => ({ app: r1(c.app), renderer: r1(c.renderer), gpu: r1(c.gpu), main: r1(c.main) })),+ };+ console.log(JSON.stringify({ idle_cpu_pct: (report.idle as { cpu_pct: unknown }).cpu_pct }));+ } finally {+ await sample.close();+ }+});++test("memory while switching Inbox rows", async () => {+ test.skip(!runMemory, "memory scenario not selected");+ test.setTimeout(MEMORY_SECONDS * 1000 + 300_000);+ await resetInbox(manifest);+ const sample = await target.newSample({ token, viewport: VIEWPORT, cpuThrottle: 1, storage: inboxStorage(manifest.workspace.slug) });+ const { page, cdp, errors } = sample;+ try {+ const rows = await openInbox(sample, manifest, "20");+ const order = manifest.inbox.slice(0, 20).map((n) => manifest.issues[n.key]!);+ const snapshots: TreeSnapshot[] = [snapshotTree(appPid)];+ const switches: { at_s: number; ready_ms: number }[] = [];+ const start = snapshots[0]!.at;+ const until = start + MEMORY_SECONDS * 1000;+ for (let i = 0; Date.now() < until; i++) {+ const issue = order[i % order.length]!;+ const marks = await switchTo(page, rows, issue, "in-view");+ const click = await page.evaluate(() => window.__corePerf.clicks.at(-1)!);+ switches.push({ at_s: Math.round((Date.now() - start) / 1000), ready_ms: Math.round(marks.content - click) });+ await settle(page, SWITCH_DWELL_MS);+ if (Date.now() - snapshots.at(-1)!.at >= MEMORY_SAMPLE_MS) snapshots.push(snapshotTree(appPid));+ }+ snapshots.push(snapshotTree(appPid));+ // After the measured window, so a forced GC cannot shape the RSS series.+ const heap = async () => Math.round(((await cdp.send("Performance.getMetrics")).metrics+ .find((m) => m.name === "JSHeapUsedSize")?.value ?? 0) / 1e6);+ const heapEnd = await heap();+ await cdp.send("HeapProfiler.collectGarbage");+ const heapAfterGc = await heap();+ expect(errors).toEqual([]);++ const minutes = snapshots.map((s) => (s.at - start) / 60_000);+ const rss = snapshots.map(rssByRole);+ const half = Math.floor(snapshots.length / 2);+ const minuteOf = (from: number, to: number, role: keyof (typeof rss)[number]) =>+ median(rss.filter((_, i) => minutes[i]! >= from && minutes[i]! < to).map((r) => r[role]));+ const total = minutes.at(-1)!;+ const firstSwitches = switches.slice(0, 40).map((s) => s.ready_ms);+ const lastSwitches = switches.slice(-40).map((s) => s.ready_ms);+ report.memory = {+ minutes: r1(total),+ switches: switches.length,+ rss_mb: byRole((role) => ({+ first_minute: Math.round(minuteOf(0, 1, role)),+ last_minute: Math.round(minuteOf(total - 1, Infinity, role)),+ slope_mb_per_min: r1(slopePerMinute(minutes, rss.map((r) => r[role]))),+ // The first minutes include caches filling; the second half is the steady state.+ slope_second_half_mb_per_min: r1(slopePerMinute(minutes.slice(half), rss.slice(half).map((r) => r[role]))),+ })),+ js_heap_mb_end: heapEnd,+ js_heap_mb_after_gc: heapAfterGc,+ switch_ready_ms: { first_40_median: median(firstSwitches), last_40_median: median(lastSwitches) },+ series: snapshots.map((s, i) => ({ min: r1(minutes[i]!), app: Math.round(rss[i]!.app), renderer: Math.round(rss[i]!.renderer) })),+ };+ console.log(JSON.stringify({ memory_rss_mb: (report.memory as { rss_mb: unknown }).rss_mb }));+ } finally {+ await sample.close();+ }+});diff --git a/e2e/perf/lib/core-steps.ts b/e2e/perf/lib/core-steps.tsnew file mode 100644index 0000000000..1b6966337a--- /dev/null+++ b/e2e/perf/lib/core-steps.ts@@ -0,0 +1,106 @@+/**+ * Steps shared by the core-path benchmark and the Desktop resource scenarios+ * (MUL-9539, MUL-9612): waiting for an issue's content, and driving the Work+ * panel's Inbox.+ */+import { expect, type Locator, type Page, type Response } from "@playwright/test";+import { settle } from "./frame-metrics";+import type { Manifest, SeededIssue } from "./core-dataset";+import type { Sample } from "./perf-target";++/** The Work panel's Inbox section at its largest limit, twenty rows. */+export function inboxStorage(slug: string): Record<string, string> {+ return { [`multica_sidebar_tree:${slug}`]: JSON.stringify({ state: { inboxSettings: { limit: 20 } }, version: 0 }) };+}++export 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.+ *+ * `first-screen`: the first comment is mounted, or the history starts below+ * the first screen (a long description or sub-issue list above it). Virtuoso+ * renders no rows out of view, so a comment below the fold mounts only when+ * the reader scrolls to it — that is the scroll step's job, not the open's.+ */+export async function waitForIssue(page: Page, title: string, commentId: string, mode: "first-screen" | "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 (mode === "first-screen" && root && !target) {+ const activity = detail.querySelector<HTMLElement>('[data-mc="issue-activity"]');+ if (activity && activity.getBoundingClientRect().top >= root.getBoundingClientRect().bottom) {+ marks.content ??= performance.now();+ return { title: marks.title, content: marks.content };+ }+ }+ 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 };+}++/**+ * Boots the app on the issues list and waits for the Work panel's Inbox rows.+ * `all` first presses "Show N more", mounting every row.+ */+export async function openInbox(sample: Sample, manifest: Manifest, rowsShown: "20" | "all"): Promise<Locator> {+ const { page } = sample;+ const rows = page.locator("li[data-inbox-row]");+ // The API sheds Inbox reads under load (503, MUL-9456) and the panel then+ // shows "No notifications" instead of retrying. Nothing is measured before+ // the rows are there, so boot again rather than fail the run.+ for (let attempt = 1; ; attempt++) {+ let shed = false;+ const onResponse = (response: Response) => {+ if (new URL(response.url()).pathname === "/api/inbox" && response.status() === 503) shed = true;+ };+ page.on("response", onResponse);+ try {+ await sample.open(`/${manifest.workspace.slug}/issues`);+ await expect.poll(async () => shed || (await rows.count()) > 0, { timeout: 60_000 }).toBe(true);+ } finally {+ page.off("response", onResponse);+ }+ if (!shed) break;+ if (attempt === 3) throw new Error("the API shed the Inbox read on three boots in a row");+ console.warn(`the API shed the Inbox read (attempt ${attempt}); booting again`);+ }+ await expect(rows.first()).toBeVisible();+ const firstTitle = manifest.issues[manifest.inbox[0]!.key]!.title;+ await expect(rows.filter({ hasText: firstTitle })).toHaveCount(1);+ if (rowsShown === "all") {+ const showMore = page.getByRole("button", { name: /^Show \d+ more/ }).first();+ const hidden = Number((await showMore.textContent())?.match(/\d+/)?.[0] ?? 0);+ expect(hidden, "the Inbox section hides hundreds of rows").toBeGreaterThan(500);+ await showMore.click();+ // A virtualized list mounts only the rows near the viewport, so the+ // expansion is read from the toggle rather than from the row count.+ await expect(page.getByRole("button", { name: "Show fewer" }).first()).toHaveAttribute("aria-expanded", "true");+ }+ await expect.poll(() => rows.count(), "the Inbox section shows the twenty measured rows").toBeGreaterThanOrEqual(20);+ await settle(page, 2000);+ return rows;+}++/** Clicks the issue's Inbox row and resolves once its content is on screen. */+export async function switchTo(page: Page, rows: Locator, issue: SeededIssue, mode: "in-view" | "title") {+ await page.evaluate(() => { window.__corePerf.marks = {}; });+ await rows.filter({ hasText: issue.title }).locator("a").first().click();+ return waitForIssue(page, issue.title, issue.targetCommentId, mode);+}diff --git a/e2e/perf/lib/perf-target.ts b/e2e/perf/lib/perf-target.tsnew file mode 100644index 0000000000..53bab206ab--- /dev/null+++ b/e2e/perf/lib/perf-target.ts@@ -0,0 +1,197 @@+/**+ * Where a core-path sample runs: a fresh Chromium context against the web+ * build (`web`), or the real Electron renderer over CDP (`desktop`, MUL-9612).+ *+ * Both give the spec the same thing: a page with the frame metrics installed,+ * a CDP session, collected page errors, and an `open(path)` that boots the app+ * straight onto a route. On the web that is a navigation. Desktop routes live+ * in a memory router, so the sample writes a tab layout holding only that+ * route and reloads the renderer: the app restores the tab exactly as it does+ * on launch. Each desktop sample also clears storage and the HTTP cache, so it+ * starts as cold as a fresh browser context does.+ */+import { chromium, type Browser, type CDPSession, type Page } from "@playwright/test";+import { installFrameMetrics } from "./frame-metrics";++export type Platform = "web" | "desktop";+export const PLATFORM: Platform = process.env.PERF_PLATFORM === "desktop" ? "desktop" : "web";++export interface SampleOptions {+ token: string;+ viewport: { width: number; height: number };+ cpuThrottle: number;+ /** localStorage entries in place before the app boots. */+ storage?: Record<string, string>;+}++export interface Sample {+ page: Page;+ cdp: CDPSession;+ errors: string[];+ /** Boots the app onto `path` (`/<slug>/...`). Resolves once the navigation has committed. */+ open(path: string): Promise<void>;+ close(): Promise<void>;+}++export interface Target {+ platform: Platform;+ /** Chromium version, plus Electron's on desktop. */+ version(): Promise<string>;+ newSample(options: SampleOptions): Promise<Sample>;+}++async function prepareSession(page: Page, cdp: CDPSession, options: SampleOptions) {+ await cdp.send("Performance.enable");+ if (options.cpuThrottle > 1) await cdp.send("Emulation.setCPUThrottlingRate", { rate: options.cpuThrottle });+ const errors: string[] = [];+ const onError = (error: Error) => errors.push(error.message);+ page.on("pageerror", onError);+ return { errors, onError };+}++export function webTarget(browser: Browser): Target {+ return {+ platform: "web",+ version: async () => browser.version(),+ async newSample(options) {+ const context = await browser.newContext({ viewport: options.viewport, locale: "en-US", colorScheme: "light" });+ const page = await context.newPage();+ await installFrameMetrics(page, options.token);+ if (options.storage) {+ await page.addInitScript((entries) => {+ for (const [key, value] of Object.entries(entries)) localStorage.setItem(key, value);+ }, options.storage);+ }+ const cdp = await context.newCDPSession(page);+ const { errors } = await prepareSession(page, cdp, options);+ return {+ page, cdp, errors,+ open: async (path) => { await page.goto(path, { waitUntil: "commit" }); },+ close: () => context.close(),+ };+ },+ };+}++/** The persisted tab layout (tab store v5) holding one tab on `path`. */+function tabLayout(path: string): string {+ const slug = path.split("/")[1]!;+ const tab = { id: "perf-tab", url: path, title: "Benchmark", pinned: false, history: { stack: [path], index: 0 }, memento: { scroll: {}, view: {} } };+ return JSON.stringify({+ state: {+ activeWorkspaceSlug: slug,+ byWorkspace: {+ [slug]: { activeTabId: tab.id, recentTabIds: [], browsingHistory: [], browsingHistoryTitles: {}, issueAliases: {}, tabs: [tab] },+ },+ },+ version: 5,+ });+}++/** The main window's renderer: issue windows load the same page, only the preload tells them apart. */+async function mainWindow(browser: Browser, deadline: number): Promise<Page> {+ for (;;) {+ for (const page of browser.contexts().flatMap((context) => context.pages())) {+ const kind = await page.evaluate(() => (window as unknown as { desktopAPI?: { windowContext?: { kind?: string } } })+ .desktopAPI?.windowContext?.kind ?? (("desktopAPI" in window) ? "main" : "")).catch(() => "");+ if (kind === "main") return page;+ }+ if (Date.now() > deadline) throw new Error("no main Desktop window appeared over CDP");+ await new Promise((done) => setTimeout(done, 500));+ }+}++/** sessionStorage key carrying the next boot's localStorage across the reload. */+const BOOT_KEY = "__perf_boot_storage";++/**+ * Desktop picks its language from localStorage, then from the OS (the web+ * target pins it through the context's `locale`). The specs find controls by+ * their English names, so every desktop boot writes the Settings choice for+ * English: on a Chinese or Japanese system the app would otherwise come up in+ * that language and the scenarios would time out looking for+ * "Toggle right sidebar".+ */+const DESKTOP_LOCALE = { "multica-locale": "en" };++/** Writes `storage` (plus the English locale) for the next boot and reloads into it. */+async function bootWith(page: Page, storage: Record<string, string>) {+ const entries = { ...DESKTOP_LOCALE, ...storage };+ await page.evaluate(({ key, value }) => sessionStorage.setItem(key, value), { key: BOOT_KEY, value: JSON.stringify(entries) });+ await page.reload({ waitUntil: "commit" });+}++/**+ * Boots once, outside any measurement, and fails with a clear message when+ * the app still comes up in another language, instead of letting a scenario+ * time out on a label it cannot find. index.html ships `lang="en"`; App+ * replaces it with the resolved locale in a layout effect of its first+ * render, so the value is final once #root has content.+ */+async function assertEnglish(page: Page) {+ await bootWith(page, {});+ await page.waitForFunction(() => !!document.getElementById("root")?.hasChildNodes(), undefined, { timeout: 60_000 });+ const lang = await page.evaluate(() => document.documentElement.lang);+ if (lang !== "en") throw new Error(`Desktop booted in "${lang}" despite multica-locale=en; the specs match English labels`);+}++export async function desktopTarget(cdpUrl: string, token: string): Promise<Target> {+ const deadline = Date.now() + 60_000;+ let browser: Browser | undefined;+ while (!browser) {+ try {+ browser = await chromium.connectOverCDP(cdpUrl);+ } catch (error) {+ if (Date.now() > deadline) throw new Error(`could not attach to Desktop at ${cdpUrl}: ${(error as Error).message}`);+ await new Promise((done) => setTimeout(done, 1000));+ }+ }+ // The connection is never closed: it drops when the worker exits, leaving the+ // app running for whoever started it. `browser.close()` could quit the app.+ const page = await mainWindow(browser, deadline);+ // Installed once: init scripts persist across reloads and would stack per+ // sample. The storage reset runs first, in the new document before any app+ // script, so whatever the outgoing page persists while unloading is gone;+ // the frame metrics then sign the session in.+ await page.addInitScript((key) => {+ const raw = sessionStorage.getItem(key);+ if (!raw) return;+ sessionStorage.clear();+ localStorage.clear();+ for (const [name, value] of Object.entries(JSON.parse(raw) as Record<string, string>)) localStorage.setItem(name, value);+ }, BOOT_KEY);+ await installFrameMetrics(page, token);+ await assertEnglish(page);+ const connected = browser;+ return {+ platform: "desktop",+ async version() {+ const ua = await page.evaluate(() => navigator.userAgent);+ return `${connected.version()} (Electron ${ua.match(/Electron\/([\d.]+)/)?.[1] ?? "?"})`;+ },+ async newSample(options) {+ const cdp = await page.context().newCDPSession(page);+ await cdp.send("Network.clearBrowserCache");+ await page.setViewportSize(options.viewport);+ const { errors, onError } = await prepareSession(page, cdp, options);+ return {+ page, cdp, errors,+ async open(path) {+ await bootWith(page, { ...options.storage, multica_tabs: tabLayout(path) });+ },+ async close() {+ page.off("pageerror", onError);+ if (options.cpuThrottle > 1) await cdp.send("Emulation.setCPUThrottlingRate", { rate: 1 }).catch(() => {});+ await cdp.detach().catch(() => {});+ },+ };+ },+ };+}++export async function perfTarget(browser: Browser, token: string): Promise<Target> {+ if (PLATFORM === "web") return webTarget(browser);+ const cdpUrl = process.env.PERF_DESKTOP_CDP_URL || process.env.MULTICA_DEV_DESKTOP_CDP_URL;+ if (!cdpUrl) throw new Error("PERF_PLATFORM=desktop needs PERF_DESKTOP_CDP_URL (scripts/perf-desktop.mjs sets it)");+ return desktopTarget(cdpUrl, token);+}diff --git a/e2e/perf/lib/process-tree.ts b/e2e/perf/lib/process-tree.tsnew file mode 100644index 0000000000..5b8c8838ab--- /dev/null+++ b/e2e/perf/lib/process-tree.ts@@ -0,0 +1,121 @@+/**+ * CPU and memory of the Desktop app, sampled from outside the app (MUL-9612).+ *+ * `ps` reports every process's cumulative CPU time and resident set size; the+ * app is the Electron main process and its descendants. CPU % is the CPU time+ * a role used between two snapshots over the wall time between them, so 100%+ * is one core busy. Nothing runs inside the app to measure it.+ *+ * Electron tags its helpers with `--type=`: renderer, gpu-process, utility+ * (network, storage, audio). Anything else under the main process — the+ * local daemon Desktop starts and the agent CLIs under it — is `other` and is+ * kept out of the app's total.+ */+import { execFileSync } from "node:child_process";++export const ROLES = ["main", "renderer", "gpu", "utility", "other"] as const;+export type Role = (typeof ROLES)[number];+/** Roles that make up the app itself. */+export const APP_ROLES: Role[] = ["main", "renderer", "gpu", "utility"];++export interface ProcessSample {+ pid: number;+ role: Role;+ cpu_s: number;+ rss_mb: number;+}++export interface TreeSnapshot {+ /** Milliseconds since the epoch. */+ at: number;+ processes: ProcessSample[];+}++/** `ps` CPU time: `[[dd-]hh:]mm:ss[.ff]` (Linux) or `mm:ss.ff` (macOS), in seconds. */+export function parseCpuTime(value: string): number {+ const [days, clock] = value.includes("-") ? value.split("-") as [string, string] : ["0", value];+ const seconds = clock.split(":").reduce((sum, part) => sum * 60 + Number(part), 0);+ return Number(days) * 86_400 + seconds;+}++function roleOf(pid: number, root: number, command: string): Role {+ if (pid === root) return "main";+ const type = command.match(/--type=([\w-]+)/)?.[1];+ if (type === "renderer") return "renderer";+ if (type === "gpu-process") return "gpu";+ if (type === "utility" || type === "zygote") return "utility";+ return "other";+}++/** The process tree under `root`, from one `ps` call. */+export function snapshotTree(root: number): TreeSnapshot {+ const out = execFileSync("ps", ["-A", "-o", "pid=,ppid=,time=,rss=,command="], { encoding: "utf8", maxBuffer: 32 << 20 });+ const at = Date.now();+ const rows = out.split("\n").flatMap((line) => {+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(.*)$/);+ return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), time: m[3]!, rss: Number(m[4]), command: m[5]! }] : [];+ });+ const children = new Map<number, typeof rows>();+ for (const row of rows) children.set(row.ppid, [...(children.get(row.ppid) ?? []), row]);+ const self = rows.find((row) => row.pid === root);+ if (!self) throw new Error(`process ${root} is not running`);+ const tree = [self];+ for (let i = 0; i < tree.length; i++) tree.push(...(children.get(tree[i]!.pid) ?? []));+ return {+ at,+ processes: tree.map((row) => ({+ pid: row.pid,+ role: roleOf(row.pid, root, row.command),+ cpu_s: parseCpuTime(row.time),+ rss_mb: row.rss / 1024,+ })),+ };+}++export type ByRole = Record<Role, number>;+const zero = (): ByRole => ({ main: 0, renderer: 0, gpu: 0, utility: 0, other: 0 });++export function rssByRole(snapshot: TreeSnapshot): ByRole & { app: number } {+ const sum = zero();+ for (const p of snapshot.processes) sum[p.role] += p.rss_mb;+ return { ...sum, app: APP_ROLES.reduce((total, role) => total + sum[role], 0) };+}++/**+ * CPU % per role between two snapshots. A process that exists only in the+ * later one counts from zero; one that exited is dropped, so a crash cannot+ * produce negative CPU.+ */+export function cpuByRole(before: TreeSnapshot, after: TreeSnapshot): ByRole & { app: number } {+ const seconds = (after.at - before.at) / 1000;+ const prior = new Map(before.processes.map((p) => [p.pid, p.cpu_s]));+ const used = zero();+ for (const p of after.processes) used[p.role] += Math.max(0, p.cpu_s - (prior.get(p.pid) ?? 0));+ const pct = zero();+ for (const role of ROLES) pct[role] = (used[role] / seconds) * 100;+ return { ...pct, app: APP_ROLES.reduce((total, role) => total + pct[role], 0) };+}++/** Least-squares slope of `values` against `minutes`, per minute. */+export function slopePerMinute(minutes: number[], values: number[]): number {+ const n = minutes.length;+ if (n < 2) return NaN;+ const mx = minutes.reduce((a, b) => a + b, 0) / n;+ const my = values.reduce((a, b) => a + b, 0) / n;+ let num = 0;+ let den = 0;+ for (let i = 0; i < n; i++) {+ num += (minutes[i]! - mx) * (values[i]! - my);+ den += (minutes[i]! - mx) ** 2;+ }+ return num / den;+}++/** The Electron main process that serves CDP on `cdpUrl`'s port (the browser process owns that listener). */+export function cdpOwnerPid(cdpUrl: string): number {+ const port = new URL(cdpUrl).port;+ const out = execFileSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8" }).trim();+ const pid = Number(out.split("\n")[0]);+ if (!pid) throw new Error(`nothing listens on CDP port ${port}`);+ return pid;+}diff --git a/scripts/perf-core-report.mjs b/scripts/perf-core-report.mjsindex e6b36d3b93..a9935f3a67 100644--- a/scripts/perf-core-report.mjs+++ b/scripts/perf-core-report.mjs@@ -1,13 +1,18 @@#!/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:+ * and Desktop resource reports (e2e/perf/desktop-resources.spec.ts, MUL-9612)+ * into Markdown tables, one column per report:** node scripts/perf-core-report.mjs before=perf/a.json after=perf/b.json+ * node scripts/perf-core-report.mjs web=perf/web.json \+ * desktop=perf/desktop/core-paths.json desktop=perf/desktop/desktop-resources.json*- * Reports measured against different datasets are refused: their numbers do- * not describe the same work. `scripts/perf-compare.mjs --scenario core-paths`- * builds and measures two refs itself and renders its summary with this module.+ * Each report lands in the tables of its own kind, so one label can name a+ * core-path report and a resource report from the same run. Reports measured+ * against different datasets are refused: their numbers do not describe the+ * same work. `scripts/perf-compare.mjs --scenario core-paths` builds and+ * measures two refs itself and renders its summary with this module.*/import { readFileSync } from "node:fs";import { resolve } from "node:path";@@ -36,46 +41,86 @@ const INBOX_ROWS = [["stall_max_ms", "Longest stall (ms)"],["freezes", "Freezes >200ms (all switches)"],];+const IDLE_ROWS = [+ ["cpu_pct.app.mean", "App CPU, mean (% of one core)"],+ ["cpu_pct.app.p95", "… p95 of 1 s samples"],+ ["cpu_pct.renderer.mean", "Renderer CPU, mean"],+ ["cpu_pct.gpu.mean", "GPU process CPU, mean"],+ ["cpu_pct.main.mean", "Main process CPU, mean"],+ ["cpu_pct.utility.mean", "Utility processes CPU, mean"],+ ["renderer_main_thread_busy_pct", "Renderer main thread busy (%)"],+ ["stalls.stalls", "Stalls >50ms while idle"],+ ["rss_mb.app.end", "App memory (RSS) at the end (MB)"],+];+const MEMORY_ROWS = [+ ["switches", "Inbox switches"],+ ["rss_mb.app.first_minute", "App RSS, first minute (MB)"],+ ["rss_mb.app.last_minute", "App RSS, last minute (MB)"],+ ["rss_mb.app.slope_mb_per_min", "App RSS growth (MB/min)"],+ ["rss_mb.app.slope_second_half_mb_per_min", "… second half only (MB/min)"],+ ["rss_mb.renderer.slope_mb_per_min", "Renderer RSS growth (MB/min)"],+ ["js_heap_mb_end", "JS heap at the end (MB)"],+ ["js_heap_mb_after_gc", "… after GC (MB)"],+ ["switch_ready_ms.first_40_median", "Switch → content, first 40, median (ms)"],+ ["switch_ready_ms.last_40_median", "Switch → content, last 40, median (ms)"],+];export class DatasetMismatchError extends Error {}+const get = (object, path) => path.split(".").reduce((v, k) => v?.[k], object);+const fmt = (v) => (typeof v === "number" ? (Number.isInteger(v) ? String(v) : v.toFixed(1)) : "—");+const header = (group) => `| | ${group.map((i) => i.label).join(" | ")} |\n|---|${group.map(() => "---:").join("|")}|`;+/*** Renders reports side by side. Each input is `{ label, report }`; throws* DatasetMismatchError when the reports were measured on different datasets.+ * Reports without a `kind` (all of them before MUL-9612) are web core-path reports.*/-export function renderCoreReport(inputs) {+export function renderCoreReport(rawInputs) {+ const inputs = rawInputs.map(({ label, report }) => ({ label, report: { kind: "core-paths", platform: "web", ...report } }));const digests = new Set(inputs.map((i) => i.report.dataset?.digest));if (digests.size > 1) {throw new DatasetMismatchError(`reports use different datasets: ${[...digests].join(", ")}`);}-- 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 ?? {})))];+ const core = inputs.filter((i) => i.report.kind === "core-paths");+ const issueKeys = [...new Set(core.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);+ lines.push(`\n**Open a big issue: \`${key}\`** (median of samples)\n`, header(core));for (const [field, name] of ISSUE_ROWS) {- lines.push(`| ${name} | ${inputs.map((i) => fmt(i.report.summary?.issue?.[key]?.[field])).join(" | ")} |`);+ lines.push(`| ${name} | ${core.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);+ if (!core.some((i) => i.report.summary?.inbox?.[phase])) continue;+ lines.push(`\n**Inbox switching: ${phase}** (all switches across samples)\n`, header(core));for (const [field, name] of INBOX_ROWS) {- lines.push(`| ${name} | ${inputs.map((i) => fmt(i.report.summary?.inbox?.[phase]?.[field])).join(" | ")} |`);+ lines.push(`| ${name} | ${core.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(" | ")} |`);+ if (core.some((i) => i.report.summary?.inbox?.heap_mb_after_gc)) {+ lines.push(`| JS heap after 30 switches, after GC (MB) | ${core.map((i) => fmt(i.report.summary?.inbox?.heap_mb_after_gc)).join(" | ")} |`);}++ const resources = inputs.filter((i) => i.report.kind === "desktop-resources");+ for (const [section, title, rows] of [+ ["idle", (r) => `**Desktop idle on the big issue** (${fmt(r.idle.seconds)} s, sampled every second from outside the app)`, IDLE_ROWS],+ ["memory", (r) => `**Desktop memory while switching Inbox rows** (${fmt(r.memory.minutes)} min, sampled every 5 s)`, MEMORY_ROWS],+ ]) {+ const group = resources.filter((i) => i.report[section]);+ if (group.length === 0) continue;+ lines.push(`\n${title(group[0].report)}\n`, header(group));+ for (const [field, name] of rows) {+ lines.push(`| ${name} | ${group.map((i) => fmt(get(i.report[section], field))).join(" | ")} |`);+ }+ }+const first = inputs.find((i) => i.report.dataset && i.report.environment)?.report;if (first) {lines.push("",`Dataset ${first.dataset.version} (${first.dataset.digest}): ${Object.entries(first.dataset.counts ?? {}).map(([k, v]) => `${v} ${k}`).join(", ")}.`,- `Chromium ${first.environment.browser}, ${first.environment.viewport}, ${first.environment.cpu} × ${first.environment.cores}.`,);}for (const { label, report } of inputs) {@@ -85,8 +130,11 @@ export function renderCoreReport(inputs) {continue;}const until = e.inbox_until === "title" ? "issue title is visible" : "notified comment is in view";- lines.push(`${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}` : "") + ".");+ const build = report.build ? ` (${report.build} build)` : "";+ lines.push(`${label} — ${report.kind}, ${report.platform}${build}: ref ${report.ref ?? "?"}, Chromium ${e.browser}, ${e.viewport}, ${e.cpu} × ${e.cores}` ++ (report.kind === "core-paths" ? `, CPU ${e.cpu_throttle}×, ${e.repeats} samples` : "") ++ (report.summary?.inbox?.["first-visit"] ? `, ${e.inbox_rows} Inbox rows, switch ends when the ${until}` : "") ++ (typeof e.load_1m_end === "number" ? `, load ${fmt(Math.round(e.load_1m_end * 10) / 10)} at the end` : "") + ".");}return lines.join("\n");}diff --git a/scripts/perf-desktop.mjs b/scripts/perf-desktop.mjsnew file mode 100644index 0000000000..c146019541--- /dev/null+++ b/scripts/perf-desktop.mjs@@ -0,0 +1,192 @@+#!/usr/bin/env node+/**+ * Run the core-path benchmark and the Desktop resource scenarios in the+ * Electron app (MUL-9612).+ *+ * make up C=api ARGS="--ephemeral"+ * make env-exec ARGS="-- node scripts/perf-desktop.mjs --out perf/desktop"+ *+ * By default it builds Desktop for production against this environment's+ * API, starts that build with a DevTools port, runs the scenarios through+ * Playwright over CDP, and stops the app again. The renderer is the+ * production bundle, the one users run; `make up C=desktop` serves the+ * development bundle, whose React is several times slower and records+ * profiling data, so its numbers do not describe a release.+ *+ * `--attach` measures the Desktop that `make up C=desktop ARGS="--cdp"`+ * already runs instead (development bundle), for problems that only exist+ * there. That app is left running.+ *+ * Options:+ * --out DIR reports go here (default perf/desktop)+ * --scenarios LIST core-paths, desktop-resources, or their parts+ * (core-issue, core-inbox, desktop-idle, desktop-memory);+ * default core-paths,desktop-resources+ * --skip-build start the existing apps/desktop/out build+ * --attach measure the managed development Desktop+ *+ * PERF_* variables (PERF_REPEATS, PERF_IDLE_SECONDS, ...) pass through to the+ * specs. Writes <scenario>.json per scenario and report.md.+ */+import { execFileSync, spawn } from "node:child_process";+import { createWriteStream, mkdirSync, writeFileSync } from "node:fs";+import { createServer } from "node:net";+import { createRequire } from "node:module";+import { join, resolve } from "node:path";++const repoRoot = execFileSync("git", ["rev-parse", "--show-toplevel"]).toString().trim();+const desktopDir = join(repoRoot, "apps", "desktop");+const args = process.argv.slice(2);+const has = (name) => args.includes(`--${name}`);+const flag = (name, fallback) => {+ const at = args.indexOf(`--${name}`);+ return at >= 0 && args[at + 1] ? args[at + 1] : fallback;+};+const outDir = resolve(flag("out", join(repoRoot, "perf", "desktop")));+const scenarios = flag("scenarios", "core-paths,desktop-resources").split(",").filter(Boolean);+const attach = has("attach");+const SPECS = {+ "core-paths": "core-paths.spec.ts", "core-issue": "core-paths.spec.ts", "core-inbox": "core-paths.spec.ts",+ "desktop-resources": "desktop-resources.spec.ts", "desktop-idle": "desktop-resources.spec.ts", "desktop-memory": "desktop-resources.spec.ts",+};++function fail(message) {+ console.error(`[perf-desktop] ${message}`);+ process.exit(1);+}+const log = (message) => console.log(`[perf-desktop] ${message}`);+const sleep = (ms) => new Promise((done) => setTimeout(done, ms));+const CDP_TIMEOUT_MS = 120_000;++for (const s of scenarios) if (!SPECS[s]) fail(`unknown scenario ${s}; pick from ${Object.keys(SPECS).join(", ")}`);+const env = process.env;+if (!env.PORT || !/^dev-/.test(env.MULTICA_DEV_PROFILE ?? "")) {+ fail('run through `make env-exec ARGS="-- node scripts/perf-desktop.mjs ..."` so the specs reach this environment\'s API.');+}++function freePort() {+ return new Promise((done, reject) => {+ const server = createServer();+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ const { port } = server.address();+ server.close(() => done(port));+ });+ });+}++async function waitForCdp(url, deadline, app) {+ for (;;) {+ try {+ const response = await fetch(`${url}/json/version`);+ if (response.ok) return;+ } catch {+ // not listening yet+ }+ if (app && exited(app)) throw new Error(`Desktop exited (${app.exitCode ?? app.signalCode}) before serving CDP; see ${join(outDir, "desktop.log")}`);+ if (Date.now() > deadline) throw new Error(`Desktop never served CDP on ${url}`);+ await sleep(500);+ }+}++function run(command, commandArgs, options) {+ return new Promise((done) => {+ const child = spawn(command, commandArgs, { stdio: "inherit", ...options });+ child.on("exit", (code, signal) => done(signal ? 1 : code ?? 1));+ });+}++// A child killed by a signal keeps exitCode null and sets signalCode instead.+const exited = (child) => child.exitCode !== null || child.signalCode !== null;++async function stop(app) {+ if (exited(app)) return;+ app.kill("SIGTERM");+ for (let i = 0; i < 40 && !exited(app); i++) await sleep(250);+ if (!exited(app)) app.kill("SIGKILL");+}++async function main() {+ mkdirSync(outDir, { recursive: true });+ let app = null;+ let cdpUrl;+ // Registered before Desktop starts, so an interrupt while it boots or while+ // a scenario runs still stops the app this script launched.+ const stopApp = () => (app ? stop(app) : Promise.resolve());+ const onSignal = (signal, code) => process.once(signal, () => {+ log(`${signal}: stopping Desktop`);+ stopApp().finally(() => process.exit(code));+ });+ onSignal("SIGINT", 130);+ onSignal("SIGTERM", 143);+ if (attach) {+ cdpUrl = env.MULTICA_DEV_DESKTOP_CDP_URL;+ if (!cdpUrl) fail('--attach needs the managed Desktop with a DevTools port: make up C=desktop ARGS="--cdp"');+ await waitForCdp(cdpUrl, Date.now() + 30_000, null);+ } else if (!has("skip-build")) {+ log("building Desktop (production bundle)");+ const code = await run("pnpm", ["--filter", "@multica/desktop", "build"], {+ cwd: repoRoot,+ env: {+ ...env,+ VITE_API_URL: `http://localhost:${env.PORT}`,+ VITE_WS_URL: `ws://localhost:${env.PORT}/ws`,+ VITE_APP_URL: `http://localhost:${env.FRONTEND_PORT ?? 3000}`,+ },+ });+ if (code !== 0) fail("the Desktop build failed");+ }++ const reports = [];+ let failed = false;+ try {+ if (!attach) {+ const electron = createRequire(join(desktopDir, "package.json"))("electron");+ const port = await freePort();+ cdpUrl = `http://127.0.0.1:${port}`;+ const appEnv = { ...env, DESKTOP_APP_SUFFIX: `Perf ${env.MULTICA_DEV_ENV ?? env.MULTICA_DEV_PROFILE}` };+ // Without these the main process loads the built renderer from disk and+ // starts signed out; the specs sign in themselves.+ delete appEnv.ELECTRON_RENDERER_URL;+ delete appEnv.MULTICA_DEV_AUTH_TOKEN;+ const appLog = createWriteStream(join(outDir, "desktop.log"));+ app = spawn(electron, [desktopDir, `--remote-debugging-port=${port}`], { env: appEnv, stdio: ["ignore", "pipe", "pipe"] });+ app.stdout.pipe(appLog);+ app.stderr.pipe(appLog);+ log(`started Desktop (pid ${app.pid}, CDP ${cdpUrl})`);+ await waitForCdp(cdpUrl, Date.now() + CDP_TIMEOUT_MS, app);+ }++ for (const scenario of scenarios) {+ const report = join(outDir, `${scenario}.json`);+ log(`running ${scenario}`);+ const code = await run("pnpm", ["exec", "playwright", "test", "--config=playwright.perf.config.ts", SPECS[scenario]], {+ cwd: repoRoot,+ env: {+ ...env,+ PERF_PLATFORM: "desktop",+ PERF_SCENARIO: scenario,+ PERF_REPORT_PATH: report,+ PERF_DESKTOP_CDP_URL: cdpUrl,+ PERF_DESKTOP_BUILD: attach ? "development" : "production",+ ...(app ? { PERF_DESKTOP_PID: String(app.pid) } : {}),+ PERF_REF: env.PERF_REF ?? execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd: repoRoot }).toString().trim(),+ },+ });+ if (code === 0) reports.push(`desktop=${report}`);+ else failed = true;+ }+ } finally {+ await stopApp();+ }++ if (reports.length > 0) {+ const table = execFileSync("node", [join(repoRoot, "scripts", "perf-core-report.mjs"), ...reports]).toString();+ writeFileSync(join(outDir, "report.md"), table);+ console.log(table);+ }+ if (failed) fail("a scenario failed; its report was not written");+ log(`reports in ${outDir}`);+}++main().catch((error) => fail(error?.stack || String(error)));