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

LocalDeviceHost.ts

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