Open History to see the last commit
1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off globalJsonInEffect:off - 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 NodeFS from "node:fs";
8import * as NodePath from "node:path";
9import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
10import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
11import * as NodeServices from "@effect/platform-node/NodeServices";
12import * as Clock from "effect/Clock";
13import * as Console from "effect/Console";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import { Command, Flag } from "effect/cli";
17
18import { CASES, type MobileBehaviorCase } from "./cases.ts";
19import { DeviceError } from "./device.ts";
20import { blockingResults, checkFails, resultsFor, summarize, type SampleRow } from "./grade.ts";
21import { SCENARIOS, type Pose, type ScenarioContext } from "./scenarios.ts";
22import { reachableHost, startSession } from "./session.ts";
23
24const REPO_ROOT = NodePath.resolve(import.meta.dirname, "../..");
25const POSES = ["phone", "duo-closed", "duo-open", "ipad"] as const satisfies ReadonlyArray<Pose>;
26
27const decodeRows = (file: string): ReadonlyArray<SampleRow> =>
28 NodeFS.readFileSync(file, "utf8")
29 .split("\n")
30 .filter(Boolean)
31 .map((line) => JSON.parse(line) as SampleRow);
32
33const command = Command.make(
34 "mobile-behavior",
35 {
36 out: Flag.String("out").pipe(Flag.withDescription("Directory for results and run state.")),
37 device: Flag.String("device").pipe(
38 Flag.withDescription(
39 "Simulator UDID; leave out for a Simlock lease, whose gateway picks it.",
40 ),
41 Flag.withDefault(""),
42 ),
43 deviceConfig: Flag.String("device-config").pipe(
44 Flag.withDescription("The --config path device_open returned for this device."),
45 ),
46 deviceSession: Flag.String("device-session").pipe(
47 Flag.withDescription("The --session name device_open returned for this device."),
48 ),
49 deviceName: Flag.String("device-name").pipe(
50 Flag.withDescription(
51 'Simulator name as Metro lists it, e.g. "iPhone 17 Pro". Leave out when this run\'s Metro serves one device.',
52 ),
53 Flag.withDefault(""),
54 ),
55 pose: Flag.Literals("pose", POSES).pipe(Flag.withDefault<Pose>("phone")),
56 label: Flag.String("label").pipe(
57 Flag.withDescription("Column name in the scoreboard; defaults to the pose."),
58 Flag.optional,
59 ),
60 cases: Flag.String("case").pipe(
61 Flag.withDescription("Comma-separated case ids."),
62 Flag.optional,
63 ),
64 samples: Flag.Int("samples").pipe(Flag.withDefault(3)),
65 baseline: Flag.String("baseline").pipe(
66 Flag.withDescription("results.jsonl from an earlier run to compare against."),
67 Flag.optional,
68 ),
69 agentDevice: Flag.String("agent-device").pipe(
70 Flag.withDefault(
71 NodePath.join(REPO_ROOT, "scripts/node_modules/agent-device/bin/agent-device.mjs"),
72 ),
73 ),
74 forgetOtherEnvironments: Flag.Boolean("forget-other-environments").pipe(
75 Flag.withDescription(
76 "Remove the app's other saved environments first. Only for a simulator kept for this eval.",
77 ),
78 Flag.withDefault(false),
79 ),
80 host: Flag.String("host").pipe(
81 Flag.withDescription(
82 "Address the simulator uses to reach this machine; defaults to the tailnet IP.",
83 ),
84 Flag.optional,
85 ),
86 },
87 Effect.fn("mobileBehavior.main")(function* (flags) {
88 const out = NodePath.resolve(flags.out);
89 // Read first: the baseline may be this --out's own results.jsonl, which the run rewrites.
90 const baseline = Option.map(flags.baseline, (file) => resultsFor(decodeRows(file), CASES));
91 NodeFS.mkdirSync(out, { recursive: true });
92 const label = Option.getOrElse(flags.label, () => flags.pose);
93 const wanted = Option.map(flags.cases, (ids) => new Set(ids.split(",").map((id) => id.trim())));
94 const selected = CASES.filter(
95 (testCase) =>
96 Option.match(wanted, { onNone: () => true, onSome: (ids) => ids.has(testCase.id) }) &&
97 (testCase.poses?.includes(flags.pose) ?? true),
98 );
99 const unknown = Option.match(wanted, {
100 onNone: () => [],
101 onSome: (ids) => [...ids].filter((id) => !CASES.some((testCase) => testCase.id === id)),
102 });
103 if (unknown.length > 0)
104 return yield* new DeviceError({ message: `Unknown case id(s): ${unknown.join(", ")}.` });
105 if (selected.length === 0) return yield* new DeviceError({ message: "No cases match." });
106 const host = Option.getOrElse(flags.host, reachableHost);
107 const startedAt = yield* Clock.currentTimeMillis;
108
109 const { env, device, longThread, seeded } = yield* startSession({
110 out,
111 host,
112 agentDevice: flags.agentDevice,
113 deviceConfig: flags.deviceConfig,
114 deviceSession: flags.deviceSession,
115 device: flags.device,
116 deviceName: flags.deviceName,
117 ...(flags.pose === "duo-closed" ? { fold: "closed" as const } : {}),
118 ...(flags.pose === "duo-open" ? { fold: "open" as const } : {}),
119 forgetOtherEnvironments: flags.forgetOtherEnvironments,
120 longTurns: 60,
121 });
122 const ctx: ScenarioContext = {
123 env,
124 device,
125 pose: flags.pose,
126 fixtures: { longThread },
127 };
128 const scenarios = [...new Set(selected.map((testCase) => testCase.scenario))];
129 const rows: SampleRow[] = [];
130 const resultsFile = NodeFS.openSync(NodePath.join(out, "results.jsonl"), "w");
131 for (const scenario of scenarios) {
132 const cases = selected.filter((testCase) => testCase.scenario === scenario);
133 for (let sample = 1; sample <= flags.samples; sample++) {
134 const outcome = yield* env.interruptAll().pipe(
135 Effect.andThen(env.archiveAllExcept(longThread)),
136 Effect.andThen(device.reload(seeded)),
137 Effect.andThen(SCENARIOS[scenario](ctx)),
138 Effect.map((metrics) => ({ metrics, error: undefined })),
139 Effect.catch((error) => Effect.succeed({ metrics: {}, error: error.message })),
140 // A bad probe reply or snapshot must cost one sample, not the run.
141 Effect.catchDefect((defect) => Effect.succeed({ metrics: {}, error: String(defect) })),
142 );
143 for (const testCase of cases) {
144 const failures = outcome.error
145 ? []
146 : testCase.checks.flatMap((check) => checkFails(check, outcome.metrics) ?? []);
147 const row: SampleRow = {
148 id: testCase.id,
149 device: label,
150 sample,
151 pass: outcome.error ? null : failures.length === 0,
152 failures,
153 metrics: outcome.metrics,
154 ...(outcome.error ? { error: outcome.error } : {}),
155 };
156 rows.push(row);
157 NodeFS.writeSync(resultsFile, `${JSON.stringify(row)}\n`);
158 yield* Console.error(
159 `${testCase.id} #${sample}: ${row.pass === null ? row.error : row.pass ? "pass" : `FAIL ${failures.join("; ")}`}`,
160 );
161 }
162 }
163 }
164 NodeFS.closeSync(resultsFile);
165 const minutes = Math.round(((yield* Clock.currentTimeMillis) - startedAt) / 60_000);
166 const results = resultsFor(rows, CASES);
167 const summary = summarize({
168 cases: selected as ReadonlyArray<MobileBehaviorCase>,
169 results,
170 ...Option.match(baseline, { onNone: () => ({}), onSome: (rows) => ({ baseline: rows }) }),
171 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.`,
172 });
173 NodeFS.writeFileSync(NodePath.join(out, "summary.md"), summary);
174 yield* Console.log(summary);
175 if (blockingResults(results, CASES).length > 0) process.exitCode = 1;
176 }, Effect.scoped),
177);
178
179Command.run(command, { version: "0.0.0" }).pipe(
180 Effect.provide([NodeServices.layer, NodeCrypto.layer]),
181 NodeRuntime.runMain,
182);