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

LocalDeviceHost.ts

800 lines29.4 KB

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