Open History to see the last commit
1import {
2 DeviceBootError,
3 type DeviceHostId,
4 DeviceOperationError,
5 type DevicePlatform,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import * as Clock from "effect/Clock";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
14
15import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost.ts";
16
17const BOOT_TIMEOUT = Duration.minutes(3);
18const ANDROID_BOOT_COMPLETED_TIMEOUT = Duration.minutes(2);
19// Poll every 1.5 s once adb is online so boot completion is noticed quickly without hammering SSH hosts.
20const ANDROID_BOOT_POLL_INTERVAL = Duration.millis(1_500);
21// Cold serve-emu startup (ffmpeg probe + scrcpy-server + capture start) can outlast the client's 15 s frame timer.
22const ANDROID_BOOT_WARMUP_TIMEOUT = Duration.seconds(60);
23const ANDROID_STREAM_POLL_INTERVAL = Duration.seconds(2);
24const ANDROID_MAX_WARMUP_FAILURES = 2;
25const ANDROID_EXIT_PROBE_TIMEOUT = Duration.seconds(2);
26// Reserve two exit-confirmation probes plus their gap inside each deadline so exit checks never overshoot it.
27const ANDROID_EXIT_CONFIRM_RESERVE_MS =
28 Duration.toMillis(ANDROID_EXIT_PROBE_TIMEOUT) * 2 + Duration.toMillis(ANDROID_BOOT_POLL_INTERVAL);
29// expo-device-hub 0.26.1 serve-emu middleware.js returns 503 with this message during its 5 s SPAWN_RETRY_COOLDOWN_MS.
30const SERVE_EMU_COOLING_DOWN = /cooling down after a failure/i;
31const EMULATOR_SERIAL = /^emulator-\d+$/;
32const SCREENSHOT_TIMEOUT = Duration.seconds(20);
33// The hub's Android shutdown waits up to 30 s for the emulator to leave adb after the kill.
34const ANDROID_SHUTDOWN_TIMEOUT = Duration.seconds(45);
35const ADB_DEVICES_TIMEOUT = Duration.seconds(10);
36// Let the hub's 30 s simctl timeout report its cause first.
37const LIST_TIMEOUT_SECONDS = 40;
38// expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes.
39const SIMULATOR_LIST_FAILED =
40 /^\[apple-utils\] (?:Failed to (?:run `xcrun simctl list devices|parse JSON output:|list devices:)|`xcrun simctl list devices --json` did not respond within )/;
41// The hub passes numeric display IDs that Xcode 26 rejects; iOS 27 needs them for multiple displays.
42// expo-device-hub 0.22.1 returns no Android devices when avdmanager fails, before it runs adb.
43const AVDMANAGER_LIST_FAILED = "[android-utils] Failed to run `avdmanager list avd`";
44const GETPROP_LINE = /^\[([^\]]+)\]: \[(.*)\]$/;
45const runsOnXcode26Runtime = (version: string) => Number(/^iOS (\d+)/.exec(version)?.[1]) <= 26;
46const DEFAULT_DISPLAY_SCREENSHOT = `f=$(mktemp -t t3-screenshot) || exit 1
47trap 'rm -f "$f"' 0
48xcrun simctl io "$1" screenshot --type=png "$f" >/dev/null && base64 -i "$f"`;
49
50const HubDevice = Schema.Struct({
51 id: Schema.String,
52 name: Schema.String,
53 version: Schema.String,
54 platform: Schema.Literals(["ios", "android"]),
55 booted: Schema.Boolean,
56 physical: Schema.Boolean,
57});
58const HubDeviceList = Schema.Struct({
59 simulators: Schema.Array(HubDevice),
60 emulators: Schema.Array(HubDevice),
61 errors: Schema.optional(
62 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
63 ),
64});
65const HubActionResult = Schema.Struct({
66 ok: Schema.Boolean,
67 id: Schema.optional(Schema.String),
68 serial: Schema.optional(Schema.String),
69 error: Schema.optional(Schema.String),
70 errors: Schema.optional(
71 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
72 ),
73});
74const ServeEmuHealth = Schema.Struct({
75 ok: Schema.Boolean,
76 status: Schema.optional(Schema.String),
77 error: Schema.optional(Schema.String),
78});
79
80// Hub diagnostics can carry a whole stderr dump.
81const boundDiagnostics = (text: string) =>
82 text.length > 2_000 ? `${text.slice(0, 1_999).replace(/[\uD800-\uDBFF]$/u, "")}…` : text;
83
84// The hub's `error` is a util.inspect of Node's exec error; the stack and the
85// inspected fields follow the first frame, so keep the lines before it.
86const errorHead = (error: string) => {
87 const lines = error.split(/\r?\n/);
88 const firstFrame = lines.findIndex((line) => /^\s+at /.test(line));
89 return (firstFrame === -1 ? lines : lines.slice(0, firstFrame))
90 .map((line) => line.trim())
91 .filter(Boolean)
92 .join(" ");
93};
94
95const vendorPrefix = (platform: DevicePlatform) =>
96 platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
97
98/** Device operations for a host that runs expo-device-hub at `origin`. */
99export const makeDeviceHubOperations = (options: {
100 readonly hostId: DeviceHostId;
101 readonly origin: string;
102 readonly token?: string | undefined;
103 readonly http: HttpClient.HttpClient;
104 readonly run: DeviceHostReady["run"];
105 readonly platformAvailable: (platform: DevicePlatform) => Effect.Effect<boolean>;
106 /** Gates listing AVDs, which the hub does not report until they boot. Phones need only adb. */
107 readonly avdsAvailable?: Effect.Effect<boolean>;
108}): DeviceOperations => {
109 const { hostId, origin, run } = options;
110 const { token } = options;
111 const httpClient = (
112 token === undefined
113 ? options.http
114 : options.http.pipe(HttpClient.mapRequest(HttpClientRequest.bearerToken(token)))
115 ).pipe(HttpClient.withScope);
116
117 const fetchJson = Effect.fn("DeviceHubOperations.fetchJson")(function* <A, I>(
118 request: HttpClientRequest.HttpClientRequest,
119 schema: Schema.Codec<A, I>,
120 ) {
121 return yield* httpClient
122 .execute(request)
123 .pipe(
124 Effect.flatMap(HttpClientResponse.filterStatusOk),
125 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
126 Effect.scoped,
127 );
128 });
129
130 const hubJson = <A, I>(
131 request: HttpClientRequest.HttpClientRequest,
132 schema: Schema.Codec<A, I>,
133 operation: string,
134 timeout: Duration.Input = Duration.seconds(15),
135 ) =>
136 fetchJson(request, schema).pipe(
137 Effect.timeout(timeout),
138 Effect.mapError(
139 (cause) => new DeviceOperationError({ operation, reason: "request_failed", cause }),
140 ),
141 );
142
143 const postJson = (path: string, body: Record<string, string>, operation: string) =>
144 HttpClientRequest.post(`${origin}${path}`).pipe(
145 HttpClientRequest.bodyJson(body),
146 Effect.mapError(
147 (cause) => new DeviceOperationError({ operation, reason: "invalid_payload", cause }),
148 ),
149 );
150
151 // Booting alone does not attach a serve-sim helper; the grid start does both
152 // and is idempotent for a booted simulator.
153 const attachIosStream = (udid: string, operation: string) =>
154 postJson(`${vendorPrefix("ios")}/grid/api/start`, { udid }, operation).pipe(
155 Effect.flatMap((request) => hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT)),
156 );
157
158 // Mirrors the hub's own adb discovery for when it skips it.
159 const listAdbDevices = Effect.gen(function* () {
160 const listed = yield* run("adb", ["devices", "-l"]);
161 if (listed.code !== 0) return undefined;
162 const serials = listed.stdout
163 .split(/\r?\n/)
164 .map((line) => line.trim().split(/\s+/))
165 .flatMap(([serial, state]) => (serial && state === "device" ? [serial] : []));
166 return yield* Effect.forEach(serials, (serial) =>
167 Effect.gen(function* () {
168 const getprop = yield* run("adb", ["-s", serial, "shell", "getprop"]);
169 const props = new Map(
170 getprop.stdout.split(/\r?\n/).flatMap((line) => {
171 const match = GETPROP_LINE.exec(line.trim());
172 return match ? [[match[1]!, match[2]!] as const] : [];
173 }),
174 );
175 const emulator = props.get("ro.kernel.qemu") === "1" || props.get("ro.boot.qemu") === "1";
176 const avdName = emulator
177 ? (yield* run("adb", ["-s", serial, "emu", "avd", "name"])).stdout
178 .split(/\r?\n/)
179 .map((line) => line.trim())
180 .find((line) => line && line !== "OK" && !line.startsWith("KO"))
181 : undefined;
182 const model = props.get("ro.product.model");
183 const manufacturer = props.get("ro.product.manufacturer");
184 const release = props.get("ro.build.version.release");
185 return {
186 id: serial,
187 name: emulator
188 ? (avdName ?? serial)
189 : model
190 ? [manufacturer, model].filter(Boolean).join(" ")
191 : serial,
192 platform: "android",
193 version: release
194 ? `Android ${/^\d+$/.test(release) ? `${release}.0` : release}`
195 : "Android",
196 booted: true,
197 physical: !emulator,
198 } satisfies HostDevice;
199 }),
200 );
201 });
202
203 const list: DeviceOperations["list"] = Effect.gen(function* () {
204 const listed = yield* fetchJson(
205 HttpClientRequest.get(`${origin}/api/devices`),
206 HubDeviceList,
207 ).pipe(
208 Effect.mapError(
209 (cause) => new DeviceOperationError({ operation: "list", reason: "request_failed", cause }),
210 ),
211 Effect.timeoutOption(Duration.seconds(LIST_TIMEOUT_SECONDS)),
212 );
213 if (Option.isNone(listed)) {
214 return {
215 devices: [],
216 detail: `The device hub did not answer within ${LIST_TIMEOUT_SECONDS} seconds.`,
217 incompletePlatforms: yield* Effect.filter(["ios", "android"] as const, (platform) =>
218 options.platformAvailable(platform),
219 ),
220 };
221 }
222 const hubList = listed.value;
223 const devices: Array<HostDevice> = [...hubList.simulators, ...hubList.emulators];
224 const androidAvailable = yield* options.platformAvailable("android");
225 const avdsAvailable =
226 androidAvailable && (yield* options.avdsAvailable ?? Effect.succeed(true));
227 const warnings = hubList.errors?.filter(
228 (error) =>
229 // The host summary already explains a missing Android SDK; the hub's failed probes are noise.
230 !(!androidAvailable && error.message.startsWith("[android-utils] ")) &&
231 // Without emulator tooling, avdmanager is expected to be missing.
232 !(!avdsAvailable && error.message.startsWith(AVDMANAGER_LIST_FAILED)) &&
233 // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
234 !(
235 error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
236 /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
237 /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
238 ),
239 );
240 const details =
241 warnings?.map((error) => {
242 const head = errorHead(error.error ?? "");
243 return boundDiagnostics(head ? `${error.message} ${head}` : error.message);
244 }) ?? [];
245 let androidDiscoveryIncomplete = false;
246 if (androidAvailable) {
247 if (hubList.errors?.some((error) => error.message.startsWith(AVDMANAGER_LIST_FAILED))) {
248 const adbDevices = yield* listAdbDevices;
249 if (adbDevices === undefined) {
250 androidDiscoveryIncomplete = true;
251 details.push("Could not list Android devices (adb devices -l).");
252 } else {
253 devices.push(...adbDevices);
254 }
255 }
256 }
257 if (avdsAvailable) {
258 const avds = yield* run("emulator", ["-list-avds"]);
259 // Discovered devices stay listed; the AVDs that could not be listed are a warning.
260 if (avds.code !== 0) {
261 androidDiscoveryIncomplete = true;
262 details.push(
263 `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
264 );
265 }
266 for (const name of (avds.code === 0 ? avds.stdout : "")
267 .split(/\r?\n/)
268 .map((line) => line.trim())
269 .filter(Boolean)) {
270 if (!devices.some((device) => device.platform === "android" && device.name === name)) {
271 devices.push({
272 id: name,
273 name,
274 platform: "android",
275 version: "Android",
276 booted: false,
277 physical: false,
278 });
279 }
280 }
281 }
282 const simulatorsUnlisted =
283 hubList.simulators.length === 0 &&
284 (hubList.errors ?? []).some((error) => SIMULATOR_LIST_FAILED.test(error.message));
285 return {
286 devices,
287 detail: details.join("\n") || undefined,
288 androidDiscoveryIncomplete,
289 ...(simulatorsUnlisted ? { incompletePlatforms: ["ios"] as const } : {}),
290 };
291 }).pipe(Effect.withSpan("DeviceHubOperations.list"));
292
293 // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an
294 // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer
295 // lists its serial in any state.
296 const emulatorExited = (serial: string, timeoutMs = Duration.toMillis(ADB_DEVICES_TIMEOUT)) =>
297 EMULATOR_SERIAL.test(serial) && timeoutMs > 0
298 ? run("adb", ["devices"], { timeoutMs }).pipe(
299 Effect.map(
300 ({ code, stdout }) =>
301 code === 0 &&
302 !stdout.split(/\r?\n/).some((line) => line.trim().split(/\s+/)[0] === serial),
303 ),
304 Effect.orElseSucceed(() => false),
305 )
306 : Effect.succeed(false);
307
308 const emulatorExitedDuringBoot = (
309 device: HostDevice,
310 serial: string,
311 stage: string,
312 cause: unknown,
313 ) =>
314 new DeviceBootError({
315 hostId,
316 deviceId: device.id,
317 reason: "launch_failed",
318 diagnostics: boundDiagnostics(
319 `The emulator process for "${device.name}" (${serial}) exited ${stage}.`,
320 ),
321 cause,
322 });
323
324 // Require two omissions separated by a poll interval so a brief adb transport blip is not misread
325 // as a process exit (an external adb server restart can still briefly return empty lists).
326 // Callers reserve ANDROID_EXIT_CONFIRM_RESERVE_MS inside deadlineMs so exit checks stay within budget.
327 const confirmEmulatorExited = Effect.fn("DeviceHubOperations.confirmEmulatorExited")(function* (
328 serial: string,
329 deadlineMs: number,
330 ) {
331 const probeTimeoutMs = Duration.toMillis(ANDROID_EXIT_PROBE_TIMEOUT);
332 const firstBudgetMs = Math.min(probeTimeoutMs, deadlineMs - (yield* Clock.currentTimeMillis));
333 if (!(yield* emulatorExited(serial, firstBudgetMs))) return false;
334 if (
335 deadlineMs - (yield* Clock.currentTimeMillis) <=
336 Duration.toMillis(ANDROID_BOOT_POLL_INTERVAL)
337 ) {
338 return false;
339 }
340 yield* Effect.sleep(ANDROID_BOOT_POLL_INTERVAL);
341 const secondBudgetMs = Math.min(probeTimeoutMs, deadlineMs - (yield* Clock.currentTimeMillis));
342 return yield* emulatorExited(serial, secondBudgetMs);
343 });
344
345 // Returns true once sys.boot_completed=1, false if a slow boot outlasts the deadline (so boot
346 // degrades to opening), and fails with DeviceBootError only when the emulator is confirmed gone.
347 const waitForAndroidBootCompleted = Effect.fn("DeviceHubOperations.waitForAndroidBootCompleted")(
348 function* (device: HostDevice, serial: string, deadlineMs: number) {
349 const probeDeadlineMs = deadlineMs - ANDROID_EXIT_CONFIRM_RESERVE_MS;
350 while (true) {
351 const remainingMs = probeDeadlineMs - (yield* Clock.currentTimeMillis);
352 if (remainingMs <= 0) {
353 yield* Effect.logWarning("Timed out waiting for Android boot completion", {
354 hostId,
355 serial,
356 });
357 return false;
358 }
359 const probe = yield* run("adb", ["-s", serial, "shell", "getprop", "sys.boot_completed"], {
360 timeoutMs: Math.min(Duration.toMillis(ADB_DEVICES_TIMEOUT), remainingMs),
361 });
362 if (probe.code === 0 && probe.stdout.trim() === "1") return true;
363 if (probe.code !== 0 && (yield* confirmEmulatorExited(serial, deadlineMs))) {
364 return yield* emulatorExitedDuringBoot(device, serial, "before finishing boot", probe);
365 }
366 if (
367 probeDeadlineMs - (yield* Clock.currentTimeMillis) <=
368 Duration.toMillis(ANDROID_BOOT_POLL_INTERVAL)
369 ) {
370 yield* Effect.logWarning("Timed out waiting for Android boot completion", {
371 hostId,
372 serial,
373 });
374 return false;
375 }
376 yield* Effect.sleep(ANDROID_BOOT_POLL_INTERVAL);
377 }
378 },
379 );
380
381 // serve-emu starts its capture session lazily on /health and returns 200 once streaming.
382 // Video/HTTP failures degrade so agent-only flows and Reconnect still work; a confirmed
383 // emulator exit fails so boot does not return a gone serial.
384 const warmAndroidStream = Effect.fn("DeviceHubOperations.warmAndroidStream")(function* (
385 device: HostDevice,
386 serial: string,
387 deadlineMs: number,
388 ) {
389 const probeDeadlineMs = deadlineMs - ANDROID_EXIT_CONFIRM_RESERVE_MS;
390 let startupFailures = 0;
391 while (true) {
392 const remainingMs = probeDeadlineMs - (yield* Clock.currentTimeMillis);
393 if (remainingMs <= 0) {
394 yield* Effect.logWarning("Android stream warm-up timed out", { hostId, serial });
395 return;
396 }
397 const attempt = yield* httpClient
398 .execute(
399 HttpClientRequest.get(
400 `${origin}${vendorPrefix("android")}/health?device=${encodeURIComponent(serial)}`,
401 ),
402 )
403 .pipe(
404 Effect.flatMap((res) =>
405 HttpClientResponse.schemaBodyJson(ServeEmuHealth)(res).pipe(
406 Effect.option,
407 Effect.map((body) => ({ status: res.status, body })),
408 ),
409 ),
410 Effect.scoped,
411 Effect.timeout(Duration.millis(remainingMs)),
412 Effect.result,
413 );
414 if (attempt._tag === "Failure") {
415 if (yield* confirmEmulatorExited(serial, deadlineMs)) {
416 return yield* emulatorExitedDuringBoot(
417 device,
418 serial,
419 "during stream warm-up",
420 attempt.failure,
421 );
422 }
423 yield* Effect.logWarning("Android stream warm-up request failed", {
424 hostId,
425 serial,
426 reason: Cause.isTimeoutError(attempt.failure) ? "timeout" : "request_failed",
427 });
428 return;
429 }
430 const response = attempt.success;
431 const body = Option.getOrUndefined(response.body);
432 if (
433 response.status >= 200 &&
434 response.status < 300 &&
435 body !== undefined &&
436 body.ok &&
437 (body.status === undefined || body.status === "streaming")
438 ) {
439 return;
440 }
441 if (response.status !== 503) {
442 yield* Effect.logWarning("Android stream warm-up returned an unexpected response", {
443 hostId,
444 serial,
445 status: response.status,
446 });
447 return;
448 }
449 if (yield* confirmEmulatorExited(serial, deadlineMs)) {
450 return yield* emulatorExitedDuringBoot(
451 device,
452 serial,
453 "during stream warm-up",
454 body ?? { status: response.status },
455 );
456 }
457 const coolingDown = SERVE_EMU_COOLING_DOWN.test(body?.error ?? "");
458 if (!coolingDown && ++startupFailures >= ANDROID_MAX_WARMUP_FAILURES) {
459 yield* Effect.logWarning("Android stream warm-up did not become ready", {
460 hostId,
461 serial,
462 status: response.status,
463 });
464 return;
465 }
466 if (
467 probeDeadlineMs - (yield* Clock.currentTimeMillis) <=
468 Duration.toMillis(ANDROID_STREAM_POLL_INTERVAL)
469 ) {
470 yield* Effect.logWarning("Android stream warm-up timed out", { hostId, serial });
471 return;
472 }
473 yield* Effect.sleep(ANDROID_STREAM_POLL_INTERVAL);
474 }
475 });
476
477 const boot: DeviceOperations["boot"] = Effect.fn("DeviceHubOperations.boot")(function* (device) {
478 const result = yield* postJson(
479 "/api/devices/boot",
480 { platform: device.platform, id: device.id, name: device.name },
481 "boot",
482 ).pipe(Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)));
483 if (!result.ok) {
484 // Keep the hub's launch command and nested failure available to agents for recovery.
485 const diagnostics = [
486 result.error,
487 ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
488 ]
489 .filter((text) => text?.trim())
490 .join("\n\n");
491 return yield* new DeviceBootError({
492 hostId,
493 deviceId: device.id,
494 reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
495 diagnostics,
496 )
497 ? "disk_space"
498 : /timed? out|timeout/i.test(diagnostics)
499 ? "timeout"
500 : "launch_failed",
501 ...(diagnostics ? { diagnostics: boundDiagnostics(diagnostics) } : {}),
502 cause: result,
503 });
504 }
505 const bootedId = result.serial ?? result.id ?? device.id;
506 if (device.platform === "ios") {
507 yield* attachIosStream(device.id, "boot");
508 } else if (
509 device.platform === "android" &&
510 !device.physical &&
511 EMULATOR_SERIAL.test(bootedId)
512 ) {
513 const bootDeadlineMs =
514 (yield* Clock.currentTimeMillis) + Duration.toMillis(ANDROID_BOOT_COMPLETED_TIMEOUT);
515 const bootCompleted = yield* waitForAndroidBootCompleted(device, bootedId, bootDeadlineMs);
516 if (bootCompleted) {
517 const warmupDeadlineMs =
518 (yield* Clock.currentTimeMillis) + Duration.toMillis(ANDROID_BOOT_WARMUP_TIMEOUT);
519 yield* warmAndroidStream(device, bootedId, warmupDeadlineMs);
520 }
521 }
522 return bootedId;
523 });
524
525 const attach: DeviceOperations["attach"] = (device) =>
526 device.platform === "ios"
527 ? attachIosStream(device.id, "open").pipe(Effect.asVoid)
528 : Effect.void;
529
530 const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")(
531 function* (device) {
532 const postShutdown = (path: string, body: Record<string, string>, timeout?: Duration.Input) =>
533 postJson(path, body, "shutdown").pipe(
534 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown", timeout)),
535 Effect.flatMap((result) =>
536 result.ok
537 ? Effect.void
538 : Effect.fail(
539 new DeviceOperationError({
540 operation: "shutdown",
541 reason: "hub_rejected",
542 cause: result,
543 }),
544 ),
545 ),
546 );
547 // serve-sim's shutdown closes its in-process capture session before it
548 // runs `simctl shutdown`; the hub's generic shutdown can leave that
549 // session cached across a reboot. serve-sim runs simctl bare, though, so
550 // a simulator that is already off fails there.
551 yield* device.platform === "ios"
552 ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: device.id }).pipe(
553 Effect.catch((cause) =>
554 list.pipe(
555 Effect.flatMap(({ devices }) =>
556 devices.find((candidate) => candidate.id === device.id)?.booted === false
557 ? Effect.logInfo("iOS simulator was already shut down", { deviceId: device.id })
558 : Effect.fail(cause),
559 ),
560 ),
561 ),
562 )
563 : postShutdown(
564 "/api/devices/shutdown",
565 { platform: device.platform, id: device.id },
566 ANDROID_SHUTDOWN_TIMEOUT,
567 ).pipe(
568 Effect.catch((cause) =>
569 emulatorExited(device.id).pipe(
570 Effect.flatMap((exited) =>
571 exited
572 ? Effect.logInfo("Android emulator has exited", {
573 deviceId: device.id,
574 })
575 : Effect.fail(cause),
576 ),
577 ),
578 ),
579 );
580 },
581 );
582
583 const defaultDisplayScreenshot = Effect.fn("DeviceHubOperations.defaultDisplayScreenshot")(
584 function* (udid: string) {
585 const capture = yield* run("sh", ["-c", DEFAULT_DISPLAY_SCREENSHOT, "sh", udid], {
586 timeoutMs: Duration.toMillis(SCREENSHOT_TIMEOUT),
587 maxOutputBytes: 64 * 1024 * 1024,
588 });
589 if (capture.code !== 0) {
590 return yield* new DeviceOperationError({
591 operation: "screenshot",
592 reason: "command_failed",
593 exitCode: capture.code,
594 cause: capture.stderr.trim(),
595 });
596 }
597 return new Uint8Array(Buffer.from(capture.stdout, "base64"));
598 },
599 );
600
601 const screenshot: DeviceOperations["screenshot"] = (device) =>
602 httpClient
603 .execute(
604 HttpClientRequest.post(
605 `${origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`,
606 ),
607 )
608 .pipe(
609 Effect.flatMap(HttpClientResponse.filterStatusOk),
610 Effect.flatMap((response) => response.arrayBuffer),
611 Effect.map((buffer) => new Uint8Array(buffer)),
612 Effect.scoped,
613 Effect.timeout(SCREENSHOT_TIMEOUT),
614 Effect.mapError(
615 (cause) =>
616 new DeviceOperationError({
617 operation: "screenshot",
618 reason:
619 HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
620 ? "hub_rejected"
621 : "request_failed",
622 cause,
623 }),
624 ),
625 Effect.catchIf(
626 (error) =>
627 device.platform === "ios" &&
628 runsOnXcode26Runtime(device.version) &&
629 error.reason === "hub_rejected",
630 () => defaultDisplayScreenshot(device.id),
631 ),
632 Effect.withSpan("DeviceHubOperations.screenshot"),
633 );
634
635 return { list, boot, attach, shutdown, screenshot };
636};