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

DeviceService.ts

1,025 lines37.9 KB

1/**
2 * Device discovery, per-thread device sessions, and the state stream clients
3 * render the Device panel from.
4 *
5 * Discovery and boot go through expo-device-hub's JSON API rather than
6 * shelling out to simctl and adb here: the hub already normalizes both
7 * platforms into one device shape and is the process that has to know a
8 * device is booted before it can stream it. Sessions are the server's own
9 * bookkeeping — which thread is looking at which device — so the panel and
10 * the `device_*` tools agree, and so a `device_open` from an agent surfaces in
11 * every connected client the way `preview_open` does.
12 */
13import {
14 type DeviceActionInput,
15 type DeviceCloseInput,
16 type DeviceConfigureInput,
17 type DeviceDetail,
18 type DeviceDetailInput,
19 type DeviceError,
20 type DeviceHostId,
21 type DeviceId,
22 DeviceBootError,
23 DeviceHostUnavailableError,
24 DeviceNotFoundError,
25 DeviceOperationError,
26 type DeviceOpenInput,
27 type DevicePlatform,
28 DevicePlatformUnavailableError,
29 type DeviceServiceState,
30 type DeviceSession,
31 type DeviceShutdownInput,
32 type DeviceSummary,
33 type SshDeviceHostConfig,
34 type DeviceHostSummary,
35 LOCAL_DEVICE_HOST_ID,
36 type ThreadId,
37} from "@t3tools/contracts";
38import * as FileSystem from "effect/FileSystem";
39import * as Path from "effect/Path";
40import { ensureAgentDevice } from "./DeviceToolchain.ts";
41import * as ServerConfig from "../config.ts";
42import {
43 agentDeviceConfigPath,
44 agentDeviceSession,
45 writeAgentDeviceConfig,
46} from "./AgentDeviceTarget.ts";
47import * as Context from "effect/Context";
48import * as DateTime from "effect/DateTime";
49import * as Duration from "effect/Duration";
50import * as Effect from "effect/Effect";
51import * as Layer from "effect/Layer";
52import * as PubSub from "effect/PubSub";
53import * as Schema from "effect/Schema";
54import * as Scope from "effect/Scope";
55import * as Semaphore from "effect/Semaphore";
56import * as Stream from "effect/Stream";
57import * as SynchronizedRef from "effect/SynchronizedRef";
58import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
59​
60import * as ServerSettings from "../serverSettings.ts";
61​
62import { readDeviceDetail, runDeviceAction } from "./DeviceActions.ts";
63import * as ProcessRunner from "../processRunner.ts";
64import * as DeviceHost from "./DeviceHost.ts";
65import * as SshDeviceHost from "./SshDeviceHost.ts";
66import * as Exit from "effect/Exit";
67import * as LocalDeviceHost from "./LocalDeviceHost.ts";
68​
69/** Origin-relative prefix the hub is proxied under. See DeviceHubProxy. */
70export const DEVICE_HUB_ROUTE_PREFIX = "/api/device-hub";
71​
72const BOOT_TIMEOUT = Duration.minutes(3);
73const SCREENSHOT_TIMEOUT = Duration.seconds(20);
74​
75const HubDevice = Schema.Struct({
76 id: Schema.String,
77 name: Schema.String,
78 version: Schema.String,
79 platform: Schema.Literals(["ios", "android"]),
80 booted: Schema.Boolean,
81 physical: Schema.Boolean,
82});
83const HubDeviceList = Schema.Struct({
84 simulators: Schema.Array(HubDevice),
85 emulators: Schema.Array(HubDevice),
86 errors: Schema.optional(Schema.Array(Schema.Struct({ message: Schema.String }))),
87});
88const HubActionResult = Schema.Struct({
89 ok: Schema.Boolean,
90 id: Schema.optional(Schema.String),
91 serial: Schema.optional(Schema.String),
92 error: Schema.optional(Schema.String),
93});
94​
95export interface DeviceScreenshot {
96 readonly device: DeviceSummary;
97 readonly png: Uint8Array;
99​
100export interface DeviceReadiness extends DeviceHost.DeviceHostReady {
101 readonly hostId: DeviceHostId;
103​
104export interface DeviceAgentReadiness extends DeviceReadiness {
105 readonly agentDevice: DeviceHost.AgentDeviceEndpoint;
107​
108export class DeviceService extends Context.Service<
109 DeviceService,
110 {
111 readonly agentCli: Effect.Effect<string, DeviceError>;
112 readonly testHost: (
113 config: SshDeviceHostConfig,
114 ) => Effect.Effect<DeviceHostSummary, DeviceError>;
115 readonly agentTarget: (input: {
116 threadId: ThreadId;
117 hostId: DeviceHostId;
118 deviceId: DeviceId;
119 }) => Effect.Effect<ReadonlyArray<string>, DeviceError>;
120 readonly state: Effect.Effect<DeviceServiceState>;
121 readonly subscribe: Effect.Effect<PubSub.Subscription<DeviceServiceState>, never, Scope.Scope>;
122 readonly configure: (
123 input: DeviceConfigureInput,
124 ) => Effect.Effect<DeviceServiceState, DeviceError>;
125 /** Refreshes devices only after device support has been enabled. */
126 readonly list: Effect.Effect<DeviceServiceState, DeviceError>;
127 readonly open: (input: DeviceOpenInput) => Effect.Effect<DeviceSession, DeviceError>;
128 readonly close: (input: DeviceCloseInput) => Effect.Effect<void, DeviceError>;
129 readonly shutdown: (input: DeviceShutdownInput) => Effect.Effect<void, DeviceError>;
130 /** Current settings and foreground app for one device. */
131 readonly detail: (input: DeviceDetailInput) => Effect.Effect<DeviceDetail, DeviceError>;
132 /** Runs one action, then returns the refreshed detail. */
133 readonly action: (input: DeviceActionInput) => Effect.Effect<DeviceDetail, DeviceError>;
134 readonly screenshot: (input: {
135 readonly hostId?: DeviceHostId | undefined;
136 readonly deviceId: DeviceId;
137 }) => Effect.Effect<DeviceScreenshot, DeviceError>;
138 /** Host endpoints for the proxy and the provider environment. */
139 readonly readiness: (hostId?: DeviceHostId) => Effect.Effect<DeviceReadiness, DeviceError>;
140 /**
141 * `readiness` only when the host can run at least one platform; a machine
142 * with no simulator toolchain never installs or starts anything.
143 */
144 readonly readinessIfSupported: (
145 hostId?: DeviceHostId,
146 ) => Effect.Effect<DeviceReadiness | null, DeviceError>;
147 readonly agentReadinessIfSupported: (
148 hostId?: DeviceHostId,
149 ) => Effect.Effect<DeviceAgentReadiness | null, DeviceError>;
150 readonly currentReadiness: (hostId?: DeviceHostId) => Effect.Effect<DeviceReadiness | null>;
151 readonly sessionsForThread: (threadId: ThreadId) => Effect.Effect<ReadonlyArray<DeviceSession>>;
152 }
153>()("t3/device/DeviceService") {}
154​
155interface ServiceState {
156 readonly state: DeviceServiceState;
158​
159const vendorPrefix = (platform: DevicePlatform) =>
160 platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
161​
162export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* (
163 hosts: ReadonlyMap<DeviceHostId, DeviceHost.DeviceHost["Service"]>,
164 testHost: DeviceService["Service"]["testHost"] = (host) =>
165 Effect.fail(
166 new DeviceHostUnavailableError({
167 hostId: host.id,
168 reason: "SSH probing is unavailable in this device service.",
169 }),
170 ),
171 configureAgent: (
172 hostId: DeviceHostId,
173 ready: DeviceHost.DeviceHostAgentReady,
174 ) => Effect.Effect<string, DeviceError> = (hostId) =>
175 Effect.fail(
176 new DeviceHostUnavailableError({
177 hostId,
178 reason: "Agent configuration is unavailable in this device service.",
179 }),
180 ),
181) {
182 const settings = yield* ServerSettings.ServerSettingsService;
183 const lifecycleLock = yield* Semaphore.make(1);
184 const readDeviceSettings = settings.getSettings.pipe(
185 Effect.map((value) => ({
186 enabled: value.enableDeviceSupport,
187 agentAccessEnabled: value.enableAgentDeviceAccess,
188 onboardingCompleted: value.deviceOnboardingCompleted,
189 })),
190 Effect.mapError(
191 (cause) =>
192 new DeviceOperationError({ operation: "settings", reason: "settings_failed", cause }),
193 ),
194 );
195 const initialSettings = yield* readDeviceSettings;
196​
197 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
198 const statePubSub = yield* PubSub.unbounded<DeviceServiceState>();
199 const initialHosts = yield* Effect.forEach(hosts.values(), (host) => host.summary);
200 let publishedHosts = new Map(hosts);
201 const stateRef = yield* SynchronizedRef.make<ServiceState>({
202 state: {
203 hosts: initialHosts,
204 hostStatus: initialSettings.enabled ? "idle" : "disabled",
205 hostStatuses: {},
206 devices: [],
207 sessions: [],
208 onboardingCompleted: initialSettings.onboardingCompleted,
209 agentAccessEnabled: initialSettings.agentAccessEnabled,
210 hubBasePath: DEVICE_HUB_ROUTE_PREFIX,
211 revision: 0,
212 },
213 });
214​
215 const publish = (update: (state: DeviceServiceState) => DeviceServiceState) =>
216 SynchronizedRef.updateAndGetEffect(stateRef, ({ state }) => {
217 const next = { ...update(state), revision: state.revision + 1 };
218 return PubSub.publish(statePubSub, next).pipe(Effect.as({ state: next }));
219 }).pipe(Effect.map(({ state }) => state));
220​
221 const resolveHost = (hostId: DeviceHostId | undefined) =>
222 Effect.gen(function* () {
223 const id = hostId ?? LOCAL_DEVICE_HOST_ID;
224 const host = hosts.get(id);
225 if (!host) {
226 return yield* new DeviceHostUnavailableError({ hostId: id, reason: "Unknown host." });
227 }
228 return host;
229 });
230​
231 const setHostStatus = (
232 hostId: DeviceHostId,
233 status: DeviceServiceState["hostStatuses"][string],
234 ) =>
235 Effect.suspend(() =>
236 !hosts.has(hostId)
237 ? SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state))
238 : publish((state) => ({
239 ...state,
240 ...(hostId === LOCAL_DEVICE_HOST_ID
241 ? { hostStatus: status.status, hostStatusDetail: status.detail }
242 : {}),
243 hostStatuses: { ...state.hostStatuses, [hostId]: status },
244 })),
245 );
246​
247 const readiness: DeviceService["Service"]["readiness"] = Effect.fn("DeviceService.readiness")(
248 function* (hostId) {
249 const host = yield* resolveHost(hostId);
250 if (!(yield* readDeviceSettings).enabled) {
251 return yield* new DeviceHostUnavailableError({
252 hostId: host.id,
253 reason:
254 "Device support is off. Enable it in the Device panel before installing or starting device tools.",
255 });
256 }
257 const ready = yield* host
258 .ensureReady((status) => setHostStatus(host.id, { status }).pipe(Effect.asVoid))
259 .pipe(
260 Effect.tapError((error) =>
261 setHostStatus(host.id, { status: "failed", detail: error.message }),
262 ),
263 Effect.mapError(
264 (error) => new DeviceHostUnavailableError({ hostId: host.id, reason: error.message }),
265 ),
266 );
267 if (hosts.get(host.id) !== host)
268 return yield* new DeviceHostUnavailableError({
269 hostId: host.id,
270 reason: "Host configuration changed. Retry the operation.",
271 });
272 const { state } = yield* SynchronizedRef.get(stateRef);
273 if (state.hostStatuses[host.id]?.status !== "ready") {
274 yield* setHostStatus(host.id, { status: "ready" });
275 }
276 return { hostId: host.id, ...ready };
277 },
278 lifecycleLock.withPermit,
279 );
280​
281 const readinessIfSupported: DeviceService["Service"]["readinessIfSupported"] = Effect.fn(
282 "DeviceService.readinessIfSupported",
283 )(function* (hostId) {
284 if (!(yield* readDeviceSettings).enabled) return null;
285 const host = yield* resolveHost(hostId);
286 const summary = yield* host.summary;
287 if (summary.kind === "local" && !summary.platforms.some((platform) => platform.available))
288 return null;
289 return yield* readiness(host.id);
290 });
291​
292 const agentReadinessIfSupported: DeviceService["Service"]["agentReadinessIfSupported"] =
293 Effect.fn("DeviceService.agentReadinessIfSupported")(function* (hostId) {
294 const deviceSettings = yield* readDeviceSettings;
295 if (!deviceSettings.enabled || !deviceSettings.agentAccessEnabled) return null;
296 const host = yield* resolveHost(hostId);
297 const summary = yield* host.summary;
298 if (summary.kind === "local" && !summary.platforms.some((platform) => platform.available))
299 return null;
300 const ready = yield* host
301 .ensureAgentReady((phase) => setHostStatus(host.id, { status: phase }).pipe(Effect.asVoid))
302 .pipe(
303 Effect.tapError((error) =>
304 setHostStatus(host.id, { status: "failed", detail: error.message }),
305 ),
306 Effect.mapError(
307 (error) => new DeviceHostUnavailableError({ hostId: host.id, reason: error.message }),
308 ),
309 );
310 const hostSummaries = yield* Effect.forEach(hosts.values(), (candidate) => candidate.summary);
311 yield* publish((state) => ({ ...state, hosts: hostSummaries }));
312 yield* setHostStatus(host.id, { status: "ready" });
313 return { hostId: host.id, ...ready };
314 }, lifecycleLock.withPermit);
315​
316 const currentReadiness: DeviceService["Service"]["currentReadiness"] = (hostId) =>
317 resolveHost(hostId).pipe(
318 Effect.flatMap((host) =>
319 host.current.pipe(Effect.map((ready) => (ready ? { hostId: host.id, ...ready } : null))),
320 ),
321 Effect.orElseSucceed(() => null),
322 );
323​
324 const hubJson = <A, I>(
325 request: HttpClientRequest.HttpClientRequest,
326 schema: Schema.Codec<A, I>,
327 operation: string,
328 timeout: Duration.Input = Duration.seconds(15),
329 ) =>
330 httpClient.execute(request).pipe(
331 Effect.flatMap(HttpClientResponse.filterStatusOk),
332 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
333 Effect.scoped,
334 Effect.timeout(timeout),
335 Effect.mapError(
336 (cause) =>
337 new DeviceOperationError({
338 operation,
339 reason: "request_failed",
340 cause,
341 }),
342 ),
343 );
344​
345 const fetchDevices = Effect.fn("DeviceService.fetchDevices")(function* (ready: DeviceReadiness) {
346 const list = yield* hubJson(
347 HttpClientRequest.get(`${ready.hub.origin}/api/devices`),
348 HubDeviceList,
349 "list",
350 );
351 const toSummary = (device: typeof HubDevice.Type): DeviceSummary => ({
352 hostId: ready.hostId,
353 id: device.id,
354 platform: device.platform,
355 name: device.name,
356 version: device.version,
357 booted: device.booted,
358 physical: device.physical,
359 });
360 const devices = [...list.simulators, ...list.emulators].map(toSummary);
361 const host = yield* resolveHost(ready.hostId);
362 if ((yield* host.platformAvailability("android")).available) {
363 const avds = yield* ready.run("emulator", ["-list-avds"]);
364 if (avds.code !== 0) {
365 return yield* new DeviceOperationError({
366 operation: "list",
367 reason: "command_failed",
368 exitCode: avds.code,
369 cause: avds,
370 });
371 }
372 for (const name of avds.stdout
373 .split(/\r?\n/)
374 .map((line) => line.trim())
375 .filter(Boolean)) {
376 if (!devices.some((device) => device.platform === "android" && device.name === name)) {
377 devices.push({
378 hostId: ready.hostId,
379 id: name,
380 name,
381 platform: "android",
382 version: "Android",
383 booted: false,
384 physical: false,
385 });
386 }
387 }
388 }
389 return { devices, detail: list.errors?.map((error) => error.message).join("\n") || undefined };
390 });
391​
392 const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {
393 const host = hosts.get(ready.hostId);
394 const { devices, detail } = yield* fetchDevices(ready);
395 const hostSummaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
396 return yield* lifecycleLock.withPermit(
397 Effect.gen(function* () {
398 if (!(yield* readDeviceSettings).enabled || !host || hosts.get(ready.hostId) !== host)
399 return (yield* SynchronizedRef.get(stateRef)).state;
400 return yield* publish((state) => ({
401 ...state,
402 hosts: hostSummaries,
403 ...(ready.hostId === LOCAL_DEVICE_HOST_ID ? { hostStatusDetail: detail } : {}),
404 devices: [
405 ...state.devices.filter((device) => device.hostId !== ready.hostId),
406 ...devices,
407 ],
408 hostStatuses: {
409 ...state.hostStatuses,
410 [ready.hostId]: { status: "ready", ...(detail ? { detail } : {}) },
411 },
412 }));
413 }),
414 );
415 });
416​
417 const list: DeviceService["Service"]["list"] = Effect.gen(function* () {
418 if (!(yield* readDeviceSettings).enabled) return (yield* SynchronizedRef.get(stateRef)).state;
419 yield* Effect.forEach(
420 hosts.values(),
421 (host) =>
422 Effect.gen(function* () {
423 const ready = yield* readinessIfSupported(host.id);
424 if (ready) yield* refresh(ready);
425 }).pipe(
426 Effect.catch((error) =>
427 setHostStatus(host.id, { status: "failed", detail: error.message }),
428 ),
429 ),
430 { concurrency: 4 },
431 );
432 return (yield* SynchronizedRef.get(stateRef)).state;
433 }).pipe(Effect.withSpan("DeviceService.list"));
434​
435 const configure: DeviceService["Service"]["configure"] = Effect.fn("DeviceService.configure")(
436 function* (input) {
437 const currentSettings = yield* readDeviceSettings;
438 const nextEnabled = input.enabled ?? currentSettings.enabled;
439 const nextAgentAccess = input.agentAccessEnabled ?? currentSettings.agentAccessEnabled;
440 yield* lifecycleLock.withPermit(
441 Effect.gen(function* () {
442 yield* settings
443 .updateSettings({
444 ...(input.enabled === undefined ? {} : { enableDeviceSupport: input.enabled }),
445 ...(input.agentAccessEnabled === undefined
446 ? {}
447 : { enableAgentDeviceAccess: input.agentAccessEnabled }),
448 ...(input.onboardingCompleted === undefined
449 ? {}
450 : { deviceOnboardingCompleted: input.onboardingCompleted }),
451 })
452 .pipe(
453 Effect.mapError(
454 (cause) =>
455 new DeviceOperationError({
456 operation: "configure",
457 reason: "settings_failed",
458 cause,
459 }),
460 ),
461 );
462 if (!nextEnabled) {
463 yield* Effect.forEach(hosts.values(), (host) => host.stop, { discard: true });
464 } else if (input.agentAccessEnabled === false) {
465 yield* Effect.forEach(hosts.values(), (host) => host.stopAgent, { discard: true });
466 }
467 yield* publish((state) => ({
468 ...state,
469 hostStatus: nextEnabled ? "idle" : "disabled",
470 hostStatusDetail: undefined,
471 hostStatuses: {},
472 devices: nextEnabled ? state.devices : [],
473 sessions: nextEnabled ? state.sessions : [],
474 bootingDevices: nextEnabled ? state.bootingDevices : [],
475 agentAccessEnabled: nextAgentAccess,
476 onboardingCompleted: input.onboardingCompleted ?? state.onboardingCompleted,
477 }));
478 }),
479 );
480 if (nextEnabled && nextAgentAccess && input.agentAccessEnabled === true) {
481 yield* agentReadinessIfSupported();
482 }
483 return yield* list;
484 },
485 );
486​
487 const findDevice = (
488 state: DeviceServiceState,
489 hostId: DeviceHostId,
490 deviceId: DeviceId,
491 ): DeviceSummary | undefined =>
492 state.devices.find((device) => device.hostId === hostId && device.id === deviceId);
493​
494 const ensurePlatform = Effect.fn("DeviceService.ensurePlatform")(function* (
495 host: DeviceHost.DeviceHost["Service"],
496 platform: DevicePlatform,
497 ) {
498 const availability = yield* host.platformAvailability(platform);
499 if (!availability.available) {
500 return yield* new DevicePlatformUnavailableError({
501 hostId: host.id,
502 platform,
503 reason: availability.reason ?? "Platform toolchain missing.",
504 });
505 }
506 });
507​
508 /**
509 * Boot through the hub so its device list and the streaming helper both see
510 * the device come up. Android AVDs change id when they boot (AVD name to
511 * emulator serial), so the returned id is authoritative.
512 */
513 const boot = Effect.fn("DeviceService.boot")(function* (
514 ready: DeviceReadiness,
515 device: DeviceSummary,
516 ) {
517 const result = yield* HttpClientRequest.post(`${ready.hub.origin}/api/devices/boot`).pipe(
518 HttpClientRequest.bodyJson({ platform: device.platform, id: device.id, name: device.name }),
519 Effect.mapError(
520 (cause) =>
521 new DeviceOperationError({ operation: "boot", reason: "invalid_payload", cause }),
522 ),
523 Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)),
524 );
525 if (!result.ok) {
526 return yield* new DeviceBootError({
527 hostId: ready.hostId,
528 deviceId: device.id,
529 reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
530 result.error ?? "",
531 )
532 ? "disk_space"
533 : /timed? out|timeout/i.test(result.error ?? "")
534 ? "timeout"
535 : "launch_failed",
536 cause: result,
537 });
538 }
539 if (device.platform === "ios") {
540 // Booting alone does not attach a serve-sim helper; the grid start
541 // does both and is idempotent for a booted simulator.
542 yield* HttpClientRequest.post(
543 `${ready.hub.origin}${vendorPrefix("ios")}/grid/api/start`,
544 ).pipe(
545 HttpClientRequest.bodyJson({ udid: device.id }),
546 Effect.mapError(
547 (cause) =>
548 new DeviceOperationError({ operation: "boot", reason: "invalid_payload", cause }),
549 ),
550 Effect.flatMap((request) =>
551 hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT),
552 ),
553 );
554 }
555 return result.serial ?? result.id ?? device.id;
556 });
557​
558 const open: DeviceService["Service"]["open"] = Effect.fn("DeviceService.open")(function* (input) {
559 const host = yield* resolveHost(input.hostId);
560 yield* ensurePlatform(host, input.platform);
561 const ready = yield* readiness(host.id);
562 let state = yield* refresh(ready);
563 let device = findDevice(state, host.id, input.deviceId);
564 if (!device) {
565 return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: input.deviceId });
566 }
567 if (!device.booted && input.boot !== false) {
568 const booting = { ...device, threadId: input.threadId };
569 yield* publish((current) => ({
570 ...current,
571 bootingDevices: [
572 ...(current.bootingDevices ?? []).filter(
573 (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
574 ),
575 booting,
576 ],
577 }));
578 const bootedId = yield* boot(ready, device).pipe(
579 Effect.ensuring(
580 publish((current) => ({
581 ...current,
582 bootingDevices: (current.bootingDevices ?? []).filter(
583 (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
584 ),
585 })),
586 ),
587 );
588 state = yield* refresh(ready);
589 device = findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id);
590 if (!device) {
591 return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });
592 }
593 } else if (device.platform === "ios" && device.booted) {
594 // A simulator booted outside T3 has no helper attached yet.
595 yield* HttpClientRequest.post(
596 `${ready.hub.origin}${vendorPrefix("ios")}/grid/api/start`,
597 ).pipe(
598 HttpClientRequest.bodyJson({ udid: device.id }),
599 Effect.mapError(
600 (cause) =>
601 new DeviceOperationError({ operation: "open", reason: "invalid_payload", cause }),
602 ),
603 Effect.flatMap((request) =>
604 hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT),
605 ),
606 );
607 }
608 if (hosts.get(host.id) !== host)
609 return yield* new DeviceHostUnavailableError({
610 hostId: host.id,
611 reason: "Host configuration changed. Retry the operation.",
612 });
613 const openedAt = DateTime.formatIso(yield* DateTime.now);
614 const session: DeviceSession = {
615 threadId: input.threadId,
616 hostId: host.id,
617 deviceId: device.id,
618 platform: device.platform,
619 openedAt,
620 };
621 yield* lifecycleLock.withPermit(
622 Effect.gen(function* () {
623 if (!(yield* readDeviceSettings).enabled)
624 return yield* new DeviceHostUnavailableError({
625 hostId: host.id,
626 reason: "Device support was turned off while the device was opening.",
627 });
628 yield* publish((current) => ({
629 ...current,
630 sessions: [
631 ...current.sessions.filter(
632 (existing) =>
633 !(
634 existing.threadId === session.threadId &&
635 existing.hostId === session.hostId &&
636 existing.deviceId === session.deviceId
637 ),
638 ),
639 session,
640 ],
641 }));
642 }),
643 );
644 return session;
645 });
646​
647 const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* (
648 hostId: DeviceHostId,
649 deviceId: DeviceId,
650 platform: DevicePlatform,
651 ) {
652 const ready = yield* readiness(hostId);
653 yield* HttpClientRequest.post(`${ready.hub.origin}/api/devices/shutdown`).pipe(
654 HttpClientRequest.bodyJson({ platform, id: deviceId }),
655 Effect.mapError(
656 (cause) =>
657 new DeviceOperationError({ operation: "shutdown", reason: "invalid_payload", cause }),
658 ),
659 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")),
660 Effect.flatMap((result) =>
661 result.ok
662 ? Effect.void
663 : Effect.fail(
664 new DeviceOperationError({
665 operation: "shutdown",
666 reason: "hub_rejected",
667 cause: result,
668 }),
669 ),
670 ),
671 );
672 yield* publish((state) => ({
673 ...state,
674 devices: state.devices.map((device) =>
675 device.hostId === ready.hostId && device.id === deviceId
676 ? { ...device, booted: false }
677 : device,
678 ),
679 sessions: state.sessions.filter(
680 (session) => !(session.hostId === ready.hostId && session.deviceId === deviceId),
681 ),
682 }));
683 // Discovery can stall while an emulator saves its snapshot. A failed
684 // refresh must not turn an accepted shutdown into an action failure.
685 yield* refresh(ready).pipe(
686 Effect.catch((cause) =>
687 Effect.logWarning("Device discovery unavailable after shutdown", { cause }),
688 ),
689 );
690 });
691​
692 const close: DeviceService["Service"]["close"] = Effect.fn("DeviceService.close")(
693 function* (input) {
694 const { state } = yield* SynchronizedRef.get(stateRef);
695 const closing = state.sessions.filter(
696 (session) =>
697 session.threadId === input.threadId &&
698 (input.hostId === undefined || session.hostId === input.hostId) &&
699 (input.deviceId === undefined || session.deviceId === input.deviceId),
700 );
701 if (closing.length === 0) return;
702 yield* publish((current) => ({
703 ...current,
704 sessions: current.sessions.filter((session) => !closing.includes(session)),
705 }));
706 if (input.shutdown) {
707 yield* Effect.forEach(
708 closing,
709 (session) => shutdownDevice(session.hostId, session.deviceId, session.platform),
710 { discard: true },
711 );
712 }
713 },
714 );
715​
716 const shutdown: DeviceService["Service"]["shutdown"] = Effect.fn("DeviceService.shutdown")(
717 function* (input) {
718 const host = yield* resolveHost(input.hostId);
719 yield* shutdownDevice(host.id, input.deviceId, input.platform);
720 // Sessions on a powered-off device are stale in every thread.
721 yield* publish((current) => ({
722 ...current,
723 sessions: current.sessions.filter(
724 (session) => !(session.hostId === host.id && session.deviceId === input.deviceId),
725 ),
726 }));
727 },
728 );
729​
730 const screenshot: DeviceService["Service"]["screenshot"] = Effect.fn("DeviceService.screenshot")(
731 function* (input) {
732 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
733 const url = `${ready.hub.origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`;
734 const png = yield* httpClient.execute(HttpClientRequest.post(url)).pipe(
735 Effect.flatMap(HttpClientResponse.filterStatusOk),
736 Effect.flatMap((response) => response.arrayBuffer),
737 Effect.map((buffer) => new Uint8Array(buffer)),
738 Effect.scoped,
739 Effect.timeout(SCREENSHOT_TIMEOUT),
740 Effect.mapError(
741 (cause) =>
742 new DeviceOperationError({
743 operation: "screenshot",
744 reason: "request_failed",
745 cause,
746 }),
747 ),
748 );
749 return { device, png };
750 },
751 );
752​
753 const resolveDevice = Effect.fn("DeviceService.resolveDevice")(function* (
754 hostId: DeviceHostId | undefined,
755 deviceId: DeviceId,
756 ) {
757 const host = yield* resolveHost(hostId);
758 const ready = yield* readiness(host.id);
759 const { state } = yield* SynchronizedRef.get(stateRef);
760 const device =
761 findDevice(state, host.id, deviceId) ?? findDevice(yield* refresh(ready), host.id, deviceId);
762 if (!device) return yield* new DeviceNotFoundError({ hostId: host.id, deviceId });
763 return { ready, device };
764 });
765​
766 const detail: DeviceService["Service"]["detail"] = Effect.fn("DeviceService.detail")(
767 function* (input) {
768 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
769 const read = yield* readDeviceDetail(ready, device.platform, device.id);
770 return {
771 hostId: ready.hostId,
772 deviceId: device.id,
773 settings: read.settings,
774 foregroundApp: read.foregroundApp,
775 readAt: DateTime.formatIso(yield* DateTime.now),
776 };
777 },
778 );
779​
780 const action: DeviceService["Service"]["action"] = Effect.fn("DeviceService.action")(
781 function* (input) {
782 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
783 yield* runDeviceAction(ready, device.platform, input);
784 return yield* detail({ hostId: ready.hostId, deviceId: device.id });
785 },
786 );
787​
788 const sessionsForThread: DeviceService["Service"]["sessionsForThread"] = (threadId) =>
789 SynchronizedRef.get(stateRef).pipe(
790 Effect.map(({ state }) => state.sessions.filter((session) => session.threadId === threadId)),
791 );
792​
793 return {
794 ...DeviceService.of({
795 testHost,
796 agentCli: Effect.fail(
797 new DeviceHostUnavailableError({
798 hostId: LOCAL_DEVICE_HOST_ID,
799 reason: "Agent CLI installation is unavailable in this device service.",
800 }),
801 ),
802 agentTarget: (input) =>
803 Effect.gen(function* () {
804 const host = yield* resolveHost(input.hostId);
805 const ready = yield* agentReadinessIfSupported(input.hostId);
806 if (!ready)
807 return yield* new DeviceHostUnavailableError({
808 hostId: input.hostId,
809 reason:
810 "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
811 });
812 const configPath = yield* lifecycleLock.withPermit(
813 Effect.gen(function* () {
814 if (hosts.get(host.id) !== host)
815 return yield* new DeviceHostUnavailableError({
816 hostId: host.id,
817 reason: "Host configuration changed. Retry the operation.",
818 });
819 return yield* configureAgent(input.hostId, ready);
820 }),
821 );
822 return [
823 "--config",
824 configPath,
825 "--session",
826 agentDeviceSession(input.threadId, input.hostId, input.deviceId),
827 ];
828 }),
829 state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
830 subscribe: PubSub.subscribe(statePubSub),
831 configure,
832 list,
833 open,
834 close,
835 shutdown,
836 detail,
837 action,
838 screenshot,
839 readiness,
840 readinessIfSupported,
841 agentReadinessIfSupported,
842 currentReadiness,
843 sessionsForThread,
844 }),
845 setHostStatus,
846 withLifecycleLock: lifecycleLock.withPermit,
847 refreshHosts: Effect.gen(function* () {
848 const summaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
849 const unchanged = (id: DeviceHostId) =>
850 hosts.has(id) && hosts.get(id) === publishedHosts.get(id);
851 yield* publish((state) => ({
852 ...state,
853 hosts: summaries,
854 hostStatuses: Object.fromEntries(
855 Object.entries(state.hostStatuses).filter(([id]) => unchanged(id)),
856 ),
857 devices: state.devices.filter((device) => unchanged(device.hostId)),
858 sessions: state.sessions.filter((session) => unchanged(session.hostId)),
859 }));
860 publishedHosts = new Map(hosts);
861 }),
862 };
863});
864​
865/** @public Service construction is part of the canonical Effect module API. */
866export const make = Effect.gen(function* () {
867 const localHost = yield* DeviceHost.DeviceHost;
868 const config = yield* ServerConfig.ServerConfig;
869 const fs = yield* FileSystem.FileSystem;
870 const path = yield* Path.Path;
871 const runner = yield* ProcessRunner.ProcessRunner;
872 const settings = yield* ServerSettings.ServerSettingsService;
873 const scope = yield* Scope.Scope;
874 const hosts = new Map<DeviceHostId, DeviceHost.DeviceHost["Service"]>([
875 [localHost.id, localHost],
876 ]);
877 const configureAgent = (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) => {
878 const file = agentDeviceConfigPath(config.stateDir, hostId, path);
879 return writeAgentDeviceConfig(file, ready.agentDevice).pipe(
880 Effect.provideService(FileSystem.FileSystem, fs),
881 Effect.provideService(Path.Path, path),
882 Effect.mapError(
883 (cause) =>
884 new DeviceOperationError({
885 operation: "configure agent",
886 reason: "settings_failed",
887 cause,
888 }),
889 ),
890 Effect.as(file),
891 );
892 };
893 const probeContext =
894 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();
895 const service = yield* makeWithHosts(
896 hosts,
897 (host) =>
898 SshDeviceHost.probe(host).pipe(
899 Effect.provide(probeContext),
900 Effect.mapError(
901 (error) =>
902 new DeviceOperationError({
903 operation: "probe host",
904 reason: "request_failed",
905 cause: error,
906 }),
907 ),
908 ),
909 configureAgent,
910 );
911 const hostContext =
912 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
913 const configured = new Map<string, { config: SshDeviceHostConfig; scope: Scope.Closeable }>();
914 const reconcile = (next: ReadonlyArray<SshDeviceHostConfig>) =>
915 Effect.gen(function* () {
916 const removed = yield* service.withLifecycleLock(
917 Effect.gen(function* () {
918 const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
919 for (const [id, previous] of configured) {
920 if (
921 next.some(
922 (host) =>
923 host.id === id &&
924 host.label === previous.config.label &&
925 host.target === previous.config.target &&
926 host.port === previous.config.port &&
927 host.identityFile === previous.config.identityFile,
928 )
929 )
930 continue;
931 hosts.delete(id);
932 configured.delete(id);
933 removed.push({ id, scope: previous.scope });
934 }
935 yield* service.refreshHosts;
936 return removed;
937 }),
938 );
939 // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.
940 yield* Effect.forEach(
941 removed,
942 ({ id, scope }) =>
943 Effect.gen(function* () {
944 yield* Scope.close(scope, Exit.void);
945 yield* fs
946 .remove(agentDeviceConfigPath(config.stateDir, id, path), { force: true })
947 .pipe(Effect.ignore);
948 }),
949 { concurrency: 4, discard: true },
950 );
951 yield* service.withLifecycleLock(
952 Effect.gen(function* () {
953 for (const host of next) {
954 if (configured.has(host.id)) continue;
955 const hostScope = yield* Scope.fork(scope);
956 const instance = yield* SshDeviceHost.make(
957 host,
958 (ready) =>
959 configureAgent(host.id, ready).pipe(
960 Effect.asVoid,
961 Effect.mapError(
962 (error) =>
963 new DeviceHost.DeviceHostError({
964 hostId: host.id,
965 step: "configuring agent access",
966 cause: error,
967 }),
968 ),
969 ),
970 (status, detail) =>
971 service
972 .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })
973 .pipe(Effect.asVoid),
974 ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));
975 hosts.set(host.id, instance);
976 configured.set(host.id, { config: host, scope: hostScope });
977 }
978 yield* service.refreshHosts;
979 }),
980 );
981 });
982 const changes = yield* settings.subscribeChanges;
983 yield* reconcile((yield* settings.getSettings).deviceHosts);
984 yield* changes.pipe(
985 Stream.runForEach((value) => reconcile(value.deviceHosts)),
986 Effect.forkIn(scope),
987 );
988 yield* Effect.addFinalizer(() =>
989 Effect.forEach(configured.values(), (value) => Scope.close(value.scope, Exit.void), {
990 discard: true,
991 concurrency: 4,
992 }),
993 );
994 return {
995 ...service,
996 agentCli: ensureAgentDevice(config.baseDir).pipe(
997 Effect.provideService(FileSystem.FileSystem, fs),
998 Effect.provideService(Path.Path, path),
999 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1000 Effect.map((tool) => tool.entryPath),
1001 Effect.mapError(
1002 (error) =>
1003 new DeviceOperationError({
1004 operation: "install agent CLI",
1005 reason: "command_failed",
1006 cause: error,
1007 }),
1008 ),
1009 ),
1010 };
1011});
1012​
1013export const layer = Layer.effect(DeviceService, make).pipe(Layer.provide(LocalDeviceHost.layer));
1014​
1015/** State stream for WS subscribers: current snapshot first, then every change. */
1016export const stateStream = (service: DeviceService["Service"]): Stream.Stream<DeviceServiceState> =>
1017 Stream.unwrap(
1018 Effect.gen(function* () {
1019 // Subscribe before reading the snapshot so no change between the two
1020 // is lost; the scope lives as long as the stream does.
1021 const subscription = yield* service.subscribe;
1022 const initial = yield* service.state;
1023 return Stream.concat(Stream.make(initial), Stream.fromSubscription(subscription));
1024 }),
1025 ).pipe(Stream.scoped);