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

LocalDeviceHost.ts

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