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