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 // Waits for the hub's lifetime and re-forks on restart; a span would nest across restarts.
497 const superviseHub: (hub: HubProcess, hubTool: DeviceToolPaths) => Effect.Effect<void> =
498 Effect.fnUntraced(
499 function* (hub: HubProcess, hubTool: DeviceToolPaths) {
500 yield* Effect.result(hub.child.exitCode);
501 const running = yield* Ref.get(runningRef);
502 if (running?.hub.child.pid !== hub.child.pid) return;
503 const uptime = (yield* Clock.currentTimeMillis) - hub.startedAtMillis;
504 const delay = yield* Ref.modify(restartDelayRef, (current) => {
505 if (uptime >= HUB_RESTART_STABLE_UPTIME_MS) return [0, 0];
506 const next = current === 0 ? 1_000 : Math.min(current * 2, HUB_RESTART_MAX_DELAY_MS);
507 return [current, next];
508 });
509 yield* Effect.logWarning("Device hub exited; restarting", {
510 pid: Number(hub.child.pid),
511 delayMs: delay,
512 });
513 yield* Effect.sleep(Duration.millis(delay));
514 yield* startLock.withPermits(1)(
515 Effect.gen(function* () {
516 const current = yield* Ref.get(runningRef);
517 if (current?.hub.child.pid !== hub.child.pid) return;
518 const replacement = yield* spawnHub(hubTool, hub.nodePath);
519 yield* Ref.set(runningRef, { ...current, hub: replacement });
520 yield* Effect.forkDetach(superviseHub(replacement, hubTool));
521 }),
522 );
523 },
524 Effect.catchCause((cause) => Effect.logWarning("Device hub supervisor failed", { cause })),
525 );
526
527 const daemonFilePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "daemon.json");
528
529 const readDaemonFile = Effect.fn("LocalDeviceHost.readDaemonFile")(function* () {
530 const raw = yield* fs.readFileString(daemonFilePath());
531 return yield* decodeDaemonFile(raw);
532 });
533
534 const startAgentDeviceDaemon = Effect.fn("LocalDeviceHost.startAgentDeviceDaemon")(function* (
535 agentTool: DeviceToolPaths,
536 nodePath: string,
537 ): Effect.fn.Return<
538 DeviceHost.AgentDeviceEndpoint,
539 | DeviceHost.DeviceHostError
540 | DeviceHost.DeviceHostTimeoutError
541 | DeviceHost.AgentDeviceStartError
542 > {
543 const stateDir = agentDeviceStateDir(path, config.stateDir);
544 yield* fs.makeDirectory(stateDir, { recursive: true }).pipe(Effect.ignore);
545 const existing = yield* readDaemonFile().pipe(Effect.option);
546 const daemonEnvironment: NodeJS.ProcessEnv = {
547 ...hostEnvironment,
548 AGENT_DEVICE_STATE_DIR: stateDir,
549 AGENT_DEVICE_DAEMON_SERVER_MODE: "http",
550 // The daemon idles out after five minutes by default; the server owns
551 // its lifetime here and stops it explicitly.
552 AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: "0",
553 AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
554 FORCE_COLOR: "0",
555 NO_COLOR: "1",
556 };
557 const toEndpoint = (
558 file: typeof AgentDeviceDaemonFile.Type,
559 ): DeviceHost.AgentDeviceEndpoint => ({
560 baseUrl: `http://127.0.0.1:${file.httpPort}`,
561 token: file.token,
562 entryPath: agentTool.entryPath,
563 });
564 if (existing._tag === "Some") {
565 const alive = yield* HttpClient.withScope(httpClient)
566 .get(`http://127.0.0.1:${existing.value.httpPort}/health`)
567 .pipe(
568 Effect.timeout(Duration.seconds(2)),
569 Effect.flatMap((response) =>
570 response.arrayBuffer.pipe(Effect.as(response.status === 200)),
571 ),
572 Effect.scoped,
573 Effect.orElseSucceed(() => false),
574 );
575 if (alive) return toEndpoint(existing.value);
576 yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore);
577 }
578 // There is no `daemon start`; the first command in a state dir spawns the
579 // daemon and blocks until it answers. `devices` is the cheapest one.
580 const runResult = yield* runner
581 .run({
582 command: nodePath,
583 args: [agentTool.entryPath, "devices", "--json"],
584 env: daemonEnvironment,
585 timeout: Duration.millis(DAEMON_READY_TIMEOUT_MS),
586 timeoutBehavior: "timedOutResult",
587 })
588 .pipe(Effect.result);
589 // Discovery can fail after the daemon starts. A published endpoint still
590 // lets agents connect; absent one, preserve the CLI failure instead of polling.
591 const started = yield* readDaemonFile().pipe(Effect.option);
592 if (started._tag === "Some") return toEndpoint(started.value);
593 if (runResult._tag === "Failure") {
594 return yield* new DeviceHost.DeviceHostError({
595 hostId,
596 step: "starting agent tools",
597 cause: runResult.failure,
598 });
599 }
600 const result = runResult.success;
601 if (result.timedOut) {
602 return yield* new DeviceHost.DeviceHostTimeoutError({
603 hostId,
604 timeoutMs: DAEMON_READY_TIMEOUT_MS,
605 });
606 }
607 if (result.code !== 0) {
608 const failure = decodeAgentDeviceFailure(result.stdout);
609 const details = Option.isSome(failure) ? failure.value.error.details : undefined;
610 const reason =
611 details?.reason === "daemon_registration_unproven"
612 ? details.inspection?.reason === "non-directory"
613 ? "daemon_lock_not_directory"
614 : "daemon_registration_unproven"
615 : details?.reason === "daemon_retirement_unconfirmed"
616 ? "daemon_retirement_unconfirmed"
617 : "command_failed";
618 return yield* new DeviceHost.AgentDeviceStartError({
619 hostId,
620 stateDir,
621 exitCode: result.code === null ? null : Number(result.code),
622 reason,
623 cause: result,
624 });
625 }
626 const deadline = (yield* Clock.currentTimeMillis) + DAEMON_READY_TIMEOUT_MS;
627 while (true) {
628 const file = yield* readDaemonFile().pipe(Effect.option);
629 if (file._tag === "Some") return toEndpoint(file.value);
630 if ((yield* Clock.currentTimeMillis) > deadline) {
631 return yield* new DeviceHost.DeviceHostTimeoutError({
632 hostId,
633 timeoutMs: DAEMON_READY_TIMEOUT_MS,
634 });
635 }
636 yield* Effect.sleep(Duration.millis(DAEMON_POLL_MS));
637 }
638 });
639
640 const stopAgentDeviceDaemon = (
641 agentTool: { readonly entryPath: string; readonly nodePath: string } | null,
642 ) =>
643 agentTool
644 ? runner
645 .run({
646 command: agentTool.nodePath,
647 args: [
648 agentTool.entryPath,
649 "daemon",
650 "stop",
651 "--state-dir",
652 agentDeviceStateDir(path, config.stateDir),
653 ],
654 env: { ...hostEnvironment, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" },
655 timeout: Duration.seconds(10),
656 timeoutBehavior: "timedOutResult",
657 })
658 .pipe(Effect.ignore)
659 : Effect.void;
660
661 let agentToolRef: { readonly entryPath: string; readonly nodePath: string } | null = null;
662
663 const ensureHubReady = Effect.fn("LocalDeviceHost.ensureHubReady")(function* (
664 onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,
665 ): Effect.fn.Return<RunningHost, DeviceHost.DeviceHostError | NodeRuntimeUnavailableError> {
666 const running = yield* Ref.get(runningRef);
667 if (running) {
668 const alive = yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false));
669 if (alive) return running;
670 yield* Ref.set(runningRef, null);
671 }
672 const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(
673 Effect.provideService(FileSystem.FileSystem, fs),
674 Effect.provideService(Path.Path, path),
675 Effect.provideService(HostProcess.Platform, hostPlatform),
676 );
677 const installed = yield* isDeviceHubInstalled(config.baseDir).pipe(
678 Effect.provideService(FileSystem.FileSystem, fs),
679 Effect.provideService(Path.Path, path),
680 );
681 if (!installed) {
682 const inventory = yield* summary;
683 yield* onPhase("installing", deviceToolInstallMessage("device hub", inventory.tools?.hub));
684 }
685 const hubTool = yield* ensureDeviceHub(config.baseDir).pipe(
686 Effect.provideService(FileSystem.FileSystem, fs),
687 Effect.provideService(Path.Path, path),
688 Effect.provideService(ProcessRunner.ProcessRunner, runner),
689 Effect.mapError(
690 (cause) =>
691 new DeviceHost.DeviceHostError({
692 hostId,
693 step: "installing device support",
694 cause,
695 }),
696 ),
697 );
698 yield* onPhase("starting");
699 const hub = yield* spawnHub(hubTool, nodePath);
700 const next = yield* Effect.gen(function* () {
701 yield* pruneLocalDeviceTools(config.baseDir, nodePath, "hub").pipe(
702 Effect.provideService(Path.Path, path),
703 Effect.provideService(ProcessRunner.ProcessRunner, runner),
704 Effect.ignore,
705 );
706 const candidate = helperPaths(hubTool);
707 const [axExists, cliExists] = yield* Effect.all([
708 fs.exists(candidate.serveSimAxSettings).pipe(Effect.orElseSucceed(() => false)),
709 fs.exists(candidate.serveSimCli).pipe(Effect.orElseSucceed(() => false)),
710 ]);
711 const next: RunningHost = {
712 hub,
713 agentDevice: null,
714 helpers: {
715 serveSimAxSettings: axExists ? candidate.serveSimAxSettings : null,
716 serveSimCli: cliExists ? candidate.serveSimCli : null,
717 },
718 };
719 yield* Ref.set(runningRef, next);
720 return next;
721 }).pipe(Effect.onError(() => stopHub(hub)));
722 yield* Ref.set(restartDelayRef, 0);
723 yield* Effect.forkDetach(superviseHub(hub, hubTool));
724 return next;
725 });
726
727 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
728 startLock.withPermits(1)(ensureHubReady(onPhase).pipe(Effect.map(toReady)));
729
730 const ensureAgentReady: DeviceHost.DeviceHost["Service"]["ensureAgentReady"] = (onPhase) =>
731 startLock.withPermits(1)(
732 Effect.gen(function* (): Generator<
733 Effect.Effect<
734 unknown,
735 | DeviceHost.DeviceHostError
736 | DeviceHost.DeviceHostTimeoutError
737 | DeviceHost.AgentDeviceStartError
738 | NodeRuntimeUnavailableError
739 >,
740 DeviceHost.DeviceHostAgentReady
741 > {
742 const running = yield* ensureHubReady(onPhase);
743 if (running.agentDevice) return { ...toReady(running), agentDevice: running.agentDevice };
744 const installed = yield* isAgentDeviceInstalled(config.baseDir).pipe(
745 Effect.provideService(FileSystem.FileSystem, fs),
746 Effect.provideService(Path.Path, path),
747 );
748 if (!installed) {
749 const inventory = yield* summary;
750 yield* onPhase(
751 "installing",
752 deviceToolInstallMessage("agent tools", inventory.tools?.agent),
753 );
754 }
755 const agentTool = yield* ensureAgentDevice(config.baseDir).pipe(
756 Effect.provideService(FileSystem.FileSystem, fs),
757 Effect.provideService(Path.Path, path),
758 Effect.provideService(ProcessRunner.ProcessRunner, runner),
759 Effect.mapError(
760 (cause) =>
761 new DeviceHost.DeviceHostError({
762 hostId,
763 step: "installing agent tools",
764 cause,
765 }),
766 ),
767 );
768 agentToolRef = { entryPath: agentTool.entryPath, nodePath: running.hub.nodePath };
769 yield* onPhase("starting");
770 const agentDevice = yield* startAgentDeviceDaemon(agentTool, running.hub.nodePath);
771 yield* pruneLocalDeviceTools(config.baseDir, running.hub.nodePath, "agent").pipe(
772 Effect.provideService(Path.Path, path),
773 Effect.provideService(ProcessRunner.ProcessRunner, runner),
774 Effect.ignore,
775 );
776 const next = { ...running, agentDevice };
777 yield* Ref.set(runningRef, next);
778 return { ...toReady(next), agentDevice };
779 }),
780 );
781
782 const helperPaths = (hubTool: DeviceToolPaths) => {
783 const serveSimDist = path.join(
784 hubTool.installDir,
785 "node_modules",
786 "expo-device-hub",
787 "vendor",
788 "serve-sim",
789 "dist",
790 );
791 return {
792 serveSimAxSettings: path.join(serveSimDist, "simax", "serve-sim-ax-settings"),
793 serveSimCli: path.join(serveSimDist, "serve-sim.js"),
794 };
795 };
796
797 const run: DeviceHost.DeviceHostReady["run"] = (command, args, options) =>
798 runner
799 .run({
800 command:
801 command === "emulator" && sdk.root
802 ? path.join(
803 sdk.root,
804 "emulator",
805 hostPlatform === "win32" ? "emulator.exe" : "emulator",
806 )
807 : command,
808 args,
809 cwd: workingDirectory,
810 env: hostEnvironment,
811 timeout: Duration.millis(options?.timeoutMs ?? 20_000),
812 timeoutBehavior: "timedOutResult",
813 ...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
814 })
815 .pipe(
816 Effect.map((result) => ({
817 stdout: result.stdout,
818 stderr: result.stderr,
819 code: result.timedOut ? 124 : Number(result.code ?? 127),
820 })),
821 Effect.catch((cause) => Effect.succeed({ stdout: "", stderr: String(cause), code: 127 })),
822 );
823
824 const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({
825 hub: { origin: running.hub.origin } satisfies DeviceHost.DeviceHubEndpoint,
826 nodePath: running.hub.nodePath,
827 run,
828 helpers: running.helpers,
829 });
830
831 const current: DeviceHost.DeviceHost["Service"]["current"] = Ref.get(runningRef).pipe(
832 Effect.map((running) => (running ? toReady(running) : null)),
833 );
834
835 const stopAgent: DeviceHost.DeviceHost["Service"]["stopAgent"] = startLock.withPermits(1)(
836 Effect.gen(function* () {
837 yield* stopAgentDeviceDaemon(agentToolRef);
838 yield* Ref.update(runningRef, (running) =>
839 running ? { ...running, agentDevice: null } : running,
840 );
841 }),
842 );
843
844 const stop: DeviceHost.DeviceHost["Service"]["stop"] = startLock.withPermits(1)(
845 Effect.gen(function* () {
846 const running = yield* Ref.getAndSet(runningRef, null);
847 yield* stopHub(running?.hub);
848 yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore);
849 yield* stopAgentDeviceDaemon(agentToolRef);
850 }),
851 );
852
853 yield* Effect.addFinalizer(() => stop);
854
855 const host: DeviceHost.DeviceHost["Service"] = {
856 id: hostId,
857 summary,
858 platformAvailability,
859 ensureReady,
860 ensureAgentReady,
861 current,
862 stopAgent,
863 stop,
864 };
865 return host;
866});
867
868export const layer = Layer.effect(DeviceHost.DeviceHost, make());
869
870export const __testing = {
871 AgentDeviceDaemonFile,
872 androidSdk,
873 platformReason,
874 deviceHostEnvironment,
875 hubEnvironment,
876};