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