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

DeviceService.ts

1,497 lines58.4 KB

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