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 Schema from "effect/Schema";
10import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
11
12import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost.ts";
13
14const BOOT_TIMEOUT = Duration.minutes(3);
15const SCREENSHOT_TIMEOUT = Duration.seconds(20);
16
17const HubDevice = Schema.Struct({
18 id: Schema.String,
19 name: Schema.String,
20 version: Schema.String,
21 platform: Schema.Literals(["ios", "android"]),
22 booted: Schema.Boolean,
23 physical: Schema.Boolean,
24});
25const HubDeviceList = Schema.Struct({
26 simulators: Schema.Array(HubDevice),
27 emulators: Schema.Array(HubDevice),
28 errors: Schema.optional(
29 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
30 ),
31});
32const HubActionResult = Schema.Struct({
33 ok: Schema.Boolean,
34 id: Schema.optional(Schema.String),
35 serial: Schema.optional(Schema.String),
36 error: Schema.optional(Schema.String),
37 errors: Schema.optional(
38 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
39 ),
40});
41
42// Hub diagnostics can carry a whole stderr dump.
43const boundDiagnostics = (text: string) =>
44 text.length > 2_000 ? `${text.slice(0, 1_999)}…` : text;
45
46// The hub's `error` is a util.inspect of Node's exec error; the stack and the
47// inspected fields follow the first frame, so keep the lines before it.
48const errorHead = (error: string) => {
49 const lines = error.split(/\r?\n/);
50 const firstFrame = lines.findIndex((line) => /^\s+at /.test(line));
51 return (firstFrame === -1 ? lines : lines.slice(0, firstFrame))
52 .map((line) => line.trim())
53 .filter(Boolean)
54 .join(" ");
55};
56
57const vendorPrefix = (platform: DevicePlatform) =>
58 platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
59
60/** Device operations for a host that runs expo-device-hub at `origin`. */
61export const makeDeviceHubOperations = (options: {
62 readonly hostId: DeviceHostId;
63 readonly origin: string;
64 readonly http: HttpClient.HttpClient;
65 readonly run: DeviceHostReady["run"];
66 /** Whether to list AVDs, which the hub does not report until they boot. */
67 readonly androidAvailable: Effect.Effect<boolean>;
68}): DeviceOperations => {
69 const { hostId, origin, run } = options;
70 const httpClient = options.http.pipe(HttpClient.withScope);
71
72 const hubJson = <A, I>(
73 request: HttpClientRequest.HttpClientRequest,
74 schema: Schema.Codec<A, I>,
75 operation: string,
76 timeout: Duration.Input = Duration.seconds(15),
77 ) =>
78 httpClient.execute(request).pipe(
79 Effect.flatMap(HttpClientResponse.filterStatusOk),
80 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
81 Effect.scoped,
82 Effect.timeout(timeout),
83 Effect.mapError(
84 (cause) =>
85 new DeviceOperationError({
86 operation,
87 reason: "request_failed",
88 cause,
89 }),
90 ),
91 );
92
93 const postJson = (path: string, body: Record<string, string>, operation: string) =>
94 HttpClientRequest.post(`${origin}${path}`).pipe(
95 HttpClientRequest.bodyJson(body),
96 Effect.mapError(
97 (cause) => new DeviceOperationError({ operation, reason: "invalid_payload", cause }),
98 ),
99 );
100
101 // Booting alone does not attach a serve-sim helper; the grid start does both
102 // and is idempotent for a booted simulator.
103 const attachIosStream = (udid: string, operation: string) =>
104 postJson(`${vendorPrefix("ios")}/grid/api/start`, { udid }, operation).pipe(
105 Effect.flatMap((request) => hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT)),
106 );
107
108 const list: DeviceOperations["list"] = Effect.gen(function* () {
109 const hubList = yield* hubJson(
110 HttpClientRequest.get(`${origin}/api/devices`),
111 HubDeviceList,
112 "list",
113 );
114 const devices: Array<HostDevice> = [...hubList.simulators, ...hubList.emulators];
115 const androidAvailable = yield* options.androidAvailable;
116 const warnings = hubList.errors?.filter(
117 (error) =>
118 // The host summary already explains a missing Android SDK; the hub's failed probes are noise.
119 !(!androidAvailable && error.message.startsWith("[android-utils] ")) &&
120 // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
121 !(
122 error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
123 /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
124 /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
125 ),
126 );
127 const details =
128 warnings?.map((error) => {
129 const head = errorHead(error.error ?? "");
130 return boundDiagnostics(head ? `${error.message} ${head}` : error.message);
131 }) ?? [];
132 let androidDiscoveryIncomplete = false;
133 if (androidAvailable) {
134 const avds = yield* run("emulator", ["-list-avds"]);
135 // Discovered devices stay listed; the AVDs that could not be listed are a warning.
136 if (avds.code !== 0) {
137 androidDiscoveryIncomplete = true;
138 details.push(
139 `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
140 );
141 }
142 for (const name of (avds.code === 0 ? avds.stdout : "")
143 .split(/\r?\n/)
144 .map((line) => line.trim())
145 .filter(Boolean)) {
146 if (!devices.some((device) => device.platform === "android" && device.name === name)) {
147 devices.push({
148 id: name,
149 name,
150 platform: "android",
151 version: "Android",
152 booted: false,
153 physical: false,
154 });
155 }
156 }
157 }
158 return {
159 devices,
160 detail: details.join("\n") || undefined,
161 androidDiscoveryIncomplete,
162 };
163 }).pipe(Effect.withSpan("DeviceHubOperations.list"));
164
165 const boot: DeviceOperations["boot"] = Effect.fn("DeviceHubOperations.boot")(function* (device) {
166 const result = yield* postJson(
167 "/api/devices/boot",
168 { platform: device.platform, id: device.id, name: device.name },
169 "boot",
170 ).pipe(Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)));
171 if (!result.ok) {
172 // Keep the hub's launch command and nested failure available to agents for recovery.
173 const diagnostics = [
174 result.error,
175 ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
176 ]
177 .filter((text) => text?.trim())
178 .join("\n\n");
179 return yield* new DeviceBootError({
180 hostId,
181 deviceId: device.id,
182 reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
183 diagnostics,
184 )
185 ? "disk_space"
186 : /timed? out|timeout/i.test(diagnostics)
187 ? "timeout"
188 : "launch_failed",
189 ...(diagnostics ? { diagnostics: boundDiagnostics(diagnostics) } : {}),
190 cause: result,
191 });
192 }
193 if (device.platform === "ios") yield* attachIosStream(device.id, "boot");
194 return result.serial ?? result.id ?? device.id;
195 });
196
197 const attach: DeviceOperations["attach"] = (device) =>
198 device.platform === "ios"
199 ? attachIosStream(device.id, "open").pipe(Effect.asVoid)
200 : Effect.void;
201
202 const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")(
203 function* (device) {
204 const postShutdown = (path: string, body: Record<string, string>) =>
205 postJson(path, body, "shutdown").pipe(
206 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")),
207 Effect.flatMap((result) =>
208 result.ok
209 ? Effect.void
210 : Effect.fail(
211 new DeviceOperationError({
212 operation: "shutdown",
213 reason: "hub_rejected",
214 cause: result,
215 }),
216 ),
217 ),
218 );
219 // serve-sim's shutdown closes its in-process capture session before it
220 // runs `simctl shutdown`; the hub's generic shutdown can leave that
221 // session cached across a reboot. serve-sim runs simctl bare, though, so
222 // a simulator that is already off fails there.
223 yield* device.platform === "ios"
224 ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: device.id }).pipe(
225 Effect.catch((cause) =>
226 list.pipe(
227 Effect.flatMap(({ devices }) =>
228 devices.find((candidate) => candidate.id === device.id)?.booted === false
229 ? Effect.logInfo("iOS simulator was already shut down", { deviceId: device.id })
230 : Effect.fail(cause),
231 ),
232 ),
233 ),
234 )
235 : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id });
236 },
237 );
238
239 const screenshot: DeviceOperations["screenshot"] = (device) =>
240 httpClient
241 .execute(
242 HttpClientRequest.post(
243 `${origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`,
244 ),
245 )
246 .pipe(
247 Effect.flatMap(HttpClientResponse.filterStatusOk),
248 Effect.flatMap((response) => response.arrayBuffer),
249 Effect.map((buffer) => new Uint8Array(buffer)),
250 Effect.scoped,
251 Effect.timeout(SCREENSHOT_TIMEOUT),
252 Effect.mapError(
253 (cause) =>
254 new DeviceOperationError({
255 operation: "screenshot",
256 reason:
257 HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
258 ? "hub_rejected"
259 : "request_failed",
260 cause,
261 }),
262 ),
263 Effect.withSpan("DeviceHubOperations.screenshot"),
264 );
265
266 return { list, boot, attach, shutdown, screenshot };
267};