TypeScript
test(mobile): measure renders on a device (#21001)
Julius Marmingeea97e8ba3146
diff --git a/apps/mobile/index.ts b/apps/mobile/index.tsindex 9b887f58a28..a91c318c3c0 100644--- a/apps/mobile/index.ts+++ b/apps/mobile/index.ts@@ -1,3 +1,5 @@+// Must stay first: the render counter wraps the DevTools hook before any React commit.+import "./src/features/development/render-counter-entry";import { registerRootComponent } from "expo";import "react-native-gesture-handler";import { LogBox } from "react-native";diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex e0b9c0e4136..ed8384acf49 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -41,6 +41,7 @@"config:prod": "APP_VARIANT=production expo config","profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review","sync:pierre-icons": "node scripts/sync-pierre-file-icons.mjs",+ "measure-renders": "node scripts/measure-renders.mts","generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate-uniwind-themes.mts","test": "vp test run --config ../../vite.config.ts --dir .","typecheck": "tsc-rs --noEmit"@@ -141,6 +142,7 @@},"devDependencies": {"@babel/core": "^7.29.7",+ "@effect/platform-node": "catalog:","@effect/vitest": "catalog:","@pierre/trees": "1.0.0-beta.6","@types/mdast": "^4.0.4",diff --git a/apps/mobile/scripts/measure-renders.mts b/apps/mobile/scripts/measure-renders.mtsnew file mode 100644index 00000000000..7ca1a8b82d7--- /dev/null+++ b/apps/mobile/scripts/measure-renders.mts@@ -0,0 +1,414 @@+// Measures React renders in a running T3 Code Dev client. See+// docs/internals/mobile-development.md#measuring-renders.+import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";+import * as NodeServices from "@effect/platform-node/NodeServices";+import * as NodeSocket from "@effect/platform-node/NodeSocket";+import {+ CommandId,+ EnvironmentId,+ ExecutionEnvironmentDescriptor,+ ORCHESTRATION_PROTOCOL_HEADER,+ ORCHESTRATION_PROTOCOL_VERSION,+ OrchestrationV2ShellSnapshot,+ ProjectId,+ ProviderInstanceId,+ ThreadId,+ WsRpcGroup,+ type OrchestrationV2ThreadProjection,+} from "@t3tools/contracts";+import * as Console from "effect/Console";+import * as Crypto from "effect/Crypto";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";+import * as Stream from "effect/Stream";+import { Command, Flag } from "effect/cli";+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";+import { RpcClient, RpcSerialization } from "effect/rpc";+import { Socket } from "effect/socket";++const RenderReport = Schema.Struct({+ commits: Schema.Number,+ totalRenders: Schema.Number,+ components: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })),+ causes: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })),+});+type RenderReport = typeof RenderReport.Type;+const decodeReport = Schema.decodeUnknownEffect(Schema.fromJsonString(RenderReport));+const InspectorTargets = Schema.Array(+ Schema.Struct({ appId: Schema.String, webSocketDebuggerUrl: Schema.String }),+);+const CdpReply = Schema.Struct({+ id: Schema.Number,+ result: Schema.optional(+ Schema.Struct({+ result: Schema.optional(Schema.Struct({ value: Schema.optional(Schema.Unknown) })),+ exceptionDetails: Schema.optional(Schema.Unknown),+ }),+ ),+});+const decodeCdpReply = Schema.decodeUnknownOption(Schema.fromJsonString(CdpReply));+const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));++class MeasureError extends Schema.TaggedError<MeasureError>()("MeasureError", {+ message: Schema.String,+}) {}++const STREAM_PROMPT =+ "Think it through step by step, then write a 3000-word essay on the history of typesetting in plain paragraphs with a few headings. Do not use any tools.";++interface Options {+ readonly server: string;+ readonly token: string;+ readonly metro: string;+ readonly scheme: string;+ readonly runs: number;+ readonly windowSeconds: number;+ readonly provider: string;+ readonly model: string;+ readonly projectRoot: string;+}++const uuid = Effect.flatMap(Crypto.Crypto, (crypto) => crypto.randomUUIDv4());++const median = (values: ReadonlyArray<number>) => {+ const sorted = [...values].sort((a, b) => a - b);+ const middle = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;+};++/** One Hermes inspector session, reached through Metro's inspector proxy. */+const connectInspector = Effect.fn("measure.connectInspector")(function* (metro: string) {+ const http = yield* HttpClient.HttpClient;+ const targets = yield* http+ .get(`${metro}/json/list`)+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(InspectorTargets)));+ const target = targets.find((entry) => entry.appId.startsWith("com.t3tools.t3code"));+ if (!target)+ return yield* new MeasureError({ message: `No T3 Code app is attached to Metro at ${metro}.` });+ // Expo terminates inspector sockets whose Origin differs from the URL Metro+ // advertises (the LAN address with `--lan`), so pass that URL as `--metro`.+ const socket = yield* Socket.makeWebSocket(target.webSocketDebuggerUrl, {+ headers: { origin: new URL(metro).origin },+ openTimeout: "10 seconds",+ });+ const writer = yield* socket.writer;+ const reader = yield* socket.reader;+ let nextId = 0;+ return Effect.fn("measure.evaluate")(function* (expression: string) {+ const id = ++nextId;+ yield* writer.write(+ encodeJson({ id, method: "Runtime.evaluate", params: { expression, returnByValue: true } }),+ );+ while (true) {+ for (const frame of yield* reader.pull) {+ const text = typeof frame === "string" ? frame : new TextDecoder().decode(frame);+ const reply = decodeCdpReply(text);+ if (Option.isNone(reply) || reply.value.id !== id) continue;+ if (reply.value.result?.exceptionDetails)+ return yield* new MeasureError({+ message: `Evaluation failed: ${encodeJson(reply.value.result.exceptionDetails)}`,+ });+ return reply.value.result?.result?.value;+ }+ }+ });+});++const connectServer = Effect.fn("measure.connectServer")(function* (options: Options) {+ const http = (yield* HttpClient.HttpClient).pipe(+ HttpClient.mapRequest((request) =>+ request.pipe(+ HttpClientRequest.bearerToken(options.token),+ HttpClientRequest.setHeader(+ ORCHESTRATION_PROTOCOL_HEADER,+ String(ORCHESTRATION_PROTOCOL_VERSION),+ ),+ ),+ ),+ HttpClient.filterStatusOk,+ );+ const descriptor = yield* http+ .get(`${options.server}/.well-known/t3/environment`)+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)));+ const shell = yield* http+ .get(`${options.server}/api/orchestration/shell`)+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot)));+ let projectId = shell.projects.find(+ (project) => project.workspaceRoot === options.projectRoot,+ )?.id;+ // A project record outlives its folder, and turns fail without it.+ yield* (yield* FileSystem.FileSystem).makeDirectory(options.projectRoot, { recursive: true });+ if (!projectId) {+ projectId = ProjectId.make(yield* uuid);+ yield* http.execute(+ HttpClientRequest.post(`${options.server}/api/projects/mutate`).pipe(+ HttpClientRequest.bodyJsonUnsafe({+ type: "project.create",+ commandId: yield* uuid,+ projectId,+ title: "Render measurement",+ workspaceRoot: options.projectRoot,+ }),+ ),+ );+ }+ const ticket = yield* http+ .execute(HttpClientRequest.post(`${options.server}/api/auth/websocket-ticket`))+ .pipe(+ Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),+ );+ // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.+ const protocol = yield* Layer.build(+ RpcClient.layerProtocolSocket().pipe(+ Layer.provide(+ Socket.layerWebSocket(+ `${options.server.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket.ticket)}`,+ ),+ ),+ Layer.provide(RpcSerialization.layerJson),+ ),+ );+ const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));+ return { client, environmentId: EnvironmentId.make(descriptor.environmentId), projectId };+});++// Streaming lands in turn items. Some providers stream reasoning but deliver the+// reply text in one piece, so any streaming text item counts as mid-stream.+const streamingItem = (projection: OrchestrationV2ThreadProjection) =>+ projection.turnItems.find(+ (item) => (item.type === "assistant_message" || item.type === "reasoning") && item.streaming,+ );++/** A thread streams a long reply: the open one, or with `route` a thread the app never shows. */+const measureStreamReply = Effect.fn("measure.streamReply")(function* (+ options: Options,+ run: number,+ route: Option.Option<string>,+) {+ if (Option.isSome(route)) yield* reloadAndOpen(options, route.value);+ const evaluate = yield* connectInspector(options.metro);+ const { client, environmentId, projectId } = yield* connectServer(options);+ const threadId = ThreadId.make(yield* uuid);+ yield* client["orchestration.launchThread"]({+ commandId: CommandId.make(yield* uuid),+ threadId,+ projectId,+ title: `Render measurement ${run}`,+ modelSelection: {+ instanceId: ProviderInstanceId.make(options.provider),+ model: options.model,+ },+ // The prompt needs no tools; approval-required keeps a stray call from acting.+ runtimeMode: "approval-required",+ interactionMode: "default",+ workspaceStrategy: { type: "root" },+ initialMessage: { text: STREAM_PROMPT, attachments: [] },+ });+ // A failed or interrupted window must not leave a provider turn running.+ yield* Effect.addFinalizer(() =>+ Effect.gen(function* () {+ const after = yield* client["orchestration.getThreadProjection"]({ threadId });+ const activeRun = after.runs.find(+ (entry) => !["completed", "failed", "interrupted", "cancelled"].includes(entry.status),+ );+ if (!activeRun) return;+ yield* client["orchestration.dispatchCommand"]({+ type: "run.interrupt",+ commandId: CommandId.make(yield* uuid),+ threadId,+ runId: activeRun.id,+ });+ }).pipe(Effect.ignore),+ );+ if (Option.isNone(route))+ yield* evaluate(+ `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://threads/${environmentId}/${threadId}`)})`,+ );+ const projectionOf = (item: { kind: string; projection?: OrchestrationV2ThreadProjection }) =>+ item.kind === "snapshot" && item.projection+ ? Effect.succeed(item.projection)+ : client["orchestration.getThreadProjection"]({ threadId });+ const streaming = yield* client["orchestration.subscribeThread"]({ threadId }).pipe(+ Stream.mapEffect(projectionOf),+ Stream.filter((projection) => streamingItem(projection) !== undefined),+ Stream.runHead,+ Effect.timeout("90 seconds"),+ );+ if (Option.isNone(streaming))+ return yield* new MeasureError({ message: `Run ${run}: the reply never started streaming.` });+ yield* evaluate("__t3RenderCounterStart()");+ yield* Effect.sleep(`${options.windowSeconds} seconds`);+ const report = yield* decodeReport(yield* evaluate("JSON.stringify(__t3RenderCounterStop())"));+ // React commits on every streamed delta, so an empty window means the app is not on the thread.+ // A thread streaming out of view may rightly commit nothing.+ if (report.commits === 0 && Option.isNone(route))+ return yield* new MeasureError({+ message: `Run ${run}: no React commits in the window. Check the device for a red box.`,+ });+ const after = yield* client["orchestration.getThreadProjection"]({ threadId });+ return { report, stillStreaming: streamingItem(after) !== undefined };+}, Effect.scoped);++const appLink = (options: Options, route: string) =>+ `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://${route.replace(/^\//, "")}`)})`;++/** Reloads onto Home, then opens `route` and lets it settle; `/` stays on Home. */+const reloadAndOpen = Effect.fn("measure.reloadAndOpen")(function* (+ options: Options,+ route: string,+) {+ // A link to an already-open screen only refocuses it, so each run starts from a reload.+ yield* Effect.scoped(+ Effect.flatMap(connectInspector(options.metro), (evaluate) =>+ evaluate("__t3RenderCounterReload()"),+ ),+ );+ yield* Effect.sleep("15 seconds");+ if (route === "/" || route === "") return;+ yield* Effect.scoped(+ Effect.flatMap(connectInspector(options.metro), (evaluate) =>+ evaluate(appLink(options, route)),+ ),+ );+ yield* Effect.sleep("5 seconds");+});++/** Opens a screen from a freshly loaded Home and records its mount and data settling. */+const measureRouteOpen = Effect.fn("measure.routeOpen")(function* (+ options: Options,+ route: string,+ run: number,+) {+ yield* Effect.scoped(+ Effect.flatMap(connectInspector(options.metro), (evaluate) =>+ evaluate("__t3RenderCounterReload()"),+ ),+ );+ yield* Effect.sleep("15 seconds");+ const evaluate = yield* connectInspector(options.metro);+ yield* evaluate("__t3RenderCounterStart()");+ yield* evaluate(appLink(options, route));+ yield* Effect.sleep(`${options.windowSeconds} seconds`);+ const report = yield* decodeReport(yield* evaluate("JSON.stringify(__t3RenderCounterStop())"));+ if (report.commits === 0)+ return yield* new MeasureError({+ message: `Run ${run}: no React commits in the window. Check that ${route} is a valid app path.`,+ });+ return { report, stillStreaming: undefined };+}, Effect.scoped);++const medianTable = (+ title: string,+ reports: ReadonlyArray<RenderReport>,+ pick: (report: RenderReport) => RenderReport["causes"],+ limit: number,+) => {+ const keys = new Set(reports.flatMap((report) => pick(report).map((entry) => entry.key)));+ const rows = [...keys]+ .map((key) => ({+ key,+ count: median(reports.map((report) => pick(report).find((e) => e.key === key)?.count ?? 0)),+ }))+ .filter((row) => row.count > 0)+ .sort((a, b) => b.count - a.count)+ .slice(0, limit);+ return [+ `| ${title} | Renders |`,+ "|---|---:|",+ ...rows.map((r) => `| \`${r.key}\` | ${r.count} |`),+ ];+};++const formatTable = (reports: ReadonlyArray<RenderReport>) => {+ const totals = (pick: (report: RenderReport) => number) => median(reports.map(pick));+ return [+ `Median of ${reports.length} runs.`,+ "",+ "| | |",+ "|---|---:|",+ `| renders | ${totals((r) => r.totalRenders)} |`,+ `| commits | ${totals((r) => r.commits)} |`,+ // Provider pace sets how many commits land in the window; per-commit cost compares across runs.+ `| renders per commit | ${totals((r) => Math.round(r.totalRenders / Math.max(r.commits, 1)))} |`,+ "",+ ...medianTable("Component", reports, (r) => r.components, 20),+ "",+ ...medianTable("Cause", reports, (r) => r.causes, 15),+ ].join("\n");+};++const command = Command.make(+ "measure-renders",+ {+ server: Flag.String("server").pipe(+ Flag.withDescription("T3 server origin the app is paired with."),+ Flag.withDefault(""),+ ),+ token: Flag.String("token").pipe(+ Flag.withDescription("Bearer token from `t3 auth session issue --token-only`."),+ Flag.withDefault(""),+ ),+ route: Flag.String("route").pipe(+ Flag.withDescription(+ "App path to open and measure. With --server, the path stays open while a new thread streams.",+ ),+ Flag.optional,+ ),+ metro: Flag.String("metro").pipe(Flag.withDefault("http://127.0.0.1:8081")),+ scheme: Flag.String("scheme").pipe(Flag.withDefault("t3code-dev")),+ runs: Flag.Int("runs").pipe(Flag.withDefault(3)),+ window: Flag.Int("window").pipe(+ Flag.withDescription("Seconds to record; defaults to 12 for a reply and 6 for --route."),+ Flag.optional,+ ),+ provider: Flag.String("provider").pipe(Flag.withDefault("claudeAgent")),+ model: Flag.String("model").pipe(Flag.withDefault("claude-haiku-5-5")),+ projectRoot: Flag.String("project-root").pipe(+ Flag.withDescription("Scratch directory for the measurement project; created if missing."),+ Flag.withDefault(""),+ ),+ },+ Effect.fn("measure.main")(function* (flags) {+ const route = flags.route;+ const options: Options = {+ ...flags,+ windowSeconds: Option.getOrElse(flags.window, () =>+ Option.isSome(route) && !flags.server ? 6 : 12,+ ),+ };+ const streams = Option.isNone(route) || flags.server !== "";+ if (streams && (!flags.server || !flags.token || !flags.projectRoot))+ return yield* new MeasureError({+ message: "Streaming a reply needs --server, --token and --project-root.",+ });+ const reports: RenderReport[] = [];+ for (let run = 1; run <= flags.runs; run++) {+ const { report, stillStreaming } =+ Option.isSome(route) && !streams+ ? yield* measureRouteOpen(options, route.value, run)+ : yield* measureStreamReply(options, run, route);+ yield* Console.error(+ `run ${run}: ${report.totalRenders} renders in ${report.commits} commits${stillStreaming === false ? " (warning: streaming ended inside the window)" : ""}`,+ );+ reports.push(report);+ // Let the interrupted turn settle so the next run starts from a quiet app.+ yield* Effect.sleep("3 seconds");+ }+ yield* Console.log(formatTable(reports));+ }),+);++Command.run(command, { version: "0.0.0" }).pipe(+ Effect.provide(+ Layer.mergeAll(+ NodeServices.layer,+ NodeHttpClient.layerUndici,+ NodeSocket.layerWebSocketConstructorWS,+ ),+ ),+ NodeRuntime.runMain,+);diff --git a/apps/mobile/src/features/development/render-counter-entry.ts b/apps/mobile/src/features/development/render-counter-entry.tsnew file mode 100644index 00000000000..b7e901cd534--- /dev/null+++ b/apps/mobile/src/features/development/render-counter-entry.ts@@ -0,0 +1,5 @@+// Production builds fold this condition to false before Metro collects+// dependencies, so the counter module never enters a release bundle.+if (__DEV__ && process.env.EXPO_PUBLIC_T3_RENDER_COUNTER === "1") {+ require("./render-counter");+}diff --git a/apps/mobile/src/features/development/render-counter.ts b/apps/mobile/src/features/development/render-counter.tsnew file mode 100644index 00000000000..b6cfa4f985f--- /dev/null+++ b/apps/mobile/src/features/development/render-counter.ts@@ -0,0 +1,177 @@+// Dev-only render counter driven by `scripts/measure-renders.mts` through the+// Hermes inspector. It wraps the DevTools hook's commit callback, so it must load+// before React renders anything; see `render-counter-entry.ts`.+//+// The fiber walk matches the web counter used for React Compiler work: a+// bailed-out subtree keeps `child === alternate.child`, so it is not descended,+// because fibers there keep stale flags and alternates from older commits.+// PerformedWork (1) is cleared whenever React clones a fiber, so a reached fiber+// with it set rendered in this commit.++interface Fiber {+ readonly tag: number;+ readonly type: unknown;+ readonly flags: number;+ readonly alternate: Fiber | null;+ readonly child: Fiber | null;+ readonly sibling: Fiber | null;+ readonly memoizedProps: Record<string, unknown> | null;+ readonly memoizedState: HookSlot | null;+}+interface HookSlot {+ readonly memoizedState: unknown;+ /** Non-null only for useState and useReducer, the hooks that can schedule a render. */+ readonly queue: unknown;+ readonly next: HookSlot | null;+}+interface DevToolsHook {+ onCommitFiberRoot?: (id: unknown, root: { current: Fiber }, ...rest: unknown[]) => unknown;+ __t3RenderCounter?: true;+}+interface RenderCounterState {+ on: boolean;+ commits: number;+ counts: Map<string, number>;+ causes: Map<string, number>;+}+export interface RenderCounterReport {+ readonly commits: number;+ readonly totalRenders: number;+ readonly components: ReadonlyArray<{ key: string; count: number }>;+ readonly causes: ReadonlyArray<{ key: string; count: number }>;+}++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 === "string") return null;+ const inner = type.type ?? type.render ?? type;+ const raw = type.displayName || inner.displayName || inner.name || "";+ return raw.replace(/^(Forget\(|Memo\()+|\)+$/g, "") || null;+}++function isEffect(value: unknown): boolean {+ return (+ typeof value === "object" &&+ value !== null &&+ "create" in value &&+ "deps" in value &&+ "tag" in value+ );+}++function changedStateSlot(alternate: Fiber, node: Fiber): number {+ let a = alternate.memoizedState;+ let b = node.memoizedState;+ for (let index = 0; a && b && index < 800; index++) {+ const before = a.memoizedState;+ const after = b.memoizedState;+ // Memo, callback and ref slots change because something upstream did; only a+ // state update is a cause of its own.+ if (b.queue !== null && !isEffect(after) && !Object.is(before, after)) return index;+ a = a.next;+ b = b.next;+ }+ return -1;+}++function causeOf(node: Fiber, parentName: string): string {+ const alternate = node.alternate;+ if (!alternate) return "mount";+ const slot = changedStateSlot(alternate, node);+ if (slot >= 0) return `state#${slot}`;+ if (alternate.memoizedProps !== node.memoizedProps) {+ const props = node.memoizedProps ?? {};+ const keys = Object.keys(props).filter(+ (key) => !Object.is(alternate.memoizedProps?.[key], props[key]),+ );+ return keys.length ? `props:${keys.slice(0, 4).join(",")}` : `parent-same-props<-${parentName}`;+ }+ return "context";+}++function increment(map: Map<string, number>, key: string) {+ map.set(key, (map.get(key) ?? 0) + 1);+}++function install(state: RenderCounterState) {+ const hook = (globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook })+ .__REACT_DEVTOOLS_GLOBAL_HOOK__;+ if (!hook || typeof hook.onCommitFiberRoot !== "function") {+ setTimeout(() => install(state), 50);+ return;+ }+ if (hook.__t3RenderCounter) return;+ hook.__t3RenderCounter = true;+ const original = hook.onCommitFiberRoot.bind(hook);++ const visit = (fiber: Fiber | null, parentName: string) => {+ let node = fiber;+ while (node) {+ const alternate = node.alternate;+ const name = COMPONENT_TAGS.has(node.tag) ? nameOf(node) : null;+ const rendered = name !== null && (node.flags & PERFORMED_WORK) === PERFORMED_WORK;+ if (rendered) {+ increment(state.counts, name);+ increment(state.causes, `${name} ${causeOf(node, parentName)}`);+ }+ const skipped = alternate !== null && node.child === alternate.child && !rendered;+ if (node.child && !skipped) visit(node.child, rendered ? name : parentName);+ node = node.sibling;+ }+ };++ hook.onCommitFiberRoot = (id, root, ...rest) => {+ if (state.on) {+ state.commits += 1;+ visit(root.current.child, "root");+ }+ return original(id, root, ...rest);+ };+}++const state: RenderCounterState = { on: false, commits: 0, counts: new Map(), causes: new Map() };++const sorted = (map: Map<string, number>) =>+ [...map].map(([key, count]) => ({ key, count })).sort((a, b) => b.count - a.count);++install(state);++Object.assign(globalThis, {+ /** Routes an app link in-process, so drivers need no simctl or adb access. */+ __t3RenderCounterOpen(url: string) {+ const { Linking } = require("react-native") as typeof import("react-native");+ void Linking.openURL(url);+ return true;+ },+ /** Restarts the JS app on Home; deferred so the inspector call can reply first. */+ __t3RenderCounterReload() {+ const { DevSettings } = require("react-native") as typeof import("react-native");+ setTimeout(() => DevSettings.reload(), 100);+ return true;+ },+ __t3RenderCounterStart() {+ state.commits = 0;+ state.counts = new Map();+ state.causes = new Map();+ state.on = true;+ return true;+ },+ __t3RenderCounterStop(): RenderCounterReport {+ state.on = false;+ const components = sorted(state.counts);+ return {+ commits: state.commits,+ totalRenders: components.reduce((total, entry) => total + entry.count, 0),+ components,+ causes: sorted(state.causes),+ };+ },+});diff --git a/docs/internals/mobile-development.md b/docs/internals/mobile-development.mdindex 19ff413166a..1b29cf37012 100644--- a/docs/internals/mobile-development.md+++ b/docs/internals/mobile-development.md@@ -35,6 +35,37 @@ so an edit to a module's TypeScript is invisible to a running dev client until`vp i` re-syncs it, while Gradle and CocoaPods compile the worktree directorydirectly. A JavaScript change that "has no effect" on device is usually this.+## Measuring renders++[`render-counter.ts`](../../apps/mobile/src/features/development/render-counter.ts) counts the+components React rendered in each commit and why: a changed state slot, changed props, or+context. It wraps the DevTools hook from the first import in `index.ts` and loads only when+`__DEV__` and `EXPO_PUBLIC_T3_RENDER_COUNTER=1`, so release bundles never contain it. The walk+skips subtrees React bailed out of. A probe that checks `flags & 1` on every fiber reports+renders that never happened, because bailed-out fibers keep flags from older commits.++[`measure-renders.mts`](../../apps/mobile/scripts/measure-renders.mts) drives a measurement from+outside the app. It evaluates the counter's globals through Metro's Hermes inspector proxy, which+works the same for iOS simulators and Android emulators and needs no taps, `simctl`, or `adb`. It+starts a real provider turn through the server, opens the thread with an app link, records a window+mid-stream, and prints the median renders, commits, top components and top causes. Expo drops inspector sockets whose `Origin` is not the URL Metro advertises, so+pass that URL (the LAN address with `--lan`) as `--metro`.++```bash+EXPO_PUBLIC_T3_RENDER_COUNTER=1 vp run dev:client # in apps/mobile, then pair the app+node apps/server/src/bin.ts auth session issue --base-dir <base-dir> --token-only+node apps/mobile/scripts/measure-renders.mts --server <server-origin> --token <token> \+ --metro http://<metro-lan-host>:8081 --project-root <scratch-dir>+```++`--route /settings/usage` instead reloads the app, opens that path from Home and records a 6 s window over+mount and data settling, with no provider turn and no `--server`, `--token` or `--project-root`.+With `--server` as well, the app reloads, opens that path (`/` stays on Home) and the reply streams in a+new thread the app never shows, which measures what streaming elsewhere costs the screen in front.++Compare before and after on the same base, on the same device, with the median of three runs.+Provider output varies run to run, so a single run or a comparison across bases is noise.+## React CompilerMetro runs the compiler only because `experiments.reactCompiler` is set in `app.config.ts`. Expodiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 34d87fc0785..97f3e0f0ba5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -588,6 +588,9 @@ importers:'@babel/core':specifier: ^7.29.7version: 7.29.7+ '@effect/platform-node':+ specifier: 4.0.5'@effect/vitest':specifier: 4.0.5version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])