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

DeviceService.ts

1,178 lines44.3 KB

1/**
2 * Device discovery, per-thread device sessions, and the state stream clients
3 * render the Device panel from.
4 *
5 * Discovery and boot go through expo-device-hub's JSON API rather than
6 * shelling out to simctl and adb here: the hub already normalizes both
7 * platforms into one device shape and is the process that has to know a
8 * device is booted before it can stream it. Sessions are the server's own
9 * bookkeeping — which thread is looking at which device — so the panel and
10 * the `device_*` tools agree, and so a `device_open` from an agent surfaces in
11 * every connected client the way `preview_open` does.
12 */
13import {
14 type DeviceActionInput,
15 type DeviceCloseInput,
16 type DeviceConfigureInput,
17 type DeviceDetail,
18 type DeviceDetailInput,
19 type DeviceError,
20 type DeviceHostId,
21 type DeviceId,
22 DeviceBootError,
23 DeviceHostUnavailableError,
24 DeviceNotFoundError,
25 DeviceOperationError,
26 type DeviceOpenInput,
27 type DevicePlatform,
28 DevicePlatformUnavailableError,
29 type DeviceServiceState,
30 type DeviceSession,
31 type DeviceShutdownInput,
32 type DeviceSummary,
33 type SshDeviceHostConfig,
34 type DeviceHostSummary,
35 LOCAL_DEVICE_HOST_ID,
36 type ThreadId,
37} from "@t3tools/contracts";
38import * as FileSystem from "effect/FileSystem";
39import { 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;
101​
102export interface DeviceReadiness extends DeviceHost.DeviceHostReady {
103 readonly hostId: DeviceHostId;
105​
106export interface DeviceAgentReadiness extends DeviceReadiness {
107 readonly agentDevice: DeviceHost.AgentDeviceEndpoint;
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;
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* new DeviceOperationError({
910 operation: "update device tool",
911 reason: "request_failed",
912 cause: new Error("Tool installation is unavailable in this device service."),
913 });
914 yield* installTool(tool);
915 return yield* inspect;
916 }),
917 ),
918 retryHost,
919 inspect,
920 agentCli: Effect.fail(
921 new DeviceHostUnavailableError({
922 hostId: LOCAL_DEVICE_HOST_ID,
923 reason: "Agent CLI installation is unavailable in this device service.",
924 }),
925 ),
926 agentTarget: (input) =>
927 Effect.gen(function* () {
928 const host = yield* resolveHost(input.hostId);
929 const ready = yield* agentReadinessIfSupported(input.hostId);
930 if (!ready)
931 return yield* new DeviceHostUnavailableError({
932 hostId: input.hostId,
933 reason:
934 "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
935 });
936 const configPath = yield* lifecycleLock.withPermit(
937 Effect.gen(function* () {
938 if (hosts.get(host.id) !== host)
939 return yield* new DeviceHostUnavailableError({
940 hostId: host.id,
941 reason: "Host configuration changed. Retry the operation.",
942 });
943 return yield* configureAgent(input.hostId, ready);
944 }),
945 );
946 return [
947 "--config",
948 configPath,
949 "--session",
950 agentDeviceSession(input.threadId, input.hostId, input.deviceId),
951 ];
952 }),
953 state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
954 subscribe: PubSub.subscribe(statePubSub),
955 configure,
956 list,
957 open,
958 close,
959 shutdown,
960 detail,
961 action,
962 screenshot,
963 readiness,
964 readinessIfSupported,
965 agentReadinessIfSupported,
966 currentReadiness,
967 sessionsForThread,
968 }),
969 setHostStatus,
970 withLifecycleLock: lifecycleLock.withPermit,
971 refreshHosts: Effect.gen(function* () {
972 const summaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
973 const unchanged = (id: DeviceHostId) =>
974 hosts.has(id) && hosts.get(id) === publishedHosts.get(id);
975 yield* publish((state) => ({
976 ...state,
977 hosts: summaries,
978 hostStatuses: Object.fromEntries(
979 Object.entries(state.hostStatuses).filter(([id]) => unchanged(id)),
980 ),
981 devices: state.devices.filter((device) => unchanged(device.hostId)),
982 sessions: state.sessions.filter((session) => unchanged(session.hostId)),
983 }));
984 publishedHosts = new Map(hosts);
985 }),
986 };
987});
988​
989/** @public Service construction is part of the canonical Effect module API. */
990export const make = Effect.gen(function* () {
991 const localHost = yield* DeviceHost.DeviceHost;
992 const config = yield* ServerConfig.ServerConfig;
993 const fs = yield* FileSystem.FileSystem;
994 const path = yield* Path.Path;
995 const runner = yield* ProcessRunner.ProcessRunner;
996 const settings = yield* ServerSettings.ServerSettingsService;
997 const scope = yield* Scope.Scope;
998 const hosts = new Map<DeviceHostId, DeviceHost.DeviceHost["Service"]>([
999 [localHost.id, localHost],
1000 ]);
1001 const configureAgent = (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) => {
1002 const file = agentDeviceConfigPath(config.stateDir, hostId, path);
1003 return writeAgentDeviceConfig(file, ready.agentDevice).pipe(
1004 Effect.provideService(FileSystem.FileSystem, fs),
1005 Effect.provideService(Path.Path, path),
1006 Effect.mapError(
1007 (cause) =>
1008 new DeviceOperationError({
1009 operation: "configure agent",
1010 reason: "settings_failed",
1011 cause,
1012 }),
1013 ),
1014 Effect.as(file),
1015 );
1016 };
1017 const probeContext =
1018 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();
1019 const localTargetContext =
1020 yield* Effect.context<Effect.Services<ReturnType<typeof isLocalSshDeviceHost>>>();
1021 const service = yield* makeWithHosts(
1022 hosts,
1023 (host) =>
1024 Effect.gen(function* () {
1025 if (yield* isLocalSshDeviceHost(host).pipe(Effect.provide(localTargetContext))) {
1026 return yield* localHost.summary;
1028 return yield* SshDeviceHost.probe(host).pipe(Effect.provide(probeContext));
1029 }).pipe(
1030 Effect.mapError(
1031 (error) =>
1032 new DeviceOperationError({
1033 operation: "probe host",
1034 reason: "request_failed",
1035 cause: error,
1036 }),
1037 ),
1038 ),
1039 configureAgent,
1040 (tool) =>
1041 (tool === "hub" ? ensureDeviceHub(config.baseDir) : ensureAgentDevice(config.baseDir)).pipe(
1042 Effect.provideService(FileSystem.FileSystem, fs),
1043 Effect.provideService(Path.Path, path),
1044 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1045 Effect.mapError(
1046 (cause) =>
1047 new DeviceOperationError({
1048 operation: "update device tool",
1049 reason: "command_failed",
1050 cause,
1051 }),
1052 ),
1053 ),
1054 );
1055 const hostContext =
1056 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
1057 const configured = new Map<string, { config: SshDeviceHostConfig; scope: Scope.Closeable }>();
1058 const reconcile = (configuredHosts: ReadonlyArray<SshDeviceHostConfig>) =>
1059 Effect.gen(function* () {
1060 const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(
1061 Effect.provide(localTargetContext),
1062 );
1063 const removed = yield* service.withLifecycleLock(
1064 Effect.gen(function* () {
1065 const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
1066 for (const [id, previous] of configured) {
1067 if (
1068 next.some(
1069 (host) =>
1070 host.id === id &&
1071 host.label === previous.config.label &&
1072 host.target === previous.config.target &&
1073 host.port === previous.config.port &&
1074 host.identityFile === previous.config.identityFile,
1077 continue;
1078 hosts.delete(id);
1079 configured.delete(id);
1080 removed.push({ id, scope: previous.scope });
1082 yield* service.refreshHosts;
1083 return removed;
1084 }),
1085 );
1086 // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.
1087 yield* Effect.forEach(
1088 removed,
1089 ({ id, scope }) =>
1090 Effect.gen(function* () {
1091 yield* Scope.close(scope, Exit.void);
1092 yield* fs
1093 .remove(agentDeviceConfigPath(config.stateDir, id, path), { force: true })
1094 .pipe(Effect.ignore);
1095 }),
1096 { concurrency: 4, discard: true },
1097 );
1098 yield* service.withLifecycleLock(
1099 Effect.gen(function* () {
1100 for (const host of next) {
1101 if (configured.has(host.id)) continue;
1102 const hostScope = yield* Scope.fork(scope);
1103 const instance = yield* SshDeviceHost.make(
1104 host,
1105 (ready) =>
1106 configureAgent(host.id, ready).pipe(
1107 Effect.asVoid,
1108 Effect.mapError(
1109 (error) =>
1110 new DeviceHost.DeviceHostError({
1111 hostId: host.id,
1112 step: "configuring agent access",
1113 cause: error,
1114 }),
1115 ),
1116 ),
1117 (status, detail) =>
1118 service
1119 .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })
1120 .pipe(Effect.asVoid),
1121 ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));
1122 hosts.set(host.id, instance);
1123 configured.set(host.id, { config: host, scope: hostScope });
1125 yield* service.refreshHosts;
1126 }),
1127 );
1128 });
1129 const changes = yield* settings.subscribeChanges;
1130 yield* reconcile((yield* settings.getSettings).deviceHosts);
1131 yield* changes.pipe(
1132 Stream.runForEach((value) => reconcile(value.deviceHosts)),
1133 Effect.forkIn(scope),
1134 );
1135 yield* Effect.addFinalizer(() =>
1136 Effect.forEach(configured.values(), (value) => Scope.close(value.scope, Exit.void), {
1137 discard: true,
1138 concurrency: 4,
1139 }),
1140 );
1141 return {
1142 ...service,
1143 agentCli: resolveNodeExecutable("Device automation").pipe(
1144 Effect.andThen(ensureAgentDevice(config.baseDir)),
1145 Effect.provideService(FileSystem.FileSystem, fs),
1146 Effect.provideService(Path.Path, path),
1147 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1148 Effect.map((tool) => tool.entryPath),
1149 Effect.mapError((error) =>
1150 error._tag === "NodeRuntimeUnavailableError"
1151 ? new DeviceHostUnavailableError({
1152 hostId: LOCAL_DEVICE_HOST_ID,
1153 reason: nodeRuntimeUnavailableMessage("Device automation"),
1154 cause: error,
1155 })
1156 : new DeviceOperationError({
1157 operation: "install agent CLI",
1158 reason: "command_failed",
1159 cause: error,
1160 }),
1161 ),
1162 ),
1163 };
1164});
1165​
1166export const layer = Layer.effect(DeviceService, make).pipe(Layer.provide(LocalDeviceHost.layer));
1167​
1168/** State stream for WS subscribers: current snapshot first, then every change. */
1169export const stateStream = (service: DeviceService["Service"]): Stream.Stream<DeviceServiceState> =>
1170 Stream.unwrap(
1171 Effect.gen(function* () {
1172 // Subscribe before reading the snapshot so no change between the two
1173 // is lost; the scope lives as long as the stream does.
1174 const subscription = yield* service.subscribe;
1175 const initial = yield* service.state;
1176 return Stream.concat(Stream.make(initial), Stream.fromSubscription(subscription));
1177 }),
1178 ).pipe(Stream.scoped);