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

DeviceService.ts

1,268 lines47.7 KB

1import {
2 type DeviceActionInput,
3 type DeviceCloseInput,
4 type DeviceConfigureInput,
5 type DeviceDetail,
6 type DeviceDetailInput,
7 type DeviceError,
8 type DeviceHostId,
9 type DeviceId,
10 DeviceBootError,
11 DeviceHostUnavailableError,
12 DeviceNotFoundError,
13 DeviceOperationError,
14 type DeviceOpenInput,
15 type DevicePlatform,
16 DevicePlatformUnavailableError,
17 type DeviceServiceState,
18 type DeviceSession,
19 type DeviceShutdownInput,
20 type DeviceSummary,
21 type SshDeviceHostConfig,
22 type DeviceHostSummary,
23 LOCAL_DEVICE_HOST_ID,
24 type ThreadId,
25} from "@t3tools/contracts";
26import { SshCommandError } from "@t3tools/ssh/errors";
27import * as FileSystem from "effect/FileSystem";
28import { resolveNodeExecutable, nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";
29import * as Path from "effect/Path";
30import { ensureAgentDevice, ensureDeviceHub } from "./DeviceToolchain.ts";
31import * as ServerConfig from "../config.ts";
32import {
33 agentDeviceConfigPath,
34 agentDeviceSession,
35 writeAgentDeviceConfig,
36} from "./AgentDeviceTarget.ts";
37import * as Context from "effect/Context";
38import * as Crypto from "effect/Crypto";
39import * as DateTime from "effect/DateTime";
40import * as Duration from "effect/Duration";
41import * as Effect from "effect/Effect";
42import * as Layer from "effect/Layer";
43import * as PubSub from "effect/PubSub";
44import * as Schema from "effect/Schema";
45import * as Scope from "effect/Scope";
46import * as Semaphore from "effect/Semaphore";
47import * as Stream from "effect/Stream";
48import * as SynchronizedRef from "effect/SynchronizedRef";
49import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
50​
51import * as ServerSettings from "../serverSettings.ts";
52import { isLocalSshDeviceHost, remoteSshDeviceHosts } from "./localSshDeviceHost.ts";
53​
54import { readDeviceDetail, runDeviceAction } from "./DeviceActions.ts";
55import * as ProcessRunner from "../processRunner.ts";
56import * as DeviceHost from "./DeviceHost.ts";
57import * as SshDeviceHost from "./SshDeviceHost.ts";
58import * as Exit from "effect/Exit";
59import * as LocalDeviceHost from "./LocalDeviceHost.ts";
60​
61export const DEVICE_HUB_ROUTE_PREFIX = "/api/device-hub";
62​
63const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => {
64 const cause = error.cause;
65 if (
66 !(cause instanceof SshCommandError) ||
67 cause.exitCode === null ||
68 cause.exitCode < 1 ||
69 cause.exitCode > 254
70 )
71 return "Could not connect to this host over SSH.";
72​
73 // Only the known bootstrap diagnostic is safe to expose as Node guidance.
74 if (
75 cause.exitCode === 1 &&
76 cause.stderr
77 .split(/\r?\n/u)
78 .some((line) => line.trim() === "Node is missing from the non-interactive SSH PATH")
79 )
80 return "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.";
81​
82 return `Connected over SSH, but the device host check failed (exit code ${cause.exitCode}).`;
83};
84​
85const BOOT_TIMEOUT = Duration.minutes(3);
86const SCREENSHOT_TIMEOUT = Duration.seconds(20);
87​
88const HubDevice = Schema.Struct({
89 id: Schema.String,
90 name: Schema.String,
91 version: Schema.String,
92 platform: Schema.Literals(["ios", "android"]),
93 booted: Schema.Boolean,
94 physical: Schema.Boolean,
95});
96const HubDeviceList = Schema.Struct({
97 simulators: Schema.Array(HubDevice),
98 emulators: Schema.Array(HubDevice),
99 errors: Schema.optional(
100 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
101 ),
102});
103const HubActionResult = Schema.Struct({
104 ok: Schema.Boolean,
105 id: Schema.optional(Schema.String),
106 serial: Schema.optional(Schema.String),
107 error: Schema.optional(Schema.String),
108 errors: Schema.optional(
109 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
110 ),
111});
112​
113export interface DeviceScreenshot {
114 readonly device: DeviceSummary;
115 readonly png: Uint8Array;
117​
118export interface DeviceReadiness extends DeviceHost.DeviceHostReady {
119 readonly hostId: DeviceHostId;
121​
122export interface DeviceAgentReadiness extends DeviceReadiness {
123 readonly agentDevice: DeviceHost.AgentDeviceEndpoint;
125​
126export class DeviceService extends Context.Service<
127 DeviceService,
128 {
129 readonly agentCli: Effect.Effect<string, DeviceError>;
130 readonly testHost: (
131 config: SshDeviceHostConfig,
132 ) => Effect.Effect<DeviceHostSummary, DeviceError>;
133 readonly agentTarget: (input: {
134 threadId: ThreadId;
135 hostId: DeviceHostId;
136 deviceId: DeviceId;
137 }) => Effect.Effect<ReadonlyArray<string>, DeviceError>;
138 readonly state: Effect.Effect<DeviceServiceState>;
139 readonly subscribe: Effect.Effect<PubSub.Subscription<DeviceServiceState>, never, Scope.Scope>;
140 readonly configure: (
141 input: DeviceConfigureInput,
142 ) => Effect.Effect<DeviceServiceState, DeviceError>;
143 readonly list: Effect.Effect<DeviceServiceState, DeviceError>;
144 readonly updateTool: (tool: "hub" | "agent") => Effect.Effect<DeviceServiceState, DeviceError>;
145 readonly inspect: Effect.Effect<DeviceServiceState>;
146 readonly retryHost: (hostId: DeviceHostId) => Effect.Effect<DeviceServiceState, DeviceError>;
147 readonly open: (input: DeviceOpenInput) => Effect.Effect<DeviceSession, DeviceError>;
148 readonly close: (input: DeviceCloseInput) => Effect.Effect<void, DeviceError>;
149 readonly shutdown: (input: DeviceShutdownInput) => Effect.Effect<void, DeviceError>;
150 readonly detail: (input: DeviceDetailInput) => Effect.Effect<DeviceDetail, DeviceError>;
151 readonly action: (input: DeviceActionInput) => Effect.Effect<DeviceDetail, DeviceError>;
152 readonly screenshot: (input: {
153 readonly hostId?: DeviceHostId | undefined;
154 readonly deviceId: DeviceId;
155 }) => Effect.Effect<DeviceScreenshot, DeviceError>;
156 readonly readiness: (hostId?: DeviceHostId) => Effect.Effect<DeviceReadiness, DeviceError>;
157 readonly readinessIfSupported: (
158 hostId?: DeviceHostId,
159 ) => Effect.Effect<DeviceReadiness | null, DeviceError>;
160 readonly agentReadinessIfSupported: (
161 hostId?: DeviceHostId,
162 ) => Effect.Effect<DeviceAgentReadiness | null, DeviceError>;
163 readonly currentReadiness: (hostId?: DeviceHostId) => Effect.Effect<DeviceReadiness | null>;
164 readonly sessionsForThread: (threadId: ThreadId) => Effect.Effect<ReadonlyArray<DeviceSession>>;
165 }
166>()("t3/device/DeviceService") {}
167​
168interface ServiceState {
169 readonly state: DeviceServiceState;
171​
172const vendorPrefix = (platform: DevicePlatform) =>
173 platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
174​
175export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* (
176 hosts: ReadonlyMap<DeviceHostId, DeviceHost.DeviceHost["Service"]>,
177 testHost: DeviceService["Service"]["testHost"] = (host) =>
178 Effect.fail(
179 new DeviceHostUnavailableError({
180 hostId: host.id,
181 reason: "SSH probing is unavailable in this device service.",
182 }),
183 ),
184 configureAgent: (
185 hostId: DeviceHostId,
186 ready: DeviceHost.DeviceHostAgentReady,
187 ) => Effect.Effect<string, DeviceError> = (hostId) =>
188 Effect.fail(
189 new DeviceHostUnavailableError({
190 hostId,
191 reason: "Agent configuration is unavailable in this device service.",
192 }),
193 ),
194 installTool?: (tool: "hub" | "agent") => Effect.Effect<unknown, DeviceError>,
195) {
196 const settings = yield* ServerSettings.ServerSettingsService;
197 const crypto = yield* Crypto.Crypto;
198 const lifecycleLock = yield* Semaphore.make(1);
199 const readDeviceSettings = settings.getSettings.pipe(
200 Effect.map((value) => ({
201 enabled: value.enableDeviceSupport,
202 agentAccessEnabled: value.enableAgentDeviceAccess,
203 onboardingCompleted: value.deviceOnboardingCompleted,
204 })),
205 Effect.mapError(
206 (cause) =>
207 new DeviceOperationError({ operation: "settings", reason: "settings_failed", cause }),
208 ),
209 );
210 const initialSettings = yield* readDeviceSettings;
211​
212 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
213 const statePubSub = yield* PubSub.unbounded<DeviceServiceState>();
214 const initialHosts = yield* Effect.forEach(hosts.values(), (host) => host.summary);
215 let publishedHosts = new Map(hosts);
216 const stateRef = yield* SynchronizedRef.make<ServiceState>({
217 state: {
218 supportsHostRetry: true,
219 supportsToolUpdate: installTool !== undefined,
220 supportsToolInspection: true,
221 hosts: initialHosts,
222 hostStatus: initialSettings.enabled ? "idle" : "disabled",
223 hostStatuses: {},
224 devices: [],
225 sessions: [],
226 onboardingCompleted: initialSettings.onboardingCompleted,
227 agentAccessEnabled: initialSettings.agentAccessEnabled,
228 hubBasePath: DEVICE_HUB_ROUTE_PREFIX,
229 revision: 0,
230 },
231 });
232​
233 const publish = (update: (state: DeviceServiceState) => DeviceServiceState) =>
234 SynchronizedRef.updateAndGetEffect(stateRef, ({ state }) => {
235 const next = { ...update(state), revision: state.revision + 1 };
236 return PubSub.publish(statePubSub, next).pipe(Effect.as({ state: next }));
237 }).pipe(Effect.map(({ state }) => state));
238​
239 const resolveHost = Effect.fn("DeviceService.resolveHost")(function* (
240 hostId: DeviceHostId | undefined,
241 ) {
242 const id = hostId ?? LOCAL_DEVICE_HOST_ID;
243 const host = hosts.get(id);
244 if (!host) {
245 return yield* new DeviceHostUnavailableError({ hostId: id, reason: "Unknown host." });
246 }
247 return host;
248 });
249​
250 const setHostStatus = (
251 hostId: DeviceHostId,
252 status: DeviceServiceState["hostStatuses"][string],
253 ) =>
254 Effect.suspend(() =>
255 !hosts.has(hostId)
256 ? SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state))
257 : publish((state) => ({
258 ...state,
259 ...(hostId === LOCAL_DEVICE_HOST_ID
260 ? { hostStatus: status.status, hostStatusDetail: status.detail }
261 : {}),
262 hostStatuses: {
263 ...state.hostStatuses,
264 [hostId]: {
265 ...(state.hostStatuses[hostId]?.androidDiscoveryIncomplete
266 ? { androidDiscoveryIncomplete: true }
267 : {}),
268 ...status,
269 },
270 },
271 })),
272 );
273​
274 const readiness: DeviceService["Service"]["readiness"] = Effect.fn("DeviceService.readiness")(
275 function* (hostId) {
276 const host = yield* resolveHost(hostId);
277 if (!(yield* readDeviceSettings).enabled) {
278 return yield* new DeviceHostUnavailableError({
279 hostId: host.id,
280 reason:
281 "Device support is off. Enable it in the Device panel before installing or starting device tools.",
282 });
283 }
284 const ready = yield* host
285 .ensureReady((status, detail) =>
286 setHostStatus(host.id, { status, detail }).pipe(Effect.asVoid),
287 )
288 .pipe(
289 Effect.tapError((error) =>
290 setHostStatus(host.id, {
291 status: "failed",
292 detail:
293 error._tag === "DeviceHostError" && error.step === "probe"
294 ? sshProbeFailureMessage(error)
295 : error.message,
296 }),
297 ),
298 Effect.mapError(
299 (error) =>
300 new DeviceHostUnavailableError({
301 hostId: host.id,
302 reason:
303 error._tag === "NodeRuntimeUnavailableError"
304 ? nodeRuntimeUnavailableMessage("Local device support")
305 : error.step === "probe"
306 ? sshProbeFailureMessage(error)
307 : `Device support failed during ${error.step}.`,
308 cause: error,
309 }),
310 ),
311 );
312 if (hosts.get(host.id) !== host)
313 return yield* new DeviceHostUnavailableError({
314 hostId: host.id,
315 reason: "Host configuration changed. Retry the operation.",
316 });
317 const { state } = yield* SynchronizedRef.get(stateRef);
318 if (state.hostStatuses[host.id]?.status !== "ready") {
319 yield* setHostStatus(host.id, { status: "ready" });
320 }
321 return { hostId: host.id, ...ready };
322 },
323 lifecycleLock.withPermit,
324 );
325​
326 const readinessIfSupported: DeviceService["Service"]["readinessIfSupported"] = Effect.fn(
327 "DeviceService.readinessIfSupported",
328 )(function* (hostId) {
329 if (!(yield* readDeviceSettings).enabled) return null;
330 const host = yield* resolveHost(hostId);
331 const summary = yield* host.summary;
332 if (summary.kind === "local" && !summary.platforms.some((platform) => platform.available))
333 return null;
334 return yield* readiness(host.id);
335 });
336​
337 const agentReadinessIfSupported: DeviceService["Service"]["agentReadinessIfSupported"] =
338 Effect.fn("DeviceService.agentReadinessIfSupported")(function* (hostId) {
339 const deviceSettings = yield* readDeviceSettings;
340 if (!deviceSettings.enabled || !deviceSettings.agentAccessEnabled) return null;
341 const host = yield* resolveHost(hostId);
342 const summary = yield* host.summary;
343 if (summary.kind === "local" && !summary.platforms.some((platform) => platform.available))
344 return null;
345 const ready = yield* host
346 .ensureAgentReady((phase, detail) =>
347 setHostStatus(host.id, { status: phase, detail }).pipe(Effect.asVoid),
348 )
349 .pipe(
350 Effect.tapError((error) =>
351 setHostStatus(host.id, {
352 status: "failed",
353 detail:
354 error._tag === "DeviceHostError" && error.step === "probe"
355 ? sshProbeFailureMessage(error)
356 : error.message,
357 }),
358 ),
359 Effect.mapError(
360 (error) =>
361 new DeviceHostUnavailableError({
362 hostId: host.id,
363 reason:
364 error._tag === "NodeRuntimeUnavailableError"
365 ? nodeRuntimeUnavailableMessage("Local device support")
366 : error._tag === "DeviceHostTimeoutError"
367 ? `Agent tools did not start within ${error.timeoutMs} ms.`
368 : error._tag === "AgentDeviceStartError"
369 ? error.message
370 : error.step === "probe"
371 ? sshProbeFailureMessage(error)
372 : `Device support failed during ${error.step}.`,
373 cause: error,
374 }),
375 ),
376 );
377 const hostSummaries = yield* Effect.forEach(hosts.values(), (candidate) => candidate.summary);
378 yield* publish((state) => ({ ...state, hosts: hostSummaries }));
379 yield* setHostStatus(host.id, { status: "ready" });
380 return { hostId: host.id, ...ready };
381 }, lifecycleLock.withPermit);
382​
383 const currentReadiness: DeviceService["Service"]["currentReadiness"] = (hostId) =>
384 resolveHost(hostId).pipe(
385 Effect.flatMap((host) =>
386 host.current.pipe(Effect.map((ready) => (ready ? { hostId: host.id, ...ready } : null))),
387 ),
388 Effect.orElseSucceed(() => null),
389 );
390​
391 const hubJson = <A, I>(
392 request: HttpClientRequest.HttpClientRequest,
393 schema: Schema.Codec<A, I>,
394 operation: string,
395 timeout: Duration.Input = Duration.seconds(15),
396 ) =>
397 httpClient.execute(request).pipe(
398 Effect.flatMap(HttpClientResponse.filterStatusOk),
399 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
400 Effect.scoped,
401 Effect.timeout(timeout),
402 Effect.mapError(
403 (cause) =>
404 new DeviceOperationError({
405 operation,
406 reason: "request_failed",
407 cause,
408 }),
409 ),
410 );
411​
412 const fetchDevices = Effect.fn("DeviceService.fetchDevices")(function* (ready: DeviceReadiness) {
413 const list = yield* hubJson(
414 HttpClientRequest.get(`${ready.hub.origin}/api/devices`),
415 HubDeviceList,
416 "list",
417 );
418 const toSummary = (device: typeof HubDevice.Type): DeviceSummary => ({
419 hostId: ready.hostId,
420 id: device.id,
421 platform: device.platform,
422 name: device.name,
423 version: device.version,
424 booted: device.booted,
425 physical: device.physical,
426 });
427 const devices = [...list.simulators, ...list.emulators].map(toSummary);
428 const warnings = list.errors?.filter(
429 (error) =>
430 // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
431 !(
432 error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
433 /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
434 /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
435 ),
436 );
437 const details = warnings?.map((error) => error.message) ?? [];
438 let androidDiscoveryIncomplete = false;
439 const host = yield* resolveHost(ready.hostId);
440 if ((yield* host.platformAvailability("android")).available) {
441 const avds = yield* ready.run("emulator", ["-list-avds"]);
442 if (avds.code !== 0) {
443 androidDiscoveryIncomplete = true;
444 details.push(
445 `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
446 );
447 }
448 for (const name of (avds.code === 0 ? avds.stdout : "")
449 .split(/\r?\n/)
450 .map((line) => line.trim())
451 .filter(Boolean)) {
452 if (!devices.some((device) => device.platform === "android" && device.name === name)) {
453 devices.push({
454 hostId: ready.hostId,
455 id: name,
456 name,
457 platform: "android",
458 version: "Android",
459 booted: false,
460 physical: false,
461 });
462 }
463 }
464 }
465 return { devices, detail: details.join("\n") || undefined, androidDiscoveryIncomplete };
466 });
467​
468 const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {
469 const host = hosts.get(ready.hostId);
470 const { devices, detail, androidDiscoveryIncomplete } = yield* fetchDevices(ready);
471 const hostSummaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
472 return yield* lifecycleLock.withPermit(
473 Effect.gen(function* () {
474 if (!(yield* readDeviceSettings).enabled || !host || hosts.get(ready.hostId) !== host)
475 return (yield* SynchronizedRef.get(stateRef)).state;
476 return yield* publish((state) => ({
477 ...state,
478 hosts: hostSummaries,
479 ...(ready.hostId === LOCAL_DEVICE_HOST_ID ? { hostStatusDetail: detail } : {}),
480 devices: [
481 ...state.devices.filter((device) => device.hostId !== ready.hostId),
482 ...devices,
483 ],
484 hostStatuses: {
485 ...state.hostStatuses,
486 [ready.hostId]: {
487 status: "ready",
488 ...(detail ? { detail } : {}),
489 ...(androidDiscoveryIncomplete ? { androidDiscoveryIncomplete } : {}),
490 },
491 },
492 }));
493 }),
494 );
495 });
496​
497 const list: DeviceService["Service"]["list"] = Effect.gen(function* () {
498 if (!(yield* readDeviceSettings).enabled) return (yield* SynchronizedRef.get(stateRef)).state;
499 yield* Effect.forEach(
500 hosts.values(),
501 (host) =>
502 Effect.gen(function* () {
503 const ready = yield* readinessIfSupported(host.id);
504 if (ready) yield* refresh(ready);
505 }).pipe(
506 Effect.catch((error) =>
507 setHostStatus(host.id, {
508 status: "failed",
509 detail: error._tag === "DeviceHostUnavailableError" ? error.reason : error.message,
510 }),
511 ),
512 ),
513 { concurrency: 4 },
514 );
515 return (yield* SynchronizedRef.get(stateRef)).state;
516 }).pipe(Effect.withSpan("DeviceService.list"));
517​
518 const inspect = Effect.gen(function* () {
519 yield* Effect.forEach(
520 hosts.values(),
521 (host) =>
522 Effect.gen(function* () {
523 const result = yield* (host.inspect ?? host.summary).pipe(Effect.result);
524 if (hosts.get(host.id) !== host) return;
525 if (result._tag === "Failure") {
526 yield* publish((state) => ({
527 ...state,
528 hosts: state.hosts.map((value) =>
529 value.id === host.id
530 ? {
531 ...value,
532 toolInspectionError:
533 "Cannot check versions. Reconnect the host and check again. Installed tools have not been changed.",
534 }
535 : value,
536 ),
537 }));
538 return;
539 }
540 yield* publish((state) => ({
541 ...state,
542 hosts: state.hosts.map((value) => (value.id === host.id ? result.success : value)),
543 }));
544 }),
545 { concurrency: 4 },
546 );
547 return (yield* SynchronizedRef.get(stateRef)).state;
548 });
549​
550 const retryHost: DeviceService["Service"]["retryHost"] = Effect.fn("DeviceService.retryHost")(
551 function* (hostId) {
552 yield* resolveHost(hostId);
553 if (!(yield* readDeviceSettings).enabled) return (yield* SynchronizedRef.get(stateRef)).state;
554 yield* Effect.gen(function* () {
555 const ready =
556 (yield* agentReadinessIfSupported(hostId)) ?? (yield* readinessIfSupported(hostId));
557 if (ready) yield* refresh(ready);
558 }).pipe(
559 Effect.catch((error) =>
560 setHostStatus(hostId, {
561 status: "failed",
562 detail: error._tag === "DeviceHostUnavailableError" ? error.reason : error.message,
563 }),
564 ),
565 );
566 return (yield* SynchronizedRef.get(stateRef)).state;
567 },
568 );
569​
570 const configure: DeviceService["Service"]["configure"] = Effect.fn("DeviceService.configure")(
571 function* (input) {
572 const currentSettings = yield* readDeviceSettings;
573 const nextEnabled = input.enabled ?? currentSettings.enabled;
574 const nextAgentAccess = input.agentAccessEnabled ?? currentSettings.agentAccessEnabled;
575 yield* lifecycleLock.withPermit(
576 Effect.gen(function* () {
577 yield* settings
578 .updateSettings({
579 ...(input.enabled === undefined ? {} : { enableDeviceSupport: input.enabled }),
580 ...(input.agentAccessEnabled === undefined
581 ? {}
582 : { enableAgentDeviceAccess: input.agentAccessEnabled }),
583 ...(input.onboardingCompleted === undefined
584 ? {}
585 : { deviceOnboardingCompleted: input.onboardingCompleted }),
586 })
587 .pipe(
588 Effect.mapError(
589 (cause) =>
590 new DeviceOperationError({
591 operation: "configure",
592 reason: "settings_failed",
593 cause,
594 }),
595 ),
596 );
597 if (!nextEnabled) {
598 yield* Effect.forEach(hosts.values(), (host) => host.stop, { discard: true });
599 } else if (input.agentAccessEnabled === false) {
600 yield* Effect.forEach(hosts.values(), (host) => host.stopAgent, { discard: true });
601 }
602 yield* publish((state) => ({
603 ...state,
604 hostStatus: nextEnabled ? "idle" : "disabled",
605 hostStatusDetail: undefined,
606 hostStatuses: {},
607 devices: nextEnabled ? state.devices : [],
608 sessions: nextEnabled ? state.sessions : [],
609 bootingDevices: nextEnabled ? state.bootingDevices : [],
610 agentAccessEnabled: nextAgentAccess,
611 onboardingCompleted: input.onboardingCompleted ?? state.onboardingCompleted,
612 }));
613 }),
614 );
615 if (nextEnabled && nextAgentAccess && input.agentAccessEnabled === true) {
616 yield* agentReadinessIfSupported();
617 }
618 return yield* list;
619 },
620 );
621​
622 const findDevice = (
623 state: DeviceServiceState,
624 hostId: DeviceHostId,
625 deviceId: DeviceId,
626 ): DeviceSummary | undefined =>
627 state.devices.find((device) => device.hostId === hostId && device.id === deviceId);
628​
629 const ensurePlatform = Effect.fn("DeviceService.ensurePlatform")(function* (
630 host: DeviceHost.DeviceHost["Service"],
631 platform: DevicePlatform,
632 ) {
633 const availability = yield* host.platformAvailability(platform);
634 if (!availability.available) {
635 return yield* new DevicePlatformUnavailableError({
636 hostId: host.id,
637 platform,
638 reason: availability.reason ?? "Platform toolchain missing.",
639 });
640 }
641 });
642​
643 /**
644 * Android AVDs change id when they boot (AVD name to emulator serial), so the
645 * returned id is authoritative.
646 */
647 const boot = Effect.fn("DeviceService.boot")(function* (
648 ready: DeviceReadiness,
649 device: DeviceSummary,
650 ) {
651 const result = yield* HttpClientRequest.post(`${ready.hub.origin}/api/devices/boot`).pipe(
652 HttpClientRequest.bodyJson({ platform: device.platform, id: device.id, name: device.name }),
653 Effect.mapError(
654 (cause) =>
655 new DeviceOperationError({ operation: "boot", reason: "invalid_payload", cause }),
656 ),
657 Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)),
658 );
659 if (!result.ok) {
660 // Keep the hub's launch command and nested failure available to agents for recovery.
661 const diagnostics = [
662 result.error,
663 ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
664 ]
665 .filter((text) => text?.trim())
666 .join("\n\n");
667 return yield* new DeviceBootError({
668 hostId: ready.hostId,
669 deviceId: device.id,
670 reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
671 diagnostics,
672 )
673 ? "disk_space"
674 : /timed? out|timeout/i.test(diagnostics)
675 ? "timeout"
676 : "launch_failed",
677 ...(diagnostics
678 ? {
679 diagnostics:
680 diagnostics.length > 2_000 ? `${diagnostics.slice(0, 1_999)}…` : diagnostics,
681 }
682 : {}),
683 cause: result,
684 });
685 }
686 if (device.platform === "ios") {
687 // Booting alone does not attach a serve-sim helper; the grid start
688 // does both and is idempotent for a booted simulator.
689 yield* HttpClientRequest.post(
690 `${ready.hub.origin}${vendorPrefix("ios")}/grid/api/start`,
691 ).pipe(
692 HttpClientRequest.bodyJson({ udid: device.id }),
693 Effect.mapError(
694 (cause) =>
695 new DeviceOperationError({ operation: "boot", reason: "invalid_payload", cause }),
696 ),
697 Effect.flatMap((request) =>
698 hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT),
699 ),
700 );
701 }
702 return result.serial ?? result.id ?? device.id;
703 });
704​
705 const open: DeviceService["Service"]["open"] = Effect.fn("DeviceService.open")(function* (input) {
706 const host = yield* resolveHost(input.hostId);
707 yield* ensurePlatform(host, input.platform);
708 const ready = yield* readiness(host.id);
709 let state = yield* refresh(ready);
710 let device = findDevice(state, host.id, input.deviceId);
711 if (!device) {
712 return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: input.deviceId });
713 }
714 if (device.platform === "android" && !device.physical) {
715 // Resolve the override on the device host the way its hub does.
716 const encoders = yield* ready.run(ready.nodePath, [
717 "-e",
718 `const { spawnSync } = require("node:child_process");
719const result = spawnSync(process.env.SERVE_EMU_FFMPEG?.trim() || "ffmpeg", ["-hide_banner", "-encoders"], {
720 stdio: "inherit", timeout: 10000, killSignal: "SIGKILL",
721});
722process.exitCode = result.error ? 1 : (result.status ?? 1);`,
723 ]);
724 if (encoders.code !== 0) {
725 return yield* new DevicePlatformUnavailableError({
726 hostId: host.id,
727 platform: "android",
728 reason:
729 "Android emulator video needs working ffmpeg with the libx264 encoder. Install it on the device host's PATH or set SERVE_EMU_FFMPEG there, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
730 });
731 }
732 if (!/^\s*V\S*[ \t]+libx264(?:[ \t]|$)/m.test(`${encoders.stdout}\n${encoders.stderr}`)) {
733 return yield* new DevicePlatformUnavailableError({
734 hostId: host.id,
735 platform: "android",
736 reason:
737 "Android emulator video needs the libx264 encoder. Install an ffmpeg build that includes libx264 on the device host, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
738 });
739 }
740 }
741 if (!device.booted && input.boot !== false) {
742 const booting = { ...device, threadId: input.threadId };
743 yield* publish((current) => ({
744 ...current,
745 bootingDevices: [
746 ...(current.bootingDevices ?? []).filter(
747 (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
748 ),
749 booting,
750 ],
751 }));
752 const bootedId = yield* boot(ready, device).pipe(
753 Effect.ensuring(
754 publish((current) => ({
755 ...current,
756 bootingDevices: (current.bootingDevices ?? []).filter(
757 (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
758 ),
759 })),
760 ),
761 );
762 state = yield* refresh(ready);
763 device = findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id);
764 if (!device) {
765 return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });
766 }
767 } else if (device.platform === "ios" && device.booted) {
768 yield* HttpClientRequest.post(
769 `${ready.hub.origin}${vendorPrefix("ios")}/grid/api/start`,
770 ).pipe(
771 HttpClientRequest.bodyJson({ udid: device.id }),
772 Effect.mapError(
773 (cause) =>
774 new DeviceOperationError({ operation: "open", reason: "invalid_payload", cause }),
775 ),
776 Effect.flatMap((request) =>
777 hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT),
778 ),
779 );
780 }
781 if (hosts.get(host.id) !== host)
782 return yield* new DeviceHostUnavailableError({
783 hostId: host.id,
784 reason: "Host configuration changed. Retry the operation.",
785 });
786 const openedAt = DateTime.formatIso(yield* DateTime.now);
787 const session: DeviceSession = {
788 threadId: input.threadId,
789 hostId: host.id,
790 deviceId: device.id,
791 platform: device.platform,
792 openedAt,
793 };
794 yield* lifecycleLock.withPermit(
795 Effect.gen(function* () {
796 if (!(yield* readDeviceSettings).enabled)
797 return yield* new DeviceHostUnavailableError({
798 hostId: host.id,
799 reason: "Device support was turned off while the device was opening.",
800 });
801 yield* publish((current) => ({
802 ...current,
803 sessions: [
804 ...current.sessions.filter(
805 (existing) =>
806 !(
807 existing.threadId === session.threadId &&
808 existing.hostId === session.hostId &&
809 existing.deviceId === session.deviceId
810 ),
811 ),
812 session,
813 ],
814 }));
815 }),
816 );
817 return session;
818 });
819​
820 const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* (
821 hostId: DeviceHostId,
822 deviceId: DeviceId,
823 platform: DevicePlatform,
824 ) {
825 const ready = yield* readiness(hostId);
826 const postShutdown = (path: string, body: Record<string, string>) =>
827 HttpClientRequest.post(`${ready.hub.origin}${path}`).pipe(
828 HttpClientRequest.bodyJson(body),
829 Effect.mapError(
830 (cause) =>
831 new DeviceOperationError({ operation: "shutdown", reason: "invalid_payload", cause }),
832 ),
833 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")),
834 Effect.flatMap((result) =>
835 result.ok
836 ? Effect.void
837 : Effect.fail(
838 new DeviceOperationError({
839 operation: "shutdown",
840 reason: "hub_rejected",
841 cause: result,
842 }),
843 ),
844 ),
845 );
846 // serve-sim's shutdown closes its in-process capture session before it runs
847 // `simctl shutdown`; the hub's generic shutdown can leave that session cached
848 // across a reboot. serve-sim runs simctl bare, though, so a simulator that is
849 // already off fails there.
850 yield* platform === "ios"
851 ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: deviceId }).pipe(
852 Effect.catch((cause) =>
853 fetchDevices(ready).pipe(
854 Effect.flatMap(({ devices }) =>
855 devices.find((device) => device.id === deviceId)?.booted === false
856 ? Effect.logInfo("iOS simulator was already shut down", { deviceId })
857 : Effect.fail(cause),
858 ),
859 ),
860 ),
861 )
862 : postShutdown("/api/devices/shutdown", { platform, id: deviceId });
863 yield* publish((state) => ({
864 ...state,
865 devices: state.devices.map((device) =>
866 device.hostId === ready.hostId && device.id === deviceId
867 ? { ...device, booted: false }
868 : device,
869 ),
870 sessions: state.sessions.filter(
871 (session) => !(session.hostId === ready.hostId && session.deviceId === deviceId),
872 ),
873 }));
874 // Discovery can stall while an emulator saves its snapshot. A failed
875 // refresh must not turn an accepted shutdown into an action failure.
876 yield* refresh(ready).pipe(
877 Effect.catch((cause) =>
878 Effect.logWarning("Device discovery unavailable after shutdown", { cause }),
879 ),
880 );
881 });
882​
883 const close: DeviceService["Service"]["close"] = Effect.fn("DeviceService.close")(
884 function* (input) {
885 const { state } = yield* SynchronizedRef.get(stateRef);
886 const closing = state.sessions.filter(
887 (session) =>
888 session.threadId === input.threadId &&
889 (input.hostId === undefined || session.hostId === input.hostId) &&
890 (input.deviceId === undefined || session.deviceId === input.deviceId),
891 );
892 if (closing.length === 0) return;
893 yield* publish((current) => ({
894 ...current,
895 sessions: current.sessions.filter((session) => !closing.includes(session)),
896 }));
897 if (input.shutdown) {
898 yield* Effect.forEach(
899 closing,
900 (session) => shutdownDevice(session.hostId, session.deviceId, session.platform),
901 { discard: true },
902 );
903 }
904 },
905 );
906​
907 const shutdown: DeviceService["Service"]["shutdown"] = Effect.fn("DeviceService.shutdown")(
908 function* (input) {
909 const host = yield* resolveHost(input.hostId);
910 yield* shutdownDevice(host.id, input.deviceId, input.platform);
911 yield* publish((current) => ({
912 ...current,
913 sessions: current.sessions.filter(
914 (session) => !(session.hostId === host.id && session.deviceId === input.deviceId),
915 ),
916 }));
917 },
918 );
919​
920 const screenshot: DeviceService["Service"]["screenshot"] = Effect.fn("DeviceService.screenshot")(
921 function* (input) {
922 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
923 const url = `${ready.hub.origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`;
924 const png = yield* httpClient.execute(HttpClientRequest.post(url)).pipe(
925 Effect.flatMap(HttpClientResponse.filterStatusOk),
926 Effect.flatMap((response) => response.arrayBuffer),
927 Effect.map((buffer) => new Uint8Array(buffer)),
928 Effect.scoped,
929 Effect.timeout(SCREENSHOT_TIMEOUT),
930 Effect.mapError(
931 (cause) =>
932 new DeviceOperationError({
933 operation: "screenshot",
934 reason: "request_failed",
935 cause,
936 }),
937 ),
938 );
939 return { device, png };
940 },
941 );
942​
943 const resolveDevice = Effect.fn("DeviceService.resolveDevice")(function* (
944 hostId: DeviceHostId | undefined,
945 deviceId: DeviceId,
946 ) {
947 const host = yield* resolveHost(hostId);
948 const ready = yield* readiness(host.id);
949 const { state } = yield* SynchronizedRef.get(stateRef);
950 const device =
951 findDevice(state, host.id, deviceId) ?? findDevice(yield* refresh(ready), host.id, deviceId);
952 if (!device) return yield* new DeviceNotFoundError({ hostId: host.id, deviceId });
953 return { ready, device };
954 });
955​
956 const detail: DeviceService["Service"]["detail"] = Effect.fn("DeviceService.detail")(
957 function* (input) {
958 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
959 const read = yield* readDeviceDetail(ready, device.platform, device.id);
960 return {
961 hostId: ready.hostId,
962 deviceId: device.id,
963 settings: read.settings,
964 foregroundApp: read.foregroundApp,
965 readAt: DateTime.formatIso(yield* DateTime.now),
966 };
967 },
968 );
969​
970 const action: DeviceService["Service"]["action"] = Effect.fn("DeviceService.action")(
971 function* (input) {
972 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
973 yield* runDeviceAction(ready, device.platform, input);
974 return yield* detail({ hostId: ready.hostId, deviceId: device.id });
975 },
976 );
977​
978 const sessionsForThread: DeviceService["Service"]["sessionsForThread"] = (threadId) =>
979 SynchronizedRef.get(stateRef).pipe(
980 Effect.map(({ state }) => state.sessions.filter((session) => session.threadId === threadId)),
981 );
982​
983 return {
984 ...DeviceService.of({
985 testHost,
986 updateTool: (tool) =>
987 lifecycleLock.withPermit(
988 Effect.gen(function* () {
989 if (!installTool)
990 return yield* new DeviceOperationError({
991 operation: "update device tool",
992 reason: "request_failed",
993 cause: new Error("Tool installation is unavailable in this device service."),
994 });
995 yield* installTool(tool);
996 return yield* inspect;
997 }),
998 ),
999 retryHost,
1000 inspect,
1001 agentCli: Effect.fail(
1002 new DeviceHostUnavailableError({
1003 hostId: LOCAL_DEVICE_HOST_ID,
1004 reason: "Agent CLI installation is unavailable in this device service.",
1005 }),
1006 ),
1007 agentTarget: Effect.fn("DeviceService.agentTarget")(function* (input) {
1008 const host = yield* resolveHost(input.hostId);
1009 const ready = yield* agentReadinessIfSupported(input.hostId);
1010 if (!ready)
1011 return yield* new DeviceHostUnavailableError({
1012 hostId: input.hostId,
1013 reason:
1014 "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
1015 });
1016 const configPath = yield* lifecycleLock.withPermit(
1017 Effect.gen(function* () {
1018 if (hosts.get(host.id) !== host)
1019 return yield* new DeviceHostUnavailableError({
1020 hostId: host.id,
1021 reason: "Host configuration changed. Retry the operation.",
1022 });
1023 return yield* configureAgent(input.hostId, ready);
1024 }),
1025 );
1026 const session = yield* agentDeviceSession(
1027 input.threadId,
1028 input.hostId,
1029 input.deviceId,
1030 ).pipe(Effect.provideService(Crypto.Crypto, crypto));
1031 return ["--config", configPath, "--session", session];
1032 }),
1033 state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
1034 subscribe: PubSub.subscribe(statePubSub),
1035 configure,
1036 list,
1037 open,
1038 close,
1039 shutdown,
1040 detail,
1041 action,
1042 screenshot,
1043 readiness,
1044 readinessIfSupported,
1045 agentReadinessIfSupported,
1046 currentReadiness,
1047 sessionsForThread,
1048 }),
1049 setHostStatus,
1050 withLifecycleLock: lifecycleLock.withPermit,
1051 refreshHosts: Effect.gen(function* () {
1052 const summaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
1053 const unchanged = (id: DeviceHostId) =>
1054 hosts.has(id) && hosts.get(id) === publishedHosts.get(id);
1055 yield* publish((state) => ({
1056 ...state,
1057 hosts: summaries,
1058 hostStatuses: Object.fromEntries(
1059 Object.entries(state.hostStatuses).filter(([id]) => unchanged(id)),
1060 ),
1061 devices: state.devices.filter((device) => unchanged(device.hostId)),
1062 sessions: state.sessions.filter((session) => unchanged(session.hostId)),
1063 }));
1064 publishedHosts = new Map(hosts);
1065 }),
1066 };
1067});
1068​
1069/** @public */
1070/** @public Service construction is part of the canonical Effect module API. */
1071export const make = Effect.gen(function* () {
1072 const localHost = yield* DeviceHost.DeviceHost;
1073 const config = yield* ServerConfig.ServerConfig;
1074 const fs = yield* FileSystem.FileSystem;
1075 const path = yield* Path.Path;
1076 const runner = yield* ProcessRunner.ProcessRunner;
1077 const settings = yield* ServerSettings.ServerSettingsService;
1078 const scope = yield* Scope.Scope;
1079 const hosts = new Map<DeviceHostId, DeviceHost.DeviceHost["Service"]>([
1080 [localHost.id, localHost],
1081 ]);
1082 const crypto = yield* Crypto.Crypto;
1083 const configPath = (hostId: DeviceHostId) =>
1084 agentDeviceConfigPath(config.stateDir, hostId, path).pipe(
1085 Effect.provideService(Crypto.Crypto, crypto),
1086 );
1087 const configureAgent = Effect.fn("DeviceService.configureAgent")(
1088 function* (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) {
1089 const file = yield* configPath(hostId);
1090 yield* writeAgentDeviceConfig(file, ready.agentDevice);
1091 return file;
1092 },
1093 Effect.provideService(FileSystem.FileSystem, fs),
1094 Effect.provideService(Path.Path, path),
1095 Effect.mapError(
1096 (cause) =>
1097 new DeviceOperationError({
1098 operation: "configure agent",
1099 reason: "settings_failed",
1100 cause,
1101 }),
1102 ),
1103 );
1104 const probeContext =
1105 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();
1106 const localTargetContext =
1107 yield* Effect.context<Effect.Services<ReturnType<typeof isLocalSshDeviceHost>>>();
1108 const service = yield* makeWithHosts(
1109 hosts,
1110 (host) =>
1111 Effect.gen(function* () {
1112 if (yield* isLocalSshDeviceHost(host).pipe(Effect.provide(localTargetContext))) {
1113 return yield* localHost.summary;
1115 return yield* SshDeviceHost.probe(host).pipe(Effect.provide(probeContext));
1116 }).pipe(
1117 Effect.mapError(
1118 (error) =>
1119 new DeviceOperationError({
1120 operation: "probe host",
1121 reason: "request_failed",
1122 cause: error,
1123 }),
1124 ),
1125 ),
1126 configureAgent,
1127 (tool) =>
1128 (tool === "hub" ? ensureDeviceHub(config.baseDir) : ensureAgentDevice(config.baseDir)).pipe(
1129 Effect.provideService(FileSystem.FileSystem, fs),
1130 Effect.provideService(Path.Path, path),
1131 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1132 Effect.mapError(
1133 (cause) =>
1134 new DeviceOperationError({
1135 operation: "update device tool",
1136 reason: "command_failed",
1137 // Only the exit code goes into the shown message; npm's stderr can carry registry credentials.
1138 ...(cause.exitCode !== undefined ? { exitCode: cause.exitCode } : {}),
1139 cause,
1140 }),
1141 ),
1142 ),
1143 );
1144 const hostContext =
1145 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
1146 const configured = new Map<string, { config: SshDeviceHostConfig; scope: Scope.Closeable }>();
1147 const reconcile = Effect.fn("DeviceService.reconcile")(function* (
1148 configuredHosts: ReadonlyArray<SshDeviceHostConfig>,
1149 ) {
1150 const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(
1151 Effect.provide(localTargetContext),
1152 );
1153 const removed = yield* service.withLifecycleLock(
1154 Effect.gen(function* () {
1155 const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
1156 for (const [id, previous] of configured) {
1157 if (
1158 next.some(
1159 (host) =>
1160 host.id === id &&
1161 host.label === previous.config.label &&
1162 host.target === previous.config.target &&
1163 host.port === previous.config.port &&
1164 host.identityFile === previous.config.identityFile,
1167 continue;
1168 hosts.delete(id);
1169 configured.delete(id);
1170 removed.push({ id, scope: previous.scope });
1172 if (removed.length > 0) yield* service.refreshHosts;
1173 return removed;
1174 }),
1175 );
1176 // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.
1177 yield* Effect.forEach(
1178 removed,
1179 ({ id, scope }) =>
1180 Effect.gen(function* () {
1181 yield* Scope.close(scope, Exit.void);
1182 yield* fs.remove(yield* configPath(id), { force: true }).pipe(Effect.ignore);
1183 }),
1184 { concurrency: 4, discard: true },
1185 );
1186 yield* service.withLifecycleLock(
1187 Effect.gen(function* () {
1188 let added = false;
1189 for (const host of next) {
1190 if (configured.has(host.id)) continue;
1191 added = true;
1192 const hostScope = yield* Scope.fork(scope);
1193 const instance = yield* SshDeviceHost.make(
1194 host,
1195 (ready) =>
1196 configureAgent(host.id, ready).pipe(
1197 Effect.asVoid,
1198 Effect.mapError(
1199 (error) =>
1200 new DeviceHost.DeviceHostError({
1201 hostId: host.id,
1202 step: "configuring agent access",
1203 cause: error,
1204 }),
1205 ),
1206 ),
1207 (status, detail) =>
1208 service
1209 .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })
1210 .pipe(Effect.asVoid),
1211 ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));
1212 hosts.set(host.id, instance);
1213 configured.set(host.id, { config: host, scope: hostScope });
1215 // Refresh again after removed scopes closed so a late status write from an old host cannot linger.
1216 if (added || removed.length > 0) yield* service.refreshHosts;
1217 }),
1218 );
1219 });
1220 const changes = yield* settings.subscribeChanges;
1221 yield* reconcile((yield* settings.getSettings).deviceHosts);
1222 yield* changes.pipe(
1223 Stream.runForEach((value) => reconcile(value.deviceHosts)),
1224 Effect.forkIn(scope),
1225 );
1226 yield* Effect.addFinalizer(() =>
1227 Effect.forEach(configured.values(), (value) => Scope.close(value.scope, Exit.void), {
1228 discard: true,
1229 concurrency: 4,
1230 }),
1231 );
1232 return {
1233 ...service,
1234 agentCli: resolveNodeExecutable("Device automation").pipe(
1235 Effect.andThen(ensureAgentDevice(config.baseDir)),
1236 Effect.provideService(FileSystem.FileSystem, fs),
1237 Effect.provideService(Path.Path, path),
1238 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1239 Effect.map((tool) => tool.entryPath),
1240 Effect.mapError((error) =>
1241 error._tag === "NodeRuntimeUnavailableError"
1242 ? new DeviceHostUnavailableError({
1243 hostId: LOCAL_DEVICE_HOST_ID,
1244 reason: nodeRuntimeUnavailableMessage("Device automation"),
1245 cause: error,
1246 })
1247 : new DeviceOperationError({
1248 operation: "install agent CLI",
1249 reason: "command_failed",
1250 cause: error,
1251 }),
1252 ),
1253 ),
1254 };
1255});
1256​
1257export const layer = Layer.effect(DeviceService, make).pipe(Layer.provide(LocalDeviceHost.layer));
1258​
1259export const stateStream = (service: DeviceService["Service"]): Stream.Stream<DeviceServiceState> =>
1260 Stream.unwrap(
1261 Effect.gen(function* () {
1262 // Subscribe before reading the snapshot so no change between the two
1263 // is lost; the scope lives as long as the stream does.
1264 const subscription = yield* service.subscribe;
1265 const initial = yield* service.state;
1266 return Stream.concat(Stream.make(initial), Stream.fromSubscription(subscription));
1267 }),
1268 ).pipe(Stream.scoped);