Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DeviceHubOperations.ts

371 lines14.0 KB

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