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

LocalDeviceHost.ts

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