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