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

LocalDeviceHost.ts

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