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

DeviceService.ts

1,167 lines45.1 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 // Snapshot saves can stall discovery; refresh failure must not fail an accepted shutdown.
713 yield* refresh(ready).pipe(
714 Effect.catch((cause) =>
715 Effect.logWarning("Device discovery unavailable after shutdown", { cause }),
716 ),
717 );
718 });
719​
720 const close: DeviceService["Service"]["close"] = Effect.fn("DeviceService.close")(
721 function* (input) {
722 const { state } = yield* SynchronizedRef.get(stateRef);
723 const closing = state.sessions.filter(
724 (session) =>
725 session.threadId === input.threadId &&
726 (input.hostId === undefined || session.hostId === input.hostId) &&
727 (input.deviceId === undefined || session.deviceId === input.deviceId),
728 );
729 if (closing.length === 0) return;
730 yield* publish((current) => ({
731 ...current,
732 sessions: current.sessions.filter((session) => !closing.includes(session)),
733 }));
734 if (input.shutdown) {
735 yield* Effect.forEach(
736 closing,
737 (session) => shutdownDevice(session.hostId, session.deviceId, session.platform),
738 { discard: true },
739 );
740 }
741 },
742 );
743​
744 const shutdown: DeviceService["Service"]["shutdown"] = Effect.fn("DeviceService.shutdown")(
745 function* (input) {
746 const host = yield* resolveHost(input.hostId);
747 yield* shutdownDevice(host.id, input.deviceId, input.platform);
748 yield* publish((current) => ({
749 ...current,
750 sessions: current.sessions.filter(
751 (session) => !(session.hostId === host.id && session.deviceId === input.deviceId),
752 ),
753 }));
754 },
755 );
756​
757 const screenshot: DeviceService["Service"]["screenshot"] = Effect.fn("DeviceService.screenshot")(
758 function* (input) {
759 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
760 return { device, png: yield* ready.devices.screenshot(device) };
761 },
762 );
763​
764 const resolveDevice = Effect.fn("DeviceService.resolveDevice")(function* (
765 hostId: DeviceHostId | undefined,
766 deviceId: DeviceId,
767 ) {
768 const host = yield* resolveHost(hostId);
769 const ready = yield* readiness(host.id);
770 const { state } = yield* SynchronizedRef.get(stateRef);
771 const device =
772 findDevice(state, host.id, deviceId) ?? findDevice(yield* refresh(ready), host.id, deviceId);
773 if (!device) return yield* new DeviceNotFoundError({ hostId: host.id, deviceId });
774 return { ready, device };
775 });
776​
777 const detail: DeviceService["Service"]["detail"] = Effect.fn("DeviceService.detail")(
778 function* (input) {
779 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
780 const read = yield* readDeviceDetail(ready, device.platform, device.id);
781 return {
782 hostId: ready.hostId,
783 deviceId: device.id,
784 settings: read.settings,
785 foregroundApp: read.foregroundApp,
786 readAt: DateTime.formatIso(yield* DateTime.now),
787 };
788 },
789 );
790​
791 const action: DeviceService["Service"]["action"] = Effect.fn("DeviceService.action")(
792 function* (input) {
793 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
794 yield* runDeviceAction(ready, device.platform, input);
795 return yield* detail({ hostId: ready.hostId, deviceId: device.id });
796 },
797 );
798​
799 const sessionsForThread: DeviceService["Service"]["sessionsForThread"] = (threadId) =>
800 SynchronizedRef.get(stateRef).pipe(
801 Effect.map(({ state }) => state.sessions.filter((session) => session.threadId === threadId)),
802 );
803​
804 return {
805 ...DeviceService.of({
806 testHost,
807 updateTool: (tool) =>
808 lifecycleLock.withPermit(
809 Effect.gen(function* () {
810 if (!installTool)
811 return yield* new DeviceOperationError({
812 operation: "update device tool",
813 reason: "request_failed",
814 cause: new Error("Tool installation is unavailable in this device service."),
815 });
816 yield* installTool(tool);
817 return yield* inspect;
818 }),
819 ),
820 retryHost,
821 inspect,
822 easAccount: () =>
823 Effect.fail(
824 new DeviceEasAccountError({
825 reason: "EAS accounts are unavailable in this device service.",
826 }),
827 ),
828 agentCli: Effect.fail(
829 new DeviceHostUnavailableError({
830 hostId: LOCAL_DEVICE_HOST_ID,
831 reason: "Agent CLI installation is unavailable in this device service.",
832 }),
833 ),
834 agentTarget: Effect.fn("DeviceService.agentTarget")(function* (input) {
835 const host = yield* resolveHost(input.hostId);
836 const ready = yield* agentReadinessIfSupported(input.hostId);
837 if (!ready)
838 return yield* new DeviceHostUnavailableError({
839 hostId: host.id,
840 hostLabel: host.label,
841 reason:
842 "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
843 });
844 const { configPath, agentDeviceId } = yield* lifecycleLock.withPermit(
845 Effect.gen(function* () {
846 if (hosts.get(host.id) !== host)
847 return yield* new DeviceHostUnavailableError({
848 hostId: host.id,
849 hostLabel: host.label,
850 reason: "Host configuration changed. Retry the operation.",
851 });
852 if (ready.devices.agentEndpoint) {
853 const endpoint = yield* ready.devices.agentEndpoint(input.deviceId);
854 return {
855 configPath: yield* configureAgent(input.hostId, endpoint, input.deviceId),
856 agentDeviceId: endpoint.agentDeviceId,
857 };
858 }
859 if (!ready.agentDevice)
860 return yield* new DeviceHostUnavailableError({
861 hostId: host.id,
862 hostLabel: host.label,
863 reason: "This host has no agent-device daemon.",
864 });
865 return {
866 configPath: yield* configureAgent(input.hostId, ready.agentDevice),
867 agentDeviceId: input.deviceId,
868 };
869 }),
870 );
871 const session = yield* agentDeviceSession(
872 input.threadId,
873 input.hostId,
874 input.deviceId,
875 ).pipe(Effect.provideService(Crypto.Crypto, crypto));
876 return { agentDeviceId, args: ["--config", configPath, "--session", session] };
877 }),
878 state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
879 subscribe: PubSub.subscribe(statePubSub),
880 configure,
881 list,
882 open,
883 close,
884 shutdown,
885 detail,
886 action,
887 screenshot,
888 readiness,
889 readinessIfSupported,
890 agentReadinessIfSupported,
891 currentReadiness,
892 sessionsForThread,
893 }),
894 setHostStatus,
895 withLifecycleLock: lifecycleLock.withPermit,
896 refreshHosts: Effect.gen(function* () {
897 const summaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
898 const unchanged = (id: DeviceHostId) =>
899 hosts.has(id) && hosts.get(id) === publishedHosts.get(id);
900 yield* publish((state) => ({
901 ...state,
902 hosts: summaries,
903 hostStatuses: Object.fromEntries(
904 Object.entries(state.hostStatuses).filter(([id]) => unchanged(id)),
905 ),
906 devices: state.devices.filter((device) => unchanged(device.hostId)),
907 sessions: state.sessions.filter((session) => unchanged(session.hostId)),
908 }));
909 publishedHosts = new Map(hosts);
910 }),
911 };
912});
913​
914/** @public */
915/** @public */
916export const make = Effect.gen(function* () {
917 const localHost = yield* DeviceHost.DeviceHost;
918 const config = yield* ServerConfig.ServerConfig;
919 const fs = yield* FileSystem.FileSystem;
920 const path = yield* Path.Path;
921 const runner = yield* ProcessRunner.ProcessRunner;
922 const settings = yield* ServerSettings.ServerSettingsService;
923 const scope = yield* Scope.Scope;
924 const hosts = new Map<DeviceHostId, DeviceHost.DeviceHost["Service"]>([
925 [localHost.id, localHost],
926 ]);
927 const crypto = yield* Crypto.Crypto;
928 const configPath = (hostId: DeviceHostId, deviceId?: DeviceId) =>
929 agentDeviceConfigPath(config.stateDir, hostId, path, deviceId).pipe(
930 Effect.provideService(Crypto.Crypto, crypto),
931 );
932 const configureAgent = Effect.fn("DeviceService.configureAgent")(
933 function* (
934 hostId: DeviceHostId,
935 endpoint: DeviceHost.AgentDaemonEndpoint,
936 deviceId?: DeviceId,
937 ) {
938 const file = yield* configPath(hostId, deviceId);
939 yield* writeAgentDeviceConfig(file, endpoint);
940 return file;
941 },
942 Effect.provideService(FileSystem.FileSystem, fs),
943 Effect.provideService(Path.Path, path),
944 Effect.mapError(
945 (cause) =>
946 new DeviceOperationError({
947 operation: "configure agent",
948 reason: "settings_failed",
949 cause,
950 }),
951 ),
952 );
953 const probeContext =
954 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();
955 const localTargetContext =
956 yield* Effect.context<Effect.Services<ReturnType<typeof isLocalSshDeviceHost>>>();
957 const service = yield* makeWithHosts(
958 hosts,
959 (host) =>
960 Effect.gen(function* () {
961 if (yield* isLocalSshDeviceHost(host).pipe(Effect.provide(localTargetContext))) {
962 return yield* localHost.summary;
963 }
964 return yield* SshDeviceHost.probe(host).pipe(Effect.provide(probeContext));
965 }).pipe(
966 Effect.mapError(
967 (error) =>
968 new DeviceOperationError({
969 operation: "probe host",
970 reason: "request_failed",
971 cause: error,
972 }),
973 ),
974 ),
975 configureAgent,
976 (tool) =>
977 (tool === "hub" ? ensureDeviceHub(config.baseDir) : ensureAgentDevice(config.baseDir)).pipe(
978 Effect.provideService(FileSystem.FileSystem, fs),
979 Effect.provideService(Path.Path, path),
980 Effect.provideService(ProcessRunner.ProcessRunner, runner),
981 Effect.mapError(
982 (cause) =>
983 new DeviceOperationError({
984 operation: "update device tool",
985 reason: "command_failed",
986 // Only the exit code goes into the shown message; npm's stderr can carry registry credentials.
987 ...(cause.exitCode !== undefined ? { exitCode: cause.exitCode } : {}),
988 cause,
989 }),
990 ),
991 ),
992 );
993 const hostContext =
994 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
995 const easContext =
996 yield* Effect.context<Effect.Services<ReturnType<typeof EasDeviceHost.make>>>();
997 const configured = new Map<string, { config: DeviceHostConfig; scope: Scope.Closeable }>();
998 const unchanged = (current: DeviceHostConfig, previous: DeviceHostConfig) =>
999 current.kind === "ssh" && previous.kind === "ssh"
1000 ? current.label === previous.label &&
1001 current.target === previous.target &&
1002 current.port === previous.port &&
1003 current.identityFile === previous.identityFile
1004 : JSON.stringify(current) === JSON.stringify(previous);
1005 const reconcile = Effect.fn("DeviceService.reconcile")(function* (
1006 configuredHosts: ReadonlyArray<DeviceHostConfig>,
1007 ) {
1008 const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(
1009 Effect.provide(localTargetContext),
1010 );
1011 const removed = yield* service.withLifecycleLock(
1012 Effect.gen(function* () {
1013 const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
1014 for (const [id, previous] of configured) {
1015 if (next.some((host) => host.id === id && unchanged(host, previous.config))) continue;
1016 hosts.delete(id);
1017 configured.delete(id);
1018 removed.push({ id, scope: previous.scope });
1020 if (removed.length > 0) yield* service.refreshHosts;
1021 return removed;
1022 }),
1023 );
1024 // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.
1025 yield* Effect.forEach(
1026 removed,
1027 ({ id, scope }) =>
1028 Effect.gen(function* () {
1029 yield* Scope.close(scope, Exit.void);
1030 yield* fs.remove(yield* configPath(id), { force: true }).pipe(Effect.ignore);
1031 }),
1032 { concurrency: 4, discard: true },
1033 );
1034 yield* service.withLifecycleLock(
1035 Effect.gen(function* () {
1036 let added = false;
1037 for (const host of next) {
1038 if (configured.has(host.id)) continue;
1039 added = true;
1040 const hostScope = yield* Scope.fork(scope);
1041 if (host.kind === "eas") {
1042 // Closing this scope stops the host's running sessions, so a changed
1043 // limit or token never leaves a billed session behind.
1044 const instance = yield* EasDeviceHost.make(host).pipe(
1045 Effect.provideService(Scope.Scope, hostScope),
1046 Effect.provide(easContext),
1047 );
1048 hosts.set(host.id, instance);
1049 configured.set(host.id, { config: host, scope: hostScope });
1050 continue;
1052 const instance = yield* SshDeviceHost.make(
1053 host,
1054 (ready) =>
1055 (ready.agentDevice
1056 ? configureAgent(host.id, ready.agentDevice).pipe(Effect.asVoid)
1057 : Effect.void
1058 ).pipe(
1059 Effect.mapError(
1060 (error) =>
1061 new DeviceHost.DeviceHostError({
1062 hostId: host.id,
1063 step: "configuring agent access",
1064 cause: error,
1065 }),
1066 ),
1067 ),
1068 (status, detail) =>
1069 service
1070 .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })
1071 .pipe(Effect.asVoid),
1072 ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));
1073 hosts.set(host.id, instance);
1074 configured.set(host.id, { config: host, scope: hostScope });
1076 // Refresh again after removed scopes closed so a late status write from an old host cannot linger.
1077 if (added || removed.length > 0) yield* service.refreshHosts;
1078 }),
1079 );
1080 });
1081 const changes = yield* settings.subscribeChanges;
1082 // Settings keep EAS hosts apart from SSH hosts; an id both lists use stays the SSH host's.
1083 const configuredHosts = (value: {
1084 readonly deviceHosts: ReadonlyArray<SshDeviceHostConfig>;
1085 readonly easDeviceHosts: ReadonlyArray<EasDeviceHostConfig>;
1086 }): ReadonlyArray<DeviceHostConfig> => [
1087 ...value.deviceHosts,
1088 ...value.easDeviceHosts.filter((host) => !value.deviceHosts.some((ssh) => ssh.id === host.id)),
1089 ];
1090 yield* reconcile(configuredHosts(yield* settings.getSettings));
1091 yield* changes.pipe(
1092 Stream.runForEach((value) => reconcile(configuredHosts(value))),
1093 Effect.forkIn(scope),
1094 );
1095 yield* Effect.addFinalizer(() =>
1096 Effect.forEach(configured.values(), (value) => Scope.close(value.scope, Exit.void), {
1097 discard: true,
1098 concurrency: 4,
1099 }),
1100 );
1101 const easAccount: DeviceService["Service"]["easAccount"] = Effect.fn("DeviceService.easAccount")(
1102 function* (input) {
1103 const saved =
1104 input.hostId === undefined
1105 ? ""
1106 : ((yield* settings.getSettings).easDeviceHosts.find((host) => host.id === input.hostId)
1107 ?.accessToken ?? "");
1108 const credential = yield* resolveExpoCredential(input.accessToken ?? saved);
1109 const viewer = yield* makeExpoApi(yield* HttpClient.HttpClient, credential).viewer;
1110 return { signedInAs: viewer.name, credentialSource: credential.source, apps: viewer.apps };
1111 },
1112 Effect.provide(easContext),
1113 // Only bounded text reaches the browser: the credential errors' own
1114 // guidance, or a category for what Expo answered, never Expo's text.
1115 Effect.mapError(
1116 (cause) =>
1117 new DeviceEasAccountError({
1118 reason:
1119 cause._tag === "ExpoApiError"
1120 ? cause.status === 401 || cause.status === 403
1121 ? `Expo rejected the credential (HTTP ${cause.status}).`
1122 : cause.rejected
1123 ? "Expo refused the account check."
1124 : "Could not complete the Expo account check."
1125 : cause.message,
1126 }),
1127 ),
1128 );
1129​
1130 return {
1131 ...service,
1132 easAccount,
1133 agentCli: resolveNodeExecutable("Device automation").pipe(
1134 Effect.andThen(ensureAgentDevice(config.baseDir)),
1135 Effect.provideService(FileSystem.FileSystem, fs),
1136 Effect.provideService(Path.Path, path),
1137 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1138 Effect.map((tool) => tool.entryPath),
1139 Effect.mapError((error) =>
1140 error._tag === "NodeRuntimeUnavailableError"
1141 ? new DeviceHostUnavailableError({
1142 hostId: LOCAL_DEVICE_HOST_ID,
1143 hostLabel: LOCAL_DEVICE_HOST_LABEL,
1144 reason: nodeRuntimeUnavailableMessage("Device automation"),
1145 cause: error,
1146 })
1147 : new DeviceOperationError({
1148 operation: "install agent CLI",
1149 reason: "command_failed",
1150 cause: error,
1151 }),
1152 ),
1153 ),
1154 };
1155});
1156​
1157export const layer = Layer.effect(DeviceService, make).pipe(Layer.provide(LocalDeviceHost.layer));
1158​
1159export const stateStream = (service: DeviceService["Service"]): Stream.Stream<DeviceServiceState> =>
1160 Stream.unwrap(
1161 Effect.gen(function* () {
1162 // Subscribe before reading so no change is lost.
1163 const subscription = yield* service.subscribe;
1164 const initial = yield* service.state;
1165 return Stream.concat(Stream.make(initial), Stream.fromSubscription(subscription));
1166 }),
1167 ).pipe(Stream.scoped);