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 * as Result from "effect/Result";
12import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
13
14import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost.ts";
15
16const BOOT_TIMEOUT = Duration.minutes(3);
17const SCREENSHOT_TIMEOUT = Duration.seconds(20);
18// Let the hub's 30 s simctl timeout report its cause first.
19const LIST_TIMEOUT_SECONDS = 40;
20// expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes.
21const SIMULATOR_LIST_FAILED =
22 /^\[apple-utils\] (?:Failed to (?:run `xcrun simctl list devices|parse JSON output:|list devices:)|`xcrun simctl list devices --json` did not respond within )/;
23
24const HubDevice = Schema.Struct({
25 id: Schema.String,
26 name: Schema.String,
27 version: Schema.String,
28 platform: Schema.Literals(["ios", "android"]),
29 booted: Schema.Boolean,
30 physical: Schema.Boolean,
31});
32const HubDeviceList = Schema.Struct({
33 simulators: Schema.Array(HubDevice),
34 emulators: Schema.Array(HubDevice),
35 errors: Schema.optional(
36 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
37 ),
38});
39const SimctlDeviceList = Schema.fromJsonString(
40 Schema.Struct({
41 devices: Schema.Record(
42 Schema.String,
43 Schema.Array(
44 Schema.Struct({
45 udid: Schema.String,
46 name: Schema.String,
47 state: Schema.String,
48 isAvailable: Schema.Boolean,
49 }),
50 ),
51 ),
52 }),
53);
54const decodeSimctlDeviceList = Schema.decodeUnknownEffect(SimctlDeviceList);
55const HubActionResult = Schema.Struct({
56 ok: Schema.Boolean,
57 id: Schema.optional(Schema.String),
58 serial: Schema.optional(Schema.String),
59 error: Schema.optional(Schema.String),
60 errors: Schema.optional(
61 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
62 ),
63});
64
65// Hub diagnostics can carry a whole stderr dump.
66const boundDiagnostics = (text: string) =>
67 text.length > 2_000 ? `${text.slice(0, 1_999)}…` : text;
68
69// The hub's `error` is a util.inspect of Node's exec error; the stack and the
70// inspected fields follow the first frame, so keep the lines before it.
71const errorHead = (error: string) => {
72 const lines = error.split(/\r?\n/);
73 const firstFrame = lines.findIndex((line) => /^\s+at /.test(line));
74 return (firstFrame === -1 ? lines : lines.slice(0, firstFrame))
75 .map((line) => line.trim())
76 .filter(Boolean)
77 .join(" ");
78};
79
80const vendorPrefix = (platform: DevicePlatform) =>
81 platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
82
83/** Device operations for a host that runs expo-device-hub at `origin`. */
84export const makeDeviceHubOperations = (options: {
85 readonly hostId: DeviceHostId;
86 readonly origin: string;
87 readonly http: HttpClient.HttpClient;
88 readonly run: DeviceHostReady["run"];
89 /** Discover both platforms once per refresh, including devices the hub has never seen boot. */
90 readonly availablePlatforms: Effect.Effect<{
91 readonly ios: boolean;
92 readonly android: boolean;
93 readonly probeFailed?: boolean;
94 }>;
95}): DeviceOperations => {
96 const { hostId, origin, run } = options;
97 const httpClient = options.http.pipe(HttpClient.withScope);
98
99 const fetchJson = Effect.fn("DeviceHubOperations.fetchJson")(function* <A, I>(
100 request: HttpClientRequest.HttpClientRequest,
101 schema: Schema.Codec<A, I>,
102 ) {
103 return yield* httpClient
104 .execute(request)
105 .pipe(
106 Effect.flatMap(HttpClientResponse.filterStatusOk),
107 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
108 Effect.scoped,
109 );
110 });
111
112 const hubJson = <A, I>(
113 request: HttpClientRequest.HttpClientRequest,
114 schema: Schema.Codec<A, I>,
115 operation: string,
116 timeout: Duration.Input = Duration.seconds(15),
117 ) =>
118 fetchJson(request, schema).pipe(
119 Effect.timeout(timeout),
120 Effect.mapError(
121 (cause) => new DeviceOperationError({ operation, reason: "request_failed", cause }),
122 ),
123 );
124
125 const postJson = (path: string, body: Record<string, string>, operation: string) =>
126 HttpClientRequest.post(`${origin}${path}`).pipe(
127 HttpClientRequest.bodyJson(body),
128 Effect.mapError(
129 (cause) => new DeviceOperationError({ operation, reason: "invalid_payload", cause }),
130 ),
131 );
132
133 // Booting alone does not attach a serve-sim helper; the grid start does both
134 // and is idempotent for a booted simulator.
135 const attachIosStream = (udid: string, operation: string) =>
136 postJson(`${vendorPrefix("ios")}/grid/api/start`, { udid }, operation).pipe(
137 Effect.flatMap((request) => hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT)),
138 );
139
140 const list: DeviceOperations["list"] = Effect.gen(function* () {
141 const listed = yield* fetchJson(
142 HttpClientRequest.get(`${origin}/api/devices`),
143 HubDeviceList,
144 ).pipe(
145 Effect.mapError(
146 (cause) => new DeviceOperationError({ operation: "list", reason: "request_failed", cause }),
147 ),
148 Effect.timeoutOption(Duration.seconds(LIST_TIMEOUT_SECONDS)),
149 );
150 const available = yield* options.availablePlatforms;
151 if (Option.isNone(listed)) {
152 return {
153 devices: [],
154 detail: `The device hub did not answer within ${LIST_TIMEOUT_SECONDS} seconds.`,
155 incompletePlatforms: (["ios", "android"] as const).filter(
156 (platform) => available.probeFailed || available[platform],
157 ),
158 };
159 }
160 const hubList = listed.value;
161 const devices: Array<HostDevice> = [...hubList.simulators, ...hubList.emulators];
162 const warnings = hubList.errors?.filter(
163 (error) =>
164 // The host summary already explains a missing Android SDK; the hub's failed probes are noise.
165 !(!available.android && error.message.startsWith("[android-utils] ")) &&
166 // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
167 !(
168 error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
169 /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
170 /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
171 ),
172 );
173 const details =
174 warnings?.map((error) => {
175 const head = errorHead(error.error ?? "");
176 return boundDiagnostics(head ? `${error.message} ${head}` : error.message);
177 }) ?? [];
178 if (available.probeFailed) {
179 details.push(
180 "Could not determine host platform availability. Device discovery may be incomplete.",
181 );
182 }
183 let iosDiscoveryIncomplete = available.probeFailed ?? false;
184 if (available.ios) {
185 const inventory = yield* run("xcrun", ["simctl", "list", "devices", "--json"]);
186 const decoded = yield* decodeSimctlDeviceList(inventory.stdout).pipe(Effect.result);
187 if (inventory.code !== 0 || Result.isFailure(decoded)) {
188 iosDiscoveryIncomplete = true;
189 details.push(
190 "Could not list all iOS simulators (xcrun simctl list devices --json). Discovered devices remain available.",
191 );
192 } else {
193 for (const [runtime, simulators] of Object.entries(decoded.success.devices)) {
194 const prefix = "com.apple.CoreSimulator.SimRuntime.iOS-";
195 if (!runtime.startsWith(prefix)) continue;
196 for (const simulator of simulators) {
197 if (
198 !simulator.isAvailable ||
199 devices.some((device) => device.platform === "ios" && device.id === simulator.udid)
200 )
201 continue;
202 devices.push({
203 id: simulator.udid,
204 name: simulator.name,
205 version: `iOS ${runtime.slice(prefix.length).replaceAll("-", ".")}`,
206 platform: "ios",
207 booted: simulator.state === "Booted",
208 physical: false,
209 });
210 }
211 }
212 }
213 }
214 let androidDiscoveryIncomplete = false;
215 if (available.android) {
216 const avds = yield* run("emulator", ["-list-avds"]);
217 // Discovered devices stay listed; the AVDs that could not be listed are a warning.
218 if (avds.code !== 0) {
219 androidDiscoveryIncomplete = true;
220 details.push(
221 `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
222 );
223 }
224 for (const name of (avds.code === 0 ? avds.stdout : "")
225 .split(/\r?\n/)
226 .map((line) => line.trim())
227 .filter(Boolean)) {
228 if (!devices.some((device) => device.platform === "android" && device.name === name)) {
229 devices.push({
230 id: name,
231 name,
232 platform: "android",
233 version: "Android",
234 booted: false,
235 physical: false,
236 });
237 }
238 }
239 }
240 const simulatorsUnlisted =
241 !devices.some((device) => device.platform === "ios") &&
242 (iosDiscoveryIncomplete ||
243 (hubList.errors ?? []).some((error) => SIMULATOR_LIST_FAILED.test(error.message)));
244 return {
245 devices,
246 detail: details.join("\n") || undefined,
247 androidDiscoveryIncomplete,
248 ...(simulatorsUnlisted ? { incompletePlatforms: ["ios"] as const } : {}),
249 };
250 }).pipe(Effect.withSpan("DeviceHubOperations.list"));
251
252 const boot: DeviceOperations["boot"] = Effect.fn("DeviceHubOperations.boot")(function* (device) {
253 const result = yield* postJson(
254 "/api/devices/boot",
255 { platform: device.platform, id: device.id, name: device.name },
256 "boot",
257 ).pipe(Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)));
258 if (!result.ok) {
259 // Keep the hub's launch command and nested failure available to agents for recovery.
260 const diagnostics = [
261 result.error,
262 ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
263 ]
264 .filter((text) => text?.trim())
265 .join("\n\n");
266 return yield* new DeviceBootError({
267 hostId,
268 deviceId: device.id,
269 reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
270 diagnostics,
271 )
272 ? "disk_space"
273 : /timed? out|timeout/i.test(diagnostics)
274 ? "timeout"
275 : "launch_failed",
276 ...(diagnostics ? { diagnostics: boundDiagnostics(diagnostics) } : {}),
277 cause: result,
278 });
279 }
280 if (device.platform === "ios") yield* attachIosStream(device.id, "boot");
281 return result.serial ?? result.id ?? device.id;
282 });
283
284 const attach: DeviceOperations["attach"] = (device) =>
285 device.platform === "ios"
286 ? attachIosStream(device.id, "open").pipe(Effect.asVoid)
287 : Effect.void;
288
289 const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")(
290 function* (device) {
291 const postShutdown = (path: string, body: Record<string, string>) =>
292 postJson(path, body, "shutdown").pipe(
293 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")),
294 Effect.flatMap((result) =>
295 result.ok
296 ? Effect.void
297 : Effect.fail(
298 new DeviceOperationError({
299 operation: "shutdown",
300 reason: "hub_rejected",
301 cause: result,
302 }),
303 ),
304 ),
305 );
306 // serve-sim's shutdown closes its in-process capture session before it
307 // runs `simctl shutdown`; the hub's generic shutdown can leave that
308 // session cached across a reboot. serve-sim runs simctl bare, though, so
309 // a simulator that is already off fails there.
310 yield* device.platform === "ios"
311 ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: device.id }).pipe(
312 Effect.catch((cause) =>
313 list.pipe(
314 Effect.flatMap(({ devices }) =>
315 devices.find((candidate) => candidate.id === device.id)?.booted === false
316 ? Effect.logInfo("iOS simulator was already shut down", { deviceId: device.id })
317 : Effect.fail(cause),
318 ),
319 ),
320 ),
321 )
322 : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id });
323 },
324 );
325
326 const screenshot: DeviceOperations["screenshot"] = (device) =>
327 httpClient
328 .execute(
329 HttpClientRequest.post(
330 `${origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`,
331 ),
332 )
333 .pipe(
334 Effect.flatMap(HttpClientResponse.filterStatusOk),
335 Effect.flatMap((response) => response.arrayBuffer),
336 Effect.map((buffer) => new Uint8Array(buffer)),
337 Effect.scoped,
338 Effect.timeout(SCREENSHOT_TIMEOUT),
339 Effect.mapError(
340 (cause) =>
341 new DeviceOperationError({
342 operation: "screenshot",
343 reason:
344 HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
345 ? "hub_rejected"
346 : "request_failed",
347 cause,
348 }),
349 ),
350 Effect.withSpan("DeviceHubOperations.screenshot"),
351 );
352
353 return { list, boot, attach, shutdown, screenshot };
354};