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