Open History to see the last commit
1import {
2 DeviceBootError,
3 type DeviceHostId,
4 DeviceOperationError,
5 type DevicePlatform,
6} from "@t3tools/contracts";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
12
13import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost.ts";
14
15const BOOT_TIMEOUT = Duration.minutes(3);
16const SCREENSHOT_TIMEOUT = Duration.seconds(20);
17// The hub's Android shutdown waits up to 30 s for the emulator to leave adb after the kill.
18const ANDROID_SHUTDOWN_TIMEOUT = Duration.seconds(45);
19const ADB_DEVICES_TIMEOUT = Duration.seconds(10);
20// Let the hub's 30 s simctl timeout report its cause first.
21const LIST_TIMEOUT_SECONDS = 40;
22// expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes.
23const SIMULATOR_LIST_FAILED =
24 /^\[apple-utils\] (?:Failed to (?:run `xcrun simctl list devices|parse JSON output:|list devices:)|`xcrun simctl list devices --json` did not respond within )/;
25// The hub passes numeric display IDs that Xcode 26 rejects; iOS 27 needs them for multiple displays.
26// expo-device-hub 0.22.1 returns no Android devices when avdmanager fails, before it runs adb.
27const AVDMANAGER_LIST_FAILED = "[android-utils] Failed to run `avdmanager list avd`";
28const GETPROP_LINE = /^\[([^\]]+)\]: \[(.*)\]$/;
29const runsOnXcode26Runtime = (version: string) => Number(/^iOS (\d+)/.exec(version)?.[1]) <= 26;
30const DEFAULT_DISPLAY_SCREENSHOT = `f=$(mktemp -t t3-screenshot) || exit 1
31trap 'rm -f "$f"' 0
32xcrun simctl io "$1" screenshot --type=png "$f" >/dev/null && base64 -i "$f"`;
33
34const HubDevice = Schema.Struct({
35 id: Schema.String,
36 name: Schema.String,
37 version: Schema.String,
38 platform: Schema.Literals(["ios", "android"]),
39 booted: Schema.Boolean,
40 physical: Schema.Boolean,
41});
42const HubDeviceList = Schema.Struct({
43 simulators: Schema.Array(HubDevice),
44 emulators: Schema.Array(HubDevice),
45 errors: Schema.optional(
46 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
47 ),
48});
49const HubActionResult = Schema.Struct({
50 ok: Schema.Boolean,
51 id: Schema.optional(Schema.String),
52 serial: Schema.optional(Schema.String),
53 error: Schema.optional(Schema.String),
54 errors: Schema.optional(
55 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
56 ),
57});
58
59// Hub diagnostics can carry a whole stderr dump.
60const boundDiagnostics = (text: string) =>
61 text.length > 2_000 ? `${text.slice(0, 1_999)}…` : text;
62
63// The hub's `error` is a util.inspect of Node's exec error; the stack and the
64// inspected fields follow the first frame, so keep the lines before it.
65const errorHead = (error: string) => {
66 const lines = error.split(/\r?\n/);
67 const firstFrame = lines.findIndex((line) => /^\s+at /.test(line));
68 return (firstFrame === -1 ? lines : lines.slice(0, firstFrame))
69 .map((line) => line.trim())
70 .filter(Boolean)
71 .join(" ");
72};
73
74const vendorPrefix = (platform: DevicePlatform) =>
75 platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
76
77/** Device operations for a host that runs expo-device-hub at `origin`. */
78export const makeDeviceHubOperations = (options: {
79 readonly hostId: DeviceHostId;
80 readonly origin: string;
81 readonly token?: string | undefined;
82 readonly http: HttpClient.HttpClient;
83 readonly run: DeviceHostReady["run"];
84 readonly platformAvailable: (platform: DevicePlatform) => Effect.Effect<boolean>;
85 /** Gates listing AVDs, which the hub does not report until they boot. Phones need only adb. */
86 readonly avdsAvailable?: Effect.Effect<boolean>;
87}): DeviceOperations => {
88 const { hostId, origin, run } = options;
89 const { token } = options;
90 const httpClient = (
91 token === undefined
92 ? options.http
93 : options.http.pipe(HttpClient.mapRequest(HttpClientRequest.bearerToken(token)))
94 ).pipe(HttpClient.withScope);
95
96 const fetchJson = Effect.fn("DeviceHubOperations.fetchJson")(function* <A, I>(
97 request: HttpClientRequest.HttpClientRequest,
98 schema: Schema.Codec<A, I>,
99 ) {
100 return yield* httpClient
101 .execute(request)
102 .pipe(
103 Effect.flatMap(HttpClientResponse.filterStatusOk),
104 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
105 Effect.scoped,
106 );
107 });
108
109 const hubJson = <A, I>(
110 request: HttpClientRequest.HttpClientRequest,
111 schema: Schema.Codec<A, I>,
112 operation: string,
113 timeout: Duration.Input = Duration.seconds(15),
114 ) =>
115 fetchJson(request, schema).pipe(
116 Effect.timeout(timeout),
117 Effect.mapError(
118 (cause) => new DeviceOperationError({ operation, reason: "request_failed", cause }),
119 ),
120 );
121
122 const postJson = (path: string, body: Record<string, string>, operation: string) =>
123 HttpClientRequest.post(`${origin}${path}`).pipe(
124 HttpClientRequest.bodyJson(body),
125 Effect.mapError(
126 (cause) => new DeviceOperationError({ operation, reason: "invalid_payload", cause }),
127 ),
128 );
129
130 // Booting alone does not attach a serve-sim helper; the grid start does both
131 // and is idempotent for a booted simulator.
132 const attachIosStream = (udid: string, operation: string) =>
133 postJson(`${vendorPrefix("ios")}/grid/api/start`, { udid }, operation).pipe(
134 Effect.flatMap((request) => hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT)),
135 );
136
137 // Mirrors the hub's own adb discovery for when it skips it.
138 const listAdbDevices = Effect.gen(function* () {
139 const listed = yield* run("adb", ["devices", "-l"]);
140 if (listed.code !== 0) return undefined;
141 const serials = listed.stdout
142 .split(/\r?\n/)
143 .map((line) => line.trim().split(/\s+/))
144 .flatMap(([serial, state]) => (serial && state === "device" ? [serial] : []));
145 return yield* Effect.forEach(serials, (serial) =>
146 Effect.gen(function* () {
147 const getprop = yield* run("adb", ["-s", serial, "shell", "getprop"]);
148 const props = new Map(
149 getprop.stdout.split(/\r?\n/).flatMap((line) => {
150 const match = GETPROP_LINE.exec(line.trim());
151 return match ? [[match[1]!, match[2]!] as const] : [];
152 }),
153 );
154 const emulator = props.get("ro.kernel.qemu") === "1" || props.get("ro.boot.qemu") === "1";
155 const avdName = emulator
156 ? (yield* run("adb", ["-s", serial, "emu", "avd", "name"])).stdout
157 .split(/\r?\n/)
158 .map((line) => line.trim())
159 .find((line) => line && line !== "OK" && !line.startsWith("KO"))
160 : undefined;
161 const model = props.get("ro.product.model");
162 const manufacturer = props.get("ro.product.manufacturer");
163 const release = props.get("ro.build.version.release");
164 return {
165 id: serial,
166 name: emulator
167 ? (avdName ?? serial)
168 : model
169 ? [manufacturer, model].filter(Boolean).join(" ")
170 : serial,
171 platform: "android",
172 version: release
173 ? `Android ${/^\d+$/.test(release) ? `${release}.0` : release}`
174 : "Android",
175 booted: true,
176 physical: !emulator,
177 } satisfies HostDevice;
178 }),
179 );
180 });
181
182 const list: DeviceOperations["list"] = Effect.gen(function* () {
183 const listed = yield* fetchJson(
184 HttpClientRequest.get(`${origin}/api/devices`),
185 HubDeviceList,
186 ).pipe(
187 Effect.mapError(
188 (cause) => new DeviceOperationError({ operation: "list", reason: "request_failed", cause }),
189 ),
190 Effect.timeoutOption(Duration.seconds(LIST_TIMEOUT_SECONDS)),
191 );
192 if (Option.isNone(listed)) {
193 return {
194 devices: [],
195 detail: `The device hub did not answer within ${LIST_TIMEOUT_SECONDS} seconds.`,
196 incompletePlatforms: yield* Effect.filter(["ios", "android"] as const, (platform) =>
197 options.platformAvailable(platform),
198 ),
199 };
200 }
201 const hubList = listed.value;
202 const devices: Array<HostDevice> = [...hubList.simulators, ...hubList.emulators];
203 const androidAvailable = yield* options.platformAvailable("android");
204 const avdsAvailable =
205 androidAvailable && (yield* options.avdsAvailable ?? Effect.succeed(true));
206 const warnings = hubList.errors?.filter(
207 (error) =>
208 // The host summary already explains a missing Android SDK; the hub's failed probes are noise.
209 !(!androidAvailable && error.message.startsWith("[android-utils] ")) &&
210 // Without emulator tooling, avdmanager is expected to be missing.
211 !(!avdsAvailable && error.message.startsWith(AVDMANAGER_LIST_FAILED)) &&
212 // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
213 !(
214 error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
215 /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
216 /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
217 ),
218 );
219 const details =
220 warnings?.map((error) => {
221 const head = errorHead(error.error ?? "");
222 return boundDiagnostics(head ? `${error.message} ${head}` : error.message);
223 }) ?? [];
224 let androidDiscoveryIncomplete = false;
225 if (androidAvailable) {
226 if (hubList.errors?.some((error) => error.message.startsWith(AVDMANAGER_LIST_FAILED))) {
227 const adbDevices = yield* listAdbDevices;
228 if (adbDevices === undefined) {
229 androidDiscoveryIncomplete = true;
230 details.push("Could not list Android devices (adb devices -l).");
231 } else {
232 devices.push(...adbDevices);
233 }
234 }
235 }
236 if (avdsAvailable) {
237 const avds = yield* run("emulator", ["-list-avds"]);
238 // Discovered devices stay listed; the AVDs that could not be listed are a warning.
239 if (avds.code !== 0) {
240 androidDiscoveryIncomplete = true;
241 details.push(
242 `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
243 );
244 }
245 for (const name of (avds.code === 0 ? avds.stdout : "")
246 .split(/\r?\n/)
247 .map((line) => line.trim())
248 .filter(Boolean)) {
249 if (!devices.some((device) => device.platform === "android" && device.name === name)) {
250 devices.push({
251 id: name,
252 name,
253 platform: "android",
254 version: "Android",
255 booted: false,
256 physical: false,
257 });
258 }
259 }
260 }
261 const simulatorsUnlisted =
262 hubList.simulators.length === 0 &&
263 (hubList.errors ?? []).some((error) => SIMULATOR_LIST_FAILED.test(error.message));
264 return {
265 devices,
266 detail: details.join("\n") || undefined,
267 androidDiscoveryIncomplete,
268 ...(simulatorsUnlisted ? { incompletePlatforms: ["ios"] as const } : {}),
269 };
270 }).pipe(Effect.withSpan("DeviceHubOperations.list"));
271
272 const boot: DeviceOperations["boot"] = Effect.fn("DeviceHubOperations.boot")(function* (device) {
273 const result = yield* postJson(
274 "/api/devices/boot",
275 { platform: device.platform, id: device.id, name: device.name },
276 "boot",
277 ).pipe(Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)));
278 if (!result.ok) {
279 // Keep the hub's launch command and nested failure available to agents for recovery.
280 const diagnostics = [
281 result.error,
282 ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
283 ]
284 .filter((text) => text?.trim())
285 .join("\n\n");
286 return yield* new DeviceBootError({
287 hostId,
288 deviceId: device.id,
289 reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
290 diagnostics,
291 )
292 ? "disk_space"
293 : /timed? out|timeout/i.test(diagnostics)
294 ? "timeout"
295 : "launch_failed",
296 ...(diagnostics ? { diagnostics: boundDiagnostics(diagnostics) } : {}),
297 cause: result,
298 });
299 }
300 if (device.platform === "ios") yield* attachIosStream(device.id, "boot");
301 return result.serial ?? result.id ?? device.id;
302 });
303
304 const attach: DeviceOperations["attach"] = (device) =>
305 device.platform === "ios"
306 ? attachIosStream(device.id, "open").pipe(Effect.asVoid)
307 : Effect.void;
308
309 // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an
310 // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer
311 // lists its serial in any state.
312 const emulatorExited = (serial: string) =>
313 /^emulator-\d+$/.test(serial)
314 ? run("adb", ["devices"], { timeoutMs: Duration.toMillis(ADB_DEVICES_TIMEOUT) }).pipe(
315 Effect.map(
316 ({ code, stdout }) =>
317 code === 0 &&
318 !stdout.split(/\r?\n/).some((line) => line.trim().split(/\s+/)[0] === serial),
319 ),
320 Effect.orElseSucceed(() => false),
321 )
322 : Effect.succeed(false);
323
324 const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")(
325 function* (device) {
326 const postShutdown = (path: string, body: Record<string, string>, timeout?: Duration.Input) =>
327 postJson(path, body, "shutdown").pipe(
328 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown", timeout)),
329 Effect.flatMap((result) =>
330 result.ok
331 ? Effect.void
332 : Effect.fail(
333 new DeviceOperationError({
334 operation: "shutdown",
335 reason: "hub_rejected",
336 cause: result,
337 }),
338 ),
339 ),
340 );
341 // serve-sim's shutdown closes its in-process capture session before it
342 // runs `simctl shutdown`; the hub's generic shutdown can leave that
343 // session cached across a reboot. serve-sim runs simctl bare, though, so
344 // a simulator that is already off fails there.
345 yield* device.platform === "ios"
346 ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: device.id }).pipe(
347 Effect.catch((cause) =>
348 list.pipe(
349 Effect.flatMap(({ devices }) =>
350 devices.find((candidate) => candidate.id === device.id)?.booted === false
351 ? Effect.logInfo("iOS simulator was already shut down", { deviceId: device.id })
352 : Effect.fail(cause),
353 ),
354 ),
355 ),
356 )
357 : postShutdown(
358 "/api/devices/shutdown",
359 { platform: device.platform, id: device.id },
360 ANDROID_SHUTDOWN_TIMEOUT,
361 ).pipe(
362 Effect.catch((cause) =>
363 emulatorExited(device.id).pipe(
364 Effect.flatMap((exited) =>
365 exited
366 ? Effect.logInfo("Android emulator has exited", {
367 deviceId: device.id,
368 })
369 : Effect.fail(cause),
370 ),
371 ),
372 ),
373 );
374 },
375 );
376
377 const defaultDisplayScreenshot = Effect.fn("DeviceHubOperations.defaultDisplayScreenshot")(
378 function* (udid: string) {
379 const capture = yield* run("sh", ["-c", DEFAULT_DISPLAY_SCREENSHOT, "sh", udid], {
380 timeoutMs: Duration.toMillis(SCREENSHOT_TIMEOUT),
381 maxOutputBytes: 64 * 1024 * 1024,
382 });
383 if (capture.code !== 0) {
384 return yield* new DeviceOperationError({
385 operation: "screenshot",
386 reason: "command_failed",
387 exitCode: capture.code,
388 cause: capture.stderr.trim(),
389 });
390 }
391 return new Uint8Array(Buffer.from(capture.stdout, "base64"));
392 },
393 );
394
395 const screenshot: DeviceOperations["screenshot"] = (device) =>
396 httpClient
397 .execute(
398 HttpClientRequest.post(
399 `${origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`,
400 ),
401 )
402 .pipe(
403 Effect.flatMap(HttpClientResponse.filterStatusOk),
404 Effect.flatMap((response) => response.arrayBuffer),
405 Effect.map((buffer) => new Uint8Array(buffer)),
406 Effect.scoped,
407 Effect.timeout(SCREENSHOT_TIMEOUT),
408 Effect.mapError(
409 (cause) =>
410 new DeviceOperationError({
411 operation: "screenshot",
412 reason:
413 HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
414 ? "hub_rejected"
415 : "request_failed",
416 cause,
417 }),
418 ),
419 Effect.catchIf(
420 (error) =>
421 device.platform === "ios" &&
422 runsOnXcode26Runtime(device.version) &&
423 error.reason === "hub_rejected",
424 () => defaultDisplayScreenshot(device.id),
425 ),
426 Effect.withSpan("DeviceHubOperations.screenshot"),
427 );
428
429 return { list, boot, attach, shutdown, screenshot };
430};