@devries-cameron20 / t3code Mirror · read-only / commits / ea97e8ba31
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 05:30 UTC

test(mobile): measure renders on a device (#21001)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 17, 2026 at 23:31 UTC ea97e8ba3146639c59e96615e3e5a207f9ffba60
7 files changed +634
apps/mobile/index.ts
+2
@@ -1,3 +1,5 @@
1 +// Must stay first: the render counter wraps the DevTools hook before any React commit.
2 +import "./src/features/development/render-counter-entry";
3 import { registerRootComponent } from "expo";
4 import "react-native-gesture-handler";
5 import { LogBox } from "react-native";
apps/mobile/package.json
+2
@@ -41,6 +41,7 @@
41 "config:prod": "APP_VARIANT=production expo config",
42 "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",
43 "sync:pierre-icons": "node scripts/sync-pierre-file-icons.mjs",
44 + "measure-renders": "node scripts/measure-renders.mts",
45 "generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate-uniwind-themes.mts",
46 "test": "vp test run --config ../../vite.config.ts --dir .",
47 "typecheck": "tsc-rs --noEmit"
@@ -141,6 +142,7 @@
142 },
143 "devDependencies": {
144 "@babel/core": "^7.29.7",
145 + "@effect/platform-node": "catalog:",
146 "@effect/vitest": "catalog:",
147 "@pierre/trees": "1.0.0-beta.6",
148 "@types/mdast": "^4.0.4",
apps/mobile/scripts/measure-renders.mts new
+414
@@ -0,0 +1,414 @@
1 +// Measures React renders in a running T3 Code Dev client. See
2 +// docs/internals/mobile-development.md#measuring-renders.
3 +import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
4 +import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5 +import * as NodeServices from "@effect/platform-node/NodeServices";
6 +import * as NodeSocket from "@effect/platform-node/NodeSocket";
7 +import {
8 + CommandId,
9 + EnvironmentId,
10 + ExecutionEnvironmentDescriptor,
11 + ORCHESTRATION_PROTOCOL_HEADER,
12 + ORCHESTRATION_PROTOCOL_VERSION,
13 + OrchestrationV2ShellSnapshot,
14 + ProjectId,
15 + ProviderInstanceId,
16 + ThreadId,
17 + WsRpcGroup,
18 + type OrchestrationV2ThreadProjection,
19 +} from "@t3tools/contracts";
20 +import * as Console from "effect/Console";
21 +import * as Crypto from "effect/Crypto";
22 +import * as Effect from "effect/Effect";
23 +import * as FileSystem from "effect/FileSystem";
24 +import * as Layer from "effect/Layer";
25 +import * as Option from "effect/Option";
26 +import * as Schema from "effect/Schema";
27 +import * as Stream from "effect/Stream";
28 +import { Command, Flag } from "effect/cli";
29 +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
30 +import { RpcClient, RpcSerialization } from "effect/rpc";
31 +import { Socket } from "effect/socket";
32 +
33 +const RenderReport = Schema.Struct({
34 + commits: Schema.Number,
35 + totalRenders: Schema.Number,
36 + components: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })),
37 + causes: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })),
38 +});
39 +type RenderReport = typeof RenderReport.Type;
40 +const decodeReport = Schema.decodeUnknownEffect(Schema.fromJsonString(RenderReport));
41 +const InspectorTargets = Schema.Array(
42 + Schema.Struct({ appId: Schema.String, webSocketDebuggerUrl: Schema.String }),
43 +);
44 +const CdpReply = Schema.Struct({
45 + id: Schema.Number,
46 + result: Schema.optional(
47 + Schema.Struct({
48 + result: Schema.optional(Schema.Struct({ value: Schema.optional(Schema.Unknown) })),
49 + exceptionDetails: Schema.optional(Schema.Unknown),
50 + }),
51 + ),
52 +});
53 +const decodeCdpReply = Schema.decodeUnknownOption(Schema.fromJsonString(CdpReply));
54 +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
55 +
56 +class MeasureError extends Schema.TaggedError<MeasureError>()("MeasureError", {
57 + message: Schema.String,
58 +}) {}
59 +
60 +const STREAM_PROMPT =
61 + "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.";
62 +
63 +interface Options {
64 + readonly server: string;
65 + readonly token: string;
66 + readonly metro: string;
67 + readonly scheme: string;
68 + readonly runs: number;
69 + readonly windowSeconds: number;
70 + readonly provider: string;
71 + readonly model: string;
72 + readonly projectRoot: string;
73 +}
74 +
75 +const uuid = Effect.flatMap(Crypto.Crypto, (crypto) => crypto.randomUUIDv4());
76 +
77 +const median = (values: ReadonlyArray<number>) => {
78 + const sorted = [...values].sort((a, b) => a - b);
79 + const middle = Math.floor(sorted.length / 2);
80 + return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
81 +};
82 +
83 +/** One Hermes inspector session, reached through Metro's inspector proxy. */
84 +const connectInspector = Effect.fn("measure.connectInspector")(function* (metro: string) {
85 + const http = yield* HttpClient.HttpClient;
86 + const targets = yield* http
87 + .get(`${metro}/json/list`)
88 + .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(InspectorTargets)));
89 + const target = targets.find((entry) => entry.appId.startsWith("com.t3tools.t3code"));
90 + if (!target)
91 + return yield* new MeasureError({ message: `No T3 Code app is attached to Metro at ${metro}.` });
92 + // Expo terminates inspector sockets whose Origin differs from the URL Metro
93 + // advertises (the LAN address with `--lan`), so pass that URL as `--metro`.
94 + const socket = yield* Socket.makeWebSocket(target.webSocketDebuggerUrl, {
95 + headers: { origin: new URL(metro).origin },
96 + openTimeout: "10 seconds",
97 + });
98 + const writer = yield* socket.writer;
99 + const reader = yield* socket.reader;
100 + let nextId = 0;
101 + return Effect.fn("measure.evaluate")(function* (expression: string) {
102 + const id = ++nextId;
103 + yield* writer.write(
104 + encodeJson({ id, method: "Runtime.evaluate", params: { expression, returnByValue: true } }),
105 + );
106 + while (true) {
107 + for (const frame of yield* reader.pull) {
108 + const text = typeof frame === "string" ? frame : new TextDecoder().decode(frame);
109 + const reply = decodeCdpReply(text);
110 + if (Option.isNone(reply) || reply.value.id !== id) continue;
111 + if (reply.value.result?.exceptionDetails)
112 + return yield* new MeasureError({
113 + message: `Evaluation failed: ${encodeJson(reply.value.result.exceptionDetails)}`,
114 + });
115 + return reply.value.result?.result?.value;
116 + }
117 + }
118 + });
119 +});
120 +
121 +const connectServer = Effect.fn("measure.connectServer")(function* (options: Options) {
122 + const http = (yield* HttpClient.HttpClient).pipe(
123 + HttpClient.mapRequest((request) =>
124 + request.pipe(
125 + HttpClientRequest.bearerToken(options.token),
126 + HttpClientRequest.setHeader(
127 + ORCHESTRATION_PROTOCOL_HEADER,
128 + String(ORCHESTRATION_PROTOCOL_VERSION),
129 + ),
130 + ),
131 + ),
132 + HttpClient.filterStatusOk,
133 + );
134 + const descriptor = yield* http
135 + .get(`${options.server}/.well-known/t3/environment`)
136 + .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)));
137 + const shell = yield* http
138 + .get(`${options.server}/api/orchestration/shell`)
139 + .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot)));
140 + let projectId = shell.projects.find(
141 + (project) => project.workspaceRoot === options.projectRoot,
142 + )?.id;
143 + // A project record outlives its folder, and turns fail without it.
144 + yield* (yield* FileSystem.FileSystem).makeDirectory(options.projectRoot, { recursive: true });
145 + if (!projectId) {
146 + projectId = ProjectId.make(yield* uuid);
147 + yield* http.execute(
148 + HttpClientRequest.post(`${options.server}/api/projects/mutate`).pipe(
149 + HttpClientRequest.bodyJsonUnsafe({
150 + type: "project.create",
151 + commandId: yield* uuid,
152 + projectId,
153 + title: "Render measurement",
154 + workspaceRoot: options.projectRoot,
155 + }),
156 + ),
157 + );
158 + }
159 + const ticket = yield* http
160 + .execute(HttpClientRequest.post(`${options.server}/api/auth/websocket-ticket`))
161 + .pipe(
162 + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
163 + );
164 + // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
165 + const protocol = yield* Layer.build(
166 + RpcClient.layerProtocolSocket().pipe(
167 + Layer.provide(
168 + Socket.layerWebSocket(
169 + `${options.server.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket.ticket)}`,
170 + ),
171 + ),
172 + Layer.provide(RpcSerialization.layerJson),
173 + ),
174 + );
175 + const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
176 + return { client, environmentId: EnvironmentId.make(descriptor.environmentId), projectId };
177 +});
178 +
179 +// Streaming lands in turn items. Some providers stream reasoning but deliver the
180 +// reply text in one piece, so any streaming text item counts as mid-stream.
181 +const streamingItem = (projection: OrchestrationV2ThreadProjection) =>
182 + projection.turnItems.find(
183 + (item) => (item.type === "assistant_message" || item.type === "reasoning") && item.streaming,
184 + );
185 +
186 +/** A thread streams a long reply: the open one, or with `route` a thread the app never shows. */
187 +const measureStreamReply = Effect.fn("measure.streamReply")(function* (
188 + options: Options,
189 + run: number,
190 + route: Option.Option<string>,
191 +) {
192 + if (Option.isSome(route)) yield* reloadAndOpen(options, route.value);
193 + const evaluate = yield* connectInspector(options.metro);
194 + const { client, environmentId, projectId } = yield* connectServer(options);
195 + const threadId = ThreadId.make(yield* uuid);
196 + yield* client["orchestration.launchThread"]({
197 + commandId: CommandId.make(yield* uuid),
198 + threadId,
199 + projectId,
200 + title: `Render measurement ${run}`,
201 + modelSelection: {
202 + instanceId: ProviderInstanceId.make(options.provider),
203 + model: options.model,
204 + },
205 + // The prompt needs no tools; approval-required keeps a stray call from acting.
206 + runtimeMode: "approval-required",
207 + interactionMode: "default",
208 + workspaceStrategy: { type: "root" },
209 + initialMessage: { text: STREAM_PROMPT, attachments: [] },
210 + });
211 + // A failed or interrupted window must not leave a provider turn running.
212 + yield* Effect.addFinalizer(() =>
213 + Effect.gen(function* () {
214 + const after = yield* client["orchestration.getThreadProjection"]({ threadId });
215 + const activeRun = after.runs.find(
216 + (entry) => !["completed", "failed", "interrupted", "cancelled"].includes(entry.status),
217 + );
218 + if (!activeRun) return;
219 + yield* client["orchestration.dispatchCommand"]({
220 + type: "run.interrupt",
221 + commandId: CommandId.make(yield* uuid),
222 + threadId,
223 + runId: activeRun.id,
224 + });
225 + }).pipe(Effect.ignore),
226 + );
227 + if (Option.isNone(route))
228 + yield* evaluate(
229 + `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://threads/${environmentId}/${threadId}`)})`,
230 + );
231 + const projectionOf = (item: { kind: string; projection?: OrchestrationV2ThreadProjection }) =>
232 + item.kind === "snapshot" && item.projection
233 + ? Effect.succeed(item.projection)
234 + : client["orchestration.getThreadProjection"]({ threadId });
235 + const streaming = yield* client["orchestration.subscribeThread"]({ threadId }).pipe(
236 + Stream.mapEffect(projectionOf),
237 + Stream.filter((projection) => streamingItem(projection) !== undefined),
238 + Stream.runHead,
239 + Effect.timeout("90 seconds"),
240 + );
241 + if (Option.isNone(streaming))
242 + return yield* new MeasureError({ message: `Run ${run}: the reply never started streaming.` });
243 + yield* evaluate("__t3RenderCounterStart()");
244 + yield* Effect.sleep(`${options.windowSeconds} seconds`);
245 + const report = yield* decodeReport(yield* evaluate("JSON.stringify(__t3RenderCounterStop())"));
246 + // React commits on every streamed delta, so an empty window means the app is not on the thread.
247 + // A thread streaming out of view may rightly commit nothing.
248 + if (report.commits === 0 && Option.isNone(route))
249 + return yield* new MeasureError({
250 + message: `Run ${run}: no React commits in the window. Check the device for a red box.`,
251 + });
252 + const after = yield* client["orchestration.getThreadProjection"]({ threadId });
253 + return { report, stillStreaming: streamingItem(after) !== undefined };
254 +}, Effect.scoped);
255 +
256 +const appLink = (options: Options, route: string) =>
257 + `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://${route.replace(/^\//, "")}`)})`;
258 +
259 +/** Reloads onto Home, then opens `route` and lets it settle; `/` stays on Home. */
260 +const reloadAndOpen = Effect.fn("measure.reloadAndOpen")(function* (
261 + options: Options,
262 + route: string,
263 +) {
264 + // A link to an already-open screen only refocuses it, so each run starts from a reload.
265 + yield* Effect.scoped(
266 + Effect.flatMap(connectInspector(options.metro), (evaluate) =>
267 + evaluate("__t3RenderCounterReload()"),
268 + ),
269 + );
270 + yield* Effect.sleep("15 seconds");
271 + if (route === "/" || route === "") return;
272 + yield* Effect.scoped(
273 + Effect.flatMap(connectInspector(options.metro), (evaluate) =>
274 + evaluate(appLink(options, route)),
275 + ),
276 + );
277 + yield* Effect.sleep("5 seconds");
278 +});
279 +
280 +/** Opens a screen from a freshly loaded Home and records its mount and data settling. */
281 +const measureRouteOpen = Effect.fn("measure.routeOpen")(function* (
282 + options: Options,
283 + route: string,
284 + run: number,
285 +) {
286 + yield* Effect.scoped(
287 + Effect.flatMap(connectInspector(options.metro), (evaluate) =>
288 + evaluate("__t3RenderCounterReload()"),
289 + ),
290 + );
291 + yield* Effect.sleep("15 seconds");
292 + const evaluate = yield* connectInspector(options.metro);
293 + yield* evaluate("__t3RenderCounterStart()");
294 + yield* evaluate(appLink(options, route));
295 + yield* Effect.sleep(`${options.windowSeconds} seconds`);
296 + const report = yield* decodeReport(yield* evaluate("JSON.stringify(__t3RenderCounterStop())"));
297 + if (report.commits === 0)
298 + return yield* new MeasureError({
299 + message: `Run ${run}: no React commits in the window. Check that ${route} is a valid app path.`,
300 + });
301 + return { report, stillStreaming: undefined };
302 +}, Effect.scoped);
303 +
304 +const medianTable = (
305 + title: string,
306 + reports: ReadonlyArray<RenderReport>,
307 + pick: (report: RenderReport) => RenderReport["causes"],
308 + limit: number,
309 +) => {
310 + const keys = new Set(reports.flatMap((report) => pick(report).map((entry) => entry.key)));
311 + const rows = [...keys]
312 + .map((key) => ({
313 + key,
314 + count: median(reports.map((report) => pick(report).find((e) => e.key === key)?.count ?? 0)),
315 + }))
316 + .filter((row) => row.count > 0)
317 + .sort((a, b) => b.count - a.count)
318 + .slice(0, limit);
319 + return [
320 + `| ${title} | Renders |`,
321 + "|---|---:|",
322 + ...rows.map((r) => `| \`${r.key}\` | ${r.count} |`),
323 + ];
324 +};
325 +
326 +const formatTable = (reports: ReadonlyArray<RenderReport>) => {
327 + const totals = (pick: (report: RenderReport) => number) => median(reports.map(pick));
328 + return [
329 + `Median of ${reports.length} runs.`,
330 + "",
331 + "| | |",
332 + "|---|---:|",
333 + `| renders | ${totals((r) => r.totalRenders)} |`,
334 + `| commits | ${totals((r) => r.commits)} |`,
335 + // Provider pace sets how many commits land in the window; per-commit cost compares across runs.
336 + `| renders per commit | ${totals((r) => Math.round(r.totalRenders / Math.max(r.commits, 1)))} |`,
337 + "",
338 + ...medianTable("Component", reports, (r) => r.components, 20),
339 + "",
340 + ...medianTable("Cause", reports, (r) => r.causes, 15),
341 + ].join("\n");
342 +};
343 +
344 +const command = Command.make(
345 + "measure-renders",
346 + {
347 + server: Flag.String("server").pipe(
348 + Flag.withDescription("T3 server origin the app is paired with."),
349 + Flag.withDefault(""),
350 + ),
351 + token: Flag.String("token").pipe(
352 + Flag.withDescription("Bearer token from `t3 auth session issue --token-only`."),
353 + Flag.withDefault(""),
354 + ),
355 + route: Flag.String("route").pipe(
356 + Flag.withDescription(
357 + "App path to open and measure. With --server, the path stays open while a new thread streams.",
358 + ),
359 + Flag.optional,
360 + ),
361 + metro: Flag.String("metro").pipe(Flag.withDefault("http://127.0.0.1:8081")),
362 + scheme: Flag.String("scheme").pipe(Flag.withDefault("t3code-dev")),
363 + runs: Flag.Int("runs").pipe(Flag.withDefault(3)),
364 + window: Flag.Int("window").pipe(
365 + Flag.withDescription("Seconds to record; defaults to 12 for a reply and 6 for --route."),
366 + Flag.optional,
367 + ),
368 + provider: Flag.String("provider").pipe(Flag.withDefault("claudeAgent")),
369 + model: Flag.String("model").pipe(Flag.withDefault("claude-haiku-5-5")),
370 + projectRoot: Flag.String("project-root").pipe(
371 + Flag.withDescription("Scratch directory for the measurement project; created if missing."),
372 + Flag.withDefault(""),
373 + ),
374 + },
375 + Effect.fn("measure.main")(function* (flags) {
376 + const route = flags.route;
377 + const options: Options = {
378 + ...flags,
379 + windowSeconds: Option.getOrElse(flags.window, () =>
380 + Option.isSome(route) && !flags.server ? 6 : 12,
381 + ),
382 + };
383 + const streams = Option.isNone(route) || flags.server !== "";
384 + if (streams && (!flags.server || !flags.token || !flags.projectRoot))
385 + return yield* new MeasureError({
386 + message: "Streaming a reply needs --server, --token and --project-root.",
387 + });
388 + const reports: RenderReport[] = [];
389 + for (let run = 1; run <= flags.runs; run++) {
390 + const { report, stillStreaming } =
391 + Option.isSome(route) && !streams
392 + ? yield* measureRouteOpen(options, route.value, run)
393 + : yield* measureStreamReply(options, run, route);
394 + yield* Console.error(
395 + `run ${run}: ${report.totalRenders} renders in ${report.commits} commits${stillStreaming === false ? " (warning: streaming ended inside the window)" : ""}`,
396 + );
397 + reports.push(report);
398 + // Let the interrupted turn settle so the next run starts from a quiet app.
399 + yield* Effect.sleep("3 seconds");
400 + }
401 + yield* Console.log(formatTable(reports));
402 + }),
403 +);
404 +
405 +Command.run(command, { version: "0.0.0" }).pipe(
406 + Effect.provide(
407 + Layer.mergeAll(
408 + NodeServices.layer,
409 + NodeHttpClient.layerUndici,
410 + NodeSocket.layerWebSocketConstructorWS,
411 + ),
412 + ),
413 + NodeRuntime.runMain,
414 +);
apps/mobile/src/features/development/render-counter-entry.ts new
+5
@@ -0,0 +1,5 @@
1 +// Production builds fold this condition to false before Metro collects
2 +// dependencies, so the counter module never enters a release bundle.
3 +if (__DEV__ && process.env.EXPO_PUBLIC_T3_RENDER_COUNTER === "1") {
4 + require("./render-counter");
5 +}
apps/mobile/src/features/development/render-counter.ts new
+177
@@ -0,0 +1,177 @@
1 +// Dev-only render counter driven by `scripts/measure-renders.mts` through the
2 +// Hermes inspector. It wraps the DevTools hook's commit callback, so it must load
3 +// before React renders anything; see `render-counter-entry.ts`.
4 +//
5 +// The fiber walk matches the web counter used for React Compiler work: a
6 +// bailed-out subtree keeps `child === alternate.child`, so it is not descended,
7 +// because fibers there keep stale flags and alternates from older commits.
8 +// PerformedWork (1) is cleared whenever React clones a fiber, so a reached fiber
9 +// with it set rendered in this commit.
10 +
11 +interface Fiber {
12 + readonly tag: number;
13 + readonly type: unknown;
14 + readonly flags: number;
15 + readonly alternate: Fiber | null;
16 + readonly child: Fiber | null;
17 + readonly sibling: Fiber | null;
18 + readonly memoizedProps: Record<string, unknown> | null;
19 + readonly memoizedState: HookSlot | null;
20 +}
21 +interface HookSlot {
22 + readonly memoizedState: unknown;
23 + /** Non-null only for useState and useReducer, the hooks that can schedule a render. */
24 + readonly queue: unknown;
25 + readonly next: HookSlot | null;
26 +}
27 +interface DevToolsHook {
28 + onCommitFiberRoot?: (id: unknown, root: { current: Fiber }, ...rest: unknown[]) => unknown;
29 + __t3RenderCounter?: true;
30 +}
31 +interface RenderCounterState {
32 + on: boolean;
33 + commits: number;
34 + counts: Map<string, number>;
35 + causes: Map<string, number>;
36 +}
37 +export interface RenderCounterReport {
38 + readonly commits: number;
39 + readonly totalRenders: number;
40 + readonly components: ReadonlyArray<{ key: string; count: number }>;
41 + readonly causes: ReadonlyArray<{ key: string; count: number }>;
42 +}
43 +
44 +const COMPONENT_TAGS = new Set([0, 1, 11, 14, 15]);
45 +const PERFORMED_WORK = 1;
46 +
47 +function nameOf(fiber: Fiber): string | null {
48 + const type = fiber.type as {
49 + displayName?: string;
50 + name?: string;
51 + type?: { displayName?: string; name?: string };
52 + render?: { displayName?: string; name?: string };
53 + } | null;
54 + if (!type || typeof type === "string") return null;
55 + const inner = type.type ?? type.render ?? type;
56 + const raw = type.displayName || inner.displayName || inner.name || "";
57 + return raw.replace(/^(Forget\(|Memo\()+|\)+$/g, "") || null;
58 +}
59 +
60 +function isEffect(value: unknown): boolean {
61 + return (
62 + typeof value === "object" &&
63 + value !== null &&
64 + "create" in value &&
65 + "deps" in value &&
66 + "tag" in value
67 + );
68 +}
69 +
70 +function changedStateSlot(alternate: Fiber, node: Fiber): number {
71 + let a = alternate.memoizedState;
72 + let b = node.memoizedState;
73 + for (let index = 0; a && b && index < 800; index++) {
74 + const before = a.memoizedState;
75 + const after = b.memoizedState;
76 + // Memo, callback and ref slots change because something upstream did; only a
77 + // state update is a cause of its own.
78 + if (b.queue !== null && !isEffect(after) && !Object.is(before, after)) return index;
79 + a = a.next;
80 + b = b.next;
81 + }
82 + return -1;
83 +}
84 +
85 +function causeOf(node: Fiber, parentName: string): string {
86 + const alternate = node.alternate;
87 + if (!alternate) return "mount";
88 + const slot = changedStateSlot(alternate, node);
89 + if (slot >= 0) return `state#${slot}`;
90 + if (alternate.memoizedProps !== node.memoizedProps) {
91 + const props = node.memoizedProps ?? {};
92 + const keys = Object.keys(props).filter(
93 + (key) => !Object.is(alternate.memoizedProps?.[key], props[key]),
94 + );
95 + return keys.length ? `props:${keys.slice(0, 4).join(",")}` : `parent-same-props<-${parentName}`;
96 + }
97 + return "context";
98 +}
99 +
100 +function increment(map: Map<string, number>, key: string) {
101 + map.set(key, (map.get(key) ?? 0) + 1);
102 +}
103 +
104 +function install(state: RenderCounterState) {
105 + const hook = (globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook })
106 + .__REACT_DEVTOOLS_GLOBAL_HOOK__;
107 + if (!hook || typeof hook.onCommitFiberRoot !== "function") {
108 + setTimeout(() => install(state), 50);
109 + return;
110 + }
111 + if (hook.__t3RenderCounter) return;
112 + hook.__t3RenderCounter = true;
113 + const original = hook.onCommitFiberRoot.bind(hook);
114 +
115 + const visit = (fiber: Fiber | null, parentName: string) => {
116 + let node = fiber;
117 + while (node) {
118 + const alternate = node.alternate;
119 + const name = COMPONENT_TAGS.has(node.tag) ? nameOf(node) : null;
120 + const rendered = name !== null && (node.flags & PERFORMED_WORK) === PERFORMED_WORK;
121 + if (rendered) {
122 + increment(state.counts, name);
123 + increment(state.causes, `${name} ${causeOf(node, parentName)}`);
124 + }
125 + const skipped = alternate !== null && node.child === alternate.child && !rendered;
126 + if (node.child && !skipped) visit(node.child, rendered ? name : parentName);
127 + node = node.sibling;
128 + }
129 + };
130 +
131 + hook.onCommitFiberRoot = (id, root, ...rest) => {
132 + if (state.on) {
133 + state.commits += 1;
134 + visit(root.current.child, "root");
135 + }
136 + return original(id, root, ...rest);
137 + };
138 +}
139 +
140 +const state: RenderCounterState = { on: false, commits: 0, counts: new Map(), causes: new Map() };
141 +
142 +const sorted = (map: Map<string, number>) =>
143 + [...map].map(([key, count]) => ({ key, count })).sort((a, b) => b.count - a.count);
144 +
145 +install(state);
146 +
147 +Object.assign(globalThis, {
148 + /** Routes an app link in-process, so drivers need no simctl or adb access. */
149 + __t3RenderCounterOpen(url: string) {
150 + const { Linking } = require("react-native") as typeof import("react-native");
151 + void Linking.openURL(url);
152 + return true;
153 + },
154 + /** Restarts the JS app on Home; deferred so the inspector call can reply first. */
155 + __t3RenderCounterReload() {
156 + const { DevSettings } = require("react-native") as typeof import("react-native");
157 + setTimeout(() => DevSettings.reload(), 100);
158 + return true;
159 + },
160 + __t3RenderCounterStart() {
161 + state.commits = 0;
162 + state.counts = new Map();
163 + state.causes = new Map();
164 + state.on = true;
165 + return true;
166 + },
167 + __t3RenderCounterStop(): RenderCounterReport {
168 + state.on = false;
169 + const components = sorted(state.counts);
170 + return {
171 + commits: state.commits,
172 + totalRenders: components.reduce((total, entry) => total + entry.count, 0),
173 + components,
174 + causes: sorted(state.causes),
175 + };
176 + },
177 +});
docs/internals/mobile-development.md
+31
@@ -35,6 +35,37 @@ so an edit to a module's TypeScript is invisible to a running dev client until
35 `vp i` re-syncs it, while Gradle and CocoaPods compile the worktree directory
36 directly. A JavaScript change that "has no effect" on device is usually this.
37
38 +## Measuring renders
39 +
40 +[`render-counter.ts`](../../apps/mobile/src/features/development/render-counter.ts) counts the
41 +components React rendered in each commit and why: a changed state slot, changed props, or
42 +context. It wraps the DevTools hook from the first import in `index.ts` and loads only when
43 +`__DEV__` and `EXPO_PUBLIC_T3_RENDER_COUNTER=1`, so release bundles never contain it. The walk
44 +skips subtrees React bailed out of. A probe that checks `flags & 1` on every fiber reports
45 +renders that never happened, because bailed-out fibers keep flags from older commits.
46 +
47 +[`measure-renders.mts`](../../apps/mobile/scripts/measure-renders.mts) drives a measurement from
48 +outside the app. It evaluates the counter's globals through Metro's Hermes inspector proxy, which
49 +works the same for iOS simulators and Android emulators and needs no taps, `simctl`, or `adb`. It
50 +starts a real provider turn through the server, opens the thread with an app link, records a window
51 +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
52 +pass that URL (the LAN address with `--lan`) as `--metro`.
53 +
54 +```bash
55 +EXPO_PUBLIC_T3_RENDER_COUNTER=1 vp run dev:client # in apps/mobile, then pair the app
56 +node apps/server/src/bin.ts auth session issue --base-dir <base-dir> --token-only
57 +node apps/mobile/scripts/measure-renders.mts --server <server-origin> --token <token> \
58 + --metro http://<metro-lan-host>:8081 --project-root <scratch-dir>
59 +```
60 +
61 +`--route /settings/usage` instead reloads the app, opens that path from Home and records a 6 s window over
62 +mount and data settling, with no provider turn and no `--server`, `--token` or `--project-root`.
63 +With `--server` as well, the app reloads, opens that path (`/` stays on Home) and the reply streams in a
64 +new thread the app never shows, which measures what streaming elsewhere costs the screen in front.
65 +
66 +Compare before and after on the same base, on the same device, with the median of three runs.
67 +Provider output varies run to run, so a single run or a comparison across bases is noise.
68 +
69 ## React Compiler
70
71 Metro runs the compiler only because `experiments.reactCompiler` is set in `app.config.ts`. Expo
pnpm-lock.yaml
+3
@@ -588,6 +588,9 @@ importers:
588 '@babel/core':
589 specifier: ^7.29.7
590 version: 7.29.7
591 + '@effect/platform-node':
592 + specifier: 4.0.5
593 + version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6)
594 '@effect/vitest':
595 specifier: 4.0.5
596 version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.1)(@vitest/ui@5.0.1)(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(msw@2.12.11(@types/node@24.12.4)(typescript@7.0.2))(terser@5.48.0)(typescript@7.0.2)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)