Open History to see the last commit
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 NodeFSP from "node:fs/promises";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import * as NodeProcess from "node:process";
9import * as NodeURL from "node:url";
10
11import { Device, type Pool, run } from "./mobile-e2e/device.ts";
12import { runJourney, type StepResult } from "./mobile-e2e/journey.ts";
13import { POSES, type Pose } from "./mobile-e2e/poses.ts";
14import { failedChecks, poseFailed, type PoseResult, renderReport } from "./mobile-e2e/report.ts";
15import { reviewPose } from "./mobile-e2e/review.ts";
16import {
17 reserveAvailablePort,
18 startShowcaseEnvironments,
19 stopProcess,
20 waitForPort,
21} from "./mobile-showcase.ts";
22import { SHOWCASE_ENVIRONMENTS } from "./mobile-showcase-environment.ts";
23
24const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
25
26const log = (scope: string, message: string) => NodeProcess.stderr.write(`[${scope}] ${message}\n`);
27
28/** This machine's Tailscale address (100.64.0.0/10), which pool devices reach it on. */
29function tailnetAddress(): string {
30 for (const addresses of Object.values(NodeOS.networkInterfaces())) {
31 for (const address of addresses ?? []) {
32 const [first, second] = address.address.split(".").map(Number);
33 if (address.family === "IPv4" && first === 100 && second! >= 64 && second! < 128)
34 return address.address;
35 }
36 }
37 throw new Error("No Tailscale IPv4 address: pool devices reach Metro and the fixture over it.");
38}
39
40async function mapConcurrent<T, R>(
41 items: ReadonlyArray<T>,
42 limit: number,
43 task: (item: T) => Promise<R>,
44): Promise<R[]> {
45 const results: R[] = Array.from({ length: items.length });
46 let next = 0;
47 await Promise.all(
48 Array.from({ length: Math.min(limit, items.length) }, async () => {
49 while (next < items.length) {
50 const index = next++;
51 results[index] = await task(items[index]!);
52 }
53 }),
54 );
55 return results;
56}
57
58async function issuePairUrl(
59 environment: { readonly baseDir: string; readonly port: number },
60 host: string,
61) {
62 const { stdout } = await run(
63 NodeProcess.execPath,
64 [
65 "apps/server/src/bin.ts",
66 "auth",
67 "pairing",
68 "create",
69 "--base-dir",
70 environment.baseDir,
71 "--base-url",
72 `http://${host}:${environment.port}`,
73 "--ttl",
74 "15m",
75 "--json",
76 ],
77 { cwd: REPO_ROOT },
78 );
79 const { pairUrl } = JSON.parse(
80 stdout.slice(stdout.indexOf("{"), stdout.lastIndexOf("}") + 1),
81 ) as {
82 pairUrl?: string;
83 };
84 if (!pairUrl) throw new Error("The pairing command returned no pairUrl.");
85 return pairUrl;
86}
87
88async function runPose(
89 pose: Pose,
90 pool: Pool,
91 runId: string,
92 outputDirectory: string,
93 metroUrl: string,
94 pair: () => Promise<string>,
95): Promise<PoseResult> {
96 const directory = NodePath.join(outputDirectory, pose.id);
97 await NodeFSP.mkdir(directory, { recursive: true });
98 const steps: StepResult[] = [];
99 let device: Device | null = null;
100 try {
101 log(pose.id, `leasing ${pose.device}`);
102 device = await Device.lease(pose, pool, runId);
103 log(pose.id, "installing the dev client");
104 await device.install();
105 await device.prepare();
106 await device.launch(metroUrl);
107 log(pose.id, "pairing and walking the app");
108 await runJourney(device, directory, pair, steps);
109 return { pose, steps };
110 } catch (error) {
111 const message = error instanceof Error ? error.message : String(error);
112 if (!device) return { pose, steps, error: message };
113 // What the device showed when the journey stopped is usually the whole diagnosis.
114 const stopped = NodePath.join(directory, "stopped.png");
115 const shot = await device.screenshot(stopped).then(
116 () => stopped,
117 () => undefined,
118 );
119 const labels = await device.snapshot().then(
120 (snapshot) =>
121 snapshot.nodes
122 .map((node) => node.label)
123 .filter(Boolean)
124 .slice(0, 12)
125 .join(" | "),
126 () => "",
127 );
128 return {
129 pose,
130 steps,
131 error: labels ? `${message} (screen: ${labels})` : message,
132 ...(shot ? { stopped: shot } : {}),
133 };
134 } finally {
135 await device?.release();
136 }
137}
138
139async function main() {
140 const args = NodeProcess.argv.slice(2);
141 if (args.includes("--list")) {
142 for (const pose of POSES)
143 NodeProcess.stdout.write(
144 `${pose.id}\t${pose.device}${pose.pending ? `\t(pending: ${pose.pending})` : ""}\n`,
145 );
146 return;
147 }
148 const values = (flag: string) =>
149 args.flatMap((arg, index) => (args[index - 1] === flag ? [arg] : []));
150 const selected = values("--pose");
151 const unknown = selected.filter((id) => !POSES.some((pose) => pose.id === id));
152 if (unknown.length) throw new Error(`Unknown pose ${unknown.join(", ")}. Run with --list.`);
153 const platforms = values("--platform");
154 const poses = POSES.filter(
155 (pose) =>
156 (selected.length === 0 ? !pose.pending : selected.includes(pose.id)) &&
157 (platforms.length === 0 || platforms.includes(pose.platform)),
158 );
159 const concurrencyFlag = values("--concurrency")[0];
160 const concurrency = concurrencyFlag ? Number(concurrencyFlag) : undefined;
161 const review = !args.includes("--no-review");
162
163 const agentDeviceUrl = NodeProcess.env.SIMLOCK_AGENT_DEVICE_URL;
164 const token = NodeProcess.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
165 if (!agentDeviceUrl || !token)
166 throw new Error(
167 "Set SIMLOCK_AGENT_DEVICE_URL (<gateway>/v1/agent-device) and AGENT_DEVICE_DAEMON_AUTH_TOKEN (a Simlock agent token) to run on the device pool.",
168 );
169 const host = tailnetAddress();
170
171 const runId = new Date().toISOString().replaceAll(/[:.]/g, "-");
172 const outputDirectory = NodePath.join(REPO_ROOT, "artifacts/mobile-e2e", runId);
173 await NodeFSP.mkdir(outputDirectory, { recursive: true });
174 const rootDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mobile-e2e-"));
175 const workspace = await NodeFSP.realpath(outputDirectory);
176 const config = NodePath.join(rootDir, "agent-device.json");
177 await NodeFSP.writeFile(
178 config,
179 JSON.stringify({
180 daemonBaseUrl: agentDeviceUrl,
181 daemonAuthToken: token,
182 stateDir: NodePath.join(rootDir, "agent-device"),
183 }),
184 { mode: 0o600 },
185 );
186 const pool: Pool = {
187 repoRoot: REPO_ROOT,
188 agentDevice: NodePath.join(REPO_ROOT, "scripts/node_modules/agent-device/bin/agent-device.mjs"),
189 agentDeviceUrl,
190 workspace,
191 env: { ...NodeProcess.env, AGENT_DEVICE_CONFIG: config, PWD: workspace },
192 };
193
194 const servers: NodeChildProcess.ChildProcess[] = [];
195 let metro: NodeChildProcess.ChildProcess | null = null;
196 try {
197 log("e2e", "starting the fixture server");
198 const [environment] = await startShowcaseEnvironments(
199 rootDir,
200 (server) => servers.push(server),
201 SHOWCASE_ENVIRONMENTS.slice(0, 1),
202 );
203 if (!environment) throw new Error("The fixture server did not start.");
204 const metroPort = await reserveAvailablePort();
205 metro = NodeChildProcess.spawn(
206 "vp",
207 [
208 "exec",
209 "expo",
210 "start",
211 "--dev-client",
212 "--scheme",
213 "t3code-dev",
214 "--lan",
215 "--port",
216 String(metroPort),
217 ],
218 {
219 cwd: NodePath.join(REPO_ROOT, "apps/mobile"),
220 env: { ...NodeProcess.env, APP_VARIANT: "development", CI: "1" },
221 stdio: ["ignore", "ignore", "inherit"],
222 // Its own group, so stopping it also stops the expo child that owns the port.
223 detached: true,
224 },
225 );
226 await waitForPort(metroPort, "Metro", 120_000);
227 // Warm each platform's bundle once, instead of on every device at once, and have its dev
228 // client cached before any lease: a cache miss builds, which can outlast a lease.
229 for (const platform of new Set(poses.map((pose) => pose.platform))) {
230 log("e2e", `preparing the ${platform} dev client`);
231 await run(
232 NodeProcess.execPath,
233 ["scripts/mobile-native-client.ts", "ensure", platform, "--prepare"],
234 { cwd: REPO_ROOT, timeoutMs: 1_800_000 },
235 );
236 log("e2e", `bundling for ${platform}`);
237 await run("curl", [
238 "-sf",
239 "-o",
240 "/dev/null",
241 `http://127.0.0.1:${metroPort}/apps/mobile/index.bundle?platform=${platform}&dev=true&minify=false`,
242 ]);
243 }
244
245 const attempt = (pose: Pose, session: string) =>
246 runPose(pose, pool, session, outputDirectory, `http://${host}:${metroPort}`, () =>
247 issuePairUrl(environment, host),
248 );
249 const runOne = async (pose: Pose) => {
250 const first = await attempt(pose, runId);
251 // A pose that failed before its first screen usually met the pool, not the app.
252 if (!first.error || first.steps.length > 0) return first;
253 log(pose.id, `retrying after: ${first.error.split("\n")[0]}`);
254 return attempt(pose, `${runId}-retry`);
255 };
256 // Each platform has its own workers, so each gets its own limit; one Mac runs every
257 // iOS simulator, and recording several at once on a shared pool times it out.
258 const byPlatform = await Promise.all(
259 (["ios", "android"] as const).map((platform) =>
260 mapConcurrent(
261 poses.filter((pose) => pose.platform === platform),
262 concurrency ?? (platform === "ios" ? 2 : 3),
263 runOne,
264 ),
265 ),
266 );
267 const results = poses.map((pose) => byPlatform.flat().find((result) => result.pose === pose)!);
268
269 const reviewed = review
270 ? await mapConcurrent(results, 4, async (result) => {
271 log(result.pose.id, "agent review");
272 const findings = await reviewPose(result, outputDirectory).catch((error) => {
273 log(result.pose.id, `review failed: ${error instanceof Error ? error.message : error}`);
274 return [];
275 });
276 return { ...result, findings };
277 })
278 : results;
279
280 const report = NodePath.join(outputDirectory, "index.html");
281 await NodeFSP.writeFile(report, renderReport(reviewed, outputDirectory));
282 await NodeFSP.writeFile(
283 NodePath.join(outputDirectory, "report.json"),
284 JSON.stringify(reviewed, null, 2),
285 );
286 for (const result of reviewed) {
287 const failures = failedChecks(result).map(
288 (item) => `${item.step}: ${item.name} (${item.detail})`,
289 );
290 log(
291 result.pose.id,
292 [result.error, ...failures].filter(Boolean).join("; ") ||
293 `passed${result.findings?.length ? `, ${result.findings.length} review findings` : ""}`,
294 );
295 }
296 const failed = reviewed.filter(poseFailed).length;
297 NodeProcess.stdout.write(
298 `${JSON.stringify({
299 report,
300 poses: reviewed.length,
301 failed,
302 findings: reviewed.reduce((count, result) => count + (result.findings?.length ?? 0), 0),
303 })}\n`,
304 );
305 process.exitCode = failed ? 1 : 0;
306 } finally {
307 if (metro?.pid) {
308 try {
309 NodeProcess.kill(-metro.pid, "SIGTERM");
310 } catch {}
311 await stopProcess(metro);
312 }
313 await Promise.all(servers.map((server) => stopProcess(server)));
314 await NodeFSP.rm(rootDir, { recursive: true, force: true });
315 }
316}
317
318if (import.meta.main) {
319 await main();
320}