Open History to see the last commit
1import { pruneLocalDeviceTools } from "./deviceToolMaintenance.ts";
2import { deviceToolInstallMessage } from "@t3tools/contracts";
3// The hub runs at origin root; T3 strips its prefix and the Device panel derives stream URLs from it.
4import {
5 type DeviceHostSummary,
6 type DevicePlatform,
7 type DevicePlatformAvailability,
8 LOCAL_DEVICE_HOST_ID,
9 LOCAL_DEVICE_HOST_LABEL,
10} from "@t3tools/contracts";
11import { waitForHttpReady } from "@t3tools/shared/httpReadiness";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import {
14 resolveNodeExecutable,
15 type NodeRuntimeUnavailableError,
16} from "@t3tools/shared/nodeRuntime";
17import * as NetService from "@t3tools/shared/Net";
18import { isCommandAvailable } from "@t3tools/shared/shell";
19import * as Clock from "effect/Clock";
20import * as Duration from "effect/Duration";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as Path from "effect/Path";
27import * as Ref from "effect/Ref";
28import * as Schema from "effect/Schema";
29import * as Scope from "effect/Scope";
30import * as Semaphore from "effect/Semaphore";
31import * as Stream from "effect/Stream";
32import { HttpClient } from "effect/http";
33import * as ChildProcess from "effect/process/ChildProcess";
34import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
35
36import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
37import * as ServerConfig from "../config.ts";
38import * as ProcessRunner from "../processRunner.ts";
39import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
40import * as DeviceHost from "./DeviceHost.ts";
41import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
42import {
43 agentDeviceStateDir,
44 type DeviceToolPaths,
45 ensureAgentDevice,
46 ensureDeviceHub,
47 isAgentDeviceInstalled,
48 isDeviceHubInstalled,
49 deviceToolVersions,
50 AGENT_DEVICE_VERSION,
51 DEVICE_HUB_VERSION,
52 installedAgentDeviceEntry,
53} from "./DeviceToolchain.ts";
54
55const HUB_READY_TIMEOUT_MS = 30_000;
56const DAEMON_READY_TIMEOUT_MS = 30_000;
57const DAEMON_POLL_MS = 100;
58const HUB_RESTART_STABLE_UPTIME_MS = 60_000;
59const HUB_RESTART_MAX_DELAY_MS = 30_000;
60
61// Persist hub state so restarts without finalizers can clean up orphaned loopback listeners.
62const HubStateFile = Schema.Struct({
63 pid: Schema.Int,
64 port: Schema.Int,
65 entryPath: Schema.String,
66});
67const decodeHubStateFile = Schema.decodeUnknownEffect(Schema.fromJsonString(HubStateFile));
68const encodeHubStateFile = Schema.encodeUnknownEffect(Schema.fromJsonString(HubStateFile));
69
70const AgentDeviceDaemonFile = Schema.Struct({
71 httpPort: Schema.Int,
72 token: Schema.String,
73 pid: Schema.optional(Schema.Int),
74 version: Schema.optional(Schema.String),
75});
76const decodeDaemonFile = Schema.decodeUnknownEffect(Schema.fromJsonString(AgentDeviceDaemonFile));
77
78const decodeAgentDeviceFailure = Schema.decodeUnknownOption(
79 Schema.fromJsonString(
80 Schema.Struct({
81 error: Schema.Struct({
82 details: Schema.Struct({
83 reason: Schema.String,
84 inspection: Schema.optional(Schema.Struct({ reason: Schema.String })),
85 }),
86 }),
87 }),
88 ),
89);
90
91interface HubProcess {
92 readonly nodePath: string;
93 readonly child: ChildProcessSpawner.ChildProcessHandle;
94 readonly scope: Scope.Closeable;
95 readonly origin: string;
96 readonly startedAtMillis: number;
97}
98
99interface RunningHost {
100 readonly hub: HubProcess;
101 readonly agentDevice: DeviceHost.AgentDeviceEndpoint | null;
102 readonly helpers: DeviceHost.DeviceHostReady["helpers"];
103}
104
105const platformReason = Effect.fn("LocalDeviceHost.platformReason")(function* (
106 platform: DevicePlatform,
107): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
108 const hostPlatform = yield* HostProcess.Platform;
109 if (platform === "ios") {
110 if (hostPlatform !== "darwin") return "iOS Simulators need macOS with Xcode.";
111 if (!(yield* isCommandAvailable("xcrun"))) return "Xcode command line tools were not found.";
112 return null;
113 }
114 const sdk = yield* androidSdk;
115 if (!sdk.root)
116 return "Android SDK was not found. Install it with Android Studio or set ANDROID_HOME to your SDK directory.";
117 if (!sdk.adb)
118 return `Android SDK Platform-Tools are missing from ${sdk.root}. Install them in Android Studio's SDK Manager.`;
119 if (!sdk.emulator)
120 return `Android Emulator is missing from ${sdk.root}. Install it in Android Studio's SDK Manager.`;
121 if (!sdk.avdmanager) {
122 if (sdk.legacyAvdmanager)
123 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.`;
124 return `Android SDK Command-line Tools (latest) are missing from ${sdk.root}. Install them in Android Studio's SDK Manager.`;
125 }
126 return null;
127});
128
129const androidSdk = Effect.gen(function* () {
130 const fs = yield* FileSystem.FileSystem;
131 const path = yield* Path.Path;
132 const environment = yield* HostProcess.Environment;
133 const platform = yield* HostProcess.Platform;
134 const windows = platform === "win32";
135 const home = environment.HOME ?? environment.USERPROFILE ?? "";
136 const explicit = environment.ANDROID_HOME?.trim() || environment.ANDROID_SDK_ROOT?.trim();
137 const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false));
138 const adbBinary = windows ? "adb.exe" : "adb";
139 const avdmanagerBinary = windows ? "avdmanager.bat" : "avdmanager";
140 const inspect = Effect.fnUntraced(function* (root: string) {
141 const adb = yield* exists(path.join(root, "platform-tools", adbBinary));
142 const emulator = yield* exists(
143 path.join(root, "emulator", windows ? "emulator.exe" : "emulator"),
144 );
145 if (!explicit && !adb && !emulator) return null;
146 const avdmanager = yield* exists(
147 path.join(root, "cmdline-tools", "latest", "bin", avdmanagerBinary),
148 );
149 const legacyAvdmanager =
150 !avdmanager && (yield* exists(path.join(root, "tools", "bin", avdmanagerBinary)));
151 return { root, adb, emulator, avdmanager, legacyAvdmanager };
152 });
153 const candidates = explicit
154 ? [explicit]
155 : [
156 path.join(home, "Library", "Android", "sdk"),
157 path.join(home, "Android", "Sdk"),
158 path.join(
159 environment.LOCALAPPDATA ?? path.join(home, "AppData", "Local"),
160 "Android",
161 "Sdk",
162 ),
163 ];
164 for (const root of candidates) {
165 const sdk = yield* inspect(root);
166 if (sdk) return sdk;
167 }
168 // PATH entries can be slow to stat (network shares), so only consult them after the standard locations miss.
169 if (!explicit) {
170 const searchPath = environment.PATH ?? environment.Path ?? "";
171 for (const directory of searchPath.split(windows ? ";" : ":")) {
172 if (!directory) continue;
173 const adb = path.join(directory, adbBinary);
174 if (!(yield* exists(adb))) continue;
175 const resolved = yield* fs.realPath(adb).pipe(Effect.orElseSucceed(() => adb));
176 const sdk = yield* inspect(path.dirname(path.dirname(resolved)));
177 if (sdk) return sdk;
178 }
179 }
180 return { root: null, adb: false, emulator: false, avdmanager: false, legacyAvdmanager: false };
181});
182
183const deviceHostEnvironment = (
184 environment: NodeJS.ProcessEnv,
185 sdkRoot: string | null,
186 hostPlatform: NodeJS.Platform,
187 path: Path.Path,
188): NodeJS.ProcessEnv => {
189 return sdkRoot
190 ? {
191 ...environment,
192 ANDROID_HOME: sdkRoot,
193 PATH: [
194 path.join(sdkRoot, "platform-tools"),
195 path.join(sdkRoot, "emulator"),
196 environment.PATH ?? environment.Path ?? "",
197 ].join(hostPlatform === "win32" ? ";" : ":"),
198 }
199 : environment;
200};
201
202const hubEnvironment = Effect.fn("LocalDeviceHost.hubEnvironment")(function* (
203 environment: NodeJS.ProcessEnv,
204) {
205 const env: NodeJS.ProcessEnv = { ...environment, FORCE_COLOR: "0", NO_COLOR: "1" };
206 const platform = yield* HostProcess.Platform;
207 const uid = yield* HostProcess.UserId;
208 if (env.ANDROID_HOME) {
209 const path = yield* Path.Path;
210 const runner = yield* ProcessRunner.ProcessRunner;
211 const emulator = path.join(
212 env.ANDROID_HOME,
213 "emulator",
214 platform === "win32" ? "emulator.exe" : "emulator",
215 );
216 const cameraArgs = yield* Effect.forEach(["front", "back"], (facing) =>
217 runner
218 .run({
219 command: emulator,
220 args: [`-help-camera-${facing}`],
221 env,
222 timeout: Duration.seconds(5),
223 })
224 .pipe(
225 Effect.map((result) => {
226 const help = `${result.stdout}\n${result.stderr}`;
227 // The hub wires imagefile cameras unconditionally; older SDK emulators reject that mode.
228 return result.code === 0 && /\bemulated\b/.test(help) && !/\bimagefile\b/.test(help)
229 ? `-camera-${facing} emulated`
230 : "";
231 }),
232 Effect.orElseSucceed(() => ""),
233 ),
234 );
235 const overrides = cameraArgs.filter(Boolean).join(" ");
236 if (overrides) {
237 env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS = [overrides, env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS]
238 .filter(Boolean)
239 .join(" ");
240 }
241 }
242 if (platform === "linux" && env.XDG_RUNTIME_DIR === undefined && uid !== undefined) {
243 // SSH sessions may omit the directory where the emulator publishes its gRPC token.
244 const runtimeDir = `/run/user/${uid}`;
245 const fs = yield* FileSystem.FileSystem;
246 const stat = yield* fs.stat(runtimeDir).pipe(Effect.option);
247 if (
248 stat._tag === "Some" &&
249 stat.value.type === "Directory" &&
250 Option.contains(stat.value.uid, uid)
251 ) {
252 env.XDG_RUNTIME_DIR = runtimeDir;
253 }
254 }
255 return env;
256});
257
258/** Only a Mac can list Apple simulators; elsewhere the hub's attempt surfaces as an error. */
259const hubPlatformArguments = (hostPlatform: NodeJS.Platform) =>
260 hostPlatform === "darwin" ? [] : ["--platform", "android"];
261
262export const make = Effect.fn("LocalDeviceHost.make")(function* () {
263 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
264 const config = yield* ServerConfig.ServerConfig;
265 const path = yield* Path.Path;
266 const fs = yield* FileSystem.FileSystem;
267 const net = yield* NetService.NetService;
268 const runner = yield* ProcessRunner.ProcessRunner;
269 const httpClient = yield* HttpClient.HttpClient;
270 const environment = yield* HostProcess.Environment;
271 const workingDirectory = yield* HostProcess.WorkingDirectory;
272 const hostPlatform = yield* HostProcess.Platform;
273 // Resolved per use: the desktop shell snapshot can select another SDK after the host exists.
274 const currentSdk = androidSdk.pipe(
275 Effect.provideService(FileSystem.FileSystem, fs),
276 Effect.provideService(Path.Path, path),
277 Effect.provideService(HostProcess.Environment, environment),
278 Effect.provideService(HostProcess.Platform, hostPlatform),
279 );
280 const currentHostEnvironment = currentSdk.pipe(
281 Effect.map((sdk) => deviceHostEnvironment(environment, sdk.root, hostPlatform, path)),
282 );
283 const startLock = yield* Semaphore.make(1);
284 const runningRef = yield* Ref.make<RunningHost | null>(null);
285 const restartDelayRef = yield* Ref.make(0);
286 const hostId = LOCAL_DEVICE_HOST_ID;
287
288 const platformAvailability = Effect.fn("LocalDeviceHost.platformAvailability")(function* (
289 platform: DevicePlatform,
290 ): Effect.fn.Return<DevicePlatformAvailability> {
291 const reason = yield* platformReason(platform).pipe(
292 Effect.provideService(FileSystem.FileSystem, fs),
293 Effect.provideService(Path.Path, path),
294 );
295 return reason === null ? { platform, available: true } : { platform, available: false, reason };
296 });
297
298 const summary: Effect.Effect<DeviceHostSummary> = Effect.gen(function* () {
299 const [platforms, hubInstalled, agentDeviceInstalled] = yield* Effect.all([
300 Effect.all([platformAvailability("ios"), platformAvailability("android")]),
301 isDeviceHubInstalled(config.baseDir).pipe(
302 Effect.provideService(FileSystem.FileSystem, fs),
303 Effect.provideService(Path.Path, path),
304 ),
305 isAgentDeviceInstalled(config.baseDir).pipe(
306 Effect.provideService(FileSystem.FileSystem, fs),
307 Effect.provideService(Path.Path, path),
308 ),
309 ]);
310 const running = yield* Ref.get(runningRef);
311 const daemon = running?.agentDevice
312 ? yield* readDaemonFile().pipe(Effect.option)
313 : Option.none();
314 const hubAlive = running
315 ? yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false))
316 : false;
317 const agentAlive =
318 Option.isSome(daemon) && daemon.value.pid ? yield* isProcessAlive(daemon.value.pid) : false;
319 const tools = yield* deviceToolVersions(config.baseDir, {
320 ...(hubAlive ? { hub: DEVICE_HUB_VERSION } : {}),
321 ...(agentAlive && Option.isSome(daemon) && daemon.value.version
322 ? { agent: daemon.value.version }
323 : {}),
324 }).pipe(
325 Effect.provideService(FileSystem.FileSystem, fs),
326 Effect.provideService(Path.Path, path),
327 );
328 return {
329 tools,
330 id: hostId,
331 kind: "local",
332 label: LOCAL_DEVICE_HOST_LABEL,
333 platforms,
334 hubInstalled,
335 agentDeviceInstalled,
336 };
337 });
338
339 const stopHub = (hub: HubProcess | undefined) =>
340 hub ? Scope.close(hub.scope, Exit.void).pipe(Effect.ignore) : Effect.void;
341
342 const hubStatePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "hub.json");
343
344 const isProcessAlive = (pid: number) =>
345 Effect.sync(() => {
346 try {
347 process.kill(pid, 0);
348 return true;
349 } catch {
350 return false;
351 }
352 });
353
354 // Check PID and entry path before reaping; the PID may have been recycled.
355 const reapStaleHub = Effect.gen(function* () {
356 const previous = yield* fs
357 .readFileString(hubStatePath())
358 .pipe(Effect.flatMap(decodeHubStateFile), Effect.option);
359 if (previous._tag === "None") return;
360 const alive = yield* isProcessAlive(previous.value.pid);
361 if (alive) {
362 const commandLine = yield* runner
363 .run({
364 command: "ps",
365 args: ["-o", "command=", "-p", String(previous.value.pid)],
366 timeout: Duration.seconds(5),
367 timeoutBehavior: "timedOutResult",
368 })
369 .pipe(
370 Effect.map((result) => result.stdout),
371 Effect.orElseSucceed(() => ""),
372 );
373 if (commandLine.includes(previous.value.entryPath)) {
374 yield* Effect.logWarning("Stopping a device hub left behind by a previous server", {
375 pid: previous.value.pid,
376 port: previous.value.port,
377 });
378 yield* Effect.sync(() => {
379 try {
380 process.kill(previous.value.pid, "SIGTERM");
381 } catch {}
382 });
383 }
384 }
385 yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore);
386 }).pipe(Effect.ignoreCause);
387
388 const recordHub = (hub: HubProcess, hubTool: DeviceToolPaths) =>
389 encodeHubStateFile({
390 pid: Number(hub.child.pid),
391 port: Number(new URL(hub.origin).port),
392 entryPath: hubTool.entryPath,
393 }).pipe(
394 Effect.flatMap((contents) =>
395 writeFileStringAtomically({ filePath: hubStatePath(), contents }),
396 ),
397 Effect.provideService(FileSystem.FileSystem, fs),
398 Effect.provideService(Path.Path, path),
399 Effect.ignore,
400 );
401
402 const spawnHub = Effect.fn("LocalDeviceHost.spawnHub")(function* (
403 hubTool: DeviceToolPaths,
404 nodePath: string,
405 ): Effect.fn.Return<HubProcess, DeviceHost.DeviceHostError> {
406 yield* reapStaleHub;
407 yield* fs
408 .makeDirectory(agentDeviceStateDir(path, config.stateDir), { recursive: true })
409 .pipe(Effect.ignore);
410 const port = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
411 Effect.mapError(
412 (cause) =>
413 new DeviceHost.DeviceHostError({
414 hostId,
415 step: "reserving a port for the device hub",
416 cause,
417 }),
418 ),
419 );
420 const origin = `http://127.0.0.1:${port}`;
421 const scope = yield* Scope.make("sequential");
422 // The hub is not recorded yet; stop it on failure or interruption from spawn onward.
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(yield* currentHostEnvironment).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: Pick<DeviceToolPaths, "entryPath">,
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 ...(yield* currentHostEnvironment),
548 AGENT_DEVICE_STATE_DIR: stateDir,
549 AGENT_DEVICE_DAEMON_SERVER_MODE: "http",
550 // Disable the five-minute idle timeout; the server owns shutdown.
551 AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: "0",
552 AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
553 FORCE_COLOR: "0",
554 NO_COLOR: "1",
555 };
556 const toEndpoint = (
557 file: typeof AgentDeviceDaemonFile.Type,
558 ): DeviceHost.AgentDeviceEndpoint => ({
559 baseUrl: `http://127.0.0.1:${file.httpPort}`,
560 token: file.token,
561 entryPath: agentTool.entryPath,
562 });
563 if (existing._tag === "Some") {
564 const alive = yield* HttpClient.withScope(httpClient)
565 .get(`http://127.0.0.1:${existing.value.httpPort}/health`)
566 .pipe(
567 Effect.timeout(Duration.seconds(2)),
568 Effect.flatMap((response) =>
569 response.arrayBuffer.pipe(Effect.as(response.status === 200)),
570 ),
571 Effect.scoped,
572 Effect.orElseSucceed(() => false),
573 );
574 if (alive) return toEndpoint(existing.value);
575 yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore);
576 }
577 // No `daemon start` exists; `devices` is the cheapest command that starts and awaits it.
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 may fail after startup; accept a published endpoint or preserve the CLI failure.
588 const started = yield* readDaemonFile().pipe(Effect.option);
589 if (started._tag === "Some") return toEndpoint(started.value);
590 if (runResult._tag === "Failure") {
591 return yield* new DeviceHost.DeviceHostError({
592 hostId,
593 step: "starting agent tools",
594 cause: runResult.failure,
595 });
596 }
597 const result = runResult.success;
598 if (result.timedOut) {
599 return yield* new DeviceHost.DeviceHostTimeoutError({
600 hostId,
601 timeoutMs: DAEMON_READY_TIMEOUT_MS,
602 });
603 }
604 if (result.code !== 0) {
605 const failure = decodeAgentDeviceFailure(result.stdout);
606 const details = Option.isSome(failure) ? failure.value.error.details : undefined;
607 const reason =
608 details?.reason === "daemon_registration_unproven"
609 ? details.inspection?.reason === "non-directory"
610 ? "daemon_lock_not_directory"
611 : "daemon_registration_unproven"
612 : details?.reason === "daemon_retirement_unconfirmed"
613 ? "daemon_retirement_unconfirmed"
614 : "command_failed";
615 return yield* new DeviceHost.AgentDeviceStartError({
616 hostId,
617 stateDir,
618 exitCode: result.code === null ? null : Number(result.code),
619 reason,
620 cause: result,
621 });
622 }
623 const deadline = (yield* Clock.currentTimeMillis) + DAEMON_READY_TIMEOUT_MS;
624 while (true) {
625 const file = yield* readDaemonFile().pipe(Effect.option);
626 if (file._tag === "Some") return toEndpoint(file.value);
627 if ((yield* Clock.currentTimeMillis) > deadline) {
628 return yield* new DeviceHost.DeviceHostTimeoutError({
629 hostId,
630 timeoutMs: DAEMON_READY_TIMEOUT_MS,
631 });
632 }
633 yield* Effect.sleep(Duration.millis(DAEMON_POLL_MS));
634 }
635 });
636
637 // The daemon may predate this process (an earlier server was killed, possibly on an
638 // older pin), so stop it with the CLI of its recorded version when that is installed.
639 const stopAgentDeviceDaemon = Effect.gen(function* () {
640 if (!(yield* fs.exists(daemonFilePath()))) return;
641 const recorded = yield* readDaemonFile().pipe(Effect.option);
642 if (
643 Option.isSome(recorded) &&
644 recorded.value.pid &&
645 !(yield* isProcessAlive(recorded.value.pid))
646 ) {
647 return yield* fs.remove(daemonFilePath(), { force: true });
648 }
649 const entryPath = yield* installedAgentDeviceEntry(config.baseDir, [
650 ...(Option.isSome(recorded) && recorded.value.version ? [recorded.value.version] : []),
651 AGENT_DEVICE_VERSION,
652 ]);
653 if (!entryPath) return;
654 const hostEnvironment = yield* currentHostEnvironment;
655 const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(
656 Effect.provideService(HostProcess.Platform, hostPlatform),
657 );
658 yield* runner.run({
659 command: nodePath,
660 args: [
661 entryPath,
662 "daemon",
663 "stop",
664 "--state-dir",
665 agentDeviceStateDir(path, config.stateDir),
666 ],
667 env: { ...hostEnvironment, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" },
668 timeout: Duration.seconds(10),
669 timeoutBehavior: "timedOutResult",
670 });
671 }).pipe(
672 Effect.provideService(FileSystem.FileSystem, fs),
673 Effect.provideService(Path.Path, path),
674 Effect.ignore,
675 );
676
677 const ensureHubReady = Effect.fn("LocalDeviceHost.ensureHubReady")(function* (
678 onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,
679 ): Effect.fn.Return<RunningHost, DeviceHost.DeviceHostError | NodeRuntimeUnavailableError> {
680 const running = yield* Ref.get(runningRef);
681 // A dead hub's record stays until a replacement is published: the agent
682 // daemon outlives the hub, and close needs its endpoint if the restart fails.
683 if (running) {
684 const alive = yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false));
685 if (alive) return running;
686 }
687 const nodePath = yield* resolveNodeExecutable(
688 "Local device support",
689 yield* currentHostEnvironment,
690 ).pipe(
691 Effect.provideService(FileSystem.FileSystem, fs),
692 Effect.provideService(Path.Path, path),
693 Effect.provideService(HostProcess.Platform, hostPlatform),
694 );
695 const installed = yield* isDeviceHubInstalled(config.baseDir).pipe(
696 Effect.provideService(FileSystem.FileSystem, fs),
697 Effect.provideService(Path.Path, path),
698 );
699 if (!installed) {
700 const inventory = yield* summary;
701 yield* onPhase("installing", deviceToolInstallMessage("device hub", inventory.tools?.hub));
702 }
703 const hubTool = yield* ensureDeviceHub(config.baseDir).pipe(
704 Effect.provideService(FileSystem.FileSystem, fs),
705 Effect.provideService(Path.Path, path),
706 Effect.provideService(ProcessRunner.ProcessRunner, runner),
707 Effect.mapError(
708 (cause) =>
709 new DeviceHost.DeviceHostError({
710 hostId,
711 step: "installing device support",
712 cause,
713 }),
714 ),
715 );
716 yield* onPhase("starting");
717 const hub = yield* spawnHub(hubTool, nodePath);
718 const next = yield* Effect.gen(function* () {
719 yield* pruneLocalDeviceTools(config.baseDir, nodePath, "hub").pipe(
720 Effect.provideService(Path.Path, path),
721 Effect.provideService(ProcessRunner.ProcessRunner, runner),
722 Effect.ignore,
723 );
724 const candidate = helperPaths(hubTool);
725 const [axExists, cliExists] = yield* Effect.all([
726 fs.exists(candidate.serveSimAxSettings).pipe(Effect.orElseSucceed(() => false)),
727 fs.exists(candidate.serveSimCli).pipe(Effect.orElseSucceed(() => false)),
728 ]);
729 const next: RunningHost = {
730 hub,
731 agentDevice: running?.agentDevice ?? null,
732 helpers: {
733 serveSimAxSettings: axExists ? candidate.serveSimAxSettings : null,
734 serveSimCli: cliExists ? candidate.serveSimCli : null,
735 },
736 };
737 yield* Ref.set(runningRef, next);
738 return next;
739 }).pipe(Effect.onError(() => stopHub(hub)));
740 yield* Ref.set(restartDelayRef, 0);
741 yield* Effect.forkDetach(superviseHub(hub, hubTool));
742 return next;
743 });
744
745 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
746 startLock.withPermits(1)(ensureHubReady(onPhase).pipe(Effect.map(toReady)));
747
748 const ensureAgentReady: DeviceHost.DeviceHost["Service"]["ensureAgentReady"] = (onPhase) =>
749 startLock.withPermits(1)(
750 Effect.gen(function* (): Generator<
751 Effect.Effect<
752 unknown,
753 | DeviceHost.DeviceHostError
754 | DeviceHost.DeviceHostTimeoutError
755 | DeviceHost.AgentDeviceStartError
756 | NodeRuntimeUnavailableError
757 >,
758 DeviceHost.DeviceHostAgentReady
759 > {
760 const running = yield* ensureHubReady(onPhase);
761 if (running.agentDevice) {
762 const agentDevice = yield* startAgentDeviceDaemon(
763 running.agentDevice,
764 running.hub.nodePath,
765 );
766 yield* Ref.set(runningRef, { ...running, agentDevice });
767 return { ...toReady(running), agentDevice };
768 }
769 const installed = yield* isAgentDeviceInstalled(config.baseDir).pipe(
770 Effect.provideService(FileSystem.FileSystem, fs),
771 Effect.provideService(Path.Path, path),
772 );
773 if (!installed) {
774 const inventory = yield* summary;
775 yield* onPhase(
776 "installing",
777 deviceToolInstallMessage("agent tools", inventory.tools?.agent),
778 );
779 }
780 const agentTool = yield* ensureAgentDevice(config.baseDir).pipe(
781 Effect.provideService(FileSystem.FileSystem, fs),
782 Effect.provideService(Path.Path, path),
783 Effect.provideService(ProcessRunner.ProcessRunner, runner),
784 Effect.mapError(
785 (cause) =>
786 new DeviceHost.DeviceHostError({
787 hostId,
788 step: "installing agent tools",
789 cause,
790 }),
791 ),
792 );
793 yield* onPhase("starting");
794 const agentDevice = yield* startAgentDeviceDaemon(agentTool, running.hub.nodePath);
795 yield* pruneLocalDeviceTools(config.baseDir, running.hub.nodePath, "agent").pipe(
796 Effect.provideService(Path.Path, path),
797 Effect.provideService(ProcessRunner.ProcessRunner, runner),
798 Effect.ignore,
799 );
800 const next = { ...running, agentDevice };
801 yield* Ref.set(runningRef, next);
802 return { ...toReady(next), agentDevice };
803 }),
804 );
805
806 const helperPaths = (hubTool: DeviceToolPaths) => {
807 const serveSimDist = path.join(
808 hubTool.installDir,
809 "node_modules",
810 "expo-device-hub",
811 "vendor",
812 "serve-sim",
813 "dist",
814 );
815 return {
816 serveSimAxSettings: path.join(serveSimDist, "simax", "serve-sim-ax-settings"),
817 serveSimCli: path.join(serveSimDist, "serve-sim.js"),
818 };
819 };
820
821 const run: DeviceHost.DeviceHostReady["run"] = (command, args, options) =>
822 currentSdk.pipe(
823 Effect.flatMap((sdk) =>
824 runner.run({
825 command:
826 command === "emulator" && sdk.root
827 ? path.join(
828 sdk.root,
829 "emulator",
830 hostPlatform === "win32" ? "emulator.exe" : "emulator",
831 )
832 : command,
833 args,
834 cwd: workingDirectory,
835 env: deviceHostEnvironment(environment, sdk.root, hostPlatform, path),
836 timeout: Duration.millis(options?.timeoutMs ?? 20_000),
837 timeoutBehavior: "timedOutResult",
838 ...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
839 ...(options?.maxOutputBytes === undefined
840 ? {}
841 : { maxOutputBytes: options.maxOutputBytes }),
842 }),
843 ),
844 Effect.map((result) => ({
845 stdout: result.stdout,
846 stderr: result.stderr,
847 code: result.timedOut ? 124 : Number(result.code ?? 127),
848 })),
849 Effect.catch((cause) => Effect.succeed({ stdout: "", stderr: String(cause), code: 127 })),
850 );
851
852 const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({
853 hub: { origin: running.hub.origin } satisfies DeviceHost.DeviceHubEndpoint,
854 devices: makeDeviceHubOperations({
855 hostId,
856 origin: running.hub.origin,
857 http: httpClient,
858 run,
859 platformAvailable: (platform) =>
860 platformAvailability(platform).pipe(Effect.map((availability) => availability.available)),
861 }),
862 nodePath: running.hub.nodePath,
863 run,
864 helpers: running.helpers,
865 ...(running.agentDevice
866 ? { releaseAgentSession: releaseAgentDeviceSession(httpClient, running.agentDevice) }
867 : {}),
868 });
869
870 const current: DeviceHost.DeviceHost["Service"]["current"] = Ref.get(runningRef).pipe(
871 Effect.map((running) => (running ? toReady(running) : null)),
872 );
873
874 const stopAgent: DeviceHost.DeviceHost["Service"]["stopAgent"] = startLock.withPermits(1)(
875 Effect.gen(function* () {
876 yield* stopAgentDeviceDaemon;
877 yield* Ref.update(runningRef, (running) =>
878 running ? { ...running, agentDevice: null } : running,
879 );
880 }),
881 );
882
883 const stop: DeviceHost.DeviceHost["Service"]["stop"] = startLock.withPermits(1)(
884 Effect.gen(function* () {
885 const running = yield* Ref.getAndSet(runningRef, null);
886 // Hub cleanup waits for its exit unbounded; it must not strand the detached agent daemon.
887 yield* Effect.all(
888 [
889 stopHub(running?.hub).pipe(
890 Effect.andThen(fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore)),
891 ),
892 stopAgentDeviceDaemon,
893 ],
894 { concurrency: "unbounded", discard: true },
895 );
896 }),
897 );
898
899 yield* Effect.addFinalizer(() => stop);
900
901 const host: DeviceHost.DeviceHost["Service"] = {
902 id: hostId,
903 label: LOCAL_DEVICE_HOST_LABEL,
904 summary,
905 platformAvailability,
906 ensureReady,
907 ensureAgentReady,
908 current,
909 stopAgent,
910 stop,
911 };
912 return host;
913});
914
915export const layer = Layer.effect(DeviceHost.DeviceHost, make());
916
917export const __testing = {
918 AgentDeviceDaemonFile,
919 androidSdk,
920 platformReason,
921 deviceHostEnvironment,
922 hubEnvironment,
923};