# Recorder HTTP API & examples

> Localhost HTTP endpoints for PitaFix's built-in web and native iOS recorder, step kinds, selectors, Live hand-over, X-Request-Id server attribution, and minimal scripts.

`pitafix record run` starts an authenticated localhost recorder daemon and passes the capture environment variables listed in [CLI reference](https://pitafix.app/wiki/agents/cli-reference.md#environment-variables). Every request requires `Authorization: Bearer $PITAFIX_RECORDER_TOKEN` and uses **`camelCase` JSON** (MCP recording tools use `snake_case`).

## Endpoints

| # | Method & path | Request / behavior | Key response fields |
| --- | --- | --- | --- |
| 1 | `GET /v1/health` | Liveness check | `{ "ok": true }` |
| 2 | `POST /v1/sessions` | Web: `{ baseUrl, dataSource, device?, seed?, role? }`<br>Native iOS (Swapify): `{ platform: "ios", dataSource, iosWorkDir?, iosNoBuild?, iosAttach?, iosDevice?, iosFullScreenshot? }` | `{ sessionId, runId, runDir, attributionUrl }` |
| 3 | `POST /v1/sessions/{id}/journey` | `{ id, name, intent?, section?, seed?, role? }` | `{ "journeyId": "<id>" }` |
| 4 | `POST /v1/sessions/{id}/step` | `{ kind, url?, selector?, text?, files?, private?, key?, scrollDx?, scrollDy?, waitMs?, cookie?, screen?, route? }` | `{ runId, stepId, journeyId, seq, status, error, url, route, title, screen, httpStatus, screenshotPath, treePath, attributionsCount, elements, networkErrors, consoleErrors, proxyRefused, live? }` |
| 5 | `POST /v1/sessions/{id}/inspect` | Read-only inspection without recording a step: `{ screenshot?: false }` | `{ url, route, title, elements, networkErrors, consoleErrors, proxyRefused, screenshotPath }` |
| 6 | `POST /v1/sessions/{id}/unreached` | `{ routes: [{ route, reason }] }` | `{ "ok": true, "count": N }` |
| 7 | `POST /v1/sessions/{id}/hold` | Blocks during Live hand-over (`PITAFIX_LIVE=1`) until Live stops | `{ "live": "running" \| "ended" }` |
| 8 | `POST /v1/sessions/{id}/finish` | `{ status: "passed" \| "failed" \| "cancelled", error?: "" }` | `{ runId, runDir, status, journeys, steps, failedSteps, frames, attributions }` |
| 9 | `POST /v1/attribution` | `{ requestId: "pfx_<runId>_<stepId>", files: [{ file, symbol?, lines?, tier?, source? }] }` (or flat single-file form) | `{ "ok": true, "matched": N }` |

> **Failure & Live semantics:** `POST /v1/sessions/{id}/step` returns HTTP `200` even when a step fails (`status: "failed"` + `error`) so callers can inspect the failure screenshot and `elements` — always check `res.status === "failed"`. Under `PITAFIX_LIVE=1`, `/step` returns `live: "started"` on hand-over (HTTP `409` while Live holds, `410` once stopped); call `/hold` before shutting down local servers.

## Step kinds & selectors

- **Web `kind` values:** `open` (`url`), `tap` (`selector`), `hover` (`selector`), `type` (`selector`, `text`, optional `private: true`), `select` (`selector`, `text`), `key` (`key`), `scroll` (`scrollDx`, `scrollDy`), `back`, `upload` (`selector`, `files`), `wait` (`waitMs`), `snapshot`, `set_cookie` (`cookie`), `clear_cookies`. Scripted web runs auto-accept `alert()`/`confirm()` and collect V8 JS coverage + source maps.
- **Native iOS (Swapify) `kind` values:** `open` (initial launch or deep link), `tap` (`testId`, `name`, `label`, or `text`), `reload` (`files` for Swift hot-reload), `wait`, `snapshot`. Requires Apple Silicon Mac, Xcode 26+, iOS 26+, `swapify` installed, and `swapify init --no-agents` run once; boots an isolated headless CoreSimulator device set deleted on exit (does not collect Swift line coverage).
- **`selector` fields:** `{ role?, name?, css?, testId?, label?, text?, placeholder?, exact?, nth? }`.
- **`route`:** optional normalized pattern (for example `"/items/:id"`) so dynamic URLs group cleanly.

## Minimal examples

### Node.js web capture (`capture.mjs`, zero dependencies)

```js
const base = process.env.PITAFIX_RECORDER_URL;
const headers = {
  "Content-Type": "application/json",
  Authorization: `Bearer ${process.env.PITAFIX_RECORDER_TOKEN}`,
};
const post = async (path, body) => {
  const res = await fetch(`${base}${path}`, { method: "POST", headers, body: JSON.stringify(body) });
  if (!res.ok) throw new Error(`${path}: ${res.status} ${await res.text()}`);
  return res.json();
};
const step = async (sid, body) => {
  const res = await post(`/v1/sessions/${sid}/step`, body);
  if (res.status === "failed") throw new Error(`step ${res.seq} failed: ${res.error}`);
  return res;
};

const diffScoped = process.env.PITAFIX_DIFF_SCOPED === "1";
const affected = (process.env.PITAFIX_AFFECTED_JOURNEYS || "").split(",").filter(Boolean);
const want = (id) => !diffScoped || affected.includes(id);

if (want("browse")) {
  const { sessionId } = await post("/v1/sessions", { baseUrl: "http://127.0.0.1:3000", dataSource: "fixture" });
  let failed = "";
  try {
    await post(`/v1/sessions/${sessionId}/journey`, { id: "browse", name: "Browse catalog", section: "Shop" });
    await step(sessionId, { kind: "open", url: "/", screen: "Home" });
    await step(sessionId, { kind: "tap", selector: { role: "link", name: "Catalog" }, screen: "Catalog" });
  } catch (err) {
    failed = err.message;
    throw err;
  } finally {
    await post(`/v1/sessions/${sessionId}/finish`, { status: failed ? "failed" : "passed", error: failed });
  }
}
```

### Native iOS via Swapify (`platform: "ios"`, `kind: "mobile"`)

Use the same `post` / `step` helpers with `platform: "ios"`:

```js
const { sessionId } = await post("/v1/sessions", { platform: "ios", dataSource: "fixture" });
let failed = "";
try {
  await post(`/v1/sessions/${sessionId}/journey`, { id: "today", name: "Today tab", section: "Main" });
  await step(sessionId, { kind: "open", screen: "Today", route: "/today" });
  await step(sessionId, { kind: "tap", selector: { label: "Settings" }, screen: "Settings", route: "/settings" });
} catch (err) {
  failed = err.message;
  throw err;
} finally {
  await post(`/v1/sessions/${sessionId}/finish`, { status: failed ? "failed" : "passed", error: failed });
}
```

### Server-side attribution probe (Rails / Rack middleware)

The web recorder injects `X-Request-Id: pfx_<runId>_<stepId>` on every browser request. Read that header on the server and post executed repo-relative files to `$PITAFIX_ATTRIBUTION_URL`:

```ruby
class PitaFixAttributionMiddleware
  def initialize(app) = @app = app
  def call(env)
    status, headers, body = @app.call(env)
    if (url = ENV["PITAFIX_ATTRIBUTION_URL"]) && (req_id = env["HTTP_X_REQUEST_ID"])&.start_with?("pfx_")
      uri = URI(url)
      req = Net::HTTP::Post.new(uri.request_uri, { "Content-Type" => "application/json", "Authorization" => "Bearer #{ENV["PITAFIX_RECORDER_TOKEN"]}" })
      req.body = JSON.generate({ requestId: req_id, files: executed_repo_files })
      Net::HTTP.start(uri.host, uri.port) { |h| h.request(req) }
    end
    [status, headers, body]
  end
end
```
