Open History to see the last commit
1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - Host-side simulator automation uses Node subprocess and timing 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 { startShowcaseEnvironments, stopProcess, waitForPort } from "./mobile-showcase.ts";
12import { SHOWCASE_ENVIRONMENTS } from "./mobile-showcase-environment.ts";
13
14const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
15const AGENT_DEVICE = NodePath.join(
16 REPO_ROOT,
17 "scripts/node_modules/agent-device/bin/agent-device.mjs",
18);
19const BUNDLE_ID = "com.t3tools.t3code.dev";
20const METRO_PORT = 8081;
21// Persistent so the XCTest runner agent-device builds per simulator survives between runs.
22const AGENT_DEVICE_STATE = NodePath.join(NodeOS.homedir(), ".cache/t3code/mobile-e2e/agent-device");
23
24export interface E2eDevice {
25 readonly id: string;
26 readonly platform: "ios";
27 readonly deviceType: string;
28 readonly runtime: string;
29}
30
31const ios = (id: string, deviceType: string): E2eDevice => ({
32 id,
33 platform: "ios",
34 deviceType: `com.apple.CoreSimulator.SimDeviceType.${deviceType}`,
35 runtime: "com.apple.CoreSimulator.SimRuntime.iOS-27-0",
36});
37
38export const DEVICES: ReadonlyArray<E2eDevice> = [
39 ios("iphone-se", "iPhone-SE-3rd-generation"),
40 ios("iphone-13-mini", "iPhone-13-mini"),
41 ios("iphone-17", "iPhone-17"),
42 ios("iphone-17-pro", "iPhone-17-Pro"),
43 ios("iphone-17-pro-max", "iPhone-17-Pro-Max"),
44 ios("iphone-air", "iPhone-Air"),
45];
46
47interface Rect {
48 readonly x: number;
49 readonly y: number;
50 readonly width: number;
51 readonly height: number;
52}
53
54export interface SnapshotNode {
55 readonly type?: string;
56 readonly role?: string;
57 readonly identifier?: string;
58 readonly label?: string;
59 readonly rect?: Rect;
60}
61
62export interface Snapshot {
63 readonly nodes: ReadonlyArray<SnapshotNode>;
64 readonly viewport: { readonly width: number; readonly height: number };
65}
66
67export interface Check {
68 readonly name: string;
69 readonly pass: boolean;
70 readonly detail: string;
71}
72
73interface StepResult {
74 readonly name: string;
75 readonly checks: ReadonlyArray<Check>;
76 readonly screenshot?: string | undefined;
77 readonly video?: string | undefined;
78 readonly contactSheet?: string | undefined;
79 readonly lagFrame?: string | undefined;
80 readonly samples: number;
81}
82
83interface DeviceResult {
84 readonly device: E2eDevice;
85 readonly label: string;
86 readonly steps: ReadonlyArray<StepResult>;
87 readonly error?: string;
88}
89
90const onScreen = (node: SnapshotNode, snapshot: Snapshot) =>
91 node.rect !== undefined &&
92 node.rect.width > 0 &&
93 node.rect.height > 0 &&
94 node.rect.x < snapshot.viewport.width &&
95 node.rect.y < snapshot.viewport.height &&
96 node.rect.x + node.rect.width > 0 &&
97 node.rect.y + node.rect.height > 0;
98
99const find = (snapshot: Snapshot, match: (node: SnapshotNode) => boolean) =>
100 snapshot.nodes.filter((node) => match(node) && onScreen(node, snapshot));
101
102export const chrome = (snapshot: Snapshot) => ({
103 tabBar: find(snapshot, (node) => node.type === "TabBar")[0],
104 navigationBar: find(snapshot, (node) => node.type === "NavigationBar")[0],
105 backButton: find(snapshot, (node) => node.identifier === "BackButton")[0],
106 send: find(snapshot, (node) => node.type === "Button" && node.label === "Send")[0],
107 newChat: find(snapshot, (node) => node.type === "Button" && node.label === "New chat")[0],
108 // Thread rows are full-width context-menu wrappers; the filter pills are narrow ones.
109 threadRows: find(
110 snapshot,
111 (node) =>
112 node.role === "MenuView" &&
113 Boolean(node.label) &&
114 (node.rect?.width ?? 0) >= snapshot.viewport.width * 0.9,
115 ),
116});
117
118const check = (name: string, pass: boolean, detail: string): Check => ({ name, pass, detail });
119const describeRect = (rect: Rect | undefined) =>
120 rect
121 ? `${Math.round(rect.x)},${Math.round(rect.y)} ${Math.round(rect.width)}×${Math.round(rect.height)}`
122 : "absent";
123const inside = (rect: Rect, snapshot: Snapshot) =>
124 rect.x >= 0 &&
125 rect.y >= 0 &&
126 rect.x + rect.width <= snapshot.viewport.width + 0.5 &&
127 rect.y + rect.height <= snapshot.viewport.height + 0.5;
128
129export function homeChecks(snapshot: Snapshot): Check[] {
130 const { tabBar, newChat } = chrome(snapshot);
131 return [
132 check("tab bar visible", tabBar !== undefined, describeRect(tabBar?.rect)),
133 check(
134 "tab bar inside the screen",
135 tabBar?.rect !== undefined && inside(tabBar.rect, snapshot),
136 describeRect(tabBar?.rect),
137 ),
138 check("new chat button visible", newChat !== undefined, describeRect(newChat?.rect)),
139 ];
140}
141
142export function threadChecks(snapshot: Snapshot, samples: ReadonlyArray<Snapshot>): Check[] {
143 const { tabBar, backButton, send } = chrome(snapshot);
144 const overlapping = samples.filter((sample) => {
145 const state = chrome(sample);
146 return state.backButton !== undefined && state.tabBar !== undefined;
147 }).length;
148 return [
149 check("tab bar hidden", tabBar === undefined, describeRect(tabBar?.rect)),
150 check("back button visible", backButton !== undefined, describeRect(backButton?.rect)),
151 check(
152 "composer inside the screen",
153 send?.rect !== undefined && inside(send.rect, snapshot),
154 describeRect(send?.rect),
155 ),
156 check(
157 "no tabs over the entering thread",
158 overlapping === 0,
159 `${overlapping} of ${samples.length} transition samples showed tabs with a Back button`,
160 ),
161 ];
162}
163
164export function backChecks(snapshot: Snapshot, samples: ReadonlyArray<Snapshot>): Check[] {
165 const listWithoutTabs = samples.filter((sample) => {
166 const state = chrome(sample);
167 return (
168 state.backButton === undefined && state.newChat !== undefined && state.tabBar === undefined
169 );
170 }).length;
171 return [
172 ...homeChecks(snapshot),
173 check(
174 "tabs return with the list",
175 listWithoutTabs === 0,
176 `${listWithoutTabs} of ${samples.length} transition samples showed the list without tabs`,
177 ),
178 ];
179}
180
181/** Downsampled grayscale crops of one region, one per video frame (or one for a PNG). */
182async function grayFrames(input: string, region: Rect, scale: number): Promise<Uint8Array[]> {
183 const even = (value: number) => Math.max(2, Math.floor(value / 2) * 2);
184 const [x, y, width, height] = [
185 Math.round(region.x * scale),
186 Math.round(region.y * scale),
187 even(region.width * scale),
188 even(region.height * scale),
189 ];
190 const [outWidth, outHeight] = [even(width / 6), even(height / 6)];
191 const bytes = await new Promise<Buffer>((resolve, reject) => {
192 const child = NodeChildProcess.spawn(
193 "ffmpeg",
194 [
195 "-v",
196 "error",
197 "-i",
198 input,
199 // One output frame per recorded frame, so indices match select=eq(n,…) for evidence.
200 "-fps_mode",
201 "passthrough",
202 "-vf",
203 `crop=${width}:${height}:${x}:${y},scale=${outWidth}:${outHeight},format=gray`,
204 "-f",
205 "rawvideo",
206 "-",
207 ],
208 { stdio: ["ignore", "pipe", "pipe"] },
209 );
210 const chunks: Buffer[] = [];
211 let stderr = "";
212 child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk));
213 child.stderr.on("data", (chunk) => (stderr += chunk));
214 child.on("error", reject);
215 child.on("close", (code) =>
216 code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`ffmpeg failed: ${stderr}`)),
217 );
218 });
219 const size = outWidth * outHeight;
220 return Array.from({ length: Math.floor(bytes.length / size) }, (_, index) =>
221 bytes.subarray(index * size, (index + 1) * size),
222 );
223}
224
225const distance = (a: Uint8Array, b: Uint8Array) => {
226 let sum = 0;
227 for (let index = 0; index < a.length; index++) sum += Math.abs(a[index]! - b[index]!);
228 return sum / a.length;
229};
230
231/** How far a region has moved from its origin toward its destination look, 0 to 1. */
232export interface FrameProgress {
233 readonly nav: number;
234 readonly chrome: number;
235}
236
237/**
238 * A frame lags when the navigation bar is well into the transition while the tab bar region
239 * still looks like the origin: tabs lingering over an entering thread, or a returned list drawn
240 * before its tabs.
241 */
242export const chromeLags = (frame: FrameProgress) => frame.nav > 0.3 && frame.chrome < 0.4;
243// One lagging frame is capture jitter; a regression lasts several.
244const LAG_FRAME_LIMIT = 2;
245
246const progress = (origin: number, destination: number) =>
247 origin + destination === 0 ? 0 : origin / (origin + destination);
248
249async function chromeLagFrames(input: {
250 readonly video: string;
251 readonly origin: string;
252 readonly destination: string;
253 readonly nav: Rect;
254 readonly chrome: Rect;
255 readonly scale: number;
256}) {
257 const [
258 navFrames,
259 chromeFrames,
260 [navOrigin],
261 [navDestination],
262 [chromeOrigin],
263 [chromeDestination],
264 ] = await Promise.all([
265 grayFrames(input.video, input.nav, input.scale),
266 grayFrames(input.video, input.chrome, input.scale),
267 grayFrames(input.origin, input.nav, input.scale),
268 grayFrames(input.destination, input.nav, input.scale),
269 grayFrames(input.origin, input.chrome, input.scale),
270 grayFrames(input.destination, input.chrome, input.scale),
271 ]);
272 if (!navOrigin || !navDestination || !chromeOrigin || !chromeDestination)
273 throw new Error("Could not read the reference screenshots.");
274 const verdicts = navFrames.map((nav, index) => {
275 const chrome = chromeFrames[index]!;
276 return {
277 nav: progress(distance(nav, navOrigin), distance(nav, navDestination)),
278 chrome: progress(distance(chrome, chromeOrigin), distance(chrome, chromeDestination)),
279 };
280 });
281 return verdicts.flatMap((verdict, index) => (chromeLags(verdict) ? [index] : []));
282}
283
284async function saveFrame(video: string, index: number, path: string) {
285 await run("ffmpeg", [
286 "-v",
287 "error",
288 "-y",
289 "-i",
290 video,
291 "-vf",
292 `select=eq(n\\,${index})`,
293 "-frames:v",
294 "1",
295 path,
296 ]);
297}
298
299async function lagCheck(
300 name: string,
301 input: Parameters<typeof chromeLagFrames>[0],
302 evidence: string,
303): Promise<{ check: Check; frame?: string }> {
304 const lagging = await chromeLagFrames(input);
305 if (lagging.length < LAG_FRAME_LIMIT)
306 return { check: check(name, true, `${lagging.length} lagging video frames`) };
307 await saveFrame(input.video, lagging[0]!, evidence);
308 return {
309 check: check(name, false, `${lagging.length} video frames (first #${lagging[0]})`),
310 frame: evidence,
311 };
312}
313
314function run(
315 command: string,
316 args: ReadonlyArray<string>,
317 options: { readonly env?: NodeJS.ProcessEnv; readonly allowFailure?: boolean } = {},
318): Promise<{ readonly code: number; readonly stdout: string; readonly stderr: string }> {
319 return new Promise((resolve, reject) => {
320 const child = NodeChildProcess.spawn(command, args, {
321 cwd: REPO_ROOT,
322 env: options.env ?? NodeProcess.env,
323 stdio: ["ignore", "pipe", "pipe"],
324 });
325 let stdout = "";
326 let stderr = "";
327 child.stdout.on("data", (chunk) => (stdout += chunk));
328 child.stderr.on("data", (chunk) => (stderr += chunk));
329 child.on("error", reject);
330 child.on("close", (code) => {
331 if (code !== 0 && !options.allowFailure)
332 reject(new Error(`${command} ${args.join(" ")} failed (${code}): ${stderr || stdout}`));
333 else resolve({ code: code ?? 1, stdout, stderr });
334 });
335 });
336}
337
338const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
339
340class Device {
341 readonly spec: E2eDevice;
342 readonly udid: string;
343
344 constructor(spec: E2eDevice, udid: string) {
345 this.spec = spec;
346 this.udid = udid;
347 }
348
349 async agent(args: ReadonlyArray<string>): Promise<Record<string, unknown>> {
350 const { stdout } = await run(
351 NodeProcess.execPath,
352 [
353 AGENT_DEVICE,
354 ...args,
355 "--platform",
356 "ios",
357 "--udid",
358 this.udid,
359 "--session",
360 `t3-e2e-${this.spec.id}`,
361 "--json",
362 ],
363 {
364 env: { ...NodeProcess.env, AGENT_DEVICE_STATE_DIR: AGENT_DEVICE_STATE },
365 allowFailure: true,
366 },
367 );
368 const parsed = JSON.parse(stdout) as {
369 success: boolean;
370 data?: Record<string, unknown>;
371 error?: { message: string };
372 };
373 if (!parsed.success) throw new Error(`agent-device ${args[0]}: ${parsed.error?.message}`);
374 return parsed.data ?? {};
375 }
376
377 async snapshot(): Promise<Snapshot> {
378 return (await this.agent(["snapshot"])) as unknown as Snapshot;
379 }
380
381 async waitFor(predicate: (snapshot: Snapshot) => boolean, label: string, timeoutMs = 60_000) {
382 const deadline = Date.now() + timeoutMs;
383 let last: Snapshot | null = null;
384 while (Date.now() < deadline) {
385 last = await this.snapshot().catch(() => null);
386 if (last && predicate(last)) return last;
387 await delay(500);
388 }
389 throw new Error(`${this.spec.id}: timed out waiting for ${label}`);
390 }
391
392 /** Open a URL the way a user would; iOS asks before opening a custom scheme from another app. */
393 async openUrl(url: string) {
394 await run("xcrun", ["simctl", "openurl", this.udid, url]);
395 await delay(1_500);
396 await this.agent(["alert", "accept"]).catch(() => undefined);
397 }
398
399 async screenshot(path: string) {
400 await run("xcrun", ["simctl", "io", this.udid, "screenshot", path]);
401 }
402
403 /** Run an action while recording and sampling the accessibility tree until the screen settles. */
404 async transition(directory: string, name: string, action: () => Promise<unknown>) {
405 const video = NodePath.join(directory, `${name}.mp4`);
406 await this.agent(["record", "start", video, "--hide-touches"]);
407 const samples: Snapshot[] = [];
408 const sampling = { active: true };
409 const sampler = (async () => {
410 while (sampling.active) {
411 const sample = await this.snapshot().catch(() => null);
412 if (sample) samples.push(sample);
413 }
414 })();
415 try {
416 await action();
417 await delay(2_000);
418 } finally {
419 sampling.active = false;
420 await sampler;
421 await this.agent(["record", "stop"]).catch(() => undefined);
422 }
423 const contactSheet = NodePath.join(directory, `${name}-frames.png`);
424 const sheet = await run(
425 NodeProcess.execPath,
426 [AGENT_DEVICE, "record", "contact-sheet", video, "--out", contactSheet],
427 {
428 env: { ...NodeProcess.env, AGENT_DEVICE_STATE_DIR: AGENT_DEVICE_STATE },
429 allowFailure: true,
430 },
431 );
432 return { samples, video, contactSheet: sheet.code === 0 ? contactSheet : undefined };
433 }
434}
435
436/** Screenshot pixels per snapshot point (3 on most iPhones). */
437async function screenshotScale(path: string, snapshot: Snapshot): Promise<number> {
438 const { stdout } = await run("ffprobe", [
439 "-v",
440 "error",
441 "-select_streams",
442 "v:0",
443 "-show_entries",
444 "stream=width",
445 "-of",
446 "csv=p=0",
447 path,
448 ]);
449 return Number(stdout.trim()) / snapshot.viewport.width;
450}
451
452async function ensureSimulator(spec: E2eDevice): Promise<string> {
453 const name = `T3 E2E ${spec.id}`;
454 const listing = JSON.parse(
455 (await run("xcrun", ["simctl", "list", "devices", "available", "-j"])).stdout,
456 ) as { devices: Record<string, ReadonlyArray<{ udid: string; name: string; state: string }>> };
457 const existing = (listing.devices[spec.runtime] ?? []).find((device) => device.name === name);
458 const udid =
459 existing?.udid ??
460 (await run("xcrun", ["simctl", "create", name, spec.deviceType, spec.runtime])).stdout.trim();
461 if (existing?.state !== "Booted")
462 await run("xcrun", ["simctl", "boot", udid], { allowFailure: true });
463 await run("xcrun", ["simctl", "bootstatus", udid, "-b"]);
464 await run("xcrun", ["simctl", "ui", udid, "appearance", "light"]);
465 await run("xcrun", [
466 "simctl",
467 "status_bar",
468 udid,
469 "override",
470 "--time",
471 "9:41",
472 "--batteryState",
473 "charged",
474 "--batteryLevel",
475 "100",
476 ]);
477 return udid;
478}
479
480function lanAddress(): string {
481 for (const addresses of Object.values(NodeOS.networkInterfaces())) {
482 for (const address of addresses ?? []) {
483 if (address.family === "IPv4" && !address.internal && !address.address.startsWith("169.254."))
484 return address.address;
485 }
486 }
487 throw new Error("No LAN IPv4 address for the simulator to reach Metro.");
488}
489
490async function runDevice(
491 spec: E2eDevice,
492 outputDirectory: string,
493 environment: { readonly baseDir: string; readonly port: number },
494 metroHost: string,
495): Promise<DeviceResult> {
496 const steps: StepResult[] = [];
497 const directory = NodePath.join(outputDirectory, spec.id);
498 await NodeFSP.mkdir(directory, { recursive: true });
499 try {
500 const udid = await ensureSimulator(spec);
501 const device = new Device(spec, udid);
502 // A fresh install drops connections paired by earlier runs; the cached client reinstalls in seconds.
503 await run("xcrun", ["simctl", "uninstall", udid, BUNDLE_ID], { allowFailure: true });
504 log(spec.id, "installing the dev client");
505 await run(NodeProcess.execPath, ["scripts/mobile-native-client.ts", "ensure", "ios", udid], {
506 env: { ...NodeProcess.env, T3_NATIVE_CLIENT_CACHE: NodeProcess.env.T3_NATIVE_CLIENT_CACHE },
507 });
508 const metroUrl = encodeURIComponent(`http://${metroHost}:${METRO_PORT}`);
509 await device.openUrl(
510 `t3code-dev://expo-development-client/?url=${metroUrl}&disableOnboarding=1&disableFab=1&disableAutoLaunch=1`,
511 );
512 // Snapshots read through an agent-device app session; open attaches one to the running app.
513 await device.agent(["open", BUNDLE_ID]);
514 // The app ignores the pairing link until its JS has loaded and shown the workspace.
515 await device.waitFor(
516 (snapshot) => chrome(snapshot).newChat !== undefined,
517 "the app to load",
518 120_000,
519 );
520 const paired = (snapshot: Snapshot) =>
521 chrome(snapshot).tabBar !== undefined && chrome(snapshot).threadRows.length > 0;
522 let home: Snapshot | null = null;
523 for (let attempt = 1; attempt <= 2 && !home; attempt++) {
524 log(spec.id, attempt === 1 ? "pairing" : "pairing again");
525 const pairing = new URLSearchParams({
526 pairingUrl: await issuePairUrl(environment),
527 autoConnect: "1",
528 });
529 await device.openUrl(`t3code-dev://connections/new?${pairing}`);
530 home = await device.waitFor(paired, "the paired thread list", 45_000).catch(() => null);
531 }
532 if (!home) throw new Error("The app did not show the fixture threads after pairing.");
533 await delay(1_000);
534 const homeShot = NodePath.join(directory, "home.png");
535 await device.screenshot(homeShot);
536 steps.push({ name: "home", checks: homeChecks(home), screenshot: homeShot, samples: 0 });
537
538 log(spec.id, "opening a thread");
539 const row = chrome(home).threadRows[0];
540 if (!row?.label) throw new Error("No thread row to open.");
541 const opened = await device.transition(directory, "open-thread", () =>
542 device.agent(["press", `label=${JSON.stringify(row.label)}`]),
543 );
544 const thread = await device.waitFor(
545 (snapshot) => chrome(snapshot).backButton !== undefined,
546 "the thread screen",
547 );
548 const threadShot = NodePath.join(directory, "thread.png");
549 await device.screenshot(threadShot);
550 const { tabBar, navigationBar } = chrome(home);
551 const scale = await screenshotScale(homeShot, home);
552 const regions =
553 tabBar?.rect && navigationBar?.rect ? { nav: navigationBar.rect, chrome: tabBar.rect } : null;
554 const openLag = regions
555 ? await lagCheck(
556 "no tabs over the entering thread (video)",
557 { video: opened.video, origin: homeShot, destination: threadShot, scale, ...regions },
558 NodePath.join(directory, "open-thread-lag.png"),
559 )
560 : null;
561 steps.push({
562 name: "open thread",
563 checks: [...threadChecks(thread, opened.samples), ...(openLag ? [openLag.check] : [])],
564 lagFrame: openLag?.frame,
565 screenshot: threadShot,
566 video: opened.video,
567 contactSheet: opened.contactSheet,
568 samples: opened.samples.length,
569 });
570
571 log(spec.id, "going back");
572 const back = await device.transition(directory, "back", () =>
573 device.agent(["press", "id=BackButton"]),
574 );
575 const list = await device.waitFor(
576 (snapshot) => chrome(snapshot).backButton === undefined,
577 "the thread list",
578 );
579 const backShot = NodePath.join(directory, "back.png");
580 await device.screenshot(backShot);
581 const backLag = regions
582 ? await lagCheck(
583 "tabs return with the list (video)",
584 { video: back.video, origin: threadShot, destination: backShot, scale, ...regions },
585 NodePath.join(directory, "back-lag.png"),
586 )
587 : null;
588 steps.push({
589 name: "back",
590 checks: [...backChecks(list, back.samples), ...(backLag ? [backLag.check] : [])],
591 lagFrame: backLag?.frame,
592 screenshot: backShot,
593 video: back.video,
594 contactSheet: back.contactSheet,
595 samples: back.samples.length,
596 });
597 return { device: spec, label: spec.id, steps };
598 } catch (error) {
599 return {
600 device: spec,
601 label: spec.id,
602 steps,
603 error: error instanceof Error ? error.message : String(error),
604 };
605 }
606}
607
608async function issuePairUrl(environment: { readonly baseDir: string; readonly port: number }) {
609 const { stdout } = await run(NodeProcess.execPath, [
610 "apps/server/src/bin.ts",
611 "auth",
612 "pairing",
613 "create",
614 "--base-dir",
615 environment.baseDir,
616 "--base-url",
617 `http://127.0.0.1:${environment.port}`,
618 "--ttl",
619 "15m",
620 "--json",
621 ]);
622 const { pairUrl } = JSON.parse(
623 stdout.slice(stdout.indexOf("{"), stdout.lastIndexOf("}") + 1),
624 ) as {
625 pairUrl?: string;
626 };
627 if (!pairUrl) throw new Error("The pairing command returned no pairUrl.");
628 return pairUrl;
629}
630
631const log = (scope: string, message: string) => NodeProcess.stderr.write(`[${scope}] ${message}\n`);
632
633const escapeHtml = (value: string) =>
634 value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
635
636function renderReport(results: ReadonlyArray<DeviceResult>, outputDirectory: string): string {
637 const relative = (path: string | undefined) =>
638 path ? escapeHtml(NodePath.relative(outputDirectory, path)) : "";
639 const rows = results
640 .map((result) => {
641 const steps = result.steps
642 .map((step) => {
643 const checks = step.checks
644 .map(
645 (item) =>
646 `<li class="${item.pass ? "pass" : "fail"}">${item.pass ? "✓" : "✗"} ${escapeHtml(item.name)} <small>${escapeHtml(item.detail)}</small></li>`,
647 )
648 .join("");
649 const media = [
650 step.screenshot
651 ? `<a href="${relative(step.screenshot)}"><img src="${relative(step.screenshot)}"></a>`
652 : "",
653 step.lagFrame
654 ? `<a href="${relative(step.lagFrame)}"><img class="lag" src="${relative(step.lagFrame)}"></a>`
655 : "",
656 step.contactSheet
657 ? `<a href="${relative(step.contactSheet)}">transition frames</a>`
658 : "",
659 step.video ? `<a href="${relative(step.video)}">video</a>` : "",
660 ].join(" ");
661 return `<td><h3>${escapeHtml(step.name)}</h3><ul>${checks}</ul>${media}</td>`;
662 })
663 .join("");
664 const error = result.error ? `<td class="fail">${escapeHtml(result.error)}</td>` : "";
665 return `<tr><th>${escapeHtml(result.label)}</th>${steps}${error}</tr>`;
666 })
667 .join("");
668 const failures = results.filter(
669 (result) => result.error || result.steps.some((step) => step.checks.some((item) => !item.pass)),
670 ).length;
671 return `<!doctype html><meta charset="utf-8"><title>Mobile E2E</title>
672<style>body{font:14px system-ui;margin:24px}table{border-collapse:collapse}td,th{border:1px solid #ddd;padding:8px;vertical-align:top}img{width:180px;display:block;margin:6px 0}img.lag{outline:3px solid #b42318}.pass{color:#16794a}.fail{color:#b42318}ul{padding-left:16px;margin:4px 0}small{color:#666}</style>
673<h1>Mobile E2E · ${failures === 0 ? "all devices passed" : `${failures} device(s) failed`}</h1>
674<table>${rows}</table>`;
675}
676
677async function main() {
678 const args = NodeProcess.argv.slice(2);
679 if (args.includes("--list")) {
680 for (const device of DEVICES) NodeProcess.stdout.write(`${device.id}\n`);
681 return;
682 }
683 const selected = args.flatMap((arg, index) => (args[index - 1] === "--device" ? [arg] : []));
684 const devices = selected.length
685 ? DEVICES.filter((device) => selected.includes(device.id))
686 : DEVICES;
687 const unknown = selected.filter((id) => !DEVICES.some((device) => device.id === id));
688 if (unknown.length) throw new Error(`Unknown device ${unknown.join(", ")}. Run with --list.`);
689 const concurrencyArg = args[args.indexOf("--concurrency") + 1];
690 const concurrency = args.includes("--concurrency") ? Number(concurrencyArg) : 3;
691
692 const stamp = new Date().toISOString().replaceAll(":", "-");
693 const outputDirectory = NodePath.join(REPO_ROOT, "artifacts/mobile-e2e", stamp);
694 await NodeFSP.mkdir(outputDirectory, { recursive: true });
695 const rootDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mobile-e2e-"));
696 const servers: NodeChildProcess.ChildProcess[] = [];
697 let metro: NodeChildProcess.ChildProcess | null = null;
698 try {
699 log("e2e", "starting the fixture server");
700 const [environment] = await startShowcaseEnvironments(
701 rootDir,
702 (server) => servers.push(server),
703 SHOWCASE_ENVIRONMENTS.slice(0, 1),
704 );
705 if (!environment) throw new Error("The fixture server did not start.");
706 const metroHost = lanAddress();
707 metro = NodeChildProcess.spawn(
708 "vp",
709 [
710 "exec",
711 "expo",
712 "start",
713 "--dev-client",
714 "--scheme",
715 "t3code-dev",
716 "--lan",
717 "--port",
718 String(METRO_PORT),
719 ],
720 {
721 cwd: NodePath.join(REPO_ROOT, "apps/mobile"),
722 env: { ...NodeProcess.env, APP_VARIANT: "development", CI: "1" },
723 stdio: ["ignore", "ignore", "inherit"],
724 // Its own group, so stopping it also stops the expo child that owns the port.
725 detached: true,
726 },
727 );
728 await waitForPort(METRO_PORT, "Metro", 120_000);
729 await run("curl", [
730 "-sf",
731 "-o",
732 "/dev/null",
733 `http://127.0.0.1:${METRO_PORT}/apps/mobile/index.bundle?platform=ios&dev=true&minify=false`,
734 ]);
735
736 // The first install may build; later ones reuse its artifact.
737 const results: DeviceResult[] = [];
738 const [first, ...rest] = devices;
739 if (first) results.push(await runDevice(first, outputDirectory, environment, metroHost));
740 for (let index = 0; index < rest.length; index += concurrency) {
741 results.push(
742 ...(await Promise.all(
743 rest
744 .slice(index, index + concurrency)
745 .map((device) => runDevice(device, outputDirectory, environment, metroHost)),
746 )),
747 );
748 }
749 const report = NodePath.join(outputDirectory, "index.html");
750 await NodeFSP.writeFile(report, renderReport(results, outputDirectory));
751 await NodeFSP.writeFile(
752 NodePath.join(outputDirectory, "report.json"),
753 JSON.stringify(results, null, 2),
754 );
755 const failed = results.filter(
756 (result) =>
757 result.error || result.steps.some((step) => step.checks.some((item) => !item.pass)),
758 );
759 for (const result of results) {
760 const failures = result.steps.flatMap((step) =>
761 step.checks
762 .filter((item) => !item.pass)
763 .map((item) => `${step.name}: ${item.name} (${item.detail})`),
764 );
765 log(result.label, result.error ?? (failures.length ? failures.join("; ") : "passed"));
766 }
767 NodeProcess.stdout.write(
768 `${JSON.stringify({ report, devices: results.length, failed: failed.length })}\n`,
769 );
770 process.exitCode = failed.length ? 1 : 0;
771 } finally {
772 if (metro?.pid) {
773 try {
774 process.kill(-metro.pid, "SIGTERM");
775 } catch {}
776 await stopProcess(metro);
777 }
778 await Promise.all(servers.map((server) => stopProcess(server)));
779 await NodeFSP.rm(rootDir, { recursive: true, force: true });
780 }
781}
782
783if (import.meta.main) {
784 await main();
785}