From 49b497ed73d3a13d934f02efc220a5ec98070f5c Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Wed, 18 Nov 2026 12:22:54 +0100 Subject: [PATCH 01/22] feat(stream): add token provider --- .env.example | 5 +- README.md | 93 +++++++++--- example/main.tsx | 27 ++-- example/server.test.ts | 81 +++++++++++ example/server.ts | 107 +++++++++----- src/components/device-stream.tsx | 5 + src/components/remote-control.tsx | 6 +- src/hooks/use-device-stream.ts | 11 +- src/hooks/use-webrtc-connection.test.ts | 186 ++++++++++++++++++++++++ src/hooks/use-webrtc-connection.ts | 66 ++++++--- src/hooks/webrtc-test-fixture.ts | 51 +++++-- 11 files changed, 536 insertions(+), 102 deletions(-) create mode 100644 example/server.test.ts diff --git a/.env.example b/.env.example index 019c098..61633fa 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,10 @@ # Example dev harness config. Copy to .env and fill in. # Bun auto-loads .env β€” these are read ONLY by example/server.ts (server-side). # The secret key never reaches the browser; the SDK helper uses it server-side. -# Stream WebSockets are direct browser connections authenticated with ?token=. +# The server mints through POST /v1/identity/stream-keys for every socket attempt. +# The browser receives only { key, keyId, expiresAt } with Cache-Control: no-store; +# stream WebSockets connect directly with the single-use key in ?token=. +# Local-only helpers are unauthenticated: add caller/device authorization for production. # Required: your mobilerun secret API key (dr_sk_…). MOBILERUN_API_KEY=dr_sk_your_key_here diff --git a/README.md b/README.md index 561d812..3c68b25 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,8 @@ Drop a live, controllable cloud device (iOS/ Android) into any React app: - πŸ“Ί **``** β€” WebRTC video with touch, swipe and keyboard control, plus automatic reconnects with exponential backoff and a retry UI once attempts are exhausted. -- πŸͺ **`useDeviceStream()`** β€” resolves a device's stream credentials from [`@mobilerun/sdk`](https://www.npmjs.com/package/@mobilerun/sdk), polling while it boots. +- πŸͺ **`useDeviceStream()`** β€” resolves a device's stream URL and state from + [`@mobilerun/sdk`](https://www.npmjs.com/package/@mobilerun/sdk), polling while it boots. - βœ… **``** + **`useTaskApproval()`** β€” show a task's pending human approval (e.g. "enter payment card X into app Y") with a countdown and Approve/Deny buttons. See [Task approvals](#-task-approvals). - 🧭 **``**, **``**, **``** β€” the surrounding chrome and a lower-level escape hatch. - 🎨 **Prebuilt stylesheet** β€” no Tailwind setup required, themeable via CSS variables. @@ -54,35 +55,62 @@ npm install @mobilerun/react @mobilerun/sdk react react-dom The object API helpers (`MobilerunSDK`, `devices.fromId`, `verifyWebhook`) require `@mobilerun/sdk` 6.2 or later. The `{ client, deviceId }` hook form works with older SDKs; the peer dependency range remains `>=2.0.0`. -Keep the API key on your backend. The browser's SDK calls your backend for the device's stream credentials, and `useDeviceStream` refreshes them when the stream reconnects. +Keep the API key on your backend. Use `useDeviceStream` for the URL and device state, and supply a +`tokenProvider` that calls your backend for a fresh single-use stream key before every WebSocket +attempt, including retries. -> ⚠️ **`MOBILERUN_API_KEY` is a secret API key β€” never ship it to the browser.** Only the server reads it. The device endpoint returns only `id`, `state`, `streamUrl`, and `streamToken` to the browser, with missing values set to `null`. The stream token is short-lived and scoped to that device; the browser SDK uses a placeholder key to call your backend. +> ⚠️ **`MOBILERUN_API_KEY` is a secret API key β€” never ship it to the browser.** Only the server reads it. +> The device endpoint returns only `id`, `state`, and `streamUrl`, with missing values set to `null`. +> A separate POST endpoint returns a short-lived stream key scoped to that device; the browser SDK +> uses a placeholder key to call your backend. On your backend, register this handler for `GET /api/v1/devices/:id`, passing the routed device ID: ```ts import { MobilerunSDK } from '@mobilerun/sdk'; -const sdk = new MobilerunSDK(); // reads MOBILERUN_API_KEY, server only +const sdk = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY, server only export async function getDevice(id: string): Promise { - // Authenticate the caller and check the device belongs to them before returning stream credentials. + // Authenticate the caller and check the device belongs to them before returning device metadata. const device = await sdk.devices.get(id); return Response.json({ id: device.info?.id ?? null, state: device.info?.state ?? null, streamUrl: device.info?.streamUrl ?? null, - streamToken: device.info?.streamToken ?? null, + }); +} + +// Register for POST /api/v1/devices/:id/stream-key. +export async function mintStreamKey(deviceId: string): Promise { + // Authenticate the caller and authorize this device in your application first. + const minted = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( + '/identity/stream-keys', + { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, + ); + const { key, keyId, expiresAt } = minted; + return Response.json({ key, keyId, expiresAt }, { + status: 201, + headers: { 'Cache-Control': 'no-store' }, }); } ``` +The public mint API is `POST /v1/identity/stream-keys`, authenticated with your server-held API key. +Its body is `{ deviceId, ttlSeconds? }`; TTL is 60–300 seconds, default 120. It returns HTTP 201 +with `{ key, keyId, expiresAt }` and `Cache-Control: no-store`. The SDK base URL already ends in +`/v1`, so use `/identity/stream-keys` with `sdk.api.post`. Revoke with +`DELETE /v1/identity/stream-keys/{keyId}`. Each key is single-use and device-scoped. `expiresAt` +is diagnostic metadata, not a browser permission or validity check. Do not log or cache keys. +Your backend must authenticate callers and authorize the requested device; never accept an arbitrary +target URL or owner from the browser. Propagate mint refusal without returning upstream credential details. + In your client component, point the SDK at that backend route, as in the example app: ```tsx 'use client'; -import { useMemo } from 'react'; +import { useCallback, useMemo } from 'react'; import { MobilerunSDK } from '@mobilerun/sdk'; import { DeviceStream, useDeviceStream } from '@mobilerun/react'; import '@mobilerun/react/styles.css'; @@ -92,15 +120,24 @@ export function DevicePanel({ deviceId }: { deviceId: string }) { apiKey: 'example-sdk-helper', // placeholder, not a Mobilerun API key baseURL: typeof window === 'undefined' ? '/api/v1' : `${window.location.origin}/api/v1`, // SSR placeholder; the hook only fetches in the browser }), []); - const { streamUrl, streamToken, state, refetch } = useDeviceStream({ + const { streamUrl, state, refetch } = useDeviceStream({ device: sdk.devices.fromId(deviceId), // no request yet }); + const getFreshStreamKey = useCallback(async () => { + const response = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { + method: 'POST', + cache: 'no-store', + }); + if (!response.ok) throw new Error('Stream key request failed'); + const { key } = await response.json(); + return key; + }, [deviceId]); return (
; + ``` -`useDeviceStream` also still accepts `{ client, deviceId }` with a plain `Mobilerun` client, so existing code keeps working. +`tokenProvider?: () => Promise` is supported by `DeviceStream` and `RemoteControl`. +It is awaited once immediately before each socket allocation. It takes precedence over static +`streamToken`/`token`; a rejection or empty key fails that attempt with no fallback. Pending results +after stop, device switch or unmount are ignored. Changing callback identity does not reconnect a +healthy stream. An ICE credential refresh on an existing socket does not call it again. +A server signaling close (including 1001) ends provider-mode media/control and triggers the existing +bounded reconnect policy with a fresh key. `onStreamHealed` can refresh URL/state; it is not per retry +and must not be used to cache a key. + +Static `DeviceStream.streamToken`, `RemoteControl.token`, and the hook's returned `streamToken` are +**deprecated**, retained for existing consumers. Manual URL/token mode is a legacy diagnostic path; +a pasted single-use key cannot reconnect after admission. `useDeviceStream` also still accepts +`{ client, deviceId }` with a plain `Mobilerun` client. ## βœ… Task approvals @@ -143,16 +190,15 @@ const sdk = new MobilerunSDK(); // reads MOBILERUN_API_KEY const APPROVAL_EVENTS = new Set(['task.run.approval_requested', 'task.run.approval_resolved']); const ID = /^[A-Za-z0-9_-]+$/; -// Device credentials: return only the fields needed for streaming. +// Device metadata: return only the fields needed for streaming. app.get('/api/v1/devices/:id', async (c) => { const id = c.req.param('id'); - // Authenticate the caller and check the device belongs to them before returning stream credentials. + // Authenticate the caller and check the device belongs to them before returning device metadata. const device = await sdk.devices.get(id); return c.json({ id: device.info?.id ?? null, state: device.info?.state ?? null, streamUrl: device.info?.streamUrl ?? null, - streamToken: device.info?.streamToken ?? null, }); }); @@ -294,14 +340,23 @@ Every user-visible string can be replaced through the `labels` prop; see `TaskAp ## πŸ§ͺ Try it locally -The repo ships the playground shown above β€” paste an API key + device id, or a raw `streamUrl` + `streamToken`, and stream a real device: +The repo ships the playground shown above. Set the API key server-side and enter a device id; +manual URL/token mode remains available for legacy diagnostics: ```sh bun install bun run example # serves the playground at http://localhost:3000 ``` -In SDK mode the example server exposes one narrow helper endpoint backed by `@mobilerun/sdk` (`sdk.devices.get(id)`) so the API key can stay server-side while retrieving `streamUrl` and `streamToken`. The stream WebSocket itself is opened directly by the browser against `streamUrl`; the component appends `streamToken` as `?token=`. The same server also demonstrates [task approvals](#-task-approvals) (set `MOBILERUN_WEBHOOK_SECRET` for the webhook route). The server binds to `127.0.0.1` and its task and SSE routes are unauthenticated by design. If you need webhooks delivered to your machine, expose only `/webhooks/mobilerun` (for example through a tunnel that forwards just that path), never the whole server. +In SDK mode the example server returns only `id`, `state`, and `streamUrl` from +`GET /api/v1/devices/:id`. Its `POST /api/v1/devices/:id/stream-key` helper calls the public mint +API through `sdk.api.post('/identity/stream-keys', ...)`, returning only `{ key, keyId, expiresAt }` +with `Cache-Control: no-store`. The browser's provider calls it for each connection attempt; the +API key stays server-side. The stream WebSocket connects directly with the fresh key in `?token=`. +The same server also demonstrates [task approvals](#-task-approvals) (set `MOBILERUN_WEBHOOK_SECRET` +for the webhook route). All example helpers are unauthenticated and **local-only**, bound to +`127.0.0.1`. Before adapting them for production, add application authentication and device +authorization. If you need webhook delivery, expose only `/webhooks/mobilerun`, never the whole server. ## 🎨 Styling & theming diff --git a/example/main.tsx b/example/main.tsx index c0208b4..242cba9 100644 --- a/example/main.tsx +++ b/example/main.tsx @@ -187,8 +187,8 @@ interface Status { /** * Drives streaming from a device id via @mobilerun/sdk. `useDeviceStream` - * resolves the device's `streamUrl` + `streamToken`; the component connects the - * WebSocket directly (the token rides in the URL). + * resolves the device's URL/state; tokenProvider mints through our server + * immediately before each direct WebSocket attempt. */ function SdkStream({ apiKey, @@ -211,10 +211,20 @@ function SdkStream({ [apiKey, baseURL], ); // `fromId` makes no request; a fresh handle each render is fine, the hook keys by id. - const { streamUrl, streamToken, state, error, isLoading, refetch } = useDeviceStream({ + const { streamUrl, state, error, isLoading, refetch } = useDeviceStream({ device: sdk.devices.fromId(deviceId), }); + const getFreshStreamKey = useCallback(async () => { + const res = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { + method: 'POST', + cache: 'no-store', + }); + if (!res.ok) throw await readError(res); + const minted = await res.json() as { key: string }; + return minted.key; + }, [deviceId]); + React.useEffect(() => onStatus({ state, error, isLoading }), [state, error, isLoading, onStatus]); const streamRef = useRef(null); @@ -224,7 +234,7 @@ function SdkStream({ ('sdk'); - // SDK mode uses the local server endpoint only to retrieve stream credentials - // without exposing the API key. The WebSocket itself opens the returned streamUrl - // directly in the browser with streamToken appended as ?token=. + // SDK mode retrieves URL/state and mints per connection through the local server. + // The parent API key stays server-side; stream WebSockets connect directly. const apiKey = ''; const baseURL = typeof window === 'undefined' ? '/api/v1' : `${window.location.origin}/api/v1`; const [deviceId, setDeviceId] = useState(''); @@ -434,7 +443,7 @@ function App() { const [status, setStatus] = useState({ isLoading: false, connected: false }); const onStatus = useCallback((p: Partial) => setStatus((s) => ({ ...s, ...p })), []); - // Manual mode: paste a streamUrl + streamToken directly. + // Legacy diagnostic mode: pasted static tokens cannot renew single-use keys on retries. const [streamUrl, setStreamUrl] = useState(''); const [streamToken, setStreamToken] = useState(''); const [applied, setApplied] = useState<{ url?: string; token?: string }>({}); @@ -497,7 +506,7 @@ function App() { SDK
diff --git a/example/server.test.ts b/example/server.test.ts new file mode 100644 index 0000000..2b8df45 --- /dev/null +++ b/example/server.test.ts @@ -0,0 +1,81 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { expect, test } from 'bun:test'; +import { MobilerunSDK } from '@mobilerun/sdk'; +import { createExampleApp } from './server'; + +const deviceId = '11111111-1111-4111-8111-111111111111'; + +// Fake only the external HTTP API; routes and the SDK's request handling stay real. +function upstream(response: object, status = 200) { + const requests: Request[] = []; + const sdk = new MobilerunSDK({ + apiKey: 'test-only-placeholder', + baseURL: 'https://api.example.invalid/v1', + logLevel: 'off', + fetch: async (input, init) => { + requests.push(new Request(input, init)); + return Response.json(response, { status }); + }, + }); + return { app: createExampleApp(sdk), requests }; +} + +test('stream key helper GET returns URL and state without old credentials', async () => { + const f = upstream({ + id: deviceId, + state: 'ready', + streamUrl: 'wss://stream.example.invalid/device', + streamToken: 'legacy-static', + }); + const response = await f.app.request(`/api/v1/devices/${deviceId}`); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + id: '11111111-1111-4111-8111-111111111111', + state: 'ready', + streamUrl: 'wss://stream.example.invalid/device', + }); + expect(f.requests).toHaveLength(1); + expect(f.requests[0].url).toBe( + 'https://api.example.invalid/v1/devices/11111111-1111-4111-8111-111111111111', + ); +}); + +test('stream key helper POST mints once and returns only the flat no-store DTO', async () => { + // Literal public identity contract, with extra upstream data to verify the projection. + const f = upstream({ + key: 'single-use-key', + keyId: 'key-id', + expiresAt: '2026-11-18T12:02:00.000Z', + extra: 'must-not-be-forwarded', + }, 201); + const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ deviceId: 'ignored-device', ttlSeconds: 300, owner: 'ignored' }), + }); + expect(response.status).toBe(201); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(await response.json()).toEqual({ + key: 'single-use-key', + keyId: 'key-id', + expiresAt: '2026-11-18T12:02:00.000Z', + }); + expect(f.requests).toHaveLength(1); + expect(f.requests[0].method).toBe('POST'); + expect(f.requests[0].url).toBe('https://api.example.invalid/v1/identity/stream-keys'); + expect(await f.requests[0].json()).toEqual({ + deviceId: '11111111-1111-4111-8111-111111111111', ttlSeconds: 120, + }); + expect(f.requests[0].headers.get('Authorization')).toBe('Bearer test-only-placeholder'); +}); + +test.each([403, 503])('stream key helper propagates refusal %i without retry or error detail', async (status) => { + const f = upstream({ message: 'sensitive upstream detail' }, status); + const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { method: 'POST' }); + expect(response.status).toBe(status); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(await response.json()).toEqual({ error: 'stream_key_mint_failed' }); + expect(f.requests).toHaveLength(1); +}); diff --git a/example/server.ts b/example/server.ts index aeeab26..ef744c8 100644 --- a/example/server.ts +++ b/example/server.ts @@ -4,15 +4,16 @@ // Dev harness server for the @mobilerun/react example. // // The stream WebSocket is not proxied: the browser connects to the SDK-provided -// streamUrl directly, and @mobilerun/react appends streamToken as ?token=. +// streamUrl directly, and @mobilerun/react appends a fresh stream key as ?token=. // -// For SDK mode, this Bun + Hono server exposes one narrow endpoint that uses the -// official SDK to retrieve streamUrl + streamToken without exposing a secret API key: +// For SDK mode, this Bun + Hono server exposes narrow endpoints that uses the +// official SDK to retrieve streamUrl and mint a key without exposing the parent API key: // // browser ──(same-origin)──▢ this server ──(@mobilerun/sdk)──▢ API // // β€’ Serves the example UI (Bun bundles index.html + main.tsx). -// β€’ Handles GET /api/v1/devices/:deviceId via sdk.devices.get() (SDK object API). +// β€’ GET /api/v1/devices/:deviceId returns id/state/streamUrl only. +// β€’ POST /api/v1/devices/:deviceId/stream-key mints one single-use key per attempt. // β€’ Local use only: the server binds to 127.0.0.1 and its task routes and SSE // route are unauthenticated by design. If you expose anything publicly (e.g. a // tunnel for webhook testing), forward only /webhooks/mobilerun, never the @@ -35,9 +36,13 @@ const API_KEY = process.env.MOBILERUN_API_KEY; const UPSTREAM = process.env.MOBILERUN_API_URL?.replace(/\/+$/, ''); const WEBHOOK_SECRET = process.env.MOBILERUN_WEBHOOK_SECRET; const PORT = Number(process.env.PORT ?? 3000); -const sdk = API_KEY ? new MobilerunSDK({ apiKey: API_KEY, ...(UPSTREAM ? { baseURL: `${UPSTREAM}/v1` } : {}) }) : null; +const sdk = API_KEY ? new MobilerunSDK({ + apiKey: API_KEY, + logLevel: 'off', + ...(UPSTREAM ? { baseURL: `${UPSTREAM}/v1` } : {}), +}) : null; -if (!API_KEY) { +if (import.meta.main && !API_KEY) { console.warn( '\n ! MOBILERUN_API_KEY is not set.\n' + ' Manual URL mode still works. SDK mode needs a key in .env or:\n' + @@ -45,34 +50,58 @@ if (!API_KEY) { ); } -const app = new Hono<{ Bindings: Server }>(); +/** Local-only helpers. Production apps must authenticate callers and authorize each device. */ +export function createExampleApp(sdk: MobilerunSDK | null) { + const app = new Hono<{ Bindings: Server }>(); -app.get('/api/v1/devices/:deviceId', async (c) => { - if (!sdk) { - return c.json({ error: 'missing_api_key', detail: 'Set MOBILERUN_API_KEY to use SDK mode.' }, 500); - } + app.get('/api/v1/devices/:deviceId', async (c) => { + if (!sdk) { + return c.json({ error: 'missing_api_key', detail: 'Set MOBILERUN_API_KEY to use SDK mode.' }, 500); + } - try { - const device = await sdk.devices.get(c.req.param('deviceId')); - return c.json({ - id: device.info?.id ?? null, - state: device.info?.state ?? null, - streamUrl: device.info?.streamUrl ?? null, - streamToken: device.info?.streamToken ?? null, - }); - } catch (err) { - return upstreamFailure(c, 'device_retrieve_failed', err); - } -}); + try { + const device = await sdk.devices.get(c.req.param('deviceId')); + return c.json({ + id: device.info?.id ?? null, + state: device.info?.state ?? null, + streamUrl: device.info?.streamUrl ?? null, + }); + } catch (err) { + return upstreamFailure(c, 'device_retrieve_failed', err); + } + }); + + app.post('/api/v1/devices/:deviceId/stream-key', async (c) => { + c.header('Cache-Control', 'no-store'); + if (!sdk) { + return c.json({ error: 'missing_api_key', detail: 'Set MOBILERUN_API_KEY to use SDK mode.' }, 500); + } + try { + const minted = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( + '/identity/stream-keys', + { body: { deviceId: c.req.param('deviceId'), ttlSeconds: 120 }, maxRetries: 0 }, + ); + const { key, keyId, expiresAt } = minted; + return c.json({ key, keyId, expiresAt }, 201); + } catch (err) { + return upstreamFailure(c, 'stream_key_mint_failed', err, true); + } + }); + return app; +} + +const app = createExampleApp(sdk); const ID_PATTERN = /^[A-Za-z0-9_-]+$/; const MAX_WEBHOOK_BODY_BYTES = 1024 * 1024; /** Maps an upstream API error to a response, passing 4xx/5xx through (404/409 let the UI refetch). */ -function upstreamFailure(c: Context, error: string, err: unknown) { +function upstreamFailure(c: Context, error: string, err: unknown, redact = false) { const { status, message } = err as { status?: number; message?: string }; + const isUpstreamError = status && status >= 400 && status < 600; + const code = (isUpstreamError ? status : 502) as ContentfulStatusCode; + if (redact) return c.json({ error }, code); console.error(`βœ— ${error}`, JSON.stringify(c.req.param()), message ?? String(err)); - const code = (status && status >= 400 && status < 600 ? status : 502) as ContentfulStatusCode; return c.json({ error, detail: message ?? String(err) }, code); } @@ -170,15 +199,21 @@ app.post('/webhooks/mobilerun', async (c) => { return c.body(null, 204); }); -Bun.serve({ - hostname: '127.0.0.1', - port: PORT, - routes: { '/': index }, // Bun bundles + serves the React UI and its assets - development: { hmr: true, console: true }, - fetch: app.fetch, -}); +if (import.meta.main) { + Bun.serve({ + hostname: '127.0.0.1', + port: PORT, + routes: { '/': index }, // Bun bundles + serves the React UI and its assets + development: { hmr: true, console: true }, + fetch: app.fetch, + }); -console.log(`\n β–Έ @mobilerun/react dev harness http://localhost:${PORT}`); -console.log(` β–Έ SDK helper GET /api/v1/devices/:id β†’ ${sdk?.api.baseURL ?? 'https://api.mobilerun.ai/v1'}/devices/:id`); -console.log(' β–Έ approvals GET/POST /api/v1/tasks/:id… Β· POST /webhooks/mobilerun Β· GET /api/v1/events'); -console.log(' β–Έ stream WS direct browser connection using ?token=\n'); + console.log(`\n β–Έ @mobilerun/react dev harness http://localhost:${PORT}`); + const upstreamUrl = sdk?.api.baseURL ?? 'https://api.mobilerun.ai/v1'; + console.log(` β–Έ SDK helper GET /api/v1/devices/:id β†’ ${upstreamUrl}/devices/:id`); + console.log(' β–Έ stream key POST /api/v1/devices/:id/stream-key'); + console.log( + ' β–Έ approvals GET/POST /api/v1/tasks/:id… Β· POST /webhooks/mobilerun Β· GET /api/v1/events', + ); + console.log(' β–Έ stream WS direct browser connection using ?token=\n'); +} diff --git a/src/components/device-stream.tsx b/src/components/device-stream.tsx index 3eb42b5..026d675 100644 --- a/src/components/device-stream.tsx +++ b/src/components/device-stream.tsx @@ -13,7 +13,10 @@ import { useStreamReconnect } from '../hooks/use-stream-reconnect'; interface DeviceStreamProps { streamUrl?: string; + /** @deprecated Use tokenProvider to acquire a fresh key for each connection attempt. */ streamToken?: string; + /** Resolves a fresh stream key immediately before each WebSocket attempt. Overrides streamToken. */ + tokenProvider?: () => Promise; hasControl: boolean; onHasControlChange?: (hasControl: boolean) => void; onConnectionStateChange?: (connected: boolean) => void; @@ -49,6 +52,7 @@ export const DeviceStream = forwardRef(f { streamUrl, streamToken, + tokenProvider, hasControl, onHasControlChange: setHasControl = () => {}, onConnectionStateChange, @@ -127,6 +131,7 @@ export const DeviceStream = forwardRef(f key={streamKey} url={activeTarget.url ?? streamUrl} token={activeTarget.token} + tokenProvider={tokenProvider} className="w-full h-full" onConnectionStateChange={handleConnectionStateChange} onConnectionFailed={onConnectionFailed} diff --git a/src/components/remote-control.tsx b/src/components/remote-control.tsx index 329cee7..a0e81a5 100644 --- a/src/components/remote-control.tsx +++ b/src/components/remote-control.tsx @@ -21,8 +21,10 @@ interface RemoteControlProps { // url is the URL of the instance to connect to. url: string; - // token is used to authenticate the connection to the instance. + /** @deprecated Use tokenProvider to acquire a fresh key for each connection attempt. */ token?: string; + /** Resolves a fresh stream key before each WebSocket attempt. Overrides token. */ + tokenProvider?: () => Promise; // className is the class name to apply to the component // on top of the default styles. @@ -120,6 +122,7 @@ export const RemoteControl = forwardRef className, url, token, + tokenProvider, sessionId: propSessionId, openUrl, onConnectionStateChange, @@ -150,6 +153,7 @@ export const RemoteControl = forwardRef } = useWebRtcConnection({ url, token, + tokenProvider, sessionId, openUrl, videoRef, diff --git a/src/hooks/use-device-stream.ts b/src/hooks/use-device-stream.ts index 8a85e07..7f45e02 100644 --- a/src/hooks/use-device-stream.ts +++ b/src/hooks/use-device-stream.ts @@ -61,7 +61,7 @@ export interface UseDeviceStreamDeviceOptions extends UseDeviceStreamBase { export interface UseDeviceStreamResult { /** WebRTC signaling URL β€” feed straight into ``. */ streamUrl?: string; - /** Stream auth token β€” feed into ``. */ + /** @deprecated Obtain a fresh key from your backend with ``. */ streamToken?: string; /** The device's lifecycle state (`ready`, `assigned`, ...). */ state?: string; @@ -72,22 +72,23 @@ export interface UseDeviceStreamResult { /** The last fetch error, if any. */ error?: unknown; /** - * Re-fetch fresh stream credentials. Wire this into + * Re-fetch the stream URL and device state. Wire this into * `` so a reconnect pulls a fresh URL. */ refetch: () => void; } /** - * Resolves live WebRTC stream credentials for a device via `@mobilerun/sdk`, + * Resolves the WebRTC stream URL and device state via `@mobilerun/sdk`, * polling while the device is still coming up. Pair with ``: * * ```tsx - * const { streamUrl, streamToken, state, refetch } = useDeviceStream({ device }); + * const { streamUrl, state, refetch } = useDeviceStream({ device }); + * // getFreshStreamKey calls your authenticated backend's stream-key endpoint. * return ( * { pc.offer.resolve({ sdp: 'old' }); await restart; f.unmount(); }); + +test('provider per socket awaits a fresh key for first connect and retry', async () => { + const f = await fixture(); + const first = deferred(); + const second = deferred(); + const keys = [first, second]; + let calls = 0; + const tokenProvider = () => keys[calls++].promise; + f.mount('a', undefined, { token: 'legacy-static', tokenProvider }); + await tick(); + expect(calls).toBe(1); + expect(f.sockets).toEqual([]); + first.resolve('first key'); + await tick(); + expect(f.sockets[0].url).toBe('wss://example.invalid/a?token=first+key'); + f.sockets[0].close(1006); + await tick(); + expect(f.failures).toEqual([true]); + f.mount('a', undefined, { tokenProvider }); + await tick(); + expect(calls).toBe(2); + expect(f.sockets).toHaveLength(1); + second.resolve('second-key'); + await tick(); + expect(f.sockets[1].url).toBe('wss://example.invalid/a?token=second-key'); + f.unmount(); +}); + +test.each([ + ['reject', (): Promise => Promise.reject(new Error('refused'))], + ['empty', async (): Promise => ''], + ['whitespace', async (): Promise => ' '], +] as const)('mint failure %s never falls back', async (_failure, tokenProvider) => { + const f = await fixture(); + f.mount('a', undefined, { token: 'legacy-static', tokenProvider }); + await tick(); + expect(f.failures).toEqual([true]); + expect(f.sockets).toEqual([]); + f.fireTimers(); + await tick(); + expect(f.failures).toEqual([true]); + f.unmount(); +}); + +test('stale mint after unmount has no socket, failure or state write', async () => { + const f = await fixture(); + const mint = deferred(); + f.mount('a', undefined, { tokenProvider: () => mint.promise }); + f.unmount(); + const writes = f.stateWrites.length; + mint.resolve('abandoned'); + await tick(); + expect(f.sockets).toEqual([]); + expect(f.failures).toEqual([]); + expect(f.stateWrites).toHaveLength(writes); +}); + +test('stale mint after device switch cannot replace the current socket', async () => { + const f = await fixture(); + const mint = deferred(); + f.mount('a', undefined, { tokenProvider: () => mint.promise }); + f.render('b', undefined, { tokenProvider: async () => 'device-b' }); + await tick(); + const writes = f.stateWrites.length; + mint.resolve('device-a'); + await tick(); + expect(f.sockets.map(ws => ws.url)).toEqual(['wss://example.invalid/b?token=device-b']); + expect(f.failures).toEqual([]); + expect(f.stateWrites).toHaveLength(writes); + f.unmount(); +}); + +test('effect restart ignores a late rejected mint', async () => { + const f = await fixture(); + const mint = deferred(); + f.mount('a', undefined, { tokenProvider: () => mint.promise }); + f.mount('a', undefined, { tokenProvider: async () => 'restarted' }); + await tick(); + const writes = f.stateWrites.length; + mint.reject(new Error('stale refusal')); + await tick(); + expect(f.sockets.map(ws => ws.url)).toEqual(['wss://example.invalid/a?token=restarted']); + expect(f.failures).toEqual([]); + expect(f.stateWrites).toHaveLength(writes); + f.unmount(); +}); + +test.each([1001, 1006])('provider close %i tears down connected media before retry', async (code) => { + const f = await fixture(); + let calls = 0; + const tokenProvider = async () => `key-${++calls}`; + f.mount('a', undefined, { tokenProvider }); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + const pc = f.peers[0]; + pc.connectionState = 'connected'; + pc.onconnectionstatechange!(); + pc.ontrack({ track: { kind: 'video' } }); + const media = f.video.current.srcObject!; + expect(media.getTracks()).toHaveLength(1); + const lateClose = f.sockets[0].onclose!; + f.sockets[0].close(code); + lateClose({ code }); + await tick(); + expect(pc.closed).toBe(true); + expect(pc.channels.map(c => c.closed)).toEqual([true, true]); + expect(f.video.current.srcObject).toBeNull(); + expect(media.getTracks()).toEqual([]); + expect(f.stateWrites.at(-1)).toBe(false); + expect(f.failures).toEqual([true]); + expect(f.bindings.at(-1)).toBeNull(); + f.mount('a', undefined, { tokenProvider }); + await tick(); + expect(calls).toBe(2); + expect(f.sockets[1].url).toBe('wss://example.invalid/a?token=key-2'); + f.unmount(); +}); + +test('provider ICE refresh reuses the existing socket without minting', async () => { + const f = await fixture(); + let calls = 0; + const tokenProvider = async () => { + calls++; + return 'one-key'; + }; + f.mount('a', undefined, { tokenProvider }); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + const pc = f.peers[0]; + pc.offer.resolve({ sdp: 'initial' }); + pc.local.resolve(); + await tick(); + const refresh = { type: 'rtcConfiguration', rtcConfiguration: { iceServers: [] } }; + await f.sockets[0].onmessage!(event(refresh)); + expect(calls).toBe(1); + expect(f.sockets).toHaveLength(1); + expect(pc.configArgs).toEqual([{ iceServers: [] }]); + expect(f.sockets[0].sent.filter(m => m.type === 'offer')).toHaveLength(2); + f.unmount(); +}); + +test('provider startup keeps visibility and keepalive bound to the eventual socket', async () => { + const f = await fixture(); + const mint = deferred(); + f.mount('a', undefined, { tokenProvider: () => mint.promise }); + await tick(); + f.document.hidden = true; + f.visibilityChange(); + mint.resolve('fresh'); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + expect(f.scheduled.filter(t => t.kind === 'interval')).toEqual([]); + f.document.hidden = false; + f.visibilityChange(); + f.fireTimers(); + expect(f.sockets[0].sent.filter(m => m.type === 'keepAlive')).toEqual([ + { type: 'keepAlive', sessionId: 'a' }, + ]); + f.unmount(); +}); + +test('legacy token compatibility keeps synchronous startup and media after signaling close', async () => { + const f = await fixture(); + f.mount('a', undefined, { token: 'legacy-static' }); + expect(f.sockets[0].url).toBe('wss://example.invalid/a?token=legacy-static'); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + f.peers[0].connectionState = 'connected'; + f.peers[0].onconnectionstatechange!(); + f.sockets[0].close(1001); + await tick(); + expect(f.peers[0].closed).toBe(false); + expect(f.failures).toEqual([]); + f.unmount(); +}); diff --git a/src/hooks/use-webrtc-connection.ts b/src/hooks/use-webrtc-connection.ts index 9742192..37e38df 100644 --- a/src/hooks/use-webrtc-connection.ts +++ b/src/hooks/use-webrtc-connection.ts @@ -39,6 +39,7 @@ interface ScreenshotData { interface UseWebRtcConnectionOptions { url: string; token?: string; + tokenProvider?: () => Promise; sessionId: string; openUrl?: string; videoRef: React.RefObject; @@ -69,6 +70,7 @@ interface UseWebRtcConnectionResult { export function useWebRtcConnection({ url, token, + tokenProvider, sessionId, openUrl, videoRef, @@ -78,6 +80,9 @@ export function useWebRtcConnection({ }: UseWebRtcConnectionOptions): UseWebRtcConnectionResult { const tokenRef = useRef(token); tokenRef.current = token; + const tokenProviderRef = useRef(tokenProvider); + tokenProviderRef.current = tokenProvider; + const attemptGenerationRef = useRef(0); const onConnectionStateChangeRef = useRef(onConnectionStateChange); onConnectionStateChangeRef.current = onConnectionStateChange; @@ -191,6 +196,17 @@ export function useWebRtcConnection({ }; const start = async () => { + const generation = ++attemptGenerationRef.current; + const provider = tokenProviderRef.current; + const isActive = () => attemptGenerationRef.current === generation; + let failed = false; + const failAttempt = () => { + if (!isActive()) return; + if (failed) return; + failed = true; + if (provider) stop(); + onConnectionFailedRef.current?.(); + }; // Reset ICE buffering state for the new session. // Done here (not in stop()) to avoid a race where stale candidates // from the old WebSocket leak into the new peer connection. @@ -206,11 +222,17 @@ export function useWebRtcConnection({ let attemptWs: WebSocket | null = null; let cancelStartup = () => {}; try { - const wsUrl = buildWebSocketUrl(url, tokenRef.current); + let streamToken = tokenRef.current; + if (provider) { + streamToken = await provider(); + if (!isActive()) return; + if (!streamToken?.trim()) throw new Error('Stream key provider returned an empty key'); + } + const wsUrl = buildWebSocketUrl(url, streamToken); const ws = new WebSocket(wsUrl); attemptWs = ws; wsRef.current = ws; - const isCurrent = () => wsRef.current === ws; + const isCurrent = () => isActive() && wsRef.current === ws; let pendingTimer: ReturnType | undefined; let configHandler: ((event: MessageEvent) => void) | undefined; let rejectStartup: ((reason: Error) => void) | undefined; @@ -231,12 +253,16 @@ export function useWebRtcConnection({ ws.onerror = (error) => { if (!isCurrent()) return; + if (provider) { + failAttempt(); + return; + } updateStatus('WebSocket error: ' + error); }; // Wait for WebSocket to connect. Teardown settles this wait and removes // its timer even when the browser never delivers another socket event. - await new Promise((resolve, reject) => { + const opened = new Promise((resolve, reject) => { rejectStartup = reject; ws.onopen = () => { if (!isCurrent()) return; @@ -252,19 +278,18 @@ export function useWebRtcConnection({ reject(new Error('WebSocket connection timeout')); }, STREAM_WS_OPEN_TIMEOUT_MS); }); + if (!document.hidden) startKeepAlive(); + await opened; if (!isCurrent()) return; - // The signaling channel dying is terminal for this session (no TURN - // credential refresh, no renegotiation), but while the peer connection - // is still 'connected' media keeps flowing without it β€” there, let the - // peer connection state decide, as it does today. Report a failure only - // when the media path isn't up either (WS died mid-negotiation). + // Provider sessions end with signaling, including a server's 1001 session + // limit. Legacy shared streams keep their existing media-only behavior. ws.onclose = () => { if (!isCurrent()) return; updateStatus('WebSocket closed'); - if (peerConnectionRef.current?.connectionState !== 'connected') { - onConnectionFailedRef.current?.(); - } + if (provider) return failAttempt(); + if (peerConnectionRef.current?.connectionState === 'connected') return; + failAttempt(); }; // Request RTCConfiguration @@ -428,7 +453,8 @@ export function useWebRtcConnection({ const connected = state === 'connected'; if (state === 'failed' || state === 'closed') { // Terminal: this peer connection will not come back on its own. - onConnectionFailedRef.current?.(); + failAttempt(); + if (!isCurrent()) return; } if (connected) { iceRestartGraceUntilRef.current = 0; @@ -663,14 +689,17 @@ export function useWebRtcConnection({ ws.send(JSON.stringify({ type: 'offer', sdp: offer.sdp, sessionId })); updateStatus('Sent offer'); } catch (e) { + if (!isActive()) return; if (wsRef.current !== attemptWs) return; cancelStartup(); - updateStatus('Error: ' + e); - onConnectionFailedRef.current?.(); + updateStatus(provider ? 'Stream connection attempt failed' : 'Error: ' + e); + failAttempt(); } }; const stop = () => { + ++attemptGenerationRef.current; + stopKeepAlive(); cancelStartupRef.current?.(); cancelStartupRef.current = null; clearRestartRecheck(); @@ -718,15 +747,10 @@ export function useWebRtcConnection({ // Start connection when component mounts start(); - // Only start keepAlive if page is visible - if (!document.hidden) { - startKeepAlive(); - } - // Add visibility change listener - const ws = wsRef.current; + const generation = attemptGenerationRef.current; const onVisibilityChange = () => { - if (wsRef.current !== ws) return; + if (attemptGenerationRef.current !== generation) return; handleVisibilityChange(); }; document.addEventListener('visibilitychange', onVisibilityChange); diff --git a/src/hooks/webrtc-test-fixture.ts b/src/hooks/webrtc-test-fixture.ts index 20a3c17..a825f7f 100644 --- a/src/hooks/webrtc-test-fixture.ts +++ b/src/hooks/webrtc-test-fixture.ts @@ -33,16 +33,21 @@ export async function fixture() { sent: Record[] = []; listeners = new Set<(event: { data: string }) => void>(); onopen: (() => void) | null = null; - onclose: (() => void) | null = null; + onclose: ((event?: { code: number }) => void) | null = null; onerror: (() => void) | null = null; onmessage: ((event: { data: string }) => Promise) | null = null; - constructor() { sockets.push(this); } + constructor(readonly url: string) { + sockets.push(this); + } open() { this.readyState = 1; this.onopen?.(); } config() { for (const fn of this.listeners) fn(event({ type: 'rtcConfiguration', rtcConfiguration: {} })); } addEventListener(_name: string, fn: (event: { data: string }) => void) { this.listeners.add(fn); } removeEventListener(_name: string, fn: (event: { data: string }) => void) { this.listeners.delete(fn); } send(data: string) { this.sent.push(JSON.parse(data)); } - close() { this.readyState = 3; this.onclose?.(); } + close(code = 1000) { + this.readyState = 3; + this.onclose?.({ code }); + } } class FakeChannel { closed = false; @@ -83,10 +88,28 @@ export async function fixture() { const states: boolean[] = []; const failures: boolean[] = []; const bindings: (FakePeer | null)[] = []; - const video = { current: { srcObject: null, muted: true } }; + const video = { current: { srcObject: null as MediaStream | null, muted: true } }; + const visibilityListeners = new Set<() => void>(); + const document = { + hidden: false, + addEventListener(_name: string, fn: () => void) { visibilityListeners.add(fn); }, + removeEventListener(_name: string, fn: () => void) { visibilityListeners.delete(fn); }, + }; + class FakeMediaStream { + tracks: object[] = []; + addTrack(track: object) { this.tracks.push(track); } + getTracks() { return [...this.tracks]; } + removeTrack(track: object) { + this.tracks = this.tracks.filter(t => t !== track); + } + } const context = { - window: { setTimeout: setTimer, clearTimeout: clearTimer, setInterval: setIntervalTimer, clearInterval: clearTimer }, - document: { hidden: false, addEventListener() {}, removeEventListener() {} }, + window: { + setTimeout: setTimer, clearTimeout: clearTimer, + setInterval: setIntervalTimer, clearInterval: clearTimer, + location: { href: 'https://example.invalid' }, + }, + document, URL, MediaStream: FakeMediaStream, WebSocket: FakeSocket, RTCPeerConnection: FakePeer, RTCRtpReceiver: { getCapabilities: () => null }, RTCSessionDescription: class { constructor(value: object) { Object.assign(this, value); } }, @@ -95,13 +118,14 @@ export async function fixture() { console, stateWrites, }; const runner = await runHook<{ useWebRtcConnection: (options: object) => { wsRef: { current: FakeSocket | null } } }>( - import.meta.dir + '/use-webrtc-connection.ts', context, { compareEffectDeps: false }, + import.meta.dir + '/use-webrtc-connection.ts', context, ); - const mount = (id = 'a', openUrl?: string) => { - runner.unmount(); + type Credentials = { token?: string; tokenProvider?: () => Promise }; + const render = (id = 'a', openUrl?: string, credentials: Credentials = {}) => { runner.beginRender(); const result = runner.module.exports.useWebRtcConnection({ url: 'wss://example.invalid/' + id, sessionId: id, videoRef: video, openUrl, + ...credentials, onConnectionStateChange: (state: boolean) => states.push(state), onConnectionFailed: () => failures.push(true), onPeerConnectionChange: (pc: FakePeer | null) => bindings.push(pc), @@ -109,8 +133,15 @@ export async function fixture() { runner.flushEffects(); return result; }; + const mount = (id = 'a', openUrl?: string, credentials?: Credentials) => { + runner.unmount(); + return render(id, openUrl, credentials); + }; return { - sockets, peers, timers, scheduled, states, failures, bindings, stateWrites, video, mount, + sockets, peers, timers, scheduled, states, failures, bindings, stateWrites, + video, mount, render, + document, + visibilityChange() { visibilityListeners.forEach(fn => fn()); }, unmount: runner.unmount, fireTimers() { const tasks = [...timers.values()]; timers.clear(); tasks.forEach(fn => fn()); }, async negotiate(id = 'a', openUrl?: string) { mount(id, openUrl); sockets[0].open(); await tick(); sockets[0].config(); await tick(); }, From 6f139eca842def898b61146428f90bb7ef22e830 Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Wed, 18 Nov 2026 12:44:02 +0100 Subject: [PATCH 02/22] fix(stream): close rule and provider timeout --- README.md | 27 ++- example/server.test.ts | 20 ++- example/server.ts | 9 +- src/components/device-stream.tsx | 3 + src/components/remote-control.tsx | 4 + src/hooks/use-device-stream.ts | 6 +- src/hooks/use-stream-reconnect.ts | 22 ++- src/hooks/use-webrtc-connection.test.ts | 223 ++++++++++++++++++++++-- src/hooks/use-webrtc-connection.ts | 58 ++++-- src/hooks/webrtc-test-fixture.ts | 14 +- src/lib/stream-reconnect.test.ts | 12 ++ src/lib/stream-reconnect.ts | 18 +- 12 files changed, 360 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 3c68b25..d7a63ec 100644 --- a/README.md +++ b/README.md @@ -84,15 +84,24 @@ export async function getDevice(id: string): Promise { // Register for POST /api/v1/devices/:id/stream-key. export async function mintStreamKey(deviceId: string): Promise { // Authenticate the caller and authorize this device in your application first. - const minted = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( - '/identity/stream-keys', - { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, - ); - const { key, keyId, expiresAt } = minted; - return Response.json({ key, keyId, expiresAt }, { - status: 201, - headers: { 'Cache-Control': 'no-store' }, - }); + try { + const minted = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( + '/identity/stream-keys', + { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, + ); + const { key, keyId, expiresAt } = minted; + return Response.json({ key, keyId, expiresAt }, { + status: 201, + headers: { 'Cache-Control': 'no-store' }, + }); + } catch (err) { + const { status } = err as { status?: number }; + const isUpstreamError = typeof status === 'number' && status >= 400 && status < 600; + return Response.json({ error: 'stream_key_mint_failed' }, { + status: isUpstreamError ? status : 502, + headers: { 'Cache-Control': 'no-store' }, + }); + } } ``` diff --git a/example/server.test.ts b/example/server.test.ts index 2b8df45..a88cdb2 100644 --- a/example/server.test.ts +++ b/example/server.test.ts @@ -1,7 +1,7 @@ // Copyright 2026 Mobilerun // SPDX-License-Identifier: Apache-2.0 -import { expect, test } from 'bun:test'; +import { expect, spyOn, test } from 'bun:test'; import { MobilerunSDK } from '@mobilerun/sdk'; import { createExampleApp } from './server'; @@ -73,9 +73,25 @@ test('stream key helper POST mints once and returns only the flat no-store DTO', test.each([403, 503])('stream key helper propagates refusal %i without retry or error detail', async (status) => { const f = upstream({ message: 'sensitive upstream detail' }, status); - const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { method: 'POST' }); + const log = spyOn(console, 'error').mockImplementation(() => {}); + let response: Response; + try { + response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { method: 'POST' }); + expect(log.mock.calls).toEqual([['stream_key_mint_failed', status]]); + } finally { + log.mockRestore(); + } expect(response.status).toBe(status); expect(response.headers.get('Cache-Control')).toBe('no-store'); expect(await response.json()).toEqual({ error: 'stream_key_mint_failed' }); expect(f.requests).toHaveLength(1); }); + +test('stream key helper rejects an invalid device id before calling upstream', async () => { + const f = upstream({ key: 'unused' }, 201); + const response = await f.app.request('/api/v1/devices/invalid.id/stream-key', { method: 'POST' }); + expect(response.status).toBe(400); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(await response.json()).toEqual({ error: 'invalid_id' }); + expect(f.requests).toEqual([]); +}); diff --git a/example/server.ts b/example/server.ts index ef744c8..27b0a33 100644 --- a/example/server.ts +++ b/example/server.ts @@ -73,13 +73,15 @@ export function createExampleApp(sdk: MobilerunSDK | null) { app.post('/api/v1/devices/:deviceId/stream-key', async (c) => { c.header('Cache-Control', 'no-store'); + const deviceId = c.req.param('deviceId'); + if (!ID_PATTERN.test(deviceId)) return c.json({ error: 'invalid_id' }, 400); if (!sdk) { return c.json({ error: 'missing_api_key', detail: 'Set MOBILERUN_API_KEY to use SDK mode.' }, 500); } try { const minted = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( '/identity/stream-keys', - { body: { deviceId: c.req.param('deviceId'), ttlSeconds: 120 }, maxRetries: 0 }, + { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, ); const { key, keyId, expiresAt } = minted; return c.json({ key, keyId, expiresAt }, 201); @@ -100,7 +102,10 @@ function upstreamFailure(c: Context, error: string, err: unknown, redact = false const { status, message } = err as { status?: number; message?: string }; const isUpstreamError = status && status >= 400 && status < 600; const code = (isUpstreamError ? status : 502) as ContentfulStatusCode; - if (redact) return c.json({ error }, code); + if (redact) { + console.error(error, code); + return c.json({ error }, code); + } console.error(`βœ— ${error}`, JSON.stringify(c.req.param()), message ?? String(err)); return c.json({ error, detail: message ?? String(err) }, code); } diff --git a/src/components/device-stream.tsx b/src/components/device-stream.tsx index 026d675..f708694 100644 --- a/src/components/device-stream.tsx +++ b/src/components/device-stream.tsx @@ -76,12 +76,14 @@ export const DeviceStream = forwardRef(f attempt, onConnectionStateChange: onReconnectConnectionChange, onConnectionFailed, + onConnectionAttemptStarted, retry, } = useStreamReconnect({ onHeal: onStreamHealed, target, targetKey: `${streamUrl ?? ''}|${streamToken ?? ''}`, enabled: !!streamUrl, + watchdogFromSocket: true, }); const handleConnectionStateChange = useCallback( @@ -135,6 +137,7 @@ export const DeviceStream = forwardRef(f className="w-full h-full" onConnectionStateChange={handleConnectionStateChange} onConnectionFailed={onConnectionFailed} + onConnectionAttemptStarted={onConnectionAttemptStarted} placeholderLabel={status === 'reconnecting' ? reconnectLabel : placeholderLabel} muted={muted} onPeerConnectionChange={onPeerConnectionChange} diff --git a/src/components/remote-control.tsx b/src/components/remote-control.tsx index a0e81a5..f9f1fe1 100644 --- a/src/components/remote-control.tsx +++ b/src/components/remote-control.tsx @@ -53,6 +53,8 @@ interface RemoteControlProps { // intentional teardown. Lets a reconnect manager retry without waiting // out a connect watchdog. onConnectionFailed?: () => void; + /** Fired when a socket is allocated, after any key provider resolves. */ + onConnectionAttemptStarted?: () => void; // Override label for the corner pill shown while the WebRTC stream is // not yet connected. Defaults to "connecting". Pass a device-state-derived @@ -127,6 +129,7 @@ export const RemoteControl = forwardRef openUrl, onConnectionStateChange, onConnectionFailed, + onConnectionAttemptStarted, placeholderLabel, muted = true, onPeerConnectionChange, @@ -159,6 +162,7 @@ export const RemoteControl = forwardRef videoRef, onConnectionStateChange, onConnectionFailed, + onConnectionAttemptStarted, onPeerConnectionChange, }); diff --git a/src/hooks/use-device-stream.ts b/src/hooks/use-device-stream.ts index 7f45e02..c1e9a93 100644 --- a/src/hooks/use-device-stream.ts +++ b/src/hooks/use-device-stream.ts @@ -107,7 +107,7 @@ export function useDeviceStream({ pollIntervalMs = 3000, onError, }: UseDeviceStreamOptions | UseDeviceStreamDeviceOptions): UseDeviceStreamResult { - const [device, setDevice] = useState(undefined); + const [loaded, setLoaded] = useState<{ targetId: string; device: SdkDevice } | undefined>(undefined); const [isLoading, setIsLoading] = useState(enabled); const [error, setError] = useState(undefined); @@ -116,6 +116,8 @@ export function useDeviceStream({ // Keyed by id + client, not handle identity: a fresh handle per render is fine. const targetId = deviceHandle?.id ?? deviceId; const source = deviceHandle?.api ?? client; + // Hide the old URL in the switch render, before effects or a backoff retry can run. + const device = loaded?.targetId === targetId ? loaded?.device : undefined; // Bumping this triggers a re-fetch without changing the polling cadence. const [fetchEpoch, setFetchEpoch] = useState(0); @@ -134,7 +136,7 @@ export function useDeviceStream({ try { const next = await (deviceHandle ? deviceHandle.refresh() : client!.devices.retrieve(targetId!)); if (cancelled) return; - setDevice(next); + setLoaded({ targetId, device: next }); setError(undefined); // Keep polling until the backend hands us a stream URL. if (!next.streamUrl && pollIntervalMs > 0) { diff --git a/src/hooks/use-stream-reconnect.ts b/src/hooks/use-stream-reconnect.ts index 7b1b304..9d070ca 100644 --- a/src/hooks/use-stream-reconnect.ts +++ b/src/hooks/use-stream-reconnect.ts @@ -2,7 +2,7 @@ // Copyright 2026 Mobilerun // SPDX-License-Identifier: Apache-2.0 -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; import { createStreamReconnectController, type StreamReconnectSnapshot } from '../lib/stream-reconnect'; interface UseStreamReconnectOptions { @@ -28,6 +28,8 @@ interface UseStreamReconnectOptions { targetKey: string; /** False while there is no stream target (no URL yet) β€” pauses all timers. */ enabled: boolean; + /** Start the watchdog via onConnectionAttemptStarted instead of mount. Defaults to false. */ + watchdogFromSocket?: boolean; } /** @@ -47,6 +49,7 @@ export function useStreamReconnect({ target, targetKey, enabled, + watchdogFromSocket = false, }: UseStreamReconnectOptions) { const [snapshot, setSnapshot] = useState({ status: 'connecting', @@ -107,16 +110,20 @@ export function useStreamReconnect({ setMount((m) => ({ epoch: m.epoch + 1, target })); } - // Every mount/remount of the stream component (or enable flip) re-arms the - // connect watchdog. Runs after render, i.e. after the remounted component - // actually exists. - useEffect(() => { + const onConnectionAttemptStarted = useCallback(() => { + controllerRef.current?.attemptMounted(); + }, []); + + // Enable failure accounting before the child's passive startup effect, so + // synchronous failures count too. DeviceStream defers the watchdog to its + // socket event; existing hook consumers keep mount-driven arming. + useLayoutEffect(() => { if (enabled) { - controllerRef.current?.attemptMounted(); + controllerRef.current?.attemptMounted(!watchdogFromSocket); } else { controllerRef.current?.setDisabled(); } - }, [mount.epoch, enabled]); + }, [mount.epoch, enabled, watchdogFromSocket]); useEffect(() => { const onVisibility = () => { @@ -151,6 +158,7 @@ export function useStreamReconnect({ status: snapshot.status, attempt: snapshot.attempt, onConnectionStateChange, + onConnectionAttemptStarted, onConnectionFailed, retry, }; diff --git a/src/hooks/use-webrtc-connection.test.ts b/src/hooks/use-webrtc-connection.test.ts index 78b2a8c..13ca775 100644 --- a/src/hooks/use-webrtc-connection.test.ts +++ b/src/hooks/use-webrtc-connection.test.ts @@ -1,8 +1,11 @@ // Copyright 2026 Mobilerun // SPDX-License-Identifier: Apache-2.0 -import { expect, test } from 'bun:test'; -import { tick } from './test-hook-runner'; +import { expect, mock, test } from 'bun:test'; +import { createStreamReconnectController } from '../lib/stream-reconnect'; +import { FakeSchedule } from '../lib/test-clock'; +import { runHook, tick } from './test-hook-runner'; +import type { UseDeviceStreamResult } from './use-device-stream'; import { deferred, event, fixture } from './webrtc-test-fixture'; for (const end of ['unmount', 'switch'] as const) { @@ -257,11 +260,13 @@ test('effect restart ignores a late rejected mint', async () => { f.unmount(); }); -test.each([1001, 1006])('provider close %i tears down connected media before retry', async (code) => { +test.each(['static', 'provider'] as const)( + '%s close 1001 tears down connected media before retry', async (mode) => { const f = await fixture(); let calls = 0; const tokenProvider = async () => `key-${++calls}`; - f.mount('a', undefined, { tokenProvider }); + const credentials = mode === 'provider' ? { tokenProvider } : { token: 'legacy-static' }; + f.mount('a', undefined, credentials); await tick(); f.sockets[0].open(); await tick(); @@ -274,20 +279,218 @@ test.each([1001, 1006])('provider close %i tears down connected media before ret const media = f.video.current.srcObject!; expect(media.getTracks()).toHaveLength(1); const lateClose = f.sockets[0].onclose!; - f.sockets[0].close(code); - lateClose({ code }); + f.sockets[0].close(1001); + lateClose({ code: 1001 }); await tick(); expect(pc.closed).toBe(true); expect(pc.channels.map(c => c.closed)).toEqual([true, true]); expect(f.video.current.srcObject).toBeNull(); expect(media.getTracks()).toEqual([]); expect(f.stateWrites.at(-1)).toBe(false); + expect(f.states).toEqual([true, false]); + expect(f.states.at(-1)).toBe(false); expect(f.failures).toEqual([true]); expect(f.bindings.at(-1)).toBeNull(); - f.mount('a', undefined, { tokenProvider }); + f.mount('a', undefined, credentials); await tick(); - expect(calls).toBe(2); - expect(f.sockets[1].url).toBe('wss://example.invalid/a?token=key-2'); + expect(calls).toBe(mode === 'provider' ? 2 : 0); + const expectedToken = mode === 'provider' ? 'key-2' : 'legacy-static'; + expect(f.sockets[1].url).toBe(`wss://example.invalid/a?token=${expectedToken}`); + f.unmount(); +}); + +test.each(['static', 'provider'] as const)( + '%s close 1006 keeps connected media until retry', async (mode) => { + const f = await fixture(); + let calls = 0; + const tokenProvider = async () => `key-${++calls}`; + const credentials = mode === 'provider' ? { tokenProvider } : { token: 'legacy-static' }; + f.mount('a', undefined, credentials); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + const pc = f.peers[0]; + pc.connectionState = 'connected'; + pc.onconnectionstatechange!(); + pc.ontrack({ track: { kind: 'video' } }); + const media = f.video.current.srcObject; + f.sockets[0].onerror!(); + f.sockets[0].close(1006); + await tick(); + expect(pc.closed).toBe(false); + expect(pc.channels.map(c => c.closed)).toEqual([false, false]); + expect(f.video.current.srcObject).toBe(media); + expect(f.failures).toEqual([]); + expect(f.states).toEqual([true]); + f.mount('a', undefined, credentials); + await tick(); + expect(calls).toBe(mode === 'provider' ? 2 : 0); + const expectedToken = mode === 'provider' ? 'key-2' : 'legacy-static'; + expect(f.sockets[1].url).toBe(`wss://example.invalid/a?token=${expectedToken}`); + f.unmount(); +}); + +test('provider peer failure reports disconnected once before teardown', async () => { + const f = await fixture(); + f.mount('a', undefined, { tokenProvider: async () => 'key' }); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + const pc = f.peers[0]; + pc.connectionState = 'connected'; + pc.onconnectionstatechange!(); + pc.connectionState = 'failed'; + pc.onconnectionstatechange!(); + await tick(); + expect(f.states).toEqual([true, false]); + expect(f.states.at(-1)).toBe(false); + expect(pc.closed).toBe(true); + expect(f.failures).toEqual([true]); + f.unmount(); +}); + +test('provider timeout fails at ten seconds and ignores a late key', async () => { + const clock = new FakeSchedule(); + const f = await fixture(clock); + const mint = deferred(); + f.mount('a', undefined, { token: 'legacy-static', tokenProvider: () => mint.promise }); + clock.advance(9_999); + await tick(); + expect(f.failures).toEqual([]); + clock.advance(1); + await tick(); + expect(f.failures).toEqual([true]); + const writes = f.stateWrites.length; + mint.resolve('too-late'); + await tick(); + expect(f.sockets).toEqual([]); + expect(f.failures).toEqual([true]); + expect(f.stateWrites).toHaveLength(writes); + f.unmount(); +}); + +test('provider phase leaves the full connect watchdog after socket allocation', async () => { + const clock = new FakeSchedule(); + const f = await fixture(clock); + const mint = deferred(); + const controller = createStreamReconnectController({ + onRemount: () => {}, + onSnapshot: () => {}, + onHeal: () => {}, + schedule: clock, + }); + controller.attemptMounted(false); + f.mount('a', undefined, { + tokenProvider: () => mint.promise, + onConnectionAttemptStarted: () => controller.attemptMounted(), + }); + expect(clock.pendingCount).toBe(1); + clock.advance(9_999); + mint.resolve('fresh'); + await tick(); + expect(f.sockets).toHaveLength(1); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + clock.advance(35_001); + expect(controller.getSnapshot()).toEqual({ status: 'connecting', attempt: 0 }); + clock.advance(9_998); + expect(controller.getSnapshot()).toEqual({ status: 'connecting', attempt: 0 }); + clock.advance(1); + expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 1 }); + controller.dispose(); + f.unmount(); +}); + +test.each([ + 'ws://stream.example.invalid/a', + 'https://stream.example.invalid/a', + 'ws://localhost.example.invalid/a', +])('provider rejects insecure URL %s before minting', async (url) => { + const f = await fixture(); + const tokenProvider = mock(async () => 'key'); + f.mount('a', undefined, { url, tokenProvider }); + await tick(); + expect(f.failures).toEqual([true]); + expect(tokenProvider).not.toHaveBeenCalled(); + expect(f.sockets).toEqual([]); + f.unmount(); +}); + +test.each([ + 'ws://localhost:3000/a', + 'ws://127.0.0.1:3000/a', + 'ws://[::1]:3000/a', +])('provider allows loopback URL %s', async (url) => { + const f = await fixture(); + const tokenProvider = mock(async () => 'key'); + f.mount('a', undefined, { url, tokenProvider }); + await tick(); + expect(tokenProvider).toHaveBeenCalledTimes(1); + expect(f.sockets.map(ws => ws.url)).toEqual([`${url}?token=key`]); + expect(f.failures).toEqual([]); + f.unmount(); +}); + +test('device switch during backoff cannot open the old URL with the new provider', async () => { + const runner = await runHook<{ useDeviceStream: (options: unknown) => UseDeviceStreamResult }>( + import.meta.dir + '/use-device-stream.ts', + ); + const nextDevice = deferred<{ streamUrl: string }>(); + const client = { devices: { retrieve: mock() + .mockResolvedValueOnce({ streamUrl: 'wss://example.invalid/a' }) + .mockImplementationOnce(() => nextDevice.promise) } }; + const readTarget = (deviceId: string) => { + runner.beginRender(); + const result = runner.module.exports.useDeviceStream({ client, deviceId }); + runner.flushEffects(); + return result; + }; + readTarget('a'); + await tick(); + let target = readTarget('a'); + const f = await fixture(); + const clock = new FakeSchedule(); + let tokenProvider = async () => 'key-a'; + const connect = () => { + if (!target.streamUrl) return; + f.mount('selected', undefined, { url: target.streamUrl, tokenProvider }); + }; + const controller = createStreamReconnectController({ + onRemount: connect, + onSnapshot: () => {}, + onHeal: () => {}, + schedule: clock, + random: () => 0.5, + }); + connect(); + await tick(); + controller.attemptMounted(); + f.sockets[0].close(1006); + await tick(); + controller.handleFailure(); + expect(controller.getSnapshot().status).toBe('reconnecting'); + target = readTarget('b'); + tokenProvider = async () => 'key-b'; + f.unmount(); + clock.advance(1_000); + await tick(); + expect(f.sockets.map(ws => ws.url)).toEqual(['wss://example.invalid/a?token=key-a']); + expect(target.device).toBeUndefined(); + expect(target.streamUrl).toBeUndefined(); + nextDevice.resolve({ streamUrl: 'wss://example.invalid/b' }); + await tick(); + target = readTarget('b'); + connect(); + await tick(); + expect(f.sockets[1].url).toBe('wss://example.invalid/b?token=key-b'); + controller.dispose(); + runner.unmount(); f.unmount(); }); @@ -350,7 +553,7 @@ test('legacy token compatibility keeps synchronous startup and media after signa await tick(); f.peers[0].connectionState = 'connected'; f.peers[0].onconnectionstatechange!(); - f.sockets[0].close(1001); + f.sockets[0].close(1006); await tick(); expect(f.peers[0].closed).toBe(false); expect(f.failures).toEqual([]); diff --git a/src/hooks/use-webrtc-connection.ts b/src/hooks/use-webrtc-connection.ts index 37e38df..6571d3e 100644 --- a/src/hooks/use-webrtc-connection.ts +++ b/src/hooks/use-webrtc-connection.ts @@ -6,6 +6,7 @@ import type React from 'react'; import { useEffect, useRef, useState } from 'react'; import { + STREAM_TOKEN_PROVIDER_TIMEOUT_MS, STREAM_RTC_CONFIG_TIMEOUT_MS, STREAM_WS_OPEN_TIMEOUT_MS, } from '../lib/stream-reconnect'; @@ -32,6 +33,14 @@ function buildWebSocketUrl(url: string, token?: string): string { return wsUrl.toString(); } +// A stream key may only travel over TLS, except for local development sockets. +function isSecureStreamUrl(url: string): boolean { + const resolved = new URL(url, window.location.href); + if (resolved.protocol === 'wss:') return true; + const isLoopback = ['localhost', '127.0.0.1', '[::1]'].includes(resolved.hostname); + return resolved.protocol === 'ws:' && isLoopback; +} + interface ScreenshotData { dataUri: string; } @@ -50,6 +59,7 @@ interface UseWebRtcConnectionOptions { // (stop/unmount). Distinct from onConnectionStateChange(false), which also // fires for transient non-connected states during normal negotiation. onConnectionFailed?: () => void; + onConnectionAttemptStarted?: () => void; // Fired with the RTCPeerConnection once it is created and with null when // it is torn down. Lets consumers observe the connection (e.g. getStats()) // without owning its lifecycle. @@ -76,6 +86,7 @@ export function useWebRtcConnection({ videoRef, onConnectionStateChange, onConnectionFailed, + onConnectionAttemptStarted, onPeerConnectionChange, }: UseWebRtcConnectionOptions): UseWebRtcConnectionResult { const tokenRef = useRef(token); @@ -87,6 +98,9 @@ export function useWebRtcConnection({ const onConnectionStateChangeRef = useRef(onConnectionStateChange); onConnectionStateChangeRef.current = onConnectionStateChange; + const onConnectionAttemptStartedRef = useRef(onConnectionAttemptStarted); + onConnectionAttemptStartedRef.current = onConnectionAttemptStarted; + const onConnectionFailedRef = useRef(onConnectionFailed); onConnectionFailedRef.current = onConnectionFailed; @@ -200,11 +214,14 @@ export function useWebRtcConnection({ const provider = tokenProviderRef.current; const isActive = () => attemptGenerationRef.current === generation; let failed = false; - const failAttempt = () => { + const failAttempt = (stopMedia = !!provider) => { if (!isActive()) return; if (failed) return; failed = true; - if (provider) stop(); + if (stopMedia) { + onConnectionStateChangeRef.current?.(false); + stop(); + } onConnectionFailedRef.current?.(); }; // Reset ICE buffering state for the new session. @@ -224,7 +241,25 @@ export function useWebRtcConnection({ try { let streamToken = tokenRef.current; if (provider) { - streamToken = await provider(); + if (!isSecureStreamUrl(url)) throw new Error('Stream key requires a secure WebSocket URL'); + let providerTimer: ReturnType | undefined; + try { + streamToken = await new Promise((resolve, reject) => { + providerTimer = setTimeout( + () => reject(new Error('Stream key provider timeout')), + STREAM_TOKEN_PROVIDER_TIMEOUT_MS, + ); + cancelStartup = () => { + clearTimeout(providerTimer); + reject(new Error('Stream key request cancelled')); + }; + cancelStartupRef.current = cancelStartup; + Promise.resolve(provider()).then(resolve, reject); + }); + } finally { + clearTimeout(providerTimer); + if (cancelStartupRef.current === cancelStartup) cancelStartupRef.current = null; + } if (!isActive()) return; if (!streamToken?.trim()) throw new Error('Stream key provider returned an empty key'); } @@ -233,6 +268,8 @@ export function useWebRtcConnection({ attemptWs = ws; wsRef.current = ws; const isCurrent = () => isActive() && wsRef.current === ws; + onConnectionAttemptStartedRef.current?.(); + if (!isCurrent()) return; let pendingTimer: ReturnType | undefined; let configHandler: ((event: MessageEvent) => void) | undefined; let rejectStartup: ((reason: Error) => void) | undefined; @@ -253,11 +290,7 @@ export function useWebRtcConnection({ ws.onerror = (error) => { if (!isCurrent()) return; - if (provider) { - failAttempt(); - return; - } - updateStatus('WebSocket error: ' + error); + updateStatus(provider ? 'WebSocket error' : 'WebSocket error: ' + error); }; // Wait for WebSocket to connect. Teardown settles this wait and removes @@ -282,12 +315,12 @@ export function useWebRtcConnection({ await opened; if (!isCurrent()) return; - // Provider sessions end with signaling, including a server's 1001 session - // limit. Legacy shared streams keep their existing media-only behavior. - ws.onclose = () => { + // A server session end closes media in every credential mode. Other + // signaling closes leave a connected media path running, as before. + ws.onclose = (event) => { if (!isCurrent()) return; updateStatus('WebSocket closed'); - if (provider) return failAttempt(); + if (event.code === 1001) return failAttempt(true); if (peerConnectionRef.current?.connectionState === 'connected') return; failAttempt(); }; @@ -757,7 +790,6 @@ export function useWebRtcConnection({ // Clean up return () => { - stopKeepAlive(); stop(); document.removeEventListener('visibilitychange', onVisibilityChange); }; diff --git a/src/hooks/webrtc-test-fixture.ts b/src/hooks/webrtc-test-fixture.ts index a825f7f..68d9b28 100644 --- a/src/hooks/webrtc-test-fixture.ts +++ b/src/hooks/webrtc-test-fixture.ts @@ -1,6 +1,7 @@ // Copyright 2026 Mobilerun // SPDX-License-Identifier: Apache-2.0 +import type { FakeSchedule } from '../lib/test-clock'; import { runHook, tick } from './test-hook-runner'; export const event = (message: object) => ({ data: JSON.stringify(message) }); @@ -12,7 +13,7 @@ export function deferred() { return { promise, resolve, reject }; } -export async function fixture() { +export async function fixture(clock?: FakeSchedule) { const sockets: FakeSocket[] = []; const peers: FakePeer[] = []; const timers = new Map void>(); @@ -105,7 +106,7 @@ export async function fixture() { } const context = { window: { - setTimeout: setTimer, clearTimeout: clearTimer, + setTimeout: clock?.setTimeout ?? setTimer, clearTimeout: clock?.clearTimeout ?? clearTimer, setInterval: setIntervalTimer, clearInterval: clearTimer, location: { href: 'https://example.invalid' }, }, @@ -114,13 +115,18 @@ export async function fixture() { RTCRtpReceiver: { getCapabilities: () => null }, RTCSessionDescription: class { constructor(value: object) { Object.assign(this, value); } }, RTCIceCandidate: class { constructor(value: object) { Object.assign(this, value); } }, - setTimeout: setTimer, clearTimeout: clearTimer, + setTimeout: clock?.setTimeout ?? setTimer, clearTimeout: clock?.clearTimeout ?? clearTimer, console, stateWrites, }; const runner = await runHook<{ useWebRtcConnection: (options: object) => { wsRef: { current: FakeSocket | null } } }>( import.meta.dir + '/use-webrtc-connection.ts', context, ); - type Credentials = { token?: string; tokenProvider?: () => Promise }; + type Credentials = { + url?: string; + token?: string; + tokenProvider?: () => Promise; + onConnectionAttemptStarted?: () => void; + }; const render = (id = 'a', openUrl?: string, credentials: Credentials = {}) => { runner.beginRender(); const result = runner.module.exports.useWebRtcConnection({ diff --git a/src/lib/stream-reconnect.test.ts b/src/lib/stream-reconnect.test.ts index 3f6af39..1a2c426 100644 --- a/src/lib/stream-reconnect.test.ts +++ b/src/lib/stream-reconnect.test.ts @@ -68,11 +68,23 @@ describe('connect watchdog', () => { // slow-but-valid handshakes the connection layer still considers on // budget β€” and on the final retry strand the stream in 'unavailable' // mid-handshake. + expect(STREAM_CONNECT_TIMEOUT_MS).toBe(45_000); expect(STREAM_CONNECT_TIMEOUT_MS).toBeGreaterThan( STREAM_WS_OPEN_TIMEOUT_MS + STREAM_RTC_CONFIG_TIMEOUT_MS, ); }); + test('a provider phase defers the watchdog but still counts its own failure', () => { + const { schedule, controller } = setup(); + controller.attemptMounted(false); + expect(schedule.pendingCount).toBe(0); + schedule.advance(10_000); + expect(controller.getSnapshot()).toEqual({ status: 'connecting', attempt: 0 }); + controller.handleFailure(); + expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 1 }); + controller.dispose(); + }); + test('an attempt that never connects fails after the timeout and schedules a retry', () => { const { schedule, calls, snapshots, controller } = setup(); controller.attemptMounted(); diff --git a/src/lib/stream-reconnect.ts b/src/lib/stream-reconnect.ts index dcd00ef..520495f 100644 --- a/src/lib/stream-reconnect.ts +++ b/src/lib/stream-reconnect.ts @@ -7,10 +7,11 @@ * into React (remounts via key bump, snapshot into state). * * Lifecycle contract with the hook: - * - `attemptMounted()` is called after every mount/remount of the underlying - * stream component (and on enable). It arms the connect watchdog. - * - `onRemount()` asks the hook to bump the mount epoch; the resulting mount - * calls `attemptMounted()` back. + * - `attemptMounted(false)` prepares a provider phase without a watchdog; + * `attemptMounted()` starts the watchdog when its socket allocates. + * The default keeps existing mount-driven callers unchanged. + * - `onRemount()` asks the hook to bump the mount epoch and prepare the next + * attempt; its socket allocation then starts the connect watchdog. * - `handleConnected`/`handleDisconnected` mirror the WebRTC connection * state; `handleFailure` is the terminal-failure signal (WS died, peer * connection failed, negotiation threw). @@ -39,6 +40,8 @@ export interface StreamReconnectSnapshot { } export const STREAM_RECONNECT_MAX_ATTEMPTS = 6; +// Key acquisition precedes socket allocation and has its own independent budget. +export const STREAM_TOKEN_PROVIDER_TIMEOUT_MS = 10_000; // Connection-layer phase budgets, enforced in use-webrtc-connection: how long // the signaling WebSocket may take to open, and how long the RTCConfiguration // reply may take after that. Each phase rejects (β†’ onConnectionFailed) when @@ -82,8 +85,8 @@ export interface StreamReconnectControllerOptions { } export interface StreamReconnectController { - /** The stream component (re)mounted; arm the connect watchdog. */ - attemptMounted(): void; + /** Begin an attempt; defer the watchdog until socket allocation when false. */ + attemptMounted(startWatchdog?: boolean): void; /** No stream target anymore (URL gone) β€” stop timers, reset counters. */ setDisabled(): void; handleConnected(): void; @@ -201,7 +204,7 @@ export function createStreamReconnectController({ }; return { - attemptMounted() { + attemptMounted(startWatchdog = true) { enabled = true; // Mid-wait mounts are stale (StrictMode remount): the scheduled // attempt owns the next watchdog. @@ -216,6 +219,7 @@ export function createStreamReconnectController({ status = 'connecting'; emit(); } + if (!startWatchdog) return; watchdogTimer = schedule.setTimeout(() => { watchdogTimer = null; countFailure(); From c58a29cec8b6709b02f6299dacd44b901cf65765 Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Thu, 19 Nov 2026 17:24:48 +0100 Subject: [PATCH 03/22] docs(stream): close rule wording --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d7a63ec..3e0c434 100644 --- a/README.md +++ b/README.md @@ -169,8 +169,9 @@ It is awaited once immediately before each socket allocation. It takes precedenc `streamToken`/`token`; a rejection or empty key fails that attempt with no fallback. Pending results after stop, device switch or unmount are ignored. Changing callback identity does not reconnect a healthy stream. An ICE credential refresh on an existing socket does not call it again. -A server signaling close (including 1001) ends provider-mode media/control and triggers the existing -bounded reconnect policy with a fresh key. `onStreamHealed` can refresh URL/state; it is not per retry +A server signaling close with code 1001 ends media/control in every mode and triggers the existing +bounded reconnect policy. Other signaling closes keep a connected media path running. Provider mode +mints a fresh key for each new socket. `onStreamHealed` can refresh URL/state; it is not per retry and must not be used to cache a key. Static `DeviceStream.streamToken`, `RemoteControl.token`, and the hook's returned `streamToken` are From f1b1b76911e247a5758213a727cd6914455de50b Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Fri, 20 Nov 2026 11:50:22 +0100 Subject: [PATCH 04/22] fix(example): loopback host guard --- README.md | 1 + example/server.test.ts | 76 +++++++++++++++++++++++++++++++++++++++--- example/server.ts | 70 ++++++++++++++++++++++---------------- 3 files changed, 115 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 3e0c434..a3c29f7 100644 --- a/README.md +++ b/README.md @@ -367,6 +367,7 @@ The same server also demonstrates [task approvals](#-task-approvals) (set `MOBIL for the webhook route). All example helpers are unauthenticated and **local-only**, bound to `127.0.0.1`. Before adapting them for production, add application authentication and device authorization. If you need webhook delivery, expose only `/webhooks/mobilerun`, never the whole server. +The helper routes only answer loopback Host headers and same-origin requests. ## 🎨 Styling & theming diff --git a/example/server.test.ts b/example/server.test.ts index a88cdb2..d9e5cc2 100644 --- a/example/server.test.ts +++ b/example/server.test.ts @@ -29,7 +29,9 @@ test('stream key helper GET returns URL and state without old credentials', asyn streamUrl: 'wss://stream.example.invalid/device', streamToken: 'legacy-static', }); - const response = await f.app.request(`/api/v1/devices/${deviceId}`); + const response = await f.app.request(`/api/v1/devices/${deviceId}`, { + headers: { Host: 'localhost:3000' }, + }); expect(response.status).toBe(200); expect(await response.json()).toEqual({ id: '11111111-1111-4111-8111-111111111111', @@ -52,7 +54,7 @@ test('stream key helper POST mints once and returns only the flat no-store DTO', }, 201); const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { Host: 'localhost:3000', 'Content-Type': 'application/json' }, body: JSON.stringify({ deviceId: 'ignored-device', ttlSeconds: 300, owner: 'ignored' }), }); expect(response.status).toBe(201); @@ -76,7 +78,10 @@ test.each([403, 503])('stream key helper propagates refusal %i without retry or const log = spyOn(console, 'error').mockImplementation(() => {}); let response: Response; try { - response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { method: 'POST' }); + response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { + method: 'POST', + headers: { Host: 'localhost:3000' }, + }); expect(log.mock.calls).toEqual([['stream_key_mint_failed', status]]); } finally { log.mockRestore(); @@ -89,9 +94,72 @@ test.each([403, 503])('stream key helper propagates refusal %i without retry or test('stream key helper rejects an invalid device id before calling upstream', async () => { const f = upstream({ key: 'unused' }, 201); - const response = await f.app.request('/api/v1/devices/invalid.id/stream-key', { method: 'POST' }); + const response = await f.app.request('/api/v1/devices/invalid.id/stream-key', { + method: 'POST', + headers: { Host: 'localhost:3000' }, + }); expect(response.status).toBe(400); expect(response.headers.get('Cache-Control')).toBe('no-store'); expect(await response.json()).toEqual({ error: 'invalid_id' }); expect(f.requests).toEqual([]); }); + +test('stream key helper rejects a foreign Host before calling upstream', async () => { + const f = upstream({ key: 'unused' }, 201); + const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { + method: 'POST', + headers: { Host: 'attacker.example:3000' }, + }); + expect(response.status).toBe(403); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(await response.json()).toEqual({ error: 'forbidden' }); + expect(f.requests).toEqual([]); +}); + +test('stream key helper rejects a foreign Origin before calling upstream', async () => { + const f = upstream({ key: 'unused' }, 201); + const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { + method: 'POST', + headers: { Host: 'localhost:3000', Origin: 'http://attacker.example:3000' }, + }); + expect(response.status).toBe(403); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(await response.json()).toEqual({ error: 'forbidden' }); + expect(f.requests).toEqual([]); +}); + +test.each([ + ['127.0.0.1:3000', 'http://127.0.0.1:3000'], + ['localhost:3000', 'http://localhost:3000'], + ['[::1]:3000', 'http://[::1]:3000'], +])('stream key helper accepts same-origin requests for %s', async (host, origin) => { + const f = upstream({ key: 'single-use-key', keyId: 'key-id', expiresAt: '2026-11-18T12:02:00.000Z' }, 201); + const response = await f.app.request(`/api/v1/devices/${deviceId}/stream-key`, { + method: 'POST', + headers: { Host: host, Origin: origin }, + }); + expect(response.status).toBe(201); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(await response.json()).toEqual({ + key: 'single-use-key', keyId: 'key-id', expiresAt: '2026-11-18T12:02:00.000Z', + }); + expect(f.requests).toHaveLength(1); +}); + +test('webhook validation is unaffected by foreign Host and Origin headers', async () => { + const f = upstream({}); + const local = await f.app.request('/webhooks/mobilerun', { + method: 'POST', + headers: { Host: 'localhost:3000' }, + body: '{}', + }); + const tunneled = await f.app.request('/webhooks/mobilerun', { + method: 'POST', + headers: { Host: 'tunnel.example', Origin: 'https://sender.example' }, + body: '{}', + }); + expect([401, 500]).toContain(local.status); + expect(tunneled.status).toBe(local.status); + expect(await tunneled.json()).toEqual(await local.json()); + expect(f.requests).toEqual([]); +}); diff --git a/example/server.ts b/example/server.ts index 27b0a33..7434b09 100644 --- a/example/server.ts +++ b/example/server.ts @@ -54,6 +54,20 @@ if (import.meta.main && !API_KEY) { export function createExampleApp(sdk: MobilerunSDK | null) { const app = new Hono<{ Bindings: Server }>(); + app.use('/api/*', async (c, next) => { + const host = c.req.header('Host'); + const allowedHosts = [`127.0.0.1:${PORT}`, `localhost:${PORT}`, `[::1]:${PORT}`]; + const isLoopbackHost = host !== undefined && allowedHosts.includes(host); + const origin = c.req.header('Origin'); + const isSameOrigin = origin === undefined || origin === `http://${host}`; + const isAllowed = isLoopbackHost && isSameOrigin; + if (!isAllowed) { + c.header('Cache-Control', 'no-store'); + return c.json({ error: 'forbidden' }, 403); + } + await next(); + }); + app.get('/api/v1/devices/:deviceId', async (c) => { if (!sdk) { return c.json({ error: 'missing_api_key', detail: 'Set MOBILERUN_API_KEY to use SDK mode.' }, 500); @@ -89,6 +103,34 @@ export function createExampleApp(sdk: MobilerunSDK | null) { return upstreamFailure(c, 'stream_key_mint_failed', err, true); } }); + + app.post('/webhooks/mobilerun', async (c) => { + if (!WEBHOOK_SECRET) return c.json({ error: 'missing_webhook_secret' }, 500); + if (Number(c.req.header('Content-Length') ?? 0) > MAX_WEBHOOK_BODY_BYTES) { + return c.json({ error: 'payload_too_large' }, 413); + } + // Raw bytes exactly as received; the SDK verifies before parsing. + const bytes = new Uint8Array(await c.req.arrayBuffer()); + let event: WebhookEvent; + try { + event = (await verifyWebhook({ + body: bytes, + headers: c.req.raw.headers, + secret: WEBHOOK_SECRET, + })) as WebhookEvent; + } catch (err) { + if (err instanceof WebhookVerificationError) { + if (err.reason === 'invalid_json') return c.json({ error: 'invalid_json' }, 400); + return c.json({ error: 'invalid_signature' }, 401); + } + throw err; + } + const taskId = event?.data?.taskId; + if (typeof event?.type === 'string' && APPROVAL_EVENTS.has(event.type) && typeof taskId === 'string') { + for (const send of subscribers) send({ taskId }); + } + return c.body(null, 204); + }); return app; } @@ -176,34 +218,6 @@ type WebhookEvent = { type?: unknown; data?: { taskId?: unknown } } | null; const APPROVAL_EVENTS = new Set(['task.run.approval_requested', 'task.run.approval_resolved']); -app.post('/webhooks/mobilerun', async (c) => { - if (!WEBHOOK_SECRET) return c.json({ error: 'missing_webhook_secret' }, 500); - if (Number(c.req.header('Content-Length') ?? 0) > MAX_WEBHOOK_BODY_BYTES) { - return c.json({ error: 'payload_too_large' }, 413); - } - // Raw bytes exactly as received; the SDK verifies before parsing. - const bytes = new Uint8Array(await c.req.arrayBuffer()); - let event: WebhookEvent; - try { - event = (await verifyWebhook({ - body: bytes, - headers: c.req.raw.headers, - secret: WEBHOOK_SECRET, - })) as WebhookEvent; - } catch (err) { - if (err instanceof WebhookVerificationError) { - if (err.reason === 'invalid_json') return c.json({ error: 'invalid_json' }, 400); - return c.json({ error: 'invalid_signature' }, 401); - } - throw err; - } - const taskId = event?.data?.taskId; - if (typeof event?.type === 'string' && APPROVAL_EVENTS.has(event.type) && typeof taskId === 'string') { - for (const send of subscribers) send({ taskId }); - } - return c.body(null, 204); -}); - if (import.meta.main) { Bun.serve({ hostname: '127.0.0.1', From de36e859810b982c312f1d21afcbee98a90a1473 Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Fri, 20 Nov 2026 14:40:16 +0100 Subject: [PATCH 05/22] docs(readme): partner-first layout --- CONTRIBUTING.md | 42 ++++ README.md | 426 +++++++---------------------------------- SECURITY.md | 5 + docs/default-ui.md | 32 ++++ docs/stream-keys.md | 129 +++++++++++++ docs/task-approvals.md | 170 ++++++++++++++++ 6 files changed, 451 insertions(+), 353 deletions(-) create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md create mode 100644 docs/default-ui.md create mode 100644 docs/stream-keys.md create mode 100644 docs/task-approvals.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..64eb940 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing + +## Build and test + +```sh +bun install +bun run build # tsup (JS + d.ts) + Tailwind (styles.css) β†’ dist/ +bun run typecheck +bun test +``` + +## Conformance + +The control messages, signalling frames, reconnect policy and input routing are replayed against the shared [conformance fixtures](https://github.com/droidrun/mobilerun-sdk-conformance) that the native SDKs also pass. The vendored copy lives in `conformance/fixtures` (release tag in `conformance/VERSION`) and runs with `bun test`. To move to another release, run `scripts/sync-conformance.sh TAG`. + +## Example app + +The repo ships the playground shown in the [README](README.md). Set the API key server-side and enter a device id; +manual URL/token mode remains available for legacy diagnostics: + +```sh +bun install +bun run example # serves the playground at http://localhost:3000 +``` + +In SDK mode the example server returns only `id`, `state`, and `streamUrl` from +`GET /api/v1/devices/:id`. Its `POST /api/v1/devices/:id/stream-key` helper calls the public mint +API through `sdk.api.post('/identity/stream-keys', ...)`, returning only `{ key, keyId, expiresAt }` +with `Cache-Control: no-store`. The browser's provider calls it for each connection attempt; the +API key stays server-side. The stream WebSocket connects directly with the fresh key in `?token=`. +The same server also demonstrates [task approvals](docs/task-approvals.md) (set `MOBILERUN_WEBHOOK_SECRET` +for the webhook route). All example helpers are unauthenticated and **local-only**, bound to +`127.0.0.1`. Before adapting them for production, add application authentication and device +authorization. If you need webhook delivery, expose only `/webhooks/mobilerun`, never the whole server. +The helper routes only answer loopback Host headers and same-origin requests. + +## Pull requests + +Use commit messages in the form `type(scope): message` and open pull requests against `main`. +Run the build, type check and tests before submitting. + +For security reports, follow [SECURITY.md](SECURITY.md). diff --git a/README.md b/README.md index a3c29f7..44d9a84 100644 --- a/README.md +++ b/README.md @@ -15,35 +15,52 @@
-πŸ“• Documentation -Β· -☁️ Mobilerun Cloud +🀝 Partner guide Β· πŸ“• Documentation Β· ☁️ Mobilerun Cloud [![npm](https://img.shields.io/npm/v/@mobilerun/react.svg?color=cb3837&logo=npm)](https://www.npmjs.com/package/@mobilerun/react) -[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](./LICENSE) -[![mobilerun.ai](https://img.shields.io/badge/mobilerun.ai-white)](https://mobilerun.ai) [![React](https://img.shields.io/badge/React-18%20%7C%2019-149eca.svg)](https://react.dev) +[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](./LICENSE) [![Discord](https://img.shields.io/discord/1360219330318696488?color=white&label=Discord&logo=discord&logoColor=white)](https://discord.gg/ZZbKEZZkwK) -
- -

- @mobilerun/react dev playground -

+**React** Β· [Android](https://github.com/droidrun/mobilerun-android) Β· [iOS](https://github.com/droidrun/mobilerun-swift) Β· [Flutter](https://github.com/droidrun/mobilerun-flutter) -## ✨ What you get - -Drop a live, controllable cloud device (iOS/ Android) into any React app: - -- πŸ“Ί **``** β€” WebRTC video with touch, swipe and keyboard control, plus automatic reconnects with exponential backoff and a retry UI once attempts are exhausted. -- πŸͺ **`useDeviceStream()`** β€” resolves a device's stream URL and state from - [`@mobilerun/sdk`](https://www.npmjs.com/package/@mobilerun/sdk), polling while it boots. -- βœ… **``** + **`useTaskApproval()`** β€” show a task's pending human approval (e.g. "enter payment card X into app Y") with a countdown and Approve/Deny buttons. See [Task approvals](#-task-approvals). -- 🧭 **``**, **``**, **``** β€” the surrounding chrome and a lower-level escape hatch. -- 🎨 **Prebuilt stylesheet** β€” no Tailwind setup required, themeable via CSS variables. -- πŸ“¦ **Typed** β€” ships its own `.d.ts`; React and the SDK are peer dependencies. + -## πŸ“¦ Install +> **Building Mobilerun phones into your platform?** Start with the [Partner guide](https://docs.mobilerun.ai/partners). It walks through the API key, one phone per user, stream keys and live viewing step by step. + + + + + + +
+ @mobilerun/react dev playground + +In this package +
    +
  • DeviceStream β€” video, touch, keyboard control and automatic reconnects.
  • +
  • useDeviceStream β€” stream URL and device state, with boot polling.
  • +
  • TaskApproval / useTaskApproval β€” approval cards and decisions.
  • +
  • NavigationBar / StreamStatusPill β€” stream controls and status.
  • +
  • RemoteControl β€” lower-level stream and input control.
  • +
  • Button / cn β€” shared button and class-name utilities.
  • +
  • useWebRtcConnection β€” lower-level WebRTC connection state.
  • +
  • useStreamReconnect β€” bounded retries and reconnect state.
  • +
  • useDeviceGridSelfHeal β€” coordinate stream recovery in a device grid.
  • +
  • useScrcpyInput β€” send touch and keyboard input.
  • +
  • scrcpy protocol helpers and constants β€” encode remote-control messages.
  • +
  • Typed exports and a prebuilt stylesheet, themeable with CSS variables.
  • +
+Requirements +
    +
  • React and React DOM 18 or 19, in a browser with WebRTC.
  • +
  • @mobilerun/sdk >=2.0.0; object helpers need 6.2+, webhook example 6.2.1+.
  • +
  • A Mobilerun API key on your server.
  • +
  • For source builds: Bun 1.4.4 and TypeScript 6.0.3 (the CI toolchain).
  • +
+
+ +## Install ```sh npm install @mobilerun/react @mobilerun/sdk react react-dom @@ -51,356 +68,59 @@ npm install @mobilerun/react @mobilerun/sdk react react-dom `react`, `react-dom` and `@mobilerun/sdk` are peer dependencies. -## πŸš€ Quick start - -The object API helpers (`MobilerunSDK`, `devices.fromId`, `verifyWebhook`) require `@mobilerun/sdk` 6.2 or later. The `{ client, deviceId }` hook form works with older SDKs; the peer dependency range remains `>=2.0.0`. - -Keep the API key on your backend. Use `useDeviceStream` for the URL and device state, and supply a -`tokenProvider` that calls your backend for a fresh single-use stream key before every WebSocket -attempt, including retries. +## Quick start -> ⚠️ **`MOBILERUN_API_KEY` is a secret API key β€” never ship it to the browser.** Only the server reads it. -> The device endpoint returns only `id`, `state`, and `streamUrl`, with missing values set to `null`. -> A separate POST endpoint returns a short-lived stream key scoped to that device; the browser SDK -> uses a placeholder key to call your backend. +1. Your server mints a short-lived stream key for one device with your API key + (`POST /v1/identity/stream-keys`). Follow the [Partner guide](https://docs.mobilerun.ai/partners). +2. Your app's `tokenProvider` asks your server for a key before each connection. +3. The SDK opens the stream with that key, one key per connection, and reconnects with a fresh one. -On your backend, register this handler for `GET /api/v1/devices/:id`, passing the routed device ID: +Keep `MOBILERUN_API_KEY` on your server. This mint handler excerpt uses the SDK's `/v1` base URL; +see [Stream keys](docs/stream-keys.md) for route setup, metadata fetching and error handling. ```ts import { MobilerunSDK } from '@mobilerun/sdk'; - -const sdk = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY, server only - -export async function getDevice(id: string): Promise { - // Authenticate the caller and check the device belongs to them before returning device metadata. - const device = await sdk.devices.get(id); - return Response.json({ - id: device.info?.id ?? null, - state: device.info?.state ?? null, - streamUrl: device.info?.streamUrl ?? null, - }); -} - -// Register for POST /api/v1/devices/:id/stream-key. +const sdk = new MobilerunSDK({ logLevel: 'off' }); // server only export async function mintStreamKey(deviceId: string): Promise { - // Authenticate the caller and authorize this device in your application first. - try { - const minted = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( - '/identity/stream-keys', - { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, - ); - const { key, keyId, expiresAt } = minted; - return Response.json({ key, keyId, expiresAt }, { - status: 201, - headers: { 'Cache-Control': 'no-store' }, - }); - } catch (err) { - const { status } = err as { status?: number }; - const isUpstreamError = typeof status === 'number' && status >= 400 && status < 600; - return Response.json({ error: 'stream_key_mint_failed' }, { - status: isUpstreamError ? status : 502, - headers: { 'Cache-Control': 'no-store' }, - }); - } -} -``` - -The public mint API is `POST /v1/identity/stream-keys`, authenticated with your server-held API key. -Its body is `{ deviceId, ttlSeconds? }`; TTL is 60–300 seconds, default 120. It returns HTTP 201 -with `{ key, keyId, expiresAt }` and `Cache-Control: no-store`. The SDK base URL already ends in -`/v1`, so use `/identity/stream-keys` with `sdk.api.post`. Revoke with -`DELETE /v1/identity/stream-keys/{keyId}`. Each key is single-use and device-scoped. `expiresAt` -is diagnostic metadata, not a browser permission or validity check. Do not log or cache keys. -Your backend must authenticate callers and authorize the requested device; never accept an arbitrary -target URL or owner from the browser. Propagate mint refusal without returning upstream credential details. - -In your client component, point the SDK at that backend route, as in the example app: - -```tsx -'use client'; - -import { useCallback, useMemo } from 'react'; -import { MobilerunSDK } from '@mobilerun/sdk'; -import { DeviceStream, useDeviceStream } from '@mobilerun/react'; -import '@mobilerun/react/styles.css'; - -export function DevicePanel({ deviceId }: { deviceId: string }) { - const sdk = useMemo(() => new MobilerunSDK({ - apiKey: 'example-sdk-helper', // placeholder, not a Mobilerun API key - baseURL: typeof window === 'undefined' ? '/api/v1' : `${window.location.origin}/api/v1`, // SSR placeholder; the hook only fetches in the browser - }), []); - const { streamUrl, state, refetch } = useDeviceStream({ - device: sdk.devices.fromId(deviceId), // no request yet - }); - const getFreshStreamKey = useCallback(async () => { - const response = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { - method: 'POST', - cache: 'no-store', - }); - if (!response.ok) throw new Error('Stream key request failed'); - const { key } = await response.json(); - return key; - }, [deviceId]); - - return ( -
- -
+ // Authenticate your user and check they own the device before minting. + const { key, keyId, expiresAt } = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( + '/identity/stream-keys', { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, ); + return Response.json({ key, keyId, expiresAt }, { status: 201, headers: { 'Cache-Control': 'no-store' } }); } ``` -### Without the hook - -Supply an existing stream URL and the same server-backed callback: +Pass a stream URL fetched through your backend and a callback that calls your mint route: ```tsx - -``` - -`tokenProvider?: () => Promise` is supported by `DeviceStream` and `RemoteControl`. -It is awaited once immediately before each socket allocation. It takes precedence over static -`streamToken`/`token`; a rejection or empty key fails that attempt with no fallback. Pending results -after stop, device switch or unmount are ignored. Changing callback identity does not reconnect a -healthy stream. An ICE credential refresh on an existing socket does not call it again. -A server signaling close with code 1001 ends media/control in every mode and triggers the existing -bounded reconnect policy. Other signaling closes keep a connected media path running. Provider mode -mints a fresh key for each new socket. `onStreamHealed` can refresh URL/state; it is not per retry -and must not be used to cache a key. - -Static `DeviceStream.streamToken`, `RemoteControl.token`, and the hook's returned `streamToken` are -**deprecated**, retained for existing consumers. Manual URL/token mode is a legacy diagnostic path; -a pasted single-use key cannot reconnect after admission. `useDeviceStream` also still accepts -`{ client, deviceId }` with a plain `Mobilerun` client. - -## βœ… Task approvals - -A task can pause and wait for a human to approve a step, for example entering a payment card into an app. `useTaskApproval()` loads the pending approval and `` renders it with a countdown and Approve/Deny buttons. - -**The decision goes through your backend.** The API key that may approve is a secret and must never reach the browser, so the browser only talks to your own routes. The Mobilerun API owns the approval state and decides: the component renders what it is given and forwards the decision, and the countdown is display only. A 404/409 from the decide call (unknown, already resolved or expired) comes back as an error and triggers a refetch. - -### 1. Subscribe a webhook - -In your Mobilerun webhook settings, point an endpoint at your backend and filter it to the two approval events: `task.run.approval_requested` and `task.run.approval_resolved`. Events only tell the browser to reload; the fetched approval is the source of truth. - -Each delivery carries `X-Mobilerun-Timestamp` (Unix ms) and `X-Mobilerun-Signature: sha256=`, an HMAC-SHA256 of `"{timestamp}.{rawBody}"` with the endpoint secret. `verifyWebhook` from `@mobilerun/sdk` checks the signature and the 5-minute timestamp window and returns the parsed payload; pass it the body bytes exactly as received. SDK 6.2.1 or later distinguishes `invalid_json` (a signed but unparsable body), which the handler answers with HTTP 400. - -### 2. Backend sketch - -```ts -import { MobilerunSDK, verifyWebhook, WebhookVerificationError } from '@mobilerun/sdk'; - -const sdk = new MobilerunSDK(); // reads MOBILERUN_API_KEY -const APPROVAL_EVENTS = new Set(['task.run.approval_requested', 'task.run.approval_resolved']); -const ID = /^[A-Za-z0-9_-]+$/; - -// Device metadata: return only the fields needed for streaming. -app.get('/api/v1/devices/:id', async (c) => { - const id = c.req.param('id'); - // Authenticate the caller and check the device belongs to them before returning device metadata. - const device = await sdk.devices.get(id); - return c.json({ - id: device.info?.id ?? null, - state: device.info?.state ?? null, - streamUrl: device.info?.streamUrl ?? null, - }); -}); - -// 1. Webhook: verify the raw bytes, then push a change signal to the user's browser (SSE, ...) -app.post('/webhooks/mobilerun', async (c) => { - const secret = process.env.MOBILERUN_WEBHOOK_SECRET; - if (!secret) return c.json({ error: 'missing_webhook_secret' }, 500); - const bytes = new Uint8Array(await c.req.arrayBuffer()); - let event; - try { - event = await verifyWebhook({ - body: bytes, - headers: c.req.raw.headers, - secret, - }) as { type?: string; data?: { taskId?: string } } | null; - } catch (err) { - if (err instanceof WebhookVerificationError) { - if (err.reason === 'invalid_json') return c.json({ error: 'invalid_json' }, 400); - return c.json({ error: 'invalid_signature' }, 401); - } - throw err; - } - const taskId = event?.data?.taskId; - if (taskId && APPROVAL_EVENTS.has(event?.type ?? '')) push({ taskId }); - return c.body(null, 204); -}); - -// 2. Pending approval: GET /tasks/{id} β†’ task.pendingApproval (null when none) -app.get('/api/tasks/:id', async (c) => { - const id = c.req.param('id'); - if (!ID.test(id)) return c.json({ error: 'invalid_id' }, 400); - // Authenticate the caller and check the task belongs to their user/org first. - const { task } = await sdk.api.get<{ task?: { pendingApproval?: unknown } }>(`/tasks/${encodeURIComponent(id)}`); - return c.json({ pendingApproval: task?.pendingApproval ?? null }); -}); - -// 3. Decision: POST /tasks/{id}/approvals/{approvalId} { decision: 'approve' | 'deny' } -app.post('/api/tasks/:id/approvals/:approvalId', async (c) => { - const id = c.req.param('id'); - const approvalId = c.req.param('approvalId'); - if (!ID.test(id) || !ID.test(approvalId)) return c.json({ error: 'invalid_id' }, 400); - const { decision } = await c.req.json(); - if (decision !== 'approve' && decision !== 'deny') return c.json({ error: 'invalid_decision' }, 422); - // Authenticate the caller and check the task belongs to their user/org first. - const url = `/tasks/${encodeURIComponent(id)}/approvals/${encodeURIComponent(approvalId)}`; - await sdk.api.post(url, { body: { decision } }); - return c.body(null, 204); -}); -``` - -Authenticate every route and check that the task belongs to the signed-in user or organization before forwarding. A delivery can be replayed within the 5-minute window; that is harmless here because events only trigger a refetch. Dedupe on the event `id` if your handler does more. - -`bun run example` runs a working version of all three plus an SSE endpoint. It is for local use only: it binds to `127.0.0.1` and its task and SSE routes are unauthenticated. - -### 3. Client - -```tsx -import { TaskApproval, useTaskApproval, type PendingApproval } from '@mobilerun/react'; +import { DeviceStream } from '@mobilerun/react'; import '@mobilerun/react/styles.css'; - -export function Approval({ taskId }: { taskId: string }) { - const { approval, decide, isDeciding, decision, error } = useTaskApproval({ - taskId, - fetchApproval: async (id) => { - const res = await fetch(`/api/tasks/${encodeURIComponent(id)}`); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - return ((await res.json()) as { pendingApproval: PendingApproval | null }).pendingApproval; - }, - decide: async ({ taskId, approvalId, decision }) => { - const url = `/api/tasks/${encodeURIComponent(taskId)}/approvals/${encodeURIComponent(approvalId)}`; - const res = await fetch(url, { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ decision }), - }); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - }, - // Optional push: reload when your backend signals a change. Without it the hook polls every 3 s. - subscribe: (taskId, onChange) => { - const source = new EventSource(`/api/events?taskId=${encodeURIComponent(taskId)}`); - source.onmessage = onChange; - return () => source.close(); - }, - }); - - return ( - } // optional live device next to the details - /> - ); -} -``` - -`` renders an inline card (wrap it in your own dialog if you want one) and nothing when `approval` is `null`. When you pass `device`, the card shows it next to the details from `md` up; below `md` a Details/Device switch toggles between the two while the device stays mounted, so a live stream never reconnects. The device slot has a fixed height and clips overflow, so the device element should fill it (`height: 100%`). For an unknown `kind` or unexpected `details` it shows a generic "Waiting for approval" body with the same buttons. - -### Show it as a bottom sheet - -The host owns the sheet or dialog; the library ships only the card. Render `` inside your own wrapper while `approval` is non-null. The CSS below turns the wrapper into a sheet below `md` (767px) and leaves it unstyled above: - -```tsx -{approval && ( -
-
- -
-
-)} -``` - -```css -@media (max-width: 767px) { - .sheet-backdrop { position: fixed; inset: 0; z-index: 50; display: flex; align-items: flex-end; background: rgba(0,0,0,.45); } - .sheet { width: 100%; max-height: 92vh; overflow-y: auto; border-radius: 24px 24px 0 0; background: var(--background); animation: sheet-up .35s cubic-bezier(.2,.7,.2,1); } - @keyframes sheet-up { from { transform: translateY(100%); } } - @media (prefers-reduced-motion: reduce) { .sheet { animation: none; } } +export function DevicePanel({ deviceId, streamUrl }: { deviceId: string; streamUrl: string }) { + const tokenProvider = async () => { + const res = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { method: 'POST', cache: 'no-store' }); + if (!res.ok) throw new Error('Stream key request failed'); + return (await res.json()).key; + }; + return
; } ``` -As a modal, the host moves focus into the sheet and makes the page behind it inert, or uses its own dialog component. - -For dark mode put `.dark` on any ancestor, or override the CSS variables (`--background`, `--card`, `--destructive`, …). - -### Labels and i18n +Never log or cache stream keys. Your backend must authenticate callers and authorize the device. +The [full example](docs/stream-keys.md) also shows `useDeviceStream` and legacy compatibility. -Every user-visible string can be replaced through the `labels` prop; see `TaskApprovalLabels` for all keys. `{time}` in `timeLeft` is replaced with the remaining time. +## Guides -```tsx - -``` - -## πŸ§ͺ Try it locally - -The repo ships the playground shown above. Set the API key server-side and enter a device id; -manual URL/token mode remains available for legacy diagnostics: - -```sh -bun install -bun run example # serves the playground at http://localhost:3000 -``` - -In SDK mode the example server returns only `id`, `state`, and `streamUrl` from -`GET /api/v1/devices/:id`. Its `POST /api/v1/devices/:id/stream-key` helper calls the public mint -API through `sdk.api.post('/identity/stream-keys', ...)`, returning only `{ key, keyId, expiresAt }` -with `Cache-Control: no-store`. The browser's provider calls it for each connection attempt; the -API key stays server-side. The stream WebSocket connects directly with the fresh key in `?token=`. -The same server also demonstrates [task approvals](#-task-approvals) (set `MOBILERUN_WEBHOOK_SECRET` -for the webhook route). All example helpers are unauthenticated and **local-only**, bound to -`127.0.0.1`. Before adapting them for production, add application authentication and device -authorization. If you need webhook delivery, expose only `/webhooks/mobilerun`, never the whole server. -The helper routes only answer loopback Host headers and same-origin requests. - -## 🎨 Styling & theming - -Import the prebuilt stylesheet once, anywhere: - -```ts -import '@mobilerun/react/styles.css'; -``` - -It bundles the design tokens, only the Tailwind utilities the components use, the animations, and the structural CSS. It does **not** include Tailwind's preflight/reset, so it won't touch your base styles β€” and you don't need Tailwind installed. - -Retheme by overriding the CSS variables on an ancestor (e.g. `--background`, `--card`, `--muted-foreground`, `--border`, `--primary`), or add a `.dark` ancestor for the bundled dark palette: - -```css -:root { - --primary: oklch(0.55 0.18 268); - --background: oklch(0.985 0.004 85); -} -``` - -## πŸ›  Building locally - -```sh -bun install -bun run build # tsup (JS + d.ts) + Tailwind (styles.css) β†’ dist/ -bun run typecheck -bun test -``` +| Guide | Covers | +| --- | --- | +| [Stream keys](docs/stream-keys.md) | Server routes, device metadata, `tokenProvider`, retries and legacy tokens. | +| [Components and styling](docs/default-ui.md) | Components, prebuilt CSS, theme variables and dark mode. | +| [Task approvals](docs/task-approvals.md) | Webhooks, backend decisions, cards, bottom sheets and labels. | -## 🧬 Conformance +## Contributing -The control messages, signalling frames, reconnect policy and input routing are replayed against the shared [conformance fixtures](https://github.com/droidrun/mobilerun-sdk-conformance) that the native SDKs also pass. The vendored copy lives in `conformance/fixtures` (release tag in `conformance/VERSION`) and runs with `bun test`. To move to another release, run `scripts/sync-conformance.sh TAG`. +See [CONTRIBUTING.md](CONTRIBUTING.md) for builds, tests, conformance fixtures and the example app. +Report vulnerabilities privately as described in [SECURITY.md](SECURITY.md). -## πŸ“„ License +## License -[Apache-2.0](./LICENSE) +[Apache-2.0](LICENSE) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..eee586d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,5 @@ +# Security + +Report vulnerabilities privately through this repository’s GitHub **Security** tab β†’ **Report a vulnerability**. Do not open public issues for security problems. + +This policy covers the SDK and its example helper; the Mobilerun API itself is out of scope here, but reports about it go through the same private channel. diff --git a/docs/default-ui.md b/docs/default-ui.md new file mode 100644 index 0000000..d789897 --- /dev/null +++ b/docs/default-ui.md @@ -0,0 +1,32 @@ +← [README](../README.md) Β· [Partner guide](https://docs.mobilerun.ai/partners) + +# Components and styling + +Drop a live, controllable cloud device (iOS/ Android) into any React app: + +- **``** β€” WebRTC video with touch, swipe and keyboard control, plus automatic reconnects with exponential backoff and a retry UI once attempts are exhausted. +- **`useDeviceStream()`** β€” resolves a device's stream URL and state from + [`@mobilerun/sdk`](https://www.npmjs.com/package/@mobilerun/sdk), polling while it boots. +- **``** + **`useTaskApproval()`** β€” show a task's pending human approval (e.g. "enter payment card X into app Y") with a countdown and Approve/Deny buttons. See [Task approvals](task-approvals.md). +- **``**, **``**, **``** β€” the surrounding chrome and a lower-level escape hatch. +- **Prebuilt stylesheet** β€” no Tailwind setup required, themeable via CSS variables. +- **Typed** β€” ships its own `.d.ts`; React and the SDK are peer dependencies. + +## Styling and theming + +Import the prebuilt stylesheet once, anywhere: + +```ts +import '@mobilerun/react/styles.css'; +``` + +It bundles the design tokens, only the Tailwind utilities the components use, the animations, and the structural CSS. It does **not** include Tailwind's preflight/reset, so it won't touch your base styles β€” and you don't need Tailwind installed. + +Retheme by overriding the CSS variables on an ancestor (e.g. `--background`, `--card`, `--muted-foreground`, `--border`, `--primary`), or add a `.dark` ancestor for the bundled dark palette: + +```css +:root { + --primary: oklch(0.55 0.18 268); + --background: oklch(0.985 0.004 85); +} +``` diff --git a/docs/stream-keys.md b/docs/stream-keys.md new file mode 100644 index 0000000..521359f --- /dev/null +++ b/docs/stream-keys.md @@ -0,0 +1,129 @@ +← [README](../README.md) Β· [Partner guide](https://docs.mobilerun.ai/partners) + +# Stream keys + +The object API helpers (`MobilerunSDK`, `devices.fromId`, `verifyWebhook`) require `@mobilerun/sdk` 6.2 or later. The `{ client, deviceId }` hook form works with older SDKs; the peer dependency range remains `>=2.0.0`. + +Keep the API key on your backend. Use `useDeviceStream` for the URL and device state, and supply a +`tokenProvider` that calls your backend for a fresh single-use stream key before every WebSocket +attempt, including retries. + +> **`MOBILERUN_API_KEY` is a secret API key β€” never ship it to the browser.** Only the server reads it. +> The device endpoint returns only `id`, `state`, and `streamUrl`, with missing values set to `null`. +> A separate POST endpoint returns a short-lived stream key scoped to that device; the browser SDK +> uses a placeholder key to call your backend. + +On your backend, register this handler for `GET /api/v1/devices/:id`, passing the routed device ID: + +```ts +import { MobilerunSDK } from '@mobilerun/sdk'; + +const sdk = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY, server only + +export async function getDevice(id: string): Promise { + // Authenticate the caller and check the device belongs to them before returning device metadata. + const device = await sdk.devices.get(id); + return Response.json({ + id: device.info?.id ?? null, + state: device.info?.state ?? null, + streamUrl: device.info?.streamUrl ?? null, + }); +} + +// Register for POST /api/v1/devices/:id/stream-key. +export async function mintStreamKey(deviceId: string): Promise { + // Authenticate the caller and authorize this device in your application first. + try { + const minted = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( + '/identity/stream-keys', + { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, + ); + const { key, keyId, expiresAt } = minted; + return Response.json({ key, keyId, expiresAt }, { + status: 201, + headers: { 'Cache-Control': 'no-store' }, + }); + } catch (err) { + const { status } = err as { status?: number }; + const isUpstreamError = typeof status === 'number' && status >= 400 && status < 600; + return Response.json({ error: 'stream_key_mint_failed' }, { + status: isUpstreamError ? status : 502, + headers: { 'Cache-Control': 'no-store' }, + }); + } +} +``` + +The public mint API is `POST /v1/identity/stream-keys`, authenticated with your server-held API key. +Its body is `{ deviceId, ttlSeconds? }`; TTL is 60–300 seconds, default 120. It returns HTTP 201 +with `{ key, keyId, expiresAt }` and `Cache-Control: no-store`. The SDK base URL already ends in +`/v1`, so use `/identity/stream-keys` with `sdk.api.post`. Revoke with +`DELETE /v1/identity/stream-keys/{keyId}`. Each key is single-use and device-scoped. `expiresAt` +is diagnostic metadata, not a browser permission or validity check. Do not log or cache keys. +Your backend must authenticate callers and authorize the requested device; never accept an arbitrary +target URL or owner from the browser. Propagate mint refusal without returning upstream credential details. + +In your client component, point the SDK at that backend route, as in the example app: + +```tsx +'use client'; + +import { useCallback, useMemo } from 'react'; +import { MobilerunSDK } from '@mobilerun/sdk'; +import { DeviceStream, useDeviceStream } from '@mobilerun/react'; +import '@mobilerun/react/styles.css'; + +export function DevicePanel({ deviceId }: { deviceId: string }) { + const sdk = useMemo(() => new MobilerunSDK({ + apiKey: 'example-sdk-helper', // placeholder, not a Mobilerun API key + baseURL: typeof window === 'undefined' ? '/api/v1' : `${window.location.origin}/api/v1`, // SSR placeholder; the hook only fetches in the browser + }), []); + const { streamUrl, state, refetch } = useDeviceStream({ + device: sdk.devices.fromId(deviceId), // no request yet + }); + const getFreshStreamKey = useCallback(async () => { + const response = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { + method: 'POST', + cache: 'no-store', + }); + if (!response.ok) throw new Error('Stream key request failed'); + const { key } = await response.json(); + return key; + }, [deviceId]); + + return ( +
+ +
+ ); +} +``` + +### Without the hook + +Supply an existing stream URL and the same server-backed callback: + +```tsx + +``` + +`tokenProvider?: () => Promise` is supported by `DeviceStream` and `RemoteControl`. +It is awaited once immediately before each socket allocation. It takes precedence over static +`streamToken`/`token`; a rejection or empty key fails that attempt with no fallback. Pending results +after stop, device switch or unmount are ignored. Changing callback identity does not reconnect a +healthy stream. An ICE credential refresh on an existing socket does not call it again. +A server signaling close with code 1001 ends media/control in every mode and triggers the existing +bounded reconnect policy. Other signaling closes keep a connected media path running. Provider mode +mints a fresh key for each new socket. `onStreamHealed` can refresh URL/state; it is not per retry +and must not be used to cache a key. + +Static `DeviceStream.streamToken`, `RemoteControl.token`, and the hook's returned `streamToken` are +**deprecated**, retained for existing consumers. Manual URL/token mode is a legacy diagnostic path; +a pasted single-use key cannot reconnect after admission. `useDeviceStream` also still accepts +`{ client, deviceId }` with a plain `Mobilerun` client. diff --git a/docs/task-approvals.md b/docs/task-approvals.md new file mode 100644 index 0000000..5043e62 --- /dev/null +++ b/docs/task-approvals.md @@ -0,0 +1,170 @@ +← [README](../README.md) Β· [Partner guide](https://docs.mobilerun.ai/partners) + +# Task approvals + +A task can pause and wait for a human to approve a step, for example entering a payment card into an app. `useTaskApproval()` loads the pending approval and `` renders it with a countdown and Approve/Deny buttons. + +**The decision goes through your backend.** The API key that may approve is a secret and must never reach the browser, so the browser only talks to your own routes. The Mobilerun API owns the approval state and decides: the component renders what it is given and forwards the decision, and the countdown is display only. A 404/409 from the decide call (unknown, already resolved or expired) comes back as an error and triggers a refetch. + +### 1. Subscribe a webhook + +In your Mobilerun webhook settings, point an endpoint at your backend and filter it to the two approval events: `task.run.approval_requested` and `task.run.approval_resolved`. Events only tell the browser to reload; the fetched approval is the source of truth. + +Each delivery carries `X-Mobilerun-Timestamp` (Unix ms) and `X-Mobilerun-Signature: sha256=`, an HMAC-SHA256 of `"{timestamp}.{rawBody}"` with the endpoint secret. `verifyWebhook` from `@mobilerun/sdk` checks the signature and the 5-minute timestamp window and returns the parsed payload; pass it the body bytes exactly as received. SDK 6.2.1 or later distinguishes `invalid_json` (a signed but unparsable body), which the handler answers with HTTP 400. + +### 2. Backend sketch + +```ts +import { MobilerunSDK, verifyWebhook, WebhookVerificationError } from '@mobilerun/sdk'; + +const sdk = new MobilerunSDK(); // reads MOBILERUN_API_KEY +const APPROVAL_EVENTS = new Set(['task.run.approval_requested', 'task.run.approval_resolved']); +const ID = /^[A-Za-z0-9_-]+$/; + +// Device metadata: return only the fields needed for streaming. +app.get('/api/v1/devices/:id', async (c) => { + const id = c.req.param('id'); + // Authenticate the caller and check the device belongs to them before returning device metadata. + const device = await sdk.devices.get(id); + return c.json({ + id: device.info?.id ?? null, + state: device.info?.state ?? null, + streamUrl: device.info?.streamUrl ?? null, + }); +}); + +// 1. Webhook: verify the raw bytes, then push a change signal to the user's browser (SSE, ...) +app.post('/webhooks/mobilerun', async (c) => { + const secret = process.env.MOBILERUN_WEBHOOK_SECRET; + if (!secret) return c.json({ error: 'missing_webhook_secret' }, 500); + const bytes = new Uint8Array(await c.req.arrayBuffer()); + let event; + try { + event = await verifyWebhook({ + body: bytes, + headers: c.req.raw.headers, + secret, + }) as { type?: string; data?: { taskId?: string } } | null; + } catch (err) { + if (err instanceof WebhookVerificationError) { + if (err.reason === 'invalid_json') return c.json({ error: 'invalid_json' }, 400); + return c.json({ error: 'invalid_signature' }, 401); + } + throw err; + } + const taskId = event?.data?.taskId; + if (taskId && APPROVAL_EVENTS.has(event?.type ?? '')) push({ taskId }); + return c.body(null, 204); +}); + +// 2. Pending approval: GET /tasks/{id} β†’ task.pendingApproval (null when none) +app.get('/api/tasks/:id', async (c) => { + const id = c.req.param('id'); + if (!ID.test(id)) return c.json({ error: 'invalid_id' }, 400); + // Authenticate the caller and check the task belongs to their user/org first. + const { task } = await sdk.api.get<{ task?: { pendingApproval?: unknown } }>(`/tasks/${encodeURIComponent(id)}`); + return c.json({ pendingApproval: task?.pendingApproval ?? null }); +}); + +// 3. Decision: POST /tasks/{id}/approvals/{approvalId} { decision: 'approve' | 'deny' } +app.post('/api/tasks/:id/approvals/:approvalId', async (c) => { + const id = c.req.param('id'); + const approvalId = c.req.param('approvalId'); + if (!ID.test(id) || !ID.test(approvalId)) return c.json({ error: 'invalid_id' }, 400); + const { decision } = await c.req.json(); + if (decision !== 'approve' && decision !== 'deny') return c.json({ error: 'invalid_decision' }, 422); + // Authenticate the caller and check the task belongs to their user/org first. + const url = `/tasks/${encodeURIComponent(id)}/approvals/${encodeURIComponent(approvalId)}`; + await sdk.api.post(url, { body: { decision } }); + return c.body(null, 204); +}); +``` + +Authenticate every route and check that the task belongs to the signed-in user or organization before forwarding. A delivery can be replayed within the 5-minute window; that is harmless here because events only trigger a refetch. Dedupe on the event `id` if your handler does more. + +`bun run example` runs a working version of all three plus an SSE endpoint. It is for local use only: it binds to `127.0.0.1` and its task and SSE routes are unauthenticated. + +### 3. Client + +```tsx +import { TaskApproval, useTaskApproval, type PendingApproval } from '@mobilerun/react'; +import '@mobilerun/react/styles.css'; + +export function Approval({ taskId }: { taskId: string }) { + const { approval, decide, isDeciding, decision, error } = useTaskApproval({ + taskId, + fetchApproval: async (id) => { + const res = await fetch(`/api/tasks/${encodeURIComponent(id)}`); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return ((await res.json()) as { pendingApproval: PendingApproval | null }).pendingApproval; + }, + decide: async ({ taskId, approvalId, decision }) => { + const url = `/api/tasks/${encodeURIComponent(taskId)}/approvals/${encodeURIComponent(approvalId)}`; + const res = await fetch(url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ decision }), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + }, + // Optional push: reload when your backend signals a change. Without it the hook polls every 3 s. + subscribe: (taskId, onChange) => { + const source = new EventSource(`/api/events?taskId=${encodeURIComponent(taskId)}`); + source.onmessage = onChange; + return () => source.close(); + }, + }); + + return ( + } // optional live device next to the details + /> + ); +} +``` + +`` renders an inline card (wrap it in your own dialog if you want one) and nothing when `approval` is `null`. When you pass `device`, the card shows it next to the details from `md` up; below `md` a Details/Device switch toggles between the two while the device stays mounted, so a live stream never reconnects. The device slot has a fixed height and clips overflow, so the device element should fill it (`height: 100%`). For an unknown `kind` or unexpected `details` it shows a generic "Waiting for approval" body with the same buttons. + +### Show it as a bottom sheet + +The host owns the sheet or dialog; the library ships only the card. Render `` inside your own wrapper while `approval` is non-null. The CSS below turns the wrapper into a sheet below `md` (767px) and leaves it unstyled above: + +```tsx +{approval && ( +
+
+ +
+
+)} +``` + +```css +@media (max-width: 767px) { + .sheet-backdrop { position: fixed; inset: 0; z-index: 50; display: flex; align-items: flex-end; background: rgba(0,0,0,.45); } + .sheet { width: 100%; max-height: 92vh; overflow-y: auto; border-radius: 24px 24px 0 0; background: var(--background); animation: sheet-up .35s cubic-bezier(.2,.7,.2,1); } + @keyframes sheet-up { from { transform: translateY(100%); } } + @media (prefers-reduced-motion: reduce) { .sheet { animation: none; } } +} +``` + +As a modal, the host moves focus into the sheet and makes the page behind it inert, or uses its own dialog component. + +For dark mode put `.dark` on any ancestor, or override the CSS variables (`--background`, `--card`, `--destructive`, …). + +### Labels and i18n + +Every user-visible string can be replaced through the `labels` prop; see `TaskApprovalLabels` for all keys. `{time}` in `timeLeft` is replaced with the remaining time. + +```tsx + +``` From 1f2bcccb954029ca7513dc5c02934518d24800a2 Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Fri, 20 Nov 2026 14:53:47 +0100 Subject: [PATCH 06/22] docs(readme): trim package list --- CONTRIBUTING.md | 2 ++ README.md | 10 ++-------- docs/default-ui.md | 9 +++++++++ 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 64eb940..482893d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,6 +2,8 @@ ## Build and test +For source builds: Bun 1.4.4 and TypeScript 6.0.3 (the CI toolchain). + ```sh bun install bun run build # tsup (JS + d.ts) + Tailwind (styles.css) β†’ dist/ diff --git a/README.md b/README.md index 44d9a84..7b948ef 100644 --- a/README.md +++ b/README.md @@ -41,20 +41,14 @@
  • TaskApproval / useTaskApproval β€” approval cards and decisions.
  • NavigationBar / StreamStatusPill β€” stream controls and status.
  • RemoteControl β€” lower-level stream and input control.
  • -
  • Button / cn β€” shared button and class-name utilities.
  • -
  • useWebRtcConnection β€” lower-level WebRTC connection state.
  • -
  • useStreamReconnect β€” bounded retries and reconnect state.
  • -
  • useDeviceGridSelfHeal β€” coordinate stream recovery in a device grid.
  • -
  • useScrcpyInput β€” send touch and keyboard input.
  • -
  • scrcpy protocol helpers and constants β€” encode remote-control messages.
  • -
  • Typed exports and a prebuilt stylesheet, themeable with CSS variables.
  • +
  • Prebuilt stylesheet β€” themeable with CSS variables.
  • +

    Lower-level hooks and scrcpy helpers: see docs/.

    Requirements
    • React and React DOM 18 or 19, in a browser with WebRTC.
    • @mobilerun/sdk >=2.0.0; object helpers need 6.2+, webhook example 6.2.1+.
    • A Mobilerun API key on your server.
    • -
    • For source builds: Bun 1.4.4 and TypeScript 6.0.3 (the CI toolchain).
    diff --git a/docs/default-ui.md b/docs/default-ui.md index d789897..dfe4c7e 100644 --- a/docs/default-ui.md +++ b/docs/default-ui.md @@ -12,6 +12,15 @@ Drop a live, controllable cloud device (iOS/ Android) into any React app: - **Prebuilt stylesheet** β€” no Tailwind setup required, themeable via CSS variables. - **Typed** β€” ships its own `.d.ts`; React and the SDK are peer dependencies. +## Lower-level exports + +- `Button` / `cn` β€” shared button and class-name utilities. +- `useWebRtcConnection` β€” lower-level WebRTC connection state. +- `useStreamReconnect` β€” bounded retries and reconnect state. +- `useDeviceGridSelfHeal` β€” coordinate stream recovery in a device grid. +- `useScrcpyInput` β€” send touch and keyboard input. +- scrcpy protocol helpers and constants β€” encode remote-control messages. + ## Styling and theming Import the prebuilt stylesheet once, anywhere: From 5451e324d96a7c20690e48a7738d222897c3e72e Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Sat, 21 Nov 2026 16:20:13 +0100 Subject: [PATCH 07/22] feat(stream): error reasons, labels, scoped css Co-Authored-By: Claude Sonnet 5.5 --- src/components/device-stream.test.tsx | 52 ++++++++++ src/components/device-stream.tsx | 51 ++++++---- src/components/navigation-bar.tsx | 2 +- src/components/remote-control.tsx | 9 +- src/components/stream-unavailable.tsx | 26 +++++ src/components/task-approval.tsx | 2 +- src/hooks/use-static-token-warning.test.ts | 35 +++++++ src/hooks/use-static-token-warning.ts | 18 ++++ src/hooks/use-stream-reconnect.ts | 12 ++- src/hooks/use-webrtc-connection.test.ts | 105 +++++++++++++++++++++ src/hooks/use-webrtc-connection.ts | 38 ++++++-- src/hooks/webrtc-test-fixture.ts | 8 +- src/index.ts | 3 +- src/lib/stream-error.ts | 64 +++++++++++++ src/lib/stream-reconnect.test.ts | 76 +++++++++++++++ src/lib/stream-reconnect.ts | 29 ++++-- src/styles.css | 87 ++++++++--------- 17 files changed, 532 insertions(+), 85 deletions(-) create mode 100644 src/components/device-stream.test.tsx create mode 100644 src/components/stream-unavailable.tsx create mode 100644 src/hooks/use-static-token-warning.test.ts create mode 100644 src/hooks/use-static-token-warning.ts create mode 100644 src/lib/stream-error.ts diff --git a/src/components/device-stream.test.tsx b/src/components/device-stream.test.tsx new file mode 100644 index 0000000..3cd8a5a --- /dev/null +++ b/src/components/device-stream.test.tsx @@ -0,0 +1,52 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, test } from 'bun:test'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { resolveDeviceStreamLabels } from '../lib/stream-error'; +import { DeviceStream } from './device-stream'; +import { StreamUnavailable } from './stream-unavailable'; + +const custom = { unavailable: 'Telefon nicht erreichbar', retry: 'Nochmal', connecting: 'Verbinde', disconnected: 'Getrennt' }; + +describe('labels', () => { + test('defaults stay English and an undefined override falls back', () => { + expect(resolveDeviceStreamLabels()).toEqual({ + connecting: 'connecting', + disconnected: 'reconnecting', + unavailable: 'device stream unavailable', + retry: 'Retry', + }); + expect(resolveDeviceStreamLabels({ retry: undefined, unavailable: 'x' })).toMatchObject({ retry: 'Retry', unavailable: 'x' }); + }); + + test('the idle and the connecting pill come from labels', () => { + const idle = renderToStaticMarkup(); + expect(idle).toContain('Verbinde'); + expect(idle).not.toContain('>connecting<'); + const connecting = renderToStaticMarkup( 'k'} labels={custom} />); + expect(connecting).toContain('Verbinde'); + expect(connecting).not.toContain('>connecting<'); + }); + + test('an explicit placeholderLabel still wins over labels.connecting', () => { + expect(renderToStaticMarkup()).toContain('booting'); + }); + + test('the unavailable view renders both strings from labels with no English left', () => { + const html = renderToStaticMarkup( {}} />); + expect(html).toContain('Telefon nicht erreichbar'); + expect(html).toContain('Nochmal'); + expect(html).not.toContain('Retry'); + expect(html).not.toContain('unavailable'); + }); + + test('the Retry button sets a foreground color of its own', () => { + const html = renderToStaticMarkup( {}} />); + expect(html).toMatch(/]*class="[^"]*\btext-foreground\b/); + }); +}); + +test('the component root carries the class the scoped CSS variables hang on', () => { + expect(renderToStaticMarkup()).toContain('mobilerun-device-stream'); +}); diff --git a/src/components/device-stream.tsx b/src/components/device-stream.tsx index f708694..89311d7 100644 --- a/src/components/device-stream.tsx +++ b/src/components/device-stream.tsx @@ -2,21 +2,38 @@ // Copyright 2026 Mobilerun // SPDX-License-Identifier: Apache-2.0 -import { RotateCw, Smartphone, WifiOff } from 'lucide-react'; +import { Smartphone } from 'lucide-react'; import { forwardRef, useCallback, useEffect, useMemo } from 'react'; import { cn } from '../lib/cn'; +import { resolveDeviceStreamLabels, type DeviceStreamLabels, type StreamError } from '../lib/stream-error'; import { STREAM_RECONNECT_MAX_ATTEMPTS } from '../lib/stream-reconnect'; import { RemoteControl, type RemoteControlHandle } from './remote-control'; import { StreamStatusPill } from './stream-status-pill'; -import { Button } from './ui/button'; +import { StreamUnavailable } from './stream-unavailable'; +import { useStaticTokenWarning } from '../hooks/use-static-token-warning'; import { useStreamReconnect } from '../hooks/use-stream-reconnect'; -interface DeviceStreamProps { +export interface DeviceStreamProps { streamUrl?: string; - /** @deprecated Use tokenProvider to acquire a fresh key for each connection attempt. */ + /** + * @deprecated A static key is single-use, so it cannot reconnect. Use `tokenProvider`, + * which returns a fresh key for every connection attempt. Logs one console warning per mount. + */ streamToken?: string; - /** Resolves a fresh stream key immediately before each WebSocket attempt. Overrides streamToken. */ + /** + * Called before every WebSocket attempt, the first connect and each reconnect, and returns + * a fresh stream key minted by your backend (`POST /v1/identity/stream-keys`). A key is never + * reused for a second connect. A throw, a rejection, an empty key or no answer within 10 s + * fails the attempt with reason `credentials_unavailable`. Wins over `streamToken`. + */ tokenProvider?: () => Promise; + /** + * Called once per failed connection attempt with the reason, the attempt number and whether + * the SDK stopped retrying (`final`). The Retry button stays available after a final error. + */ + onError?: (error: StreamError) => void; + /** Replaces the built-in English texts. Every key is optional. */ + labels?: Partial; hasControl: boolean; onHasControlChange?: (hasControl: boolean) => void; onConnectionStateChange?: (connected: boolean) => void; @@ -53,6 +70,8 @@ export const DeviceStream = forwardRef(f streamUrl, streamToken, tokenProvider, + onError, + labels: labelOverrides, hasControl, onHasControlChange: setHasControl = () => {}, onConnectionStateChange, @@ -80,6 +99,7 @@ export const DeviceStream = forwardRef(f retry, } = useStreamReconnect({ onHeal: onStreamHealed, + onError, target, targetKey: `${streamUrl ?? ''}|${streamToken ?? ''}`, enabled: !!streamUrl, @@ -101,30 +121,27 @@ export const DeviceStream = forwardRef(f } }, [streamUrl, setHasControl]); + const labels = resolveDeviceStreamLabels(labelOverrides); + + useStaticTokenWarning(!!streamToken && !tokenProvider); + const reconnectLabel = - attempt > 1 ? `reconnecting (${attempt}/${STREAM_RECONNECT_MAX_ATTEMPTS})` : 'reconnecting'; + attempt > 1 ? `${labels.disconnected} (${attempt}/${STREAM_RECONNECT_MAX_ATTEMPTS})` : labels.disconnected; return (
    {!streamUrl ? ( <> - + ) : status === 'unavailable' ? ( -
    - - device stream unavailable - -
    + ) : ( <>
    @@ -138,7 +155,7 @@ export const DeviceStream = forwardRef(f onConnectionStateChange={handleConnectionStateChange} onConnectionFailed={onConnectionFailed} onConnectionAttemptStarted={onConnectionAttemptStarted} - placeholderLabel={status === 'reconnecting' ? reconnectLabel : placeholderLabel} + placeholderLabel={status === 'reconnecting' ? reconnectLabel : (placeholderLabel ?? labels.connecting)} muted={muted} onPeerConnectionChange={onPeerConnectionChange} /> diff --git a/src/components/navigation-bar.tsx b/src/components/navigation-bar.tsx index 2a3f184..e26ef6c 100644 --- a/src/components/navigation-bar.tsx +++ b/src/components/navigation-bar.tsx @@ -14,7 +14,7 @@ interface NavigationBarProps { export function NavigationBar({ onAction, className }: NavigationBarProps) { return ( -
    +
    ); }, diff --git a/src/components/stream-unavailable.tsx b/src/components/stream-unavailable.tsx new file mode 100644 index 0000000..7c883fa --- /dev/null +++ b/src/components/stream-unavailable.tsx @@ -0,0 +1,26 @@ +'use client'; +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { RotateCw, WifiOff } from 'lucide-react'; +import type { DeviceStreamLabels } from '../lib/stream-error'; +import { Button } from './ui/button'; + +interface StreamUnavailableProps { + labels: Pick; + onRetry: () => void; +} + +/** Shown once the reconnect budget is spent. The button text sets its own color so it stays readable on dark hosts. */ +export function StreamUnavailable({ labels, onRetry }: StreamUnavailableProps) { + return ( +
    + + {labels.unavailable} + +
    + ); +} diff --git a/src/components/task-approval.tsx b/src/components/task-approval.tsx index 4cd7b55..6ddd79c 100644 --- a/src/components/task-approval.tsx +++ b/src/components/task-approval.tsx @@ -154,7 +154,7 @@ function ApprovalCard({ return (

    {title}

    diff --git a/src/hooks/use-static-token-warning.test.ts b/src/hooks/use-static-token-warning.test.ts new file mode 100644 index 0000000..c736210 --- /dev/null +++ b/src/hooks/use-static-token-warning.test.ts @@ -0,0 +1,35 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { expect, test } from 'bun:test'; +import { runHook } from './test-hook-runner'; + +async function harness() { + const warnings: string[] = []; + const runner = await runHook<{ useStaticTokenWarning: (using: boolean) => void }>( + import.meta.dir + '/use-static-token-warning.ts', + { console: { warn: (message: string) => warnings.push(message) } }, + ); + const render = (using: boolean) => { + runner.beginRender(); + runner.module.exports.useStaticTokenWarning(using); + runner.flushEffects(); + }; + return { warnings, render }; +} + +test('a static key warns once per mount, however often it re-renders', async () => { + const { warnings, render } = await harness(); + render(true); + render(true); + render(true); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('tokenProvider'); +}); + +test('no warning while a provider is in use', async () => { + const { warnings, render } = await harness(); + render(false); + render(false); + expect(warnings).toEqual([]); +}); diff --git a/src/hooks/use-static-token-warning.ts b/src/hooks/use-static-token-warning.ts new file mode 100644 index 0000000..22d959d --- /dev/null +++ b/src/hooks/use-static-token-warning.ts @@ -0,0 +1,18 @@ +'use client'; +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { useEffect, useRef } from 'react'; + +/** One console warning per mount while a deprecated static stream key is in use. */ +export function useStaticTokenWarning(usingStaticToken: boolean) { + const warnedRef = useRef(false); + useEffect(() => { + if (!usingStaticToken || warnedRef.current) return; + warnedRef.current = true; + // eslint-disable-next-line no-console -- one-time deprecation notice + console.warn( + '[@mobilerun/react] DeviceStream `streamToken` is deprecated: a stream key is single-use and cannot reconnect. Pass `tokenProvider` to get a fresh key for every connection.', + ); + }, [usingStaticToken]); +} diff --git a/src/hooks/use-stream-reconnect.ts b/src/hooks/use-stream-reconnect.ts index 9d070ca..9eac19d 100644 --- a/src/hooks/use-stream-reconnect.ts +++ b/src/hooks/use-stream-reconnect.ts @@ -3,6 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; +import type { StreamError, StreamFailure } from '../lib/stream-error'; import { createStreamReconnectController, type StreamReconnectSnapshot } from '../lib/stream-reconnect'; interface UseStreamReconnectOptions { @@ -13,6 +14,8 @@ interface UseStreamReconnectOptions { * network, and grids share one fleet-wide refetch across every card. */ onHeal?: () => void; + /** Fired once per counted failed attempt, with `final: true` when retries stop. */ + onError?: (error: StreamError) => void; /** * The connection target (URL/credentials) the consumer currently wants. * The hook pins the target the stream actually uses: `activeTarget` only @@ -46,6 +49,7 @@ interface UseStreamReconnectOptions { */ export function useStreamReconnect({ onHeal, + onError, target, targetKey, enabled, @@ -65,6 +69,8 @@ export function useStreamReconnect({ const onHealRef = useRef(onHeal); onHealRef.current = onHeal; + const onErrorRef = useRef(onError); + onErrorRef.current = onError; // Latest committed target (and its key), for timer-driven remounts // (backoff fire, wake, retry). Written in an effect so a render React @@ -91,6 +97,7 @@ export function useStreamReconnect({ onRemount: bumpMount, onSnapshot: (s) => setSnapshot(s), onHeal: () => onHealRef.current?.(), + onError: (error) => onErrorRef.current?.(error), }); } @@ -147,7 +154,10 @@ export function useStreamReconnect({ else controllerRef.current?.handleDisconnected(); }, []); - const onConnectionFailed = useCallback(() => controllerRef.current?.handleFailure(), []); + const onConnectionFailed = useCallback( + (failure?: StreamFailure) => controllerRef.current?.handleFailure(failure), + [], + ); const retry = useCallback(() => controllerRef.current?.retry(), []); diff --git a/src/hooks/use-webrtc-connection.test.ts b/src/hooks/use-webrtc-connection.test.ts index 13ca775..7b6d1bd 100644 --- a/src/hooks/use-webrtc-connection.test.ts +++ b/src/hooks/use-webrtc-connection.test.ts @@ -559,3 +559,108 @@ test('legacy token compatibility keeps synchronous startup and media after signa expect(f.failures).toEqual([]); f.unmount(); }); + +// Failure reasons (stream client contract v1). The reason list lives in lib/stream-error.ts. +const reasons = (f: { failureInfos: { reason: string }[] }) => f.failureInfos.map(i => i.reason); + +test.each([ + ['reject', (): Promise => Promise.reject(new Error('refused'))], + ['empty', async (): Promise => ''], +] as const)('provider %s reports credentials_unavailable', async (_name, tokenProvider) => { + const f = await fixture(); + f.mount('a', undefined, { tokenProvider }); + await tick(); + expect(reasons(f)).toEqual(['credentials_unavailable']); + f.unmount(); +}); + +test('provider timeout reports credentials_unavailable', async () => { + const clock = new FakeSchedule(); + const f = await fixture(clock); + f.mount('a', undefined, { tokenProvider: () => deferred().promise }); + clock.advance(10_000); + await tick(); + expect(reasons(f)).toEqual(['credentials_unavailable']); + expect(f.failureInfos[0].message).toContain('timeout'); + f.unmount(); +}); + +test('a socket that closes before open reports connection_refused, with or without a provider', async () => { + for (const credentials of [{ tokenProvider: async () => 'key' }, { token: 'legacy' }]) { + const f = await fixture(); + f.mount('a', undefined, credentials); + await tick(); + f.sockets[0].close(1006); + await tick(); + expect(reasons(f)).toEqual(['connection_refused']); + f.unmount(); + } +}); + +test('a socket that never opens is unknown, not a refusal', async () => { + const clock = new FakeSchedule(); + const f = await fixture(clock); + f.mount('a', undefined, { token: 'legacy' }); + await tick(); + clock.advance(15_000); + await tick(); + expect(reasons(f)).toEqual(['unknown']); + f.unmount(); +}); + +test.each([ + ['server session end (1001)', 1001], + ['abnormal close', 1006], +] as const)('an open socket dropped by %s reports disconnected', async (_name, code) => { + const f = await fixture(); + f.mount('a', undefined, { tokenProvider: async () => 'key' }); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].close(code); + await tick(); + expect(reasons(f)).toEqual(['disconnected']); + expect(f.failureInfos[0].message).toContain(String(code)); + f.unmount(); +}); + +test('peer failure is disconnected after it connected and unknown before', async () => { + for (const [connectFirst, expected] of [[true, 'disconnected'], [false, 'unknown']] as const) { + const f = await fixture(); + f.mount('a', undefined, { tokenProvider: async () => 'key' }); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + const pc = f.peers[0]; + if (connectFirst) { + pc.connectionState = 'connected'; + pc.onconnectionstatechange!(); + } + pc.connectionState = 'failed'; + pc.onconnectionstatechange!(); + await tick(); + expect(reasons(f)).toEqual([expected]); + f.unmount(); + } +}); + +test('every connect attempt calls the provider again and never reuses a key', async () => { + const f = await fixture(); + let minted = 0; + const tokenProvider = async () => `key-${++minted}`; + for (let attempt = 1; attempt <= 3; attempt++) { + f.mount('a', undefined, { tokenProvider }); + await tick(); + f.sockets[attempt - 1].close(1006); + await tick(); + } + expect(f.sockets.map(s => s.url)).toEqual([ + 'wss://example.invalid/a?token=key-1', + 'wss://example.invalid/a?token=key-2', + 'wss://example.invalid/a?token=key-3', + ]); + expect(minted).toBe(3); + f.unmount(); +}); diff --git a/src/hooks/use-webrtc-connection.ts b/src/hooks/use-webrtc-connection.ts index 6571d3e..212993f 100644 --- a/src/hooks/use-webrtc-connection.ts +++ b/src/hooks/use-webrtc-connection.ts @@ -10,6 +10,7 @@ import { STREAM_RTC_CONFIG_TIMEOUT_MS, STREAM_WS_OPEN_TIMEOUT_MS, } from '../lib/stream-reconnect'; +import type { StreamErrorReason, StreamFailure } from '../lib/stream-error'; import { createRTCConfigurationRequest } from '../webrtc-messages'; const debugLog = (...args: any[]) => { @@ -58,7 +59,8 @@ interface UseWebRtcConnectionOptions { // connection reaches 'failed'/'closed'. Never fired on intentional teardown // (stop/unmount). Distinct from onConnectionStateChange(false), which also // fires for transient non-connected states during normal negotiation. - onConnectionFailed?: () => void; + // Carries the reason of the failure (stream client contract v1). + onConnectionFailed?: (failure: StreamFailure) => void; onConnectionAttemptStarted?: () => void; // Fired with the RTCPeerConnection once it is created and with null when // it is torn down. Lets consumers observe the connection (e.g. getStats()) @@ -214,7 +216,10 @@ export function useWebRtcConnection({ const provider = tokenProviderRef.current; const isActive = () => attemptGenerationRef.current === generation; let failed = false; - const failAttempt = (stopMedia = !!provider) => { + // Whether this attempt's peer connection ever reached 'connected': a later + // failure is a drop of an open session, an earlier one a failed connect. + let everConnected = false; + const failAttempt = (failure: StreamFailure, stopMedia = !!provider) => { if (!isActive()) return; if (failed) return; failed = true; @@ -222,7 +227,7 @@ export function useWebRtcConnection({ onConnectionStateChangeRef.current?.(false); stop(); } - onConnectionFailedRef.current?.(); + onConnectionFailedRef.current?.(failure); }; // Reset ICE buffering state for the new session. // Done here (not in stop()) to avoid a race where stale candidates @@ -238,11 +243,14 @@ export function useWebRtcConnection({ // nothing about it may be reported anymore. let attemptWs: WebSocket | null = null; let cancelStartup = () => {}; + // Set while a startup step runs so the catch below can name the failing step. + let phase: StreamErrorReason = 'unknown'; try { let streamToken = tokenRef.current; if (provider) { if (!isSecureStreamUrl(url)) throw new Error('Stream key requires a secure WebSocket URL'); let providerTimer: ReturnType | undefined; + phase = 'credentials_unavailable'; try { streamToken = await new Promise((resolve, reject) => { providerTimer = setTimeout( @@ -262,6 +270,7 @@ export function useWebRtcConnection({ } if (!isActive()) return; if (!streamToken?.trim()) throw new Error('Stream key provider returned an empty key'); + phase = 'unknown'; } const wsUrl = buildWebSocketUrl(url, streamToken); const ws = new WebSocket(wsUrl); @@ -295,6 +304,7 @@ export function useWebRtcConnection({ // Wait for WebSocket to connect. Teardown settles this wait and removes // its timer even when the browser never delivers another socket event. + phase = 'connection_refused'; const opened = new Promise((resolve, reject) => { rejectStartup = reject; ws.onopen = () => { @@ -308,21 +318,28 @@ export function useWebRtcConnection({ }; pendingTimer = setTimeout(() => { if (!isCurrent()) return; + // Not a refusal: nothing answered in time. + phase = 'unknown'; reject(new Error('WebSocket connection timeout')); }, STREAM_WS_OPEN_TIMEOUT_MS); }); if (!document.hidden) startKeepAlive(); await opened; if (!isCurrent()) return; + phase = 'unknown'; // A server session end closes media in every credential mode. Other // signaling closes leave a connected media path running, as before. ws.onclose = (event) => { if (!isCurrent()) return; updateStatus('WebSocket closed'); - if (event.code === 1001) return failAttempt(true); + const dropped: StreamFailure = { + reason: 'disconnected', + message: `Signaling connection closed (code ${event.code})`, + }; + if (event.code === 1001) return failAttempt(dropped, true); if (peerConnectionRef.current?.connectionState === 'connected') return; - failAttempt(); + failAttempt(dropped); }; // Request RTCConfiguration @@ -484,9 +501,13 @@ export function useWebRtcConnection({ const state = pc.connectionState; updateStatus('Connection state: ' + state); const connected = state === 'connected'; + if (connected) everConnected = true; if (state === 'failed' || state === 'closed') { // Terminal: this peer connection will not come back on its own. - failAttempt(); + failAttempt({ + reason: everConnected ? 'disconnected' : 'unknown', + message: `Peer connection ${state}`, + }); if (!isCurrent()) return; } if (connected) { @@ -726,7 +747,10 @@ export function useWebRtcConnection({ if (wsRef.current !== attemptWs) return; cancelStartup(); updateStatus(provider ? 'Stream connection attempt failed' : 'Error: ' + e); - failAttempt(); + failAttempt({ + reason: phase, + message: e instanceof Error && e.message ? e.message : 'Stream connection attempt failed', + }); } }; diff --git a/src/hooks/webrtc-test-fixture.ts b/src/hooks/webrtc-test-fixture.ts index 68d9b28..414a63d 100644 --- a/src/hooks/webrtc-test-fixture.ts +++ b/src/hooks/webrtc-test-fixture.ts @@ -88,6 +88,7 @@ export async function fixture(clock?: FakeSchedule) { const stateWrites: boolean[] = []; const states: boolean[] = []; const failures: boolean[] = []; + const failureInfos: { reason: string; message: string }[] = []; const bindings: (FakePeer | null)[] = []; const video = { current: { srcObject: null as MediaStream | null, muted: true } }; const visibilityListeners = new Set<() => void>(); @@ -133,7 +134,10 @@ export async function fixture(clock?: FakeSchedule) { url: 'wss://example.invalid/' + id, sessionId: id, videoRef: video, openUrl, ...credentials, onConnectionStateChange: (state: boolean) => states.push(state), - onConnectionFailed: () => failures.push(true), + onConnectionFailed: (failure: { reason: string; message: string }) => { + failures.push(true); + failureInfos.push(failure); + }, onPeerConnectionChange: (pc: FakePeer | null) => bindings.push(pc), }); runner.flushEffects(); @@ -144,7 +148,7 @@ export async function fixture(clock?: FakeSchedule) { return render(id, openUrl, credentials); }; return { - sockets, peers, timers, scheduled, states, failures, bindings, stateWrites, + sockets, peers, timers, scheduled, states, failures, failureInfos, bindings, stateWrites, video, mount, render, document, visibilityChange() { visibilityListeners.forEach(fn => fn()); }, diff --git a/src/index.ts b/src/index.ts index b86c4f2..1ecb4b4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 // Components -export { DeviceStream } from './components/device-stream'; +export { DeviceStream, type DeviceStreamProps } from './components/device-stream'; export { RemoteControl, type RemoteControlHandle, @@ -25,6 +25,7 @@ export type { export { useTaskApproval } from './hooks/use-task-approval'; export type { UseTaskApprovalOptions, UseTaskApprovalResult } from './hooks/use-task-approval'; export type { PendingApproval, ApprovalDecision } from './lib/task-approval'; +export type { DeviceStreamLabels, StreamError, StreamErrorReason } from './lib/stream-error'; export { useStreamReconnect } from './hooks/use-stream-reconnect'; export { STREAM_RECONNECT_MAX_ATTEMPTS, diff --git a/src/lib/stream-error.ts b/src/lib/stream-error.ts new file mode 100644 index 0000000..d12319e --- /dev/null +++ b/src/lib/stream-error.ts @@ -0,0 +1,64 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +/** + * Why a stream connection attempt failed (stream client contract v1). + * + * - `credentials_unavailable`: `tokenProvider` threw, timed out or returned an empty key. + * - `connection_refused`: the signaling WebSocket closed before it opened. A browser cannot + * see the HTTP status, so a rejected, used or expired key, a wrong device and a refused + * origin all land here. + * - `disconnected`: an open session dropped (includes the server's session cap). + * - `device_unavailable`: the server reported the device offline or not ready. The current + * signaling protocol has no such message, so this package does not report it yet. + * - `unknown`: anything else, e.g. a handshake timeout. + */ +export type StreamErrorReason = + | 'credentials_unavailable' + | 'connection_refused' + | 'disconnected' + | 'device_unavailable' + | 'unknown'; + +/** What a single failed attempt looked like, before the reconnect policy adds its counters. */ +export interface StreamFailure { + reason: StreamErrorReason; + message: string; +} + +/** Payload of `onError`. */ +export interface StreamError extends StreamFailure { + /** Consecutive failed attempts in the current reconnect cycle, starting at 1. */ + attempt: number; + /** True when the SDK stops retrying; the Retry button stays available. */ + final: boolean; +} + +/** User-visible strings of `DeviceStream`; every key is optional and has an English default. */ +export interface DeviceStreamLabels { + /** Pill while the stream has no URL yet or is negotiating. Default `connecting`. */ + connecting: string; + /** Pill while reconnecting after a drop; ` (n/6)` is appended from the second attempt. Default `reconnecting`. */ + disconnected: string; + /** Message once retries are exhausted. Default `device stream unavailable`. */ + unavailable: string; + /** Retry button text. Default `Retry`. */ + retry: string; +} + +const DEFAULT_DEVICE_STREAM_LABELS: DeviceStreamLabels = { + connecting: 'connecting', + disconnected: 'reconnecting', + unavailable: 'device stream unavailable', + retry: 'Retry', +}; + +/** Fills every label the integrator left out (or set to undefined) with its English default. */ +export function resolveDeviceStreamLabels(overrides?: Partial): DeviceStreamLabels { + return { + connecting: overrides?.connecting ?? DEFAULT_DEVICE_STREAM_LABELS.connecting, + disconnected: overrides?.disconnected ?? DEFAULT_DEVICE_STREAM_LABELS.disconnected, + unavailable: overrides?.unavailable ?? DEFAULT_DEVICE_STREAM_LABELS.unavailable, + retry: overrides?.retry ?? DEFAULT_DEVICE_STREAM_LABELS.retry, + }; +} diff --git a/src/lib/stream-reconnect.test.ts b/src/lib/stream-reconnect.test.ts index 1a2c426..6b72fd1 100644 --- a/src/lib/stream-reconnect.test.ts +++ b/src/lib/stream-reconnect.test.ts @@ -412,3 +412,79 @@ describe('heal cadence', () => { expect(calls.heals).toBe(3); }); }); + +describe('onError reporting', () => { + function withErrors() { + const schedule = new FakeSchedule(); + const errors: { reason: string; message: string; attempt: number; final: boolean }[] = []; + const controller = createStreamReconnectController({ + onRemount: () => controller.attemptMounted(), + onHeal: () => {}, + onSnapshot: () => {}, + onError: (error) => { + errors.push(error); + }, + schedule, + random: NO_JITTER, + }); + controller.attemptMounted(); + return { schedule, controller, errors }; + } + + test('reports each failed attempt once with its reason and counter', () => { + const { schedule, controller, errors } = withErrors(); + controller.handleFailure({ reason: 'credentials_unavailable', message: 'no key' }); + controller.handleFailure({ reason: 'connection_refused', message: 'ignored: same attempt' }); + expect(errors).toEqual([{ reason: 'credentials_unavailable', message: 'no key', attempt: 1, final: false }]); + schedule.advance(DELAYS[0]); + controller.handleFailure({ reason: 'connection_refused', message: 'closed' }); + expect(errors.map((e) => [e.reason, e.attempt, e.final])).toEqual([ + ['credentials_unavailable', 1, false], + ['connection_refused', 2, false], + ]); + }); + + test('marks the last failure final once retries stop, and not before', () => { + const { schedule, controller, errors } = withErrors(); + for (let i = 0; i <= STREAM_RECONNECT_MAX_ATTEMPTS; i++) { + controller.handleFailure({ reason: 'connection_refused', message: 'closed' }); + schedule.advance(30_000); + } + expect(errors).toHaveLength(STREAM_RECONNECT_MAX_ATTEMPTS + 1); + expect(errors.filter((e) => e.final)).toHaveLength(1); + expect(errors.at(-1)).toMatchObject({ final: true, attempt: STREAM_RECONNECT_MAX_ATTEMPTS + 1 }); + expect(controller.getSnapshot().status).toBe('unavailable'); + }); + + test('a dropped session is disconnected and a silent attempt is unknown', () => { + const { schedule, controller, errors } = withErrors(); + controller.handleConnected(); + controller.handleDisconnected(); + schedule.advance(DELAYS[0]); + schedule.advance(STREAM_CONNECT_TIMEOUT_MS); + expect(errors.map((e) => e.reason)).toEqual(['disconnected', 'unknown']); + }); + + test('a failure without detail is unknown', () => { + const { controller, errors } = withErrors(); + controller.handleFailure(); + expect(errors.map((e) => e.reason)).toEqual(['unknown']); + }); + + test('a throwing consumer callback does not stop the retry', () => { + const schedule = new FakeSchedule(); + let remounts = 0; + const controller = createStreamReconnectController({ + onRemount: () => { remounts += 1; }, + onHeal: () => {}, + onSnapshot: () => {}, + onError: () => { throw new Error('consumer bug'); }, + schedule, + random: NO_JITTER, + }); + controller.attemptMounted(); + controller.handleFailure(); + schedule.advance(DELAYS[0]); + expect(remounts).toBe(1); + }); +}); diff --git a/src/lib/stream-reconnect.ts b/src/lib/stream-reconnect.ts index 520495f..b0e6d49 100644 --- a/src/lib/stream-reconnect.ts +++ b/src/lib/stream-reconnect.ts @@ -1,6 +1,8 @@ // Copyright 2026 Mobilerun // SPDX-License-Identifier: Apache-2.0 +import type { StreamError, StreamFailure } from './stream-error'; + /** * Pure reconnect state machine for a single device stream. Framework-free so * the timing/backoff logic is unit-testable; `use-stream-reconnect` wires it @@ -80,6 +82,8 @@ export interface StreamReconnectControllerOptions { onSnapshot(snapshot: StreamReconnectSnapshot): void; /** A reconnect attempt is being scheduled β€” refetch stream credentials. */ onHeal(): void; + /** One call per counted failure, with the reason and whether retries stopped. */ + onError?(error: StreamError): void; schedule?: StreamReconnectSchedule; random?: () => number; } @@ -91,7 +95,8 @@ export interface StreamReconnectController { setDisabled(): void; handleConnected(): void; handleDisconnected(): void; - handleFailure(): void; + /** Terminal failure of the current attempt; `failure` names why (default `unknown`). */ + handleFailure(failure?: StreamFailure): void; /** * Whether a stream-target change (URL/token rotation) must be held back * instead of applied right now. True while waiting out a backoff (an @@ -113,6 +118,7 @@ export function createStreamReconnectController({ onRemount, onSnapshot, onHeal, + onError, schedule = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }, random = Math.random, }: StreamReconnectControllerOptions): StreamReconnectController { @@ -150,12 +156,21 @@ export function createStreamReconnectController({ stabilityTimer = clearTimer(stabilityTimer); }; + const reportError = (failure: StreamFailure, final: boolean) => { + // A consumer callback must never break the reconnect machine. + try { + onError?.({ reason: failure.reason, message: failure.message, attempt, final }); + } catch { + // Ignored on purpose. + } + }; + const startAttempt = () => { onRemount(); // The resulting mount calls attemptMounted(), which arms the watchdog. }; - const countFailure = () => { + const countFailure = (failure: StreamFailure) => { // A wait is already scheduled (or we already gave up) β€” e.g. a stale // watchdog armed by a StrictMode double-mount. Never stack timers. if (backoffTimer !== null || status === 'unavailable') return; @@ -166,10 +181,12 @@ export function createStreamReconnectController({ if (attempt > STREAM_RECONNECT_MAX_ATTEMPTS) { status = 'unavailable'; emit(); + reportError(failure, true); return; } status = 'reconnecting'; emit(); + reportError(failure, false); // Refetch credentials once per recovery cycle, not per attempt: consumer // onHeal callbacks trigger network refetches (grids share one full-fleet // refetch across every card), so per-attempt heals would multiply into a @@ -222,7 +239,7 @@ export function createStreamReconnectController({ if (!startWatchdog) return; watchdogTimer = schedule.setTimeout(() => { watchdogTimer = null; - countFailure(); + countFailure({ reason: 'unknown', message: 'Connection attempt timed out' }); }, STREAM_CONNECT_TIMEOUT_MS); }, @@ -267,13 +284,13 @@ export function createStreamReconnectController({ if (!enabled) return; if (!everConnectedThisEpoch) return; if (failureLatched) return; - countFailure(); + countFailure({ reason: 'disconnected', message: 'The stream connection dropped' }); }, - handleFailure() { + handleFailure(failure = { reason: 'unknown', message: 'Connection failed' }) { if (!enabled) return; if (failureLatched) return; - countFailure(); + countFailure(failure); }, shouldDeferTargetChange() { diff --git a/src/styles.css b/src/styles.css index e762d1e..fdadff8 100644 --- a/src/styles.css +++ b/src/styles.css @@ -10,7 +10,9 @@ * import '@mobilerun/react/styles.css'; * * All colors resolve through CSS custom properties, so a host app can override - * any token by redefining e.g. `--background` on `:root` (or scope a `.dark`). + * any token by setting e.g. `--mr-background` on an ancestor or on the component + * root (`.mobilerun-device-stream`). The unprefixed names (`--background`, ...) + * still work for one more minor release. */ @layer theme, base, components, utilities; @@ -23,55 +25,46 @@ @source './components/**/*.{ts,tsx}'; /* Map semantic color utilities (bg-background, text-muted-foreground, ...) onto - * overridable CSS variables. `inline` keeps the var() reference so host apps can - * restyle by setting the variables below. */ + * overridable CSS variables. `inline` keeps the var() reference. + * + * Each color resolves, in order: `--mr-` (the documented name, set it on + * any ancestor or on the component root), then the legacy unprefixed `--` + * for one more minor release (host themes such as shadcn already define it), then + * the bundled default below. The package itself defines no unprefixed variable. */ @theme inline { - --color-background: var(--background); - --color-foreground: var(--foreground); - --color-card: var(--card); - --color-card-foreground: var(--card-foreground); - --color-muted: var(--muted); - --color-muted-foreground: var(--muted-foreground); - --color-border: var(--border); - --color-ring: var(--ring); - --color-primary: var(--primary); - --color-primary-foreground: var(--primary-foreground); - --color-accent: var(--accent); - --color-accent-foreground: var(--accent-foreground); - --color-destructive: var(--destructive); -} - -/* Default token values (light). Override on the host's :root to retheme. */ -:root { - --background: oklch(1 0 0); - --foreground: oklch(0.145 0 0); - --card: oklch(1 0 0); - --card-foreground: oklch(0.145 0 0); - --muted: oklch(0.97 0 0); - --muted-foreground: oklch(0.556 0 0); - --border: oklch(0.922 0 0); - --ring: oklch(0.708 0 0); - --primary: oklch(0.205 0 0); - --primary-foreground: oklch(0.985 0 0); - --accent: oklch(0.97 0 0); - --accent-foreground: oklch(0.205 0 0); - --destructive: oklch(0.577 0.245 27.325); + --color-background: var(--mr-background, var(--background, var(--mr-default-background, oklch(1 0 0)))); + --color-foreground: var(--mr-foreground, var(--foreground, var(--mr-default-foreground, oklch(0.145 0 0)))); + --color-card: var(--mr-card, var(--card, var(--mr-default-card, oklch(1 0 0)))); + --color-card-foreground: var(--mr-card-foreground, var(--card-foreground, var(--mr-default-card-foreground, oklch(0.145 0 0)))); + --color-muted: var(--mr-muted, var(--muted, var(--mr-default-muted, oklch(0.97 0 0)))); + --color-muted-foreground: var(--mr-muted-foreground, var(--muted-foreground, var(--mr-default-muted-foreground, oklch(0.556 0 0)))); + --color-border: var(--mr-border, var(--border, var(--mr-default-border, oklch(0.922 0 0)))); + --color-ring: var(--mr-ring, var(--ring, var(--mr-default-ring, oklch(0.708 0 0)))); + --color-primary: var(--mr-primary, var(--primary, var(--mr-default-primary, oklch(0.205 0 0)))); + --color-primary-foreground: var(--mr-primary-foreground, var(--primary-foreground, var(--mr-default-primary-foreground, oklch(0.985 0 0)))); + --color-accent: var(--mr-accent, var(--accent, var(--mr-default-accent, oklch(0.97 0 0)))); + --color-accent-foreground: var(--mr-accent-foreground, var(--accent-foreground, var(--mr-default-accent-foreground, oklch(0.205 0 0)))); + --color-destructive: var(--mr-destructive, var(--destructive, var(--mr-default-destructive, oklch(0.577 0.245 27.325)))); } -.dark { - --background: oklch(0.145 0 0); - --foreground: oklch(0.985 0 0); - --card: oklch(0.205 0 0); - --card-foreground: oklch(0.985 0 0); - --muted: oklch(0.269 0 0); - --muted-foreground: oklch(0.708 0 0); - --border: oklch(1 0 0 / 10%); - --ring: oklch(0.556 0 0); - --primary: oklch(0.985 0 0); - --primary-foreground: oklch(0.205 0 0); - --accent: oklch(0.269 0 0); - --accent-foreground: oklch(0.985 0 0); - --destructive: oklch(0.704 0.191 22.216); +/* Bundled dark defaults, scoped to the component roots (never to :root or a bare + * `.dark`). Light defaults are the literal fallbacks above. Add `.dark` to an + * ancestor of the component, or to the root itself, to use them. */ +:is(.dark .mobilerun-device-stream, .dark .mobilerun-task-approval, .dark .mobilerun-navigation-bar, .dark .rc-container), +:is(.mobilerun-device-stream, .mobilerun-task-approval, .mobilerun-navigation-bar, .rc-container).dark { + --mr-default-background: oklch(0.145 0 0); + --mr-default-foreground: oklch(0.985 0 0); + --mr-default-card: oklch(0.205 0 0); + --mr-default-card-foreground: oklch(0.985 0 0); + --mr-default-muted: oklch(0.269 0 0); + --mr-default-muted-foreground: oklch(0.708 0 0); + --mr-default-border: oklch(1 0 0 / 10%); + --mr-default-ring: oklch(0.556 0 0); + --mr-default-primary: oklch(0.985 0 0); + --mr-default-primary-foreground: oklch(0.205 0 0); + --mr-default-accent: oklch(0.269 0 0); + --mr-default-accent-foreground: oklch(0.985 0 0); + --mr-default-destructive: oklch(0.704 0.191 22.216); } /* ---- Structural component CSS (not utility-based) ---- */ From 54dae2c41cb9c2094ba951d29bc52b17436632ad Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Sat, 21 Nov 2026 16:20:13 +0100 Subject: [PATCH 08/22] docs(stream): errors, labels, theming Co-Authored-By: Claude Sonnet 5.5 --- README.md | 22 ++++++++++++++++++++++ docs/default-ui.md | 19 +++++++++++++++---- docs/stream-keys.md | 41 ++++++++++++++++++++++++++++++++++++++++- docs/task-approvals.md | 4 ++-- example/main.tsx | 21 ++++++++++++++++----- 5 files changed, 95 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 7b948ef..88381a8 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,28 @@ export function DevicePanel({ deviceId, streamUrl }: { deviceId: string; streamU Never log or cache stream keys. Your backend must authenticate callers and authorize the device. The [full example](docs/stream-keys.md) also shows `useDeviceStream` and legacy compatibility. +`tokenProvider` runs before every connection attempt, the first one and each reconnect, and a key is +never used twice. The static `streamToken` prop still works but is **deprecated**: a single-use key +cannot reconnect, and the component logs one console warning per mount. + +React to failures and white-label the texts: + +```tsx + report(reason, attempt, final)} + labels={{ connecting: 'Starting…', disconnected: 'Reconnecting', unavailable: 'Phone unavailable', retry: 'Try again' }} +/> +``` + +`reason` is `credentials_unavailable` (your provider threw or took longer than 10 s), +`connection_refused` (the socket closed before it opened: a used, expired or wrong key, a wrong +device or a refused origin; browsers cannot see the HTTP status), `disconnected` (an open session +dropped, including the 30-minute server cap) or `unknown`. `final: true` means retries stopped and +the Retry button is showing. `labels` replaces every text the component renders. + ## Guides | Guide | Covers | diff --git a/docs/default-ui.md b/docs/default-ui.md index dfe4c7e..f99d37c 100644 --- a/docs/default-ui.md +++ b/docs/default-ui.md @@ -31,11 +31,22 @@ import '@mobilerun/react/styles.css'; It bundles the design tokens, only the Tailwind utilities the components use, the animations, and the structural CSS. It does **not** include Tailwind's preflight/reset, so it won't touch your base styles β€” and you don't need Tailwind installed. -Retheme by overriding the CSS variables on an ancestor (e.g. `--background`, `--card`, `--muted-foreground`, `--border`, `--primary`), or add a `.dark` ancestor for the bundled dark palette: +Retheme by setting the `--mr-*` variables on an ancestor or on the component root +(`.mobilerun-device-stream`, `.mobilerun-task-approval`, `.mobilerun-navigation-bar`). The package +defines no unprefixed variable globally, so it cannot clash with your own `--background`. Add a +`.dark` ancestor (or class on the component root) for the bundled dark palette: ```css -:root { - --primary: oklch(0.55 0.18 268); - --background: oklch(0.985 0.004 85); +.mobilerun-device-stream { + --mr-primary: oklch(0.55 0.18 268); + --mr-background: oklch(0.985 0.004 85); } ``` + +Available tokens: `--mr-background`, `--mr-foreground`, `--mr-card`, `--mr-card-foreground`, +`--mr-muted`, `--mr-muted-foreground`, `--mr-border`, `--mr-ring`, `--mr-primary`, +`--mr-primary-foreground`, `--mr-accent`, `--mr-accent-foreground`, `--mr-destructive`. + +The old unprefixed names (`--background`, `--card`, ...) are still read as a fallback for one more +minor release, so themes written for 0.3 keep working; move them to `--mr-*`. User-visible texts are +set with the `labels` prop, see [Stream keys](stream-keys.md#labels). diff --git a/docs/stream-keys.md b/docs/stream-keys.md index 521359f..713e993 100644 --- a/docs/stream-keys.md +++ b/docs/stream-keys.md @@ -124,6 +124,45 @@ mints a fresh key for each new socket. `onStreamHealed` can refresh URL/state; i and must not be used to cache a key. Static `DeviceStream.streamToken`, `RemoteControl.token`, and the hook's returned `streamToken` are -**deprecated**, retained for existing consumers. Manual URL/token mode is a legacy diagnostic path; +**deprecated**, retained for existing consumers. `DeviceStream` logs one console warning per mount +when it runs on a static key; `tokenProvider` wins when both are given. Manual URL/token mode is a legacy diagnostic path; a pasted single-use key cannot reconnect after admission. `useDeviceStream` also still accepts `{ client, deviceId }` with a plain `Mobilerun` client. + +## Errors + +`DeviceStream` calls `onError` once per failed connection attempt: + +```ts +onError?: (error: { + reason: 'credentials_unavailable' | 'connection_refused' | 'disconnected' | 'device_unavailable' | 'unknown'; + message: string; // for logs, not for end users + attempt: number; // consecutive failed attempts in this cycle, from 1 + final: boolean; // true when the SDK stops retrying; the Retry button stays available +}) => void; +``` + +| `reason` | Meaning | +| --- | --- | +| `credentials_unavailable` | `tokenProvider` threw, rejected, returned an empty key or took longer than 10 s. Normal backoff applies. | +| `connection_refused` | The signaling socket closed before it opened. A browser cannot read the HTTP status, so a used, expired or revoked key, a wrong device and a refused origin all land here. Check the mint call first. | +| `disconnected` | An open session dropped, including the 30-minute server session cap. | +| `device_unavailable` | Reserved for a server message that the device is offline or not ready. The current signaling protocol has none, so React does not report it yet. | +| `unknown` | Anything else, for example a handshake that never finished. | + +## Labels + +Every text the component renders comes from `labels`, with English defaults: + +```tsx + +``` + +A `placeholderLabel` (for example the device state) still takes precedence over `labels.connecting`. diff --git a/docs/task-approvals.md b/docs/task-approvals.md index 5043e62..8e89678 100644 --- a/docs/task-approvals.md +++ b/docs/task-approvals.md @@ -147,7 +147,7 @@ The host owns the sheet or dialog; the library ships only the card. Render ` first and then these + * unprefixed names (--background, --card, --muted-foreground, ...), which stay + * supported for one more minor release, so the embedded DeviceStream and + * NavigationBar pick up the cloud palette too. New code sets --mr-. */ .app { --background: oklch(0.985 0.004 85); --foreground: oklch(0.26 0.008 65); --card: oklch(0.995 0.005 85); --card-foreground: oklch(0.26 0.008 65); @@ -183,6 +185,7 @@ interface Status { isLoading: boolean; error?: unknown; connected: boolean; + streamError?: StreamError; } /** @@ -239,7 +242,9 @@ function SdkStream({ muted={muted} placeholderLabel={state ?? (isLoading ? 'loading…' : 'connecting')} onStreamHealed={refetch} - onConnectionStateChange={(c) => onStatus({ connected: c })} + // `reason` tells a refused key from a dropped session; `final` means the Retry button is showing. + onError={(streamError) => onStatus({ streamError })} + onConnectionStateChange={(c) => onStatus({ connected: c, ...(c ? { streamError: undefined } : {}) })} /> ); @@ -249,17 +254,23 @@ type Mode = 'sdk' | 'manual'; function StatusLine({ s, active }: { s: Status; active: boolean }) { const errText = s.error ? (s.error as { message?: string })?.message ?? String(s.error) : null; + const streamError = active && !s.connected ? s.streamError : undefined; let tone: 'idle' | 'warn' | 'ok' | 'err' = 'idle'; let text = 'idle'; if (errText) { tone = 'err'; text = 'error'; + } else if (streamError?.final) { + tone = 'err'; + text = `stream failed: ${streamError.reason}`; } else if (active && s.connected) { tone = 'ok'; text = 'live'; } else if (active) { tone = 'warn'; - text = s.state ? `${s.state}…` : s.isLoading ? 'loading…' : 'connecting…'; + text = streamError + ? `retrying after ${streamError.reason} (attempt ${streamError.attempt})` + : s.state ? `${s.state}…` : s.isLoading ? 'loading…' : 'connecting…'; } return (
    From d4d5249adbe3f2f9fd17a762a7d54b71ee6266de Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Sat, 21 Nov 2026 17:07:53 +0100 Subject: [PATCH 09/22] fix(stream): credential-free error text Co-Authored-By: Claude Sonnet 5.5 --- docs/stream-keys.md | 2 +- src/hooks/use-webrtc-connection.test.ts | 53 ++++++++++++++++++++++++- src/hooks/use-webrtc-connection.ts | 5 ++- src/hooks/webrtc-test-fixture.ts | 7 ++++ src/lib/stream-error.ts | 15 ++++++- 5 files changed, 77 insertions(+), 5 deletions(-) diff --git a/docs/stream-keys.md b/docs/stream-keys.md index 713e993..6bb9f04 100644 --- a/docs/stream-keys.md +++ b/docs/stream-keys.md @@ -136,7 +136,7 @@ a pasted single-use key cannot reconnect after admission. `useDeviceStream` also ```ts onError?: (error: { reason: 'credentials_unavailable' | 'connection_refused' | 'disconnected' | 'device_unavailable' | 'unknown'; - message: string; // for logs, not for end users + message: string; // fixed SDK text for logs, never exception text from your provider or the socket attempt: number; // consecutive failed attempts in this cycle, from 1 final: boolean; // true when the SDK stops retrying; the Retry button stays available }) => void; diff --git a/src/hooks/use-webrtc-connection.test.ts b/src/hooks/use-webrtc-connection.test.ts index 7b6d1bd..66a6685 100644 --- a/src/hooks/use-webrtc-connection.test.ts +++ b/src/hooks/use-webrtc-connection.test.ts @@ -581,7 +581,7 @@ test('provider timeout reports credentials_unavailable', async () => { clock.advance(10_000); await tick(); expect(reasons(f)).toEqual(['credentials_unavailable']); - expect(f.failureInfos[0].message).toContain('timeout'); + expect(f.failureInfos[0].message).toBe('Stream key provider failed'); f.unmount(); }); @@ -664,3 +664,54 @@ test('every connect attempt calls the provider again and never reuses a key', as expect(minted).toBe(3); f.unmount(); }); + +// Credential-free messages. The fixture shares one Error with the hook (as a browser does), so +// `e instanceof Error` is true here and a forwarded `message` would show up. +const MARKER = 'dr_st_SYNTHETIC_MARKER'; + +function expectNoCredential(f: { failureInfos: object[] }, onErrorPayloads: object[]) { + for (const text of [JSON.stringify(f.failureInfos), JSON.stringify(onErrorPayloads)]) { + expect(text).not.toContain(MARKER); + expect(text).not.toContain('token='); + } +} + +function throughController(failures: { reason: string; message: string }[]) { + const payloads: object[] = []; + const controller = createStreamReconnectController({ + onRemount: () => {}, onHeal: () => {}, onSnapshot: () => {}, + onError: (error) => { payloads.push(error); }, + schedule: new FakeSchedule(), + }); + controller.attemptMounted(); + controller.handleFailure(failures[0] as never); + return payloads; +} + +test.each([ + ['an Error naming the key', async () => { throw new Error('mint failed for ' + MARKER); }], + ['an Error naming a token URL', async () => { throw new Error('GET https://api.invalid/stream?token=' + MARKER + ' 401'); }], + ['a thrown string', async () => { throw 'token=' + MARKER; }], +] as const)('provider rejecting with %s never leaks its text', async (_name, tokenProvider) => { + const f = await fixture(); + f.mount('a', undefined, { tokenProvider }); + await tick(); + expect(reasons(f)).toEqual(['credentials_unavailable']); + expect(f.failureInfos[0].message).toBe('Stream key provider failed'); + expectNoCredential(f, throughController(f.failureInfos)); + f.unmount(); +}); + +test.each([ + ['provider', { tokenProvider: async () => MARKER }], + ['static token', { token: MARKER }], +] as const)('a socket constructor error carrying the token URL never leaks it (%s)', async (_name, credentials) => { + const f = await fixture(); + f.hooks.onConstruct = (url) => { throw new Error('cannot open ' + url); }; + f.mount('a', undefined, credentials); + await tick(); + expect(reasons(f)).toEqual(['unknown']); + expect(f.failureInfos[0].message).toBe('Stream connection attempt failed'); + expectNoCredential(f, throughController(f.failureInfos)); + f.unmount(); +}); diff --git a/src/hooks/use-webrtc-connection.ts b/src/hooks/use-webrtc-connection.ts index 212993f..b44a1ae 100644 --- a/src/hooks/use-webrtc-connection.ts +++ b/src/hooks/use-webrtc-connection.ts @@ -10,7 +10,7 @@ import { STREAM_RTC_CONFIG_TIMEOUT_MS, STREAM_WS_OPEN_TIMEOUT_MS, } from '../lib/stream-reconnect'; -import type { StreamErrorReason, StreamFailure } from '../lib/stream-error'; +import { STREAM_FAILURE_MESSAGES, type StreamErrorReason, type StreamFailure } from '../lib/stream-error'; import { createRTCConfigurationRequest } from '../webrtc-messages'; const debugLog = (...args: any[]) => { @@ -749,7 +749,8 @@ export function useWebRtcConnection({ updateStatus(provider ? 'Stream connection attempt failed' : 'Error: ' + e); failAttempt({ reason: phase, - message: e instanceof Error && e.message ? e.message : 'Stream connection attempt failed', + // Never forward `e.message`: provider and socket errors can carry the key or a ?token= URL. + message: STREAM_FAILURE_MESSAGES[phase], }); } }; diff --git a/src/hooks/webrtc-test-fixture.ts b/src/hooks/webrtc-test-fixture.ts index 414a63d..388dc5d 100644 --- a/src/hooks/webrtc-test-fixture.ts +++ b/src/hooks/webrtc-test-fixture.ts @@ -28,6 +28,8 @@ export async function fixture(clock?: FakeSchedule) { const setTimer = schedule('timeout'); const setIntervalTimer = schedule('interval'); const clearTimer = (id: number) => { timers.delete(id); }; + // Lets a test make the socket constructor throw. + const hooks: { onConstruct?: (url: string) => void } = {}; class FakeSocket { static OPEN = 1; readyState = 0; @@ -38,6 +40,7 @@ export async function fixture(clock?: FakeSchedule) { onerror: (() => void) | null = null; onmessage: ((event: { data: string }) => Promise) | null = null; constructor(readonly url: string) { + hooks.onConstruct?.(url); sockets.push(this); } open() { this.readyState = 1; this.onopen?.(); } @@ -117,6 +120,9 @@ export async function fixture(clock?: FakeSchedule) { RTCSessionDescription: class { constructor(value: object) { Object.assign(this, value); } }, RTCIceCandidate: class { constructor(value: object) { Object.assign(this, value); } }, setTimeout: clock?.setTimeout ?? setTimer, clearTimeout: clock?.clearTimeout ?? clearTimer, + // The hook runs in a VM realm with its own Error; sharing the host's keeps `e instanceof Error` + // true for errors the tests throw, as in a browser where there is one realm. + Error, console, stateWrites, }; const runner = await runHook<{ useWebRtcConnection: (options: object) => { wsRef: { current: FakeSocket | null } } }>( @@ -148,6 +154,7 @@ export async function fixture(clock?: FakeSchedule) { return render(id, openUrl, credentials); }; return { + hooks, sockets, peers, timers, scheduled, states, failures, failureInfos, bindings, stateWrites, video, mount, render, document, diff --git a/src/lib/stream-error.ts b/src/lib/stream-error.ts index d12319e..99bfcd0 100644 --- a/src/lib/stream-error.ts +++ b/src/lib/stream-error.ts @@ -20,12 +20,25 @@ export type StreamErrorReason = | 'device_unavailable' | 'unknown'; -/** What a single failed attempt looked like, before the reconnect policy adds its counters. */ +/** + * What a single failed attempt looked like, before the reconnect policy adds its counters. + * `message` is always SDK-owned text: exception messages from `tokenProvider` or the socket + * can carry a stream key or a `?token=` URL and are never forwarded. + */ export interface StreamFailure { reason: StreamErrorReason; message: string; } +/** Fixed, credential-free text for a failure whose cause is an arbitrary exception. */ +export const STREAM_FAILURE_MESSAGES: Record = { + credentials_unavailable: 'Stream key provider failed', + connection_refused: 'Signaling connection closed before it opened', + disconnected: 'The stream connection dropped', + device_unavailable: 'The device is unavailable', + unknown: 'Stream connection attempt failed', +}; + /** Payload of `onError`. */ export interface StreamError extends StreamFailure { /** Consecutive failed attempts in the current reconnect cycle, starting at 1. */ From 1bcebd4655584d886f8eea86e95208481b149bee Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Sat, 21 Nov 2026 17:18:23 +0100 Subject: [PATCH 10/22] docs(stream): static token exception Co-Authored-By: Claude Sonnet 5.5 --- README.md | 10 +++++++--- docs/stream-keys.md | 10 ++++++++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 88381a8..d74a612 100644 --- a/README.md +++ b/README.md @@ -102,9 +102,13 @@ export function DevicePanel({ deviceId, streamUrl }: { deviceId: string; streamU Never log or cache stream keys. Your backend must authenticate callers and authorize the device. The [full example](docs/stream-keys.md) also shows `useDeviceStream` and legacy compatibility. -`tokenProvider` runs before every connection attempt, the first one and each reconnect, and a key is -never used twice. The static `streamToken` prop still works but is **deprecated**: a single-use key -cannot reconnect, and the component logs one console warning per mount. +`tokenProvider` runs before every connection attempt, the first one and each reconnect, and the SDK +never reuses a key it returns. **Use it: stream keys are single-use, so only a provider can reconnect.** + +The static `streamToken` prop is **deprecated** and an explicit exception to that rule: it is kept until the +legacy token is removed, and the SDK passes the same value again on every reconnect. A single-use key +given this way is rejected on the second attempt, so the stream ends in the Retry state +(`connection_refused`). The component logs one console warning per mount. React to failures and white-label the texts: diff --git a/docs/stream-keys.md b/docs/stream-keys.md index 6bb9f04..4b7d07d 100644 --- a/docs/stream-keys.md +++ b/docs/stream-keys.md @@ -125,8 +125,14 @@ and must not be used to cache a key. Static `DeviceStream.streamToken`, `RemoteControl.token`, and the hook's returned `streamToken` are **deprecated**, retained for existing consumers. `DeviceStream` logs one console warning per mount -when it runs on a static key; `tokenProvider` wins when both are given. Manual URL/token mode is a legacy diagnostic path; -a pasted single-use key cannot reconnect after admission. `useDeviceStream` also still accepts +when it runs on a static key; `tokenProvider` wins when both are given. + +**Exception to the no-reuse rule:** with a static token the SDK does not fetch anything new; it sends +the same value on the first connect and on every reconnect, until the legacy token is removed. Stream +keys are single-use, so a static key that was already admitted or rejected fails the retry attempts +(`connection_refused`) and ends in the Retry state. A long-lived legacy token keeps reconnecting. +`tokenProvider` is the recommended path and the only one that works with single-use keys. Manual +URL/token mode is a legacy diagnostic path; a pasted single-use key cannot reconnect after admission. `useDeviceStream` also still accepts `{ client, deviceId }` with a plain `Mobilerun` client. ## Errors From dca607556ce9b85b345d4316f83944067f714278 Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Sat, 21 Nov 2026 18:25:43 +0100 Subject: [PATCH 11/22] fix(stream): npm links, attempt count, theme vars Co-Authored-By: Claude Sonnet 5.5 --- README.md | 44 +++++++++++++++-------- docs/stream-keys.md | 4 +-- src/components/device-stream.tsx | 10 ++++-- src/components/stream-status-pill.tsx | 2 +- src/lib/readme.test.ts | 24 +++++++++++++ src/lib/stream-error.ts | 13 +++++-- src/lib/stream-reconnect.test.ts | 35 ++++++++++++++++++ src/lib/styles.test.ts | 52 +++++++++++++++++++++++++++ src/styles.css | 9 +++-- 9 files changed, 169 insertions(+), 24 deletions(-) create mode 100644 src/lib/readme.test.ts create mode 100644 src/lib/styles.test.ts diff --git a/README.md b/README.md index d74a612..5be905f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@

    - - - Mobilerun + + + Mobilerun

    @@ -19,7 +19,7 @@ [![npm](https://img.shields.io/npm/v/@mobilerun/react.svg?color=cb3837&logo=npm)](https://www.npmjs.com/package/@mobilerun/react) [![React](https://img.shields.io/badge/React-18%20%7C%2019-149eca.svg)](https://react.dev) -[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](./LICENSE) +[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/droidrun/mobilerun-react/blob/main/LICENSE) [![Discord](https://img.shields.io/discord/1360219330318696488?color=white&label=Discord&logo=discord&logoColor=white)](https://discord.gg/ZZbKEZZkwK) **React** Β· [Android](https://github.com/droidrun/mobilerun-android) Β· [iOS](https://github.com/droidrun/mobilerun-swift) Β· [Flutter](https://github.com/droidrun/mobilerun-flutter) @@ -31,7 +31,7 @@
    - @mobilerun/react dev playground + @mobilerun/react dev playground In this package @@ -43,7 +43,7 @@
  • RemoteControl β€” lower-level stream and input control.
  • Prebuilt stylesheet β€” themeable with CSS variables.
  • -

    Lower-level hooks and scrcpy helpers: see docs/.

    +

    Lower-level hooks and scrcpy helpers: see docs/.

    Requirements
    • React and React DOM 18 or 19, in a browser with WebRTC.
    • @@ -70,7 +70,7 @@ npm install @mobilerun/react @mobilerun/sdk react react-dom 3. The SDK opens the stream with that key, one key per connection, and reconnects with a fresh one. Keep `MOBILERUN_API_KEY` on your server. This mint handler excerpt uses the SDK's `/v1` base URL; -see [Stream keys](docs/stream-keys.md) for route setup, metadata fetching and error handling. +see [Stream keys](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-keys.md) for route setup, metadata fetching and error handling. ```ts import { MobilerunSDK } from '@mobilerun/sdk'; @@ -100,7 +100,7 @@ export function DevicePanel({ deviceId, streamUrl }: { deviceId: string; streamU ``` Never log or cache stream keys. Your backend must authenticate callers and authorize the device. -The [full example](docs/stream-keys.md) also shows `useDeviceStream` and legacy compatibility. +The [full example](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-keys.md) also shows `useDeviceStream` and legacy compatibility. `tokenProvider` runs before every connection attempt, the first one and each reconnect, and the SDK never reuses a key it returns. **Use it: stream keys are single-use, so only a provider can reconnect.** @@ -128,19 +128,35 @@ device or a refused origin; browsers cannot see the HTTP status), `disconnected` dropped, including the 30-minute server cap) or `unknown`. `final: true` means retries stopped and the Retry button is showing. `labels` replaces every text the component renders. +## Theming + +The stylesheet defines no unprefixed CSS variable, so it cannot clash with your own `--background`. Set +these on any ancestor of the component or on its root (`.mobilerun-device-stream`): +`--mr-background`, `--mr-foreground`, `--mr-card`, `--mr-card-foreground`, `--mr-muted`, +`--mr-muted-foreground`, `--mr-border`, `--mr-ring`, `--mr-primary`, `--mr-primary-foreground`, +`--mr-accent`, `--mr-accent-foreground`, `--mr-destructive`. + +Each color resolves in this order: `--mr-`, then the old unprefixed `--` (kept for one more +minor release, so a host theme that already defines `--background` keeps working), then the bundled +default. Add `.dark` to an ancestor, or to the component root, for the bundled dark defaults. + +```css +.mobilerun-device-stream { --mr-primary: oklch(0.55 0.18 268); --mr-background: oklch(0.985 0.004 85); } +``` + ## Guides | Guide | Covers | | --- | --- | -| [Stream keys](docs/stream-keys.md) | Server routes, device metadata, `tokenProvider`, retries and legacy tokens. | -| [Components and styling](docs/default-ui.md) | Components, prebuilt CSS, theme variables and dark mode. | -| [Task approvals](docs/task-approvals.md) | Webhooks, backend decisions, cards, bottom sheets and labels. | +| [Stream keys](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-keys.md) | Server routes, device metadata, `tokenProvider`, retries and legacy tokens. | +| [Components and styling](https://github.com/droidrun/mobilerun-react/blob/main/docs/default-ui.md) | Components, prebuilt CSS, theme variables and dark mode. | +| [Task approvals](https://github.com/droidrun/mobilerun-react/blob/main/docs/task-approvals.md) | Webhooks, backend decisions, cards, bottom sheets and labels. | ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md) for builds, tests, conformance fixtures and the example app. -Report vulnerabilities privately as described in [SECURITY.md](SECURITY.md). +See [CONTRIBUTING.md](https://github.com/droidrun/mobilerun-react/blob/main/CONTRIBUTING.md) for builds, tests, conformance fixtures and the example app. +Report vulnerabilities privately as described in [SECURITY.md](https://github.com/droidrun/mobilerun-react/blob/main/SECURITY.md). ## License -[Apache-2.0](LICENSE) +[Apache-2.0](https://github.com/droidrun/mobilerun-react/blob/main/LICENSE) diff --git a/docs/stream-keys.md b/docs/stream-keys.md index 4b7d07d..167dbb8 100644 --- a/docs/stream-keys.md +++ b/docs/stream-keys.md @@ -143,7 +143,7 @@ URL/token mode is a legacy diagnostic path; a pasted single-use key cannot recon onError?: (error: { reason: 'credentials_unavailable' | 'connection_refused' | 'disconnected' | 'device_unavailable' | 'unknown'; message: string; // fixed SDK text for logs, never exception text from your provider or the socket - attempt: number; // consecutive failed attempts in this cycle, from 1 + attempt: number; // consecutive failed attempts in this cycle, from 1; the pill shows the same n as "(n/6)" final: boolean; // true when the SDK stops retrying; the Retry button stays available }) => void; ``` @@ -164,7 +164,7 @@ Every text the component renders comes from `labels`, with English defaults: (f useStaticTokenWarning(!!streamToken && !tokenProvider); - const reconnectLabel = - attempt > 1 ? `${labels.disconnected} (${attempt}/${STREAM_RECONNECT_MAX_ATTEMPTS})` : labels.disconnected; + const reconnectLabel = reconnectPillLabel(labels.disconnected, attempt, STREAM_RECONNECT_MAX_ATTEMPTS); return (
      diff --git a/src/lib/readme.test.ts b/src/lib/readme.test.ts new file mode 100644 index 0000000..4300e17 --- /dev/null +++ b/src/lib/readme.test.ts @@ -0,0 +1,24 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const readme = readFileSync(join(import.meta.dir, '..', '..', 'README.md'), 'utf8'); + +// npmjs.com renders the README without the repository tree, so a relative target is a dead link there. +test('every README link and image target is absolute', () => { + const targets = [ + ...[...readme.matchAll(/\]\(([^)\s]+)/g)].map((m) => m[1]), + ...[...readme.matchAll(/\b(?:href|src|srcset)="([^"]+)"/g)].map((m) => m[1]), + ]; + expect(targets.length).toBeGreaterThan(10); + expect(targets.filter((t) => !/^(https?:\/\/|#|mailto:)/.test(t))).toEqual([]); +}); + +test('the README names the --mr-* variables and the fallback order', () => { + expect(readme).toContain('--mr-background'); + expect(readme).toContain('--mr-primary'); + expect(readme).toMatch(/`--mr-`, then the old unprefixed `--`.*then the bundled\s+default/s); +}); diff --git a/src/lib/stream-error.ts b/src/lib/stream-error.ts index 99bfcd0..59a97b7 100644 --- a/src/lib/stream-error.ts +++ b/src/lib/stream-error.ts @@ -41,7 +41,11 @@ export const STREAM_FAILURE_MESSAGES: Record = { /** Payload of `onError`. */ export interface StreamError extends StreamFailure { - /** Consecutive failed attempts in the current reconnect cycle, starting at 1. */ + /** + * Consecutive failed attempts in the current reconnect cycle: 1 for the failed first connect, + * up to 7 (the first connect plus 6 retries), which is the `final` one. It is the same number + * the reconnect pill shows as `(n/6)` while retry n is pending; the pill is gone once `final`. + */ attempt: number; /** True when the SDK stops retrying; the Retry button stays available. */ final: boolean; @@ -51,7 +55,7 @@ export interface StreamError extends StreamFailure { export interface DeviceStreamLabels { /** Pill while the stream has no URL yet or is negotiating. Default `connecting`. */ connecting: string; - /** Pill while reconnecting after a drop; ` (n/6)` is appended from the second attempt. Default `reconnecting`. */ + /** Pill while reconnecting after a drop; ` (n/6)` is appended from the first retry. Default `reconnecting`. */ disconnected: string; /** Message once retries are exhausted. Default `device stream unavailable`. */ unavailable: string; @@ -75,3 +79,8 @@ export function resolveDeviceStreamLabels(overrides?: Partial= 1 ? `${label} (${attempt}/${maxAttempts})` : label; +} diff --git a/src/lib/stream-reconnect.test.ts b/src/lib/stream-reconnect.test.ts index 6b72fd1..d424ba1 100644 --- a/src/lib/stream-reconnect.test.ts +++ b/src/lib/stream-reconnect.test.ts @@ -12,6 +12,7 @@ import { streamReconnectDelayMs, type StreamReconnectSnapshot, } from './stream-reconnect'; +import { reconnectPillLabel } from './stream-error'; import { FakeSchedule } from './test-clock'; // random() => 0.5 makes the jitter factor exactly 1.0. @@ -488,3 +489,37 @@ describe('onError reporting', () => { expect(remounts).toBe(1); }); }); + +describe('attempt counting', () => { + test('the reconnect pill number and onError attempt are the same count at every failure', () => { + const schedule = new FakeSchedule(); + const snapshots: StreamReconnectSnapshot[] = []; + const errors: { attempt: number; final: boolean }[] = []; + const controller = createStreamReconnectController({ + onRemount: () => controller.attemptMounted(), + onHeal: () => {}, + onSnapshot: (s) => snapshots.push(s), + onError: (e) => { errors.push(e); }, + schedule, + random: NO_JITTER, + }); + controller.attemptMounted(); + const pills: string[] = []; + for (let failure = 1; failure <= STREAM_RECONNECT_MAX_ATTEMPTS + 1; failure++) { + controller.handleFailure({ reason: 'connection_refused', message: 'closed' }); + const { status, attempt } = controller.getSnapshot(); + expect(errors.at(-1)!.attempt).toBe(attempt); + if (status === 'reconnecting') pills.push(reconnectPillLabel('reconnecting', attempt, STREAM_RECONNECT_MAX_ATTEMPTS)); + schedule.advance(30_000); + } + expect(pills).toEqual([1, 2, 3, 4, 5, 6].map((n) => `reconnecting (${n}/6)`)); + expect(errors.map((e) => e.attempt)).toEqual([1, 2, 3, 4, 5, 6, 7]); + expect(errors.map((e) => e.final)).toEqual([false, false, false, false, false, false, true]); + expect(controller.getSnapshot().status).toBe('unavailable'); + }); + + test('the pill label has no suffix before the first failure', () => { + expect(reconnectPillLabel('reconnecting', 0, 6)).toBe('reconnecting'); + expect(reconnectPillLabel('Getrennt', 2, 6)).toBe('Getrennt (2/6)'); + }); +}); diff --git a/src/lib/styles.test.ts b/src/lib/styles.test.ts new file mode 100644 index 0000000..21588d7 --- /dev/null +++ b/src/lib/styles.test.ts @@ -0,0 +1,52 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { expect, test } from 'bun:test'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +// The host's own theme names the stylesheet reads as a fallback; it must not declare them. +const LEGACY_HOST_TOKENS = [ + 'background', 'foreground', 'card', 'card-foreground', 'muted', 'muted-foreground', 'border', 'ring', + 'primary', 'primary-foreground', 'accent', 'accent-foreground', 'destructive', +]; + +async function compileStylesheet(): Promise { + const dir = mkdtempSync(join(tmpdir(), 'mobilerun-css-')); + try { + const root = join(import.meta.dir, '..', '..'); + const out = join(dir, 'styles.css'); + const proc = Bun.spawn([join(root, 'node_modules/.bin/tailwindcss'), '-i', join(root, 'src/styles.css'), '-o', out, '--minify'], { + cwd: root, stdout: 'pipe', stderr: 'pipe', + }); + expect(await proc.exited).toBe(0); + return readFileSync(out, 'utf8'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +test('the stylesheet declares no custom property on :root, :host or a bare .dark', async () => { + const css = await compileStylesheet(); + expect(css).not.toContain(':root'); + expect(css).not.toContain(':host'); + expect(css).not.toMatch(/(^|\})\.dark\{/); + // Nothing generic such as --background, --spacing or --text-xs is declared at all. + const declared = [...css.matchAll(/(?:^|[{;])(--[a-z0-9-]+):/g)].map((m) => m[1]); + expect(declared.filter((name) => !name.startsWith('--tw-') && !name.startsWith('--mr-'))).toEqual([]); + // source(none) must not have dropped the utilities the components use. + for (const selector of ['.animate-spin', '.bg-background', '.slide-in-from-bottom-\\[1\\.5rem\\]', '.md\\:hidden', '.rc-video']) { + expect(css).toContain(selector); + } +}); + +test('every variable the stylesheet reads is either its own, prefixed, or a documented host token', async () => { + const css = await compileStylesheet(); + const declared = new Set([...css.matchAll(/(?:^|[{;])(--[a-z0-9-]+):/g)].map((m) => m[1])); + const read = [...css.matchAll(/var\((--[a-z0-9-]+)/g)].map((m) => m[1]); + const orphans = read.filter( + (name) => !declared.has(name) && !name.startsWith('--mr-') && !LEGACY_HOST_TOKENS.includes(name.slice(2)) && !name.startsWith('--tw-'), + ); + expect(orphans).toEqual([]); +}); diff --git a/src/styles.css b/src/styles.css index fdadff8..6e6400b 100644 --- a/src/styles.css +++ b/src/styles.css @@ -17,8 +17,13 @@ @layer theme, base, components, utilities; -@import 'tailwindcss/theme.css' layer(theme); -@import 'tailwindcss/utilities.css' layer(utilities); +/* `theme(inline)` resolves Tailwind's theme values (spacing, text sizes, radii, ...) into the + * utilities instead of declaring them as variables on :root, so the package adds no global + * custom property to the host page. */ +@import 'tailwindcss/theme.css' layer(theme) theme(inline); +/* `source(none)`: only the @source below is scanned, so a mention of a theme name in a test or + * doc can never pull Tailwind's variables back onto :root. */ +@import 'tailwindcss/utilities.css' layer(utilities) source(none); @import 'tw-animate-css'; /* Scan the component source so only used utilities are emitted. */ From ebc7a1c9b2873738cff1b2322bcc0a41628bfa91 Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Mon, 23 Nov 2026 08:50:29 +0100 Subject: [PATCH 12/22] feat(stream): network-aware reconnect --- src/hooks/test-hook-runner.ts | 4 +- src/hooks/use-stream-reconnect.test.ts | 141 ++++++++++++++++++++++++ src/hooks/use-stream-reconnect.ts | 27 ++++- src/hooks/use-webrtc-connection.test.ts | 77 +++++++++++++ src/hooks/use-webrtc-connection.ts | 22 +++- src/hooks/webrtc-test-fixture.ts | 11 +- src/lib/stream-reconnect.test.ts | 58 ++++++++++ src/lib/stream-reconnect.ts | 38 ++++++- 8 files changed, 364 insertions(+), 14 deletions(-) create mode 100644 src/hooks/use-stream-reconnect.test.ts diff --git a/src/hooks/test-hook-runner.ts b/src/hooks/test-hook-runner.ts index 11954a1..1de561b 100644 --- a/src/hooks/test-hook-runner.ts +++ b/src/hooks/test-hook-runner.ts @@ -9,7 +9,8 @@ const fixtureSource = ` const effectSlots = new Set(); export function useRef(value) { return slots[cursor++] ??= { current: value }; } export function useState(value) { - const ref = useRef(value); + const ref = slots[cursor] ?? { current: typeof value === 'function' ? value() : value }; + slots[cursor++] = ref; return [ref.current, next => { ref.current = typeof next === 'function' ? next(ref.current) : next; stateWrites.push(ref.current); @@ -27,6 +28,7 @@ const fixtureSource = ` const slot = ref.current = { deps, cleanup: undefined }; pending.push(() => { slot.cleanup = fn(); }); } + export const useLayoutEffect = useEffect; globalThis.beginRender = () => { cursor = 0; }; globalThis.cleanupEffects = () => { for (const ref of effectSlots) { diff --git a/src/hooks/use-stream-reconnect.test.ts b/src/hooks/use-stream-reconnect.test.ts new file mode 100644 index 0000000..c1538fc --- /dev/null +++ b/src/hooks/use-stream-reconnect.test.ts @@ -0,0 +1,141 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { expect, mock, test } from 'bun:test'; +import { FakeSchedule } from '../lib/test-clock'; +import { runHook, tick } from './test-hook-runner'; +import { fixture } from './webrtc-test-fixture'; +import type { useStreamReconnect } from './use-stream-reconnect'; + +async function reconnectFixture(online = true, enabled = true) { + const clock = new FakeSchedule(); + const navigator = { onLine: online }; + const listeners = { online: new Set<() => void>(), offline: new Set<() => void>(), visibilitychange: new Set<() => void>() }; + const events = { + addEventListener(name: keyof typeof listeners, fn: () => void) { listeners[name].add(fn); }, + removeEventListener(name: keyof typeof listeners, fn: () => void) { listeners[name].delete(fn); }, + }; + const heal = mock(() => {}); + const error = mock(() => {}); + const runner = await runHook<{ useStreamReconnect: typeof useStreamReconnect }>( + import.meta.dir + '/use-stream-reconnect.ts', { + navigator, window: events, document: { ...events, visibilityState: 'visible' }, + setTimeout: clock.setTimeout, clearTimeout: clock.clearTimeout, + Math: { ...Math, random: () => 0.5, min: Math.min, max: Math.max, round: Math.round }, + }, + ); + const render = (target = 'a', onHeal = heal) => { + runner.beginRender(); + const result = runner.module.exports.useStreamReconnect({ + target, targetKey: target, enabled, watchdogFromSocket: true, onHeal, onError: error, + }); + runner.flushEffects(); + return result; + }; + const network = (available: boolean) => { + navigator.onLine = available; + listeners[available ? 'online' : 'offline'].forEach(fn => fn()); + }; + return { clock, listeners, heal, error, render, network, unmount: runner.unmount }; +} + +test('initial offline, target change, visibility and retry wait for one fresh online attempt', async () => { + const r = await reconnectFixture(false); + const f = await fixture(); + f.networkChange(false); + let result = r.render(); + const provider = mock(async () => 'fresh'); + f.mount(result.activeTarget, undefined, { tokenProvider: provider }); + result.retry(); + r.listeners.visibilitychange.forEach(fn => fn()); + result = r.render('b'); + r.clock.advance(45_001); + await tick(); + expect(result.streamKey).toBe('0'); + expect(result.activeTarget).toBe('a'); + expect(provider).not.toHaveBeenCalled(); + expect(f.sockets).toHaveLength(0); + expect(r.error).not.toHaveBeenCalled(); + r.network(true); + r.network(true); + r.listeners.visibilitychange.forEach(fn => fn()); + result = r.render('b'); + f.networkChange(true); + f.mount(result.activeTarget, undefined, { tokenProvider: provider }); + await tick(); + expect(result.streamKey).toBe('1'); + expect(result.activeTarget).toBe('b'); + expect(result.attempt).toBe(0); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + expect(r.heal).toHaveBeenCalledTimes(1); + r.unmount(); + f.unmount(); + expect(r.listeners.online.size + r.listeners.offline.size + r.listeners.visibilitychange.size).toBe(0); +}); + +test('network return resets high backoff, uses latest callback and ignores the old child', async () => { + const r = await reconnectFixture(); + let result = r.render(); + result.onConnectionFailed(); + r.clock.advance(1_000); + result = r.render(); + result.onConnectionFailed(); + r.clock.advance(2_000); + result = r.render(); + result.onConnectionFailed(); + result = r.render(); + expect(result.attempt).toBe(3); + const stale = result; + const latestHeal = mock(() => {}); + r.network(false); + result.retry(); + r.listeners.visibilitychange.forEach(fn => fn()); + r.render('new', latestHeal); + r.clock.advance(60_000); + await tick(); + r.network(true); + result = r.render('new', latestHeal); + stale.onConnectionFailed(); + stale.onConnectionStateChange(true); + stale.onConnectionAttemptStarted(); + r.network(true); + result = r.render('new', latestHeal); + expect(result.streamKey).toBe('3'); + expect(result.activeTarget).toBe('new'); + expect(result.attempt).toBe(0); + expect(result.status).toBe('reconnecting'); + expect(latestHeal).toHaveBeenCalledTimes(1); + expect(r.error).toHaveBeenCalledTimes(3); + expect(r.clock.pendingCount).toBe(0); + r.unmount(); +}); + +test('connected hook survives offline/online and detached observers cannot revive it', async () => { + const r = await reconnectFixture(); + let result = r.render(); + result.onConnectionStateChange(true); + r.network(false); + r.network(true); + result = r.render(); + expect(result.streamKey).toBe('0'); + expect(result.status).toBe('connected'); + expect(r.heal).not.toHaveBeenCalled(); + r.network(false); + const lateOnline = [...r.listeners.online][0]!; + r.unmount(); + lateOnline(); + r.clock.advance(60_000); + expect(r.heal).not.toHaveBeenCalled(); + expect(r.clock.pendingCount).toBe(0); +}); + +test('online with no target asks the discovery owner to refresh once', async () => { + const r = await reconnectFixture(false, false); + r.render(); + r.network(true); + r.network(true); + expect(r.heal).toHaveBeenCalledTimes(1); + expect(r.render().streamKey).toBe('0'); + r.unmount(); +}); diff --git a/src/hooks/use-stream-reconnect.ts b/src/hooks/use-stream-reconnect.ts index 9eac19d..e3b2eaf 100644 --- a/src/hooks/use-stream-reconnect.ts +++ b/src/hooks/use-stream-reconnect.ts @@ -77,7 +77,7 @@ export function useStreamReconnect({ // abandons never leaks its value into a later attempt. const targetRef = useRef(target); const targetKeyRef = useRef(targetKey); - useEffect(() => { + useLayoutEffect(() => { targetRef.current = target; targetKeyRef.current = targetKey; }); @@ -94,6 +94,7 @@ export function useStreamReconnect({ const controllerRef = useRef | null>(null); if (controllerRef.current === null) { controllerRef.current = createStreamReconnectController({ + networkAvailable: typeof navigator === 'undefined' || navigator.onLine !== false, onRemount: bumpMount, onSnapshot: (s) => setSnapshot(s), onHeal: () => onHealRef.current?.(), @@ -117,31 +118,42 @@ export function useStreamReconnect({ setMount((m) => ({ epoch: m.epoch + 1, target })); } + const activeEpochRef = useRef(mount.epoch); const onConnectionAttemptStarted = useCallback(() => { + if (activeEpochRef.current !== mount.epoch) return; controllerRef.current?.attemptMounted(); - }, []); + }, [mount.epoch]); // Enable failure accounting before the child's passive startup effect, so // synchronous failures count too. DeviceStream defers the watchdog to its // socket event; existing hook consumers keep mount-driven arming. useLayoutEffect(() => { + activeEpochRef.current = mount.epoch; if (enabled) { controllerRef.current?.attemptMounted(!watchdogFromSocket); } else { controllerRef.current?.setDisabled(); } + return () => { activeEpochRef.current = null; }; }, [mount.epoch, enabled, watchdogFromSocket]); useEffect(() => { const onVisibility = () => { if (document.visibilityState === 'visible') controllerRef.current?.handleWake(); }; - const onOnline = () => controllerRef.current?.handleWake(); + const onOnline = () => controllerRef.current?.setNetworkAvailable(true); + const onOffline = () => controllerRef.current?.setNetworkAvailable(false); + // Re-read after commit in case connectivity changed between render and effects. + controllerRef.current?.setNetworkAvailable( + typeof navigator === 'undefined' || navigator.onLine !== false, + ); document.addEventListener('visibilitychange', onVisibility); window.addEventListener('online', onOnline); + window.addEventListener('offline', onOffline); return () => { document.removeEventListener('visibilitychange', onVisibility); window.removeEventListener('online', onOnline); + window.removeEventListener('offline', onOffline); }; }, []); @@ -150,13 +162,16 @@ export function useStreamReconnect({ }, []); const onConnectionStateChange = useCallback((connected: boolean) => { + if (activeEpochRef.current !== mount.epoch) return; if (connected) controllerRef.current?.handleConnected(); else controllerRef.current?.handleDisconnected(); - }, []); + }, [mount.epoch]); const onConnectionFailed = useCallback( - (failure?: StreamFailure) => controllerRef.current?.handleFailure(failure), - [], + (failure?: StreamFailure) => { + if (activeEpochRef.current === mount.epoch) controllerRef.current?.handleFailure(failure); + }, + [mount.epoch], ); const retry = useCallback(() => controllerRef.current?.retry(), []); diff --git a/src/hooks/use-webrtc-connection.test.ts b/src/hooks/use-webrtc-connection.test.ts index 66a6685..c006b00 100644 --- a/src/hooks/use-webrtc-connection.test.ts +++ b/src/hooks/use-webrtc-connection.test.ts @@ -715,3 +715,80 @@ test.each([ expectNoCredential(f, throughController(f.failureInfos)); f.unmount(); }); + +test.each([false, true])('offline start gates provider and socket (provider=%s)', async (withProvider) => { + const f = await fixture(); + const provider = mock(async () => 'fresh'); + f.networkChange(false); + f.mount('a', undefined, withProvider ? { tokenProvider: provider } : { token: 'legacy' }); + f.visibilityChange(); + f.fireTimers(); + f.render('b', undefined, withProvider ? { tokenProvider: provider } : { token: 'legacy' }); + await tick(); + expect(provider).not.toHaveBeenCalled(); + expect(f.sockets).toEqual([]); + expect(f.failures).toEqual([]); + f.unmount(); + expect(f.networkListeners.online.size + f.networkListeners.offline.size).toBe(0); +}); + +test.each(['resolve', 'reject'] as const)('offline cancels provider wait and ignores late %s', async (outcome) => { + const clock = new FakeSchedule(); + const f = await fixture(clock); + const pending = deferred(); + f.mount('a', undefined, { tokenProvider: () => pending.promise }); + f.networkChange(false); + await tick(); + expect(clock.pendingCount).toBe(0); + const settle = { resolve: () => pending.resolve('unused'), reject: () => pending.reject(new Error('late')) }; + settle[outcome](); + clock.advance(45_001); + await tick(); + expect(clock.pendingCount).toBe(0); + expect(f.sockets).toEqual([]); + expect(f.failures).toEqual([]); + f.networkChange(true); + await tick(); + expect(f.sockets).toEqual([]); // Low-level hook has no autonomous retry loop. + f.unmount(); +}); + +test('availability is rechecked before socket allocation without an offline event', async () => { + const f = await fixture(); + const pending = deferred(); + f.mount('a', undefined, { tokenProvider: () => pending.promise }); + f.navigator.onLine = false; + pending.resolve('unused'); + await tick(); + expect(f.sockets).toEqual([]); + expect(f.failures).toEqual([]); + f.unmount(); +}); + +test('offline cancels a socket handshake without reporting a failure', async () => { + const clock = new FakeSchedule(); + const f = await fixture(clock); + f.mount(); + f.networkChange(false); + clock.advance(45_001); + await tick(); + expect(f.sockets[0].readyState).toBe(3); + expect(f.failures).toEqual([]); + expect(clock.pendingCount).toBe(0); + f.unmount(); +}); + +test('advisory offline preserves connected media and online allocates no second socket', async () => { + const f = await fixture(); + await f.negotiate(); + const pc = f.peers[0]; + pc.connectionState = 'connected'; + pc.onconnectionstatechange!(); + f.networkChange(false); + f.networkChange(true); + await tick(); + expect(pc.closed).toBe(false); + expect(f.sockets).toHaveLength(1); + expect(f.failures).toEqual([]); + f.unmount(); +}); diff --git a/src/hooks/use-webrtc-connection.ts b/src/hooks/use-webrtc-connection.ts index b44a1ae..3f060e3 100644 --- a/src/hooks/use-webrtc-connection.ts +++ b/src/hooks/use-webrtc-connection.ts @@ -96,6 +96,9 @@ export function useWebRtcConnection({ const tokenProviderRef = useRef(tokenProvider); tokenProviderRef.current = tokenProvider; const attemptGenerationRef = useRef(0); + const networkAvailableRef = useRef(typeof navigator === 'undefined' || navigator.onLine !== false); + const isOffline = () => !networkAvailableRef.current || + (typeof navigator !== 'undefined' && navigator.onLine === false); const onConnectionStateChangeRef = useRef(onConnectionStateChange); onConnectionStateChangeRef.current = onConnectionStateChange; @@ -212,6 +215,7 @@ export function useWebRtcConnection({ }; const start = async () => { + if (isOffline()) return; const generation = ++attemptGenerationRef.current; const provider = tokenProviderRef.current; const isActive = () => attemptGenerationRef.current === generation; @@ -262,6 +266,11 @@ export function useWebRtcConnection({ reject(new Error('Stream key request cancelled')); }; cancelStartupRef.current = cancelStartup; + if (isOffline()) { + ++attemptGenerationRef.current; + cancelStartup(); + return; + } Promise.resolve(provider()).then(resolve, reject); }); } finally { @@ -272,6 +281,7 @@ export function useWebRtcConnection({ if (!streamToken?.trim()) throw new Error('Stream key provider returned an empty key'); phase = 'unknown'; } + if (!isActive() || isOffline()) return; const wsUrl = buildWebSocketUrl(url, streamToken); const ws = new WebSocket(wsUrl); attemptWs = ws; @@ -802,7 +812,15 @@ export function useWebRtcConnection({ }; useEffect(() => { - // Start connection when component mounts + // Connectivity only gates/cancels here; useStreamReconnect owns recovery. + networkAvailableRef.current = typeof navigator === 'undefined' || navigator.onLine !== false; + const onOffline = () => { + networkAvailableRef.current = false; + if (peerConnectionRef.current?.connectionState !== 'connected') stop(); + }; + const onOnline = () => { networkAvailableRef.current = true; }; + window.addEventListener('offline', onOffline); + window.addEventListener('online', onOnline); start(); // Add visibility change listener @@ -817,6 +835,8 @@ export function useWebRtcConnection({ return () => { stop(); document.removeEventListener('visibilitychange', onVisibilityChange); + window.removeEventListener('offline', onOffline); + window.removeEventListener('online', onOnline); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- intentional: reconnect only on url/session change; start/stop/keepAlive helpers are re-created each render and must not be deps }, [url, sessionId]); diff --git a/src/hooks/webrtc-test-fixture.ts b/src/hooks/webrtc-test-fixture.ts index 388dc5d..65b9503 100644 --- a/src/hooks/webrtc-test-fixture.ts +++ b/src/hooks/webrtc-test-fixture.ts @@ -108,8 +108,13 @@ export async function fixture(clock?: FakeSchedule) { this.tracks = this.tracks.filter(t => t !== track); } } + const navigator = { onLine: true }; + const networkListeners = { online: new Set<() => void>(), offline: new Set<() => void>() }; const context = { + navigator, window: { + addEventListener(name: 'online' | 'offline', fn: () => void) { networkListeners[name].add(fn); }, + removeEventListener(name: 'online' | 'offline', fn: () => void) { networkListeners[name].delete(fn); }, setTimeout: clock?.setTimeout ?? setTimer, clearTimeout: clock?.clearTimeout ?? clearTimer, setInterval: setIntervalTimer, clearInterval: clearTimer, location: { href: 'https://example.invalid' }, @@ -154,7 +159,11 @@ export async function fixture(clock?: FakeSchedule) { return render(id, openUrl, credentials); }; return { - hooks, + hooks, navigator, networkListeners, + networkChange(online: boolean) { + navigator.onLine = online; + networkListeners[online ? 'online' : 'offline'].forEach(fn => fn()); + }, sockets, peers, timers, scheduled, states, failures, failureInfos, bindings, stateWrites, video, mount, render, document, diff --git a/src/lib/stream-reconnect.test.ts b/src/lib/stream-reconnect.test.ts index d424ba1..f9b4de5 100644 --- a/src/lib/stream-reconnect.test.ts +++ b/src/lib/stream-reconnect.test.ts @@ -523,3 +523,61 @@ describe('attempt counting', () => { expect(reconnectPillLabel('Getrennt', 2, 6)).toBe('Getrennt (2/6)'); }); }); + +describe('network availability', () => { + test('offline stops a watchdog across its deadline without counting failures', () => { + const { controller, schedule, calls } = setup(); + controller.attemptMounted(); + schedule.advance(44_999); + controller.setNetworkAvailable(false); + expect(schedule.pendingCount).toBe(0); + controller.handleWake(); + controller.retry(); + controller.attemptMounted(); + schedule.advance(45_001); + expect(controller.getSnapshot()).toEqual({ status: 'connecting', attempt: 0 }); + expect(schedule.pendingCount).toBe(0); + expect(calls).toEqual({ remounts: 0, heals: 0 }); + controller.setNetworkAvailable(true); + controller.setNetworkAvailable(true); + expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 0 }); + expect(calls).toEqual({ remounts: 1, heals: 1 }); + controller.dispose(); + }); + + test('network return revives unavailable with a full budget exactly once', () => { + const { controller, schedule, calls } = setup(); + controller.attemptMounted(); + DELAYS.forEach(delay => { + controller.handleFailure(); + schedule.advance(delay); + controller.attemptMounted(); + }); + controller.handleFailure(); + expect(controller.getSnapshot()).toEqual({ status: 'unavailable', attempt: 7 }); + controller.setNetworkAvailable(false); + controller.retry(); + controller.handleWake(); + expect(calls.remounts).toBe(6); + controller.setNetworkAvailable(true); + controller.setNetworkAvailable(true); + expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 0 }); + expect(calls.remounts).toBe(7); + expect(calls.heals).toBe(2); + controller.dispose(); + }); + + test('a live transport can report one drop offline but cannot schedule another retry', () => { + const { controller, schedule, calls } = setup(); + controller.attemptMounted(); + controller.handleConnected(); + controller.setNetworkAvailable(false); + controller.handleDisconnected(); + controller.handleFailure(); + schedule.advance(60_000); + expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 1 }); + expect(schedule.pendingCount).toBe(0); + expect(calls).toEqual({ remounts: 0, heals: 0 }); + controller.dispose(); + }); +}); diff --git a/src/lib/stream-reconnect.ts b/src/lib/stream-reconnect.ts index b0e6d49..4a632fd 100644 --- a/src/lib/stream-reconnect.ts +++ b/src/lib/stream-reconnect.ts @@ -25,7 +25,7 @@ import type { StreamError, StreamFailure } from './stream-error'; * - Holding a connection for STABILITY_MS refills the retry budget, so the * known server-side ~2min disconnect loop (DRO-2705) keeps reconnecting * quickly forever instead of escalating into `unavailable`. - * - `handleWake` (tab visible / back online) short-circuits a pending + * - `handleWake` (tab visible) short-circuits a pending * backoff wait, and starts a fresh retry cycle when unavailable. */ @@ -86,6 +86,8 @@ export interface StreamReconnectControllerOptions { onError?(error: StreamError): void; schedule?: StreamReconnectSchedule; random?: () => number; + /** Unknown connectivity is optimistic; false pauses acquisition and retry timing. */ + networkAvailable?: boolean; } export interface StreamReconnectController { @@ -106,7 +108,9 @@ export interface StreamReconnectController { * disabled β€” the new target applies immediately. */ shouldDeferTargetChange(): boolean; - /** Tab became visible / browser back online. */ + /** Observe browser connectivity; only false β†’ true starts a fresh cycle. */ + setNetworkAvailable(available: boolean): void; + /** Tab became visible. */ handleWake(): void; /** Manual retry (Unavailable-state button). */ retry(): void; @@ -121,8 +125,10 @@ export function createStreamReconnectController({ onError, schedule = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }, random = Math.random, + networkAvailable = true, }: StreamReconnectControllerOptions): StreamReconnectController { let enabled = false; + let disposed = false; let status: StreamReconnectStatus = 'connecting'; let attempt = 0; // Whether the current mount epoch ever reached 'connected'. Gates @@ -166,6 +172,7 @@ export function createStreamReconnectController({ }; const startAttempt = () => { + if (!enabled || !networkAvailable || disposed) return; onRemount(); // The resulting mount calls attemptMounted(), which arms the watchdog. }; @@ -174,6 +181,7 @@ export function createStreamReconnectController({ // A wait is already scheduled (or we already gave up) β€” e.g. a stale // watchdog armed by a StrictMode double-mount. Never stack timers. if (backoffTimer !== null || status === 'unavailable') return; + if (!networkAvailable && !everConnectedThisEpoch) return; failureLatched = true; watchdogTimer = clearTimer(watchdogTimer); stabilityTimer = clearTimer(stabilityTimer); @@ -194,10 +202,12 @@ export function createStreamReconnectController({ // Credentials fetched at cycle start stay fresh across the cycle's ~2min // span, and a refresh that resolves after a retry started still applies // via shouldDeferTargetChange/onRemount. + if (!networkAvailable) return; if (!healedThisCycle) { healedThisCycle = true; onHeal(); } + if (!networkAvailable) return; backoffTimer = schedule.setTimeout( () => { backoffTimer = null; @@ -223,6 +233,8 @@ export function createStreamReconnectController({ return { attemptMounted(startWatchdog = true) { enabled = true; + disposed = false; + if (!networkAvailable) return; // Mid-wait mounts are stale (StrictMode remount): the scheduled // attempt owns the next watchdog. if (backoffTimer !== null || status === 'unavailable') return; @@ -245,6 +257,7 @@ export function createStreamReconnectController({ setDisabled() { enabled = false; + disposed = false; clearAllTimers(); everConnectedThisEpoch = false; failureLatched = false; @@ -269,6 +282,7 @@ export function createStreamReconnectController({ emit(); } stabilityTimer = clearTimer(stabilityTimer); + if (!networkAvailable) return; stabilityTimer = schedule.setTimeout(() => { stabilityTimer = null; // The cycle is over β€” the next failure run heals anew. @@ -298,11 +312,24 @@ export function createStreamReconnectController({ // retry has started; outside the two deferred states the change must // apply immediately or an in-flight attempt would run on stale // credentials until the connect watchdog fails it. - return backoffTimer !== null || status === 'unavailable'; + return !networkAvailable || backoffTimer !== null || status === 'unavailable'; + }, + + setNetworkAvailable(available) { + if (disposed || available === networkAvailable) return; + networkAvailable = available; + clearAllTimers(); + if (!available) return; + if (status === 'connected') { + emit(); // Let the hook apply a target change held back while offline. + return; + } + if (enabled) freshCycle(); + else onHeal(); // No target yet: its existing owner resumes discovery. }, handleWake() { - if (!enabled) return; + if (!enabled || !networkAvailable) return; if (status === 'unavailable') { freshCycle(); return; @@ -316,11 +343,12 @@ export function createStreamReconnectController({ }, retry() { - if (!enabled) return; + if (!enabled || !networkAvailable) return; if (status === 'unavailable') freshCycle(); }, dispose() { + disposed = true; enabled = false; clearAllTimers(); }, From 9cd8b8050d5db11264f50e7c4d1b74f49a4a342a Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Mon, 23 Nov 2026 08:53:00 +0100 Subject: [PATCH 13/22] docs(stream): stream token wording --- CONTRIBUTING.md | 6 +- README.md | 31 ++-- docs/default-ui.md | 2 +- docs/stream-keys.md | 175 +----------------- docs/stream-tokens.md | 199 +++++++++++++++++++++ example/main.tsx | 10 +- example/server.ts | 8 +- src/components/device-stream.tsx | 8 +- src/components/remote-control.tsx | 6 +- src/hooks/use-device-stream.ts | 6 +- src/hooks/use-static-token-warning.test.ts | 4 +- src/hooks/use-static-token-warning.ts | 4 +- src/hooks/use-webrtc-connection.test.ts | 6 +- src/hooks/use-webrtc-connection.ts | 12 +- src/lib/stream-error.ts | 8 +- 15 files changed, 259 insertions(+), 226 deletions(-) create mode 100644 docs/stream-tokens.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 482893d..c78120d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,7 +18,7 @@ The control messages, signalling frames, reconnect policy and input routing are ## Example app The repo ships the playground shown in the [README](README.md). Set the API key server-side and enter a device id; -manual URL/token mode remains available for legacy diagnostics: +manual URL/token mode remains available for device token (legacy) diagnostics: ```sh bun install @@ -29,7 +29,9 @@ In SDK mode the example server returns only `id`, `state`, and `streamUrl` from `GET /api/v1/devices/:id`. Its `POST /api/v1/devices/:id/stream-key` helper calls the public mint API through `sdk.api.post('/identity/stream-keys', ...)`, returning only `{ key, keyId, expiresAt }` with `Cache-Control: no-store`. The browser's provider calls it for each connection attempt; the -API key stays server-side. The stream WebSocket connects directly with the fresh key in `?token=`. +API key stays server-side. The stream WebSocket connects directly with the fresh stream token in `?token=`. +The route names and `key` / `keyId` DTO fields remain transitional wire names until the identity API +cutover; the credential is a stream token. See [Stream tokens](docs/stream-tokens.md). The same server also demonstrates [task approvals](docs/task-approvals.md) (set `MOBILERUN_WEBHOOK_SECRET` for the webhook route). All example helpers are unauthenticated and **local-only**, bound to `127.0.0.1`. Before adapting them for production, add application authentication and device diff --git a/README.md b/README.md index 5be905f..0983d35 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@
      -> **Building Mobilerun phones into your platform?** Start with the [Partner guide](https://docs.mobilerun.ai/partners). It walks through the API key, one phone per user, stream keys and live viewing step by step. +> **Building Mobilerun phones into your platform?** Start with the [Partner guide](https://docs.mobilerun.ai/partners). It walks through the API key, one phone per user, stream tokens and live viewing step by step. @@ -64,18 +64,21 @@ npm install @mobilerun/react @mobilerun/sdk react react-dom ## Quick start -1. Your server mints a short-lived stream key for one device with your API key +1. Your server mints a short-lived stream token for one device with your API key (`POST /v1/identity/stream-keys`). Follow the [Partner guide](https://docs.mobilerun.ai/partners). -2. Your app's `tokenProvider` asks your server for a key before each connection. -3. The SDK opens the stream with that key, one key per connection, and reconnects with a fresh one. +2. Your app's `tokenProvider` asks your server for a stream token before each connection. +3. The SDK opens the stream with that token, one token per connection, and reconnects with a fresh one. + +The current wire routes still use `stream-key` / `stream-keys` and return `key` / `keyId` during +the stream-token naming transition. Use these existing routes until the identity API cutover. Keep `MOBILERUN_API_KEY` on your server. This mint handler excerpt uses the SDK's `/v1` base URL; -see [Stream keys](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-keys.md) for route setup, metadata fetching and error handling. +see [Stream tokens](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-tokens.md) for route setup, metadata fetching and error handling. ```ts import { MobilerunSDK } from '@mobilerun/sdk'; const sdk = new MobilerunSDK({ logLevel: 'off' }); // server only -export async function mintStreamKey(deviceId: string): Promise { +export async function mintStreamToken(deviceId: string): Promise { // Authenticate your user and check they own the device before minting. const { key, keyId, expiresAt } = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( '/identity/stream-keys', { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, @@ -92,21 +95,21 @@ import '@mobilerun/react/styles.css'; export function DevicePanel({ deviceId, streamUrl }: { deviceId: string; streamUrl: string }) { const tokenProvider = async () => { const res = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { method: 'POST', cache: 'no-store' }); - if (!res.ok) throw new Error('Stream key request failed'); + if (!res.ok) throw new Error('Stream token request failed'); return (await res.json()).key; }; return
      ; } ``` -Never log or cache stream keys. Your backend must authenticate callers and authorize the device. -The [full example](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-keys.md) also shows `useDeviceStream` and legacy compatibility. +Never log or cache stream tokens. Your backend must authenticate callers and authorize the device. +The [full example](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-tokens.md) also shows `useDeviceStream` and device token (legacy) compatibility. `tokenProvider` runs before every connection attempt, the first one and each reconnect, and the SDK -never reuses a key it returns. **Use it: stream keys are single-use, so only a provider can reconnect.** +never reuses a token it returns. **Use it: stream tokens are single-use, so only a provider can reconnect.** -The static `streamToken` prop is **deprecated** and an explicit exception to that rule: it is kept until the -legacy token is removed, and the SDK passes the same value again on every reconnect. A single-use key +The device token (legacy) `streamToken` prop is **deprecated** and an explicit exception to that rule: it is kept until the +device token (legacy) is removed, and the SDK passes the same value again on every reconnect. A single-use stream token given this way is rejected on the second attempt, so the stream ends in the Retry state (`connection_refused`). The component logs one console warning per mount. @@ -123,7 +126,7 @@ React to failures and white-label the texts: ``` `reason` is `credentials_unavailable` (your provider threw or took longer than 10 s), -`connection_refused` (the socket closed before it opened: a used, expired or wrong key, a wrong +`connection_refused` (the socket closed before it opened: a used, expired or wrong stream token, a wrong device or a refused origin; browsers cannot see the HTTP status), `disconnected` (an open session dropped, including the 30-minute server cap) or `unknown`. `final: true` means retries stopped and the Retry button is showing. `labels` replaces every text the component renders. @@ -148,7 +151,7 @@ default. Add `.dark` to an ancestor, or to the component root, for the bundled d | Guide | Covers | | --- | --- | -| [Stream keys](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-keys.md) | Server routes, device metadata, `tokenProvider`, retries and legacy tokens. | +| [Stream tokens](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-tokens.md) | Server routes, device metadata, `tokenProvider`, retries and device tokens (legacy). | | [Components and styling](https://github.com/droidrun/mobilerun-react/blob/main/docs/default-ui.md) | Components, prebuilt CSS, theme variables and dark mode. | | [Task approvals](https://github.com/droidrun/mobilerun-react/blob/main/docs/task-approvals.md) | Webhooks, backend decisions, cards, bottom sheets and labels. | diff --git a/docs/default-ui.md b/docs/default-ui.md index f99d37c..b3bf9ec 100644 --- a/docs/default-ui.md +++ b/docs/default-ui.md @@ -49,4 +49,4 @@ Available tokens: `--mr-background`, `--mr-foreground`, `--mr-card`, `--mr-card- The old unprefixed names (`--background`, `--card`, ...) are still read as a fallback for one more minor release, so themes written for 0.3 keep working; move them to `--mr-*`. User-visible texts are -set with the `labels` prop, see [Stream keys](stream-keys.md#labels). +set with the `labels` prop, see [Stream tokens](stream-tokens.md#labels). diff --git a/docs/stream-keys.md b/docs/stream-keys.md index 167dbb8..1366a6b 100644 --- a/docs/stream-keys.md +++ b/docs/stream-keys.md @@ -1,174 +1 @@ -← [README](../README.md) Β· [Partner guide](https://docs.mobilerun.ai/partners) - -# Stream keys - -The object API helpers (`MobilerunSDK`, `devices.fromId`, `verifyWebhook`) require `@mobilerun/sdk` 6.2 or later. The `{ client, deviceId }` hook form works with older SDKs; the peer dependency range remains `>=2.0.0`. - -Keep the API key on your backend. Use `useDeviceStream` for the URL and device state, and supply a -`tokenProvider` that calls your backend for a fresh single-use stream key before every WebSocket -attempt, including retries. - -> **`MOBILERUN_API_KEY` is a secret API key β€” never ship it to the browser.** Only the server reads it. -> The device endpoint returns only `id`, `state`, and `streamUrl`, with missing values set to `null`. -> A separate POST endpoint returns a short-lived stream key scoped to that device; the browser SDK -> uses a placeholder key to call your backend. - -On your backend, register this handler for `GET /api/v1/devices/:id`, passing the routed device ID: - -```ts -import { MobilerunSDK } from '@mobilerun/sdk'; - -const sdk = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY, server only - -export async function getDevice(id: string): Promise { - // Authenticate the caller and check the device belongs to them before returning device metadata. - const device = await sdk.devices.get(id); - return Response.json({ - id: device.info?.id ?? null, - state: device.info?.state ?? null, - streamUrl: device.info?.streamUrl ?? null, - }); -} - -// Register for POST /api/v1/devices/:id/stream-key. -export async function mintStreamKey(deviceId: string): Promise { - // Authenticate the caller and authorize this device in your application first. - try { - const minted = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( - '/identity/stream-keys', - { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, - ); - const { key, keyId, expiresAt } = minted; - return Response.json({ key, keyId, expiresAt }, { - status: 201, - headers: { 'Cache-Control': 'no-store' }, - }); - } catch (err) { - const { status } = err as { status?: number }; - const isUpstreamError = typeof status === 'number' && status >= 400 && status < 600; - return Response.json({ error: 'stream_key_mint_failed' }, { - status: isUpstreamError ? status : 502, - headers: { 'Cache-Control': 'no-store' }, - }); - } -} -``` - -The public mint API is `POST /v1/identity/stream-keys`, authenticated with your server-held API key. -Its body is `{ deviceId, ttlSeconds? }`; TTL is 60–300 seconds, default 120. It returns HTTP 201 -with `{ key, keyId, expiresAt }` and `Cache-Control: no-store`. The SDK base URL already ends in -`/v1`, so use `/identity/stream-keys` with `sdk.api.post`. Revoke with -`DELETE /v1/identity/stream-keys/{keyId}`. Each key is single-use and device-scoped. `expiresAt` -is diagnostic metadata, not a browser permission or validity check. Do not log or cache keys. -Your backend must authenticate callers and authorize the requested device; never accept an arbitrary -target URL or owner from the browser. Propagate mint refusal without returning upstream credential details. - -In your client component, point the SDK at that backend route, as in the example app: - -```tsx -'use client'; - -import { useCallback, useMemo } from 'react'; -import { MobilerunSDK } from '@mobilerun/sdk'; -import { DeviceStream, useDeviceStream } from '@mobilerun/react'; -import '@mobilerun/react/styles.css'; - -export function DevicePanel({ deviceId }: { deviceId: string }) { - const sdk = useMemo(() => new MobilerunSDK({ - apiKey: 'example-sdk-helper', // placeholder, not a Mobilerun API key - baseURL: typeof window === 'undefined' ? '/api/v1' : `${window.location.origin}/api/v1`, // SSR placeholder; the hook only fetches in the browser - }), []); - const { streamUrl, state, refetch } = useDeviceStream({ - device: sdk.devices.fromId(deviceId), // no request yet - }); - const getFreshStreamKey = useCallback(async () => { - const response = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { - method: 'POST', - cache: 'no-store', - }); - if (!response.ok) throw new Error('Stream key request failed'); - const { key } = await response.json(); - return key; - }, [deviceId]); - - return ( -
      - -
      - ); -} -``` - -### Without the hook - -Supply an existing stream URL and the same server-backed callback: - -```tsx - -``` - -`tokenProvider?: () => Promise` is supported by `DeviceStream` and `RemoteControl`. -It is awaited once immediately before each socket allocation. It takes precedence over static -`streamToken`/`token`; a rejection or empty key fails that attempt with no fallback. Pending results -after stop, device switch or unmount are ignored. Changing callback identity does not reconnect a -healthy stream. An ICE credential refresh on an existing socket does not call it again. -A server signaling close with code 1001 ends media/control in every mode and triggers the existing -bounded reconnect policy. Other signaling closes keep a connected media path running. Provider mode -mints a fresh key for each new socket. `onStreamHealed` can refresh URL/state; it is not per retry -and must not be used to cache a key. - -Static `DeviceStream.streamToken`, `RemoteControl.token`, and the hook's returned `streamToken` are -**deprecated**, retained for existing consumers. `DeviceStream` logs one console warning per mount -when it runs on a static key; `tokenProvider` wins when both are given. - -**Exception to the no-reuse rule:** with a static token the SDK does not fetch anything new; it sends -the same value on the first connect and on every reconnect, until the legacy token is removed. Stream -keys are single-use, so a static key that was already admitted or rejected fails the retry attempts -(`connection_refused`) and ends in the Retry state. A long-lived legacy token keeps reconnecting. -`tokenProvider` is the recommended path and the only one that works with single-use keys. Manual -URL/token mode is a legacy diagnostic path; a pasted single-use key cannot reconnect after admission. `useDeviceStream` also still accepts -`{ client, deviceId }` with a plain `Mobilerun` client. - -## Errors - -`DeviceStream` calls `onError` once per failed connection attempt: - -```ts -onError?: (error: { - reason: 'credentials_unavailable' | 'connection_refused' | 'disconnected' | 'device_unavailable' | 'unknown'; - message: string; // fixed SDK text for logs, never exception text from your provider or the socket - attempt: number; // consecutive failed attempts in this cycle, from 1; the pill shows the same n as "(n/6)" - final: boolean; // true when the SDK stops retrying; the Retry button stays available -}) => void; -``` - -| `reason` | Meaning | -| --- | --- | -| `credentials_unavailable` | `tokenProvider` threw, rejected, returned an empty key or took longer than 10 s. Normal backoff applies. | -| `connection_refused` | The signaling socket closed before it opened. A browser cannot read the HTTP status, so a used, expired or revoked key, a wrong device and a refused origin all land here. Check the mint call first. | -| `disconnected` | An open session dropped, including the 30-minute server session cap. | -| `device_unavailable` | Reserved for a server message that the device is offline or not ready. The current signaling protocol has none, so React does not report it yet. | -| `unknown` | Anything else, for example a handshake that never finished. | - -## Labels - -Every text the component renders comes from `labels`, with English defaults: - -```tsx - -``` - -A `placeholderLabel` (for example the device state) still takes precedence over `labels.connecting`. +[Stream tokens guide](stream-tokens.md) diff --git a/docs/stream-tokens.md b/docs/stream-tokens.md new file mode 100644 index 0000000..3a025fe --- /dev/null +++ b/docs/stream-tokens.md @@ -0,0 +1,199 @@ +← [README](../README.md) Β· [Partner guide](https://docs.mobilerun.ai/partners) + +# Stream tokens + +The object API helpers (`MobilerunSDK`, `devices.fromId`, `verifyWebhook`) require `@mobilerun/sdk` 6.2 or later. The `{ client, deviceId }` hook form works with older SDKs; the peer dependency range remains `>=2.0.0`. + +Keep the API key on your backend. Use `useDeviceStream` for the URL and device state, and supply a +`tokenProvider` that calls your backend for a fresh single-use stream token before every WebSocket +attempt, including retries. + +> **`MOBILERUN_API_KEY` is a secret API key β€” never ship it to the browser.** Only the server reads it. +> The device endpoint returns only `id`, `state`, and `streamUrl`, with missing values set to `null`. +> A separate POST endpoint returns a short-lived stream token scoped to that device; the browser SDK +> uses a placeholder key to call your backend. + +On your backend, register this handler for `GET /api/v1/devices/:id`, passing the routed device ID: + +```ts +import { MobilerunSDK } from '@mobilerun/sdk'; + +const sdk = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY, server only + +export async function getDevice(id: string): Promise { + // Authenticate the caller and check the device belongs to them before returning device metadata. + const device = await sdk.devices.get(id); + return Response.json({ + id: device.info?.id ?? null, + state: device.info?.state ?? null, + streamUrl: device.info?.streamUrl ?? null, + }); +} + +// Register for POST /api/v1/devices/:id/stream-key. +export async function mintStreamToken(deviceId: string): Promise { + // Authenticate the caller and authorize this device in your application first. + try { + const minted = await sdk.api.post<{ key: string; keyId: string; expiresAt: string }>( + '/identity/stream-keys', + { body: { deviceId, ttlSeconds: 120 }, maxRetries: 0 }, + ); + const { key, keyId, expiresAt } = minted; + return Response.json({ key, keyId, expiresAt }, { + status: 201, + headers: { 'Cache-Control': 'no-store' }, + }); + } catch (err) { + const { status } = err as { status?: number }; + const isUpstreamError = typeof status === 'number' && status >= 400 && status < 600; + return Response.json({ error: 'stream_key_mint_failed' }, { + status: isUpstreamError ? status : 502, + headers: { 'Cache-Control': 'no-store' }, + }); + } +} +``` + +During the naming transition, the existing wire routes retain `stream-key` / `stream-keys` +and the DTO retains `key` / `keyId`. These examples use the currently available API; a route/DTO +cutover follows the identity API separately. + +The public mint API is `POST /v1/identity/stream-keys`, authenticated with your server-held API key. +Its body is `{ deviceId, ttlSeconds? }`; TTL is 60–300 seconds, default 120. It returns HTTP 201 +with `{ key, keyId, expiresAt }` and `Cache-Control: no-store`. The SDK base URL already ends in +`/v1`, so use `/identity/stream-keys` with `sdk.api.post`. Revoke with +`DELETE /v1/identity/stream-keys/{keyId}`. Each stream token is single-use and device-scoped. `expiresAt` +is diagnostic metadata, not a browser permission or validity check. Do not log or cache stream tokens. +Your backend must authenticate callers and authorize the requested device; never accept an arbitrary +target URL or owner from the browser. Propagate mint refusal without returning upstream credential details. + +In your client component, point the SDK at that backend route, as in the example app: + +```tsx +'use client'; + +import { useCallback, useMemo } from 'react'; +import { MobilerunSDK } from '@mobilerun/sdk'; +import { DeviceStream, useDeviceStream } from '@mobilerun/react'; +import '@mobilerun/react/styles.css'; + +export function DevicePanel({ deviceId }: { deviceId: string }) { + const sdk = useMemo(() => new MobilerunSDK({ + apiKey: 'example-sdk-helper', // placeholder, not a Mobilerun API key + baseURL: typeof window === 'undefined' ? '/api/v1' : `${window.location.origin}/api/v1`, // SSR placeholder; the hook only fetches in the browser + }), []); + const { streamUrl, state, refetch } = useDeviceStream({ + device: sdk.devices.fromId(deviceId), // no request yet + }); + const getFreshStreamToken = useCallback(async () => { + const response = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { + method: 'POST', + cache: 'no-store', + }); + if (!response.ok) throw new Error('Stream token request failed'); + const { key } = await response.json(); + return key; + }, [deviceId]); + + return ( +
      + +
      + ); +} +``` + +### Without the hook + +Supply an existing stream URL and the same server-backed callback: + +```tsx + +``` + +`tokenProvider?: () => Promise` is supported by `DeviceStream` and `RemoteControl`. +It is awaited once immediately before each socket allocation. It takes precedence over static +`streamToken`/`token`; a rejection or empty stream token fails that attempt with no fallback. Pending results +after stop, device switch or unmount are ignored. Changing callback identity does not reconnect a +healthy stream. An ICE credential refresh on an existing socket does not call it again. +A server signaling close with code 1001 ends media/control in every mode and triggers the existing +bounded reconnect policy. Other signaling closes keep a connected media path running. Provider mode +mints a fresh stream token for each new socket. `onStreamHealed` can refresh URL/state; it is not per retry +and must not be used to cache a stream token. + +## Device token (legacy) + +Static `DeviceStream.streamToken`, `RemoteControl.token`, and the hook's returned `streamToken` are +**deprecated**, retained for existing consumers. `DeviceStream` logs one console warning per mount +when it runs on a static token; `tokenProvider` wins when both are given. + +**Exception to the no-reuse rule:** with a static token the SDK does not fetch anything new; it sends +the same value on the first connect and on every reconnect, until the device token (legacy) is removed. Stream +tokens are single-use, so a stream token passed statically that was already admitted or rejected fails the retry attempts +(`connection_refused`) and ends in the Retry state. A long-lived device token (legacy) keeps reconnecting. +`tokenProvider` is the recommended path and the only one that works with single-use stream tokens. Manual +URL/token mode is a device token (legacy) diagnostic path; a pasted single-use stream token cannot reconnect after admission. `useDeviceStream` also still accepts +`{ client, deviceId }` with a plain `Mobilerun` client. + +## Network recovery + +While the browser reports offline (`navigator.onLine === false` or an `offline` event), no new +`tokenProvider` call or socket allocation starts. Pending acquisition, retry waits and connect +watchdogs are cancelled; late provider results are ignored without an error. Retry, visibility +wake and target changes cannot bypass this pause. An advisory offline notification preserves +healthy media until its transport actually fails. + +A false-to-true network transition starts one immediate fresh attempt when a connection is needed, +resets backoff to attempt 0, and calls the latest provider for a new stream token. Duplicate online +events do nothing; a healthy stream is not remounted. Connectivity is only a scheduling hint, +not proof that the server is reachable. Existing labels and bounded retries still apply. + +`DeviceStream` manages this through `useStreamReconnect`. Direct `RemoteControl` or +`useWebRtcConnection` consumers get offline gating and cancellation, but must own remounting and +recovery (for example, with `useStreamReconnect`); the low-level socket hook does not retry on its +own. Observers detach on unmount. Custom lifecycle owners that remove an observer while a session +continues must replace that network source or forward availability to the controller themselves. + +## Errors + +`DeviceStream` calls `onError` once per failed connection attempt: + +```ts +onError?: (error: { + reason: 'credentials_unavailable' | 'connection_refused' | 'disconnected' | 'device_unavailable' | 'unknown'; + message: string; // fixed SDK text for logs, never exception text from your provider or the socket + attempt: number; // consecutive failed attempts in this cycle, from 1; the pill shows the same n as "(n/6)" + final: boolean; // true when the SDK stops retrying; the Retry button stays available +}) => void; +``` + +| `reason` | Meaning | +| --- | --- | +| `credentials_unavailable` | `tokenProvider` threw, rejected, returned an empty stream token or took longer than 10 s. Normal backoff applies. | +| `connection_refused` | The signaling socket closed before it opened. A browser cannot read the HTTP status, so a used, expired or revoked stream token, a wrong device and a refused origin all land here. Check the mint call first. | +| `disconnected` | An open session dropped, including the 30-minute server session cap. | +| `device_unavailable` | Reserved for a server message that the device is offline or not ready. The current signaling protocol has none, so React does not report it yet. | +| `unknown` | Anything else, for example a handshake that never finished. | + +## Labels + +Every text the component renders comes from `labels`, with English defaults: + +```tsx + +``` + +A `placeholderLabel` (for example the device state) still takes precedence over `labels.connecting`. diff --git a/example/main.tsx b/example/main.tsx index 3556102..16f4714 100644 --- a/example/main.tsx +++ b/example/main.tsx @@ -218,7 +218,7 @@ function SdkStream({ device: sdk.devices.fromId(deviceId), }); - const getFreshStreamKey = useCallback(async () => { + const getFreshStreamToken = useCallback(async () => { const res = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { method: 'POST', cache: 'no-store', @@ -237,12 +237,12 @@ function SdkStream({ onStatus({ streamError })} onConnectionStateChange={(c) => onStatus({ connected: c, ...(c ? { streamError: undefined } : {}) })} /> @@ -454,7 +454,7 @@ function App() { const [status, setStatus] = useState({ isLoading: false, connected: false }); const onStatus = useCallback((p: Partial) => setStatus((s) => ({ ...s, ...p })), []); - // Legacy diagnostic mode: pasted static tokens cannot renew single-use keys on retries. + // Device token (legacy) diagnostic mode: pasted tokens cannot renew single-use stream tokens on retries. const [streamUrl, setStreamUrl] = useState(''); const [streamToken, setStreamToken] = useState(''); const [applied, setApplied] = useState<{ url?: string; token?: string }>({}); @@ -564,7 +564,7 @@ function App() { setStreamUrl(e.target.value)} placeholder="wss://…" />
      - + setStreamToken(e.target.value)} placeholder="token…" />
      diff --git a/example/server.ts b/example/server.ts index 7434b09..84d49b0 100644 --- a/example/server.ts +++ b/example/server.ts @@ -4,16 +4,16 @@ // Dev harness server for the @mobilerun/react example. // // The stream WebSocket is not proxied: the browser connects to the SDK-provided -// streamUrl directly, and @mobilerun/react appends a fresh stream key as ?token=. +// streamUrl directly, and @mobilerun/react appends a fresh stream token as ?token=. // // For SDK mode, this Bun + Hono server exposes narrow endpoints that uses the -// official SDK to retrieve streamUrl and mint a key without exposing the parent API key: +// official SDK to retrieve streamUrl and mint a stream token without exposing the parent API key: // // browser ──(same-origin)──▢ this server ──(@mobilerun/sdk)──▢ API // // β€’ Serves the example UI (Bun bundles index.html + main.tsx). // β€’ GET /api/v1/devices/:deviceId returns id/state/streamUrl only. -// β€’ POST /api/v1/devices/:deviceId/stream-key mints one single-use key per attempt. +// β€’ POST /api/v1/devices/:deviceId/stream-key mints one single-use stream token per attempt. // β€’ Local use only: the server binds to 127.0.0.1 and its task routes and SSE // route are unauthenticated by design. If you expose anything publicly (e.g. a // tunnel for webhook testing), forward only /webhooks/mobilerun, never the @@ -230,7 +230,7 @@ if (import.meta.main) { console.log(`\n β–Έ @mobilerun/react dev harness http://localhost:${PORT}`); const upstreamUrl = sdk?.api.baseURL ?? 'https://api.mobilerun.ai/v1'; console.log(` β–Έ SDK helper GET /api/v1/devices/:id β†’ ${upstreamUrl}/devices/:id`); - console.log(' β–Έ stream key POST /api/v1/devices/:id/stream-key'); + console.log(' β–Έ stream token POST /api/v1/devices/:id/stream-key'); console.log( ' β–Έ approvals GET/POST /api/v1/tasks/:id… Β· POST /webhooks/mobilerun Β· GET /api/v1/events', ); diff --git a/src/components/device-stream.tsx b/src/components/device-stream.tsx index 2d6b916..889e5c1 100644 --- a/src/components/device-stream.tsx +++ b/src/components/device-stream.tsx @@ -21,14 +21,14 @@ import { useStreamReconnect } from '../hooks/use-stream-reconnect'; export interface DeviceStreamProps { streamUrl?: string; /** - * @deprecated A static key is single-use, so it cannot reconnect. Use `tokenProvider`, - * which returns a fresh key for every connection attempt. Logs one console warning per mount. + * @deprecated Device token (legacy). Use `tokenProvider` for a fresh stream token + * on every connection attempt. Logs one console warning per mount. */ streamToken?: string; /** * Called before every WebSocket attempt, the first connect and each reconnect, and returns - * a fresh stream key minted by your backend (`POST /v1/identity/stream-keys`). A key is never - * reused for a second connect. A throw, a rejection, an empty key or no answer within 10 s + * a fresh stream token minted by your backend (`POST /v1/identity/stream-keys`). A stream token is never + * reused for a second connect. A throw, a rejection, an empty stream token or no answer within 10 s * fails the attempt with reason `credentials_unavailable`. Wins over `streamToken`. */ tokenProvider?: () => Promise; diff --git a/src/components/remote-control.tsx b/src/components/remote-control.tsx index 287ea4b..99f87b6 100644 --- a/src/components/remote-control.tsx +++ b/src/components/remote-control.tsx @@ -22,9 +22,9 @@ interface RemoteControlProps { // url is the URL of the instance to connect to. url: string; - /** @deprecated Use tokenProvider to acquire a fresh key for each connection attempt. */ + /** @deprecated Device token (legacy). Use tokenProvider to acquire a fresh stream token for each connection attempt. */ token?: string; - /** Resolves a fresh stream key before each WebSocket attempt. Overrides token. */ + /** Resolves a fresh stream token before each WebSocket attempt. Overrides token. */ tokenProvider?: () => Promise; // className is the class name to apply to the component @@ -55,7 +55,7 @@ interface RemoteControlProps { // out a connect watchdog. // Receives the reason of the failure. onConnectionFailed?: (failure: StreamFailure) => void; - /** Fired when a socket is allocated, after any key provider resolves. */ + /** Fired when a socket is allocated, after any token provider resolves. */ onConnectionAttemptStarted?: () => void; // Override label for the corner pill shown while the WebRTC stream is diff --git a/src/hooks/use-device-stream.ts b/src/hooks/use-device-stream.ts index c1e9a93..2cd8221 100644 --- a/src/hooks/use-device-stream.ts +++ b/src/hooks/use-device-stream.ts @@ -61,7 +61,7 @@ export interface UseDeviceStreamDeviceOptions extends UseDeviceStreamBase { export interface UseDeviceStreamResult { /** WebRTC signaling URL β€” feed straight into ``. */ streamUrl?: string; - /** @deprecated Obtain a fresh key from your backend with ``. */ + /** @deprecated Device token (legacy). Obtain a fresh stream token from your backend with ``. */ streamToken?: string; /** The device's lifecycle state (`ready`, `assigned`, ...). */ state?: string; @@ -84,11 +84,11 @@ export interface UseDeviceStreamResult { * * ```tsx * const { streamUrl, state, refetch } = useDeviceStream({ device }); - * // getFreshStreamKey calls your authenticated backend's stream-key endpoint. + * // getFreshStreamToken calls your authenticated backend's stream-token endpoint. * return ( * { +test('a device token (legacy) warns once per mount, however often it re-renders', async () => { const { warnings, render } = await harness(); render(true); render(true); render(true); expect(warnings).toHaveLength(1); expect(warnings[0]).toContain('tokenProvider'); + expect(warnings[0]).toContain('device token (legacy)'); + expect(warnings[0]).toContain('fresh stream token'); }); test('no warning while a provider is in use', async () => { diff --git a/src/hooks/use-static-token-warning.ts b/src/hooks/use-static-token-warning.ts index 22d959d..fa83859 100644 --- a/src/hooks/use-static-token-warning.ts +++ b/src/hooks/use-static-token-warning.ts @@ -4,7 +4,7 @@ import { useEffect, useRef } from 'react'; -/** One console warning per mount while a deprecated static stream key is in use. */ +/** One console warning per mount while a device token (legacy) is in use. */ export function useStaticTokenWarning(usingStaticToken: boolean) { const warnedRef = useRef(false); useEffect(() => { @@ -12,7 +12,7 @@ export function useStaticTokenWarning(usingStaticToken: boolean) { warnedRef.current = true; // eslint-disable-next-line no-console -- one-time deprecation notice console.warn( - '[@mobilerun/react] DeviceStream `streamToken` is deprecated: a stream key is single-use and cannot reconnect. Pass `tokenProvider` to get a fresh key for every connection.', + '[@mobilerun/react] DeviceStream `streamToken` is deprecated (device token (legacy)). Pass `tokenProvider` to get a fresh stream token for every connection; a single-use stream token passed statically cannot reconnect.', ); }, [usingStaticToken]); } diff --git a/src/hooks/use-webrtc-connection.test.ts b/src/hooks/use-webrtc-connection.test.ts index c006b00..602a6c4 100644 --- a/src/hooks/use-webrtc-connection.test.ts +++ b/src/hooks/use-webrtc-connection.test.ts @@ -174,7 +174,7 @@ test('a queued ICE grace recheck cannot change replacement state', async () => { f.unmount(); }); -test('provider per socket awaits a fresh key for first connect and retry', async () => { +test('provider per socket awaits a fresh stream token for first connect and retry', async () => { const f = await fixture(); const first = deferred(); const second = deferred(); @@ -581,7 +581,7 @@ test('provider timeout reports credentials_unavailable', async () => { clock.advance(10_000); await tick(); expect(reasons(f)).toEqual(['credentials_unavailable']); - expect(f.failureInfos[0].message).toBe('Stream key provider failed'); + expect(f.failureInfos[0].message).toBe('Stream token provider failed'); f.unmount(); }); @@ -697,7 +697,7 @@ test.each([ f.mount('a', undefined, { tokenProvider }); await tick(); expect(reasons(f)).toEqual(['credentials_unavailable']); - expect(f.failureInfos[0].message).toBe('Stream key provider failed'); + expect(f.failureInfos[0].message).toBe('Stream token provider failed'); expectNoCredential(f, throughController(f.failureInfos)); f.unmount(); }); diff --git a/src/hooks/use-webrtc-connection.ts b/src/hooks/use-webrtc-connection.ts index 3f060e3..54f0468 100644 --- a/src/hooks/use-webrtc-connection.ts +++ b/src/hooks/use-webrtc-connection.ts @@ -34,7 +34,7 @@ function buildWebSocketUrl(url: string, token?: string): string { return wsUrl.toString(); } -// A stream key may only travel over TLS, except for local development sockets. +// A stream token may only travel over TLS, except for local development sockets. function isSecureStreamUrl(url: string): boolean { const resolved = new URL(url, window.location.href); if (resolved.protocol === 'wss:') return true; @@ -252,18 +252,18 @@ export function useWebRtcConnection({ try { let streamToken = tokenRef.current; if (provider) { - if (!isSecureStreamUrl(url)) throw new Error('Stream key requires a secure WebSocket URL'); + if (!isSecureStreamUrl(url)) throw new Error('Stream token requires a secure WebSocket URL'); let providerTimer: ReturnType | undefined; phase = 'credentials_unavailable'; try { streamToken = await new Promise((resolve, reject) => { providerTimer = setTimeout( - () => reject(new Error('Stream key provider timeout')), + () => reject(new Error('Stream token provider timeout')), STREAM_TOKEN_PROVIDER_TIMEOUT_MS, ); cancelStartup = () => { clearTimeout(providerTimer); - reject(new Error('Stream key request cancelled')); + reject(new Error('Stream token request cancelled')); }; cancelStartupRef.current = cancelStartup; if (isOffline()) { @@ -278,7 +278,7 @@ export function useWebRtcConnection({ if (cancelStartupRef.current === cancelStartup) cancelStartupRef.current = null; } if (!isActive()) return; - if (!streamToken?.trim()) throw new Error('Stream key provider returned an empty key'); + if (!streamToken?.trim()) throw new Error('Stream token provider returned an empty stream token'); phase = 'unknown'; } if (!isActive() || isOffline()) return; @@ -759,7 +759,7 @@ export function useWebRtcConnection({ updateStatus(provider ? 'Stream connection attempt failed' : 'Error: ' + e); failAttempt({ reason: phase, - // Never forward `e.message`: provider and socket errors can carry the key or a ?token= URL. + // Never forward `e.message`: provider and socket errors can carry the token or a ?token= URL. message: STREAM_FAILURE_MESSAGES[phase], }); } diff --git a/src/lib/stream-error.ts b/src/lib/stream-error.ts index 59a97b7..94b01c0 100644 --- a/src/lib/stream-error.ts +++ b/src/lib/stream-error.ts @@ -4,9 +4,9 @@ /** * Why a stream connection attempt failed (stream client contract v1). * - * - `credentials_unavailable`: `tokenProvider` threw, timed out or returned an empty key. + * - `credentials_unavailable`: `tokenProvider` threw, timed out or returned an empty stream token. * - `connection_refused`: the signaling WebSocket closed before it opened. A browser cannot - * see the HTTP status, so a rejected, used or expired key, a wrong device and a refused + * see the HTTP status, so a rejected, used or expired stream token, a wrong device and a refused * origin all land here. * - `disconnected`: an open session dropped (includes the server's session cap). * - `device_unavailable`: the server reported the device offline or not ready. The current @@ -23,7 +23,7 @@ export type StreamErrorReason = /** * What a single failed attempt looked like, before the reconnect policy adds its counters. * `message` is always SDK-owned text: exception messages from `tokenProvider` or the socket - * can carry a stream key or a `?token=` URL and are never forwarded. + * can carry a stream token or a `?token=` URL and are never forwarded. */ export interface StreamFailure { reason: StreamErrorReason; @@ -32,7 +32,7 @@ export interface StreamFailure { /** Fixed, credential-free text for a failure whose cause is an arbitrary exception. */ export const STREAM_FAILURE_MESSAGES: Record = { - credentials_unavailable: 'Stream key provider failed', + credentials_unavailable: 'Stream token provider failed', connection_refused: 'Signaling connection closed before it opened', disconnected: 'The stream connection dropped', device_unavailable: 'The device is unavailable', From dcbcbba08f5f3bb0a12256cb2dc5ed103285c9dc Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Mon, 23 Nov 2026 09:06:22 +0100 Subject: [PATCH 14/22] fix(stream): offline edge cases --- CONTRIBUTING.md | 2 +- README.md | 2 +- src/hooks/use-static-token-warning.ts | 2 +- src/hooks/use-stream-reconnect.test.ts | 82 ++++++++++++++++++++++--- src/hooks/use-stream-reconnect.ts | 13 ++-- src/hooks/use-webrtc-connection.test.ts | 53 ++++++++++++++++ src/hooks/use-webrtc-connection.ts | 36 +++++------ src/hooks/webrtc-test-fixture.ts | 1 + src/lib/browser-network.ts | 7 +++ src/lib/stream-reconnect.test.ts | 38 ++++++++++++ src/lib/stream-reconnect.ts | 22 +++---- 11 files changed, 210 insertions(+), 48 deletions(-) create mode 100644 src/lib/browser-network.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c78120d..d4ba83c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,7 +18,7 @@ The control messages, signalling frames, reconnect policy and input routing are ## Example app The repo ships the playground shown in the [README](README.md). Set the API key server-side and enter a device id; -manual URL/token mode remains available for device token (legacy) diagnostics: +manual URL/token mode remains available for diagnostics with the legacy `streamToken` prop (device token): ```sh bun install diff --git a/README.md b/README.md index 0983d35..919bef8 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ The [full example](https://github.com/droidrun/mobilerun-react/blob/main/docs/st `tokenProvider` runs before every connection attempt, the first one and each reconnect, and the SDK never reuses a token it returns. **Use it: stream tokens are single-use, so only a provider can reconnect.** -The device token (legacy) `streamToken` prop is **deprecated** and an explicit exception to that rule: it is kept until the +The legacy `streamToken` prop (device token) is **deprecated** and an explicit exception to that rule: it is kept until the device token (legacy) is removed, and the SDK passes the same value again on every reconnect. A single-use stream token given this way is rejected on the second attempt, so the stream ends in the Retry state (`connection_refused`). The component logs one console warning per mount. diff --git a/src/hooks/use-static-token-warning.ts b/src/hooks/use-static-token-warning.ts index fa83859..4e363e4 100644 --- a/src/hooks/use-static-token-warning.ts +++ b/src/hooks/use-static-token-warning.ts @@ -12,7 +12,7 @@ export function useStaticTokenWarning(usingStaticToken: boolean) { warnedRef.current = true; // eslint-disable-next-line no-console -- one-time deprecation notice console.warn( - '[@mobilerun/react] DeviceStream `streamToken` is deprecated (device token (legacy)). Pass `tokenProvider` to get a fresh stream token for every connection; a single-use stream token passed statically cannot reconnect.', + '[@mobilerun/react] DeviceStream `streamToken` is deprecated; it is a device token (legacy). Pass `tokenProvider` to get a fresh stream token for every connection; a single-use stream token passed statically cannot reconnect.', ); }, [usingStaticToken]); } diff --git a/src/hooks/use-stream-reconnect.test.ts b/src/hooks/use-stream-reconnect.test.ts index c1538fc..619b26c 100644 --- a/src/hooks/use-stream-reconnect.test.ts +++ b/src/hooks/use-stream-reconnect.test.ts @@ -24,19 +24,19 @@ async function reconnectFixture(online = true, enabled = true) { Math: { ...Math, random: () => 0.5, min: Math.min, max: Math.max, round: Math.round }, }, ); - const render = (target = 'a', onHeal = heal) => { + const render = (target = 'a', onHeal = heal, commit = true) => { runner.beginRender(); const result = runner.module.exports.useStreamReconnect({ target, targetKey: target, enabled, watchdogFromSocket: true, onHeal, onError: error, }); - runner.flushEffects(); + if (commit) runner.flushEffects(); return result; }; const network = (available: boolean) => { navigator.onLine = available; listeners[available ? 'online' : 'offline'].forEach(fn => fn()); }; - return { clock, listeners, heal, error, render, network, unmount: runner.unmount }; + return { clock, listeners, heal, error, render, network, navigator, commit: runner.flushEffects, unmount: runner.unmount }; } test('initial offline, target change, visibility and retry wait for one fresh online attempt', async () => { @@ -48,11 +48,12 @@ test('initial offline, target change, visibility and retry wait for one fresh on f.mount(result.activeTarget, undefined, { tokenProvider: provider }); result.retry(); r.listeners.visibilitychange.forEach(fn => fn()); - result = r.render('b'); + r.render('b'); + result = r.render('b'); // Settle React's render-phase target update. r.clock.advance(45_001); await tick(); - expect(result.streamKey).toBe('0'); - expect(result.activeTarget).toBe('a'); + expect(result.streamKey).toBe('1'); + expect(result.activeTarget).toBe('b'); expect(provider).not.toHaveBeenCalled(); expect(f.sockets).toHaveLength(0); expect(r.error).not.toHaveBeenCalled(); @@ -63,7 +64,7 @@ test('initial offline, target change, visibility and retry wait for one fresh on f.networkChange(true); f.mount(result.activeTarget, undefined, { tokenProvider: provider }); await tick(); - expect(result.streamKey).toBe('1'); + expect(result.streamKey).toBe('2'); expect(result.activeTarget).toBe('b'); expect(result.attempt).toBe(0); expect(provider).toHaveBeenCalledTimes(1); @@ -92,6 +93,7 @@ test('network return resets high backoff, uses latest callback and ignores the o result.retry(); r.listeners.visibilitychange.forEach(fn => fn()); r.render('new', latestHeal); + r.render('new', latestHeal); r.clock.advance(60_000); await tick(); r.network(true); @@ -101,7 +103,7 @@ test('network return resets high backoff, uses latest callback and ignores the o stale.onConnectionAttemptStarted(); r.network(true); result = r.render('new', latestHeal); - expect(result.streamKey).toBe('3'); + expect(result.streamKey).toBe('4'); expect(result.activeTarget).toBe('new'); expect(result.attempt).toBe(0); expect(result.status).toBe('reconnecting'); @@ -139,3 +141,67 @@ test('online with no target asks the discovery owner to refresh once', async () expect(r.render().streamKey).toBe('0'); r.unmount(); }); + +test('offline switch from connected A to B tears down A and acquires B once on return', async () => { + const r = await reconnectFixture(); + const f = await fixture(); + const provider = mock(async () => 'fresh'); + let result = r.render(); + f.mount(result.activeTarget, undefined, { tokenProvider: provider }); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + const oldPeer = f.peers[0]; + oldPeer.connectionState = 'connected'; + oldPeer.onconnectionstatechange!(); + result.onConnectionStateChange(true); + r.network(false); + f.networkChange(false); + r.render('b'); + r.render('b'); + result = r.render('b'); // Observe the snapshot emitted by the new mount's layout effect. + expect(result.activeTarget).toBe('b'); + expect(result.status).toBe('connecting'); + f.mount(result.activeTarget, undefined, { tokenProvider: provider }); + await tick(); + expect(oldPeer.closed).toBe(true); + expect(oldPeer.channels.map(channel => channel.closed)).toEqual([true, true]); + expect(f.sockets[0].readyState).toBe(3); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + r.network(true); + f.networkChange(true); + result = r.render('b'); + f.mount(result.activeTarget, undefined, { tokenProvider: provider }); + await tick(); + expect(result.attempt).toBe(0); + expect(result.status).toBe('reconnecting'); + expect(result.streamKey).toBe('2'); + expect(provider).toHaveBeenCalledTimes(2); + expect(f.sockets).toHaveLength(2); + expect(f.sockets[1].url).toContain('/b?'); + r.unmount(); + f.unmount(); +}); + +test('offline render followed by online commit starts one provider call without remount', async () => { + const r = await reconnectFixture(false); + const f = await fixture(); + const provider = mock(async () => 'fresh'); + r.render('a', r.heal, false); + r.navigator.onLine = true; + r.commit(); + const result = r.render(); + f.mount(result.activeTarget, undefined, { tokenProvider: provider, onConnectionAttemptStarted: result.onConnectionAttemptStarted }); + await tick(); + expect(result.streamKey).toBe('0'); + expect(result.status).toBe('connecting'); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + expect(r.heal).not.toHaveBeenCalled(); + expect(r.clock.pendingCount).toBe(1); // The one allocated socket owns its watchdog. + r.unmount(); + f.unmount(); +}); diff --git a/src/hooks/use-stream-reconnect.ts b/src/hooks/use-stream-reconnect.ts index e3b2eaf..b74fd9d 100644 --- a/src/hooks/use-stream-reconnect.ts +++ b/src/hooks/use-stream-reconnect.ts @@ -4,6 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; import type { StreamError, StreamFailure } from '../lib/stream-error'; +import { browserReportsOnline } from '../lib/browser-network'; import { createStreamReconnectController, type StreamReconnectSnapshot } from '../lib/stream-reconnect'; interface UseStreamReconnectOptions { @@ -94,7 +95,7 @@ export function useStreamReconnect({ const controllerRef = useRef | null>(null); if (controllerRef.current === null) { controllerRef.current = createStreamReconnectController({ - networkAvailable: typeof navigator === 'undefined' || navigator.onLine !== false, + networkAvailable: browserReportsOnline(), onRemount: bumpMount, onSnapshot: (s) => setSnapshot(s), onHeal: () => onHealRef.current?.(), @@ -124,6 +125,12 @@ export function useStreamReconnect({ controllerRef.current?.attemptMounted(); }, [mount.epoch]); + // Seed commit-time connectivity before the child's passive startup. A render + // that saw offline must not cause a second mount if startup now sees online. + useLayoutEffect(() => { + controllerRef.current?.setNetworkAvailable(browserReportsOnline(), true); + }, []); + // Enable failure accounting before the child's passive startup effect, so // synchronous failures count too. DeviceStream defers the watchdog to its // socket event; existing hook consumers keep mount-driven arming. @@ -143,10 +150,6 @@ export function useStreamReconnect({ }; const onOnline = () => controllerRef.current?.setNetworkAvailable(true); const onOffline = () => controllerRef.current?.setNetworkAvailable(false); - // Re-read after commit in case connectivity changed between render and effects. - controllerRef.current?.setNetworkAvailable( - typeof navigator === 'undefined' || navigator.onLine !== false, - ); document.addEventListener('visibilitychange', onVisibility); window.addEventListener('online', onOnline); window.addEventListener('offline', onOffline); diff --git a/src/hooks/use-webrtc-connection.test.ts b/src/hooks/use-webrtc-connection.test.ts index 602a6c4..ed029a5 100644 --- a/src/hooks/use-webrtc-connection.test.ts +++ b/src/hooks/use-webrtc-connection.test.ts @@ -792,3 +792,56 @@ test('advisory offline preserves connected media and online allocates no second expect(f.failures).toEqual([]); f.unmount(); }); + +test('offline during ICE restart grace preserves media and control through peer recovery', async () => { + const clock = new FakeSchedule(); + const f = await fixture(clock); + await f.negotiate(); + const pc = f.peers[0]; + pc.connectionState = 'connected'; + pc.onconnectionstatechange!(); + pc.ontrack({ track: { kind: 'video' } }); + const media = f.video.current.srcObject; + const restart = f.sockets[0].onmessage!(event({ type: 'rtcConfiguration', rtcConfiguration: { iceServers: [] } })); + pc.connectionState = 'connecting'; + pc.onconnectionstatechange!(); + f.networkChange(false); + await tick(); + expect(pc.closed).toBe(false); + expect(pc.channels.map(channel => channel.closed)).toEqual([false, false]); + expect(f.video.current.srcObject).toBe(media); + expect(f.states).toEqual([true]); + clock.advance(14_999); + expect(f.states).toEqual([true]); + pc.connectionState = 'connected'; + pc.onconnectionstatechange!(); + clock.advance(1); + pc.offer.resolve({ sdp: 'restart' }); + await tick(); + pc.local.resolve(); + await restart; + f.networkChange(true); + await tick(); + expect(pc.closed).toBe(false); + expect(f.sockets).toHaveLength(1); + expect(f.failures).toEqual([]); + f.unmount(); +}); + +test('offline reports a previously connected stalled peer before stopping it', async () => { + const f = await fixture(); + await f.negotiate(); + const pc = f.peers[0]; + pc.connectionState = 'connected'; + pc.onconnectionstatechange!(); + pc.connectionState = 'disconnected'; // No state event has reported this dip yet. + const close = pc.close.bind(pc); + let statesAtClose: boolean[] = []; + pc.close = () => { statesAtClose = [...f.states]; close(); }; + f.networkChange(false); + await tick(); + expect(statesAtClose).toEqual([true, false]); + expect(pc.closed).toBe(true); + expect(f.failures).toEqual([]); + f.unmount(); +}); diff --git a/src/hooks/use-webrtc-connection.ts b/src/hooks/use-webrtc-connection.ts index 54f0468..6e2ce1c 100644 --- a/src/hooks/use-webrtc-connection.ts +++ b/src/hooks/use-webrtc-connection.ts @@ -12,6 +12,7 @@ import { } from '../lib/stream-reconnect'; import { STREAM_FAILURE_MESSAGES, type StreamErrorReason, type StreamFailure } from '../lib/stream-error'; import { createRTCConfigurationRequest } from '../webrtc-messages'; +import { browserReportsOnline } from '../lib/browser-network'; const debugLog = (...args: any[]) => { if (window.debugRemoteControl) { @@ -96,13 +97,16 @@ export function useWebRtcConnection({ const tokenProviderRef = useRef(tokenProvider); tokenProviderRef.current = tokenProvider; const attemptGenerationRef = useRef(0); - const networkAvailableRef = useRef(typeof navigator === 'undefined' || navigator.onLine !== false); - const isOffline = () => !networkAvailableRef.current || - (typeof navigator !== 'undefined' && navigator.onLine === false); + const lastReportedConnectedRef = useRef(false); const onConnectionStateChangeRef = useRef(onConnectionStateChange); onConnectionStateChangeRef.current = onConnectionStateChange; + const reportConnectionState = (connected: boolean) => { + lastReportedConnectedRef.current = connected; + onConnectionStateChangeRef.current?.(connected); + }; + const onConnectionAttemptStartedRef = useRef(onConnectionAttemptStarted); onConnectionAttemptStartedRef.current = onConnectionAttemptStarted; @@ -174,7 +178,7 @@ export function useWebRtcConnection({ if (state === 'connected') return; updateStatus('ICE-restart grace expired, reporting state: ' + state); setIsConnected(false); - onConnectionStateChangeRef.current?.(false); + reportConnectionState(false); }, Math.max(0, iceRestartGraceUntilRef.current - Date.now()), ); @@ -215,7 +219,7 @@ export function useWebRtcConnection({ }; const start = async () => { - if (isOffline()) return; + if (!browserReportsOnline()) return; const generation = ++attemptGenerationRef.current; const provider = tokenProviderRef.current; const isActive = () => attemptGenerationRef.current === generation; @@ -228,7 +232,7 @@ export function useWebRtcConnection({ if (failed) return; failed = true; if (stopMedia) { - onConnectionStateChangeRef.current?.(false); + reportConnectionState(false); stop(); } onConnectionFailedRef.current?.(failure); @@ -266,11 +270,6 @@ export function useWebRtcConnection({ reject(new Error('Stream token request cancelled')); }; cancelStartupRef.current = cancelStartup; - if (isOffline()) { - ++attemptGenerationRef.current; - cancelStartup(); - return; - } Promise.resolve(provider()).then(resolve, reject); }); } finally { @@ -281,7 +280,7 @@ export function useWebRtcConnection({ if (!streamToken?.trim()) throw new Error('Stream token provider returned an empty stream token'); phase = 'unknown'; } - if (!isActive() || isOffline()) return; + if (!isActive() || !browserReportsOnline()) return; const wsUrl = buildWebSocketUrl(url, streamToken); const ws = new WebSocket(wsUrl); attemptWs = ws; @@ -538,7 +537,7 @@ export function useWebRtcConnection({ } clearRestartRecheck(); setIsConnected(connected); - onConnectionStateChangeRef.current?.(connected); + reportConnectionState(connected); }; pc.oniceconnectionstatechange = () => { @@ -807,20 +806,20 @@ export function useWebRtcConnection({ hoverChannelRef.current.close(); hoverChannelRef.current = null; } + lastReportedConnectedRef.current = false; setIsConnected(false); updateStatus('Stopped'); }; useEffect(() => { // Connectivity only gates/cancels here; useStreamReconnect owns recovery. - networkAvailableRef.current = typeof navigator === 'undefined' || navigator.onLine !== false; const onOffline = () => { - networkAvailableRef.current = false; - if (peerConnectionRef.current?.connectionState !== 'connected') stop(); + if (peerConnectionRef.current?.connectionState === 'connected' || + Date.now() < iceRestartGraceUntilRef.current) return; + if (lastReportedConnectedRef.current) reportConnectionState(false); + stop(); }; - const onOnline = () => { networkAvailableRef.current = true; }; window.addEventListener('offline', onOffline); - window.addEventListener('online', onOnline); start(); // Add visibility change listener @@ -836,7 +835,6 @@ export function useWebRtcConnection({ stop(); document.removeEventListener('visibilitychange', onVisibilityChange); window.removeEventListener('offline', onOffline); - window.removeEventListener('online', onOnline); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- intentional: reconnect only on url/session change; start/stop/keepAlive helpers are re-created each render and must not be deps }, [url, sessionId]); diff --git a/src/hooks/webrtc-test-fixture.ts b/src/hooks/webrtc-test-fixture.ts index 65b9503..8b82174 100644 --- a/src/hooks/webrtc-test-fixture.ts +++ b/src/hooks/webrtc-test-fixture.ts @@ -120,6 +120,7 @@ export async function fixture(clock?: FakeSchedule) { location: { href: 'https://example.invalid' }, }, document, URL, MediaStream: FakeMediaStream, + Date: clock ? class extends Date { static now() { return clock.now; } } : Date, WebSocket: FakeSocket, RTCPeerConnection: FakePeer, RTCRtpReceiver: { getCapabilities: () => null }, RTCSessionDescription: class { constructor(value: object) { Object.assign(this, value); } }, diff --git a/src/lib/browser-network.ts b/src/lib/browser-network.ts new file mode 100644 index 0000000..20bfb20 --- /dev/null +++ b/src/lib/browser-network.ts @@ -0,0 +1,7 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +/** Unknown browser connectivity is optimistic; this is only a scheduling hint. */ +export function browserReportsOnline(): boolean { + return typeof navigator === 'undefined' || navigator.onLine !== false; +} diff --git a/src/lib/stream-reconnect.test.ts b/src/lib/stream-reconnect.test.ts index f9b4de5..a155d11 100644 --- a/src/lib/stream-reconnect.test.ts +++ b/src/lib/stream-reconnect.test.ts @@ -581,3 +581,41 @@ describe('network availability', () => { controller.dispose(); }); }); + +// Fix round 1: advisory offline does not interrupt a stable media session. +test('stability budget and heal cadence survive connected offline online transitions', () => { + const { controller, schedule, calls } = setup(); + controller.attemptMounted(); + controller.handleFailure(); + schedule.advance(1_000); + controller.attemptMounted(); + controller.handleConnected(); + schedule.advance(10_000); + controller.setNetworkAvailable(false); + schedule.advance(10_000); + controller.setNetworkAvailable(true); + schedule.advance(9_999); + expect(controller.getSnapshot()).toEqual({ status: 'connected', attempt: 1 }); + schedule.advance(1); + expect(controller.getSnapshot()).toEqual({ status: 'connected', attempt: 0 }); + controller.handleDisconnected(); + expect(calls.heals).toBe(2); // A new failure heals anew after stability. + expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 1 }); + controller.dispose(); +}); + +test('a peer connecting while offline still refills its stability budget', () => { + const { controller, schedule, calls } = setup(); + controller.attemptMounted(); + controller.handleFailure(); + schedule.advance(1_000); + controller.attemptMounted(); + controller.setNetworkAvailable(false); + controller.handleConnected(); + schedule.advance(30_000); + expect(controller.getSnapshot()).toEqual({ status: 'connected', attempt: 0 }); + controller.setNetworkAvailable(true); + controller.handleDisconnected(); + expect(calls.heals).toBe(2); + controller.dispose(); +}); diff --git a/src/lib/stream-reconnect.ts b/src/lib/stream-reconnect.ts index 4a632fd..4da0575 100644 --- a/src/lib/stream-reconnect.ts +++ b/src/lib/stream-reconnect.ts @@ -108,8 +108,8 @@ export interface StreamReconnectController { * disabled β€” the new target applies immediately. */ shouldDeferTargetChange(): boolean; - /** Observe browser connectivity; only false β†’ true starts a fresh cycle. */ - setNetworkAvailable(available: boolean): void; + /** Observe connectivity; initial commit only seeds a still-fresh connecting attempt. */ + setNetworkAvailable(available: boolean, initialCommit?: boolean): void; /** Tab became visible. */ handleWake(): void; /** Manual retry (Unavailable-state button). */ @@ -207,7 +207,6 @@ export function createStreamReconnectController({ healedThisCycle = true; onHeal(); } - if (!networkAvailable) return; backoffTimer = schedule.setTimeout( () => { backoffTimer = null; @@ -234,7 +233,6 @@ export function createStreamReconnectController({ attemptMounted(startWatchdog = true) { enabled = true; disposed = false; - if (!networkAvailable) return; // Mid-wait mounts are stale (StrictMode remount): the scheduled // attempt owns the next watchdog. if (backoffTimer !== null || status === 'unavailable') return; @@ -248,7 +246,7 @@ export function createStreamReconnectController({ status = 'connecting'; emit(); } - if (!startWatchdog) return; + if (!networkAvailable || !startWatchdog) return; watchdogTimer = schedule.setTimeout(() => { watchdogTimer = null; countFailure({ reason: 'unknown', message: 'Connection attempt timed out' }); @@ -282,7 +280,6 @@ export function createStreamReconnectController({ emit(); } stabilityTimer = clearTimer(stabilityTimer); - if (!networkAvailable) return; stabilityTimer = schedule.setTimeout(() => { stabilityTimer = null; // The cycle is over β€” the next failure run heals anew. @@ -312,18 +309,17 @@ export function createStreamReconnectController({ // retry has started; outside the two deferred states the change must // apply immediately or an in-flight attempt would run on stale // credentials until the connect watchdog fails it. - return !networkAvailable || backoffTimer !== null || status === 'unavailable'; + return backoffTimer !== null || status === 'unavailable'; }, - setNetworkAvailable(available) { + setNetworkAvailable(available, initialCommit = false) { if (disposed || available === networkAvailable) return; networkAvailable = available; - clearAllTimers(); + watchdogTimer = clearTimer(watchdogTimer); + backoffTimer = clearTimer(backoffTimer); if (!available) return; - if (status === 'connected') { - emit(); // Let the hook apply a target change held back while offline. - return; - } + if (status === 'connected') return; + if (initialCommit && status === 'connecting' && attempt === 0) return; if (enabled) freshCycle(); else onHeal(); // No target yet: its existing owner resumes discovery. }, From 23410fc08f00234f60d4ec4669d2c5421e4ccb3b Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Mon, 23 Nov 2026 09:26:18 +0100 Subject: [PATCH 15/22] feat(stream): retry overrides offline --- docs/stream-tokens.md | 6 +- src/components/device-stream.tsx | 2 + src/components/remote-control.tsx | 4 ++ src/hooks/use-stream-reconnect.test.ts | 86 +++++++++++++++++++++++-- src/hooks/use-stream-reconnect.ts | 18 ++++-- src/hooks/use-webrtc-connection.test.ts | 15 +++++ src/hooks/use-webrtc-connection.ts | 8 ++- src/hooks/webrtc-test-fixture.ts | 1 + src/lib/stream-reconnect.test.ts | 42 +++++++++++- src/lib/stream-reconnect.ts | 35 ++++++---- 10 files changed, 187 insertions(+), 30 deletions(-) diff --git a/docs/stream-tokens.md b/docs/stream-tokens.md index 3a025fe..fe5b171 100644 --- a/docs/stream-tokens.md +++ b/docs/stream-tokens.md @@ -145,8 +145,10 @@ URL/token mode is a device token (legacy) diagnostic path; a pasted single-use s While the browser reports offline (`navigator.onLine === false` or an `offline` event), no new `tokenProvider` call or socket allocation starts. Pending acquisition, retry waits and connect -watchdogs are cancelled; late provider results are ignored without an error. Retry, visibility -wake and target changes cannot bypass this pause. An advisory offline notification preserves +watchdogs are cancelled; late provider results are ignored without an error. An explicit Retry overrides +this hint for one fresh attempt (direct `useStreamReconnect` consumers forward its `allowOffline` +value to the socket hook/component); if it fails offline, the failure is reported once and automatic +retries, visibility wake and target changes remain gated until online. An advisory offline notification preserves healthy media until its transport actually fails. A false-to-true network transition starts one immediate fresh attempt when a connection is needed, diff --git a/src/components/device-stream.tsx b/src/components/device-stream.tsx index 889e5c1..9a35931 100644 --- a/src/components/device-stream.tsx +++ b/src/components/device-stream.tsx @@ -96,6 +96,7 @@ export const DeviceStream = forwardRef(f const { streamKey, activeTarget, + allowOffline, status, attempt, onConnectionStateChange: onReconnectConnectionChange, @@ -155,6 +156,7 @@ export const DeviceStream = forwardRef(f url={activeTarget.url ?? streamUrl} token={activeTarget.token} tokenProvider={tokenProvider} + allowOffline={allowOffline} className="w-full h-full" onConnectionStateChange={handleConnectionStateChange} onConnectionFailed={onConnectionFailed} diff --git a/src/components/remote-control.tsx b/src/components/remote-control.tsx index 99f87b6..bd79e3b 100644 --- a/src/components/remote-control.tsx +++ b/src/components/remote-control.tsx @@ -26,6 +26,8 @@ interface RemoteControlProps { token?: string; /** Resolves a fresh stream token before each WebSocket attempt. Overrides token. */ tokenProvider?: () => Promise; + /** Permit one explicitly requested Retry mount despite advisory offline. */ + allowOffline?: boolean; // className is the class name to apply to the component // on top of the default styles. @@ -129,6 +131,7 @@ export const RemoteControl = forwardRef url, token, tokenProvider, + allowOffline, sessionId: propSessionId, openUrl, onConnectionStateChange, @@ -162,6 +165,7 @@ export const RemoteControl = forwardRef url, token, tokenProvider, + allowOffline, sessionId, openUrl, videoRef, diff --git a/src/hooks/use-stream-reconnect.test.ts b/src/hooks/use-stream-reconnect.test.ts index 619b26c..3fe879e 100644 --- a/src/hooks/use-stream-reconnect.test.ts +++ b/src/hooks/use-stream-reconnect.test.ts @@ -3,6 +3,7 @@ import { expect, mock, test } from 'bun:test'; import { FakeSchedule } from '../lib/test-clock'; +import type { StreamError, StreamFailure } from '../lib/stream-error'; import { runHook, tick } from './test-hook-runner'; import { fixture } from './webrtc-test-fixture'; import type { useStreamReconnect } from './use-stream-reconnect'; @@ -16,7 +17,7 @@ async function reconnectFixture(online = true, enabled = true) { removeEventListener(name: keyof typeof listeners, fn: () => void) { listeners[name].delete(fn); }, }; const heal = mock(() => {}); - const error = mock(() => {}); + const error = mock((_error: StreamError) => {}); const runner = await runHook<{ useStreamReconnect: typeof useStreamReconnect }>( import.meta.dir + '/use-stream-reconnect.ts', { navigator, window: events, document: { ...events, visibilityState: 'visible' }, @@ -39,14 +40,13 @@ async function reconnectFixture(online = true, enabled = true) { return { clock, listeners, heal, error, render, network, navigator, commit: runner.flushEffects, unmount: runner.unmount }; } -test('initial offline, target change, visibility and retry wait for one fresh online attempt', async () => { +test('initial offline, target change and visibility wait for one fresh online attempt', async () => { const r = await reconnectFixture(false); const f = await fixture(); f.networkChange(false); let result = r.render(); const provider = mock(async () => 'fresh'); f.mount(result.activeTarget, undefined, { tokenProvider: provider }); - result.retry(); r.listeners.visibilitychange.forEach(fn => fn()); r.render('b'); result = r.render('b'); // Settle React's render-phase target update. @@ -90,7 +90,6 @@ test('network return resets high backoff, uses latest callback and ignores the o const stale = result; const latestHeal = mock(() => {}); r.network(false); - result.retry(); r.listeners.visibilitychange.forEach(fn => fn()); r.render('new', latestHeal); r.render('new', latestHeal); @@ -205,3 +204,82 @@ test('offline render followed by online commit starts one provider call without r.unmount(); f.unmount(); }); + +test('explicit Retry offline opens once, reports one failure and resumes once online', async () => { + const r = await reconnectFixture(false); + const f = await fixture(); + f.networkChange(false); + const provider = mock(async () => 'fresh'); + let result = r.render(); + f.mount(result.activeTarget, undefined, { tokenProvider: provider, allowOffline: result.allowOffline }); + r.listeners.visibilitychange.forEach(fn => fn()); + r.clock.advance(60_000); + await tick(); + expect(provider).not.toHaveBeenCalled(); + expect(f.sockets).toHaveLength(0); + result.retry(); + result = r.render(); + f.mount(result.activeTarget, undefined, { + tokenProvider: provider, allowOffline: result.allowOffline, + onConnectionAttemptStarted: result.onConnectionAttemptStarted, + }); + await tick(); + expect(result.streamKey).toBe('1'); + expect(result.allowOffline).toBe(true); + expect(result.attempt).toBe(0); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + expect(r.clock.pendingCount).toBe(1); + f.sockets[0].close(1006); + await tick(); + result.onConnectionFailed(f.failureInfos[0] as StreamFailure); + result.onConnectionFailed(f.failureInfos[0] as StreamFailure); + result = r.render(); + expect(r.error.mock.calls).toEqual([[{ + reason: 'connection_refused', message: 'Signaling connection closed before it opened', attempt: 1, final: false, + }]]); + expect(r.clock.pendingCount).toBe(0); + r.listeners.visibilitychange.forEach(fn => fn()); + r.clock.advance(60_000); + await tick(); + expect(r.render().streamKey).toBe('1'); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + r.network(true); + f.networkChange(true); + result = r.render(); + f.mount(result.activeTarget, undefined, { tokenProvider: provider, allowOffline: result.allowOffline }); + await tick(); + r.network(true); + r.listeners.visibilitychange.forEach(fn => fn()); + expect(result.streamKey).toBe('2'); + expect(result.allowOffline).toBe(false); + expect(result.attempt).toBe(0); + expect(provider).toHaveBeenCalledTimes(2); + expect(f.sockets).toHaveLength(2); + r.unmount(); + f.unmount(); +}); + +test('an automatic target change cannot reuse the explicit offline Retry permission', async () => { + const r = await reconnectFixture(false); + const f = await fixture(); + f.networkChange(false); + const provider = mock(async () => 'fresh'); + let result = r.render(); + result.retry(); + result = r.render(); + f.mount(result.activeTarget, undefined, { tokenProvider: provider, allowOffline: result.allowOffline }); + await tick(); + expect(provider).toHaveBeenCalledTimes(1); + r.render('b'); + result = r.render('b'); + f.mount(result.activeTarget, undefined, { tokenProvider: provider, allowOffline: result.allowOffline }); + await tick(); + expect(result.allowOffline).toBe(false); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + expect(f.sockets[0].readyState).toBe(3); + r.unmount(); + f.unmount(); +}); diff --git a/src/hooks/use-stream-reconnect.ts b/src/hooks/use-stream-reconnect.ts index b74fd9d..17fcfe4 100644 --- a/src/hooks/use-stream-reconnect.ts +++ b/src/hooks/use-stream-reconnect.ts @@ -45,7 +45,7 @@ interface UseStreamReconnectOptions { * when the tab becomes visible / the browser comes back online / `retry()` * is called. * - * Forward `onConnectionStateChange` and `onConnectionFailed` to the stream + * Forward `onConnectionStateChange`, `onConnectionFailed` and `allowOffline` to the stream * component; render status/attempt as the user-facing connection state. */ export function useStreamReconnect({ @@ -62,7 +62,9 @@ export function useStreamReconnect({ }); // The mount epoch and the target that mount uses advance atomically, so a // remounted stream never renders one commit on a stale target. - const [mount, setMount] = useState<{ epoch: number; target: T }>(() => ({ epoch: 0, target })); + const [mount, setMount] = useState<{ epoch: number; target: T; allowOffline: boolean }>( + () => ({ epoch: 0, target, allowOffline: false }), + ); // Key of the last APPLIED target β€” the comparison base for detecting // pending target changes. Deliberately not advanced when a change is // deferred; see the render-phase check below. @@ -85,9 +87,9 @@ export function useStreamReconnect({ // Applying a target always records its key too, so a change that was // pending while deferred is not re-applied a second time afterwards. - const bumpMount = useCallback(() => { + const bumpMount = useCallback((allowOffline = false) => { setLastTargetKey(targetKeyRef.current); - setMount((m) => ({ epoch: m.epoch + 1, target: targetRef.current })); + setMount((m) => ({ epoch: m.epoch + 1, target: targetRef.current, allowOffline })); }, []); // Lazy-initialized once; stable for the component's lifetime, so effects @@ -116,13 +118,13 @@ export function useStreamReconnect({ // the next committed render instead of being consumed and lost. if (lastTargetKey !== targetKey && !controllerRef.current.shouldDeferTargetChange()) { setLastTargetKey(targetKey); - setMount((m) => ({ epoch: m.epoch + 1, target })); + setMount((m) => ({ epoch: m.epoch + 1, target, allowOffline: false })); } const activeEpochRef = useRef(mount.epoch); const onConnectionAttemptStarted = useCallback(() => { if (activeEpochRef.current !== mount.epoch) return; - controllerRef.current?.attemptMounted(); + controllerRef.current?.attemptMounted(true, mount.allowOffline); }, [mount.epoch]); // Seed commit-time connectivity before the child's passive startup. A render @@ -137,7 +139,7 @@ export function useStreamReconnect({ useLayoutEffect(() => { activeEpochRef.current = mount.epoch; if (enabled) { - controllerRef.current?.attemptMounted(!watchdogFromSocket); + controllerRef.current?.attemptMounted(!watchdogFromSocket, mount.allowOffline); } else { controllerRef.current?.setDisabled(); } @@ -183,6 +185,8 @@ export function useStreamReconnect({ streamKey: String(mount.epoch), /** The pinned target to render the stream from β€” NOT the raw props. */ activeTarget: mount.target, + /** Forward to the socket hook/component for this explicit Retry mount only. */ + allowOffline: mount.allowOffline, status: snapshot.status, attempt: snapshot.attempt, onConnectionStateChange, diff --git a/src/hooks/use-webrtc-connection.test.ts b/src/hooks/use-webrtc-connection.test.ts index ed029a5..03db81d 100644 --- a/src/hooks/use-webrtc-connection.test.ts +++ b/src/hooks/use-webrtc-connection.test.ts @@ -845,3 +845,18 @@ test('offline reports a previously connected stalled peer before stopping it', a expect(f.failures).toEqual([]); f.unmount(); }); + +test('an explicit offline Retry ignores offline notifications while awaiting its fresh token', async () => { + const f = await fixture(); + const pending = deferred(); + const provider = mock(() => pending.promise); + f.networkChange(false); + f.mount('a', undefined, { tokenProvider: provider, allowOffline: true }); + f.networkChange(false); + pending.resolve('fresh'); + await tick(); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + expect(f.failures).toEqual([]); + f.unmount(); +}); diff --git a/src/hooks/use-webrtc-connection.ts b/src/hooks/use-webrtc-connection.ts index 6e2ce1c..5de1cd4 100644 --- a/src/hooks/use-webrtc-connection.ts +++ b/src/hooks/use-webrtc-connection.ts @@ -51,6 +51,8 @@ interface UseWebRtcConnectionOptions { url: string; token?: string; tokenProvider?: () => Promise; + /** Set by an explicit Retry mount; automatic mounts leave this false. */ + allowOffline?: boolean; sessionId: string; openUrl?: string; videoRef: React.RefObject; @@ -84,6 +86,7 @@ export function useWebRtcConnection({ url, token, tokenProvider, + allowOffline = false, sessionId, openUrl, videoRef, @@ -219,7 +222,7 @@ export function useWebRtcConnection({ }; const start = async () => { - if (!browserReportsOnline()) return; + if (!allowOffline && !browserReportsOnline()) return; const generation = ++attemptGenerationRef.current; const provider = tokenProviderRef.current; const isActive = () => attemptGenerationRef.current === generation; @@ -280,7 +283,7 @@ export function useWebRtcConnection({ if (!streamToken?.trim()) throw new Error('Stream token provider returned an empty stream token'); phase = 'unknown'; } - if (!isActive() || !browserReportsOnline()) return; + if (!isActive() || (!allowOffline && !browserReportsOnline())) return; const wsUrl = buildWebSocketUrl(url, streamToken); const ws = new WebSocket(wsUrl); attemptWs = ws; @@ -814,6 +817,7 @@ export function useWebRtcConnection({ useEffect(() => { // Connectivity only gates/cancels here; useStreamReconnect owns recovery. const onOffline = () => { + if (allowOffline) return; if (peerConnectionRef.current?.connectionState === 'connected' || Date.now() < iceRestartGraceUntilRef.current) return; if (lastReportedConnectedRef.current) reportConnectionState(false); diff --git a/src/hooks/webrtc-test-fixture.ts b/src/hooks/webrtc-test-fixture.ts index 8b82174..bac0c1d 100644 --- a/src/hooks/webrtc-test-fixture.ts +++ b/src/hooks/webrtc-test-fixture.ts @@ -138,6 +138,7 @@ export async function fixture(clock?: FakeSchedule) { url?: string; token?: string; tokenProvider?: () => Promise; + allowOffline?: boolean; onConnectionAttemptStarted?: () => void; }; const render = (id = 'a', openUrl?: string, credentials: Credentials = {}) => { diff --git a/src/lib/stream-reconnect.test.ts b/src/lib/stream-reconnect.test.ts index a155d11..8450982 100644 --- a/src/lib/stream-reconnect.test.ts +++ b/src/lib/stream-reconnect.test.ts @@ -532,7 +532,6 @@ describe('network availability', () => { controller.setNetworkAvailable(false); expect(schedule.pendingCount).toBe(0); controller.handleWake(); - controller.retry(); controller.attemptMounted(); schedule.advance(45_001); expect(controller.getSnapshot()).toEqual({ status: 'connecting', attempt: 0 }); @@ -556,7 +555,6 @@ describe('network availability', () => { controller.handleFailure(); expect(controller.getSnapshot()).toEqual({ status: 'unavailable', attempt: 7 }); controller.setNetworkAvailable(false); - controller.retry(); controller.handleWake(); expect(calls.remounts).toBe(6); controller.setNetworkAvailable(true); @@ -619,3 +617,43 @@ test('a peer connecting while offline still refills its stability budget', () => expect(calls.heals).toBe(2); controller.dispose(); }); + +test('offline explicit Retry resets the counter and a timed out forced attempt waits for online', () => { + const schedule = new FakeSchedule(); + const remounts: (boolean | undefined)[] = []; + const errors: object[] = []; + const controller = createStreamReconnectController({ + schedule, random: NO_JITTER, onRemount: allowOffline => remounts.push(allowOffline), + onHeal: () => {}, onSnapshot: () => {}, onError: error => errors.push(error), + }); + controller.attemptMounted(); + controller.handleFailure(); + schedule.advance(1_000); + controller.attemptMounted(); + controller.handleFailure(); + expect(controller.getSnapshot().attempt).toBe(2); + controller.setNetworkAvailable(false); + controller.retry(); + expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 0 }); + expect(remounts).toEqual([false, true]); + controller.attemptMounted(true, true); + schedule.advance(44_999); + expect(errors).toHaveLength(2); + schedule.advance(1); + expect(errors).toEqual([ + { reason: 'unknown', message: 'Connection failed', attempt: 1, final: false }, + { reason: 'unknown', message: 'Connection failed', attempt: 2, final: false }, + { reason: 'unknown', message: 'Connection attempt timed out', attempt: 1, final: false }, + ]); + controller.handleFailure(); + controller.handleWake(); + schedule.advance(60_000); + expect(remounts).toEqual([false, true]); + expect(schedule.pendingCount).toBe(0); + expect(errors).toHaveLength(3); + controller.setNetworkAvailable(true); + controller.setNetworkAvailable(true); + expect(remounts).toEqual([false, true, false]); + expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 0 }); + controller.dispose(); +}); diff --git a/src/lib/stream-reconnect.ts b/src/lib/stream-reconnect.ts index 4da0575..f22e050 100644 --- a/src/lib/stream-reconnect.ts +++ b/src/lib/stream-reconnect.ts @@ -77,7 +77,7 @@ export interface StreamReconnectSchedule { export interface StreamReconnectControllerOptions { /** Bump the mount epoch β€” remounts the stream component. */ - onRemount(): void; + onRemount(allowOffline?: boolean): void; /** Status/attempt changed. */ onSnapshot(snapshot: StreamReconnectSnapshot): void; /** A reconnect attempt is being scheduled β€” refetch stream credentials. */ @@ -92,7 +92,7 @@ export interface StreamReconnectControllerOptions { export interface StreamReconnectController { /** Begin an attempt; defer the watchdog until socket allocation when false. */ - attemptMounted(startWatchdog?: boolean): void; + attemptMounted(startWatchdog?: boolean, allowOffline?: boolean): void; /** No stream target anymore (URL gone) β€” stop timers, reset counters. */ setDisabled(): void; handleConnected(): void; @@ -112,7 +112,7 @@ export interface StreamReconnectController { setNetworkAvailable(available: boolean, initialCommit?: boolean): void; /** Tab became visible. */ handleWake(): void; - /** Manual retry (Unavailable-state button). */ + /** Manual retry; explicitly overrides advisory offline for one fresh attempt. */ retry(): void; dispose(): void; getSnapshot(): StreamReconnectSnapshot; @@ -129,6 +129,7 @@ export function createStreamReconnectController({ }: StreamReconnectControllerOptions): StreamReconnectController { let enabled = false; let disposed = false; + let forcedAttempt = false; let status: StreamReconnectStatus = 'connecting'; let attempt = 0; // Whether the current mount epoch ever reached 'connected'. Gates @@ -171,9 +172,9 @@ export function createStreamReconnectController({ } }; - const startAttempt = () => { - if (!enabled || !networkAvailable || disposed) return; - onRemount(); + const startAttempt = (allowOffline = false) => { + if (!enabled || (!networkAvailable && !allowOffline) || disposed) return; + onRemount(allowOffline); // The resulting mount calls attemptMounted(), which arms the watchdog. }; @@ -181,7 +182,8 @@ export function createStreamReconnectController({ // A wait is already scheduled (or we already gave up) β€” e.g. a stale // watchdog armed by a StrictMode double-mount. Never stack timers. if (backoffTimer !== null || status === 'unavailable') return; - if (!networkAvailable && !everConnectedThisEpoch) return; + if (!networkAvailable && !everConnectedThisEpoch && !forcedAttempt) return; + forcedAttempt = false; failureLatched = true; watchdogTimer = clearTimer(watchdogTimer); stabilityTimer = clearTimer(stabilityTimer); @@ -216,7 +218,8 @@ export function createStreamReconnectController({ ); }; - const freshCycle = () => { + const freshCycle = (allowOffline = false) => { + forcedAttempt = allowOffline; attempt = 0; failureLatched = false; everConnectedThisEpoch = false; @@ -226,11 +229,12 @@ export function createStreamReconnectController({ status = 'reconnecting'; emit(); onHeal(); - startAttempt(); + startAttempt(allowOffline); }; return { - attemptMounted(startWatchdog = true) { + attemptMounted(startWatchdog = true, allowOffline = false) { + forcedAttempt = allowOffline; enabled = true; disposed = false; // Mid-wait mounts are stale (StrictMode remount): the scheduled @@ -246,7 +250,7 @@ export function createStreamReconnectController({ status = 'connecting'; emit(); } - if (!networkAvailable || !startWatchdog) return; + if ((!networkAvailable && !forcedAttempt) || !startWatchdog) return; watchdogTimer = schedule.setTimeout(() => { watchdogTimer = null; countFailure({ reason: 'unknown', message: 'Connection attempt timed out' }); @@ -254,6 +258,7 @@ export function createStreamReconnectController({ }, setDisabled() { + forcedAttempt = false; enabled = false; disposed = false; clearAllTimers(); @@ -339,11 +344,15 @@ export function createStreamReconnectController({ }, retry() { - if (!enabled || !networkAvailable) return; - if (status === 'unavailable') freshCycle(); + if (!enabled) return; + if (!networkAvailable || status === 'unavailable') { + clearAllTimers(); + freshCycle(!networkAvailable); + } }, dispose() { + forcedAttempt = false; disposed = true; enabled = false; clearAllTimers(); From 3de3ff16c731ea47c0c2789c08d9f8a0e41cb61b Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Mon, 23 Nov 2026 10:06:38 +0100 Subject: [PATCH 16/22] fix(stream): offline retry edges --- docs/stream-tokens.md | 7 +- src/hooks/use-stream-reconnect.test.ts | 133 +++++++++++++++++++++++-- src/hooks/use-stream-reconnect.ts | 8 +- src/lib/stream-reconnect.test.ts | 24 ++++- src/lib/stream-reconnect.ts | 36 +++++-- 5 files changed, 183 insertions(+), 25 deletions(-) diff --git a/docs/stream-tokens.md b/docs/stream-tokens.md index fe5b171..a6e41ed 100644 --- a/docs/stream-tokens.md +++ b/docs/stream-tokens.md @@ -149,12 +149,15 @@ watchdogs are cancelled; late provider results are ignored without an error. An this hint for one fresh attempt (direct `useStreamReconnect` consumers forward its `allowOffline` value to the socket hook/component); if it fails offline, the failure is reported once and automatic retries, visibility wake and target changes remain gated until online. An advisory offline notification preserves -healthy media until its transport actually fails. +healthy media until its transport actually fails. Retry is ignored while connected or while an explicit +attempt is still live; otherwise an offline pause shows `unavailable` with the default Retry action. A false-to-true network transition starts one immediate fresh attempt when a connection is needed, resets backoff to attempt 0, and calls the latest provider for a new stream token. Duplicate online events do nothing; a healthy stream is not remounted. Connectivity is only a scheduling hint, -not proof that the server is reachable. Existing labels and bounded retries still apply. +not proof that the server is reachable. A forced attempt with an allocated socket continues when online +returns, while a forced provider wait is discarded for a fresh attempt. Existing labels and bounded +retries still apply. `DeviceStream` manages this through `useStreamReconnect`. Direct `RemoteControl` or `useWebRtcConnection` consumers get offline gating and cancellation, but must own remounting and diff --git a/src/hooks/use-stream-reconnect.test.ts b/src/hooks/use-stream-reconnect.test.ts index 3fe879e..f019d2b 100644 --- a/src/hooks/use-stream-reconnect.test.ts +++ b/src/hooks/use-stream-reconnect.test.ts @@ -5,7 +5,7 @@ import { expect, mock, test } from 'bun:test'; import { FakeSchedule } from '../lib/test-clock'; import type { StreamError, StreamFailure } from '../lib/stream-error'; import { runHook, tick } from './test-hook-runner'; -import { fixture } from './webrtc-test-fixture'; +import { deferred, fixture } from './webrtc-test-fixture'; import type { useStreamReconnect } from './use-stream-reconnect'; async function reconnectFixture(online = true, enabled = true) { @@ -45,6 +45,7 @@ test('initial offline, target change and visibility wait for one fresh online at const f = await fixture(); f.networkChange(false); let result = r.render(); + expect(result.status).toBe('unavailable'); const provider = mock(async () => 'fresh'); f.mount(result.activeTarget, undefined, { tokenProvider: provider }); r.listeners.visibilitychange.forEach(fn => fn()); @@ -52,8 +53,8 @@ test('initial offline, target change and visibility wait for one fresh online at result = r.render('b'); // Settle React's render-phase target update. r.clock.advance(45_001); await tick(); - expect(result.streamKey).toBe('1'); - expect(result.activeTarget).toBe('b'); + expect(result.streamKey).toBe('0'); + expect(result.activeTarget).toBe('a'); expect(provider).not.toHaveBeenCalled(); expect(f.sockets).toHaveLength(0); expect(r.error).not.toHaveBeenCalled(); @@ -64,7 +65,7 @@ test('initial offline, target change and visibility wait for one fresh online at f.networkChange(true); f.mount(result.activeTarget, undefined, { tokenProvider: provider }); await tick(); - expect(result.streamKey).toBe('2'); + expect(result.streamKey).toBe('1'); expect(result.activeTarget).toBe('b'); expect(result.attempt).toBe(0); expect(provider).toHaveBeenCalledTimes(1); @@ -102,7 +103,7 @@ test('network return resets high backoff, uses latest callback and ignores the o stale.onConnectionAttemptStarted(); r.network(true); result = r.render('new', latestHeal); - expect(result.streamKey).toBe('4'); + expect(result.streamKey).toBe('3'); expect(result.activeTarget).toBe('new'); expect(result.attempt).toBe(0); expect(result.status).toBe('reconnecting'); @@ -162,7 +163,7 @@ test('offline switch from connected A to B tears down A and acquires B once on r r.render('b'); result = r.render('b'); // Observe the snapshot emitted by the new mount's layout effect. expect(result.activeTarget).toBe('b'); - expect(result.status).toBe('connecting'); + expect(result.status).toBe('unavailable'); f.mount(result.activeTarget, undefined, { tokenProvider: provider }); await tick(); expect(oldPeer.closed).toBe(true); @@ -236,8 +237,9 @@ test('explicit Retry offline opens once, reports one failure and resumes once on result.onConnectionFailed(f.failureInfos[0] as StreamFailure); result = r.render(); expect(r.error.mock.calls).toEqual([[{ - reason: 'connection_refused', message: 'Signaling connection closed before it opened', attempt: 1, final: false, + reason: 'connection_refused', message: 'Signaling connection closed before it opened', attempt: 1, final: true, }]]); + expect(result.status).toBe('unavailable'); expect(r.clock.pendingCount).toBe(0); r.listeners.visibilitychange.forEach(fn => fn()); r.clock.advance(60_000); @@ -283,3 +285,120 @@ test('an automatic target change cannot reuse the explicit offline Retry permiss r.unmount(); f.unmount(); }); + +test('offline Retry keeps healthy media without minting or remounting', async () => { + const r = await reconnectFixture(); + const f = await fixture(); + const provider = mock(async () => 'fresh'); + let result = r.render(); + f.mount('a', undefined, { tokenProvider: provider }); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + const pc = f.peers[0]; + pc.connectionState = 'connected'; + pc.onconnectionstatechange!(); + pc.ontrack({ track: { kind: 'video' } }); + const media = f.video.current.srcObject; + result.onConnectionStateChange(true); + r.network(false); + f.networkChange(false); + result.retry(); + result.retry(); + result = r.render(); + await tick(); + expect(result.streamKey).toBe('0'); + expect(result.status).toBe('connected'); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + expect(pc.closed).toBe(false); + expect(pc.channels.map(channel => channel.closed)).toEqual([false, false]); + expect(f.video.current.srcObject).toBe(media); + r.unmount(); + f.unmount(); +}); + +test('offline Retry double taps share one live provider and socket attempt', async () => { + const r = await reconnectFixture(false); + const f = await fixture(); + f.networkChange(false); + const pending = deferred(); + const provider = mock(() => pending.promise); + let result = r.render(); + result.retry(); + result.retry(); // Before React commits the requested mount. + result = r.render(); + f.mount('a', undefined, { tokenProvider: provider, allowOffline: result.allowOffline, onConnectionAttemptStarted: result.onConnectionAttemptStarted }); + result.retry(); // The provider is still live. + expect(r.render().streamKey).toBe('1'); + pending.resolve('fresh'); + await tick(); + result.retry(); // The socket is now live. + expect(r.render().streamKey).toBe('1'); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + expect(r.heal).toHaveBeenCalledTimes(1); + r.unmount(); + f.unmount(); +}); + +test.each([['opening', 0], ['open', 1]] as const)('online return keeps the forced %s socket and its original watchdog', async (phase, expectedReadyState) => { + const r = await reconnectFixture(false); + const f = await fixture(); + f.networkChange(false); + const provider = mock(async () => 'fresh'); + let result = r.render(); + result.retry(); + result = r.render(); + f.mount('a', undefined, { tokenProvider: provider, allowOffline: result.allowOffline, onConnectionAttemptStarted: result.onConnectionAttemptStarted }); + await tick(); + const socket = f.sockets[0]; + const enterPhase = { opening: () => {}, open: () => socket.open() }; + enterPhase[phase](); + await tick(); + r.clock.advance(10_000); + r.network(true); + f.networkChange(true); + result = r.render(); + await tick(); + expect(result.streamKey).toBe('1'); + expect(provider).toHaveBeenCalledTimes(1); + expect(f.sockets).toHaveLength(1); + expect(socket.readyState).toBe(expectedReadyState); + expect(r.clock.pendingCount).toBe(1); + expect(r.heal).toHaveBeenCalledTimes(1); + r.clock.advance(34_999); + expect(r.error).not.toHaveBeenCalled(); + r.clock.advance(1); + expect(r.error).toHaveBeenCalledTimes(1); // Online did not reset the 45s deadline. + r.unmount(); + f.unmount(); +}); + +test('online return discards a forced provider wait before opening one fresh socket', async () => { + const r = await reconnectFixture(false); + const f = await fixture(); + f.networkChange(false); + const pending = deferred(); + const provider = mock(async () => 'fresh').mockImplementationOnce(() => pending.promise); + let result = r.render(); + result.retry(); + result = r.render(); + f.mount('a', undefined, { tokenProvider: provider, allowOffline: result.allowOffline, onConnectionAttemptStarted: result.onConnectionAttemptStarted }); + r.network(true); + f.networkChange(true); + result = r.render(); + f.mount('a', undefined, { tokenProvider: provider, allowOffline: result.allowOffline, onConnectionAttemptStarted: result.onConnectionAttemptStarted }); + pending.resolve('obsolete'); + await tick(); + expect(result.streamKey).toBe('2'); + expect(result.allowOffline).toBe(false); + expect(provider).toHaveBeenCalledTimes(2); + expect(f.sockets).toHaveLength(1); + expect(f.failures).toEqual([]); + expect(r.error).not.toHaveBeenCalled(); + r.unmount(); + f.unmount(); +}); diff --git a/src/hooks/use-stream-reconnect.ts b/src/hooks/use-stream-reconnect.ts index 17fcfe4..8103605 100644 --- a/src/hooks/use-stream-reconnect.ts +++ b/src/hooks/use-stream-reconnect.ts @@ -56,10 +56,10 @@ export function useStreamReconnect({ enabled, watchdogFromSocket = false, }: UseStreamReconnectOptions) { - const [snapshot, setSnapshot] = useState({ - status: 'connecting', + const [snapshot, setSnapshot] = useState(() => ({ + status: browserReportsOnline() ? 'connecting' : 'unavailable', attempt: 0, - }); + })); // The mount epoch and the target that mount uses advance atomically, so a // remounted stream never renders one commit on a stale target. const [mount, setMount] = useState<{ epoch: number; target: T; allowOffline: boolean }>( @@ -124,7 +124,7 @@ export function useStreamReconnect({ const activeEpochRef = useRef(mount.epoch); const onConnectionAttemptStarted = useCallback(() => { if (activeEpochRef.current !== mount.epoch) return; - controllerRef.current?.attemptMounted(true, mount.allowOffline); + controllerRef.current?.attemptMounted(true, mount.allowOffline, true); }, [mount.epoch]); // Seed commit-time connectivity before the child's passive startup. A render diff --git a/src/lib/stream-reconnect.test.ts b/src/lib/stream-reconnect.test.ts index 8450982..5ffee67 100644 --- a/src/lib/stream-reconnect.test.ts +++ b/src/lib/stream-reconnect.test.ts @@ -19,7 +19,7 @@ import { FakeSchedule } from './test-clock'; const NO_JITTER = () => 0.5; const DELAYS = [1000, 2000, 4000, 8000, 16000, 30000]; -function setup() { +function setup(networkAvailable = true) { const schedule = new FakeSchedule(); const calls = { remounts: 0, heals: 0 }; const snapshots: StreamReconnectSnapshot[] = []; @@ -34,6 +34,7 @@ function setup() { snapshots.push(s); }, schedule, + networkAvailable, random: NO_JITTER, }); // Simulate React: every remount request results in a mounted attempt. @@ -534,7 +535,7 @@ describe('network availability', () => { controller.handleWake(); controller.attemptMounted(); schedule.advance(45_001); - expect(controller.getSnapshot()).toEqual({ status: 'connecting', attempt: 0 }); + expect(controller.getSnapshot()).toEqual({ status: 'unavailable', attempt: 0 }); expect(schedule.pendingCount).toBe(0); expect(calls).toEqual({ remounts: 0, heals: 0 }); controller.setNetworkAvailable(true); @@ -573,7 +574,7 @@ describe('network availability', () => { controller.handleDisconnected(); controller.handleFailure(); schedule.advance(60_000); - expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 1 }); + expect(controller.getSnapshot()).toEqual({ status: 'unavailable', attempt: 1 }); expect(schedule.pendingCount).toBe(0); expect(calls).toEqual({ remounts: 0, heals: 0 }); controller.dispose(); @@ -643,7 +644,7 @@ test('offline explicit Retry resets the counter and a timed out forced attempt w expect(errors).toEqual([ { reason: 'unknown', message: 'Connection failed', attempt: 1, final: false }, { reason: 'unknown', message: 'Connection failed', attempt: 2, final: false }, - { reason: 'unknown', message: 'Connection attempt timed out', attempt: 1, final: false }, + { reason: 'unknown', message: 'Connection attempt timed out', attempt: 1, final: true }, ]); controller.handleFailure(); controller.handleWake(); @@ -657,3 +658,18 @@ test('offline explicit Retry resets the counter and a timed out forced attempt w expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 0 }); controller.dispose(); }); + +test('initial offline state offers Retry and network return starts one fresh cycle', () => { + const { controller, calls, schedule } = setup(false); + expect(controller.getSnapshot()).toEqual({ status: 'unavailable', attempt: 0 }); + controller.attemptMounted(false); + controller.handleWake(); + schedule.advance(60_000); + expect(controller.getSnapshot()).toEqual({ status: 'unavailable', attempt: 0 }); + expect(calls.remounts).toBe(0); + controller.setNetworkAvailable(true); + controller.setNetworkAvailable(true); + expect(controller.getSnapshot()).toEqual({ status: 'reconnecting', attempt: 0 }); + expect(calls.remounts).toBe(1); + controller.dispose(); +}); diff --git a/src/lib/stream-reconnect.ts b/src/lib/stream-reconnect.ts index f22e050..2f42f63 100644 --- a/src/lib/stream-reconnect.ts +++ b/src/lib/stream-reconnect.ts @@ -91,8 +91,8 @@ export interface StreamReconnectControllerOptions { } export interface StreamReconnectController { - /** Begin an attempt; defer the watchdog until socket allocation when false. */ - attemptMounted(startWatchdog?: boolean, allowOffline?: boolean): void; + /** Begin an attempt; false defers the watchdog. fromSocket marks actual socket allocation. */ + attemptMounted(startWatchdog?: boolean, allowOffline?: boolean, fromSocket?: boolean): void; /** No stream target anymore (URL gone) β€” stop timers, reset counters. */ setDisabled(): void; handleConnected(): void; @@ -130,7 +130,8 @@ export function createStreamReconnectController({ let enabled = false; let disposed = false; let forcedAttempt = false; - let status: StreamReconnectStatus = 'connecting'; + let socketStarted = false; + let status: StreamReconnectStatus = networkAvailable ? 'connecting' : 'unavailable'; let attempt = 0; // Whether the current mount epoch ever reached 'connected'. Gates // handleDisconnected: the peer connection reports non-connected states @@ -188,7 +189,7 @@ export function createStreamReconnectController({ watchdogTimer = clearTimer(watchdogTimer); stabilityTimer = clearTimer(stabilityTimer); attempt += 1; - if (attempt > STREAM_RECONNECT_MAX_ATTEMPTS) { + if (!networkAvailable || attempt > STREAM_RECONNECT_MAX_ATTEMPTS) { status = 'unavailable'; emit(); reportError(failure, true); @@ -204,7 +205,6 @@ export function createStreamReconnectController({ // Credentials fetched at cycle start stay fresh across the cycle's ~2min // span, and a refresh that resolves after a retry started still applies // via shouldDeferTargetChange/onRemount. - if (!networkAvailable) return; if (!healedThisCycle) { healedThisCycle = true; onHeal(); @@ -220,6 +220,7 @@ export function createStreamReconnectController({ const freshCycle = (allowOffline = false) => { forcedAttempt = allowOffline; + socketStarted = false; attempt = 0; failureLatched = false; everConnectedThisEpoch = false; @@ -233,10 +234,17 @@ export function createStreamReconnectController({ }; return { - attemptMounted(startWatchdog = true, allowOffline = false) { + attemptMounted(startWatchdog = true, allowOffline = false, fromSocket = false) { forcedAttempt = allowOffline; + socketStarted = fromSocket; enabled = true; disposed = false; + if (!networkAvailable && !forcedAttempt) { + clearAllTimers(); + status = 'unavailable'; + emit(); + return; + } // Mid-wait mounts are stale (StrictMode remount): the scheduled // attempt owns the next watchdog. if (backoffTimer !== null || status === 'unavailable') return; @@ -320,11 +328,22 @@ export function createStreamReconnectController({ setNetworkAvailable(available, initialCommit = false) { if (disposed || available === networkAvailable) return; networkAvailable = available; + if (forcedAttempt && socketStarted) return; watchdogTimer = clearTimer(watchdogTimer); backoffTimer = clearTimer(backoffTimer); - if (!available) return; + if (!available) { + if (status !== 'connected' && !forcedAttempt) { + status = 'unavailable'; + emit(); + } + return; + } if (status === 'connected') return; - if (initialCommit && status === 'connecting' && attempt === 0) return; + if (initialCommit && attempt === 0) { + status = 'connecting'; + emit(); + return; + } if (enabled) freshCycle(); else onHeal(); // No target yet: its existing owner resumes discovery. }, @@ -345,6 +364,7 @@ export function createStreamReconnectController({ retry() { if (!enabled) return; + if (!networkAvailable && (status === 'connected' || forcedAttempt)) return; if (!networkAvailable || status === 'unavailable') { clearAllTimers(); freshCycle(!networkAvailable); From 9f6ca5b3b4de24fa6a1351837f50f07e42ac7801 Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Mon, 23 Nov 2026 17:02:10 +0100 Subject: [PATCH 17/22] docs(stream): add device stream skill --- README.md | 2 + skills/mobilerun-device-stream/SKILL.md | 180 ++++++++++++++++++++++++ 2 files changed, 182 insertions(+) create mode 100644 skills/mobilerun-device-stream/SKILL.md diff --git a/README.md b/README.md index 919bef8..404519c 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,8 @@ default. Add `.dark` to an ancestor, or to the component root, for the bundled d ## Guides +Coding agents: [Mobilerun device stream skill](https://github.com/droidrun/mobilerun-react/blob/main/skills/mobilerun-device-stream/SKILL.md). + | Guide | Covers | | --- | --- | | [Stream tokens](https://github.com/droidrun/mobilerun-react/blob/main/docs/stream-tokens.md) | Server routes, device metadata, `tokenProvider`, retries and device tokens (legacy). | diff --git a/skills/mobilerun-device-stream/SKILL.md b/skills/mobilerun-device-stream/SKILL.md new file mode 100644 index 0000000..5847e5c --- /dev/null +++ b/skills/mobilerun-device-stream/SKILL.md @@ -0,0 +1,180 @@ +--- +name: mobilerun-device-stream +description: Use when integrating a live Mobilerun device into a React partner app with server-minted stream tokens, reconnect handling, labels and theming. +--- + +# Mobilerun device stream for React + +## When to use + +Use `@mobilerun/react` to embed live WebRTC video and device control in a React 18 or 19 app. +Install `@mobilerun/react`, its peer `@mobilerun/sdk`, `react` and `react-dom`. +Use a browser with WebRTC. Keep device authorization and token minting on your backend. + +## Backend: mint one token per connect + +Call `POST https://api.mobilerun.ai/v1/identity/stream-keys` with the server's API key from +`MOBILERUN_API_KEY`. The body is `{ deviceId, ttlSeconds, allowedOrigins? }` and the response is +`{ key, keyId, expiresAt }` (HTTP 201). `ttlSeconds` defaults to 120 seconds (range 60–300). +Tokens start with `dr_st_`; `dr_sk_` can appear during the prefix transition. Treat both as opaque. +Each token is single-use. `allowedOrigins` binds browser use to the listed sites, for example +`['https://partner.example']`; configure the list on the server. + +The following server-only helper uses `MobilerunSDK` from `@mobilerun/sdk` 6.2+. +Register it behind your application's authenticated +`POST /api/v1/devices/:id/stream-key` route. **Before calling it, authorize the caller for that +device.** This helper is not an authentication implementation. + +```ts +import { MobilerunSDK } from '@mobilerun/sdk'; + +const sdk = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY on the server + +export async function mintStreamToken(deviceId: string): Promise { + const { key, keyId, expiresAt } = await sdk.api.post<{ + key: string; keyId: string; expiresAt: string; + }>('/identity/stream-keys', { + body: { + deviceId, + ttlSeconds: 120, + allowedOrigins: ['https://partner.example'], // replace with your browser app's origin + }, + maxRetries: 0, + }); + return Response.json({ key, keyId, expiresAt }, { + status: 201, + headers: { 'Cache-Control': 'no-store' }, + }); +} +``` + +The SDK base URL already includes `/v1`; pass `/identity/stream-keys` to `sdk.api.post`. +The route and response fields still use the transitional `stream-keys`, `key` and `keyId` names. +Handle mint errors in your route without exposing upstream credential details. + +## Client: a fresh token for every connection + +Supply the device's `streamUrl` obtained through your authorized backend. Its usual form is +`wss://api.mobilerun.ai/v1/devices/{deviceId}/stream`; the component appends `?token=` itself. +The application route below is your own backend route, not a React SDK endpoint. + +```tsx +'use client'; + +import { useCallback } from 'react'; +import { DeviceStream } from '@mobilerun/react'; +import '@mobilerun/react/styles.css'; + +export function DevicePanel({ deviceId, streamUrl }: { + deviceId: string; + streamUrl: string; +}) { + const tokenProvider = useCallback(async (): Promise => { + const res = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { + method: 'POST', + cache: 'no-store', + }); + if (!res.ok) throw new Error('Stream token request failed'); + const { key } = await res.json(); + if (typeof key !== 'string' || !key) throw new Error('Missing stream token'); + return key; + }, [deviceId]); + + return ( +
      + { + // Fixed SDK text; never include tokens or connection URLs in diagnostics. + console.warn('Device stream', { reason, message, attempt, final }); + }} + labels={{ connecting: 'Starting…', disconnected: 'Reconnecting', + unavailable: 'Phone unavailable', retry: 'Try again' }} + /> +
      + ); +} +``` + +`tokenProvider: () => Promise` runs before every WebSocket connect attempt, including +reconnects. Never cache, memoize the returned token, or reuse it; memoizing the callback is fine. +A throw, rejection, empty result or 10-second timeout fails the attempt and uses normal backoff. +If both credentials are supplied, `tokenProvider` wins without falling back to `streamToken`. +The component handles bounded retries; do not mint through `onStreamHealed`, which is not per attempt. +While offline, automatic attempts pause; the Retry button can request a fresh attempt. + +## Errors and recovery + +`onError` receives the exported `StreamError` shape `{ reason, message, attempt, final }`. +`message` is fixed SDK text; `attempt` counts consecutive failures from 1. +`final: true` means automatic retries stopped; keep the component's Retry button available. + +| `reason` (`StreamErrorReason`) | Meaning and action | +| --- | --- | +| `credentials_unavailable` | Provider threw, rejected, returned an empty token or exceeded 10 s. Check your backend route, caller session and mint response; let normal backoff run. | +| `connection_refused` | Socket closed before opening. Check fresh minting, device ID, expiry, revocation and allowed origin. React cannot inspect the upgrade HTTP status, so it does not report `token_rejected`. | +| `disconnected` | An open session dropped, including the 30-minute server session cap. Let the SDK reconnect with a newly minted token; check network/device state if persistent. | +| `device_unavailable` | Reserved for a server report of an offline/not-ready device. The current signaling protocol has no such message, so React does not emit it yet. Fetch device state through your backend when diagnosing availability. | +| `unknown` | Other failure, such as a handshake timeout. Check connectivity and device state, then retry. | + +## Labels and theming + +`labels?: Partial` accepts exactly these keys, all optional: + +| Key | English default | +| --- | --- | +| `connecting` | `connecting` | +| `disconnected` | `reconnecting` (retry counters such as ` (1/6)` are appended) | +| `unavailable` | `device stream unavailable` | +| `retry` | `Retry` | + +`placeholderLabel` overrides `connecting` while waiting for a URL/connection; the reconnect label +takes precedence after a drop. Use `className` on `DeviceStream` for host styling and a parent with +explicit dimensions. Import `@mobilerun/react/styles.css` once. + +Set variables on `.mobilerun-device-stream` or an ancestor: +`--mr-background`, `--mr-foreground`, `--mr-card`, `--mr-card-foreground`, `--mr-muted`, +`--mr-muted-foreground`, `--mr-border`, `--mr-ring`, `--mr-primary`, `--mr-primary-foreground`, +`--mr-accent`, `--mr-accent-foreground`, `--mr-destructive`. + +```css +.mobilerun-device-stream { + --mr-primary: oklch(0.55 0.18 268); + --mr-primary-foreground: white; + --mr-background: oklch(0.985 0.004 85); +} +``` + +Add `.dark` on an ancestor or the root for bundled dark defaults. Colors resolve from `--mr-*`, +then legacy unprefixed variables (supported for one more minor release), then bundled defaults. +The package does not define generic variables on `:root`. Keep retry text/button contrast at WCAG AA. + +## Security rules + +- Never ship `MOBILERUN_API_KEY` to a client or use it as a stream credential. +- Authenticate callers and authorize the device before minting or returning device metadata. + Use a server-configured API target and origin list, never an arbitrary browser-provided upstream URL. +- A stream token grants view and control of one device. It can be redeemed until first connect or + expiry; consuming it does not end the admitted session when the mint TTL elapses. + `hasControl={false}` is only a UI input overlay, not a server-enforced view-only permission. +- Never log tokens, store them in local storage, cache mint responses or expose `?token=` URLs in logs. + `expiresAt` is metadata, not a client-side authorization check. +- Static `streamToken` is deprecated, only for existing integrations until retired. It warns once + per mount and reuses the same value on reconnect. A single-use token passed statically fails on + reuse; migrate to `tokenProvider`. + +## Troubleshooting + +- **401 at connect:** the token may be used, expired, revoked or bound to the wrong origin/device. + Mint a new token for every attempt and check the server-configured `allowedOrigins` against the + browser origin. React surfaces this as `connection_refused`, not an HTTP status. +- **422 on mint:** read the response's `issues` on the server; correct the invalid request fields + (including TTL/origin format) before retrying. Do not expose credential details to the browser. +- **Provider failures:** check the same-origin backend route, application authentication, response + status and nonempty `key`; keep it within 10 seconds. Never return a previously minted token as + a fallback. Look for `credentials_unavailable` and `final` in `onError`. + +For full route/hook examples see [Stream tokens](../../docs/stream-tokens.md); +for styling see [Components and styling](../../docs/default-ui.md). From 0da1ed822a68efe8af168202cbd00cd84d81d1b2 Mon Sep 17 00:00:00 2001 From: lutz-grex Date: Tue, 24 Nov 2026 08:48:43 +0100 Subject: [PATCH 18/22] feat(stream): publish local inputs --- README.md | 15 + docs/publish.md | 116 +++++++ skills/mobilerun-device-stream/SKILL.md | 31 +- src/components/device-stream.test.tsx | 6 + src/components/device-stream.tsx | 83 ++++- src/components/publish-controls.test.tsx | 57 ++++ src/components/publish-controls.tsx | 58 ++++ src/components/remote-control.tsx | 23 +- src/hooks/use-webrtc-connection.test.ts | 37 +++ src/hooks/use-webrtc-connection.ts | 42 ++- src/hooks/webrtc-test-fixture.ts | 28 +- src/index.ts | 3 + src/lib/publish-controller.test.ts | 374 +++++++++++++++++++++++ src/lib/publish-controller.ts | 225 ++++++++++++++ src/lib/publish-media.test.ts | 66 ++++ src/lib/publish-media.ts | 62 ++++ src/lib/publish.ts | 51 ++++ src/lib/stream-error.ts | 39 ++- src/styles.css | 49 +++ 19 files changed, 1345 insertions(+), 20 deletions(-) create mode 100644 docs/publish.md create mode 100644 src/components/publish-controls.test.tsx create mode 100644 src/components/publish-controls.tsx create mode 100644 src/lib/publish-controller.test.ts create mode 100644 src/lib/publish-controller.ts create mode 100644 src/lib/publish-media.test.ts create mode 100644 src/lib/publish-media.ts create mode 100644 src/lib/publish.ts diff --git a/README.md b/README.md index 404519c..1d239ee 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,21 @@ device or a refused origin; browsers cannot see the HTTP status), `disconnected` dropped, including the 30-minute server cap) or `unknown`. `final: true` means retries stopped and the Retry button is showing. `labels` replaces every text the component renders. +## Microphone and camera publishing + +Pass your backend's per-device `publishCapabilities` snapshot to enable microphone injection +(and camera injection when supported). A floating pill over the stream provides both toggles; +active inputs show red. Set `hidePublishControls` for your own controls and use a +`DeviceStreamHandle` ref's `startPublish({ audio: true, video: true })`, `stopPublish()` and +`getPublishState()`. Audio is required; the SDK never silently starts a video-only session. + +`onPublishStateChange` observes this separate state. Publish errors carry `operation: 'publish'` +in `onError`; an explicit server `forbidden` maps to `publish_not_allowed`, while a silent server +maps to `publish_unsupported` after 5 seconds. Permission prompts require an explicit start. +Stopping or reconnecting releases capture; publication never resumes automatically. +See [Publishing inputs](https://github.com/droidrun/mobilerun-react/blob/main/docs/publish.md) +for capabilities, permissions, ref types and labels. + ## Theming The stylesheet defines no unprefixed CSS variable, so it cannot clash with your own `--background`. Set diff --git a/docs/publish.md b/docs/publish.md new file mode 100644 index 0000000..61faa2e --- /dev/null +++ b/docs/publish.md @@ -0,0 +1,116 @@ +← [README](../README.md) Β· [Components and styling](default-ui.md) + +# Publishing microphone and camera inputs + +Publishing sends your local microphone and optionally camera into the remote device's virtual +inputs. It uses the existing viewer connection, independently of received device audio and its +`muted` prop. It does not create a preview or another connection. + +Your authorized backend fetches `GET /v1/devices/{deviceId}/capabilities` and returns its +`.capabilities` snapshot to your app. Pass that as `publishCapabilities`; do not use a stream token +to call this endpoint or expose a privileged API key. The snapshot describes device support, +not the viewer's permission. Every start is admitted or refused by the server. + +```tsx +import { useRef } from 'react'; +import { DeviceStream, type DeviceStreamHandle, type DevicePublishCapabilities } from '@mobilerun/react'; +import '@mobilerun/react/styles.css'; + +export function Phone({ streamUrl, tokenProvider, capabilities }: { + streamUrl: string; + tokenProvider: () => Promise; + capabilities: DevicePublishCapabilities; +}) { + const stream = useRef(null); + return
      + console.info('Publish phase', state.phase)} + onError={error => { + if (error.operation === 'publish') console.info(error.reason, error.detail); + }} + /> +
      ; +} +``` + +The default pill floats at the bottom centre without changing the video layout. Microphone toggles +publication on/off. Camera starts microphone+camera; toggling it off restarts microphone-only. +Live inputs show red. Both controls are disabled during setup. The pill is hidden without a snapshot +with `microphoneInjection: true` and `mediaInjectionTransport: 'direct'`; camera also requires +`cameraInjection: true` and a compatible browser H.264 encoder. `hasControl` controls remote input +UI only and does not grant or revoke publishing authority. + +Set `hidePublishControls` to hide the pill and call the ref methods from your own user actions: + +- `startPublish({ audio: true })`: microphone only. `video: true` requests both inputs atomically. + `audio` is required; false, missing audio and video-only requests reject before capture/signaling. + The promise resolves with an `active` snapshot only after server activation and track attachment. +- `stopPublish()`: cancels setup or stops active capture, idempotently. It completes local teardown + without waiting for a server acknowledgement. Cancellation rejects a pending start with + `publish_cancelled` and emits a stopped snapshot, without `onError`. +- `getPublishState()`: current immutable snapshot, initially + `{ phase: 'idle', mediaSessionId: null, kinds: [] }`. + +`DeviceStreamHandle` extends `RemoteControlHandle`; existing ref operations remain supported. +`onPublishStateChange` observes `capturing β†’ starting β†’ accepted β†’ active` and terminal +`stopped`/`error` states. Captured tracks stay detached until acceptance. Only one operation is +allowed; a concurrent start rejects without changing it. Explicitly stop then start to change kinds. +Capabilities are fixed for the first viewer offer: remount with a new `key` and fresh stream token +to apply a different snapshot. No publish-time SDP renegotiation or automatic resume occurs. +Browsers unable to produce compatible SSRC-bearing trackless sender reservations keep viewing +and reject publication with `publish_unsupported`. + +## Permissions and cleanup + +Use HTTPS or localhost and permit the required inputs in your site's Permissions Policy. For +cross-origin iframe embeds configure the parent policy and `allow="microphone; camera"` on the +iframe. Only explicit start requests capture permission; mounting, connecting and reconnecting +never prompt. Audio-only does not request camera permission. The default browser input devices +are used. The capture profile targets 720p at 24–30 fps with a 1 Mbps uplink cap where supported. + +Capture is released on cancellation, failure, source loss, signaling/peer loss, pagehide and +unmount. A pending permission prompt may remain visible, but any later tracks are stopped without +attachment. Reconnection never resumes publication; start again explicitly. An ICE credential +refresh on the same socket/peer preserves publication. Stopping publish leaves viewing and +downstream mute unchanged. + +## Failures + +A rejected start throws `PublishError`, carrying `reason`, `message`, optional `detail` and +`serverReason`. Branch on structured fields, not display text. Terminal failures also update +publish state and emit one `onError` with `operation: 'publish'`, the current viewer attempt, +`final: true`, and an allocated `mediaSessionId` when available. `final` applies to publishing; +viewer reconnect and later explicit starts remain available. A publish refusal never marks the +viewer unavailable. + +| Reason | Cause | +| --- | --- | +| `publish_not_allowed` | Explicit server `forbidden`; support never overrides this decision. | +| `publish_unsupported` | Missing/incompatible capabilities, codecs/reservations, or no acceptance within 5 s (`response_timeout`). Silence is not proof of denial. | +| `permission_denied` | Browser `NotAllowedError`/`SecurityError` (`capture_permission`). | +| `publish_busy` | Another publisher holds the device's lease. No stealing or retry. | +| `publish_failed` | Invalid options, concurrent start, missing/busy inputs, source loss, attachment/injection failure or unexpected terminal server response. | +| `publish_timeout` | Accepted but no server active within 15 s (`active_timeout`). | +| `publish_cancelled` | Pending start cancelled locally; no error callback. | +| `disconnected` | Viewer is not connected, is closed, or loses its socket/peer. | + +Original string wire reasons are preserved as `serverReason`. Unknown reasons become +`publish_failed`; stale/malformed/foreign-session messages are ignored. + +## Labels and styling + +All pill text uses `labels` with English defaults: + +| Key | Default | +| --- | --- | +| `publishMicrophone` | Microphone | +| `publishCamera` | Camera | +| `publishStarting` | Starting inputs | +| `publishPermissionDenied` | Microphone or camera permission denied | +| `publishNotAllowed` | Publishing is not allowed | +| `publishFailed` | Unable to publish inputs | + +The pill uses the existing card, foreground, border and ring tokens. Override the red live state +with `--mr-publish-live` and `--mr-publish-live-foreground` on `.mobilerun-device-stream` or an +ancestor, keeping sufficient contrast. diff --git a/skills/mobilerun-device-stream/SKILL.md b/skills/mobilerun-device-stream/SKILL.md index 5847e5c..1081f18 100644 --- a/skills/mobilerun-device-stream/SKILL.md +++ b/skills/mobilerun-device-stream/SKILL.md @@ -121,7 +121,7 @@ While offline, automatic attempts pause; the Retry button can request a fresh at ## Labels and theming -`labels?: Partial` accepts exactly these keys, all optional: +`labels?: Partial` accepts the following connection keys and the publish keys below, all optional: | Key | English default | | --- | --- | @@ -151,6 +151,35 @@ Add `.dark` on an ancestor or the root for bundled dark defaults. Colors resolve then legacy unprefixed variables (supported for one more minor release), then bundled defaults. The package does not define generic variables on `:root`. Keep retry text/button contrast at WCAG AA. +## Microphone and camera publishing + +Get the specific device's `GET /v1/devices/{deviceId}/capabilities` response through the authorized +backend and pass its `.capabilities` as `publishCapabilities`. A stream token cannot call that API. +`microphoneInjection: true` and `mediaInjectionTransport: 'direct'` enable the floating publish pill; +camera additionally requires `cameraInjection: true` and a compatible local H.264 encoder. +Capabilities describe support; the server decides admission on every start, independently of `hasControl`. + +Use a `DeviceStreamHandle` ref for `startPublish({ audio: true, video?: boolean })`, +`stopPublish()` and `getPublishState()`. Start resolves only after server `active` and successful +track attachment. Audio is required. To change camera mode, stop then start. Set +`hidePublishControls` to use your own controls. Observe `onPublishStateChange` separately from +connection state; `onError` publish events have `operation: 'publish'`, the viewer attempt index, +`final: true`, and optional `mediaSessionId`, `detail`, `serverReason`. Handle rejected starts with +`PublishError.reason`. `forbidden` β†’ `publish_not_allowed`; silence after 5 s β†’ +`publish_unsupported`; acceptance without active after 15 s β†’ `publish_timeout`. There is no retry. + +Use HTTPS (or localhost), permit microphone/camera in Permissions Policy and set iframe +`allow="microphone; camera"` when embedding. Capture only starts on explicit action and is stopped +on stop, pagehide, disconnection or unmount. Reconnect never resumes it. Receiving audio mute +is independent. Capability changes require a new viewer connection and fresh token (remount the +component with a new `key`). No privileged API key belongs in the browser. + +Publish labels and English defaults: `publishMicrophone` (β€œMicrophone”), `publishCamera` (β€œCamera”), +`publishStarting` (β€œStarting inputs”), `publishPermissionDenied` (β€œMicrophone or camera permission denied”), +`publishNotAllowed` (β€œPublishing is not allowed”), `publishFailed` (β€œUnable to publish inputs”). +Style the pill with existing card/border tokens and `--mr-publish-live` / `--mr-publish-live-foreground`. +See [Publishing inputs](../../docs/publish.md) for the full API and failure details. + ## Security rules - Never ship `MOBILERUN_API_KEY` to a client or use it as a stream credential. diff --git a/src/components/device-stream.test.tsx b/src/components/device-stream.test.tsx index 3cd8a5a..e96d33a 100644 --- a/src/components/device-stream.test.tsx +++ b/src/components/device-stream.test.tsx @@ -16,6 +16,12 @@ describe('labels', () => { disconnected: 'reconnecting', unavailable: 'device stream unavailable', retry: 'Retry', + publishMicrophone: 'Microphone', + publishCamera: 'Camera', + publishStarting: 'Starting inputs', + publishPermissionDenied: 'Microphone or camera permission denied', + publishNotAllowed: 'Publishing is not allowed', + publishFailed: 'Unable to publish inputs', }); expect(resolveDeviceStreamLabels({ retry: undefined, unavailable: 'x' })).toMatchObject({ retry: 'Retry', unavailable: 'x' }); }); diff --git a/src/components/device-stream.tsx b/src/components/device-stream.tsx index 9a35931..36db63d 100644 --- a/src/components/device-stream.tsx +++ b/src/components/device-stream.tsx @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 import { Smartphone } from 'lucide-react'; -import { forwardRef, useCallback, useEffect, useMemo } from 'react'; +import { forwardRef, useCallback, useEffect, useMemo, useRef, useState, useImperativeHandle } from 'react'; import { cn } from '../lib/cn'; import { reconnectPillLabel, @@ -12,13 +12,20 @@ import { type StreamError, } from '../lib/stream-error'; import { STREAM_RECONNECT_MAX_ATTEMPTS } from '../lib/stream-reconnect'; -import { RemoteControl, type RemoteControlHandle } from './remote-control'; +import { RemoteControl, type DeviceStreamHandle, type RemoteControlHandle } from './remote-control'; +import { PublishControls } from './publish-controls'; +import { INITIAL_PUBLISH_STATE, PublishError, type DevicePublishCapabilities, type PublishState, type PublishErrorEvent } from '../lib/publish'; import { StreamStatusPill } from './stream-status-pill'; import { StreamUnavailable } from './stream-unavailable'; import { useStaticTokenWarning } from '../hooks/use-static-token-warning'; import { useStreamReconnect } from '../hooks/use-stream-reconnect'; export interface DeviceStreamProps { + /** Device capability snapshot supplied by your backend, fixed for this viewer connection. */ + publishCapabilities?: DevicePublishCapabilities; + onPublishStateChange?: (state: PublishState) => void; + /** Hide the built-in floating microphone/camera pill. Headless ref methods remain available. */ + hidePublishControls?: boolean; streamUrl?: string; /** * @deprecated Device token (legacy). Use `tokenProvider` for a fresh stream token @@ -70,8 +77,11 @@ export interface DeviceStreamProps { onPeerConnectionChange?: (pc: RTCPeerConnection | null) => void; } -export const DeviceStream = forwardRef(function DeviceStream( +export const DeviceStream = forwardRef(function DeviceStream( { + publishCapabilities, + onPublishStateChange, + hidePublishControls = false, streamUrl, streamToken, tokenProvider, @@ -88,6 +98,47 @@ export const DeviceStream = forwardRef(f }: DeviceStreamProps, ref, ) { + const remoteRef = useRef(null); + const [publishState, setPublishState] = useState(INITIAL_PUBLISH_STATE); + const [connected, setConnected] = useState(false); + const publishStateRef = useRef(publishState); + const disposed = useRef(false); + useEffect(() => { + disposed.current = false; + return () => { + disposed.current = true; + const state = publishStateRef.current; + if (['capturing', 'starting', 'accepted', 'active'].includes(state.phase)) { + publishStateRef.current = Object.freeze({ ...state, phase: 'stopped', reason: 'stopped_by_client' }); + } + }; + }, []); + const attemptIndex = useRef(1); + const onPublishError = (error: PublishErrorEvent) => { + if (!disposed.current) onError?.({ ...error, operation: 'publish', attempt: attemptIndex.current, final: true }); + }; + const updatePublishState = (state: PublishState) => { + if (disposed.current) return; + publishStateRef.current = state; + setPublishState(state); + onPublishStateChange?.(state); + }; + useImperativeHandle(ref, () => ({ + openUrl: url => remoteRef.current?.openUrl(url), + sendKeyEvent: event => remoteRef.current?.sendKeyEvent(event), + sendSystemKey: button => remoteRef.current?.sendSystemKey(button), + screenshot: () => remoteRef.current?.screenshot() ?? Promise.reject(new Error('The viewer is not connected')), + getPublishState: () => remoteRef.current?.getPublishState() ?? publishStateRef.current, + stopPublish: () => remoteRef.current?.stopPublish() ?? Promise.resolve(), + startPublish: options => { + if (disposed.current) return Promise.reject(new PublishError({ reason: 'disconnected', message: 'The session is closed', detail: 'session_closed' })); + if (remoteRef.current) return remoteRef.current.startPublish(options); + const failure = { reason: 'disconnected' as const, message: 'The viewer is not connected', detail: 'not_connected' }; + updatePublishState({ phase: 'error', mediaSessionId: null, kinds: [], ...failure }); + onPublishError(failure); + return Promise.reject(new PublishError(failure)); + }, + })); // The reconnect manager pins which URL/token the mounted stream uses: // fresh credentials arriving mid-backoff must not restart the connection // early (RemoteControl reconnects in place on a url prop change), so @@ -112,8 +163,22 @@ export const DeviceStream = forwardRef(f watchdogFromSocket: true, }); + // Capabilities describe this viewer's first offer. A new viewer takes a new snapshot. + const connectionPublishCapabilities = useMemo( + () => publishCapabilities ? { ...publishCapabilities } : undefined, + [streamKey, activeTarget.url], + ); + + useEffect(() => { + const state = remoteRef.current?.getPublishState() ?? INITIAL_PUBLISH_STATE; + publishStateRef.current = state; + setPublishState(state); + setConnected(false); + }, [streamKey, streamUrl]); + const handleConnectionStateChange = useCallback( (connected: boolean) => { + setConnected(connected); onReconnectConnectionChange(connected); onConnectionStateChange?.(connected); }, @@ -151,7 +216,10 @@ export const DeviceStream = forwardRef(f <>
      (f className="w-full h-full" onConnectionStateChange={handleConnectionStateChange} onConnectionFailed={onConnectionFailed} - onConnectionAttemptStarted={onConnectionAttemptStarted} + onConnectionAttemptStarted={() => { attemptIndex.current = attempt + 1; onConnectionAttemptStarted(); }} placeholderLabel={status === 'reconnecting' ? reconnectLabel : (placeholderLabel ?? labels.connecting)} muted={muted} onPeerConnectionChange={onPeerConnectionChange} />
      +