* perf(web): drive session-list activity indicators from one low-rate ticker
* fix(web): keep one reduced-motion query for the ticker's lifetime
* fix(web): keep the model-error halo pulsing on the low-rate ticker
* fix(web): start each ping subscription at its own first frame
Job wakes interrupted running turns: `deliverJobTerminalWake` only
special-cased inactive sessions, so an opted-in terminal job posted a
user message into whatever the agent was doing. Drop the wake when a
turn is running and settle the claim so a later idle flip cannot re-fire.
Those wakes also impersonated operator input — `sentFrom: 'webapp'`, a
bare user message with a "Verify the outcome and continue" imperative.
Tag them `hapi-system` and render them as a quiet status line in the web
chat instead of a user bubble with fork/retry actions. Drop the default
imperative; a prescription now has to come from `--wake-prompt`.
Agents attached jobs to short work (tests, builds, typechecks) because
the injected prompt was 2.1k chars of REQUIRED / MUST / FORBIDDEN. Replace
it with a decision rule: default is not to attach, never for work that
finishes in this turn, and run `hapi job --help` for the mechanics.
Co-Authored-By: HAPI <noreply@hapi.run>
Add WebAuthn passkeys as another way to obtain a web JWT, so the browser
no longer has to keep CLI_API_TOKEN after the first sign-in.
- hub: passkey_credentials table (schema v36), register/list/delete
routes behind the JWT, unauthenticated login routes with one-time
challenges, and a 30-day passkey session exchanged via POST /api/auth.
Passkeys are bound to the registering namespace, the browser origin
(same host or an explicit CORS origin; HTTPS or localhost), and an
HMAC fingerprint of CLI_API_TOKEN, so rotating the token revokes them.
- web: "Sign in with a passkey" on the login screen, Settings → Passkeys,
passkey auth source with silent JWT refresh, en/zh-CN/ru strings.
- docs: client contract, hub README, PWA guide.
* fix(web): keep unread rows mounted when a collapsed project group is toggled
A collapsed group drew its unread rows in a separate peek list and the
expanded group drew every row inside its CollapsiblePanel, so toggling the
group remounted those rows: on expand they faded in from opacity 0 and their
icon and spinner restarted; on collapse they showed twice while the panel
closed.
Render each group's rows once, each in its own CollapsiblePanel that is open
while the group is expanded or the row is a kept unread row. Toggling the
group now only folds the other rows. Spacing moves inside the panels so
folded rows take no room.
Fixes#2433
* test(e2e): count expanded project groups by header, not by open panels
Rows now have their own collapsible panels, so open panels no longer map
one-to-one to expanded groups.
Node 25+ exposes its own localStorage/sessionStorage globals, which shadow
jsdom's in the Vitest environment. Tests that spy on Storage.prototype or
pass localStorage to StorageEvent then fail (5 tests in markdown-a and
sessionLastSeen). Bind both globals to the jsdom window's storage instead of
the memory fallback that only kicked in when methods were missing.
via [HAPI](https://hapi.run)
Co-authored-by: HAPI <noreply@hapi.run>
* feat(web): unpin a session from the list on hover
* fix(web): preserve focus when unpinning into a collapsed project
* fix(web): reserve width for visible row quick actions
* fix(web): harden keyboard-only unpin focus handoff and simplify reveal logic
* feat(web): export and import browser settings from Settings → About
Browser-local settings (theme, display, chat, voice, machine labels, ...)
can now be exported to a JSON file and imported in another browser.
Only an explicit allowlist (SETTINGS_STORAGE_KEYS) moves; credentials,
hub URL, drafts, UI state and trust grants never do. Import replaces the
allowlisted keys and reloads so every hook re-reads its value.
A test scans web/src and shared/src storage code and fails on any hapi*
key that is not classified as a setting or not, so new keys get decided
by whoever adds them.
Closes#2441
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(web): reject malformed settings files and carry legacy fallback keys
Addresses Swear Review on #2442: reject array settings and unknown
versions before touching storage, and move legacy keys that settings
still fall back to (tool-card display, active-only list filter,
ElevenLabs voice) along with them. The session-list status filter is a
Display setting, so it and unread-only are now settings too.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
---------
Co-authored-by: HAPI <noreply@hapi.run>
Cursor ACP sessions can fail mid-turn with a transient model error that the
agent reports inline rather than as an RPC rejection. HAPI treated those turns
as successful, so the session went quiet with no banner, no push, and no way to
resume without retyping the prompt.
This adds the full path:
- detect: classify inline/stderr model errors from the Cursor ACP stream,
requiring strong signatures before typing a failure as a model error
- surface: persist `lastModelError` on session metadata; render a chat banner
and a session-list indicator, with the prompt text kept out of list/SSE
summaries so they never ship up to 32 KB of user prompt
- notify: deliver a push for an unacknowledged error, watermarked on the hub
copy so a restart does not re-page the same eventId
- bridge & retry: offer a one-shot recovery prompt that replays the failed
turn, bound to the originating eventId and gated so a real user turn always
supersedes it. Auto-bridge is opt-in and defaults to OFF, persisted in hub
settings and fanned out to live Cursor CLIs.
Re-cut onto current upstream/main. The branch had accumulated 108 iterative
hardening commits against a 289-commit-older base; replaying them individually
would have re-resolved the same conflicts ~100 times. The pre-re-cut tip was
2c28a1365 if the granular history is ever needed.
Absorbing upstream required adapting to three refactors that landed meanwhile:
- `MessageQueue2` grew an `internal?: boolean` control-message flag upstream
while this branch added richer `internal` provenance. Unified on a tagged
`QueueItemInternal` union (`control` | `model-error-bridge`) so one field
carries one concept. `hasPendingNonBridgeTurn()` now treats *any* internal
item as non-user: otherwise a queued `/auto-review` control slash would have
counted as a user turn and wrongly superseded a live bridge.
- `AcpSdkBackend.prompt()` gained a `timing` callback upstream; merged it with
this branch's `shouldSend` gate into a single options object.
- The hub settings route moved to a unified `updateSettings` transaction.
`autoBridgeTransientModelErrors` is applied outside that transaction because
SyncEngine owns its CLI fan-out and rollback under its own lock.
via [HAPI](https://hapi.run)
Co-authored-by: HAPI <noreply@hapi.run>
#2380 moved the disconnected-row fade onto the title text, which also removed a
stacking-context defect I had an open fix for (#2375 / #2373): the fade used to
sit on the title grid, and that grid holds the schedule and attention
HoverTooltips, whose panels render inline as `absolute z-30` rather than through
a portal. An `opacity < 1` ancestor forms a stacking context, so the panel was
both washed out and had its z-index trapped — a later row could paint over a
downward-opening scheduled-send panel.
The code is correct now, so this is only the guard. The natural refactor — hoist
the fade onto the grid so the whole row dims — reintroduces the bug silently, and
only on inactive rows that also have scheduled messages, which is why it survived
review the first time.
Asserted structurally: no element carrying the fade may contain a role="tooltip".
Fails if the fade moves back onto the grid; passes on current main.
via [HAPI](https://hapi.run)
Co-authored-by: HAPI <noreply@hapi.run>
* fix(web): keep the recovery pending until the row sweep succeeds
The recovery consumed pendingGapRecovery at the latest-page upsert,
before the by-ID row sweep ran: a context request that failed there
propagated to the run's catch and surfaced the warning, but the flag
was already gone, so the next ordinary tail sync did cursor catch-up
only, skipped the sweep, and cleared the warning — the enriched cached
call stayed stale with no retry path.
Keep the flag pending until the catch-up, the upsert, and every row
refresh have succeeded: the upsert now consumes only the activation
flag it subsumes, and the recovery completes — clearing
pendingGapRecovery — after the sweep finishes without a failure. The
sweep's failure exits (a thrown request, a row the endpoint no longer
knows, a different-epoch answer) leave the flag set, so the next sync —
ordinary or recovery — retries the whole choreography. The upsert
itself is idempotent, so a retry costs one extra latest-page round.
* fix(android): keep the recovery pending until the row sweep succeeds
Mirror of the web fix: the recovery consumed pendingGapRecovery at the
latest-page upsert, before the by-ID row sweep ran — a context request
that failed there left the enriched cached call stale with no retry
path, because the next ordinary tail sync does cursor catch-up only,
skips the sweep, and clears the warning.
The upsert now consumes only the activation flag it subsumes, and the
recovery completes — clearing pendingGapRecovery — after the sweep
finishes without a failure; the sweep's failure exits leave the flag
set, so the next sync retries the whole choreography. The upsert itself
is idempotent, so a retry costs one extra latest-page round.
* fix(ios): keep the recovery pending until the row sweep succeeds
Mirror of the web/android fix: the recovery consumed pendingGapRecovery
at the latest-page upsert, before the by-ID row sweep ran — a context
request that failed there left the enriched cached call stale with no
retry path, because the next ordinary tail sync does cursor catch-up
only, skips the sweep, and clears the warning.
The upsert now consumes only the activation flag it subsumes, and the
recovery completes — clearing pendingGapRecovery — after the sweep
finishes without a failure; the sweep's failure exits leave the flag
set, so the next sync retries the whole choreography. The upsert itself
is idempotent, so a retry costs one extra latest-page round. Test rides
CI.
* fix(hub): advance the idle-progress clock on merged tool-call ticks
A repeated tick folds into the call's existing row, and the stored row
keeps its first snapshot's createdAt for stable ordering — but
onAgentProgress received that frozen timestamp on every tick, so
repeated snapshots of a live ACP call never advanced the keepalive-idle
clock and a session with thinking=false and no background task could be
marked idle despite fresh updates.
Feed onAgentProgress the merge observation time when the tick updates
an existing row; the stored ordering timestamp is unchanged, and the
derived todo/team version stamp keeps its strictly-advancing gate.
* test(ios): await the actor-isolated failure injection in the sweep-retry test
GatedMessagesProvider is an actor, so failNextContextRequests must be
awaited from the async test body; without it the new test fails to
compile in CI. No production change.
* fix(agy): keep empty strings in edit and write tool card inputs
A deletion edit (empty Replacement) or an empty-file write was mapped
without new_string/content, so the web Edit and Write views rendered
nothing. Keep '' for old_string, new_string and content.
* fix(web): take the question card's free-text flag from the pending request
agy's ask_question tool call is shown before its form arrives, so its input
cannot say whether free text is allowed, and the card kept offering Other on
forms without qN_other. Fill allowFreeText on the tool call input from the
pending request's input for questions that carry none. Inputs and requests
without the flag keep showing Other.
crypto.randomUUID is undefined outside secure contexts (plain HTTP on a LAN IP), so enqueueing a read threw and no read-state PUT was sent. Use the randomId() helper, which falls back to getRandomValues.
* feat(usage): display CLI account quotas and rate limits across Codex, Antigravity, and Claude
* fix(usage): persist live quota state across processes and normalize agy usage
* fix(cli): isolate Claude quota observations by account and bound probe deadlines
* fix(usage): bind Claude quota events to producing session account and surface quota fetch errors
* fix(usage): preserve OAuth token isolation without email and surface Codex read failures
* fix(usage): skip host claude path lookup when test probe override is active
* refactor(web): share the AskUserQuestion option row and pill button styles
Move the interactive option row and the footer pill button class into
askUserQuestionOptionCard so another footer can reuse the exact presentation.
Pure move, no behavior change.
* fix(web): show Waiting for your reply on pending question cards
A pending question keeps the 'running' tool state until its reply lands in
the transcript, so the card header counted an ever-growing Duration and the
detail dialog showed a 'Running…' result pill. Neither is true: the agent is
not working on the question, it is waiting for an answer.
For question tools with a pending permission (AskUserQuestion and
request_user_input, covering Claude, OpenCode, agy, Cursor and Codex), the
card header now reads 'Waiting for your reply' instead of the timing rows,
and the result pill follows suit. The tool state and fixtures are unchanged.
* fix(web): title Codex question cards with the question text
request_user_input questions carry no header field, so the card title was
always the generic 'Question' while the actual question hid in the subtitle.
When no header is present, use the question text as the title and drop the
now-redundant subtitle; a header (Claude-style payloads) keeps the previous
title/subtitle split, and multi-question batches keep the counted title.
* fix(web): drop the redundant header chip on single-question cards
The card title already shows the question header for a single-question
AskUserQuestion, and the footer repeated it as a badge ('Database' twice).
Render the header chip only for multi-question steps, where it labels the
current step and adds information.
* fix(web): request_user_input footer adopts the shared question option rows
Codex question footers rendered their own flat option rows (dot glyphs,
aria-pressed buttons) and default-variant nav buttons, visually diverging
from the AskUserQuestion card. Reuse the shared option row and pill button
styles so both question surfaces present identically; rows now expose the
same radio/checkbox roles and aria-checked state. Behavior (selection
rules, notes, dismissal) is unchanged.
* fix(web): render request_user_input option labels as Markdown
The shared option row renders titles and descriptions as plain text, but
request_user_input option labels and descriptions are authored as Markdown
(bold targets, code commands) and the footer's own rows used to render them
through MarkdownRenderer. Give the shared row an opt-in markdown mode that
keeps the compact spacing, and enable it for the request_user_input footer.
* fix(web): title CursorAskQuestion cards from the parsed question header
CursorAskQuestion renders through the AskUserQuestion footer but had no
knownTools entry, so its card title stayed the raw tool name. Now that the
single-question header chip is deduped against the title, a Cursor question
lost its header entirely. Share the question-tool presentation (header as
title, question as subtitle, minimal pending header) with Cursor payloads,
reading their title/prompt field names the same way the parser does.
* fix(web): translate tool.waitingForReply for zh-CN and ru
Both locales shipped the English copy. Use the same register as the
neighbouring strings: zh-CN '等待你的回复' (matches the 等待+object pattern of
the ready toast and the approval key) and ru 'Ожидание вашего ответа'
(noun form of 'Ожидание одобрения').
* fix(web): fall back to the Cursor request title for question card headers
A Cursor question whose descriptive title lives only on the request
(input.title) produced an empty header in the card presentation, so the
single-question card fell back to the generic 'Question' title while the
footer's header chip is deduped away — the request lost its descriptive
title everywhere. Route the CursorAskQuestion presentation through
parseCursorAskQuestionInput, which already applies the request-level title
fallback, keeping that fallback the single source of truth.
The job label, stale marker and progress/elapsed text shared one truncating
span, so a long label hid the parts that change. The label now grows only
into the space the status leaves, down to a small minimum, and the status
truncates only after that.
Closes#2391
via [HAPI](https://hapi.run)
Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix: keep one stable HAPI session id per Claude conversation
Every terminal `hapi claude -r` minted a new HAPI session id for the same
Claude conversation; the hub then merged the duplicates after the fact and
deleted the older row, so links and peer references to it broke, and two
live duplicates hid one row in the web sidebar.
CLI: resolve identity before Claude starts (HAPI_SESSION_ID is fixed at
bootstrap). `--resume <id>` / `--continue` look up the owning HAPI session
and reopen it with the same id, handing an active remote session over and
refusing one controlled by another terminal; bare `--resume` uses the
`hapi resume` picker filtered to Claude. Rotated Claude ids are kept in
`claudeSessionIdHistory` so older ids still match.
Hub: schema v35 adds `session_redirects`; every merge that deletes a row
records old -> survivor, and client-facing lookups follow it (sockets and
job ownership stay strict). New `GET /cli/sessions/resume-target-by-agent`.
Web: a merged-away URL moves to the survivor instead of bouncing home, and
live Claude duplicates stay visible in the sidebar.
* fix: keep job-key remaps and hub-archived resumes working after redirects
Review follow-up for the stable session identity change.
- Job routes: the session lookup now follows a merged-away id to the
survivor, so `requestedSessionId` must stay the raw URL id. Otherwise a
colliding `<old id>/<key>` remap was bypassed and PATCH/DELETE/late PUT
through the old id hit the survivor's own job.
- Terminal resume of an inactive session now asks the hub to clear a
hub-authored archive first (`POST /cli/sessions/:id/prepare-local-resume`,
same clear as hub reopen), so `hapi claude --resume/--continue` (and
`hapi resume`) no longer exit on the #1911 existing-session guard.
* fix(cli): refuse an explicit Claude resume whose transcript is gone
Reopening the owning HAPI session drops --resume and hands the id to the
local launcher, which silently starts a fresh conversation when the
transcript is missing — under the existing HAPI id, title and history.
Check the transcript before any handoff or archive change and fail
explicitly instead.
* fix: follow merged-session redirects on /api only for clients that rebind
Native clients store a session detail under the requested id and drop SSE
events for any other id, so a merged-away id that resolved to the survivor
loaded history but never showed live messages.
`SyncEngine.resolveSessionAccess` is strict again by default; `/api` routes
follow redirects only with `x-hapi-follow-session-redirects: 1`, which the
web client (that rebinds to the returned id) sends. Native clients keep the
previous 404. CLI REST always follows. Job routes still keep the raw URL id
for key remaps under both modes.
* feat(codex): fill the round footer tok/s from app-server timing
Measure each Codex round's generation window the way agy rounds do: the
live turn span minus tool-execution and wait-for-the-user windows, over
the thread-cumulative output-token delta, emitted on the turn's
turn_duration so the round footer shows tok/s. Tool windows prefer the
app-server's own item timing (startedAtMs/completedAtMs/durationMs).
The token baseline is the last reported cumulative total: the CLI seeds
a thread it created in this process (thread/start) to zero, while
resumed and forked threads receive the app-server's attach-time usage
replay and stay unseeded, so inherited history is never counted as a
turn's output. Only the live root-turn feed reaches the ledger: history
replays re-project old items and must not settle a round. Permission
hooks keep timing waits for the user.
* fix(codex): seed gateway-created threads for the first-turn tok/s baseline
Native /new and /clear create threads through the gateway before/after
hooks, whose after() binds the fresh root without the zero usage seed
the runtime create path applies - so the new thread's first turn
captured a null baseline and never showed tok/s. Seed it there too,
same as create(): thread/start only, since forked threads receive the
app-server's attach-time usage replay instead (tiann/hapi#2379).
* fix(codex): keep the active generation ledger across a hub-only reconnect
SharedCodexRoot's session.onReconnect reset the whole projection, but a
hub reconnect only replays final history: the native turn keeps running
without a new turn/started, so dropping the ledger identity, baseline
and windows made generation.settle() return null at completion and the
round permanently lost its tok/s. Add projection.resetAfterHubReconnect
which replays without touching the ledger; the app-server reconnect
path keeps the full reset, because the resumed turn re-announces itself
and must re-measure from its own start (tiann/hapi#2379).
* fix(codex): seed fresh usage before session-ready releases queued input
The gateway thread/start seed ran in the after() hook, after the bind
wrapper had already activated the root: registerControls and
emitSessionReady open the input gates, so a queued Web prompt (or one
submitted on session-ready while the runner notification is delayed)
could start the thread's first turn before the zero baseline existed,
and seeding afterward could not repair that captured-null turn. Move
the seed into the bind wrapper right after root.bind, guarded by a
freshThread flag the create and gateway paths set for thread/start
only - forks keep their app-server attach-time replay baseline
(tiann/hapi#2379).
* 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.
832c5922f moved liveness onto the agent icon and dropped the row fade; #2296
then gave every state its own mark, so stopped is no longer shown by an absence.
That fixes identity. It doesn't fix scale.
The badge answers "what state is this row in?" once you look at it. It can't
answer "which of these sessions is still held in memory?" across a long list,
because that's a whole-list scan and a 10px mark doesn't survive one. At a
handful of sessions the badge covers both jobs. At ~30 active, a stopped row and
a resident idle row are the same shape of row until you inspect each badge.
So restore the fade on `!active` — the same predicate the stopped badge uses,
rendered at the other scale. Shape carries which state; dimming carries which
rows.
The fade covers the title line only. The presence badge and the attached-job
meter sit outside it deliberately: a job outliving its agent is exactly the case
where the row is non-resident but the work is live, and both facts have to stay
readable at once. #2296 already marks that session's badge as working; this
keeps the row dim underneath it.
via [HAPI](https://hapi.run)
Co-authored-by: HAPI <noreply@hapi.run>
* refactor(agent): extract agy's generation-time clock into a shared helper
agy computes generation time as the round minus tool-run and user-wait
windows. Move the window math and the event-fed bookkeeping into
cli/src/agent/generationClock.ts (GenerationClock + generationTimeMs) so
other ACP launchers can time their rounds the same way, and feed agy's
clock the same session updates and permission waits it always did.
Numbers are identical: the moved pure function is agyGenerationMs
verbatim and the agy tok/s integration tests pass unchanged.
* feat(claude): fill the round footer tok/s from the SDK result
Claude Code reports duration_api_ms on every result: the API-active time
of the round, with tool execution and permission waits already outside
it. Pair it with the round's usage.output_tokens and send both in the
existing turn_duration resultSummary, so the web's generic round-summary
normalizer picks them up and the footer renders tok/s — no new wire
types, and the renderer already knew how to format the pair.
Errored rounds and the manual /compact turn carry no meaningful
generation rate, so they emit nothing: claudeRemote marks the compact
turn result in-process (hapi_compact_turn) before it reaches the log
converter. Values that cannot produce a rate (zero, negative, fractional,
missing) are omitted rather than guessed.
Project headers are now role=button tab stops: Enter/Space toggles the
group, ContextMenu or Shift+F10 opens the project menu anchored under
the header (Enter opens it on non-collapsible headers). Menu items keep
the shared anchored-menu behaviour (first item focused, Escape closes).
* feat(fue): just-in-time callouts for three unlabelled icon-only controls
The message-content search scope toggle, the session list sort/filter menu,
and the per-session title lock are shipped, icon-only controls with no text
label and no existing discovery path. Wire each into the existing hapi.fue.v1
primitive (useFue + FueDot + FueCallout) so first click explains the control,
following the pattern already used for scratchlist, terminal-to-agent, and
rich composer mentions.
via HAPI (https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(fue): don't collapse search on blur into the portaled FUE callout
The scope FueCallout (like the other two) portals to document.body, so it
is never a DOM descendant of the search container. The container's
existing onBlur handler used a raw DOM .contains() check to decide whether
to collapse the search bar, which doesn't account for that — clicking
"Got it" in the callout read as focus leaving the search bar entirely and
collapsed it out from under the dismiss action.
Also marks FueCallout's portal root with a stable data-fue-callout
attribute so any caller (not just this one) can make the same
"is this interaction actually inside my UI" check despite the portal.
Investigated the review bot's related "modal interaction scope" concern on
RenameSessionDialog.tsx against a differential control (confirmed a truly
detached element at the same point in the interaction sequence does close
the dialog, so the harness/timing is valid): clicking the title-lock
callout does NOT close the dialog, because Radix's outside-pointerdown
check is itself a React onPointerDownCapture handler, and React's synthetic
events bubble along the logical JSX tree regardless of portal placement.
No fix needed there.
That investigation surfaced a narrower, real limitation instead: Radix's
FocusScope traps focus via a raw DOM containment check (unlike the
pointerdown case, there's no portal transparency here), so Tab/programmatic
focus into the portaled callout gets pulled back to the dialog's input.
Mouse-click dismiss and Escape-to-dismiss both still work. Tracked with an
it.fails() regression marker rather than left invisible; not fixed in this
PR (would mean restructuring FueCallout's portal/positioning, which is
riskier than this diff's scope).
via HAPI (https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(fue): keep the callout clickable when hosted inside a modal dialog
The automated review's follow-up pass caught something my first response
missed: Radix's modal Dialog sets document.body's pointer-events to none
and re-enables it only on its own content node. FueCallout's portal is a
separate sibling of that node — document.body, not a descendant of
DialogContent — so without an explicit override its buttons inherited
pointer-events: none and were unclickable by a real pointer while the
rename dialog was open.
This is distinct from (and more severe than) the modal-interaction-scope
question already answered: that was about whether Radix's own
outside-click *detection* misfires on the callout (it doesn't, verified
earlier), not about whether a real click can land on it at all. A plain
fireEvent.click in jsdom bypasses CSS hit-testing entirely, which is
exactly why the existing "dismisses and persists acknowledgement on Got it"
test kept passing throughout — it was never exercising this path.
Fixed by setting pointer-events: auto on the callout panel unconditionally.
Harmless outside a modal context (no other FUE caller sets body's
pointer-events to none). Red/green verified.
via HAPI (https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
---------
Co-authored-by: HAPI <noreply@hapi.run>
* feat(cli): Cursor emits AGENT_NOTIFY_SUMMARY via rules overlay
When Emit status summaries is on, install a transient workspace
.cursor/rules overlay for Cursor ACP sessions and clean it up on
teardown, closing the flavor hole left after #1376.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): harden Cursor notify-rule overlay ownership and exclude
Address review on the emit overlay: clear ownership state under lock,
refresh crash-recovery snapshots after user replacement, fall back to
an alternate rule filename when the primary path is tracked, and lease
.git/info/exclude so git add -A cannot stage the transient rule.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): path-scope notify overlay ownership and reap excludes
Refresh restore snapshots on live user replacements, key ownership by
selected rule path, and prune dead PID-stamped .git/info/exclude leases
left by crashed Cursor sessions.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): harden Cursor notify overlay against symlink and path traps
Refuse rule writes through symlinks, canonicalize workspace paths for
ownership, escape literal Git exclude patterns, and qualify settings
copy as Cursor ACP.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): preserve unreadable rules and file modes in notify overlay
Skip install when an existing rule cannot be backed up, restore original
permission bits on cleanup, and stop retrying ownership-lock callback
failures as lock contention.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): keep notify overlay restore snapshot on unreadable cleanup
When teardown cannot read the generated rule, leave the file alone but
retain the private ownership snapshot so a later session can restore the
user's original content; write state.json as 0600.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): restore notify overlay snapshot even if install never wrote
Last-owner cleanup now restores from the shared snapshot whenever the
on-disk rule is still HAPI-owned, including handles that registered then
failed before writing the generated rule.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): write notify overlay ownership state atomically
Replace in-place state.json writes with temp+rename so a partial failure
cannot destroy the only backup of a user rule, and harden the failed-
install recovery test to actually chmod the exclude file.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): fail closed on abandoned notify overlay locks
Publish pid+token via link(2) like the MCP overlay so a crashed holder
leaves an identifiable lock, and surface an actionable rm path instead of
silently spinning for five seconds.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): retry notify overlay lock when holder already released
After link EEXIST, a missing lock means the contender freed it before our
owner read - retry acquire instead of misreporting the path as abandoned.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): treat notify lock ENOENT during owner read as retry
Distinguish missing vs invalid lock contents so a holder that releases
between existsSync and readFile is not misclassified as abandoned.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): recreate notify overlay stateDir under the ownership lock
Last-owner cleanup no longer rmdirs stateDir, and install mkdir+write runs
inside the lock so a waiting installer cannot hit ENOENT on state.json.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>