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

LocalDeviceHost.ts

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