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

DeviceService.ts

1,164 lines43.4 KB

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