TypeScript
fix(devices): recover simulator streams after failures (#12639)
Julius Marminge9f73ca3677fa
diff --git a/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx b/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsxindex 82b2b90feca..824164dc2e2 100644--- a/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx+++ b/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx@@ -68,7 +68,7 @@ function DevicePreviewScreen({const insets = useSafeAreaInsets();const { themeVariables } = useAppearancePreferences();const focused = useIsFocused();- const [foreground, setForeground] = useState(AppState.currentState === "active");+ const [foreground, setForeground] = useState(AppState.currentState !== "background");const [selectedKey, setSelectedKey] = useState<string | null>(null);const [inputConnected, setInputConnected] = useState(false);const [streamAttempt, setStreamAttempt] = useState(0);@@ -87,7 +87,7 @@ function DevicePreviewScreen({);useEffect(() => {const subscription = AppState.addEventListener("change", (state) =>- setForeground(state === "active"),+ setForeground(state !== "background"),);return () => subscription.remove();}, []);diff --git a/apps/mobile/src/features/devices/DeviceStreamWebView.tsx b/apps/mobile/src/features/devices/DeviceStreamWebView.tsxindex 9a5cef83ae3..423fdb1c84a 100644--- a/apps/mobile/src/features/devices/DeviceStreamWebView.tsx+++ b/apps/mobile/src/features/devices/DeviceStreamWebView.tsx@@ -1,7 +1,19 @@import deviceStreamScript from "@t3tools/mobile-device-stream";-import { useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type Ref } from "react";-import { Platform } from "react-native";+import {+ useEffect,+ useEffectEvent,+ useImperativeHandle,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type Ref,+} from "react";+import { ActivityIndicator, Platform, Pressable, View } from "react-native";import { WebView } from "react-native-webview";+import type { DeviceStreamStatus } from "@t3tools/client-runtime/device/stream";++import { AppText } from "../../components/AppText";import {deviceStreamDocument,@@ -27,6 +39,7 @@ export function DeviceStreamWebView({...props}: DeviceStreamConfiguration & NativeStreamBridge) {const [attempt, setAttempt] = useState(0);+ const processRetried = useRef(false);const configuration = JSON.stringify({access: props.access,platform: props.platform,@@ -41,7 +54,21 @@ export function DeviceStreamWebView({background={props.colors.background}onUnauthorized={props.onUnauthorized}onInputConnected={props.onInputConnected}- onRetry={() => setAttempt((attempt) => attempt + 1)}+ onRetry={() => {+ processRetried.current = false;+ setAttempt((attempt) => attempt + 1);+ void props.onUnauthorized();+ }}+ onStreaming={() => {+ processRetried.current = false;+ }}+ onRecoverProcess={() => {+ if (processRetried.current) return false;+ processRetried.current = true;+ setAttempt((attempt) => attempt + 1);+ void props.onUnauthorized();+ return true;+ }}/>);}@@ -53,12 +80,38 @@ function DeviceStreamDocumentView({onUnauthorized,onInputConnected,onRetry,+ onStreaming,+ onRecoverProcess,}: NativeStreamBridge & {readonly configuration: string;readonly background: string;readonly onRetry: () => void;+ readonly onStreaming: () => void;+ readonly onRecoverProcess: () => boolean;}) {const webView = useRef<WebView>(null);+ const active = useRef(true);+ const failed = useRef(false);+ const [status, setStatus] = useState<DeviceStreamStatus>("connecting");+ const [error, setError] = useState<string | null>(null);+ const [started, setStarted] = useState(false);+ const fail = (message: string) => {+ if (!active.current || failed.current) return;+ failed.current = true;+ void onInputConnected(false);+ webView.current?.injectJavaScript("window.T3DeviceStream?.stop(); true;");+ setError(message);+ setStatus("error");+ };+ // The shared transport owns video timeouts once the document acknowledges startup.+ const bootstrapTimedOut = useEffectEvent(() =>+ fail("Device viewer could not start. Reconnect to try again."),+ );+ useEffect(() => {+ if (started) return;+ const timer = setTimeout(bootstrapTimedOut, 15_000);+ return () => clearTimeout(timer);+ }, [started]);const source = useMemo(() => ({html: deviceStreamDocument(configuration, deviceStreamScript),@@ -78,32 +131,80 @@ function DeviceStreamDocumentView({appSwitcher: () => command("appSwitcher"),rotate: () => command("rotate"),}));+ const resetInput = useEffectEvent(() => void onInputConnected(false));useLayoutEffect(() => {+ active.current = true;+ resetInput();const view = webView.current;- return () => view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");+ return () => {+ active.current = false;+ view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");+ };}, []);+ const processTerminated = () => {+ if (!active.current || failed.current) return;+ void onInputConnected(false);+ if (!onRecoverProcess()) fail("Device viewer stopped. Reconnect to try again.");+ };return (- <WebView- ref={webView}- source={source}- originWhitelist={["*"]}- scrollEnabled={false}- bounces={false}- mixedContentMode="always"- allowUniversalAccessFromFileURLs- contentInsetAdjustmentBehavior="never"- setSupportMultipleWindows={false}- style={{ flex: 1, backgroundColor: background }}- onLoadStart={() => void onInputConnected(false)}- onShouldStartLoadWithRequest={(request) =>- request.url === "about:blank" || request.url === source.baseUrl- }- onMessage={(event) => {- const message = deviceStreamMessage(event.nativeEvent.data);- if (message?.type === "unauthorized") void onUnauthorized();- else if (message?.type === "input") void onInputConnected(message.connected);- else if (message?.type === "retry") onRetry();- }}- />+ <View className="flex-1" style={{ backgroundColor: background }}>+ <WebView+ ref={webView}+ source={source}+ originWhitelist={["*"]}+ scrollEnabled={false}+ bounces={false}+ mixedContentMode="always"+ allowUniversalAccessFromFileURLs+ contentInsetAdjustmentBehavior="never"+ setSupportMultipleWindows={false}+ style={{ flex: 1, backgroundColor: background }}+ onError={() => fail("Device viewer could not load. Reconnect to try again.")}+ onHttpError={() => fail("Device viewer could not load. Reconnect to try again.")}+ onContentProcessDidTerminate={processTerminated}+ onRenderProcessGone={processTerminated}+ onShouldStartLoadWithRequest={(request) =>+ request.url === "about:blank" || request.url === source.baseUrl+ }+ onMessage={(event) => {+ if (!active.current || failed.current) return;+ const message = deviceStreamMessage(event.nativeEvent.data);+ if (message?.type === "unauthorized") void onUnauthorized();+ else if (message?.type === "input") void onInputConnected(message.connected);+ else if (message?.type === "retry") onRetry();+ else if (message?.type === "status") {+ setStarted(true);+ if (message.status === "error") fail(message.detail ?? "Device stream failed.");+ else {+ setStatus(message.status);+ if (message.status === "streaming") onStreaming();+ }+ }+ }}+ />+ {status !== "streaming" ? (+ <View+ className="absolute inset-0 items-center justify-center gap-4 px-6"+ style={{ backgroundColor: background }}+ >+ {status === "connecting" ? <ActivityIndicator colorClassName="accent-icon" /> : null}+ <AppText+ accessibilityLiveRegion="polite"+ className="text-center text-sm text-foreground-muted"+ >+ {status === "error" ? error : "Connecting to device..."}+ </AppText>+ {status === "error" ? (+ <Pressable+ accessibilityRole="button"+ className="rounded-full border border-secondary-border bg-secondary px-6 py-3"+ onPress={onRetry}+ >+ <AppText className="text-secondary-foreground">Reconnect</AppText>+ </Pressable>+ ) : null}+ </View>+ ) : null}+ </View>);}diff --git a/apps/mobile/src/features/devices/device-stream-document.test.ts b/apps/mobile/src/features/devices/device-stream-document.test.tsindex ffc08667a14..95aa6a9dad2 100644--- a/apps/mobile/src/features/devices/device-stream-document.test.ts+++ b/apps/mobile/src/features/devices/device-stream-document.test.ts@@ -1,5 +1,5 @@import * as NodeVM from "node:vm";-import { describe, expect, it } from "vite-plus/test";+import { describe, expect, it, vi } from "vite-plus/test";import { deviceStreamDocument, deviceStreamMessage } from "./device-stream-document";@@ -13,7 +13,7 @@ describe("native device stream document", () => {);const script = html.match(/<script>([\s\S]*)<\/script>/)?.[1];expect(html.match(/<script>/g)).toHaveLength(1);- const input: unknown = NodeVM.runInNewContext(script!);+ const input: unknown = NodeVM.runInNewContext(script!, { window: { addEventListener() {} } });expect(input).toEqual({ deviceId, ticket: "<ticket>" });});@@ -22,6 +22,39 @@ describe("native device stream document", () => {expect(html.match(/<\/script>/g)).toHaveLength(1);expect(html).toContain('var text="<\\/script>";');});++ it("reports a bootstrap exception to the native recovery UI", () => {+ const postMessage = vi.fn();+ const html = deviceStreamDocument(+ "{}",+ 'var T3DeviceStream={start(){throw new Error("startup")}};',+ );+ NodeVM.runInNewContext(html.match(/<script>([\s\S]*)<\/script>/)![1]!, {+ window: { addEventListener() {}, ReactNativeWebView: { postMessage } },+ });+ expect(JSON.parse(postMessage.mock.calls[0]![0] as string)).toEqual({+ type: "status",+ status: "error",+ detail: "Device viewer stopped unexpectedly.",+ });+ });++ it.each(["error", "unhandledrejection"])("reports later %s failures to native", (event) => {+ const postMessage = vi.fn();+ const listeners = new Map<string, () => void>();+ const html = deviceStreamDocument("{}", "var T3DeviceStream={start(){}};");+ NodeVM.runInNewContext(html.match(/<script>([\s\S]*)<\/script>/)![1]!, {+ window: {+ addEventListener: (name: string, callback: () => void) => listeners.set(name, callback),+ ReactNativeWebView: { postMessage },+ },+ });+ listeners.get(event)!();+ expect(JSON.parse(postMessage.mock.calls[0]![0] as string)).toMatchObject({+ type: "status",+ status: "error",+ });+ });});describe("native device stream messages", () => {@@ -38,6 +71,12 @@ describe("native device stream messages", () => {expect(deviceStreamMessage('{"type":"retry"}')).toEqual({ type: "retry" });});+ it.each(["connecting", "streaming", "error"])("accepts stream %s feedback", (status) => {+ expect(+ deviceStreamMessage(JSON.stringify({ type: "status", status, detail: "Stream feedback" })),+ ).toEqual({ type: "status", status, detail: "Stream feedback" });+ });+it.each(["invalid JSON","null",@@ -45,5 +84,8 @@ describe("native device stream messages", () => {"{}",'{"type":"input","connected":"yes"}','{"type":"unknown"}',+ '{"type":"status","status":"unknown"}',+ '{"type":"status","status":"error","detail":42}',+ '{"type":"status"}',])("ignores invalid bridge messages: %s", (data) => expect(deviceStreamMessage(data)).toBeNull());});diff --git a/apps/mobile/src/features/devices/device-stream-document.ts b/apps/mobile/src/features/devices/device-stream-document.tsindex f3b753d5e99..961dee9affe 100644--- a/apps/mobile/src/features/devices/device-stream-document.ts+++ b/apps/mobile/src/features/devices/device-stream-document.ts@@ -19,7 +19,8 @@ export function deviceStreamDocument(configuration: string, script: string) {// Tickets and device names are data, including any HTML delimiter characters.const safeConfiguration = configuration.replace(/</g, "\\u003c");const safeScript = script.replace(/<\/script/gi, "<\\/script");- return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"></head><body><script>${safeScript}\nT3DeviceStream.start(${safeConfiguration});</script></body></html>`;+ const failure = `window.ReactNativeWebView.postMessage(JSON.stringify({type:"status",status:"error",detail:"Device viewer stopped unexpectedly."}));`;+ return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"></head><body><script>window.addEventListener("error",function(){${failure}});window.addEventListener("unhandledrejection",function(){${failure}});\n${safeScript}\ntry{T3DeviceStream.start(${safeConfiguration});}catch{${failure}}</script></body></html>`;}export function deviceStreamMessage(data: string) {@@ -36,6 +37,21 @@ export function deviceStreamMessage(data: string) {) {return { type: message.type, connected: message.connected } as const;}+ if (+ message.type === "status" &&+ "status" in message &&+ (message.status === "connecting" ||+ message.status === "streaming" ||+ message.status === "error") &&+ (!("detail" in message) || typeof message.detail === "string")+ ) {+ return {+ type: message.type,+ status: message.status,+ detail:+ "detail" in message && typeof message.detail === "string" ? message.detail : undefined,+ } as const;+ }} catch {// Ignore messages that are not part of the stream bridge.}diff --git a/apps/mobile/src/features/devices/device-stream.browser.test.ts b/apps/mobile/src/features/devices/device-stream.browser.test.tsnew file mode 100644index 00000000000..5aeefdac020--- /dev/null+++ b/apps/mobile/src/features/devices/device-stream.browser.test.ts@@ -0,0 +1,117 @@+import { afterEach, expect, it, vi } from "vite-plus/test";+import { start, stop } from "./device-stream.browser";++class Element extends EventTarget {+ readonly style = {};+ naturalWidth = 0;+ naturalHeight = 0;+ src = "";+ readonly tag: string;+ constructor(tag: string) {+ super();+ this.tag = tag;+ }+ setAttribute() {}+ removeAttribute(name: string) {+ if (name === "src") this.src = "";+ }+ append() {}+}++async function setup() {+ vi.useFakeTimers();+ const elements: Element[] = [];+ vi.stubGlobal("document", {+ documentElement: { style: {} },+ body: { style: {}, replaceChildren() {} },+ createElement: (tag: string) => {+ const element = new Element(tag);+ elements.push(element);+ return element;+ },+ });+ const postMessage = vi.fn();+ vi.stubGlobal("window", { ReactNativeWebView: { postMessage }, addEventListener() {} });+ vi.stubGlobal("fetch", () => Promise.resolve(new Response("prime")));+ const sockets: Socket[] = [];+ class Socket {+ static OPEN = 1;+ readyState = 1;+ onopen: (() => void) | null = null;+ close = vi.fn();+ send = vi.fn();+ constructor() {+ sockets.push(this);+ }+ }+ vi.stubGlobal("WebSocket", Socket);+ const configuration = {+ platform: "ios" as const,+ deviceId: "fixture-device",+ access: {+ httpBase: "https://device.test",+ wsBase: "wss://device.test",+ credentials: false,+ query: {},+ },+ colors: {+ background: "white",+ foreground: "black",+ muted: "gray",+ buttonBackground: "gray",+ buttonForeground: "black",+ buttonBorder: "gray",+ },+ };+ start(configuration);+ await vi.advanceTimersByTimeAsync(0);+ return {+ configuration,+ elements,+ sockets,+ messages: () =>+ postMessage.mock.calls.map(+ ([message]) => JSON.parse(message as string) as { type: string; status?: string },+ ),+ };+}++afterEach(() => {+ stop();+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++it("bridges shared first-frame readiness, image failure, and a successful fresh attempt to native", async () => {+ const { elements, messages, sockets, configuration } = await setup();+ sockets[0]!.onopen?.();+ expect(messages()).not.toContainEqual({ type: "status", status: "streaming" });+ expect(messages()).toContainEqual({ type: "input", connected: true });+ const image = elements.find((element) => element.tag === "img")!;+ image.naturalWidth = 400;+ image.naturalHeight = 800;+ await vi.advanceTimersByTimeAsync(250);+ expect(messages()).toContainEqual({ type: "status", status: "streaming" });+ image.dispatchEvent(new Event("error"));+ expect(messages()).toContainEqual({+ type: "status",+ status: "error",+ detail: "Could not receive the device stream. Reconnect to try again.",+ });+ expect(messages()).toContainEqual({ type: "input", connected: false });+ expect(messages()).not.toContainEqual({ type: "unauthorized" });+ expect(image.src).toBe("");+ expect(sockets[0]!.close).toHaveBeenCalledOnce();+ start(configuration);+ await vi.advanceTimersByTimeAsync(0);+ const replacement = elements.findLast((element) => element.tag === "img")!;+ replacement.naturalWidth = 400;+ replacement.naturalHeight = 800;+ replacement.dispatchEvent(new Event("load"));+ expect(messages().at(-1)).toEqual({ type: "status", status: "streaming" });+ image.dispatchEvent(new Event("error"));+ expect(sockets[1]!.close).not.toHaveBeenCalled();+ stop();+ expect(replacement.src).toBe("");+ expect(vi.getTimerCount()).toBe(0);+});diff --git a/apps/mobile/src/features/devices/device-stream.browser.ts b/apps/mobile/src/features/devices/device-stream.browser.tsindex efa81d9a043..0b9e98a51b9 100644--- a/apps/mobile/src/features/devices/device-stream.browser.ts+++ b/apps/mobile/src/features/devices/device-stream.browser.ts@@ -12,13 +12,10 @@ declare global {}let activeClient: ReturnType<typeof createDeviceStreamClient> | null = null;-let activeImage: HTMLImageElement | null = null;export function stop() {activeClient?.stop();activeClient = null;- activeImage?.removeAttribute("src");- activeImage = null;}export function command(button: "home" | "back" | "appSwitcher" | "rotate") {@@ -70,34 +67,6 @@ export function start(configuration: DeviceStreamConfiguration) {image.alt = "";image.draggable = false;image.style.display = "none";- const overlay = document.createElement("div");- overlay.setAttribute("role", "status");- Object.assign(overlay.style, {- position: "fixed",- inset: "0",- display: "flex",- flexDirection: "column",- alignItems: "center",- justifyContent: "center",- gap: "16px",- padding: "24px",- textAlign: "center",- background: colors.background,- });- const detail = document.createElement("span");- const retry = document.createElement("button");- retry.textContent = "Retry";- Object.assign(retry.style, {- padding: "12px 24px",- borderRadius: "20px",- border: `1px solid ${colors.buttonBorder}`,- background: colors.buttonBackground,- color: colors.buttonForeground,- font: "inherit",- display: "none",- });- retry.addEventListener("click", () => post({ type: "retry" }));- overlay.append(detail, retry);const inputStatus = document.createElement("div");inputStatus.setAttribute("role", "status");inputStatus.textContent = "Reconnecting device controls...";@@ -114,11 +83,17 @@ export function start(configuration: DeviceStreamConfiguration) {});frame.append(canvas, image);container.append(frame);- document.body.replaceChildren(container, overlay, inputStatus);+ document.body.replaceChildren(container, inputStatus);let pointerId: number | null = null;let inputConnected = false;let streaming = false;+ const reportStatus = (status: "connecting" | "streaming" | "error", detail?: string) => {+ if (activeClient !== client) return;+ streaming = status === "streaming";+ inputStatus.style.display = streaming && !inputConnected ? "block" : "none";+ post({ type: "status", status, detail });+ };const layout = (screen: DeviceScreenSize | null) => {const landscape =screen?.orientation === "landscape_left" || screen?.orientation === "landscape_right";@@ -160,19 +135,11 @@ export function start(configuration: DeviceStreamConfiguration) {{ ...configuration, preferMjpeg: platform === "ios" },canvas,{- onStatus: (status, message) => {- streaming = status === "streaming";- overlay.style.display = streaming ? "none" : "flex";- inputStatus.style.display = streaming && !inputConnected ? "block" : "none";- detail.textContent =- status === "error" ? (message ?? "Device stream failed.") : "Connecting to device...";- retry.style.display = status === "error" ? "block" : "none";- },+ onStatus: reportStatus,onScreen: layout,- onMjpegFallback: (url) => {+ onMjpegFallback: () => {canvas.style.display = "none";image.style.display = "block";- image.src = url;},onUnauthorized: unauthorized,onInputConnected: (connected) => {@@ -183,8 +150,7 @@ export function start(configuration: DeviceStreamConfiguration) {},);activeClient = client;- activeImage = image;- image.addEventListener("error", unauthorized);+ client.setMjpegImage(image);const touch = (event: PointerEvent, phase: "begin" | "move" | "end") => {const rect = frame.getBoundingClientRect();client.sendTouch(diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.tsindex f1ed9a7f025..c70f30b1fe8 100644--- a/apps/server/src/device/DeviceService.test.ts+++ b/apps/server/src/device/DeviceService.test.ts@@ -11,6 +11,7 @@ import * as Deferred from "effect/Deferred";import * as Fiber from "effect/Fiber";import * as PubSub from "effect/PubSub";import * as Ref from "effect/Ref";+import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import { HttpClient, HttpClientResponse } from "effect/unstable/http";import { ServerSettingsService } from "../serverSettings.ts";@@ -19,6 +20,8 @@ import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";import { type DeviceService, makeWithHosts, stateStream } from "./DeviceService.ts";+const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));+const baseState: DeviceServiceState = {hosts: [],hostStatus: "idle",@@ -378,3 +381,91 @@ it.effect("keeps shutdown successful when subsequent discovery fails", () =>expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false);}).pipe(Effect.scoped),);++it.effect.each(["shutdown", "close"] as const)(+ "%s releases iOS capture so reopening uses a fresh session",+ (operation) =>+ Effect.gen(function* () {+ const deviceId = DeviceId.make("11111111-1111-1111-1111-111111111111");+ const threadId = ThreadId.make("capture-recovery");+ let booted = true;+ let capture: number | null = null;+ let generation = 0;+ const ready: DeviceHost.DeviceHostReady = {+ nodePath: process.execPath,+ hub: { origin: "http://device.test" },+ helpers: { serveSimAxSettings: null, serveSimCli: null },+ run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),+ };+ const host: DeviceHost.DeviceHost["Service"] = {+ id: LOCAL_DEVICE_HOST_ID,+ summary: Effect.succeed({+ id: LOCAL_DEVICE_HOST_ID,+ kind: "local",+ label: "Simulator host",+ platforms: [{ platform: "ios", available: true }],+ hubInstalled: true,+ agentDeviceInstalled: false,+ }),+ platformAvailability: (platform) => Effect.succeed({ platform, available: true }),+ ensureReady: () => Effect.succeed(ready),+ ensureAgentReady: () => Effect.die("Agent access is not used in this test"),+ current: Effect.succeed(ready),+ stopAgent: Effect.void,+ stop: Effect.void,+ };+ const http = HttpClient.make((request) =>+ Effect.sync(() => {+ const path = new URL(request.url).pathname;+ if (path === "/api/devices") {+ return HttpClientResponse.fromWeb(+ request,+ Response.json({+ emulators: [],+ simulators: [+ {+ id: deviceId,+ name: "iPhone",+ platform: "ios",+ version: "26",+ physical: false,+ booted,+ },+ ],+ }),+ );+ }+ if (path === "/vendor/serve-sim/grid/api/start") capture ??= ++generation;+ else if (path === "/vendor/serve-sim/grid/api/shutdown") {+ if (request.body._tag !== "Uint8Array") throw new Error("Missing shutdown body");+ expect(decodeJson(new TextDecoder().decode(request.body.body))).toEqual({+ udid: deviceId,+ });+ capture = null;+ booted = false;+ } else if (path === "/api/devices/shutdown") {+ // This route powers off without releasing serve-sim's cached capture.+ booted = false;+ } else if (path === "/api/devices/boot") booted = true;+ else throw new Error(`Unexpected hub path: ${path}`);+ return HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId }));+ }),+ );+ const service = yield* makeWithHosts(new Map([[host.id, host]])).pipe(+ Effect.provideService(HttpClient.HttpClient, http),+ );+ const input = { threadId, deviceId, platform: "ios" as const };+ yield* service.open(input);+ expect(capture).toBe(1);+ if (operation === "shutdown") yield* service.shutdown(input);+ else yield* service.close({ threadId, deviceId, shutdown: true });+ expect(capture).toBeNull();+ expect((yield* service.state).sessions).toEqual([]);+ yield* service.open(input);+ expect(capture).toBe(2);+ expect((yield* service.state).sessions).toHaveLength(1);+ }).pipe(+ Effect.provide(ServerSettingsService.layerTest({ enableDeviceSupport: true })),+ Effect.scoped,+ ),+);diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.tsindex 30e1f18c049..8b7db9b5e59 100644--- a/apps/server/src/device/DeviceService.ts+++ b/apps/server/src/device/DeviceService.ts@@ -670,8 +670,14 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*platform: DevicePlatform,) {const ready = yield* readiness(hostId);- yield* HttpClientRequest.post(`${ready.hub.origin}/api/devices/shutdown`).pipe(- HttpClientRequest.bodyJson({ platform, id: deviceId }),+ // serve-sim's shutdown closes its in-process capture session before powering off.+ // The hub's generic shutdown can leave that session cached across a reboot.+ const path =+ platform === "ios" ? `${vendorPrefix("ios")}/grid/api/shutdown` : "/api/devices/shutdown";+ yield* HttpClientRequest.post(`${ready.hub.origin}${path}`).pipe(+ HttpClientRequest.bodyJson(+ platform === "ios" ? { udid: deviceId } : { platform, id: deviceId },+ ),Effect.mapError((cause) =>new DeviceOperationError({ operation: "shutdown", reason: "invalid_payload", cause }),diff --git a/apps/web/src/components/device/DeviceLoadingView.tsx b/apps/web/src/components/device/DeviceLoadingView.tsxindex 70e848c3ce7..332d3994cca 100644--- a/apps/web/src/components/device/DeviceLoadingView.tsx+++ b/apps/web/src/components/device/DeviceLoadingView.tsx@@ -1,3 +1,4 @@+import type { ReactNode } from "react";import { Smartphone } from "lucide-react";import { Spinner } from "~/components/ui/spinner";@@ -8,6 +9,7 @@ export function DeviceLoadingView(props: {readonly stage: "opening" | "stream";readonly message: string;readonly error?: boolean;+ readonly children?: ReactNode;}) {return (<div@@ -28,6 +30,7 @@ export function DeviceLoadingView(props: {{!props.error ? <Spinner className="size-3" /> : null}<span>{props.message}</span></div>+ {props.children}{!props.error ? (<divclassName="flex w-24 gap-1"diff --git a/apps/web/src/components/device/DeviceStreamView.test.tsx b/apps/web/src/components/device/DeviceStreamView.test.tsxindex 78556078313..73d3bf11ee2 100644--- a/apps/web/src/components/device/DeviceStreamView.test.tsx+++ b/apps/web/src/components/device/DeviceStreamView.test.tsx@@ -8,25 +8,37 @@ vi.mock("~/state/device", () => ({refreshDeviceHubAccess: vi.fn(),}));const access = { httpBase: "http://test", wsBase: "ws://test", query: {}, credentials: true };-vi.mock("@t3tools/client-runtime/device/stream", () => ({- createDeviceStreamClient: (- _target: unknown,- _canvas: unknown,- events: { onMjpegFallback: (url: string) => void },- ) => ({- start: () => events.onMjpegFallback("http://test/stream.mjpeg"),- stop: vi.fn(),- }),-}));import { DeviceStreamView } from "./DeviceStreamView";++class Image extends EventTarget {+ src = "";+ naturalWidth = 0;+ naturalHeight = 0;+ removeAttribute(name: string) {+ if (name === "src") this.src = "";+ }+}let renderer: ReactTestRenderer | undefined;afterEach(async () => {await act(async () => renderer?.unmount());+ renderer = undefined;+ vi.useRealTimers();vi.unstubAllGlobals();});-it("removes MJPEG requests while hidden and reconnects when shown", async () => {+async function setup() {+ vi.useFakeTimers();vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.stubGlobal("fetch", () => Promise.resolve(new Response("prime")));+ vi.stubGlobal(+ "WebSocket",+ class {+ static OPEN = 1;+ readyState = 1;+ send() {}+ close() {}+ },+ );vi.stubGlobal("ResizeObserver",class {@@ -34,6 +46,7 @@ it("removes MJPEG requests while hidden and reconnects when shown", async () =>disconnect() {}},);+ const images: Image[] = [];const view = (visible: boolean) => (<DeviceStreamViewhostId="local"@@ -45,15 +58,51 @@ it("removes MJPEG requests while hidden and reconnects when shown", async () =>);await act(async () => {renderer = create(view(true), {- createNodeMock: () => ({- style: { setProperty() {} },- getBoundingClientRect: () => ({ width: 400, height: 800 }),- }),+ createNodeMock: (node) => {+ if (node.type === "img") {+ const image = new Image();+ images.push(image);+ return image;+ }+ return {+ style: { setProperty() {} },+ getBoundingClientRect: () => ({ width: 400, height: 800 }),+ };+ },});});- expect(renderer!.root.findAllByType("img")).toHaveLength(1);+ return { images, view };+}++it("removes MJPEG requests while hidden and reconnects when shown", async () => {+ const { images, view } = await setup();+ expect(images[0]!.src).toContain("stream.mjpeg");await act(async () => renderer!.update(view(false)));expect(renderer!.root.findAllByType("img")).toHaveLength(0);+ expect(images[0]!.src).toBe("");+ expect(vi.getTimerCount()).toBe(0);await act(async () => renderer!.update(view(true)));- expect(renderer!.root.findAllByType("img")).toHaveLength(1);+ expect(images.at(-1)!.src).toContain("stream.mjpeg");+});++it("offers Reconnect after the shared timeout and receives a frame after retry with unchanged access", async () => {+ const { images } = await setup();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(15_000);+ });+ expect(+ renderer!.root.findByProps({ role: "alert" }).findByType("span").children.join(""),+ ).toContain("No video");+ expect(images[0]!.src).toBe("");+ await act(async () => renderer!.root.findByType("button").props.onClick());+ expect(renderer!.root.findAllByProps({ role: "alert" })).toHaveLength(0);+ expect(images[1]!.src).toContain("stream.mjpeg");+ await act(async () => {+ images[1]!.naturalWidth = 400;+ images[1]!.naturalHeight = 800;+ images[1]!.dispatchEvent(new Event("load"));+ });+ expect(renderer!.root.findAllByProps({ role: "status" })).toHaveLength(0);+ expect(renderer!.root.findAllByType("button")).toHaveLength(0);+ expect(vi.getTimerCount()).toBe(0);});diff --git a/apps/web/src/components/device/DeviceStreamView.tsx b/apps/web/src/components/device/DeviceStreamView.tsxindex 60e8414fb06..8078eac7ce1 100644--- a/apps/web/src/components/device/DeviceStreamView.tsx+++ b/apps/web/src/components/device/DeviceStreamView.tsx@@ -1,7 +1,8 @@import type { DevicePlatform, EnvironmentId } from "@t3tools/contracts";-import { useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { cn } from "~/lib/utils";+import { Button } from "~/components/ui/button";import { refreshDeviceHubAccess, useDeviceHubAccess } from "~/state/device";import { DeviceLoadingView } from "./DeviceLoadingView";import { type DeviceAxElement, fetchDeviceAxTree } from "./deviceHubApi";@@ -49,6 +50,9 @@ export function DeviceStreamView(props: {const [screen, setScreen] = useState<DeviceScreenSize | null>(null);const [mjpegUrl, setMjpegUrl] = useState<string | null>(null);const [mjpegGeneration, setMjpegGeneration] = useState(0);+ const attachMjpegImage = useCallback((image: HTMLImageElement | null) => {+ clientRef.current?.setMjpegImage(image);+ }, []);const [inputState, setInputState] = useState<{ connected: boolean; detail?: string }>({connected: false,});@@ -235,11 +239,13 @@ export function DeviceStreamView(props: {role="application"aria-label={`${props.platform === "ios" ? "iOS Simulator" : "Android Emulator"} screen`}onKeyDown={(event) => {+ if (event.target !== event.currentTarget) return;if (event.metaKey && !["r", "R"].includes(event.key)) return;event.preventDefault();clientRef.current?.sendKey(event.nativeEvent, "down");}}onKeyUp={(event) => {+ if (event.target !== event.currentTarget) return;clientRef.current?.sendKey(event.nativeEvent, "up");}}>@@ -279,7 +285,7 @@ export function DeviceStreamView(props: {{props.visible && access && mjpegUrl ? (<imgkey={mjpegGeneration}- src={mjpegUrl}+ ref={attachMjpegImage}alt=""draggable={false}className="absolute top-0 left-0 object-contain"@@ -317,14 +323,28 @@ export function DeviceStreamView(props: {</div>) : null}{status !== "streaming" ? (- <div className="pointer-events-none absolute inset-0">+ <div className="absolute inset-0"><DeviceLoadingViewname={props.deviceName ?? "Device"}description={props.deviceDescription ?? ""}stage="stream"message={status === "error" ? (detail ?? "Stream failed.") : "Connecting video…"}error={status === "error"}- />+ >+ {status === "error" ? (+ <Button+ size="sm"+ variant="outline"+ onClick={() => {+ refreshDeviceHubAccess(props.environmentId);+ clientRef.current?.stop();+ clientRef.current?.start();+ }}+ >+ Reconnect+ </Button>+ ) : null}+ </DeviceLoadingView></div>) : null}</div>diff --git a/apps/web/src/components/device/deviceStream.test.ts b/apps/web/src/components/device/deviceStream.test.tsdeleted file mode 100644index 13a57d44ffc..00000000000--- a/apps/web/src/components/device/deviceStream.test.ts+++ /dev/null@@ -1,345 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vite-plus/test";--import {- createDeviceStreamClient,- AvccDemuxer,- avcCodecString,- parseSemuPacket,- scanAccessUnit,-} from "@t3tools/client-runtime/device/stream";--const envelope = (tag: number, payload: number[]) => {- const length = 1 + payload.length;- return [- (length >>> 24) & 0xff,- (length >>> 16) & 0xff,- (length >>> 8) & 0xff,- length & 0xff,- tag,- ...payload,- ];-};--describe("AvccDemuxer", () => {- it("reassembles envelopes split across reads", () => {- const demuxer = new AvccDemuxer();- const bytes = new Uint8Array([- ...envelope(1, [1, 0x64, 0x00, 0x1f]),- ...envelope(2, [9, 9, 9]),- ...envelope(0x7f, [0]),- ...envelope(3, [4]),- ]);- const first = demuxer.push(bytes.subarray(0, 7));- const rest = demuxer.push(bytes.subarray(7));- const chunks = [...first, ...rest];- expect(chunks.map((chunk) => chunk.type)).toEqual(["description", "keyframe", "delta"]);- expect(Array.from(chunks[0]!.payload)).toEqual([1, 0x64, 0x00, 0x1f]);- expect(Array.from(chunks[1]!.payload)).toEqual([9, 9, 9]);- });-- it("derives the WebCodecs codec string from the avcC record", () => {- expect(avcCodecString(new Uint8Array([1, 0x64, 0x00, 0x1f]))).toBe("avc1.64001f");- expect(avcCodecString(new Uint8Array([1]))).toBe("avc1.42E01E");- });-});--describe("native device stream transport", () => {- afterEach(() => {- vi.useRealTimers();- vi.unstubAllGlobals();- });-- function setup(platform: "ios" | "android") {- vi.useFakeTimers();- vi.stubGlobal("VideoDecoder", vi.fn());- vi.stubGlobal("EncodedVideoChunk", vi.fn());- let resolveOpened!: (socket: FakeSocket) => void;- const waitForSocket = () =>- new Promise<FakeSocket>((resolve) => {- resolveOpened = resolve;- });- const opened = waitForSocket();- class FakeSocket {- static OPEN = 1;- readyState = 1;- binaryType = "";- onopen: (() => 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;- resolveOpened(this);- }- }- vi.stubGlobal("WebSocket", FakeSocket);- const fetch = vi.fn(() => Promise.resolve(new Response("frame")));- vi.stubGlobal("fetch", fetch);- const events = {- onStatus: vi.fn(),- onScreen: vi.fn(),- onUnauthorized: vi.fn(),- onMjpegFallback: vi.fn(),- onInputConnected: vi.fn(),- };- const client = createDeviceStreamClient(- {- platform,- deviceId: "test device",- preferMjpeg: platform === "ios",- access: {- httpBase: "https://environment.test/api/device-hub",- wsBase: "wss://environment.test/api/device-hub",- credentials: false,- query: { wsTicket: "stream-ticket", hostId: "ssh-host" },- },- },- { getContext: () => null } as unknown as HTMLCanvasElement,- events,- );- return { client, opened, waitForSocket, events, fetch };- }-- it("uses authenticated iOS MJPEG and forwards controls without a cross-origin video fetch", async () => {- const { client, opened, events, fetch } = setup("ios");- client.start();- const socket = await opened;- const imageUrl = new URL(events.onMjpegFallback.mock.calls[0]![0] as string);- expect(imageUrl.pathname).toContain("test%20device/stream.mjpeg");- expect(imageUrl.searchParams.get("wsTicket")).toBe("stream-ticket");- expect(imageUrl.searchParams.get("hostId")).toBe("ssh-host");- expect(fetch).toHaveBeenCalledTimes(1);- socket.onopen?.();- client.pressButton("home");- client.sendTouch("begin", 0.25, 0.75);- const messages = socket.send.mock.calls.slice(1).map(([bytes]) => {- const packet = bytes as Uint8Array;- return {- tag: packet[0],- body: JSON.parse(new TextDecoder().decode(packet.subarray(1))) as unknown,- };- });- expect(messages).toEqual([- { tag: 0x04, body: { button: "home" } },- { tag: 0x03, body: { type: "begin", x: 0.25, y: 0.75 } },- ]);- client.stop();- expect(socket.close).toHaveBeenCalledTimes(1);- expect(vi.getTimerCount()).toBe(0);- });-- it("forwards Android gestures and device controls through the ticketed host socket", async () => {- const { client, opened } = setup("android");- client.start();- const socket = await opened;- const url = new URL(socket.url);- expect(url.searchParams.get("device")).toBe("test device");- expect(url.searchParams.get("wsTicket")).toBe("stream-ticket");- expect(url.searchParams.get("hostId")).toBe("ssh-host");- client.sendTouch("begin", 0.2, 0.8);- client.sendTouch("move", 0.2, 0.4);- client.sendTouch("end", 0.2, 0.1);- client.pressButton("home");- client.pressButton("appSwitcher");- expect(- socket.send.mock.calls.map(([message]) => JSON.parse(message as string) as unknown),- ).toEqual([- { type: "touch", action: "down", x: 0.2, y: 0.8 },- { type: "touch", action: "move", x: 0.2, y: 0.4 },- { type: "touch", action: "up", x: 0.2, y: 0.1 },- { type: "home" },- { type: "recents" },- ]);- client.stop();- expect(socket.close).toHaveBeenCalledTimes(1);- });-- it("renews an expired Android ticket when the HTTP upgrade is rejected instead of retrying it forever", async () => {- const { client, opened, events } = setup("android");- client.start();- const socket = await opened;- socket.onclose?.({ code: 1006, reason: "" });- expect(events.onUnauthorized).toHaveBeenCalledTimes(1);- expect(vi.getTimerCount()).toBe(0);- client.stop();- });-- it.each(["ios", "android"] as const)(- "keeps a restarted %s stream connected when the discarded socket closes late",- async (platform) => {- const { client, opened, waitForSocket, events } = setup(platform);- client.start();- const discarded = await opened;- client.stop();- const reopened = waitForSocket();- client.start();- const replacement = await reopened;- replacement.onopen?.();- replacement.send.mockClear();- events.onInputConnected.mockClear();-- discarded.onclose?.({ code: 1006, reason: "" });-- expect(events.onUnauthorized).not.toHaveBeenCalled();- expect(events.onInputConnected).not.toHaveBeenCalled();- expect(replacement.close).not.toHaveBeenCalled();- client.pressButton("home");- expect(replacement.send).toHaveBeenCalledTimes(1);- client.stop();- expect(replacement.close).toHaveBeenCalledTimes(1);- expect(vi.getTimerCount()).toBe(0);- },- );-- it.each(["ios", "android"] as const)(- "does not renew credentials or reconnect a stopped %s stream",- async (platform) => {- const { client, opened, events } = setup(platform);- client.start();- const socket = await opened;- events.onInputConnected.mockClear();- client.stop();- socket.onclose?.({ code: 1006, reason: "" });- expect(events.onUnauthorized).not.toHaveBeenCalled();- expect(events.onInputConnected).not.toHaveBeenCalled();- expect(vi.getTimerCount()).toBe(0);- },- );-});--describe("serve-emu frames", () => {- it("strips the SEMU header and reads the keyframe flag and timestamp", () => {- const buffer = new ArrayBuffer(16 + 3);- const view = new DataView(buffer);- view.setUint32(0, 0x53454d55);- view.setUint8(4, 1);- view.setUint8(5, 1);- view.setBigUint64(8, 123456n);- new Uint8Array(buffer).set([7, 8, 9], 16);- const packet = parseSemuPacket(buffer);- expect(packet.isKey).toBe(true);- expect(packet.timestamp).toBe(123456);- expect(Array.from(packet.data)).toEqual([7, 8, 9]);- });-- it("treats a frame without the header as raw data", () => {- const packet = parseSemuPacket(new Uint8Array([0, 0, 1, 0x65]).buffer);- expect(packet.isKey).toBeNull();- expect(packet.data.length).toBe(4);- });-- it("finds the SPS and IDR NAL units in an Annex-B access unit", () => {- const unit = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1f, 0, 0, 1, 0x65, 0xaa]);- const scanned = scanAccessUnit(unit);- expect(scanned.isKey).toBe(true);- expect(scanned.sps && avcCodecString(scanned.sps)).toBe("avc1.64001f");- expect(scanAccessUnit(new Uint8Array([0, 0, 1, 0x41, 0x00])).isKey).toBe(false);- });-});--describe("iOS input startup", () => {- afterEach(() => {- vi.useRealTimers();- vi.unstubAllGlobals();- });-- const setup = () => {- vi.useFakeTimers();- const sockets: FakeSocket[] = [];- class FakeSocket {- static OPEN = 1;- readyState = 1;- binaryType = "";- onopen: (() => void) | null = null;- onmessage: ((event: { data: ArrayBuffer }) => void) | null = null;- onclose: ((event: { code: number; reason: string }) => void) | null = null;- send = vi.fn();- close = vi.fn();- constructor() {- sockets.push(this);- }- }- vi.stubGlobal("WebSocket", FakeSocket);- const signals: AbortSignal[] = [];- vi.stubGlobal(- "fetch",- vi.fn((_url, init: RequestInit) => {- const signal = init.signal!;- signals.push(signal);- return Promise.resolve(- new Response(- new ReadableStream({- start(controller) {- signal.addEventListener("abort", () => controller.error(new Error("aborted")));- },- }),- ),- );- }),- );- const client = createDeviceStreamClient(- {- platform: "ios",- deviceId: "test-device",- access: {- httpBase: "http://test/api/device-hub",- wsBase: "ws://test/api/device-hub",- credentials: true,- query: {},- },- },- { getContext: () => null } as unknown as HTMLCanvasElement,- {- onStatus: vi.fn(),- onScreen: vi.fn(),- onUnauthorized: vi.fn(),- onMjpegFallback: vi.fn(),- onInputConnected: vi.fn(),- },- );- return { client, sockets, signals };- };-- it("connects input when the MJPEG prime never produces a frame", async () => {- const { client, sockets, signals } = setup();- client.start();- await vi.advanceTimersByTimeAsync(2_000);- expect(signals[0]?.aborted).toBe(true);- expect(sockets).toHaveLength(1);- client.stop();- });-- it("aborts priming immediately when hidden without opening a socket later", async () => {- const { client, sockets, signals } = setup();- client.start();- await vi.advanceTimersByTimeAsync(0);- client.stop();- expect(signals[0]?.aborted).toBe(true);- await vi.advanceTimersByTimeAsync(2_000);- expect(sockets).toHaveLength(0);- });-- it.each([- ["landscape_left", 0.7, 1 - 0.2],- ["landscape_right", 1 - 0.7, 0.2],- ])("maps %s touches back to the raw iOS framebuffer", async (orientation, x, y) => {- const { client, sockets } = setup();- client.start();- await vi.advanceTimersByTimeAsync(2_000);- const socket = sockets[0]!;- const json = new TextEncoder().encode(JSON.stringify({ width: 400, height: 800, orientation }));- const packet = new Uint8Array(1 + json.length);- packet[0] = 0x82;- packet.set(json, 1);- socket.onmessage?.({ data: packet.buffer });- client.sendTouch("begin", 0.2, 0.7);- const sent = socket.send.mock.calls[0]![0] as Uint8Array;- expect(JSON.parse(new TextDecoder().decode(sent.subarray(1)))).toEqual({- type: "begin",- x,- y,- });- client.stop();- });-});diff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.tsnew file mode 100644index 00000000000..b947f5c17a7--- /dev/null+++ b/packages/client-runtime/src/device/stream.test.ts@@ -0,0 +1,735 @@+import { afterEach, describe, expect, it, vi } from "vite-plus/test";++import {+ createDeviceStreamClient,+ AvccDemuxer,+ avcCodecString,+ parseSemuPacket,+ scanAccessUnit,+} from "./stream.ts";++const envelope = (tag: number, payload: number[]) => {+ const length = 1 + payload.length;+ return [+ (length >>> 24) & 0xff,+ (length >>> 16) & 0xff,+ (length >>> 8) & 0xff,+ length & 0xff,+ tag,+ ...payload,+ ];+};++describe("AvccDemuxer", () => {+ it("reassembles envelopes split across reads", () => {+ const demuxer = new AvccDemuxer();+ const bytes = new Uint8Array([+ ...envelope(1, [1, 0x64, 0x00, 0x1f]),+ ...envelope(2, [9, 9, 9]),+ ...envelope(0x7f, [0]),+ ...envelope(3, [4]),+ ]);+ const first = demuxer.push(bytes.subarray(0, 7));+ const rest = demuxer.push(bytes.subarray(7));+ const chunks = [...first, ...rest];+ expect(chunks.map((chunk) => chunk.type)).toEqual(["description", "keyframe", "delta"]);+ expect(Array.from(chunks[0]!.payload)).toEqual([1, 0x64, 0x00, 0x1f]);+ expect(Array.from(chunks[1]!.payload)).toEqual([9, 9, 9]);+ });++ it("derives the WebCodecs codec string from the avcC record", () => {+ expect(avcCodecString(new Uint8Array([1, 0x64, 0x00, 0x1f]))).toBe("avc1.64001f");+ expect(avcCodecString(new Uint8Array([1]))).toBe("avc1.42E01E");+ });+});++describe("native device stream transport", () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ function setup(platform: "ios" | "android") {+ vi.useFakeTimers();+ vi.stubGlobal("VideoDecoder", vi.fn());+ vi.stubGlobal("EncodedVideoChunk", vi.fn());+ let resolveOpened!: (socket: FakeSocket) => void;+ const waitForSocket = () =>+ new Promise<FakeSocket>((resolve) => {+ resolveOpened = resolve;+ });+ const opened = waitForSocket();+ class FakeSocket {+ static OPEN = 1;+ readyState = 1;+ binaryType = "";+ onopen: (() => 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;+ resolveOpened(this);+ }+ }+ vi.stubGlobal("WebSocket", FakeSocket);+ const fetch = vi.fn(() => Promise.resolve(new Response("frame")));+ vi.stubGlobal("fetch", fetch);+ const events = {+ onStatus: vi.fn(),+ onScreen: vi.fn(),+ onUnauthorized: vi.fn(),+ onMjpegFallback: vi.fn(),+ onInputConnected: vi.fn(),+ };+ const client = createDeviceStreamClient(+ {+ platform,+ deviceId: "test device",+ preferMjpeg: platform === "ios",+ access: {+ httpBase: "https://environment.test/api/device-hub",+ wsBase: "wss://environment.test/api/device-hub",+ credentials: false,+ query: { wsTicket: "stream-ticket", hostId: "ssh-host" },+ },+ },+ { getContext: () => null } as unknown as HTMLCanvasElement,+ events,+ );+ return { client, opened, waitForSocket, events, fetch };+ }++ it("uses authenticated iOS MJPEG and forwards controls without a cross-origin video fetch", async () => {+ const { client, opened, events, fetch } = setup("ios");+ client.start();+ const socket = await opened;+ const imageUrl = new URL(events.onMjpegFallback.mock.calls[0]![0] as string);+ expect(imageUrl.pathname).toContain("test%20device/stream.mjpeg");+ expect(imageUrl.searchParams.get("wsTicket")).toBe("stream-ticket");+ expect(imageUrl.searchParams.get("hostId")).toBe("ssh-host");+ expect(fetch).toHaveBeenCalledTimes(1);+ socket.onopen?.();+ client.pressButton("home");+ client.sendTouch("begin", 0.25, 0.75);+ const messages = socket.send.mock.calls.slice(1).map(([bytes]) => {+ const packet = bytes as Uint8Array;+ return {+ tag: packet[0],+ body: JSON.parse(new TextDecoder().decode(packet.subarray(1))) as unknown,+ };+ });+ expect(messages).toEqual([+ { tag: 0x04, body: { button: "home" } },+ { tag: 0x03, body: { type: "begin", x: 0.25, y: 0.75 } },+ ]);+ client.stop();+ expect(socket.close).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it("forwards Android gestures and device controls through the ticketed host socket", async () => {+ const { client, opened } = setup("android");+ client.start();+ const socket = await opened;+ const url = new URL(socket.url);+ expect(url.searchParams.get("device")).toBe("test device");+ expect(url.searchParams.get("wsTicket")).toBe("stream-ticket");+ expect(url.searchParams.get("hostId")).toBe("ssh-host");+ client.sendTouch("begin", 0.2, 0.8);+ client.sendTouch("move", 0.2, 0.4);+ client.sendTouch("end", 0.2, 0.1);+ client.pressButton("home");+ client.pressButton("appSwitcher");+ expect(+ socket.send.mock.calls.map(([message]) => JSON.parse(message as string) as unknown),+ ).toEqual([+ { type: "touch", action: "down", x: 0.2, y: 0.8 },+ { type: "touch", action: "move", x: 0.2, y: 0.4 },+ { type: "touch", action: "up", x: 0.2, y: 0.1 },+ { type: "home" },+ { type: "recents" },+ ]);+ client.stop();+ expect(socket.close).toHaveBeenCalledTimes(1);+ });++ it("renews an expired Android ticket when the HTTP upgrade is rejected instead of retrying it forever", async () => {+ const { client, opened, events } = setup("android");+ client.start();+ const socket = await opened;+ socket.onclose?.({ code: 1006, reason: "" });+ expect(events.onUnauthorized).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ client.stop();+ });++ it.each(["ios", "android"] as const)(+ "keeps a restarted %s stream connected when the discarded socket closes late",+ async (platform) => {+ const { client, opened, waitForSocket, events } = setup(platform);+ client.start();+ const discarded = await opened;+ client.stop();+ const reopened = waitForSocket();+ client.start();+ const replacement = await reopened;+ replacement.onopen?.();+ replacement.send.mockClear();+ events.onInputConnected.mockClear();++ discarded.onclose?.({ code: 1006, reason: "" });++ expect(events.onUnauthorized).not.toHaveBeenCalled();+ expect(events.onInputConnected).not.toHaveBeenCalled();+ expect(replacement.close).not.toHaveBeenCalled();+ client.pressButton("home");+ expect(replacement.send).toHaveBeenCalledTimes(1);+ client.stop();+ expect(replacement.close).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ },+ );++ it.each(["ios", "android"] as const)(+ "does not renew credentials or reconnect a stopped %s stream",+ async (platform) => {+ const { client, opened, events } = setup(platform);+ client.start();+ const socket = await opened;+ events.onInputConnected.mockClear();+ client.stop();+ socket.onclose?.({ code: 1006, reason: "" });+ expect(events.onUnauthorized).not.toHaveBeenCalled();+ expect(events.onInputConnected).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ },+ );+});++describe("serve-emu frames", () => {+ it("strips the SEMU header and reads the keyframe flag and timestamp", () => {+ const buffer = new ArrayBuffer(16 + 3);+ const view = new DataView(buffer);+ view.setUint32(0, 0x53454d55);+ view.setUint8(4, 1);+ view.setUint8(5, 1);+ view.setBigUint64(8, 123456n);+ new Uint8Array(buffer).set([7, 8, 9], 16);+ const packet = parseSemuPacket(buffer);+ expect(packet.isKey).toBe(true);+ expect(packet.timestamp).toBe(123456);+ expect(Array.from(packet.data)).toEqual([7, 8, 9]);+ });++ it("treats a frame without the header as raw data", () => {+ const packet = parseSemuPacket(new Uint8Array([0, 0, 1, 0x65]).buffer);+ expect(packet.isKey).toBeNull();+ expect(packet.data.length).toBe(4);+ });++ it("finds the SPS and IDR NAL units in an Annex-B access unit", () => {+ const unit = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1f, 0, 0, 1, 0x65, 0xaa]);+ const scanned = scanAccessUnit(unit);+ expect(scanned.isKey).toBe(true);+ expect(scanned.sps && avcCodecString(scanned.sps)).toBe("avc1.64001f");+ expect(scanAccessUnit(new Uint8Array([0, 0, 1, 0x41, 0x00])).isKey).toBe(false);+ });+});++describe("iOS input startup", () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ const setup = () => {+ vi.useFakeTimers();+ const sockets: FakeSocket[] = [];+ class FakeSocket {+ static OPEN = 1;+ readyState = 1;+ binaryType = "";+ onopen: (() => void) | null = null;+ onmessage: ((event: { data: ArrayBuffer }) => void) | null = null;+ onclose: ((event: { code: number; reason: string }) => void) | null = null;+ send = vi.fn();+ close = vi.fn();+ constructor() {+ sockets.push(this);+ }+ }+ vi.stubGlobal("WebSocket", FakeSocket);+ const signals: AbortSignal[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn((_url, init: RequestInit) => {+ const signal = init.signal!;+ signals.push(signal);+ return Promise.resolve(+ new Response(+ new ReadableStream({+ start(controller) {+ signal.addEventListener("abort", () => controller.error(new Error("aborted")));+ },+ }),+ ),+ );+ }),+ );+ const client = createDeviceStreamClient(+ {+ platform: "ios",+ deviceId: "test-device",+ access: {+ httpBase: "http://test/api/device-hub",+ wsBase: "ws://test/api/device-hub",+ credentials: true,+ query: {},+ },+ },+ { getContext: () => null } as unknown as HTMLCanvasElement,+ {+ onStatus: vi.fn(),+ onScreen: vi.fn(),+ onUnauthorized: vi.fn(),+ onMjpegFallback: vi.fn(),+ onInputConnected: vi.fn(),+ },+ );+ return { client, sockets, signals };+ };++ it("connects input when the MJPEG prime never produces a frame", async () => {+ const { client, sockets, signals } = setup();+ client.start();+ await vi.advanceTimersByTimeAsync(2_000);+ expect(signals[0]?.aborted).toBe(true);+ expect(sockets).toHaveLength(1);+ client.stop();+ });++ it("aborts priming immediately when hidden without opening a socket later", async () => {+ const { client, sockets, signals } = setup();+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ client.stop();+ expect(signals[0]?.aborted).toBe(true);+ await vi.advanceTimersByTimeAsync(2_000);+ expect(sockets).toHaveLength(0);+ });++ it.each([+ ["landscape_left", 0.7, 1 - 0.2],+ ["landscape_right", 1 - 0.7, 0.2],+ ])("maps %s touches back to the raw iOS framebuffer", async (orientation, x, y) => {+ const { client, sockets } = setup();+ client.start();+ await vi.advanceTimersByTimeAsync(2_000);+ const socket = sockets[0]!;+ const json = new TextEncoder().encode(JSON.stringify({ width: 400, height: 800, orientation }));+ const packet = new Uint8Array(1 + json.length);+ packet[0] = 0x82;+ packet.set(json, 1);+ socket.onmessage?.({ data: packet.buffer });+ client.sendTouch("begin", 0.2, 0.7);+ const sent = socket.send.mock.calls[0]![0] as Uint8Array;+ expect(JSON.parse(new TextDecoder().decode(sent.subarray(1)))).toEqual({+ type: "begin",+ x,+ y,+ });+ client.stop();+ });+});++class MjpegImage extends EventTarget {+ naturalWidth = 0;+ naturalHeight = 0;+ src = "";+ removeAttribute(name: string) {+ if (name === "src") {+ this.src = "";+ this.naturalWidth = 0;+ this.naturalHeight = 0;+ }+ }+}++function recoveryFixture(platform: "ios" | "android" = "ios", preferMjpeg = true) {+ vi.useFakeTimers();+ const sockets: Socket[] = [];+ class Socket {+ static OPEN = 1;+ readyState = 1;+ binaryType = "";+ onopen: (() => void) | null = null;+ onmessage: ((event: { data: ArrayBuffer | string }) => void) | null = null;+ onclose: ((event: { code: number; reason: string }) => void) | null = null;+ send = vi.fn();+ close = vi.fn();+ constructor() {+ sockets.push(this);+ }+ }+ vi.stubGlobal("WebSocket", Socket);+ const decoders: Decoder[] = [];+ class Decoder {+ static isConfigSupported = vi.fn(async () => ({ supported: true }));+ state = "unconfigured";+ decodeQueueSize = 0;+ configure() {+ this.state = "configured";+ }+ close() {+ this.state = "closed";+ }+ decode() {}+ readonly callbacks: { output: (frame: VideoFrame) => void; error: () => void };+ constructor(callbacks: { output: (frame: VideoFrame) => void; error: () => void }) {+ this.callbacks = callbacks;+ decoders.push(this);+ }+ }+ vi.stubGlobal("VideoDecoder", Decoder);+ vi.stubGlobal("EncodedVideoChunk", vi.fn());+ const videoBodies: ReadableStreamDefaultController<Uint8Array>[] = [];+ const signals: AbortSignal[] = [];+ const fetch = vi.fn((url: string, init: RequestInit) => {+ const signal = init.signal!;+ signals.push(signal);+ if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime"));+ return Promise.resolve(+ new Response(+ new ReadableStream<Uint8Array>({+ start(body) {+ videoBodies.push(body);+ signal.addEventListener("abort", () => body.error(new Error("aborted")), {+ once: true,+ });+ },+ }),+ ),+ );+ });+ vi.stubGlobal("fetch", fetch);+ const events = {+ onStatus: vi.fn(),+ onScreen: vi.fn(),+ onUnauthorized: vi.fn(),+ onMjpegFallback: vi.fn(),+ onInputConnected: vi.fn(),+ };+ const drawImage = vi.fn();+ const image = new MjpegImage();+ const client = createDeviceStreamClient(+ {+ platform,+ preferMjpeg,+ deviceId: "test-device",+ access: {+ httpBase: "https://test/api/device-hub",+ wsBase: "wss://test/api/device-hub",+ credentials: true,+ query: {},+ },+ },+ { getContext: () => ({ drawImage }) } as unknown as HTMLCanvasElement,+ events,+ );+ client.setMjpegImage(image as unknown as HTMLImageElement);+ const imageReady = () => {+ image.naturalWidth = 400;+ image.naturalHeight = 800;+ image.dispatchEvent(new Event("load"));+ };+ const decodedFrame = (index = decoders.length - 1) => {+ const close = vi.fn();+ decoders[index]!.callbacks.output({+ displayWidth: 400,+ displayHeight: 800,+ close,+ } as unknown as VideoFrame);+ return close;+ };+ const sps = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 1, 0x65]).buffer;+ return {+ client,+ events,+ image,+ imageReady,+ sockets,+ signals,+ fetch,+ videoBodies,+ decoders,+ Decoder,+ drawImage,+ decodedFrame,+ sps,+ };+}++describe("shared device stream readiness and recovery", () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ it("waits for actual MJPEG dimensions without requiring a multipart load event", async () => {+ const { client, events, image } = recoveryFixture();+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(image.src).toContain("stream.mjpeg");+ expect(events.onStatus).not.toHaveBeenCalledWith("streaming", undefined);+ image.naturalWidth = 400;+ image.naturalHeight = 800;+ await vi.advanceTimersByTimeAsync(250);+ expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);+ expect(vi.getTimerCount()).toBe(0);+ await vi.advanceTimersByTimeAsync(20_000);+ expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);+ client.stop();+ });++ it("observes a web image attached after MJPEG fallback has already begun", async () => {+ const { client, image, imageReady, events } = recoveryFixture();+ client.setMjpegImage(null);+ client.start();+ expect(image.src).toBe("");+ await vi.advanceTimersByTimeAsync(1000);+ client.setMjpegImage(image as unknown as HTMLImageElement);+ imageReady();+ expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);+ client.stop();+ expect(image.src).toBe("");+ expect(vi.getTimerCount()).toBe(0);+ });++ it("stops input and video on an image error without treating it as expired credentials", async () => {+ const { client, image, imageReady, sockets, events } = recoveryFixture();+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ sockets[0]!.onopen?.();+ imageReady();+ image.dispatchEvent(new Event("error"));+ expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("Reconnect"));+ expect(events.onInputConnected).toHaveBeenLastCalledWith(false, expect.any(String));+ expect(events.onUnauthorized).not.toHaveBeenCalled();+ expect(sockets[0]!.close).toHaveBeenCalledOnce();+ expect(image.src).toBe("");+ client.pressButton("home");+ expect(sockets[0]!.send).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each([+ ["ios", true],+ ["ios", false],+ ["android", false],+ ] as const)(+ "bounds missing first frames for %s with preferMjpeg=%s",+ async (platform, preferMjpeg) => {+ const { client, events, signals, sockets, image } = recoveryFixture(platform, preferMjpeg);+ client.start();+ await vi.advanceTimersByTimeAsync(14_999);+ expect(events.onStatus.mock.calls.some(([status]) => status === "error")).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ expect(events.onStatus).toHaveBeenLastCalledWith(+ "error",+ expect.stringContaining("No video"),+ );+ expect(events.onInputConnected).toHaveBeenLastCalledWith(false, expect.any(String));+ expect(signals.every((signal) => signal.aborted)).toBe(true);+ expect(sockets[0]!.close).toHaveBeenCalledOnce();+ expect(image.src).toBe("");+ expect(vi.getTimerCount()).toBe(0);+ },+ );++ it("does not extend the first-frame deadline each time a socket reconnects", async () => {+ const { client, sockets, events } = recoveryFixture("android");+ client.start();+ sockets[0]!.onopen?.();+ sockets[0]!.onclose?.({ code: 1000, reason: "restart" });+ await vi.advanceTimersByTimeAsync(14_999);+ sockets[1]!.onopen?.();+ await vi.advanceTimersByTimeAsync(1);+ expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("No video"));+ expect(sockets[1]!.close).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("gives a manual restart a fresh deadline and ignores queued image events from its old binding", async () => {+ const { client, image, events } = recoveryFixture();+ const listeners: EventListener[] = [];+ const add = image.addEventListener.bind(image);+ vi.spyOn(image, "addEventListener").mockImplementation((name, callback, options) => {+ if (typeof callback === "function") listeners.push(callback);+ add(name, callback, options);+ });+ client.start();+ await vi.advanceTimersByTimeAsync(10_000);+ client.stop();+ client.start();+ events.onStatus.mockClear();+ for (const listener of listeners.slice(0, 2)) listener(new Event("error"));+ await vi.advanceTimersByTimeAsync(10_000);+ expect(events.onStatus).not.toHaveBeenCalled();+ const replacement = new MjpegImage();+ client.setMjpegImage(replacement as unknown as HTMLImageElement);+ replacement.naturalWidth = 400;+ replacement.naturalHeight = 800;+ replacement.dispatchEvent(new Event("load"));+ expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);+ client.stop();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("falls back from unsupported iOS H.264 without publishing a terminal error", async () => {+ const { client, videoBodies, Decoder, events, imageReady } = recoveryFixture("ios", false);+ Decoder.isConfigSupported.mockResolvedValue({ supported: false });+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ videoBodies[0]!.enqueue(new Uint8Array(envelope(1, [1, 0x64, 0, 0x1f])));+ await vi.advanceTimersByTimeAsync(0);+ expect(events.onMjpegFallback).toHaveBeenCalledOnce();+ expect(events.onStatus.mock.calls.some(([status]) => status === "error")).toBe(false);+ imageReady();+ expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);+ client.stop();+ });++ it("publishes a terminal unsupported-profile error for Android and closes its socket", async () => {+ const { client, sockets, sps, Decoder, events } = recoveryFixture("android");+ Decoder.isConfigSupported.mockResolvedValue({ supported: false });+ client.start();+ sockets[0]!.onmessage?.({ data: sps });+ await vi.advanceTimersByTimeAsync(0);+ expect(events.onStatus).toHaveBeenLastCalledWith(+ "error",+ expect.stringContaining("cannot decode"),+ );+ expect(sockets[0]!.close).toHaveBeenCalledOnce();+ expect(events.onMjpegFallback).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("waits for decoded Android output and bounds a rotation that never produces another frame", async () => {+ const { client, sockets, sps, events, decodedFrame, drawImage } = recoveryFixture("android");+ client.start();+ sockets[0]!.onmessage?.({ data: sps });+ await vi.advanceTimersByTimeAsync(0);+ expect(events.onStatus.mock.calls.some(([status]) => status === "streaming")).toBe(false);+ expect(decodedFrame()).toHaveBeenCalledOnce();+ expect(drawImage).toHaveBeenCalledOnce();+ expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);+ sockets[0]!.onmessage?.({ data: JSON.stringify({ type: "video-session" }) });+ await vi.advanceTimersByTimeAsync(15_000);+ expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("No video"));+ expect(vi.getTimerCount()).toBe(0);+ });++ it("discards decoder support results and output from a previous Android socket", async () => {+ const { client, sockets, sps, events, Decoder, decoders, decodedFrame, drawImage } =+ recoveryFixture("android");+ let resolveSupport!: (support: { supported: boolean }) => void;+ Decoder.isConfigSupported.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveSupport = resolve;+ }),+ );+ client.start();+ sockets[0]!.onmessage?.({ data: sps });+ client.stop();+ client.start();+ resolveSupport({ supported: true });+ await vi.advanceTimersByTimeAsync(0);+ expect(decoders).toHaveLength(0);+ sockets[1]!.onmessage?.({ data: sps });+ await vi.advanceTimersByTimeAsync(0);+ client.stop();+ client.start();+ events.onStatus.mockClear();+ expect(decodedFrame()).toHaveBeenCalledOnce();+ expect(drawImage).not.toHaveBeenCalled();+ expect(events.onStatus).not.toHaveBeenCalled();+ client.stop();+ });++ it("ignores an old AVCC response rejected after a new attempt is connected", async () => {+ const { client, fetch, events } = recoveryFixture("ios", false);+ let resolveResponse!: (response: Response) => void;+ fetch.mockImplementationOnce(() => Promise.resolve(new Response("prime")));+ fetch.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveResponse = resolve;+ }),+ );+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ client.stop();+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ events.onStatus.mockClear();+ resolveResponse(new Response(null, { status: 401 }));+ await vi.advanceTimersByTimeAsync(0);+ expect(events.onUnauthorized).not.toHaveBeenCalled();+ expect(events.onStatus).not.toHaveBeenCalled();+ client.stop();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("closes a delayed JPEG seed from a stopped AVCC attempt without painting it", async () => {+ const { client, videoBodies, drawImage, events } = recoveryFixture("ios", false);+ let resolveBitmap!: (bitmap: ImageBitmap) => void;+ vi.stubGlobal(+ "createImageBitmap",+ () =>+ new Promise((resolve) => {+ resolveBitmap = resolve;+ }),+ );+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ videoBodies[0]!.enqueue(new Uint8Array(envelope(4, [1])));+ await vi.advanceTimersByTimeAsync(0);+ client.stop();+ client.start();+ events.onStatus.mockClear();+ const close = vi.fn();+ resolveBitmap({ width: 400, height: 800, close } as unknown as ImageBitmap);+ await vi.advanceTimersByTimeAsync(0);+ expect(close).toHaveBeenCalledOnce();+ expect(drawImage).not.toHaveBeenCalled();+ expect(events.onStatus).not.toHaveBeenCalled();+ client.stop();+ });+});++it("reports a stalled AVCC body after its initial image instead of leaving a frozen streaming state", async () => {+ const { client, videoBodies, events, signals } = recoveryFixture("ios", false);+ const close = vi.fn();+ vi.stubGlobal("createImageBitmap", () => Promise.resolve({ width: 400, height: 800, close }));+ try {+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ videoBodies[0]!.enqueue(new Uint8Array(envelope(4, [1])));+ await vi.advanceTimersByTimeAsync(0);+ expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);+ await vi.advanceTimersByTimeAsync(15_000);+ expect(events.onStatus).toHaveBeenLastCalledWith(+ "error",+ expect.stringContaining("stopped receiving video"),+ );+ expect(signals.every((signal) => signal.aborted)).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ client.stop();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ }+});diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.tsindex 02aa46c67e1..9275f7be464 100644--- a/packages/client-runtime/src/device/stream.ts+++ b/packages/client-runtime/src/device/stream.ts@@ -37,8 +37,8 @@ export interface DeviceStreamEvents {readonly onUnauthorized: () => void;/*** H.264 cannot be decoded here (no WebCodecs, or the simulator's profile is- * unsupported); the owner should show this MJPEG URL in an `<img>` instead of- * the canvas.+ * unsupported); the owner should show an `<img>` instead of the canvas+ * and attach it with `setMjpegImage` so the client can observe real frames.*/readonly onMjpegFallback: (url: string) => void;/** Whether touches and keys can currently reach the device. */@@ -56,6 +56,8 @@ export interface DeviceStreamTarget {export type DeviceHardwareButton = "home" | "back" | "recents" | "power" | "appSwitcher";const RETRY_DELAY_MS = 1_000;+const FIRST_FRAME_TIMEOUT_MS = 15_000;+const MJPEG_FRAME_CHECK_MS = 250;const FRAME_DURATION_US = 16_667;const SEMU_MAGIC = 0x53454d55;const SEMU_HEADER_BYTES = 16;@@ -205,6 +207,11 @@ export class AvccDemuxer {export interface DeviceStreamClient {readonly start: () => void;readonly stop: () => void;+ /**+ * Own the displayed MJPEG image's source and frame/error observation.+ * `stop()` detaches it; attach a fresh image for each restart.+ */+ readonly setMjpegImage: (image: HTMLImageElement | null) => void;/** Normalized 0..1 coordinates in the displayed frame. */readonly sendTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;readonly sendKey: (event: KeyboardEvent, phase: "down" | "up") => void;@@ -298,19 +305,99 @@ export function createDeviceStreamClient(let firstFrame = false;let configuring = false;let mjpeg = false;+ let generation = 0;+ let decoderEpoch = 0;+ let frameTimer: ReturnType<typeof setTimeout> | null = null;+ let videoReadTimer: ReturnType<typeof setTimeout> | null = null;+ let mjpegImage: HTMLImageElement | null = null;+ let releaseImage: (() => void) | null = null;const mjpegUrl = () => httpUrl(`/helper/${device}/stream.mjpeg`);+ const setStatus = (status: DeviceStreamStatus, detail?: string) => {+ if (!stopped) events.onStatus(status, detail);+ };++ const clearFrameTimer = () => {+ if (frameTimer !== null) clearTimeout(frameTimer);+ frameTimer = null;+ };++ const fail = (detail: string) => {+ if (stopped) return;+ stop();+ events.onInputConnected(false, detail);+ events.onStatus("error", detail);+ };++ const connecting = (detail?: string) => {+ firstFrame = false;+ if (frameTimer === null) {+ frameTimer = setTimeout(+ () => fail("No video received from the device. Reconnect to try again."),+ FIRST_FRAME_TIMEOUT_MS,+ );+ }+ setStatus("connecting", detail);+ };++ const frameReceived = () => {+ if (firstFrame) return;+ firstFrame = true;+ clearFrameTimer();+ setStatus("streaming");+ };++ const observeMjpegImage = () => {+ releaseImage?.();+ releaseImage = null;+ const image = mjpegImage;+ if (!image || stopped || !mjpeg) return;+ let timer: ReturnType<typeof setTimeout> | null = null;+ let released = false;+ const check = () => {+ if (released || stopped) return;+ if (timer !== null) clearTimeout(timer);+ timer = null;+ if (image.naturalWidth > 0 && image.naturalHeight > 0) frameReceived();+ else {+ // Multipart images may not emit load until the response ends. Stop checking after the first frame.+ timer = setTimeout(check, MJPEG_FRAME_CHECK_MS);+ }+ };+ const error = () => {+ if (!released) fail("Could not receive the device stream. Reconnect to try again.");+ };+ image.addEventListener("load", check);+ image.addEventListener("error", error);+ releaseImage = () => {+ released = true;+ if (timer !== null) clearTimeout(timer);+ image.removeEventListener("load", check);+ image.removeEventListener("error", error);+ image.removeAttribute("src");+ };+ image.src = mjpegUrl();+ check();+ };++ const setMjpegImage = (image: HTMLImageElement | null) => {+ if (mjpegImage === image) return;+ releaseImage?.();+ releaseImage = null;+ mjpegImage = image;+ observeMjpegImage();+ };+const fallBackToMjpeg = () => {if (stopped || mjpeg) return;mjpeg = true;+ controller?.abort();+ controller = null;closeDecoder();+ connecting();events.onMjpegFallback(mjpegUrl());- setStatus("streaming");- };-- const setStatus = (status: DeviceStreamStatus, detail?: string) => {- if (!stopped) events.onStatus(status, detail);+ if (!releaseImage) observeMjpegImage();};const paint = (source: CanvasImageSource, width: number, height: number) => {@@ -323,14 +410,14 @@ export function createDeviceStreamClient(events.onScreen(screen);}}- canvas.getContext("2d")?.drawImage(source, 0, 0, width, height);- if (!firstFrame) {- firstFrame = true;- setStatus("streaming");- }+ const context = canvas.getContext("2d");+ if (!context) return fail("Could not display the device stream. Reconnect to try again.");+ context.drawImage(source, 0, 0, width, height);+ frameReceived();};const closeDecoder = () => {+ decoderEpoch++;try {videoDecoder?.close();} catch {@@ -340,40 +427,51 @@ export function createDeviceStreamClient(awaitingKeyframe = true;};- const makeDecoder = () =>- new VideoDecoder({+ const recoverDecoder = () => {+ if (platform === "ios") fallBackToMjpeg();+ else {+ closeDecoder();+ connecting("Video decoder restarted.");+ requestKeyframe();+ }+ };++ const makeDecoder = () => {+ const decoder = new VideoDecoder({output: (frame) => {try {- paint(frame, frame.displayWidth, frame.displayHeight);+ if (videoDecoder === decoder) paint(frame, frame.displayWidth, frame.displayHeight);} finally {frame.close();}},error: () => {- closeDecoder();- requestKeyframe();+ if (stopped || videoDecoder !== decoder) return;+ recoverDecoder();},});+ return decoder;+ };- /**- * Resolves false when this browser cannot decode the stream's profile- * (simulators encode High 5.1, which headless and some hardware decoders- * reject). iOS then falls back to MJPEG; Android has no MJPEG.- */- const configureDecoder = async (config: VideoDecoderConfig): Promise<boolean> => {+ /** iOS can fall back to MJPEG when the stream's H.264 profile is unsupported. */+ const configureDecoder = async (+ config: VideoDecoderConfig,+ isCurrent: () => boolean,+ ): Promise<boolean> => {+ const epoch = decoderEpoch;const full: VideoDecoderConfig = { ...config, optimizeForLatency: true };const support = await VideoDecoder.isConfigSupported(full).catch(() => ({ supported: false }));- if (stopped) return false;+ if (!isCurrent() || epoch !== decoderEpoch) return false;if (!support.supported) {- setStatus("error", `This browser cannot decode ${config.codec}.`);+ if (platform === "android") fail(`This browser cannot decode ${config.codec}.`);return false;}- if (!videoDecoder || videoDecoder.state === "closed") videoDecoder = makeDecoder();try {+ if (!videoDecoder || videoDecoder.state === "closed") videoDecoder = makeDecoder();videoDecoder.configure(full);return true;} catch (cause) {- setStatus("error", `Video decoder: ${(cause as Error).message}`);+ if (platform === "android") fail(`Video decoder: ${(cause as Error).message}`);return false;}};@@ -385,8 +483,7 @@ export function createDeviceStreamClient(awaitingKeyframe = false;}if (videoDecoder.decodeQueueSize > SOFT_DECODE_QUEUE) {- closeDecoder();- requestKeyframe();+ recoverDecoder();return;}try {@@ -399,8 +496,7 @@ export function createDeviceStreamClient();timestamp += FRAME_DURATION_US;} catch {- closeDecoder();- requestKeyframe();+ recoverDecoder();}};@@ -423,42 +519,66 @@ export function createDeviceStreamClient(const handleUnauthorized = () => {stop();+ events.onInputConnected(false);events.onUnauthorized();};// iOS video: fetch the AVCC body and demux into the decoder.const readIosVideo = async () => {const demuxer = new AvccDemuxer();- controller = new AbortController();+ const session = generation;+ const videoController = new AbortController();+ controller = videoController;+ const isCurrent = () => !stopped && generation === session && controller === videoController;+ let retryDetail: string | undefined;try {const response = await fetch(httpUrl(`/helper/${device}/stream.avcc`), {- signal: controller.signal,+ signal: videoController.signal,credentials: access.credentials ? "include" : "same-origin",});+ if (!isCurrent()) return;if (response.status === 401 || response.status === 403) return handleUnauthorized();if (!response.ok || !response.body) throw new Error(`stream ${response.status}`);const reader = response.body.getReader();for (;;) {- const { done, value } = await reader.read();- if (done || stopped) break;+ // An AVCC body can stay open after its helper stops producing frames.+ const timer = setTimeout(() => {+ if (isCurrent()) fail("Device stream stopped receiving video. Reconnect to try again.");+ }, FIRST_FRAME_TIMEOUT_MS);+ videoReadTimer = timer;+ let result: ReadableStreamReadResult<Uint8Array>;+ try {+ result = await reader.read();+ } finally {+ clearTimeout(timer);+ if (videoReadTimer === timer) videoReadTimer = null;+ }+ const { done, value } = result;+ if (!isCurrent()) return;+ if (done) break;for (const chunk of demuxer.push(value)) {switch (chunk.type) {case "seed":void createImageBitmap(new Blob([chunk.payload as BlobPart], { type: "image/jpeg" })).then((bitmap) => {- paint(bitmap, bitmap.width, bitmap.height);- bitmap.close();+ try {+ if (isCurrent()) paint(bitmap, bitmap.width, bitmap.height);+ } finally {+ bitmap.close();+ }}).catch(() => {});break;case "description": {awaitingKeyframe = true;- const configured = await configureDecoder({- codec: avcCodecString(chunk.payload),- description: chunk.payload,- });+ const configured = await configureDecoder(+ { codec: avcCodecString(chunk.payload), description: chunk.payload },+ isCurrent,+ );+ if (!isCurrent()) return;if (!configured) {await reader.cancel().catch(() => {});+ if (!isCurrent()) return;fallBackToMjpeg();return;}@@ -472,10 +592,16 @@ export function createDeviceStreamClient(}}} catch (cause) {- if (stopped) return;- setStatus("connecting", (cause as Error).message);+ if (!isCurrent()) return;+ retryDetail = (cause as Error).message;+ }+ if (isCurrent()) {+ controller = null;+ videoController.abort();+ closeDecoder();+ connecting(retryDetail);+ scheduleRetry("video", () => void readIosVideo());}- if (!stopped) scheduleRetry("video", () => void readIosVideo());};/**@@ -483,7 +609,7 @@ export function createDeviceStreamClient(* screen capture is running, and the AVCC stream does not reliably start* it. Touching the MJPEG endpoint does; one aborted request is enough.*/- const primeIosHelper = async () => {+ const primeIosHelper = async (session: number) => {const controller = new AbortController();primeController = controller;const timeout = setTimeout(() => controller.abort(), 2_000);@@ -492,6 +618,7 @@ export function createDeviceStreamClient(signal: controller.signal,credentials: access.credentials ? "include" : "same-origin",});+ if (stopped || generation !== session) return;if (response.status === 401 || response.status === 403) return handleUnauthorized();await response.body?.getReader().read();} catch {@@ -506,16 +633,19 @@ export function createDeviceStreamClient(// iOS input socket; also carries the screen config the helper pushes.const connectIosInput = async () => {if (stopped) return;- await primeIosHelper();- if (stopped) return;+ const session = generation;+ await primeIosHelper(session);+ if (stopped || generation !== session) return;const ws = new WebSocket(wsUrl(`/helper/ws?device=${device}`));ws.binaryType = "arraybuffer";socket = ws;ws.onopen = () => {+ if (stopped || socket !== ws) return;ws.send(taggedJson(IOS_MSG_HARDWARE_KEYBOARD, { enabled: false }));events.onInputConnected(true);};ws.onmessage = (event) => {+ if (stopped || socket !== ws) return;if (!(event.data instanceof ArrayBuffer)) return;const bytes = new Uint8Array(event.data);if (bytes.length < 1 || bytes[0] !== IOS_TAG_SCREEN_CONFIG) return;@@ -556,14 +686,21 @@ export function createDeviceStreamClient(ws.binaryType = "arraybuffer";socket = ws;ws.onopen = () => {- setStatus("connecting");+ if (stopped || socket !== ws) return;+ connecting();events.onInputConnected(true);};ws.onmessage = (event) => {+ if (stopped || socket !== ws) 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.- if (isVideoSessionMessage(event.data)) closeDecoder();+ if (isVideoSessionMessage(event.data)) {+ closeDecoder();+ configuring = false;+ connecting();+ requestKeyframe();+ }return;}if (!(event.data instanceof ArrayBuffer)) return;@@ -576,11 +713,16 @@ export function createDeviceStreamClient(if (scanned?.sps && (!videoDecoder || videoDecoder.state !== "configured")) {if (configuring) return;configuring = true;- void configureDecoder({ codec: avcCodecString(scanned.sps) }).then((configured) => {- configuring = false;- awaitingKeyframe = true;- if (configured) requestKeyframe();- });+ const epoch = decoderEpoch;+ const isCurrent = () => !stopped && socket === ws;+ void configureDecoder({ codec: avcCodecString(scanned.sps) }, isCurrent).then(+ (configured) => {+ if (!isCurrent() || epoch !== decoderEpoch) return;+ configuring = false;+ awaitingKeyframe = true;+ if (configured) requestKeyframe();+ },+ );return;}if (!videoDecoder || videoDecoder.state !== "configured") {@@ -601,7 +743,8 @@ export function createDeviceStreamClient((event.code === 1006 && access.query.wsTicket))return handleUnauthorized();- setStatus("connecting", event.reason || undefined);+ configuring = false;+ connecting(event.reason || undefined);scheduleRetry("input", connectAndroid);};ws.onerror = () => ws.close();@@ -610,8 +753,9 @@ export function createDeviceStreamClient(const start = () => {if (!stopped) return;stopped = false;- firstFrame = false;- events.onStatus("connecting");+ generation++;+ configuring = false;+ connecting();if (platform === "ios") {void connectIosInput();if (useWebCodecs) void readIosVideo();@@ -619,27 +763,35 @@ export function createDeviceStreamClient(} else if (useWebCodecs) {connectAndroid();} else {- setStatus("error", "This browser cannot decode the Android stream (WebCodecs unavailable).");+ fail("This browser cannot decode the Android stream (WebCodecs unavailable).");}};const stop = () => {if (stopped) return;stopped = true;+ generation++;mjpeg = false;+ clearFrameTimer();+ if (videoReadTimer !== null) clearTimeout(videoReadTimer);+ videoReadTimer = null;+ releaseImage?.();+ releaseImage = null;+ mjpegImage = null;for (const timer of retryTimers.values()) clearTimeout(timer);retryTimers.clear();primeController?.abort();primeController = null;controller?.abort();controller = null;- socket?.close();+ const discarded = socket;socket = null;+ discarded?.close();closeDecoder();};const send = (payload: Uint8Array<ArrayBuffer> | string) => {- if (socket?.readyState === WebSocket.OPEN) socket.send(payload);+ if (!stopped && socket?.readyState === WebSocket.OPEN) socket.send(payload);};const rawPoint = (x: number, y: number) => {@@ -661,6 +813,7 @@ export function createDeviceStreamClient(return {start,stop,+ setMjpegImage,sendTouch: (phase, x, y) => {if (platform === "ios") {send(taggedJson(IOS_MSG_TOUCH, { type: phase, ...rawPoint(x, y) }));