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) NodeProcess.stdout.write(`${pose.id}\t${pose.device}\n`);
143 return;
144 }
145 const values = (flag: string) =>
146 args.flatMap((arg, index) => (args[index - 1] === flag ? [arg] : []));
147 const selected = values("--pose");
148 const unknown = selected.filter((id) => !POSES.some((pose) => pose.id === id));
149 if (unknown.length) throw new Error(`Unknown pose ${unknown.join(", ")}. Run with --list.`);
150 const platforms = values("--platform");
151 const poses = POSES.filter(
152 (pose) =>
153 (selected.length === 0 || selected.includes(pose.id)) &&
154 (platforms.length === 0 || platforms.includes(pose.platform)),
155 );
156 const concurrencyFlag = values("--concurrency")[0];
157 const concurrency = concurrencyFlag ? Number(concurrencyFlag) : undefined;
158 const review = !args.includes("--no-review");
159
160 const agentDeviceUrl = NodeProcess.env.SIMLOCK_AGENT_DEVICE_URL;
161 const token = NodeProcess.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
162 if (!agentDeviceUrl || !token)
163 throw new Error(
164 "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.",
165 );
166 const host = tailnetAddress();
167
168 const runId = new Date().toISOString().replaceAll(/[:.]/g, "-");
169 const outputDirectory = NodePath.join(REPO_ROOT, "artifacts/mobile-e2e", runId);
170 await NodeFSP.mkdir(outputDirectory, { recursive: true });
171 const rootDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mobile-e2e-"));
172 const workspace = await NodeFSP.realpath(outputDirectory);
173 const config = NodePath.join(rootDir, "agent-device.json");
174 await NodeFSP.writeFile(
175 config,
176 JSON.stringify({
177 daemonBaseUrl: agentDeviceUrl,
178 daemonAuthToken: token,
179 stateDir: NodePath.join(rootDir, "agent-device"),
180 }),
181 { mode: 0o600 },
182 );
183 const pool: Pool = {
184 repoRoot: REPO_ROOT,
185 agentDevice: NodePath.join(REPO_ROOT, "scripts/node_modules/agent-device/bin/agent-device.mjs"),
186 agentDeviceUrl,
187 workspace,
188 env: { ...NodeProcess.env, AGENT_DEVICE_CONFIG: config, PWD: workspace },
189 };
190
191 const servers: NodeChildProcess.ChildProcess[] = [];
192 let metro: NodeChildProcess.ChildProcess | null = null;
193 try {
194 log("e2e", "starting the fixture server");
195 const [environment] = await startShowcaseEnvironments(
196 rootDir,
197 (server) => servers.push(server),
198 SHOWCASE_ENVIRONMENTS.slice(0, 1),
199 );
200 if (!environment) throw new Error("The fixture server did not start.");
201 const metroPort = await reserveAvailablePort();
202 metro = NodeChildProcess.spawn(
203 "vp",
204 [
205 "exec",
206 "expo",
207 "start",
208 "--dev-client",
209 "--scheme",
210 "t3code-dev",
211 "--lan",
212 "--port",
213 String(metroPort),
214 ],
215 {
216 cwd: NodePath.join(REPO_ROOT, "apps/mobile"),
217 env: { ...NodeProcess.env, APP_VARIANT: "development", CI: "1" },
218 stdio: ["ignore", "ignore", "inherit"],
219 // Its own group, so stopping it also stops the expo child that owns the port.
220 detached: true,
221 },
222 );
223 await waitForPort(metroPort, "Metro", 120_000);
224 // Warm each platform's bundle once, instead of on every device at once.
225 for (const platform of new Set(poses.map((pose) => pose.platform))) {
226 log("e2e", `bundling for ${platform}`);
227 await run("curl", [
228 "-sf",
229 "-o",
230 "/dev/null",
231 `http://127.0.0.1:${metroPort}/apps/mobile/index.bundle?platform=${platform}&dev=true&minify=false`,
232 ]);
233 }
234
235 const attempt = (pose: Pose, session: string) =>
236 runPose(pose, pool, session, outputDirectory, `http://${host}:${metroPort}`, () =>
237 issuePairUrl(environment, host),
238 );
239 const runOne = async (pose: Pose) => {
240 const first = await attempt(pose, runId);
241 // A pose that failed before its first screen usually met the pool, not the app.
242 if (!first.error || first.steps.length > 0) return first;
243 log(pose.id, `retrying after: ${first.error.split("\n")[0]}`);
244 return attempt(pose, `${runId}-retry`);
245 };
246 // Each platform has its own workers, so each gets its own limit; one Mac runs every
247 // iOS simulator, and recording several at once on a shared pool times it out.
248 const byPlatform = await Promise.all(
249 (["ios", "android"] as const).map((platform) =>
250 mapConcurrent(
251 poses.filter((pose) => pose.platform === platform),
252 concurrency ?? (platform === "ios" ? 2 : 3),
253 runOne,
254 ),
255 ),
256 );
257 const results = poses.map((pose) => byPlatform.flat().find((result) => result.pose === pose)!);
258
259 const reviewed = review
260 ? await mapConcurrent(results, 4, async (result) => {
261 log(result.pose.id, "agent review");
262 const findings = await reviewPose(result, outputDirectory).catch((error) => {
263 log(result.pose.id, `review failed: ${error instanceof Error ? error.message : error}`);
264 return [];
265 });
266 return { ...result, findings };
267 })
268 : results;
269
270 const report = NodePath.join(outputDirectory, "index.html");
271 await NodeFSP.writeFile(report, renderReport(reviewed, outputDirectory));
272 await NodeFSP.writeFile(
273 NodePath.join(outputDirectory, "report.json"),
274 JSON.stringify(reviewed, null, 2),
275 );
276 for (const result of reviewed) {
277 const failures = failedChecks(result).map(
278 (item) => `${item.step}: ${item.name} (${item.detail})`,
279 );
280 log(
281 result.pose.id,
282 [result.error, ...failures].filter(Boolean).join("; ") ||
283 `passed${result.findings?.length ? `, ${result.findings.length} review findings` : ""}`,
284 );
285 }
286 const failed = reviewed.filter(poseFailed).length;
287 NodeProcess.stdout.write(
288 `${JSON.stringify({
289 report,
290 poses: reviewed.length,
291 failed,
292 findings: reviewed.reduce((count, result) => count + (result.findings?.length ?? 0), 0),
293 })}\n`,
294 );
295 process.exitCode = failed ? 1 : 0;
296 } finally {
297 if (metro?.pid) {
298 try {
299 NodeProcess.kill(-metro.pid, "SIGTERM");
300 } catch {}
301 await stopProcess(metro);
302 }
303 await Promise.all(servers.map((server) => stopProcess(server)));
304 await NodeFSP.rm(rootDir, { recursive: true, force: true });
305 }
306}
307
308if (import.meta.main) {
309 await main();
310}