Repository navigation
Expand file tree
/
Copy pathmeasure-renders.mts
More file actions
406 lines (389 loc) · 15.7 KB
/
Copy pathmeasure-renders.mts
File metadata and controls
406 lines (389 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// 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;
};
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 closes inspector sockets unless Origin matches Metro's advertised URL; 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 };
});
// Some providers stream only reasoning, so any streaming text item counts.
const streamingItem = (projection: OrchestrationV2ThreadProjection) =>
projection.turnItems.find(
(item) => (item.type === "assistant_message" || item.type === "reasoning") && item.streaming,
);
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())"));
// An in-view streaming thread must commit; out-of-view streaming may 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(/^\//, "")}`)})`;
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");
});
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,
);