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