The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,683 lines 55.3 KB
Raw
1 #!/usr/bin/env node
2 // @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - Host-side simulator and emulator automation uses Node subprocess and timing APIs directly.
3
4 import * as NodeChildProcess from "node:child_process";
5 import * as NodeFSP from "node:fs/promises";
6 import * as NodeNet from "node:net";
7 import * as NodeOS from "node:os";
8 import * as NodePath from "node:path";
9 import * as NodeProcess from "node:process";
10 import * as NodeURL from "node:url";
11
12 import { PNG } from "pngjs";
13
14 import showcaseConfig, {
15 type ShowcaseAppearance,
16 type ShowcaseAndroidDevice,
17 type ShowcaseConfig,
18 type ShowcaseDevice,
19 type ShowcaseIosDevice,
20 type ShowcaseStoreAssetSpec,
21 SHOWCASE_SCENES,
22 type ShowcaseScene,
23 SHOWCASE_THEMES,
24 type ShowcaseTheme,
25 } from "./mobile-showcase.config.ts";
26 import {
27 SHOWCASE_ENVIRONMENTS,
28 SHOWCASE_PROJECTS,
29 SHOWCASE_THREADS,
30 seedShowcaseEnvironment,
31 } from "./mobile-showcase-environment.ts";
32
33 const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
34 const MOBILE_ROOT = NodePath.join(REPO_ROOT, "apps/mobile");
35 const ANDROID_PACKAGE = "com.t3tools.t3code";
36 const APP_SCHEME = "t3code";
37 // Manifest flags update expo-dev-launcher preferences before loading, hiding dev chrome in captures.
38 const DEV_CLIENT_LAUNCH_FLAGS = "disableOnboarding=1&disableFab=1&disableAutoLaunch=1";
39 const IOS_READY_FILENAME = "T3ShowcaseReadyScene";
40 const SERVER_HOST = "0.0.0.0";
41 const IOS_SIMULATOR_ARCH = NodeProcess.arch === "arm64" ? "arm64" : "x86_64";
42 const IOS_APP_PATH = NodePath.join(
43 MOBILE_ROOT,
44 ".showcase/ios-derived-data/Build/Products/Debug-iphonesimulator/T3Code.app",
45 );
46 const ANDROID_APK_PATH = NodePath.join(
47 MOBILE_ROOT,
48 "android/app/build/outputs/apk/debug/app-debug.apk",
49 );
50 export function resolveAndroidSdkRoot(
51 environment: Readonly<Record<string, string | undefined>>,
52 platform: NodeJS.Platform = NodeProcess.platform,
53 ): string {
54 const configured = environment.ANDROID_HOME ?? environment.ANDROID_SDK_ROOT;
55 if (configured) return configured;
56 const home = environment.HOME ?? environment.USERPROFILE ?? "";
57 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
58 return path.join(home, platform === "darwin" ? "Library/Android/sdk" : "Android/Sdk");
59 }
60
61 const ANDROID_SDK_ROOT = resolveAndroidSdkRoot(NodeProcess.env);
62 const MOBILE_BUILD_ENV = {
63 ...NodeProcess.env,
64 ANDROID_HOME: ANDROID_SDK_ROOT,
65 APP_VARIANT: "production",
66 EXPO_NO_GIT_STATUS: "1",
67 // iPad self-rotation needs the capture build's fullscreen mode (app.config.ts).
68 T3_SHOWCASE_CAPTURE_BUILD: "1",
69 JAVA_HOME:
70 NodeProcess.env.JAVA_HOME ??
71 (NodeProcess.platform === "darwin"
72 ? "/Applications/Android Studio.app/Contents/jbr/Contents/Home"
73 : undefined),
74 NODE_ENV: "development",
75 };
76
77 interface CliOptions {
78 readonly platforms: ReadonlySet<ShowcaseDevice["platform"]>;
79 readonly deviceIds: ReadonlySet<string>;
80 readonly scenes: ReadonlySet<ShowcaseScene>;
81 readonly appearances: ReadonlySet<ShowcaseAppearance>;
82 readonly themes: ReadonlySet<ShowcaseTheme>;
83 readonly skipBuild: boolean;
84 readonly skipMetro: boolean;
85 readonly keepRunning: boolean;
86 readonly validateOnly: boolean;
87 readonly list: boolean;
88 }
89
90 export interface ShowcaseCapture {
91 readonly device: ShowcaseDevice;
92 readonly scenes: ReadonlyArray<ShowcaseScene>;
93 readonly appearance: ShowcaseAppearance;
94 readonly theme: ShowcaseTheme;
95 }
96
97 interface IosCaptureCleanup {
98 readonly udid: string;
99 readonly startedByRunner: boolean;
100 readonly createdByRunner: boolean;
101 }
102
103 interface AndroidCaptureCleanup {
104 readonly device: ShowcaseAndroidDevice;
105 readonly serial: string;
106 readonly startedByRunner: boolean;
107 }
108
109 interface NetworkAddress {
110 readonly address: string;
111 readonly family: string;
112 readonly internal: boolean;
113 }
114
115 export function selectLanIpv4Address(addresses: ReadonlyArray<NetworkAddress>): string | null {
116 return (
117 addresses.find(
118 ({ address, family, internal }) =>
119 family === "IPv4" && !internal && !address.startsWith("169.254."),
120 )?.address ?? null
121 );
122 }
123
124 function lanIpv4Address(): string {
125 const address = selectLanIpv4Address(
126 Object.values(NodeOS.networkInterfaces()).flatMap((addresses) => addresses ?? []),
127 );
128 if (!address) {
129 throw new Error("No LAN IPv4 address is available for the iOS Simulator to reach Metro.");
130 }
131 return address;
132 }
133
134 export interface PngMetadata {
135 readonly width: number;
136 readonly height: number;
137 readonly bitDepth: number;
138 readonly colorType: number;
139 readonly hasAlpha: boolean;
140 }
141
142 export function readPngMetadata(bytes: Uint8Array): PngMetadata {
143 const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];
144 if (bytes.byteLength < 26 || !pngSignature.every((value, index) => bytes[index] === value)) {
145 throw new Error("Captured file is not a valid PNG.");
146 }
147 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
148 const colorType = view.getUint8(25);
149 return {
150 width: view.getUint32(16),
151 height: view.getUint32(20),
152 bitDepth: view.getUint8(24),
153 colorType,
154 hasAlpha: colorType === 4 || colorType === 6,
155 };
156 }
157
158 export function readPngDimensions(bytes: Uint8Array): {
159 readonly width: number;
160 readonly height: number;
161 } {
162 const { width, height } = readPngMetadata(bytes);
163 return { width, height };
164 }
165
166 export function normalizeStorePng(bytes: Uint8Array): Buffer {
167 const png = PNG.sync.read(Buffer.from(bytes));
168 return PNG.sync.write(png, {
169 bitDepth: 8,
170 colorType: 2,
171 inputColorType: 6,
172 inputHasAlpha: true,
173 });
174 }
175
176 export function validateStoreAsset(
177 spec: ShowcaseStoreAssetSpec,
178 bytes: Uint8Array,
179 label = "Screenshot",
180 ): PngMetadata {
181 const metadata = readPngMetadata(bytes);
182 if (metadata.width !== spec.width || metadata.height !== spec.height) {
183 throw new Error(
184 `${label} is ${metadata.width}×${metadata.height}; ${spec.store} requires ${spec.width}×${spec.height}.`,
185 );
186 }
187 if (metadata.bitDepth !== 8 || metadata.colorType !== 2 || metadata.hasAlpha) {
188 throw new Error(
189 `${label} must be an 8-bit, 24-bit RGB PNG without alpha (found bit depth ${metadata.bitDepth}, color type ${metadata.colorType}).`,
190 );
191 }
192 if (spec.maximumFileSizeBytes && bytes.byteLength > spec.maximumFileSizeBytes) {
193 throw new Error(
194 `${label} is ${bytes.byteLength} bytes; ${spec.store} allows at most ${spec.maximumFileSizeBytes} bytes.`,
195 );
196 }
197 if (spec.store === "google-play") {
198 const shortestSide = Math.min(metadata.width, metadata.height);
199 const longestSide = Math.max(metadata.width, metadata.height);
200 if (shortestSide < 320 || longestSide > 3_840 || longestSide > shortestSide * 2) {
201 throw new Error(
202 `${label} does not meet Google Play's 320–3,840 px bounds and 2:1 maximum aspect ratio.`,
203 );
204 }
205 if (metadata.width * 16 !== metadata.height * 9) {
206 throw new Error(`${label} must use Google Play's recommended portrait 9:16 aspect ratio.`);
207 }
208 }
209 try {
210 PNG.sync.read(Buffer.from(bytes));
211 } catch (cause) {
212 throw new Error(`${label} is not a valid PNG.`, { cause });
213 }
214 return metadata;
215 }
216
217 export function validateStoreAssetCount(
218 spec: ShowcaseStoreAssetSpec,
219 count: number,
220 requireMinimum: boolean,
221 ): void {
222 if (count > spec.maximumUploadCount) {
223 throw new Error(
224 `${spec.directory} contains ${count} screenshots; ${spec.store} allows at most ${spec.maximumUploadCount}.`,
225 );
226 }
227 if (requireMinimum && count < spec.minimumUploadCount) {
228 throw new Error(
229 `${spec.directory} contains ${count} screenshots; ${spec.store} requires at least ${spec.minimumUploadCount}.`,
230 );
231 }
232 }
233
234 export function showcaseCaptureDirectory(
235 outputDirectory: string,
236 capture: Pick<ShowcaseCapture, "device" | "appearance" | "theme">,
237 ): string {
238 return NodePath.join(
239 outputDirectory,
240 capture.device.storeAsset.directory,
241 capture.appearance,
242 capture.theme,
243 );
244 }
245
246 async function finalizeCapture(destination: string, device: ShowcaseDevice): Promise<void> {
247 const normalized = normalizeStorePng(await NodeFSP.readFile(destination));
248 await NodeFSP.writeFile(destination, normalized);
249 const metadata = validateStoreAsset(
250 device.storeAsset,
251 normalized,
252 NodePath.basename(destination),
253 );
254 NodeProcess.stdout.write(
255 `Captured ${NodePath.relative(REPO_ROOT, destination)} (${metadata.width}×${metadata.height}, 24-bit RGB, validated for ${device.storeAsset.store})\n`,
256 );
257 }
258
259 async function validateCaptureSet(
260 capture: ShowcaseCapture,
261 outputDirectory: string,
262 requireMinimum: boolean,
263 ): Promise<void> {
264 const directory = showcaseCaptureDirectory(outputDirectory, capture);
265 const files = (await NodeFSP.readdir(directory)).filter((file) => file.endsWith(".png")).sort();
266 const expectedFiles = capture.scenes.map((scene) => `${scene}.png`).sort();
267 const missingFiles = expectedFiles.filter((file) => !files.includes(file));
268 if (missingFiles.length > 0) {
269 throw new Error(`${capture.device.id} is missing ${missingFiles.join(", ")} in ${directory}.`);
270 }
271 validateStoreAssetCount(capture.device.storeAsset, files.length, requireMinimum);
272 for (const file of files) {
273 const bytes = await NodeFSP.readFile(NodePath.join(directory, file));
274 validateStoreAsset(capture.device.storeAsset, bytes, `${capture.device.id}/${file}`);
275 }
276 NodeProcess.stdout.write(
277 `Validated ${files.length} upload-ready ${capture.device.storeAsset.store} screenshots in ${NodePath.relative(REPO_ROOT, directory)}/\n`,
278 );
279 }
280
281 function argumentValue(args: ReadonlyArray<string>, index: number, flag: string): string {
282 const value = args[index + 1];
283 if (!value || value.startsWith("--")) {
284 throw new Error(`${flag} requires a value.`);
285 }
286 return value;
287 }
288
289 export function parseShowcaseCliArgs(args: ReadonlyArray<string>): CliOptions {
290 const platforms = new Set<ShowcaseDevice["platform"]>();
291 const deviceIds = new Set<string>();
292 const scenes = new Set<ShowcaseScene>();
293 const appearances = new Set<ShowcaseAppearance>();
294 const themes = new Set<ShowcaseTheme>();
295 let skipBuild = false;
296 let skipMetro = false;
297 let keepRunning = false;
298 let validateOnly = false;
299 let list = false;
300
301 for (let index = 0; index < args.length; index += 1) {
302 const argument = args[index];
303 if (argument === "--platform") {
304 const value = argumentValue(args, index, argument);
305 if (value !== "ios" && value !== "android" && value !== "all") {
306 throw new Error(`Unsupported platform '${value}'. Use ios, android, or all.`);
307 }
308 if (value === "all") {
309 platforms.add("ios");
310 platforms.add("android");
311 } else {
312 platforms.add(value);
313 }
314 index += 1;
315 } else if (argument === "--device") {
316 deviceIds.add(argumentValue(args, index, argument));
317 index += 1;
318 } else if (argument === "--scene") {
319 const value = argumentValue(args, index, argument);
320 if (!SHOWCASE_SCENES.includes(value as ShowcaseScene)) {
321 throw new Error(`Unsupported scene '${value}'. Use ${SHOWCASE_SCENES.join(", ")}.`);
322 }
323 scenes.add(value as ShowcaseScene);
324 index += 1;
325 } else if (argument === "--appearance") {
326 const value = argumentValue(args, index, argument);
327 if (value !== "light" && value !== "dark" && value !== "both") {
328 throw new Error(`Unsupported appearance '${value}'. Use light, dark, or both.`);
329 }
330 if (value === "both") {
331 appearances.add("light");
332 appearances.add("dark");
333 } else {
334 appearances.add(value);
335 }
336 index += 1;
337 } else if (argument === "--theme") {
338 const value = argumentValue(args, index, argument);
339 if (value === "all") {
340 for (const theme of SHOWCASE_THEMES) themes.add(theme);
341 } else if (SHOWCASE_THEMES.some((theme) => theme === value)) {
342 themes.add(value as ShowcaseTheme);
343 } else {
344 // Unknown themes silently use the default palette; reject mislabeled captures.
345 throw new Error(`Unsupported theme '${value}'. Use ${SHOWCASE_THEMES.join(", ")}, or all.`);
346 }
347 index += 1;
348 } else if (argument === "--skip-build") {
349 skipBuild = true;
350 } else if (argument === "--skip-metro") {
351 skipMetro = true;
352 } else if (argument === "--keep-running") {
353 keepRunning = true;
354 } else if (argument === "--validate-only") {
355 validateOnly = true;
356 } else if (argument === "--list") {
357 list = true;
358 } else if (argument === "--help" || argument === "-h") {
359 list = true;
360 } else {
361 throw new Error(`Unknown option '${argument}'.`);
362 }
363 }
364
365 return {
366 platforms,
367 deviceIds,
368 scenes,
369 appearances,
370 themes,
371 skipBuild,
372 skipMetro,
373 keepRunning,
374 validateOnly,
375 list,
376 };
377 }
378
379 export function planShowcaseCaptures(
380 config: ShowcaseConfig,
381 options: Pick<CliOptions, "platforms" | "deviceIds" | "scenes" | "appearances" | "themes">,
382 ): ReadonlyArray<ShowcaseCapture> {
383 const captures = config.devices
384 .filter((device) => options.platforms.size === 0 || options.platforms.has(device.platform))
385 .filter((device) => options.deviceIds.size === 0 || options.deviceIds.has(device.id))
386 .flatMap((device) => {
387 const appearances =
388 options.appearances.size === 0 ? [device.appearance] : options.appearances;
389 const themes = options.themes.size === 0 ? [device.theme] : options.themes;
390 return [...appearances].flatMap((appearance) =>
391 [...themes].map((theme) => ({
392 device,
393 appearance,
394 theme,
395 scenes:
396 options.scenes.size === 0
397 ? device.scenes
398 : device.scenes.filter((scene) => options.scenes.has(scene)),
399 })),
400 );
401 })
402 .filter((capture) => capture.scenes.length > 0);
403
404 const knownDeviceIds = new Set(config.devices.map((device) => device.id));
405 for (const id of options.deviceIds) {
406 if (!knownDeviceIds.has(id)) {
407 throw new Error(`Unknown device '${id}'. Run with --list to see configured devices.`);
408 }
409 }
410 if (captures.length === 0) {
411 throw new Error("No captures match the selected platform, device, and scene filters.");
412 }
413 return captures;
414 }
415
416 function printUsage(config: ShowcaseConfig): void {
417 NodeProcess.stdout.write(`App screenshot showcase
418
419 Usage:
420 pnpm --filter @t3tools/mobile screenshots [options]
421
422 Options:
423 --platform ios|android|all Capture one platform (repeatable)
424 --device <id> Capture one configured device (repeatable)
425 --scene <name> Capture one scene (repeatable)
426 --appearance light|dark|both
427 Override the configured appearance
428 --theme <id>|all Override the configured palette (repeatable)
429 --skip-build Reuse the existing simulator app / debug APK
430 --skip-metro Reuse an already running showcase Metro server
431 --keep-running Leave devices and Metro running after capture
432 --validate-only Validate existing upload assets without capturing
433 --list Print this help and the configured matrix
434
435 Scenes: ${SHOWCASE_SCENES.join(", ")}
436 Themes: ${SHOWCASE_THEMES.join(", ")}
437
438 Configured devices:
439 ${config.devices
440 .map((device) => {
441 const target = device.platform === "ios" ? device.simulator : device.avd;
442 return ` ${device.id.padEnd(18)} ${device.platform.padEnd(8)} ${target} -> ${device.storeAsset.directory}/{light|dark}/<theme> (${device.storeAsset.width}×${device.storeAsset.height}, default ${device.appearance} ${device.theme}) [${device.scenes.join(", ")}]`;
443 })
444 .join("\n")}
445 `);
446 }
447
448 function spawnProcess(
449 command: string,
450 args: ReadonlyArray<string>,
451 options: NodeChildProcess.SpawnOptions = {},
452 ): NodeChildProcess.ChildProcess {
453 return NodeChildProcess.spawn(command, args, {
454 cwd: REPO_ROOT,
455 env: NodeProcess.env,
456 stdio: "inherit",
457 ...options,
458 });
459 }
460
461 async function runCommand(
462 command: string,
463 args: ReadonlyArray<string>,
464 options: NodeChildProcess.SpawnOptions = {},
465 ): Promise<void> {
466 await new Promise<void>((resolve, reject) => {
467 const child = spawnProcess(command, args, options);
468 child.once("error", reject);
469 child.once("exit", (code, signal) => {
470 if (code === 0) {
471 resolve();
472 } else {
473 reject(
474 new Error(
475 `${command} ${args.join(" ")} failed ${signal ? `with signal ${signal}` : `with code ${String(code)}`}.`,
476 ),
477 );
478 }
479 });
480 });
481 }
482
483 async function commandOutput(
484 command: string,
485 args: ReadonlyArray<string>,
486 options: NodeChildProcess.ExecFileOptions = {},
487 ): Promise<string> {
488 return await new Promise<string>((resolve, reject) => {
489 NodeChildProcess.execFile(
490 command,
491 [...args],
492 { cwd: REPO_ROOT, encoding: "utf8", maxBuffer: 10 * 1024 * 1024, ...options },
493 (error, stdout) => {
494 if (error) reject(error);
495 else resolve(String(stdout));
496 },
497 );
498 });
499 }
500
501 function delay(milliseconds: number): Promise<void> {
502 return new Promise((resolve) => setTimeout(resolve, milliseconds));
503 }
504
505 export async function stopProcess(child: NodeChildProcess.ChildProcess): Promise<void> {
506 if (child.exitCode !== null || child.signalCode !== null) return;
507
508 const exited = new Promise<void>((resolve) => {
509 child.once("exit", () => resolve());
510 });
511 child.kill("SIGTERM");
512 await Promise.race([exited, delay(5_000)]);
513 if (child.exitCode !== null || child.signalCode !== null) return;
514
515 child.kill("SIGKILL");
516 await Promise.race([exited, delay(1_000)]);
517 }
518
519 export async function waitForPort(
520 port: number,
521 label = "Process",
522 timeoutMs = 60_000,
523 ): Promise<void> {
524 const deadline = Date.now() + timeoutMs;
525 while (Date.now() < deadline) {
526 const open = await new Promise<boolean>((resolve) => {
527 const socket = NodeNet.createConnection({ host: "127.0.0.1", port });
528 socket.once("connect", () => {
529 socket.destroy();
530 resolve(true);
531 });
532 socket.once("error", () => resolve(false));
533 socket.setTimeout(500, () => {
534 socket.destroy();
535 resolve(false);
536 });
537 });
538 if (open) return;
539 await delay(500);
540 }
541 throw new Error(`${label} did not begin listening on port ${port} within ${timeoutMs}ms.`);
542 }
543
544 async function waitForFileContent(
545 filePath: string,
546 label: string,
547 timeoutMs = 60_000,
548 ): Promise<string> {
549 const deadline = Date.now() + timeoutMs;
550 while (Date.now() < deadline) {
551 const content = await NodeFSP.readFile(filePath, "utf8").then(
552 (value) => value.trim(),
553 () => "",
554 );
555 if (content) return content;
556 await delay(250);
557 }
558 throw new Error(`${label} was not written to ${filePath} within ${timeoutMs}ms.`);
559 }
560
561 export async function reserveAvailablePort(): Promise<number> {
562 return await new Promise<number>((resolve, reject) => {
563 const server = NodeNet.createServer();
564 server.once("error", reject);
565 server.listen(0, "127.0.0.1", () => {
566 const address = server.address();
567 if (!address || typeof address === "string") {
568 server.close();
569 reject(new Error("Could not reserve a local port for the showcase environment."));
570 return;
571 }
572 server.close((error) => (error ? reject(error) : resolve(address.port)));
573 });
574 });
575 }
576
577 async function createShowcaseShell(baseDir: string): Promise<string> {
578 const shellPath = NodePath.join(baseDir, "showcase-shell");
579 await NodeFSP.writeFile(
580 shellPath,
581 `#!/bin/sh
582 if [ "$1" = "-ilc" ] || [ "$1" = "-lic" ]; then
583 exec /bin/sh -c "$2"
584 fi
585 exec /bin/cat
586 `,
587 { mode: 0o755 },
588 );
589 return shellPath;
590 }
591
592 async function createShowcaseLabelProbe(baseDir: string, label: string): Promise<string> {
593 const binDirectory = NodePath.join(baseDir, "showcase-bin");
594 await NodeFSP.mkdir(binDirectory, { recursive: true });
595 const probeScript = `#!/bin/sh
596 if [ "$1" = "--get" ] && [ "$2" = "ComputerName" ]; then
597 printf '%s\\n' ${JSON.stringify(label)}
598 exit 0
599 fi
600 if [ "$1" = "--pretty" ]; then
601 printf '%s\\n' ${JSON.stringify(label)}
602 exit 0
603 fi
604 exit 1
605 `;
606 await Promise.all(
607 ["scutil", "hostnamectl"].map((executable) =>
608 NodeFSP.writeFile(NodePath.join(binDirectory, executable), probeScript, { mode: 0o755 }),
609 ),
610 );
611 return binDirectory;
612 }
613
614 function startShowcaseServer(
615 baseDir: string,
616 workspaceRoot: string,
617 port: number,
618 shellPath: string,
619 labelProbeDirectory: string,
620 ): NodeChildProcess.ChildProcess {
621 return spawnProcess(
622 "node",
623 [
624 "apps/server/src/bin.ts",
625 "serve",
626 "--host",
627 SERVER_HOST,
628 "--port",
629 String(port),
630 "--base-dir",
631 baseDir,
632 "--no-browser",
633 "--log-level",
634 "error",
635 workspaceRoot,
636 ],
637 {
638 env: {
639 ...NodeProcess.env,
640 PATH: `${labelProbeDirectory}:${NodeProcess.env.PATH ?? ""}`,
641 SHELL: shellPath,
642 },
643 },
644 );
645 }
646
647 export interface ShowcaseEnvironment {
648 readonly baseDir: string;
649 readonly environmentId: string;
650 readonly label: string;
651 readonly port: number;
652 }
653
654 /** Boot one seeded fixture server per showcase environment; `track` receives every spawned server. */
655 export async function startShowcaseEnvironments(
656 rootDir: string,
657 track: (server: NodeChildProcess.ChildProcess) => void,
658 environments: ReadonlyArray<(typeof SHOWCASE_ENVIRONMENTS)[number]> = SHOWCASE_ENVIRONMENTS,
659 ): Promise<ShowcaseEnvironment[]> {
660 const started: ShowcaseEnvironment[] = [];
661 for (const environment of environments) {
662 const projectId = environment.projectIds[0];
663 const project = SHOWCASE_PROJECTS.find((candidate) => candidate.id === projectId);
664 if (!project) throw new Error(`Showcase environment '${environment.id}' has no project.`);
665
666 const baseDir = NodePath.join(rootDir, "environments", environment.id);
667 const workspaceRoot = NodePath.join(baseDir, "workspace", project.directory);
668 const port = await reserveAvailablePort();
669 await NodeFSP.mkdir(workspaceRoot, { recursive: true });
670 const shellPath = await createShowcaseShell(baseDir);
671 const labelProbeDirectory = await createShowcaseLabelProbe(baseDir, environment.label);
672 const server = startShowcaseServer(
673 baseDir,
674 workspaceRoot,
675 port,
676 shellPath,
677 labelProbeDirectory,
678 );
679 track(server);
680 await waitForPort(port, `${environment.label} server`);
681 await seedShowcaseEnvironment({ baseDir, projectIds: environment.projectIds });
682 // Legacy fixture threads are imported into V2 during server startup.
683 await stopProcess(server);
684 const seededServer = startShowcaseServer(
685 baseDir,
686 workspaceRoot,
687 port,
688 shellPath,
689 labelProbeDirectory,
690 );
691 track(seededServer);
692 await waitForPort(port, `${environment.label} seeded server`);
693 // The server begins listening before the ServerEnvironment layer
694 // persists the environment id, so poll rather than read once.
695 const environmentId = await waitForFileContent(
696 NodePath.join(baseDir, "userdata", "environment-id"),
697 `${environment.label} environment id`,
698 );
699 started.push({ baseDir, environmentId, label: environment.label, port });
700 }
701 return started;
702 }
703
704 export function parsePairingCredentialOutput(output: string): string {
705 const jsonStart = output.indexOf("{");
706 const jsonEnd = output.lastIndexOf("}");
707 if (jsonStart === -1 || jsonEnd < jsonStart) {
708 throw new Error("Pairing credential command did not return JSON.");
709 }
710 const parsed = JSON.parse(output.slice(jsonStart, jsonEnd + 1)) as {
711 readonly credential?: unknown;
712 };
713 if (typeof parsed.credential !== "string" || parsed.credential.length === 0) {
714 throw new Error("Pairing credential command returned no credential.");
715 }
716 return parsed.credential;
717 }
718
719 export async function issuePairingCredential(baseDir: string): Promise<string> {
720 const output = await commandOutput(
721 "node",
722 ["apps/server/src/bin.ts", "auth", "pairing", "create", "--base-dir", baseDir, "--json"],
723 { env: { ...NodeProcess.env, NO_COLOR: "1" } },
724 );
725 return parsePairingCredentialOutput(output);
726 }
727
728 export function buildShowcasePairingUrl(host: string, port: number, credential: string): string {
729 const url = new URL(`http://${host}:${port}/`);
730 url.hash = new URLSearchParams([["token", credential]]).toString();
731 return url.toString();
732 }
733
734 export function encodeAndroidPairingUrls(pairingUrls: ReadonlyArray<string>): string {
735 return `json-uri:${encodeURIComponent(JSON.stringify(pairingUrls))}`;
736 }
737
738 function startMetro(config: ShowcaseConfig): NodeChildProcess.ChildProcess {
739 return spawnProcess(
740 "pnpm",
741 ["exec", "expo", "start", "--dev-client", "--port", String(config.metroPort)],
742 {
743 cwd: MOBILE_ROOT,
744 env: {
745 ...MOBILE_BUILD_ENV,
746 EXPO_PUBLIC_SHOWCASE: "1",
747 },
748 },
749 );
750 }
751
752 async function warmMetroBundle(
753 platform: ShowcaseDevice["platform"],
754 host: string,
755 config: ShowcaseConfig,
756 ): Promise<void> {
757 const url = `http://${host}:${config.metroPort}/apps/mobile/index.bundle?platform=${platform}&dev=true&minify=false`;
758 await runCommand("curl", ["--fail", "--silent", "--show-error", "--output", "/dev/null", url]);
759 }
760
761 async function buildIos(): Promise<string> {
762 const derivedData = NodePath.join(MOBILE_ROOT, ".showcase/ios-derived-data");
763 await runCommand("pnpm", ["exec", "expo", "prebuild", "--clean", "--platform", "ios"], {
764 cwd: MOBILE_ROOT,
765 env: MOBILE_BUILD_ENV,
766 });
767 await runCommand(
768 "xcodebuild",
769 [
770 "-workspace",
771 NodePath.join(MOBILE_ROOT, "ios/T3Code.xcworkspace"),
772 "-scheme",
773 "T3Code",
774 "-configuration",
775 "Debug",
776 "-sdk",
777 "iphonesimulator",
778 "-derivedDataPath",
779 derivedData,
780 "-quiet",
781 `ARCHS=${IOS_SIMULATOR_ARCH}`,
782 "ONLY_ACTIVE_ARCH=YES",
783 "build",
784 ],
785 { cwd: MOBILE_ROOT, env: MOBILE_BUILD_ENV },
786 );
787 return IOS_APP_PATH;
788 }
789
790 async function buildAndroid(abis: ReadonlyArray<string>): Promise<string> {
791 await runCommand("pnpm", ["exec", "expo", "prebuild", "--clean", "--platform", "android"], {
792 cwd: MOBILE_ROOT,
793 env: MOBILE_BUILD_ENV,
794 });
795 await runCommand(
796 "./gradlew",
797 [
798 "app:assembleDebug",
799 ...(abis.length > 0 ? [`-PreactNativeArchitectures=${abis.join(",")}`] : []),
800 ],
801 {
802 cwd: NodePath.join(MOBILE_ROOT, "android"),
803 env: MOBILE_BUILD_ENV,
804 },
805 );
806 return ANDROID_APK_PATH;
807 }
808
809 async function existingArtifact(path: string): Promise<string | null> {
810 return await NodeFSP.access(path).then(
811 () => path,
812 () => null,
813 );
814 }
815
816 interface SimctlDevice {
817 readonly name: string;
818 readonly udid: string;
819 readonly state: "Booted" | "Shutdown" | string;
820 readonly isAvailable: boolean;
821 }
822
823 async function findIosSimulator(name: string): Promise<SimctlDevice | null> {
824 const parsed = JSON.parse(
825 await commandOutput("xcrun", ["simctl", "list", "devices", "available", "-j"]),
826 ) as {
827 readonly devices: Readonly<Record<string, ReadonlyArray<SimctlDevice>>>;
828 };
829 const candidates = Object.entries(parsed.devices)
830 .filter(([runtime]) => runtime.includes("iOS"))
831 .flatMap(([, devices]) => devices)
832 .filter((device) => device.isAvailable && device.name === name);
833 return candidates.at(-1) ?? null;
834 }
835
836 async function ensureIosSimulator(device: ShowcaseIosDevice): Promise<{
837 readonly simulator: SimctlDevice;
838 readonly createdByRunner: boolean;
839 }> {
840 const existing = await findIosSimulator(device.simulator);
841 if (existing) return { simulator: existing, createdByRunner: false };
842 if (!device.simulatorDeviceType) {
843 throw new Error(
844 `iOS simulator '${device.simulator}' is not installed and has no simulatorDeviceType configured.`,
845 );
846 }
847 const udid = (
848 await commandOutput("xcrun", ["simctl", "create", device.simulator, device.simulatorDeviceType])
849 ).trim();
850 if (!udid) throw new Error(`Could not create iOS simulator '${device.simulator}'.`);
851 return {
852 simulator: {
853 name: device.simulator,
854 udid,
855 state: "Shutdown",
856 isAvailable: true,
857 },
858 createdByRunner: true,
859 };
860 }
861
862 async function iosSimulatorDataPath(udid: string): Promise<string> {
863 const parsed = JSON.parse(await commandOutput("xcrun", ["simctl", "list", "devices", "-j"])) as {
864 readonly devices: Readonly<
865 Record<string, ReadonlyArray<SimctlDevice & { readonly dataPath: string }>>
866 >;
867 };
868 const dataPath = Object.values(parsed.devices)
869 .flat()
870 .find((device) => device.udid === udid)?.dataPath;
871 if (!dataPath) throw new Error(`Could not resolve the data path of iOS simulator ${udid}.`);
872 return dataPath;
873 }
874
875 // Apple Intelligence posts persistent first-boot banners; mark readiness and clear queued CoreFollowUp notices.
876 async function suppressIosSystemFollowUps(udid: string): Promise<void> {
877 const dataPath = await iosSimulatorDataPath(udid);
878 const preferences = NodePath.join(dataPath, "Library/Preferences");
879 await NodeFSP.mkdir(preferences, { recursive: true });
880 await NodeFSP.writeFile(
881 NodePath.join(preferences, "com.apple.generativeexperiences.corefollowup.plist"),
882 `<?xml version="1.0" encoding="UTF-8"?>
883 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
884 <plist version="1.0">
885 <dict>
886 \t<key>DateOfLastAppleIntelligenceReadinessCFU</key>
887 \t<date>2020-01-01T00:00:00Z</date>
888 </dict>
889 </plist>
890 `,
891 );
892 await NodeFSP.rm(NodePath.join(dataPath, "Library/CoreFollowUp"), {
893 recursive: true,
894 force: true,
895 });
896 }
897
898 async function normalizeIosSimulator(appearance: ShowcaseAppearance, udid: string): Promise<void> {
899 await runCommand("xcrun", ["simctl", "ui", udid, "appearance", appearance]);
900 // Disable always-on dimming so lock-screen wake can distinguish off from fully lit.
901 await runCommand("xcrun", [
902 "simctl",
903 "spawn",
904 udid,
905 "defaults",
906 "write",
907 "com.apple.springboard",
908 "SBEnableAlwaysOn",
909 "-bool",
910 "false",
911 ]);
912 await runCommand("xcrun", [
913 "simctl",
914 "status_bar",
915 udid,
916 "override",
917 "--time",
918 "9:41",
919 "--batteryState",
920 "charged",
921 "--batteryLevel",
922 "100",
923 "--wifiBars",
924 "3",
925 "--cellularBars",
926 "4",
927 ]);
928 }
929
930 // iPadOS 26 windowing forces fullscreen apps into portrait, defeating capture-build rotation.
931 async function ensureIosFullScreenAppsMode(udid: string): Promise<void> {
932 const current = await commandOutput("xcrun", [
933 "simctl",
934 "spawn",
935 udid,
936 "defaults",
937 "read",
938 "com.apple.springboard",
939 "SBChamoisWindowingEnabled",
940 ]).catch(() => "");
941 if (current.trim() === "0") return;
942 // Fresh devices honor the Settings toggle only when all three keys are written.
943 for (const key of [
944 "SBChamoisWindowingEnabled",
945 "SBMedusaMultitaskingEnabled",
946 "SBFlexibleWindowingPreviouslyEnabledAutomaticStageCreation",
947 ]) {
948 await runCommand("xcrun", [
949 "simctl",
950 "spawn",
951 udid,
952 "defaults",
953 "write",
954 "com.apple.springboard",
955 key,
956 "-bool",
957 "false",
958 ]);
959 }
960 // New simulators require a reboot, not just SpringBoard restart, before windowing settings take effect.
961 await runCommand("xcrun", ["simctl", "shutdown", udid]);
962 await runCommand("xcrun", ["simctl", "boot", udid]);
963 await runCommand("xcrun", ["simctl", "bootstatus", udid, "-b"]);
964 const applied = await commandOutput("xcrun", [
965 "simctl",
966 "spawn",
967 udid,
968 "defaults",
969 "read",
970 "com.apple.springboard",
971 "SBChamoisWindowingEnabled",
972 ]).catch(() => "");
973 if (applied.trim() !== "0") {
974 throw new Error(`Simulator ${udid} did not switch to Full Screen Apps mode.`);
975 }
976 }
977
978 async function iosAppContainer(udid: string): Promise<string> {
979 return (
980 await commandOutput("xcrun", ["simctl", "get_app_container", udid, ANDROID_PACKAGE, "data"])
981 ).trim();
982 }
983
984 async function waitForIosShowcaseScene(
985 udid: string,
986 scene: ShowcaseScene,
987 timeoutMs = 90_000,
988 ): Promise<void> {
989 const readyPath = NodePath.join(
990 await iosAppContainer(udid),
991 "Library/Caches",
992 IOS_READY_FILENAME,
993 );
994 const deadline = Date.now() + timeoutMs;
995 while (Date.now() < deadline) {
996 const readyScene = await NodeFSP.readFile(readyPath, "utf8").catch(() => "");
997 if (readyScene.trim() === scene) return;
998 await delay(500);
999 }
1000 throw new Error(`iOS showcase scene '${scene}' did not render within ${timeoutMs}ms.`);
1001 }
1002
1003 function iosAxe(): string {
1004 return NodeProcess.env.AXE_PATH ?? "axe";
1005 }
1006
1007 async function runAxe(udid: string, args: ReadonlyArray<string>): Promise<void> {
1008 // HID events sent right after the simulator settles are dropped without it.
1009 await runCommand(iosAxe(), [...args, "--udid", udid], {
1010 env: { ...NodeProcess.env, AXE_HID_STABILIZATION_MS: "3000" },
1011 }).catch((error: unknown) => {
1012 if ((error as NodeJS.ErrnoException).code === "ENOENT") {
1013 throw new Error(
1014 "The agent-activity scene drives the simulator with AXe. Install it with `brew tap cameroncooke/axe && brew install axe`, or set AXE_PATH.",
1015 );
1016 }
1017 throw error;
1018 });
1019 }
1020
1021 async function iosSimulatorLocked(udid: string): Promise<boolean> {
1022 const state = await commandOutput("xcrun", [
1023 "simctl",
1024 "spawn",
1025 udid,
1026 "notifyutil",
1027 "-g",
1028 "com.apple.springboard.lockstate",
1029 ]).catch(() => "");
1030 return state.trim().endsWith(" 1");
1031 }
1032
1033 // simctl has no notification privacy service; answer the staging app's prompt until ready.
1034 async function allowIosNotificationsUntilReady(udid: string, ready: Promise<void>): Promise<void> {
1035 const state = { settled: false };
1036 const tapping = (async () => {
1037 while (!state.settled) {
1038 await runAxe(udid, ["tap", "--label", "Allow"]).catch(() => undefined);
1039 if (!state.settled) await delay(1_000);
1040 }
1041 })();
1042 try {
1043 await ready;
1044 } finally {
1045 state.settled = true;
1046 await tapping;
1047 }
1048 }
1049
1050 async function presentIosLockScreen(udid: string): Promise<void> {
1051 await runAxe(udid, ["button", "lock"]);
1052 const deadline = Date.now() + 15_000;
1053 while (!(await iosSimulatorLocked(udid))) {
1054 if (Date.now() > deadline) throw new Error(`Simulator ${udid} did not lock.`);
1055 await delay(500);
1056 }
1057 const alert = showcaseAgentAlert();
1058 await new Promise<void>((resolve, reject) => {
1059 const child = NodeChildProcess.execFile(
1060 "xcrun",
1061 ["simctl", "push", udid, ANDROID_PACKAGE, "-"],
1062 { cwd: REPO_ROOT },
1063 (error) => (error ? reject(error) : resolve()),
1064 );
1065 child.stdin?.end(
1066 JSON.stringify({
1067 aps: { alert: { title: alert.title, body: alert.body }, sound: "default" },
1068 }),
1069 );
1070 });
1071 await wakeIosLockScreen(udid);
1072 // The first Live Activity on the lock screen asks to keep allowing them.
1073 await delay(2_000);
1074 await runAxe(udid, ["tap", "--label", "Allow"]).catch(() => undefined);
1075 }
1076
1077 /** Press home only if a screenshot proves the lock screen is dark; a lit display would unlock instead. */
1078 async function wakeIosLockScreen(udid: string): Promise<void> {
1079 const probe = NodePath.join(NodeOS.tmpdir(), `t3-showcase-wake-${udid}.png`);
1080 try {
1081 for (let attempt = 0; attempt < 5; attempt += 1) {
1082 await delay(2_000);
1083 await runCommand("xcrun", ["simctl", "io", udid, "screenshot", probe]);
1084 if (!pngIsBlack(await NodeFSP.readFile(probe))) return;
1085 await runAxe(udid, ["button", "home"]);
1086 }
1087 throw new Error(`Simulator ${udid} lock screen stayed dark.`);
1088 } finally {
1089 await NodeFSP.rm(probe, { force: true });
1090 }
1091 }
1092
1093 function pngIsBlack(bytes: Uint8Array): boolean {
1094 const { data } = PNG.sync.read(Buffer.from(bytes));
1095 for (let offset = 0; offset < data.length; offset += 4 * 997) {
1096 if ((data[offset] ?? 0) > 8 || (data[offset + 1] ?? 0) > 8 || (data[offset + 2] ?? 0) > 8) {
1097 return false;
1098 }
1099 }
1100 return true;
1101 }
1102
1103 async function unlockIosSimulator(udid: string): Promise<void> {
1104 await runAxe(udid, ["button", "home"]);
1105 await delay(2_000);
1106 await runAxe(udid, ["button", "home"]);
1107 }
1108
1109 function showcaseAgentAlert(): { readonly title: string; readonly body: string } {
1110 const thread = SHOWCASE_THREADS.find((candidate) => candidate.id === "pocket-command-center");
1111 const project = SHOWCASE_PROJECTS.find((candidate) => candidate.id === thread?.projectId);
1112 if (!thread || !project) throw new Error("The showcase fixture lost its agent-activity thread.");
1113 return { title: thread.title, body: `Approval: ${project.title}` };
1114 }
1115
1116 async function captureIos(
1117 capture: ShowcaseCapture & { readonly device: ShowcaseIosDevice },
1118 appPath: string | null,
1119 outputDirectory: string,
1120 config: ShowcaseConfig,
1121 metroHost: string,
1122 pairingUrls: ReadonlyArray<string>,
1123 registerCleanup: (cleanup: IosCaptureCleanup) => void,
1124 ): Promise<void> {
1125 const { simulator, createdByRunner } = await ensureIosSimulator(capture.device);
1126 const startedByRunner = simulator.state !== "Booted";
1127 registerCleanup({ udid: simulator.udid, startedByRunner, createdByRunner });
1128 if (!startedByRunner) {
1129 await runCommand("xcrun", ["simctl", "shutdown", simulator.udid]);
1130 }
1131 await suppressIosSystemFollowUps(simulator.udid);
1132 await runCommand("xcrun", ["simctl", "boot", simulator.udid]);
1133 await runCommand("xcrun", ["simctl", "bootstatus", simulator.udid, "-b"]);
1134 if (capture.device.orientation === "landscape") {
1135 await ensureIosFullScreenAppsMode(simulator.udid);
1136 }
1137 if (capture.device.fold) {
1138 const command = NodeProcess.env.AGENT_DEVICE_PATH ?? "agent-device";
1139 const target = [
1140 "--platform",
1141 "ios",
1142 "--udid",
1143 simulator.udid,
1144 "--session",
1145 `showcase-${simulator.udid}`,
1146 ];
1147 await runCommand(command, ["open", ...target]);
1148 try {
1149 await runCommand(command, ["fold", capture.device.fold, ...target]);
1150 } finally {
1151 await runCommand(command, ["close", ...target]);
1152 }
1153 }
1154 await normalizeIosSimulator(capture.appearance, simulator.udid);
1155 if (appPath) {
1156 await runCommand("xcrun", ["simctl", "uninstall", simulator.udid, ANDROID_PACKAGE]).catch(
1157 () => undefined,
1158 );
1159 await runCommand("xcrun", ["simctl", "install", simulator.udid, appPath]);
1160 }
1161
1162 const metroUrl = `http://${metroHost}:${config.metroPort}?${DEV_CLIENT_LAUNCH_FLAGS}`;
1163 const scenePath = NodePath.join(
1164 await iosAppContainer(simulator.udid),
1165 "Library/Caches/T3ShowcaseScene",
1166 );
1167 const readyPath = NodePath.join(
1168 await iosAppContainer(simulator.udid),
1169 "Library/Caches",
1170 IOS_READY_FILENAME,
1171 );
1172 const firstScene = capture.scenes[0] ?? "threads";
1173 const launchShowcaseApp = async (terminateRunningProcess: boolean) => {
1174 await runCommand("xcrun", [
1175 "simctl",
1176 "launch",
1177 ...(terminateRunningProcess ? ["--terminate-running-process"] : []),
1178 simulator.udid,
1179 ANDROID_PACKAGE,
1180 "--initialUrl",
1181 metroUrl,
1182 "--showcasePairingUrl",
1183 JSON.stringify(pairingUrls),
1184 "--showcaseScene",
1185 firstScene,
1186 "--showcaseTheme",
1187 capture.theme,
1188 // Simulator rotation UI scripting needs Accessibility permission unavailable on CI.
1189 "--showcaseOrientation",
1190 capture.device.orientation ?? "portrait",
1191 ]);
1192 };
1193 await NodeFSP.rm(readyPath, { force: true });
1194 await NodeFSP.writeFile(scenePath, firstScene);
1195 await launchShowcaseApp(false);
1196 for (const [sceneIndex, scene] of capture.scenes.entries()) {
1197 if (sceneIndex > 0) await NodeFSP.rm(readyPath, { force: true });
1198 await NodeFSP.writeFile(scenePath, scene);
1199 const waitForScene = (timeoutMs?: number) => {
1200 const ready = waitForIosShowcaseScene(simulator.udid, scene, timeoutMs);
1201 return scene === "agent-activity"
1202 ? allowIosNotificationsUntilReady(simulator.udid, ready)
1203 : ready;
1204 };
1205 if (sceneIndex === 0) {
1206 for (let attempt = 0; attempt < 2; attempt += 1) {
1207 const isLastAttempt = attempt === 1;
1208 try {
1209 // A fresh Expo build can spend over 30 s applying a bundled update; killing it returns to the launcher.
1210 await waitForScene(120_000);
1211 break;
1212 } catch (error) {
1213 if (isLastAttempt) throw error;
1214 await launchShowcaseApp(true);
1215 }
1216 }
1217 } else {
1218 await waitForScene();
1219 }
1220 if (scene === "agent-activity") await presentIosLockScreen(simulator.udid);
1221 await delay(scene === "review" ? Math.max(config.settleDelayMs, 8_000) : config.settleDelayMs);
1222 const destination = NodePath.join(
1223 showcaseCaptureDirectory(outputDirectory, capture),
1224 `${scene}.png`,
1225 );
1226 await runCommand("xcrun", [
1227 "simctl",
1228 "io",
1229 simulator.udid,
1230 "screenshot",
1231 ...(capture.device.fold ? ["--display", capture.device.fold === "closed" ? "1" : "3"] : []),
1232 destination,
1233 ]);
1234 if (capture.device.orientation === "landscape") {
1235 // Headless displays stay portrait despite app rotation; post-rotate only captures still in portrait.
1236 const { width, height } = readPngDimensions(await NodeFSP.readFile(destination));
1237 if (height > width) {
1238 await runCommand("sips", ["--rotate", capture.device.fold ? "90" : "270", destination]);
1239 }
1240 }
1241 if (scene === "agent-activity") await unlockIosSimulator(simulator.udid);
1242 await finalizeCapture(destination, capture.device);
1243 }
1244 }
1245
1246 function androidSdkTool(relativePath: string): string {
1247 return NodePath.join(ANDROID_SDK_ROOT, relativePath);
1248 }
1249
1250 async function adbOutput(serial: string, args: ReadonlyArray<string>): Promise<string> {
1251 return await commandOutput(androidSdkTool("platform-tools/adb"), ["-s", serial, ...args]);
1252 }
1253
1254 async function runAdb(serial: string, args: ReadonlyArray<string>): Promise<void> {
1255 await runCommand(androidSdkTool("platform-tools/adb"), ["-s", serial, ...args]);
1256 }
1257
1258 /** Snooze emulator system notices for an hour so only app notifications appear in captures. */
1259 async function snoozeAndroidSystemNotifications(serial: string): Promise<void> {
1260 const keys = (await adbOutput(serial, ["shell", "cmd", "notification", "list"]))
1261 .split("\n")
1262 .map((line) => line.trim())
1263 .filter((key) => key.includes("|") && !key.includes(`|${ANDROID_PACKAGE}|`));
1264 for (const key of keys) {
1265 // adb joins shell args with spaces, so the key needs quoting for the pipes.
1266 await runAdb(serial, ["shell", `cmd notification snooze --for 3600000 '${key}'`]);
1267 }
1268 }
1269
1270 async function runningAndroidAvds(): Promise<ReadonlyMap<string, string>> {
1271 const adb = androidSdkTool("platform-tools/adb");
1272 const devices = (await commandOutput(adb, ["devices"]))
1273 .split("\n")
1274 .map((line) => line.trim().split(/\s+/u))
1275 .filter((parts) => parts[0]?.startsWith("emulator-") && parts[1] === "device")
1276 .map((parts) => parts[0] as string);
1277 const result = new Map<string, string>();
1278 for (const serial of devices) {
1279 const avdName = (await adbOutput(serial, ["emu", "avd", "name"])).split("\n")[0]?.trim();
1280 if (avdName) result.set(avdName, serial);
1281 }
1282 return result;
1283 }
1284
1285 async function waitForAndroidSerial(avd: string, timeoutMs = 120_000): Promise<string> {
1286 const deadline = Date.now() + timeoutMs;
1287 while (Date.now() < deadline) {
1288 const serial = (await runningAndroidAvds()).get(avd);
1289 if (serial) {
1290 await runAdb(serial, ["wait-for-device"]);
1291 const bootCompleted = (
1292 await adbOutput(serial, ["shell", "getprop", "sys.boot_completed"])
1293 ).trim();
1294 if (bootCompleted === "1") return serial;
1295 }
1296 await delay(1_000);
1297 }
1298 throw new Error(`Android AVD '${avd}' did not finish booting within ${timeoutMs}ms.`);
1299 }
1300
1301 async function normalizeAndroidEmulator(
1302 device: ShowcaseAndroidDevice,
1303 appearance: ShowcaseAppearance,
1304 serial: string,
1305 ): Promise<void> {
1306 await runAdb(serial, ["shell", "settings", "put", "global", "window_animation_scale", "0"]);
1307 await runAdb(serial, ["shell", "settings", "put", "global", "transition_animation_scale", "0"]);
1308 await runAdb(serial, ["shell", "settings", "put", "global", "animator_duration_scale", "0"]);
1309 await runAdb(serial, ["shell", "cmd", "uimode", "night", appearance === "dark" ? "yes" : "no"]);
1310 await runAdb(serial, ["shell", "settings", "put", "system", "time_12_24", "12"]);
1311 await runAdb(serial, ["emu", "power", "capacity", "100"]);
1312 await runAdb(serial, ["shell", "settings", "put", "global", "sysui_demo_allowed", "1"]);
1313 await runAdb(serial, [
1314 "shell",
1315 "am",
1316 "broadcast",
1317 "-a",
1318 "com.android.systemui.demo",
1319 "-e",
1320 "command",
1321 "enter",
1322 ]);
1323 await runAdb(serial, [
1324 "shell",
1325 "am",
1326 "broadcast",
1327 "-a",
1328 "com.android.systemui.demo",
1329 "-e",
1330 "command",
1331 "clock",
1332 "-e",
1333 "hhmm",
1334 "0941",
1335 ]);
1336 await runAdb(serial, [
1337 "shell",
1338 "am",
1339 "broadcast",
1340 "-a",
1341 "com.android.systemui.demo",
1342 "-e",
1343 "command",
1344 "battery",
1345 "-e",
1346 "level",
1347 "100",
1348 "-e",
1349 "plugged",
1350 "false",
1351 ]);
1352 if (device.viewport) {
1353 await runAdb(serial, [
1354 "shell",
1355 "wm",
1356 "size",
1357 `${device.viewport.width}x${device.viewport.height}`,
1358 ]);
1359 if (device.viewport.density) {
1360 await runAdb(serial, ["shell", "wm", "density", String(device.viewport.density)]);
1361 }
1362 }
1363 }
1364
1365 async function waitForAndroidShowcaseScene(
1366 serial: string,
1367 scene: ShowcaseScene,
1368 timeoutMs = 90_000,
1369 ): Promise<void> {
1370 const deadline = Date.now() + timeoutMs;
1371 while (Date.now() < deadline) {
1372 const readyScene = await adbOutput(serial, [
1373 "shell",
1374 "run-as",
1375 ANDROID_PACKAGE,
1376 "cat",
1377 "files/t3-showcase-ready",
1378 ]).catch(() => "");
1379 if (readyScene.trim() === scene) return;
1380 await delay(500);
1381 }
1382 throw new Error(`Android showcase scene '${scene}' did not render within ${timeoutMs}ms.`);
1383 }
1384
1385 async function writeAndroidShowcaseScene(serial: string, scene: ShowcaseScene): Promise<void> {
1386 await runAdb(serial, [
1387 "shell",
1388 `run-as ${ANDROID_PACKAGE} sh -c 'mkdir -p files && rm -f files/t3-showcase-ready && printf %s ${scene} > files/t3-showcase-scene'`,
1389 ]);
1390 }
1391
1392 // Gesture/key-command toggles have no URL flags; set preferences separately from DEV_CLIENT_LAUNCH_FLAGS.
1393 async function prepareAndroidShowcaseApp(serial: string): Promise<void> {
1394 const preferences = `<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
1395 <map>
1396 <boolean name="motionGestureEnabled" value="false" />
1397 <boolean name="touchGestureEnabled" value="false" />
1398 <boolean name="keyCommandsEnabled" value="false" />
1399 </map>`;
1400 const encodedPreferences = Buffer.from(preferences).toString("base64");
1401 await runAdb(serial, [
1402 "shell",
1403 `run-as ${ANDROID_PACKAGE} sh -c 'mkdir -p shared_prefs && printf %s ${encodedPreferences} | base64 -d > shared_prefs/expo.modules.devmenu.sharedpreferences.xml'`,
1404 ]);
1405 }
1406
1407 async function captureAndroid(
1408 capture: ShowcaseCapture & { readonly device: ShowcaseAndroidDevice },
1409 apkPath: string | null,
1410 outputDirectory: string,
1411 config: ShowcaseConfig,
1412 pairingUrls: ReadonlyArray<string>,
1413 registerCleanup: (cleanup: AndroidCaptureCleanup) => void,
1414 ): Promise<void> {
1415 const running = await runningAndroidAvds();
1416 const existingSerial = running.get(capture.device.avd);
1417 const startedByRunner = !existingSerial;
1418 let launchedEmulator: NodeChildProcess.ChildProcess | null = null;
1419 if (startedByRunner) {
1420 const installedAvds = (await commandOutput(androidSdkTool("emulator/emulator"), ["-list-avds"]))
1421 .split("\n")
1422 .map((value) => value.trim());
1423 if (!installedAvds.includes(capture.device.avd)) {
1424 throw new Error(
1425 `Android AVD '${capture.device.avd}' is not installed. Run emulator -list-avds.`,
1426 );
1427 }
1428 launchedEmulator = spawnProcess(
1429 androidSdkTool("emulator/emulator"),
1430 ["-avd", capture.device.avd, "-no-snapshot-load", "-no-boot-anim"],
1431 { stdio: "ignore", detached: true },
1432 );
1433 launchedEmulator.unref();
1434 }
1435 const serial =
1436 existingSerial ??
1437 (await waitForAndroidSerial(capture.device.avd).catch(async (error: unknown) => {
1438 if (launchedEmulator) await stopProcess(launchedEmulator);
1439 throw error;
1440 }));
1441 registerCleanup({ device: capture.device, serial, startedByRunner });
1442 await normalizeAndroidEmulator(capture.device, capture.appearance, serial);
1443 if (apkPath) {
1444 await runAdb(serial, ["install", "-r", apkPath]);
1445 }
1446 await runAdb(serial, ["shell", "pm", "clear", ANDROID_PACKAGE]);
1447 await runAdb(serial, [
1448 "shell",
1449 "pm",
1450 "grant",
1451 ANDROID_PACKAGE,
1452 "android.permission.POST_NOTIFICATIONS",
1453 ]);
1454 await prepareAndroidShowcaseApp(serial);
1455 await runAdb(serial, ["reverse", `tcp:${config.metroPort}`, `tcp:${config.metroPort}`]);
1456 const metroUrl = encodeURIComponent(`http://127.0.0.1:${config.metroPort}?disableOnboarding=1`);
1457 const firstScene = capture.scenes[0] ?? "threads";
1458 await runAdb(serial, [
1459 "shell",
1460 "am",
1461 "start",
1462 "-W",
1463 "-a",
1464 "android.intent.action.VIEW",
1465 "-d",
1466 `'${APP_SCHEME}://expo-development-client/?url=${metroUrl}&${DEV_CLIENT_LAUNCH_FLAGS}'`,
1467 "--es",
1468 "showcasePairingUrl",
1469 encodeAndroidPairingUrls(pairingUrls),
1470 "--es",
1471 "showcaseScene",
1472 firstScene,
1473 "--es",
1474 "showcaseTheme",
1475 capture.theme,
1476 ANDROID_PACKAGE,
1477 ]);
1478 for (const [sceneIndex, scene] of capture.scenes.entries()) {
1479 if (sceneIndex > 0) await writeAndroidShowcaseScene(serial, scene);
1480 await waitForAndroidShowcaseScene(serial, scene);
1481 if (scene === "agent-activity") {
1482 await snoozeAndroidSystemNotifications(serial);
1483 await runAdb(serial, ["shell", "cmd", "statusbar", "expand-notifications"]);
1484 }
1485 await delay(Math.max(config.settleDelayMs, scene === "review" ? 8_000 : 5_000));
1486 const destination = NodePath.join(
1487 showcaseCaptureDirectory(outputDirectory, capture),
1488 `${scene}.png`,
1489 );
1490 const png = await new Promise<Buffer>((resolve, reject) => {
1491 NodeChildProcess.execFile(
1492 androidSdkTool("platform-tools/adb"),
1493 ["-s", serial, "exec-out", "screencap", "-p"],
1494 { cwd: REPO_ROOT, encoding: "buffer", maxBuffer: 64 * 1024 * 1024 },
1495 (error, stdout) => {
1496 if (error) reject(error);
1497 else resolve(stdout);
1498 },
1499 );
1500 });
1501 await NodeFSP.writeFile(destination, png);
1502 if (scene === "agent-activity") {
1503 await runAdb(serial, ["shell", "cmd", "statusbar", "collapse"]);
1504 }
1505 await finalizeCapture(destination, capture.device);
1506 }
1507 }
1508
1509 async function cleanupAndroidViewport(
1510 device: ShowcaseAndroidDevice,
1511 serial: string,
1512 ): Promise<void> {
1513 await runAdb(serial, [
1514 "shell",
1515 "am",
1516 "broadcast",
1517 "-a",
1518 "com.android.systemui.demo",
1519 "-e",
1520 "command",
1521 "exit",
1522 ]);
1523 if (!device.viewport) return;
1524 await runAdb(serial, ["shell", "wm", "size", "reset"]);
1525 if (device.viewport.density) {
1526 await runAdb(serial, ["shell", "wm", "density", "reset"]);
1527 }
1528 }
1529
1530 async function main(): Promise<void> {
1531 const options = parseShowcaseCliArgs(NodeProcess.argv.slice(2));
1532 if (options.list) {
1533 printUsage(showcaseConfig);
1534 return;
1535 }
1536 const captures = planShowcaseCaptures(showcaseConfig, options);
1537 const outputDirectory = NodePath.resolve(REPO_ROOT, showcaseConfig.outputDirectory);
1538 if (options.validateOnly) {
1539 for (const capture of captures) {
1540 await validateCaptureSet(
1541 capture,
1542 outputDirectory,
1543 capture.scenes.length === capture.device.scenes.length,
1544 );
1545 }
1546 return;
1547 }
1548 const hasIos = captures.some((capture) => capture.device.platform === "ios");
1549 const hasAndroid = captures.some((capture) => capture.device.platform === "android");
1550 const metroHost = hasIos ? lanIpv4Address() : "127.0.0.1";
1551 await NodeFSP.mkdir(outputDirectory, { recursive: true });
1552 for (const capture of captures) {
1553 const directory = showcaseCaptureDirectory(outputDirectory, capture);
1554 await NodeFSP.rm(directory, { recursive: true, force: true });
1555 await NodeFSP.mkdir(directory, { recursive: true });
1556 }
1557
1558 const showcaseRootDir = await NodeFSP.mkdtemp(
1559 NodePath.join(NodeOS.tmpdir(), "t3-mobile-showcase-"),
1560 );
1561 const showcaseServers: NodeChildProcess.ChildProcess[] = [];
1562 const showcaseEnvironments: ShowcaseEnvironment[] = [];
1563 let metro: NodeChildProcess.ChildProcess | null = null;
1564 const iosCleanups: IosCaptureCleanup[] = [];
1565 const androidCleanups: AndroidCaptureCleanup[] = [];
1566
1567 try {
1568 showcaseEnvironments.push(
1569 ...(await startShowcaseEnvironments(showcaseRootDir, (server) =>
1570 showcaseServers.push(server),
1571 )),
1572 );
1573
1574 if (!options.skipMetro) {
1575 metro = startMetro(showcaseConfig);
1576 await waitForPort(showcaseConfig.metroPort, "Metro");
1577 await Promise.all([
1578 hasIos ? warmMetroBundle("ios", metroHost, showcaseConfig) : Promise.resolve(),
1579 hasAndroid ? warmMetroBundle("android", "127.0.0.1", showcaseConfig) : Promise.resolve(),
1580 ]);
1581 }
1582
1583 const iosAppPath = hasIos
1584 ? options.skipBuild
1585 ? await existingArtifact(IOS_APP_PATH)
1586 : await buildIos()
1587 : null;
1588 const androidAbis = captures.flatMap((capture) =>
1589 capture.device.platform === "android" && capture.device.abi ? [capture.device.abi] : [],
1590 );
1591 const androidApkPath = hasAndroid
1592 ? options.skipBuild
1593 ? await existingArtifact(ANDROID_APK_PATH)
1594 : await buildAndroid([...new Set(androidAbis)])
1595 : null;
1596
1597 for (const capture of captures) {
1598 const pairingHost = capture.device.platform === "ios" ? "127.0.0.1" : "10.0.2.2";
1599 const pairingUrls = await Promise.all(
1600 showcaseEnvironments.map(async (environment) => {
1601 const credential = await issuePairingCredential(environment.baseDir);
1602 return buildShowcasePairingUrl(pairingHost, environment.port, credential);
1603 }),
1604 );
1605 if (capture.device.platform === "ios") {
1606 await captureIos(
1607 capture as ShowcaseCapture & { readonly device: ShowcaseIosDevice },
1608 iosAppPath,
1609 outputDirectory,
1610 showcaseConfig,
1611 metroHost,
1612 pairingUrls,
1613 (cleanup) => iosCleanups.push(cleanup),
1614 );
1615 } else {
1616 await captureAndroid(
1617 capture as ShowcaseCapture & { readonly device: ShowcaseAndroidDevice },
1618 androidApkPath,
1619 outputDirectory,
1620 showcaseConfig,
1621 pairingUrls,
1622 (cleanup) => androidCleanups.push(cleanup),
1623 );
1624 }
1625 await validateCaptureSet(
1626 capture,
1627 outputDirectory,
1628 capture.scenes.length === capture.device.scenes.length,
1629 );
1630 }
1631
1632 NodeProcess.stdout.write(
1633 `\nDone. Upload-ready screenshots are in ${NodePath.relative(REPO_ROOT, outputDirectory)}/apple/ and ${NodePath.relative(REPO_ROOT, outputDirectory)}/google-play/.\n`,
1634 );
1635 if (options.keepRunning) {
1636 const serverSummary = showcaseEnvironments
1637 .map((environment) => `${environment.label}:${environment.port}`)
1638 .join(", ");
1639 NodeProcess.stdout.write(
1640 `Showcase environments kept at ${showcaseRootDir} (${serverSummary}).\n`,
1641 );
1642 }
1643 } finally {
1644 if (options.keepRunning) {
1645 metro?.unref();
1646 for (const server of showcaseServers) server.unref();
1647 } else {
1648 for (const cleanup of androidCleanups) {
1649 await cleanupAndroidViewport(cleanup.device, cleanup.serial).catch(() => undefined);
1650 if (cleanup.startedByRunner) {
1651 await runAdb(cleanup.serial, ["emu", "kill"]).catch(() => undefined);
1652 }
1653 }
1654 for (const cleanup of iosCleanups) {
1655 if (cleanup.startedByRunner || cleanup.createdByRunner) {
1656 await runCommand("xcrun", ["simctl", "shutdown", cleanup.udid]).catch(() => undefined);
1657 }
1658 if (cleanup.createdByRunner) {
1659 await runCommand("xcrun", ["simctl", "delete", cleanup.udid]).catch(() => undefined);
1660 }
1661 }
1662 await Promise.all([
1663 ...(metro ? [stopProcess(metro)] : []),
1664 ...showcaseServers.map((server) => stopProcess(server)),
1665 ]);
1666 await NodeFSP.rm(showcaseRootDir, {
1667 recursive: true,
1668 force: true,
1669 maxRetries: 5,
1670 retryDelay: 100,
1671 });
1672 }
1673 }
1674 }
1675
1676 if (import.meta.main) {
1677 void main().catch((error: unknown) => {
1678 NodeProcess.stderr.write(
1679 `${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
1680 );
1681 NodeProcess.exit(1);
1682 });
1683 }