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