Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - Host-side device automation uses Node subprocess and timing APIs directly.
2
3import * as NodeChildProcess from "node:child_process";
4import * as NodePath from "node:path";
5import * as NodeProcess from "node:process";
6
7import type { Snapshot } from "./checks.ts";
8import type { Pose } from "./poses.ts";
9
10export const BUNDLE_ID = "com.t3tools.t3code.dev";
11
12export interface RunResult {
13 readonly code: number;
14 readonly stdout: string;
15 readonly stderr: string;
16}
17
18export function run(
19 command: string,
20 args: ReadonlyArray<string>,
21 options: {
22 readonly cwd?: string;
23 readonly env?: NodeJS.ProcessEnv;
24 readonly allowFailure?: boolean;
25 readonly timeoutMs?: number;
26 } = {},
27): Promise<RunResult> {
28 return new Promise((resolve, reject) => {
29 const child = NodeChildProcess.spawn(command, args, {
30 ...(options.cwd ? { cwd: options.cwd } : {}),
31 env: options.env ?? NodeProcess.env,
32 stdio: ["ignore", "pipe", "pipe"],
33 ...(options.timeoutMs ? { timeout: options.timeoutMs } : {}),
34 });
35 let stdout = "";
36 let stderr = "";
37 child.stdout.on("data", (chunk) => (stdout += chunk));
38 child.stderr.on("data", (chunk) => (stderr += chunk));
39 child.on("error", reject);
40 child.on("close", (code) => {
41 if (code !== 0 && !options.allowFailure)
42 reject(new Error(`${command} ${args.join(" ")} failed (${code}): ${stderr || stdout}`));
43 else resolve({ code: code ?? 1, stdout, stderr });
44 });
45 });
46}
47
48export const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
49
50/** How this run reaches the pool: one agent-device config, from one workspace. */
51export interface Pool {
52 readonly repoRoot: string;
53 readonly agentDevice: string;
54 /** The gateway's agent-device front, `<gateway>/v1/agent-device`. */
55 readonly agentDeviceUrl: string;
56 /**
57 * agent-device ties a lease to the workspace it was opened from and reads it from both the
58 * real cwd and $PWD, so every command runs from this real path with a matching PWD.
59 */
60 readonly workspace: string;
61 readonly env: NodeJS.ProcessEnv;
62}
63
64class AgentDeviceError extends Error {}
65
66// A shared pool's workers drop off the gateway and stall under load for seconds at a time.
67const TRANSIENT =
68 /Remote daemon is unavailable|not connected to the gateway|still finishing a previous command|Invalid daemon response|Daemon request timed out|no worker connected/i;
69
70/** Failures that say the pool could not serve the pose, not that the app misbehaved. */
71export const poolError = (message: string) =>
72 TRANSIENT.test(message) ||
73 /Daemon connection closed|Failed to read daemon response|WORKER_UNREACHABLE|xcrun timed out|refused by simlock|is not available on this simlock/i.test(
74 message,
75 );
76
77export class Device {
78 readonly pose: Pose;
79 readonly session: string;
80 readonly pool: Pool;
81
82 private constructor(pose: Pose, session: string, pool: Pool) {
83 this.pose = pose;
84 this.session = session;
85 this.pool = pool;
86 }
87
88 /** Leases a device for the pose; `open` waits in the pool's queue while every match is busy. */
89 static async lease(pose: Pose, pool: Pool, runId: string): Promise<Device> {
90 const device = new Device(pose, `t3-e2e-${runId}-${pose.id}`, pool);
91 await device.agent(["connect", "proxy", "--daemon-base-url", pool.agentDeviceUrl]);
92 await device.agent(
93 [
94 "open",
95 "--platform",
96 pose.platform,
97 "--device",
98 pose.device,
99 // A real keyboard, so the layout under it is what people see.
100 ...(pose.platform === "android" ? ["--no-test-ime"] : []),
101 ],
102 { timeoutMs: 420_000 },
103 );
104 return device;
105 }
106
107 async agent(
108 args: ReadonlyArray<string>,
109 options: { readonly timeoutMs?: number } = {},
110 ): Promise<Record<string, unknown>> {
111 for (let attempt = 1; ; attempt++) {
112 try {
113 return await this.agentOnce(args, options);
114 } catch (error) {
115 if (attempt >= 5 || !(error instanceof AgentDeviceError) || !TRANSIENT.test(error.message))
116 throw error;
117 await delay(5_000 * attempt);
118 }
119 }
120 }
121
122 private async agentOnce(
123 args: ReadonlyArray<string>,
124 options: { readonly timeoutMs?: number },
125 ): Promise<Record<string, unknown>> {
126 const { stdout, stderr } = await run(
127 NodeProcess.execPath,
128 [this.pool.agentDevice, ...args, "--session", this.session, "--json"],
129 {
130 cwd: this.pool.workspace,
131 env: this.pool.env,
132 allowFailure: true,
133 timeoutMs: options.timeoutMs ?? 120_000,
134 },
135 );
136 let parsed: { success: boolean; data?: Record<string, unknown>; error?: { message: string } };
137 try {
138 parsed = JSON.parse(stdout);
139 } catch {
140 throw new AgentDeviceError(`agent-device ${args[0]}: ${(stderr || stdout).slice(-400)}`);
141 }
142 if (!parsed.success)
143 throw new AgentDeviceError(`agent-device ${args.join(" ")}: ${parsed.error?.message}`);
144 return parsed.data ?? {};
145 }
146
147 /** The shared-cache dev client for this checkout; the worker downloads it itself. */
148 async install() {
149 await run(
150 NodeProcess.execPath,
151 [
152 NodePath.join(this.pool.repoRoot, "scripts/mobile-native-client.ts"),
153 "ensure",
154 this.pose.platform,
155 "--session",
156 this.session,
157 ],
158 { cwd: this.pool.workspace, env: this.pool.env, timeoutMs: 600_000 },
159 );
160 }
161
162 /** Device settings that must be in place before the app starts. */
163 async prepare() {
164 await this.agent(["settings", "appearance", this.pose.appearance]);
165 if (this.pose.textSize) await this.agent(["settings", "text-size", this.pose.textSize]);
166 if (this.pose.fold) await this.agent(["fold", this.pose.fold]);
167 }
168
169 async launch(metroUrl: string) {
170 const url = encodeURIComponent(metroUrl);
171 await this.agent(
172 [
173 "open",
174 BUNDLE_ID,
175 `t3code-dev://expo-development-client/?url=${url}&disableOnboarding=1&disableFab=1&disableAutoLaunch=1`,
176 // A real keyboard, so the layout under it is what people see.
177 ...(this.pose.platform === "android" ? ["--no-test-ime"] : []),
178 ],
179 { timeoutMs: 180_000 },
180 );
181 await this.acceptOpenPrompt();
182 }
183
184 /**
185 * agent-device names rotations relative to the device's natural orientation, which is
186 * landscape on tablets and unfolded folds, so try each name until the screen has the shape.
187 */
188 async orient(shape: "landscape" | "portrait"): Promise<Snapshot> {
189 let snapshot = await this.snapshot();
190 for (const name of ["landscape-left", "portrait", "landscape-right"]) {
191 const { width, height } = snapshot.viewport;
192 if (width > height === (shape === "landscape")) return snapshot;
193 await this.agent(["orientation", name]);
194 await delay(2_000);
195 snapshot = await this.snapshot();
196 }
197 return snapshot;
198 }
199
200 async openUrl(url: string) {
201 await this.agent(["open", BUNDLE_ID, url]);
202 await this.acceptOpenPrompt();
203 }
204
205 /** iOS asks before another app opens a custom scheme, and agent-device does not always answer. */
206 private async acceptOpenPrompt() {
207 if (this.pose.platform !== "ios") return;
208 await delay(1_500);
209 await this.agent(["alert", "accept"]).catch(() => undefined);
210 }
211
212 async snapshot(): Promise<Snapshot> {
213 return (await this.agent(["snapshot"])) as unknown as Snapshot;
214 }
215
216 async waitFor(predicate: (snapshot: Snapshot) => boolean, label: string, timeoutMs = 60_000) {
217 const deadline = Date.now() + timeoutMs;
218 while (Date.now() < deadline) {
219 const snapshot = await this.snapshot().catch(() => null);
220 if (snapshot && predicate(snapshot)) return snapshot;
221 await delay(750);
222 }
223 throw new Error(`timed out waiting for ${label}`);
224 }
225
226 async screenshot(path: string) {
227 // iOS defaults to 1x points, too coarse for anyone reviewing the screenshot.
228 await this.agent([
229 "screenshot",
230 path,
231 ...(this.pose.platform === "ios" ? ["--pixel-density", "2"] : []),
232 ]);
233 }
234
235 /** Runs an action while recording, so transitions can be checked frame by frame. */
236 async recorded(directory: string, name: string, action: () => Promise<unknown>) {
237 const video = NodePath.join(directory, `${name}.mp4`);
238 await this.agent(["record", "start", video, "--hide-touches"]);
239 try {
240 await action();
241 await delay(2_000);
242 } finally {
243 await this.agent(["record", "stop"], { timeoutMs: 180_000 }).catch(() => undefined);
244 }
245 return video;
246 }
247
248 async release() {
249 await this.agent(["close"]).catch(() => undefined);
250 }
251}