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