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 yield* HttpClientRequest.post(`${ready.hub.origin}/api/devices/shutdown`).pipe(
674 HttpClientRequest.bodyJson({ platform, id: deviceId }),
675 Effect.mapError(
676 (cause) =>
677 new DeviceOperationError({ operation: "shutdown", reason: "invalid_payload", cause }),
678 ),
679 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")),
680 Effect.flatMap((result) =>
681 result.ok
682 ? Effect.void
683 : Effect.fail(
684 new DeviceOperationError({
685 operation: "shutdown",
686 reason: "hub_rejected",
687 cause: result,
688 }),
689 ),
690 ),
691 );
692 yield* publish((state) => ({
693 ...state,
694 devices: state.devices.map((device) =>
695 device.hostId === ready.hostId && device.id === deviceId
696 ? { ...device, booted: false }
697 : device,
698 ),
699 sessions: state.sessions.filter(
700 (session) => !(session.hostId === ready.hostId && session.deviceId === deviceId),
701 ),
702 }));
703 // Discovery can stall while an emulator saves its snapshot. A failed
704 // refresh must not turn an accepted shutdown into an action failure.
705 yield* refresh(ready).pipe(
706 Effect.catch((cause) =>
707 Effect.logWarning("Device discovery unavailable after shutdown", { cause }),
708 ),
709 );
710 });
711
712 const close: DeviceService["Service"]["close"] = Effect.fn("DeviceService.close")(
713 function* (input) {
714 const { state } = yield* SynchronizedRef.get(stateRef);
715 const closing = state.sessions.filter(
716 (session) =>
717 session.threadId === input.threadId &&
718 (input.hostId === undefined || session.hostId === input.hostId) &&
719 (input.deviceId === undefined || session.deviceId === input.deviceId),
720 );
721 if (closing.length === 0) return;
722 yield* publish((current) => ({
723 ...current,
724 sessions: current.sessions.filter((session) => !closing.includes(session)),
725 }));
726 if (input.shutdown) {
727 yield* Effect.forEach(
728 closing,
729 (session) => shutdownDevice(session.hostId, session.deviceId, session.platform),
730 { discard: true },
731 );
732 }
733 },
734 );
735
736 const shutdown: DeviceService["Service"]["shutdown"] = Effect.fn("DeviceService.shutdown")(
737 function* (input) {
738 const host = yield* resolveHost(input.hostId);
739 yield* shutdownDevice(host.id, input.deviceId, input.platform);
740 // Sessions on a powered-off device are stale in every thread.
741 yield* publish((current) => ({
742 ...current,
743 sessions: current.sessions.filter(
744 (session) => !(session.hostId === host.id && session.deviceId === input.deviceId),
745 ),
746 }));
747 },
748 );
749
750 const screenshot: DeviceService["Service"]["screenshot"] = Effect.fn("DeviceService.screenshot")(
751 function* (input) {
752 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
753 const url = `${ready.hub.origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`;
754 const png = yield* httpClient.execute(HttpClientRequest.post(url)).pipe(
755 Effect.flatMap(HttpClientResponse.filterStatusOk),
756 Effect.flatMap((response) => response.arrayBuffer),
757 Effect.map((buffer) => new Uint8Array(buffer)),
758 Effect.scoped,
759 Effect.timeout(SCREENSHOT_TIMEOUT),
760 Effect.mapError(
761 (cause) =>
762 new DeviceOperationError({
763 operation: "screenshot",
764 reason: "request_failed",
765 cause,
766 }),
767 ),
768 );
769 return { device, png };
770 },
771 );
772
773 const resolveDevice = Effect.fn("DeviceService.resolveDevice")(function* (
774 hostId: DeviceHostId | undefined,
775 deviceId: DeviceId,
776 ) {
777 const host = yield* resolveHost(hostId);
778 const ready = yield* readiness(host.id);
779 const { state } = yield* SynchronizedRef.get(stateRef);
780 const device =
781 findDevice(state, host.id, deviceId) ?? findDevice(yield* refresh(ready), host.id, deviceId);
782 if (!device) return yield* new DeviceNotFoundError({ hostId: host.id, deviceId });
783 return { ready, device };
784 });
785
786 const detail: DeviceService["Service"]["detail"] = Effect.fn("DeviceService.detail")(
787 function* (input) {
788 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
789 const read = yield* readDeviceDetail(ready, device.platform, device.id);
790 return {
791 hostId: ready.hostId,
792 deviceId: device.id,
793 settings: read.settings,
794 foregroundApp: read.foregroundApp,
795 readAt: DateTime.formatIso(yield* DateTime.now),
796 };
797 },
798 );
799
800 const action: DeviceService["Service"]["action"] = Effect.fn("DeviceService.action")(
801 function* (input) {
802 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
803 yield* runDeviceAction(ready, device.platform, input);
804 return yield* detail({ hostId: ready.hostId, deviceId: device.id });
805 },
806 );
807
808 const sessionsForThread: DeviceService["Service"]["sessionsForThread"] = (threadId) =>
809 SynchronizedRef.get(stateRef).pipe(
810 Effect.map(({ state }) => state.sessions.filter((session) => session.threadId === threadId)),
811 );
812
813 return {
814 ...DeviceService.of({
815 testHost,
816 agentCli: Effect.fail(
817 new DeviceHostUnavailableError({
818 hostId: LOCAL_DEVICE_HOST_ID,
819 reason: "Agent CLI installation is unavailable in this device service.",
820 }),
821 ),
822 agentTarget: (input) =>
823 Effect.gen(function* () {
824 const host = yield* resolveHost(input.hostId);
825 const ready = yield* agentReadinessIfSupported(input.hostId);
826 if (!ready)
827 return yield* new DeviceHostUnavailableError({
828 hostId: input.hostId,
829 reason:
830 "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
831 });
832 const configPath = yield* lifecycleLock.withPermit(
833 Effect.gen(function* () {
834 if (hosts.get(host.id) !== host)
835 return yield* new DeviceHostUnavailableError({
836 hostId: host.id,
837 reason: "Host configuration changed. Retry the operation.",
838 });
839 return yield* configureAgent(input.hostId, ready);
840 }),
841 );
842 return [
843 "--config",
844 configPath,
845 "--session",
846 agentDeviceSession(input.threadId, input.hostId, input.deviceId),
847 ];
848 }),
849 state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
850 subscribe: PubSub.subscribe(statePubSub),
851 configure,
852 list,
853 open,
854 close,
855 shutdown,
856 detail,
857 action,
858 screenshot,
859 readiness,
860 readinessIfSupported,
861 agentReadinessIfSupported,
862 currentReadiness,
863 sessionsForThread,
864 }),
865 setHostStatus,
866 withLifecycleLock: lifecycleLock.withPermit,
867 refreshHosts: Effect.gen(function* () {
868 const summaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
869 const unchanged = (id: DeviceHostId) =>
870 hosts.has(id) && hosts.get(id) === publishedHosts.get(id);
871 yield* publish((state) => ({
872 ...state,
873 hosts: summaries,
874 hostStatuses: Object.fromEntries(
875 Object.entries(state.hostStatuses).filter(([id]) => unchanged(id)),
876 ),
877 devices: state.devices.filter((device) => unchanged(device.hostId)),
878 sessions: state.sessions.filter((session) => unchanged(session.hostId)),
879 }));
880 publishedHosts = new Map(hosts);
881 }),
882 };
883});
884
885/** @public Service construction is part of the canonical Effect module API. */
886export const make = Effect.gen(function* () {
887 const localHost = yield* DeviceHost.DeviceHost;
888 const config = yield* ServerConfig.ServerConfig;
889 const fs = yield* FileSystem.FileSystem;
890 const path = yield* Path.Path;
891 const runner = yield* ProcessRunner.ProcessRunner;
892 const settings = yield* ServerSettings.ServerSettingsService;
893 const scope = yield* Scope.Scope;
894 const hosts = new Map<DeviceHostId, DeviceHost.DeviceHost["Service"]>([
895 [localHost.id, localHost],
896 ]);
897 const configureAgent = (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) => {
898 const file = agentDeviceConfigPath(config.stateDir, hostId, path);
899 return writeAgentDeviceConfig(file, ready.agentDevice).pipe(
900 Effect.provideService(FileSystem.FileSystem, fs),
901 Effect.provideService(Path.Path, path),
902 Effect.mapError(
903 (cause) =>
904 new DeviceOperationError({
905 operation: "configure agent",
906 reason: "settings_failed",
907 cause,
908 }),
909 ),
910 Effect.as(file),
911 );
912 };
913 const probeContext =
914 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();
915 const localTargetContext =
916 yield* Effect.context<Effect.Services<ReturnType<typeof isLocalSshDeviceHost>>>();
917 const service = yield* makeWithHosts(
918 hosts,
919 (host) =>
920 Effect.gen(function* () {
921 if (yield* isLocalSshDeviceHost(host).pipe(Effect.provide(localTargetContext))) {
922 return yield* localHost.summary;
923 }
924 return yield* SshDeviceHost.probe(host).pipe(Effect.provide(probeContext));
925 }).pipe(
926 Effect.mapError(
927 (error) =>
928 new DeviceOperationError({
929 operation: "probe host",
930 reason: "request_failed",
931 cause: error,
932 }),
933 ),
934 ),
935 configureAgent,
936 );
937 const hostContext =
938 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
939 const configured = new Map<string, { config: SshDeviceHostConfig; scope: Scope.Closeable }>();
940 const reconcile = (configuredHosts: ReadonlyArray<SshDeviceHostConfig>) =>
941 Effect.gen(function* () {
942 const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(
943 Effect.provide(localTargetContext),
944 );
945 const removed = yield* service.withLifecycleLock(
946 Effect.gen(function* () {
947 const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
948 for (const [id, previous] of configured) {
949 if (
950 next.some(
951 (host) =>
952 host.id === id &&
953 host.label === previous.config.label &&
954 host.target === previous.config.target &&
955 host.port === previous.config.port &&
956 host.identityFile === previous.config.identityFile,
957 )
958 )
959 continue;
960 hosts.delete(id);
961 configured.delete(id);
962 removed.push({ id, scope: previous.scope });
963 }
964 yield* service.refreshHosts;
965 return removed;
966 }),
967 );
968 // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.
969 yield* Effect.forEach(
970 removed,
971 ({ id, scope }) =>
972 Effect.gen(function* () {
973 yield* Scope.close(scope, Exit.void);
974 yield* fs
975 .remove(agentDeviceConfigPath(config.stateDir, id, path), { force: true })
976 .pipe(Effect.ignore);
977 }),
978 { concurrency: 4, discard: true },
979 );
980 yield* service.withLifecycleLock(
981 Effect.gen(function* () {
982 for (const host of next) {
983 if (configured.has(host.id)) continue;
984 const hostScope = yield* Scope.fork(scope);
985 const instance = yield* SshDeviceHost.make(
986 host,
987 (ready) =>
988 configureAgent(host.id, ready).pipe(
989 Effect.asVoid,
990 Effect.mapError(
991 (error) =>
992 new DeviceHost.DeviceHostError({
993 hostId: host.id,
994 step: "configuring agent access",
995 cause: error,
996 }),
997 ),
998 ),
999 (status, detail) =>
1000 service
1001 .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })
1002 .pipe(Effect.asVoid),
1003 ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));
1004 hosts.set(host.id, instance);
1005 configured.set(host.id, { config: host, scope: hostScope });
1006 }
1007 yield* service.refreshHosts;
1008 }),
1009 );
1010 });
1011 const changes = yield* settings.subscribeChanges;
1012 yield* reconcile((yield* settings.getSettings).deviceHosts);
1013 yield* changes.pipe(
1014 Stream.runForEach((value) => reconcile(value.deviceHosts)),
1015 Effect.forkIn(scope),
1016 );
1017 yield* Effect.addFinalizer(() =>
1018 Effect.forEach(configured.values(), (value) => Scope.close(value.scope, Exit.void), {
1019 discard: true,
1020 concurrency: 4,
1021 }),
1022 );
1023 return {
1024 ...service,
1025 agentCli: resolveNodeExecutable("Device automation").pipe(
1026 Effect.flatMap(() => ensureAgentDevice(config.baseDir)),
1027 Effect.provideService(FileSystem.FileSystem, fs),
1028 Effect.provideService(Path.Path, path),
1029 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1030 Effect.map((tool) => tool.entryPath),
1031 Effect.mapError((error) =>
1032 error._tag === "NodeRuntimeUnavailableError"
1033 ? new DeviceHostUnavailableError({
1034 hostId: LOCAL_DEVICE_HOST_ID,
1035 reason: nodeRuntimeUnavailableMessage("Device automation"),
1036 cause: error,
1037 })
1038 : new DeviceOperationError({
1039 operation: "install agent CLI",
1040 reason: "command_failed",
1041 cause: error,
1042 }),
1043 ),
1044 ),
1045 };
1046});
1047
1048export const layer = Layer.effect(DeviceService, make).pipe(Layer.provide(LocalDeviceHost.layer));
1049
1050/** State stream for WS subscribers: current snapshot first, then every change. */
1051export const stateStream = (service: DeviceService["Service"]): Stream.Stream<DeviceServiceState> =>
1052 Stream.unwrap(
1053 Effect.gen(function* () {
1054 // Subscribe before reading the snapshot so no change between the two
1055 // is lost; the scope lives as long as the stream does.
1056 const subscription = yield* service.subscribe;
1057 const initial = yield* service.state;
1058 return Stream.concat(Stream.make(initial), Stream.fromSubscription(subscription));
1059 }),
1060 ).pipe(Stream.scoped);