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