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

DeviceService.ts

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