Open History to see the last commit
1import { pruneLocalDeviceTools } from "./deviceToolMaintenance.ts";
2import { deviceToolInstallMessage } from "@t3tools/contracts";
3/**
4 * The device host that is this machine.
5 *
6 * Runs expo-device-hub as a supervised child on a loopback port and starts the
7 * agent-device daemon in HTTP mode under a T3-owned state directory. Both are
8 * lazy: the device service requires explicit setup consent before it calls
9 * ensureReady to install tools or start helper processes.
10 *
11 * The hub runs in its standalone mode (origin root). The T3 proxy strips its
12 * own prefix, and the Device panel derives stream and socket URLs from the
13 * prefix itself rather than from anything the hub prints.
14 */
15import {
16 type DeviceHostSummary,
17 type DevicePlatform,
18 type DevicePlatformAvailability,
19 LOCAL_DEVICE_HOST_ID,
20} from "@t3tools/contracts";
21import { waitForHttpReady } from "@t3tools/shared/httpReadiness";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23import {
24 resolveNodeExecutable,
25 type NodeRuntimeUnavailableError,
26} from "@t3tools/shared/nodeRuntime";
27import * as NetService from "@t3tools/shared/Net";
28import { isCommandAvailable } from "@t3tools/shared/shell";
29import * as Clock from "effect/Clock";
30import * as Duration from "effect/Duration";
31import * as Effect from "effect/Effect";
32import * as Exit from "effect/Exit";
33import * as FileSystem from "effect/FileSystem";
34import * as Layer from "effect/Layer";
35import * as Option from "effect/Option";
36import * as Path from "effect/Path";
37import * as Ref from "effect/Ref";
38import * as Schema from "effect/Schema";
39import * as Scope from "effect/Scope";
40import * as Semaphore from "effect/Semaphore";
41import * as Stream from "effect/Stream";
42import { HttpClient } from "effect/http";
43import * as ChildProcess from "effect/process/ChildProcess";
44import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
45
46import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
47import * as ServerConfig from "../config.ts";
48import * as ProcessRunner from "../processRunner.ts";
49import * as DeviceHost from "./DeviceHost.ts";
50import {
51 agentDeviceStateDir,
52 type DeviceToolPaths,
53 ensureAgentDevice,
54 ensureDeviceHub,
55 isAgentDeviceInstalled,
56 isDeviceHubInstalled,
57 deviceToolVersions,
58 DEVICE_HUB_VERSION,
59} from "./DeviceToolchain.ts";
60
61const HUB_READY_TIMEOUT_MS = 30_000;
62const DAEMON_READY_TIMEOUT_MS = 30_000;
63const DAEMON_POLL_MS = 100;
64const HUB_RESTART_STABLE_UPTIME_MS = 60_000;
65const HUB_RESTART_MAX_DELAY_MS = 30_000;
66
67/**
68 * Written beside the agent-device state so a server that dies without running
69 * its finalizers (SIGKILL, dev-runner restarts) does not leave a hub bound to
70 * a loopback port forever. The next start reads it, kills only a process that
71 * is still that hub, and replaces the file.
72 */
73const HubStateFile = Schema.Struct({
74 pid: Schema.Int,
75 port: Schema.Int,
76 entryPath: Schema.String,
77});
78const decodeHubStateFile = Schema.decodeUnknownEffect(Schema.fromJsonString(HubStateFile));
79const encodeHubStateFile = Schema.encodeUnknownEffect(Schema.fromJsonString(HubStateFile));
80
81const AgentDeviceDaemonFile = Schema.Struct({
82 httpPort: Schema.Int,
83 token: Schema.String,
84 pid: Schema.optional(Schema.Int),
85 version: Schema.optional(Schema.String),
86});
87const decodeDaemonFile = Schema.decodeUnknownEffect(Schema.fromJsonString(AgentDeviceDaemonFile));
88
89const decodeAgentDeviceFailure = Schema.decodeUnknownOption(
90 Schema.fromJsonString(
91 Schema.Struct({
92 error: Schema.Struct({
93 details: Schema.Struct({
94 reason: Schema.String,
95 inspection: Schema.optional(Schema.Struct({ reason: Schema.String })),
96 }),
97 }),
98 }),
99 ),
100);
101
102interface HubProcess {
103 readonly nodePath: string;
104 readonly child: ChildProcessSpawner.ChildProcessHandle;
105 readonly scope: Scope.Closeable;
106 readonly origin: string;
107 readonly startedAtMillis: number;
108}
109
110interface RunningHost {
111 readonly hub: HubProcess;
112 readonly agentDevice: DeviceHost.AgentDeviceEndpoint | null;
113 readonly helpers: DeviceHost.DeviceHostReady["helpers"];
114}
115
116const platformReason = Effect.fn("LocalDeviceHost.platformReason")(function* (
117 platform: DevicePlatform,
118): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
119 const hostPlatform = yield* HostProcess.Platform;
120 if (platform === "ios") {
121 if (hostPlatform !== "darwin") return "iOS Simulators need macOS with Xcode.";
122 if (!(yield* isCommandAvailable("xcrun"))) return "Xcode command line tools were not found.";
123 return null;
124 }
125 const sdk = yield* androidSdk;
126 if (!sdk.root)
127 return "Android SDK was not found. Install it with Android Studio or set ANDROID_HOME to your SDK directory.";
128 if (!sdk.adb)
129 return `Android SDK Platform-Tools are missing from ${sdk.root}. Install them in Android Studio's SDK Manager.`;
130 if (!sdk.emulator)
131 return `Android Emulator is missing from ${sdk.root}. Install it in Android Studio's SDK Manager.`;
132 if (!sdk.avdmanager) {
133 if (sdk.legacyAvdmanager)
134 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.`;
135 return `Android SDK Command-line Tools (latest) are missing from ${sdk.root}. Install them in Android Studio's SDK Manager.`;
136 }
137 return null;
138});
139
140/** Resolve the SDK once for both diagnostics and the environment passed to helpers. */
141const androidSdk = Effect.gen(function* () {
142 const fs = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const environment = yield* HostProcess.Environment;
145 const platform = yield* HostProcess.Platform;
146 const windows = platform === "win32";
147 const home = environment.HOME ?? environment.USERPROFILE ?? "";
148 const explicit = environment.ANDROID_HOME?.trim() || environment.ANDROID_SDK_ROOT?.trim();
149 const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false));
150 const adbBinary = windows ? "adb.exe" : "adb";
151 const avdmanagerBinary = windows ? "avdmanager.bat" : "avdmanager";
152 const inspect = Effect.fnUntraced(function* (root: string) {
153 const adb = yield* exists(path.join(root, "platform-tools", adbBinary));
154 const emulator = yield* exists(
155 path.join(root, "emulator", windows ? "emulator.exe" : "emulator"),
156 );
157 if (!explicit && !adb && !emulator) return null;
158 const avdmanager = yield* exists(
159 path.join(root, "cmdline-tools", "latest", "bin", avdmanagerBinary),
160 );
161 const legacyAvdmanager =
162 !avdmanager && (yield* exists(path.join(root, "tools", "bin", avdmanagerBinary)));
163 return { root, adb, emulator, avdmanager, legacyAvdmanager };
164 });
165 const candidates = explicit
166 ? [explicit]
167 : [
168 path.join(home, "Library", "Android", "sdk"),
169 path.join(home, "Android", "Sdk"),
170 path.join(
171 environment.LOCALAPPDATA ?? path.join(home, "AppData", "Local"),
172 "Android",
173 "Sdk",
174 ),
175 ];
176 for (const root of candidates) {
177 const sdk = yield* inspect(root);
178 if (sdk) return sdk;
179 }
180 // PATH entries can be slow to stat (network shares), so only consult them after the standard locations miss.
181 if (!explicit) {
182 const searchPath = environment.PATH ?? environment.Path ?? "";
183 for (const directory of searchPath.split(windows ? ";" : ":")) {
184 if (!directory) continue;
185 const adb = path.join(directory, adbBinary);
186 if (!(yield* exists(adb))) continue;
187 const resolved = yield* fs.realPath(adb).pipe(Effect.orElseSucceed(() => adb));
188 const sdk = yield* inspect(path.dirname(path.dirname(resolved)));
189 if (sdk) return sdk;
190 }
191 }
192 return { root: null, adb: false, emulator: false, avdmanager: false, legacyAvdmanager: false };
193});
194
195const deviceHostEnvironment = (
196 environment: NodeJS.ProcessEnv,
197 sdkRoot: string | null,
198 hostPlatform: NodeJS.Platform,
199 path: Path.Path,
200): NodeJS.ProcessEnv => {
201 return sdkRoot
202 ? {
203 ...environment,
204 ANDROID_HOME: sdkRoot,
205 PATH: [
206 path.join(sdkRoot, "platform-tools"),
207 path.join(sdkRoot, "emulator"),
208 environment.PATH ?? environment.Path ?? "",
209 ].join(hostPlatform === "win32" ? ";" : ":"),
210 }
211 : environment;
212};
213
214const hubEnvironment = Effect.fn("LocalDeviceHost.hubEnvironment")(function* (
215 environment: NodeJS.ProcessEnv,
216) {
217 const env: NodeJS.ProcessEnv = { ...environment, FORCE_COLOR: "0", NO_COLOR: "1" };
218 const platform = yield* HostProcess.Platform;
219 const uid = yield* HostProcess.UserId;
220 if (platform === "linux" && env.XDG_RUNTIME_DIR === undefined && uid !== undefined) {
221 // SSH sessions may omit the directory where the emulator publishes its gRPC token.
222 const runtimeDir = `/run/user/${uid}`;
223 const fs = yield* FileSystem.FileSystem;
224 const stat = yield* fs.stat(runtimeDir).pipe(Effect.option);
225 if (
226 stat._tag === "Some" &&
227 stat.value.type === "Directory" &&
228 Option.contains(stat.value.uid, uid)
229 ) {
230 env.XDG_RUNTIME_DIR = runtimeDir;
231 }
232 }
233 return env;
234});
235
236export const make = Effect.fn("LocalDeviceHost.make")(function* () {
237 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
238 const config = yield* ServerConfig.ServerConfig;
239 const path = yield* Path.Path;
240 const fs = yield* FileSystem.FileSystem;
241 const net = yield* NetService.NetService;
242 const runner = yield* ProcessRunner.ProcessRunner;
243 const httpClient = yield* HttpClient.HttpClient;
244 const environment = yield* HostProcess.Environment;
245 const hostPlatform = yield* HostProcess.Platform;
246 const sdk = yield* androidSdk;
247 const hostEnvironment = deviceHostEnvironment(environment, sdk.root, hostPlatform, path);
248 const startLock = yield* Semaphore.make(1);
249 const runningRef = yield* Ref.make<RunningHost | null>(null);
250 const restartDelayRef = yield* Ref.make(0);
251 const hostId = LOCAL_DEVICE_HOST_ID;
252
253 const platformAvailability = Effect.fn("LocalDeviceHost.platformAvailability")(function* (
254 platform: DevicePlatform,
255 ): Effect.fn.Return<DevicePlatformAvailability> {
256 const reason = yield* platformReason(platform).pipe(
257 Effect.provideService(FileSystem.FileSystem, fs),
258 Effect.provideService(Path.Path, path),
259 );
260 return reason === null ? { platform, available: true } : { platform, available: false, reason };
261 });
262
263 const summary: Effect.Effect<DeviceHostSummary> = Effect.gen(function* () {
264 const [platforms, hubInstalled, agentDeviceInstalled] = yield* Effect.all([
265 Effect.all([platformAvailability("ios"), platformAvailability("android")]),
266 isDeviceHubInstalled(config.baseDir).pipe(
267 Effect.provideService(FileSystem.FileSystem, fs),
268 Effect.provideService(Path.Path, path),
269 ),
270 isAgentDeviceInstalled(config.baseDir).pipe(
271 Effect.provideService(FileSystem.FileSystem, fs),
272 Effect.provideService(Path.Path, path),
273 ),
274 ]);
275 const running = yield* Ref.get(runningRef);
276 const daemon = running?.agentDevice
277 ? yield* readDaemonFile().pipe(Effect.option)
278 : Option.none();
279 const hubAlive = running
280 ? yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false))
281 : false;
282 const agentAlive =
283 Option.isSome(daemon) && daemon.value.pid ? yield* isProcessAlive(daemon.value.pid) : false;
284 const tools = yield* deviceToolVersions(config.baseDir, {
285 ...(hubAlive ? { hub: DEVICE_HUB_VERSION } : {}),
286 ...(agentAlive && Option.isSome(daemon) && daemon.value.version
287 ? { agent: daemon.value.version }
288 : {}),
289 }).pipe(
290 Effect.provideService(FileSystem.FileSystem, fs),
291 Effect.provideService(Path.Path, path),
292 );
293 return {
294 tools,
295 id: hostId,
296 kind: "local",
297 label: "This machine",
298 platforms,
299 hubInstalled,
300 agentDeviceInstalled,
301 };
302 });
303
304 const stopHub = (hub: HubProcess | undefined) =>
305 hub ? Scope.close(hub.scope, Exit.void).pipe(Effect.ignore) : Effect.void;
306
307 const hubStatePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "hub.json");
308
309 const isProcessAlive = (pid: number) =>
310 Effect.sync(() => {
311 try {
312 process.kill(pid, 0);
313 return true;
314 } catch {
315 return false;
316 }
317 });
318
319 /**
320 * A hub left behind by a previous server is identified by pid plus the
321 * command line's entry path, so a recycled pid belonging to something else
322 * is never touched.
323 */
324 const reapStaleHub = Effect.gen(function* () {
325 const previous = yield* fs
326 .readFileString(hubStatePath())
327 .pipe(Effect.flatMap(decodeHubStateFile), Effect.option);
328 if (previous._tag === "None") return;
329 const alive = yield* isProcessAlive(previous.value.pid);
330 if (alive) {
331 const commandLine = yield* runner
332 .run({
333 command: "ps",
334 args: ["-o", "command=", "-p", String(previous.value.pid)],
335 timeout: Duration.seconds(5),
336 timeoutBehavior: "timedOutResult",
337 })
338 .pipe(
339 Effect.map((result) => result.stdout),
340 Effect.orElseSucceed(() => ""),
341 );
342 if (commandLine.includes(previous.value.entryPath)) {
343 yield* Effect.logWarning("Stopping a device hub left behind by a previous server", {
344 pid: previous.value.pid,
345 port: previous.value.port,
346 });
347 yield* Effect.sync(() => {
348 try {
349 process.kill(previous.value.pid, "SIGTERM");
350 } catch {
351 // Already gone.
352 }
353 });
354 }
355 }
356 yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore);
357 }).pipe(Effect.ignoreCause);
358
359 const recordHub = (hub: HubProcess, hubTool: DeviceToolPaths) =>
360 encodeHubStateFile({
361 pid: Number(hub.child.pid),
362 port: Number(new URL(hub.origin).port),
363 entryPath: hubTool.entryPath,
364 }).pipe(
365 Effect.flatMap((contents) =>
366 writeFileStringAtomically({ filePath: hubStatePath(), contents }),
367 ),
368 Effect.provideService(FileSystem.FileSystem, fs),
369 Effect.provideService(Path.Path, path),
370 Effect.ignore,
371 );
372
373 const spawnHub = Effect.fn("LocalDeviceHost.spawnHub")(function* (
374 hubTool: DeviceToolPaths,
375 nodePath: string,
376 ): Effect.fn.Return<HubProcess, DeviceHost.DeviceHostError> {
377 yield* reapStaleHub;
378 yield* fs
379 .makeDirectory(agentDeviceStateDir(path, config.stateDir), { recursive: true })
380 .pipe(Effect.ignore);
381 const port = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
382 Effect.mapError(
383 (cause) =>
384 new DeviceHost.DeviceHostError({
385 hostId,
386 step: "reserving a port for the device hub",
387 cause,
388 }),
389 ),
390 );
391 const origin = `http://127.0.0.1:${port}`;
392 const scope = yield* Scope.make("sequential");
393 // On failure or interrupt, from the spawn on: the hub is not recorded yet,
394 // so nothing else stops it.
395 return yield* Effect.gen(function* () {
396 const child = yield* spawner
397 .spawn(
398 ChildProcess.make(
399 nodePath,
400 [
401 hubTool.entryPath,
402 "--port",
403 String(port),
404 "--host",
405 "127.0.0.1",
406 "--hide-sidebar",
407 "--hide-boot-device",
408 ],
409 {
410 detached: false,
411 shell: false,
412 stdout: "pipe",
413 stderr: "pipe",
414 env: yield* hubEnvironment(hostEnvironment).pipe(
415 Effect.provideService(FileSystem.FileSystem, fs),
416 Effect.provideService(HostProcess.Platform, hostPlatform),
417 ),
418 },
419 ),
420 )
421 .pipe(
422 Effect.provideService(Scope.Scope, scope),
423 Effect.mapError(
424 (cause) =>
425 new DeviceHost.DeviceHostError({
426 hostId,
427 step: "starting the device hub",
428 cause,
429 }),
430 ),
431 );
432 const startedAtMillis = yield* Clock.currentTimeMillis;
433 const hub: HubProcess = { child, scope, origin, startedAtMillis, nodePath };
434 yield* Effect.forkIn(observeHubOutput(hub), scope);
435 yield* waitForHttpReady({
436 baseUrl: origin,
437 path: "/readyz",
438 timeoutMs: HUB_READY_TIMEOUT_MS,
439 makeError: (info) =>
440 new DeviceHost.DeviceHostError({
441 hostId,
442 step: "waiting for the device hub to answer",
443 cause: info.cause,
444 }),
445 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
446 yield* recordHub(hub, hubTool);
447 yield* Effect.logInfo("Device hub started", { pid: Number(child.pid), port });
448 return hub;
449 }).pipe(Effect.onError(() => Scope.close(scope, Exit.void).pipe(Effect.ignore)));
450 });
451
452 const observeHubOutput = (hub: HubProcess) =>
453 hub.child.all.pipe(
454 Stream.decodeText(),
455 Stream.splitLines,
456 Stream.map((line) => line.trim()),
457 Stream.filter((line) => line.length > 0),
458 Stream.runForEach((line) =>
459 Effect.logDebug("Device hub output", { pid: Number(hub.child.pid), output: line }),
460 ),
461 Effect.ignoreCause,
462 );
463
464 /**
465 * Restart the hub when it dies under us, with the same doubling backoff the
466 * relay connector uses so a hub that crashes on boot cannot spin.
467 */
468 const superviseHub = (hub: HubProcess, hubTool: DeviceToolPaths): Effect.Effect<void> =>
469 Effect.gen(function* () {
470 yield* Effect.result(hub.child.exitCode);
471 const running = yield* Ref.get(runningRef);
472 if (running?.hub.child.pid !== hub.child.pid) return;
473 const uptime = (yield* Clock.currentTimeMillis) - hub.startedAtMillis;
474 const delay = yield* Ref.modify(restartDelayRef, (current) => {
475 if (uptime >= HUB_RESTART_STABLE_UPTIME_MS) return [0, 0];
476 const next = current === 0 ? 1_000 : Math.min(current * 2, HUB_RESTART_MAX_DELAY_MS);
477 return [current, next];
478 });
479 yield* Effect.logWarning("Device hub exited; restarting", {
480 pid: Number(hub.child.pid),
481 delayMs: delay,
482 });
483 yield* Effect.sleep(Duration.millis(delay));
484 yield* startLock.withPermits(1)(
485 Effect.gen(function* () {
486 const current = yield* Ref.get(runningRef);
487 if (current?.hub.child.pid !== hub.child.pid) return;
488 const replacement = yield* spawnHub(hubTool, hub.nodePath);
489 yield* Ref.set(runningRef, { ...current, hub: replacement });
490 yield* Effect.forkDetach(superviseHub(replacement, hubTool));
491 }),
492 );
493 }).pipe(
494 Effect.catchCause((cause) => Effect.logWarning("Device hub supervisor failed", { cause })),
495 );
496
497 const daemonFilePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "daemon.json");
498
499 const readDaemonFile = Effect.fn("LocalDeviceHost.readDaemonFile")(function* () {
500 const raw = yield* fs.readFileString(daemonFilePath());
501 return yield* decodeDaemonFile(raw);
502 });
503
504 /**
505 * agent-device auto-starts its daemon on any command. A trivial `devices`
506 * call in HTTP mode is the documented way to bring it up; its output is the
507 * daemon.json this reads back.
508 */
509 const startAgentDeviceDaemon = Effect.fn("LocalDeviceHost.startAgentDeviceDaemon")(function* (
510 agentTool: DeviceToolPaths,
511 nodePath: string,
512 ): Effect.fn.Return<
513 DeviceHost.AgentDeviceEndpoint,
514 | DeviceHost.DeviceHostError
515 | DeviceHost.DeviceHostTimeoutError
516 | DeviceHost.AgentDeviceStartError
517 > {
518 const stateDir = agentDeviceStateDir(path, config.stateDir);
519 yield* fs.makeDirectory(stateDir, { recursive: true }).pipe(Effect.ignore);
520 const existing = yield* readDaemonFile().pipe(Effect.option);
521 const daemonEnvironment: NodeJS.ProcessEnv = {
522 ...hostEnvironment,
523 AGENT_DEVICE_STATE_DIR: stateDir,
524 AGENT_DEVICE_DAEMON_SERVER_MODE: "http",
525 // The daemon idles out after five minutes by default; the server owns
526 // its lifetime here and stops it explicitly.
527 AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: "0",
528 AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
529 FORCE_COLOR: "0",
530 NO_COLOR: "1",
531 };
532 const toEndpoint = (
533 file: typeof AgentDeviceDaemonFile.Type,
534 ): DeviceHost.AgentDeviceEndpoint => ({
535 baseUrl: `http://127.0.0.1:${file.httpPort}`,
536 token: file.token,
537 entryPath: agentTool.entryPath,
538 });
539 if (existing._tag === "Some") {
540 const alive = yield* HttpClient.withScope(httpClient)
541 .get(`http://127.0.0.1:${existing.value.httpPort}/health`)
542 .pipe(
543 Effect.timeout(Duration.seconds(2)),
544 Effect.flatMap((response) =>
545 response.arrayBuffer.pipe(Effect.as(response.status === 200)),
546 ),
547 Effect.scoped,
548 Effect.orElseSucceed(() => false),
549 );
550 if (alive) return toEndpoint(existing.value);
551 yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore);
552 }
553 // There is no `daemon start`; the first command in a state dir spawns the
554 // daemon and blocks until it answers. `devices` is the cheapest one.
555 const runResult = yield* runner
556 .run({
557 command: nodePath,
558 args: [agentTool.entryPath, "devices", "--json"],
559 env: daemonEnvironment,
560 timeout: Duration.millis(DAEMON_READY_TIMEOUT_MS),
561 timeoutBehavior: "timedOutResult",
562 })
563 .pipe(Effect.result);
564 // Discovery can fail after the daemon starts. A published endpoint still
565 // lets agents connect; absent one, preserve the CLI failure instead of polling.
566 const started = yield* readDaemonFile().pipe(Effect.option);
567 if (started._tag === "Some") return toEndpoint(started.value);
568 if (runResult._tag === "Failure") {
569 return yield* new DeviceHost.DeviceHostError({
570 hostId,
571 step: "starting agent tools",
572 cause: runResult.failure,
573 });
574 }
575 const result = runResult.success;
576 if (result.timedOut) {
577 return yield* new DeviceHost.DeviceHostTimeoutError({
578 hostId,
579 timeoutMs: DAEMON_READY_TIMEOUT_MS,
580 });
581 }
582 if (result.code !== 0) {
583 const failure = decodeAgentDeviceFailure(result.stdout);
584 const details = Option.isSome(failure) ? failure.value.error.details : undefined;
585 const reason =
586 details?.reason === "daemon_registration_unproven"
587 ? details.inspection?.reason === "non-directory"
588 ? "daemon_lock_not_directory"
589 : "daemon_registration_unproven"
590 : details?.reason === "daemon_retirement_unconfirmed"
591 ? "daemon_retirement_unconfirmed"
592 : "command_failed";
593 return yield* new DeviceHost.AgentDeviceStartError({
594 hostId,
595 stateDir,
596 exitCode: result.code === null ? null : Number(result.code),
597 reason,
598 cause: result,
599 });
600 }
601 const deadline = (yield* Clock.currentTimeMillis) + DAEMON_READY_TIMEOUT_MS;
602 while (true) {
603 const file = yield* readDaemonFile().pipe(Effect.option);
604 if (file._tag === "Some") return toEndpoint(file.value);
605 if ((yield* Clock.currentTimeMillis) > deadline) {
606 return yield* new DeviceHost.DeviceHostTimeoutError({
607 hostId,
608 timeoutMs: DAEMON_READY_TIMEOUT_MS,
609 });
610 }
611 yield* Effect.sleep(Duration.millis(DAEMON_POLL_MS));
612 }
613 });
614
615 const stopAgentDeviceDaemon = (
616 agentTool: { readonly entryPath: string; readonly nodePath: string } | null,
617 ) =>
618 agentTool
619 ? runner
620 .run({
621 command: agentTool.nodePath,
622 args: [
623 agentTool.entryPath,
624 "daemon",
625 "stop",
626 "--state-dir",
627 agentDeviceStateDir(path, config.stateDir),
628 ],
629 env: { ...hostEnvironment, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" },
630 timeout: Duration.seconds(10),
631 timeoutBehavior: "timedOutResult",
632 })
633 .pipe(Effect.ignore)
634 : Effect.void;
635
636 let agentToolRef: { readonly entryPath: string; readonly nodePath: string } | null = null;
637
638 const ensureHubReady = Effect.fn("LocalDeviceHost.ensureHubReady")(function* (
639 onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,
640 ): Effect.fn.Return<RunningHost, DeviceHost.DeviceHostError | NodeRuntimeUnavailableError> {
641 const running = yield* Ref.get(runningRef);
642 if (running) {
643 const alive = yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false));
644 if (alive) return running;
645 yield* Ref.set(runningRef, null);
646 }
647 const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(
648 Effect.provideService(FileSystem.FileSystem, fs),
649 Effect.provideService(Path.Path, path),
650 Effect.provideService(HostProcess.Platform, hostPlatform),
651 );
652 const installed = yield* isDeviceHubInstalled(config.baseDir).pipe(
653 Effect.provideService(FileSystem.FileSystem, fs),
654 Effect.provideService(Path.Path, path),
655 );
656 if (!installed) {
657 const inventory = yield* summary;
658 yield* onPhase("installing", deviceToolInstallMessage("device hub", inventory.tools?.hub));
659 }
660 const hubTool = yield* ensureDeviceHub(config.baseDir).pipe(
661 Effect.provideService(FileSystem.FileSystem, fs),
662 Effect.provideService(Path.Path, path),
663 Effect.provideService(ProcessRunner.ProcessRunner, runner),
664 Effect.mapError(
665 (cause) =>
666 new DeviceHost.DeviceHostError({
667 hostId,
668 step: "installing device support",
669 cause,
670 }),
671 ),
672 );
673 yield* onPhase("starting");
674 const hub = yield* spawnHub(hubTool, nodePath);
675 // Until the hub is in runningRef, nothing else stops it, so publishing it
676 // is part of the guarded step.
677 const next = yield* Effect.gen(function* () {
678 yield* pruneLocalDeviceTools(config.baseDir, nodePath, "hub").pipe(
679 Effect.provideService(Path.Path, path),
680 Effect.provideService(ProcessRunner.ProcessRunner, runner),
681 Effect.ignore,
682 );
683 const candidate = helperPaths(hubTool);
684 const [axExists, cliExists] = yield* Effect.all([
685 fs.exists(candidate.serveSimAxSettings).pipe(Effect.orElseSucceed(() => false)),
686 fs.exists(candidate.serveSimCli).pipe(Effect.orElseSucceed(() => false)),
687 ]);
688 const next: RunningHost = {
689 hub,
690 agentDevice: null,
691 helpers: {
692 serveSimAxSettings: axExists ? candidate.serveSimAxSettings : null,
693 serveSimCli: cliExists ? candidate.serveSimCli : null,
694 },
695 };
696 yield* Ref.set(runningRef, next);
697 return next;
698 }).pipe(Effect.onError(() => stopHub(hub)));
699 yield* Ref.set(restartDelayRef, 0);
700 yield* Effect.forkDetach(superviseHub(hub, hubTool));
701 return next;
702 });
703
704 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
705 startLock.withPermits(1)(ensureHubReady(onPhase).pipe(Effect.map(toReady)));
706
707 const ensureAgentReady: DeviceHost.DeviceHost["Service"]["ensureAgentReady"] = (onPhase) =>
708 startLock.withPermits(1)(
709 Effect.gen(function* (): Generator<
710 Effect.Effect<
711 unknown,
712 | DeviceHost.DeviceHostError
713 | DeviceHost.DeviceHostTimeoutError
714 | DeviceHost.AgentDeviceStartError
715 | NodeRuntimeUnavailableError
716 >,
717 DeviceHost.DeviceHostAgentReady
718 > {
719 const running = yield* ensureHubReady(onPhase);
720 if (running.agentDevice) return { ...toReady(running), agentDevice: running.agentDevice };
721 const installed = yield* isAgentDeviceInstalled(config.baseDir).pipe(
722 Effect.provideService(FileSystem.FileSystem, fs),
723 Effect.provideService(Path.Path, path),
724 );
725 if (!installed) {
726 const inventory = yield* summary;
727 yield* onPhase(
728 "installing",
729 deviceToolInstallMessage("agent tools", inventory.tools?.agent),
730 );
731 }
732 const agentTool = yield* ensureAgentDevice(config.baseDir).pipe(
733 Effect.provideService(FileSystem.FileSystem, fs),
734 Effect.provideService(Path.Path, path),
735 Effect.provideService(ProcessRunner.ProcessRunner, runner),
736 Effect.mapError(
737 (cause) =>
738 new DeviceHost.DeviceHostError({
739 hostId,
740 step: "installing agent tools",
741 cause,
742 }),
743 ),
744 );
745 agentToolRef = { entryPath: agentTool.entryPath, nodePath: running.hub.nodePath };
746 yield* onPhase("starting");
747 const agentDevice = yield* startAgentDeviceDaemon(agentTool, running.hub.nodePath);
748 yield* pruneLocalDeviceTools(config.baseDir, running.hub.nodePath, "agent").pipe(
749 Effect.provideService(Path.Path, path),
750 Effect.provideService(ProcessRunner.ProcessRunner, runner),
751 Effect.ignore,
752 );
753 const next = { ...running, agentDevice };
754 yield* Ref.set(runningRef, next);
755 return { ...toReady(next), agentDevice };
756 }),
757 );
758
759 const helperPaths = (hubTool: DeviceToolPaths) => {
760 const serveSimDist = path.join(
761 hubTool.installDir,
762 "node_modules",
763 "expo-device-hub",
764 "vendor",
765 "serve-sim",
766 "dist",
767 );
768 return {
769 serveSimAxSettings: path.join(serveSimDist, "simax", "serve-sim-ax-settings"),
770 serveSimCli: path.join(serveSimDist, "serve-sim.js"),
771 };
772 };
773
774 const run: DeviceHost.DeviceHostReady["run"] = (command, args, options) =>
775 runner
776 .run({
777 command:
778 command === "emulator" && sdk.root
779 ? path.join(
780 sdk.root,
781 "emulator",
782 hostPlatform === "win32" ? "emulator.exe" : "emulator",
783 )
784 : command,
785 args,
786 env: hostEnvironment,
787 timeout: Duration.millis(options?.timeoutMs ?? 20_000),
788 timeoutBehavior: "timedOutResult",
789 ...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
790 })
791 .pipe(
792 Effect.map((result) => ({
793 stdout: result.stdout,
794 stderr: result.stderr,
795 code: Number(result.code),
796 })),
797 Effect.catch((cause) => Effect.succeed({ stdout: "", stderr: String(cause), code: 127 })),
798 );
799
800 const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({
801 hub: { origin: running.hub.origin } satisfies DeviceHost.DeviceHubEndpoint,
802 nodePath: running.hub.nodePath,
803 run,
804 helpers: running.helpers,
805 });
806
807 const current: DeviceHost.DeviceHost["Service"]["current"] = Ref.get(runningRef).pipe(
808 Effect.map((running) => (running ? toReady(running) : null)),
809 );
810
811 const stopAgent: DeviceHost.DeviceHost["Service"]["stopAgent"] = startLock.withPermits(1)(
812 Effect.gen(function* () {
813 yield* stopAgentDeviceDaemon(agentToolRef);
814 yield* Ref.update(runningRef, (running) =>
815 running ? { ...running, agentDevice: null } : running,
816 );
817 }),
818 );
819
820 const stop: DeviceHost.DeviceHost["Service"]["stop"] = startLock.withPermits(1)(
821 Effect.gen(function* () {
822 const running = yield* Ref.getAndSet(runningRef, null);
823 yield* stopHub(running?.hub);
824 yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore);
825 yield* stopAgentDeviceDaemon(agentToolRef);
826 }),
827 );
828
829 // Never leave the hub or daemon behind when the server's scope closes.
830 yield* Effect.addFinalizer(() => stop);
831
832 const host: DeviceHost.DeviceHost["Service"] = {
833 id: hostId,
834 summary,
835 platformAvailability,
836 ensureReady,
837 ensureAgentReady,
838 current,
839 stopAgent,
840 stop,
841 };
842 return host;
843});
844
845export const layer = Layer.effect(DeviceHost.DeviceHost, make());
846
847/** Exposed for tests. */
848export const __testing = {
849 AgentDeviceDaemonFile,
850 androidSdk,
851 platformReason,
852 deviceHostEnvironment,
853 hubEnvironment,
854};