Open History to see the last commit
1// Measures React renders in a running T3 Code Dev client. See
2// docs/internals/mobile-development.md#measuring-renders.
3import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
4import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as NodeSocket from "@effect/platform-node/NodeSocket";
7import {
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";
20import * as Console from "effect/Console";
21import * as Crypto from "effect/Crypto";
22import * as Effect from "effect/Effect";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as Schema from "effect/Schema";
27import * as Stream from "effect/Stream";
28import { Command, Flag } from "effect/cli";
29import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
30import { RpcClient, RpcSerialization } from "effect/rpc";
31import { Socket } from "effect/socket";
32
33const 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});
39type RenderReport = typeof RenderReport.Type;
40const decodeReport = Schema.decodeUnknownEffect(Schema.fromJsonString(RenderReport));
41const InspectorTargets = Schema.Array(
42 Schema.Struct({ appId: Schema.String, webSocketDebuggerUrl: Schema.String }),
43);
44const 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});
53const decodeCdpReply = Schema.decodeUnknownOption(Schema.fromJsonString(CdpReply));
54const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
55
56class MeasureError extends Schema.TaggedError<MeasureError>()("MeasureError", {
57 message: Schema.String,
58}) {}
59
60const 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
63interface 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
75const uuid = Effect.flatMap(Crypto.Crypto, (crypto) => crypto.randomUUIDv4());
76
77const 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. */
84const 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
121const 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.
181const 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. */
187const 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
256const 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. */
260const 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. */
281const 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
304const 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
326const 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
344const 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
405Command.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);