Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LocalDeviceHost.ts

1,018 lines38.4 KB

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