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