# Quickstart: zero to a live embed in 30 minutes

This is the timed path the acceptance criterion API-03 describes: an integrator
starts with nothing and ends with a published workbook embedded in their own
page, watching row writes arrive over the WebSocket event stream. Every step has
a `run-wb` CLI form except claiming, which is a human sign-in (the browser, or
the raw HTTP API with a session cookie). The scripted walk that
runs this path against staging and prints per-step timings is
`verification/src/journeys/api03-quickstart-walk.ts`
(`pnpm --filter @workbookrun/verification journey:api03-walk`).

Everything here was verified live on staging with the published CLI.

## What you need

- Node.js ≥ 20.
- A staging or production sign-in for the two human-only steps (claim and
  publish). Claiming is session-only; publishing bills, so the account needs a
  payment method on file (`run-wb` prints the billing-portal hint when publish
  answers `402 payment_required`).
- A browser or host page for the final iframe.

Staging is used throughout; drop `WB_ENV=staging` (and the `.staging.` host
pieces) for production.

## Step 1 — Create a workbook and capture its token

```bash
export WB_ENV=staging
npx -y run-wb@latest create "quickstart" --show-secrets --use
# → workbook id, agent token (wbt_…, printed once) and a claim link
```

`--use` saves the token and workbook id for the later commands. The token prints
once — copy it now. The workbook starts unclaimed; the claim link is the
handoff you will use in step 3.

## Step 2 — Add a table with rows

The fastest path from zero to a real table is a CSV import (create mode
infers the schema from the file):

```bash
cat > tasks.csv <<'CSV'
title,done
Write the quickstart,true
Embed it in our docs,false
CSV

npx -y run-wb@latest import tasks.csv --table tasks --mode create
```

Check it landed:

```bash
npx -y run-wb@latest events --after 0
WORKBOOK_ID=$(npx -y run-wb@latest status --json | node -e 'process.stdin.on("data",d=>console.log(JSON.parse(d).workbook.id))')
```

## Step 3 — Claim the workbook (session step)

Publishing requires an owner. Sign in to
`https://app.staging.workbook.run` in a browser, open the claim link from
step 1, and claim the workbook into your account. (Or run the same flow over
the API with your session cookie:

```bash
CLAIM_CODE=$(echo "$CLAIM_URL" | sed 's|.*/claim/||')
curl -s -X POST "https://api.staging.workbook.run/v1/workbooks/$WORKBOOK_ID/claim" \
  -H "Cookie: $SESSION_COOKIE" -H 'Content-Type: application/json' \
  -d "{ \"claimToken\": \"$CLAIM_CODE\" }"
```

)

## Step 4 — Publish

```bash
npx -y run-wb@latest publish
```

A `402 payment_required` here means the account has no card on file — open the
billing portal (`https://app.staging.workbook.run` → Billing), add one, and
retry. Publishing is what turns on the public `/p/` surface the embed rides.

## Step 5 — Mint an embed grant

Minting before publishing is refused (`409`, "publish it first"). The
workbook's agent token acts as the owner:

```bash
npx -y run-wb@latest embed add --label "quickstart embed" --expires-in-hours 24
# → the grant id and an embed URL: https://app.staging.workbook.run/p/<id>?embed=…
```

The URL is the embed — an iframe-ready `/p/` view whose access is the grant,
so treat the whole URL as a secret. A read grant (the default) is read-only,
revocable, and optionally expiring; `--mode edit` needs the deployment's
embed-edit flag plus `--write-tables`, `--allowed-origins` and an expiry of at
most 24 hours. `run-wb embed ls` lists grants and `run-wb embed revoke <id>`
ends one. Without the CLI, the same call is `POST /v1/workbooks/:id/embeds`
with `{ "label": …, "expiresInHours": … }`.

## Step 6 — Embed it in a host page

The embed URL from step 5 now renders for anyone. In your own page:

```html
<iframe
  src="https://app.staging.workbook.run/p/<workbookId>?embed=<grant token>"
  width="960" height="600"
  allow="clipboard-write"
></iframe>
```

Load the host page: the grid renders the `tasks` table with the two imported
rows. Note the staging caveat the walk records: the embed shell on
`api.staging.workbook.run` serves an app-shell whose entry asset 404s today —
use the `app.staging.workbook.run` host until that is fixed.

## Step 7 — Watch a write arrive live

While the embed is open, insert a row through the workbook API. The event
stream is served by the edge at `/api/events` (a WebSocket — or plain HTTP
polling with `after=<seq>`; a WS upgrade cannot carry headers, so the credential
rides the URL):

```ts
// quickstart-ws.ts — run with: node --experimental-websocket quickstart-ws.ts
// Replace the two placeholders with your workbook id and step-1 agent token.
const WORKBOOK_ID = 'wb_XXXXXXXX';
const TOKEN = 'wbt_XXXXXXXX';
const EDGE = 'https://api.staging.workbook.run';

// Token writes exchange for short-lived signed claims first.
const res = await fetch(`${EDGE}/v1/workbooks/${WORKBOOK_ID}/claims`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${TOKEN}` },
});
const { claims } = (await res.json()) as { claims: string };
const vmHost = `${WORKBOOK_ID.toLowerCase().replace('_', '-')}.vms.staging.workbook.run`;

const socket = new WebSocket(
  `wss://api.staging.workbook.run/api/events?workbook=${WORKBOOK_ID}&after=0&token=${encodeURIComponent(TOKEN)}`,
);
socket.onmessage = async (m) => {
  const msg = JSON.parse(String(m.data)) as { kind: string; event?: { seq: number; type: string } };
  if (msg.kind === 'hello') {
    const r = await fetch(`https://${vmHost}/api/tables/tasks/rows`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-WB-Claims': claims, 'X-WB-Workbook': WORKBOOK_ID },
      body: JSON.stringify({ rows: [{ title: 'live update', done: true }], clientOpId: 'quickstart-1' }),
    });
    console.log(`insert: ${r.status}`);
  } else if (msg.kind === 'event') {
    console.log(`live: seq ${msg.event?.seq} ${msg.event?.type}`); // rows.changed
    socket.close();
  }
};
```

The write lands with `201` and the `rows.changed` event arrives on the open
socket within a beat of the insert (94 ms on the timed staging walk). A plain
HTTP poll of the same stream works too:

```bash
curl -s "https://api.staging.workbook.run/api/events?workbook=$WORKBOOK_ID&after=0&token=$WB_TOKEN"
# → { "events": [ … ], "latest": N, "resync": false }
```

## Where to go next

- The full API surface, scopes, and error shapes: [the integrator guide](./integrator-guide.md).
- Setting up MCP clients: the in-app `/docs` route (Settings → Documentation).
- Revoking the embed: `run-wb embed revoke <id>` (or
  `DELETE /v1/workbooks/:id/embeds/:embedId`) — the iframe stops rendering on
  its next load.
