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