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