diff --git a/docs/api/client-contract/messages.md b/docs/api/client-contract/messages.md new file mode 100644 index 00000000..eb2d41a8 --- /dev/null +++ b/docs/api/client-contract/messages.md @@ -0,0 +1,249 @@ +# Message decode tree + +**Audience:** Implementers of native HAPI clients (iOS / Android). This page specifies how to decode `DecryptedMessage.content` into renderable chat structure. This is the largest porting surface — the reference pipeline is `web/src/chat/` (~4600 lines); this page is its wire-level contract. Companion pages: [pagination](./pagination.md) (how messages arrive), [sse](./sse.md) (live delivery). + +Source of truth: `shared/src/schemas.ts` (`DecryptedMessageSchema`), `shared/src/messages.ts` (envelope helpers), `web/src/chat/normalize.ts`, `web/src/chat/normalizeUser.ts`, `web/src/chat/normalizeAgent.ts`, `web/src/chat/types.ts`, `hub/src/store/contentCodec.ts`. + +--- + +## Wire shape + +```ts +type DecryptedMessage = { + id: string // server uuid (optimistic rows: == localId until echoed) + seq: number | null // per-session insert counter + localId: string | null // client-generated id for optimistic reconciliation + content: unknown // the role-wrapped envelope — everything below + createdAt: number // hub receive time (epoch ms) + invokedAt?: number | null // when the agent consumed it (null = still queued) + scheduledAt?: number | null // future-scheduled sends +} +``` + +`content` is deliberately `unknown` on the wire. **Decoding must be total**: malformed content degrades to a stringified fallback — a client must never drop or crash on a message it does not recognize (with the two precise exceptions listed in [Fallback rules](#fallback-rules)). + +--- + +## Envelope + +`content` is a role-wrapped envelope: + +```ts +{ role: 'user' | 'agent', content: , meta?: unknown } +``` + +Unwrap algorithm (`unwrapRoleWrappedRecordEnvelope`, `shared/src/messages.ts`) — a record qualifies when it has a string `role` and a `content` key; if `content` itself is not one, also probe, in order: + +1. `content.message` +2. `content.data.message` +3. `content.payload.message` + +No envelope found ⇒ render the **whole** `content` as stringified agent text. `role` other than `user`/`agent` ⇒ stringify `record.content` as agent text. + +### `meta` + +Opaque record; carry it through. Known keys: + +| Key | Values | Meaning | +|---|---|---| +| `sentFrom` | `'webapp'`, `'telegram-bot'`, `'cli'`, … | Origin of a user message. **`'cli'` marks CLI-echo traffic**: user/assistant text containing ``, ``, ``, or `` tags renders as a monospace *cli-output* block instead of a chat bubble, and a `` block merges with its `` follow-up (`web/src/chat/reducerCliOutput.ts`). | +| `deliveryMode` | `'queue'` \| `'steer'` | Durable delivery intent of a user send (see [pagination](./pagination.md#send-constraints)). Absent = `queue`. | + +--- + +## Decode tree + +``` +DecryptedMessage.content +└─ unwrap envelope → { role, content: payload, meta? } + ├─ role: 'user' + │ ├─ payload is string → user text + │ ├─ payload {type:'text', text, attachments?} → user text (+ attachments) + │ └─ anything else → user text (stringified payload) + └─ role: 'agent' — dispatch on payload.type + ├─ 'codex' → generic agent family (payload.data.type dispatch) + ├─ 'output' → Claude SDK passthrough + agy (payload.data.type dispatch) + ├─ 'event' → AgentEvent union (payload.data) + └─ unknown → agent text (stringified payload) +``` + +--- + +## `role: 'user'` payloads + +Reference: `web/src/chat/normalizeUser.ts`. + +| Payload | Result | +|---|---| +| bare `string` | user text | +| `{type:'text', text: string, attachments?: AttachmentMetadata[]}` | user text with attachments. Each attachment is accepted only when `id`, `filename`, `mimeType` (strings), `size` (number), `path` (string) are all present; optional `previewUrl`. Invalid entries are skipped, an empty result means "no attachments". | +| anything else | user text = stringified payload (**never drop**) | + +--- + +## `role: 'agent'` — family `'codex'` + +`payload.type === 'codex'` (`AGENT_MESSAGE_PAYLOAD_TYPE`, `shared/src/modes.ts:8`) is the **generic agent envelope** used by the non-Claude-SDK flavors (codex, gemini, cursor, copilot, grok, opencode, pi, kimi; agy uses the `'output'` family below). Dispatch on `payload.data.type` (`web/src/chat/normalizeAgent.ts`): + +| `data.type` | Payload fields | Renders as | +|---|---|---| +| `message` | `message: string`, `id?` (stream id), `streamSnapshot?` | Agent text. If the text is a bare JSON object with review markers (`findings` / `overall_correctness` / `overall_explanation`), parse it as a **codex review** block instead — unless it is a Pi stream snapshot (`streamSnapshot: true` or `id` matching `/^pi-.+-turn-\d+-message-\d+-text-\d+$/`), which is always plain text. | +| `reasoning` | `message: string`, `id?` | Reasoning (thinking) block. | +| `error` | `message: string` | Error event row. | +| `tool-call` | `callId`, `name?`, `input?`, `description?`, `nativeTitle?/title?`, `nativeKind?/kind?`, `progress?` | Open a tool card keyed by `callId`. | +| `tool-call-result` | `callId`, `output`, `is_error?` | Complete the tool card with the same `callId`. | +| `generated-image` | `imageId`/`image_id`, `fileName`/`file_name`, `mimeType`/`mime_type`, `id?`, `source?` | Inline generated image (fetch via the images REST endpoint). Missing `imageId` ⇒ drop. | +| `context_compacted` | `trigger?`, `preTokens`/`pre_tokens` | `compact` event row. | +| `compact-summary` | `summary`, `tokensBefore?`, `estimatedTokensAfter?` | `compact-summary` event row. | +| `token_count` | `info: {last \| total \| …}`, `thread_id?`, `scope?` | Usage sample (event). Prefer `info.last*` over `info.total*`; `context_tokens` falls back to `input_tokens`; `modelContextWindow` → `context_window`. Unparseable usage ⇒ drop. | +| `thread_goal_updated` | `goal {threadId, objective, status, tokenBudget?, tokensUsed?, timeUsedSeconds?, createdAt?, updatedAt?}`, `threadId?`, `turnId?` | `thread-goal-updated` event. `status` ∈ `active\|paused\|budgetLimited\|usageLimited\|blocked\|complete`; invalid goal ⇒ drop. | +| `thread_goal_cleared` | `threadId?` | `thread-goal-cleared` event. | +| `plan` | `entries`/`items`/`steps`: list of steps | Synthetic completed `update_plan` tool pair (cursor flavor). Steps accept `step\|content\|text\|title\|description` + `status\|state` (normalized to `pending\|in_progress\|completed`). Empty plan ⇒ drop. | +| `plan_update` | `plan`/`update`/`items`/`steps` | Same, codex flavor. | +| `agent-run-start` / `agent-run-update` / `agent-run-trace` | run payload | Background agent-run event rows (windowed separately, see [pagination](./pagination.md#client-windowing-normative-recommendation)). | +| *anything else* | — | **Drop silently** (`normalize.ts`: unknown codex content returns `null`, not a stringified bubble). | + +Snake_case/camelCase field pairs above are both accepted — always probe both. + +--- + +## `role: 'agent'` — family `'output'` (Claude SDK passthrough) + +`payload.data` is a Claude Code SDK log entry, forwarded verbatim. Envelope-level fields on `data`: `uuid`, `parentUuid`, `isSidechain?`, `parentToolUseId?`, `timestamp?` (ISO-8601 execution-machine clock — parse to epoch ms, fall back to `createdAt`), and the flags below. + +**Skip filters — evaluate first** (`isSkippableAgentContent` / `isClaudeChatVisibleMessage`): + +- `data.isMeta` or `data.isCompactSummary` truthy ⇒ hidden. +- `data.type === 'rate_limit_event'` or `'tool_progress'` ⇒ hidden. +- `data.type === 'system'` with `subtype` **not** in `{api_error, turn_duration, microcompact_boundary, compact_boundary, away_summary}` ⇒ hidden. +- Empty `away_summary` / empty `agy_message` ⇒ hidden. + +Then dispatch on `data.type`: + +### `assistant` + +`data.message` = `{model?, content, usage?}`. `content` is a string (⇒ one text block) or an array of blocks: + +| Block | Fields | Renders as | +|---|---|---| +| `text` | `text` | agent text | +| `thinking` | `thinking` | reasoning | +| `tool_use` | `id`, `name`, `input` | tool card open (`description` convention: `input.description` when present) | + +Other block types are ignored. `message.usage` carries `input_tokens`, `output_tokens`, `cache_creation_input_tokens?`, `cache_read_input_tokens?`, `service_tier?`, `context_window?`. + +### `user` + +Despite the name, these arrive through the agent path (tool results and system-injected turns). `data.message.content` cases: + +| Case | Renders as | +|---|---| +| array with `tool_result` blocks `{tool_use_id, content, is_error?, permissions?}` | tool card completion. Prefer entry-level `data.toolUseResult` over the block's `content` when present. `permissions` = `{date, result:'approved'\|'denied', mode?, allowedTools?, decision?}` — merge into the tool card's permission state. | +| string content (any), or sidechain array-of-text | **sidechain marker** `{prompt}` — subagent prompts and system-injected turns; group under the parent Task tool card via `parentToolUseId` (fallback: exact prompt match). | +| non-sidechain array that is *entirely* `text` blocks | a real user message the CLI wrapped as output ⇒ render in the **user** lane. | +| `text` blocks mixed with tool results | agent text blocks. | + +### `system` subtypes → event rows + +| `subtype` | Fields | Event | +|---|---|---| +| `api_error` | `retryAttempt`, `maxRetries`, `error` | `api-error` | +| `turn_duration` | `durationMs`, `messageId?` | `turn-duration {durationMs, targetMessageId?}` | +| `microcompact_boundary` | `microcompactMetadata {trigger, preTokens, tokensSaved}` | `microcompact` | +| `compact_boundary` | `compactMetadata {trigger, preTokens}` | `compact` | +| `away_summary` | `content: string` | `recap {text}` | + +### `summary` + +`data.summary: string` ⇒ conversation-summary content block. + +### agy (Antigravity) — also in the `'output'` family + +| `data.type` | Renders as | +|---|---| +| `agy_message` | Agent text (`data.content`, per-turn `data.model?`). Empty ⇒ skip. Text starting `Inside the task-NNN log` ⇒ compact `AgyTaskLog` chip (synthetic completed tool pair). Echoed raw task results (`[Message] timestamp=…` trailer) are stripped from the prose. | +| `agy_tool_action` | Synthetic **completed** tool pair (tool-call + tool-result, same id — prefer `data.toolUseId`, falling back to the message id). `name === 'SYSTEM_MESSAGE'` ⇒ `AgyAsyncTask` background-task card; `name === 'ERROR_MESSAGE'` ⇒ `AgyError` card (`is_error: true`); otherwise map agy tool names to canonical ones (`run_command`→Bash, `view_file`→Read, `write_to_file`→Write, `replace_file_content`→Edit, `grep_search`→Grep, `list_dir`→LS) and translate arg keys (`CommandLine`→`command`, `TargetFile`→`file_path`, …), stripping agy's result preambles/trailers. See `normalizeAgent.ts` for the exact strip rules. | + +### Unknown `'output'` types + +A visible `data.type` not matched above ⇒ stringified agent text fallback (unlike the codex family, which drops). + +--- + +## `role: 'agent'` — family `'event'` + +`payload.data` is one `AgentEvent` (`web/src/chat/types.ts` lines 17–36). The union is **open-ended** — the last member is `{type: string} & Record`; tolerate unknown types (render generically or ignore, never crash). + +| `type` | Fields | +|---|---| +| `switch` | `mode: 'local' \| 'remote'` | +| `message` | `message: string` | +| `error` | `message: string` | +| `title-changed` | `title: string` | +| `limit-reached` | `endsAt: number`, `limitType: string` | +| `limit-warning` | `utilization: number` (0–1), `endsAt`, `limitType` | +| `ready` | — | +| `api-error` | `retryAttempt`, `maxRetries`, `error: unknown` | +| `turn-duration` | `durationMs`, `targetMessageId?` | +| `microcompact` | `trigger`, `preTokens`, `tokensSaved` | +| `compact` | `trigger`, `preTokens` | +| `compact-summary` | `summary`, `tokensBefore?`, `estimatedTokensAfter?` | +| `recap` | `text` | +| `thread-goal-updated` | `goal: ThreadGoal`, `threadId?`, `turnId?` | +| `thread-goal-cleared` | `threadId?` | +| `abort-restore` | `text` | +| *(catch-all)* | `{type: string, …}` | + +Several event rows are also synthesized by the other two families (system subtypes, `context_compacted`, `token-count`, `agent-run-*`) — the renderer should treat them uniformly. Note: `event`-family `message` rows whose text is a `Goal …` status line are filtered by the **hub** at ingest and from REST pages (`isRedundantGoalStatusEventContent`, `shared/src/messages.ts`); clients need no special handling. + +--- + +## Fallback rules + +| Situation | Behavior | +|---|---| +| No unwrappable envelope | stringify whole `content` as agent text | +| `role` not `user`/`agent` | stringify `record.content` as agent text | +| user payload unrecognized | stringify as user text | +| `'codex'` family, unknown `data.type` | **drop** (return nothing) | +| `'output'` family, hidden by skip filters | **drop** | +| `'output'` family, visible but unknown `data.type` | stringify as agent text | +| `'event'` family, `data` lacks a string `type` | stringify as agent text | + +"Stringify" = a stable JSON serialization (web: `safeStringify`) rendered as plain text. These are the only two legitimate drop paths; everything else must render something. + +--- + +## Truncation marker + +At ingest the hub head+tail-truncates any **string longer than 64 KiB found anywhere inside agent-role content** (`hub/src/store/contentCodec.ts`): the stored value becomes first 48 KiB + `\n…[hapi: truncated N chars]…\n` + last 12 KiB. User-role content is never truncated (it is delivered verbatim to the CLI). The operation is idempotent and applied deep (arrays/objects). + +Clients must render truncated strings as-is (recognizing the `…[hapi: truncated N chars]…` marker is optional polish), must not assume tool results are complete, and must never choke on the marker. + +--- + +## Permission requests are NOT messages + +Pending tool approvals never appear in the message stream. They live on the session object (`shared/src/schemas.ts:167-203`): + +```ts +session.agentState = { + requests?: Record + completedRequests?: Record // flat (AskUserQuestion) + | Record // nested (request_user_input) + }> +} +``` + +`agentState` updates arrive as a versioned SSE patch — apply it under the version gate described in [sse.md](./sse.md#versioned-patch-algorithm). Render pending `requests` as approval cards interleaved with the chat (the web reducer keys them to the matching `tool_use` when one exists); on resolution the entry moves to `completedRequests`, whose `status`/`answers` back-fill the tool card's permission state. Decide via `POST /api/sessions/:id/permissions/:requestId/approve` (`{mode?, allowTools?, decision?, answers?}`) or `…/deny` (`{decision?}`) — see [rest.md](./rest.md). Session-list badges come precomputed on `SessionSummary.pendingRequestsCount` / `pendingRequests` (≤ 5 entries). + +--- + +## Golden fixtures + +The golden fixtures in `shared/fixtures/chat/` are the executable form of this section: input `DecryptedMessage` samples paired with the canonical decoded projection, generated from the web pipeline. A native decode implementation is correct when it reproduces them exactly — when the fixtures and this page disagree, the fixtures win. diff --git a/docs/api/client-contract/pagination.md b/docs/api/client-contract/pagination.md new file mode 100644 index 00000000..52f7bae2 --- /dev/null +++ b/docs/api/client-contract/pagination.md @@ -0,0 +1,191 @@ +# Message pagination, windowing, and optimistic sends + +**Audience:** Implementers of native HAPI clients (iOS / Android). This page specifies the message paging protocol (`GET /api/sessions/:id/messages`), the epoch reset contract, the tail-sync loop, recommended client windowing, and the optimistic-send / cancel lifecycle. Companion pages: [sse](./sse.md), [messages](./messages.md), [rest](./rest.md). + +Source of truth: `shared/src/apiTypes.ts` (`MessagesQuerySchema`, `MessagesResponse`, `SendMessageRequestSchema`), `hub/src/web/routes/messages.ts`, `hub/src/sync/messageService.ts`, `hub/src/store/messages.ts`, reference client `web/src/lib/message-window-store.ts` + `web/src/lib/messages.ts`. + +--- + +## Position key + +Messages are ordered by a **compound position**, not by `seq` alone: + +``` +position = (at, seq) where at = invokedAt ?? createdAt +``` + +Ascending by `at`, ties broken by `seq`. Rationale: a queued user message sits at its `createdAt` until the agent consumes it, at which point `invokedAt` is stamped and the row **moves forward** to its invocation position. `seq` (per-session insert counter) alone would freeze queued rows at enqueue order. Every cursor in this protocol is therefore a `(seq, at)` **pair** — both halves are always required together. + +--- + +## `GET /api/sessions/:id/messages` + +Query parameters (`MessagesQuerySchema`; all numbers coerced from strings): + +| Param | Type | Constraint | +|---|---|---| +| `limit` | int | 1–200. **Default 50** when omitted (the web reference always sends 200). | +| `beforeSeq` + `beforeAt` | int + int | Page strictly older than this position. Pairwise required. | +| `afterSeq` + `afterAt` | int + int | Page strictly newer than this position. Pairwise required. | +| `untilSeq` + `untilAt` | int + int | Inclusive snapshot head for a catch-up loop. Pairwise required; **requires an `after` cursor**. | +| `epoch` | int ≥ 0 | Client's cached epoch. **Requires an `after` cursor.** | + +Validation rules (violations are `400 {"error":"Invalid query","issues":…}`): + +- `beforeAt`⇄`beforeSeq`, `afterAt`⇄`afterSeq`, `untilAt`⇄`untilSeq` must each be provided together. +- `before` and `after` are **mutually exclusive**. +- `until` and `epoch` are only valid alongside `after`. + +Session errors: `404` not found, `403` foreign namespace (see [errors](./errors.md)). + +### Response shape + +```ts +type MessagesResponse = { + messages: DecryptedMessage[] // ascending display order + page: { + direction: 'latest' | 'before' | 'after' + limit: number + epoch: number // server's current epoch for this session + reset: boolean // true ⇒ discard your window, this page replaces it + nextBeforeSeq: number | null // cursor for the next OLDER page + nextBeforeAt: number | null + nextAfterSeq: number | null // cursor for the next NEWER page + nextAfterAt: number | null + snapshotHeadSeq: number | null // newest position at snapshot time + snapshotHeadAt: number | null + hasMore: boolean // more rows exist in the requested direction + } +} +``` + +### `latest` (no cursor) + +Newest `limit` rows by position, **plus** — out of band — every uninvoked local user message (queued rows, including future-scheduled ones), so a fresh client still sees the queued bar even when those rows fall outside the page. The out-of-band rows are pinned to every latest response and do **not** affect the cursor: `nextBefore*` anchors to the oldest row of the position-ordered page proper. `hasMore` = at least one row exists before that. If a page contains only server-side-filtered rows (see [messages](./messages.md)), the hub auto-advances to older pages until it can return something or history is exhausted. + +### `before` + +Rows strictly older than the cursor. `nextBefore*` = oldest row of this page; `hasMore` = at least one row older than that. The response also carries the current `epoch` — compare it to your cached one (see below). + +### `after` + +Rows strictly newer than the cursor, bounded by an **inclusive snapshot head** = `min(until, currentHead)` (or whichever exists). This keeps a catch-up loop from chasing messages appended while it runs. Responses: + +- Client `epoch` ≠ server epoch ⇒ the server ignores the cursor and returns the **latest page with `reset: true`** (`direction: 'latest'`). +- Snapshot head ≤ cursor ⇒ empty page, `hasMore: false`, `nextAfter*` echoes the cursor. +- Otherwise: `nextAfter*` = last row's position, `hasMore` = `nextAfter < snapshotHead`. + +--- + +## Epoch + +`epoch` is a per-session monotonic counter (`message_epochs` table, starts at 0) that is bumped whenever history changes in a way that invalidates composite cursors (`hub/src/store/messages.ts`): + +- a new row lands **before** the current head position (out-of-order insert, e.g. transcript import with an earlier timestamp); +- a queued message is deleted (cancel); +- rewind / history replace (`replaceSessionMessagesFrom`); +- messages are copied/merged between sessions (both sides), fork hydration. + +Client contract: + +- **`after` request** — always send your cached `epoch`. On mismatch the server answers with the latest page and `reset: true`; **discard the entire local window** and replace it with that page. +- **`before` request** — the response's `page.epoch` may differ from your cached one; if it does, your cursors are meaningless: drop cursor state, flag the window for a latest reset, and run a fresh tail sync (web: `fetchOlderMessages` → `epoch-reset` outcome). +- A structural change is also announced live via the `messages-invalidated` SSE event — on the open session, clear the window and tail-sync from scratch. + +--- + +## Tail-sync loop + +Run after connect, after an SSE `resume: 'gap'` handshake, on session open, and when told to (`messages-invalidated`). Reference: `runTailSync` in `web/src/lib/message-window-store.ts`. + +1. **No usable state** (no newest cursor, no cached epoch, or a reset is pending): `GET …/messages?limit=200` (latest), replace/merge into the window, store `page.epoch`, `nextBefore*` (older-page cursor) and `snapshotHead*` (newest cursor). Done. +2. **Have cursor + epoch**: loop + - `GET …/messages?afterSeq&afterAt&epoch[&untilSeq&untilAt]&limit=200`, where `after` starts at your newest cursor and `until` is the `snapshotHead*` captured from the **first** response of the loop (fixes the target so the loop terminates). + - `page.reset` or `direction: 'latest'` ⇒ replace the window with this page; stop. + - Otherwise merge the rows, advance `after = nextAfter*`, update the newest cursor to `max(current, nextAfter)`; stop when `hasMore` is false. + - Guard: if `nextAfter` did not advance past the previous cursor, abort with an error (protocol violation, do not spin). + +New live rows keep arriving via the SSE `message-received` event; ingest them and advance the newest cursor to `max(current, incoming position)`. Only run one tail sync at a time per session; if events force another (e.g. a reset was flagged mid-loop), queue a trailing run. + +--- + +## Client windowing (normative recommendation) + +Constants from the web reference (`web/src/lib/message-window-store.ts`): + +| Constant | Value | Meaning | +|---|---|---| +| `PAGE_SIZE` | 200 | Request size for every page fetch. | +| `VISIBLE_WINDOW_SIZE` | 400 | Max regular rows kept in **tail** mode (following live bottom). | +| `HISTORY_WINDOW_SIZE` | 600 | Max regular rows kept in **history** mode (user scrolled back). | +| `OLDER_LOAD_WINDOW_SIZE` | 800 | Temporary cap while an older page is being merged (prepend). | +| `AGENT_RUN_WINDOW_SIZE` | 800 | Separate trim bucket for codex `agent-run-*` rows so background-agent traces don't evict chat. | + +Rules: + +- **Tail mode** trims from the top (oldest dropped). Dropping rows ⇒ set `hasMore: true` and recompute the older-page cursor from the oldest kept row. +- **History mode** trims from the bottom (newest dropped). Dropping newest rows means your window no longer reaches the tail ⇒ flag "latest reset required": on returning to tail mode, discard cursors and fetch a fresh latest page rather than trusting stale ones. +- **Queued rows are never trimmed** (user messages with `invokedAt === null`, see below) — they are re-merged after every trim. +- Persist the window (messages + cursors + epoch) per session for instant cold-start rendering; on re-activation with a persisted cursor, still fetch a fresh latest page first (another client may have advanced the session by many pages) and reconcile. + +--- + +## Optimistic sends + +Send: `POST /api/sessions/:id/messages` (see constraints below). Reference: `web/src/hooks/mutations/useSendMessage.ts`, `mergeMessages` in `web/src/lib/messages.ts`. + +Lifecycle: + +1. Generate a client-side `localId` and append an **optimistic row**: `{id: localId, seq: null, localId, invokedAt: null, scheduledAt, createdAt: now, status:'sending', content: {role:'user', content:{type:'text', text, attachments?}, meta:{deliveryMode}}}`. A row is *optimistic* iff `id === localId`. +2. On POST success: status → `queued` if the session is currently thinking, else `sent`. On failure: drop the row and restore the composer (or keep it as `failed` with a retry affordance when attachments are involved). +3. **Echo**: the hub emits `message-received` carrying the stored row (server `id`, real `seq`, same `localId`). Merging a stored row whose `localId` matches an optimistic row **replaces** the optimistic one, preserving the client-side `status` and any already-known `invokedAt` the server row lacks. Fallback when no `localId` echo matches: drop an optimistic `sent` row when a server user message lands within **10 s** of the same position. +4. **`messages-consumed {localIds, invokedAt}`** (SSE): stamp `invokedAt` and flip status to `sent` on matching rows (skip `failed` ones). This is what moves a message out of the queued bar and into the thread at its invocation position. +5. **`message-cancelled {messageId, localId?}`** (SSE): remove the row (match either id). + +**Queued semantics**: a user message is "queued" iff `invokedAt === null` **strictly** and `status !== 'failed'`. `undefined` means already-invoked (rows from pre-V8 hubs omit the field) — only rows explicitly carrying `null` belong in the queued bar. Server-side, rows sent without a `localId` are stamped invoked at insert and can never be queued. + +### Queued-state recovery + +After a reconnect whose handshake said `resume: 'gap'` (an `ok` resume replayed the consume/cancel events already), the consumed/cancelled events for your queued rows may have been lost. Reference: `web/src/lib/queued-state-reconciliation.ts`. + +1. Finish a tail sync. +2. Collect candidate `localId`s: user rows with `invokedAt === null`, excluding optimistic rows still `sending`/`failed`. +3. `POST /api/sessions/:id/messages/queued-state` with `{"localIds": […]}` (max 1000 per call; batch above that) → `{queuedLocalIds: string[], invokedLocalMessages: [{localId, invokedAt}]}`. +4. Apply `invokedLocalMessages` exactly like `messages-consumed`; drop candidates that are in **neither** list (deleted server-side). + +--- + +## Send constraints + +`POST /api/sessions/:id/messages` body (`SendMessageRequestSchema`): + +| Field | Type | Rules | +|---|---|---| +| `text` | string | Required (route also accepts empty text when `attachments` is non-empty). | +| `localId` | string | Optional but **required for `scheduledAt`**, and required in practice: without it the row is stamped invoked at insert (no queue/ack/cancel path). | +| `attachments` | `AttachmentMetadata[]` | Optional. Not allowed with `scheduledAt`. | +| `scheduledAt` | epoch ms | Optional. Must be ≤ now + **7 days**; requires `localId`; no attachments; never `steer`. | +| `deliveryMode` | `'queue'` \| `'steer'` | Optional, default `queue`. `steer` is honored only for **Pi-flavor** sessions and never for scheduled sends — the hub silently normalizes everything else to `queue`, and deferred/replayed delivery (reconnect backfill, retries, scheduled release) always degrades `steer` to `queue`. | + +Response `{"ok": true}`. Sending to an inactive session returns `409 {"error":"Session is inactive","code":"session_inactive"}` — resume/reopen first, and note the resumed session **may have a different id** (migrate drafts and re-target, see [rest](./rest.md)). + +--- + +## Cancel and steer + +**Cancel**: `DELETE /api/sessions/:id/messages/:messageId` — `:messageId` may be the server id **or** the `localId`. Response union (`CancelMessageResponseSchema`): + +| Response | Meaning | Client action | +|---|---|---| +| `{"status":"cancelled","localId":string\|null}` | Row deleted (or already gone). Bumps the epoch. | Remove the row. | +| `{"status":"invoked","message":DecryptedMessage}` | Too late — the agent consumed it before the cancel landed. | **Ingest the returned message** as the authoritative row (correct `invokedAt`, status `sent`); do not resurrect the queued snapshot. | + +Other subscribers learn the same outcome via `message-cancelled` / `messages-consumed` SSE events. + +**Steer a queued message into the current turn**: `POST /api/sessions/:id/messages/:messageId/steer` (Pi sessions) → `SteerQueuedMessageResponseSchema`: + +| Response | Client action | +|---|---| +| `{"status":"steered","localId"}` | Keep the row queued-side; it is being injected into the live turn. | +| `{"status":"invoked","message"}` | Already consumed — ingest the message. | +| `{"status":"failed","error","localId":string\|null}` | Surface the error; the row remains queued. | diff --git a/docs/api/client-contract/sse.md b/docs/api/client-contract/sse.md new file mode 100644 index 00000000..e6ae7872 --- /dev/null +++ b/docs/api/client-contract/sse.md @@ -0,0 +1,202 @@ +# SSE stream (`GET /api/events`) + +**Audience:** Implementers of native HAPI clients (iOS / Android). This page specifies the hub's server-sent-events stream: subscription model, framing, resume protocol, the `SyncEvent` union, and the versioned session-patch algorithm. Companion pages: [auth](./auth.md), [REST](./rest.md), [pagination](./pagination.md), [messages](./messages.md). + +Source of truth: `hub/src/web/routes/events.ts`, `hub/src/sse/sseManager.ts`, `hub/src/web/sseCompression.ts`, `shared/src/schemas.ts` (`SyncEventSchema`), reference client `web/src/hooks/useSSE.ts`. + +--- + +## Endpoint + +`GET /api/events` — long-lived `text/event-stream` response. + +| Query param | Values | Notes | +|---|---|---| +| `token` | JWT | Browser `EventSource` cannot set headers, so the auth middleware accepts `?token=` **on this path only** (`hub/src/web/middleware/auth.ts`). Clients that can set headers may use `Authorization: Bearer` instead. | +| `all` | `true` \| `1` | Global subscription: every event in the token's namespace. | +| `sessionId` | session id | Session-scoped subscription. | +| `machineId` | machine id | Machine-scoped subscription (web does not use this). | +| `visibility` | `visible` \| `hidden` | Initial visibility state. Anything other than the literal `visible` is treated as `hidden` (the default). See [Visibility](#visibility). | +| `lastEventId` | event id | Resume cursor for manually rebuilt connections. The standard `Last-Event-ID` **request header wins** over this param when both are present (auto-reconnecting EventSource implementations send the header). | + +Up-front checks, before any bytes stream: + +| Condition | Response | +|---|---| +| Hub sync engine not ready | `503 {"error":"Not connected"}` | +| `sessionId` unknown | `404 {"error":"Session not found"}` | +| `sessionId` in another namespace | `403 {"error":"Session access denied"}` | +| `machineId` unknown / foreign namespace | `404` / `403` (same pattern) | + +A `sessionId` may resolve to a canonical id (superseded/merged sessions); the subscription binds to the **resolved** id. + +--- + +## Framing + +Every frame is a standard SSE message whose `data:` line is one JSON-encoded `SyncEvent`: + +``` +id: 018f3c2a:412:9b1f00aa +data: {"type":"session-updated","sessionId":"...","data":{...}} +``` + +- **Broadcast events** (replayed and live) carry an `id:` field. +- **`connection-changed`, `heartbeat`, and `toast` frames carry NO `id`.** SSE cursors are sticky: a frame without `id` must keep the previously seen id (native `EventSource` does this automatically; hand-rolled parsers must replicate it). A heartbeat must never reset or blank your cursor. +- The server never sends `retry:`; reconnect policy is entirely client-owned (see [Reconnect policy](#reconnect-policy-normative-recommendation)). + +### Event id format + +`{epoch}:{seq}:{nsTag}` — treat as opaque; store and echo it back, never interpret it. + +| Part | Meaning | +|---|---| +| `epoch` | 8-char random string, fixed per hub **process**. A cursor from before a hub restart can never match. | +| `seq` | Integer, monotonically increasing per hub process (shared across all namespaces/sessions). | +| `nsTag` | First 8 hex chars of `sha256("{epoch}|{namespace}")` — binds the cursor to the namespace it was issued under. | + +### Replay ring + +The hub keeps the last **256** broadcast events, capped at **2 MiB** of JSON (oldest evicted first; the byte cap always keeps at least one entry). `toast` frames are not recorded (they are visibility-targeted, not broadcast). + +--- + +## Handshake and resume + +On subscribe the hub emits, **in this guaranteed order**: + +1. `connection-changed` — `{"type":"connection-changed","data":{"status":"connected","subscriptionId":"","resume":"ok"|"gap"}}` (no `id`). +2. Replayed events (each with its `id`), when `resume` is `ok`. +3. Live traffic. + +Live broadcasts that occur while the replay is being written are queued server-side and flushed after it, so ordering is preserved. + +| `resume` verdict | Meaning | Client action | +|---|---|---| +| `ok` | The replay that follows contains **every** event missed since the cursor. | Skip the REST resync entirely. | +| `gap` (or field absent — older hubs) | The hub cannot prove continuity. | Full refetch: session list, session detail(s), message tail sync, and queued-state reconcile for the open session (see [pagination](./pagination.md#queued-state-recovery)). | + +`gap` is returned whenever: no cursor was sent, the cursor is malformed, `epoch` differs (hub restarted), `nsTag` differs (cursor issued under a different namespace — e.g. after a token swap on the same hub), `seq` is out of range, or events between the cursor and the ring's oldest entry were evicted. + +### Cursor rules (normative) + +- Keep one cursor **per subscription filter set** (the `all` / `sessionId` / `machineId` tuple, plus hub + namespace). Never replay a cursor recorded under a different filter set — the hub would replay against the wrong filter and the `ok` verdict would be wrong for what you actually missed. +- Update the cursor **after** the event is durably handled. If handling throws, leave the cursor behind the event so the hub redelivers it (at-least-once delivery; handlers must be idempotent). +- Send the cursor on reconnect via `Last-Event-ID` header or `?lastEventId`. + +--- + +## Reconnect policy (normative recommendation) + +These constants come from the web reference client (`web/src/hooks/useSSE.ts`) and the hub (`hub/src/sse/sseManager.ts`); native clients should adopt them. + +| Constant | Value | Notes | +|---|---|---| +| Server heartbeat interval | 30 s | `{"type":"heartbeat","namespace":"…","data":{"timestamp":}}` | +| Staleness threshold | 90 s | No frames (of any kind) for 90 s ⇒ tear down and reconnect. | +| Watchdog tick | 10 s | Staleness check interval; **skip checks while backgrounded**. | +| Foreground-resume staleness check | 45 s | On app-foreground, if the last frame is older than 45 s, reconnect immediately (an OS suspend can kill the socket without any error ever surfacing; one missed heartbeat interval is already enough to distrust it). | +| Connect timeout | 10 s | An attempt that has not reached OPEN in 10 s is likely hung on a dead pooled socket — abandon it and retry on a fresh connection. | +| Backoff | 1 s base, ×2, cap 30 s | Delay for attempt *n* (n ≥ 1) = `min(cap, 1000 · 2^(n-1))`. **First retry is immediate** (jitter only). | +| Jitter | +0–500 ms | Uniform, added to every delay. | +| Slow ceiling | 300 s after 8 attempts | A hub that stays unreachable is usually down for hours; each retry through a relay costs a TLS handshake. | +| Backgrounded | defer retries | Do not schedule retries while backgrounded; reconnect immediately on foreground. Reset the attempt counter to 0 on every successful open. | + +Any received frame — heartbeat included — counts as activity for the staleness clock. Do not rely on a platform SSE library's built-in auto-reconnect: it will not honor the backoff, the background deferral, or the connect timeout. + +--- + +## Dual-subscription model + +The reference client holds **two** concurrent connections (`web/src/App.tsx`, `web/src/lib/appSseSubscriptions.ts`): + +1. **Global** — `all=true`, alive for the whole app session. Drives the session list, machine list, badges, toasts. +2. **Session** — `sessionId=`, recreated on every session switch. Drives the open chat. + +Hub-side delivery (`SSEManager.shouldSend`): + +| Event type | Delivered to | +|---|---| +| `connection-changed` | the connection itself | +| `heartbeat` | every connection | +| `toast` | every **visible** connection in the namespace, regardless of filter (no `id`, never replayed) | +| `message-received`, `scheduled-matured` | `all=true` connections + matching `sessionId` connections | +| `session-added` / `session-updated` / `session-removed` / `session-ended` / `messages-invalidated` / `messages-consumed` / `message-cancelled` | `all=true` connections + matching `sessionId` connections | +| `machine-updated` | `all=true` connections + matching `machineId` connections | + +**The global connection must also handle the message-stream events** (`message-received`, `messages-consumed`, `message-cancelled`, `scheduled-matured`): while a session connection is down (reconnect gap) or the session isn't open, the global pipe is the only one alive, and it must still keep queued/optimistic bookkeeping correct — mark local messages consumed, remove cancelled rows, and refresh session-list scheduled counts. The session-scoped connection additionally ingests `message-received` into the message window. + +The two connections have **no ordering relationship with each other** — the same `session-updated` patch can arrive on both, in either order. That is why the versioned-patch gate below exists. + +--- + +## SyncEvent union (13 types) + +Schema: `SyncEventSchema` in `shared/src/schemas.ts` (discriminated on `type`). All events except `connection-changed` carry `namespace?: string`. Ignore unknown event types. + +| `type` | Payload (beyond `type`, `namespace?`) | Client handling | +|---|---|---| +| `session-added` | `sessionId`, `data?: unknown` | Handle exactly like `session-updated` (the reference client shares the branch): a full `Session` upserts; anything else falls back to refetching the session list. | +| `session-updated` | `sessionId`, `data?: Session \| SessionPatch` | See [Versioned patch algorithm](#versioned-patch-algorithm). | +| `session-removed` | `sessionId` | Drop the session from the list, drop its detail cache, clear its message window. | +| `message-received` | `sessionId`, `message: DecryptedMessage` | Ingest into the message window; advance the tail cursor (see [pagination](./pagination.md)). Also fired for the caller's own send (the localId echo). | +| `messages-invalidated` | `sessionId` | Message history changed **structurally** (rewind, fork, import, clear). Session scope: discard the whole window and run a fresh tail sync. Global scope: refetch the session list. | +| `scheduled-matured` | `sessionId` | A scheduled message became due and was handed to the agent. Refetch list/queue indicators. | +| `session-ended` | `sessionId`, `reason?: 'completed'\|'terminated'\|'error'\|'handoff'\|'cleared'` | Session lifecycle signal (the `session-updated` flow still carries the state change). | +| `machine-updated` | `machineId`, `data?: Machine \| MachinePatch \| null` | Full `Machine`: upsert (remove when `active:false`). `null`: machine removed. Patch `{active?, activeAt?, updatedAt?}`: `active:false` ⇒ remove, otherwise refetch machines. `data` absent ⇒ refetch. | +| `toast` | `data: {title, body, sessionId, url}` | Show as in-app toast/banner. Only delivered to visible connections (see [Visibility](#visibility)). | +| `messages-consumed` | `sessionId`, `localIds: string[]`, `invokedAt: number` | The agent consumed queued user messages: stamp `invokedAt`, flip status to `sent`, remove from the queued bar. | +| `message-cancelled` | `sessionId`, `messageId`, `localId?` | A queued message was cancelled: remove the row (match by `messageId` **or** `localId`). | +| `heartbeat` | `data?: {timestamp}` | Feed the staleness watchdog. No other action. **Carries no `id`.** | +| `connection-changed` | `data?: {status, subscriptionId?, resume?: 'ok'\|'gap'}` | Handshake; see [Handshake and resume](#handshake-and-resume). Store `subscriptionId` for visibility reporting. **Carries no `id`.** | + +--- + +## Versioned patch algorithm + +The most bug-prone part of the protocol. `session-updated.data` is either a **full `Session`** or a **`SessionPatch`** (`shared/src/schemas.ts`); reference implementation `applySessionDetailPatch` in `web/src/hooks/useSSE.ts`. + +1. **Full session** (validates against `SessionSchema` and `data.id === event.sessionId`): replace the cached session wholesale. +2. **Patch** (validates against the strict `SessionPatchSchema` — unknown keys make it fail — and is non-empty): apply field-by-field as below. +3. **Absent or unparseable `data`**: fall back to refetching the session detail and list over REST. + +Patch application, field by field: + +- **Flat fields** — `active`, `thinking`, `activeTurnStartedAt`, `activeAt`, `model`, `modelReasoningEffort`, `effort`, `serviceTier`, `permissionMode`, `collaborationMode`, `copilotAgentMode`, `backgroundTaskCount`: last-write-wins assignment when present. +- **`updatedAt`** — max-monotonic: `updatedAt = max(cached.updatedAt, patch.updatedAt)`. A stale replay must never move the clock backward. +- **Versioned sub-patches** — `metadata`, `agentState`, `todos`, `teamState` each arrive as a wrapper `{version: number, value: …}`. Apply `value` and store `version` **only when `version` is strictly greater than the cached watermark**: + + | Wrapper | Cached watermark on `Session` | `value` type | + |---|---|---| + | `metadata` | `metadataVersion` | `Metadata \| null` | + | `agentState` | `agentStateVersion` | `AgentState \| null` | + | `todos` | `todosUpdatedAt` (treat absent as 0) | `TodoItem[]` | + | `teamState` | `teamStateUpdatedAt` (treat absent as 0) | `TeamState \| null` — `null` means "team deleted": clear it | + + Strictly greater, because the two SSE connections have **no shared ordering** — the same version can arrive twice and an older version can arrive after a newer one. Applying a stale `agentState` would resurrect resolved permission requests; a stale `metadata` would regress the resume/session-id state. (The web session-*list* path tolerates `>=` because re-deriving its summary from an equal version is idempotent; for a single-cache native client, strict `>` is the rule.) +- **Never wholesale-spread the wrapper.** `session.metadata` must become `wrapper.value` — assigning `{version, value}` itself into the session is a classic porting bug. +- **`scratchlistUpdatedAt`** — a bare refetch trigger: the patch carries no entries; its presence means "refetch `GET /api/sessions/:id/scratchlist`". Nothing else to apply. + +### Keep-alive noise + +The CLI keep-alive makes the hub re-broadcast a patch roughly **every 10 s per active session**, in which typically only `activeAt` moves. Recommendation (web: `isRenderIrrelevantSessionPatch`): treat a patch as render-irrelevant when the only effective change is an `activeAt` delta **< 60 s** (relative-time labels only change at minute boundaries); the session-list path ignores `activeAt` entirely. Apply the data if you like, but do not re-render or re-sort six times a minute for it. + +Reference list sort (web): `globalPinned` > `pinned` > `active` > `pendingRequestsCount` (among active) > `updatedAt` desc. + +--- + +## Visibility + +`POST /api/visibility` with body `{"subscriptionId": "", "visibility": "visible" | "hidden"}` → `{"ok": true}`. Errors: `400` invalid body, `404` unknown `subscriptionId` (or namespace mismatch), `503` hub not ready. Each new connection has a **new** `subscriptionId` — re-report after every reconnect (the web reference reports both of its connections on every foreground/background transition and retries a failed report after 2 s). + +Semantics (`hub/src/visibility/visibilityTracker.ts`, `hub/src/push/pushNotificationChannel.ts`): when **any** connection in the namespace is visible, the hub delivers notification events (ready / permission request / task result) as in-app **`toast` SSE frames to the visible connections** and suppresses Web Push for the namespace; Web Push fires only when no visible connection exists (or toast delivery reached zero connections). Native FCM devices (`POST /api/devices/register`) are independent of visibility and fire unconditionally — see [native-companion-contract](../native-companion-contract.md). + +Native rule: report `visible` on foreground and `hidden` on background, every time. A native client that stays `visible` while backgrounded suppresses its own (and every PWA's) hub-side push for the namespace, and receives its notifications only as toast frames nobody is looking at. + +--- + +## Gzip + +SSE responses are gzip-compressed when `Accept-Encoding` allows it (`hub/src/web/sseCompression.ts`): the hub drives zlib directly and issues a **sync flush after every chunk**, so events arrive immediately despite compression (~75 % ratio on real traffic). Negotiation is q-value-aware (`gzip;q=0` refuses, `*` honored); the response carries `Content-Encoding: gzip` with no `Content-Length`. + +Native clients must verify that their HTTP stack **decompresses the stream incrementally** (frames visible per flush, not buffered until EOF). If it does not — or if it only auto-decompresses when it injected `Accept-Encoding` itself — send `Accept-Encoding: identity` and take the uncompressed stream.