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

main
ts 965 lines 35.9 KB
Raw
1 import { pruneLocalDeviceTools } from "./deviceToolMaintenance.ts";
2 import { deviceToolInstallMessage } from "@t3tools/contracts";
3 // The hub runs at origin root; T3 strips its prefix and the Device panel derives stream URLs from it.
4 import {
5 type DeviceHostSummary,
6 type DevicePlatform,
7 type DevicePlatformAvailability,
8 LOCAL_DEVICE_HOST_ID,
9 LOCAL_DEVICE_HOST_LABEL,
10 } from "@t3tools/contracts";
11 import { waitForHttpReady } from "@t3tools/shared/httpReadiness";
12 import * as HostProcess from "@t3tools/shared/HostProcess";
13 import {
14 resolveNodeExecutable,
15 type NodeRuntimeUnavailableError,
16 } from "@t3tools/shared/nodeRuntime";
17 import * as NetService from "@t3tools/shared/Net";
18 import { isCommandAvailable } from "@t3tools/shared/shell";
19 import * as Clock from "effect/Clock";
20 import * as Duration from "effect/Duration";
21 import * as Effect from "effect/Effect";
22 import * as Exit from "effect/Exit";
23 import * as FileSystem from "effect/FileSystem";
24 import * as Layer from "effect/Layer";
25 import * as Option from "effect/Option";
26 import * as Path from "effect/Path";
27 import * as Ref from "effect/Ref";
28 import * as Schema from "effect/Schema";
29 import * as Scope from "effect/Scope";
30 import * as Semaphore from "effect/Semaphore";
31 import * as Stream from "effect/Stream";
32 import { HttpClient } from "effect/http";
33 import * as ChildProcess from "effect/process/ChildProcess";
34 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
35
36 import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
37 import * as ServerConfig from "../config.ts";
38 import * as ProcessRunner from "../processRunner.ts";
39 import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
40 import * as DeviceHost from "./DeviceHost.ts";
41 import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
42 import {
43 agentDeviceStateDir,
44 type DeviceToolPaths,
45 ensureAgentDevice,
46 ensureDeviceHub,
47 isAgentDeviceInstalled,
48 isDeviceHubInstalled,
49 deviceToolVersions,
50 AGENT_DEVICE_VERSION,
51 DEVICE_HUB_VERSION,
52 installedAgentDeviceEntry,
53 } from "./DeviceToolchain.ts";
54
55 const HUB_READY_TIMEOUT_MS = 30_000;
56 const DAEMON_READY_TIMEOUT_MS = 30_000;
57 const DAEMON_POLL_MS = 100;
58 const HUB_RESTART_STABLE_UPTIME_MS = 60_000;
59 const HUB_RESTART_MAX_DELAY_MS = 30_000;
60
61 // Persist hub state so restarts without finalizers can clean up orphaned loopback listeners.
62 const HubStateFile = Schema.Struct({
63 pid: Schema.Int,
64 port: Schema.Int,
65 entryPath: Schema.String,
66 });
67 const decodeHubStateFile = Schema.decodeUnknownEffect(Schema.fromJsonString(HubStateFile));
68 const encodeHubStateFile = Schema.encodeUnknownEffect(Schema.fromJsonString(HubStateFile));
69
70 const AgentDeviceDaemonFile = Schema.Struct({
71 httpPort: Schema.Int,
72 token: Schema.String,
73 pid: Schema.optional(Schema.Int),
74 version: Schema.optional(Schema.String),
75 });
76 const decodeDaemonFile = Schema.decodeUnknownEffect(Schema.fromJsonString(AgentDeviceDaemonFile));
77
78 const decodeAgentDeviceFailure = Schema.decodeUnknownOption(
79 Schema.fromJsonString(
80 Schema.Struct({
81 error: Schema.Struct({
82 details: Schema.Struct({
83 reason: Schema.String,
84 inspection: Schema.optional(Schema.Struct({ reason: Schema.String })),
85 }),
86 }),
87 }),
88 ),
89 );
90
91 interface HubProcess {
92 readonly nodePath: string;
93 readonly child: ChildProcessSpawner.ChildProcessHandle;
94 readonly scope: Scope.Closeable;
95 readonly origin: string;
96 readonly startedAtMillis: number;
97 readonly emulatorExtraArgs: string | undefined;
98 readonly emulatorStamp: string | undefined;
99 }
100
101 interface RunningHost {
102 readonly hub: HubProcess;
103 readonly agentDevice: DeviceHost.AgentDeviceEndpoint | null;
104 readonly helpers: DeviceHost.DeviceHostReady["helpers"];
105 }
106
107 const platformReason = Effect.fn("LocalDeviceHost.platformReason")(function* (
108 platform: DevicePlatform,
109 ): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
110 const hostPlatform = yield* HostProcess.Platform;
111 if (platform === "ios") {
112 if (hostPlatform !== "darwin") return "iOS Simulators need macOS with Xcode.";
113 if (!(yield* isCommandAvailable("xcrun"))) return "Xcode command line tools were not found.";
114 return null;
115 }
116 const sdk = yield* androidSdk;
117 if (!sdk.root)
118 return "Android SDK was not found. Install it with Android Studio or set ANDROID_HOME to your SDK directory.";
119 if (!sdk.adb)
120 return `Android SDK Platform-Tools are missing from ${sdk.root}. Install them in Android Studio's SDK Manager.`;
121 if (!sdk.emulator)
122 return `Android Emulator is missing from ${sdk.root}. Install it in Android Studio's SDK Manager.`;
123 if (!sdk.avdmanager) {
124 if (sdk.legacyAvdmanager)
125 return `The Android SDK command-line tools in ${sdk.root} appear to be an older, unsupported version. Install Android SDK Command-line Tools (latest) in Android Studio's SDK Manager under SDK Tools.`;
126 return `Android SDK Command-line Tools (latest) are missing from ${sdk.root}. Install them in Android Studio's SDK Manager.`;
127 }
128 return null;
129 });
130
131 const androidSdk = Effect.gen(function* () {
132 const fs = yield* FileSystem.FileSystem;
133 const path = yield* Path.Path;
134 const environment = yield* HostProcess.Environment;
135 const platform = yield* HostProcess.Platform;
136 const windows = platform === "win32";
137 const home = environment.HOME ?? environment.USERPROFILE ?? "";
138 const explicit = [environment.ANDROID_HOME?.trim(), environment.ANDROID_SDK_ROOT?.trim()].filter(
139 (root): root is string => !!root,
140 );
141 const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false));
142 const adbBinary = windows ? "adb.exe" : "adb";
143 const avdmanagerBinary = windows ? "avdmanager.bat" : "avdmanager";
144 const inspect = Effect.fnUntraced(function* (root: string) {
145 const adb = yield* exists(path.join(root, "platform-tools", adbBinary));
146 const emulator = yield* exists(
147 path.join(root, "emulator", windows ? "emulator.exe" : "emulator"),
148 );
149 const avdmanager = yield* exists(
150 path.join(root, "cmdline-tools", "latest", "bin", avdmanagerBinary),
151 );
152 const legacyAvdmanager =
153 !avdmanager && (yield* exists(path.join(root, "tools", "bin", avdmanagerBinary)));
154 return { root, adb, emulator, avdmanager, legacyAvdmanager };
155 });
156 const candidates = [
157 ...explicit,
158 path.join(home, "Library", "Android", "sdk"),
159 path.join(home, "Android", "Sdk"),
160 path.join(environment.LOCALAPPDATA ?? path.join(home, "AppData", "Local"), "Android", "Sdk"),
161 ];
162 for (const root of candidates) {
163 const sdk = yield* inspect(root);
164 if (sdk.adb || sdk.emulator) return sdk;
165 }
166 // PATH entries can be slow to stat (network shares), so only consult them after the standard locations miss.
167 const searchPath = environment.PATH ?? environment.Path ?? "";
168 for (const directory of searchPath.split(windows ? ";" : ":")) {
169 if (!directory) continue;
170 const adb = path.join(directory, adbBinary);
171 if (!(yield* exists(adb))) continue;
172 const resolved = yield* fs.realPath(adb).pipe(Effect.orElseSucceed(() => adb));
173 const sdk = yield* inspect(path.dirname(path.dirname(resolved)));
174 if (sdk.adb || sdk.emulator) return sdk;
175 }
176 // No real SDK anywhere: report what the configured root is missing.
177 if (explicit[0]) return yield* inspect(explicit[0]);
178 return { root: null, adb: false, emulator: false, avdmanager: false, legacyAvdmanager: false };
179 });
180
181 const deviceHostEnvironment = (
182 environment: NodeJS.ProcessEnv,
183 sdkRoot: string | null,
184 hostPlatform: NodeJS.Platform,
185 path: Path.Path,
186 ): NodeJS.ProcessEnv => {
187 return sdkRoot
188 ? {
189 ...environment,
190 ANDROID_HOME: sdkRoot,
191 PATH: [
192 path.join(sdkRoot, "platform-tools"),
193 path.join(sdkRoot, "emulator"),
194 environment.PATH ?? environment.Path ?? "",
195 ].join(hostPlatform === "win32" ? ";" : ":"),
196 }
197 : environment;
198 };
199
200 const hubEnvironment = Effect.fn("LocalDeviceHost.hubEnvironment")(function* (
201 environment: NodeJS.ProcessEnv,
202 ) {
203 const env: NodeJS.ProcessEnv = { ...environment, FORCE_COLOR: "0", NO_COLOR: "1" };
204 const platform = yield* HostProcess.Platform;
205 const uid = yield* HostProcess.UserId;
206 if (env.ANDROID_HOME) {
207 const path = yield* Path.Path;
208 const runner = yield* ProcessRunner.ProcessRunner;
209 const emulator = path.join(
210 env.ANDROID_HOME,
211 "emulator",
212 platform === "win32" ? "emulator.exe" : "emulator",
213 );
214 const cameraArgs = yield* Effect.forEach(["front", "back"], (facing) =>
215 runner
216 .run({
217 command: emulator,
218 args: [`-help-camera-${facing}`],
219 env,
220 timeout: Duration.seconds(5),
221 })
222 .pipe(
223 Effect.map((result) => {
224 const help = `${result.stdout}\n${result.stderr}`;
225 // The hub wires imagefile cameras unconditionally; older SDK emulators reject that mode.
226 return result.code === 0 && /\bemulated\b/.test(help) && !/\bimagefile\b/.test(help)
227 ? `-camera-${facing} emulated`
228 : "";
229 }),
230 Effect.orElseSucceed(() => ""),
231 ),
232 );
233 const overrides = cameraArgs.filter(Boolean).join(" ");
234 if (overrides) {
235 env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS = [overrides, env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS]
236 .filter(Boolean)
237 .join(" ");
238 }
239 }
240 if (platform === "linux" && env.XDG_RUNTIME_DIR === undefined && uid !== undefined) {
241 // SSH sessions may omit the directory where the emulator publishes its gRPC token.
242 const runtimeDir = `/run/user/${uid}`;
243 const fs = yield* FileSystem.FileSystem;
244 const stat = yield* fs.stat(runtimeDir).pipe(Effect.option);
245 if (
246 stat._tag === "Some" &&
247 stat.value.type === "Directory" &&
248 Option.contains(stat.value.uid, uid)
249 ) {
250 env.XDG_RUNTIME_DIR = runtimeDir;
251 }
252 }
253 return env;
254 });
255
256 /** Only a Mac can list Apple simulators; elsewhere the hub's attempt surfaces as an error. */
257 const hubPlatformArguments = (hostPlatform: NodeJS.Platform) =>
258 hostPlatform === "darwin" ? [] : ["--platform", "android"];
259
260 export const make = Effect.fn("LocalDeviceHost.make")(function* () {
261 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
262 const config = yield* ServerConfig.ServerConfig;
263 const path = yield* Path.Path;
264 const fs = yield* FileSystem.FileSystem;
265 const net = yield* NetService.NetService;
266 const runner = yield* ProcessRunner.ProcessRunner;
267 const httpClient = yield* HttpClient.HttpClient;
268 const environment = yield* HostProcess.Environment;
269 const workingDirectory = yield* HostProcess.WorkingDirectory;
270 const hostPlatform = yield* HostProcess.Platform;
271 // Resolved per use: the desktop shell snapshot can select another SDK after the host exists.
272 const currentSdk = androidSdk.pipe(
273 Effect.provideService(FileSystem.FileSystem, fs),
274 Effect.provideService(Path.Path, path),
275 Effect.provideService(HostProcess.Environment, environment),
276 Effect.provideService(HostProcess.Platform, hostPlatform),
277 );
278 const currentHostEnvironment = currentSdk.pipe(
279 Effect.map((sdk) => deviceHostEnvironment(environment, sdk.root, hostPlatform, path)),
280 );
281 const startLock = yield* Semaphore.make(1);
282 const runningRef = yield* Ref.make<RunningHost | null>(null);
283 const restartDelayRef = yield* Ref.make(0);
284 const hostId = LOCAL_DEVICE_HOST_ID;
285
286 const platformAvailability = Effect.fn("LocalDeviceHost.platformAvailability")(function* (
287 platform: DevicePlatform,
288 ): Effect.fn.Return<DevicePlatformAvailability> {
289 const reason = yield* platformReason(platform).pipe(
290 Effect.provideService(FileSystem.FileSystem, fs),
291 Effect.provideService(Path.Path, path),
292 );
293 return reason === null ? { platform, available: true } : { platform, available: false, reason };
294 });
295
296 const summary: Effect.Effect<DeviceHostSummary> = Effect.gen(function* () {
297 const [platforms, hubInstalled, agentDeviceInstalled] = yield* Effect.all([
298 Effect.all([platformAvailability("ios"), platformAvailability("android")]),
299 isDeviceHubInstalled(config.baseDir).pipe(
300 Effect.provideService(FileSystem.FileSystem, fs),
301 Effect.provideService(Path.Path, path),
302 ),
303 isAgentDeviceInstalled(config.baseDir).pipe(
304 Effect.provideService(FileSystem.FileSystem, fs),
305 Effect.provideService(Path.Path, path),
306 ),
307 ]);
308 const running = yield* Ref.get(runningRef);
309 const daemon = running?.agentDevice
310 ? yield* readDaemonFile().pipe(Effect.option)
311 : Option.none();
312 const hubAlive = running
313 ? yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false))
314 : false;
315 const agentAlive =
316 Option.isSome(daemon) && daemon.value.pid ? yield* isProcessAlive(daemon.value.pid) : false;
317 const tools = yield* deviceToolVersions(config.baseDir, {
318 ...(hubAlive ? { hub: DEVICE_HUB_VERSION } : {}),
319 ...(agentAlive && Option.isSome(daemon) && daemon.value.version
320 ? { agent: daemon.value.version }
321 : {}),
322 }).pipe(
323 Effect.provideService(FileSystem.FileSystem, fs),
324 Effect.provideService(Path.Path, path),
325 );
326 return {
327 tools,
328 id: hostId,
329 kind: "local",
330 label: LOCAL_DEVICE_HOST_LABEL,
331 platforms,
332 hubInstalled,
333 agentDeviceInstalled,
334 };
335 });
336
337 const stopHub = (hub: HubProcess | undefined) =>
338 hub ? Scope.close(hub.scope, Exit.void).pipe(Effect.ignore) : Effect.void;
339
340 const hubStatePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "hub.json");
341
342 const isProcessAlive = (pid: number) =>
343 Effect.sync(() => {
344 try {
345 process.kill(pid, 0);
346 return true;
347 } catch {
348 return false;
349 }
350 });
351
352 // Check PID and entry path before reaping; the PID may have been recycled.
353 const reapStaleHub = Effect.gen(function* () {
354 const previous = yield* fs
355 .readFileString(hubStatePath())
356 .pipe(Effect.flatMap(decodeHubStateFile), Effect.option);
357 if (previous._tag === "None") return;
358 const alive = yield* isProcessAlive(previous.value.pid);
359 if (alive) {
360 const commandLine = yield* runner
361 .run({
362 command: "ps",
363 args: ["-o", "command=", "-p", String(previous.value.pid)],
364 timeout: Duration.seconds(5),
365 timeoutBehavior: "timedOutResult",
366 })
367 .pipe(
368 Effect.map((result) => result.stdout),
369 Effect.orElseSucceed(() => ""),
370 );
371 if (commandLine.includes(previous.value.entryPath)) {
372 yield* Effect.logWarning("Stopping a device hub left behind by a previous server", {
373 pid: previous.value.pid,
374 port: previous.value.port,
375 });
376 yield* Effect.sync(() => {
377 try {
378 process.kill(previous.value.pid, "SIGTERM");
379 } catch {}
380 });
381 }
382 }
383 yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore);
384 }).pipe(Effect.ignoreCause);
385
386 const recordHub = (hub: HubProcess, hubTool: DeviceToolPaths) =>
387 encodeHubStateFile({
388 pid: Number(hub.child.pid),
389 port: Number(new URL(hub.origin).port),
390 entryPath: hubTool.entryPath,
391 }).pipe(
392 Effect.flatMap((contents) =>
393 writeFileStringAtomically({ filePath: hubStatePath(), contents }),
394 ),
395 Effect.provideService(FileSystem.FileSystem, fs),
396 Effect.provideService(Path.Path, path),
397 Effect.ignore,
398 );
399
400 const currentHubEnvironment = Effect.gen(function* () {
401 return yield* hubEnvironment(yield* currentHostEnvironment).pipe(
402 Effect.provideService(FileSystem.FileSystem, fs),
403 Effect.provideService(Path.Path, path),
404 Effect.provideService(ProcessRunner.ProcessRunner, runner),
405 Effect.provideService(HostProcess.Platform, hostPlatform),
406 );
407 });
408
409 // The camera probe spawns the emulator; re-run it for a live hub only after the binary changes.
410 const emulatorStamp = Effect.gen(function* () {
411 const sdk = yield* currentSdk;
412 if (!sdk.root) return undefined;
413 const binary = path.join(
414 sdk.root,
415 "emulator",
416 hostPlatform === "win32" ? "emulator.exe" : "emulator",
417 );
418 const info = yield* fs.stat(binary).pipe(Effect.option);
419 if (Option.isNone(info)) return undefined;
420 return `${Option.getOrUndefined(info.value.mtime)?.getTime()}:${info.value.size}`;
421 });
422
423 const spawnHub = Effect.fn("LocalDeviceHost.spawnHub")(function* (
424 hubTool: DeviceToolPaths,
425 nodePath: string,
426 env: NodeJS.ProcessEnv,
427 ): Effect.fn.Return<HubProcess, DeviceHost.DeviceHostError> {
428 yield* reapStaleHub;
429 const stamp = yield* emulatorStamp;
430 yield* fs
431 .makeDirectory(agentDeviceStateDir(path, config.stateDir), { recursive: true })
432 .pipe(Effect.ignore);
433 const port = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
434 Effect.mapError(
435 (cause) =>
436 new DeviceHost.DeviceHostError({
437 hostId,
438 step: "reserving a port for the device hub",
439 cause,
440 }),
441 ),
442 );
443 const origin = `http://127.0.0.1:${port}`;
444 const scope = yield* Scope.make("sequential");
445 // The hub is not recorded yet; stop it on failure or interruption from spawn onward.
446 return yield* Effect.gen(function* () {
447 const child = yield* spawner
448 .spawn(
449 ChildProcess.make(
450 nodePath,
451 [
452 hubTool.entryPath,
453 "--port",
454 String(port),
455 "--host",
456 "127.0.0.1",
457 "--hide-sidebar",
458 "--hide-boot-device",
459 ...hubPlatformArguments(hostPlatform),
460 ],
461 {
462 cwd: workingDirectory,
463 detached: false,
464 shell: false,
465 stdout: "pipe",
466 stderr: "pipe",
467 env,
468 },
469 ),
470 )
471 .pipe(
472 Effect.provideService(Scope.Scope, scope),
473 Effect.mapError(
474 (cause) =>
475 new DeviceHost.DeviceHostError({
476 hostId,
477 step: "starting the device hub",
478 cause,
479 }),
480 ),
481 );
482 const startedAtMillis = yield* Clock.currentTimeMillis;
483 const hub: HubProcess = {
484 child,
485 scope,
486 origin,
487 startedAtMillis,
488 nodePath,
489 emulatorExtraArgs: env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS,
490 emulatorStamp: stamp,
491 };
492 yield* Effect.forkIn(observeHubOutput(hub), scope);
493 yield* waitForHttpReady({
494 baseUrl: origin,
495 path: "/readyz",
496 timeoutMs: HUB_READY_TIMEOUT_MS,
497 makeError: (info) =>
498 new DeviceHost.DeviceHostError({
499 hostId,
500 step: "waiting for the device hub to answer",
501 cause: info.cause,
502 }),
503 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
504 yield* recordHub(hub, hubTool);
505 yield* Effect.logInfo("Device hub started", { pid: Number(child.pid), port });
506 return hub;
507 }).pipe(Effect.onError(() => Scope.close(scope, Exit.void).pipe(Effect.ignore)));
508 });
509
510 const observeHubOutput = (hub: HubProcess) =>
511 hub.child.all.pipe(
512 Stream.decodeText(),
513 Stream.splitLines,
514 Stream.map((line) => line.trim()),
515 Stream.filter((line) => line.length > 0),
516 Stream.runForEach((line) =>
517 Effect.logDebug("Device hub output", { pid: Number(hub.child.pid), output: line }),
518 ),
519 Effect.ignoreCause,
520 );
521
522 // Waits for the hub's lifetime and re-forks on restart; a span would nest across restarts.
523 const superviseHub: (hub: HubProcess, hubTool: DeviceToolPaths) => Effect.Effect<void> =
524 Effect.fnUntraced(
525 function* (hub: HubProcess, hubTool: DeviceToolPaths) {
526 yield* Effect.result(hub.child.exitCode);
527 const running = yield* Ref.get(runningRef);
528 if (running?.hub.child.pid !== hub.child.pid) return;
529 const uptime = (yield* Clock.currentTimeMillis) - hub.startedAtMillis;
530 const delay = yield* Ref.modify(restartDelayRef, (current) => {
531 if (uptime >= HUB_RESTART_STABLE_UPTIME_MS) return [0, 0];
532 const next = current === 0 ? 1_000 : Math.min(current * 2, HUB_RESTART_MAX_DELAY_MS);
533 return [current, next];
534 });
535 yield* Effect.logWarning("Device hub exited; restarting", {
536 pid: Number(hub.child.pid),
537 delayMs: delay,
538 });
539 yield* Effect.sleep(Duration.millis(delay));
540 yield* startLock.withPermits(1)(
541 Effect.gen(function* () {
542 const current = yield* Ref.get(runningRef);
543 if (current?.hub.child.pid !== hub.child.pid) return;
544 const replacement = yield* spawnHub(
545 hubTool,
546 hub.nodePath,
547 yield* currentHubEnvironment,
548 );
549 yield* Ref.set(runningRef, { ...current, hub: replacement });
550 yield* Effect.forkDetach(superviseHub(replacement, hubTool));
551 }),
552 );
553 },
554 Effect.catchCause((cause) => Effect.logWarning("Device hub supervisor failed", { cause })),
555 );
556
557 const daemonFilePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "daemon.json");
558
559 const readDaemonFile = Effect.fn("LocalDeviceHost.readDaemonFile")(function* () {
560 const raw = yield* fs.readFileString(daemonFilePath());
561 return yield* decodeDaemonFile(raw);
562 });
563
564 const startAgentDeviceDaemon = Effect.fn("LocalDeviceHost.startAgentDeviceDaemon")(function* (
565 agentTool: Pick<DeviceToolPaths, "entryPath">,
566 nodePath: string,
567 ): Effect.fn.Return<
568 DeviceHost.AgentDeviceEndpoint,
569 | DeviceHost.DeviceHostError
570 | DeviceHost.DeviceHostTimeoutError
571 | DeviceHost.AgentDeviceStartError
572 > {
573 const stateDir = agentDeviceStateDir(path, config.stateDir);
574 yield* fs.makeDirectory(stateDir, { recursive: true }).pipe(Effect.ignore);
575 const existing = yield* readDaemonFile().pipe(Effect.option);
576 const daemonEnvironment: NodeJS.ProcessEnv = {
577 ...(yield* currentHostEnvironment),
578 AGENT_DEVICE_STATE_DIR: stateDir,
579 AGENT_DEVICE_DAEMON_SERVER_MODE: "http",
580 // Disable the five-minute idle timeout; the server owns shutdown.
581 AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: "0",
582 AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
583 FORCE_COLOR: "0",
584 NO_COLOR: "1",
585 };
586 const toEndpoint = (
587 file: typeof AgentDeviceDaemonFile.Type,
588 ): DeviceHost.AgentDeviceEndpoint => ({
589 baseUrl: `http://127.0.0.1:${file.httpPort}`,
590 token: file.token,
591 entryPath: agentTool.entryPath,
592 });
593 if (existing._tag === "Some") {
594 const alive = yield* HttpClient.withScope(httpClient)
595 .get(`http://127.0.0.1:${existing.value.httpPort}/health`)
596 .pipe(
597 Effect.timeout(Duration.seconds(2)),
598 Effect.flatMap((response) =>
599 response.arrayBuffer.pipe(Effect.as(response.status === 200)),
600 ),
601 Effect.scoped,
602 Effect.orElseSucceed(() => false),
603 );
604 if (alive) return toEndpoint(existing.value);
605 yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore);
606 }
607 // No `daemon start` exists; `devices` is the cheapest command that starts and awaits it.
608 const runResult = yield* runner
609 .run({
610 command: nodePath,
611 args: [agentTool.entryPath, "devices", "--json"],
612 env: daemonEnvironment,
613 timeout: Duration.millis(DAEMON_READY_TIMEOUT_MS),
614 timeoutBehavior: "timedOutResult",
615 })
616 .pipe(Effect.result);
617 // Discovery may fail after startup; accept a published endpoint or preserve the CLI failure.
618 const started = yield* readDaemonFile().pipe(Effect.option);
619 if (started._tag === "Some") return toEndpoint(started.value);
620 if (runResult._tag === "Failure") {
621 return yield* new DeviceHost.DeviceHostError({
622 hostId,
623 step: "starting agent tools",
624 cause: runResult.failure,
625 });
626 }
627 const result = runResult.success;
628 if (result.timedOut) {
629 return yield* new DeviceHost.DeviceHostTimeoutError({
630 hostId,
631 timeoutMs: DAEMON_READY_TIMEOUT_MS,
632 });
633 }
634 if (result.code !== 0) {
635 const failure = decodeAgentDeviceFailure(result.stdout);
636 const details = Option.isSome(failure) ? failure.value.error.details : undefined;
637 const reason =
638 details?.reason === "daemon_registration_unproven"
639 ? details.inspection?.reason === "non-directory"
640 ? "daemon_lock_not_directory"
641 : "daemon_registration_unproven"
642 : details?.reason === "daemon_retirement_unconfirmed"
643 ? "daemon_retirement_unconfirmed"
644 : "command_failed";
645 return yield* new DeviceHost.AgentDeviceStartError({
646 hostId,
647 stateDir,
648 exitCode: result.code === null ? null : Number(result.code),
649 reason,
650 cause: result,
651 });
652 }
653 const deadline = (yield* Clock.currentTimeMillis) + DAEMON_READY_TIMEOUT_MS;
654 while (true) {
655 const file = yield* readDaemonFile().pipe(Effect.option);
656 if (file._tag === "Some") return toEndpoint(file.value);
657 if ((yield* Clock.currentTimeMillis) > deadline) {
658 return yield* new DeviceHost.DeviceHostTimeoutError({
659 hostId,
660 timeoutMs: DAEMON_READY_TIMEOUT_MS,
661 });
662 }
663 yield* Effect.sleep(Duration.millis(DAEMON_POLL_MS));
664 }
665 });
666
667 // The daemon may predate this process (an earlier server was killed, possibly on an
668 // older pin), so stop it with the CLI of its recorded version when that is installed.
669 const stopAgentDeviceDaemon = Effect.gen(function* () {
670 if (!(yield* fs.exists(daemonFilePath()))) return;
671 const recorded = yield* readDaemonFile().pipe(Effect.option);
672 if (
673 Option.isSome(recorded) &&
674 recorded.value.pid &&
675 !(yield* isProcessAlive(recorded.value.pid))
676 ) {
677 return yield* fs.remove(daemonFilePath(), { force: true });
678 }
679 const entryPath = yield* installedAgentDeviceEntry(config.baseDir, [
680 ...(Option.isSome(recorded) && recorded.value.version ? [recorded.value.version] : []),
681 AGENT_DEVICE_VERSION,
682 ]);
683 if (!entryPath) return;
684 const hostEnvironment = yield* currentHostEnvironment;
685 const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(
686 Effect.provideService(HostProcess.Platform, hostPlatform),
687 );
688 yield* runner.run({
689 command: nodePath,
690 args: [
691 entryPath,
692 "daemon",
693 "stop",
694 "--state-dir",
695 agentDeviceStateDir(path, config.stateDir),
696 ],
697 env: { ...hostEnvironment, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" },
698 timeout: Duration.seconds(10),
699 timeoutBehavior: "timedOutResult",
700 });
701 }).pipe(
702 Effect.provideService(FileSystem.FileSystem, fs),
703 Effect.provideService(Path.Path, path),
704 Effect.ignore,
705 );
706
707 const ensureHubReady = Effect.fn("LocalDeviceHost.ensureHubReady")(function* (
708 onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,
709 ): Effect.fn.Return<RunningHost, DeviceHost.DeviceHostError | NodeRuntimeUnavailableError> {
710 const running = yield* Ref.get(runningRef);
711 let env: NodeJS.ProcessEnv | undefined;
712 // A dead hub's record stays until a replacement is published: the agent
713 // daemon outlives the hub, and close needs its endpoint if the restart fails.
714 if (running) {
715 const alive = yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false));
716 if (alive) {
717 const stamp = yield* emulatorStamp;
718 if (stamp === running.hub.emulatorStamp) return running;
719 // An updated emulator can change the camera overrides; replace the hub only if they did.
720 env = yield* currentHubEnvironment;
721 if (env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS === running.hub.emulatorExtraArgs) {
722 const next = { ...running, hub: { ...running.hub, emulatorStamp: stamp } };
723 yield* Ref.set(runningRef, next);
724 return next;
725 }
726 yield* stopHub(running.hub);
727 }
728 }
729 const nodePath = yield* resolveNodeExecutable(
730 "Local device support",
731 yield* currentHostEnvironment,
732 ).pipe(
733 Effect.provideService(FileSystem.FileSystem, fs),
734 Effect.provideService(Path.Path, path),
735 Effect.provideService(HostProcess.Platform, hostPlatform),
736 );
737 const installed = yield* isDeviceHubInstalled(config.baseDir).pipe(
738 Effect.provideService(FileSystem.FileSystem, fs),
739 Effect.provideService(Path.Path, path),
740 );
741 if (!installed) {
742 const inventory = yield* summary;
743 yield* onPhase("installing", deviceToolInstallMessage("device hub", inventory.tools?.hub));
744 }
745 const hubTool = yield* ensureDeviceHub(config.baseDir).pipe(
746 Effect.provideService(FileSystem.FileSystem, fs),
747 Effect.provideService(Path.Path, path),
748 Effect.provideService(ProcessRunner.ProcessRunner, runner),
749 Effect.mapError(
750 (cause) =>
751 new DeviceHost.DeviceHostError({
752 hostId,
753 step: "installing device support",
754 cause,
755 }),
756 ),
757 );
758 yield* onPhase("starting");
759 const hub = yield* spawnHub(hubTool, nodePath, env ?? (yield* currentHubEnvironment));
760 const next = yield* Effect.gen(function* () {
761 yield* pruneLocalDeviceTools(config.baseDir, nodePath, "hub").pipe(
762 Effect.provideService(Path.Path, path),
763 Effect.provideService(ProcessRunner.ProcessRunner, runner),
764 Effect.ignore,
765 );
766 const candidate = helperPaths(hubTool);
767 const [axExists, cliExists] = yield* Effect.all([
768 fs.exists(candidate.serveSimAxSettings).pipe(Effect.orElseSucceed(() => false)),
769 fs.exists(candidate.serveSimCli).pipe(Effect.orElseSucceed(() => false)),
770 ]);
771 const next: RunningHost = {
772 hub,
773 agentDevice: running?.agentDevice ?? null,
774 helpers: {
775 serveSimAxSettings: axExists ? candidate.serveSimAxSettings : null,
776 serveSimCli: cliExists ? candidate.serveSimCli : null,
777 },
778 };
779 yield* Ref.set(runningRef, next);
780 return next;
781 }).pipe(Effect.onError(() => stopHub(hub)));
782 yield* Ref.set(restartDelayRef, 0);
783 yield* Effect.forkDetach(superviseHub(hub, hubTool));
784 return next;
785 });
786
787 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
788 startLock.withPermits(1)(ensureHubReady(onPhase).pipe(Effect.map(toReady)));
789
790 const ensureAgentReady: DeviceHost.DeviceHost["Service"]["ensureAgentReady"] = (onPhase) =>
791 startLock.withPermits(1)(
792 Effect.gen(function* (): Generator<
793 Effect.Effect<
794 unknown,
795 | DeviceHost.DeviceHostError
796 | DeviceHost.DeviceHostTimeoutError
797 | DeviceHost.AgentDeviceStartError
798 | NodeRuntimeUnavailableError
799 >,
800 DeviceHost.DeviceHostAgentReady
801 > {
802 const running = yield* ensureHubReady(onPhase);
803 if (running.agentDevice) {
804 const agentDevice = yield* startAgentDeviceDaemon(
805 running.agentDevice,
806 running.hub.nodePath,
807 );
808 yield* Ref.set(runningRef, { ...running, agentDevice });
809 return { ...toReady(running), agentDevice };
810 }
811 const installed = yield* isAgentDeviceInstalled(config.baseDir).pipe(
812 Effect.provideService(FileSystem.FileSystem, fs),
813 Effect.provideService(Path.Path, path),
814 );
815 if (!installed) {
816 const inventory = yield* summary;
817 yield* onPhase(
818 "installing",
819 deviceToolInstallMessage("agent tools", inventory.tools?.agent),
820 );
821 }
822 const agentTool = yield* ensureAgentDevice(config.baseDir).pipe(
823 Effect.provideService(FileSystem.FileSystem, fs),
824 Effect.provideService(Path.Path, path),
825 Effect.provideService(ProcessRunner.ProcessRunner, runner),
826 Effect.mapError(
827 (cause) =>
828 new DeviceHost.DeviceHostError({
829 hostId,
830 step: "installing agent tools",
831 cause,
832 }),
833 ),
834 );
835 yield* onPhase("starting");
836 const agentDevice = yield* startAgentDeviceDaemon(agentTool, running.hub.nodePath);
837 yield* pruneLocalDeviceTools(config.baseDir, running.hub.nodePath, "agent").pipe(
838 Effect.provideService(Path.Path, path),
839 Effect.provideService(ProcessRunner.ProcessRunner, runner),
840 Effect.ignore,
841 );
842 const next = { ...running, agentDevice };
843 yield* Ref.set(runningRef, next);
844 return { ...toReady(next), agentDevice };
845 }),
846 );
847
848 const helperPaths = (hubTool: DeviceToolPaths) => {
849 const serveSimDist = path.join(
850 hubTool.installDir,
851 "node_modules",
852 "expo-device-hub",
853 "vendor",
854 "serve-sim",
855 "dist",
856 );
857 return {
858 serveSimAxSettings: path.join(serveSimDist, "simax", "serve-sim-ax-settings"),
859 serveSimCli: path.join(serveSimDist, "serve-sim.js"),
860 };
861 };
862
863 const run: DeviceHost.DeviceHostReady["run"] = (command, args, options) =>
864 currentSdk.pipe(
865 Effect.flatMap((sdk) =>
866 runner.run({
867 command:
868 command === "emulator" && sdk.root
869 ? path.join(
870 sdk.root,
871 "emulator",
872 hostPlatform === "win32" ? "emulator.exe" : "emulator",
873 )
874 : command,
875 args,
876 cwd: workingDirectory,
877 env: deviceHostEnvironment(environment, sdk.root, hostPlatform, path),
878 timeout: Duration.millis(options?.timeoutMs ?? 20_000),
879 timeoutBehavior: "timedOutResult",
880 ...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
881 ...(options?.maxOutputBytes === undefined
882 ? {}
883 : { maxOutputBytes: options.maxOutputBytes }),
884 }),
885 ),
886 Effect.map((result) => ({
887 stdout: result.stdout,
888 stderr: result.stderr,
889 code: result.timedOut ? 124 : Number(result.code ?? 127),
890 })),
891 Effect.catch((cause) => Effect.succeed({ stdout: "", stderr: String(cause), code: 127 })),
892 );
893
894 const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({
895 hub: { origin: running.hub.origin } satisfies DeviceHost.DeviceHubEndpoint,
896 devices: makeDeviceHubOperations({
897 hostId,
898 origin: running.hub.origin,
899 http: httpClient,
900 run,
901 platformAvailable: (platform) =>
902 platformAvailability(platform).pipe(Effect.map((availability) => availability.available)),
903 }),
904 nodePath: running.hub.nodePath,
905 run,
906 helpers: running.helpers,
907 ...(running.agentDevice
908 ? { releaseAgentSession: releaseAgentDeviceSession(httpClient, running.agentDevice) }
909 : {}),
910 });
911
912 const current: DeviceHost.DeviceHost["Service"]["current"] = Ref.get(runningRef).pipe(
913 Effect.map((running) => (running ? toReady(running) : null)),
914 );
915
916 const stopAgent: DeviceHost.DeviceHost["Service"]["stopAgent"] = startLock.withPermits(1)(
917 Effect.gen(function* () {
918 yield* stopAgentDeviceDaemon;
919 yield* Ref.update(runningRef, (running) =>
920 running ? { ...running, agentDevice: null } : running,
921 );
922 }),
923 );
924
925 const stop: DeviceHost.DeviceHost["Service"]["stop"] = startLock.withPermits(1)(
926 Effect.gen(function* () {
927 const running = yield* Ref.getAndSet(runningRef, null);
928 // Hub cleanup waits for its exit unbounded; it must not strand the detached agent daemon.
929 yield* Effect.all(
930 [
931 stopHub(running?.hub).pipe(
932 Effect.andThen(fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore)),
933 ),
934 stopAgentDeviceDaemon,
935 ],
936 { concurrency: "unbounded", discard: true },
937 );
938 }),
939 );
940
941 yield* Effect.addFinalizer(() => stop);
942
943 const host: DeviceHost.DeviceHost["Service"] = {
944 id: hostId,
945 label: LOCAL_DEVICE_HOST_LABEL,
946 summary,
947 platformAvailability,
948 ensureReady,
949 ensureAgentReady,
950 current,
951 stopAgent,
952 stop,
953 };
954 return host;
955 });
956
957 export const layer = Layer.effect(DeviceHost.DeviceHost, make());
958
959 export const __testing = {
960 AgentDeviceDaemonFile,
961 androidSdk,
962 platformReason,
963 deviceHostEnvironment,
964 hubEnvironment,
965 };