Files
hapi/docs/api/client-contract/sse.md
T
Junmo KimandGitHub 523decdf86 fix(hub): fold repeated ACP tool-call updates into one row per callId (#2350)
* feat(shared): read the callId of a supersedable tool-call row

ACP agents re-emit the same tool call under a stable callId on every
state tick, and the timeline folds all of those rows into one card. The
hub and the web both need to recognise the rows that may be superseded,
so add `getToolCallId`, mirroring `getReasoningStreamId`/`getLiveReasoningStreamId`.

Only `codex`/`tool-call` payloads match. The `tool-call-result` that
shares the callId is a different row type that carries completion, so it
never matches and is never dropped. Anything unrecognised reads as null
("keep it").

* fix(hub): fold ACP tool-call updates into one row per callId

ACP agents re-emit a tool_call agent message for the first tool_call and
again for every tool_call_update, all under one callId, and the hub stored
each as its own row. History pages therefore filled with 2-4 duplicate
tool-call rows per call that the web then folded back into a single card
by callId.

Route agent tool-call messages (getToolCallId != null) through an upsert:
scan the session tail for a live tool-call row with the same callId,
stopping at a tool-call-result with that callId or at a user message row
(both mean the incoming message is a new call). On a match, merge the new
payload into the stored row in place — non-null new values win for
name/input/nativeTitle/nativeKind/nativeName/nativeArgs/status so a
status-only tick cannot erase an earlier tick's input — and keep the
row's id, seq, createdAt and localId. The content swap follows the
queued-message edit pattern (no new seq, no content_revision bump).

The post-store broadcast is unchanged (session-room update + web
message-received) and now carries the existing row's id/seq with the
merged content, which the web window store already upserts by id.
Nothing is deleted: result rows, permissions, localId resend handling
and non-tool messages behave exactly as before.

* fix(hub): never regress a merged tool-call row's status

A later tool-call tick that re-emits status pending (agents normalize a
missing/unknown status to pending, so OpenCode permission rounds resend
it after the call already ran) overwrote an earlier in_progress or
terminal status under the plain newest-non-null-wins merge.

Merge status by progression rank instead: pending < in_progress <
completed/failed. The merged row keeps the higher rank, so a running or
finished call never falls back to pending, and a terminal status always
wins over a non-terminal one in either direction. completed/failed share
the terminal tier and ties keep the newer value; unrecognized status
strings rank below every known state so they cannot regress one either.

Also pin the behaviors the upsert relies on with tests: the 200-row
lookback boundary on both sides, a tool-call-result for a different
callId not stopping the scan, nativeName/nativeArgs/progress merging,
and the handler re-broadcasting the existing row id/seq through both the
session-room update and web message-received without storing an extra
row.

* fix(hub): stamp derived tool state at merge time and skip no-op tool-call writes

A merged tool-call row keeps its first snapshot's createdAt for stable
ordering, but the session's derived TodoWrite/team versions gate on
strictly advancing timestamps (todos_updated_at and team_state_updated_at
only accept candidates greater than the stored watermark), so a refined
snapshot arriving on a later tick of the same callId was rejected and the
session's todo list stayed at its first snapshot. Stamp those versions at
merge time instead.

A re-emitted tick whose payload changes nothing now skips the row write
entirely: only observable content changes touch the database.

* fix(web): recover merged tool-call rows after an SSE replay gap

A gap resume (resume: 'gap') cannot prove continuity, and in-place
tool-call merges keep the row's original cursor position, so the
cursor-based tail sync after a gap re-delivered new rows but never the
merged content of rows the window already held. Tool cards could stay
stuck on their first snapshot until a reload.

On the gap path of both connect handlers, reconcile the window from an
authoritative latest page applied as an upsert: rows in the response
replace the held rows by id, while already-loaded rows older than the
latest page and the hasMore/oldest cursor and context survive; an older
load caught in flight is invalidated like on every tail sync and is
re-requested by the user's scroll. Replacing the whole window is not an
option here: a fresh session subscription is always a gap verdict, so
every session switch-back would throw away the user's scrolled-up
history. Rows older than the latest page are not re-fetched; a live
tool-call tick always updates a row inside the newest page, and a
failed recovery fetch leaves the flag set so the next sync retries the
latest page. Cold and structurally invalidated windows keep the plain
reset choreography.

* fix(web): catch up the disconnected interval before the gap-recovery upsert

Gap recovery fetched only the newest page and applied it as an upsert,
so a warm window whose cached tail sat below the page's oldest row kept
a permanent hole: rows that arrived while disconnected between the
cached tail and the page vanished, and the advanced newest cursor never
filled them (cursor syncs only return rows after their cursor).

Run a plain cursor sync first so the window catches up every row it
missed, then apply the authoritative latest page as an upsert to
refresh in-place merged rows. One extra round trip on reconnect; the
upsert alone stays correct for windows that are already contiguous.

* fix(web): replace retained rows when gap recovery observes a different epoch

The recovery upsert requested the latest page without an epoch and the
hub always answers reset:false for latest requests, so rows deleted
while disconnected survived: another client's rewind deletes rows and
bumps the epoch, but the missed messages-invalidated event left the
window's requiresLatestReset false and nothing detected the change.

Compare the response's epoch with the window's epoch in the latest-page
branch and fall back to a full replacement on mismatch. The cursor
catch-up that now precedes the upsert already carries the window epoch
and gets the hub's reset verdict, so this closes the remaining window
where the upsert runs without a preceding successful epoch-carrying
sync.

* fix(web): require a successful catch-up before the gap-recovery upsert

runTailSync resolves normally after catching a request error, so the
recovery continued to the latest-page reconciliation even when the
catch-up failed. With a cached tail at row 10 and the server head at
310, a failed after request followed by a successful latest request
retained row 10 alongside rows 111-310 and advanced the newest cursor
to 310: rows 11-110 became unreachable through ordinary tail or older
paging, and the successful latest response cleared the failure warning.

Fold the recovery into the tail sync itself: the pendingGapRecovery run
catches the window up through the ordinary cursor phase and only
reconciles the latest page once that phase completed without error. A
reset verdict inside the catch-up already replaced the window
authoritatively, so the recovery flag is simply consumed there. On a
catch-up failure the catch skips the reconciliation, keeping the
original cursor, the flag for the next sync's retry, and the visible
warning.

* fix(web): keep the loaded history budget across the gap-recovery upsert

applyLatestResponse always trimmed the merged window to the 400-row
tail budget, even when only refreshing it in place. A reader with 600
loaded history rows therefore lost the oldest rows on a same-epoch
reconnect with no new messages, shifting their reading anchor even
though nothing on the server changed.

Size the recovery upsert's trim to the window's own history budget,
capped at the 800-row older-load ceiling: rows the reader already
loaded are preserved on a no-news recovery instead of being re-evicted.
Full replacements keep the tail budget, since a replaced window holds
only the response rows anyway.

* fix(web): run the catch-up when gap recovery overlaps a cached activation

A cached session's activation asks for a direct latest page
(preferLatestOnActivation), and runTailSync's canIncrement excluded that
flag unconditionally. When gap recovery was requested on top of such an
activation, the recovery therefore took the activation shortcut: a
direct latest-page fetch with no cursor catch-up. With cached rows 1-10
and the server head at 310, the window retained rows 1-10 plus the
latest page 111-310 and advanced its newest cursor to 310, leaving rows
11-110 unreachable through ordinary tail or older paging; the recovery
flag was consumed without ever catching the window up.

Let a pending recovery claim the cursor path even when an activation
shortcut is pending, and defer the activation flag for that run: the
recovery's catch-up + latest-page reconciliation subsumes the
activation's refresh-from-latest, so consuming it there is equivalent.
The flag is also cleared when the recovery finishes through a reset
verdict or its latest-page reconciliation, so a mid-run activation
cannot linger into a later full replacement.

* fix(web): refresh out-of-page tool-call rows during gap recovery

A tool-call row cached before a disconnect can be enriched in place
afterwards; when more than a latest page of newer rows follows before
reconnect, neither the catch-up (newer rows only) nor the latest page
reaches it, and the cached card keeps its stale input/status until the
session is reopened (review finding on hub messages.ts:378, the web
half of the documented jkRY limit).

After the recovery's latest-page reconciliation, sweep the window for
retained non-terminal tool-call rows older than the page bound and
older than the recovery cursor, and refresh each by id through the
existing message-context endpoint. Bounded at 20 (newest first),
best-effort (a failed or epoch-mismatched refresh leaves the row to the
next recovery), and generation-guarded like the rest of the run.

* fix(web): surface gap-recovery refresh failures as the usual sync warning

The out-of-page tool-call refresh sweep swallowed per-row context-fetch
errors, leaving a stale row silently. Let a rejected refresh propagate
to runTailSync's catch so the run's usual warning surfaces; the row
stays as is and the next sync retries the sweep. A refresh answered
under a different epoch, or one that no longer contains the row, stops
the sweep without touching the window. Terminal rows are never swept
(merge status only advances); tests pin the zero-request skip and the
warning on failure.

* fix(android): recover merged tool-call rows through the gap-recovery upsert

The Android window store's gap path recovered through a cursor sync
only: merged tool-call rows keep their original cursor position, so a
row enriched while disconnected kept its stale input/status until a
fresh page happened to include it (the same hole the web recovery
closed).

Port the web choreography: the gap entry point (resume: 'gap' on the
session pipe) flags the window (pendingGapRecovery) and runs
recoverAfterGapResume; the next tail sync catches up the missed
interval with the cursor sync, then fetches an authoritative latest
page and applies it as an upsert — rows present in the page are
replaced by id while rows older than the page, the hasMore/oldest
cursor and the loaded history budget (up to the 800-row older-load
ceiling, mirroring the web trim) survive. An epoch mismatch under the
page falls back to full replacement, a reset verdict during the
catch-up consumes the recovery, and a failed catch-up keeps the flag
and the original cursor so the next sync retries the whole recovery. A
recovery requested while a cached activation's preferLatestOnActivation
is set claims the cursor path and defers the activation shortcut, and
the tail-sync coalescing joins or replaces in-flight runs by their
snapshotted recovery/activation mode like the web does. The queued
-state reconciliation keeps its own ensureAfterCurrent drain and runs
concurrently with the recovery, mirroring the web's two post-gap calls.

The bounded by-id refresh of out-of-page non-terminal rows stays
web-only (Limits follow-up; it needs the message-context endpoint in
the native API seam).

* fix(ios): recover merged tool-call rows through the gap-recovery upsert

Mirror of the Android recovery port for the HapiKit window controller:
the session layer's resume: 'gap' handling now flags the window
(pendingGapRecovery) and runs recoverAfterGapResume alongside the
queued-state reconciliation, and the tail sync catches up the missed
interval with the cursor sync, then fetches an authoritative latest
page and applies it as an upsert — rows present in the page are
replaced by id while rows older than the page, the hasMore/oldest
cursor and the loaded history budget (up to the 800-row older-load
ceiling, mirroring the web trim) survive. An epoch mismatch under the
page falls back to full replacement, a reset verdict during the
catch-up consumes the recovery, and a failed catch-up keeps the flag
and the original cursor so the next sync retries the whole recovery. A
recovery requested while a cached activation's preferLatestOnActivation
is set claims the cursor path and defers the activation shortcut, and
syncTail coalescing joins or replaces in-flight runs by their
snapshotted recovery/activation mode like the web does.

Tests run in CI (Swift toolchain is not available on this machine):
recovery converges the merged row through catch-up + latest page, and a
failed catch-up stops before the latest page and retries on the next
recovery. The bounded by-id refresh of out-of-page non-terminal rows
stays web-only (Limits follow-up).

* test(ios): read the window-message envelope from content, not wire

The new gap-recovery tests compared the merged tool-call row through a
`.wire` accessor that does not exist on WindowMessage (the
role-wrapped envelope lives on the public `content` field; `wire` is
only the convenience initializer's parameter name), which failed to
compile the whole HapiKit test target in CI. Compare the envelope
content values directly — still by value, not by WindowMessage
identity.

* test(ios): read the retry requests off the cumulative request list

provider.requests accumulates across the whole test: the failed first
catch-up stays at index 0, so the retry's catch-up and latest page sit
at indices 1 and 2 — the assertion counted from the retry point and
failed in CI even though the retry behaved exactly as pinned
([after, after, latest]).

* fix(web): keep the reset requirement when the recovery catch-up overflows

A recovery catch-up page can overflow the window's history budget:
history-mode trimming keeps the reading anchor, drops the newer
caught-up rows, and marks the window for a reset
(mergeIntoWindow's prepend trim). The loop breaks on
requiresLatestReset without distinguishing that overflow from a
completed catch-up, and the recovery then reconciled the latest page
on top anyway and consumed the recovery flags — stranding the rows
between the reset-marked window and the page, unreachable from either
cursor (older paging descends from the window edge, the newest cursor
has already passed them).

When the catch-up ends with the window reset-marked, leave the reset
requirement and the recovery flags intact: the next sync's
authoritative replacement closes the hole and consumes the flags, the
same choreography as every other reset-marked window.

* fix(web): finish the sync when the gap-recovery refresh sweep stops early

The out-of-page tool-call refresh sweep early-returned when a context
response no longer contained the row or answered under a different
epoch, bypassing finishTailSync and leaving the window marked syncing
after the controller promise resolved — suppressing tool-history
hydration and read receipts until another sync ran.

Complete the run's bookkeeping on both exits: a missing row finishes
with the usual warning and the row as is; an epoch mismatch marks the
window for the authoritative replacement (server rows may have been
deleted since the page was fetched) and finishes with the warning
instead of reconciling against a stale snapshot.

* fix(android): keep the reset requirement when the recovery catch-up overflows

A recovery catch-up page can overflow the window's history budget: the
history-mode prepend trim keeps the reading anchor, drops the newer
caught-up rows, and marks the window for a reset. The catch-up loop
breaks on requiresLatestReset without distinguishing that overflow from
a completed catch-up, and the recovery then reconciled the latest page
on top anyway and consumed the recovery flags — stranding the rows
between the reset-marked window and the page, unreachable from either
cursor.

When the catch-up ends with the window reset-marked, leave the reset
requirement and the recovery flags intact: the next authoritative
replacement (on returning to the tail view, or on a sync that may reset
history) closes the hole and consumes the flags, the same choreography
as every other reset-marked window. Mirrors the web fix.

* fix(android): keep the earlier older cursor when the recovery upsert retains rows

When the recovery's latest-page upsert retains rows older than the
page (no trim), applyLatestResponse still preferred the response page's
own bound as the older-paging cursor, so an 800-row no-news recovery
re-pointed older loads at the page's oldest row and left the held rows
1-600 unpaged. Keep whichever side is older, like the web has since the
loaded-history-budget fix.

* fix(android): refresh out-of-page tool-call rows during gap recovery

Port the web sweep: after the recovery's latest-page reconciliation, the
window re-reads its retained non-terminal tool-call rows that sit older
than the page bound and were not delivered fresh by the catch-up through
the existing message-context endpoint — bounded at 20 newest-first, with
the same exit semantics the web sweep carries (a missing row finishes
the run with the usual warning and the row as is; a refresh answered
under a different epoch marks the window for the authoritative
replacement and finishes with the warning).

The seam gains getMessageContext (wire types MessageContextPage/
MessageContextResponse; the hub answers a bare null when the message
does not resolve), implemented by HapiApi and scripted null in the
fakes.

* fix(ios): keep the reset requirement when the recovery catch-up overflows

Mirror of the Android/web recovery overflow fix: a recovery catch-up
page can overflow the window's history budget — the history-mode
prepend trim keeps the reading anchor, drops the newer caught-up rows,
and marks the window for a reset — and the recovery then reconciled the
latest page on top anyway and consumed the recovery flags, stranding
the rows between the reset-marked window and the page, unreachable from
either cursor.

When the catch-up ends with the window reset-marked, leave the reset
requirement and the recovery flags intact: the next authoritative
replacement (on returning to the tail view, or on a sync that may reset
history) closes the hole and consumes the flags. Test rides CI — no
Swift toolchain on this machine.

* fix(ios): keep the earlier older cursor when the recovery upsert retains rows

Mirror of the Android/web cursor fix: when the recovery's latest-page
upsert retains rows older than the page (no trim), applyLatestResponse
still preferred the response page's own bound as the older-paging
cursor, so an 800-row no-news recovery re-pointed older loads at the
page's oldest row and left the held rows 1-600 unpaged. Keep whichever
side is older, like the web has since the loaded-history-budget fix.
Test rides CI.

* fix(ios): refresh out-of-page tool-call rows during gap recovery

Port the web sweep: after the recovery's latest-page reconciliation, the
window re-reads its retained non-terminal tool-call rows that sit older
than the page bound and were not delivered fresh by the catch-up through
the message-context endpoint — bounded at 20 newest-first, with the same
exit semantics the web sweep carries (a missing row finishes the run
with the usual warning and the row as is; a refresh answered under a
different epoch marks the window for the authoritative replacement and
finishes with the warning).

The transport gains the endpoint end to end: MessageContextPage/
MessageContextResponse wire types (the hub answers a bare null when the
message does not resolve), APIClient.messageContext, the MessagesProviding
requirement, and the row-swap helper on the window logic. agentMessage-
PayloadType becomes public so the controller can classify rows like the
web does. Tests ride CI — no Swift toolchain on this machine.
2026-11-11 13:05:04 +08:00

237 lines
21 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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":"<uuid>","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 **catching up the cursor first, then the latest page applied by id** (rows updated in place keep their cursor position, so a cursor sync alone never re-delivers them; the applied page must not discard already-loaded history, and an epoch change falls back to a full replacement), 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":<ms>}}` |
| 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=<open session>`, 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` / `messages-indeterminate` / `messages-requeued` / `message-cancelled` | `all=true` connections + matching `sessionId` connections |
| `machine-updated`, `machine-agy-models-updated` | `all=true` connections + matching `machineId` connections |
**The global connection must also handle the message-stream events** (`message-received`, `messages-consumed`, `messages-indeterminate`, `messages-requeued`, `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 (16 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`; rewind may also include `reason: 'rewind'` and `truncateFromLocalId` | Message history changed **structurally** (rewind, fork, import, clear). For a rewind, retain only the known prefix through the client boundary before tail-syncing; for every other invalidation, 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. |
| `machine-agy-models-updated` | `machineId` | The machine's `agy models` listing changed on a background re-check. Refetch `GET /api/machines/:id/agy-models` for that machine (answered from the machine's cache; it starts no `agy` run and produces no further event). Emitted when the re-check changes what that route would answer — a different listing, or a sign-in warning that appeared or cleared — never for the machine's first listing. |
| `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. |
| `messages-indeterminate` | `sessionId`, `localIds: string[]` | A native dispatch/queue mutation has an unknown outcome. Keep the row uninvoked, show an explicit Retry/Cancel resolution, and do not auto-replay it. Shared-engine Retry/Cancel can remain unavailable until reconciliation proves the outcome. |
| `messages-requeued` | `sessionId`, `localIds: string[]` | An explicit Retry restored delivery to the normal queue. Clear the indeterminate marker. |
| `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`, `activeAt`, `model`, `modelReasoningEffort`, `effort`, `serviceTier`, `permissionMode`, `collaborationMode`, `copilotAgentMode`, `backgroundTaskCount`, `backgroundTasks` (Claude's full `{id, type, description}` list): last-write-wins assignment when present. `activeTurnStartedAt` appears in patches but the reference implementation deliberately never applies it from a patch (`web/src/lib/sessionPatch.ts`) — take it from full-session payloads only; the `sse/` fixtures pin this.
- **`lastUserMessageAt`** — max-monotonic when present, in both detail and summary caches. Include it in render-relevance checks: a patch containing only this field can reorder the list. Full-session summary upserts and delayed REST list responses must also retain a newer cached value.
- **`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.
- **`attachedJob`** — `{version, value: AttachedJob | null}` for the session list row only (`SessionSummary.attachedJob` / `attachedJobUpdatedAt`, [session jobs](../../guide/session-jobs.md)); the detail `Session` has no such field. Apply when `version` is strictly greater than the row's `attachedJobUpdatedAt` (missing = 0), so a lagged heartbeat cannot resurrect a cleared job. A full-session payload cannot carry the job; keep the row's existing job and watermark when one replaces the summary.
### 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 session-list comparator (`shared/src/sessionOrder.ts`, mirrored by
Android/iOS): `globalPinned` > `pinned` > `lastUserMessageAt ?? createdAt`
descending, then creation time descending and ID ascending. Missing pin flags
count as false. The ID tie-break makes refetch order irrelevant. Output,
connection and pending-request changes do not reorder rows; a new user message
does. Web project/machine groups use the same stable activity key, while search
keeps relevance as its primary ranking.
### `active` is transport liveness, not agent health
Two different signals travel on a `Session` and clients routinely conflate them (tiann/hapi#1820):
| Signal | Means | Refreshed by |
|---|---|---|
| `active` / `activeAt` | the CLI socket is connected and reachable | the `session-alive` keep-alive, every ~2 s |
| `metadata.lifecycleState` | what the agent behind that socket is actually doing | lifecycle transitions only |
A session can keep `active: true` indefinitely on keep-alives alone, with no messages and no thinking, for days. That is a live socket in front of an idle agent, not a working session.
`metadata.lifecycleState` is the health signal:
- `running` — live working session (stamped by the CLI at session start)
- `idle` — the hub has seen nothing but keep-alives for `HAPI_SESSION_IDLE_TIMEOUT_MS` (default 12 h). Reversible and non-destructive: `active` stays `true`, and the next message, queued prompt or background task flips it back to `running` within one hub tick
- `archived` — session closed
Client rules:
- Treat both `running` and `idle` as "a CLI still owns this session". Comparing against the `'running'` literal makes an `idle` session read as a dead row.
- Surface `idle` distinctly from `active`-and-recently-working, so an operator can tell a busy fleet from a pile of keep-alive zombies (web: the `idle` bucket in `SessionList`).
- Sessions that are meant to sit quiet indefinitely can set `metadata.idleReconcileExempt: true` to opt out of reconciliation entirely.
---
## Visibility
`POST /api/visibility` with body `{"subscriptionId": "<from connection-changed>", "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`): Android/iOS native delivery is independent of Web visibility. When a native provider accepts a notification for at least one device, the hub skips the Web Push/toast duplicate for that dispatch. Otherwise, if **any** connection in the namespace is visible, the hub first sends **`toast` SSE frames to visible connections**. Web Push is the fallback when no connection is visible or toast delivery reaches zero connections. Provider acceptance is not a handset delivery receipt — see the [native companion contract](../native-companion-contract.md).
Native rule: report `visible` on foreground and `hidden` on background, every time. A stale `visible` report can divert the namespace's Web Push fallback into unseen toast frames; it does not disable native push. The native app separately suppresses its local notification when the corresponding chat is already open in the foreground.
---
## 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.