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

run.ts

298 lines13.0 KB

1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off preferSchemaOverJson:off - owns Metro and writes result files.
3/**
4 * Drives the T3 Code iOS dev client on one simulator against an isolated server with scripted
5 * replies, and grades app behavior from the dev-only probe and server state. See README.md.
6 */
7import * as NodeChildProcess from "node:child_process";
8import * as NodeFS from "node:fs";
9import * as NodeOS from "node:os";
10import * as NodePath from "node:path";
11import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
12import * as NodeServices from "@effect/platform-node/NodeServices";
13import * as Clock from "effect/Clock";
14import * as Console from "effect/Console";
15import * as Effect from "effect/Effect";
16import * as Option from "effect/Option";
17import { Command, Flag } from "effect/cli";
18import { FetchHttpClient, HttpClient } from "effect/http";
19​
20import { CASES, type MobileBehaviorCase } from "./cases.ts";
21import { APP_ID, DeviceError, makeDevice, SCHEME } from "./device.ts";
22import { freePort, startEnvironment, uuid } from "./environment.ts";
23import { blockingResults, checkFails, resultsFor, summarize, type SampleRow } from "./grade.ts";
24import { SCENARIOS, type Pose, type ScenarioContext } from "./scenarios.ts";
25​
26const REPO_ROOT = NodePath.resolve(import.meta.dirname, "../..");
27const POSES = ["phone", "duo-closed", "duo-open", "ipad"] as const satisfies ReadonlyArray<Pose>;
28​
29/** This machine's address as the simulator sees it: the tailnet address, else the first LAN IPv4. */
30function reachableHost(): string {
31 const tailnet = NodeChildProcess.spawnSync("tailscale", ["ip", "-4"], { encoding: "utf8" });
32 const ip = tailnet.status === 0 ? tailnet.stdout.trim().split("\n")[0] : undefined;
33 if (ip) return ip;
34 const lan = Object.values(NodeOS.networkInterfaces())
35 .flatMap((entries) => entries ?? [])
36 .find((entry) => entry.family === "IPv4" && !entry.internal);
37 return lan?.address ?? "127.0.0.1";
39​
40/** Metro with the behavior probe compiled in, stopped with its process group when the scope ends. */
41const startMetro = Effect.fn("run.startMetro")(function* (host: string, out: string) {
42 const port = yield* freePort();
43 const log = NodeFS.openSync(NodePath.join(out, "metro.log"), "w");
44 yield* Effect.acquireRelease(
45 Effect.sync(() =>
46 NodeChildProcess.spawn(
47 "npx",
48 ["expo", "start", "--dev-client", "--scheme", SCHEME, "--lan", "--port", String(port)],
49 {
50 cwd: NodePath.join(REPO_ROOT, "apps/mobile"),
51 detached: true,
52 stdio: ["ignore", log, log],
53 env: {
54 ...process.env,
55 APP_VARIANT: "development",
56 CI: "1",
57 // Lazily fetched chunks sometimes arrive broken on pool emulators and throw SyntaxErrors.
58 EXPO_NO_METRO_LAZY: "1",
59 EXPO_PUBLIC_T3_BEHAVIOR_PROBE: "1",
60 REACT_NATIVE_PACKAGER_HOSTNAME: host,
61 },
62 },
63 ),
64 ),
65 (child) => Effect.sync(() => child.pid !== undefined && process.kill(-child.pid, "SIGTERM")),
66 );
67 const metro = `http://${host}:${port}`;
68 for (let attempt = 0; attempt < 120; attempt++) {
69 const ready = yield* HttpClient.get(`${metro}/status`).pipe(
70 Effect.flatMap((response) => response.text),
71 Effect.provide(FetchHttpClient.layer),
72 Effect.orElseSucceed(() => ""),
73 );
74 if (ready.includes("running")) return metro;
75 yield* Effect.sleep("1 second");
76 }
77 return yield* new DeviceError({ message: `Metro never started; see ${out}/metro.log.` });
78});
79​
80const decodeRows = (file: string): ReadonlyArray<SampleRow> =>
81 NodeFS.readFileSync(file, "utf8")
82 .split("\n")
83 .filter(Boolean)
84 .map((line) => JSON.parse(line) as SampleRow);
85​
86const command = Command.make(
87 "mobile-behavior",
88 {
89 out: Flag.String("out").pipe(Flag.withDescription("Directory for results and run state.")),
90 device: Flag.String("device").pipe(
91 Flag.withDescription(
92 "Simulator UDID; leave out for a Simlock lease, whose gateway picks it.",
93 ),
94 Flag.withDefault(""),
95 ),
96 deviceConfig: Flag.String("device-config").pipe(
97 Flag.withDescription("The --config path device_open returned for this device."),
98 ),
99 deviceSession: Flag.String("device-session").pipe(
100 Flag.withDescription("The --session name device_open returned for this device."),
101 ),
102 deviceName: Flag.String("device-name").pipe(
103 Flag.withDescription(
104 'Simulator name as Metro lists it, e.g. "iPhone 17 Pro". Leave out when this run\'s Metro serves one device.',
105 ),
106 Flag.withDefault(""),
107 ),
108 pose: Flag.Literals("pose", POSES).pipe(Flag.withDefault<Pose>("phone")),
109 label: Flag.String("label").pipe(
110 Flag.withDescription("Column name in the scoreboard; defaults to the pose."),
111 Flag.optional,
112 ),
113 cases: Flag.String("case").pipe(
114 Flag.withDescription("Comma-separated case ids."),
115 Flag.optional,
116 ),
117 samples: Flag.Int("samples").pipe(Flag.withDefault(3)),
118 baseline: Flag.String("baseline").pipe(
119 Flag.withDescription("results.jsonl from an earlier run to compare against."),
120 Flag.optional,
121 ),
122 agentDevice: Flag.String("agent-device").pipe(
123 Flag.withDefault(
124 NodePath.join(REPO_ROOT, "scripts/node_modules/agent-device/bin/agent-device.mjs"),
125 ),
126 ),
127 forgetOtherEnvironments: Flag.Boolean("forget-other-environments").pipe(
128 Flag.withDescription(
129 "Remove the app's other saved environments first. Only for a simulator kept for this eval.",
130 ),
131 Flag.withDefault(false),
132 ),
133 host: Flag.String("host").pipe(
134 Flag.withDescription(
135 "Address the simulator uses to reach this machine; defaults to the tailnet IP.",
136 ),
137 Flag.optional,
138 ),
139 },
140 Effect.fn("mobileBehavior.main")(function* (flags) {
141 const out = NodePath.resolve(flags.out);
142 // Read first: the baseline may be this --out's own results.jsonl, which the run rewrites.
143 const baseline = Option.map(flags.baseline, (file) => resultsFor(decodeRows(file), CASES));
144 NodeFS.mkdirSync(out, { recursive: true });
145 const label = Option.getOrElse(flags.label, () => flags.pose);
146 const wanted = Option.map(flags.cases, (ids) => new Set(ids.split(",").map((id) => id.trim())));
147 const selected = CASES.filter(
148 (testCase) =>
149 Option.match(wanted, { onNone: () => true, onSome: (ids) => ids.has(testCase.id) }) &&
150 (testCase.poses?.includes(flags.pose) ?? true),
151 );
152 const unknown = Option.match(wanted, {
153 onNone: () => [],
154 onSome: (ids) => [...ids].filter((id) => !CASES.some((testCase) => testCase.id === id)),
155 });
156 if (unknown.length > 0)
157 return yield* new DeviceError({ message: `Unknown case id(s): ${unknown.join(", ")}.` });
158 if (selected.length === 0) return yield* new DeviceError({ message: "No cases match." });
159 const host = Option.getOrElse(flags.host, reachableHost);
160 const startedAt = yield* Clock.currentTimeMillis;
161​
162 const env = yield* startEnvironment({ baseDir: NodePath.join(out, "env"), deviceHost: host });
163 const tag = (yield* uuid).slice(0, 4);
164 yield* Console.error(`Seeding a 60-turn thread on ${env.origin}...`);
165 const longThread = yield* env.longThread(`Long settled thread ${tag}`, 60);
166​
167 const metro = yield* startMetro(host, out);
168 const device = makeDevice({
169 agentDevice: flags.agentDevice,
170 targetArgs: [
171 "--platform",
172 "ios",
173 ...(flags.device ? ["--udid", flags.device] : []),
174 "--config",
175 flags.deviceConfig,
176 "--session",
177 flags.deviceSession,
178 ],
179 metro,
180 deviceName: flags.deviceName,
181 });
182 yield* Console.error(`Opening the dev client against ${metro}...`);
183 // agent-device answers iOS's "Open in" prompt; the flags keep dev-menu chrome off the app.
184 const metroUrl = new URL(metro);
185 const launchUrl = `${SCHEME}://expo-development-client/?url=${encodeURIComponent(metro)}&disableOnboarding=1&__expo_disable_fab=1&__expo_disable_auto_launch=1`;
186 yield* device
187 .run(
188 [
189 "open",
190 APP_ID,
191 "--relaunch",
192 "--metro-host",
193 metroUrl.hostname,
194 "--metro-port",
195 metroUrl.port,
196 "--launch-url",
197 launchUrl,
198 ],
199 240_000,
200 )
201 .pipe(Effect.retry({ times: 2 }));
202 for (let attempt = 0; ; attempt++) {
203 const loaded = yield* device
204 .evaluate("typeof __t3Behavior")
205 .pipe(Effect.orElseSucceed(() => ""));
206 if (loaded === "object") break;
207 // iOS asks before a URL opens another app; busy hosts can miss the first accept.
208 if (attempt % 5 === 0) yield* device.acceptOpenPrompt.pipe(Effect.ignore);
209 if (attempt > 120)
210 return yield* new DeviceError({
211 message:
212 "The probe never loaded. Is this a dev client built from this checkout's native fingerprint?",
213 });
214 yield* Effect.sleep("2 seconds");
215 }
216 if (flags.pose === "duo-closed" || flags.pose === "duo-open")
217 yield* device.fold(flags.pose === "duo-closed" ? "closed" : "open");
218 const forget = (ids: ReadonlyArray<string>) =>
219 device
220 .evaluate(`__t3Behavior.forgetEnvironments(${JSON.stringify(ids)})`)
221 .pipe(Effect.andThen(Effect.sleep("3 seconds")));
222 const pairing = yield* env.pairingUrl();
223 yield* device.openUrl(
224 `${SCHEME}://connections/new?pairingUrl=${encodeURIComponent(pairing)}&autoConnect=1`,
225 );
226 // Registered once pairing starts, so a stopped run never leaves its environment in the app.
227 yield* Effect.addFinalizer(() => forget([env.environmentId]).pipe(Effect.ignore));
228 const seeded = (state: { homeList: unknown; threads: Record<string, string> }) =>
229 state.homeList !== null && longThread in state.threads;
230 yield* device.waitFor("the paired environment's threads on Home", seeded, 60_000);
231 // Other saved environments keep cached threads (some stuck working) that skew status cases.
232 const others = (yield* device.state).environments.filter((id) => id !== env.environmentId);
233 if (others.length > 0 && !flags.forgetOtherEnvironments)
234 return yield* new DeviceError({
235 message: `The app has ${others.length} other saved environment(s). Use a simulator with no other connections, or pass --forget-other-environments to remove them.`,
236 });
237 if (others.length > 0) yield* forget(others);
238 const ctx: ScenarioContext = {
239 env,
240 device,
241 pose: flags.pose,
242 fixtures: { longThread },
243 };
244 const scenarios = [...new Set(selected.map((testCase) => testCase.scenario))];
245 const rows: SampleRow[] = [];
246 const resultsFile = NodeFS.openSync(NodePath.join(out, "results.jsonl"), "w");
247 for (const scenario of scenarios) {
248 const cases = selected.filter((testCase) => testCase.scenario === scenario);
249 for (let sample = 1; sample <= flags.samples; sample++) {
250 const outcome = yield* env.interruptAll().pipe(
251 Effect.andThen(env.archiveAllExcept(longThread)),
252 Effect.andThen(device.reload(seeded)),
253 Effect.andThen(SCENARIOS[scenario](ctx)),
254 Effect.map((metrics) => ({ metrics, error: undefined })),
255 Effect.catch((error) => Effect.succeed({ metrics: {}, error: error.message })),
256 // A bad probe reply or snapshot must cost one sample, not the run.
257 Effect.catchDefect((defect) => Effect.succeed({ metrics: {}, error: String(defect) })),
258 );
259 for (const testCase of cases) {
260 const failures = outcome.error
261 ? []
262 : testCase.checks.flatMap((check) => checkFails(check, outcome.metrics) ?? []);
263 const row: SampleRow = {
264 id: testCase.id,
265 device: label,
266 sample,
267 pass: outcome.error ? null : failures.length === 0,
268 failures,
269 metrics: outcome.metrics,
270 ...(outcome.error ? { error: outcome.error } : {}),
271 };
272 rows.push(row);
273 NodeFS.writeSync(resultsFile, `${JSON.stringify(row)}\n`);
274 yield* Console.error(
275 `${testCase.id} #${sample}: ${row.pass === null ? row.error : row.pass ? "pass" : `FAIL ${failures.join("; ")}`}`,
276 );
277 }
278 }
279 }
280 NodeFS.closeSync(resultsFile);
281 const minutes = Math.round(((yield* Clock.currentTimeMillis) - startedAt) / 60_000);
282 const results = resultsFor(rows, CASES);
283 const summary = summarize({
284 cases: selected as ReadonlyArray<MobileBehaviorCase>,
285 results,
286 ...Option.match(baseline, { onNone: () => ({}), onSome: (rows) => ({ baseline: rows }) }),
287 header: `# Mobile behavior: ${label}\n\n${flags.deviceName || label}, ${flags.samples} samples per case, ${minutes} min. Cells show pass or FAIL and the key metric's median.`,
288 });
289 NodeFS.writeFileSync(NodePath.join(out, "summary.md"), summary);
290 yield* Console.log(summary);
291 if (blockingResults(results, CASES).length > 0) process.exitCode = 1;
292 }, Effect.scoped),
293);
294​
295Command.run(command, { version: "0.0.0" }).pipe(
296 Effect.provide(NodeServices.layer),
297 NodeRuntime.runMain,
298);