# Live updates (WebSocket)

> Push updates to browsers the moment a check finishes; webhooks for servers.

activQC by wavbee pushes status changes to browsers over an Action Cable WebSocket so your UI reacts the moment a background check, fix, run, review, master render, or stem split finishes — instead of polling every few seconds.

## WebSocket vs webhooks

Use the right channel for each job:

| Use case | Channel | Why |
|---|---|---|
| Browser UIs (embedded builder, hosted console, your own Draft API frontend, mastering/stems UI) | **WebSocket (Action Cable)** | Sub-second push when background work finishes; no idle polling. |
| Server-to-server pipelines (delivering to DSPs, updating your database, triggering downstream jobs) | **Webhooks** | HMAC-SHA256 signed, retried with exponential backoff, and recorded in the event log with redelivery. |

Validation itself (`POST /v1/qc/validate` and `POST /v1/release_drafts/:id/validate`) stays plain HTTP so every request keeps idempotency, caching, and the OpenAPI contract. The socket only tells the browser *when* to re-validate or re-fetch.

Nothing depends on the socket for correctness. If a corporate proxy blocks WebSockets or the connection drops, the client falls back to HTTP polling automatically.

## Authentication

Every socket connection is bound to a single tenant and scope. **Never put an API key (`wqc_live_…` or `wqc_test_…`) in a WebSocket URL or header — the server rejects it immediately.**

| Surface | Endpoint | Credential | Scope |
|---|---|---|---|
| Hosted / tenant console | `/cable` | Signed-in console session cookie | That console's active tenant |
| Embedded builder (`<wavbee-release-builder>`) | `/embed/cable` | HttpOnly `wqc_embed_session` cookie | That embed's draft, its submitted run, and its uploads only |
| Your own browser UI (Draft API / custom frontend) | `/cable` | Short-lived, single-use **cable token** (`wqc_ct_…`) | Token's tenant, optionally narrowed to a `draft_id` and/or `run_id` |

### Minting a cable token

From your backend (holding your API key), call `POST /v1/realtime/tokens`:

```bash
curl -X POST "$ACTIVQC_BASE_URL/v1/realtime/tokens" \
  -H "Authorization: Bearer wqc_test_..." \
  -H "Content-Type: application/json" \
  -d '{ "draft_id": "rd_7fK2aBcDeFgHiJkLmNoPqRsT" }'
```

Response (`201 Created`):

```json
{
  "object": "realtime.token",
  "token": "wqc_ct_9f3c...",
  "expires_at": "2026-11-23T12:10:00Z",
  "url": "wss://YOUR-ACTIVQC-HOST/cable",
  "scope": {
    "draft_id": "rd_7fK2aBcDeFgHiJkLmNoPqRsT",
    "run_id": null
  }
}
```

- Tokens expire after **10 minutes** and are **single-use**: the server stores only the SHA-256 digest and marks the token consumed on handshake. Mint a fresh token when reconnecting.
- Pass the token either in the `Sec-WebSocket-Protocol` header (`["actioncable-v1-json", "wqc_ct_..."]`) or as `?token=wqc_ct_...` (allowed because the token is short-lived and single-use).
- Omit `draft_id` and `run_id` to mint a tenant-scoped token, or pass either to restrict which streams the browser may join.
- Ensure your browser's origin is registered in your tenant's allowed origins (`frame_ancestors` under **Developers → Embed**).

## Subscribing (`LiveChannel`)

Connect with `@rails/actioncable` (or any Action Cable JSON client) and subscribe to `LiveChannel` with `{ stream, id }`:

```js
import { createConsumer } from '@rails/actioncable'

const { token, url } = await fetch('/your-backend/qc-cable-token', { method: 'POST' }).then((r) => r.json())
const consumer = createConsumer(`${url}?token=${encodeURIComponent(token)}`)

const sub = consumer.subscriptions.create(
  { channel: 'LiveChannel', stream: 'draft', id: 'rd_7fK2aBcDeFgHiJkLmNoPqRsT' },
  {
    received(data) {
      if (data.event === 'check.updated') {
        // Re-validate once over HTTP to fetch the new findings.
      }
    },
  },
)
```

Available streams:

| `stream` | `id` | What arrives |
|---|---|---|
| `draft` | `rd_…` (`ReleaseDraft` public id) | `check.updated` and `fix.updated` for uploads referenced in the saved draft, plus `run.updated` and `review.decided` once submitted |
| `upload` | Builder upload `id` (signed id from `/v1/builder/uploads`) | `check.updated` and `fix.updated` for that cover or audio upload (useful before a draft is saved) |
| `run` | `QcRun` integer id | `run.updated` and `review.decided` |
| `mastering_session` | `MasteringSession` integer id | `mastering_session.updated`, plus `render.updated` and `stems.updated` for child jobs |
| `render` | `MasteringRender` integer id | `render.updated` |
| `stems` | `StemSeparation` integer id | `stems.updated` |

Subscriptions outside the principal's tenant or scope are rejected by the server.

## Events

Payloads are intentionally small (ids and statuses only). Fetch the full findings, URLs, or decisions through the regular HTTP endpoints you already call.

| `event` | Streams | Payload fields | Client action |
|---|---|---|---|
| `check.updated` | `upload`, `draft` | `check` (`cover_read`, `cover_crosscheck`, `audio_scan`, `edge_silence`), `status`, `upload_id` | Call validate once |
| `fix.updated` | `upload`, `draft` | `kind` (`audio_fix`, `trim`, `cover_fix`), `status`, `upload_id` | Fetch fix status (`/v1/builder/fixes/:id`, `/cover_fixes/:id`, `/trims/:id`) |
| `run.updated` | `run`, `draft` | `id`, `status`, `verdict`, `final_decision`, optional `track_number` | Fetch `GET /v1/qc/runs/:id` (and `/report`, `/clarifications` when completed) |
| `review.decided` | `run`, `draft` | `id`, `review_case_id`, `decision`, `final_decision` | Refresh `GET /v1/qc/runs/:id` |
| `mastering_session.updated` | `mastering_session` | `id`, `status` | Fetch `GET /v1/mastering/sessions/:id` |
| `render.updated` | `render`, `mastering_session` | `id`, `mastering_session_id`, `status` | Fetch render or session |
| `stems.updated` | `stems`, `mastering_session` | `id`, `mastering_session_id`, `status` | Fetch stems or session |

## Reconnect and fallback

Reconnect with exponential backoff (500 ms, 1.5 s, 3.5 s), minting a fresh single-use token before each retry. After 3 consecutive failures, stop reconnecting and switch to HTTP polling (every 4 s for pending artwork/audio checks, 2 s for fixes, runs, mastering, and stems). The built-in builder and console do this automatically via `useLiveChannel`.
