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 Deferred from "effect/Deferred";
21import * as Duration from "effect/Duration";
22import * as Effect from "effect/Effect";
23import * as Exit from "effect/Exit";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Path from "effect/Path";
28import * as Ref from "effect/Ref";
29import * as Schema from "effect/Schema";
30import * as Scope from "effect/Scope";
31import * as Semaphore from "effect/Semaphore";
32import * as Stream from "effect/Stream";
33import { HttpClient } from "effect/http";
34import * as ChildProcess from "effect/process/ChildProcess";
35import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
36
37import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
38import * as ServerConfig from "../config.ts";
39import * as ProcessRunner from "../processRunner.ts";
40import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
41import * as DeviceHost from "./DeviceHost.ts";
42import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
43import {
44 agentDeviceStateDir,
45 type DeviceToolPaths,
46 ensureAgentDevice,
47 ensureDeviceHub,
48 isAgentDeviceInstalled,
49 isDeviceHubInstalled,
50 deviceToolVersions,
51 AGENT_DEVICE_VERSION,
52 DEVICE_HUB_VERSION,
53 installedAgentDeviceEntry,
54} from "./DeviceToolchain.ts";
55
56const HUB_READY_TIMEOUT_MS = 30_000;
57const HUB_TOKEN_PATTERN = /\btoken=([\w.~-]+)/;
58const DAEMON_READY_TIMEOUT_MS = 30_000;
59const DAEMON_POLL_MS = 100;
60const HUB_RESTART_STABLE_UPTIME_MS = 60_000;
61const HUB_RESTART_MAX_DELAY_MS = 30_000;
62
63// Persist hub state so restarts without finalizers can clean up orphaned loopback listeners.
64const HubStateFile = Schema.Struct({
65 pid: Schema.Int,
66 port: Schema.Int,
67 entryPath: Schema.String,
68});
69const decodeHubStateFile = Schema.decodeUnknownEffect(Schema.fromJsonString(HubStateFile));
70const encodeHubStateFile = Schema.encodeUnknownEffect(Schema.fromJsonString(HubStateFile));
71
72const AgentDeviceDaemonFile = Schema.Struct({
73 httpPort: Schema.Int,
74 token: Schema.String,
75 pid: Schema.optional(Schema.Int),
76 version: Schema.optional(Schema.String),
77});
78const decodeDaemonFile = Schema.decodeUnknownEffect(Schema.fromJsonString(AgentDeviceDaemonFile));
79
80const decodeAgentDeviceFailure = Schema.decodeUnknownOption(
81 Schema.fromJsonString(
82 Schema.Struct({
83 error: Schema.Struct({
84 details: Schema.Struct({
85 reason: Schema.String,
86 inspection: Schema.optional(Schema.Struct({ reason: Schema.String })),
87 }),
88 }),
89 }),
90 ),
91);
92
93interface HubProcess {
94 readonly nodePath: string;
95 readonly child: ChildProcessSpawner.ChildProcessHandle;
96 readonly scope: Scope.Closeable;
97 readonly origin: string;
98 readonly token: string;
99 readonly startedAtMillis: number;
100 readonly emulatorExtraArgs: string | undefined;
101 readonly emulatorStamp: string | undefined;
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()].filter(
142 (root): root is string => !!root,
143 );
144 const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false));
145 const adbBinary = windows ? "adb.exe" : "adb";
146 const avdmanagerBinary = windows ? "avdmanager.bat" : "avdmanager";
147 const inspect = Effect.fnUntraced(function* (root: string) {
148 const adb = yield* exists(path.join(root, "platform-tools", adbBinary));
149 const emulator = yield* exists(
150 path.join(root, "emulator", windows ? "emulator.exe" : "emulator"),
151 );
152 const avdmanager = yield* exists(
153 path.join(root, "cmdline-tools", "latest", "bin", avdmanagerBinary),
154 );
155 const legacyAvdmanager =
156 !avdmanager && (yield* exists(path.join(root, "tools", "bin", avdmanagerBinary)));
157 return { root, adb, emulator, avdmanager, legacyAvdmanager };
158 });
159 const candidates = [
160 ...explicit,
161 path.join(home, "Library", "Android", "sdk"),
162 path.join(home, "Android", "Sdk"),
163 path.join(environment.LOCALAPPDATA ?? path.join(home, "AppData", "Local"), "Android", "Sdk"),
164 ];
165 for (const root of candidates) {
166 const sdk = yield* inspect(root);
167 if (sdk.adb || sdk.emulator) return sdk;
168 }
169 // PATH entries can be slow to stat (network shares), so only consult them after the standard locations miss.
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.adb || sdk.emulator) return sdk;
178 }
179 // No real SDK anywhere: report what the configured root is missing.
180 if (explicit[0]) return yield* inspect(explicit[0]);
181 return { root: null, adb: false, emulator: false, avdmanager: false, legacyAvdmanager: false };
182});
183
184const deviceHostEnvironment = (
185 environment: NodeJS.ProcessEnv,
186 sdkRoot: string | null,
187 hostPlatform: NodeJS.Platform,
188 path: Path.Path,
189): NodeJS.ProcessEnv => {
190 return sdkRoot
191 ? {
192 ...environment,
193 ANDROID_HOME: sdkRoot,
194 PATH: [
195 path.join(sdkRoot, "platform-tools"),
196 path.join(sdkRoot, "emulator"),
197 environment.PATH ?? environment.Path ?? "",
198 ].join(hostPlatform === "win32" ? ";" : ":"),
199 }
200 : environment;
201};
202
203const hubEnvironment = Effect.fn("LocalDeviceHost.hubEnvironment")(function* (
204 environment: NodeJS.ProcessEnv,
205) {
206 const env: NodeJS.ProcessEnv = { ...environment, FORCE_COLOR: "0", NO_COLOR: "1" };
207 const platform = yield* HostProcess.Platform;
208 const uid = yield* HostProcess.UserId;
209 if (env.ANDROID_HOME) {
210 const path = yield* Path.Path;
211 const runner = yield* ProcessRunner.ProcessRunner;
212 const emulator = path.join(
213 env.ANDROID_HOME,
214 "emulator",
215 platform === "win32" ? "emulator.exe" : "emulator",
216 );
217 const cameraArgs = yield* Effect.forEach(["front", "back"], (facing) =>
218 runner
219 .run({
220 command: emulator,
221 args: [`-help-camera-${facing}`],
222 env,
223 timeout: Duration.seconds(5),
224 })
225 .pipe(
226 Effect.map((result) => {
227 const help = `${result.stdout}\n${result.stderr}`;
228 // The hub wires imagefile cameras unconditionally; older SDK emulators reject that mode.
229 return result.code === 0 && /\bemulated\b/.test(help) && !/\bimagefile\b/.test(help)
230 ? `-camera-${facing} emulated`
231 : "";
232 }),
233 Effect.orElseSucceed(() => ""),
234 ),
235 );
236 const overrides = cameraArgs.filter(Boolean).join(" ");
237 if (overrides) {
238 env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS = [overrides, env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS]
239 .filter(Boolean)
240 .join(" ");
241 }
242 }
243 if (platform === "linux" && env.XDG_RUNTIME_DIR === undefined && uid !== undefined) {
244 // SSH sessions may omit the directory where the emulator publishes its gRPC token.
245 const runtimeDir = `/run/user/${uid}`;
246 const fs = yield* FileSystem.FileSystem;
247 const stat = yield* fs.stat(runtimeDir).pipe(Effect.option);
248 if (
249 stat._tag === "Some" &&
250 stat.value.type === "Directory" &&
251 Option.contains(stat.value.uid, uid)
252 ) {
253 env.XDG_RUNTIME_DIR = runtimeDir;
254 }
255 }
256 return env;
257});
258
259/** Only a Mac can list Apple simulators; elsewhere the hub's attempt surfaces as an error. */
260const hubPlatformArguments = (hostPlatform: NodeJS.Platform) =>
261 hostPlatform === "darwin" ? [] : ["--platform", "android"];
262
263export const make = Effect.fn("LocalDeviceHost.make")(function* () {
264 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
265 const config = yield* ServerConfig.ServerConfig;
266 const path = yield* Path.Path;
267 const fs = yield* FileSystem.FileSystem;
268 const net = yield* NetService.NetService;
269 const runner = yield* ProcessRunner.ProcessRunner;
270 const httpClient = yield* HttpClient.HttpClient;
271 const environment = yield* HostProcess.Environment;
272 const workingDirectory = yield* HostProcess.WorkingDirectory;
273 const hostPlatform = yield* HostProcess.Platform;
274 // Resolved per use: the desktop shell snapshot can select another SDK after the host exists.
275 const currentSdk = androidSdk.pipe(
276 Effect.provideService(FileSystem.FileSystem, fs),
277 Effect.provideService(Path.Path, path),
278 Effect.provideService(HostProcess.Environment, environment),
279 Effect.provideService(HostProcess.Platform, hostPlatform),
280 );
281 const currentHostEnvironment = currentSdk.pipe(
282 Effect.map((sdk) => deviceHostEnvironment(environment, sdk.root, hostPlatform, path)),
283 );
284 const startLock = yield* Semaphore.make(1);
285 const runningRef = yield* Ref.make<RunningHost | null>(null);
286 const restartDelayRef = yield* Ref.make(0);
287 const hostId = LOCAL_DEVICE_HOST_ID;
288
289 const platformAvailability = Effect.fn("LocalDeviceHost.platformAvailability")(function* (
290 platform: DevicePlatform,
291 ): Effect.fn.Return<DevicePlatformAvailability> {
292 const reason = yield* platformReason(platform).pipe(
293 Effect.provideService(FileSystem.FileSystem, fs),
294 Effect.provideService(Path.Path, path),
295 );
296 return reason === null ? { platform, available: true } : { platform, available: false, reason };
297 });
298
299 const summary: Effect.Effect<DeviceHostSummary> = Effect.gen(function* () {
300 const [platforms, hubInstalled, agentDeviceInstalled] = yield* Effect.all([
301 Effect.all([platformAvailability("ios"), platformAvailability("android")]),
302 isDeviceHubInstalled(config.baseDir).pipe(
303 Effect.provideService(FileSystem.FileSystem, fs),
304 Effect.provideService(Path.Path, path),
305 ),
306 isAgentDeviceInstalled(config.baseDir).pipe(
307 Effect.provideService(FileSystem.FileSystem, fs),
308 Effect.provideService(Path.Path, path),
309 ),
310 ]);
311 const running = yield* Ref.get(runningRef);
312 const daemon = running?.agentDevice
313 ? yield* readDaemonFile().pipe(Effect.option)
314 : Option.none();
315 const hubAlive = running
316 ? yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false))
317 : false;
318 const agentAlive =
319 Option.isSome(daemon) && daemon.value.pid ? yield* isProcessAlive(daemon.value.pid) : false;
320 const tools = yield* deviceToolVersions(config.baseDir, {
321 ...(hubAlive ? { hub: DEVICE_HUB_VERSION } : {}),
322 ...(agentAlive && Option.isSome(daemon) && daemon.value.version
323 ? { agent: daemon.value.version }
324 : {}),
325 }).pipe(
326 Effect.provideService(FileSystem.FileSystem, fs),
327 Effect.provideService(Path.Path, path),
328 );
329 return {
330 tools,
331 id: hostId,
332 kind: "local",
333 label: LOCAL_DEVICE_HOST_LABEL,
334 platforms,
335 hubInstalled,
336 agentDeviceInstalled,
337 };
338 });
339
340 const stopHub = (hub: HubProcess | undefined) =>
341 hub ? Scope.close(hub.scope, Exit.void).pipe(Effect.ignore) : Effect.void;
342
343 const hubStatePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "hub.json");
344
345 const isProcessAlive = (pid: number) =>
346 Effect.sync(() => {
347 try {
348 process.kill(pid, 0);
349 return true;
350 } catch {
351 return false;
352 }
353 });
354
355 // Check PID and entry path before reaping; the PID may have been recycled.
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 currentHubEnvironment = Effect.gen(function* () {
404 return yield* hubEnvironment(yield* currentHostEnvironment).pipe(
405 Effect.provideService(FileSystem.FileSystem, fs),
406 Effect.provideService(Path.Path, path),
407 Effect.provideService(ProcessRunner.ProcessRunner, runner),
408 Effect.provideService(HostProcess.Platform, hostPlatform),
409 );
410 });
411
412 // The camera probe spawns the emulator; re-run it for a live hub only after the binary changes.
413 const emulatorStamp = Effect.gen(function* () {
414 const sdk = yield* currentSdk;
415 if (!sdk.root) return undefined;
416 const binary = path.join(
417 sdk.root,
418 "emulator",
419 hostPlatform === "win32" ? "emulator.exe" : "emulator",
420 );
421 const info = yield* fs.stat(binary).pipe(Effect.option);
422 if (Option.isNone(info)) return undefined;
423 return `${Option.getOrUndefined(info.value.mtime)?.getTime()}:${info.value.size}`;
424 });
425
426 const spawnHub = Effect.fn("LocalDeviceHost.spawnHub")(function* (
427 hubTool: DeviceToolPaths,
428 nodePath: string,
429 env: NodeJS.ProcessEnv,
430 ): Effect.fn.Return<HubProcess, DeviceHost.DeviceHostError> {
431 yield* reapStaleHub;
432 const stamp = yield* emulatorStamp;
433 yield* fs
434 .makeDirectory(agentDeviceStateDir(path, config.stateDir), { recursive: true })
435 .pipe(Effect.ignore);
436 // The hub records its token in this folder, kept with the rest of the server's state.
437 const hubStateDir = path.join(config.stateDir, "device", "hub");
438 yield* fs.makeDirectory(hubStateDir, { recursive: true, mode: 0o700 }).pipe(Effect.ignore);
439 const port = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
440 Effect.mapError(
441 (cause) =>
442 new DeviceHost.DeviceHostError({
443 hostId,
444 step: "reserving a port for the device hub",
445 cause,
446 }),
447 ),
448 );
449 const origin = `http://127.0.0.1:${port}`;
450 const scope = yield* Scope.make("sequential");
451 // The hub is not recorded yet; stop it on failure or interruption from spawn onward.
452 return yield* Effect.gen(function* () {
453 const child = yield* spawner
454 .spawn(
455 ChildProcess.make(
456 nodePath,
457 [
458 hubTool.entryPath,
459 "--port",
460 String(port),
461 "--host",
462 "127.0.0.1",
463 // Only the server, which reads the token the hub prints, talks to the hub.
464 "--require-token",
465 "--hide-sidebar",
466 "--hide-boot-device",
467 ...hubPlatformArguments(hostPlatform),
468 ],
469 {
470 cwd: workingDirectory,
471 detached: false,
472 shell: false,
473 stdout: "pipe",
474 stderr: "pipe",
475 env: { ...env, EXPO_DEVICE_HUB_STATE_DIR: hubStateDir },
476 },
477 ),
478 )
479 .pipe(
480 Effect.provideService(Scope.Scope, scope),
481 Effect.mapError(
482 (cause) =>
483 new DeviceHost.DeviceHostError({
484 hostId,
485 step: "starting the device hub",
486 cause,
487 }),
488 ),
489 );
490 const startedAtMillis = yield* Clock.currentTimeMillis;
491 const announcedToken = yield* Deferred.make<string>();
492 yield* Effect.forkIn(observeHubOutput(child, announcedToken), scope);
493 yield* waitForHttpReady({
494 baseUrl: origin,
495 path: "/readyz",
496 timeoutMs: HUB_READY_TIMEOUT_MS,
497 makeError: (info) =>
498 new DeviceHost.DeviceHostError({
499 hostId,
500 step: "waiting for the device hub to answer",
501 cause: info.cause,
502 }),
503 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
504 const token = yield* Deferred.await(announcedToken).pipe(
505 Effect.timeoutOrElse({
506 duration: Duration.millis(HUB_READY_TIMEOUT_MS),
507 orElse: () =>
508 Effect.fail(
509 new DeviceHost.DeviceHostError({
510 hostId,
511 step: "reading the device hub's session token",
512 cause: new Error("The device hub did not print a session token."),
513 }),
514 ),
515 }),
516 );
517 const hub: HubProcess = {
518 child,
519 scope,
520 origin,
521 token,
522 startedAtMillis,
523 nodePath,
524 emulatorExtraArgs: env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS,
525 emulatorStamp: stamp,
526 };
527 yield* recordHub(hub, hubTool);
528 yield* Effect.logInfo("Device hub started", { pid: Number(child.pid), port });
529 return hub;
530 }).pipe(Effect.onError(() => Scope.close(scope, Exit.void).pipe(Effect.ignore)));
531 });
532
533 // The hub generates its session token and prints it in its startup link; keep it out of logs.
534 const observeHubOutput = (
535 child: ChildProcessSpawner.ChildProcessHandle,
536 announcedToken: Deferred.Deferred<string>,
537 ) =>
538 child.all.pipe(
539 Stream.decodeText(),
540 Stream.splitLines,
541 Stream.map((line) => line.trim()),
542 Stream.filter((line) => line.length > 0),
543 Stream.runForEach((line) => {
544 const token = HUB_TOKEN_PATTERN.exec(line)?.[1];
545 return (token === undefined ? Effect.void : Deferred.succeed(announcedToken, token)).pipe(
546 Effect.andThen(
547 Effect.logDebug("Device hub output", {
548 pid: Number(child.pid),
549 output: line.replace(HUB_TOKEN_PATTERN, "token=<redacted>"),
550 }),
551 ),
552 );
553 }),
554 Effect.ignoreCause,
555 );
556
557 // Waits for the hub's lifetime and re-forks on restart; a span would nest across restarts.
558 const superviseHub: (hub: HubProcess, hubTool: DeviceToolPaths) => Effect.Effect<void> =
559 Effect.fnUntraced(
560 function* (hub: HubProcess, hubTool: DeviceToolPaths) {
561 yield* Effect.result(hub.child.exitCode);
562 const running = yield* Ref.get(runningRef);
563 if (running?.hub.child.pid !== hub.child.pid) return;
564 const uptime = (yield* Clock.currentTimeMillis) - hub.startedAtMillis;
565 const delay = yield* Ref.modify(restartDelayRef, (current) => {
566 if (uptime >= HUB_RESTART_STABLE_UPTIME_MS) return [0, 0];
567 const next = current === 0 ? 1_000 : Math.min(current * 2, HUB_RESTART_MAX_DELAY_MS);
568 return [current, next];
569 });
570 yield* Effect.logWarning("Device hub exited; restarting", {
571 pid: Number(hub.child.pid),
572 delayMs: delay,
573 });
574 yield* Effect.sleep(Duration.millis(delay));
575 yield* startLock.withPermits(1)(
576 Effect.gen(function* () {
577 const current = yield* Ref.get(runningRef);
578 if (current?.hub.child.pid !== hub.child.pid) return;
579 const replacement = yield* spawnHub(
580 hubTool,
581 hub.nodePath,
582 yield* currentHubEnvironment,
583 );
584 yield* Ref.set(runningRef, { ...current, hub: replacement });
585 yield* Effect.forkDetach(superviseHub(replacement, hubTool));
586 }),
587 );
588 },
589 Effect.catchCause((cause) => Effect.logWarning("Device hub supervisor failed", { cause })),
590 );
591
592 const daemonFilePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "daemon.json");
593
594 const readDaemonFile = Effect.fn("LocalDeviceHost.readDaemonFile")(function* () {
595 const raw = yield* fs.readFileString(daemonFilePath());
596 return yield* decodeDaemonFile(raw);
597 });
598
599 const startAgentDeviceDaemon = Effect.fn("LocalDeviceHost.startAgentDeviceDaemon")(function* (
600 agentTool: Pick<DeviceToolPaths, "entryPath">,
601 nodePath: string,
602 ): Effect.fn.Return<
603 DeviceHost.AgentDeviceEndpoint,
604 | DeviceHost.DeviceHostError
605 | DeviceHost.DeviceHostTimeoutError
606 | DeviceHost.AgentDeviceStartError
607 > {
608 const stateDir = agentDeviceStateDir(path, config.stateDir);
609 yield* fs.makeDirectory(stateDir, { recursive: true }).pipe(Effect.ignore);
610 const existing = yield* readDaemonFile().pipe(Effect.option);
611 const daemonEnvironment: NodeJS.ProcessEnv = {
612 ...(yield* currentHostEnvironment),
613 AGENT_DEVICE_STATE_DIR: stateDir,
614 AGENT_DEVICE_DAEMON_SERVER_MODE: "http",
615 // Disable the five-minute idle timeout; the server owns shutdown.
616 AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: "0",
617 AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
618 FORCE_COLOR: "0",
619 NO_COLOR: "1",
620 };
621 const toEndpoint = (
622 file: typeof AgentDeviceDaemonFile.Type,
623 ): DeviceHost.AgentDeviceEndpoint => ({
624 baseUrl: `http://127.0.0.1:${file.httpPort}`,
625 token: file.token,
626 entryPath: agentTool.entryPath,
627 });
628 const daemonAnswersHealth = (httpPort: number) =>
629 HttpClient.withScope(httpClient)
630 .get(`http://127.0.0.1:${httpPort}/health`)
631 .pipe(
632 Effect.flatMap((response) =>
633 response.arrayBuffer.pipe(Effect.as(response.status === 200)),
634 ),
635 Effect.timeout(Duration.seconds(2)),
636 Effect.scoped,
637 Effect.orElseSucceed(() => false),
638 );
639 if (existing._tag === "Some") {
640 const alive = yield* daemonAnswersHealth(existing.value.httpPort);
641 const samePin =
642 existing.value.version === undefined || existing.value.version === AGENT_DEVICE_VERSION;
643 if (alive && samePin) return toEndpoint(existing.value);
644 // A live daemon from another pin may speak another RPC protocol. Keep its registration so
645 // the pinned CLI retires it, which that CLI does only while the daemon holds no work.
646 if (!alive) yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore);
647 }
648 // No `daemon start` exists; `devices` is the cheapest command that starts and awaits it.
649 const runResult = yield* runner
650 .run({
651 command: nodePath,
652 args: [agentTool.entryPath, "devices", "--json"],
653 env: daemonEnvironment,
654 timeout: Duration.millis(DAEMON_READY_TIMEOUT_MS),
655 timeoutBehavior: "timedOutResult",
656 })
657 .pipe(Effect.result);
658 // A failed run can stop the previous daemon and leave its file. Keep that registration
659 // only while it still answers; a successful run has published the endpoint it reached.
660 const started = yield* readDaemonFile().pipe(Effect.option);
661 if (started._tag === "Some") {
662 const runSucceeded =
663 runResult._tag === "Success" && !runResult.success.timedOut && runResult.success.code === 0;
664 if (runSucceeded || (yield* daemonAnswersHealth(started.value.httpPort))) {
665 return toEndpoint(started.value);
666 }
667 }
668 if (runResult._tag === "Failure") {
669 return yield* new DeviceHost.DeviceHostError({
670 hostId,
671 step: "starting agent tools",
672 cause: runResult.failure,
673 });
674 }
675 const result = runResult.success;
676 if (result.timedOut) {
677 return yield* new DeviceHost.DeviceHostTimeoutError({
678 hostId,
679 timeoutMs: DAEMON_READY_TIMEOUT_MS,
680 });
681 }
682 if (result.code !== 0) {
683 const failure = decodeAgentDeviceFailure(result.stdout);
684 const details = Option.isSome(failure) ? failure.value.error.details : undefined;
685 const reason =
686 details?.reason === "daemon_registration_unproven"
687 ? details.inspection?.reason === "non-directory"
688 ? "daemon_lock_not_directory"
689 : "daemon_registration_unproven"
690 : details?.reason === "daemon_retirement_unconfirmed"
691 ? "daemon_retirement_unconfirmed"
692 : "command_failed";
693 return yield* new DeviceHost.AgentDeviceStartError({
694 hostId,
695 stateDir,
696 exitCode: result.code === null ? null : Number(result.code),
697 reason,
698 cause: result,
699 });
700 }
701 const deadline = (yield* Clock.currentTimeMillis) + DAEMON_READY_TIMEOUT_MS;
702 while (true) {
703 const file = yield* readDaemonFile().pipe(Effect.option);
704 if (file._tag === "Some") return toEndpoint(file.value);
705 if ((yield* Clock.currentTimeMillis) > deadline) {
706 return yield* new DeviceHost.DeviceHostTimeoutError({
707 hostId,
708 timeoutMs: DAEMON_READY_TIMEOUT_MS,
709 });
710 }
711 yield* Effect.sleep(Duration.millis(DAEMON_POLL_MS));
712 }
713 });
714
715 // The daemon may predate this process (an earlier server was killed, possibly on an
716 // older pin), so stop it with the CLI of its recorded version when that is installed.
717 const stopAgentDeviceDaemon = Effect.gen(function* () {
718 if (!(yield* fs.exists(daemonFilePath()))) return;
719 const recorded = yield* readDaemonFile().pipe(Effect.option);
720 if (
721 Option.isSome(recorded) &&
722 recorded.value.pid &&
723 !(yield* isProcessAlive(recorded.value.pid))
724 ) {
725 return yield* fs.remove(daemonFilePath(), { force: true });
726 }
727 const entryPath = yield* installedAgentDeviceEntry(config.baseDir, [
728 ...(Option.isSome(recorded) && recorded.value.version ? [recorded.value.version] : []),
729 AGENT_DEVICE_VERSION,
730 ]);
731 if (!entryPath) return;
732 const hostEnvironment = yield* currentHostEnvironment;
733 const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(
734 Effect.provideService(HostProcess.Platform, hostPlatform),
735 );
736 yield* runner.run({
737 command: nodePath,
738 args: [
739 entryPath,
740 "daemon",
741 "stop",
742 "--state-dir",
743 agentDeviceStateDir(path, config.stateDir),
744 ],
745 env: { ...hostEnvironment, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" },
746 timeout: Duration.seconds(10),
747 timeoutBehavior: "timedOutResult",
748 });
749 }).pipe(
750 Effect.provideService(FileSystem.FileSystem, fs),
751 Effect.provideService(Path.Path, path),
752 Effect.ignore,
753 );
754
755 const ensureHubReady = Effect.fn("LocalDeviceHost.ensureHubReady")(function* (
756 onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,
757 ): Effect.fn.Return<RunningHost, DeviceHost.DeviceHostError | NodeRuntimeUnavailableError> {
758 const running = yield* Ref.get(runningRef);
759 let env: NodeJS.ProcessEnv | undefined;
760 // A dead hub's record stays until a replacement is published: the agent
761 // daemon outlives the hub, and close needs its endpoint if the restart fails.
762 if (running) {
763 const alive = yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false));
764 if (alive) {
765 const stamp = yield* emulatorStamp;
766 if (stamp === running.hub.emulatorStamp) return running;
767 // An updated emulator can change the camera overrides; replace the hub only if they did.
768 env = yield* currentHubEnvironment;
769 if (env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS === running.hub.emulatorExtraArgs) {
770 const next = { ...running, hub: { ...running.hub, emulatorStamp: stamp } };
771 yield* Ref.set(runningRef, next);
772 return next;
773 }
774 yield* stopHub(running.hub);
775 }
776 }
777 const nodePath = yield* resolveNodeExecutable(
778 "Local device support",
779 yield* currentHostEnvironment,
780 ).pipe(
781 Effect.provideService(FileSystem.FileSystem, fs),
782 Effect.provideService(Path.Path, path),
783 Effect.provideService(HostProcess.Platform, hostPlatform),
784 );
785 const installed = yield* isDeviceHubInstalled(config.baseDir).pipe(
786 Effect.provideService(FileSystem.FileSystem, fs),
787 Effect.provideService(Path.Path, path),
788 );
789 if (!installed) {
790 const inventory = yield* summary;
791 yield* onPhase("installing", deviceToolInstallMessage("device hub", inventory.tools?.hub));
792 }
793 const hubTool = yield* ensureDeviceHub(config.baseDir).pipe(
794 Effect.provideService(FileSystem.FileSystem, fs),
795 Effect.provideService(Path.Path, path),
796 Effect.provideService(ProcessRunner.ProcessRunner, runner),
797 Effect.mapError(
798 (cause) =>
799 new DeviceHost.DeviceHostError({
800 hostId,
801 step: "installing device support",
802 cause,
803 }),
804 ),
805 );
806 yield* onPhase("starting");
807 const hub = yield* spawnHub(hubTool, nodePath, env ?? (yield* currentHubEnvironment));
808 const next = yield* Effect.gen(function* () {
809 yield* pruneLocalDeviceTools(config.baseDir, nodePath, "hub").pipe(
810 Effect.provideService(Path.Path, path),
811 Effect.provideService(ProcessRunner.ProcessRunner, runner),
812 Effect.ignore,
813 );
814 const candidate = helperPaths(hubTool);
815 const [axExists, cliExists] = yield* Effect.all([
816 fs.exists(candidate.serveSimAxSettings).pipe(Effect.orElseSucceed(() => false)),
817 fs.exists(candidate.serveSimCli).pipe(Effect.orElseSucceed(() => false)),
818 ]);
819 const next: RunningHost = {
820 hub,
821 agentDevice: running?.agentDevice ?? null,
822 helpers: {
823 serveSimAxSettings: axExists ? candidate.serveSimAxSettings : null,
824 serveSimCli: cliExists ? candidate.serveSimCli : null,
825 },
826 };
827 yield* Ref.set(runningRef, next);
828 return next;
829 }).pipe(Effect.onError(() => stopHub(hub)));
830 yield* Ref.set(restartDelayRef, 0);
831 yield* Effect.forkDetach(superviseHub(hub, hubTool));
832 return next;
833 });
834
835 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
836 startLock.withPermits(1)(ensureHubReady(onPhase).pipe(Effect.map(toReady)));
837
838 const ensureAgentReady: DeviceHost.DeviceHost["Service"]["ensureAgentReady"] = (onPhase) =>
839 startLock.withPermits(1)(
840 Effect.gen(function* (): Generator<
841 Effect.Effect<
842 unknown,
843 | DeviceHost.DeviceHostError
844 | DeviceHost.DeviceHostTimeoutError
845 | DeviceHost.AgentDeviceStartError
846 | NodeRuntimeUnavailableError
847 >,
848 DeviceHost.DeviceHostAgentReady
849 > {
850 const running = yield* ensureHubReady(onPhase);
851 if (running.agentDevice) {
852 const agentDevice = yield* startAgentDeviceDaemon(
853 running.agentDevice,
854 running.hub.nodePath,
855 );
856 yield* Ref.set(runningRef, { ...running, agentDevice });
857 return { ...toReady(running), agentDevice };
858 }
859 const installed = yield* isAgentDeviceInstalled(config.baseDir).pipe(
860 Effect.provideService(FileSystem.FileSystem, fs),
861 Effect.provideService(Path.Path, path),
862 );
863 if (!installed) {
864 const inventory = yield* summary;
865 yield* onPhase(
866 "installing",
867 deviceToolInstallMessage("agent tools", inventory.tools?.agent),
868 );
869 }
870 const agentTool = yield* ensureAgentDevice(config.baseDir).pipe(
871 Effect.provideService(FileSystem.FileSystem, fs),
872 Effect.provideService(Path.Path, path),
873 Effect.provideService(ProcessRunner.ProcessRunner, runner),
874 Effect.mapError(
875 (cause) =>
876 new DeviceHost.DeviceHostError({
877 hostId,
878 step: "installing agent tools",
879 cause,
880 }),
881 ),
882 );
883 yield* onPhase("starting");
884 const agentDevice = yield* startAgentDeviceDaemon(agentTool, running.hub.nodePath);
885 yield* pruneLocalDeviceTools(config.baseDir, running.hub.nodePath, "agent").pipe(
886 Effect.provideService(Path.Path, path),
887 Effect.provideService(ProcessRunner.ProcessRunner, runner),
888 Effect.ignore,
889 );
890 const next = { ...running, agentDevice };
891 yield* Ref.set(runningRef, next);
892 return { ...toReady(next), agentDevice };
893 }),
894 );
895
896 const helperPaths = (hubTool: DeviceToolPaths) => {
897 const serveSimDist = path.join(
898 hubTool.installDir,
899 "node_modules",
900 "expo-device-hub",
901 "vendor",
902 "serve-sim",
903 "dist",
904 );
905 return {
906 serveSimAxSettings: path.join(serveSimDist, "simax", "serve-sim-ax-settings"),
907 serveSimCli: path.join(serveSimDist, "serve-sim.js"),
908 };
909 };
910
911 const run: DeviceHost.DeviceHostReady["run"] = (command, args, options) =>
912 currentSdk.pipe(
913 Effect.flatMap((sdk) =>
914 runner.run({
915 command:
916 command === "emulator" && sdk.root
917 ? path.join(
918 sdk.root,
919 "emulator",
920 hostPlatform === "win32" ? "emulator.exe" : "emulator",
921 )
922 : command,
923 args,
924 cwd: workingDirectory,
925 env: deviceHostEnvironment(environment, sdk.root, hostPlatform, path),
926 timeout: Duration.millis(options?.timeoutMs ?? 20_000),
927 timeoutBehavior: "timedOutResult",
928 ...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
929 ...(options?.maxOutputBytes === undefined
930 ? {}
931 : { maxOutputBytes: options.maxOutputBytes }),
932 }),
933 ),
934 Effect.map((result) => ({
935 stdout: result.stdout,
936 stderr: result.stderr,
937 code: result.timedOut ? 124 : Number(result.code ?? 127),
938 })),
939 Effect.catch((cause) => Effect.succeed({ stdout: "", stderr: String(cause), code: 127 })),
940 );
941
942 const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({
943 hub: {
944 origin: running.hub.origin,
945 token: running.hub.token,
946 } satisfies DeviceHost.DeviceHubEndpoint,
947 devices: makeDeviceHubOperations({
948 hostId,
949 origin: running.hub.origin,
950 token: running.hub.token,
951 http: httpClient,
952 run,
953 platformAvailable: (platform) =>
954 platformAvailability(platform).pipe(Effect.map((availability) => availability.available)),
955 }),
956 nodePath: running.hub.nodePath,
957 run,
958 helpers: running.helpers,
959 ...(running.agentDevice
960 ? { releaseAgentSession: releaseAgentDeviceSession(httpClient, running.agentDevice) }
961 : {}),
962 });
963
964 const current: DeviceHost.DeviceHost["Service"]["current"] = Ref.get(runningRef).pipe(
965 Effect.map((running) => (running ? toReady(running) : null)),
966 );
967
968 const stopAgent: DeviceHost.DeviceHost["Service"]["stopAgent"] = startLock.withPermits(1)(
969 Effect.gen(function* () {
970 yield* stopAgentDeviceDaemon;
971 yield* Ref.update(runningRef, (running) =>
972 running ? { ...running, agentDevice: null } : running,
973 );
974 }),
975 );
976
977 const stop: DeviceHost.DeviceHost["Service"]["stop"] = startLock.withPermits(1)(
978 Effect.gen(function* () {
979 const running = yield* Ref.getAndSet(runningRef, null);
980 // Hub cleanup waits for its exit unbounded; it must not strand the detached agent daemon.
981 yield* Effect.all(
982 [
983 stopHub(running?.hub).pipe(
984 Effect.andThen(fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore)),
985 ),
986 stopAgentDeviceDaemon,
987 ],
988 { concurrency: "unbounded", discard: true },
989 );
990 }),
991 );
992
993 yield* Effect.addFinalizer(() => stop);
994
995 const host: DeviceHost.DeviceHost["Service"] = {
996 id: hostId,
997 label: LOCAL_DEVICE_HOST_LABEL,
998 summary,
999 platformAvailability,
1000 ensureReady,
1001 ensureAgentReady,
1002 current,
1003 stopAgent,
1004 stop,
1005 };
1006 return host;
1007});
1008
1009export const layer = Layer.effect(DeviceHost.DeviceHost, make());
1010
1011export const __testing = {
1012 AgentDeviceDaemonFile,
1013 androidSdk,
1014 platformReason,
1015 deviceHostEnvironment,
1016 hubEnvironment,
1017};