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 DeviceHostId,
9 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 {
37 agentDeviceCloseOutcome,
38 bindAgentDeviceLauncher,
39 ensureAgentDeviceShim,
40 pruneAgentDeviceLaunchers,
41} from "./AgentDeviceShim.ts";
42import * as ServerConfig from "../config.ts";
43import {
44 agentDeviceConfigPath,
45 agentDeviceSession,
46 writeAgentDeviceConfig,
47} from "./AgentDeviceTarget.ts";
48import * as Context from "effect/Context";
49import * as Crypto from "effect/Crypto";
50import * as DateTime from "effect/DateTime";
51import * as Effect from "effect/Effect";
52import * as Layer from "effect/Layer";
53import * as Option from "effect/Option";
54import * as PubSub from "effect/PubSub";
55import * as Schema from "effect/Schema";
56import * as Scope from "effect/Scope";
57import * as Semaphore from "effect/Semaphore";
58import * as Stream from "effect/Stream";
59import * as SynchronizedRef from "effect/SynchronizedRef";
60import * as HttpClient from "effect/http/HttpClient";
61
62import * as ServerSettings from "../serverSettings.ts";
63import { isLocalSshDeviceHost, remoteSshDeviceHosts } from "./localSshDeviceHost.ts";
64
65import { readDeviceDetail, runDeviceAction } from "./DeviceActions.ts";
66import * as ProcessRunner from "../processRunner.ts";
67import * as DeviceHost from "./DeviceHost.ts";
68import * as SshDeviceHost from "./SshDeviceHost.ts";
69import * as EasDeviceHost from "./EasDeviceHost.ts";
70import { makeExpoApi, resolveExpoCredential } from "./ExpoApi.ts";
71import * as Exit from "effect/Exit";
72import * as LocalDeviceHost from "./LocalDeviceHost.ts";
73
74export const DEVICE_HUB_ROUTE_PREFIX = "/api/device-hub";
75
76const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => {
77 const cause = error.cause;
78 if (
79 !(cause instanceof SshCommandError) ||
80 cause.exitCode === null ||
81 cause.exitCode < 1 ||
82 cause.exitCode > 254
83 )
84 return "Could not connect to this host over SSH.";
85
86 // Only the known bootstrap diagnostic is safe to expose as Node guidance.
87 if (
88 cause.exitCode === 1 &&
89 cause.stderr
90 .split(/\r?\n/u)
91 .some((line) => line.trim() === "Node is missing from the non-interactive SSH PATH")
92 )
93 return "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.";
94
95 return `Connected over SSH, but the device host check failed (exit code ${cause.exitCode}).`;
96};
97
98export interface DeviceScreenshot {
99 readonly device: DeviceSummary;
100 readonly png: Uint8Array;
101}
102
103export interface DeviceReadiness extends DeviceHost.DeviceHostReady {
104 readonly hostId: DeviceHostId;
105}
106
107export interface DeviceAgentReadiness extends DeviceReadiness {
108 /** Null when each device has its own daemon; see `DeviceOperations.agentEndpoint`. */
109 readonly agentDevice: DeviceHost.AgentDeviceEndpoint | null;
110}
111
112const DeviceHostName = Schema.Struct({ id: DeviceHostId, label: Schema.optional(Schema.String) });
113const hostName = (host: typeof DeviceHostName.Type) => host.label ?? `host ${host.id}`;
114
115export class DeviceHostAmbiguousError extends Schema.TaggedError<DeviceHostAmbiguousError>()(
116 "DeviceHostAmbiguousError",
117 { deviceId: DeviceId, hosts: Schema.Array(DeviceHostName) },
118) {
119 override get message(): string {
120 return `Device ${this.deviceId} is on more than one host: ${this.hosts.map(hostName).join(", ")}.`;
121 }
122}
123
124export class DeviceOnOtherHostError extends Schema.TaggedError<DeviceOnOtherHostError>()(
125 "DeviceOnOtherHostError",
126 { deviceId: DeviceId, host: DeviceHostName, hosts: Schema.Array(DeviceHostName) },
127) {
128 override get message(): string {
129 return `Device ${this.deviceId} is not on ${hostName(this.host)}. It is on ${this.hosts.map(hostName).join(", ")}.`;
130 }
131}
132
133export class DeviceService extends Context.Service<
134 DeviceService,
135 {
136 readonly testHost: (
137 config: SshDeviceHostConfig,
138 ) => Effect.Effect<DeviceHostSummary, DeviceError>;
139 /** Who an Expo credential signs in as and which EAS projects it can run sessions under. */
140 readonly easAccount: (
141 input: DeviceEasAccountInput,
142 ) => Effect.Effect<DeviceEasAccount, DeviceEasAccountError>;
143 /**
144 * The agent-device flags that reach the device: its config and session,
145 * and the id agent-device selects it by, which can differ from its id here.
146 */
147 readonly agentTarget: (input: {
148 threadId: ThreadId;
149 hostId: DeviceHostId;
150 deviceId: DeviceId;
151 }) => Effect.Effect<
152 {
153 readonly agentDeviceId: string;
154 readonly session: string;
155 readonly args: ReadonlyArray<string>;
156 },
157 DeviceError
158 >;
159 /**
160 * The command agents run for one agent-device session; it is removed when the session ends.
161 * None when the session closed before it could be bound.
162 */
163 readonly agentLauncher: (input: {
164 readonly threadId: ThreadId;
165 readonly hostId: DeviceHostId;
166 readonly deviceId: DeviceId;
167 readonly targetArgs: ReadonlyArray<string>;
168 }) => Effect.Effect<Option.Option<string>, DeviceError>;
169 readonly state: Effect.Effect<DeviceServiceState>;
170 readonly subscribe: Effect.Effect<PubSub.Subscription<DeviceServiceState>, never, Scope.Scope>;
171 readonly configure: (
172 input: DeviceConfigureInput,
173 ) => Effect.Effect<DeviceServiceState, DeviceError>;
174 readonly list: Effect.Effect<DeviceServiceState, DeviceError>;
175 readonly updateTool: (tool: "hub" | "agent") => Effect.Effect<DeviceServiceState, DeviceError>;
176 readonly inspect: Effect.Effect<DeviceServiceState>;
177 readonly retryHost: (hostId: DeviceHostId) => Effect.Effect<DeviceServiceState, DeviceError>;
178 readonly open: (
179 input: DeviceOpenInput,
180 context?: DeviceHost.DeviceOpenContext,
181 ) => Effect.Effect<DeviceSession, DeviceError>;
182 readonly close: (input: DeviceCloseInput) => Effect.Effect<void, DeviceError>;
183 readonly shutdown: (input: DeviceShutdownInput) => Effect.Effect<void, DeviceError>;
184 readonly detail: (input: DeviceDetailInput) => Effect.Effect<DeviceDetail, DeviceError>;
185 readonly action: (input: DeviceActionInput) => Effect.Effect<DeviceDetail, DeviceError>;
186 readonly screenshot: (input: {
187 readonly hostId?: DeviceHostId | undefined;
188 readonly deviceId: DeviceId;
189 }) => Effect.Effect<DeviceScreenshot, DeviceError>;
190 /**
191 * The device an id names in the last listing. Ids are unique per host, not across hosts (an
192 * Android AVD name can exist on two), so a hostId decides, and without one the id has to be
193 * on a single host.
194 */
195 readonly locateDevice: (input: {
196 readonly hostId?: DeviceHostId | undefined;
197 readonly deviceId: DeviceId;
198 }) => Effect.Effect<
199 Option.Option<DeviceSummary>,
200 DeviceHostAmbiguousError | DeviceOnOtherHostError
201 >;
202 /** As `locateDevice`, among the devices a thread has open. */
203 readonly locateSession: (input: {
204 readonly threadId: ThreadId;
205 readonly hostId?: DeviceHostId | undefined;
206 readonly deviceId: DeviceId;
207 }) => Effect.Effect<
208 Option.Option<DeviceSession>,
209 DeviceHostAmbiguousError | DeviceOnOtherHostError
210 >;
211 readonly readiness: (hostId?: DeviceHostId) => Effect.Effect<DeviceReadiness, DeviceError>;
212 readonly readinessIfSupported: (
213 hostId?: DeviceHostId,
214 ) => Effect.Effect<DeviceReadiness | null, DeviceError>;
215 readonly agentReadinessIfSupported: (
216 hostId?: DeviceHostId,
217 ) => Effect.Effect<DeviceAgentReadiness | null, DeviceError>;
218 readonly currentReadiness: (hostId?: DeviceHostId) => Effect.Effect<DeviceReadiness | null>;
219 readonly sessionsForThread: (threadId: ThreadId) => Effect.Effect<ReadonlyArray<DeviceSession>>;
220 }
221>()("t3/device/DeviceService") {}
222
223interface ServiceState {
224 readonly state: DeviceServiceState;
225}
226
227export interface AgentDeviceLaunchers {
228 readonly bind: (input: {
229 readonly session: string;
230 readonly targetArgs: ReadonlyArray<string>;
231 }) => Effect.Effect<string, DeviceError>;
232 /** Removes every launcher whose session is not in `live`. */
233 readonly prune: (live: ReadonlySet<string>) => Effect.Effect<void>;
234 /** Ends the agent-device session behind a launcher, which releases its claim on the device. */
235 readonly release?: (launcher: string) => Effect.Effect<void>;
236}
237
238export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* (
239 hosts: ReadonlyMap<DeviceHostId, DeviceHost.DeviceHost["Service"]>,
240 testHost: DeviceService["Service"]["testHost"] = (host) =>
241 Effect.fail(
242 new DeviceHostUnavailableError({
243 hostId: host.id,
244 hostLabel: host.label,
245 reason: "SSH probing is unavailable in this device service.",
246 }),
247 ),
248 configureAgent: (
249 hostId: DeviceHostId,
250 endpoint: DeviceHost.AgentDaemonEndpoint,
251 deviceId?: DeviceId,
252 ) => Effect.Effect<string, DeviceError> = (hostId) =>
253 Effect.fail(
254 new DeviceHostUnavailableError({
255 hostId,
256 reason: "Agent configuration is unavailable in this device service.",
257 }),
258 ),
259 installTool?: (tool: "hub" | "agent") => Effect.Effect<unknown, DeviceError>,
260 launchers?: AgentDeviceLaunchers,
261) {
262 const settings = yield* ServerSettings.ServerSettingsService;
263 const crypto = yield* Crypto.Crypto;
264 const lifecycleLock = yield* Semaphore.make(1);
265 const readDeviceSettings = settings.getSettings.pipe(
266 Effect.map((value) => ({
267 enabled: value.enableDeviceSupport,
268 agentAccessEnabled: value.enableAgentDeviceAccess,
269 onboardingCompleted: value.deviceOnboardingCompleted,
270 })),
271 Effect.mapError(
272 (cause) =>
273 new DeviceOperationError({ operation: "settings", reason: "settings_failed", cause }),
274 ),
275 );
276 const initialSettings = yield* readDeviceSettings;
277
278 const statePubSub = yield* PubSub.unbounded<DeviceServiceState>();
279 const initialHosts = yield* Effect.forEach(hosts.values(), (host) => host.summary);
280 let publishedHosts = new Map(hosts);
281 const stateRef = yield* SynchronizedRef.make<ServiceState>({
282 state: {
283 supportsHostRetry: true,
284 supportsToolUpdate: installTool !== undefined,
285 supportsToolInspection: true,
286 supportsEasHosts: true,
287 hosts: initialHosts,
288 hostStatus: initialSettings.enabled ? "idle" : "disabled",
289 hostStatuses: {},
290 devices: [],
291 sessions: [],
292 onboardingCompleted: initialSettings.onboardingCompleted,
293 agentAccessEnabled: initialSettings.agentAccessEnabled,
294 hubBasePath: DEVICE_HUB_ROUTE_PREFIX,
295 revision: 0,
296 },
297 });
298
299 const launcherLock = yield* Semaphore.make(1);
300 /** Launchers bound since startup, by agent-device session. */
301 const boundLaunchers = new Map<string, string>();
302 // Binding and pruning read sessions under the lock, so neither acts on a session list the other has outdated.
303 // A retired session's agent-device session ends before its launcher goes, and a reopen of the same
304 // device waits for the lock, so the close cannot end the reopened session.
305 const pruneLaunchers = launcherLock.withPermit(
306 Effect.gen(function* () {
307 if (!launchers) return;
308 const { state } = yield* SynchronizedRef.get(stateRef);
309 const live = new Set(
310 yield* Effect.forEach(state.sessions, (session) =>
311 agentDeviceSession(session.threadId, session.hostId, session.deviceId),
312 ).pipe(Effect.provideService(Crypto.Crypto, crypto)),
313 );
314 const retired = [...boundLaunchers].filter(([session]) => !live.has(session));
315 for (const [session] of retired) boundLaunchers.delete(session);
316 const release = launchers.release;
317 if (release)
318 yield* Effect.forEach(retired, ([, launcher]) => release(launcher), {
319 concurrency: "unbounded",
320 discard: true,
321 });
322 yield* launchers.prune(live);
323 }),
324 );
325
326 // Uninterruptible so a committed retirement always prunes, even if its caller is cancelled.
327 const publish = (update: (state: DeviceServiceState) => DeviceServiceState) =>
328 SynchronizedRef.modifyEffect(stateRef, ({ state }) => {
329 const next = { ...update(state), revision: state.revision + 1 };
330 const retired = state.sessions.some((session) => !next.sessions.includes(session));
331 return PubSub.publish(statePubSub, next).pipe(
332 Effect.as([{ next, retired }, { state: next }] as const),
333 );
334 }).pipe(
335 Effect.tap(({ retired }) => (retired ? pruneLaunchers : Effect.void)),
336 Effect.map(({ next }) => next),
337 Effect.uninterruptible,
338 );
339
340 const resolveHost = Effect.fn("DeviceService.resolveHost")(function* (
341 hostId: DeviceHostId | undefined,
342 ) {
343 const id = hostId ?? LOCAL_DEVICE_HOST_ID;
344 const host = hosts.get(id);
345 if (!host) {
346 return yield* new DeviceHostUnavailableError({ hostId: id, reason: "Unknown host." });
347 }
348 return host;
349 });
350
351 const setHostStatus = (
352 hostId: DeviceHostId,
353 status: DeviceServiceState["hostStatuses"][string],
354 ) =>
355 Effect.suspend(() =>
356 !hosts.has(hostId)
357 ? SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state))
358 : publish((state) => ({
359 ...state,
360 ...(hostId === LOCAL_DEVICE_HOST_ID
361 ? { hostStatus: status.status, hostStatusDetail: status.detail }
362 : {}),
363 hostStatuses: {
364 ...state.hostStatuses,
365 [hostId]: {
366 ...(state.hostStatuses[hostId]?.androidDiscoveryIncomplete
367 ? { androidDiscoveryIncomplete: true }
368 : {}),
369 ...status,
370 },
371 },
372 })),
373 );
374
375 const readiness: DeviceService["Service"]["readiness"] = Effect.fn("DeviceService.readiness")(
376 function* (hostId) {
377 const host = yield* resolveHost(hostId);
378 if (!(yield* readDeviceSettings).enabled) {
379 return yield* new DeviceHostUnavailableError({
380 hostId: host.id,
381 hostLabel: host.label,
382 reason:
383 "Device support is off. Enable it in the Device panel before installing or starting device tools.",
384 });
385 }
386 const ready = yield* host
387 .ensureReady((status, detail) =>
388 setHostStatus(host.id, { status, detail }).pipe(Effect.asVoid),
389 )
390 .pipe(
391 Effect.tapError((error) =>
392 setHostStatus(host.id, {
393 status: "failed",
394 detail:
395 error._tag === "DeviceHostError" && error.step === "probe"
396 ? sshProbeFailureMessage(error)
397 : error.message,
398 }),
399 ),
400 Effect.mapError(
401 (error) =>
402 new DeviceHostUnavailableError({
403 hostId: host.id,
404 hostLabel: host.label,
405 reason:
406 error._tag === "NodeRuntimeUnavailableError"
407 ? nodeRuntimeUnavailableMessage("Local device support")
408 : error.step === "probe"
409 ? sshProbeFailureMessage(error)
410 : `Device support failed during ${error.step}.`,
411 cause: error,
412 }),
413 ),
414 );
415 if (hosts.get(host.id) !== host)
416 return yield* new DeviceHostUnavailableError({
417 hostId: host.id,
418 hostLabel: host.label,
419 reason: "Host configuration changed. Retry the operation.",
420 });
421 const { state } = yield* SynchronizedRef.get(stateRef);
422 if (state.hostStatuses[host.id]?.status !== "ready") {
423 yield* setHostStatus(host.id, { status: "ready" });
424 }
425 return { hostId: host.id, ...ready };
426 },
427 lifecycleLock.withPermit,
428 );
429
430 const readinessIfSupported: DeviceService["Service"]["readinessIfSupported"] = Effect.fn(
431 "DeviceService.readinessIfSupported",
432 )(function* (hostId) {
433 if (!(yield* readDeviceSettings).enabled) return null;
434 const host = yield* resolveHost(hostId);
435 const summary = yield* host.summary;
436 if (summary.kind === "local" && !summary.platforms.some((platform) => platform.available))
437 return null;
438 return yield* readiness(host.id);
439 });
440
441 const agentReadinessIfSupported: DeviceService["Service"]["agentReadinessIfSupported"] =
442 Effect.fn("DeviceService.agentReadinessIfSupported")(function* (hostId) {
443 const deviceSettings = yield* readDeviceSettings;
444 if (!deviceSettings.enabled || !deviceSettings.agentAccessEnabled) return null;
445 const host = yield* resolveHost(hostId);
446 const summary = yield* host.summary;
447 if (summary.kind === "local" && !summary.platforms.some((platform) => platform.available))
448 return null;
449 const ready = yield* host
450 .ensureAgentReady((phase, detail) =>
451 setHostStatus(host.id, { status: phase, detail }).pipe(Effect.asVoid),
452 )
453 .pipe(
454 Effect.tapError((error) =>
455 setHostStatus(host.id, {
456 status: "failed",
457 detail:
458 error._tag === "DeviceHostError" && error.step === "probe"
459 ? sshProbeFailureMessage(error)
460 : error.message,
461 }),
462 ),
463 Effect.mapError(
464 (error) =>
465 new DeviceHostUnavailableError({
466 hostId: host.id,
467 hostLabel: host.label,
468 reason:
469 error._tag === "NodeRuntimeUnavailableError"
470 ? nodeRuntimeUnavailableMessage("Local device support")
471 : error._tag === "DeviceHostTimeoutError"
472 ? `Agent tools did not start within ${error.timeoutMs} ms.`
473 : error._tag === "AgentDeviceStartError"
474 ? error.message
475 : error.step === "probe"
476 ? sshProbeFailureMessage(error)
477 : `Device support failed during ${error.step}.`,
478 cause: error,
479 }),
480 ),
481 );
482 const hostSummaries = yield* Effect.forEach(hosts.values(), (candidate) => candidate.summary);
483 yield* publish((state) => ({ ...state, hosts: hostSummaries }));
484 yield* setHostStatus(host.id, { status: "ready" });
485 return { hostId: host.id, ...ready };
486 }, lifecycleLock.withPermit);
487
488 const currentReadiness: DeviceService["Service"]["currentReadiness"] = (hostId) =>
489 resolveHost(hostId).pipe(
490 Effect.flatMap((host) =>
491 host.current.pipe(Effect.map((ready) => (ready ? { hostId: host.id, ...ready } : null))),
492 ),
493 Effect.orElseSucceed(() => null),
494 );
495
496 const fetchDevices = Effect.fn("DeviceService.fetchDevices")(function* (ready: DeviceReadiness) {
497 const { devices, detail, androidDiscoveryIncomplete } = yield* ready.devices.list;
498 return {
499 devices: devices.map((device): DeviceSummary => ({ ...device, hostId: ready.hostId })),
500 detail,
501 androidDiscoveryIncomplete,
502 };
503 });
504
505 const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {
506 const host = hosts.get(ready.hostId);
507 // A session opened while the listing ran is on a device the listing could
508 // not have seen yet; only sessions from before it can be pruned by it.
509 const sessionKey = (session: DeviceSession) =>
510 `${session.hostId}\u0000${session.deviceId}\u0000${session.threadId}\u0000${session.openedAt}`;
511 const before = new Set((yield* SynchronizedRef.get(stateRef)).state.sessions.map(sessionKey));
512 const { devices, detail, androidDiscoveryIncomplete } = yield* fetchDevices(ready);
513 const hostSummaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
514 return yield* lifecycleLock.withPermit(
515 Effect.gen(function* () {
516 if (!(yield* readDeviceSettings).enabled || !host || hosts.get(ready.hostId) !== host)
517 return (yield* SynchronizedRef.get(stateRef)).state;
518 return yield* publish((state) => ({
519 ...state,
520 hosts: hostSummaries,
521 ...(ready.hostId === LOCAL_DEVICE_HOST_ID ? { hostStatusDetail: detail } : {}),
522 devices: [
523 ...state.devices.filter((device) => device.hostId !== ready.hostId),
524 ...devices,
525 ],
526 // A host that ends devices itself (EAS stops sessions at their limits)
527 // leaves sessions on devices it no longer lists with nothing to stream.
528 // Other hosts can miss a device for one listing, so theirs stay.
529 sessions: ready.devices.endsDevices
530 ? state.sessions.filter(
531 (session) =>
532 session.hostId !== ready.hostId ||
533 !before.has(sessionKey(session)) ||
534 devices.some((device) => device.id === session.deviceId),
535 )
536 : state.sessions,
537 hostStatuses: {
538 ...state.hostStatuses,
539 [ready.hostId]: {
540 status: "ready",
541 ...(detail ? { detail } : {}),
542 ...(androidDiscoveryIncomplete ? { androidDiscoveryIncomplete } : {}),
543 },
544 },
545 }));
546 }),
547 );
548 });
549
550 const list: DeviceService["Service"]["list"] = Effect.gen(function* () {
551 if (!(yield* readDeviceSettings).enabled) return (yield* SynchronizedRef.get(stateRef)).state;
552 yield* Effect.forEach(
553 hosts.values(),
554 (host) =>
555 Effect.gen(function* () {
556 const ready = yield* readinessIfSupported(host.id);
557 if (ready) yield* refresh(ready);
558 }).pipe(
559 Effect.catch((error) =>
560 setHostStatus(host.id, {
561 status: "failed",
562 detail: error._tag === "DeviceHostUnavailableError" ? error.reason : error.message,
563 }),
564 ),
565 ),
566 { concurrency: 4 },
567 );
568 return (yield* SynchronizedRef.get(stateRef)).state;
569 }).pipe(Effect.withSpan("DeviceService.list"));
570
571 const inspect = Effect.gen(function* () {
572 yield* Effect.forEach(
573 hosts.values(),
574 (host) =>
575 Effect.gen(function* () {
576 const result = yield* (host.inspect ?? host.summary).pipe(Effect.result);
577 if (hosts.get(host.id) !== host) return;
578 if (result._tag === "Failure") {
579 yield* publish((state) => ({
580 ...state,
581 hosts: state.hosts.map((value) =>
582 value.id === host.id
583 ? {
584 ...value,
585 toolInspectionError:
586 "Cannot check versions. Reconnect the host and check again. Installed tools have not been changed.",
587 }
588 : value,
589 ),
590 }));
591 return;
592 }
593 yield* publish((state) => ({
594 ...state,
595 hosts: state.hosts.map((value) => (value.id === host.id ? result.success : value)),
596 }));
597 }),
598 { concurrency: 4 },
599 );
600 return (yield* SynchronizedRef.get(stateRef)).state;
601 });
602
603 const retryHost: DeviceService["Service"]["retryHost"] = Effect.fn("DeviceService.retryHost")(
604 function* (hostId) {
605 yield* resolveHost(hostId);
606 if (!(yield* readDeviceSettings).enabled) return (yield* SynchronizedRef.get(stateRef)).state;
607 yield* Effect.gen(function* () {
608 const ready =
609 (yield* agentReadinessIfSupported(hostId)) ?? (yield* readinessIfSupported(hostId));
610 if (ready) yield* refresh(ready);
611 }).pipe(
612 Effect.catch((error) =>
613 setHostStatus(hostId, {
614 status: "failed",
615 detail: error._tag === "DeviceHostUnavailableError" ? error.reason : error.message,
616 }),
617 ),
618 );
619 return (yield* SynchronizedRef.get(stateRef)).state;
620 },
621 );
622
623 const configure: DeviceService["Service"]["configure"] = Effect.fn("DeviceService.configure")(
624 function* (input) {
625 const currentSettings = yield* readDeviceSettings;
626 const nextEnabled = input.enabled ?? currentSettings.enabled;
627 const nextAgentAccess = input.agentAccessEnabled ?? currentSettings.agentAccessEnabled;
628 yield* lifecycleLock.withPermit(
629 Effect.gen(function* () {
630 yield* settings
631 .updateSettings({
632 ...(input.enabled === undefined ? {} : { enableDeviceSupport: input.enabled }),
633 ...(input.agentAccessEnabled === undefined
634 ? {}
635 : { enableAgentDeviceAccess: input.agentAccessEnabled }),
636 ...(input.onboardingCompleted === undefined
637 ? {}
638 : { deviceOnboardingCompleted: input.onboardingCompleted }),
639 })
640 .pipe(
641 Effect.mapError(
642 (cause) =>
643 new DeviceOperationError({
644 operation: "configure",
645 reason: "settings_failed",
646 cause,
647 }),
648 ),
649 );
650 if (!nextEnabled) {
651 yield* Effect.forEach(hosts.values(), (host) => host.stop, { discard: true });
652 } else if (input.agentAccessEnabled === false) {
653 yield* Effect.forEach(hosts.values(), (host) => host.stopAgent, { discard: true });
654 }
655 yield* publish((state) => ({
656 ...state,
657 hostStatus: nextEnabled ? "idle" : "disabled",
658 hostStatusDetail: undefined,
659 hostStatuses: {},
660 devices: nextEnabled ? state.devices : [],
661 sessions: nextEnabled ? state.sessions : [],
662 bootingDevices: nextEnabled ? state.bootingDevices : [],
663 agentAccessEnabled: nextAgentAccess,
664 onboardingCompleted: input.onboardingCompleted ?? state.onboardingCompleted,
665 }));
666 }),
667 );
668 if (nextEnabled && nextAgentAccess && input.agentAccessEnabled === true) {
669 yield* agentReadinessIfSupported();
670 }
671 return yield* list;
672 },
673 );
674
675 const findDevice = (
676 state: DeviceServiceState,
677 hostId: DeviceHostId,
678 deviceId: DeviceId,
679 ): DeviceSummary | undefined =>
680 state.devices.find((device) => device.hostId === hostId && device.id === deviceId);
681
682 const ensurePlatform = Effect.fn("DeviceService.ensurePlatform")(function* (
683 host: DeviceHost.DeviceHost["Service"],
684 platform: DevicePlatform,
685 ) {
686 const availability = yield* host.platformAvailability(platform);
687 if (!availability.available) {
688 return yield* new DevicePlatformUnavailableError({
689 hostId: host.id,
690 platform,
691 reason: availability.reason ?? "Platform toolchain missing.",
692 });
693 }
694 });
695
696 const open: DeviceService["Service"]["open"] = Effect.fn("DeviceService.open")(
697 function* (input, context) {
698 const host = yield* resolveHost(input.hostId);
699 yield* ensurePlatform(host, input.platform);
700 const ready = yield* readiness(host.id);
701 let state = yield* refresh(ready);
702 let device = findDevice(state, host.id, input.deviceId);
703 if (!device) {
704 return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: input.deviceId });
705 }
706 if (device.platform === "android" && !device.physical) {
707 // Resolve the override on the device host the way its hub does.
708 const encoders = yield* ready.run(ready.nodePath, [
709 "-e",
710 `const { spawnSync } = require("node:child_process");
711 const result = spawnSync(process.env.SERVE_EMU_FFMPEG?.trim() || "ffmpeg", ["-hide_banner", "-encoders"], {
712 stdio: "inherit", timeout: 10000, killSignal: "SIGKILL",
713 });
714 process.exitCode = result.error ? 1 : (result.status ?? 1);`,
715 ]);
716 if (encoders.code !== 0) {
717 return yield* new DevicePlatformUnavailableError({
718 hostId: host.id,
719 platform: "android",
720 reason:
721 "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.",
722 });
723 }
724 if (!/^\s*V\S*[ \t]+libx264(?:[ \t]|$)/m.test(`${encoders.stdout}\n${encoders.stderr}`)) {
725 return yield* new DevicePlatformUnavailableError({
726 hostId: host.id,
727 platform: "android",
728 reason:
729 "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.",
730 });
731 }
732 }
733 if (!device.booted && input.boot !== false) {
734 const booting = { ...device, threadId: input.threadId };
735 yield* publish((current) => ({
736 ...current,
737 bootingDevices: [
738 ...(current.bootingDevices ?? []).filter(
739 (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
740 ),
741 booting,
742 ],
743 }));
744 const bootedId = yield* ready.devices.boot(device, context).pipe(
745 Effect.ensuring(
746 publish((current) => ({
747 ...current,
748 bootingDevices: (current.bootingDevices ?? []).filter(
749 (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
750 ),
751 })),
752 ),
753 );
754 state = yield* refresh(ready);
755 device = findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id);
756 if (!device) {
757 return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });
758 }
759 } else if (device.booted) {
760 yield* ready.devices.attach(device);
761 }
762 if (hosts.get(host.id) !== host)
763 return yield* new DeviceHostUnavailableError({
764 hostId: host.id,
765 hostLabel: host.label,
766 reason: "Host configuration changed. Retry the operation.",
767 });
768 const openedAt = DateTime.formatIso(yield* DateTime.now);
769 const session: DeviceSession = {
770 threadId: input.threadId,
771 hostId: host.id,
772 deviceId: device.id,
773 platform: device.platform,
774 openedAt,
775 };
776 yield* lifecycleLock.withPermit(
777 Effect.gen(function* () {
778 if (!(yield* readDeviceSettings).enabled)
779 return yield* new DeviceHostUnavailableError({
780 hostId: host.id,
781 hostLabel: host.label,
782 reason: "Device support was turned off while the device was opening.",
783 });
784 yield* publish((current) => ({
785 ...current,
786 sessions: [
787 ...current.sessions.filter(
788 (existing) =>
789 !(
790 existing.threadId === session.threadId &&
791 existing.hostId === session.hostId &&
792 existing.deviceId === session.deviceId
793 ),
794 ),
795 session,
796 ],
797 }));
798 }),
799 );
800 return session;
801 },
802 );
803
804 const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* (
805 hostId: DeviceHostId,
806 deviceId: DeviceId,
807 platform: DevicePlatform,
808 ) {
809 const ready = yield* readiness(hostId);
810 yield* ready.devices.shutdown({ id: deviceId, platform });
811 yield* publish((state) => ({
812 ...state,
813 devices: state.devices.map((device) =>
814 device.hostId === ready.hostId && device.id === deviceId
815 ? { ...device, booted: false }
816 : device,
817 ),
818 sessions: state.sessions.filter(
819 (session) => !(session.hostId === ready.hostId && session.deviceId === deviceId),
820 ),
821 }));
822 // Snapshot saves can stall discovery; refresh failure must not fail an accepted shutdown.
823 yield* refresh(ready).pipe(
824 Effect.catch((cause) =>
825 Effect.logWarning("Device discovery unavailable after shutdown", { cause }),
826 ),
827 );
828 });
829
830 const close: DeviceService["Service"]["close"] = Effect.fn("DeviceService.close")(
831 function* (input) {
832 const { state } = yield* SynchronizedRef.get(stateRef);
833 const closing = state.sessions.filter(
834 (session) =>
835 session.threadId === input.threadId &&
836 (input.hostId === undefined || session.hostId === input.hostId) &&
837 (input.deviceId === undefined || session.deviceId === input.deviceId),
838 );
839 if (closing.length === 0) return;
840 // Powering off ends every session on the device, so all of them retire, and release, while it is on.
841 const ending = (session: DeviceSession) =>
842 closing.includes(session) ||
843 (input.shutdown === true &&
844 closing.some(
845 (closed) => closed.hostId === session.hostId && closed.deviceId === session.deviceId,
846 ));
847 yield* publish((current) => ({
848 ...current,
849 sessions: current.sessions.filter((session) => !ending(session)),
850 }));
851 if (input.shutdown) {
852 yield* Effect.forEach(
853 closing,
854 (session) => shutdownDevice(session.hostId, session.deviceId, session.platform),
855 { discard: true },
856 );
857 }
858 },
859 );
860
861 // Sessions retire before the power-off, while their agent-device sessions can still close the app;
862 // agent-device keeps a claim whose app close fails.
863 const shutdown: DeviceService["Service"]["shutdown"] = Effect.fn("DeviceService.shutdown")(
864 function* (input) {
865 const host = yield* resolveHost(input.hostId);
866 yield* publish((current) => ({
867 ...current,
868 sessions: current.sessions.filter(
869 (session) => !(session.hostId === host.id && session.deviceId === input.deviceId),
870 ),
871 }));
872 yield* shutdownDevice(host.id, input.deviceId, input.platform);
873 },
874 );
875
876 const screenshot: DeviceService["Service"]["screenshot"] = Effect.fn("DeviceService.screenshot")(
877 function* (input) {
878 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
879 return { device, png: yield* ready.devices.screenshot(device) };
880 },
881 );
882
883 const resolveDevice = Effect.fn("DeviceService.resolveDevice")(function* (
884 hostId: DeviceHostId | undefined,
885 deviceId: DeviceId,
886 ) {
887 const host = yield* resolveHost(hostId);
888 const ready = yield* readiness(host.id);
889 const { state } = yield* SynchronizedRef.get(stateRef);
890 const device =
891 findDevice(state, host.id, deviceId) ?? findDevice(yield* refresh(ready), host.id, deviceId);
892 if (!device) return yield* new DeviceNotFoundError({ hostId: host.id, deviceId });
893 return { ready, device };
894 });
895
896 const detail: DeviceService["Service"]["detail"] = Effect.fn("DeviceService.detail")(
897 function* (input) {
898 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
899 const read = yield* readDeviceDetail(ready, device.platform, device.id);
900 return {
901 hostId: ready.hostId,
902 deviceId: device.id,
903 settings: read.settings,
904 foregroundApp: read.foregroundApp,
905 readAt: DateTime.formatIso(yield* DateTime.now),
906 };
907 },
908 );
909
910 const action: DeviceService["Service"]["action"] = Effect.fn("DeviceService.action")(
911 function* (input) {
912 const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
913 yield* runDeviceAction(ready, device.platform, input);
914 return yield* detail({ hostId: ready.hostId, deviceId: device.id });
915 },
916 );
917
918 const sessionsForThread: DeviceService["Service"]["sessionsForThread"] = (threadId) =>
919 SynchronizedRef.get(stateRef).pipe(
920 Effect.map(({ state }) => state.sessions.filter((session) => session.threadId === threadId)),
921 );
922
923 const locate = <T extends { readonly hostId: DeviceHostId }>(
924 state: DeviceServiceState,
925 input: { readonly hostId?: DeviceHostId | undefined; readonly deviceId: DeviceId },
926 matches: ReadonlyArray<T>,
927 ): Effect.Effect<Option.Option<T>, DeviceHostAmbiguousError | DeviceOnOtherHostError> => {
928 const named = (id: DeviceHostId) => ({
929 id,
930 label: state.hosts.find((host) => host.id === id)?.label,
931 });
932 const onHost = matches.filter(
933 (match) => input.hostId === undefined || match.hostId === input.hostId,
934 );
935 const hostIds = [...new Set(onHost.map((match) => match.hostId))];
936 if (hostIds.length === 1) return Effect.succeedSome(onHost.at(-1)!);
937 if (hostIds.length > 1) {
938 return Effect.fail(
939 new DeviceHostAmbiguousError({ deviceId: input.deviceId, hosts: hostIds.map(named) }),
940 );
941 }
942 const elsewhere = [...new Set(matches.map((match) => match.hostId))];
943 return input.hostId !== undefined && elsewhere.length > 0
944 ? Effect.fail(
945 new DeviceOnOtherHostError({
946 deviceId: input.deviceId,
947 host: named(input.hostId),
948 hosts: elsewhere.map(named),
949 }),
950 )
951 : Effect.succeedNone;
952 };
953
954 const locateDevice: DeviceService["Service"]["locateDevice"] = Effect.fn(
955 "DeviceService.locateDevice",
956 )(function* (input) {
957 const { state } = yield* SynchronizedRef.get(stateRef);
958 return yield* locate(
959 state,
960 input,
961 state.devices.filter((device) => device.id === input.deviceId),
962 );
963 });
964
965 const locateSession: DeviceService["Service"]["locateSession"] = Effect.fn(
966 "DeviceService.locateSession",
967 )(function* (input) {
968 const { state } = yield* SynchronizedRef.get(stateRef);
969 return yield* locate(
970 state,
971 input,
972 state.sessions.filter(
973 (session) => session.threadId === input.threadId && session.deviceId === input.deviceId,
974 ),
975 );
976 });
977
978 // Sessions live in memory, so this removes every launcher a previous run left behind.
979 yield* pruneLaunchers;
980
981 return {
982 ...DeviceService.of({
983 testHost,
984 updateTool: Effect.fn("DeviceService.updateTool")(function (tool) {
985 return lifecycleLock.withPermit(
986 Effect.gen(function* () {
987 if (!installTool)
988 return yield* new DeviceOperationError({
989 operation: "update device tool",
990 reason: "request_failed",
991 cause: new Error("Tool installation is unavailable in this device service."),
992 });
993 yield* installTool(tool);
994 return yield* inspect;
995 }),
996 );
997 }),
998 retryHost,
999 inspect,
1000 easAccount: Effect.fn("DeviceService.easAccount")(function () {
1001 return Effect.fail(
1002 new DeviceEasAccountError({
1003 reason: "EAS accounts are unavailable in this device service.",
1004 }),
1005 );
1006 }),
1007 agentTarget: Effect.fn("DeviceService.agentTarget")(function* (input) {
1008 const host = yield* resolveHost(input.hostId);
1009 const ready = yield* agentReadinessIfSupported(input.hostId);
1010 if (!ready)
1011 return yield* new DeviceHostUnavailableError({
1012 hostId: host.id,
1013 hostLabel: host.label,
1014 reason:
1015 "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
1016 });
1017 const { configPath, agentDeviceId } = yield* lifecycleLock.withPermit(
1018 Effect.gen(function* () {
1019 if (hosts.get(host.id) !== host)
1020 return yield* new DeviceHostUnavailableError({
1021 hostId: host.id,
1022 hostLabel: host.label,
1023 reason: "Host configuration changed. Retry the operation.",
1024 });
1025 if (ready.devices.agentEndpoint) {
1026 const endpoint = yield* ready.devices.agentEndpoint(input.deviceId);
1027 return {
1028 configPath: yield* configureAgent(input.hostId, endpoint, input.deviceId),
1029 agentDeviceId: endpoint.agentDeviceId,
1030 };
1031 }
1032 if (!ready.agentDevice)
1033 return yield* new DeviceHostUnavailableError({
1034 hostId: host.id,
1035 hostLabel: host.label,
1036 reason: "This host has no agent-device daemon.",
1037 });
1038 return {
1039 configPath: yield* configureAgent(input.hostId, ready.agentDevice),
1040 agentDeviceId: input.deviceId,
1041 };
1042 }),
1043 );
1044 const session = yield* agentDeviceSession(
1045 input.threadId,
1046 input.hostId,
1047 input.deviceId,
1048 ).pipe(Effect.provideService(Crypto.Crypto, crypto));
1049 return { agentDeviceId, session, args: ["--config", configPath, "--session", session] };
1050 }),
1051 agentLauncher: Effect.fn("DeviceService.agentLauncher")(function* ({
1052 targetArgs,
1053 ...target
1054 }) {
1055 if (!launchers)
1056 return yield* new DeviceHostUnavailableError({
1057 hostId: target.hostId,
1058 reason: "Agent launchers are unavailable in this device service.",
1059 });
1060 const session = yield* agentDeviceSession(
1061 target.threadId,
1062 target.hostId,
1063 target.deviceId,
1064 ).pipe(Effect.provideService(Crypto.Crypto, crypto));
1065 return yield* launcherLock.withPermit(
1066 Effect.gen(function* () {
1067 const { state } = yield* SynchronizedRef.get(stateRef);
1068 if (
1069 !state.sessions.some(
1070 (live) =>
1071 live.threadId === target.threadId &&
1072 live.hostId === target.hostId &&
1073 live.deviceId === target.deviceId,
1074 )
1075 )
1076 return Option.none();
1077 const launcher = yield* launchers.bind({ session, targetArgs });
1078 boundLaunchers.set(session, launcher);
1079 return Option.some(launcher);
1080 }),
1081 );
1082 }),
1083 state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
1084 subscribe: PubSub.subscribe(statePubSub),
1085 configure,
1086 list,
1087 open,
1088 close,
1089 shutdown,
1090 detail,
1091 action,
1092 screenshot,
1093 locateDevice,
1094 locateSession,
1095 readiness,
1096 readinessIfSupported,
1097 agentReadinessIfSupported,
1098 currentReadiness,
1099 sessionsForThread,
1100 }),
1101 setHostStatus,
1102 withLifecycleLock: lifecycleLock.withPermit,
1103 refreshHosts: Effect.gen(function* () {
1104 const summaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
1105 const unchanged = (id: DeviceHostId) =>
1106 hosts.has(id) && hosts.get(id) === publishedHosts.get(id);
1107 yield* publish((state) => ({
1108 ...state,
1109 hosts: summaries,
1110 hostStatuses: Object.fromEntries(
1111 Object.entries(state.hostStatuses).filter(([id]) => unchanged(id)),
1112 ),
1113 devices: state.devices.filter((device) => unchanged(device.hostId)),
1114 sessions: state.sessions.filter((session) => unchanged(session.hostId)),
1115 }));
1116 publishedHosts = new Map(hosts);
1117 }),
1118 };
1119});
1120
1121/** @public */
1122/** @public */
1123export const make = Effect.gen(function* () {
1124 const localHost = yield* DeviceHost.DeviceHost;
1125 const config = yield* ServerConfig.ServerConfig;
1126 const fs = yield* FileSystem.FileSystem;
1127 const path = yield* Path.Path;
1128 const runner = yield* ProcessRunner.ProcessRunner;
1129 const settings = yield* ServerSettings.ServerSettingsService;
1130 const scope = yield* Scope.Scope;
1131 const hosts = new Map<DeviceHostId, DeviceHost.DeviceHost["Service"]>([
1132 [localHost.id, localHost],
1133 ]);
1134 const crypto = yield* Crypto.Crypto;
1135 const configPath = (hostId: DeviceHostId, deviceId?: DeviceId) =>
1136 agentDeviceConfigPath(config.stateDir, hostId, path, deviceId).pipe(
1137 Effect.provideService(Crypto.Crypto, crypto),
1138 );
1139 const configureAgent = Effect.fn("DeviceService.configureAgent")(
1140 function* (
1141 hostId: DeviceHostId,
1142 endpoint: DeviceHost.AgentDaemonEndpoint,
1143 deviceId?: DeviceId,
1144 ) {
1145 const file = yield* configPath(hostId, deviceId);
1146 yield* writeAgentDeviceConfig(file, endpoint);
1147 return file;
1148 },
1149 Effect.provideService(FileSystem.FileSystem, fs),
1150 Effect.provideService(Path.Path, path),
1151 Effect.mapError(
1152 (cause) =>
1153 new DeviceOperationError({
1154 operation: "configure agent",
1155 reason: "settings_failed",
1156 cause,
1157 }),
1158 ),
1159 );
1160 const agentCli = resolveNodeExecutable("Device automation").pipe(
1161 Effect.andThen(ensureAgentDevice(config.baseDir)),
1162 Effect.provideService(FileSystem.FileSystem, fs),
1163 Effect.provideService(Path.Path, path),
1164 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1165 Effect.map((tool) => tool.entryPath),
1166 Effect.mapError((error) =>
1167 error._tag === "NodeRuntimeUnavailableError"
1168 ? new DeviceHostUnavailableError({
1169 hostId: LOCAL_DEVICE_HOST_ID,
1170 hostLabel: LOCAL_DEVICE_HOST_LABEL,
1171 reason: nodeRuntimeUnavailableMessage("Device automation"),
1172 cause: error,
1173 })
1174 : new DeviceOperationError({
1175 operation: "install agent CLI",
1176 reason: "command_failed",
1177 cause: error,
1178 }),
1179 ),
1180 );
1181 const launchers: AgentDeviceLaunchers = {
1182 bind: Effect.fn("DeviceService.bindLauncher")(
1183 function* (input) {
1184 const entryPath = yield* agentCli;
1185 // The unbound launcher stays current for agents that still call it with flags.
1186 yield* ensureAgentDeviceShim({ entryPath, stateDir: config.stateDir });
1187 return yield* bindAgentDeviceLauncher({ entryPath, stateDir: config.stateDir, ...input });
1188 },
1189 Effect.provideService(FileSystem.FileSystem, fs),
1190 Effect.provideService(Path.Path, path),
1191 Effect.catchTags({
1192 NodeRuntimeUnavailableError: (cause) =>
1193 Effect.fail(
1194 new DeviceHostUnavailableError({
1195 hostId: LOCAL_DEVICE_HOST_ID,
1196 hostLabel: LOCAL_DEVICE_HOST_LABEL,
1197 reason: nodeRuntimeUnavailableMessage("Device automation"),
1198 cause,
1199 }),
1200 ),
1201 PlatformError: (cause) =>
1202 Effect.fail(
1203 new DeviceHostUnavailableError({
1204 hostId: LOCAL_DEVICE_HOST_ID,
1205 hostLabel: LOCAL_DEVICE_HOST_LABEL,
1206 reason: "Could not prepare the agent-device launcher.",
1207 cause,
1208 }),
1209 ),
1210 }),
1211 ),
1212 prune: (live) =>
1213 pruneAgentDeviceLaunchers({ stateDir: config.stateDir, live }).pipe(
1214 Effect.provideService(FileSystem.FileSystem, fs),
1215 Effect.provideService(Path.Path, path),
1216 ),
1217 // Best effort: an unreachable host fails fast in the launcher's connection check, and the
1218 // launcher goes either way. Only a failed or timed-out close can leave the device claimed.
1219 release: (launcher) =>
1220 resolveNodeExecutable("Device automation").pipe(
1221 Effect.flatMap((node) =>
1222 runner.run({
1223 command: node,
1224 args: [path.join(path.dirname(launcher), "agent-device-launcher.mjs"), "close"],
1225 env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
1226 timeout: "15 seconds",
1227 timeoutBehavior: "timedOutResult",
1228 }),
1229 ),
1230 Effect.provideService(FileSystem.FileSystem, fs),
1231 Effect.provideService(Path.Path, path),
1232 Effect.flatMap((result) => {
1233 const outcome = agentDeviceCloseOutcome(result);
1234 return outcome === "failed" || outcome === "timed-out"
1235 ? Effect.logWarning("Could not end the agent-device session", {
1236 launcher,
1237 outcome,
1238 stderr: result.stderr.slice(-500),
1239 })
1240 : Effect.void;
1241 }),
1242 Effect.tapError((cause) =>
1243 Effect.logWarning("Could not end the agent-device session", { launcher, cause }),
1244 ),
1245 Effect.ignore,
1246 ),
1247 };
1248 const probeContext =
1249 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();
1250 const localTargetContext =
1251 yield* Effect.context<Effect.Services<ReturnType<typeof isLocalSshDeviceHost>>>();
1252 const service = yield* makeWithHosts(
1253 hosts,
1254 (host) =>
1255 Effect.gen(function* () {
1256 if (yield* isLocalSshDeviceHost(host).pipe(Effect.provide(localTargetContext))) {
1257 return yield* localHost.summary;
1258 }
1259 return yield* SshDeviceHost.probe(host).pipe(Effect.provide(probeContext));
1260 }).pipe(
1261 Effect.mapError(
1262 (error) =>
1263 new DeviceOperationError({
1264 operation: "probe host",
1265 reason: "request_failed",
1266 cause: error,
1267 }),
1268 ),
1269 ),
1270 configureAgent,
1271 (tool) =>
1272 (tool === "hub" ? ensureDeviceHub(config.baseDir) : ensureAgentDevice(config.baseDir)).pipe(
1273 Effect.provideService(FileSystem.FileSystem, fs),
1274 Effect.provideService(Path.Path, path),
1275 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1276 Effect.mapError(
1277 (cause) =>
1278 new DeviceOperationError({
1279 operation: "update device tool",
1280 reason: "command_failed",
1281 // Only the exit code goes into the shown message; npm's stderr can carry registry credentials.
1282 ...(cause.exitCode !== undefined ? { exitCode: cause.exitCode } : {}),
1283 cause,
1284 }),
1285 ),
1286 ),
1287 launchers,
1288 );
1289 const hostContext =
1290 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
1291 const easContext =
1292 yield* Effect.context<Effect.Services<ReturnType<typeof EasDeviceHost.make>>>();
1293 const configured = new Map<string, { config: DeviceHostConfig; scope: Scope.Closeable }>();
1294 const unchanged = (current: DeviceHostConfig, previous: DeviceHostConfig) =>
1295 current.kind === "ssh" && previous.kind === "ssh"
1296 ? current.label === previous.label &&
1297 current.target === previous.target &&
1298 current.port === previous.port &&
1299 current.identityFile === previous.identityFile
1300 : JSON.stringify(current) === JSON.stringify(previous);
1301 const reconcile = Effect.fn("DeviceService.reconcile")(function* (
1302 configuredHosts: ReadonlyArray<DeviceHostConfig>,
1303 ) {
1304 const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(
1305 Effect.provide(localTargetContext),
1306 );
1307 const removed = yield* service.withLifecycleLock(
1308 Effect.gen(function* () {
1309 const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
1310 for (const [id, previous] of configured) {
1311 if (next.some((host) => host.id === id && unchanged(host, previous.config))) continue;
1312 hosts.delete(id);
1313 configured.delete(id);
1314 removed.push({ id, scope: previous.scope });
1315 }
1316 if (removed.length > 0) yield* service.refreshHosts;
1317 return removed;
1318 }),
1319 );
1320 // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.
1321 yield* Effect.forEach(
1322 removed,
1323 ({ id, scope }) =>
1324 Effect.gen(function* () {
1325 yield* Scope.close(scope, Exit.void);
1326 yield* fs.remove(yield* configPath(id), { force: true }).pipe(Effect.ignore);
1327 }),
1328 { concurrency: 4, discard: true },
1329 );
1330 yield* service.withLifecycleLock(
1331 Effect.gen(function* () {
1332 let added = false;
1333 for (const host of next) {
1334 if (configured.has(host.id)) continue;
1335 added = true;
1336 const hostScope = yield* Scope.fork(scope);
1337 if (host.kind === "eas") {
1338 // Closing this scope stops the host's running sessions, so a changed
1339 // limit or token never leaves a billed session behind.
1340 const instance = yield* EasDeviceHost.make(host).pipe(
1341 Effect.provideService(Scope.Scope, hostScope),
1342 Effect.provide(easContext),
1343 );
1344 hosts.set(host.id, instance);
1345 configured.set(host.id, { config: host, scope: hostScope });
1346 continue;
1347 }
1348 const instance = yield* SshDeviceHost.make(
1349 host,
1350 (ready) =>
1351 (ready.agentDevice
1352 ? configureAgent(host.id, ready.agentDevice).pipe(Effect.asVoid)
1353 : Effect.void
1354 ).pipe(
1355 Effect.mapError(
1356 (error) =>
1357 new DeviceHost.DeviceHostError({
1358 hostId: host.id,
1359 step: "configuring agent access",
1360 cause: error,
1361 }),
1362 ),
1363 ),
1364 (status, detail) =>
1365 service
1366 .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })
1367 .pipe(Effect.asVoid),
1368 ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));
1369 hosts.set(host.id, instance);
1370 configured.set(host.id, { config: host, scope: hostScope });
1371 }
1372 // Refresh again after removed scopes closed so a late status write from an old host cannot linger.
1373 if (added || removed.length > 0) yield* service.refreshHosts;
1374 }),
1375 );
1376 });
1377 const changes = yield* settings.subscribeChanges;
1378 // Settings keep EAS hosts apart from SSH hosts; an id both lists use stays the SSH host's.
1379 const configuredHosts = (value: {
1380 readonly deviceHosts: ReadonlyArray<SshDeviceHostConfig>;
1381 readonly easDeviceHosts: ReadonlyArray<EasDeviceHostConfig>;
1382 }): ReadonlyArray<DeviceHostConfig> => [
1383 ...value.deviceHosts,
1384 ...value.easDeviceHosts.filter((host) => !value.deviceHosts.some((ssh) => ssh.id === host.id)),
1385 ];
1386 yield* reconcile(configuredHosts(yield* settings.getSettings));
1387 yield* changes.pipe(
1388 Stream.runForEach((value) => reconcile(configuredHosts(value))),
1389 Effect.forkIn(scope),
1390 );
1391 yield* Effect.addFinalizer(() =>
1392 Effect.forEach(configured.values(), (value) => Scope.close(value.scope, Exit.void), {
1393 discard: true,
1394 concurrency: 4,
1395 }),
1396 );
1397 const easAccount: DeviceService["Service"]["easAccount"] = Effect.fn("DeviceService.easAccount")(
1398 function* (input) {
1399 const saved =
1400 input.hostId === undefined
1401 ? ""
1402 : ((yield* settings.getSettings).easDeviceHosts.find((host) => host.id === input.hostId)
1403 ?.accessToken ?? "");
1404 const credential = yield* resolveExpoCredential(input.accessToken ?? saved);
1405 const viewer = yield* makeExpoApi(yield* HttpClient.HttpClient, credential).viewer;
1406 return { signedInAs: viewer.name, credentialSource: credential.source, apps: viewer.apps };
1407 },
1408 Effect.provide(easContext),
1409 // Only bounded text reaches the browser: the credential errors' own
1410 // guidance, or a category for what Expo answered, never Expo's text.
1411 Effect.mapError(
1412 (cause) =>
1413 new DeviceEasAccountError({
1414 reason:
1415 cause._tag === "ExpoApiError"
1416 ? cause.status === 401 || cause.status === 403
1417 ? `Expo rejected the credential (HTTP ${cause.status}).`
1418 : cause.rejected
1419 ? "Expo refused the account check."
1420 : "Could not complete the Expo account check."
1421 : cause.message,
1422 }),
1423 ),
1424 );
1425
1426 return {
1427 ...service,
1428 easAccount,
1429 };
1430});
1431
1432export const layer = Layer.effect(DeviceService, make).pipe(Layer.provide(LocalDeviceHost.layer));
1433
1434export const stateStream = (service: DeviceService["Service"]): Stream.Stream<DeviceServiceState> =>
1435 Stream.unwrap(
1436 Effect.gen(function* () {
1437 // Subscribe before reading so no change is lost.
1438 const subscription = yield* service.subscribe;
1439 const initial = yield* service.state;
1440 return Stream.concat(Stream.make(initial), Stream.fromSubscription(subscription));
1441 }),
1442 ).pipe(Stream.scoped);