Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

perf(entity): keep list row layout inputs independently reactive (#9427)

Wolf Mermelstein6e90542077d3
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 68e9e9208b..c31c85a70b 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -1148,3 +1148,10 @@ of posting, multi-paragraph anchors, saved ranges, and cancellation during posti
static `data-input-surface` categories on editor/field owners, never caller
labels.
- Keep record names, addresses, answers and query text out of attributes.
+
+### Entity rows
+
+- Keep `ListEntity` layout fields independently reactive (getters, not a
+ dynamic object spread); a spread makes a selection change revisit every
+ unrelated layout input. Profile with the
+ [entity collection fixture](src/features/entity/browser-test/README.md).
diff --git a/apps/web/src/features/entity/browser-test/README.md b/apps/web/src/features/entity/browser-test/README.md
new file mode 100644
index 0000000000..bd86a42901
--- /dev/null
+++ b/apps/web/src/features/entity/browser-test/README.md
@@ -0,0 +1,65 @@
+# Static entity collection profile
+
+This page renders 1,000 real `ListEntity` rows, half documents and half pull
+requests with compacting pills. It supplies the static metadata provider and
+anonymous app contexts. Empty PR links keep linked-session queries disabled.
+The fixture rejects a browser with a login hint; use a fresh context.
+
+Run the regular web dev server on port 3009 (`PORT=3009 bun run dev`). The
+fixture uses that server's real module/WASM configuration. It needs no backend.
+From `apps/web`:
+
+```sh
+PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/path/to/chrome \
+LIST_OUTPUT=/tmp/runtime-long-list \
+node src/features/entity/browser-test/measure.mjs
+```
+
+`LIST_URL` overrides the default HTTPS URL on port 3009. The tool blocks
+unexpected API requests, including same-origin proxies, and fails on page errors,
+reloads, missing rows, or wheel input that did not scroll. It runs one fresh
+browser at a time and closes each in `finally`.
+
+Each default/`--disable-gpu` capture uses 4× CDP CPU throttling: 10 seconds idle,
+40 wheel steps, then 80 pointer moves across visible rows. Results include
+Performance-domain task/style/layout deltas, bounded timer/rAF/long-frame counts,
+raw paint/raster/compositor traces and viewport screenshots. Missing legacy
+`CompositeLayers` or `GPUTask` events do not establish zero compositor/GPU work.
+Use Node for this Playwright runner; the Bun process close path can stall between
+browser launches.
+
+This deliberately mounts every row without virtualization. Its CPU numbers are
+a stress baseline, not representative of a production Soup viewport. Keep
+virtualization and application providers out of performance conclusions drawn
+from this collection. Use authenticated application profiles for those paths.
+
+## Row creation and updates
+
+`row-cost.mjs` uses the same real components with `?benchmark&count=200`,
+including store-backed models, selection checkboxes and shared Button actions. From `apps/web`:
+
+```sh
+PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/path/to/chrome \
+ROW_OUTPUT=/tmp/entity-row-cost \
+node src/features/entity/browser-test/row-cost.mjs
+```
+
+`ROW_URL` overrides the default HTTPS URL on port 3008. Use the regular dev
+server and a fresh anonymous browser. No login or backend is required; the
+runner fails on API requests, reloads during capture or browser errors. It warms the component/variant
+paths, then records five rounds of mounting 200 rows, toggling selection,
+renaming models, reconciling new snapshots by id, and disposal. Updates must
+preserve row, checkbox and action DOM identity, update the displayed model,
+and propagate selection to every checkbox. Synchronous action time excludes the
+runner's identity checks; ScriptDuration and TaskDuration include two animation
+frames after each action. Divide 200 by mount time in milliseconds for rows/ms.
+
+A separate pass samples allocated bytes with CDP HeapProfiler at a 16 KiB
+sampling interval, including allocations collected during that action. These
+are statistical byte estimates, not allocation counts or retained heap sizes;
+they and the Performance deltas include driver validation.
+A final diagnostic pass writes a CPU profile for each action; profiler overhead
+is excluded from the five timing rounds. Results also contain element classes
+and a viewport screenshot for before/after appearance comparisons. Run captures
+sequentially on the same browser, viewport and CPU settings; host contention
+can affect elapsed times. This fixture isolates row work, not full-app routing.
diff --git a/apps/web/src/features/entity/browser-test/long-list.html b/apps/web/src/features/entity/browser-test/long-list.html
new file mode 100644
index 0000000000..7b5657f101
--- /dev/null
+++ b/apps/web/src/features/entity/browser-test/long-list.html
@@ -0,0 +1 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head><body><div id="root"></div><script type="module" src="./long-list.tsx"></script></body></html>
diff --git a/apps/web/src/features/entity/browser-test/long-list.tsx b/apps/web/src/features/entity/browser-test/long-list.tsx
new file mode 100644
index 0000000000..d92d9216ff
--- /dev/null
+++ b/apps/web/src/features/entity/browser-test/long-list.tsx
@@ -0,0 +1,168 @@
+import { ListEntity } from '@app/features/entity/composed/ListEntity';
+import { ListEntityNoopMetadataProvider } from '@app/features/entity/composed/list-entity/list-entity-metadata-provider';
+import type { EntityData } from '@app/features/entity/types/entity';
+import { macroDarkTheme } from '@app/features/theme/themes/macro-dark';
+import { macroLightTheme } from '@app/features/theme/themes/macro-light';
+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
+import { PosthogProvider } from '@app/lib/analytics/posthog';
+import { EmailLinksContextProvider } from '@core/context/emailLinks';
+import { UserContextProvider } from '@core/context/user';
+import { hasLoginCookie } from '@core/util/cookies';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { Button } from '@ui/components/Button';
+import { createSignal, For, onCleanup } from 'solid-js';
+import { createStore, produce, reconcile } from 'solid-js/store';
+import { render } from 'solid-js/web';
+import '../../../index.css';
+
+if (hasLoginCookie())
+ throw new Error('Use a fresh browser context for the static entity fixture.');
+
+const params = new URLSearchParams(location.search);
+const count = Number(params.get('count') ?? 1000);
+const theme =
+ params.get('theme') === 'light' ? macroLightTheme : macroDarkTheme;
+for (const [token, value] of Object.entries(theme.colorTokens)) {
+ document.documentElement.style.setProperty(`--color-${token}`, value);
+}
+document.documentElement.dataset.themeLight = String(theme.mode === 'light');
+document.documentElement.dataset.touchDevice = 'false';
+const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+});
+const fixtures: EntityData[] = Array.from({ length: count }, (_, index) => {
+ const base = {
+ id: `fixture-row-${index}`,
+ name: `Example item ${index}`,
+ ownerId: '',
+ updatedAt: '2025-01-15T12:00:00Z',
+ };
+ if (index % 2 === 0) return { ...base, type: 'document', fileType: 'pdf' };
+ return {
+ ...base,
+ type: 'foreign',
+ foreignSource: 'github_pull_request',
+ foreignId: `fixture-pr-${index}`,
+ storedForId: '',
+ storedForAuthEntity: 'team',
+ metadata: {
+ number: index,
+ name: base.name,
+ owner: 'example',
+ repo: 'fixture',
+ // Empty links leave linked-session lookup disabled in this static collection.
+ url: '',
+ status: 'open',
+ additions: 24,
+ deletions: 8,
+ comments: [],
+ checks: [],
+ labels: [
+ { name: 'Performance' },
+ { name: 'Needs review' },
+ { name: 'Frontend' },
+ ],
+ },
+ };
+});
+
+// The benchmark changes data/selection through the same store semantics as a
+// live collection. The regular stress fixture keeps its plain static rows.
+const benchmark = params.has('benchmark');
+const [models, setModels] = createStore(fixtures);
+const [mounted, setMounted] = createSignal(!benchmark);
+const [selected, setSelected] = createSignal(false);
+const rows = () => (mounted() ? (benchmark ? models : fixtures) : []);
+let mounts = 0;
+let disposals = 0;
+let update = 0;
+const api = {
+ stats: () => ({
+ mounts,
+ disposals,
+ selected: selected(),
+ checked: document.querySelectorAll('[role="checkbox"][aria-checked="true"]')
+ .length,
+ firstName: models[0]?.name,
+ rows: document.querySelectorAll('[data-entity]').length,
+ }),
+ mount: () => setMounted(true),
+ clear() {
+ setMounted(false);
+ setSelected(false);
+ },
+ select: () => setSelected((value) => !value),
+ rename() {
+ update++;
+ setModels(
+ produce((rows) => {
+ for (let index = 0; index < rows.length; index++)
+ rows[index].name = `Example item ${index} update ${update}`;
+ })
+ );
+ },
+ replace() {
+ update++;
+ setModels(
+ reconcile(
+ fixtures.map((entity, index) => ({
+ ...entity,
+ name: `Example item ${index} update ${update}`,
+ })),
+ { key: 'id', merge: true }
+ )
+ );
+ },
+};
+declare global {
+ interface Window {
+ entityRowBenchmark: typeof api;
+ }
+}
+
+render(
+ () => (
+ <QueryClientProvider client={client}>
+ <AnalyticsContextProvider>
+ <PosthogProvider>
+ <UserContextProvider>
+ <EmailLinksContextProvider>
+ <ListEntityNoopMetadataProvider>
+ <main
+ data-list
+ class="h-screen overflow-y-auto bg-page p-4 text-ink"
+ >
+ <h1 class="mb-4 text-lg">Static entity collection</h1>
+ <For each={rows()}>
+ {(entity) => {
+ mounts++;
+ onCleanup(() => disposals++);
+ return (
+ <ListEntity
+ entity={entity}
+ deferInteractions
+ hideCheckbox={
+ !benchmark || params.has('hideCheckbox')
+ }
+ checked={selected()}
+ actions={
+ <Button size="sm" variant="ghost">
+ Open
+ </Button>
+ }
+ />
+ );
+ }}
+ </For>
+ </main>
+ </ListEntityNoopMetadataProvider>
+ </EmailLinksContextProvider>
+ </UserContextProvider>
+ </PosthogProvider>
+ </AnalyticsContextProvider>
+ </QueryClientProvider>
+ ),
+ document.getElementById('root')!
+);
+
+window.entityRowBenchmark = api;
diff --git a/apps/web/src/features/entity/browser-test/measure.mjs b/apps/web/src/features/entity/browser-test/measure.mjs
new file mode 100644
index 0000000000..a35049245d
--- /dev/null
+++ b/apps/web/src/features/entity/browser-test/measure.mjs
@@ -0,0 +1,130 @@
+import { mkdir, writeFile } from 'node:fs/promises';
+import { chromium } from 'playwright';
+
+const output = process.env.LIST_OUTPUT ?? '/tmp/runtime-long-list';
+const url = process.env.LIST_URL ?? 'https://localhost:3009/src/features/entity/browser-test/long-list.html';
+await mkdir(output, { recursive: true });
+const results = [];
+for (const mode of ['default', 'software']) {
+ const browser = await chromium.launch({
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ args: ['--disable-http2', ...(mode === 'software' ? ['--disable-gpu'] : [])],
+ });
+ try {
+ const page = await browser.newPage({ ignoreHTTPSErrors: true, viewport: { width: 1280, height: 900 } });
+ const errors = [];
+ const requests = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.route('**/*', async (route) => {
+ const request = route.request();
+ const resource = new URL(request.url());
+ const staticFetch = ['/src/', '/node_modules/', '/@fs/', '/@vite/', '/@id/', '/assets/'].some((prefix) => resource.pathname.startsWith(prefix));
+ const apiFetch = ['fetch', 'xhr'].includes(request.resourceType()) && !staticFetch;
+ if (resource.origin !== new URL(url).origin || apiFetch) {
+ requests.push(resource.origin + resource.pathname);
+ await route.abort();
+ return;
+ }
+ await route.continue();
+ });
+ await page.addInitScript(() => {
+ const capture = { nonce: crypto.randomUUID(), start: 0, active: false, raf: 0, timers: {}, longEntries: [] };
+ window.__runtimeCapture = capture;
+ for (const kind of ['setTimeout', 'setInterval']) {
+ const original = window[kind].bind(window);
+ window[kind] = (callback, delay, ...args) => {
+ if (typeof callback !== 'function') return original(callback, delay, ...args);
+ const key = `${kind}:${delay ?? 0}`;
+ return original((...values) => {
+ if (capture.active && (key in capture.timers || Object.keys(capture.timers).length < 64)) {
+ capture.timers[key] = (capture.timers[key] ?? 0) + 1;
+ }
+ callback.apply(window, values);
+ }, delay, ...args);
+ };
+ }
+ const originalFrame = window.requestAnimationFrame.bind(window);
+ window.requestAnimationFrame = (callback) => originalFrame((time) => {
+ if (capture.active) capture.raf++;
+ callback(time);
+ });
+ for (const type of ['longtask', 'long-animation-frame']) {
+ if (!PerformanceObserver.supportedEntryTypes.includes(type)) continue;
+ new PerformanceObserver((list) => {
+ if (!capture.active) return;
+ for (const entry of list.getEntries()) {
+ if (entry.startTime >= capture.start && capture.longEntries.length < 200) capture.longEntries.push({ type, startTime: entry.startTime, duration: entry.duration, blockingDuration: entry.blockingDuration });
+ }
+ }).observe({ type });
+ }
+ });
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 90000 });
+ await page.locator('[data-entity]').first().waitFor({ timeout: 90000 });
+ await page.evaluate(() => document.fonts.ready);
+ await page.waitForTimeout(2000);
+ if (errors.length || requests.length) throw new Error(JSON.stringify({ errors, requests }));
+ const nonce = await page.evaluate(() => window.__runtimeCapture.nonce);
+ const count = await page.locator('[data-entity]').count();
+ if (count !== 1000) throw new Error(`Expected 1000 mounted rows, got ${count}`);
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Performance.enable');
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 });
+ const metrics = async () => Object.fromEntries((await cdp.send('Performance.getMetrics')).metrics.map(({ name, value }) => [name, value]));
+ for (const phase of ['idle', 'scroll', 'hover']) {
+ const traceFinished = new Promise((resolve) => cdp.once('Tracing.tracingComplete', resolve));
+ await cdp.send('Tracing.start', { categories: 'devtools.timeline,blink.user_timing,cc,gpu', transferMode: 'ReturnAsStream' });
+ await page.evaluate(() => {
+ Object.assign(window.__runtimeCapture, { start: performance.now(), active: true, raf: 0, timers: {}, longEntries: [] });
+ });
+ const before = await metrics();
+ if (phase === 'idle') await page.waitForTimeout(10000);
+ if (phase === 'scroll') {
+ await page.mouse.move(500, 450);
+ for (let index = 0; index < 40; index++) {
+ await page.mouse.wheel(0, 500);
+ await page.waitForTimeout(100);
+ }
+ await page.waitForTimeout(300);
+ }
+ if (phase === 'hover') {
+ for (let index = 0; index < 80; index++) {
+ await page.mouse.move(300, 30 + (index % 20) * 40);
+ await page.waitForTimeout(40);
+ }
+ await page.mouse.move(2, 2);
+ await page.waitForTimeout(300);
+ }
+ const after = await metrics();
+ const capture = await page.evaluate(() => {
+ window.__runtimeCapture.active = false;
+ return { ...window.__runtimeCapture, rows: document.querySelectorAll('[data-entity]').length, scrollTop: document.querySelector('[data-list]').scrollTop };
+ });
+ if (capture.nonce !== nonce || capture.rows !== count || after.TaskDuration < before.TaskDuration) throw new Error('Page changed during capture');
+ if (phase === 'scroll' && capture.scrollTop <= 0) throw new Error('Wheel input did not scroll the collection');
+ await cdp.send('Tracing.end');
+ const { stream } = await traceFinished;
+ let trace = '';
+ for (;;) {
+ const chunk = await cdp.send('IO.read', { handle: stream });
+ trace += chunk.data;
+ if (chunk.eof) break;
+ }
+ await cdp.send('IO.close', { handle: stream });
+ await writeFile(`${output}/${mode}-${phase}-trace.json`, trace);
+ const events = JSON.parse(trace).traceEvents;
+ const counts = {};
+ for (const name of ['Paint', 'RasterTask', 'ProxyImpl::ScheduledActionDraw', 'CompositeLayers', 'GPUTask']) {
+ const matches = events.filter((event) => event.name === name);
+ counts[name] = { count: matches.length, durationMs: matches.reduce((sum, event) => sum + (event.dur ?? 0), 0) / 1000 };
+ }
+ const row = { mode, phase, delta: Object.fromEntries(['Timestamp', 'TaskDuration', 'ScriptDuration', 'RecalcStyleDuration', 'LayoutDuration', 'RecalcStyleCount', 'LayoutCount'].map((key) => [key, after[key] - before[key]])), capture, counts };
+ results.push(row);
+ await page.screenshot({ path: `${output}/${mode}-${phase}.png` });
+ console.log(JSON.stringify(row));
+ await writeFile(`${output}/results.json`, JSON.stringify(results, null, 2));
+ }
+ if (errors.length || requests.length) throw new Error(JSON.stringify({ errors, requests }));
+ } finally {
+ await browser.close();
+ }
+}
diff --git a/apps/web/src/features/entity/browser-test/row-cost.mjs b/apps/web/src/features/entity/browser-test/row-cost.mjs
new file mode 100644
index 0000000000..739ee41ee9
--- /dev/null
+++ b/apps/web/src/features/entity/browser-test/row-cost.mjs
@@ -0,0 +1,212 @@
+import { mkdir, writeFile } from 'node:fs/promises';
+import { chromium } from 'playwright';
+
+const output = process.env.ROW_OUTPUT ?? '/tmp/entity-row-cost';
+const url =
+ process.env.ROW_URL ??
+ 'https://localhost:3008/src/features/entity/browser-test/long-list.html?benchmark&count=200';
+await mkdir(output, { recursive: true });
+const browser = await chromium.launch({
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ args: ['--enable-precise-memory-info', '--js-flags=--expose-gc'],
+});
+try {
+ const page = await browser.newPage({
+ ignoreHTTPSErrors: true,
+ viewport: { width: 1440, height: 900 },
+ });
+ const errors = [];
+ const rejected = [];
+ let capturing = false;
+ page.on('load', () => {
+ if (capturing) errors.push('Unexpected reload during capture');
+ });
+ const origin = new URL(url).origin;
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.route('**/*', async (route) => {
+ const request = route.request();
+ const resource = new URL(request.url());
+ const asset = [
+ '/src/',
+ '/node_modules/',
+ '/@fs/',
+ '/@vite/',
+ '/@id/',
+ '/assets/',
+ ].some((prefix) => resource.pathname.startsWith(prefix));
+ if (
+ resource.origin !== origin ||
+ (['fetch', 'xhr'].includes(request.resourceType()) && !asset)
+ ) {
+ rejected.push(resource.origin + resource.pathname);
+ await route.abort();
+ } else await route.continue();
+ });
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 90000 });
+ await page.waitForFunction(
+ () => window.entityRowBenchmark !== undefined,
+ undefined,
+ { timeout: 90000 }
+ );
+ await page.evaluate(() => document.fonts.ready);
+ await page.waitForLoadState('load');
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Performance.enable');
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 });
+ const metrics = async () =>
+ Object.fromEntries(
+ (await cdp.send('Performance.getMetrics')).metrics.map(
+ ({ name, value }) => [name, value]
+ )
+ );
+ const frame = () =>
+ page.evaluate(
+ () =>
+ new Promise((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(resolve))
+ )
+ );
+ const invoke = (action) =>
+ page.evaluate((action) => {
+ const api = window.entityRowBenchmark;
+ const before = api.stats();
+ const elements = [
+ ...document.querySelectorAll(
+ '[data-entity], [data-button], [role=checkbox]'
+ ),
+ ];
+ const start = performance.now();
+ api[action]();
+ const durationMs = performance.now() - start;
+ if (['select', 'rename', 'replace'].includes(action)) {
+ const current = [
+ ...document.querySelectorAll(
+ '[data-entity], [data-button], [role=checkbox]'
+ ),
+ ];
+ if (
+ elements.length !== current.length ||
+ elements.some((element, index) => current[index] !== element)
+ )
+ throw new Error(`${action} replaced row or action DOM`);
+ }
+ const after = api.stats();
+ if (action === 'select' && after.checked !== (after.selected ? 200 : 0))
+ throw new Error('Selection did not reach every checkbox');
+ if (
+ ['rename', 'replace'].includes(action) &&
+ !document
+ .querySelector('[data-entity]')
+ .textContent.includes(after.firstName)
+ )
+ throw new Error('Updated model did not reach row content');
+ return { durationMs, before, after };
+ }, action);
+ // Warm module caches, variant strings and model proxies outside captures.
+ await invoke('mount');
+ await frame();
+ await invoke('clear');
+ await frame();
+ capturing = true;
+ const captures = [];
+ for (let round = 0; round < 5; round++) {
+ for (const phase of ['mount', 'select', 'rename', 'replace', 'clear']) {
+ const before = await metrics();
+ const result = await invoke(phase);
+ await frame();
+ const after = await metrics();
+ if (phase !== 'clear' && result.after.rows !== 200)
+ throw new Error(`Expected 200 rows in ${phase}`);
+ if (
+ ['select', 'rename', 'replace'].includes(phase) &&
+ result.after.mounts !== result.before.mounts
+ )
+ throw new Error(`${phase} remounted rows`);
+ captures.push({
+ round,
+ phase,
+ ...result,
+ scriptMs: 1000 * (after.ScriptDuration - before.ScriptDuration),
+ taskMs: 1000 * (after.TaskDuration - before.TaskDuration),
+ });
+ }
+ }
+ const allocations = [];
+ for (const phase of ['mount', 'select', 'rename', 'replace', 'clear']) {
+ await cdp.send('HeapProfiler.collectGarbage');
+ const before = await metrics();
+ await cdp.send('HeapProfiler.startSampling', {
+ samplingInterval: 16384,
+ includeObjectsCollectedByMajorGC: true,
+ includeObjectsCollectedByMinorGC: true,
+ });
+ const result = await invoke(phase);
+ await frame();
+ const { profile } = await cdp.send('HeapProfiler.stopSampling');
+ const after = await metrics();
+ const bytes = (node) =>
+ node.selfSize +
+ node.children.reduce((sum, child) => sum + bytes(child), 0);
+ allocations.push({
+ phase,
+ sampledAllocatedBytes: bytes(profile.head),
+ heapGrowthBytes: after.JSHeapUsedSize - before.JSHeapUsedSize,
+ ...result,
+ });
+ }
+ // Separate diagnostic pass: profiler overhead is excluded from timing samples.
+ await cdp.send('Profiler.enable');
+ await cdp.send('Profiler.setSamplingInterval', { interval: 100 });
+ for (const phase of ['mount', 'select', 'rename', 'replace', 'clear']) {
+ await cdp.send('Profiler.start');
+ await invoke(phase);
+ const { profile } = await cdp.send('Profiler.stop');
+ await writeFile(`${output}/${phase}.cpuprofile`, JSON.stringify(profile));
+ await frame();
+ }
+ await invoke('mount');
+ await frame();
+ await page.screenshot({ path: `${output}/rows.png` });
+ const classes = await page.locator('[data-entity]').evaluateAll((rows) =>
+ rows.map((row) =>
+ [...row.querySelectorAll('*'), row].map((element) => ({
+ tag: element.tagName,
+ class: element.getAttribute('class'),
+ slot: element.getAttribute('data-slot'),
+ }))
+ )
+ );
+ if (errors.length || rejected.length)
+ throw new Error(JSON.stringify({ errors, rejected }));
+ const report = {
+ captures,
+ allocations,
+ stats: await page.evaluate(() => window.entityRowBenchmark.stats()),
+ classes,
+ };
+ await writeFile(`${output}/results.json`, JSON.stringify(report, null, 2));
+ const median = (values) =>
+ values.sort((a, b) => a - b)[Math.floor(values.length / 2)];
+ console.log(
+ JSON.stringify({
+ phases: Object.fromEntries(
+ ['mount', 'select', 'rename', 'replace', 'clear'].map((phase) => [
+ phase,
+ {
+ medianMs: median(
+ captures
+ .filter((row) => row.phase === phase)
+ .map((row) => row.durationMs)
+ ),
+ sampledAllocatedBytes: allocations.find(
+ (row) => row.phase === phase
+ ).sampledAllocatedBytes,
+ },
+ ])
+ ),
+ stats: report.stats,
+ })
+ );
+} finally {
+ await browser.close();
+}
diff --git a/apps/web/src/features/entity/composed/ListEntity.tsx b/apps/web/src/features/entity/composed/ListEntity.tsx
index 34d8deff2b..4ff277dd49 100644
--- a/apps/web/src/features/entity/composed/ListEntity.tsx
+++ b/apps/web/src/features/entity/composed/ListEntity.tsx
@@ -164,35 +164,86 @@ export function ListEntity(props: ListEntityProps) {
const showContentHits = () => showHitSnippet() && !isContentHitsRedundant();
- const layoutProps = (): LayoutProps => ({
- entity: props.entity,
- actions: !isTouchDevice() ? rowActions() : undefined,
- leadingAction: isTouchDevice() ? touchActions() : leadingAction(),
- titleLeading: titleLeading(),
- icon: icon(),
- titleTrailing: titleTrailing(),
- meta: meta(),
- metaEnd: metaEnd(),
- previewLeading: previewLeading(),
- scheduleStatus: scheduleStatus(),
- referenceProperties: referenceProperties(),
- authorDisplayName: props.authorDisplayName,
- checked: props.checked,
- hideCheckbox: props.hideCheckbox,
- onChecked: props.onChecked,
- unread: unread(),
- isShared: isShared(),
- hasNotifications: hasNotifications(),
- showHitSnippet: showHitSnippet(),
- streamState: streamState(),
+ // Forward fields independently. A dynamic object spread would make a
+ // selection change reevaluate every layout input and its downstream memos.
+ const layoutProps: LayoutProps = {
+ get entity() {
+ return props.entity;
+ },
+ get actions() {
+ return !isTouchDevice() ? rowActions() : undefined;
+ },
+ get leadingAction() {
+ return isTouchDevice() ? touchActions() : leadingAction();
+ },
+ get titleLeading() {
+ return titleLeading();
+ },
+ get icon() {
+ return icon();
+ },
+ get titleTrailing() {
+ return titleTrailing();
+ },
+ get meta() {
+ return meta();
+ },
+ get metaEnd() {
+ return metaEnd();
+ },
+ get previewLeading() {
+ return previewLeading();
+ },
+ get scheduleStatus() {
+ return scheduleStatus();
+ },
+ get referenceProperties() {
+ return referenceProperties();
+ },
+ get authorDisplayName() {
+ return props.authorDisplayName;
+ },
+ get checked() {
+ return props.checked;
+ },
+ get hideCheckbox() {
+ return props.hideCheckbox;
+ },
+ get onChecked() {
+ return props.onChecked;
+ },
+ get unread() {
+ return unread();
+ },
+ get isShared() {
+ return isShared();
+ },
+ get hasNotifications() {
+ return hasNotifications();
+ },
+ get showHitSnippet() {
+ return showHitSnippet();
+ },
+ get streamState() {
+ return streamState();
+ },
setSnippetContainerRef,
- chars: chars(),
- onProjectClick: props.onProjectClick,
- onFilterByTag: props.onFilterByTag ?? soupView?.filterByTag,
- showCalendarAttendance:
- props.showCalendarAttendance ??
- (soupView?.activeTab() ?? 'all') === 'all',
- });
+ get chars() {
+ return chars();
+ },
+ get onProjectClick() {
+ return props.onProjectClick;
+ },
+ get onFilterByTag() {
+ return props.onFilterByTag ?? soupView?.filterByTag;
+ },
+ get showCalendarAttendance() {
+ return (
+ props.showCalendarAttendance ??
+ (soupView?.activeTab() ?? 'all') === 'all'
+ );
+ },
+ };
const draggable = createEntityDraggable({
entity: props.entity,
@@ -298,7 +349,7 @@ export function ListEntity(props: ListEntityProps) {
entityId={props.entity.id}
config={props.entityRowConfig}
>
- <WideLayout {...layoutProps()} />
+ <WideLayout {...layoutProps} />
</MaybeEntityRow>
</Match>
{/* Mixed-type lists (Search) render every entity as one line, ahead
@@ -308,7 +359,7 @@ export function ListEntity(props: ListEntityProps) {
entityId={props.entity.id}
config={props.entityRowConfig}
>
- <NarrowSingleLineLayout {...layoutProps()} />
+ <NarrowSingleLineLayout {...layoutProps} />
</MaybeEntityRow>
</Match>
{/* Email lists on desktop stack their rows compactly; mixed lists keep
@@ -321,7 +372,7 @@ export function ListEntity(props: ListEntityProps) {
entityId={props.entity.id}
config={props.entityRowConfig}
>
- <NarrowEmailLayout {...layoutProps()} entity={entity()} />
+ <NarrowEmailLayout {...layoutProps} entity={entity()} />
</MaybeEntityRow>
)}
</Match>
@@ -345,7 +396,7 @@ export function ListEntity(props: ListEntityProps) {
entityId={props.entity.id}
config={props.entityRowConfig}
>
- <NarrowInboxLayout {...layoutProps()} />
+ <NarrowInboxLayout {...layoutProps} />
</MaybeEntityRow>
</Match>
<Match when={!isMobile() && usesCondensedNarrowLayout()}>
@@ -353,7 +404,7 @@ export function ListEntity(props: ListEntityProps) {
entityId={props.entity.id}
config={props.entityRowConfig}
>
- <NarrowCondensedLayout {...layoutProps()} />
+ <NarrowCondensedLayout {...layoutProps} />
</MaybeEntityRow>
</Match>
<Match when={true}>
@@ -361,7 +412,7 @@ export function ListEntity(props: ListEntityProps) {
entityId={props.entity.id}
config={props.entityRowConfig}
>
- <NarrowLayout {...layoutProps()} />
+ <NarrowLayout {...layoutProps} />
</MaybeEntityRow>
</Match>
</Switch>
diff --git a/apps/web/src/features/entity/utils/timestamp.test.ts b/apps/web/src/features/entity/utils/timestamp.test.ts
index 6fe84f62c5..446a2a903f 100644
--- a/apps/web/src/features/entity/utils/timestamp.test.ts
+++ b/apps/web/src/features/entity/utils/timestamp.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { formatCompactRelativeTimestamp } from './timestamp';
+import { formatCompactRelativeTimestamp, formatTimestamp } from './timestamp';
const NOW = new Date('2026-09-07T12:00:00.000Z');
@@ -33,3 +33,42 @@ describe('formatCompactRelativeTimestamp', () => {
expect(formatCompactRelativeTimestamp('not a date')).toBe('not a date');
});
});
+
+describe('formatTimestamp system timezone', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllEnvs();
+ });
+
+ it('keeps invalid input from throwing during row rendering', () => {
+ expect(formatTimestamp('not a date')).toBe('Invalid Date');
+ });
+
+ it('updates time, calendar day and year after system timezone changes', () => {
+ const today = '2026-09-07T11:00:00Z';
+ const sameYear = '2026-07-04T01:00:00Z';
+ const oldYear = '2025-01-01T01:00:00Z';
+ vi.stubEnv('TZ', 'UTC');
+ expect([today, sameYear, oldYear].map(formatTimestamp)).toEqual([
+ '11:00 AM',
+ 'Jul 4',
+ '1/1/25',
+ ]);
+ vi.stubEnv('TZ', 'America/New_York');
+ expect([today, sameYear, oldYear].map(formatTimestamp)).toEqual([
+ '7:00 AM',
+ 'Jul 3',
+ '12/31/24',
+ ]);
+ vi.stubEnv('TZ', 'UTC');
+ expect([today, sameYear, oldYear].map(formatTimestamp)).toEqual([
+ '11:00 AM',
+ 'Jul 4',
+ '1/1/25',
+ ]);
+ });
+});
diff --git a/apps/web/src/features/entity/utils/timestamp.ts b/apps/web/src/features/entity/utils/timestamp.ts
index de2b88c9df..97641958f3 100644
--- a/apps/web/src/features/entity/utils/timestamp.ts
+++ b/apps/web/src/features/entity/utils/timestamp.ts
@@ -11,6 +11,7 @@ import {
isSameYear,
isToday,
isYesterday,
+ toDate,
} from 'date-fns';
/**
@@ -20,15 +21,17 @@ import {
* - Older: Shows full date (e.g., "1/27/24")
*/
export function formatTimestamp(date: DateValue): string {
- if (isToday(date)) {
- return format(date, 'h:mm a');
+ const value = toDate(date);
+ if (Number.isNaN(value.getTime())) return 'Invalid Date';
+ if (isToday(value)) {
+ return format(value, 'h:mm a');
}
- if (isSameYear(date, new Date())) {
- return format(date, 'MMM d');
+ if (isSameYear(value, new Date())) {
+ return format(value, 'MMM d');
}
- return format(date, 'M/d/yy');
+ return format(value, 'M/d/yy');
}
/**