Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

measure-renders.mts

406 lines15.7 KB

1// See docs/internals/mobile-development.md#measuring-renders.
2import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as NodeSocket from "@effect/platform-node/NodeSocket";
6import {
7 CommandId,
8 EnvironmentId,
9 ExecutionEnvironmentDescriptor,
10 ORCHESTRATION_PROTOCOL_HEADER,
11 ORCHESTRATION_PROTOCOL_VERSION,
12 OrchestrationV2ShellSnapshot,
13 ProjectId,
14 ProviderInstanceId,
15 ThreadId,
16 WsRpcGroup,
17 type OrchestrationV2ThreadProjection,
18} from "@t3tools/contracts";
19import * as Console from "effect/Console";
20import * as Crypto from "effect/Crypto";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Schema from "effect/Schema";
26import * as Stream from "effect/Stream";
27import { Command, Flag } from "effect/cli";
28import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
29import { RpcClient, RpcSerialization } from "effect/rpc";
30import { Socket } from "effect/socket";
31​
32const RenderReport = Schema.Struct({
33 commits: Schema.Number,
34 totalRenders: Schema.Number,
35 components: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })),
36 causes: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })),
37});
38type RenderReport = typeof RenderReport.Type;
39const decodeReport = Schema.decodeUnknownEffect(Schema.fromJsonString(RenderReport));
40const InspectorTargets = Schema.Array(
41 Schema.Struct({ appId: Schema.String, webSocketDebuggerUrl: Schema.String }),
42);
43const CdpReply = Schema.Struct({
44 id: Schema.Number,
45 result: Schema.optional(
46 Schema.Struct({
47 result: Schema.optional(Schema.Struct({ value: Schema.optional(Schema.Unknown) })),
48 exceptionDetails: Schema.optional(Schema.Unknown),
49 }),
50 ),
51});
52const decodeCdpReply = Schema.decodeUnknownOption(Schema.fromJsonString(CdpReply));
53const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
54​
55class MeasureError extends Schema.TaggedError<MeasureError>()("MeasureError", {
56 message: Schema.String,
57}) {}
58​
59const STREAM_PROMPT =
60 "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.";
61​
62interface Options {
63 readonly server: string;
64 readonly token: string;
65 readonly metro: string;
66 readonly scheme: string;
67 readonly runs: number;
68 readonly windowSeconds: number;
69 readonly provider: string;
70 readonly model: string;
71 readonly projectRoot: string;
73​
74const uuid = Effect.flatMap(Crypto.Crypto, (crypto) => crypto.randomUUIDv4());
75​
76const median = (values: ReadonlyArray<number>) => {
77 const sorted = [...values].sort((a, b) => a - b);
78 const middle = Math.floor(sorted.length / 2);
79 return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
80};
81​
82const connectInspector = Effect.fn("measure.connectInspector")(function* (metro: string) {
83 const http = yield* HttpClient.HttpClient;
84 const targets = yield* http
85 .get(`${metro}/json/list`)
86 .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(InspectorTargets)));
87 const target = targets.find((entry) => entry.appId.startsWith("com.t3tools.t3code"));
88 if (!target)
89 return yield* new MeasureError({ message: `No T3 Code app is attached to Metro at ${metro}.` });
90 // Expo closes inspector sockets unless Origin matches Metro's advertised URL; pass that URL as --metro.
91 const socket = yield* Socket.makeWebSocket(target.webSocketDebuggerUrl, {
92 headers: { origin: new URL(metro).origin },
93 openTimeout: "10 seconds",
94 });
95 const writer = yield* socket.writer;
96 const reader = yield* socket.reader;
97 let nextId = 0;
98 return Effect.fn("measure.evaluate")(function* (expression: string) {
99 const id = ++nextId;
100 yield* writer.write(
101 encodeJson({ id, method: "Runtime.evaluate", params: { expression, returnByValue: true } }),
102 );
103 while (true) {
104 for (const frame of yield* reader.pull) {
105 const text = typeof frame === "string" ? frame : new TextDecoder().decode(frame);
106 const reply = decodeCdpReply(text);
107 if (Option.isNone(reply) || reply.value.id !== id) continue;
108 if (reply.value.result?.exceptionDetails)
109 return yield* new MeasureError({
110 message: `Evaluation failed: ${encodeJson(reply.value.result.exceptionDetails)}`,
111 });
112 return reply.value.result?.result?.value;
113 }
114 }
115 });
116});
117​
118const connectServer = Effect.fn("measure.connectServer")(function* (options: Options) {
119 const http = (yield* HttpClient.HttpClient).pipe(
120 HttpClient.mapRequest((request) =>
121 request.pipe(
122 HttpClientRequest.bearerToken(options.token),
123 HttpClientRequest.setHeader(
124 ORCHESTRATION_PROTOCOL_HEADER,
125 String(ORCHESTRATION_PROTOCOL_VERSION),
126 ),
127 ),
128 ),
129 HttpClient.filterStatusOk,
130 );
131 const descriptor = yield* http
132 .get(`${options.server}/.well-known/t3/environment`)
133 .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)));
134 const shell = yield* http
135 .get(`${options.server}/api/orchestration/shell`)
136 .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot)));
137 let projectId = shell.projects.find(
138 (project) => project.workspaceRoot === options.projectRoot,
139 )?.id;
140 // A project record outlives its folder, and turns fail without it.
141 yield* (yield* FileSystem.FileSystem).makeDirectory(options.projectRoot, { recursive: true });
142 if (!projectId) {
143 projectId = ProjectId.make(yield* uuid);
144 yield* http.execute(
145 HttpClientRequest.post(`${options.server}/api/projects/mutate`).pipe(
146 HttpClientRequest.bodyJsonUnsafe({
147 type: "project.create",
148 commandId: yield* uuid,
149 projectId,
150 title: "Render measurement",
151 workspaceRoot: options.projectRoot,
152 }),
153 ),
154 );
155 }
156 const ticket = yield* http
157 .execute(HttpClientRequest.post(`${options.server}/api/auth/websocket-ticket`))
158 .pipe(
159 Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
160 );
161 // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
162 const protocol = yield* Layer.build(
163 RpcClient.layerProtocolSocket().pipe(
164 Layer.provide(
165 Socket.layerWebSocket(
166 `${options.server.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket.ticket)}`,
167 ),
168 ),
169 Layer.provide(RpcSerialization.layerJson),
170 ),
171 );
172 const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
173 return { client, environmentId: EnvironmentId.make(descriptor.environmentId), projectId };
174});
175​
176// Some providers stream only reasoning, so any streaming text item counts.
177const streamingItem = (projection: OrchestrationV2ThreadProjection) =>
178 projection.turnItems.find(
179 (item) => (item.type === "assistant_message" || item.type === "reasoning") && item.streaming,
180 );
181​
182const measureStreamReply = Effect.fn("measure.streamReply")(function* (
183 options: Options,
184 run: number,
185 route: Option.Option<string>,
186) {
187 if (Option.isSome(route)) yield* reloadAndOpen(options, route.value);
188 const evaluate = yield* connectInspector(options.metro);
189 const { client, environmentId, projectId } = yield* connectServer(options);
190 const threadId = ThreadId.make(yield* uuid);
191 yield* client["orchestration.launchThread"]({
192 commandId: CommandId.make(yield* uuid),
193 threadId,
194 projectId,
195 title: `Render measurement ${run}`,
196 modelSelection: {
197 instanceId: ProviderInstanceId.make(options.provider),
198 model: options.model,
199 },
200 // The prompt needs no tools; approval-required keeps a stray call from acting.
201 runtimeMode: "approval-required",
202 interactionMode: "default",
203 workspaceStrategy: { type: "root" },
204 initialMessage: { text: STREAM_PROMPT, attachments: [] },
205 });
206 // A failed or interrupted window must not leave a provider turn running.
207 yield* Effect.addFinalizer(() =>
208 Effect.gen(function* () {
209 const after = yield* client["orchestration.getThreadProjection"]({ threadId });
210 const activeRun = after.runs.find(
211 (entry) => !["completed", "failed", "interrupted", "cancelled"].includes(entry.status),
212 );
213 if (!activeRun) return;
214 yield* client["orchestration.dispatchCommand"]({
215 type: "run.interrupt",
216 commandId: CommandId.make(yield* uuid),
217 threadId,
218 runId: activeRun.id,
219 });
220 }).pipe(Effect.ignore),
221 );
222 if (Option.isNone(route))
223 yield* evaluate(
224 `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://threads/${environmentId}/${threadId}`)})`,
225 );
226 const projectionOf = (item: { kind: string; projection?: OrchestrationV2ThreadProjection }) =>
227 item.kind === "snapshot" && item.projection
228 ? Effect.succeed(item.projection)
229 : client["orchestration.getThreadProjection"]({ threadId });
230 const streaming = yield* client["orchestration.subscribeThread"]({ threadId }).pipe(
231 Stream.mapEffect(projectionOf),
232 Stream.filter((projection) => streamingItem(projection) !== undefined),
233 Stream.runHead,
234 Effect.timeout("90 seconds"),
235 );
236 if (Option.isNone(streaming))
237 return yield* new MeasureError({ message: `Run ${run}: the reply never started streaming.` });
238 yield* evaluate("__t3RenderCounterStart()");
239 yield* Effect.sleep(`${options.windowSeconds} seconds`);
240 const report = yield* decodeReport(yield* evaluate("JSON.stringify(__t3RenderCounterStop())"));
241 // An in-view streaming thread must commit; out-of-view streaming may commit nothing.
242 if (report.commits === 0 && Option.isNone(route))
243 return yield* new MeasureError({
244 message: `Run ${run}: no React commits in the window. Check the device for a red box.`,
245 });
246 const after = yield* client["orchestration.getThreadProjection"]({ threadId });
247 return { report, stillStreaming: streamingItem(after) !== undefined };
248}, Effect.scoped);
249​
250const appLink = (options: Options, route: string) =>
251 `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://${route.replace(/^\//, "")}`)})`;
252​
253const reloadAndOpen = Effect.fn("measure.reloadAndOpen")(function* (
254 options: Options,
255 route: string,
256) {
257 // A link to an already-open screen only refocuses it, so each run starts from a reload.
258 yield* Effect.scoped(
259 Effect.flatMap(connectInspector(options.metro), (evaluate) =>
260 evaluate("__t3RenderCounterReload()"),
261 ),
262 );
263 yield* Effect.sleep("15 seconds");
264 if (route === "/" || route === "") return;
265 yield* Effect.scoped(
266 Effect.flatMap(connectInspector(options.metro), (evaluate) =>
267 evaluate(appLink(options, route)),
268 ),
269 );
270 yield* Effect.sleep("5 seconds");
271});
272​
273const measureRouteOpen = Effect.fn("measure.routeOpen")(function* (
274 options: Options,
275 route: string,
276 run: number,
277) {
278 yield* Effect.scoped(
279 Effect.flatMap(connectInspector(options.metro), (evaluate) =>
280 evaluate("__t3RenderCounterReload()"),
281 ),
282 );
283 yield* Effect.sleep("15 seconds");
284 const evaluate = yield* connectInspector(options.metro);
285 yield* evaluate("__t3RenderCounterStart()");
286 yield* evaluate(appLink(options, route));
287 yield* Effect.sleep(`${options.windowSeconds} seconds`);
288 const report = yield* decodeReport(yield* evaluate("JSON.stringify(__t3RenderCounterStop())"));
289 if (report.commits === 0)
290 return yield* new MeasureError({
291 message: `Run ${run}: no React commits in the window. Check that ${route} is a valid app path.`,
292 });
293 return { report, stillStreaming: undefined };
294}, Effect.scoped);
295​
296const medianTable = (
297 title: string,
298 reports: ReadonlyArray<RenderReport>,
299 pick: (report: RenderReport) => RenderReport["causes"],
300 limit: number,
301) => {
302 const keys = new Set(reports.flatMap((report) => pick(report).map((entry) => entry.key)));
303 const rows = [...keys]
304 .map((key) => ({
305 key,
306 count: median(reports.map((report) => pick(report).find((e) => e.key === key)?.count ?? 0)),
307 }))
308 .filter((row) => row.count > 0)
309 .sort((a, b) => b.count - a.count)
310 .slice(0, limit);
311 return [
312 `| ${title} | Renders |`,
313 "|---|---:|",
314 ...rows.map((r) => `| \`${r.key}\` | ${r.count} |`),
315 ];
316};
317​
318const formatTable = (reports: ReadonlyArray<RenderReport>) => {
319 const totals = (pick: (report: RenderReport) => number) => median(reports.map(pick));
320 return [
321 `Median of ${reports.length} runs.`,
322 "",
323 "| | |",
324 "|---|---:|",
325 `| renders | ${totals((r) => r.totalRenders)} |`,
326 `| commits | ${totals((r) => r.commits)} |`,
327 // Provider pace sets how many commits land in the window; per-commit cost compares across runs.
328 `| renders per commit | ${totals((r) => Math.round(r.totalRenders / Math.max(r.commits, 1)))} |`,
329 "",
330 ...medianTable("Component", reports, (r) => r.components, 20),
331 "",
332 ...medianTable("Cause", reports, (r) => r.causes, 15),
333 ].join("\n");
334};
335​
336const command = Command.make(
337 "measure-renders",
338 {
339 server: Flag.String("server").pipe(
340 Flag.withDescription("T3 server origin the app is paired with."),
341 Flag.withDefault(""),
342 ),
343 token: Flag.String("token").pipe(
344 Flag.withDescription("Bearer token from `t3 auth session issue --token-only`."),
345 Flag.withDefault(""),
346 ),
347 route: Flag.String("route").pipe(
348 Flag.withDescription(
349 "App path to open and measure. With --server, the path stays open while a new thread streams.",
350 ),
351 Flag.optional,
352 ),
353 metro: Flag.String("metro").pipe(Flag.withDefault("http://127.0.0.1:8081")),
354 scheme: Flag.String("scheme").pipe(Flag.withDefault("t3code-dev")),
355 runs: Flag.Int("runs").pipe(Flag.withDefault(3)),
356 window: Flag.Int("window").pipe(
357 Flag.withDescription("Seconds to record; defaults to 12 for a reply and 6 for --route."),
358 Flag.optional,
359 ),
360 provider: Flag.String("provider").pipe(Flag.withDefault("claudeAgent")),
361 model: Flag.String("model").pipe(Flag.withDefault("claude-haiku-5-5")),
362 projectRoot: Flag.String("project-root").pipe(
363 Flag.withDescription("Scratch directory for the measurement project; created if missing."),
364 Flag.withDefault(""),
365 ),
366 },
367 Effect.fn("measure.main")(function* (flags) {
368 const route = flags.route;
369 const options: Options = {
370 ...flags,
371 windowSeconds: Option.getOrElse(flags.window, () =>
372 Option.isSome(route) && !flags.server ? 6 : 12,
373 ),
374 };
375 const streams = Option.isNone(route) || flags.server !== "";
376 if (streams && (!flags.server || !flags.token || !flags.projectRoot))
377 return yield* new MeasureError({
378 message: "Streaming a reply needs --server, --token and --project-root.",
379 });
380 const reports: RenderReport[] = [];
381 for (let run = 1; run <= flags.runs; run++) {
382 const { report, stillStreaming } =
383 Option.isSome(route) && !streams
384 ? yield* measureRouteOpen(options, route.value, run)
385 : yield* measureStreamReply(options, run, route);
386 yield* Console.error(
387 `run ${run}: ${report.totalRenders} renders in ${report.commits} commits${stillStreaming === false ? " (warning: streaming ended inside the window)" : ""}`,
388 );
389 reports.push(report);
390 // Let the interrupted turn settle so the next run starts from a quiet app.
391 yield* Effect.sleep("3 seconds");
392 }
393 yield* Console.log(formatTable(reports));
394 }),
395);
396​
397Command.run(command, { version: "0.0.0" }).pipe(
398 Effect.provide(
399 Layer.mergeAll(
400 NodeServices.layer,
401 NodeHttpClient.layerUndici,
402 NodeSocket.layerWebSocketConstructorWS,
403 ),
404 ),
405 NodeRuntime.runMain,
406);