@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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