Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LocalDeviceHost.ts

725 lines26.1 KB

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