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

LocalDeviceHost.ts

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