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

LocalDeviceHost.ts

830 lines30.4 KB

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