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

LocalDeviceHost.ts

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