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