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/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d4ba83c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,46 @@ +# Contributing + +## 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/ +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 diagnostics with the legacy `streamToken` prop (device token): + +```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 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 +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 561d812..beb3a65 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@

- - - Mobilerun + + + Mobilerun

@@ -15,34 +15,46 @@
-πŸ“• 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)](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) -
- -

- @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 credentials 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 tokens 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.
  • +
  • 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+, stream-token examples 6.3.0+.
  • +
  • A Mobilerun API key on your server.
  • +
+
+ +## Install ```sh npm install @mobilerun/react @mobilerun/sdk react react-dom @@ -50,291 +62,126 @@ 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`. +## Quick start -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. +1. Your server mints a short-lived stream token for one device with your API key + using `client.streamTokens.create` from `@mobilerun/sdk` 6.3.0+. Follow the [Partner guide](https://docs.mobilerun.ai/partners). +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. -> ⚠️ **`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. - -On your backend, register this handler for `GET /api/v1/devices/:id`, passing the routed device ID: +Use this Node backend helper with `@mobilerun/sdk` 6.3.0 or later. It reads +`MOBILERUN_API_KEY` on the server; +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(); // 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. - 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, - }); +const client = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY on the Node server +export async function mintStreamToken(deviceId: string): Promise { + // Authenticate your user and check they own the device before minting. + const { key, keyId, expiresAt } = await client.streamTokens.create({ + 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' } }); } ``` -In your client component, point the SDK at that backend route, as in the example app: - -```tsx -'use client'; - -import { 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, streamToken, state, refetch } = useDeviceStream({ - device: sdk.devices.fromId(deviceId), // no request yet - }); - - return ( -
- -
- ); -} -``` - -### Without the hook - -Already have the device? Feed its fields straight in β€” no hook required: - -```tsx -const device = await sdk.devices.get(deviceId); - -; -``` - -`useDeviceStream` also still accepts `{ client, deviceId }` with a plain `Mobilerun` client, so existing code keeps working. - -## βœ… 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 credentials: 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. - 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, - }); -}); - -// 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. +REST fallback: `POST /v1/identity/stream-keys` with the same body and your server-held API key. -`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. +Revoke a token on the server with `await client.streamTokens.delete(keyId)`. -### 3. Client +Pass a stream URL fetched through your backend and a callback that calls your mint route: ```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 - /> - ); +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 token request failed'); + return (await res.json()).key; + }; + return
; } ``` -`` 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. +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. -### Show it as a bottom sheet +`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 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; } } -} -``` +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. -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. +React to failures and white-label the texts: ```tsx - report(reason, attempt, final)} + labels={{ connecting: 'Starting…', disconnected: 'Reconnecting', unavailable: 'Phone unavailable', retry: 'Try again' }} /> ``` -## πŸ§ͺ 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: - -```sh -bun install -bun run example # serves the playground at http://localhost:3000 -``` +`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 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. -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. +## Microphone and camera publishing -## 🎨 Styling & theming +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. -Import the prebuilt stylesheet once, anywhere: +`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 happen only after the device accepts an explicit start; the 30-second active +window includes the prompt. Refused or silent requests never capture. +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. -```ts -import '@mobilerun/react/styles.css'; -``` +## Theming -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. +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`. -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: +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 -: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); } ``` -## πŸ›  Building locally +## Guides -```sh -bun install -bun run build # tsup (JS + d.ts) + Tailwind (styles.css) β†’ dist/ -bun run typecheck -bun test -``` +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). | +| [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. | -## 🧬 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](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 +## License -[Apache-2.0](./LICENSE) +[Apache-2.0](https://github.com/droidrun/mobilerun-react/blob/main/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/bun.lock b/bun.lock index e43328a..20fcd24 100644 --- a/bun.lock +++ b/bun.lock @@ -12,7 +12,7 @@ "tailwind-merge": "^3.2.0", }, "devDependencies": { - "@mobilerun/sdk": "^6.2.1", + "@mobilerun/sdk": "^6.3.0", "@tailwindcss/cli": "^4.1.5", "@types/bun": "1.4.3", "@types/node": "^24", @@ -100,7 +100,7 @@ "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], - "@mobilerun/sdk": ["@mobilerun/sdk@6.2.1", "", { "peerDependencies": { "zod": ">=4.0.0 <5" }, "optionalPeers": ["zod"] }, "sha512-ELhSHYur/E7StYvtC1pTyQkKl73BLYBkWETIdFrST3YDLBW6XYG3Lp9nlQhQ6L3V9wWRni2WjoLZj9m1sG3Qvg=="], + "@mobilerun/sdk": ["@mobilerun/sdk@6.3.0", "", { "peerDependencies": { "zod": ">=4.0.0 <5" }, "optionalPeers": ["zod"] }, "sha512-nJvX7t+zk9/G/KBK7094KzT+rGV5dfVIXgEBvw4C+hiqLswGDAMsqKyGzm8UX6NEiC+1DBuXBWM6Bt1dM0sLUA=="], "@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="], diff --git a/docs/default-ui.md b/docs/default-ui.md new file mode 100644 index 0000000..b3bf9ec --- /dev/null +++ b/docs/default-ui.md @@ -0,0 +1,52 @@ +← [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. + +## 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: + +```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 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 +.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 tokens](stream-tokens.md#labels). diff --git a/docs/publish.md b/docs/publish.md new file mode 100644 index 0000000..c3acdb0 --- /dev/null +++ b/docs/publish.md @@ -0,0 +1,125 @@ +← [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. Only its buttons receive taps; the background and separate status +text above the pill pass taps through. After 3 seconds without nearby interaction it fades to 50%; +nearby pointer/touch input or button focus restores full opacity. 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 `starting β†’ accepted β†’ capturing β†’ active` and terminal +`stopped`/`error` states. The SDK sends the start request before opening inputs; refused and silent requests never prompt +or capture. Acceptance starts a 30-second window covering the permission prompt, capture and activation. Only one operation is +allowed; a concurrent start rejects without changing it. Explicitly stop then start to change kinds. +When capabilities arrive or their values change, the SDK renews the viewer connection and obtains +a fresh token through `tokenProvider` to reserve the inputs in its first offer. Equivalent snapshots +do not reconnect. The camera button follows the verified offer reservation. 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 an explicit start accepted by the device 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. + +Viewer replacement/remount emits terminal `disconnected` once through state and `onError`. A +throwing start/stop signaling write also reports `disconnected` and releases capture. + +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 30 s (including the permission prompt) (`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 | +| --- | --- | +| `microphone` | Microphone | +| `camera` | Camera | +| `stopMicrophone` | Stop microphone | +| `stopCamera` | Stop camera | +| `publishStarting` | Starting inputs | +| `publishPermissionDenied` | Microphone or camera permission denied | +| `publishNotAllowed` | Publishing is not allowed | +| `publishFailed` | Could not 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/docs/stream-keys.md b/docs/stream-keys.md new file mode 100644 index 0000000..1366a6b --- /dev/null +++ b/docs/stream-keys.md @@ -0,0 +1 @@ +[Stream tokens guide](stream-tokens.md) diff --git a/docs/stream-tokens.md b/docs/stream-tokens.md new file mode 100644 index 0000000..7750fa4 --- /dev/null +++ b/docs/stream-tokens.md @@ -0,0 +1,202 @@ +← [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 backend stream-token helpers below require `@mobilerun/sdk` 6.3.0 or later on Node. 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 client = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY on the Node server + +export async function getDevice(id: string): Promise { + // Authenticate the caller and check the device belongs to them before returning device metadata. + const device = await client.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 { key, keyId, expiresAt } = await client.streamTokens.create({ + 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' }, + }); + } 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' }, + }); + } +} +``` + +`client.streamTokens.create({ deviceId, ttlSeconds, allowedOrigins })` returns +`{ key, keyId, expiresAt }`. TTL is 60–300 seconds, default 120. Configure `allowedOrigins` on +the server with your browser app's exact origins. Each stream token is single-use and device-scoped. +Revoke it on the server with `await client.streamTokens.delete(keyId)`. `expiresAt` is diagnostic +metadata, not a browser permission or validity check. Do not log or cache stream tokens. + +REST fallback: `POST /v1/identity/stream-keys` with the same body, or `DELETE /v1/identity/stream-keys/{keyId}`, authenticated with your server-held API key. + +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. 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. 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. 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 +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/docs/task-approvals.md b/docs/task-approvals.md new file mode 100644 index 0000000..8e89678 --- /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(--mr-background, var(--background, white)); 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 (`--mr-background`, `--mr-card`, `--mr-destructive`, …; see [Components and styling](default-ui.md#styling-and-theming)). + +### 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 + +``` diff --git a/example/main.tsx b/example/main.tsx index c0208b4..16f4714 100644 --- a/example/main.tsx +++ b/example/main.tsx @@ -15,6 +15,7 @@ import { type ApprovalDecision, type PendingApproval, type RemoteControlHandle, + type StreamError, } from '../src/index'; // Prebuilt themed stylesheet (run `bun run build:css` once to generate it). import '../dist/styles.css'; @@ -28,9 +29,10 @@ import logoUrl from '../assets/mobilerun-logo.png'; const HARNESS_CSS = ` *, *::before, *::after { box-sizing: border-box; } html, body { margin: 0; } - /* Cloud app theme tokens. Uses the SAME variable names the package reads - * (--background, --card, --muted-foreground, --border, --primary, ...), so - * the embedded DeviceStream/NavigationBar pick up the cloud palette too. */ + /* Cloud app theme tokens. The package reads --mr- 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,12 +185,13 @@ interface Status { isLoading: boolean; error?: unknown; connected: boolean; + streamError?: StreamError; } /** * 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 +214,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 getFreshStreamToken = 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,12 +237,14 @@ function SdkStream({ onStatus({ connected: c })} + // `reason` tells a refused stream token from a dropped session; `final` means the Retry button is showing. + onError={(streamError) => onStatus({ streamError })} + onConnectionStateChange={(c) => onStatus({ connected: c, ...(c ? { streamError: undefined } : {}) })} /> ); @@ -239,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 (
@@ -424,9 +445,8 @@ function ApprovalSection() { function App() { const [mode, setMode] = useState('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 +454,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. + // 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 }>({}); @@ -497,7 +517,7 @@ function App() { SDK
@@ -544,7 +564,7 @@ function App() { setStreamUrl(e.target.value)} placeholder="wss://…" />
- + setStreamToken(e.target.value)} placeholder="token…" />
diff --git a/example/server.test.ts b/example/server.test.ts new file mode 100644 index 0000000..d9e5cc2 --- /dev/null +++ b/example/server.test.ts @@ -0,0 +1,165 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { expect, spyOn, 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}`, { + headers: { Host: 'localhost:3000' }, + }); + 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: { Host: 'localhost:3000', '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 log = spyOn(console, 'error').mockImplementation(() => {}); + let response: Response; + try { + 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(); + } + 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', + 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 aeeab26..3199bb9 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 token 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 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). -// β€’ 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 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 @@ -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,105 @@ 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.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); - } + 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'); + 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.streamTokens.create( + { 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); + } + }); + + 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; +} + +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) { + console.error(error, code); + 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); } @@ -142,43 +218,21 @@ 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); -}); - -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 token 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/package.json b/package.json index d9c69a9..41d28d8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@mobilerun/react", - "version": "0.3.0", + "version": "0.4.0", "description": "React components for embedding Mobilerun's native device streaming (WebRTC + scrcpy) and task approvals β€” plug-and-play with @mobilerun/sdk.", "license": "Apache-2.0", "author": "Mobilerun ", @@ -64,7 +64,7 @@ "react-dom": "^18.0.0 || ^19.0.0" }, "devDependencies": { - "@mobilerun/sdk": "^6.2.1", + "@mobilerun/sdk": "^6.3.0", "@tailwindcss/cli": "^4.1.5", "@types/bun": "1.4.3", "@types/node": "^24", diff --git a/skills/mobilerun-device-stream/SKILL.md b/skills/mobilerun-device-stream/SKILL.md new file mode 100644 index 0000000..03fc96e --- /dev/null +++ b/skills/mobilerun-device-stream/SKILL.md @@ -0,0 +1,209 @@ +--- +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 + +On your Node backend, use `client.streamTokens.create({ deviceId, ttlSeconds, allowedOrigins })` +from `@mobilerun/sdk` 6.3.0 or later. The client reads the server's `MOBILERUN_API_KEY`; the method +returns `{ key, keyId, expiresAt }`. `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.3.0+. +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 client = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY on the Node server + +export async function mintStreamToken(deviceId: string): Promise { + const { key, keyId, expiresAt } = await client.streamTokens.create({ + 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' }, + }); +} +``` + +Revoke a token on the server with `await client.streamTokens.delete(keyId)`. + +REST fallback: `POST /v1/identity/stream-keys` with the same body, or `DELETE /v1/identity/stream-keys/{keyId}`, authenticated with your server-held API key. + +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 the following connection keys and the publish keys below, 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. + +## 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 30 s (including the permission prompt) β†’ `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 after an explicit action is accepted by the device and is stopped +on stop, pagehide, disconnection or unmount. Reconnect never resumes it. Receiving audio mute +is independent. Arriving or changed capabilities automatically renew the viewer with a fresh token; equivalent +snapshots do not reconnect. Camera controls follow verified first-offer reservations. No privileged API key belongs in the browser. + +Publish labels and English defaults: `microphone` (β€œMicrophone”), `camera` (β€œCamera”), +`stopMicrophone` (β€œStop microphone”), `stopCamera` (β€œStop camera”), `publishStarting` (β€œStarting inputs”), `publishPermissionDenied` (β€œMicrophone or camera permission denied”), +`publishNotAllowed` (β€œPublishing is not allowed”), `publishFailed` (β€œCould not publish inputs”). +Only pill buttons receive input; its background/status text pass through. It fades to 50% after +3 s and restores on nearby pointer/touch input. Status text stays above it. A viewer replacement or +throwing start/stop socket write emits `disconnected` once and releases capture. +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. +- 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). diff --git a/src/components/device-stream.test.tsx b/src/components/device-stream.test.tsx new file mode 100644 index 0000000..79ec5a5 --- /dev/null +++ b/src/components/device-stream.test.tsx @@ -0,0 +1,60 @@ +// 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', + microphone: 'Microphone', + camera: 'Camera', + stopMicrophone: 'Stop microphone', + stopCamera: 'Stop camera', + publishStarting: 'Starting inputs', + publishPermissionDenied: 'Microphone or camera permission denied', + publishNotAllowed: 'Publishing is not allowed', + publishFailed: 'Could not publish inputs', + }); + 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 3eb42b5..25d4075 100644 --- a/src/components/device-stream.tsx +++ b/src/components/device-stream.tsx @@ -2,18 +2,50 @@ // Copyright 2026 Mobilerun // SPDX-License-Identifier: Apache-2.0 -import { RotateCw, Smartphone, WifiOff } from 'lucide-react'; -import { forwardRef, useCallback, useEffect, useMemo } from 'react'; +import { Smartphone } from 'lucide-react'; +import { forwardRef, useCallback, useEffect, useMemo, useRef, useState, useImperativeHandle } from 'react'; import { cn } from '../lib/cn'; +import { + reconnectPillLabel, + 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 { RemoteControl, type DeviceStreamHandle, type RemoteControlHandle } from './remote-control'; +import { PublishControls } from './publish-controls'; +import { INITIAL_PUBLISH_STATE, PublishError, publishCapabilitiesKey, type PublishKind, type DevicePublishCapabilities, type PublishState, type PublishErrorEvent } from '../lib/publish'; 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 { + /** Device capability snapshot supplied by your backend; changed values renew the 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 + * 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 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; + /** + * 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; @@ -45,10 +77,16 @@ 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, + onError, + labels: labelOverrides, hasControl, onHasControlChange: setHasControl = () => {}, onConnectionStateChange, @@ -60,6 +98,54 @@ export const DeviceStream = forwardRef(f }: DeviceStreamProps, ref, ) { + const remoteRef = useRef(null); + const [publishState, setPublishState] = useState(INITIAL_PUBLISH_STATE); + const [connected, setConnected] = useState(false); + const [offeredKinds, setOfferedKinds] = useState([]); + const observers = useRef({ onError, onPublishStateChange }); + observers.current = { onError, onPublishStateChange }; + const publishStateRef = useRef(publishState); + const disposed = useRef(false); + useEffect(() => { + disposed.current = false; + return () => { + const state = publishStateRef.current; + if (['capturing', 'starting', 'accepted', 'active'].includes(state.phase)) { + const failure = { reason: 'disconnected' as const, message: 'Publishing connection closed' }; + publishStateRef.current = Object.freeze({ ...state, phase: 'error', ...failure }); + observers.current.onPublishStateChange?.(publishStateRef.current); + observers.current.onError?.({ ...failure, operation: 'publish', attempt: attemptIndex.current, final: true, + ...(state.mediaSessionId ? { mediaSessionId: state.mediaSessionId } : {}) }); + } + disposed.current = true; + }; + }, []); + 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: () => 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 @@ -68,20 +154,34 @@ export const DeviceStream = forwardRef(f const { streamKey, activeTarget, + allowOffline, status, attempt, onConnectionStateChange: onReconnectConnectionChange, onConnectionFailed, + onConnectionAttemptStarted, retry, } = useStreamReconnect({ onHeal: onStreamHealed, + onError, target, targetKey: `${streamUrl ?? ''}|${streamToken ?? ''}`, enabled: !!streamUrl, + watchdogFromSocket: true, }); + const capabilitiesKey = publishCapabilitiesKey(publishCapabilities); + + useEffect(() => { + const state = remoteRef.current?.getPublishState() ?? INITIAL_PUBLISH_STATE; + publishStateRef.current = state; + setPublishState(state); + setConnected(false); + }, [streamKey, streamUrl, capabilitiesKey]); + const handleConnectionStateChange = useCallback( (connected: boolean) => { + setConnected(connected); onReconnectConnectionChange(connected); onConnectionStateChange?.(connected); }, @@ -95,47 +195,55 @@ export const DeviceStream = forwardRef(f } }, [streamUrl, setHasControl]); - const reconnectLabel = - attempt > 1 ? `reconnecting (${attempt}/${STREAM_RECONNECT_MAX_ATTEMPTS})` : 'reconnecting'; + const labels = resolveDeviceStreamLabels(labelOverrides); + + useStaticTokenWarning(!!streamToken && !tokenProvider); + + const reconnectLabel = reconnectPillLabel(labels.disconnected, attempt, STREAM_RECONNECT_MAX_ATTEMPTS); return (
{!streamUrl ? ( <> - + ) : status === 'unavailable' ? ( -
- - device stream unavailable - -
+ ) : ( <>
{ attemptIndex.current = attempt + 1; onConnectionAttemptStarted(); }} + placeholderLabel={status === 'reconnecting' ? reconnectLabel : (placeholderLabel ?? labels.connecting)} muted={muted} onPeerConnectionChange={onPeerConnectionChange} />
+
); }, diff --git a/src/components/stream-status-pill.tsx b/src/components/stream-status-pill.tsx index 8a4a923..42afdb9 100644 --- a/src/components/stream-status-pill.tsx +++ b/src/components/stream-status-pill.tsx @@ -19,7 +19,7 @@ export function StreamStatusPill({ label, className }: StreamStatusPillProps) { 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/test-hook-runner.ts b/src/hooks/test-hook-runner.ts index 11954a1..f01a11f 100644 --- a/src/hooks/test-hook-runner.ts +++ b/src/hooks/test-hook-runner.ts @@ -9,13 +9,19 @@ 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); }]; } export function useCallback(fn) { return fn; } + export function jsx(type, props) { return { type, props }; } + export const jsxDEV = jsx, jsxs = jsx; + export const Fragment = Symbol.for('react.fragment'); + export function forwardRef(fn) { return fn; } + export function createElement(type, props, ...children) { return { type, props: { ...props, children } }; } export function useEffect(fn, deps) { const ref = useRef(undefined); effectSlots.add(ref); @@ -27,6 +33,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) { @@ -49,7 +56,7 @@ async function bundleHook(entry: string): Promise { plugins: [{ name: 'hook-runner', setup(build) { - build.onResolve({ filter: /^react$/ }, () => ({ path: 'react', namespace: 'fixture' })); + build.onResolve({ filter: /^react(?:\/jsx(?:-dev)?-runtime)?$/ }, () => ({ path: 'react', namespace: 'fixture' })); build.onLoad({ filter: /.*/, namespace: 'fixture' }, () => ({ loader: 'js', contents: fixtureSource })); }, }], diff --git a/src/hooks/use-device-stream.ts b/src/hooks/use-device-stream.ts index 8a85e07..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; - /** Stream auth token β€” feed into ``. */ + /** @deprecated Device token (legacy). Obtain a fresh stream token 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 }); + * // getFreshStreamToken calls your authenticated backend's stream-token endpoint. * return ( * (undefined); + const [loaded, setLoaded] = useState<{ targetId: string; device: SdkDevice } | undefined>(undefined); const [isLoading, setIsLoading] = useState(enabled); const [error, setError] = useState(undefined); @@ -115,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); @@ -133,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-static-token-warning.test.ts b/src/hooks/use-static-token-warning.test.ts new file mode 100644 index 0000000..f2293bd --- /dev/null +++ b/src/hooks/use-static-token-warning.test.ts @@ -0,0 +1,37 @@ +// 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 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 () => { + 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..4e363e4 --- /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 device token (legacy) 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; 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 new file mode 100644 index 0000000..f019d2b --- /dev/null +++ b/src/hooks/use-stream-reconnect.test.ts @@ -0,0 +1,404 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +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 { deferred, 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((_error: StreamError) => {}); + 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, commit = true) => { + runner.beginRender(); + const result = runner.module.exports.useStreamReconnect({ + target, targetKey: target, enabled, watchdogFromSocket: true, onHeal, onError: error, + }); + 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, navigator, commit: runner.flushEffects, unmount: runner.unmount }; +} + +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(); + expect(result.status).toBe('unavailable'); + const provider = mock(async () => 'fresh'); + f.mount(result.activeTarget, undefined, { tokenProvider: provider }); + r.listeners.visibilitychange.forEach(fn => fn()); + 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(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); + r.listeners.visibilitychange.forEach(fn => fn()); + r.render('new', latestHeal); + 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(); +}); + +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('unavailable'); + 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(); +}); + +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: true, + }]]); + expect(result.status).toBe('unavailable'); + 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(); +}); + +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 7b1b304..8103605 100644 --- a/src/hooks/use-stream-reconnect.ts +++ b/src/hooks/use-stream-reconnect.ts @@ -2,7 +2,9 @@ // 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 type { StreamError, StreamFailure } from '../lib/stream-error'; +import { browserReportsOnline } from '../lib/browser-network'; import { createStreamReconnectController, type StreamReconnectSnapshot } from '../lib/stream-reconnect'; interface UseStreamReconnectOptions { @@ -13,6 +15,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 @@ -28,6 +32,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; } /** @@ -39,22 +45,26 @@ 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({ onHeal, + onError, target, targetKey, 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 }>(() => ({ 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. @@ -62,22 +72,24 @@ 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 // 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; }); // 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 @@ -85,9 +97,11 @@ export function useStreamReconnect({ const controllerRef = useRef | null>(null); if (controllerRef.current === null) { controllerRef.current = createStreamReconnectController({ + networkAvailable: browserReportsOnline(), onRemount: bumpMount, onSnapshot: (s) => setSnapshot(s), onHeal: () => onHealRef.current?.(), + onError: (error) => onErrorRef.current?.(error), }); } @@ -104,30 +118,47 @@ 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 })); } - // 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 activeEpochRef = useRef(mount.epoch); + const onConnectionAttemptStarted = useCallback(() => { + if (activeEpochRef.current !== mount.epoch) return; + controllerRef.current?.attemptMounted(true, mount.allowOffline, true); + }, [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. + useLayoutEffect(() => { + activeEpochRef.current = mount.epoch; if (enabled) { - controllerRef.current?.attemptMounted(); + controllerRef.current?.attemptMounted(!watchdogFromSocket, mount.allowOffline); } else { controllerRef.current?.setDisabled(); } - }, [mount.epoch, enabled]); + 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); 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); }; }, []); @@ -136,11 +167,17 @@ 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(() => controllerRef.current?.handleFailure(), []); + const onConnectionFailed = useCallback( + (failure?: StreamFailure) => { + if (activeEpochRef.current === mount.epoch) controllerRef.current?.handleFailure(failure); + }, + [mount.epoch], + ); const retry = useCallback(() => controllerRef.current?.retry(), []); @@ -148,9 +185,12 @@ 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, + onConnectionAttemptStarted, onConnectionFailed, retry, }; diff --git a/src/hooks/use-webrtc-connection.test.ts b/src/hooks/use-webrtc-connection.test.ts index fc5c5a3..0259276 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) { @@ -170,3 +173,791 @@ test('a queued ICE grace recheck cannot change replacement state', async () => { pc.offer.resolve({ sdp: 'old' }); await restart; f.unmount(); }); + +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(); + 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(['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}`; + 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!; + expect(media.getTracks()).toHaveLength(1); + const lateClose = f.sockets[0].onclose!; + 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, 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.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(); +}); + +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(1006); + await tick(); + expect(f.peers[0].closed).toBe(false); + 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).toBe('Stream token provider failed'); + 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(); +}); + +// 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 token 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(); +}); + +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(); +}); + +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(); +}); + +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(); +}); + +test('publish stops on signaling loss even while downstream stays connected; ICE refresh keeps it', async () => { + const f = await fixture(); + const publishCapabilities = { microphoneInjection: true, cameraInjection: true, mediaInjectionTransport: 'direct' }; + const changes: unknown[] = []; + const result = f.mount('publish', undefined, { publishCapabilities, onPublishStateChange: state => changes.push(state) }); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + const pc = f.peers[0]; + expect(pc.transceivers.map(t => [t.kind, t.direction])).toEqual([['audio', 'recvonly'], ['video', 'recvonly'], ['video', 'sendonly'], ['audio', 'sendonly']]); + expect(f.captureRequests).toEqual([]); + pc.offer.resolve({ sdp: 'v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=mid:2\r\na=sendonly\r\na=ssrc:100 cname:test\r\na=rtpmap:96 H264/90000\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:3\r\na=sendonly\r\na=ssrc:101 cname:test\r\na=rtpmap:111 opus/48000/2\r\n' }); + pc.local.resolve(); + await tick(); + pc.connectionState = 'connected'; + pc.onconnectionstatechange?.(); + let stopped = false; + const track = { kind: 'audio', readyState: 'live', addEventListener() {}, removeEventListener() {}, stop() { stopped = true; } }; + const start = result.publisher.start({ audio: true }); + f.capture.resolve({ getTracks: () => [track] } as unknown as MediaStream); + await tick(); + await f.sockets[0].onmessage?.(event({ type: 'publishState', mediaSessionId: '11111111-1111-4111-8111-111111111111', state: 'active' })); + await start; + await f.sockets[0].onmessage?.(event({ type: 'rtcConfiguration', rtcConfiguration: { iceServers: [] } })); + expect(result.publisher.getState().phase).toBe('active'); + expect(stopped).toBe(false); + expect(f.sockets[0].sent.filter(frame => frame.type === 'publishStart')).toHaveLength(1); + f.sockets[0].close(1006); + await tick(); + expect(stopped).toBe(true); + expect(result.publisher.getState()).toMatchObject({ phase: 'error', reason: 'disconnected' }); + expect(pc.closed).toBe(false); + expect(f.states.at(-1)).toBe(true); + f.unmount(); +}); + +test('late capabilities renew the viewer with a fresh token and publish reservations', async () => { + const f = await fixture(); + let mints = 0; + const tokenProvider = async () => 'fresh-' + ++mints; + const kinds: unknown[] = []; + f.render('late', undefined, { tokenProvider }); + await tick(); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + expect(f.peers[0].transceivers.map(t => t.direction)).toEqual(['recvonly', 'recvonly']); + const publishCapabilities = { microphoneInjection: true, cameraInjection: true, mediaInjectionTransport: 'direct' }; + f.render('late', undefined, { tokenProvider, publishCapabilities, onPublishKindsChange: value => kinds.push(value) }); + await tick(); + expect(mints).toBe(2); + expect(f.peers[0].closed).toBe(true); + f.sockets[1].open(); + await tick(); + f.sockets[1].config(); + await tick(); + expect(f.peers[1].transceivers.map(t => [t.kind, t.direction])).toEqual([['audio', 'recvonly'], ['video', 'recvonly'], ['video', 'sendonly'], ['audio', 'sendonly']]); + f.peers[1].offer.resolve({ sdp: 'v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:3\r\na=sendonly\r\na=ssrc:101 cname:test\r\na=rtpmap:111 opus/48000/2\r\n' }); + f.peers[1].local.resolve(); + await tick(); + expect(kinds).toEqual([[], ['audio']]); // No verified camera section in this offer. + f.render('late', undefined, { tokenProvider, publishCapabilities: { ...publishCapabilities } }); + await tick(); + expect(mints).toBe(2); // A new object with the same values does not reconnect. + expect(f.captureRequests).toEqual([]); + f.unmount(); +}); + +test.each(['target', 'capabilities'] as const)('%s replacement terminates publishing once', async replacement => { + const f = await fixture(); + const errors: unknown[] = []; + const states: unknown[] = []; + const publishCapabilities = { microphoneInjection: true, cameraInjection: true, mediaInjectionTransport: 'direct' }; + const credentials = { publishCapabilities, onPublishError: (error: unknown) => errors.push(error), onPublishStateChange: (state: unknown) => states.push(state) }; + const result = f.mount('old', undefined, credentials); + f.sockets[0].open(); + await tick(); + f.sockets[0].config(); + await tick(); + f.peers[0].offer.resolve({ sdp: 'v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:3\r\na=sendonly\r\na=ssrc:101 cname:test\r\na=rtpmap:111 opus/48000/2\r\n' }); + f.peers[0].local.resolve(); + await tick(); + f.peers[0].connectionState = 'connected'; + const starting = result.publisher.start({ audio: true }); + const outcome = starting.catch(error => error); + const actions = { + target: () => f.render('new', undefined, credentials), + capabilities: () => f.render('old', undefined, { ...credentials, publishCapabilities: { ...publishCapabilities, cameraInjection: false } }), + }; + actions[replacement](); + await tick(); + expect(await outcome).toMatchObject({ reason: 'disconnected' }); + expect(errors).toHaveLength(1); + expect(states.at(-1)).toMatchObject({ phase: 'error', reason: 'disconnected' }); + expect(f.captureRequests).toEqual([]); + expect(result.publisher.getState()).toMatchObject({ phase: 'error', reason: 'disconnected' }); + f.unmount(); +}); diff --git a/src/hooks/use-webrtc-connection.ts b/src/hooks/use-webrtc-connection.ts index 9742192..485e5e0 100644 --- a/src/hooks/use-webrtc-connection.ts +++ b/src/hooks/use-webrtc-connection.ts @@ -6,10 +6,16 @@ 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'; +import { STREAM_FAILURE_MESSAGES, type ConnectionErrorReason, type StreamFailure } from '../lib/stream-error'; import { createRTCConfigurationRequest } from '../webrtc-messages'; +import { browserReportsOnline } from '../lib/browser-network'; +import { PublishController } from '../lib/publish-controller'; +import { inspectPublishOffer, reservePublish } from '../lib/publish-media'; +import { publishCapabilitiesKey, type DevicePublishCapabilities, type PublishState, type PublishErrorEvent, type PublishKind } from '../lib/publish'; const debugLog = (...args: any[]) => { if (window.debugRemoteControl) { @@ -32,13 +38,28 @@ function buildWebSocketUrl(url: string, token?: string): string { return wsUrl.toString(); } +// 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; + const isLoopback = ['localhost', '127.0.0.1', '[::1]'].includes(resolved.hostname); + return resolved.protocol === 'ws:' && isLoopback; +} + interface ScreenshotData { dataUri: string; } interface UseWebRtcConnectionOptions { + publishCapabilities?: DevicePublishCapabilities; + onPublishStateChange?: (state: PublishState) => void; + onPublishError?: (error: PublishErrorEvent) => void; + onPublishKindsChange?: (kinds: PublishKind[]) => void; 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; @@ -48,7 +69,9 @@ 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()) // without owning its lifecycle. @@ -56,6 +79,7 @@ interface UseWebRtcConnectionOptions { } interface UseWebRtcConnectionResult { + publisher: PublishController; wsRef: React.MutableRefObject; dataChannelRef: React.MutableRefObject; hoverChannelRef: React.MutableRefObject; @@ -67,21 +91,50 @@ interface UseWebRtcConnectionResult { } export function useWebRtcConnection({ + publishCapabilities, + onPublishStateChange, + onPublishError, + onPublishKindsChange, url, token, + tokenProvider, + allowOffline = false, sessionId, openUrl, videoRef, onConnectionStateChange, onConnectionFailed, + onConnectionAttemptStarted, onPeerConnectionChange, }: UseWebRtcConnectionOptions): UseWebRtcConnectionResult { + const publishCallbacks = useRef({ onPublishStateChange, onPublishError, onPublishKindsChange }); + publishCallbacks.current = { onPublishStateChange, onPublishError, onPublishKindsChange }; + const capabilitiesKey = publishCapabilitiesKey(publishCapabilities); + const viewerKey = `${url}|${sessionId}|${capabilitiesKey}`; + const publisherRef = useRef<{ key: string; publisher: PublishController } | null>(null); + if (publisherRef.current?.key !== viewerKey) publisherRef.current = { key: viewerKey, publisher: new PublishController({ + onState: state => publishCallbacks.current.onPublishStateChange?.(state), + onError: error => publishCallbacks.current.onPublishError?.(error), + }) }; + const publisher = publisherRef.current.publisher; const tokenRef = useRef(token); tokenRef.current = token; + const tokenProviderRef = useRef(tokenProvider); + tokenProviderRef.current = tokenProvider; + const attemptGenerationRef = useRef(0); + 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; + const onConnectionFailedRef = useRef(onConnectionFailed); onConnectionFailedRef.current = onConnectionFailed; @@ -148,9 +201,10 @@ export function useWebRtcConnection({ } const state = pcAtArm.connectionState; if (state === 'connected') return; + publisher.disconnect(); updateStatus('ICE-restart grace expired, reporting state: ' + state); setIsConnected(false); - onConnectionStateChangeRef.current?.(false); + reportConnectionState(false); }, Math.max(0, iceRestartGraceUntilRef.current - Date.now()), ); @@ -191,6 +245,24 @@ export function useWebRtcConnection({ }; const start = async () => { + if (!allowOffline && !browserReportsOnline()) return; + const generation = ++attemptGenerationRef.current; + const provider = tokenProviderRef.current; + const isActive = () => attemptGenerationRef.current === generation; + let failed = false; + // 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; + if (stopMedia) { + reportConnectionState(false); + stop(); + } + onConnectionFailedRef.current?.(failure); + }; // 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. @@ -205,12 +277,43 @@ 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: ConnectionErrorReason = 'unknown'; try { - const wsUrl = buildWebSocketUrl(url, tokenRef.current); + let streamToken = tokenRef.current; + if (provider) { + 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 token provider timeout')), + STREAM_TOKEN_PROVIDER_TIMEOUT_MS, + ); + cancelStartup = () => { + clearTimeout(providerTimer); + reject(new Error('Stream token 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 token provider returned an empty stream token'); + phase = 'unknown'; + } + if (!isActive() || (!allowOffline && !browserReportsOnline())) return; + 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; + onConnectionAttemptStartedRef.current?.(); + if (!isCurrent()) return; let pendingTimer: ReturnType | undefined; let configHandler: ((event: MessageEvent) => void) | undefined; let rejectStartup: ((reason: Error) => void) | undefined; @@ -231,12 +334,13 @@ export function useWebRtcConnection({ ws.onerror = (error) => { if (!isCurrent()) return; - updateStatus('WebSocket error: ' + error); + updateStatus(provider ? 'WebSocket error' : '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) => { + phase = 'connection_refused'; + const opened = new Promise((resolve, reject) => { rejectStartup = reject; ws.onopen = () => { if (!isCurrent()) return; @@ -249,22 +353,29 @@ 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'; - // 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). - 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; + publisher.disconnect(); updateStatus('WebSocket closed'); - if (peerConnectionRef.current?.connectionState !== 'connected') { - onConnectionFailedRef.current?.(); - } + 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(dropped); }; // Request RTCConfiguration @@ -305,6 +416,9 @@ export function useWebRtcConnection({ direction: 'recvonly', }); + const reservations = reservePublish(pc, publishCapabilities); + publisher.bind({ socket: ws, peer: pc, capabilities: publishCapabilities, reservations }); + // Ask the jitter buffer to target zero playout delay. Trades a bit of // smoothness for ~100ms lower glass-to-glass latency β€” critical for // cursor/touch responsiveness. Supported in Chromium and Safari; a @@ -426,9 +540,15 @@ export function useWebRtcConnection({ const state = pc.connectionState; updateStatus('Connection state: ' + state); const connected = state === 'connected'; + if (connected) everConnected = true; + if (state === 'failed' || state === 'closed' || (state === 'disconnected' && Date.now() >= iceRestartGraceUntilRef.current)) publisher.disconnect(); if (state === 'failed' || state === 'closed') { // Terminal: this peer connection will not come back on its own. - onConnectionFailedRef.current?.(); + failAttempt({ + reason: everConnected ? 'disconnected' : 'unknown', + message: `Peer connection ${state}`, + }); + if (!isCurrent()) return; } if (connected) { iceRestartGraceUntilRef.current = 0; @@ -448,7 +568,7 @@ export function useWebRtcConnection({ } clearRestartRecheck(); setIsConnected(connected); - onConnectionStateChangeRef.current?.(connected); + reportConnectionState(connected); }; pc.oniceconnectionstatechange = () => { @@ -518,6 +638,9 @@ export function useWebRtcConnection({ } updateStatus('Received: ' + message.type); switch (message.type) { + case 'publishState': + publisher.handle(ws, message); + break; case 'answer': if (!peerConnectionRef.current) { updateStatus('No peer connection, skipping answer'); @@ -660,17 +783,28 @@ export function useWebRtcConnection({ if (!isCurrent() || peerConnectionRef.current !== pc) return; await pc.setLocalDescription(offer); if (!isCurrent() || peerConnectionRef.current !== pc) return; - ws.send(JSON.stringify({ type: 'offer', sdp: offer.sdp, sessionId })); + const sdp = pc.localDescription?.sdp ?? offer.sdp ?? ''; + inspectPublishOffer(reservations, sdp); + publishCallbacks.current.onPublishKindsChange?.([...reservations.offered]); + ws.send(JSON.stringify({ type: '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({ + reason: phase, + // Never forward `e.message`: provider and socket errors can carry the token or a ?token= URL. + message: STREAM_FAILURE_MESSAGES[phase], + }); } }; const stop = () => { + publisher.disconnect(); + ++attemptGenerationRef.current; + stopKeepAlive(); cancelStartupRef.current?.(); cancelStartupRef.current = null; clearRestartRecheck(); @@ -710,37 +844,48 @@ export function useWebRtcConnection({ hoverChannelRef.current.close(); hoverChannelRef.current = null; } + lastReportedConnectedRef.current = false; setIsConnected(false); updateStatus('Stopped'); }; useEffect(() => { - // Start connection when component mounts + publisher.open(publishCapabilities); + publishCallbacks.current.onPublishKindsChange?.([]); + // 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); + stop(); + }; + const onPageHide = () => { void publisher.stop(); }; + window.addEventListener('pagehide', onPageHide); + window.addEventListener('offline', onOffline); 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); // Clean up return () => { - stopKeepAlive(); + void publisher.replace(); stop(); + window.removeEventListener('pagehide', onPageHide); document.removeEventListener('visibilitychange', onVisibilityChange); + window.removeEventListener('offline', onOffline); }; // 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]); + }, [url, sessionId, capabilitiesKey]); return { + publisher, wsRef, dataChannelRef, hoverChannelRef, diff --git a/src/hooks/webrtc-test-fixture.ts b/src/hooks/webrtc-test-fixture.ts index 20a3c17..e4dd007 100644 --- a/src/hooks/webrtc-test-fixture.ts +++ b/src/hooks/webrtc-test-fixture.ts @@ -1,6 +1,9 @@ // Copyright 2026 Mobilerun // SPDX-License-Identifier: Apache-2.0 +import type { PublishController } from '../lib/publish-controller'; +import type { DevicePublishCapabilities } from '../lib/publish'; +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 +15,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>(); @@ -27,22 +30,30 @@ export async function fixture() { 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; 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) { + hooks.onConstruct?.(url); + 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; @@ -70,7 +81,14 @@ export async function fixture() { onicecandidate = (_event: object) => {}; ontrack = (_event: object) => {}; constructor() { peers.push(this); } - addTransceiver() { return { receiver: {} }; } + transceivers: { kind: string; direction: string; mid: string; currentDirection: string; receiver: object; sender: { replaceTrack: (track: unknown) => Promise }; setCodecPreferences: (codecs: unknown) => void }[] = []; + attachments: unknown[] = []; + addTransceiver(kind: string, options: { direction: string }) { + const transceiver = { kind, direction: options.direction, mid: String(this.transceivers.length), currentDirection: options.direction, + receiver: {}, sender: { replaceTrack: async (track: unknown) => { this.attachments.push(track); } }, setCodecPreferences: () => {} }; + this.transceivers.push(transceiver); + return transceiver; + } createDataChannel(label: string, options: Record) { this.channelOptions.push({ label, options }); const c = new FakeChannel(); this.channels.push(c); return c; } createOffer() { return this.offer.promise; } setLocalDescription() { this.localCalls++; return this.local.promise; } @@ -82,35 +100,95 @@ export async function fixture() { const stateWrites: boolean[] = []; const states: boolean[] = []; const failures: boolean[] = []; + const failureInfos: { reason: string; message: string }[] = []; 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 capture = deferred(); + const captureRequests: MediaStreamConstraints[] = []; + const navigator = { onLine: true, mediaDevices: { getUserMedia(constraints: MediaStreamConstraints) { captureRequests.push(constraints); return capture.promise; } } }; + const networkListeners = { online: new Set<() => void>(), offline: new Set<() => void>(), pagehide: new Set<() => void>() }; const context = { - window: { setTimeout: setTimer, clearTimeout: clearTimer, setInterval: setIntervalTimer, clearInterval: clearTimer }, - document: { hidden: false, addEventListener() {}, removeEventListener() {} }, + 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' }, + }, + document, URL, MediaStream: FakeMediaStream, + Date: clock ? class extends Date { static now() { return clock.now; } } : Date, WebSocket: FakeSocket, RTCPeerConnection: FakePeer, RTCRtpReceiver: { getCapabilities: () => null }, + RTCRtpSender: { getCapabilities: (kind: string) => ({ codecs: kind === 'audio' + ? [{ mimeType: 'audio/opus', clockRate: 48000, channels: 2 }] + : [{ mimeType: 'video/H264', clockRate: 90000, sdpFmtpLine: 'packetization-mode=1;profile-level-id=42e01f' }] }) }, + crypto: { randomUUID: () => '11111111-1111-4111-8111-111111111111' }, 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, + // 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 } } }>( - import.meta.dir + '/use-webrtc-connection.ts', context, { compareEffectDeps: false }, + const runner = await runHook<{ useWebRtcConnection: (options: object) => { wsRef: { current: FakeSocket | null }; publisher: PublishController } }>( + import.meta.dir + '/use-webrtc-connection.ts', context, ); - const mount = (id = 'a', openUrl?: string) => { - runner.unmount(); + type Credentials = { + publishCapabilities?: DevicePublishCapabilities; + onPublishStateChange?: (state: unknown) => void; + onPublishError?: (error: unknown) => void; + onPublishKindsChange?: (kinds: unknown) => void; + url?: string; + token?: string; + tokenProvider?: () => Promise; + allowOffline?: boolean; + onConnectionAttemptStarted?: () => void; + }; + 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), + onConnectionFailed: (failure: { reason: string; message: string }) => { + failures.push(true); + failureInfos.push(failure); + }, onPeerConnectionChange: (pc: FakePeer | null) => bindings.push(pc), }); 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, + hooks, navigator, networkListeners, capture, captureRequests, + 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, + 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(); }, diff --git a/src/index.ts b/src/index.ts index b86c4f2..0de319f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 // Components -export { DeviceStream } from './components/device-stream'; +export type { DeviceStreamHandle } from './components/remote-control'; +export { PublishError } from './lib/publish'; +export type { PublishOptions, PublishKind, PublishPhase, PublishFailureReason, PublishFailure, PublishState, DevicePublishCapabilities } from './lib/publish'; +export { DeviceStream, type DeviceStreamProps } from './components/device-stream'; export { RemoteControl, type RemoteControlHandle, @@ -25,6 +28,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/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/publish-controller.test.ts b/src/lib/publish-controller.test.ts new file mode 100644 index 0000000..b25f051 --- /dev/null +++ b/src/lib/publish-controller.test.ts @@ -0,0 +1,424 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, test } from 'bun:test'; +import { deferred } from '../hooks/webrtc-test-fixture'; +import { tick } from '../hooks/test-hook-runner'; +import { FakeSchedule } from './test-clock'; +import { PublishController } from './publish-controller'; +import type { DevicePublishCapabilities, PublishErrorEvent, PublishOptions, PublishState } from './publish'; + +const capabilities: DevicePublishCapabilities = { microphoneInjection: true, cameraInjection: true, mediaInjectionTransport: 'direct' }; +const uuid = '11111111-1111-4111-8111-111111111111'; + +function fixture(config: { capabilities?: DevicePublishCapabilities | null; camera?: boolean; offered?: boolean } = {}) { + const clock = new FakeSchedule(); + const states: PublishState[] = []; + const errors: PublishErrorEvent[] = []; + const sent: object[] = []; + const captures: MediaStreamConstraints[] = []; + const attachments: { kind: string; track: unknown }[] = []; + const media = deferred(); + const pendingAttach = deferred(); + let captureResult = media.promise; + let holdAudio = false; + let failVideo = false; + let stopThrows = false; + let startThrows = false; + class Track extends EventTarget { + readyState = 'live'; + stops = 0; + constructor(readonly kind: string) { super(); } + stop() { this.stops++; this.readyState = 'ended'; } + } + const audio = new Track('audio'); + const video = new Track('video'); + const stream = { getTracks: () => config.camera ? [audio, video] : [audio] } as unknown as MediaStream; + const transceiver = (kind: string) => ({ + currentDirection: 'sendonly', + sender: { async replaceTrack(track: unknown) { + attachments.push({ kind, track }); + if (track && kind === 'audio' && holdAudio) await pendingAttach.promise; + if (track && kind === 'video' && failVideo) throw new Error('attach'); + } }, + } as unknown as RTCRtpTransceiver); + const reservations = { transceivers: { audio: transceiver('audio'), video: transceiver('video') }, offered: new Set<'audio' | 'video'>(config.offered === false ? [] : ['audio', 'video']) }; + const socket = { readyState: 1, send(data: string) { + const frame = JSON.parse(data); + if (startThrows && frame.type === 'publishStart') throw new Error('closed'); + if (stopThrows && frame.type === 'stopPublish') throw new Error('closed'); + sent.push(frame); + } } as unknown as WebSocket; + const peer = { connectionState: 'connected' } as RTCPeerConnection; + let nextId = 0; + const controller = new PublishController({ + onState: state => states.push(state), onError: error => errors.push(error), + capture: constraints => { captures.push(constraints); return captureResult; }, + uuid: () => nextId++ === 0 ? uuid : '22222222-2222-4222-8222-222222222222', + setTimer: clock.setTimeout, clearTimer: timer => { if (timer !== undefined) clock.clearTimeout(timer); }, + }); + const caps = config.capabilities === null ? undefined : config.capabilities ?? capabilities; + const bind = () => controller.bind({ socket, peer, capabilities: caps, reservations }); + bind(); + const signal = (state: string, reason?: unknown, id = uuid, source = socket) => controller.handle(source, { type: 'publishState', mediaSessionId: id, state, reason }); + const start = async (options: PublishOptions = { audio: true }) => { + const result = controller.start(options); + const outcome = result.catch(error => error); + media.resolve(stream); + await tick(); + return { result, outcome }; + }; + return { controller, clock, states, errors, sent, captures, attachments, media, audio, video, stream, reservations, socket, peer, bind, signal, start, + freshMedia() { + const track = new Track('audio'); + captureResult = Promise.resolve({ getTracks: () => [track] } as unknown as MediaStream); + return track; + }, + holdAudio() { holdAudio = true; }, releaseAudio() { pendingAttach.resolve(); }, failVideo() { failVideo = true; }, stopThrows() { stopThrows = true; }, startThrows() { startThrows = true; } }; +} + +describe('publish wire and state', () => { + test('accepted authorizes audio then video; active waits for attachment and stop preserves viewing', async () => { + const f = fixture({ camera: true }); + expect(f.controller.getState()).toEqual({ phase: 'idle', mediaSessionId: null, kinds: [] }); + const { result } = await f.start({ audio: true, video: true }); + expect(f.sent).toEqual([{ type: 'publishStart', mediaSessionId: uuid, kinds: ['audio', 'video'] }]); + expect(f.attachments).toEqual([]); + f.holdAudio(); + f.signal('accepted'); + f.signal('active'); + await tick(); + expect(f.controller.getState().phase).toBe('capturing'); + expect(f.attachments).toEqual([{ kind: 'audio', track: f.audio }]); + f.releaseAudio(); + await tick(); + expect(await result).toEqual({ phase: 'active', mediaSessionId: uuid, kinds: ['audio', 'video'] }); + expect(f.states.map(state => state.phase)).toEqual(['starting', 'accepted', 'capturing', 'active']); + expect(f.attachments).toEqual([{ kind: 'audio', track: f.audio }, { kind: 'video', track: f.video }]); + await f.controller.stop(); + await f.controller.stop(); + expect(f.controller.getState()).toEqual({ phase: 'stopped', mediaSessionId: uuid, kinds: ['audio', 'video'], reason: 'stopped_by_client' }); + expect(f.sent).toEqual([{ type: 'publishStart', mediaSessionId: uuid, kinds: ['audio', 'video'] }, { type: 'stopPublish', mediaSessionId: uuid }]); + expect(f.audio.stops).toBe(1); + expect(f.video.stops).toBe(1); + expect(f.peer.connectionState).toBe('connected'); + expect(f.errors).toEqual([]); + expect(f.clock.pendingCount).toBe(0); + expect(Object.isFrozen(f.states[0].kinds)).toBe(true); + }); + + test('active alone accepts once and ignores duplicate and foreign messages', async () => { + const f = fixture(); + const { result } = await f.start(); + f.signal('active', undefined, 'foreign'); + f.signal('active', undefined, uuid, {} as WebSocket); + f.controller.handle(f.socket, { type: 'publishState', mediaSessionId: uuid, state: 'unknown' }); + expect(f.attachments).toEqual([]); + f.signal('active'); + f.signal('accepted'); + f.signal('active'); + await result; + expect(f.states.map(state => state.phase)).toEqual(['starting', 'accepted', 'capturing', 'active']); + expect(f.attachments).toEqual([{ kind: 'audio', track: f.audio }]); + await f.controller.stop(); + f.signal('active'); + expect(f.controller.getState().phase).toBe('stopped'); + }); + + test.each([ + ['forbidden', 'publish_not_allowed', undefined], ['unsupported', 'publish_unsupported', undefined], + ['busy', 'publish_busy', undefined], ['inject_failed', 'publish_failed', undefined], + ['source_lost', 'publish_failed', undefined], ['connection_closed', 'disconnected', undefined], + ['stopped_by_client', 'publish_failed', 'remote_stop'], ['unknown', 'publish_failed', undefined], + ['toString', 'publish_failed', undefined], [undefined, 'publish_failed', undefined], [42, 'publish_failed', undefined], + ])('terminal server reason %s maps to %s', async (reason, expected, detail) => { + const f = fixture(); + const { outcome } = await f.start(); + f.signal('rejected', reason); + f.signal('error', reason); + const failure = await outcome; + expect(failure.reason).toBe(expected); + expect(failure.detail).toBe(detail); + expect(failure.serverReason).toBe(typeof reason === 'string' ? reason : undefined); + expect(f.controller.getState()).toMatchObject({ phase: 'error', reason: expected }); + expect(f.errors).toHaveLength(1); + expect(f.audio.stops).toBe(0); + expect(f.captures).toEqual([]); + expect(f.attachments.filter(call => call.track !== null)).toEqual([]); + expect(f.sent[1]).toEqual({ type: 'stopPublish', mediaSessionId: uuid }); + expect(f.clock.pendingCount).toBe(0); + }); + + test('silence is unsupported exactly at 5 seconds and late active cannot attach', async () => { + const f = fixture(); + const { outcome } = await f.start(); + f.clock.advance(4999); + expect(f.controller.getState().phase).toBe('starting'); + f.clock.advance(1); + expect(await outcome).toMatchObject({ reason: 'publish_unsupported', detail: 'response_timeout' }); + f.signal('active'); + await tick(); + expect(f.audio.stops).toBe(0); + expect(f.captures).toEqual([]); + expect(f.attachments.filter(call => call.track !== null)).toEqual([]); + }); + + test('acceptance has its own 30-second deadline, which duplicates do not extend', async () => { + const f = fixture(); + const { outcome } = await f.start(); + f.clock.advance(4999); + f.signal('accepted'); + await tick(); + f.clock.advance(29999); + await tick(); + f.signal('accepted'); + expect(f.controller.getState().phase).toBe('capturing'); + f.clock.advance(1); + expect(await outcome).toMatchObject({ reason: 'publish_timeout', detail: 'active_timeout' }); + expect(f.audio.stops).toBe(1); + expect(f.clock.pendingCount).toBe(0); + }); + + test('a concurrent start preserves the first operation; a new explicit start uses a fresh UUID', async () => { + const f = fixture(); + const { result } = await f.start(); + const pending = f.controller.getState(); + await expect(f.controller.start({ audio: true })).rejects.toMatchObject({ reason: 'publish_failed', detail: 'publish_in_progress' }); + expect(f.controller.getState()).toBe(pending); + f.signal('active'); + await result; + await expect(f.controller.start({ audio: true })).rejects.toMatchObject({ reason: 'publish_failed', detail: 'already_publishing' }); + expect(f.captures).toHaveLength(1); + await f.controller.stop(); + f.freshMedia(); + const { outcome } = await f.start(); + expect(f.sent[2]).toEqual({ type: 'publishStart', mediaSessionId: '22222222-2222-4222-8222-222222222222', kinds: ['audio'] }); + f.signal('active'); // old UUID cannot affect the replacement + expect(f.controller.getState().phase).toBe('starting'); + await f.controller.stop(); + expect(await outcome).toMatchObject({ reason: 'publish_cancelled' }); + }); +}); + +describe('publish local guards and capture', () => { + test.each([{ audio: false }, { audio: false, video: true }, {}, { audio: true, video: 'yes' }])('audio-required validation: %j', async options => { + const f = fixture(); + await expect(f.controller.start(options as PublishOptions)).rejects.toMatchObject({ reason: 'publish_failed', detail: 'invalid_options' }); + expect(f.captures).toEqual([]); + expect(f.sent).toEqual([]); + }); + + test.each([ + [null, 'capabilities_unavailable'], + [{ ...capabilities, microphoneInjection: false }, 'device_capability'], + [{ ...capabilities, mediaInjectionTransport: 'relay' }, 'device_capability'], + [{ ...capabilities, cameraInjection: false }, 'device_capability'], + ] as const)('capability guard %j', async (caps, detail) => { + const f = fixture({ capabilities: caps }); + await expect(f.controller.start({ audio: true, video: true })).rejects.toMatchObject({ reason: 'publish_unsupported', detail }); + expect(f.captures).toEqual([]); + expect(f.sent).toEqual([]); + }); + + test('a disconnected viewer fails before capture even with support', async () => { + const f = fixture(); + f.controller.disconnect(); + await expect(f.controller.start({ audio: true })).rejects.toMatchObject({ reason: 'disconnected', detail: 'not_connected' }); + expect(f.captures).toEqual([]); + }); + + test('missing SSRC/codec reservations fail locally without capture', async () => { + const f = fixture({ offered: false }); + await expect(f.controller.start({ audio: true })).rejects.toMatchObject({ reason: 'publish_unsupported', detail: 'local_media_support' }); + expect(f.captures).toEqual([]); + }); + + test('a rejected upstream answer still allows explicit forbidden to be authoritative', async () => { + const f = fixture(); + Object.defineProperty(f.reservations.transceivers.audio, 'currentDirection', { value: 'inactive' }); + const { outcome } = await f.start(); + f.signal('rejected', 'forbidden'); + expect(await outcome).toMatchObject({ reason: 'publish_not_allowed' }); + expect(f.attachments.filter(call => call.track !== null)).toEqual([]); + }); + + test('accepted with an inactive sender is unsupported, never not allowed', async () => { + const f = fixture(); + Object.defineProperty(f.reservations.transceivers.audio, 'currentDirection', { value: 'inactive' }); + const { outcome } = await f.start(); + f.signal('accepted'); + expect(await outcome).toMatchObject({ reason: 'publish_unsupported', detail: 'negotiated_sender' }); + expect(f.audio.stops).toBe(1); + }); + + test.each([['NotAllowedError', 'permission_denied', 'capture_permission'], ['SecurityError', 'permission_denied', 'capture_permission'], ['NotReadableError', 'publish_failed', 'capture_unavailable'], ['AbortError', 'publish_failed', 'capture_unavailable']])('capture %s is %s', async (name, reason, detail) => { + const f = fixture(); + const result = f.controller.start({ audio: true }); + f.signal('accepted'); + f.media.reject(Object.assign(new Error('capture'), { name })); + await expect(result).rejects.toMatchObject({ reason, detail }); + expect(f.sent).toEqual([{ type: 'publishStart', mediaSessionId: uuid, kinds: ['audio'] }, { type: 'stopPublish', mediaSessionId: uuid }]); + expect(f.errors).toHaveLength(1); + }); + + test('a partial camera capture stops the accepted session and microphone', async () => { + const f = fixture(); + const { outcome } = await f.start({ audio: true, video: true }); + f.signal('accepted'); + expect(await outcome).toMatchObject({ reason: 'publish_failed', detail: 'capture_unavailable' }); + expect(f.audio.stops).toBe(1); + expect(f.sent).toEqual([{ type: 'publishStart', mediaSessionId: uuid, kinds: ['audio', 'video'] }, { type: 'stopPublish', mediaSessionId: uuid }]); + }); +}); + +describe('publish cancellation and teardown', () => { + test('stop during permission capture rejects start, then stops late tracks without attaching', async () => { + const f = fixture(); + const result = f.controller.start({ audio: true }); + const failure = result.catch(error => error); + f.signal('accepted'); + f.clock.advance(29999); // The accepted window includes the permission prompt. + expect(f.controller.getState().phase).toBe('capturing'); + await f.controller.stop(); + expect(await failure).toMatchObject({ reason: 'publish_cancelled' }); + f.media.resolve(f.stream); + await tick(); + expect(f.audio.stops).toBe(1); + expect(f.sent).toEqual([{ type: 'publishStart', mediaSessionId: uuid, kinds: ['audio'] }, { type: 'stopPublish', mediaSessionId: uuid }]); + expect(f.attachments.filter(call => call.track !== null)).toEqual([]); + expect(f.errors).toEqual([]); + }); + + test('late attachment is detached before a subsequent operation can attach', async () => { + const f = fixture(); + f.holdAudio(); + const { outcome } = await f.start(); + f.signal('accepted'); + await tick(); + const stopped = f.controller.stop(); + expect(f.audio.stops).toBe(1); + await expect(f.controller.start({ audio: true })).rejects.toMatchObject({ reason: 'publish_failed', detail: 'publish_in_progress' }); + f.releaseAudio(); + await stopped; + const nextAudio = f.freshMedia(); + const next = f.controller.start({ audio: true }); + const nextOutcome = next.catch(error => error); + await tick(); + f.signal('active', undefined, '22222222-2222-4222-8222-222222222222'); + expect(await outcome).toMatchObject({ reason: 'publish_cancelled' }); + expect(await nextOutcome).toMatchObject({ phase: 'active', mediaSessionId: '22222222-2222-4222-8222-222222222222' }); + expect(f.attachments).toEqual([{ kind: 'audio', track: f.audio }, { kind: 'audio', track: null }, { kind: 'audio', track: null }, { kind: 'audio', track: nextAudio }]); + await f.controller.stop(); + }); + + test('video attachment failure releases the already-attached audio', async () => { + const f = fixture({ camera: true }); + f.failVideo(); + const { outcome } = await f.start({ audio: true, video: true }); + f.signal('active'); + expect(await outcome).toMatchObject({ reason: 'publish_failed', detail: 'attach_failed' }); + await tick(); + expect(f.audio.stops).toBe(1); + expect(f.video.stops).toBe(1); + expect(f.attachments.slice(-2)).toEqual([{ kind: 'audio', track: null }, { kind: 'video', track: null }]); + }); + + test('disconnect releases capture; replacement never resumes it', async () => { + const f = fixture(); + const { result } = await f.start(); + f.signal('active'); + await result; + f.controller.disconnect(); + await tick(); + expect(f.audio.stops).toBe(1); + expect(f.attachments.at(-1)).toEqual({ kind: 'audio', track: null }); + expect(f.errors[0]).toMatchObject({ reason: 'disconnected', mediaSessionId: uuid }); + f.bind(); + await tick(); + expect(f.captures).toHaveLength(1); + expect(f.sent).toEqual([{ type: 'publishStart', mediaSessionId: uuid, kinds: ['audio'] }, { type: 'stopPublish', mediaSessionId: uuid }]); + expect(f.clock.pendingCount).toBe(0); + }); + + test('ended capture terminates the entire audio/video publication', async () => { + const f = fixture({ camera: true }); + const { result } = await f.start({ audio: true, video: true }); + f.signal('active'); + await result; + f.video.dispatchEvent(new Event('ended')); + await tick(); + expect(f.audio.stops).toBe(1); + expect(f.video.stops).toBe(1); + expect(f.errors).toEqual([{ reason: 'publish_failed', message: 'A local input stopped', detail: 'capture_unavailable', mediaSessionId: uuid }]); + }); + + test('a failing stop write reports disconnected and cannot hold capture open', async () => { + const f = fixture(); + const { result } = await f.start(); + f.signal('active'); + await result; + f.stopThrows(); + await f.controller.stop(); + expect(f.audio.stops).toBe(1); + expect(f.attachments.at(-1)).toEqual({ kind: 'audio', track: null }); + expect(f.errors).toEqual([{ reason: 'disconnected', message: 'Publishing connection closed', mediaSessionId: uuid }]); + expect(f.controller.getState()).toMatchObject({ phase: 'error', reason: 'disconnected' }); + expect(f.clock.pendingCount).toBe(0); + }); + + test('dispose stops capture, closes methods and prevents later callbacks', async () => { + const f = fixture(); + const { result } = await f.start(); + f.signal('active'); + await result; + const count = f.states.length; + f.controller.dispose(); + await tick(); + await expect(f.controller.start({ audio: true })).rejects.toMatchObject({ reason: 'disconnected', detail: 'session_closed' }); + expect(f.audio.stops).toBe(1); + expect(f.attachments.at(-1)).toEqual({ kind: 'audio', track: null }); + expect(f.states).toHaveLength(count); + expect(f.errors).toEqual([]); + }); +}); + +test('no permission or capture before acceptance; the 30-second window covers a stalled prompt', async () => { + const f = fixture(); + const result = f.controller.start({ audio: true }); + const outcome = result.catch(error => error); + expect(f.captures).toEqual([]); + expect(f.sent).toEqual([{ type: 'publishStart', mediaSessionId: uuid, kinds: ['audio'] }]); + f.signal('accepted'); + expect(f.captures).toHaveLength(1); + f.clock.advance(29999); + await tick(); + expect(f.controller.getState().phase).toBe('capturing'); + f.signal('accepted'); + f.clock.advance(1); + expect(await outcome).toMatchObject({ reason: 'publish_timeout', detail: 'active_timeout' }); + f.media.resolve(f.stream); + await tick(); + expect(f.audio.stops).toBe(1); + expect(f.attachments.filter(call => call.track !== null)).toEqual([]); +}); + +test('throwing publishStart reports disconnected without capture', async () => { + const f = fixture(); + f.startThrows(); + await expect(f.controller.start({ audio: true })).rejects.toMatchObject({ reason: 'disconnected' }); + expect(f.captures).toEqual([]); + expect(f.errors).toHaveLength(1); + expect(f.clock.pendingCount).toBe(0); +}); + +test('viewer replacement reports one disconnected terminal state and error', async () => { + const f = fixture(); + const { result } = await f.start(); + f.signal('active'); + await result; + await f.controller.replace(); + f.signal('error', 'connection_closed'); + expect(f.controller.getState()).toMatchObject({ phase: 'error', reason: 'disconnected', mediaSessionId: uuid }); + expect(f.errors).toEqual([{ reason: 'disconnected', message: 'Publishing connection closed', mediaSessionId: uuid }]); + expect(f.audio.stops).toBe(1); +}); diff --git a/src/lib/publish-controller.ts b/src/lib/publish-controller.ts new file mode 100644 index 0000000..d6d87bb --- /dev/null +++ b/src/lib/publish-controller.ts @@ -0,0 +1,246 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { + INITIAL_PUBLISH_STATE, PublishError, supportsPublish, + type DevicePublishCapabilities, type PublishErrorEvent, type PublishFailure, + type PublishKind, type PublishOptions, type PublishState, +} from './publish'; +import { usablePublishSender, type PublishReservations } from './publish-media'; + +type Binding = { + socket: WebSocket; + peer: RTCPeerConnection; + capabilities?: DevicePublishCapabilities; + reservations: PublishReservations; +}; +type Operation = { + binding: Binding; + kinds: PublishKind[]; + id: string | null; + stream?: MediaStream; + sent: boolean; + accepted: boolean; + active: boolean; + attached: boolean; + timer?: ReturnType; + ended?: () => void; + sendFailed?: boolean; + resolve: (state: PublishState) => void; + reject: (error: PublishError) => void; +}; +type Options = { + onState: (state: PublishState) => void; + onError: (error: PublishErrorEvent) => void; + capture?: (constraints: MediaStreamConstraints) => Promise; + uuid?: () => string; + setTimer?: (callback: () => void, ms: number) => ReturnType; + clearTimer?: (timer: ReturnType | undefined) => void; +}; + +/** One operation per viewer. All sender mutations share a queue across operations. */ +export class PublishController { + private binding?: Binding; + private capabilities?: DevicePublishCapabilities; + private operation?: Operation; + private ending?: Promise; + private closed = false; + private state = INITIAL_PUBLISH_STATE; + private mutations: Promise = Promise.resolve(); + private readonly setTimer; + private readonly clearTimer; + constructor(private readonly options: Options) { + this.setTimer = options.setTimer ?? ((callback, ms) => setTimeout(callback, ms)); + this.clearTimer = options.clearTimer ?? (timer => clearTimeout(timer)); + } + getState = (): PublishState => this.state; + open(capabilities?: DevicePublishCapabilities): void { this.closed = false; this.capabilities = capabilities; } + bind(binding: Binding): void { + this.disconnect(); + this.binding = binding; + this.capabilities = binding.capabilities; + } + disconnect(): void { + const op = this.operation; + this.binding = undefined; + if (op) void this.fail(op, { reason: 'disconnected', message: 'Publishing connection closed' }); + } + async replace(): Promise { + const op = this.operation; + this.binding = undefined; + if (op) await this.fail(op, { reason: 'disconnected', message: 'Publishing connection closed' }); + this.closed = true; + } + dispose(): void { + this.closed = true; + this.binding = undefined; + void this.stop(); + } + private emit(state: PublishState): void { + this.state = Object.freeze({ ...state, kinds: Object.freeze([...state.kinds]) as unknown as PublishKind[] }); + if (!this.closed) this.options.onState(this.state); + } + private current(op: Operation): boolean { return this.operation === op && this.binding === op.binding && !this.closed; } + private report(failure: PublishFailure, id?: string | null): PublishError { + if (!this.closed) this.options.onError({ ...failure, ...(id ? { mediaSessionId: id } : {}) }); + return new PublishError(failure); + } + private invalid(failure: PublishFailure, kinds: PublishKind[], preserve = false): Promise { + if (!preserve) this.emit({ phase: 'error', mediaSessionId: null, kinds, ...failure }); + return Promise.reject(this.report(failure)); + } + start = (options: PublishOptions): Promise => { + if (this.operation || this.ending) return this.invalid({ reason: 'publish_failed', message: 'Publishing is already in progress', + detail: this.operation && this.state.phase === 'active' ? 'already_publishing' : 'publish_in_progress' }, [], true); + const kinds: PublishKind[] = options?.video === true ? ['audio', 'video'] : ['audio']; + if (this.closed) return this.invalid({ reason: 'disconnected', message: 'The session is closed', detail: 'session_closed' }, []); + if (options?.audio !== true || (options.video !== undefined && typeof options.video !== 'boolean')) { + return this.invalid({ reason: 'publish_failed', message: 'Microphone audio is required', detail: 'invalid_options' }, []); + } + const binding = this.binding; + const capabilities = this.capabilities; + if (!capabilities) return this.invalid({ reason: 'publish_unsupported', message: 'Publish capabilities are unavailable', detail: 'capabilities_unavailable' }, kinds); + if (!supportsPublish(capabilities) || (options.video && !capabilities.cameraInjection)) { + return this.invalid({ reason: 'publish_unsupported', message: 'The device does not support these inputs', detail: 'device_capability' }, kinds); + } + if (!binding || binding.socket.readyState !== 1 || binding.peer.connectionState !== 'connected') { + return this.invalid({ reason: 'disconnected', message: 'The viewer is not connected', detail: 'not_connected' }, kinds); + } + if ((!this.options.capture && (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia)) + || kinds.some(kind => !binding.reservations.offered.has(kind))) { + return this.invalid({ reason: 'publish_unsupported', message: 'Local media publishing is unsupported', detail: 'local_media_support' }, kinds); + } + const promise = new Promise((resolve, reject) => { + const op: Operation = { binding, kinds, id: null, sent: false, accepted: false, active: false, attached: false, resolve, reject }; + this.operation = op; + try { + op.id = (this.options.uuid ?? (() => crypto.randomUUID()))(); + this.emit({ phase: 'starting', mediaSessionId: op.id, kinds }); + if (!this.current(op)) return; + op.sent = true; + op.timer = this.setTimer(() => { void this.fail(op, { reason: 'publish_unsupported', message: 'The device did not answer the publish request', detail: 'response_timeout' }); }, 5000); + binding.socket.send(JSON.stringify({ type: 'publishStart', mediaSessionId: op.id, kinds })); + } catch { + void this.fail(op, { reason: 'disconnected', message: 'Publishing connection closed' }); + } + }); + return promise; + }; + private async capture(op: Operation): Promise { + try { + const constraints: MediaStreamConstraints = { + audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }, + video: op.kinds.includes('video') ? { width: { ideal: 1280, max: 1280 }, height: { ideal: 720, max: 720 }, frameRate: { ideal: 24, max: 30 } } : false, + }; + const stream = await (this.options.capture?.(constraints) ?? navigator.mediaDevices.getUserMedia(constraints)); + if (!this.current(op)) { stream.getTracks().forEach(track => track.stop()); return; } + op.stream = stream; + if (op.kinds.some(kind => !stream.getTracks().some(track => track.kind === kind && track.readyState === 'live'))) { + throw new Error('Missing live capture track'); + } + op.ended = () => { void this.fail(op, { reason: 'publish_failed', message: 'A local input stopped', detail: 'capture_unavailable' }); }; + stream.getTracks().forEach(track => track.addEventListener('ended', op.ended!)); + await this.attach(op); + } catch (error) { + const name = error && typeof error === 'object' && 'name' in error ? error.name : undefined; + const denied = name === 'NotAllowedError' || name === 'SecurityError'; + await this.fail(op, { reason: denied ? 'permission_denied' : 'publish_failed', + message: denied ? 'Microphone or camera permission was denied' : 'Local capture is unavailable', detail: denied ? 'capture_permission' : 'capture_unavailable' }); + } + } + handle(socket: WebSocket, message: unknown): void { + const op = this.operation; + if (!op || !this.current(op) || socket !== op.binding.socket || !op.sent || !message || typeof message !== 'object') return; + const frame = message as Record; + if (frame.type !== 'publishState' || typeof frame.mediaSessionId !== 'string' || frame.mediaSessionId !== op.id + || !['accepted', 'active', 'rejected', 'error', 'stopped'].includes(String(frame.state)) || typeof frame.state !== 'string') return; + if (frame.state === 'accepted' || frame.state === 'active') { + if (frame.state === 'active') op.active = true; + if (!op.accepted) { + op.accepted = true; + this.clearTimer(op.timer); + op.timer = this.setTimer(() => { void this.fail(op, { reason: 'publish_timeout', message: 'Publishing did not become active', detail: 'active_timeout' }); }, 30000); + this.emit({ phase: 'accepted', mediaSessionId: op.id, kinds: op.kinds }); + if (this.current(op)) { + this.emit({ phase: 'capturing', mediaSessionId: op.id, kinds: op.kinds }); + if (this.current(op)) void this.capture(op); + } + } + this.complete(op); + return; + } + const serverReason = typeof frame.reason === 'string' ? frame.reason : undefined; + const reasons: Record = { + forbidden: 'publish_not_allowed', unsupported: 'publish_unsupported', busy: 'publish_busy', connection_closed: 'disconnected', + }; + void this.fail(op, { reason: serverReason && Object.hasOwn(reasons, serverReason) ? reasons[serverReason]! : 'publish_failed', message: 'The device stopped or refused publishing', + ...(serverReason ? { serverReason } : {}), ...(serverReason === 'stopped_by_client' ? { detail: 'remote_stop' } : {}) }); + } + private async attach(op: Operation): Promise { + try { + for (const kind of op.kinds) { + const sender = usablePublishSender(op.binding.reservations, kind); + if (!sender) { await this.fail(op, { reason: 'publish_unsupported', message: 'The negotiated sender is unavailable', detail: 'negotiated_sender' }); return; } + const track = op.stream!.getTracks().find(track => track.kind === kind)!; + await this.mutate(async () => { + if (!this.current(op)) return; + await sender.replaceTrack(track); + if (!this.current(op)) { track.stop(); await sender.replaceTrack(null); } + }); + if (!this.current(op)) return; + } + op.attached = true; + this.complete(op); + } catch { + await this.fail(op, { reason: 'publish_failed', message: 'Could not attach local inputs', detail: 'attach_failed' }); + } + } + private complete(op: Operation): void { + if (!this.current(op) || !op.active || !op.attached || this.state.phase === 'active') return; + this.clearTimer(op.timer); + this.emit({ phase: 'active', mediaSessionId: op.id, kinds: op.kinds }); + op.resolve(this.state); + } + private mutate(fn: () => Promise): Promise { + const next = this.mutations.then(fn); + this.mutations = next.catch(() => {}); + return next; + } + private teardown(op: Operation): Promise { + this.operation = undefined; // invalidate before any asynchronous cleanup + this.clearTimer(op.timer); + op.stream?.getTracks().forEach(track => { if (op.ended) track.removeEventListener('ended', op.ended); track.stop(); }); + if (op.sent && op.binding.socket.readyState === 1) { + try { op.binding.socket.send(JSON.stringify({ type: 'stopPublish', mediaSessionId: op.id })); } catch { op.sendFailed = true; } + } + const cleanup = !op.accepted ? Promise.resolve() : this.mutate(async () => { + for (const kind of op.kinds) { + try { await op.binding.reservations.transceivers[kind]?.sender.replaceTrack(null); } catch { /* closed peer */ } + } + }); + this.ending = cleanup; + return cleanup; + } + private async fail(op: Operation, failure: PublishFailure): Promise { + if (this.operation !== op) return; + await this.teardown(op); + this.ending = undefined; + if (op.sendFailed) failure = { reason: 'disconnected', message: 'Publishing connection closed' }; + this.emit({ phase: 'error', mediaSessionId: op.id, kinds: op.kinds, ...failure }); + op.reject(this.report(failure, op.id)); + } + stop = async (): Promise => { + const op = this.operation; + if (!op) { await this.ending; return; } + await this.teardown(op); + this.ending = undefined; + if (op.sendFailed) { + const failure: PublishFailure = { reason: 'disconnected', message: 'Publishing connection closed' }; + this.emit({ phase: 'error', mediaSessionId: op.id, kinds: op.kinds, ...failure }); + op.reject(this.report(failure, op.id)); + return; + } + this.emit({ phase: 'stopped', mediaSessionId: op.id, kinds: op.kinds, reason: 'stopped_by_client' }); + op.reject(new PublishError({ reason: 'publish_cancelled', message: 'Publishing was cancelled' })); + }; +} diff --git a/src/lib/publish-media.test.ts b/src/lib/publish-media.test.ts new file mode 100644 index 0000000..d09ac47 --- /dev/null +++ b/src/lib/publish-media.test.ts @@ -0,0 +1,80 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, expect, test } from 'bun:test'; +import { inspectPublishOffer, reservePublish, supportsPublishCamera, usablePublishSender } from './publish-media'; + +const original = globalThis.RTCRtpSender; +afterEach(() => { globalThis.RTCRtpSender = original; }); +const caps = { microphoneInjection: true, cameraInjection: true, mediaInjectionTransport: 'direct' }; +const audio = { mimeType: 'audio/opus', clockRate: 48000, channels: 2 }; +const video = { mimeType: 'video/H264', clockRate: 90000, sdpFmtpLine: 'packetization-mode=1;profile-level-id=42e01f' }; + +function fixture(camera = true) { + globalThis.RTCRtpSender = { getCapabilities: (kind: string) => ({ codecs: kind === 'audio' ? [audio] : camera ? [video] : [] }) } as unknown as typeof RTCRtpSender; + const added: { kind: string; options: RTCRtpTransceiverInit }[] = []; + const preferred: RTCRtpCodec[][] = []; + const pc = { addTransceiver(kind: string, options: RTCRtpTransceiverInit) { + added.push({ kind, options }); + return { mid: String(added.length + 1), currentDirection: 'sendonly', sender: {}, setCodecPreferences(codecs: RTCRtpCodec[]) { preferred.push(codecs); } }; + } } as unknown as RTCPeerConnection; + return { pc, added, preferred }; +} + +// Browser-generated section shape. No rewritten/dummy-track SDP in production. +const sdp = 'v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=mid:2\r\na=sendonly\r\na=ssrc:100 cname:test\r\na=rtpmap:96 H264/90000\r\na=fmtp:96 packetization-mode=1;profile-level-id=42e01f\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:3\r\na=sendonly\r\na=ssrc:101 cname:test\r\na=rtpmap:111 opus/48000/2\r\n'; + +test('trackless reservations keep video then audio, exact codecs and the uplink cap', () => { + const f = fixture(); + const reservations = reservePublish(f.pc, caps); + expect(f.added).toEqual([ + { kind: 'video', options: { direction: 'sendonly', sendEncodings: [{ maxBitrate: 1000000 }] } }, + { kind: 'audio', options: { direction: 'sendonly' } }, + ]); + expect(f.preferred).toEqual([[video], [audio]]); + inspectPublishOffer(reservations, sdp); + expect([...reservations.offered]).toEqual(['audio', 'video']); + expect(usablePublishSender(reservations, 'audio')).toBe(reservations.transceivers.audio!.sender); +}); + +test('receive-only configuration never reserves upstream sections', () => { + const f = fixture(); + reservePublish(f.pc); + expect(f.added).toEqual([]); +}); + +test('microphone does not depend on a camera encoder', () => { + const f = fixture(false); + expect(supportsPublishCamera()).toBe(false); + const reservations = reservePublish(f.pc, caps); + inspectPublishOffer(reservations, ('v=0\r\n' + sdp.slice(sdp.indexOf('m=audio'))).replace('a=mid:3', 'a=mid:2')); + expect(f.added).toEqual([{ kind: 'audio', options: { direction: 'sendonly' } }]); + expect([...reservations.offered]).toEqual(['audio']); +}); + +test('missing SSRCs are unsupported without SDP surgery', () => { + const f = fixture(); + const reservations = reservePublish(f.pc, caps); + inspectPublishOffer(reservations, sdp.replaceAll(/a=ssrc:[^\r]+\r\n/g, '')); + expect([...reservations.offered]).toEqual([]); + expect(usablePublishSender(reservations, 'audio')).toBeUndefined(); +}); + +test('incompatible H.264 profile is not a camera encoder', () => { + globalThis.RTCRtpSender = { getCapabilities: () => ({ codecs: [{ ...video, sdpFmtpLine: 'packetization-mode=0;profile-level-id=42e01f' }] }) } as unknown as typeof RTCRtpSender; + expect(supportsPublishCamera()).toBe(false); +}); + +test.each(['42e01f', '42e02a', '42c020', '4d0028', '640c33'])('camera accepts profile and offered level %s unchanged', profile => { + const f = fixture(); + const offered = { ...video, sdpFmtpLine: 'packetization-mode=1;profile-level-id=' + profile }; + globalThis.RTCRtpSender = { getCapabilities: () => ({ codecs: [offered] }) } as unknown as typeof RTCRtpSender; + expect(supportsPublishCamera()).toBe(true); + reservePublish(f.pc, caps); + expect(f.preferred[0]).toEqual([offered]); +}); + +test.each(['42e01e', '42c00b', '4d001e', '640c1e', '12342a'])('camera rejects unsupported profile/level %s', profile => { + globalThis.RTCRtpSender = { getCapabilities: () => ({ codecs: [{ ...video, sdpFmtpLine: 'packetization-mode=1;profile-level-id=' + profile }] }) } as unknown as typeof RTCRtpSender; + expect(supportsPublishCamera()).toBe(false); +}); diff --git a/src/lib/publish-media.ts b/src/lib/publish-media.ts new file mode 100644 index 0000000..5f1a621 --- /dev/null +++ b/src/lib/publish-media.ts @@ -0,0 +1,65 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import { supportsPublish, type DevicePublishCapabilities, type PublishKind } from './publish'; + +export type PublishReservations = { + transceivers: Partial>; + offered: Set; +}; + +const H264_PUBLISH_PROFILE = /(?:^|;)\s*profile-level-id=(42e0|42c0|4d00|640c)([0-9a-f]{2})(?:;|$)/i; + +function codecs(kind: PublishKind): RTCRtpCodec[] { + if (typeof RTCRtpSender === 'undefined' || !RTCRtpSender.getCapabilities) return []; + return (RTCRtpSender.getCapabilities(kind)?.codecs ?? []).filter(codec => { + if (kind === 'audio') return codec.mimeType.toLowerCase() === 'audio/opus' && codec.clockRate === 48000 && codec.channels === 2; + const fmtp = codec.sdpFmtpLine ?? ''; + const profile = fmtp.match(H264_PUBLISH_PROFILE); + return codec.mimeType.toLowerCase() === 'video/h264' && /(?:^|;)\s*packetization-mode=1(?:;|$)/i.test(fmtp) + && !!profile && Number.parseInt(profile[2], 16) >= 0x1f; + }).sort((a, b) => Number(!/profile-level-id=42/i.test(a.sdpFmtpLine ?? '')) - Number(!/profile-level-id=42/i.test(b.sdpFmtpLine ?? ''))); +} + +export function supportsPublishCamera(): boolean { return codecs('video').length > 0; } + +/** Trackless reservations in the first offer, after both downstream sections. */ +export function reservePublish(pc: RTCPeerConnection, capabilities?: DevicePublishCapabilities): PublishReservations { + const result: PublishReservations = { transceivers: {}, offered: new Set() }; + if (!supportsPublish(capabilities)) return result; + for (const kind of ['video', 'audio'] as const) { + const preferences = codecs(kind); + if ((kind === 'video' && !capabilities?.cameraInjection) || !preferences.length) continue; + try { + const transceiver = pc.addTransceiver(kind, { + direction: 'sendonly', + ...(kind === 'video' ? { sendEncodings: [{ maxBitrate: 1_000_000 }] } : {}), + }); + transceiver.setCodecPreferences(preferences); + result.transceivers[kind] = transceiver; + } catch { + // Preserve viewing on implementations without usable codec preferences. + } + } + return result; +} + +/** Verify browser-generated SSRC-bearing upstream sections; never rewrite SDP. */ +export function inspectPublishOffer(reservations: PublishReservations, sdp: string): void { + const sections = sdp.split(/(?=^m=)/m); + for (const kind of ['audio', 'video'] as const) { + const transceiver = reservations.transceivers[kind]; + const section = sections.find(part => transceiver?.mid != null && part.split(/\r?\n/).includes(`a=mid:${transceiver.mid}`)); + const codec = kind === 'audio' ? /a=rtpmap:\d+ opus\/48000\/2/i : /a=rtpmap:\d+ H264\/90000/i; + if (section && /^a=sendonly\r?$/m.test(section) && /^a=ssrc:\d+ /m.test(section) && codec.test(section)) { + reservations.offered.add(kind); + } + } +} + +export function usablePublishSender(reservations: PublishReservations, kind: PublishKind): RTCRtpSender | undefined { + const transceiver = reservations.transceivers[kind]; + return reservations.offered.has(kind) && transceiver + && (transceiver.currentDirection === 'sendonly' || transceiver.currentDirection === 'sendrecv') + ? transceiver.sender : undefined; +} diff --git a/src/lib/publish.ts b/src/lib/publish.ts new file mode 100644 index 0000000..0d6b34b --- /dev/null +++ b/src/lib/publish.ts @@ -0,0 +1,56 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +export type PublishOptions = { audio: boolean; video?: boolean }; +export type PublishKind = 'audio' | 'video'; +export type PublishPhase = 'idle' | 'capturing' | 'starting' | 'accepted' | 'active' | 'stopped' | 'error'; +export type PublishFailureReason = 'publish_not_allowed' | 'publish_unsupported' | 'permission_denied' + | 'publish_busy' | 'publish_failed' | 'publish_timeout' | 'publish_cancelled' | 'disconnected'; +export type PublishFailure = { + reason: PublishFailureReason; + message: string; + detail?: string; + serverReason?: string; +}; +export type PublishState = { + phase: PublishPhase; + mediaSessionId: string | null; + kinds: PublishKind[]; + reason?: PublishFailureReason | 'stopped_by_client'; + message?: string; + detail?: string; + serverReason?: string; +}; +export type DevicePublishCapabilities = { + microphoneInjection: boolean; + cameraInjection: boolean; + mediaInjectionTransport?: string; +}; +export type PublishErrorEvent = PublishFailure & { mediaSessionId?: string }; + +/** Structured rejection from startPublish; branch on reason/detail, not message. */ +export class PublishError extends Error implements PublishFailure { + readonly reason: PublishFailureReason; + readonly detail?: string; + readonly serverReason?: string; + constructor(failure: PublishFailure) { + super(failure.message); + this.name = 'PublishError'; + this.reason = failure.reason; + this.detail = failure.detail; + this.serverReason = failure.serverReason; + } +} + +export const INITIAL_PUBLISH_STATE: PublishState = Object.freeze({ + phase: 'idle', mediaSessionId: null, kinds: Object.freeze([]) as unknown as PublishKind[], +}); + +export function supportsPublish(capabilities?: DevicePublishCapabilities): boolean { + return capabilities?.microphoneInjection === true && capabilities.mediaInjectionTransport === 'direct'; +} + +/** Value key: arriving/changed capabilities require fresh first-offer reservations. */ +export function publishCapabilitiesKey(capabilities?: DevicePublishCapabilities): string { + return capabilities ? `${capabilities.microphoneInjection}|${capabilities.cameraInjection}|${capabilities.mediaInjectionTransport ?? ''}` : ''; +} 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 new file mode 100644 index 0000000..29a6c8b --- /dev/null +++ b/src/lib/stream-error.ts @@ -0,0 +1,121 @@ +// Copyright 2026 Mobilerun +// SPDX-License-Identifier: Apache-2.0 + +import type { PublishFailureReason } from './publish'; + +/** + * Why a stream connection attempt failed (stream client contract v1). + * + * - `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 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 + * signaling protocol has no such message, so this package does not report it yet. + * - `unknown`: anything else, e.g. a handshake timeout. + */ +export type ConnectionErrorReason = + | 'credentials_unavailable' + | 'connection_refused' + | 'disconnected' + | 'device_unavailable' + | 'unknown'; + +/** + * 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 token or a `?token=` URL and are never forwarded. + */ +export interface StreamFailure { + reason: ConnectionErrorReason; + message: string; +} + +/** Fixed, credential-free text for a failure whose cause is an arbitrary exception. */ +export const STREAM_FAILURE_MESSAGES: Record = { + 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', + unknown: 'Stream connection attempt failed', +}; + +export type StreamErrorReason = ConnectionErrorReason | PublishFailureReason; + +/** Payload of `onError`; publish failures never change the viewer retry state. */ +export interface StreamError { + reason: StreamErrorReason; + message: string; + operation?: 'publish'; + mediaSessionId?: string; + detail?: string; + serverReason?: string; + /** + * 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; +} + +/** 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 first retry. Default `reconnecting`. */ + disconnected: string; + /** Message once retries are exhausted. Default `device stream unavailable`. */ + unavailable: string; + /** Retry button text. Default `Retry`. */ + retry: string; + microphone: string; + camera: string; + stopMicrophone: string; + stopCamera: string; + publishStarting: string; + publishPermissionDenied: string; + publishNotAllowed: string; + publishFailed: string; +} + +const DEFAULT_DEVICE_STREAM_LABELS: DeviceStreamLabels = { + connecting: 'connecting', + disconnected: 'reconnecting', + unavailable: 'device stream unavailable', + retry: 'Retry', + microphone: 'Microphone', + camera: 'Camera', + stopMicrophone: 'Stop microphone', + stopCamera: 'Stop camera', + publishStarting: 'Starting inputs', + publishPermissionDenied: 'Microphone or camera permission denied', + publishNotAllowed: 'Publishing is not allowed', + publishFailed: 'Could not publish inputs', +}; + +/** 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, + microphone: overrides?.microphone ?? DEFAULT_DEVICE_STREAM_LABELS.microphone, + camera: overrides?.camera ?? DEFAULT_DEVICE_STREAM_LABELS.camera, + stopMicrophone: overrides?.stopMicrophone ?? DEFAULT_DEVICE_STREAM_LABELS.stopMicrophone, + stopCamera: overrides?.stopCamera ?? DEFAULT_DEVICE_STREAM_LABELS.stopCamera, + publishStarting: overrides?.publishStarting ?? DEFAULT_DEVICE_STREAM_LABELS.publishStarting, + publishPermissionDenied: overrides?.publishPermissionDenied ?? DEFAULT_DEVICE_STREAM_LABELS.publishPermissionDenied, + publishNotAllowed: overrides?.publishNotAllowed ?? DEFAULT_DEVICE_STREAM_LABELS.publishNotAllowed, + publishFailed: overrides?.publishFailed ?? DEFAULT_DEVICE_STREAM_LABELS.publishFailed, + + }; +} + +/** Reconnect pill text: the label plus `(n/max)` for retry n, n counted as in `StreamError.attempt`. */ +export function reconnectPillLabel(label: string, attempt: number, maxAttempts: number): string { + return attempt >= 1 ? `${label} (${attempt}/${maxAttempts})` : label; +} diff --git a/src/lib/stream-reconnect.test.ts b/src/lib/stream-reconnect.test.ts index 3f6af39..5ffee67 100644 --- a/src/lib/stream-reconnect.test.ts +++ b/src/lib/stream-reconnect.test.ts @@ -12,13 +12,14 @@ 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. 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[] = []; @@ -33,6 +34,7 @@ function setup() { snapshots.push(s); }, schedule, + networkAvailable, random: NO_JITTER, }); // Simulate React: every remount request results in a mounted attempt. @@ -68,11 +70,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(); @@ -400,3 +414,262 @@ 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); + }); +}); + +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)'); + }); +}); + +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.attemptMounted(); + schedule.advance(45_001); + expect(controller.getSnapshot()).toEqual({ status: 'unavailable', 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.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: 'unavailable', attempt: 1 }); + expect(schedule.pendingCount).toBe(0); + expect(calls).toEqual({ remounts: 0, heals: 0 }); + 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(); +}); + +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: true }, + ]); + 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(); +}); + +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 dcd00ef..2f42f63 100644 --- a/src/lib/stream-reconnect.ts +++ b/src/lib/stream-reconnect.ts @@ -1,16 +1,19 @@ // 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 * 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). @@ -22,7 +25,7 @@ * - 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. */ @@ -39,6 +42,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 @@ -72,23 +77,28 @@ 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. */ onHeal(): void; + /** One call per counted failure, with the reason and whether retries stopped. */ + onError?(error: StreamError): void; schedule?: StreamReconnectSchedule; random?: () => number; + /** Unknown connectivity is optimistic; false pauses acquisition and retry timing. */ + networkAvailable?: boolean; } export interface StreamReconnectController { - /** The stream component (re)mounted; arm the connect watchdog. */ - attemptMounted(): 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; 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 @@ -98,9 +108,11 @@ export interface StreamReconnectController { * disabled β€” the new target applies immediately. */ shouldDeferTargetChange(): boolean; - /** Tab became visible / browser back online. */ + /** 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). */ + /** Manual retry; explicitly overrides advisory offline for one fresh attempt. */ retry(): void; dispose(): void; getSnapshot(): StreamReconnectSnapshot; @@ -110,11 +122,16 @@ export function createStreamReconnectController({ onRemount, onSnapshot, onHeal, + onError, schedule = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }, random = Math.random, + networkAvailable = true, }: StreamReconnectControllerOptions): StreamReconnectController { let enabled = false; - let status: StreamReconnectStatus = 'connecting'; + let disposed = false; + let forcedAttempt = false; + 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 @@ -147,26 +164,40 @@ export function createStreamReconnectController({ stabilityTimer = clearTimer(stabilityTimer); }; - const startAttempt = () => { - onRemount(); + 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 = (allowOffline = false) => { + if (!enabled || (!networkAvailable && !allowOffline) || disposed) return; + onRemount(allowOffline); // 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; + if (!networkAvailable && !everConnectedThisEpoch && !forcedAttempt) return; + forcedAttempt = false; failureLatched = true; 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); 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 @@ -187,7 +218,9 @@ export function createStreamReconnectController({ ); }; - const freshCycle = () => { + const freshCycle = (allowOffline = false) => { + forcedAttempt = allowOffline; + socketStarted = false; attempt = 0; failureLatched = false; everConnectedThisEpoch = false; @@ -197,12 +230,21 @@ export function createStreamReconnectController({ status = 'reconnecting'; emit(); onHeal(); - startAttempt(); + startAttempt(allowOffline); }; return { - attemptMounted() { + 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; @@ -216,14 +258,17 @@ export function createStreamReconnectController({ status = 'connecting'; emit(); } + if ((!networkAvailable && !forcedAttempt) || !startWatchdog) return; watchdogTimer = schedule.setTimeout(() => { watchdogTimer = null; - countFailure(); + countFailure({ reason: 'unknown', message: 'Connection attempt timed out' }); }, STREAM_CONNECT_TIMEOUT_MS); }, setDisabled() { + forcedAttempt = false; enabled = false; + disposed = false; clearAllTimers(); everConnectedThisEpoch = false; failureLatched = false; @@ -263,13 +308,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() { @@ -280,8 +325,31 @@ export function createStreamReconnectController({ return backoffTimer !== null || status === 'unavailable'; }, + setNetworkAvailable(available, initialCommit = false) { + if (disposed || available === networkAvailable) return; + networkAvailable = available; + if (forcedAttempt && socketStarted) return; + watchdogTimer = clearTimer(watchdogTimer); + backoffTimer = clearTimer(backoffTimer); + if (!available) { + if (status !== 'connected' && !forcedAttempt) { + status = 'unavailable'; + emit(); + } + return; + } + if (status === 'connected') return; + if (initialCommit && attempt === 0) { + status = 'connecting'; + emit(); + 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; @@ -296,10 +364,16 @@ export function createStreamReconnectController({ retry() { if (!enabled) return; - if (status === 'unavailable') freshCycle(); + if (!networkAvailable && (status === 'connected' || forcedAttempt)) return; + if (!networkAvailable || status === 'unavailable') { + clearAllTimers(); + freshCycle(!networkAvailable); + } }, dispose() { + forcedAttempt = false; + disposed = true; enabled = false; clearAllTimers(); }, 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 e762d1e..0e23f95 100644 --- a/src/styles.css +++ b/src/styles.css @@ -10,68 +10,66 @@ * 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; -@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. */ @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) ---- */ @@ -127,3 +125,62 @@ object-fit: contain !important; display: block !important; } + +/* Capture controls float above both video and the optional input-blocking overlay. */ +.mobilerun-device-stream .mr-publish-controls { + position: absolute; + z-index: 60; + bottom: max(16px, env(safe-area-inset-bottom)); + left: 50%; + transform: translateX(-50%); + pointer-events: none; + max-width: calc(100% - 24px); + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; +} +.mobilerun-device-stream .mr-publish-controls[data-dimmed='true'] .mr-publish-pill { opacity: 0.5; } +.mobilerun-device-stream .mr-publish-pill { + pointer-events: none; + transition: opacity 150ms ease; + display: flex; + padding: 4px; + gap: 4px; + border: 1px solid var(--mr-border, var(--border, #d4d4d4)); + border-radius: 999px; + background: var(--mr-card, var(--card, var(--mr-default-card, #fff))); + color: var(--mr-card-foreground, var(--card-foreground, var(--mr-default-card-foreground, #171717))); + box-shadow: 0 3px 16px #0003; +} +.mobilerun-device-stream .mr-publish-pill button { + pointer-events: auto; + display: grid; + place-items: center; + width: 40px; + height: 40px; + border: 0; + border-radius: 999px; + background: transparent; + color: inherit; + cursor: pointer; +} +.mobilerun-device-stream .mr-publish-pill button[aria-pressed='true'] { + background: var(--mr-publish-live, #b91c1c); + color: var(--mr-publish-live-foreground, #fff); +} +.mobilerun-device-stream .mr-publish-pill button:disabled { opacity: 0.45; cursor: default; } +.mobilerun-device-stream .mr-publish-pill button:focus-visible { outline: 2px solid var(--mr-ring, #737373); outline-offset: 2px; } +.mobilerun-device-stream .mr-publish-status { + position: absolute; + bottom: calc(100% + 8px); + width: max-content; + max-width: calc(100vw - 24px); + pointer-events: none; + padding: 6px 10px; + border-radius: 10px; + font: 12px/1.4 system-ui, sans-serif; + text-align: center; + color: var(--mr-card-foreground, var(--mr-default-card-foreground, #171717)); + background: var(--mr-card, var(--mr-default-card, #fff)); +}