TypeScript
chore(web): measure renders before/after with render scenarios (#24980)
Julius Marminge2dfd6bf0ea04
diff --git a/apps/web/test/appScenarios.renders.tsx b/apps/web/test/appScenarios.renders.tsxnew file mode 100644index 00000000000..897e1cb02ab--- /dev/null+++ b/apps/web/test/appScenarios.renders.tsx@@ -0,0 +1,282 @@+// Render scenarios that mount the whole app (AppRoot with the app's router) on a thread,+// against the in-process environment in fakeEnvironment.ts. Counts cover ChatView, the+// chat and settings routes, the sidebar and the right panel, through the same stores and+// atoms the app reads. See renderScenarios.renders.tsx for the counting rules.+import { createMemoryHistory } from "@tanstack/react-router";+import type { ThreadId } from "@t3tools/contracts";+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";+import type * as Context from "effect/Context";+import { expect, it, vi } from "vite-plus/test";+import { commands, page, userEvent } from "vite-plus/test/browser";++import "~/index.css";++import { AppRoot } from "~/AppRoot";+import { __setClientSettingsForTests } from "~/hooks/useSettings";+import { getRouter, type AppRouter } from "~/router";+import {+ ENVIRONMENT_ID,+ assistantItem,+ emitThreadEvent,+ installFakeEnvironment,+ isThreadSubscribed,+ runningRun,+ threadWithHistory,+ userItem,+ type FakeDriver,+} from "./fakeEnvironment";+import { commitsSoFar, startCounting, stopCounting, type RenderReport } from "./renderCounter";+import { act, fakeTimers, render } from "./render";++// The socket is the only fake layer: client-runtime's driver hands every connection the+// in-process session. A string path, since a typed import pulls client-runtime's sources+// into this project, and imports inside, since the factory runs before this file's own.+vi.mock("../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {+ const [actual, { fakeDriver }, Layer] = await Promise.all([+ importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),+ import("./fakeEnvironment"),+ import("effect/Layer"),+ ]);+ return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };+});++// The fake server leaves most requests unanswered, which would raise the slow-request toast+// 15s of wall clock after each one, at a different point in every run.+vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({+ ...(await original()),+ trackRpcRequestSent: () => {},+}));++const HISTORY_TURNS = 20;+const STREAM_DELTAS = 30;+const TYPED_TEXT = "fix the flaky tests!";+// The stream scenario leaves a turn on its thread, so it streams into one no other scenario opens.+const THREADS = ["thread-warm", "thread-a", "thread-b", "thread-live"].map((name) =>+ threadWithHistory(name, HISTORY_TURNS),+);+const [WARM, A, B, LIVE] = THREADS.map((thread) => thread.id) as [+ ThreadId,+ ThreadId,+ ThreadId,+ ThreadId,+];++installFakeEnvironment(THREADS);+// Desktop-sized, so the sidebar, composer and right panel lay out as they do in the app.+await page.viewport(1400, 900);+// A returning user: the first-run gate would otherwise wait on onboarding evidence.+__setClientSettingsForTests({+ ...DEFAULT_CLIENT_SETTINGS,+ onboardingCompletedAt: "2026-01-01T00:00:00.000Z",+});++async function quiet() {+ let seen = -1;+ await vi.waitFor(+ () => {+ const now = commitsSoFar();+ const settled = now === seen;+ seen = now;+ expect(settled).toBe(true);+ },+ { interval: 100, timeout: 15_000 },+ );+}++// Relative times and durations re-render on minute and second ticks of the wall clock, so a+// window that spans a tick counts extra renders. Only Date is frozen; timers run for real.+const frozenClock = () =>+ fakeTimers({ toFake: ["Date"], now: new Date("2026-03-18T09:00:30.000Z") });++const threadPath = (threadId: ThreadId) => `/${ENVIRONMENT_ID}/${threadId}`;+const lastAnswer = (threadId: ThreadId) =>+ page.getByText(`Answer ${HISTORY_TURNS - 1} for ${threadId}.`);++// The app owns its router, as main.tsx does, so render() adds none.+async function mountApp(path: string) {+ const router = getRouter(createMemoryHistory({ initialEntries: [path] }));+ await router.load();+ const container = document.createElement("div");+ container.style.cssText = "height: 900px; width: 1400px;";+ const screen = await render(<AppRoot router={router} />, { container, router: false });+ return { screen, router };+}++async function openThread(threadId: ThreadId) {+ const app = await mountApp(threadPath(threadId));+ await expect.element(lastAnswer(threadId)).toBeVisible();+ await quiet();+ return app;+}++async function measure(action: () => Promise<void>): Promise<RenderReport> {+ await quiet();+ startCounting();+ await action();+ await quiet();+ return stopCounting();+}++// Commits are left out across several windows, and where frame batching splits a window's+// commits differently from run to run while its renders stay identical.+async function report(+ scenario: string,+ windows: ReadonlyArray<RenderReport>,+ { commits: countCommits = windows.length === 1 } = {},+) {+ const components: Record<string, number> = {};+ for (const window of windows) {+ for (const [name, count] of Object.entries(window.components)) {+ components[name] = (components[name] ?? 0) + count;+ }+ }+ const total = windows.reduce((sum, window) => sum + window.renders, 0);+ const commits = countCommits ? windows[0]!.commits : null;+ await commands.writeRenderReport(+ scenario,+ JSON.stringify({ commits, renders: total, components }),+ );+}++// A first mount loads lazy route chunks, fonts and the connection at varying times. The diff+// panel and settings load more chunks on first open (the T3 Connect sidebar, the terminal+// preview's renderer), which can land after a window has gone quiet, so the warm-up opens+// each once and lets it settle.+it("warm up", async () => {+ using _clock = frozenClock();+ const { screen, router } = await openThread(WARM);+ await using _app = screen;+ await document.fonts.ready;+ await quiet();+ await toggleDiff("open")();+ await quiet();+ await toggleDiff("close")();+ await quiet();+ await openSettings(router, "/settings/general")();+ await openSettings(router, "/settings/appearance")();+ await quiet();+});++it("app-mount-thread", async () => {+ using _clock = frozenClock();+ startCounting();+ await using _app = (await mountApp(threadPath(A))).screen;+ await expect.element(lastAnswer(A)).toBeVisible();+ await quiet();+ await report("app-mount-thread", [stopCounting()]);+});++it("app-stream-assistant-turn", async () => {+ using _clock = frozenClock();+ await using _app = (await openThread(LIVE)).screen;+ expect(isThreadSubscribed(LIVE)).toBe(true);+ const live = runningRun(LIVE, "live-run", HISTORY_TURNS + 1, "live-user");+ await act(async () => {+ await emitThreadEvent(LIVE, { type: "run.created", payload: live });+ await emitThreadEvent(LIVE, {+ type: "turn-item.updated",+ payload: userItem(LIVE, live.id, "live-user", HISTORY_TURNS * 2, "Continue"),+ });+ });+ await expect.element(page.getByText("Continue", { exact: true })).toBeVisible();+ const counted = await measure(async () => {+ let text = "";+ for (let delta = 0; delta < STREAM_DELTAS; delta++) {+ text += `word${delta} `;+ await act(() =>+ emitThreadEvent(LIVE, {+ type: "turn-item.updated",+ payload: assistantItem(+ LIVE,+ live.id,+ "live-assistant",+ HISTORY_TURNS * 2 + 1,+ text,+ true,+ ),+ }),+ );+ }+ await expect+ .element(page.getByText(`word${STREAM_DELTAS - 1}`, { exact: false }))+ .toBeVisible();+ });+ await report("app-stream-assistant-turn", [counted], { commits: false });+});++it("app-type-in-composer", async () => {+ using _clock = frozenClock();+ await using _app = (await openThread(A)).screen;+ const editor = page.getByTestId("composer-editor");+ await userEvent.click(editor);+ const counted = await measure(async () => {+ await userEvent.type(editor, TYPED_TEXT);+ await expect.element(editor).toHaveTextContent(TYPED_TEXT);+ });+ await report("app-type-in-composer", [counted]);+});++it("app-switch-thread", async () => {+ using _clock = frozenClock();+ const { screen, router } = await openThread(A);+ await using _app = screen;+ const go = (threadId: ThreadId) => async () => {+ await act(() =>+ router.navigate({+ to: "/$environmentId/$threadId",+ params: { environmentId: ENVIRONMENT_ID, threadId },+ }),+ );+ await expect.element(lastAnswer(threadId)).toBeVisible();+ };+ await report("app-switch-thread", [await measure(go(B)), await measure(go(A))]);+});++// Through the diff.toggle shortcut, the same handler as the header's diff button.+const toggleDiff = (to: "open" | "close") => async () => {+ await userEvent.keyboard("{Control>}d{/Control}");+ const diff = page.getByRole("group", { name: "Diff layout" });+ if (to === "open") await expect.element(diff).toBeVisible();+ else await expect.element(diff).not.toBeInTheDocument();+};++it("app-toggle-diff-panel", async () => {+ using _clock = frozenClock();+ await using _app = (await openThread(A)).screen;+ const open = await measure(toggleDiff("open"));+ const close = await measure(toggleDiff("close"));+ await report("app-toggle-diff-panel", [open, close]);+});++const openSettings =+ (router: AppRouter, to: "/settings/general" | "/settings/appearance") => async () => {+ await act(() => router.navigate({ to }));+ // A section title from each page, since neither page has a heading that names it.+ const name = to === "/settings/general" ? "Time format" : "Motion";+ await expect.element(page.getByRole("heading", { name, exact: true })).toBeVisible();+ // Appearance highlights its code font preview off-thread, then attaches it in a shadow root.+ if (to === "/settings/appearance") {+ await vi.waitFor(+ () =>+ expect([...document.querySelectorAll("div")].some((node) => node.shadowRoot)).toBe(true),+ { interval: 100, timeout: 15_000 },+ );+ }+ };++it("app-open-settings", async () => {+ using _clock = frozenClock();+ const { screen, router } = await openThread(A);+ await using _app = screen;+ await report("app-open-settings", [await measure(openSettings(router, "/settings/general"))]);+});++it("app-switch-settings-section", async () => {+ using _clock = frozenClock();+ const { screen, router } = await openThread(A);+ await using _app = screen;+ await openSettings(router, "/settings/general")();+ await report("app-switch-settings-section", [+ await measure(openSettings(router, "/settings/appearance")),+ ]);+});diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.tsnew file mode 100644index 00000000000..318a8cd0267--- /dev/null+++ b/apps/web/test/fakeEnvironment.ts@@ -0,0 +1,469 @@+// An in-process environment for app render scenarios: a fetch stub for its HTTP API and a+// session that answers the shell, thread and config subscriptions from fixtures. Other RPCs+// stay pending so nothing retries on timers. Everything above the wire is the app's own.+import {+ AuthStandardClientScopes,+ EnvironmentId,+ EventId,+ ExecutionEnvironmentDescriptor,+ MessageId,+ ORCHESTRATION_PROTOCOL_VERSION,+ ORCHESTRATION_V2_WS_METHODS,+ ProjectId,+ ProviderInstanceId,+ RunId,+ ServerConfig,+ ThreadId,+ TurnItemId,+ WS_METHODS,+ WsRpcGroup,+ type OrchestrationProjectShell,+ type OrchestrationV2ProjectedTurnItem,+ type OrchestrationV2Run,+ type OrchestrationV2ShellStreamItem,+ type OrchestrationV2ThreadProjection,+ type OrchestrationV2ThreadShell,+ type OrchestrationV2ThreadStreamItem,+ type OrchestrationV2TurnItem,+} from "@t3tools/contracts";+import type {+ ConnectionAttemptError,+ ConnectionCatalogEntry,+ EnvironmentConnectionLease,+ RouteCheck,+} from "@t3tools/client-runtime/connection";+import type { WsRpcProtocolClient } from "@t3tools/client-runtime/rpc";+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";+import { APP_VERSION } from "~/branding";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Queue from "effect/Queue";+import type * as Scope from "effect/Scope";+import * as Schema from "effect/Schema";+import * as Stream from "effect/Stream";+import { RpcSchema } from "effect/rpc";++export const ENVIRONMENT_ID = EnvironmentId.make("environment-render");+const PROJECT_ID = ProjectId.make("project-render");+const CODEX = ProviderInstanceId.make("codex");+const MODEL = { instanceId: CODEX, model: "gpt-5.4" };+const AT = DateTime.makeUnsafe("2026-03-17T19:12:28.000Z");++const descriptor = {+ environmentId: ENVIRONMENT_ID,+ label: "Render scenarios",+ platform: { os: "linux", arch: "x64" },+ // A matching version, since a mismatch adds an update banner a typical user never sees.+ serverVersion: APP_VERSION,+ orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,+ capabilities: { repositoryIdentity: true },+};+const auth = {+ policy: "loopback-browser",+ bootstrapMethods: ["one-time-token"],+ sessionMethods: ["browser-session-cookie"],+ sessionCookieName: "t3_session",+};++const serverConfig: ServerConfig = {+ ...Schema.decodeUnknownSync(ServerConfig)({+ environment: descriptor,+ auth,+ cwd: "/workspace/render",+ keybindingsConfigPath: "/workspace/.t3/keybindings.json",+ keybindings: [],+ issues: [],+ providers: [+ {+ instanceId: CODEX,+ driver: "codex",+ enabled: true,+ installed: true,+ version: "1.0.0",+ status: "ready",+ auth: { status: "authenticated" },+ checkedAt: "2026-03-17T19:12:28.000Z",+ models: [{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: null }],+ },+ ],+ availableEditors: [],+ observability: {+ logsDirectoryPath: "/workspace/.t3/logs",+ localTracingEnabled: false,+ otlpTracesEnabled: false,+ otlpMetricsEnabled: false,+ },+ settings: {},+ threadSnapshotPagination: true,+ threadResumeCompletionMarker: true,+ shellResumeCompletionMarker: true,+ }),+ keybindings: DEFAULT_RESOLVED_KEYBINDINGS,+};++const project: OrchestrationProjectShell = {+ id: PROJECT_ID,+ title: "render",+ workspaceRoot: "/workspace/render",+ repositoryIdentity: null,+ defaultModelSelection: null,+ scripts: [],+ createdAt: "2026-03-17T19:12:28.000Z",+ updatedAt: "2026-03-17T19:12:28.000Z",+};++const base = (threadId: ThreadId, runId: RunId, id: string, ordinal: number) => ({+ id: TurnItemId.make(id),+ threadId,+ runId,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal,+ status: "completed" as const,+ title: null,+ startedAt: AT,+ completedAt: AT,+ updatedAt: AT,+});++function userItem(threadId: ThreadId, runId: RunId, id: string, ordinal: number, text: string) {+ return {+ ...base(threadId, runId, id, ordinal),+ type: "user_message",+ messageId: MessageId.make(id),+ text,+ attachments: [],+ inputIntent: "turn_start",+ createdBy: "user",+ creationSource: "web",+ } satisfies OrchestrationV2TurnItem;+}++export function assistantItem(+ threadId: ThreadId,+ runId: RunId,+ id: string,+ ordinal: number,+ text: string,+ streaming = false,+) {+ return {+ ...base(threadId, runId, id, ordinal),+ type: "assistant_message",+ messageId: MessageId.make(id),+ text,+ streaming,+ ...(streaming ? { status: "running" as const, completedAt: null } : {}),+ } satisfies OrchestrationV2TurnItem;+}++function run(threadId: ThreadId, id: RunId, ordinal: number, userMessageId: string) {+ return {+ id,+ threadId,+ ordinal,+ providerInstanceId: CODEX,+ modelSelection: MODEL,+ providerThreadId: null,+ userMessageId: MessageId.make(userMessageId),+ rootNodeId: null,+ activeAttemptId: null,+ status: "completed",+ requestedAt: AT,+ startedAt: AT,+ completedAt: AT,+ checkpointId: null,+ contextHandoffId: null,+ } satisfies OrchestrationV2Run;+}++export interface FakeThread {+ readonly id: ThreadId;+ readonly title: string;+ readonly runs: ReadonlyArray<OrchestrationV2Run>;+ readonly items: ReadonlyArray<OrchestrationV2TurnItem>;+}++/** A thread of `turns` user prompts, each answered in markdown with a list and inline code. */+export function threadWithHistory(name: string, turns: number): FakeThread {+ const id = ThreadId.make(name);+ const runs: OrchestrationV2Run[] = [];+ const items: OrchestrationV2TurnItem[] = [];+ for (let turn = 0; turn < turns; turn++) {+ const runId = RunId.make(`${name}-run-${turn}`);+ runs.push(run(id, runId, turn + 1, `${name}-user-${turn}`));+ items.push(+ userItem(id, runId, `${name}-user-${turn}`, turn * 2, `${name}: question ${turn}`),+ assistantItem(+ id,+ runId,+ `${name}-assistant-${turn}`,+ turn * 2 + 1,+ `Answer ${turn} for ${name}.\n\n- checked \`Sidebar.tsx\`\n- ran the tests\n\n` ++ "The width is now `clamp(next, MIN_WIDTH, MAX_WIDTH)`, so the layout no longer jumps.",+ ),+ );+ }+ return { id, title: `Thread ${name}`, runs, items };+}++function shellOf(thread: FakeThread): OrchestrationV2ThreadShell {+ const latest = thread.runs.at(-1);+ return {+ id: thread.id,+ projectId: PROJECT_ID,+ title: thread.title,+ providerInstanceId: CODEX,+ modelSelection: MODEL,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: "main",+ worktreePath: null,+ activeProviderThreadId: null,+ lineage: { rootThreadId: thread.id, parentThreadId: null, relationshipToParent: null },+ forkedFrom: null,+ createdBy: "user",+ creationSource: "web",+ latestRunId: latest?.id ?? null,+ activeRunId: null,+ // Idle reads as waiting on the user, which shows a per-second duration in the sidebar.+ status: latest ? "completed" : "idle",+ pendingRuntimeRequest: null,+ latestVisibleMessage: null,+ latestUserMessageAt: AT,+ hasActionableProposedPlan: false,+ itemCount: thread.items.length,+ visibleItemCount: thread.items.length,+ createdAt: AT,+ updatedAt: AT,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: AT,+ deletedAt: null,+ };+}++function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection {+ const shell = shellOf(thread);+ const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = thread.items.map(+ (item, position) => ({+ position,+ visibility: "local",+ sourceThreadId: thread.id,+ sourceItemId: item.id,+ item,+ }),+ );+ return {+ thread: {+ id: shell.id,+ projectId: shell.projectId,+ title: shell.title,+ providerInstanceId: shell.providerInstanceId,+ modelSelection: shell.modelSelection,+ runtimeMode: shell.runtimeMode,+ interactionMode: shell.interactionMode,+ branch: shell.branch,+ worktreePath: shell.worktreePath,+ activeProviderThreadId: null,+ lineage: shell.lineage,+ forkedFrom: null,+ createdBy: "user",+ creationSource: "web",+ createdAt: AT,+ updatedAt: AT,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: AT,+ deletedAt: null,+ },+ runs: [...thread.runs],+ attempts: [],+ nodes: [],+ subagents: [],+ providerSessions: [],+ providerThreads: [],+ providerTurns: [],+ runtimeRequests: [],+ messages: [],+ plans: [],+ turnItems: [...thread.items],+ checkpointScopes: [],+ checkpoints: [],+ contextHandoffs: [],+ contextTransfers: [],+ visibleTurnItems,+ updatedAt: AT,+ };+}++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });++// Keyed by thread id: a live thread subscription's queue, for pushing events to it.+const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStreamItem>>();+let threads: ReadonlyArray<FakeThread> = [];+let sequence = 1;++const subscribe = <A>(first: ReadonlyArray<A>, register?: (queue: Queue.Queue<A>) => () => void) =>+ Stream.unwrap(+ Effect.gen(function* () {+ const queue = yield* Queue.unbounded<A>();+ yield* Queue.offerAll(queue, first);+ if (register) {+ const unregister = register(queue);+ yield* Effect.addFinalizer(() => Effect.sync(unregister));+ }+ return Stream.fromQueue(queue);+ }),+ );++const handlers: Record<string, (input: never) => unknown> = {+ [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>+ subscribe<OrchestrationV2ShellStreamItem>([+ {+ kind: "snapshot",+ snapshot: {+ schemaVersion: 1,+ snapshotSequence: sequence,+ projects: [project],+ threads: threads.map(shellOf),+ archivedThreads: [],+ },+ },+ { kind: "synchronized" },+ ]),+ [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { readonly threadId: ThreadId }) => {+ const thread = threads.find((candidate) => candidate.id === input.threadId);+ if (!thread) return Stream.never;+ return subscribe<OrchestrationV2ThreadStreamItem>(+ [+ { kind: "snapshot", snapshotSequence: sequence, projection: projectionOf(thread) },+ { kind: "synchronized" },+ ],+ (queue) => {+ threadSubscribers.set(thread.id, queue);++ // A replaced subscription closes after its successor registers.+ return () => {+ if (threadSubscribers.get(thread.id) === queue) threadSubscribers.delete(thread.id);+ };+ },+ );+ },+ [WS_METHODS.subscribeServerConfig]: () =>+ subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig }]),+};++// Unanswered calls stay pending, like a server that has not replied yet.+const client = new Proxy(handlers, {+ get: (target, method: string) =>+ target[method] ??+ (() => {+ const rpc = WsRpcGroup.requests.get(method);+ return rpc && RpcSchema.isStreamSchema(rpc.successSchema) ? Stream.never : Effect.never;+ }),+});++const session: EnvironmentConnectionLease["session"] = {+ client: client as unknown as WsRpcProtocolClient,+ initialConfig: Effect.succeed(serverConfig),+ subscribeServerConfig: () =>+ subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig }]),+ ready: Effect.void,+ probe: Effect.void,+ closed: Effect.never,+};++/** Stands in for client-runtime's ConnectionDriver: every connection opens the session above. */+export const fakeDriver = {+ connect: (+ entry: ConnectionCatalogEntry,+ ): Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope> =>+ Effect.succeed({+ prepared: {+ environmentId: ENVIRONMENT_ID,+ label: descriptor.label,+ httpBaseUrl: window.location.origin,+ socketUrl: window.location.origin.replace(/^http/, "ws"),+ httpAuthorization: null,+ target: entry.target,+ },+ session,+ }),+ checkRoute: () => Effect.succeed<RouteCheck>("answered"),+ preflight: () => Effect.succeed(true),+};+export type FakeDriver = typeof fakeDriver;++const realFetch = globalThis.fetch;+const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)(+ Schema.decodeUnknownSync(ExecutionEnvironmentDescriptor)(descriptor),+);++/** Serves the environment's HTTP API and these threads until disposed. */+export function installFakeEnvironment(fixtures: ReadonlyArray<FakeThread>): Disposable {+ threads = fixtures;+ globalThis.fetch = async (input, init) => {+ const url = new URL(input instanceof Request ? input.url : String(input), window.location.href);+ if (url.origin !== window.location.origin) return realFetch(input, init);+ if (url.pathname === "/.well-known/t3/environment") return json(encodedDescriptor);+ if (url.pathname === "/api/auth/session") {+ return json({+ authenticated: true,+ auth,+ scopes: AuthStandardClientScopes,+ sessionMethod: "browser-session-cookie",+ expiresAt: "2099-01-01T00:00:00.000Z",+ });+ }+ // Snapshot endpoints fall back to the socket, which serves the same fixtures.+ if (/^\/(api|oauth|\.well-known)\//.test(url.pathname)) return json({}, 404);+ return realFetch(input, init);+ };+ return {+ [Symbol.dispose]: () => {+ globalThis.fetch = realFetch;+ threads = [];+ },+ };+}++type ThreadEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>["event"];++/** Whether the app holds a live subscription to the thread, so events reach it. */+export function isThreadSubscribed(threadId: ThreadId): boolean {+ return threadSubscribers.has(threadId);+}++/** Delivers one domain event, such as a run or turn-item update, to the thread's subscription. */+export async function emitThreadEvent(+ threadId: ThreadId,+ event: Pick<ThreadEvent, "type" | "payload">,+): Promise<void> {+ const queue = threadSubscribers.get(threadId);+ if (!queue) throw new Error(`No live subscription for ${threadId}`);+ sequence += 1;+ await Effect.runPromise(+ Queue.offer(queue, {+ kind: "event",+ sequence,+ event: { ...event, id: EventId.make(`event-${sequence}`), threadId, occurredAt: AT },+ } as OrchestrationV2ThreadStreamItem),+ );+}++export function runningRun(threadId: ThreadId, id: string, ordinal: number, userMessageId: string) {+ return {+ ...run(threadId, RunId.make(id), ordinal, userMessageId),+ status: "running" as const,+ completedAt: null,+ };+}++export { userItem };diff --git a/apps/web/test/renderCounter.ts b/apps/web/test/renderCounter.tsnew file mode 100644index 00000000000..06957306460--- /dev/null+++ b/apps/web/test/renderCounter.ts@@ -0,0 +1,108 @@+// Counts commits and component renders via the DevTools hook, so it loads before react-dom.+// Same walk as apps/mobile/src/features/development/render-counter.ts: bailed-out subtrees+// (child === alternate.child) keep stale PerformedWork flags and are skipped.++interface Fiber {+ readonly tag: number;+ readonly type: unknown;+ readonly flags: number;+ readonly alternate: Fiber | null;+ readonly child: Fiber | null;+ readonly sibling: Fiber | null;+}++export interface RenderReport {+ readonly commits: number;+ readonly renders: number;+ readonly components: Readonly<Record<string, number>>;+}++// Function, class, forwardRef, memo and simple memo components.+const COMPONENT_TAGS = new Set([0, 1, 11, 14, 15]);+const PERFORMED_WORK = 1;++function nameOf(fiber: Fiber): string | null {+ const type = fiber.type as {+ displayName?: string;+ name?: string;+ type?: { displayName?: string; name?: string };+ render?: { displayName?: string; name?: string };+ } | null;+ if (!type || (typeof type !== "object" && typeof type !== "function")) return null;+ const inner = type.type ?? type.render ?? type;+ const raw = type.displayName || inner.displayName || inner.name || "";+ return raw.replace(/^(Forget\(|Memo\()+|\)+$/g, "") || "Anonymous";+}++// The setup file and a test file can load this module as two instances. React reports to+// whichever hook existed when react-dom initialized, so both share one hook and one state.+const STATE = Symbol.for("t3code.renderCounter");+const state = ((globalThis as { [STATE]?: CounterState })[STATE] ??= {+ on: false,+ commits: 0,+ everCommitted: 0,+ counts: new Map(),+});++interface CounterState {+ on: boolean;+ commits: number;+ everCommitted: number;+ counts: Map<string, number>;+}++/** Adds the components that rendered under `fiber` and returns how many did. */+function visit(fiber: Fiber | null): number {+ let rendered = 0;+ for (let node = fiber; node; node = node.sibling) {+ const performed =+ COMPONENT_TAGS.has(node.tag) && (node.flags & PERFORMED_WORK) === PERFORMED_WORK;+ const name = performed ? nameOf(node) : null;+ if (name) {+ state.counts.set(name, (state.counts.get(name) ?? 0) + 1);+ rendered += 1;+ }+ const skipped = node.alternate !== null && node.child === node.alternate.child && !performed;+ if (node.child && !skipped) rendered += visit(node.child);+ }+ return rendered;+}++// React only reports commits to a hook that exists when react-dom initializes.+if (!("__REACT_DEVTOOLS_GLOBAL_HOOK__" in globalThis))+ Object.assign(globalThis, {+ __REACT_DEVTOOLS_GLOBAL_HOOK__: {+ supportsFiber: true,+ renderers: new Map(),+ inject: () => 1,+ checkDCE: () => {},+ onCommitFiberUnmount: () => {},+ onPostCommitFiberRoot: () => {},+ onCommitFiberRoot: (_id: unknown, root: { current: Fiber }) => {+ state.everCommitted += 1;+ // Commits that render no component (layout-only batches) vary with frame timing.+ if (state.on && visit(root.current.child) > 0) state.commits += 1;+ },+ },+ });++/** Every commit since load, counted or not, so a scenario can wait for the tree to go quiet. */+export function commitsSoFar(): number {+ return state.everCommitted;+}++export function startCounting(): void {+ state.commits = 0;+ state.counts = new Map();+ state.on = true;+}++export function stopCounting(): RenderReport {+ state.on = false;+ const sorted = [...state.counts].sort(([a, x], [b, y]) => y - x || a.localeCompare(b));+ return {+ commits: state.commits,+ renders: sorted.reduce((total, [, count]) => total + count, 0),+ components: Object.fromEntries(sorted),+ };+}diff --git a/apps/web/test/renderScenarios.renders.tsx b/apps/web/test/renderScenarios.renders.tsxnew file mode 100644index 00000000000..85d08c7a73d--- /dev/null+++ b/apps/web/test/renderScenarios.renders.tsx@@ -0,0 +1,283 @@+// Render scenarios for scripts/render-metrics.ts. Each one mounts real components on+// fixed fixtures, counts React commits and component renders while it drives them,+// and writes the counts through the writeRenderReport browser command. They mount the+// components ChatView composes, not ChatView, which needs a live environment connection.+import { EnvironmentId, MessageId } from "@t3tools/contracts";+import type { LegendListRef } from "@legendapp/list/react";+import { createRef, useRef, useState, type ComponentProps, type ReactNode } from "react";+import { expect, it, vi } from "vite-plus/test";+import { commands, userEvent } from "vite-plus/test/browser";++import "~/index.css";++import { MessagesTimeline } from "~/components/chat/MessagesTimeline";+import {+ ComposerPromptEditor,+ type ComposerPromptEditorHandle,+} from "~/components/ComposerPromptEditor";+import { commitsSoFar, startCounting, stopCounting } from "./renderCounter";+import { render } from "./render";++declare module "vite-plus/test/browser" {+ interface BrowserCommands {+ /** Defined in vite.config.ts for the renders project. */+ writeRenderReport: (scenario: string, json: string) => Promise<void>;+ }+}++vi.mock(import("~/state/query"), async (original) => ({+ ...(await original()),+ useEnvironmentQuery: (() => ({+ data: { tasks: [] },+ dataUpdatedAt: 0,+ error: null,+ failure: null,+ isPending: false,+ isSuccess: true,+ refresh: () => {},+ })) as never,+}));++const ENVIRONMENT_ID = EnvironmentId.make("environment-local");+const CREATED_AT = "2026-03-17T19:12:28.000Z";+const HISTORY_TURNS = 20;+const STREAM_DELTAS = 30;+const TYPED_TEXT = "fix the flaky tests!";++type TimelineProps = ComponentProps<typeof MessagesTimeline>;+type Entry = TimelineProps["timelineEntries"][number];++function message(id: string, role: "user" | "assistant", text: string, streaming = false): Entry {+ return {+ id: `entry-${id}`,+ kind: "message",+ createdAt: CREATED_AT,+ message: {+ id: MessageId.make(id),+ role,+ text,+ runId: null,+ createdAt: CREATED_AT,+ updatedAt: CREATED_AT,+ streaming,+ },+ } as Entry;+}++// A thread with history: user prompts and markdown answers with lists and inline code.+// No fenced code: Shiki highlights it asynchronously, and whether a block first renders+// its fallback varies run to run.+function history(thread: string): Entry[] {+ return Array.from({ length: HISTORY_TURNS }, (_, turn) => [+ message(`${thread}-user-${turn}`, "user", `${thread}: question ${turn} about the sidebar`),+ message(+ `${thread}-assistant-${turn}`,+ "assistant",+ `Answer ${turn} for ${thread}.\n\n- checked \`Sidebar.tsx\`\n- ran the tests\n\n` ++ "The width is now `clamp(next, MIN_WIDTH, MAX_WIDTH)`, so the layout no longer jumps.",+ ),+ ]).flat();+}++// Props that some trees under comparison have dropped. A JSX spread is not checked for+// excess properties, so this file type-checks on trees with and without them.+const versionedProps = { onManualNavigation: () => {} };++// One list handle per mounted timeline, as ChatView keeps one: the timeline compares the+// handle across renders, and a new one per render would skip its scroll-to-end and settle work.+function timelineFor() {+ const listRef = createRef<LegendListRef | null>();+ return (thread: string, entries: Entry[]) => (+ <MessagesTimeline+ timelineEntries={entries}+ isWorking={false}+ activeTurnInProgress={false}+ listRef={listRef}+ latestRun={null}+ turnDiffSummaries={[]}+ runs={[]}+ routeThreadKey={`environment-local:${thread}`}+ onOpenTurnDiff={() => {}}+ onOpenThread={() => {}}+ onForkFromRun={async () => {}}+ onRollbackCheckpoint={() => {}}+ supportsConversationRollback={false}+ onRevertToTurnCount={() => {}}+ isRevertingCheckpoint={false}+ onImageExpand={() => {}}+ activeThreadEnvironmentId={ENVIRONMENT_ID}+ markdownCwd={undefined}+ resolvedTheme="light"+ timestampFormat="locale"+ workspaceRoot={undefined}+ anchorMessageId={null}+ onAnchorReady={() => {}}+ onAnchorSizeChanged={() => {}}+ contentInsetEndAdjustment={0}+ emptyPlaceholderInset={0}+ liveFollowEnabled+ onIsAtEndChange={() => {}}+ {...versionedProps}+ />+ );+}++function sizedContainer() {+ const container = document.createElement("div");+ container.style.cssText = "height: 900px; width: 900px; display: flex; flex-direction: column;";+ return container;+}++// Legend List measures rows, and the minimap follows scroll, on later frames, and how+// much of that lands inside a window varies run to run. Every window opens and closes+// on a quiet tree: no commit across two consecutive checks.+async function quiet() {+ let seen = -1;+ await vi.waitFor(+ () => {+ const now = commitsSoFar();+ const settled = now === seen;+ seen = now;+ expect(settled).toBe(true);+ },+ { interval: 100, timeout: 10_000 },+ );+}++// Off the guest page the connection runtime retries a missing environment on timers, and+// its atom updates commit at varying times. On it, the runtime fails once and stays quiet.+function onGuestPage(): Disposable {+ const previous = `${window.location.pathname}${window.location.search}`;+ window.history.replaceState(window.history.state, "", "/guest?share=render-scenarios");+ return {+ [Symbol.dispose]: () => window.history.replaceState(window.history.state, "", previous),+ };+}++// A first mount loads lazy modules, web fonts and syntax highlighting at varying times.+// Each scenario mounts its tree once uncounted, so the counted run starts warm.+async function warmUp(ui: ReactNode, container?: HTMLElement) {+ await using screen = await render(ui, container ? { container } : {});+ await document.fonts.ready;+ await quiet();+ expect(screen.container.childElementCount).toBeGreaterThan(0);+}++async function report(scenario: string) {+ await quiet();+ const counts = stopCounting();+ await commands.writeRenderReport(scenario, JSON.stringify(counts));+}++it("mount-thread", async () => {+ using _guest = onGuestPage();+ const timeline = timelineFor();+ await warmUp(timelineFor()("thread-warm", history("thread-warm")), sizedContainer());+ startCounting();+ await using screen = await render(timeline("thread-a", history("thread-a")), {+ container: sizedContainer(),+ });+ await expect.element(screen.getByText(`Answer ${HISTORY_TURNS - 1} for thread-a.`)).toBeVisible();+ await report("mount-thread");+});++it("stream-assistant-turn", async () => {+ using _guest = onGuestPage();+ const timeline = timelineFor();+ const base = history("thread-a");+ const streamed = (text: string) => [+ ...base,+ message("live-user", "user", "Continue"),+ message("live-assistant", "assistant", text, true),+ ];+ await warmUp(timelineFor()("thread-warm", streamed("warm")), sizedContainer());+ await using screen = await render(timeline("thread-a", streamed("")), {+ container: sizedContainer(),+ });+ await expect.element(screen.getByText("Continue")).toBeVisible();+ await quiet();++ startCounting();+ let text = "";+ for (let delta = 0; delta < STREAM_DELTAS; delta++) {+ text += `word${delta} `;+ await screen.rerender(timeline("thread-a", streamed(text)));+ }+ await expect+ .element(screen.getByText(`word${STREAM_DELTAS - 1}`, { exact: false }))+ .toBeVisible();+ await report("stream-assistant-turn");+});++// Thread A to B and back, each switch counted until the tree is quiet again. Commits+// are not reported: the minimap's follow-up renders sometimes split across two frames,+// so the commit count varies by one while the renders stay identical.+it("switch-thread", async () => {+ using _guest = onGuestPage();+ const timeline = timelineFor();+ const a = history("thread-a");+ const b = history("thread-b");+ const lastAnswer = (thread: string) =>+ screen.getByText(`Answer ${HISTORY_TURNS - 1} for ${thread}.`);+ await warmUp(timelineFor()("thread-warm", a), sizedContainer());+ await using screen = await render(timeline("thread-a", a), { container: sizedContainer() });+ await expect.element(lastAnswer("thread-a")).toBeVisible();++ await quiet();+ startCounting();+ await screen.rerender(timeline("thread-b", b));+ await expect.element(lastAnswer("thread-b")).toBeVisible();+ await quiet();+ const toB = stopCounting();+ startCounting();+ await screen.rerender(timeline("thread-a", a));+ await expect.element(lastAnswer("thread-a")).toBeVisible();+ await quiet();+ const toA = stopCounting();++ const components = { ...toB.components };+ for (const [name, count] of Object.entries(toA.components)) {+ components[name] = (components[name] ?? 0) + count;+ }+ await commands.writeRenderReport(+ "switch-thread",+ JSON.stringify({+ commits: null,+ renders: toB.renders + toA.renders,+ components,+ }),+ );+});++function Composer() {+ const [prompt, setPrompt] = useState({ value: "", cursor: 0 });+ const editorRef = useRef<ComposerPromptEditorHandle>(null);+ return (+ <ComposerPromptEditor+ editorRef={editorRef}+ value={prompt.value}+ cursor={prompt.cursor}+ richTextEnabled+ contextRecords={new Map()}+ skills={[]}+ disabled={false}+ placeholder="Ask anything"+ onChange={(value, cursor) => setPrompt({ value, cursor })}+ onPaste={() => {}}+ />+ );+}++it("type-in-composer", async () => {+ using _guest = onGuestPage();+ await warmUp(<Composer />);+ await using screen = await render(<Composer />);+ const editor = screen.getByRole("textbox");+ await userEvent.click(editor);+ await quiet();++ startCounting();+ await userEvent.type(editor, TYPED_TEXT);+ await expect.element(editor).toHaveTextContent(TYPED_TEXT);+ await report("type-in-composer");+});diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex 577dda09c9b..38a4cccf5de 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -1,3 +1,5 @@+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Vite config runs before any Effect runtime.+import * as NodeFSP from "node:fs/promises";import * as NodeZlib from "node:zlib";import react from "@vitejs/plugin-react";@@ -122,6 +124,34 @@ const browserTestProject = {},} satisfies TestProjectInlineConfiguration;+// Render scenarios count React commits; they run only through scripts/render-metrics.ts,+// which reads the per-scenario reports this command writes.+const renderScenariosProject = {+ ...browserTestProject,+ test: {+ ...browserTestProject.test,+ name: "renders",+ include: ["test/*.renders.tsx"],+ // App scenarios mount the whole app per test, which outlasts 15s on a loaded machine.+ hookTimeout: 60_000,+ testTimeout: 60_000,+ setupFiles: ["./test/renderCounter.ts", ...browserTestProject.test.setupFiles],+ browser: {+ ...browserTestProject.test.browser,+ // Vitest names each instance in place, so a shared array would clash with the browser project.+ instances: [{ browser: "chromium" }],+ commands: {+ ...browserTestProject.test.browser.commands,+ writeRenderReport: async (_context, scenario: string, json: string) => {+ const directory = process.env.T3CODE_RENDER_REPORT_DIR;+ if (!directory) throw new Error("T3CODE_RENDER_REPORT_DIR is not set");+ await NodeFSP.writeFile(`${directory}/${scenario}.json`, json);+ },+ },+ },+ },+} satisfies TestProjectInlineConfiguration;+function resolveDevProxyTarget(backendPort: string | undefined,wsUrl: string | undefined,@@ -296,7 +326,11 @@ export default defineConfig(() => {sourcemap: buildSourcemap,},test: {- projects: [defineProject(unitTestProject), defineProject(browserTestProject)],+ projects: [+ defineProject(unitTestProject),+ defineProject(browserTestProject),+ defineProject(renderScenariosProject),+ ],},};});diff --git a/package.json b/package.jsonindex 80370d5cc8b..ef9a38f8d12 100644--- a/package.json+++ b/package.json@@ -27,6 +27,7 @@"typecheck": "vp run -r --cache --concurrency-limit 4 typecheck","tc": "vp run -r --cache --concurrency-limit 4 typecheck","check:changed": "node scripts/check-changed.ts",+ "report:renders": "node scripts/render-metrics.ts","lint": "vp lint --report-unused-disable-directives","knip": "knip --preprocessor ./scripts/knip-schemas.ts","knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-grok --workspace packages/source-control-core --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints",diff --git a/scripts/render-metrics.test.ts b/scripts/render-metrics.test.tsnew file mode 100644index 00000000000..919ba77e5c3--- /dev/null+++ b/scripts/render-metrics.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vite-plus/test";++import { nondeterministic, renderComparison } from "./render-metrics.ts";++describe("nondeterministic", () => {+ it("names only the scenarios whose counts differ between runs", () => {+ const stable = { commits: 2, renders: 10, components: { Row: 10 } };+ expect(+ nondeterministic([+ { mount: stable, type: { commits: 1, renders: 4, components: { Editor: 4 } } },+ { mount: stable, type: { commits: 1, renders: 5, components: { Editor: 5 } } },+ ]),+ ).toEqual(["type"]);+ });+});++describe("renderComparison", () => {+ it("prints per-scenario deltas and the components that moved most", () => {+ const output = renderComparison(+ { stream: { commits: 40, renders: 400, components: { Row: 300, Header: 100 } } },+ { stream: { commits: 30, renders: 250, components: { Row: 150, Header: 100 } } },+ );+ expect(output).toContain("| stream | 40 → 30 (-10, -25%) | 400 → 250 (-150, -37%) |");+ expect(output).toContain("| `Row` | 300 → 150 (-150, -50%) |");+ expect(output).not.toContain("`Header`");+ });+});diff --git a/scripts/render-metrics.ts b/scripts/render-metrics.tsnew file mode 100644index 00000000000..a49154ff5c7--- /dev/null+++ b/scripts/render-metrics.ts@@ -0,0 +1,156 @@+// @effect-diagnostics nodeBuiltinImport:off globalConsole:off - a synchronous wrapper around one vitest project.+import * as NodeChildProcess from "node:child_process";+import * as NodeFS from "node:fs";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";++const HELP = `Usage:+ node scripts/render-metrics.ts run [--out <file>] [--runs <n>]+ node scripts/render-metrics.ts compare <before.json> <after.json> [--top <n>]++run Runs the web render scenarios (apps/web/test/renderScenarios.renders.tsx,+ vitest project "renders") on this checkout and writes one JSON object of+ { scenario: { commits, renders, components } }. With --runs above 1 (default 3)+ it fails unless every run produced identical counts.+compare Prints a markdown table of commit and render deltas per scenario, plus the+ components whose counts changed most (default top 10).++commits are React commits that rendered at least one component (null where frame+timing splits them); renders are function and class component renders, counted from the+fibers React worked on. Every scenario waits for the tree to go quiet before and after+its counted window, so layout follow-ups are included.++Comparing two refs needs both checkouts, since the scenarios run each tree's code:+ node scripts/render-metrics.ts run --out ../main-renders.json # on main+ node scripts/render-metrics.ts run --out ../branch-renders.json # on the branch+ node scripts/render-metrics.ts compare ../main-renders.json ../branch-renders.json+A second checkout comes from \`git worktree add ../<name> main\`; copy the harness files+in if that tree predates them.`;++export interface ScenarioReport {+ /** null where a scenario's commit count depends on frame timing. */+ readonly commits: number | null;+ readonly renders: number;+ readonly components: Readonly<Record<string, number>>;+}+export type RenderMetrics = Readonly<Record<string, ScenarioReport>>;++const root = NodePath.resolve(import.meta.dirname, "..");++function runOnce(): RenderMetrics {+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.homedir(), ".cache", "t3-renders-"));+ try {+ const result = NodeChildProcess.spawnSync("vp", ["test", "run", "--project", "renders"], {+ cwd: NodePath.join(root, "apps/web"),+ env: { ...process.env, T3CODE_RENDER_REPORT_DIR: directory },+ stdio: ["ignore", "inherit", "inherit"],+ });+ if (result.status !== 0) throw new Error(`render scenarios failed (exit ${result.status})`);+ const files = NodeFS.readdirSync(directory)+ .filter((file) => file.endsWith(".json"))+ .toSorted();+ return Object.fromEntries(+ files.map((file) => [+ file.replace(/\.json$/, ""),+ JSON.parse(NodeFS.readFileSync(NodePath.join(directory, file), "utf8")) as ScenarioReport,+ ]),+ );+ } finally {+ NodeFS.rmSync(directory, { recursive: true, force: true });+ }+}++/** Scenarios whose counts differ between runs, by name. */+export function nondeterministic(runs: ReadonlyArray<RenderMetrics>): string[] {+ const [first, ...rest] = runs;+ if (!first) return [];+ return Object.keys(first).filter((scenario) =>+ rest.some((run) => JSON.stringify(run[scenario]) !== JSON.stringify(first[scenario])),+ );+}++const signed = (value: number) => (value > 0 ? `+${value}` : `${value}`);+const change = (before: number | null, after: number | null) =>+ before === null || after === null+ ? "n/a"+ : before === after+ ? `${after}`+ : `${before} → ${after} (${signed(after - before)}${before ? `, ${signed(Math.round(((after - before) / before) * 100))}%` : ""})`;++export function renderComparison(before: RenderMetrics, after: RenderMetrics, top = 10): string {+ const scenarios = [...new Set([...Object.keys(before), ...Object.keys(after)])].toSorted();+ const lines = [+ "### Render scenarios",+ "",+ "| scenario | commits | renders |",+ "| :-- | --: | --: |",+ ];+ const empty: ScenarioReport = { commits: 0, renders: 0, components: {} };+ for (const scenario of scenarios) {+ const a = before[scenario] ?? empty;+ const b = after[scenario] ?? empty;+ lines.push(+ `| ${scenario} | ${change(a.commits, b.commits)} | ${change(a.renders, b.renders)} |`,+ );+ }+ for (const scenario of scenarios) {+ const a = before[scenario]?.components ?? {};+ const b = after[scenario]?.components ?? {};+ const moved = [...new Set([...Object.keys(a), ...Object.keys(b)])]+ .map((name) => [name, a[name] ?? 0, b[name] ?? 0] as const)+ .filter(([, x, y]) => x !== y)+ .sort(([n, x, y], [m, p, q]) => Math.abs(q - p) - Math.abs(y - x) || n.localeCompare(m))+ .slice(0, top);+ if (moved.length === 0) continue;+ lines.push("", `<details><summary>${scenario}: components that changed most</summary>`, "");+ lines.push("| component | renders |", "| :-- | --: |");+ for (const [name, x, y] of moved) lines.push(`| \`${name}\` | ${change(x, y)} |`);+ lines.push("", "</details>");+ }+ return lines.join("\n");+}++function option(args: ReadonlyArray<string>, name: string): string | undefined {+ const index = args.indexOf(name);+ return index === -1 ? undefined : args[index + 1];+}++if (import.meta.main) {+ const [command, ...args] = process.argv.slice(2);+ if (command === "run") {+ const runs = Number(option(args, "--runs") ?? 3);+ const results = Array.from({ length: runs }, runOnce);+ const unstable = nondeterministic(results);+ if (unstable.length) {+ for (const scenario of unstable) {+ const counts = results.map((run) => `${run[scenario]?.commits}/${run[scenario]?.renders}`);+ console.error(`${scenario} differed between runs (commits/renders): ${counts.join(", ")}`);+ const first = results[0]?.[scenario]?.components ?? {};+ for (const [index, run] of results.entries()) {+ const other = run[scenario]?.components ?? {};+ const names = [...new Set([...Object.keys(first), ...Object.keys(other)])];+ const moved = names.filter((name) => first[name] !== other[name]);+ if (moved.length) {+ const detail = moved.map((name) => `${name} ${first[name] ?? 0}→${other[name] ?? 0}`);+ console.error(` run ${index + 1} vs run 1: ${detail.join(", ")}`);+ }+ }+ }+ process.exitCode = 1;+ } else {+ const json = JSON.stringify(results[0], null, 2);+ const out = option(args, "--out");+ if (out) NodeFS.writeFileSync(out, json + "\n");+ else console.log(json);+ console.error(`${runs} run(s) produced identical counts.`);+ }+ } else if (command === "compare" && args[0] && args[1]) {+ const read = (path: string) => JSON.parse(NodeFS.readFileSync(path, "utf8")) as RenderMetrics;+ console.log(+ renderComparison(read(args[0]), read(args[1]), Number(option(args, "--top") ?? 10)),+ );+ } else {+ console.log(HELP);+ if (command !== "--help" && command !== "-h" && command !== undefined) process.exitCode = 1;+ }+}