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.platform === "android" && !device.physical) {
675 // Resolve the override on the device host the way its hub does.
676 const encoders = yield* ready.run(ready.nodePath, [
677 "-e",
678 `const { spawnSync } = require("node:child_process");
679const result = spawnSync(process.env.SERVE_EMU_FFMPEG?.trim() || "ffmpeg", ["-hide_banner", "-encoders"], {
680 stdio: "inherit", timeout: 10000, killSignal: "SIGKILL",
681});
682process.exitCode = result.error ? 1 : (result.status ?? 1);`,
683 ]);
684 if (encoders.code !== 0) {
685 return yield* new DevicePlatformUnavailableError({
686 hostId: host.id,
687 platform: "android",
688 reason:
689 "Android emulator video needs working ffmpeg with the libx264 encoder. Install it on the device host's PATH or set SERVE_EMU_FFMPEG there, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
690 });
691 }
692 if (!/^\s*V\S*[ \t]+libx264(?:[ \t]|$)/m.test(`${encoders.stdout}\n${encoders.stderr}`)) {
693 return yield* new DevicePlatformUnavailableError({
694 hostId: host.id,
695 platform: "android",
696 reason:
697 "Android emulator video needs the libx264 encoder. Install an ffmpeg build that includes libx264 on the device host, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
698 });
699 }
700 }
701 if (!device.booted && input.boot !== false) {
702 const booting = { ...device, threadId: input.threadId };
703 yield* publish((current) => ({
704 ...current,
705 bootingDevices: [
706 ...(current.bootingDevices ?? []).filter(
707 (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
708 ),
709 booting,
710 ],
711 }));
712 const bootedId = yield* boot(ready, device).pipe(
713 Effect.ensuring(
714 publish((current) => ({
715 ...current,
716 bootingDevices: (current.bootingDevices ?? []).filter(
717 (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
718 ),
719 })),
720 ),
721 );
722 state = yield* refresh(ready);
723 device = findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id);
724 if (!device) {
725 return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });
726 }
727 } else if (device.platform === "ios" && device.booted) {
728 yield* HttpClientRequest.post(
729 `${ready.hub.origin}${vendorPrefix("ios")}/grid/api/start`,
730 ).pipe(
731 HttpClientRequest.bodyJson({ udid: device.id }),
732 Effect.mapError(
733 (cause) =>
734 new DeviceOperationError({ operation: "open", reason: "invalid_payload", cause }),
735 ),
736 Effect.flatMap((request) =>
737 hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT),
738 ),
739 );
740 }
741 if (hosts.get(host.id) !== host)
742 return yield* new DeviceHostUnavailableError({
743 hostId: host.id,
744 reason: "Host configuration changed. Retry the operation.",
745 });
746 const openedAt = DateTime.formatIso(yield* DateTime.now);
747 const session: DeviceSession = {
748 threadId: input.threadId,
749 hostId: host.id,
750 deviceId: device.id,
751 platform: device.platform,
752 openedAt,
753 };
754 yield* lifecycleLock.withPermit(
755 Effect.gen(function* () {
756 if (!(yield* readDeviceSettings).enabled)
757 return yield* new DeviceHostUnavailableError({
758 hostId: host.id,
759 reason: "Device support was turned off while the device was opening.",
760 });
761 yield* publish((current) => ({
762 ...current,
763 sessions: [
764 ...current.sessions.filter(
765 (existing) =>
766 !(
767 existing.threadId === session.threadId &&
768 existing.hostId === session.hostId &&
769 existing.deviceId === session.deviceId
770 ),
771 ),
772 session,
773 ],
774 }));
775 }),
776 );
777 return session;
778 });
779
780 const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* (
781 hostId: DeviceHostId,
782 deviceId: DeviceId,
783 platform: DevicePlatform,
784 ) {
785 const ready = yield* readiness(hostId);
786 const postShutdown = (path: string, body: Record<string, string>) =>
787 HttpClientRequest.post(`${ready.hub.origin}${path}`).pipe(
788 HttpClientRequest.bodyJson(body),
789 Effect.mapError(
790 (cause) =>
791 new DeviceOperationError({ operation: "shutdown", reason: "invalid_payload", cause }),
792 ),
793 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")),
794 Effect.flatMap((result) =>
795 result.ok
796 ? Effect.void
797 : Effect.fail(
798 new DeviceOperationError({
799 operation: "shutdown",
800 reason: "hub_rejected",
801 cause: result,
802 }),
803 ),
804 ),
805 );
806 // serve-sim's shutdown closes its in-process capture session before it runs
807 // `simctl shutdown`; the hub's generic shutdown can leave that session cached
808 // across a reboot. serve-sim runs simctl bare, though, so a simulator that is
809 // already off fails there.
810 yield* platform === "ios"
811 ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: deviceId }).pipe(
812 Effect.catch((cause) =>
813 fetchDevices(ready).pipe(
814 Effect.flatMap(({ devices }) =>
815 devices.find((device) => device.id === deviceId)?.booted === false
816 ? Effect.logInfo("iOS simulator was already shut down", { deviceId })
817 : Effect.fail(cause),
818 ),
819 ),
820 ),
821 )
822 : postShutdown("/api/devices/shutdown", { platform, id: deviceId });
823 yield* publish((state) => ({
824 ...state,
825 devices: state.devices.map((device) =>
826 device.hostId === ready.hostId && device.id === deviceId
827 ? { ...device, booted: false }
828 : device,
829 ),
830 sessions: state.sessions.filter(
831 (session) => !(session.hostId === ready.hostId && session.deviceId === deviceId),
832 ),
833 }));
834 // Discovery can stall while an emulator saves its snapshot. A failed
835 // refresh must not turn an accepted shutdown into an action failure.
836 yield* refresh(ready).pipe(
837 Effect.catch((cause) =>
838 Effect.logWarning("Device discovery unavailable after shutdown", { cause }),
839 ),
840 );
841 });
842
843 const close: DeviceService["Service"]["close"] = Effect.fn("DeviceService.close")(
844 function* (input) {
845 const { state } = yield* SynchronizedRef.get(stateRef);
846 const closing = state.sessions.filter(
847 (session) =>
848 session.threadId === input.threadId &&
849 (input.hostId === undefined || session.hostId === input.hostId) &&
850 (input.deviceId === undefined || session.deviceId === input.deviceId),
851 );
852 if (closing.length === 0) return;
853 yield* publish((current) => ({
854 ...current,
855 sessions: current.sessions.filter((session) => !closing.includes(session)),
856 }));
857 if (input.shutdown) {
858 yield* Effect.forEach(
859 closing,
860 (session) => shutdownDevice(session.hostId, session.deviceId, session.platform),
861 { discard: true },
862 );
863 }
864 },
865 );
866
867 const shutdown: DeviceService["Service"]["shutdown"] = Effect.fn("DeviceService.shutdown")(
868 function* (input) {
869 const host = yield* resolveHost(input.hostId);
870 yield* shutdownDevice(host.id, input.deviceId, input.platform);
871 yield* publish((current) => ({
872 ...current,
873 sessions: current.sessions.filter(
874 (session) => !(session.hostId === host.id && session.deviceId === input.deviceId),
875 ),
876 }));
877 },
878 );
879
880 const screenshot: DeviceService["Service"]["screenshot"] = Effect.fn("DeviceService.screenshot")(
881 function* (input) {
882 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
883 const url = `${ready.hub.origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`;
884 const png = yield* httpClient.execute(HttpClientRequest.post(url)).pipe(
885 Effect.flatMap(HttpClientResponse.filterStatusOk),
886 Effect.flatMap((response) => response.arrayBuffer),
887 Effect.map((buffer) => new Uint8Array(buffer)),
888 Effect.scoped,
889 Effect.timeout(SCREENSHOT_TIMEOUT),
890 Effect.mapError(
891 (cause) =>
892 new DeviceOperationError({
893 operation: "screenshot",
894 reason: "request_failed",
895 cause,
896 }),
897 ),
898 );
899 return { device, png };
900 },
901 );
902
903 const resolveDevice = Effect.fn("DeviceService.resolveDevice")(function* (
904 hostId: DeviceHostId | undefined,
905 deviceId: DeviceId,
906 ) {
907 const host = yield* resolveHost(hostId);
908 const ready = yield* readiness(host.id);
909 const { state } = yield* SynchronizedRef.get(stateRef);
910 const device =
911 findDevice(state, host.id, deviceId) ?? findDevice(yield* refresh(ready), host.id, deviceId);
912 if (!device) return yield* new DeviceNotFoundError({ hostId: host.id, deviceId });
913 return { ready, device };
914 });
915
916 const detail: DeviceService["Service"]["detail"] = Effect.fn("DeviceService.detail")(
917 function* (input) {
918 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
919 const read = yield* readDeviceDetail(ready, device.platform, device.id);
920 return {
921 hostId: ready.hostId,
922 deviceId: device.id,
923 settings: read.settings,
924 foregroundApp: read.foregroundApp,
925 readAt: DateTime.formatIso(yield* DateTime.now),
926 };
927 },
928 );
929
930 const action: DeviceService["Service"]["action"] = Effect.fn("DeviceService.action")(
931 function* (input) {
932 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
933 yield* runDeviceAction(ready, device.platform, input);
934 return yield* detail({ hostId: ready.hostId, deviceId: device.id });
935 },
936 );
937
938 const sessionsForThread: DeviceService["Service"]["sessionsForThread"] = (threadId) =>
939 SynchronizedRef.get(stateRef).pipe(
940 Effect.map(({ state }) => state.sessions.filter((session) => session.threadId === threadId)),
941 );
942
943 return {
944 ...DeviceService.of({
945 testHost,
946 updateTool: (tool) =>
947 lifecycleLock.withPermit(
948 Effect.gen(function* () {
949 if (!installTool)
950 return yield* new DeviceOperationError({
951 operation: "update device tool",
952 reason: "request_failed",
953 cause: new Error("Tool installation is unavailable in this device service."),
954 });
955 yield* installTool(tool);
956 return yield* inspect;
957 }),
958 ),
959 retryHost,
960 inspect,
961 agentCli: Effect.fail(
962 new DeviceHostUnavailableError({
963 hostId: LOCAL_DEVICE_HOST_ID,
964 reason: "Agent CLI installation is unavailable in this device service.",
965 }),
966 ),
967 agentTarget: (input) =>
968 Effect.gen(function* () {
969 const host = yield* resolveHost(input.hostId);
970 const ready = yield* agentReadinessIfSupported(input.hostId);
971 if (!ready)
972 return yield* new DeviceHostUnavailableError({
973 hostId: input.hostId,
974 reason:
975 "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
976 });
977 const configPath = yield* lifecycleLock.withPermit(
978 Effect.gen(function* () {
979 if (hosts.get(host.id) !== host)
980 return yield* new DeviceHostUnavailableError({
981 hostId: host.id,
982 reason: "Host configuration changed. Retry the operation.",
983 });
984 return yield* configureAgent(input.hostId, ready);
985 }),
986 );
987 const session = yield* agentDeviceSession(
988 input.threadId,
989 input.hostId,
990 input.deviceId,
991 ).pipe(Effect.provideService(Crypto.Crypto, crypto));
992 return ["--config", configPath, "--session", session];
993 }),
994 state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
995 subscribe: PubSub.subscribe(statePubSub),
996 configure,
997 list,
998 open,
999 close,
1000 shutdown,
1001 detail,
1002 action,
1003 screenshot,
1004 readiness,
1005 readinessIfSupported,
1006 agentReadinessIfSupported,
1007 currentReadiness,
1008 sessionsForThread,
1009 }),
1010 setHostStatus,
1011 withLifecycleLock: lifecycleLock.withPermit,
1012 refreshHosts: Effect.gen(function* () {
1013 const summaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
1014 const unchanged = (id: DeviceHostId) =>
1015 hosts.has(id) && hosts.get(id) === publishedHosts.get(id);
1016 yield* publish((state) => ({
1017 ...state,
1018 hosts: summaries,
1019 hostStatuses: Object.fromEntries(
1020 Object.entries(state.hostStatuses).filter(([id]) => unchanged(id)),
1021 ),
1022 devices: state.devices.filter((device) => unchanged(device.hostId)),
1023 sessions: state.sessions.filter((session) => unchanged(session.hostId)),
1024 }));
1025 publishedHosts = new Map(hosts);
1026 }),
1027 };
1028});
1029
1030/** @public */
1031/** @public Service construction is part of the canonical Effect module API. */
1032export const make = Effect.gen(function* () {
1033 const localHost = yield* DeviceHost.DeviceHost;
1034 const config = yield* ServerConfig.ServerConfig;
1035 const fs = yield* FileSystem.FileSystem;
1036 const path = yield* Path.Path;
1037 const runner = yield* ProcessRunner.ProcessRunner;
1038 const settings = yield* ServerSettings.ServerSettingsService;
1039 const scope = yield* Scope.Scope;
1040 const hosts = new Map<DeviceHostId, DeviceHost.DeviceHost["Service"]>([
1041 [localHost.id, localHost],
1042 ]);
1043 const crypto = yield* Crypto.Crypto;
1044 const configPath = (hostId: DeviceHostId) =>
1045 agentDeviceConfigPath(config.stateDir, hostId, path).pipe(
1046 Effect.provideService(Crypto.Crypto, crypto),
1047 );
1048 const configureAgent = (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) =>
1049 Effect.gen(function* () {
1050 const file = yield* configPath(hostId);
1051 yield* writeAgentDeviceConfig(file, ready.agentDevice);
1052 return file;
1053 }).pipe(
1054 Effect.provideService(FileSystem.FileSystem, fs),
1055 Effect.provideService(Path.Path, path),
1056 Effect.mapError(
1057 (cause) =>
1058 new DeviceOperationError({
1059 operation: "configure agent",
1060 reason: "settings_failed",
1061 cause,
1062 }),
1063 ),
1064 );
1065 const probeContext =
1066 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();
1067 const localTargetContext =
1068 yield* Effect.context<Effect.Services<ReturnType<typeof isLocalSshDeviceHost>>>();
1069 const service = yield* makeWithHosts(
1070 hosts,
1071 (host) =>
1072 Effect.gen(function* () {
1073 if (yield* isLocalSshDeviceHost(host).pipe(Effect.provide(localTargetContext))) {
1074 return yield* localHost.summary;
1075 }
1076 return yield* SshDeviceHost.probe(host).pipe(Effect.provide(probeContext));
1077 }).pipe(
1078 Effect.mapError(
1079 (error) =>
1080 new DeviceOperationError({
1081 operation: "probe host",
1082 reason: "request_failed",
1083 cause: error,
1084 }),
1085 ),
1086 ),
1087 configureAgent,
1088 (tool) =>
1089 (tool === "hub" ? ensureDeviceHub(config.baseDir) : ensureAgentDevice(config.baseDir)).pipe(
1090 Effect.provideService(FileSystem.FileSystem, fs),
1091 Effect.provideService(Path.Path, path),
1092 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1093 Effect.mapError(
1094 (cause) =>
1095 new DeviceOperationError({
1096 operation: "update device tool",
1097 reason: "command_failed",
1098 // Only the exit code goes into the shown message; npm's stderr can carry registry credentials.
1099 ...(cause.exitCode !== undefined ? { exitCode: cause.exitCode } : {}),
1100 cause,
1101 }),
1102 ),
1103 ),
1104 );
1105 const hostContext =
1106 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
1107 const configured = new Map<string, { config: SshDeviceHostConfig; scope: Scope.Closeable }>();
1108 const reconcile = (configuredHosts: ReadonlyArray<SshDeviceHostConfig>) =>
1109 Effect.gen(function* () {
1110 const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(
1111 Effect.provide(localTargetContext),
1112 );
1113 const removed = yield* service.withLifecycleLock(
1114 Effect.gen(function* () {
1115 const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
1116 for (const [id, previous] of configured) {
1117 if (
1118 next.some(
1119 (host) =>
1120 host.id === id &&
1121 host.label === previous.config.label &&
1122 host.target === previous.config.target &&
1123 host.port === previous.config.port &&
1124 host.identityFile === previous.config.identityFile,
1125 )
1126 )
1127 continue;
1128 hosts.delete(id);
1129 configured.delete(id);
1130 removed.push({ id, scope: previous.scope });
1131 }
1132 if (removed.length > 0) yield* service.refreshHosts;
1133 return removed;
1134 }),
1135 );
1136 // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.
1137 yield* Effect.forEach(
1138 removed,
1139 ({ id, scope }) =>
1140 Effect.gen(function* () {
1141 yield* Scope.close(scope, Exit.void);
1142 yield* fs.remove(yield* configPath(id), { force: true }).pipe(Effect.ignore);
1143 }),
1144 { concurrency: 4, discard: true },
1145 );
1146 yield* service.withLifecycleLock(
1147 Effect.gen(function* () {
1148 let added = false;
1149 for (const host of next) {
1150 if (configured.has(host.id)) continue;
1151 added = true;
1152 const hostScope = yield* Scope.fork(scope);
1153 const instance = yield* SshDeviceHost.make(
1154 host,
1155 (ready) =>
1156 configureAgent(host.id, ready).pipe(
1157 Effect.asVoid,
1158 Effect.mapError(
1159 (error) =>
1160 new DeviceHost.DeviceHostError({
1161 hostId: host.id,
1162 step: "configuring agent access",
1163 cause: error,
1164 }),
1165 ),
1166 ),
1167 (status, detail) =>
1168 service
1169 .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })
1170 .pipe(Effect.asVoid),
1171 ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));
1172 hosts.set(host.id, instance);
1173 configured.set(host.id, { config: host, scope: hostScope });
1174 }
1175 // Refresh again after removed scopes closed so a late status write from an old host cannot linger.
1176 if (added || removed.length > 0) yield* service.refreshHosts;
1177 }),
1178 );
1179 });
1180 const changes = yield* settings.subscribeChanges;
1181 yield* reconcile((yield* settings.getSettings).deviceHosts);
1182 yield* changes.pipe(
1183 Stream.runForEach((value) => reconcile(value.deviceHosts)),
1184 Effect.forkIn(scope),
1185 );
1186 yield* Effect.addFinalizer(() =>
1187 Effect.forEach(configured.values(), (value) => Scope.close(value.scope, Exit.void), {
1188 discard: true,
1189 concurrency: 4,
1190 }),
1191 );
1192 return {
1193 ...service,
1194 agentCli: resolveNodeExecutable("Device automation").pipe(
1195 Effect.andThen(ensureAgentDevice(config.baseDir)),
1196 Effect.provideService(FileSystem.FileSystem, fs),
1197 Effect.provideService(Path.Path, path),
1198 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1199 Effect.map((tool) => tool.entryPath),
1200 Effect.mapError((error) =>
1201 error._tag === "NodeRuntimeUnavailableError"
1202 ? new DeviceHostUnavailableError({
1203 hostId: LOCAL_DEVICE_HOST_ID,
1204 reason: nodeRuntimeUnavailableMessage("Device automation"),
1205 cause: error,
1206 })
1207 : new DeviceOperationError({
1208 operation: "install agent CLI",
1209 reason: "command_failed",
1210 cause: error,
1211 }),
1212 ),
1213 ),
1214 };
1215});
1216
1217export const layer = Layer.effect(DeviceService, make).pipe(Layer.provide(LocalDeviceHost.layer));
1218
1219export const stateStream = (service: DeviceService["Service"]): Stream.Stream<DeviceServiceState> =>
1220 Stream.unwrap(
1221 Effect.gen(function* () {
1222 // Subscribe before reading the snapshot so no change between the two
1223 // is lost; the scope lives as long as the stream does.
1224 const subscription = yield* service.subscribe;
1225 const initial = yield* service.state;
1226 return Stream.concat(Stream.make(initial), Stream.fromSubscription(subscription));
1227 }),
1228 ).pipe(Stream.scoped);