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
64export class 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
70export class Device {
71 readonly pose: Pose;
72 readonly session: string;
73 readonly pool: Pool;
74
75 private constructor(pose: Pose, session: string, pool: Pool) {
76 this.pose = pose;
77 this.session = session;
78 this.pool = pool;
79 }
80
81 /** Leases a device for the pose; `open` waits in the pool's queue while every match is busy. */
82 static async lease(pose: Pose, pool: Pool, runId: string): Promise<Device> {
83 const device = new Device(pose, `t3-e2e-${runId}-${pose.id}`, pool);
84 await device.agent(["connect", "proxy", "--daemon-base-url", pool.agentDeviceUrl]);
85 await device.agent(
86 [
87 "open",
88 "--platform",
89 pose.platform,
90 "--device",
91 pose.device,
92 // A real keyboard, so the layout under it is what people see.
93 ...(pose.platform === "android" ? ["--no-test-ime"] : []),
94 ],
95 { timeoutMs: 420_000 },
96 );
97 return device;
98 }
99
100 async agent(
101 args: ReadonlyArray<string>,
102 options: { readonly timeoutMs?: number } = {},
103 ): Promise<Record<string, unknown>> {
104 for (let attempt = 1; ; attempt++) {
105 try {
106 return await this.agentOnce(args, options);
107 } catch (error) {
108 if (attempt >= 5 || !(error instanceof AgentDeviceError) || !TRANSIENT.test(error.message))
109 throw error;
110 await delay(5_000 * attempt);
111 }
112 }
113 }
114
115 private async agentOnce(
116 args: ReadonlyArray<string>,
117 options: { readonly timeoutMs?: number },
118 ): Promise<Record<string, unknown>> {
119 const { stdout, stderr } = await run(
120 NodeProcess.execPath,
121 [this.pool.agentDevice, ...args, "--session", this.session, "--json"],
122 {
123 cwd: this.pool.workspace,
124 env: this.pool.env,
125 allowFailure: true,
126 timeoutMs: options.timeoutMs ?? 120_000,
127 },
128 );
129 let parsed: { success: boolean; data?: Record<string, unknown>; error?: { message: string } };
130 try {
131 parsed = JSON.parse(stdout);
132 } catch {
133 throw new AgentDeviceError(`agent-device ${args[0]}: ${(stderr || stdout).slice(-400)}`);
134 }
135 if (!parsed.success)
136 throw new AgentDeviceError(`agent-device ${args.join(" ")}: ${parsed.error?.message}`);
137 return parsed.data ?? {};
138 }
139
140 /** The shared-cache dev client for this checkout; the worker downloads it itself. */
141 async install() {
142 await run(
143 NodeProcess.execPath,
144 [
145 NodePath.join(this.pool.repoRoot, "scripts/mobile-native-client.ts"),
146 "ensure",
147 this.pose.platform,
148 "--session",
149 this.session,
150 ],
151 { cwd: this.pool.workspace, env: this.pool.env, timeoutMs: 600_000 },
152 );
153 }
154
155 /** Device settings that must be in place before the app starts. */
156 async prepare() {
157 await this.agent(["settings", "appearance", this.pose.appearance]);
158 if (this.pose.textSize) await this.agent(["settings", "text-size", this.pose.textSize]);
159 if (this.pose.fold) await this.agent(["fold", this.pose.fold]);
160 }
161
162 async launch(metroUrl: string) {
163 const url = encodeURIComponent(metroUrl);
164 await this.agent(
165 [
166 "open",
167 BUNDLE_ID,
168 `t3code-dev://expo-development-client/?url=${url}&disableOnboarding=1&disableFab=1&disableAutoLaunch=1`,
169 // A real keyboard, so the layout under it is what people see.
170 ...(this.pose.platform === "android" ? ["--no-test-ime"] : []),
171 ],
172 { timeoutMs: 180_000 },
173 );
174 await this.acceptOpenPrompt();
175 }
176
177 /**
178 * agent-device names rotations relative to the device's natural orientation, which is
179 * landscape on tablets and unfolded folds, so try each name until the screen has the shape.
180 */
181 async orient(shape: "landscape" | "portrait"): Promise<Snapshot> {
182 let snapshot = await this.snapshot();
183 for (const name of ["landscape-left", "portrait", "landscape-right"]) {
184 const { width, height } = snapshot.viewport;
185 if (width > height === (shape === "landscape")) return snapshot;
186 await this.agent(["orientation", name]);
187 await delay(2_000);
188 snapshot = await this.snapshot();
189 }
190 return snapshot;
191 }
192
193 async openUrl(url: string) {
194 await this.agent(["open", BUNDLE_ID, url]);
195 await this.acceptOpenPrompt();
196 }
197
198 /** iOS asks before another app opens a custom scheme, and agent-device does not always answer. */
199 private async acceptOpenPrompt() {
200 if (this.pose.platform !== "ios") return;
201 await delay(1_500);
202 await this.agent(["alert", "accept"]).catch(() => undefined);
203 }
204
205 async snapshot(): Promise<Snapshot> {
206 return (await this.agent(["snapshot"])) as unknown as Snapshot;
207 }
208
209 async waitFor(predicate: (snapshot: Snapshot) => boolean, label: string, timeoutMs = 60_000) {
210 const deadline = Date.now() + timeoutMs;
211 while (Date.now() < deadline) {
212 const snapshot = await this.snapshot().catch(() => null);
213 if (snapshot && predicate(snapshot)) return snapshot;
214 await delay(750);
215 }
216 throw new Error(`timed out waiting for ${label}`);
217 }
218
219 async screenshot(path: string) {
220 // iOS defaults to 1x points, too coarse for anyone reviewing the screenshot.
221 await this.agent([
222 "screenshot",
223 path,
224 ...(this.pose.platform === "ios" ? ["--pixel-density", "2"] : []),
225 ]);
226 }
227
228 /** Runs an action while recording, so transitions can be checked frame by frame. */
229 async recorded(directory: string, name: string, action: () => Promise<unknown>) {
230 const video = NodePath.join(directory, `${name}.mp4`);
231 await this.agent(["record", "start", video, "--hide-touches"]);
232 try {
233 await action();
234 await delay(2_000);
235 } finally {
236 await this.agent(["record", "stop"], { timeoutMs: 180_000 }).catch(() => undefined);
237 }
238 return video;
239 }
240
241 async release() {
242 await this.agent(["close"]).catch(() => undefined);
243 }
244}