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