Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9609 perf(desktop): benchmark tab switches and Inbox clicks, cut per-switch render work (#10939)
Multica Eve84bf627f2fff
diff --git a/apps/desktop/.gitignore b/apps/desktop/.gitignoreindex f96eeb2ea8..97b9800725 100644--- a/apps/desktop/.gitignore+++ b/apps/desktop/.gitignore@@ -8,3 +8,4 @@ outresources/bin/# Speech engine staged at build time (scripts/bundle-voice-engine.mjs)resources/voice-engine/+/.perf-buildsdiff --git a/e2e/perf/README.md b/e2e/perf/README.mdindex f27eedc48f..5498174c3a 100644--- a/e2e/perf/README.md+++ b/e2e/perf/README.md@@ -227,6 +227,43 @@ settings above pass through. It writes `base.json`, `head.json` andit to the PR. The **UI performance report** workflow does not offer thesescenarios, because a GitHub runner has no local API to run them against.+## Desktop: tab switches and Inbox clicks++`desktop-tabs.spec.ts` measures what only Desktop has, in the real Electron+app (production renderer from `electron-vite build`) on the core-path+dataset (MUL-9609). Desktop mounts one tab at a time, so a tab switch+unmounts the outgoing page and mounts the incoming one from the Query cache.++- **tabs**: open six tabs (issue list, Inbox, the `large` issue read down to+ its notified comment, `p99`, a 120-comment and a small issue), then click+ through the tab strip twice.+- **inbox**: the core-path Inbox scenario inside Desktop: click twenty Work+ panel Inbox rows, then go back and forth between the first five.++Each step reports the time from the click until the content is in view, the+next paint (Event Timing), main-thread task time and Long Animation Frames,+plus mounted DOM nodes. Every launch gets a fresh app-data directory and a+temporary HOME with daemon auto-start off, so it never touches an installed+Multica, its CLI profiles or its daemon, and hands the `multica://` handler+back on exit.++```bash+make up C=api ARGS="--ephemeral"+# Build each ref's Desktop against the API and keep its output under apps/desktop.+(cd apps/desktop && VITE_API_URL=http://localhost:<api-port> VITE_WS_URL=ws://localhost:<api-port>/ws \+ pnpm exec electron-vite build && rm -rf .perf-builds/head && cp -R out .perf-builds/head)+PERF_SCENARIO=desktop PERF_REPORT_PATH=$PWD/perf/desktop.json \+ PERF_DESKTOP_TARGETS=main=apps/desktop/.perf-builds/main,head=apps/desktop/.perf-builds/head \+ make env-exec ARGS="-- pnpm exec playwright test --config=playwright.perf.config.ts desktop-tabs.spec.ts"+```++`PERF_SCENARIO=desktop-tabs` or `desktop-inbox` runs one scenario. Rounds+alternate between the `PERF_DESKTOP_TARGETS` builds (default: this+checkout's `apps/desktop/out`); `PERF_REPEATS`, `PERF_WARMUP` and+`PERF_CPU_THROTTLE` work as in the core-path benchmark. `PERF_TRACE_DIR`+writes 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.+## Inbox jump`inbox-jump.spec.ts` opens a notification about a reply deep in a long issuediff --git a/e2e/perf/desktop-tabs.spec.ts b/e2e/perf/desktop-tabs.spec.tsnew file mode 100644index 0000000000..e1848f975a--- /dev/null+++ b/e2e/perf/desktop-tabs.spec.ts@@ -0,0 +1,415 @@+/**+ * Desktop benchmark (MUL-9609): switching between tabs, and opening issues+ * from the Work panel's Inbox, in the real Electron app on the "large+ * workspace" dataset of the core-path benchmark.+ *+ * Tabs exist only on Desktop. Exactly one tab is mounted at a time, so a+ * switch tears down the outgoing page and mounts the incoming one from the+ * Query cache; neither the web benchmarks nor jsdom can see that cost.+ *+ * 1. `tabs` — open six tabs (issue list, Inbox, four issues of different+ * sizes; the long one read down to a comment 80% of the way), then click+ * through the tab strip twice.+ * 2. `inbox` — the core-path Inbox scenario, inside Desktop: click twenty+ * Work panel Inbox rows, then go back and forth between the first five.+ *+ * Every step reports the time from the click until the content is in view,+ * the next paint, main-thread task time, and Long Animation Frames, on the+ * page's own clock (`lib/frame-metrics.ts`). Opt in with+ * PERF_SCENARIO=desktop (both) or desktop-tabs / desktop-inbox; see README.+ */+import { _electron as electron, expect, test, type CDPSession, type ElectronApplication, type Page } from "@playwright/test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { cpus, loadavg, tmpdir } from "node:os";+import { basename, dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import {+ attachFrameMetrics, interactionLatency, lastClick, median, pageNow, quantile, settle, stallsBetween,+} from "./lib/frame-metrics";+import { ensureDataset, perfApi, resetInbox, type Manifest } from "./lib/core-dataset";++const scenario = process.env.PERF_SCENARIO ?? "";+const runTabs = scenario === "desktop" || scenario === "desktop-tabs";+const runInbox = scenario === "desktop" || scenario === "desktop-inbox";+const REPEATS = Number(process.env.PERF_REPEATS ?? 5);+const WARMUP = Number(process.env.PERF_WARMUP ?? 1);+const CPU_THROTTLE = Number(process.env.PERF_CPU_THROTTLE ?? 1);+const WINDOW = { width: 1440, height: 900 };+const SWITCH_DWELL_MS = 1000;+const TAB_CYCLES = 2;+const DESKTOP_DIR = fileURLToPath(new URL("../../apps/desktop", import.meta.url));++/**+ * Builds to measure, `name=<electron-vite out dir>` pairs separated by+ * commas. Rounds alternate between them. An out dir must sit inside+ * apps/desktop (e.g. apps/desktop/.perf-builds/main) so the main process+ * resolves its externalized dependencies. Defaults to this checkout's build.+ */+const TARGETS = (process.env.PERF_DESKTOP_TARGETS ?? `head=${join(DESKTOP_DIR, "out")}`)+ .split(",").map((pair) => { const [name, dir] = pair.split("="); return { name: name!, dir: resolve(dir!) }; });++test.describe.configure({ mode: "serial" });++let manifest: Manifest;+let token: string;+const report: { tabs: Record<string, unknown>[]; inbox: Record<string, unknown>[] } = { tabs: [], inbox: [] };++test.beforeAll(async () => {+ test.skip(!runTabs && !runInbox, "set PERF_SCENARIO=desktop (or desktop-tabs / desktop-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 () => {+ if (!manifest || !process.env.PERF_REPORT_PATH) return;+ const path = process.env.PERF_REPORT_PATH;+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify({+ dataset: { version: manifest.version, digest: manifest.digest, counts: manifest.counts },+ environment: {+ window: `${WINDOW.width}x${WINDOW.height}`, cpu_throttle: CPU_THROTTLE, cpu: cpus()[0]?.model,+ cores: cpus().length, load_1m_end: loadavg()[0], repeats: REPEATS, targets: TARGETS.map((t) => t.name),+ },+ summary: summarize(),+ samples: report,+ }, null, 2));+});++interface Desktop {+ app: ElectronApplication;+ page: Page;+ cdp: CDPSession;+ errors: string[];+ close: () => Promise<void>;+}++let launches = 0;++/**+ * Launches a signed-in Desktop on the perf workspace. Each launch gets its own+ * app-data directory (DESKTOP_APP_SUFFIX) and HOME, so it never shares a+ * single-instance lock, CLI profile or daemon with an installed Multica or an+ * earlier launch still shutting down, and daemon auto-start is off: no agent+ * daemon runs during a sample.+ */+async function launchDesktop(outDir: string, label: string): Promise<Desktop> {+ const home = mkdtempSync(join(tmpdir(), "multica-perf-desktop-"));+ mkdirSync(join(home, ".multica"));+ writeFileSync(join(home, ".multica", "desktop_prefs.json"), JSON.stringify({ autoStart: false, autoStop: false }));+ const executablePath = createRequire(join(DESKTOP_DIR, "package.json"))("electron") as unknown as string;+ const app = await electron.launch({+ executablePath,+ args: [join(outDir, "main", "index.js"), "--use-mock-keychain"],+ env: {+ ...process.env,+ HOME: home,+ DESKTOP_APP_SUFFIX: `perf-${label}-${process.pid}-${++launches}`,+ MULTICA_DEV_AUTH_TOKEN: token,+ ELECTRON_RENDERER_URL: "",+ },+ });+ const userData = await app.evaluate(({ app }) => app.getPath("userData"));+ // Only a dev launch takes the suffix; anything else is a real install's data.+ if (!basename(userData).includes(`perf-${label}-`)) {+ await app.close().catch(() => {});+ rmSync(home, { recursive: true, force: true });+ throw new Error(`refusing to use app data outside this run: ${userData}`);+ }+ const close = async () => {+ // A dev launch registers itself as the multica:// handler; hand it back.+ await app.evaluate(({ app }) => app.removeAsDefaultProtocolClient("multica", process.execPath, [app.getAppPath()])).catch(() => {});+ await app.close().catch(() => {});+ rmSync(userData, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ };+ let page = await app.firstWindow();+ try {+ // The main window is the one that shows the tab strip once signed in.+ await expect.poll(async () => {+ for (const candidate of app.windows()) {+ if (await candidate.locator("[data-tab-id]").count().catch(() => 0)) { page = candidate; return true; }+ }+ return false;+ }, { timeout: 60_000, intervals: [250] }).toBe(true);+ await app.evaluate(({ BrowserWindow }, size) => {+ const win = BrowserWindow.getAllWindows()[0]!;+ win.setContentSize(size.width, size.height);+ win.center();+ }, WINDOW);+ // Pin the Inbox section's size and keep Chat closed; a reload applies both+ // from storage, as for a returning user.+ await page.evaluate((slug) => {+ localStorage.setItem(`multica_sidebar_tree:${slug}`, JSON.stringify({ state: { inboxSettings: { limit: 20 } }, version: 0 }));+ localStorage.setItem("multica:chat:isOpen", "false");+ }, manifest.workspace.slug);+ await navigate(page, `/${manifest.workspace.slug}/issues`, "push");+ await page.reload();+ await expect(page.locator("li[data-inbox-row]").first()).toBeVisible({ timeout: 60_000 });+ await attachFrameMetrics(page);+ const cdp = await page.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 { app, page, cdp, errors, close };+ } catch (error) {+ const urls = app.windows().map((w) => w.url());+ await page.screenshot({ path: test.info().outputPath(`launch-${label}.png`) }).catch(() => {});+ await close();+ throw new Error(`Desktop did not come up signed in (windows: ${urls.join(", ")})`, { cause: error });+ }+}++/** The app's own internal-link entry point (what a link click or ⌘-click dispatches). */+async function navigate(page: Page, path: string, disposition: "push" | "foreground-tab") {+ await page.evaluate(({ path, disposition }) => {+ window.dispatchEvent(new CustomEvent("multica:navigate", { detail: { path, disposition } }));+ }, { path, disposition });+}++const TRACE_DIR = process.env.PERF_TRACE_DIR;++/** Starts a Chrome trace and a sampling CPU profile; the returned function writes both. */+async function startTrace({ cdp }: Desktop): Promise<(path: string) => Promise<void>> {+ const events: unknown[] = [];+ const collect = (e: { value: unknown[] }) => events.push(...e.value);+ cdp.on("Tracing.dataCollected", collect);+ await cdp.send("Tracing.start", {+ categories: "devtools.timeline,disabled-by-default-devtools.timeline,v8.execute,blink.user_timing,loading",+ transferMode: "ReportEvents",+ } as never);+ await cdp.send("Profiler.enable");+ await cdp.send("Profiler.setSamplingInterval", { interval: 100 });+ await cdp.send("Profiler.start");+ return async (path) => {+ const { profile } = await cdp.send("Profiler.stop");+ const done = new Promise<void>((resolve) => cdp.once("Tracing.tracingComplete", () => resolve()));+ await cdp.send("Tracing.end");+ await done;+ cdp.off("Tracing.dataCollected", collect);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(`${path}.cpuprofile`, JSON.stringify(profile));+ writeFileSync(`${path}.trace.json`, JSON.stringify({ traceEvents: events }));+ };+}++async function taskTime(cdp: CDPSession): Promise<number> {+ const { metrics } = await cdp.send("Performance.getMetrics");+ return (metrics.find((m) => m.name === "TaskDuration")?.value ?? 0) * 1000;+}++/** `text`: a page whose content is a fixed message, such as the Inbox page while the Work panel lists the notifications. */+type TabSpec = { key: string; path: string; kind: "issue" | "list" | "text"; title?: string };++/**+ * Resolves with the page-clock time of the first frame in which the tab's+ * content is laid out inside the main area's viewport: for an issue, its+ * title and a piece of its history (description or comment); for a list,+ * a row; for a text page, its message. The Work panel's own rows do not count.+ */+async function waitForContent(page: Page, tab: TabSpec): Promise<number> {+ const handle = await page.waitForFunction(({ kind, title }) => {+ const inPanel = (el: Element) => !!el.closest('[data-slot="space-panel"]');+ const inView = (el: Element, root: Element | null) => {+ const box = el.getBoundingClientRect();+ if (box.height === 0) return false;+ const view = (root ?? document.documentElement).getBoundingClientRect();+ return box.bottom > view.top && box.top < view.bottom && box.top < window.innerHeight;+ };+ let ready = false;+ if (kind === "issue") {+ const detail = [...document.querySelectorAll('[data-mc="issue-detail"][data-view="page"]')]+ .find((d) => !inPanel(d) && d.querySelector('[data-mc="issue-title"]')?.textContent?.includes(title!));+ const root = detail?.querySelector("[data-tab-scroll-root]") ?? null;+ ready = !!detail && [...detail.querySelectorAll("[data-comment-content]")].some((el) => el.textContent?.trim() && inView(el, root));+ } else if (kind === "text") {+ ready = [...document.querySelectorAll("p")].some((el) => el.textContent?.trim() === title && !inPanel(el) && inView(el, null));+ } else {+ ready = [...document.querySelectorAll('[data-mc="issue-row"], [data-mc="board-card"]')].some((el) => !inPanel(el) && inView(el, null));+ }+ if (!ready) return false;+ return performance.now();+ }, { kind: tab.kind, title: tab.title }, { polling: "raf", timeout: 60_000 }).catch(async (error) => {+ await page.screenshot({ path: test.info().outputPath(`timeout-${tab.key}.png`) }).catch(() => {});+ throw error;+ });+ return (await handle.jsonValue()) as number;+}++async function measureStep(desktop: Desktop, act: () => Promise<void>, tab: TabSpec) {+ const { page, cdp } = desktop;+ await settle(page, 200);+ const workBefore = await taskTime(cdp);+ await act();+ const ready = await waitForContent(page, tab);+ const click = await lastClick(page);+ await settle(page, SWITCH_DWELL_MS);+ const end = await pageNow(page);+ return {+ ready_ms: Math.round(ready - click),+ next_paint_ms: (await interactionLatency(page, click, end)) ?? 16,+ task_ms: Math.round((await taskTime(cdp)) - workBefore),+ ...(await stallsBetween(page, click - 1, end)),+ dom_nodes: await page.evaluate(() => document.getElementsByTagName("*").length),+ };+}++function tabSet(): TabSpec[] {+ const slug = manifest.workspace.slug;+ const issue = (key: string): TabSpec => {+ const i = manifest.issues[key]!;+ return { key, path: `/${slug}/issues/${i.id}`, kind: "issue", title: i.title };+ };+ return [+ { key: "issue-list", path: `/${slug}/issues`, kind: "list" },+ issue("large"),+ { key: "inbox", path: `/${slug}/inbox`, kind: "text", title: "Select a notification to view details" },+ issue("p99"),+ issue("medium-0"),+ issue("small-4"),+ ];+}++test("switch between Desktop tabs", async () => {+ test.skip(!runTabs, "tabs scenario not selected");+ test.setTimeout(3_600_000);+ const tabs = tabSet();+ for (let round = -WARMUP; round < REPEATS; round++) {+ for (const target of round % 2 ? TARGETS : [...TARGETS].reverse()) {+ const desktop = await launchDesktop(target.dir, target.name);+ try {+ const { page } = desktop;+ // The launch tab already shows the issue list; open the rest in new tabs.+ const opens: Record<string, unknown>[] = [];+ for (const tab of tabs.slice(1)) {+ await settle(page, 200);+ const before = await pageNow(page);+ await navigate(page, tab.path, "foreground-tab");+ const ready = await waitForContent(page, tab);+ await settle(page, SWITCH_DWELL_MS);+ opens.push({ tab: tab.key, ready_ms: Math.round(ready - before), ...(await stallsBetween(page, before, await pageNow(page))) });+ if (tab.key === "large") {+ // Read down to the notified comment (80% of the way), so its restore has+ // real depth and every sample restores the same rows.+ const reached = await page.evaluate(async (commentId) => {+ const root = document.querySelector<HTMLElement>('[data-mc="issue-detail"][data-view="page"] [data-tab-scroll-root]')!;+ for (let i = 0; i < 400; i++) {+ const target = root.querySelector<HTMLElement>(`[data-comment-content="${commentId}"]`);+ if (target) {+ target.scrollIntoView({ block: "start" });+ return true;+ }+ root.scrollTop += root.clientHeight;+ await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)));+ }+ return false;+ }, manifest.issues.large!.targetCommentId);+ expect(reached, "scrolled to the notified comment").toBe(true);+ await settle(page, 1500);+ }+ }+ const tabIds = await page.locator("[data-tab-id]").evaluateAll((els) => els.map((el) => el.getAttribute("data-tab-id")!));+ expect(tabIds, "one tab per destination").toHaveLength(tabs.length);+ const switches: Record<string, unknown>[] = [];+ for (let cycle = 0; cycle < TAB_CYCLES; cycle++) {+ // PERF_TRACE_DIR records the last cycle of the last round: a Chrome trace and a CPU profile.+ const trace = TRACE_DIR && round === REPEATS - 1 && cycle === TAB_CYCLES - 1 ? await startTrace(desktop) : null;+ for (const [index, tab] of tabs.entries()) {+ const frame = page.locator(`[data-tab-id="${tabIds[index]}"]`);+ const step = await measureStep(desktop, () => frame.click(), tab);+ switches.push({ cycle, tab: tab.key, ...step });+ }+ await trace?.(`${TRACE_DIR}/${target.name}-tabs`);+ }+ expect(desktop.errors).toEqual([]);+ if (round >= 0) {+ const record = { target: target.name, round, opens, switches, load_1m: loadavg()[0] };+ report.tabs.push(record);+ console.log(JSON.stringify({ target: target.name, round, ready_ms: switches.map((s) => `${s.tab}:${s.ready_ms}`).join(" "), task_ms: switches.map((s) => s.task_ms).join(" ") }));+ }+ } finally {+ await desktop.close();+ }+ }+ }+});++test("click Work panel Inbox rows on Desktop", async () => {+ test.skip(!runInbox, "inbox scenario not selected");+ test.setTimeout(3_600_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++) {+ for (const target of round % 2 ? TARGETS : [...TARGETS].reverse()) {+ await resetInbox(manifest);+ const desktop = await launchDesktop(target.dir, target.name);+ try {+ const { page } = desktop;+ const rows = page.locator("li[data-inbox-row]");+ await expect.poll(() => rows.count(), "the Inbox section shows the twenty measured rows").toBeGreaterThanOrEqual(20);+ await settle(page, 2000);+ const switches: Record<string, unknown>[] = [];+ for (const [step, { key, phase }] of sequence.entries()) {+ const issue = manifest.issues[key]!;+ const tab: TabSpec = { key, path: "", kind: "issue", title: issue.title };+ const result = await measureStep(desktop, () => rows.filter({ hasText: issue.title }).locator("a").first().click(), tab);+ switches.push({ step, phase, issue: key, comments: issue.comments, ...result });+ }+ expect(desktop.errors).toEqual([]);+ if (round >= 0) {+ report.inbox.push({ target: target.name, round, switches, load_1m: loadavg()[0] });+ console.log(JSON.stringify({ target: target.name, round, ready_ms: switches.map((s) => s.ready_ms).join(" ") }));+ }+ } finally {+ await desktop.close();+ }+ }+ }+});++type Row = Record<string, unknown>;+const nums = (rows: Row[], key: string) => rows.map((r) => r[key]).filter((v): v is number => typeof v === "number");+const round1 = (v: number) => Math.round(v * 10) / 10;++function stepSummary(rows: Row[]) {+ const ready = nums(rows, "ready_ms");+ const sources = new Map<string, number>();+ for (const line of rows.flatMap((r) => r.top_sources as string[])) {+ const [ms, ...rest] = line.split(" ");+ sources.set(rest.join(" "), (sources.get(rest.join(" ")) ?? 0) + Number.parseInt(ms!, 10));+ }+ return {+ steps: rows.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(nums(rows, "next_paint_ms")), next_paint_max_ms: Math.max(...nums(rows, "next_paint_ms")),+ task_median_ms: median(nums(rows, "task_ms")),+ stalls_per_step: round1(nums(rows, "stalls").reduce((a, b) => a + b, 0) / rows.length),+ stall_max_ms: Math.max(...nums(rows, "stall_max_ms")),+ freezes: nums(rows, "freezes").reduce((a, b) => a + b, 0),+ top_sources: [...sources.entries()].sort((a, b) => b[1] - a[1]).slice(0, 4).map(([s, ms]) => `${ms}ms ${s}`),+ };+}++/** Per target: tab switches overall and per destination; Inbox first visits and revisits. */+function summarize() {+ const out: Record<string, unknown> = {};+ for (const { name } of TARGETS) {+ const switches = report.tabs.filter((r) => r.target === name).flatMap((r) => r.switches as Row[]);+ const inbox = report.inbox.filter((r) => r.target === name).flatMap((r) => r.switches as Row[]);+ out[name] = {+ tabs: switches.length === 0 ? null : {+ all: stepSummary(switches),+ by_tab: Object.fromEntries(tabSet().map((t) => [t.key, stepSummary(switches.filter((s) => s.tab === t.key))])),+ },+ inbox: inbox.length === 0 ? null : {+ "first-visit": stepSummary(inbox.filter((s) => s.phase === "first-visit")),+ revisit: stepSummary(inbox.filter((s) => s.phase === "revisit")),+ },+ };+ }+ return out;+}diff --git a/e2e/perf/lib/frame-metrics.ts b/e2e/perf/lib/frame-metrics.tsindex 0eb51df574..8743f30a0a 100644--- a/e2e/perf/lib/frame-metrics.ts+++ b/e2e/perf/lib/frame-metrics.ts@@ -61,42 +61,57 @@ export async function installFrameMetrics(page: Page, token: string): Promise<voawait 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);+ await page.addInitScript(observeFrames);+}++/**+ * Installs the observers into a page that has already loaded, such as an+ * Electron window. Long Animation Frames are buffered, so the frames from+ * before the call are kept too.+ */+export async function attachFrameMetrics(page: Page): Promise<void> {+ await page.evaluate(observeFrames);+}++/** Runs in the page: records clicks, key presses, Long Animation Frames and Event Timing. */+function observeFrames() {+ if (window.__corePerf) return;+ 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);}/** The page clock, for bracketing a measured window. */diff --git a/packages/views/i18n/use-t.test.tsx b/packages/views/i18n/use-t.test.tsxindex 959fd49af4..5246644be8 100644--- a/packages/views/i18n/use-t.test.tsx+++ b/packages/views/i18n/use-t.test.tsx@@ -5,8 +5,8 @@ import { I18nProvider } from "@multica/core/i18n/react";import { useT } from "./use-t";const resources = {- en: { common: { daemon_setup: { loading: "Hello" } } },- "zh-Hans": { common: { daemon_setup: { loading: "你好" } } },+ en: { common: { daemon_setup: { loading: "Hello" }, time: { minutes_ago: "{{count}}m ago" } } },+ "zh-Hans": { common: { daemon_setup: { loading: "你好" }, time: { minutes_ago: "{{count}} 分钟前" } } },};function wrapper({ children }: { children: ReactNode }) {@@ -46,4 +46,20 @@ describe("useT", () => {// Array form, as react-i18next returns.expect(a[0]).toBe(a.t);});++ it("answers repeated lookups the same and still applies options", async () => {+ const { result } = renderHook(() => useT("common"), { wrapper });+ const { t, i18n } = result.current;+ expect(t(($) => $.daemon_setup.loading)).toBe("Hello");+ expect(t(($) => $.daemon_setup.loading)).toBe("Hello");+ expect(t(($) => $.time.minutes_ago, { count: 3 })).toBe("3m ago");+ expect(t(($) => $.time.minutes_ago, { count: 5 })).toBe("5m ago");++ // A resource reload announces itself with languageChanged (I18nProvider).+ await act(async () => {+ i18n.addResourceBundle("en", "common", { daemon_setup: { loading: "Hi" } }, true, true);+ i18n.emit("languageChanged", "en");+ });+ expect(result.current.t(($) => $.daemon_setup.loading)).toBe("Hi");+ });});diff --git a/packages/views/i18n/use-t.ts b/packages/views/i18n/use-t.tsindex 50d3966d78..2cd371d2e4 100644--- a/packages/views/i18n/use-t.ts+++ b/packages/views/i18n/use-t.ts@@ -88,6 +88,43 @@ const noInstance = Object.assign([notReadyT, {} as I18n, false] as [AnyT, I18n,});const noInstanceStore = { subscribe: () => () => {}, revision: 0 };+/** The key path a selector reads (`$ => $.a.b` → "a\u0001b"), or null for anything else. */+function selectorPath(selector: (root: unknown) => unknown): string | null {+ const path: string[] = [];+ const recorder: object = new Proxy(Object.create(null), {+ get(_target, key) {+ if (typeof key === "symbol") return undefined;+ path.push(key);+ return recorder;+ },+ });+ return selector(recorder) === recorder && path.length > 0 ? path.join("\u0001") : null;+}++/**+ * A namespace's `t` with its plain lookups remembered. i18next resolves every+ * call from scratch, copying its options several times, and a page mount+ * makes thousands of `t($ => $.x.y)` calls (MUL-9609). A call with nothing+ * but a selector depends only on the language, namespace and resources, and+ * the store drops this `t` whenever any of them changes (`languageChanged`).+ * Calls with options (counts, values, defaults) always go to i18next.+ */+function memoizeSelectorCalls(t: AnyT): AnyT {+ const results = new Map<string, unknown>();+ const memoized: AnyT = (...args: unknown[]) => {+ const [key] = args;+ if (args.length !== 1 || typeof key !== "function") return t(...args);+ const path = selectorPath(key as (root: unknown) => unknown);+ if (path === null) return t(...args);+ if (results.has(path)) return results.get(path);+ const result = t(...args);+ results.set(path, result);+ return result;+ };+ // react-i18next and callers read the fixed language and namespace off `t`.+ return Object.assign(memoized, { lng: (t as { lng?: unknown }).lng, ns: (t as { ns?: unknown }).ns, keyPrefix: (t as { keyPrefix?: unknown }).keyPrefix });+}+function useTranslationShared(ns?: string) {const context = useContext(I18nContext);const i18n = context?.i18n ?? (getI18n() as I18n | undefined);@@ -99,7 +136,7 @@ function useTranslationShared(ns?: string) {if (!i18n || !("fixedT" in store)) return noInstance;let t = store.fixedT.get(namespace);if (!t) {- t = i18n.getFixedT(null, namespace as never) as unknown as AnyT;+ t = memoizeSelectorCalls(i18n.getFixedT(null, namespace as never) as unknown as AnyT);store.fixedT.set(namespace, t);}const result = [t, store.view, true] as [AnyT, I18n, boolean] & { t: AnyT; i18n: I18n; ready: boolean };diff --git a/packages/views/inbox/components/inbox-snooze-menu.tsx b/packages/views/inbox/components/inbox-snooze-menu.tsxindex 03aceadf2a..112b00f33b 100644--- a/packages/views/inbox/components/inbox-snooze-menu.tsx+++ b/packages/views/inbox/components/inbox-snooze-menu.tsx@@ -69,9 +69,6 @@ export function InboxSnoozeMenu({side?: "bottom" | "right";align?: "start" | "end";}) {- const { t } = useT("inbox");- const locale = useLocale();- const presetLabel = useSnoozePresetLabel();const [picking, setPicking] = useState(false);// Read whenever the menu opens, from its trigger or from the parent (`H`, a// hover card), so the times it lists are the ones it snoozes to.@@ -99,45 +96,71 @@ export function InboxSnoozeMenu({}}/>) : (- <>- {snoozed && onUnsnooze && (- <>- <DropdownMenuItem onClick={onUnsnooze}>- <Undo2 className="size-4" />- {t(($) => $.snooze.unsnooze)}- </DropdownMenuItem>- <DropdownMenuSeparator />- </>- )}- <DropdownMenuGroup>- <DropdownMenuLabel>- {snoozed ? t(($) => $.snooze.change_time) : t(($) => $.snooze.menu_title)}- </DropdownMenuLabel>- {inboxSnoozeOptions(now).map((option) => (- <DropdownMenuItem key={option.preset} onClick={() => onSnooze(option.until)}>- <Clock className="size-4" />- {presetLabel(option.preset)}- <DropdownMenuShortcut className="tracking-normal tabular-nums">- {formatSnoozeTime(option.until, now, locale)}- </DropdownMenuShortcut>- </DropdownMenuItem>- ))}- </DropdownMenuGroup>- <DropdownMenuSeparator />- <DropdownMenuItem closeOnClick={false} onClick={() => setPicking(true)}>- <CalendarDays className="size-4" />- {t(($) => $.snooze.pick_time)}- <ChevronRight className="ml-auto size-4 text-muted-foreground" />- </DropdownMenuItem>- <DropdownMenuSeparator />- <p className="px-2 py-1 text-caption text-muted-foreground">{t(($) => $.snooze.hint)}</p>- </>+ <SnoozeChoices now={now} snoozed={snoozed} onSnooze={onSnooze} onUnsnooze={onUnsnooze} onPick={() => setPicking(true)} />)}</DropdownMenuContent></DropdownMenu>);}+/**+ * The menu's choices, a component of their own so their times are formatted+ * only while the menu is open: every Inbox row and issue header carries a+ * closed menu, and re-renders with the page.+ */+function SnoozeChoices({+ now,+ snoozed,+ onSnooze,+ onUnsnooze,+ onPick,+}: {+ now: Date;+ snoozed: boolean;+ onSnooze: (until: Date) => void;+ onUnsnooze?: () => void;+ onPick: () => void;+}) {+ const { t } = useT("inbox");+ const locale = useLocale();+ const presetLabel = useSnoozePresetLabel();+ return (+ <>+ {snoozed && onUnsnooze && (+ <>+ <DropdownMenuItem onClick={onUnsnooze}>+ <Undo2 className="size-4" />+ {t(($) => $.snooze.unsnooze)}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuGroup>+ <DropdownMenuLabel>+ {snoozed ? t(($) => $.snooze.change_time) : t(($) => $.snooze.menu_title)}+ </DropdownMenuLabel>+ {inboxSnoozeOptions(now).map((option) => (+ <DropdownMenuItem key={option.preset} onClick={() => onSnooze(option.until)}>+ <Clock className="size-4" />+ {presetLabel(option.preset)}+ <DropdownMenuShortcut className="tracking-normal tabular-nums">+ {formatSnoozeTime(option.until, now, locale)}+ </DropdownMenuShortcut>+ </DropdownMenuItem>+ ))}+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuItem closeOnClick={false} onClick={onPick}>+ <CalendarDays className="size-4" />+ {t(($) => $.snooze.pick_time)}+ <ChevronRight className="ml-auto size-4 text-muted-foreground" />+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <p className="px-2 py-1 text-caption text-muted-foreground">{t(($) => $.snooze.hint)}</p>+ </>+ );+}+function startOfDay(date: Date): Date {return new Date(date.getFullYear(), date.getMonth(), date.getDate());}diff --git a/packages/views/layout/panels/inbox-section.tsx b/packages/views/layout/panels/inbox-section.tsxindex 7dc6066d32..a9f407bc16 100644--- a/packages/views/layout/panels/inbox-section.tsx+++ b/packages/views/layout/panels/inbox-section.tsx@@ -1,6 +1,6 @@"use client";-import { type ReactNode, type Ref, useLayoutEffect, useMemo, useState } from "react";+import { memo, type ReactNode, type Ref, useLayoutEffect, useMemo, useRef, useState } from "react";import { useVirtualizer } from "@tanstack/react-virtual";import { useQuery } from "@tanstack/react-query";import { toast } from "sonner";@@ -182,13 +182,43 @@ export function InboxSection({}, [list.notifications]);const scrollRef = usePanelScrollRef();+ // Rows are memoized and re-render only when their own props change, not on+ // every navigation that re-renders this section (MUL-9609); the handlers+ // keep one identity and read this render's state when they run.+ const latest = {+ prefetch: (item: InboxItem) => void prefetchRow(item),+ archive: (item: InboxItem) => {+ archive(item.id, inboxRowKey(item));+ leaveIfOpen(item);+ },+ unsubscribe: (item: InboxItem) => {+ unsubscribeArchive({ id: item.id, issueId: item.issue_id! });+ leaveIfOpen(item);+ },+ snooze: (item: InboxItem, until: Date) => {+ snooze(item, until);+ leaveIfOpen(item);+ },+ };+ const latestRef = useRef(latest);+ useLayoutEffect(() => {+ latestRef.current = latest;+ });+ const handlers = useMemo<InboxRowHandlers>(() => ({+ prefetch: (item) => latestRef.current.prefetch(item),+ archive: (item) => latestRef.current.archive(item),+ unsubscribe: (item) => latestRef.current.unsubscribe(item),+ snooze: (item, until) => latestRef.current.snooze(item, until),+ }), []);const renderRow = (item: InboxItem, measure?: RowMeasure) => (<InboxRowkey={item.id}item={item}- measure={measure}+ // Two props rather than the object: a fresh object every render would+ // defeat the row's memo (the measuring ref keeps one identity).+ measureIndex={measure?.index}+ measureRef={measure?.ref}href={inboxRowHref(p, item)}- onPrefetch={() => void prefetchRow(item)}active={(!!item.issue_id && item.issue_id === activeIssueId) ||(!!openKey && (item.issue_id ?? item.id) === openKey)@@ -197,22 +227,8 @@ export function InboxSection({kept={list.kept?.item.id === item.id ? keptText.line(list.kept) : null}settled={list.kept?.item.id === item.id && list.kept.reason !== "filtered"}updatesWhileSnoozed={item.issue_id ? (updatesWhileSnoozed.get(item.issue_id) ?? 0) : 0}- onArchive={() => {- archive(item.id, inboxRowKey(item));- leaveIfOpen(item);- }}- onUnsubscribe={- item.issue_id && unsubscribable(item)- ? () => {- unsubscribeArchive({ id: item.id, issueId: item.issue_id! });- leaveIfOpen(item);- }- : undefined- }- onSnooze={(until) => {- snooze(item, until);- leaveIfOpen(item);- }}+ unsubscribable={!!item.issue_id && unsubscribable(item)}+ handlers={handlers}/>);@@ -507,26 +523,34 @@ function InboxSectionActions({);}-function InboxRow({+/** What a row does with its notification; one stable set shared by every row. */+interface InboxRowHandlers {+ /** Warms the issue a row opens, so the click renders from cache. */+ prefetch: (item: InboxItem) => void;+ archive: (item: InboxItem) => void;+ /** Unsubscribe & archive. */+ unsubscribe: (item: InboxItem) => void;+ snooze: (item: InboxItem, until: Date) => void;+}++const InboxRow = memo(function InboxRow({item,- measure,+ measureIndex,+ measureRef,href,- onPrefetch,active,compact,kept,settled,updatesWhileSnoozed,- onArchive,- onUnsubscribe,- onSnooze,+ unsubscribable,+ handlers,}: {item: InboxItem;- /** Set when the row is one of a virtualized list's window. */- measure?: RowMeasure;+ /** Set when the row is one of a virtualized list's window (`RowMeasure`). */+ measureIndex?: number;+ measureRef?: Ref<HTMLLIElement>;href: string;- /** Warms the issue this row opens, so the click renders from cache. */- onPrefetch: () => void;active: boolean;/** One line (status, title, agents, dot or time) instead of the actor line under the title. */compact: boolean;@@ -536,11 +560,14 @@ function InboxRow({settled: boolean;/** Notifications that arrived while the issue was snoozed. */updatesWhileSnoozed: number;- onArchive: () => void;- /** Unsubscribe & archive; only for issues that are not the viewer's own. */- onUnsubscribe?: () => void;- onSnooze: (until: Date) => void;+ /** Offers Unsubscribe & archive; only for issues that are not the viewer's own. */+ unsubscribable: boolean;+ handlers: InboxRowHandlers;}) {+ const onPrefetch = () => handlers.prefetch(item);+ const onArchive = () => handlers.archive(item);+ const onUnsubscribe = unsubscribable ? () => handlers.unsubscribe(item) : undefined;+ const onSnooze = (until: Date) => handlers.snooze(item, until);const { t } = useT("inbox");const typeLabels = useTypeLabels();const timeAgo = useTimeAgo();@@ -619,8 +646,8 @@ function InboxRow({return (<li- ref={measure?.ref}- data-index={measure?.index}+ ref={measureRef}+ data-index={measureIndex}data-inbox-rowdata-read={unread ? "false" : "true"}className="group/inbox relative"@@ -792,7 +819,7 @@ function InboxRow({)}</li>);-}+});/** A row's hover button. */function rowButtonClass(compact: boolean) {diff --git a/packages/views/rich-content/rich-table.test.tsx b/packages/views/rich-content/rich-table.test.tsxindex 7a5830c05f..a6af1f0f67 100644--- a/packages/views/rich-content/rich-table.test.tsx+++ b/packages/views/rich-content/rich-table.test.tsx@@ -98,6 +98,36 @@ describe("RichTable", () => {}});+ it("measures again for web fonts only while they are still loading", async () => {+ const rect = vi.spyOn(HTMLTableCellElement.prototype, "getBoundingClientRect").mockReturnValue({ width: 100 } as DOMRect);+ const clientWidth = vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(560);+ const measures = async (status: FontFaceSet["status"]) => {+ let fontsLoaded!: () => void;+ const ready = new Promise<void>((resolve) => (fontsLoaded = resolve));+ Object.defineProperty(document, "fonts", { configurable: true, value: { status, ready } });+ rect.mockClear();+ const view = renderTable();+ const first = rect.mock.calls.length;+ fontsLoaded();+ await ready;+ await Promise.resolve();+ const total = rect.mock.calls.length;+ view.unmount();+ return { first, total };+ };+ try {+ const loaded = await measures("loaded");+ expect(loaded.first).toBeGreaterThan(0);+ expect(loaded.total).toBe(loaded.first);+ const loading = await measures("loading");+ expect(loading.total).toBeGreaterThan(loading.first);+ } finally {+ delete (document as { fonts?: unknown }).fonts;+ rect.mockRestore();+ clientWidth.mockRestore();+ }+ });+it("resizes a column from the keyboard, persists it, and resets", async () => {const { table, unmount } = renderTable();const handle = screen.getByRole("separator", { name: "Resize Relation column" });diff --git a/packages/views/rich-content/rich-table.tsx b/packages/views/rich-content/rich-table.tsxindex 0875aaf057..5bd5589b4f 100644--- a/packages/views/rich-content/rich-table.tsx+++ b/packages/views/rich-content/rich-table.tsx@@ -237,11 +237,15 @@ export function RichTableFrame({ model, getMarkdown, tableRef: onTable, childrenfit();const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(fit);observer?.observe(wrapper);- // Content widths change when a web font replaces its fallback.- void document.fonts?.ready.then(() => {- measuredAt = -1;- fit();- });+ // Content widths change when a web font replaces its fallback. Once the+ // fonts have loaded, `ready` resolves at once and a second measure of every+ // table would only repeat the first.+ if (document.fonts && document.fonts.status !== "loaded") {+ void document.fonts.ready.then(() => {+ measuredAt = -1;+ fit();+ });+ }return () => {active = false;observer?.disconnect();