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 hostPlatform = yield* HostProcess.Platform;
241 const sdk = yield* androidSdk;
242 const hostEnvironment = deviceHostEnvironment(environment, sdk.root, hostPlatform, path);
243 const startLock = yield* Semaphore.make(1);
244 const runningRef = yield* Ref.make<RunningHost | null>(null);
245 const restartDelayRef = yield* Ref.make(0);
246 const hostId = LOCAL_DEVICE_HOST_ID;
247
248 const platformAvailability = Effect.fn("LocalDeviceHost.platformAvailability")(function* (
249 platform: DevicePlatform,
250 ): Effect.fn.Return<DevicePlatformAvailability> {
251 const reason = yield* platformReason(platform).pipe(
252 Effect.provideService(FileSystem.FileSystem, fs),
253 Effect.provideService(Path.Path, path),
254 );
255 return reason === null ? { platform, available: true } : { platform, available: false, reason };
256 });
257
258 const summary: Effect.Effect<DeviceHostSummary> = Effect.gen(function* () {
259 const [platforms, hubInstalled, agentDeviceInstalled] = yield* Effect.all([
260 Effect.all([platformAvailability("ios"), platformAvailability("android")]),
261 isDeviceHubInstalled(config.baseDir).pipe(
262 Effect.provideService(FileSystem.FileSystem, fs),
263 Effect.provideService(Path.Path, path),
264 ),
265 isAgentDeviceInstalled(config.baseDir).pipe(
266 Effect.provideService(FileSystem.FileSystem, fs),
267 Effect.provideService(Path.Path, path),
268 ),
269 ]);
270 const running = yield* Ref.get(runningRef);
271 const daemon = running?.agentDevice
272 ? yield* readDaemonFile().pipe(Effect.option)
273 : Option.none();
274 const hubAlive = running
275 ? yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false))
276 : false;
277 const agentAlive =
278 Option.isSome(daemon) && daemon.value.pid ? yield* isProcessAlive(daemon.value.pid) : false;
279 const tools = yield* deviceToolVersions(config.baseDir, {
280 ...(hubAlive ? { hub: DEVICE_HUB_VERSION } : {}),
281 ...(agentAlive && Option.isSome(daemon) && daemon.value.version
282 ? { agent: daemon.value.version }
283 : {}),
284 }).pipe(
285 Effect.provideService(FileSystem.FileSystem, fs),
286 Effect.provideService(Path.Path, path),
287 );
288 return {
289 tools,
290 id: hostId,
291 kind: "local",
292 label: "This machine",
293 platforms,
294 hubInstalled,
295 agentDeviceInstalled,
296 };
297 });
298
299 const stopHub = (hub: HubProcess | undefined) =>
300 hub ? Scope.close(hub.scope, Exit.void).pipe(Effect.ignore) : Effect.void;
301
302 const hubStatePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "hub.json");
303
304 const isProcessAlive = (pid: number) =>
305 Effect.sync(() => {
306 try {
307 process.kill(pid, 0);
308 return true;
309 } catch {
310 return false;
311 }
312 });
313
314 /**
315 * A hub left behind by a previous server is identified by pid plus the
316 * command line's entry path, so a recycled pid belonging to something else
317 * is never touched.
318 */
319 const reapStaleHub = Effect.gen(function* () {
320 const previous = yield* fs
321 .readFileString(hubStatePath())
322 .pipe(Effect.flatMap(decodeHubStateFile), Effect.option);
323 if (previous._tag === "None") return;
324 const alive = yield* isProcessAlive(previous.value.pid);
325 if (alive) {
326 const commandLine = yield* runner
327 .run({
328 command: "ps",
329 args: ["-o", "command=", "-p", String(previous.value.pid)],
330 timeout: Duration.seconds(5),
331 timeoutBehavior: "timedOutResult",
332 })
333 .pipe(
334 Effect.map((result) => result.stdout),
335 Effect.orElseSucceed(() => ""),
336 );
337 if (commandLine.includes(previous.value.entryPath)) {
338 yield* Effect.logWarning("Stopping a device hub left behind by a previous server", {
339 pid: previous.value.pid,
340 port: previous.value.port,
341 });
342 yield* Effect.sync(() => {
343 try {
344 process.kill(previous.value.pid, "SIGTERM");
345 } catch {}
346 });
347 }
348 }
349 yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore);
350 }).pipe(Effect.ignoreCause);
351
352 const recordHub = (hub: HubProcess, hubTool: DeviceToolPaths) =>
353 encodeHubStateFile({
354 pid: Number(hub.child.pid),
355 port: Number(new URL(hub.origin).port),
356 entryPath: hubTool.entryPath,
357 }).pipe(
358 Effect.flatMap((contents) =>
359 writeFileStringAtomically({ filePath: hubStatePath(), contents }),
360 ),
361 Effect.provideService(FileSystem.FileSystem, fs),
362 Effect.provideService(Path.Path, path),
363 Effect.ignore,
364 );
365
366 const spawnHub = Effect.fn("LocalDeviceHost.spawnHub")(function* (
367 hubTool: DeviceToolPaths,
368 nodePath: string,
369 ): Effect.fn.Return<HubProcess, DeviceHost.DeviceHostError> {
370 yield* reapStaleHub;
371 yield* fs
372 .makeDirectory(agentDeviceStateDir(path, config.stateDir), { recursive: true })
373 .pipe(Effect.ignore);
374 const port = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
375 Effect.mapError(
376 (cause) =>
377 new DeviceHost.DeviceHostError({
378 hostId,
379 step: "reserving a port for the device hub",
380 cause,
381 }),
382 ),
383 );
384 const origin = `http://127.0.0.1:${port}`;
385 const scope = yield* Scope.make("sequential");
386 // On failure or interrupt, from the spawn on: the hub is not recorded yet,
387 // so nothing else stops it.
388 return yield* Effect.gen(function* () {
389 const child = yield* spawner
390 .spawn(
391 ChildProcess.make(
392 nodePath,
393 [
394 hubTool.entryPath,
395 "--port",
396 String(port),
397 "--host",
398 "127.0.0.1",
399 "--hide-sidebar",
400 "--hide-boot-device",
401 ...hubPlatformArguments(hostPlatform),
402 ],
403 {
404 detached: false,
405 shell: false,
406 stdout: "pipe",
407 stderr: "pipe",
408 env: yield* hubEnvironment(hostEnvironment).pipe(
409 Effect.provideService(FileSystem.FileSystem, fs),
410 Effect.provideService(HostProcess.Platform, hostPlatform),
411 ),
412 },
413 ),
414 )
415 .pipe(
416 Effect.provideService(Scope.Scope, scope),
417 Effect.mapError(
418 (cause) =>
419 new DeviceHost.DeviceHostError({
420 hostId,
421 step: "starting the device hub",
422 cause,
423 }),
424 ),
425 );
426 const startedAtMillis = yield* Clock.currentTimeMillis;
427 const hub: HubProcess = { child, scope, origin, startedAtMillis, nodePath };
428 yield* Effect.forkIn(observeHubOutput(hub), scope);
429 yield* waitForHttpReady({
430 baseUrl: origin,
431 path: "/readyz",
432 timeoutMs: HUB_READY_TIMEOUT_MS,
433 makeError: (info) =>
434 new DeviceHost.DeviceHostError({
435 hostId,
436 step: "waiting for the device hub to answer",
437 cause: info.cause,
438 }),
439 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
440 yield* recordHub(hub, hubTool);
441 yield* Effect.logInfo("Device hub started", { pid: Number(child.pid), port });
442 return hub;
443 }).pipe(Effect.onError(() => Scope.close(scope, Exit.void).pipe(Effect.ignore)));
444 });
445
446 const observeHubOutput = (hub: HubProcess) =>
447 hub.child.all.pipe(
448 Stream.decodeText(),
449 Stream.splitLines,
450 Stream.map((line) => line.trim()),
451 Stream.filter((line) => line.length > 0),
452 Stream.runForEach((line) =>
453 Effect.logDebug("Device hub output", { pid: Number(hub.child.pid), output: line }),
454 ),
455 Effect.ignoreCause,
456 );
457
458 const superviseHub = (hub: HubProcess, hubTool: DeviceToolPaths): Effect.Effect<void> =>
459 Effect.gen(function* () {
460 yield* Effect.result(hub.child.exitCode);
461 const running = yield* Ref.get(runningRef);
462 if (running?.hub.child.pid !== hub.child.pid) return;
463 const uptime = (yield* Clock.currentTimeMillis) - hub.startedAtMillis;
464 const delay = yield* Ref.modify(restartDelayRef, (current) => {
465 if (uptime >= HUB_RESTART_STABLE_UPTIME_MS) return [0, 0];
466 const next = current === 0 ? 1_000 : Math.min(current * 2, HUB_RESTART_MAX_DELAY_MS);
467 return [current, next];
468 });
469 yield* Effect.logWarning("Device hub exited; restarting", {
470 pid: Number(hub.child.pid),
471 delayMs: delay,
472 });
473 yield* Effect.sleep(Duration.millis(delay));
474 yield* startLock.withPermits(1)(
475 Effect.gen(function* () {
476 const current = yield* Ref.get(runningRef);
477 if (current?.hub.child.pid !== hub.child.pid) return;
478 const replacement = yield* spawnHub(hubTool, hub.nodePath);
479 yield* Ref.set(runningRef, { ...current, hub: replacement });
480 yield* Effect.forkDetach(superviseHub(replacement, hubTool));
481 }),
482 );
483 }).pipe(
484 Effect.catchCause((cause) => Effect.logWarning("Device hub supervisor failed", { cause })),
485 );
486
487 const daemonFilePath = () => path.join(agentDeviceStateDir(path, config.stateDir), "daemon.json");
488
489 const readDaemonFile = Effect.fn("LocalDeviceHost.readDaemonFile")(function* () {
490 const raw = yield* fs.readFileString(daemonFilePath());
491 return yield* decodeDaemonFile(raw);
492 });
493
494 const startAgentDeviceDaemon = Effect.fn("LocalDeviceHost.startAgentDeviceDaemon")(function* (
495 agentTool: DeviceToolPaths,
496 nodePath: string,
497 ): Effect.fn.Return<
498 DeviceHost.AgentDeviceEndpoint,
499 | DeviceHost.DeviceHostError
500 | DeviceHost.DeviceHostTimeoutError
501 | DeviceHost.AgentDeviceStartError
502 > {
503 const stateDir = agentDeviceStateDir(path, config.stateDir);
504 yield* fs.makeDirectory(stateDir, { recursive: true }).pipe(Effect.ignore);
505 const existing = yield* readDaemonFile().pipe(Effect.option);
506 const daemonEnvironment: NodeJS.ProcessEnv = {
507 ...hostEnvironment,
508 AGENT_DEVICE_STATE_DIR: stateDir,
509 AGENT_DEVICE_DAEMON_SERVER_MODE: "http",
510 // The daemon idles out after five minutes by default; the server owns
511 // its lifetime here and stops it explicitly.
512 AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: "0",
513 AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
514 FORCE_COLOR: "0",
515 NO_COLOR: "1",
516 };
517 const toEndpoint = (
518 file: typeof AgentDeviceDaemonFile.Type,
519 ): DeviceHost.AgentDeviceEndpoint => ({
520 baseUrl: `http://127.0.0.1:${file.httpPort}`,
521 token: file.token,
522 entryPath: agentTool.entryPath,
523 });
524 if (existing._tag === "Some") {
525 const alive = yield* HttpClient.withScope(httpClient)
526 .get(`http://127.0.0.1:${existing.value.httpPort}/health`)
527 .pipe(
528 Effect.timeout(Duration.seconds(2)),
529 Effect.flatMap((response) =>
530 response.arrayBuffer.pipe(Effect.as(response.status === 200)),
531 ),
532 Effect.scoped,
533 Effect.orElseSucceed(() => false),
534 );
535 if (alive) return toEndpoint(existing.value);
536 yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore);
537 }
538 // There is no `daemon start`; the first command in a state dir spawns the
539 // daemon and blocks until it answers. `devices` is the cheapest one.
540 const runResult = yield* runner
541 .run({
542 command: nodePath,
543 args: [agentTool.entryPath, "devices", "--json"],
544 env: daemonEnvironment,
545 timeout: Duration.millis(DAEMON_READY_TIMEOUT_MS),
546 timeoutBehavior: "timedOutResult",
547 })
548 .pipe(Effect.result);
549 // Discovery can fail after the daemon starts. A published endpoint still
550 // lets agents connect; absent one, preserve the CLI failure instead of polling.
551 const started = yield* readDaemonFile().pipe(Effect.option);
552 if (started._tag === "Some") return toEndpoint(started.value);
553 if (runResult._tag === "Failure") {
554 return yield* new DeviceHost.DeviceHostError({
555 hostId,
556 step: "starting agent tools",
557 cause: runResult.failure,
558 });
559 }
560 const result = runResult.success;
561 if (result.timedOut) {
562 return yield* new DeviceHost.DeviceHostTimeoutError({
563 hostId,
564 timeoutMs: DAEMON_READY_TIMEOUT_MS,
565 });
566 }
567 if (result.code !== 0) {
568 const failure = decodeAgentDeviceFailure(result.stdout);
569 const details = Option.isSome(failure) ? failure.value.error.details : undefined;
570 const reason =
571 details?.reason === "daemon_registration_unproven"
572 ? details.inspection?.reason === "non-directory"
573 ? "daemon_lock_not_directory"
574 : "daemon_registration_unproven"
575 : details?.reason === "daemon_retirement_unconfirmed"
576 ? "daemon_retirement_unconfirmed"
577 : "command_failed";
578 return yield* new DeviceHost.AgentDeviceStartError({
579 hostId,
580 stateDir,
581 exitCode: result.code === null ? null : Number(result.code),
582 reason,
583 cause: result,
584 });
585 }
586 const deadline = (yield* Clock.currentTimeMillis) + DAEMON_READY_TIMEOUT_MS;
587 while (true) {
588 const file = yield* readDaemonFile().pipe(Effect.option);
589 if (file._tag === "Some") return toEndpoint(file.value);
590 if ((yield* Clock.currentTimeMillis) > deadline) {
591 return yield* new DeviceHost.DeviceHostTimeoutError({
592 hostId,
593 timeoutMs: DAEMON_READY_TIMEOUT_MS,
594 });
595 }
596 yield* Effect.sleep(Duration.millis(DAEMON_POLL_MS));
597 }
598 });
599
600 const stopAgentDeviceDaemon = (
601 agentTool: { readonly entryPath: string; readonly nodePath: string } | null,
602 ) =>
603 agentTool
604 ? runner
605 .run({
606 command: agentTool.nodePath,
607 args: [
608 agentTool.entryPath,
609 "daemon",
610 "stop",
611 "--state-dir",
612 agentDeviceStateDir(path, config.stateDir),
613 ],
614 env: { ...hostEnvironment, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" },
615 timeout: Duration.seconds(10),
616 timeoutBehavior: "timedOutResult",
617 })
618 .pipe(Effect.ignore)
619 : Effect.void;
620
621 let agentToolRef: { readonly entryPath: string; readonly nodePath: string } | null = null;
622
623 const ensureHubReady = Effect.fn("LocalDeviceHost.ensureHubReady")(function* (
624 onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,
625 ): Effect.fn.Return<RunningHost, DeviceHost.DeviceHostError | NodeRuntimeUnavailableError> {
626 const running = yield* Ref.get(runningRef);
627 if (running) {
628 const alive = yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false));
629 if (alive) return running;
630 yield* Ref.set(runningRef, null);
631 }
632 const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(
633 Effect.provideService(FileSystem.FileSystem, fs),
634 Effect.provideService(Path.Path, path),
635 Effect.provideService(HostProcess.Platform, hostPlatform),
636 );
637 const installed = yield* isDeviceHubInstalled(config.baseDir).pipe(
638 Effect.provideService(FileSystem.FileSystem, fs),
639 Effect.provideService(Path.Path, path),
640 );
641 if (!installed) {
642 const inventory = yield* summary;
643 yield* onPhase("installing", deviceToolInstallMessage("device hub", inventory.tools?.hub));
644 }
645 const hubTool = yield* ensureDeviceHub(config.baseDir).pipe(
646 Effect.provideService(FileSystem.FileSystem, fs),
647 Effect.provideService(Path.Path, path),
648 Effect.provideService(ProcessRunner.ProcessRunner, runner),
649 Effect.mapError(
650 (cause) =>
651 new DeviceHost.DeviceHostError({
652 hostId,
653 step: "installing device support",
654 cause,
655 }),
656 ),
657 );
658 yield* onPhase("starting");
659 const hub = yield* spawnHub(hubTool, nodePath);
660 const next = yield* Effect.gen(function* () {
661 yield* pruneLocalDeviceTools(config.baseDir, nodePath, "hub").pipe(
662 Effect.provideService(Path.Path, path),
663 Effect.provideService(ProcessRunner.ProcessRunner, runner),
664 Effect.ignore,
665 );
666 const candidate = helperPaths(hubTool);
667 const [axExists, cliExists] = yield* Effect.all([
668 fs.exists(candidate.serveSimAxSettings).pipe(Effect.orElseSucceed(() => false)),
669 fs.exists(candidate.serveSimCli).pipe(Effect.orElseSucceed(() => false)),
670 ]);
671 const next: RunningHost = {
672 hub,
673 agentDevice: null,
674 helpers: {
675 serveSimAxSettings: axExists ? candidate.serveSimAxSettings : null,
676 serveSimCli: cliExists ? candidate.serveSimCli : null,
677 },
678 };
679 yield* Ref.set(runningRef, next);
680 return next;
681 }).pipe(Effect.onError(() => stopHub(hub)));
682 yield* Ref.set(restartDelayRef, 0);
683 yield* Effect.forkDetach(superviseHub(hub, hubTool));
684 return next;
685 });
686
687 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
688 startLock.withPermits(1)(ensureHubReady(onPhase).pipe(Effect.map(toReady)));
689
690 const ensureAgentReady: DeviceHost.DeviceHost["Service"]["ensureAgentReady"] = (onPhase) =>
691 startLock.withPermits(1)(
692 Effect.gen(function* (): Generator<
693 Effect.Effect<
694 unknown,
695 | DeviceHost.DeviceHostError
696 | DeviceHost.DeviceHostTimeoutError
697 | DeviceHost.AgentDeviceStartError
698 | NodeRuntimeUnavailableError
699 >,
700 DeviceHost.DeviceHostAgentReady
701 > {
702 const running = yield* ensureHubReady(onPhase);
703 if (running.agentDevice) return { ...toReady(running), agentDevice: running.agentDevice };
704 const installed = yield* isAgentDeviceInstalled(config.baseDir).pipe(
705 Effect.provideService(FileSystem.FileSystem, fs),
706 Effect.provideService(Path.Path, path),
707 );
708 if (!installed) {
709 const inventory = yield* summary;
710 yield* onPhase(
711 "installing",
712 deviceToolInstallMessage("agent tools", inventory.tools?.agent),
713 );
714 }
715 const agentTool = yield* ensureAgentDevice(config.baseDir).pipe(
716 Effect.provideService(FileSystem.FileSystem, fs),
717 Effect.provideService(Path.Path, path),
718 Effect.provideService(ProcessRunner.ProcessRunner, runner),
719 Effect.mapError(
720 (cause) =>
721 new DeviceHost.DeviceHostError({
722 hostId,
723 step: "installing agent tools",
724 cause,
725 }),
726 ),
727 );
728 agentToolRef = { entryPath: agentTool.entryPath, nodePath: running.hub.nodePath };
729 yield* onPhase("starting");
730 const agentDevice = yield* startAgentDeviceDaemon(agentTool, running.hub.nodePath);
731 yield* pruneLocalDeviceTools(config.baseDir, running.hub.nodePath, "agent").pipe(
732 Effect.provideService(Path.Path, path),
733 Effect.provideService(ProcessRunner.ProcessRunner, runner),
734 Effect.ignore,
735 );
736 const next = { ...running, agentDevice };
737 yield* Ref.set(runningRef, next);
738 return { ...toReady(next), agentDevice };
739 }),
740 );
741
742 const helperPaths = (hubTool: DeviceToolPaths) => {
743 const serveSimDist = path.join(
744 hubTool.installDir,
745 "node_modules",
746 "expo-device-hub",
747 "vendor",
748 "serve-sim",
749 "dist",
750 );
751 return {
752 serveSimAxSettings: path.join(serveSimDist, "simax", "serve-sim-ax-settings"),
753 serveSimCli: path.join(serveSimDist, "serve-sim.js"),
754 };
755 };
756
757 const run: DeviceHost.DeviceHostReady["run"] = (command, args, options) =>
758 runner
759 .run({
760 command:
761 command === "emulator" && sdk.root
762 ? path.join(
763 sdk.root,
764 "emulator",
765 hostPlatform === "win32" ? "emulator.exe" : "emulator",
766 )
767 : command,
768 args,
769 env: hostEnvironment,
770 timeout: Duration.millis(options?.timeoutMs ?? 20_000),
771 timeoutBehavior: "timedOutResult",
772 ...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
773 })
774 .pipe(
775 Effect.map((result) => ({
776 stdout: result.stdout,
777 stderr: result.stderr,
778 code: Number(result.code),
779 })),
780 Effect.catch((cause) => Effect.succeed({ stdout: "", stderr: String(cause), code: 127 })),
781 );
782
783 const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({
784 hub: { origin: running.hub.origin } satisfies DeviceHost.DeviceHubEndpoint,
785 nodePath: running.hub.nodePath,
786 run,
787 helpers: running.helpers,
788 });
789
790 const current: DeviceHost.DeviceHost["Service"]["current"] = Ref.get(runningRef).pipe(
791 Effect.map((running) => (running ? toReady(running) : null)),
792 );
793
794 const stopAgent: DeviceHost.DeviceHost["Service"]["stopAgent"] = startLock.withPermits(1)(
795 Effect.gen(function* () {
796 yield* stopAgentDeviceDaemon(agentToolRef);
797 yield* Ref.update(runningRef, (running) =>
798 running ? { ...running, agentDevice: null } : running,
799 );
800 }),
801 );
802
803 const stop: DeviceHost.DeviceHost["Service"]["stop"] = startLock.withPermits(1)(
804 Effect.gen(function* () {
805 const running = yield* Ref.getAndSet(runningRef, null);
806 yield* stopHub(running?.hub);
807 yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore);
808 yield* stopAgentDeviceDaemon(agentToolRef);
809 }),
810 );
811
812 yield* Effect.addFinalizer(() => stop);
813
814 const host: DeviceHost.DeviceHost["Service"] = {
815 id: hostId,
816 summary,
817 platformAvailability,
818 ensureReady,
819 ensureAgentReady,
820 current,
821 stopAgent,
822 stop,
823 };
824 return host;
825});
826
827export const layer = Layer.effect(DeviceHost.DeviceHost, make());
828
829export const __testing = {
830 AgentDeviceDaemonFile,
831 androidSdk,
832 platformReason,
833 deviceHostEnvironment,
834 hubEnvironment,
835};