TypeScript
feat(devices): support Android EAS Simulator sessions (#26797)
Nathan Schroeder812c0a71c785
diff --git a/apps/server/src/device/DeviceHubProxy.test.ts b/apps/server/src/device/DeviceHubProxy.test.tsindex 07b45737f67..72c8f9e0e5d 100644--- a/apps/server/src/device/DeviceHubProxy.test.ts+++ b/apps/server/src/device/DeviceHubProxy.test.ts@@ -169,6 +169,32 @@ describe("device hub proxy", () => {expect(headers[0]?.["content-type"]).toBe("application/json");});+ it("lets a viewer read Android stream capabilities and signal WebRTC with read scope", async () => {+ const { handler, requests } = fixture([AuthOrchestrationReadScope]);+ const hub = "http://t3.test/api/device-hub/vendor/serve-emu";+ const api = await handler(new Request(`${hub}/api?device=session-1`));+ expect(api.status).toBe(200);+ await api.text();+ for (const action of ["offer", "close"]) {+ const signal = await handler(+ new Request(`${hub}/webrtc/${action}?device=session-1`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: '{"sessionId":"viewer"}',+ }),+ );+ expect(signal.status).toBe(200);+ await signal.text();+ }+ expect(requests).toEqual([+ "http://hub.test/vendor/serve-emu/api?device=session-1",+ "http://hub.test/vendor/serve-emu/webrtc/offer?device=session-1",+ "http://hub.test/vendor/serve-emu/webrtc/close?device=session-1",+ ]);+ expect((await handler(new Request(`${hub}/api`, { method: "POST" }))).status).toBe(405);+ expect((await handler(new Request(`${hub}/webrtc/offer`))).status).toBe(405);+ });+it("sends requests a host routes itself to its upstream with its credentials", async () => {const { handler, requests, headers } = fixture([AuthOrchestrationReadScope],diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.tsindex 89cad0d7206..c1aaab3c612 100644--- a/apps/server/src/device/DeviceHubProxy.ts+++ b/apps/server/src/device/DeviceHubProxy.ts@@ -27,14 +27,17 @@ const ALLOWED_PATHS: ReadonlyArray<RegExp> = [/^\/vendor\/serve-sim\/helper\/[^/]+\/panel\/(1|3)\/stream\.avcc$/,/^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,/^\/vendor\/serve-sim\/appstate$/,+ /^\/vendor\/serve-emu\/api$/,/^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility|fold)$/,/^\/vendor\/serve-emu\/health$/,];+// Paths that take methods besides GET; one missing from ALLOWED_PATHS takes no GET.const MUTABLE_PATHS: ReadonlyArray<RegExp> = [/^\/vendor\/serve-sim\/api\/screenshot$/,// WebRTC signalling: opening and closing a view of the stream, so read scope./^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,+ /^\/vendor\/serve-emu\/webrtc\/(offer|close)$/,/^\/vendor\/serve-emu\/api\/(screenshot|stream-mode|stream-settings)$/,/^\/vendor\/serve-emu\/api\/fold$/,];@@ -178,14 +181,15 @@ const handler = Effect.gen(function* () {}const hubPath = url.value.pathname.slice(DeviceService.DEVICE_HUB_ROUTE_PREFIX.length) || "/";const upgrade = isWebSocketUpgrade(request);- const allowed = (upgrade ? ALLOWED_WS_PATHS : ALLOWED_PATHS).some((pattern) =>- pattern.test(hubPath),- );+ const matches = (paths: ReadonlyArray<RegExp>) => paths.some((pattern) => pattern.test(hubPath));+ const allowed = upgrade+ ? matches(ALLOWED_WS_PATHS)+ : matches(ALLOWED_PATHS) || matches(MUTABLE_PATHS);if (!allowed) {return HttpServerResponse.text("Not Found", { status: 404 });}const readOnly = request.method === "GET" || request.method === "HEAD";- if (!upgrade && !readOnly && !MUTABLE_PATHS.some((pattern) => pattern.test(hubPath))) {+ if (!upgrade && !matches(readOnly ? ALLOWED_PATHS : MUTABLE_PATHS)) {return HttpServerResponse.text("Method Not Allowed", { status: 405 });}const controlsDevice =diff --git a/apps/server/src/device/EasDeviceHost.test.ts b/apps/server/src/device/EasDeviceHost.test.tsindex 5802956e699..62a6a0c247a 100644--- a/apps/server/src/device/EasDeviceHost.test.ts+++ b/apps/server/src/device/EasDeviceHost.test.ts@@ -62,6 +62,7 @@ const fakeExpo = (const calls: Array<{ operation: string; variables: Record<string, unknown> }> = [];let created = 0;let createdName = "";+ const previews: string[] = [];let previewFails = options.failPreview ?? false;let createFails = options.failCreate ?? false;let sessionGated = false;@@ -69,6 +70,7 @@ const fakeExpo = (Effect.gen(function* () {const url = new URL(request.url);if (url.origin === "https://preview.test") {+ previews.push(`${url.pathname}${url.search}`);expect(request.headers.authorization).toBe("Bearer preview-token");if (options.previewGate) {yield* Deferred.succeed(options.previewGate.requested, undefined);@@ -77,7 +79,17 @@ const fakeExpo = (if (previewFails) {return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));}- return HttpClientResponse.fromWeb(request, Response.json({ device: "UDID-1" }));+ if (url.pathname.endsWith("/api/screenshot")) {+ return HttpClientResponse.fromWeb(request, new Response(Uint8Array.of(137, 80, 78, 71)));+ }+ return HttpClientResponse.fromWeb(+ request,+ Response.json(+ url.pathname === "/vendor/serve-emu/api"+ ? { serial: "emulator-5554" }+ : { device: "UDID-1" },+ ),+ );}const body =request.body._tag === "Uint8Array"@@ -195,7 +207,7 @@ const fakeExpo = (const allowCreate = () => {createFails = false;};- return { http, named, stopped, allowPreview, allowCreate };+ return { http, named, stopped, allowPreview, allowCreate, previews };};const layer = Layer.mergeAll(@@ -221,7 +233,10 @@ describe("EAS Simulator host", () => {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(catalog.map((device) => [device.id, device.booted])).toEqual([+ ["eas-ios", false],+ ["eas-android", false],+ ]);expect(yield* ready.devices.boot(catalog[0]!)).toBe("session-1");expect(expo.named("T3CreateEasSimulatorSession")[0]?.variables.input).toMatchObject({@@ -266,6 +281,55 @@ describe("EAS Simulator host", () => {}).pipe(Effect.scoped, Effect.provide(layer)),);+ it.effect("runs an Android session through serve-emu beside an iOS one", () =>+ Effect.gen(function* () {+ const expo = fakeExpo();+ const scope = yield* Scope.make();+ const host = yield* makeHost(expo, config(), scope);+ expect(yield* host.platformAvailability("android")).toEqual({+ platform: "android",+ available: true,+ });+ const ready = yield* host.ensureReady(() => Effect.void);+ const [ios, android] = (yield* ready.devices.list).devices;+ expect(yield* ready.devices.boot(ios!)).toBe("session-1");+ expect(yield* ready.devices.boot(android!)).toBe("session-2");+ expect(expo.named("T3CreateEasSimulatorSession")[1]?.variables.input).toMatchObject({+ platform: "ANDROID",+ });+ const running = (yield* ready.devices.list).devices.find(+ (device) => device.id === "session-2",+ );+ expect(running).toMatchObject({ platform: "android", booted: true });++ expect(yield* ready.devices.agentEndpoint!("session-2")).toMatchObject({+ agentDeviceId: "emulator-5554",+ });+ expect(Array.from(yield* ready.devices.screenshot(running!))).toEqual([137, 80, 78, 71]);+ expect(expo.previews.slice(-2)).toEqual([+ "/vendor/serve-emu/api",+ "/vendor/serve-emu/api/screenshot?device=emulator-5554",+ ]);+ expect(+ yield* ready.upstream!(+ "/vendor/serve-emu/webrtc/offer",+ new URLSearchParams("device=session-2&hostId=eas"),+ ),+ ).toEqual({+ url: "https://preview.test/vendor/serve-emu/webrtc/offer?device=emulator-5554&hostId=eas",+ headers: { authorization: "Bearer preview-token" },+ protocols: ["serve-emu.token.preview-token"],+ });+ // Each session answers only on its own platform's stream.+ expect(+ yield* ready.upstream!("/vendor/serve-emu/api", new URLSearchParams("device=session-1")),+ ).toBeNull();+ expect(+ yield* ready.upstream!("/vendor/serve-sim/api", new URLSearchParams("device=session-2")),+ ).toBeNull();+ }).pipe(Effect.scoped, Effect.provide(layer)),+ );+it.effect("refuses to start past its session limit", () =>Effect.gen(function* () {const expo = fakeExpo();@@ -292,6 +356,7 @@ describe("EAS Simulator host", () => {expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios",+ "eas-android","session-1","session-2",]);@@ -306,6 +371,7 @@ describe("EAS Simulator host", () => {expect(expo.stopped()).toEqual(["session-1"]);expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios",+ "eas-android","session-2",]);yield* Scope.close(scope, Exit.void);@@ -421,7 +487,10 @@ describe("EAS Simulator host", () => {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((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([+ "eas-ios",+ "eas-android",+ ]);expect(expo.stopped().filter((id) => id === "session-1").length).toBeGreaterThanOrEqual(2);}).pipe(Effect.scoped, Effect.provide(layer)),);@@ -438,7 +507,10 @@ describe("EAS Simulator host", () => {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"]);+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([+ "eas-ios",+ "eas-android",+ ]);status = "IN_PROGRESS";expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");}).pipe(Effect.scoped, Effect.provide(layer)),@@ -488,7 +560,10 @@ describe("EAS Simulator host", () => {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"]);+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([+ "eas-ios",+ "eas-android",+ ]);}).pipe(Effect.scoped, Effect.provide(layer)),);});diff --git a/apps/server/src/device/EasDeviceHost.ts b/apps/server/src/device/EasDeviceHost.tsindex da8a665d4b4..a1137fe5156 100644--- a/apps/server/src/device/EasDeviceHost.ts+++ b/apps/server/src/device/EasDeviceHost.ts@@ -42,14 +42,48 @@ 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";+const decodeServeSimApi = Schema.decodeUnknownEffect(+ Schema.Struct({ device: Schema.NonEmptyString }),+);+const decodeServeEmuApi = Schema.decodeUnknownEffect(+ Schema.Struct({ serial: Schema.NonEmptyString }),+);+/**+ * Each session's preview host serves serve-sim at its root and serve-emu under+ * its vendor prefix, and names its device by an id of its own that agent-device+ * also selects it by.+ */+const PLATFORMS = {+ ios: {+ name: "iPhone (EAS Simulator)",+ hubPrefix: "/vendor/serve-sim",+ previewPrefix: "",+ protocol: "serve-sim",+ remoteDeviceId: (api: unknown) => decodeServeSimApi(api).pipe(Effect.map((api) => api.device)),+ },+ android: {+ name: "Android (EAS Simulator)",+ hubPrefix: "/vendor/serve-emu",+ previewPrefix: "/vendor/serve-emu",+ protocol: "serve-emu",+ remoteDeviceId: (api: unknown) => decodeServeEmuApi(api).pipe(Effect.map((api) => api.serial)),+ },+} as const;/** EAS picks the simulator model; one entry starts a session. */const CATALOG: ReadonlyArray<DeviceHost.HostDevice> = [{id: "eas-ios",platform: "ios",- name: "iPhone (EAS Simulator)",+ name: PLATFORMS.ios.name,+ version: "Cloud",+ booted: false,+ physical: false,+ },+ {+ id: "eas-android",+ platform: "android",+ name: PLATFORMS.android.name,version: "Cloud",booted: false,physical: false,@@ -59,7 +93,8 @@ const CATALOG: ReadonlyArray<DeviceHost.HostDevice> = [interface RunningSession {readonly sessionId: string;readonly name: string;- readonly udid: string;+ readonly platform: DevicePlatform;+ readonly remoteDeviceId: 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. */@@ -94,7 +129,6 @@ const RECORD_MAX_AGE_MS = 24 * 60 * 60_000;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 => {@@ -116,7 +150,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDeviceconst 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.+ // simulator reports the same remote device id, so that id cannot tell sessions apart.const sessions = new Map<string, RunningSession>();const checkedAt = new Map<string, number>();const startLock = yield* Semaphore.make(1);@@ -348,18 +382,21 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice),);- const previewDevice = (origin: string, token: Redacted.Redacted<string>) =>+ const previewDevice = (+ origin: string,+ token: Redacted.Redacted<string>,+ platform: DevicePlatform,+ ) =>http.execute(- HttpClientRequest.get(`${origin}/api`).pipe(+ HttpClientRequest.get(`${origin}${PLATFORMS[platform].previewPrefix}/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.flatMap(PLATFORMS[platform].remoteDeviceId),Effect.scoped,Effect.timeout(PREVIEW_TIMEOUT),Effect.retry(TRANSIENT_RETRY),@@ -500,7 +537,9 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice),Effect.mapError((error) => unavailable(error.message, error)),);- return yield* restore(trackSession(expo, sessionId, name, startedIn)).pipe(+ return yield* restore(+ trackSession(expo, sessionId, name, device.platform, startedIn),+ ).pipe(Effect.onError(() =>stopSession(expo, sessionId, name).pipe(// Still running and billed: owned, counted, and retried by listing.@@ -520,6 +559,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDeviceexpo: ExpoApi,sessionId: string,name: string,+ platform: DevicePlatform,startedIn: number,) {const endpoints = yield* awaitRunning(expo, sessionId);@@ -532,7 +572,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice});}const origin = new URL(endpoints.preview.url).origin;- const udid = yield* previewDevice(origin, endpoints.preview.token).pipe(+ const remoteDeviceId = yield* previewDevice(origin, endpoints.preview.token, platform).pipe(Effect.mapError((cause) =>new DeviceBootError({@@ -549,7 +589,8 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevicesessions.set(sessionId, {sessionId,name,- udid,+ platform,+ remoteDeviceId,preview: { origin, token: endpoints.preview.token },agent: {baseUrl: endpoints.agentDevice.url,@@ -650,8 +691,8 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice...CATALOG,...[...sessions.values()].map((session): DeviceHost.HostDevice => ({id: session.sessionId,- platform: "ios",- name: "iPhone (EAS Simulator)",+ platform: session.platform,+ name: PLATFORMS[session.platform].name,version: "Cloud",booted: true,physical: false,@@ -708,7 +749,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevicehttp.execute(HttpClientRequest.post(- `${session.preview.origin}/api/screenshot?device=${encodeURIComponent(session.udid)}`,+ `${session.preview.origin}${PLATFORMS[session.platform].previewPrefix}/api/screenshot?device=${encodeURIComponent(session.remoteDeviceId)}`,).pipe(HttpClientRequest.bearerToken(Redacted.value(session.preview.token))),).pipe(@@ -730,42 +771,45 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDeviceagentEndpoint: (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 }),+ onSome: (session) =>+ Effect.succeed({ ...session.agent, agentDeviceId: session.remoteDeviceId }),}),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.+ * Clients name the device by its session id; the preview host knows it by its+ * own id, so the session id is swapped for that in the path and in the+ * `device` parameter. A session answers only on its own platform's server.*/const upstream: NonNullable<DeviceHost.DeviceHostReady["upstream"]> = (hubPath, search) =>Effect.sync(() => {- if (!hubPath.startsWith(`${SERVE_SIM_PREFIX}/`)) return null;+ const platform = (["ios", "android"] as const).find((candidate) =>+ hubPath.startsWith(`${PLATFORMS[candidate].hubPrefix}/`),+ );+ if (!platform) 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+ deviceId !== null? sessions.get(deviceId): sessions.size === 1? [...sessions.values()][0]: undefined;- if (!session) return null;+ if (session?.platform !== platform) return null;+ const { hubPrefix, previewPrefix, protocol } = PLATFORMS[platform];const path = helper- ? `/helper/${encodeURIComponent(session.udid)}${hubPath.slice(helper[0].length - 1)}`- : hubPath.slice(SERVE_SIM_PREFIX.length);+ ? `/helper/${encodeURIComponent(session.remoteDeviceId)}${hubPath.slice(helper[0].length - 1)}`+ : `${previewPrefix}${hubPath.slice(hubPrefix.length)}`;const params = new URLSearchParams(search);- if (params.has("device")) params.set("device", session.udid);+ if (params.has("device")) params.set("device", session.remoteDeviceId);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}`],+ protocols: [`${protocol}.token.${token}`],};});@@ -833,19 +877,13 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice// Each server signs in on its own, so one with no Expo credential answers for itself. Reading// the credential is local; whether Expo accepts it is only known once a session starts.const platformAvailability = (platform: DevicePlatform) =>- platform === "ios"- ? resolveExpoCredential(config.accessToken).pipe(- Effect.provide(services),- Effect.as({ platform, available: true }),- Effect.catch((error) =>- Effect.succeed({ platform, available: false, reason: error.message }),- ),- )- : Effect.succeed({- platform,- available: false,- reason: "EAS Simulator Android emulators are not supported yet.",- });+ resolveExpoCredential(config.accessToken).pipe(+ Effect.provide(services),+ Effect.as({ platform, available: true }),+ Effect.catch((error) =>+ Effect.succeed({ platform, available: false, reason: error.message }),+ ),+ );const summary: Effect.Effect<DeviceHostSummary> = Effect.all([platformAvailability("ios"),diff --git a/apps/web/src/components/device/DeviceControlsRail.tsx b/apps/web/src/components/device/DeviceControlsRail.tsxindex 3ed2b3a4fa5..740c342b2cf 100644--- a/apps/web/src/components/device/DeviceControlsRail.tsx+++ b/apps/web/src/components/device/DeviceControlsRail.tsx@@ -1,4 +1,4 @@-import type { DevicePlatform } from "@t3tools/contracts";+import type { DeviceHostSummary, DevicePlatform } from "@t3tools/contracts";import {Camera,ChevronLeft,@@ -36,6 +36,7 @@ import type { DeviceControls } from "./useDeviceControls";export function DeviceControlsRail(props: {platform: DevicePlatform;+ hostKind: DeviceHostSummary["kind"] | undefined;handle: DeviceStreamHandle | null;view: DeviceViewControls;controls: DeviceControls;@@ -46,13 +47,12 @@ export function DeviceControlsRail(props: {onFloat: () => void;onClose: () => void;onPowerOff: () => void;- /** The host takes input but runs no device commands (Simlock): no rotation, settings, tools, or screenshots. */- inputOnly?: boolean;}) {const { view, handle, controls } = props;const popupSide = "left";const settings = controls.detail?.settings;const inputDisabled = !handle?.inputConnected;+ const runsHostCommands = props.hostKind === "local" || props.hostKind === "ssh";const nextAppearance = settings?.appearance === "dark" ? "light" : "dark";return (<aside@@ -87,7 +87,7 @@ export function DeviceControlsRail(props: {><Square /></RailButton>- {props.inputOnly ? null : (+ {runsHostCommands ? (<Menu><MenuTriggerrender={@@ -116,9 +116,9 @@ export function DeviceControlsRail(props: {</MenuItem></MenuPopup></Menu>- )}+ ) : null}</>- ) : props.inputOnly ? null : (+ ) : props.hostKind === "simlock" ? null : (<RailButtontooltipSide={popupSide}label="Rotate device"@@ -128,7 +128,7 @@ export function DeviceControlsRail(props: {<RotateCcw /></RailButton>)}- {props.inputOnly ? null : (+ {runsHostCommands ? (<><RailDivider /><RailButton@@ -193,8 +193,8 @@ export function DeviceControlsRail(props: {<SlidersHorizontal /></RailButton></>- )}- {props.inputOnly ? null : (+ ) : null}+ {props.hostKind === "simlock" ? null : (<RailButtontooltipSide={popupSide}label={props.screenshotPending ? "Capturing screenshot" : "Save screenshot"}@@ -229,7 +229,7 @@ export function DeviceControlsRail(props: {<MenuSeparator /><MenuItem variant="destructive" onClick={props.onPowerOff}><Power />- {props.inputOnly ? "Return device to the pool" : "Power off device"}+ {props.hostKind === "simlock" ? "Return device to the pool" : "Power off device"}</MenuItem></MenuPopup></Menu>diff --git a/apps/web/src/components/device/DevicePanel.tsx b/apps/web/src/components/device/DevicePanel.tsxindex c8f55665113..90cc7533c0b 100644--- a/apps/web/src/components/device/DevicePanel.tsx+++ b/apps/web/src/components/device/DevicePanel.tsx@@ -238,7 +238,7 @@ export function DevicePanel(props: {environmentId={environmentId}device={activeDevice}hostLabel={activeHost?.label ?? "Device host"}- simlock={activeHost?.kind === "simlock"}+ hostKind={activeHost?.kind}hostDiagnostics={diagnostics.find(({ hostId }) => hostId === activeDevice.hostId)?.detail}diff --git a/apps/web/src/components/device/DeviceSetup.tsx b/apps/web/src/components/device/DeviceSetup.tsxindex 9d7b30c0456..29b46e99319 100644--- a/apps/web/src/components/device/DeviceSetup.tsx+++ b/apps/web/src/components/device/DeviceSetup.tsx@@ -119,7 +119,7 @@ export function platformSetupStatus(state: DeviceServiceState, platform: DevicePready: true,message:remoteHost?.kind === "eas"- ? `${remoteHost.label} starts iOS Simulators in the cloud with EAS Simulator.`+ ? `${remoteHost.label} starts ${platform === "ios" ? "iOS Simulators" : "Android emulators"} in the cloud with EAS Simulator.`: platform === "ios"? `Xcode and iOS Simulator are available${location}.`: `The Android SDK and Emulator are available${location}.`,diff --git a/apps/web/src/components/device/DeviceWorkspace.tsx b/apps/web/src/components/device/DeviceWorkspace.tsxindex b57adae0232..08ce51c1c54 100644--- a/apps/web/src/components/device/DeviceWorkspace.tsx+++ b/apps/web/src/components/device/DeviceWorkspace.tsx@@ -1,4 +1,4 @@-import type { DeviceSummary, EnvironmentId } from "@t3tools/contracts";+import type { DeviceHostSummary, DeviceSummary, EnvironmentId } from "@t3tools/contracts";import { useRef, useState } from "react";import {captureDeviceScreenshot,@@ -16,8 +16,7 @@ export function DeviceWorkspace(props: {environmentId: EnvironmentId;device: DeviceSummary;hostLabel: string;- /** Leased from a Simlock pool: serve-sim input, no host commands. */- simlock?: boolean;+ hostKind: DeviceHostSummary["kind"] | undefined;hostDiagnostics: string | undefined;visible: boolean;onFloat: () => void;@@ -31,7 +30,13 @@ export function DeviceWorkspace(props: {// A capture always finishes, even if the panel hides or closes meanwhile; the user asked for it.const capturing = useRef(false);const access = useDeviceHubAccess(props.environmentId, props.device.hostId);- const controls = useDeviceControls({ ...props, access });+ // Settings and tools run commands on the device's own machine, which EAS and Simlock do not expose.+ const runsHostCommands = props.hostKind === "local" || props.hostKind === "ssh";+ const controls = useDeviceControls({+ ...props,+ access,+ visible: props.visible && runsHostCommands,+ });const saveScreenshot = () => {if (!access || capturing.current || !props.visible) return;capturing.current = true;@@ -82,12 +87,13 @@ export function DeviceWorkspace(props: {deviceId={props.device.id}hostId={props.device.hostId}visible={props.visible}- serveSimOnly={props.simlock === true}+ serveSimOnly={props.hostKind === "simlock"}axOverlay={axOverlay}allowPhoneViewrenderControls={(view) => (<DeviceControlsRailplatform={props.device.platform}+ hostKind={props.hostKind}handle={view.handle}view={view}controls={controls}@@ -98,7 +104,6 @@ export function DeviceWorkspace(props: {onFloat={props.onFloat}onClose={props.onClose}onPowerOff={props.onPowerOff}- inputOnly={props.simlock === true}/>)}/>diff --git a/docs/internals/devices.md b/docs/internals/devices.mdindex 5273f7942e9..28fa103feb5 100644--- a/docs/internals/devices.md+++ b/docs/internals/devices.md@@ -36,13 +36,13 @@ its sessions. Sessions it starts are recorded under the state directory andstopped by the next server if this one dies; sessions other tools started onthe 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+Each session brings its own preview host (serve-sim, or serve-emu for Android)+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, soclients 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.+device before targeting it. Device settings and tools run `simctl` or `adb` on+the device's machine, which EAS does not expose, so they are unavailable there.## Simlock hosts lease through the agent-device front@@ -147,8 +147,8 @@ decoder then retains frames for seconds despite `optimizeForLatency` and an empt`decodeQueueSize`. The iOS AVCC viewer restores the missing metadata beforeconfiguring the decoder so hardware decoding can remain enabled. WebCodecs issecure-context only, so the viewer probes `isConfigSupported` and falls back to-MJPEG on iOS when decoding is unavailable. Android has no MJPEG; there the panel-reports that it cannot decode.+MJPEG on iOS when decoding is unavailable. Android's SEMU socket has no MJPEG;+there the panel reports that it cannot decode.serve-sim can also be locked to WebRTC, as on EAS Simulator, and then refusesAVCC with a 409 naming the transport. The viewer still asks for AVCC first, so@@ -156,3 +156,6 @@ hubs that serve it pay nothing, and switches on that 409, or when its MJPEGimage fails in a browser that has `RTCPeerConnection`. Offers are not trickled:serve-sim takes one offer with every candidate. The video element only feedsthe same canvas sink, so the panel and the mobile WebView keep one surface.+Android asks serve-emu's `/api` before opening its video socket and streams+WebRTC when it is advertised (EAS Simulator), keeping a separate `video=0`+socket for input so input can reconnect without restarting video.diff --git a/docs/user/devices.md b/docs/user/devices.mdindex ce5a7d8d06d..46a5a427cc8 100644--- a/docs/user/devices.md+++ b/docs/user/devices.md@@ -94,7 +94,7 @@ started from then on; your own Device panel is unaffected.The device stream goes through the environment server, so it works over thelocal network, Tailscale, and T3 Connect. Live video needs a secure page(HTTPS or localhost); on a plain-HTTP remote origin iOS falls back to a slower-still-image stream and Android cannot show video.+still-image stream and Android cannot show video, except on EAS Simulator.## SSH device hostsdiff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.tsindex 737daf5158c..09f04c52780 100644--- a/packages/client-runtime/src/device/stream.test.ts+++ b/packages/client-runtime/src/device/stream.test.ts@@ -75,7 +75,7 @@ describe("native device stream transport", () => {}}vi.stubGlobal("WebSocket", FakeSocket);- const fetch = vi.fn(() => Promise.resolve(new Response("frame")));+ const fetch = vi.fn(() => Promise.resolve(Response.json({})));vi.stubGlobal("fetch", fetch);const events = {onStatus: vi.fn(),@@ -251,6 +251,7 @@ function recoveryFixture(const fetch = vi.fn((url: string, init: RequestInit) => {const signal = init.signal!;signals.push(signal);+ if (url.includes("/api?")) return Promise.resolve(Response.json({}));if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime"));return Promise.resolve(new Response(@@ -450,9 +451,11 @@ describe("shared device stream readiness and recovery", () => {}),);client.start();+ await vi.advanceTimersByTimeAsync(0);sockets[0]!.onmessage?.({ data: sps });client.stop();client.start();+ await vi.advanceTimersByTimeAsync(0);resolveSupport({ supported: true });await vi.advanceTimersByTimeAsync(0);expect(decoders).toHaveLength(0);@@ -491,3 +494,136 @@ describe("shared device stream readiness and recovery", () => {expect(vi.getTimerCount()).toBe(0);});});++describe("Android WebRTC device streams", () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ function setup() {+ vi.useFakeTimers();+ const sockets: Socket[] = [];+ class Socket {+ static OPEN = 1;+ readyState = 1;+ binaryType = "";+ onopen: (() => void) | null = null;+ onmessage: ((event: { data: string }) => void) | null = null;+ onclose: ((event: { code: number; reason: string }) => void) | null = null;+ send = vi.fn();+ close = vi.fn();+ readonly url: string;+ constructor(url: string) {+ this.url = url;+ sockets.push(this);+ }+ }+ const videos: Video[] = [];+ class Video {+ muted = false;+ playsInline = false;+ style = { cssText: "" };+ srcObject: unknown = null;+ videoWidth = 400;+ videoHeight = 800;+ setAttribute = vi.fn();+ remove = vi.fn();+ play = vi.fn(async () => {});+ callback: (() => void) | null = null;+ requestVideoFrameCallback(callback: () => void) {+ this.callback = callback;+ return 0;+ }+ constructor() {+ videos.push(this);+ }+ }+ const peers: Peer[] = [];+ class Peer {+ iceGatheringState = "complete";+ connectionState = "connected";+ localDescription = { type: "offer", sdp: "offer-sdp" };+ ontrack: ((event: { streams: unknown[]; track: unknown }) => void) | null = null;+ onconnectionstatechange: (() => void) | null = null;+ close = vi.fn();+ createOffer = vi.fn(async () => this.localDescription);+ setLocalDescription = vi.fn(async () => {});+ setRemoteDescription = vi.fn(async () => {});+ addTransceiver = vi.fn(() => ({ setCodecPreferences: vi.fn() }));+ addEventListener = vi.fn();+ removeEventListener = vi.fn();+ constructor() {+ peers.push(this);+ }+ }+ vi.stubGlobal("WebSocket", Socket);+ vi.stubGlobal("RTCPeerConnection", Peer);+ vi.stubGlobal("RTCRtpReceiver", { getCapabilities: () => ({ codecs: [] }) });+ vi.stubGlobal("document", { createElement: () => new Video(), body: { append: vi.fn() } });+ const fetch = vi.fn((url: string, _init?: RequestInit) =>+ Promise.resolve(+ url.includes("/api?")+ ? Response.json({ serial: "emulator-5554", stream: { transport: "webrtc" } })+ : Response.json({ type: "answer", sdp: "answer-sdp" }),+ ),+ );+ vi.stubGlobal("fetch", fetch);+ const events = {+ onStatus: vi.fn(),+ onScreen: vi.fn(),+ onUnauthorized: vi.fn(),+ onMjpegFallback: vi.fn(),+ onInputConnected: vi.fn(),+ };+ const present = vi.fn(() => true);+ const client = createDeviceStreamClient(+ {+ platform: "android",+ deviceId: "session-1",+ access: {+ httpBase: "https://test/api/device-hub",+ wsBase: "wss://test/api/device-hub",+ credentials: true,+ query: { hostId: "eas" },+ },+ },+ { present },+ events,+ );+ return { client, events, fetch, peers, videos, sockets, present };+ }++ it("streams over WebRTC when serve-emu advertises it, with input that reconnects on its own", async () => {+ const { client, events, fetch, peers, videos, sockets, present } = setup();+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(fetch.mock.calls.map(([url]) => url)).toEqual([+ "https://test/api/device-hub/vendor/serve-emu/api?device=session-1&hostId=eas",+ "https://test/api/device-hub/vendor/serve-emu/webrtc/offer?device=session-1&hostId=eas",+ ]);+ expect(peers[0]?.setRemoteDescription).toHaveBeenCalledWith({+ type: "answer",+ sdp: "answer-sdp",+ });+ peers[0]?.ontrack?.({ streams: [{}], track: {} });+ videos[0]?.callback?.();+ expect(present).toHaveBeenCalledWith(videos[0], 400, 800);+ expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);++ expect(sockets.map((socket) => socket.url)).toEqual([+ "wss://test/api/device-hub/vendor/serve-emu/ws?device=session-1&video=0&hostId=eas",+ ]);+ sockets[0]!.onopen?.();+ client.pressButton("back");+ expect(sockets[0]!.send).toHaveBeenCalledWith(JSON.stringify({ type: "back" }));+ events.onStatus.mockClear();+ sockets[0]!.onclose?.({ code: 1001, reason: "going away" });+ await vi.advanceTimersByTimeAsync(1_000);+ expect(sockets[1]?.url).toContain("video=0");+ expect(peers).toHaveLength(1);+ expect(peers[0]?.close).not.toHaveBeenCalled();+ expect(events.onStatus).not.toHaveBeenCalled();+ client.stop();+ });+});diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.tsindex c4b80785972..a8913d5a410 100644--- a/packages/client-runtime/src/device/stream.ts+++ b/packages/client-runtime/src/device/stream.ts@@ -836,9 +836,10 @@ export function createDeviceStreamClient(/*** serve-sim can be locked to WebRTC (EAS Simulator always is), and then- * refuses AVCC and MJPEG. An unreadable answer keeps the AVCC path.+ * refuses AVCC and MJPEG; serve-emu advertises WebRTC the same way. An+ * unreadable answer keeps the default path.*/- const probeIosTransport = async (): Promise<WebRtcSettings | null> => {+ const probeWebRtc = async (): Promise<WebRtcSettings | null> => {const probe = new AbortController();const timeout = setTimeout(() => probe.abort(), TRANSPORT_PROBE_TIMEOUT_MS);try {@@ -858,6 +859,9 @@ export function createDeviceStreamClient(}};+ const webRtcUrl = (action: "offer" | "close") =>+ httpUrl(avcc ? `/helper/${device}/webrtc/${action}` : `/webrtc/${action}?device=${device}`);+const closePeer = () => {const current = peer;if (!current) return;@@ -865,8 +869,8 @@ export function createDeviceStreamClient(current.connection.close();current.video.srcObject = null;current.video.remove();- // Releases serve-sim's capture session; best effort because the page may be unloading.- void fetch(httpUrl(`/helper/${device}/webrtc/close`), {+ // Releases the capture session; best effort because the page may be unloading.+ void fetch(webRtcUrl("close"), {method: "POST",keepalive: true,headers: { "content-type": "application/json" },@@ -875,7 +879,7 @@ export function createDeviceStreamClient(}).catch(() => {});};- const readIosWebRtc = async (settings: WebRtcSettings) => {+ const readWebRtc = async (settings: WebRtcSettings) => {const lifecycle = generation;const feedGeneration = ++videoGeneration;closePeer();@@ -920,7 +924,7 @@ export function createDeviceStreamClient(if (!isCurrent()) return;closePeer();connecting(detail);- scheduleRetry("video", () => void readIosWebRtc(settings));+ scheduleRetry("video", () => void readWebRtc(settings));};const presentFrame = () => {if (!isCurrent()) {@@ -988,7 +992,7 @@ export function createDeviceStreamClient(iceGatheringDeadlineMs = Math.min(iceGatheringDeadlineMs * 2, ICE_GATHERING_MAX_TIMEOUT_MS);return retry("Device stream found no network candidates yet. Retrying…");}- const response = await fetch(httpUrl(`/helper/${device}/webrtc/offer`), {+ const response = await fetch(webRtcUrl("offer"), {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({@@ -1023,8 +1027,7 @@ export function createDeviceStreamClient(const switchToWebRtc = async (failure: string, locked: boolean) => {const session = generation;if (typeof RTCPeerConnection === "undefined") return fail(failure);- const settings =- (await probeIosTransport()) ?? (locked ? { transport: "webrtc" as const } : null);+ const settings = (await probeWebRtc()) ?? (locked ? { transport: "webrtc" as const } : null);if (stopped || generation !== session) return;if (!settings) return fail(failure);if (mjpeg) {@@ -1036,7 +1039,7 @@ export function createDeviceStreamClient(// MJPEG may have shown frames already: say the stream is connecting again// rather than leave a blank canvas until the first WebRTC frame.connecting("Switching to WebRTC.");- void readIosWebRtc(settings);+ void readWebRtc(settings);};const startDuoVideo = (panels: DuoPanelSinks) => {@@ -1161,18 +1164,21 @@ export function createDeviceStreamClient(ws.onerror = () => ws.close();};- const connectAndroid = () => {+ /** `inputOnly` keeps a socket for input beside a WebRTC feed, so its reconnects leave video alone. */+ const connectAndroid = (inputOnly = false) => {if (stopped) return;- const ws = new WebSocket(wsUrl(`/ws?device=${device}&frame-meta=1`));+ const ws = new WebSocket(+ wsUrl(`/ws?device=${device}&${inputOnly ? "video=0" : "frame-meta=1"}`),+ );ws.binaryType = "arraybuffer";socket = ws;ws.onopen = () => {if (stopped || socket !== ws) return;- connecting();+ if (!inputOnly) connecting();events.onInputConnected(true);};ws.onmessage = (event) => {- if (stopped || socket !== ws) return;+ if (stopped || socket !== ws || inputOnly) return;if (typeof event.data === "string") {// The encoder restarts at a new size when the device rotates; the// next keyframe carries a fresh SPS, so the decoder is rebuilt from it.@@ -1224,13 +1230,29 @@ export function createDeviceStreamClient((event.code === 1006 && access.query.wsTicket))return handleUnauthorized();- configuring = false;- connecting(event.reason || undefined);- scheduleRetry("input", connectAndroid);+ if (!inputOnly) {+ configuring = false;+ connecting(event.reason || undefined);+ }+ // A full socket re-probes, so one failed /api read does not pin SEMU on a WebRTC host.+ scheduleRetry("input", () => (inputOnly ? connectAndroid(true) : void startAndroid()));};ws.onerror = () => ws.close();};+ const startAndroid = async () => {+ const session = generation;+ const settings = await probeWebRtc();+ if (stopped || generation !== session) return;+ if (settings) {+ if (typeof RTCPeerConnection === "undefined")+ return fail("This browser cannot receive the device's WebRTC stream.");+ if (!target.videoOnly) connectAndroid(true);+ void readWebRtc(settings);+ } else if (useWebCodecs) connectAndroid();+ else fail("This browser cannot decode the Android stream (WebCodecs unavailable).");+ };+const start = () => {if (!stopped) return;stopped = false;@@ -1247,11 +1269,7 @@ export function createDeviceStreamClient(if (!target.videoOnly) void connectIosInput();if (useWebCodecs) void readIosVideo();else fallBackToMjpeg();- } else if (useWebCodecs) {- connectAndroid();- } else {- fail("This browser cannot decode the Android stream (WebCodecs unavailable).");- }+ } else void startAndroid();};const stop = () => {