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

mobile-behavior.ts

184 lines6.9 KB

1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off globalDate:off - Host-side device automation uses Node subprocess and filesystem APIs directly.
3​
4import * as NodeChildProcess from "node:child_process";
5import * as NodeFS from "node:fs";
6import * as NodeFSP from "node:fs/promises";
7import * as NodePath from "node:path";
8import * as NodeProcess from "node:process";
9import * as NodeReadline from "node:readline";
10import * as NodeURL from "node:url";
11​
12import { CASES } from "./mobile-behavior/cases.ts";
13import { blockingResults, resultsFor, summarize, type SampleRow } from "./mobile-behavior/grade.ts";
14import { type Device, run } from "./mobile-e2e/device.ts";
15import {
16 leaseAndInstall,
17 openPool,
18 releaseOnCrash,
19 renewWhileRunning,
20 type PoolAccess,
21} from "./mobile-behavior/pool.ts";
22import type { Pose } from "./mobile-e2e/poses.ts";
23​
24const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
25​
26/** The devices the behavior cases run on; each runs in parallel with its own server and Metro. */
27const TARGETS = [
28 { id: "iphone-18-pro", device: "iPhone 18 Pro", form: "phone", behaviorPose: "phone" },
29 { id: "ipad-pro-13", device: "iPad Pro 13-inch (M5)", form: "tablet", behaviorPose: "ipad" },
30] as const;
31type Target = (typeof TARGETS)[number];
32​
33const log = (scope: string, message: string) => NodeProcess.stderr.write(`[${scope}] ${message}\n`);
34​
35interface TargetRun {
36 readonly target: Target;
37 readonly directory: string;
38 readonly error?: string;
40​
41async function runTarget(
42 target: Target,
43 access: PoolAccess,
44 runId: string,
45 outputDirectory: string,
46 passThrough: ReadonlyArray<string>,
47): Promise<TargetRun> {
48 const { pool, config } = access;
49 const directory = NodePath.join(outputDirectory, target.id);
50 await NodeFSP.mkdir(directory, { recursive: true });
51 const pose: Pose = {
52 id: target.id,
53 platform: "ios",
54 device: target.device,
55 form: target.form,
56 appearance: "light",
57 };
58 let device: Device;
59 try {
60 device = await leaseAndInstall(pose, pool, runId, (message) => log(target.id, message));
61 } catch (error) {
62 return { target, directory, error: error instanceof Error ? error.message : String(error) };
63 }
64 const stopRenewing = renewWhileRunning(access, device.session);
65 const stopCrashGuard = releaseOnCrash(device, access);
66 try {
67 log(target.id, "running the behavior cases");
68 const child = NodeChildProcess.spawn(
69 NodeProcess.execPath,
70 [
71 "scripts/mobile-behavior/run.ts",
72 "--out",
73 directory,
74 "--label",
75 target.id,
76 "--pose",
77 target.behaviorPose,
78 "--device-config",
79 config,
80 "--device-session",
81 device.session,
82 "--agent-device",
83 pool.agentDevice,
84 ...passThrough,
85 ],
86 { cwd: REPO_ROOT, env: NodeProcess.env, stdio: ["ignore", "pipe", "pipe"] },
87 );
88 const transcript = NodeFS.createWriteStream(NodePath.join(directory, "run.log"));
89 // The scoreboard and any fatal error go to stdout, progress to stderr; the transcript keeps both.
90 NodeReadline.createInterface({ input: child.stdout }).on("line", (line) =>
91 transcript.write(`${line}\n`),
92 );
93 NodeReadline.createInterface({ input: child.stderr }).on("line", (line) => {
94 transcript.write(`${line}\n`);
95 if (/#\d+: /.test(line)) log(target.id, line);
96 });
97 const code = await new Promise<number>((resolve) =>
98 child.on("close", (exit) => resolve(exit ?? 1)),
99 );
100 transcript.end();
101 const hasResults = NodeFS.existsSync(NodePath.join(directory, "results.jsonl"));
102 return hasResults || code === 0
103 ? { target, directory }
104 : { target, directory, error: `the cases stopped (exit ${code}); see ${directory}/run.log` };
105 } finally {
106 stopRenewing();
107 stopCrashGuard();
108 await device.release();
109 }
111​
112async function main() {
113 const args = NodeProcess.argv.slice(2);
114 const values = (flag: string) =>
115 args.flatMap((arg, index) => (args[index - 1] === flag ? [arg] : []));
116 if (args.includes("--list")) {
117 for (const target of TARGETS) NodeProcess.stdout.write(`${target.id}\t${target.device}\n`);
118 for (const testCase of CASES)
119 NodeProcess.stdout.write(`${testCase.id}\t${testCase.kind}\t${testCase.source}\n`);
120 return;
121 }
122 const selected = values("--device");
123 const unknown = selected.filter((id) => !TARGETS.some((target) => target.id === id));
124 if (unknown.length) throw new Error(`Unknown device ${unknown.join(", ")}. Run with --list.`);
125 const targets = TARGETS.filter((target) => selected.length === 0 || selected.includes(target.id));
126 const passThrough = [
127 ...values("--samples").flatMap((value) => ["--samples", value]),
128 ...values("--case").flatMap((value) => ["--case", value]),
129 ];
130​
131 const runId = new Date().toISOString().replaceAll(/[:.]/g, "-");
132 const outputDirectory = NodePath.join(REPO_ROOT, "artifacts/mobile-behavior", runId);
133 await NodeFSP.mkdir(outputDirectory, { recursive: true });
134 const access = await openPool(REPO_ROOT, outputDirectory);
135 try {
136 // A cache miss builds the dev client, which can outlast a lease, so it is ready first.
137 log("behavior", "preparing the ios dev client");
138 await run(
139 NodeProcess.execPath,
140 ["scripts/mobile-native-client.ts", "ensure", "ios", "--prepare"],
141 { cwd: REPO_ROOT, timeoutMs: 1_800_000 },
142 );
143 const runs = await Promise.all(
144 targets.map((target) => runTarget(target, access, runId, outputDirectory, passThrough)),
145 );
146​
147 const rows = runs.flatMap((entry) => {
148 const file = NodePath.join(entry.directory, "results.jsonl");
149 if (!NodeFS.existsSync(file)) return [];
150 return NodeFS.readFileSync(file, "utf8")
151 .split("\n")
152 .filter(Boolean)
153 .map((line) => JSON.parse(line) as SampleRow);
154 });
155 const results = resultsFor(rows, CASES);
156 const stopped = runs.filter((entry) => entry.error);
157 const summary = summarize({
158 cases: CASES,
159 results,
160 header: [
161 `# Mobile behavior · ${runId}`,
162 "",
163 "Cells show pass or FAIL, passed/samples, and the key metric's median. `bad` cases reproduce known bugs and are expected to fail until they are fixed.",
164 ...stopped.map((entry) => `\n**${entry.target.id} did not finish:** ${entry.error}`),
165 ].join("\n"),
166 });
167 const summaryFile = NodePath.join(outputDirectory, "summary.md");
168 await NodeFSP.writeFile(summaryFile, summary);
169 const blocking = blockingResults(results, CASES);
170 for (const result of blocking)
171 log(result.device, `${result.id}: ${result.pass === null ? "incomplete" : "FAIL"}`);
172 for (const entry of stopped) log(entry.target.id, entry.error!);
173 NodeProcess.stdout.write(
174 `${JSON.stringify({ summary: summaryFile, cases: results.length, blocking: blocking.length, stopped: stopped.length })}\n`,
175 );
176 process.exitCode = blocking.length || stopped.length ? 1 : 0;
177 } finally {
178 await access.close();
179 }
181​
182if (import.meta.main) {
183 await main();