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

DeviceService.ts

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