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

DeviceService.ts

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