TypeScript
feat(server): EAS Simulator device hosts (#21844)
Julius Marmingeaee25acd17aa
diff --git a/apps/server/src/device/AgentDeviceTarget.test.ts b/apps/server/src/device/AgentDeviceTarget.test.tsindex 448fd592e69..24a71c34c4e 100644--- a/apps/server/src/device/AgentDeviceTarget.test.ts+++ b/apps/server/src/device/AgentDeviceTarget.test.ts@@ -94,7 +94,6 @@ if (process.env.AGENT_DEVICE_DAEMON_BASE_URL) process.exit(2);`,yield* writeAgentDeviceConfig(file, {baseUrl: `http://127.0.0.1:${1000 + index}`,token: `token-${index}`,- entryPath,});const invoke = (file: string) =>exec(@@ -117,10 +116,14 @@ if (process.env.AGENT_DEVICE_DAEMON_BASE_URL) process.exit(2);`,yield* writeAgentDeviceConfig(files[0]!, {baseUrl: "http://127.0.0.1:2000",token: "new",- entryPath,});expect((yield* Effect.promise(() => invoke(files[0]!))).daemonAuthToken).toBe("new");expect(yield* fs.readFileString(files[1]!)).toBe(second);+ // Hosts with a daemon per device get a file per device, apart from the host's own.+ const perDevice = yield* Effect.forEach(["udid-1", "udid-2"], (device) =>+ agentDeviceConfigPath(dir, "eas", path, device),+ );+ expect(new Set([...perDevice, yield* agentDeviceConfigPath(dir, "eas", path)]).size).toBe(3);expect(yield* agentDeviceSession("thread", "mini", "same-id")).not.toBe(yield* agentDeviceSession("thread", "android", "same-id"),);diff --git a/apps/server/src/device/AgentDeviceTarget.ts b/apps/server/src/device/AgentDeviceTarget.tsindex d9c6dda12a6..de5ff7ec713 100644--- a/apps/server/src/device/AgentDeviceTarget.ts+++ b/apps/server/src/device/AgentDeviceTarget.ts@@ -5,7 +5,7 @@ import * as Schema from "effect/Schema";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";-import type { AgentDeviceEndpoint } from "./DeviceHost.ts";+import type { AgentDaemonEndpoint } from "./DeviceHost.ts";const encodeEndpoint = Schema.encodeEffect(Schema.fromJsonString(@@ -21,16 +21,26 @@ const key = Effect.fn("AgentDeviceTarget.key")(function* (value: string) {return Hex.encode(digest).slice(0, 24);});-/** A stable file per host lets forwarded endpoints change without retargeting other commands. */-export const agentDeviceConfigPath = (stateDir: string, hostId: string, path: Path.Path) =>- key(hostId).pipe(Effect.map((hash) => path.join(stateDir, "device", "hosts", `${hash}.json`)));+/**+ * A stable file per host lets forwarded endpoints change without retargeting+ * other commands. Hosts with a daemon per device get a file per device.+ */+export const agentDeviceConfigPath = (+ stateDir: string,+ hostId: string,+ path: Path.Path,+ deviceId?: string,+) =>+ key(deviceId === undefined ? hostId : JSON.stringify([hostId, deviceId])).pipe(+ Effect.map((hash) => path.join(stateDir, "device", "hosts", `${hash}.json`)),+ );export const agentDeviceSession = (threadId: string, hostId: string, deviceId: string) =>key(JSON.stringify([threadId, hostId, deviceId])).pipe(Effect.map((hash) => `t3-${hash}`));export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")(function* (file: string,- endpoint: AgentDeviceEndpoint,+ endpoint: AgentDaemonEndpoint,) {const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;diff --git a/apps/server/src/device/DeviceHost.ts b/apps/server/src/device/DeviceHost.tsindex fdc01ee664f..13a1e55e148 100644--- a/apps/server/src/device/DeviceHost.ts+++ b/apps/server/src/device/DeviceHost.ts@@ -1,6 +1,7 @@import type {DeviceBootError,DeviceHostId,+ DeviceHostUnavailableError,DeviceHostSummary,DeviceOperationError,DevicePlatform,@@ -76,6 +77,20 @@ export interface AgentDeviceEndpoint {export type HostDevice = Omit<DeviceSummary, "hostId">;+/** Where a device is being opened from, for hosts whose devices depend on the project. */+export interface DeviceOpenContext {+ readonly workspaceRoot?: string | undefined;+}++export type AgentDaemonEndpoint = Pick<AgentDeviceEndpoint, "baseUrl" | "token">;++/** Where the proxy sends a device hub request, for hosts that serve several upstreams. */+export interface HubUpstream {+ readonly url: string;+ readonly headers: Readonly<Record<string, string>>;+ readonly protocols: ReadonlyArray<string>;+}+/** Discovery and lifecycle for the devices a ready host can run. */export interface DeviceOperations {readonly list: Effect.Effect<@@ -93,7 +108,8 @@ export interface DeviceOperations {*/readonly boot: (device: HostDevice,- ) => Effect.Effect<string, DeviceOperationError | DeviceBootError>;+ context?: DeviceOpenContext,+ ) => Effect.Effect<string, DeviceOperationError | DeviceBootError | DeviceHostUnavailableError>;/** Prepares the stream of a device that is already booted. */readonly attach: (device: HostDevice) => Effect.Effect<void, DeviceOperationError>;readonly shutdown: (device: {@@ -101,6 +117,22 @@ export interface DeviceOperations {readonly platform: DevicePlatform;}) => Effect.Effect<void, DeviceOperationError>;readonly screenshot: (device: HostDevice) => Effect.Effect<Uint8Array, DeviceOperationError>;+ /**+ * For hosts that run one agent-device daemon per device instead of one per+ * host. `agentDeviceId` is the id agent-device selects the device by, when+ * it differs from the host's device id.+ */+ readonly agentEndpoint?: (+ deviceId: string,+ ) => Effect.Effect<+ AgentDaemonEndpoint & { readonly agentDeviceId: string },+ DeviceHostUnavailableError+ >;+ /**+ * Set by hosts that end devices on their own (EAS stops sessions at their+ * limits), so a session on a device the host stops listing is dropped.+ */+ readonly endsDevices?: boolean;}export interface DeviceHostReady {@@ -116,16 +148,24 @@ export interface DeviceHostReady {readonly serveSimAxSettings: string | null;readonly serveSimCli: string | null;};+ /** Routes proxied hub requests itself; otherwise they go to `hub.origin`. */+ readonly upstream?: (+ hubPath: string,+ search: URLSearchParams,+ ) => Effect.Effect<HubUpstream | null>;}export interface DeviceHostAgentReady extends DeviceHostReady {- readonly agentDevice: AgentDeviceEndpoint;+ /** Null when each device has its own daemon; see `DeviceOperations.agentEndpoint`. */+ readonly agentDevice: AgentDeviceEndpoint | null;}export class DeviceHost extends Context.Service<DeviceHost,{readonly id: DeviceHostId;+ /** The name errors and the Device panel show for this host. */+ readonly label: string;readonly summary: Effect.Effect<DeviceHostSummary>;readonly inspect?: Effect.Effect<DeviceHostSummary, DeviceHostError>;readonly platformAvailability: (diff --git a/apps/server/src/device/DeviceHubProxy.test.ts b/apps/server/src/device/DeviceHubProxy.test.tsindex 53f4a061244..f59952a0aa9 100644--- a/apps/server/src/device/DeviceHubProxy.test.ts+++ b/apps/server/src/device/DeviceHubProxy.test.ts@@ -10,6 +10,7 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import { HttpClient, HttpClientResponse, HttpRouter } from "effect/http";import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";+import type * as DeviceHost from "./DeviceHost.ts";import * as DeviceService from "./DeviceService.ts";import * as DeviceHubProxy from "./DeviceHubProxy.ts";@@ -22,6 +23,7 @@ const fixture = (scopes: ReadonlyArray<AuthEnvironmentScope>,fail = false,authError?: EnvironmentAuth.ServerAuthCredentialError | EnvironmentAuth.ServerAuthInternalError,+ upstream?: DeviceHost.DeviceHostReady["upstream"],) => {let finalized = 0;const requests: string[] = [];@@ -34,7 +36,10 @@ const fixture = (finalized++;});if (fail) return yield* Effect.die(new Error("upstream failed"));- return HttpClientResponse.fromWeb(request, new Response("frame"));+ return HttpClientResponse.fromWeb(+ request,+ new Response("frame", { headers: { "set-cookie": "upstream=1" } }),+ );}),);const { handler, dispose } = HttpRouter.toWebHandler(@@ -55,7 +60,11 @@ const fixture = (Layer.provideMerge(Layer.succeed(DeviceService.DeviceService, {currentReadiness: () =>- Effect.succeed({ hostId: LOCAL_DEVICE_HOST_ID, hub: { origin: "http://hub.test" } }),+ Effect.succeed({+ hostId: LOCAL_DEVICE_HOST_ID,+ hub: { origin: "http://hub.test" },+ ...(upstream ? { upstream } : {}),+ }),} as DeviceService.DeviceService["Service"]),),Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),@@ -167,6 +176,39 @@ describe("device hub proxy", () => {expect(headers[0]?.["content-type"]).toBe("application/json");});+ it("sends requests a host routes itself to its upstream with its credentials", async () => {+ const { handler, requests, headers } = fixture(+ [AuthOrchestrationReadScope],+ false,+ undefined,+ (hubPath, search) =>+ Effect.succeed(+ hubPath === "/vendor/serve-sim/api"+ ? {+ url: `https://session.test${hubPath.slice("/vendor/serve-sim".length)}?${search}`,+ headers: { authorization: "Bearer session-token" },+ protocols: [],+ }+ : null,+ ),+ );+ const routed = await handler(+ new Request("http://t3.test/api/device-hub/vendor/serve-sim/api?device=udid-1&hostId=eas", {+ headers: { authorization: "Bearer environment-token" },+ }),+ );+ expect(routed.status).toBe(200);+ expect(routed.headers.get("set-cookie")).toBeNull();+ await routed.text();+ expect(requests).toEqual(["https://session.test/api?device=udid-1"]);+ expect(headers[0]?.authorization).toBe("Bearer session-token");+ const unrouted = await handler(+ new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/udid-2/stream.mjpeg"),+ );+ expect(unrouted.status).toBe(404);+ expect(requests).toHaveLength(1);+ });+it("never forwards the vendor shell endpoint", async () => {const { handler, requests } = fixture([AuthOrchestrationOperateScope]);expect(diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.tsindex a0a8a5f5d0a..642aa20b04c 100644--- a/apps/server/src/device/DeviceHubProxy.ts+++ b/apps/server/src/device/DeviceHubProxy.ts@@ -83,10 +83,12 @@ const forwardHeaders = (request: HttpServerRequest.HttpServerRequest, origin: stconst proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (request: HttpServerRequest.HttpServerRequest,upstreamUrl: string,+ protocols: ReadonlyArray<string> = [],) {const client = yield* request.upgrade;const upstream = yield* Socket.makeWebSocket(upstreamUrl, {openTimeout: "10 seconds",+ ...(protocols.length > 0 ? { protocols: [...protocols] } : {}),}).pipe(Effect.provide(NodeSocket.layerWebSocketConstructor));yield* Effect.scoped(Effect.gen(function* () {@@ -115,12 +117,15 @@ const pumpFrames =const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (request: HttpServerRequest.HttpServerRequest,upstreamUrl: string,- hubOrigin: string,+ extraHeaders: Readonly<Record<string, string>> = {},) {const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);const method = request.method;const upstreamRequest = HttpClientRequest.make(method)(upstreamUrl).pipe(- HttpClientRequest.setHeaders(forwardHeaders(request, hubOrigin)),+ HttpClientRequest.setHeaders({+ ...forwardHeaders(request, new URL(upstreamUrl).origin),+ ...extraHeaders,+ }),method === "GET" || method === "HEAD"? (self) => self: // A bare stream body is sent as octet-stream; serve-sim refuses WebRTC@@ -132,7 +137,13 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (const response = yield* httpClient.execute(upstreamRequest);const headers: Record<string, string> = {};for (const [name, value] of Object.entries(response.headers)) {- if (name === "content-encoding" || name === "transfer-encoding" || name === "connection") {+ // A cookie from an upstream such as an EAS session's preview host would land on T3's origin.+ if (+ name === "content-encoding" ||+ name === "transfer-encoding" ||+ name === "connection" ||+ name === "set-cookie"+ ) {continue;}if (value !== undefined) headers[name] = value;@@ -183,14 +194,16 @@ const handler = Effect.gen(function* () {upstreamSearch.delete("wsTicket");upstreamSearch.delete("hostId");const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";- const upstreamPath = `${hubPath}${search}`;+ // Hosts with several upstreams (one per cloud session) route and authenticate requests themselves.+ const routed = ready.upstream ? yield* ready.upstream(hubPath, upstreamSearch) : undefined;+ if (routed === null) {+ return HttpServerResponse.text("Not Found", { status: 404 });+ }+ const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`;if (upgrade) {- return yield* proxyWebSocket(- request,- `${ready.hub.origin.replace(/^http/, "ws")}${upstreamPath}`,- );+ return yield* proxyWebSocket(request, upstreamUrl.replace(/^http/, "ws"), routed?.protocols);}- return yield* proxyHttp(request, `${ready.hub.origin}${upstreamPath}`, ready.hub.origin);+ return yield* proxyHttp(request, upstreamUrl, routed?.headers);});export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler);diff --git a/apps/server/src/device/DeviceMultiHost.test.ts b/apps/server/src/device/DeviceMultiHost.test.tsindex 3250908299a..7bbd8418de7 100644--- a/apps/server/src/device/DeviceMultiHost.test.ts+++ b/apps/server/src/device/DeviceMultiHost.test.ts@@ -55,6 +55,7 @@ it.effect("keeps hosts independent when serials collide and another host fails",};return {id,+ label: id,summary: Effect.succeed({id,label: id,diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.tsindex 58dec58369e..f7e578e4d1a 100644--- a/apps/server/src/device/DeviceService.test.ts+++ b/apps/server/src/device/DeviceService.test.ts@@ -89,6 +89,7 @@ const fixture = Effect.fn("fixture")(function* (| DeviceHost.AgentDeviceStartError,inspectError = false,installTool?: Parameters<typeof DeviceService.makeWithHosts>[3],+ options: { readonly endsDevices?: boolean } = {},) {const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);const starts: string[] = [];@@ -160,13 +161,16 @@ const fixture = Effect.fn("fixture")(function* (const ready: DeviceHost.DeviceHostReady = {nodePath: process.execPath,hub: { origin: "http://device.test" },- devices: makeDeviceHubOperations({- hostId: LOCAL_DEVICE_HOST_ID,- origin: "http://device.test",- http,- run,- androidAvailable: Effect.succeed(true),- }),+ devices: {+ ...makeDeviceHubOperations({+ hostId: LOCAL_DEVICE_HOST_ID,+ origin: "http://device.test",+ http,+ run,+ androidAvailable: Effect.succeed(true),+ }),+ ...(options.endsDevices ? { endsDevices: true } : {}),+ },helpers: { serveSimAxSettings: null, serveSimCli: null },run,};@@ -183,6 +187,7 @@ const fixture = Effect.fn("fixture")(function* (}: {}),id: LOCAL_DEVICE_HOST_ID,+ label: "This machine",summary: Effect.succeed({id: LOCAL_DEVICE_HOST_ID,kind: "local",@@ -251,6 +256,10 @@ const fixture = Effect.fn("fixture")(function* (}),),);+ // The host ending a device on its own, as EAS does at a session's limits.+ const endDevice = () => {+ booted = false;+ };return {service,starts,@@ -261,6 +270,7 @@ const fixture = Effect.fn("fixture")(function* (devices,encoderResult,discoveryErrors,+ endDevice,};});@@ -509,6 +519,36 @@ it.effect("publishes boot progress and does not restore sessions after support i}).pipe(Effect.scoped),);+it.effect.each([+ { case: "drops it on a host that ends devices itself", endsDevices: true, kept: 0 },+ {+ case: "keeps it on a host that can miss a device for one listing",+ endsDevices: false,+ kept: 1,+ },+])("when a host stops listing a session's device, $case", ({ endsDevices, kept }) =>+ Effect.gen(function* () {+ const { service, endDevice } = yield* fixture(+ Effect.void,+ undefined,+ false,+ undefined,+ false,+ undefined,+ { endsDevices },+ );+ yield* service.configure({ enabled: true });+ const threadId = ThreadId.make("ended-by-host");+ yield* service.open({ threadId, deviceId: "Pixel_API_35", platform: "android" });+ expect((yield* service.state).sessions.map((session) => session.deviceId)).toEqual([+ "emulator-5554",+ ]);+ endDevice();+ yield* service.list;+ expect((yield* service.state).sessions).toHaveLength(kept);+ }).pipe(Effect.scoped),+);+describe("device discovery after server restart", () => {it.effect("captures an explicit device before any client lists devices", () =>Effect.gen(function* () {@@ -718,6 +758,7 @@ it.effect.each(["shutdown", "close"] as const)(};const host: DeviceHost.DeviceHost["Service"] = {id: LOCAL_DEVICE_HOST_ID,+ label: "This machine",summary: Effect.succeed({id: LOCAL_DEVICE_HOST_ID,kind: "local",@@ -816,6 +857,7 @@ it.effect.each([};const host: DeviceHost.DeviceHost["Service"] = {id: LOCAL_DEVICE_HOST_ID,+ label: "This machine",summary: Effect.succeed({id: LOCAL_DEVICE_HOST_ID,kind: "local",@@ -887,6 +929,7 @@ it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(};const host: DeviceHost.DeviceHost["Service"] = {id: hostId,+ label: "Test device host",summary: Effect.succeed({id: hostId,kind: hostId === LOCAL_DEVICE_HOST_ID ? "local" : "ssh",@@ -1167,6 +1210,7 @@ it.effect("reconciles SSH host settings without publishing no-op changes", () =>const removedFiles: string[] = [];const localHost: DeviceHost.DeviceHost["Service"] = {id: LOCAL_DEVICE_HOST_ID,+ label: "This machine",summary: Effect.succeed({id: LOCAL_DEVICE_HOST_ID,label: "Local",@@ -1270,6 +1314,7 @@ it.effect("a failed tool update reports npm's exit code but not its output", ()Effect.gen(function* () {const host: DeviceHost.DeviceHost["Service"] = {id: LOCAL_DEVICE_HOST_ID,+ label: "This machine",summary: Effect.succeed({id: LOCAL_DEVICE_HOST_ID,kind: "local",diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.tsindex f6793bb4d5d..d9963033b38 100644--- a/apps/server/src/device/DeviceService.ts+++ b/apps/server/src/device/DeviceService.ts@@ -22,6 +22,7 @@ import {type SshDeviceHostConfig,type DeviceHostSummary,LOCAL_DEVICE_HOST_ID,+ LOCAL_DEVICE_HOST_LABEL,type ThreadId,} from "@t3tools/contracts";import { SshCommandError } from "@t3tools/ssh/errors";@@ -53,6 +54,7 @@ import { readDeviceDetail, runDeviceAction } from "./DeviceActions.ts";import * as ProcessRunner from "../processRunner.ts";import * as DeviceHost from "./DeviceHost.ts";import * as SshDeviceHost from "./SshDeviceHost.ts";+import * as EasDeviceHost from "./EasDeviceHost.ts";import * as Exit from "effect/Exit";import * as LocalDeviceHost from "./LocalDeviceHost.ts";@@ -90,7 +92,8 @@ export interface DeviceReadiness extends DeviceHost.DeviceHostReady {}export interface DeviceAgentReadiness extends DeviceReadiness {- readonly agentDevice: DeviceHost.AgentDeviceEndpoint;+ /** Null when each device has its own daemon; see `DeviceOperations.agentEndpoint`. */+ readonly agentDevice: DeviceHost.AgentDeviceEndpoint | null;}export class DeviceService extends Context.Service<@@ -100,11 +103,18 @@ export class DeviceService extends Context.Service<readonly testHost: (config: SshDeviceHostConfig,) => Effect.Effect<DeviceHostSummary, DeviceError>;+ /**+ * The agent-device flags that reach the device: its config and session,+ * and the id agent-device selects it by, which can differ from its id here.+ */readonly agentTarget: (input: {threadId: ThreadId;hostId: DeviceHostId;deviceId: DeviceId;- }) => Effect.Effect<ReadonlyArray<string>, DeviceError>;+ }) => Effect.Effect<+ { readonly agentDeviceId: string; readonly args: ReadonlyArray<string> },+ DeviceError+ >;readonly state: Effect.Effect<DeviceServiceState>;readonly subscribe: Effect.Effect<PubSub.Subscription<DeviceServiceState>, never, Scope.Scope>;readonly configure: (@@ -114,7 +124,10 @@ export class DeviceService extends Context.Service<readonly updateTool: (tool: "hub" | "agent") => Effect.Effect<DeviceServiceState, DeviceError>;readonly inspect: Effect.Effect<DeviceServiceState>;readonly retryHost: (hostId: DeviceHostId) => Effect.Effect<DeviceServiceState, DeviceError>;- readonly open: (input: DeviceOpenInput) => Effect.Effect<DeviceSession, DeviceError>;+ readonly open: (+ input: DeviceOpenInput,+ context?: DeviceHost.DeviceOpenContext,+ ) => Effect.Effect<DeviceSession, DeviceError>;readonly close: (input: DeviceCloseInput) => Effect.Effect<void, DeviceError>;readonly shutdown: (input: DeviceShutdownInput) => Effect.Effect<void, DeviceError>;readonly detail: (input: DeviceDetailInput) => Effect.Effect<DeviceDetail, DeviceError>;@@ -145,12 +158,14 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*Effect.fail(new DeviceHostUnavailableError({hostId: host.id,+ hostLabel: host.label,reason: "SSH probing is unavailable in this device service.",}),),configureAgent: (hostId: DeviceHostId,- ready: DeviceHost.DeviceHostAgentReady,+ endpoint: DeviceHost.AgentDaemonEndpoint,+ deviceId?: DeviceId,) => Effect.Effect<string, DeviceError> = (hostId) =>Effect.fail(new DeviceHostUnavailableError({@@ -243,6 +258,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*if (!(yield* readDeviceSettings).enabled) {return yield* new DeviceHostUnavailableError({hostId: host.id,+ hostLabel: host.label,reason:"Device support is off. Enable it in the Device panel before installing or starting device tools.",});@@ -265,6 +281,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*(error) =>new DeviceHostUnavailableError({hostId: host.id,+ hostLabel: host.label,reason:error._tag === "NodeRuntimeUnavailableError"? nodeRuntimeUnavailableMessage("Local device support")@@ -278,6 +295,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*if (hosts.get(host.id) !== host)return yield* new DeviceHostUnavailableError({hostId: host.id,+ hostLabel: host.label,reason: "Host configuration changed. Retry the operation.",});const { state } = yield* SynchronizedRef.get(stateRef);@@ -326,6 +344,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*(error) =>new DeviceHostUnavailableError({hostId: host.id,+ hostLabel: host.label,reason:error._tag === "NodeRuntimeUnavailableError"? nodeRuntimeUnavailableMessage("Local device support")@@ -365,6 +384,11 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {const host = hosts.get(ready.hostId);+ // A session opened while the listing ran is on a device the listing could+ // not have seen yet; only sessions from before it can be pruned by it.+ const sessionKey = (session: DeviceSession) =>+ `${session.hostId}\u0000${session.deviceId}\u0000${session.threadId}\u0000${session.openedAt}`;+ const before = new Set((yield* SynchronizedRef.get(stateRef)).state.sessions.map(sessionKey));const { devices, detail, androidDiscoveryIncomplete } = yield* fetchDevices(ready);const hostSummaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);return yield* lifecycleLock.withPermit(@@ -379,6 +403,17 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*...state.devices.filter((device) => device.hostId !== ready.hostId),...devices,],+ // A host that ends devices itself (EAS stops sessions at their limits)+ // leaves sessions on devices it no longer lists with nothing to stream.+ // Other hosts can miss a device for one listing, so theirs stay.+ sessions: ready.devices.endsDevices+ ? state.sessions.filter(+ (session) =>+ session.hostId !== ready.hostId ||+ !before.has(sessionKey(session)) ||+ devices.some((device) => device.id === session.deviceId),+ )+ : state.sessions,hostStatuses: {...state.hostStatuses,[ready.hostId]: {@@ -538,109 +573,113 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*}});- const open: DeviceService["Service"]["open"] = Effect.fn("DeviceService.open")(function* (input) {- const host = yield* resolveHost(input.hostId);- yield* ensurePlatform(host, input.platform);- const ready = yield* readiness(host.id);- let state = yield* refresh(ready);- let device = findDevice(state, host.id, input.deviceId);- if (!device) {- return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: input.deviceId });- }- if (device.platform === "android" && !device.physical) {- // Resolve the override on the device host the way its hub does.- const encoders = yield* ready.run(ready.nodePath, [- "-e",- `const { spawnSync } = require("node:child_process");-const result = spawnSync(process.env.SERVE_EMU_FFMPEG?.trim() || "ffmpeg", ["-hide_banner", "-encoders"], {- stdio: "inherit", timeout: 10000, killSignal: "SIGKILL",-});-process.exitCode = result.error ? 1 : (result.status ?? 1);`,- ]);- if (encoders.code !== 0) {- return yield* new DevicePlatformUnavailableError({- hostId: host.id,- platform: "android",- reason:- "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.",- });- }- if (!/^\s*V\S*[ \t]+libx264(?:[ \t]|$)/m.test(`${encoders.stdout}\n${encoders.stderr}`)) {- return yield* new DevicePlatformUnavailableError({- hostId: host.id,- platform: "android",- reason:- "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.",- });- }- }- if (!device.booted && input.boot !== false) {- const booting = { ...device, threadId: input.threadId };- yield* publish((current) => ({- ...current,- bootingDevices: [- ...(current.bootingDevices ?? []).filter(- (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,- ),- booting,- ],- }));- const bootedId = yield* ready.devices.boot(device).pipe(- Effect.ensuring(- publish((current) => ({- ...current,- bootingDevices: (current.bootingDevices ?? []).filter(- (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,- ),- })),- ),- );- state = yield* refresh(ready);- device = findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id);+ const open: DeviceService["Service"]["open"] = Effect.fn("DeviceService.open")(+ function* (input, context) {+ const host = yield* resolveHost(input.hostId);+ yield* ensurePlatform(host, input.platform);+ const ready = yield* readiness(host.id);+ let state = yield* refresh(ready);+ let device = findDevice(state, host.id, input.deviceId);if (!device) {- return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });+ return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: input.deviceId });}- } else if (device.booted) {- yield* ready.devices.attach(device);- }- if (hosts.get(host.id) !== host)- return yield* new DeviceHostUnavailableError({- hostId: host.id,- reason: "Host configuration changed. Retry the operation.",- });- const openedAt = DateTime.formatIso(yield* DateTime.now);- const session: DeviceSession = {- threadId: input.threadId,- hostId: host.id,- deviceId: device.id,- platform: device.platform,- openedAt,- };- yield* lifecycleLock.withPermit(- Effect.gen(function* () {- if (!(yield* readDeviceSettings).enabled)- return yield* new DeviceHostUnavailableError({+ if (device.platform === "android" && !device.physical) {+ // Resolve the override on the device host the way its hub does.+ const encoders = yield* ready.run(ready.nodePath, [+ "-e",+ `const { spawnSync } = require("node:child_process");+ const result = spawnSync(process.env.SERVE_EMU_FFMPEG?.trim() || "ffmpeg", ["-hide_banner", "-encoders"], {+ stdio: "inherit", timeout: 10000, killSignal: "SIGKILL",+ });+ process.exitCode = result.error ? 1 : (result.status ?? 1);`,+ ]);+ if (encoders.code !== 0) {+ return yield* new DevicePlatformUnavailableError({hostId: host.id,- reason: "Device support was turned off while the device was opening.",+ platform: "android",+ reason:+ "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.",});+ }+ if (!/^\s*V\S*[ \t]+libx264(?:[ \t]|$)/m.test(`${encoders.stdout}\n${encoders.stderr}`)) {+ return yield* new DevicePlatformUnavailableError({+ hostId: host.id,+ platform: "android",+ reason:+ "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.",+ });+ }+ }+ if (!device.booted && input.boot !== false) {+ const booting = { ...device, threadId: input.threadId };yield* publish((current) => ({...current,- sessions: [- ...current.sessions.filter(- (existing) =>- !(- existing.threadId === session.threadId &&- existing.hostId === session.hostId &&- existing.deviceId === session.deviceId- ),+ bootingDevices: [+ ...(current.bootingDevices ?? []).filter(+ (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,),- session,+ booting,],}));- }),- );- return session;- });+ const bootedId = yield* ready.devices.boot(device, context).pipe(+ Effect.ensuring(+ publish((current) => ({+ ...current,+ bootingDevices: (current.bootingDevices ?? []).filter(+ (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,+ ),+ })),+ ),+ );+ state = yield* refresh(ready);+ device = findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id);+ if (!device) {+ return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });+ }+ } else if (device.booted) {+ yield* ready.devices.attach(device);+ }+ if (hosts.get(host.id) !== host)+ return yield* new DeviceHostUnavailableError({+ hostId: host.id,+ hostLabel: host.label,+ reason: "Host configuration changed. Retry the operation.",+ });+ const openedAt = DateTime.formatIso(yield* DateTime.now);+ const session: DeviceSession = {+ threadId: input.threadId,+ hostId: host.id,+ deviceId: device.id,+ platform: device.platform,+ openedAt,+ };+ yield* lifecycleLock.withPermit(+ Effect.gen(function* () {+ if (!(yield* readDeviceSettings).enabled)+ return yield* new DeviceHostUnavailableError({+ hostId: host.id,+ hostLabel: host.label,+ reason: "Device support was turned off while the device was opening.",+ });+ yield* publish((current) => ({+ ...current,+ sessions: [+ ...current.sessions.filter(+ (existing) =>+ !(+ existing.threadId === session.threadId &&+ existing.hostId === session.hostId &&+ existing.deviceId === session.deviceId+ ),+ ),+ session,+ ],+ }));+ }),+ );+ return session;+ },+ );const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* (hostId: DeviceHostId,@@ -782,18 +821,36 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,const ready = yield* agentReadinessIfSupported(input.hostId);if (!ready)return yield* new DeviceHostUnavailableError({- hostId: input.hostId,+ hostId: host.id,+ hostLabel: host.label,reason:"Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",});- const configPath = yield* lifecycleLock.withPermit(+ const { configPath, agentDeviceId } = yield* lifecycleLock.withPermit(Effect.gen(function* () {if (hosts.get(host.id) !== host)return yield* new DeviceHostUnavailableError({hostId: host.id,+ hostLabel: host.label,reason: "Host configuration changed. Retry the operation.",});- return yield* configureAgent(input.hostId, ready);+ if (ready.devices.agentEndpoint) {+ const endpoint = yield* ready.devices.agentEndpoint(input.deviceId);+ return {+ configPath: yield* configureAgent(input.hostId, endpoint, input.deviceId),+ agentDeviceId: endpoint.agentDeviceId,+ };+ }+ if (!ready.agentDevice)+ return yield* new DeviceHostUnavailableError({+ hostId: host.id,+ hostLabel: host.label,+ reason: "This host has no agent-device daemon.",+ });+ return {+ configPath: yield* configureAgent(input.hostId, ready.agentDevice),+ agentDeviceId: input.deviceId,+ };}),);const session = yield* agentDeviceSession(@@ -801,7 +858,7 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,input.hostId,input.deviceId,).pipe(Effect.provideService(Crypto.Crypto, crypto));- return ["--config", configPath, "--session", session];+ return { agentDeviceId, args: ["--config", configPath, "--session", session] };}),state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),subscribe: PubSub.subscribe(statePubSub),@@ -853,14 +910,18 @@ export const make = Effect.gen(function* () {[localHost.id, localHost],]);const crypto = yield* Crypto.Crypto;- const configPath = (hostId: DeviceHostId) =>- agentDeviceConfigPath(config.stateDir, hostId, path).pipe(+ const configPath = (hostId: DeviceHostId, deviceId?: DeviceId) =>+ agentDeviceConfigPath(config.stateDir, hostId, path, deviceId).pipe(Effect.provideService(Crypto.Crypto, crypto),);const configureAgent = Effect.fn("DeviceService.configureAgent")(- function* (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) {- const file = yield* configPath(hostId);- yield* writeAgentDeviceConfig(file, ready.agentDevice);+ function* (+ hostId: DeviceHostId,+ endpoint: DeviceHost.AgentDaemonEndpoint,+ deviceId?: DeviceId,+ ) {+ const file = yield* configPath(hostId, deviceId);+ yield* writeAgentDeviceConfig(file, endpoint);return file;},Effect.provideService(FileSystem.FileSystem, fs),@@ -916,28 +977,27 @@ export const make = Effect.gen(function* () {);const hostContext =yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();- const configured = new Map<string, { config: SshDeviceHostConfig; scope: Scope.Closeable }>();+ const easContext =+ yield* Effect.context<Effect.Services<ReturnType<typeof EasDeviceHost.make>>>();+ const configured = new Map<string, { config: DeviceHostConfig; scope: Scope.Closeable }>();+ const unchanged = (current: DeviceHostConfig, previous: DeviceHostConfig) =>+ current.kind === "ssh" && previous.kind === "ssh"+ ? current.label === previous.label &&+ current.target === previous.target &&+ current.port === previous.port &&+ current.identityFile === previous.identityFile+ : JSON.stringify(current) === JSON.stringify(previous);const reconcile = Effect.fn("DeviceService.reconcile")(function* (configuredHosts: ReadonlyArray<DeviceHostConfig>,) {- const next = yield* remoteSshDeviceHosts(- configuredHosts.filter((host): host is SshDeviceHostConfig => host.kind === "ssh"),- ).pipe(Effect.provide(localTargetContext));+ const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(+ Effect.provide(localTargetContext),+ );const removed = yield* service.withLifecycleLock(Effect.gen(function* () {const removed: Array<{ id: string; scope: Scope.Closeable }> = [];for (const [id, previous] of configured) {- if (- next.some(- (host) =>- host.id === id &&- host.label === previous.config.label &&- host.target === previous.config.target &&- host.port === previous.config.port &&- host.identityFile === previous.config.identityFile,- )- )- continue;+ if (next.some((host) => host.id === id && unchanged(host, previous.config))) continue;hosts.delete(id);configured.delete(id);removed.push({ id, scope: previous.scope });@@ -963,11 +1023,24 @@ export const make = Effect.gen(function* () {if (configured.has(host.id)) continue;added = true;const hostScope = yield* Scope.fork(scope);+ if (host.kind === "eas") {+ // Closing this scope stops the host's running sessions, so a changed+ // limit or token never leaves a billed session behind.+ const instance = yield* EasDeviceHost.make(host).pipe(+ Effect.provideService(Scope.Scope, hostScope),+ Effect.provide(easContext),+ );+ hosts.set(host.id, instance);+ configured.set(host.id, { config: host, scope: hostScope });+ continue;+ }const instance = yield* SshDeviceHost.make(host,(ready) =>- configureAgent(host.id, ready).pipe(- Effect.asVoid,+ (ready.agentDevice+ ? configureAgent(host.id, ready.agentDevice).pipe(Effect.asVoid)+ : Effect.void+ ).pipe(Effect.mapError((error) =>new DeviceHost.DeviceHostError({@@ -1022,6 +1095,7 @@ export const make = Effect.gen(function* () {error._tag === "NodeRuntimeUnavailableError"? new DeviceHostUnavailableError({hostId: LOCAL_DEVICE_HOST_ID,+ hostLabel: LOCAL_DEVICE_HOST_LABEL,reason: nodeRuntimeUnavailableMessage("Device automation"),cause: error,})diff --git a/apps/server/src/device/EasDeviceHost.test.ts b/apps/server/src/device/EasDeviceHost.test.tsnew file mode 100644index 00000000000..633338b584e--- /dev/null+++ b/apps/server/src/device/EasDeviceHost.test.ts@@ -0,0 +1,907 @@+import { describe, expect, it } from "@effect/vitest";+import * as NodeServices from "@effect/platform-node/NodeServices";+import type { EasDeviceHostConfig } from "@t3tools/contracts";+import * as Deferred from "effect/Deferred";+import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";+import * as Exit from "effect/Exit";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Path from "effect/Path";+import * as Scope from "effect/Scope";+import * as TestClock from "effect/testing/TestClock";+import { HttpClient, HttpClientResponse } from "effect/http";++import * as ServerConfig from "../config.ts";+import * as ProcessRunner from "../processRunner.ts";+import * as EasDeviceHost from "./EasDeviceHost.ts";++const APP_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454";++const config = (overrides: Partial<EasDeviceHostConfig> = {}): EasDeviceHostConfig => ({+ kind: "eas",+ id: "eas",+ label: "EAS Simulator",+ appId: APP_ID,+ accessToken: "expo-token",+ maxSessionMinutes: 25,+ idleMinutes: 5,+ maxConcurrentSessions: 2,+ ...overrides,+});++interface Gate {+ readonly requested: Deferred.Deferred<void>;+ readonly release: Deferred.Deferred<void>;+}+const makeGate = Effect.all({+ requested: Deferred.make<void>(),+ release: Deferred.make<void>(),+});++/** Expo's API and one session's preview host, recording what was asked of them. */+const fakeExpo = (+ options: {+ readonly status?: () => string;+ readonly failCreate?: boolean;+ /** Expo answers the create with GraphQL errors: a refusal. */+ readonly rejectCreate?: boolean;+ readonly failStop?: () => boolean;+ readonly failList?: () => boolean;+ readonly active?: ReadonlyArray<{ id: string; status: string; name: string }>;+ readonly previewGate?: Gate;+ readonly createGate?: Gate;+ /** Holds the first session read it answers with a gate. */+ readonly sessionGate?: () => Gate | undefined;+ readonly activeIncludesCreated?: boolean;+ readonly failPreview?: boolean;+ readonly omitCreatedFromActive?: boolean;+ } = {},+) => {+ const calls: Array<{ operation: string; variables: Record<string, unknown> }> = [];+ let created = 0;+ let createdName = "";+ let previewFails = options.failPreview ?? false;+ let createFails = options.failCreate ?? false;+ let sessionGated = false;+ const http = HttpClient.make((request) =>+ Effect.gen(function* () {+ const url = new URL(request.url);+ if (url.origin === "https://preview.test") {+ expect(request.headers.authorization).toBe("Bearer preview-token");+ if (options.previewGate) {+ yield* Deferred.succeed(options.previewGate.requested, undefined);+ yield* Deferred.await(options.previewGate.release);+ }+ if (previewFails) {+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));+ }+ return HttpClientResponse.fromWeb(request, Response.json({ device: "UDID-1" }));+ }+ const body =+ request.body._tag === "Uint8Array"+ ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {+ query: string;+ variables: Record<string, { name?: string } & Record<string, unknown>>;+ })+ : { query: "", variables: {} };+ expect(request.headers.authorization).toBe("Bearer expo-token");+ const operation = /(?:query|mutation) (\w+)/.exec(body.query)?.[1] ?? "unknown";+ calls.push({ operation, variables: body.variables });+ if (operation === "T3CreateEasSimulatorSession") {+ createdName = body.variables.input?.name ?? "";+ if (options.createGate) {+ yield* Deferred.succeed(options.createGate.requested, undefined);+ yield* Deferred.await(options.createGate.release);+ }+ if (createFails)+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));+ if (options.rejectCreate)+ return HttpClientResponse.fromWeb(+ request,+ Response.json({ errors: [{ message: "Not allowed" }] }),+ );+ }+ if (operation === "T3StopEasSimulatorSession" && options.failStop?.()) {+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));+ }+ if (operation === "T3ActiveEasSimulatorSessions" && options.failList?.()) {+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));+ }+ const sessionGate =+ operation === "T3EasSimulatorSession" ? options.sessionGate?.() : undefined;+ if (sessionGate && !sessionGated) {+ sessionGated = true;+ yield* Deferred.succeed(sessionGate.requested, undefined);+ yield* Deferred.await(sessionGate.release);+ }+ const data =+ operation === "T3EasSimulatorAvailability"+ ? {+ app: {+ byId: {+ ownerAccount: {+ name: "pingdotgg",+ accountFeatureGates: { "device-run-sessions": true },+ },+ },+ },+ }+ : operation === "T3CreateEasSimulatorSession"+ ? { deviceRunSession: { createDeviceRunSession: { id: `session-${++created}` } } }+ : operation === "T3ActiveEasSimulatorSessions"+ ? {+ app: {+ byId: {+ deviceRunSessionsPaginated: {+ edges: [+ ...(options.omitCreatedFromActive+ ? []+ : [{ node: { id: "orphan", status: "NEW", name: createdName } }]),+ {+ node: {+ id: "someone-else",+ status: "IN_PROGRESS",+ name: "T3 Code · EAS Simulator · 000000",+ },+ },+ ...(options.active ?? []).map((node) => ({ node })),+ ...(options.activeIncludesCreated && created > 0+ ? [+ {+ node: {+ id: `session-${created}`,+ status: "STARTING",+ name: createdName,+ },+ },+ ]+ : []),+ ],+ },+ },+ },+ }+ : operation === "T3EasSimulatorSession"+ ? {+ deviceRunSessions: {+ byId: {+ id: body.variables.id,+ status: options.status?.() ?? "IN_PROGRESS",+ remoteConfig: {+ __typename: "AgentDeviceRunSessionRemoteConfig",+ agentDeviceRemoteSessionUrl: "https://agent.test",+ agentDeviceRemoteSessionToken: "agent-token",+ webPreviewToken: "preview-token",+ previewApiUrl: "https://preview.test?token=preview-token",+ },+ },+ },+ }+ : {+ deviceRunSession: {+ ensureDeviceRunSessionStopped: { id: body.variables.id, status: "STOPPED" },+ },+ };+ return HttpClientResponse.fromWeb(request, Response.json({ data }));+ }),+ );+ const named = (operation: string) => calls.filter((call) => call.operation === operation);+ const stopped = () => named("T3StopEasSimulatorSession").map((call) => call.variables.id);+ const allowPreview = () => {+ previewFails = false;+ };+ const allowCreate = () => {+ createFails = false;+ };+ return { http, named, stopped, allowPreview, allowCreate };+};++const layer = Layer.mergeAll(+ ProcessRunner.layer,+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-eas-host-" }),+).pipe(Layer.provideMerge(NodeServices.layer));++const makeHost = (+ expo: ReturnType<typeof fakeExpo>,+ hostConfig: EasDeviceHostConfig,+ scope: Scope.Scope,+) =>+ EasDeviceHost.make(hostConfig).pipe(+ Effect.provideService(HttpClient.HttpClient, expo.http),+ Effect.provideService(Scope.Scope, scope),+ );++describe("EAS Simulator host", () => {+ it.effect("starts a bounded session and routes its stream and agent to that session", () =>+ Effect.gen(function* () {+ const expo = fakeExpo();+ const scope = yield* Scope.make();+ const host = yield* makeHost(expo, config(), scope);+ const ready = yield* host.ensureReady(() => Effect.void);+ const catalog = (yield* ready.devices.list).devices;+ expect(catalog.map((device) => [device.id, device.booted])).toEqual([["eas-ios", false]]);++ expect(yield* ready.devices.boot(catalog[0]!)).toBe("session-1");+ expect(expo.named("T3CreateEasSimulatorSession")[0]?.variables.input).toMatchObject({+ appId: APP_ID,+ platform: "IOS",+ type: "AGENT_DEVICE",+ maxRunTimeMinutes: 25,+ maxIdleTimeMinutes: 5,+ });+ const listed = (yield* ready.devices.list).devices;+ expect(listed.find((device) => device.id === "session-1")?.booted).toBe(true);+ expect(yield* ready.devices.agentEndpoint!("session-1")).toEqual({+ baseUrl: "https://agent.test",+ token: "agent-token",+ agentDeviceId: "UDID-1",+ });++ const routed = yield* ready.upstream!(+ "/vendor/serve-sim/helper/session-1/webrtc/offer",+ new URLSearchParams("hostId=eas"),+ );+ expect(routed).toEqual({+ url: "https://preview.test/helper/UDID-1/webrtc/offer?hostId=eas",+ headers: { authorization: "Bearer preview-token" },+ protocols: ["serve-sim.token.preview-token"],+ });+ expect(+ yield* ready.upstream!(+ "/vendor/serve-sim/helper/ws",+ new URLSearchParams("device=session-1"),+ ),+ ).toMatchObject({ url: "https://preview.test/helper/ws?device=UDID-1" });+ expect(yield* ready.upstream!("/vendor/serve-emu/ws", new URLSearchParams())).toBeNull();+ expect(+ yield* ready.upstream!("/vendor/serve-sim/helper/%E0/config", new URLSearchParams()),+ ).toBeNull();++ yield* Scope.close(scope, Exit.void);+ expect(expo.named("T3StopEasSimulatorSession").map((call) => call.variables.id)).toEqual([+ "session-1",+ ]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("refuses to start past its session limit", () =>+ Effect.gen(function* () {+ const expo = fakeExpo();+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ yield* ready.devices.boot(catalogDevice!);+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(refused.message).toBe(+ "EAS Simulator is unavailable: EAS Simulator is limited to 1 running session. Close one in the Device panel first.",+ );+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("tells concurrent sessions apart although EAS gives each the same UDID", () =>+ Effect.gen(function* () {+ const expo = fakeExpo();+ const scope = yield* Scope.make();+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 2 }), scope);+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([+ "eas-ios",+ "session-1",+ "session-2",+ ]);+ expect(+ yield* ready.upstream!(+ "/vendor/serve-sim/api",+ new URLSearchParams("device=session-2&hostId=eas"),+ ),+ ).toMatchObject({ url: "https://preview.test/api?device=UDID-1&hostId=eas" });++ yield* ready.devices.shutdown({ id: "session-1", platform: "ios" });+ expect(expo.stopped()).toEqual(["session-1"]);+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([+ "eas-ios",+ "session-2",+ ]);+ yield* Scope.close(scope, Exit.void);+ expect(expo.stopped()).toEqual(["session-1", "session-2"]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("stops only the sessions a previous server recorded, found by name", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });+ yield* fs.writeFileString(+ ledger,+ JSON.stringify([+ { name: "T3 Code · EAS Simulator · left", appId: APP_ID, recordedAt: 0 },+ // Recorded long enough ago that Expo has ended it, so the record goes.+ { name: "T3 Code · EAS Simulator · gone", appId: APP_ID, recordedAt: -181 * 60_000 },+ // Recorded just now and not listed yet: kept for a later sweep.+ { name: "T3 Code · EAS Simulator · new", appId: APP_ID, recordedAt: 0 },+ ]),+ );+ const expo = fakeExpo({+ active: [+ { id: "left-behind", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · left" },+ ],+ });+ const host = yield* makeHost(expo, config(), yield* Scope.make());+ yield* host.ensureReady(() => Effect.void);+ // The sweep runs in the background, so readiness does not wait on Expo.+ const ledgerNames = Effect.map(+ Effect.flatMap(fs.readFileString(ledger), (text) =>+ Effect.try(() => JSON.parse(text) as ReadonlyArray<{ name: string }>),+ ),+ (entries) => entries.map((entry) => entry.name),+ );+ yield* Effect.eventually(+ Effect.flatMap(ledgerNames, (names) =>+ names.length === 1 ? Effect.void : Effect.fail("not swept yet"),+ ),+ );+ expect(expo.stopped()).toEqual(["left-behind"]);+ expect(yield* ledgerNames).toEqual(["T3 Code · EAS Simulator · new"]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("counts a fresh record a previous server left until Expo lists it or would have", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });+ yield* fs.writeFileString(+ ledger,+ JSON.stringify([{ name: "T3 Code · EAS Simulator · new", appId: APP_ID, recordedAt: 0 }]),+ );+ const expo = fakeExpo();+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ // The record is fresh and Expo does not list it yet: it holds the slot.+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(refused.message).toContain("still being cleaned up");+ yield* TestClock.adjust("6 minutes");+ yield* ready.devices.list;+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("counts an old record a previous server left until a sweep stops its session", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });+ yield* fs.writeFileString(+ ledger,+ JSON.stringify([+ { name: "T3 Code · EAS Simulator · old", appId: APP_ID, recordedAt: -10 * 60_000 },+ ]),+ );+ const expo = fakeExpo({+ active: [+ { id: "old-session", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · old" },+ ],+ });+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ // Listing sweeps before anything starts, so the old session is stopped first.+ const [catalogDevice] = (yield* ready.devices.list).devices;+ expect(expo.stopped()).toContain("old-session");+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("keeps an old record counted while the listing that would find it fails", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });+ yield* fs.writeFileString(+ ledger,+ JSON.stringify([+ { name: "T3 Code · EAS Simulator · old", appId: APP_ID, recordedAt: -10 * 60_000 },+ ]),+ );+ let listFails = true;+ const expo = fakeExpo({+ active: [+ { id: "old-session", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · old" },+ ],+ failList: () => listFails,+ });+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ // The sweep could not look, so the record still holds the slot.+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(refused.message).toContain("still being cleaned up");+ listFails = false;+ yield* ready.devices.list;+ expect(expo.stopped()).toContain("old-session");+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect(+ "frees the slot of a record Expo has ended by now, but keeps it until a listing confirms",+ () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });+ yield* fs.writeFileString(+ ledger,+ JSON.stringify([+ { name: "T3 Code · EAS Simulator · gone", appId: APP_ID, recordedAt: -181 * 60_000 },+ {+ name: "T3 Code · EAS Simulator · refused",+ appId: APP_ID,+ recordedAt: -181 * 60_000,+ refused: true,+ },+ // No queue holds a session for a day: forgotten unconfirmed.+ {+ name: "T3 Code · EAS Simulator · ancient",+ appId: APP_ID,+ recordedAt: -25 * 60 * 60_000,+ },+ ]),+ );+ // The app is gone, say: listing it fails for good.+ const expo = fakeExpo({ failList: () => true });+ const host = yield* makeHost(+ expo,+ config({ maxConcurrentSessions: 1 }),+ yield* Scope.make(),+ );+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");+ const names = (JSON.parse(yield* fs.readFileString(ledger)) as Array<{ name: string }>).map(+ (entry) => entry.name,+ );+ // The listing never confirmed the two: a queued session could still be+ // running, so their records stay for the reaper.+ expect(names.filter((name) => !/[0-9a-f]{6}$/.test(name))).toEqual([+ "T3 Code · EAS Simulator · gone",+ "T3 Code · EAS Simulator · refused",+ ]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect(+ "keeps a refused create's record for the reaper without counting it after a restart",+ () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");+ // Expo refuses the create and lists nothing.+ const expo = fakeExpo({ rejectCreate: true, omitCreatedFromActive: true });+ const first = yield* Scope.make();+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), first);+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ const entries = JSON.parse(yield* fs.readFileString(ledger)) as Array<{+ refused?: boolean;+ }>;+ expect(entries.map((entry) => entry.refused)).toEqual([true]);+ yield* Scope.close(first, Exit.void);+ // A later server cannot even list the app: the record must not hold a slot.+ const later = fakeExpo({ failList: () => true });+ const restarted = yield* makeHost(+ later,+ config({ maxConcurrentSessions: 1 }),+ yield* Scope.make(),+ );+ const readyAgain = yield* restarted.ensureReady(() => Effect.void);+ const [device] = (yield* readyAgain.devices.list).devices;+ expect(yield* readyAgain.devices.boot(device!)).toBe("session-1");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("leaves a replacement's session alone once its own scope has closed", () =>+ Effect.gen(function* () {+ // One Expo for both instances: they share the record and the account.+ const expo = fakeExpo();+ const first = yield* Scope.make();+ const old = yield* makeHost(expo, config(), first);+ const oldReady = yield* old.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* oldReady.devices.list).devices;+ expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");+ // Settings saved: the old instance goes, a replacement takes its id.+ yield* Scope.close(first, Exit.void);+ expect(expo.stopped()).toEqual(["session-1"]);+ const replacement = yield* makeHost(expo, config(), yield* Scope.make());+ const ready = yield* replacement.ensureReady(() => Effect.void);+ const [device] = (yield* ready.devices.list).devices;+ expect(yield* ready.devices.boot(device!)).toBe("session-2");+ // A listing still running on the old instance must not sweep the new+ // session, which it does not own but its replacement does.+ yield* TestClock.adjust("2 minutes");+ yield* oldReady.devices.list;+ expect(expo.stopped()).toEqual(["session-1"]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect(+ "does not sweep a replacement's session from a listing in flight when its scope closes",+ () =>+ Effect.gen(function* () {+ const gate = yield* makeGate;+ let armed = false;+ const expo = fakeExpo({ sessionGate: () => (armed ? gate : undefined) });+ const first = yield* Scope.make();+ const old = yield* makeHost(expo, config(), first);+ const oldReady = yield* old.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* oldReady.devices.list).devices;+ expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");+ // Long enough that the listing reads the session's status and a sweep is due.+ yield* TestClock.adjust("2 minutes");+ armed = true;+ const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);+ yield* Deferred.await(gate.requested);+ // Settings saved while the old listing waits on Expo.+ yield* Scope.close(first, Exit.void);+ const replacement = yield* makeHost(expo, config(), yield* Scope.make());+ const ready = yield* replacement.ensureReady(() => Effect.void);+ const [device] = (yield* ready.devices.list).devices;+ expect(yield* ready.devices.boot(device!)).toBe("session-2");+ yield* Deferred.succeed(gate.release, undefined);+ yield* Fiber.join(listing);+ expect(expo.stopped()).toEqual(["session-1"]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("waits for a record write in flight before its scope closes", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const gate = yield* makeGate;+ let armed = false;+ // The ledger read inside a write waits on the gate once armed.+ const gatedFs: FileSystem.FileSystem = {+ ...fs,+ readFileString: (path, encoding) =>+ Effect.gen(function* () {+ if (armed && path.endsWith("eas.json")) {+ armed = false;+ yield* Deferred.succeed(gate.requested, undefined);+ yield* Deferred.await(gate.release);+ }+ return yield* fs.readFileString(path, encoding);+ }),+ };+ let status = "IN_PROGRESS";+ // Nothing is listed, so the close's own sweep writes nothing: only the+ // write in flight can hold the close.+ const expo = fakeExpo({ status: () => status, omitCreatedFromActive: true });+ const first = yield* Scope.make();+ const old = yield* makeHost(expo, config(), first).pipe(+ Effect.provideService(FileSystem.FileSystem, gatedFs),+ );+ const oldReady = yield* old.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* oldReady.devices.list).devices;+ expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");+ // Expo ended the session; the next listing forgets its record.+ status = "STOPPED";+ yield* TestClock.adjust("20 seconds");+ armed = true;+ const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);+ yield* Deferred.await(gate.requested);+ // Settings saved while that write is in flight: closing waits for it.+ const listingsBefore = expo.named("T3ActiveEasSimulatorSessions").length;+ const closing = yield* Scope.close(first, Exit.void).pipe(Effect.forkChild);+ // The close reads the record and lists sessions in real time: yield until+ // its sweep has listed, then a good deal more, before looking at it.+ while (expo.named("T3ActiveEasSimulatorSessions").length === listingsBefore) {+ yield* Effect.yieldNow;+ }+ for (let i = 0; i < 200; i++) yield* Effect.yieldNow;+ expect(closing.pollUnsafe()).toBeUndefined();+ yield* Deferred.succeed(gate.release, undefined);+ yield* Fiber.join(listing);+ yield* Fiber.join(closing);+ const replacement = yield* makeHost(expo, config(), yield* Scope.make());+ const ready = yield* replacement.ensureReady(() => Effect.void);+ const [device] = (yield* ready.devices.list).devices;+ status = "IN_PROGRESS";+ expect(yield* ready.devices.boot(device!)).toBe("session-2");+ // The old write landed first, so the replacement's record is intact.+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const entries = JSON.parse(+ yield* fs.readFileString(path.join(server.stateDir, "device", "eas", "eas.json")),+ ) as Array<{ name: string }>;+ expect(entries).toHaveLength(1);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("keeps an old record whose session is listed but cannot be stopped", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });+ yield* fs.writeFileString(+ ledger,+ JSON.stringify([+ { name: "T3 Code · EAS Simulator · old", appId: APP_ID, recordedAt: -181 * 60_000 },+ ]),+ );+ // Expo still lists it (queued for hours, say) and refuses to stop it.+ const expo = fakeExpo({+ active: [+ { id: "old-session", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · old" },+ ],+ failStop: () => true,+ });+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ // Found and still running: its slot stays taken and its record stays.+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(refused.message).toContain("still being cleaned up");+ const names = (JSON.parse(yield* fs.readFileString(ledger)) as Array<{ name: string }>).map(+ (entry) => entry.name,+ );+ expect(names).toContain("T3 Code · EAS Simulator · old");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("stops the session a refused create made anyway", () =>+ Effect.gen(function* () {+ // Expo refuses the create but lists a session by its name.+ const expo = fakeExpo({ rejectCreate: true });+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(failure.message).toContain("Not allowed");+ expect(expo.stopped()).toEqual(["orphan"]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("records a session before creating it and refuses to start without the record", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ // A directory where the ledger file should be: it can be neither read nor written.+ yield* fs.makeDirectory(path.join(server.stateDir, "device", "eas", "eas.json"), {+ recursive: true,+ });+ const expo = fakeExpo();+ const host = yield* makeHost(expo, config(), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(failure.message).toContain("could not be read");+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("keeps a session tracked when the open that started it is interrupted", () =>+ Effect.gen(function* () {+ const createGate = yield* makeGate;+ const expo = fakeExpo({ createGate });+ const scope = yield* Scope.make();+ const host = yield* makeHost(expo, config(), scope);+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ const opening = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);+ yield* Deferred.await(createGate.requested);+ yield* Fiber.interrupt(opening);+ yield* Deferred.succeed(createGate.release, undefined);+ // The start goes on in the host and tracks its session.+ yield* Effect.eventually(+ ready.devices.list.pipe(+ Effect.flatMap(({ devices }) =>+ devices.some((device) => device.id === "session-1")+ ? Effect.void+ : Effect.fail("not tracked yet"),+ ),+ ),+ );+ yield* Scope.close(scope, Exit.void);+ expect(expo.stopped()).toEqual(["session-1"]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("keeps a session it could not stop counted, listed, and retried", () =>+ Effect.gen(function* () {+ let stopFails = true;+ const expo = fakeExpo({ failStop: () => stopFails });+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ yield* ready.devices.boot(catalogDevice!);+ yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(refused.message).toContain("limited to 1 running session");+ stopFails = false;+ yield* ready.devices.list;+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);+ expect(expo.stopped().filter((id) => id === "session-1").length).toBeGreaterThanOrEqual(2);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("lets go of a stopping session Expo has ended although its stop keeps failing", () =>+ Effect.gen(function* () {+ let status = "IN_PROGRESS";+ const expo = fakeExpo({ failStop: () => true, status: () => status });+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ yield* ready.devices.boot(catalogDevice!);+ yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");+ // Expo ended it by itself: the stop keeps failing, but the status says so.+ status = "STOPPED";+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);+ status = "IN_PROGRESS";+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("asks for an EAS project before starting anything when none can be found", () =>+ Effect.gen(function* () {+ const expo = fakeExpo();+ const host = yield* makeHost(expo, config({ appId: undefined }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(failure.message).toContain("Choose one for this host in Settings");+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );+ it.effect("stops listing sessions Expo already ended", () =>+ Effect.gen(function* () {+ let status = "IN_PROGRESS";+ const expo = fakeExpo({ status: () => status });+ const host = yield* makeHost(expo, config(), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ yield* ready.devices.boot(catalogDevice!);+ status = "STOPPED";+ yield* TestClock.adjust("20 seconds");+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);+ expect(yield* ready.devices.agentEndpoint!("session-1").pipe(Effect.flip)).toMatchObject({+ reason: "This EAS Simulator device is no longer running.",+ });+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("stops a session that is still starting when the host stops", () =>+ Effect.gen(function* () {+ const previewGate = yield* makeGate;+ const expo = fakeExpo({ previewGate });+ const host = yield* makeHost(expo, config(), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);+ yield* Deferred.await(previewGate.requested);+ // Never released: stopping must not wait for the session to become ready.+ yield* host.stop;+ expect(expo.stopped()).toEqual(["session-1"]);+ const failure = yield* Fiber.join(booting).pipe(Effect.flip);+ expect(failure.message).toContain("was stopped while the session started");+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("leaves a start in progress to its owner when the sweep runs", () =>+ Effect.gen(function* () {+ const previewGate = yield* makeGate;+ // Expo lists the starting session by name, as it does while it boots.+ const expo = fakeExpo({ previewGate, activeIncludesCreated: true });+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const host = yield* makeHost(expo, config(), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);+ yield* Deferred.await(previewGate.requested);+ yield* TestClock.adjust("61 seconds");+ yield* ready.devices.list;+ expect(expo.stopped()).toEqual([]);+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");+ expect(JSON.parse(yield* fs.readFileString(ledger))).toHaveLength(1);+ yield* Deferred.succeed(previewGate.release, undefined);+ expect(yield* Fiber.join(booting)).toBe("session-1");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("keeps a session counted when its start fails and stopping it fails too", () =>+ Effect.gen(function* () {+ let stopFails = true;+ const expo = fakeExpo({ failPreview: true, failStop: () => stopFails });+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ // The preview probe is retried a few seconds apart before the start gives up.+ const failing = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip, Effect.forkChild);+ while (failing.pollUnsafe() === undefined) yield* TestClock.adjust("1 second");+ yield* Fiber.join(failing);+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(refused.message).toContain("still being cleaned up");+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);+ stopFails = false;+ yield* ready.devices.list;+ expect(expo.stopped().at(-1)).toBe("session-1");+ expo.allowPreview();+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("stops only its own session when creating one fails after Expo made it", () =>+ Effect.gen(function* () {+ const expo = fakeExpo({ failCreate: true });+ const host = yield* makeHost(expo, config(), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(expo.stopped()).toEqual(["orphan"]);+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("counts a create whose outcome is unknown against the limit, then frees it", () =>+ Effect.gen(function* () {+ // Create fails and the session is not listed yet, so the outcome is unknown.+ const expo = fakeExpo({ failCreate: true, omitCreatedFromActive: true });+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ // The slot is held: Expo may have made the session.+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(refused.message).toContain("still being cleaned up");+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);+ // After Expo would have listed it, the slot frees and a new start runs.+ yield* TestClock.adjust("6 minutes");+ yield* ready.devices.list;+ expo.allowCreate();+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );++ it.effect("holds the slot when a failed create’s session is listed but its stop fails", () =>+ Effect.gen(function* () {+ let stopFails = true;+ // Create fails, Expo lists the session by name, and stopping it fails too.+ const expo = fakeExpo({ failCreate: true, failStop: () => stopFails });+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());+ const ready = yield* host.ensureReady(() => Effect.void);+ const [catalogDevice] = (yield* ready.devices.list).devices;+ yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);+ expect(refused.message).toContain("still being cleaned up");+ stopFails = false;+ yield* ready.devices.list;+ expect(expo.stopped()).toContain("orphan");+ expo.allowCreate();+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );+});diff --git a/apps/server/src/device/EasDeviceHost.ts b/apps/server/src/device/EasDeviceHost.tsnew file mode 100644index 00000000000..21ac3aa4a8f--- /dev/null+++ b/apps/server/src/device/EasDeviceHost.ts@@ -0,0 +1,875 @@+/**+ * Cloud simulators from EAS Simulator. A device exists only while a session+ * runs, and every session bills the Expo account until it stops, so this host+ * bounds each one, stops all of them when it stops, and stops sessions a+ * previous server left behind. It never touches sessions it did not start.+ */+import {+ DeviceBootError,+ type DeviceHostSummary,+ DeviceHostUnavailableError,+ DeviceOperationError,+ type DevicePlatform,+ type EasDeviceHostConfig,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import * as Clock from "effect/Clock";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as Exit from "effect/Exit";+import * as Fiber from "effect/Fiber";+import * as FiberSet from "effect/FiberSet";+import * as FileSystem from "effect/FileSystem";+import * as Option from "effect/Option";+import * as Path from "effect/Path";+import * as Random from "effect/Random";+import * as Redacted from "effect/Redacted";+import * as Schedule from "effect/Schedule";+import * as Schema from "effect/Schema";+import * as Semaphore from "effect/Semaphore";+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";+import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";+import * as HostProcess from "@t3tools/shared/HostProcess";++import * as ServerConfig from "../config.ts";+import * as DeviceHost from "./DeviceHost.ts";+import { findEasProjectId } from "./easProjectId.ts";+import { type ExpoApi, makeExpoApi, resolveExpoCredential } from "./ExpoApi.ts";++const POLL_INTERVAL = Duration.seconds(5);+// How stale a running session's status may get before listing rechecks it.+const STATUS_TTL_MS = 15_000;+// Expo's own CLI waits this long once a worker picks the session up.+const START_TIMEOUT = Duration.minutes(15);+const PREVIEW_TIMEOUT = Duration.seconds(20);+const SERVE_SIM_PREFIX = "/vendor/serve-sim";++/** EAS picks the simulator model; one entry starts a session. */+const CATALOG: ReadonlyArray<DeviceHost.HostDevice> = [+ {+ id: "eas-ios",+ platform: "ios",+ name: "iPhone (EAS Simulator)",+ version: "Cloud",+ booted: false,+ physical: false,+ },+];++interface RunningSession {+ readonly sessionId: string;+ readonly name: string;+ readonly udid: string;+ readonly preview: { readonly origin: string; readonly token: Redacted.Redacted<string> };+ readonly agent: DeviceHost.AgentDaemonEndpoint;+ /** Set once a stop has been asked for but Expo has not confirmed it. */+ stopping: boolean;+}++/**+ * Every session this host may have started, recorded by its unique name before+ * Expo is asked to create it, so a server that crashes at any point can still+ * find and stop the session on its next start.+ */+const LedgerEntry = Schema.Struct({+ name: Schema.String,+ appId: Schema.String,+ recordedAt: Schema.Number,+ /** Expo refused the create: nothing should run, but the reaper still looks. */+ refused: Schema.optional(Schema.Boolean),+});+type LedgerEntry = typeof LedgerEntry.Type;+const Ledger = Schema.fromJsonString(Schema.Array(LedgerEntry));+const decodeLedger = Schema.decodeUnknownEffect(Ledger);+const encodeLedger = Schema.encodeSync(Ledger);+// How often listing looks for recorded sessions this host no longer tracks.+const REAP_INTERVAL_MS = 60_000;+// Expo's longest session runs 115 minutes from when it is ready, plus five+// minutes of cleanup. A recorded session Expo does not list (not showing+// yet, or past the first page) stops counting against the limit after this+// long, and its record is forgotten once a listing confirms it is not+// running. Being ready can wait on Expo's queue, which has no bound, so the+// record outlives the slot: only after a day is it forgotten unconfirmed.+const RECORD_LIFETIME_MS = 180 * 60_000;+const RECORD_MAX_AGE_MS = 24 * 60 * 60_000;+// Expo lists a session it made within seconds; a create with an unknown+// outcome stops counting against the limit once it has had this long.+const UNCERTAIN_CREATE_MS = 5 * 60_000;+// One failed request to Expo during a minutes-long start does not end the start.+const TRANSIENT_RETRY = { times: 3, schedule: Schedule.spaced("2 seconds") } as const;+const decodePreviewApi = Schema.decodeUnknownEffect(Schema.Struct({ device: Schema.String }));++/** A malformed escape names no device, so the proxy answers 404 instead of failing. */+const decodePathSegment = (segment: string): string | null => {+ try {+ return decodeURIComponent(segment);+ } catch {+ return null;+ }+};++export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDeviceHostConfig) {+ const http = yield* HttpClient.HttpClient;+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const server = yield* ServerConfig.ServerConfig;+ const services = yield* Effect.context<+ FileSystem.FileSystem | Path.Path | Effect.Services<ReturnType<typeof findEasProjectId>>+ >();+ const hostId = config.id;+ const ledgerPath = path.join(server.stateDir, "device", "eas", `${hostId}.json`);+ // Keyed by Expo's session id, which is also the device id: every EAS+ // simulator reports the same UDID, so the UDID cannot tell sessions apart.+ const sessions = new Map<string, RunningSession>();+ const checkedAt = new Map<string, number>();+ const startLock = yield* Semaphore.make(1);+ const ledgerLock = yield* Semaphore.make(1);+ // One sweep at a time: two would stop the same session twice.+ const reapLock = yield* Semaphore.make(1);+ // Starts run in the host rather than the caller: a client that disconnects+ // while a session boots leaves it running and tracked, and stopping or+ // closing the host interrupts the start, which then stops its session.+ const starts = yield* FiberSet.make<string, unknown>();+ // The startup sweep for recorded leftovers.+ const background = yield* FiberSet.make<void, never>();+ // Sessions this host owns that `sessions` does not hold: starts in progress,+ // and sessions whose stop after a failed start failed too. The reaper leaves+ // them alone and they count against the limit.+ const starting = new Set<string>();+ const unresolved = new Map<string, { readonly sessionId: string }>();+ // Creates whose outcome is unknown (no answer, or a server error), and+ // fresh records a previous server left: Expo may have made the session.+ // Each listing looks for it, and it counts against the limit until found+ // or until Expo would have listed it by now. The reaper handles these.+ const uncertain = new Map<string, { readonly entry: LedgerEntry; readonly until: number }>();+ const ownedNames = () =>+ new Set([+ ...[...sessions.values()].map((session) => session.name),+ ...starting,+ ...unresolved.keys(),+ ]);+ // Bumped whenever the host stops its sessions, so a start that finishes+ // afterwards stops its own session instead of leaving it untracked.+ let epoch = 0;+ // Set once the host's scope closes. A listing still running on this+ // instance then neither sweeps nor writes the ledger: a replacement with+ // the same id owns the sessions and the record now.+ let closed = false;+ let reapedAt = 0;+ let ready: DeviceHost.DeviceHostReady | null = null;++ const unavailable = (reason: string, cause?: unknown) =>+ new DeviceHostUnavailableError({+ hostId,+ hostLabel: config.label,+ reason,+ ...(cause === undefined ? {} : { cause }),+ });++ const api: Effect.Effect<ExpoApi, DeviceHostUnavailableError> = resolveExpoCredential(+ config.accessToken,+ ).pipe(+ Effect.map((credential) => makeExpoApi(http, credential)),+ Effect.provide(services),+ Effect.mapError((error) => unavailable(error.message, error)),+ );++ /** A missing ledger is empty; an unreadable one is an error, never an empty list. */+ const readLedger = fs.readFileString(ledgerPath).pipe(+ Effect.catchIf(+ (error) => error.reason._tag === "NotFound",+ () => Effect.succeed("[]"),+ ),+ Effect.flatMap(decodeLedger),+ Effect.mapError((cause) =>+ unavailable(+ `The record of running EAS sessions at ${ledgerPath} could not be read. Fix or remove it.`,+ cause,+ ),+ ),+ );+ const writeLedger = Effect.fn("EasDeviceHost.writeLedger")(function* (+ update: (entries: ReadonlyArray<LedgerEntry>) => ReadonlyArray<LedgerEntry>,+ ) {+ if (closed) return yield* unavailable(`${config.label} was replaced or removed.`);+ const entries = update(yield* readLedger);+ yield* writeFileStringAtomically({+ filePath: ledgerPath,+ contents: encodeLedger(entries),+ }).pipe(+ Effect.provide(services),+ Effect.mapError((cause) =>+ unavailable(+ `The record of running EAS sessions at ${ledgerPath} could not be written.`,+ cause,+ ),+ ),+ );+ }, ledgerLock.withPermit);+ const markRefused = (name: string) =>+ writeLedger((entries) =>+ entries.map((entry) => (entry.name === name ? { ...entry, refused: true } : entry)),+ ).pipe(+ Effect.catch((cause) =>+ Effect.logWarning("Could not update the EAS session record", { name, cause }),+ ),+ );+ const forgetEntry = (name: string) =>+ writeLedger((entries) => entries.filter((entry) => entry.name !== name)).pipe(+ Effect.catch((cause) =>+ Effect.logWarning("Could not update the EAS session record", { name, cause }),+ ),+ );++ /** Stops a session and, once Expo confirms it, drops it from the ledger. */+ const stopSession = (expo: ExpoApi, sessionId: string, name: string) =>+ expo.stop(sessionId).pipe(+ Effect.andThen(forgetEntry(name)),+ Effect.tapError((cause) =>+ Effect.logWarning("Could not stop EAS Simulator session", { sessionId, cause }),+ ),+ );++ /** Finds recorded sessions by name, so a session whose id never arrived is found too. */+ const stopRecorded = (expo: ExpoApi, entries: ReadonlyArray<LedgerEntry>) => {+ const found = new Set<string>();+ const listed = new Set<string>();+ return Effect.forEach(+ [...new Set(entries.map((entry) => entry.appId))],+ (appId) =>+ expo.activeSessions(appId).pipe(+ Effect.flatMap((active) =>+ Effect.forEach(+ entries.filter((entry) => entry.appId === appId),+ (entry) =>+ Effect.gen(function* () {+ const running = active.filter((session) => session.name === entry.name);+ if (running.length > 0) {+ found.add(entry.name);+ return yield* Effect.forEach(+ running,+ (session) =>+ stopSession(expo, session.id, entry.name).pipe(+ // Still running and billed: owned, counted, and retried by listing.+ Effect.catch(() =>+ Effect.sync(+ () => void unresolved.set(entry.name, { sessionId: session.id }),+ ),+ ),+ ),+ { discard: true },+ );+ }+ }),+ { discard: true },+ ),+ ),+ Effect.tap(() => Effect.sync(() => void listed.add(appId))),+ Effect.ignore,+ ),+ { discard: true, concurrency: 4 },+ ).pipe(+ Effect.as({ found, listed } as {+ readonly found: ReadonlySet<string>;+ /** The apps whose listing succeeded; a failed one rules nothing out. */+ readonly listed: ReadonlySet<string>;+ }),+ );+ };++ /**+ * Retries the stop of a session whose stop failed. A session Expo already+ * ended is let go even if stopping it keeps failing.+ */+ const retryUnresolved = (expo: ExpoApi, name: string, sessionId: string) =>+ stopSession(expo, sessionId, name).pipe(+ Effect.catch(() =>+ expo+ .session(sessionId)+ .pipe(+ Effect.flatMap((current) =>+ current.status === "STOPPED" || current.status === "ERRORED"+ ? forgetEntry(name)+ : Effect.fail(current.status),+ ),+ ),+ ),+ Effect.andThen(Effect.sync(() => void unresolved.delete(name))),+ Effect.ignore,+ );++ /**+ * Records a previous server left count against the limit until a sweep+ * finds them (a fresh one until Expo would have listed it by now), so a+ * restart cannot start past it.+ */+ const adoptRecorded = Effect.gen(function* () {+ const now = yield* Clock.currentTimeMillis;+ const owned = ownedNames();+ for (const entry of yield* readLedger) {+ const until = Math.max(entry.recordedAt + UNCERTAIN_CREATE_MS, now);+ // A refused create made nothing: its record is for the reaper only.+ if (!owned.has(entry.name) && !entry.refused) uncertain.set(entry.name, { entry, until });+ }+ }).pipe(Effect.ignore);++ /**+ * Stops recorded sessions this host does not own: a previous server's, or+ * a failed or uncertain start's. An uncertain one found (stopped, or+ * unresolved if that failed) or long enough unlisted frees its slot; its+ * record stays until it expires.+ */+ const reapLeftovers = Effect.fn("EasDeviceHost.reapLeftovers")(+ function* (expo: ExpoApi) {+ if (closed) return;+ reapedAt = yield* Clock.currentTimeMillis;+ const entries = yield* readLedger;+ const owned = ownedNames();+ const leftovers = entries.filter((entry) => !owned.has(entry.name));+ const { found, listed } = yield* stopRecorded(expo, leftovers);+ for (const [name, { entry, until }] of uncertain) {+ if (found.has(name) || (reapedAt >= until && listed.has(entry.appId))) {+ uncertain.delete(name);+ }+ }+ // Expo has ended these by now unless they waited in its queue: the slot+ // goes whatever the listing says (the app may be gone, or belong to+ // another account); the record goes once a listing confirms Expo does+ // not run it, or once no queue could have held it.+ for (const entry of leftovers) {+ const age = reapedAt - entry.recordedAt;+ if (age > RECORD_LIFETIME_MS) uncertain.delete(entry.name);+ if (found.has(entry.name)) continue;+ if ((age > RECORD_LIFETIME_MS && listed.has(entry.appId)) || age > RECORD_MAX_AGE_MS) {+ yield* forgetEntry(entry.name);+ }+ }+ },+ reapLock.withPermit,+ Effect.catch((cause) =>+ Effect.logWarning("Could not stop recorded EAS Simulator sessions", { cause }),+ ),+ );++ const previewDevice = (origin: string, token: Redacted.Redacted<string>) =>+ http+ .execute(+ HttpClientRequest.get(`${origin}/api`).pipe(+ HttpClientRequest.bearerToken(Redacted.value(token)),+ ),+ )+ .pipe(+ Effect.flatMap(HttpClientResponse.filterStatusOk),+ Effect.flatMap((response) => response.json),+ Effect.flatMap(decodePreviewApi),+ Effect.map((api) => api.device),+ Effect.scoped,+ Effect.timeout(PREVIEW_TIMEOUT),+ Effect.retry(TRANSIENT_RETRY),+ );++ const awaitRunning = Effect.fn("EasDeviceHost.awaitRunning")(+ function* (expo: ExpoApi, sessionId: string) {+ for (;;) {+ const session = yield* expo.session(sessionId).pipe(+ Effect.retry(TRANSIENT_RETRY),+ Effect.mapError((error) => unavailable(error.message, error)),+ );+ if (session.status === "STOPPED" || session.status === "ERRORED") {+ return yield* new DeviceBootError({+ hostId,+ deviceId: sessionId,+ reason: "launch_failed",+ cause: new Error(`EAS Simulator session ended (${session.status}) before it was ready`),+ });+ }+ if (session.status === "IN_PROGRESS" && session.endpoints) return session.endpoints;+ yield* Effect.sleep(POLL_INTERVAL);+ }+ },+ (poll, _expo, sessionId) =>+ poll.pipe(+ Effect.timeoutOrElse({+ duration: START_TIMEOUT,+ orElse: () =>+ Effect.fail(+ new DeviceBootError({+ hostId,+ deviceId: sessionId,+ reason: "timeout",+ cause: new Error("EAS Simulator session did not start in time"),+ }),+ ),+ }),+ ),+ );++ const reserveSlot = (name: string) =>+ startLock.withPermit(+ Effect.suspend(() => {+ const pending = unresolved.size + uncertain.size;+ if (sessions.size + starting.size + pending >= config.maxConcurrentSessions) {+ const limit = `${config.label} is limited to ${config.maxConcurrentSessions} running ${config.maxConcurrentSessions === 1 ? "session" : "sessions"}.`;+ return Effect.fail(+ unavailable(+ pending > 0+ ? `${limit} ${pending === 1 ? "A session" : `${pending} sessions`} that failed to start or stop ${pending === 1 ? "is" : "are"} still being cleaned up; try again shortly.`+ : `${limit} Close one in the Device panel first.`,+ ),+ );+ }+ starting.add(name);+ return Effect.void;+ }),+ );++ const startSession = Effect.fn("EasDeviceHost.startSession")(function* (+ device: DeviceHost.HostDevice,+ context: DeviceHost.DeviceOpenContext | undefined,+ startedIn: number,+ ) {+ const name = `T3 Code · ${config.label} · ${(yield* Random.nextIntBetween(0, 0xffffff)).toString(16).padStart(6, "0")}`;+ // The credential comes first: without one, the answer is how to sign in,+ // not that the limit is reached.+ const expo = yield* api;+ return yield* Effect.acquireUseRelease(+ reserveSlot(name),+ () =>+ Effect.gen(function* () {+ const appId =+ config.appId ??+ Option.getOrUndefined(+ context?.workspaceRoot+ ? yield* findEasProjectId(context.workspaceRoot).pipe(Effect.provide(services))+ : Option.none<string>(),+ );+ if (!appId) {+ return yield* unavailable(+ "No EAS project to run the session under. Choose one for this host in Settings, or open the device from a thread whose project names extra.eas.projectId in app.json or its app config.",+ );+ }+ const access = yield* expo+ .availability(appId)+ .pipe(Effect.mapError((error) => unavailable(error.message, error)));+ if (!access.available) {+ return yield* unavailable(+ `EAS Simulator is not enabled for the ${access.account} Expo account.`,+ );+ }+ const entry = { name, appId, recordedAt: yield* Clock.currentTimeMillis };+ // Recorded first: a session the ledger cannot hold is never started.+ yield* writeLedger((entries) => [...entries, entry]);+ if (epoch !== startedIn) {+ yield* forgetEntry(name);+ return yield* unavailable(`${config.label} was stopped while the session started.`);+ }+ // Create runs uninterrupted (Expo's API answers within 30 seconds) and+ // the stop below is in place before anything can interrupt the start,+ // so a session Expo made is always either tracked or stopped.+ return yield* Effect.uninterruptibleMask((restore) =>+ Effect.gen(function* () {+ const sessionId = yield* expo+ .create({+ appId,+ platform: device.platform,+ name,+ maxRunTimeMinutes: config.maxSessionMinutes,+ maxIdleTimeMinutes: config.idleMinutes,+ })+ .pipe(+ // Unless Expo refused, it may have made the session before+ // failing to answer. Unlisted, it stays counted for a while.+ // Refused, it made nothing: the slot frees, but the record+ // stays for the reaper in case the refusal was misread.+ Effect.tapError((error) =>+ error.rejected+ ? stopRecorded(expo, [entry]).pipe(+ Effect.flatMap(({ found }) =>+ found.has(name) ? Effect.void : markRefused(name),+ ),+ )+ : stopRecorded(expo, [entry]).pipe(+ Effect.flatMap(({ found }) =>+ found.has(name)+ ? Effect.void+ : Effect.map(Clock.currentTimeMillis, (now) => {+ uncertain.set(name, {+ entry,+ until: now + UNCERTAIN_CREATE_MS,+ });+ }),+ ),+ ),+ ),+ Effect.mapError((error) => unavailable(error.message, error)),+ );+ return yield* restore(trackSession(expo, sessionId, name, startedIn)).pipe(+ Effect.onError(() =>+ stopSession(expo, sessionId, name).pipe(+ // Still running and billed: owned, counted, and retried by listing.+ Effect.catch(() => Effect.sync(() => void unresolved.set(name, { sessionId }))),+ ),+ ),+ );+ }),+ );+ }),+ () => Effect.sync(() => void starting.delete(name)),+ );+ });++ /** Waits for a created session and starts tracking it. */+ const trackSession = Effect.fn("EasDeviceHost.trackSession")(function* (+ expo: ExpoApi,+ sessionId: string,+ name: string,+ startedIn: number,+ ) {+ const endpoints = yield* awaitRunning(expo, sessionId);+ if (!endpoints.preview) {+ return yield* new DeviceBootError({+ hostId,+ deviceId: sessionId,+ reason: "launch_failed",+ cause: new Error("EAS Simulator returned no preview endpoint"),+ });+ }+ const origin = new URL(endpoints.preview.url).origin;+ const udid = yield* previewDevice(origin, endpoints.preview.token).pipe(+ Effect.mapError(+ (cause) =>+ new DeviceBootError({+ hostId,+ deviceId: sessionId,+ reason: "launch_failed",+ cause,+ }),+ ),+ );+ if (epoch !== startedIn) {+ return yield* unavailable(`${config.label} was stopped while the session started.`);+ }+ sessions.set(sessionId, {+ sessionId,+ name,+ udid,+ preview: { origin, token: endpoints.preview.token },+ agent: {+ baseUrl: endpoints.agentDevice.url,+ token: Redacted.value(endpoints.agentDevice.token),+ },+ stopping: false,+ });+ return sessionId;+ });++ const sessionFor = (deviceId: string) => Option.fromNullishOr(sessions.get(deviceId));++ const forget = (session: RunningSession) =>+ Effect.sync(() => {+ sessions.delete(session.sessionId);+ checkedAt.delete(session.sessionId);+ });++ /**+ * Expo ends sessions on its own at their run or idle limit; stop listing+ * those. A stop that failed earlier is retried, and recorded sessions nothing+ * tracks are reaped now and then.+ */+ const dropEnded = Effect.gen(function* () {+ if (closed) return;+ const now = yield* Clock.currentTimeMillis;+ const stale = [...sessions.values()].filter(+ (session) =>+ session.stopping || now - (checkedAt.get(session.sessionId) ?? 0) > STATUS_TTL_MS,+ );+ const reapDue = now - reapedAt > REAP_INTERVAL_MS;+ if (stale.length === 0 && unresolved.size === 0 && uncertain.size === 0 && !reapDue) return;+ const reap = reapDue || uncertain.size > 0;+ if (reap) reapedAt = now;+ const expo = yield* api.pipe(+ // Without a credential no sweep can look; a record Expo would have+ // listed by now still stops counting, so the limit is not held forever.+ Effect.tapError(() =>+ Effect.sync(() => {+ for (const [name, { until }] of uncertain) if (now >= until) uncertain.delete(name);+ }),+ ),+ );+ yield* Effect.forEach(+ [...unresolved],+ ([name, { sessionId }]) => retryUnresolved(expo, name, sessionId),+ { discard: true, concurrency: 4 },+ );+ yield* Effect.forEach(+ stale,+ (session) =>+ (session.stopping+ ? stopSession(expo, session.sessionId, session.name).pipe(+ Effect.andThen(forget(session)),+ // A session Expo already ended is let go even if stopping it keeps failing.+ Effect.catch(() =>+ expo+ .session(session.sessionId)+ .pipe(+ Effect.flatMap((current) =>+ current.status === "STOPPED" || current.status === "ERRORED"+ ? forget(session).pipe(Effect.andThen(forgetEntry(session.name)))+ : Effect.fail(current.status),+ ),+ ),+ ),+ )+ : expo+ .session(session.sessionId)+ .pipe(+ Effect.flatMap((current) =>+ current.status === "STOPPED" || current.status === "ERRORED"+ ? forget(session).pipe(Effect.andThen(forgetEntry(session.name)))+ : Effect.sync(() => void checkedAt.set(session.sessionId, now)),+ ),+ )+ ).pipe(Effect.ignore),+ { discard: true, concurrency: 4 },+ );+ if (reap) yield* reapLeftovers(expo);+ }).pipe(Effect.ignore);++ /**+ * Stops a tracked session. Until Expo confirms, it stays tracked: listed,+ * counted against the limit, and retried by the next listing.+ */+ const stopTracked = (expo: ExpoApi, session: RunningSession) =>+ Effect.suspend(() => {+ session.stopping = true;+ return stopSession(expo, session.sessionId, session.name);+ }).pipe(Effect.andThen(forget(session)));++ const devices: DeviceHost.DeviceOperations = {+ list: dropEnded.pipe(+ Effect.andThen(+ Effect.sync(() => ({+ devices: [+ ...CATALOG,+ ...[...sessions.values()].map((session): DeviceHost.HostDevice => ({+ id: session.sessionId,+ platform: "ios",+ name: "iPhone (EAS Simulator)",+ version: "Cloud",+ booted: true,+ physical: false,+ })),+ ],+ detail: undefined,+ })),+ ),+ ),+ boot: (device, context) => {+ if (sessions.has(device.id)) return Effect.succeed(device.id);+ // Read before anything yields, so a stop that lands while the start+ // reads settings or files is seen.+ const startedIn = epoch;+ return startSession(device, context, startedIn).pipe(+ FiberSet.run(starts),+ Effect.flatMap(Fiber.await),+ Effect.flatMap((exit) =>+ Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)+ ? Effect.fail(unavailable(`${config.label} was stopped while the session started.`))+ : exit,+ ),+ );+ },+ attach: () => Effect.void,+ shutdown: (device) =>+ Option.match(sessionFor(device.id), {+ onNone: () => Effect.void,+ onSome: (session) =>+ api.pipe(+ Effect.flatMap((expo) => stopTracked(expo, session)),+ Effect.asVoid,+ Effect.mapError(+ (cause) =>+ new DeviceOperationError({+ operation: "shutdown",+ reason: "request_failed",+ cause,+ }),+ ),+ ),+ }),+ screenshot: (device) =>+ Option.match(sessionFor(device.id), {+ onNone: () =>+ Effect.fail(+ new DeviceOperationError({+ operation: "screenshot",+ reason: "request_failed",+ cause: new Error("The EAS Simulator session is not running"),+ }),+ ),+ onSome: (session) =>+ http+ .execute(+ HttpClientRequest.post(+ `${session.preview.origin}/api/screenshot?device=${encodeURIComponent(session.udid)}`,+ ).pipe(HttpClientRequest.bearerToken(Redacted.value(session.preview.token))),+ )+ .pipe(+ Effect.flatMap(HttpClientResponse.filterStatusOk),+ Effect.flatMap((response) => response.arrayBuffer),+ Effect.map((buffer) => new Uint8Array(buffer)),+ Effect.scoped,+ Effect.timeout(PREVIEW_TIMEOUT),+ Effect.mapError(+ (cause) =>+ new DeviceOperationError({+ operation: "screenshot",+ reason: "request_failed",+ cause,+ }),+ ),+ ),+ }),+ agentEndpoint: (deviceId) =>+ Option.match(sessionFor(deviceId), {+ onNone: () => Effect.fail(unavailable("This EAS Simulator device is no longer running.")),+ // agent-device selects the simulator by its UDID, not the session id T3 shows.+ onSome: (session) => Effect.succeed({ ...session.agent, agentDeviceId: session.udid }),+ }),+ endsDevices: true,+ };++ /**+ * serve-sim runs at the root of each session's preview host and wants its+ * token on every request. Clients name the device by its session id; serve-sim+ * knows it by its UDID, so the id is swapped for the UDID in the path and in+ * the `device` parameter.+ */+ const upstream: NonNullable<DeviceHost.DeviceHostReady["upstream"]> = (hubPath, search) =>+ Effect.sync(() => {+ if (!hubPath.startsWith(`${SERVE_SIM_PREFIX}/`)) return null;+ const helper = /^\/vendor\/serve-sim\/helper\/([^/]+)\//.exec(hubPath);+ const deviceId = helper ? decodePathSegment(helper[1]!) : search.get("device");+ if (helper && deviceId === null) return null;+ const session =+ deviceId !== null && deviceId !== undefined+ ? sessions.get(deviceId)+ : sessions.size === 1+ ? [...sessions.values()][0]+ : undefined;+ if (!session) return null;+ const path = helper+ ? `/helper/${encodeURIComponent(session.udid)}${hubPath.slice(helper[0].length - 1)}`+ : hubPath.slice(SERVE_SIM_PREFIX.length);+ const params = new URLSearchParams(search);+ if (params.has("device")) params.set("device", session.udid);+ const query = params.size > 0 ? `?${params.toString()}` : "";+ const token = Redacted.value(session.preview.token);+ return {+ url: `${session.preview.origin}${path}${query}`,+ headers: { authorization: `Bearer ${token}` },+ protocols: [`serve-sim.token.${token}`],+ };+ });++ const nodePath = yield* HostProcess.ExecutablePath;+ const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = Effect.fn(+ "EasDeviceHost.ensureReady",+ )(function* () {+ if (ready) return ready;+ yield* adoptRecorded;+ // Without a credential the host is still ready: opening a device then+ // says how to sign in, and listing reaps once one is there.+ yield* FiberSet.run(background)(api.pipe(Effect.flatMap(reapLeftovers), Effect.ignore));+ ready = {+ nodePath,+ hub: { origin: "https://api.expo.dev" },+ devices,+ upstream,+ // Device settings run simctl on the simulator's own machine, which EAS does not expose.+ run: () =>+ Effect.succeed({+ stdout: "",+ stderr: "EAS Simulator devices cannot run host commands.",+ code: 127,+ }),+ helpers: { serveSimAxSettings: null, serveSimCli: null },+ };+ return ready;+ });++ // A session whose stop fails stays tracked for the next listing to retry,+ // and stays in the ledger for the next server if this one closes first.+ const stopAll = Effect.gen(function* () {+ epoch++;+ // Interrupted starts stop the sessions they created before this returns.+ yield* FiberSet.clear(starts);+ yield* FiberSet.clear(background);+ const expo = yield* api;+ yield* Effect.forEach(+ [...sessions.values()],+ (session) => stopTracked(expo, session).pipe(Effect.ignore),+ { discard: true, concurrency: 4 },+ );+ yield* Effect.forEach(+ [...unresolved],+ ([name, { sessionId }]) => retryUnresolved(expo, name, sessionId),+ { discard: true, concurrency: 4 },+ );+ // Also stop a recorded session a create with an unknown outcome made after all.+ yield* reapLeftovers(expo);+ }).pipe(Effect.ignore);+ yield* Effect.addFinalizer(() =>+ stopAll.pipe(+ // Under the ledger lock, so a write still in flight lands before a+ // replacement writes its own, which that write would overwrite.+ Effect.andThen(+ ledgerLock.withPermit(+ Effect.sync(() => {+ closed = true;+ }),+ ),+ ),+ ),+ );++ const platformAvailability = (platform: DevicePlatform) =>+ Effect.succeed(+ platform === "ios"+ ? { platform, available: true }+ : {+ platform,+ available: false,+ reason: "EAS Simulator Android emulators are not supported yet.",+ },+ );++ const summary: Effect.Effect<DeviceHostSummary> = Effect.all([+ platformAvailability("ios"),+ platformAvailability("android"),+ ]).pipe(+ Effect.map((platforms) => ({+ id: hostId,+ label: config.label,+ kind: "eas" as const,+ platforms,+ // Nothing to install: the hub and agent-device daemon run in each session.+ hubInstalled: true,+ agentDeviceInstalled: true,+ })),+ );++ return DeviceHost.DeviceHost.of({+ id: hostId,+ label: config.label,+ summary,+ platformAvailability,+ ensureReady,+ ensureAgentReady: (onPhase) =>+ ensureReady(onPhase).pipe(Effect.map((value) => ({ ...value, agentDevice: null }))),+ current: Effect.sync(() => ready),+ stopAgent: Effect.void,+ // Unlike machines the user owns, every running session here is billed.+ stop: stopAll,+ });+});diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.tsindex 8bf5840e3fc..cb8ab4ac859 100644--- a/apps/server/src/device/LocalDeviceHost.ts+++ b/apps/server/src/device/LocalDeviceHost.ts@@ -10,6 +10,7 @@ import {type DevicePlatform,type DevicePlatformAvailability,LOCAL_DEVICE_HOST_ID,+ LOCAL_DEVICE_HOST_LABEL,} from "@t3tools/contracts";import { waitForHttpReady } from "@t3tools/shared/httpReadiness";import * as HostProcess from "@t3tools/shared/HostProcess";@@ -325,7 +326,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {tools,id: hostId,kind: "local",- label: "This machine",+ label: LOCAL_DEVICE_HOST_LABEL,platforms,hubInstalled,agentDeviceInstalled,@@ -864,6 +865,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {const host: DeviceHost.DeviceHost["Service"] = {id: hostId,+ label: LOCAL_DEVICE_HOST_LABEL,summary,platformAvailability,ensureReady,diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.tsindex 936f4723037..998eaefe709 100644--- a/apps/server/src/device/SshDeviceHost.ts+++ b/apps/server/src/device/SshDeviceHost.ts@@ -472,6 +472,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (yield* Effect.addFinalizer(() => stop);return {id: config.id,+ label: config.label,summary: Effect.sync(() => summary),inspect: provide(probe(config, owner)).pipe(Effect.tap((value) =>diff --git a/apps/server/src/mcp/McpDeviceToolkit.test.ts b/apps/server/src/mcp/McpDeviceToolkit.test.tsindex 306d5cabc71..87801ea7368 100644--- a/apps/server/src/mcp/McpDeviceToolkit.test.ts+++ b/apps/server/src/mcp/McpDeviceToolkit.test.ts@@ -10,10 +10,12 @@ import {} from "@t3tools/contracts";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";+import * as Option from "effect/Option";import { McpSchema, McpServer } from "effect/ai";import * as ServerConfig from "../config.ts";import * as DeviceService from "../device/DeviceService.ts";+import * as ProjectService from "../project/ProjectService.ts";import * as McpHttpServer from "./McpHttpServer.ts";import * as McpInvocationContext from "./McpInvocationContext.ts";import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";@@ -84,9 +86,30 @@ new DataView(png.buffer).setUint32(12, 0x49484452);new DataView(png.buffer).setUint32(16, 1206);new DataView(png.buffer).setUint32(20, 2622);+const unused = Effect.die("not used");+const readiness = {+ hostId: "local",+ nodePath: process.execPath,+ hub: { origin: "http://hub.test" },+ devices: {+ list: unused,+ boot: () => unused,+ attach: () => unused,+ shutdown: () => unused,+ screenshot: () => unused,+ },+ run: () => unused,+ helpers: { serveSimAxSettings: null, serveSimCli: null },+ agentDevice: null,+};+const layerProjectsMock = Layer.mock(ProjectService.ProjectService)({+ getById: () => Effect.succeed(Option.none()),+});+const layerDeviceServiceMock = Layer.mock(DeviceService.DeviceService)({state: Effect.succeed(state),list: Effect.succeed(state),+ agentReadinessIfSupported: () => Effect.succeed(readiness),open: (input) =>Effect.succeed({threadId: input.threadId,@@ -114,13 +137,19 @@ const layerDeviceServiceMock = Layer.mock(DeviceService.DeviceService)({close: () => Effect.void,agentCli: Effect.succeed("/cli"),testHost: () => Effect.die("not used"),- agentTarget: () => Effect.succeed(["--config", "/host.json", "--session", "thread-device"]),+ // As for an EAS device, agent-device knows the device by a different id than T3.+ agentTarget: () =>+ Effect.succeed({+ agentDeviceId: "SIM-UDID",+ args: ["--config", "/host.json", "--session", "thread-device"],+ }),});const layerTest = McpHttpServer.layerDeviceToolkit.pipe(Layer.provideMerge(McpServer.McpServer.layer),Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),Layer.provideMerge(layerDeviceServiceMock),+ Layer.provide(layerProjectsMock),Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" })),Layer.provide(NodeServices.layer),);@@ -137,7 +166,8 @@ it.effect("returns the complete bounded launch diagnostics to the agent", () =>});const failedDevices = Layer.mock(DeviceService.DeviceService)({list: Effect.succeed(state),- agentTarget: () => Effect.succeed([]),+ agentReadinessIfSupported: () => Effect.succeed(readiness),+ agentTarget: () => Effect.succeed({ agentDeviceId: "UDID-1", args: [] }),open: () => Effect.fail(failure),});return Effect.gen(function* () {@@ -157,6 +187,7 @@ it.effect("returns the complete bounded launch diagnostics to the agent", () =>Layer.provideMerge(McpServer.McpServer.layer),Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),Layer.provide(failedDevices),+ Layer.provide(layerProjectsMock),Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-boot-error-test-" })),Layer.provide(NodeServices.layer),),@@ -179,7 +210,7 @@ it.effect("registers the device tools and returns the screenshot as image conten.pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client));expect(opened.isError).toBe(false);const openedContent = opened.structuredContent as { quickStart: string };- expect(openedContent.quickStart).toContain("--udid UDID-1");+ expect(openedContent.quickStart).toContain("--udid SIM-UDID");const shot = yield* server.callTool({ name: "device_screenshot", arguments: { deviceId: "UDID-1" } })@@ -207,7 +238,7 @@ it.effect("registers the device tools and returns the screenshot as image contenit.effect("rejects unavailable agent access before booting or opening a device", () => {const layerUnavailable = Layer.mock(DeviceService.DeviceService)({list: Effect.succeed(state),- agentTarget: () =>+ agentReadinessIfSupported: () =>Effect.fail(new DeviceHostUnavailableError({ hostId: "local", reason: "Agent access is disabled." }),),@@ -237,6 +268,7 @@ it.effect("rejects unavailable agent access before booting or opening a device",Layer.provideMerge(McpServer.McpServer.layer),Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),Layer.provide(layerUnavailable),+ Layer.provide(layerProjectsMock),Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" }),),diff --git a/apps/server/src/mcp/toolkits/device/handlers.ts b/apps/server/src/mcp/toolkits/device/handlers.tsindex c4f3449a290..4c06fbb8784 100644--- a/apps/server/src/mcp/toolkits/device/handlers.ts+++ b/apps/server/src/mcp/toolkits/device/handlers.ts@@ -15,6 +15,7 @@ import { ensureAgentDeviceShim } from "../../../device/AgentDeviceShim.ts";import { nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";import * as DeviceService from "../../../device/DeviceService.ts";+import { threadWorkspaceRoot } from "../../../project/threadWorkspaceRoot.ts";import * as McpInvocationContext from "../../McpInvocationContext.ts";import * as McpToolAccess from "../../McpToolAccess.ts";import { DeviceScreenshotToolkit, DeviceStandardToolkit, DeviceToolkit } from "./tools.ts";@@ -29,6 +30,7 @@ export function agentDeviceQuickStart(device: DeviceSummary,targetArgs = agentDeviceTargetArgs(device),command = "agent-device",+ cloud = false,): string {const executable = /^[a-zA-Z0-9_./:-]+$/.test(command)? command@@ -38,8 +40,9 @@ export function agentDeviceQuickStart(/^[a-zA-Z0-9_./:-]+$/.test(arg) ? arg : "'" + arg.replaceAll("'", "'\"'\"'") + "'",).join(" ");- const platformNotes =- device.platform === "ios"+ const platformNotes = cloud+ ? "This is an EAS Simulator session in the cloud. It bills the Expo account per minute until it stops, so call device_close with shutdown: true when you are done. It starts with no apps installed: install-from-source <url> installs a build from a URL (iOS needs a .tar.gz containing a .app), and install uploads one from this machine."+ : device.platform === "ios"? "First use builds an XCTest runner and can take a couple of minutes; later commands are fast.": "The Android snapshot helper installs itself on first use.";return [@@ -152,23 +155,38 @@ const handlers = {}const target = yield* pickDevice(state.devices, input);// Resolve consent and agent connectivity before booting or registering a session.- const agentArgs = yield* devices.agentTarget({- threadId: scope.thread.threadId,- hostId: target.hostId,- deviceId: target.id,- });- const session = yield* devices.open({- threadId: scope.thread.threadId,- hostId: target.hostId,- deviceId: target.id,- platform: target.platform,- });+ if (!(yield* devices.agentReadinessIfSupported(target.hostId))) {+ return yield* new DeviceToolUnavailableError({+ reason:+ "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",+ });+ }+ const session = yield* devices.open(+ {+ threadId: scope.thread.threadId,+ hostId: target.hostId,+ deviceId: target.id,+ platform: target.platform,+ },+ { workspaceRoot: yield* threadWorkspaceRoot(scope.thread.threadId) },+ );const after = yield* devices.state;const device =after.devices.find((candidate) => candidate.hostId === session.hostId && candidate.id === session.deviceId,) ?? target;- const targetArgs = [...agentDeviceTargetArgs(device), ...agentArgs];+ // Target the opened device: an EAS device and its agent-device daemon+ // exist only once its session runs, and Android ids change on boot.+ const agent = yield* devices.agentTarget({+ threadId: scope.thread.threadId,+ hostId: device.hostId,+ deviceId: device.id,+ });+ const cloud = after.hosts.some((host) => host.id === device.hostId && host.kind === "eas");+ const targetArgs = [+ ...agentDeviceTargetArgs({ ...device, id: agent.agentDeviceId }),+ ...agent.args,+ ];const config = yield* ServerConfig.ServerConfig;const path = yield* Path.Path;const platform = yield* HostProcess.Platform;@@ -194,7 +212,7 @@ const handlers = {return {device,agentDevice: { command, targetArgs },- quickStart: agentDeviceQuickStart(device, targetArgs, command),+ quickStart: agentDeviceQuickStart(device, targetArgs, command, cloud),};}).pipe(Effect.mapError(toolError)),),diff --git a/apps/server/src/mcp/toolkits/device/tools.ts b/apps/server/src/mcp/toolkits/device/tools.tsindex 5771e8233cd..31d8c41dccf 100644--- a/apps/server/src/mcp/toolkits/device/tools.ts+++ b/apps/server/src/mcp/toolkits/device/tools.ts@@ -17,6 +17,7 @@ import { Tool, Toolkit } from "effect/ai";import * as McpInvocationContext from "../../McpInvocationContext.ts";import * as DeviceService from "../../../device/DeviceService.ts";import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";+import * as ProjectService from "../../../project/ProjectService.ts";const dependencies = [McpInvocationContext.McpInvocationContext,@@ -52,7 +53,14 @@ const DeviceOpenTool = Tool.make("device_open", {parameters: DeviceToolOpenInput,success: DeviceToolOpenResult,failure: DeviceToolFailure,- dependencies: [...dependencies, FileSystem.FileSystem, Path.Path, ServerConfig.ServerConfig],+ dependencies: [+ ...dependencies,+ FileSystem.FileSystem,+ Path.Path,+ ServerConfig.ServerConfig,+ // The thread's project can name the EAS project a cloud device runs under.+ ProjectService.ProjectService,+ ],}).annotate(Tool.Title, "Open device").annotate(Tool.Readonly, false)diff --git a/apps/server/src/project/threadWorkspaceRoot.ts b/apps/server/src/project/threadWorkspaceRoot.tsnew file mode 100644index 00000000000..7ad8a3da993--- /dev/null+++ b/apps/server/src/project/threadWorkspaceRoot.ts@@ -0,0 +1,19 @@+import type { ThreadId } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";++import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";+import * as ProjectService from "./ProjectService.ts";++/** The directory a thread works in, or undefined when the thread or its project is gone. */+export const threadWorkspaceRoot = Effect.fn("threadWorkspaceRoot")(+ function* (threadId: ThreadId) {+ const threads = yield* ThreadManagementService.ThreadManagementService;+ const projects = yield* ProjectService.ProjectService;+ const shell = yield* threads.getThreadShell(threadId);+ if (shell === null) return undefined;+ if (shell.worktreePath) return shell.worktreePath;+ return Option.getOrUndefined(yield* projects.getById(shell.projectId))?.workspaceRoot;+ },+ Effect.orElseSucceed(() => undefined),+);diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 83deec74ca8..5667a3b3730 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -203,6 +203,7 @@ import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts";import * as ReviewService from "./review/ReviewService.ts";import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";import * as ProjectService from "./project/ProjectService.ts";+import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts";import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";import { projectMutationOperation } from "./project/ProjectMutation.ts";import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";@@ -2914,7 +2915,10 @@ export const layerWsRpc = (? deviceService.retryHost(input.retryHostId): deviceService.list,),- [WS_METHODS.deviceOpen]: (input) => deviceService.open(input),+ [WS_METHODS.deviceOpen]: (input) =>+ threadWorkspaceRoot(input.threadId).pipe(+ Effect.flatMap((workspaceRoot) => deviceService.open(input, { workspaceRoot })),+ ),[WS_METHODS.deviceClose]: (input) => deviceService.close(input),[WS_METHODS.deviceShutdown]: (input) => deviceService.shutdown(input),[WS_METHODS.deviceDetail]: (input) => deviceService.detail(input),diff --git a/docs/internals/devices.md b/docs/internals/devices.mdindex b57b9dc8d71..b0d03ab76a6 100644--- a/docs/internals/devices.md+++ b/docs/internals/devices.md@@ -26,6 +26,24 @@ operations, so a host whose devices live elsewhere only replaces them.SSH hosts forward both endpoints to server loopback. Every proxied requestalso carries the host id; device ids alone are not unique across hosts.+## EAS Simulator hosts are billed sessions++An [EAS host](../../apps/server/src/device/EasDeviceHost.ts) has no machine:+each opened device is an EAS Simulator session that bills the Expo account+until it stops. Every session is created with the host's run and idle limits,+the host refuses to start past its session limit, and closing the host stops+its sessions. Sessions it starts are recorded under the state directory and+stopped by the next server if this one dies; sessions other tools started on+the same account are never touched.++Each session brings its own serve-sim preview host and agent-device daemon,+with their own tokens. The proxy asks the host to route each request+(`DeviceHostReady.upstream`) and adds the session token server-side, so+clients never hold it. Agent config files are written per device+(`DeviceOperations.agentEndpoint`), which is why `device_open` opens the+device before targeting it. Device settings run `simctl` on the simulator's+machine, which EAS does not expose, so they are unavailable there.+## The hub is never exposedserve-sim has a shell-exec route whose token is readable from its owndiff --git a/packages/client-runtime/src/state/device.ts b/packages/client-runtime/src/state/device.tsindex c56a10103fd..7af65307859 100644--- a/packages/client-runtime/src/state/device.ts+++ b/packages/client-runtime/src/state/device.ts@@ -16,6 +16,25 @@ export function createDeviceEnvironmentAtoms<R, E>(mode: "serial" as const,key: ({ environmentId }: { environmentId: string }) => environmentId,};+ // An EAS Simulator start can take minutes; it must not hold up powering off+ // another device or turning device support off, so each device opens in its+ // own lane. Every EAS start opens the same catalog device, so the thread is+ // part of the lane too.+ const openConcurrency = {+ mode: "serial" as const,+ key: ({+ environmentId,+ input,+ }: {+ environmentId: string;+ input: {+ readonly threadId: string;+ readonly hostId?: string | undefined;+ readonly deviceId: string;+ };+ }) =>+ JSON.stringify([environmentId, "open", input.threadId, input.hostId ?? null, input.deviceId]),+ };return {state: createEnvironmentRpcSubscriptionAtomFamily(runtime, {label: "environment-data:device:state",@@ -41,7 +60,7 @@ export function createDeviceEnvironmentAtoms<R, E>(label: "environment-data:device:open",tag: WS_METHODS.deviceOpen,scheduler,- concurrency,+ concurrency: openConcurrency,}),close: createEnvironmentRpcCommand(runtime, {label: "environment-data:device:close",diff --git a/packages/contracts/src/device.ts b/packages/contracts/src/device.tsindex f55c1aafde4..ecc99e46f52 100644--- a/packages/contracts/src/device.ts+++ b/packages/contracts/src/device.ts@@ -11,6 +11,7 @@ export const DeviceHostId = TrimmedNonEmptyString.check(Schema.isMaxLength(128))export type DeviceHostId = typeof DeviceHostId.Type;export const LOCAL_DEVICE_HOST_ID = "local" as DeviceHostId;+export const LOCAL_DEVICE_HOST_LABEL = "This machine";const ConfiguredDeviceHostId = DeviceHostId.check(Schema.isPattern(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/),@@ -419,12 +420,14 @@ export class DeviceHostUnavailableError extends Schema.TaggedError<DeviceHostUna"DeviceHostUnavailableError",{hostId: DeviceHostId,+ /** The host's name in Settings, which the message shows instead of its id. */+ hostLabel: Schema.optional(Schema.String),reason: Schema.String,cause: Schema.optional(Schema.Defect()),},) {override get message(): string {- return `Device host ${this.hostId} is unavailable: ${this.reason}`;+ return `${this.hostLabel ?? `Device host ${this.hostId}`} is unavailable: ${this.reason}`;}}