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

DeviceService.ts

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