Server-level title/body templates with {variable} placeholders for web
push notifications, configured via settings.json `notificationCopy` and
an admin-only editing section on the Notifications settings page with
live preview and variable chips. Empty templates fall back to the
hardcoded defaults; the channel also now delivers session-completion
pushes, which the existing preference toggle previously had no web push
effect for.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
Co-Authored-By: Claude <noreply@anthropic.com>
The app's main chunk grew past workbox's 2MiB default precache cap,
which made vite-plugin-pwa fail the production build (and would have
failed the GitHub Pages deploy too). Raise the limit to 4MiB so the
SPA stays fully precached for offline use.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
Co-Authored-By: Claude <noreply@anthropic.com>
Add per-namespace notification preferences so users can choose which
event types trigger push notifications (permission requests, session
ready, task notifications, session completion). Adds the
notification_preferences table (schema v20), GET/PUT
/api/notification-preferences, POST /api/push/test for test pushes, and
a Notifications settings page in the web app with a confirm dialog for
disabling permission requests. Defaults keep all event types enabled.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(web): drop Idle session-list badge (keep working/pending)
Quiet active rows already read as the default via full opacity vs faded
archived; labeling Idle was badge inflation. Pin-in-progress now only
surfaces working/pending so the section does not advertise lack-of-state.
Fixes#1362
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): include deliveryMode on abort send-error restore
Unblocks web typecheck: RawSendError requires deliveryMode, and the
abort-restore path was omitting it (already red on upstream/main CI).
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(agy): extract brain UUID adoption from the PreToolUse hook handler
Pull the first-wins UUID-adoption block out of onPreToolUse into a
standalone adoptBrainUuidIfUnset() helper so it can be shared with the
upcoming PreInvocation hook handler without duplicating the guard logic.
No behavior change.
* feat(agy): discover the brain UUID from agy's PreInvocation hook
PreToolUse only fires once a tool actually runs, so a tool-free turn
(e.g. a plain "hi") never gets a brain UUID from it. Register agy's
PreInvocation hook alongside PreToolUse: it fires before every model
call regardless of tool use, carries the same conversationId, and lets
discovery resolve deterministically instead of depending on a tool
being invoked.
PreInvocation uses agy's flat hook schema (distinct from PreToolUse's
grouped {matcher,hooks} shape) and a short 5s timeout, since it blocks
the agent loop synchronously on every model call. The forwarder gains
an explicit --event flag (default pre-tool-use, unchanged) to route to
a new /hook/agy-invocation endpoint; that path is fail-open (always
responds 200 / stdout "{}") since a lost discovery signal must never
block a model call, unlike a permission decision.
Both hooks funnel into the same first-wins UUID adoption guard, so a
resume-seeded sessionId is never overwritten by either.
* refactor(agy): drop transcript content-matching now that the hook is authoritative
The scanner's content-match discovery was the fallback for turns where
the PreToolUse hook never fired (no tool used). Now that PreInvocation
covers exactly that case, the fallback never actually gets a chance to
run in practice: carrier hook loading fails all-or-nothing (both events
live in the same hooks.json), and a failed carrier already aborts the
PTY session before discovery matters. Keeping unreachable code around
just keeps the risk it was flagged for — attaching to an unrelated agy
session that happens to share the same first prompt.
Removes the scan-window heuristics, the wrapped-USER_REQUEST content
matcher, and the ambiguity-reporting path entirely. The scanner is now
purely reactive: it watches nothing until onNewSession() (driven by a
hook) tells it which brain to watch. extractUserRequest/
normalizeUserInput and the launcher's userRequestMatches are untouched
— they answer a different question (did the web-submitted message echo
back into the PTY), which hook payloads carry no text to answer.
* feat(agy): drop the PreInvocation discovery hook once the conversation is identified
PreInvocation fires on every model call (~424ms round trip measured), but the
brain UUID only needs to be discovered once. agy re-reads hooks.json before
every model call, so the carrier's hooks.json can be rewritten in place (via
a temp-file-plus-rename atomic write) to drop the PreInvocation block the
moment handleSessionFound confirms the UUID, leaving PreToolUse untouched.
PreInvocation is restored before every respawn, since a resume that silently
fails would otherwise leave no way to discover the replacement conversation's
UUID. If the carrier itself has vanished (e.g. /tmp's tmpfiles.d sweep on a
long-lived session), it is rebuilt from scratch and hookCarrierDir is
repointed for the next agy spawn.
* refactor(cli): extract resolveHapiHomeDir from Configuration's constructor
Configuration.happyHomeDir is a singleton computed once at process
startup, which the upcoming agy carrier relocation can't reuse directly
without breaking per-test HAPI_HOME isolation. Extract the priority
logic into a standalone, env-injectable function with no behavior
change.
* feat(agy): relocate the hook carrier under HAPI_HOME and sweep dead ones
Carriers used to live under mkdtempSync(join(tmpdir(), 'hapi-agy-
carrier-')). On this machine /tmp is swept by tmpfiles.d after 30 days,
and agy re-reads hooks.json on every model call (not just at spawn), so
a long-lived session's carrier could be deleted out from under it,
silently killing both the permission bridge and discovery at once.
Move carriers to <HAPI_HOME>/agy-carriers/<random>/, record owner
metadata (pid, startedAt) at the carrier root (outside .agents/, which
agy itself reads), and sweep carriers whose owner process has
confirmed-died at session start. Liveness is judged strictly by
process.kill(pid, 0): ESRCH means dead and safe to remove, EPERM means
alive but not ours and must be preserved, anything else is unknown and
also preserved. Carriers with unreadable or missing owner metadata
(pre-existing or corrupted) are only swept once old enough to rule out
a carrier still mid-creation. Every ambiguous case defaults to
preservation, since deleting a live session's carrier is far more
costly than leaving an inert directory on disk.
* fix(agy): abort respawn instead of spawning agy without a permission bridge
syncPreInvocationHookForLaunch used to log-and-return when the hook
carrier could not be recreated before a respawn, letting launchOnce
spawn agy anyway with --dangerously-skip-permissions and no PreToolUse
hook wired up — every tool call would auto-approve with nobody in the
loop. Throw instead, matching runAgy.ts's existing fail-closed contract
for the initial carrier, and notify the web chat via sendSessionEvent
so the abort isn't silent.
* fix(agy): sweep carriers only when the owner is positively identified
An unreadable owner.json is not evidence of staleness: a live session
whose metadata cannot be parsed would have its carrier removed once it
aged past the threshold, taking the PreToolUse approval bridge with it.
Hostname is not an identity either — containers sharing a HAPI_HOME can
share a hostname while their PIDs live in unrelated namespaces, so a
liveness probe there reports ESRCH for a process that is very much alive.
Scope the owner record to the boot id and PID namespace on Linux, fall
back to a distinguishable hostname-only scope elsewhere, and delete only
when the scope matches and the pid is confirmed dead. Carriers whose
owner cannot be identified are now kept.
* fix(agy): drop the hostname scope fallback rather than guess ownership
Hostname is not an identity. Where /proc is unavailable, two machines or
containers sharing a HAPI_HOME and a hostname compute the same scope, so a
pid that is live on the owning system reads as ESRCH here and its carrier
is deleted — taking the PreToolUse approval bridge with it while agy runs
with --dangerously-skip-permissions.
Without a strong boot and PID-namespace identity the scope is now
undefined, which makes the sweep preserve everything. Orphaned carriers
accumulate on those platforms instead, which is the cheaper failure:
ordinary teardown still removes carriers, so only crash leftovers remain.
* fix(agy): point carrier failures at HAPI_HOME instead of the temp dir
The carrier moved under HAPI_HOME/agy-carriers earlier in this branch,
but the abort messages still told users to check the temporary directory.
On a custom or quota-limited HAPI_HOME that sends remediation to a
filesystem that has nothing to do with the failure.
Both the initial-preparation path and the respawn-recreation path carried
the stale hint, so both are updated — otherwise the same failure would
suggest two different places to look.
* test: reproduce issue #865
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(opencode): surface stall errors and clear thinking spinner (closes#865)
Route quota/rate-limit/HTTP-2 cancel stderr through error-styled agent
messages, cancel the in-flight prompt, and clear thinking so the web UI
does not stay stuck while OpenCode retries upstream.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(opencode): non-stall stderr surfaces error without canceling prompt
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(acp): use agent-neutral retry stderr message in shared transport
AcpStdioTransport is shared by Cursor, Gemini, Kimi, and OpenCode.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(opencode): surface stall errors and clear thinking spinner
* fix(acp): parse split stderr stall records
Buffer stderr through newline-delimited records so split retry and HTTP/2 cancel
signatures still clear stalled OpenCode turns, and retain one web error
presentation branch.
Verified: targeted ACP and presentation tests plus CLI/web typechecks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(acp): emit stalled stderr tails immediately
Classify buffered retry and HTTP/2 cancellation tails as soon as their signatures
are complete, without waiting for the ACP process to close.
Verified: targeted ACP transport test and CLI typecheck.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(acp): flush newline-free quota errors
* fix(acp): surface newline-free stderr errors
* fix(acp): scope stall cancellation and bound stderr
* fix(opencode): bind stall cancellation to prompt RPC
* fix(acp): preserve partial stderr until classification
* fix(acp): report complete cancellation records
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
The Codex Desktop restart route already supports a Windows PowerShell script, but macOS installations can have Codex.app available without any Restart-CodexDesktop.ps1 file or pwsh. In that case the web restart control reports a missing script even though the desktop app is installed.
This adds a native macOS path that detects Codex.app, reports running state via pgrep, and restarts the app with osascript plus open when no custom restart script is configured. Existing configured scripts and Windows behavior stay unchanged.
Constraint: macOS users may not have PowerShell installed for the Codex Desktop restart control.
Rejected: Require HAPI_CODEX_RESTART_SCRIPT on macOS | preserves the current failure mode for default installs.
Confidence: medium
Scope-risk: narrow
Directive: Keep configured restart scripts higher priority than native macOS fallback so operators can override local app behavior.
Tested: bun test hub/src/web/routes/codexDesktop.test.ts
Tested: tsc -p hub/tsconfig.json --noEmit
Not-tested: Manual click of restart button, to avoid restarting the active Codex desktop session during development.
Co-authored-by: zhangrui <3014594405@qq.com>
* feat(web): FUE + placeholder for rich composer session @-mentions
Discover session @-mentions via composer-grounded FUE and always-on
placeholder copy when rich composer is active (#1273).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): notify onFocus after programmatic rich-composer autofocus
Playwright headless (and some engines) skip the DOM focus event for
element.focus(), so FUE engage never ran. Call the onFocus prop after
autofocus so discovery still works.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): engage rich-composer FUE on mount
DOM focus events are unreliable for programmatic autofocus (and in
Playwright). Treat the live rich composer as the affordance and open
the callout when the rich path mounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): measure FueCallout height; ellipsis rich placeholder
Bot review on #1274: position from real panel height (ResizeObserver)
so multi-line FUE bodies clear the composer, and keep long mention
placeholders on one ellipsized line in the input row.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): Escape dismisses rich-composer FUE; keep expand flex chain
Escape while the mention FUE is engaging only dismisses the callout
(no abort/collapse). FUE anchor is a flex container so expanded
RichComposerInput still fills height. Mock resolveComposerPlaceholderKey
in sendError tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(pi): complete RPC interaction parity
* feat(pi): integrate native conversation history
* fix(pi): harden RPC lifecycle boundaries
* fix(pi): address review lifecycle and upload boundaries
* fix(pi): release history transaction on rollback deadline
* fix(pi): isolate preflight and timed-out mutations
* fix(pi): preserve retry and editor boundaries
* fix(pi): disable unavailable history synchronization
* fix(pi): gate fallback readiness on history baseline
* fix(pi): bind uploads and retire extension requests
* fix(pi): preserve canceled and legacy stream boundaries
* fix(pi): preserve native fork runtime state
* fix(pi): persist dialogs and preserve select values
* fix(pi): keep upload authorization path-stable
* feat(pi): preserve native steer semantics
Route ordinary sends during an active Pi main turn through native steer while keeping explicit queue delivery on the existing composer gestures. Persist the delivery contract across Hub replay and Web retries, and guard stale steer dispatch with streaming generations and ordered prompt fallback.
* fix(pi): queue deferred steer deliveries
Keep native steer only for the initial live emit. Reconnect replay, CLI backfill, clear-gate release, and mature delivery now downgrade turn-scoped steer intent to the durable HAPI queue without mutating stored provenance.
* fix(pi): retain abort guard through preflight miss
Treat an immediate no-active abort rejection as a possible async-preflight race. Keep the existing abort boundary alive so a late agent_start receives the compensating abort before queued work is released.
* fix(pi): queue stale steer retries
A failed send no longer reuses turn-scoped steer intent after its original Pi generation is lost. Text restoration, attachment retry, and legacy retry provenance all enter the durable HAPI queue while fresh ordinary sends retain native steer behavior.
* fix(pi): invalidate rejected abort generation
After a no-active preflight abort waits through late-start compensation, mark the target stream idle while the runtime mutation lease is still held. Waiting native steers therefore fall back instead of entering the aborted generation.
* fix(pi): queue idempotent steer retries
Track whether a localId insert created a new row. Initial inserts may retain live Pi steer, while duplicate-localId retries deliver a queue-safe view of the stored row without overwriting its original provenance.
* fix(pi): sync command-only history before fallback
Read the Pi append log before retiring a successful prompt that produced no agent lifecycle. Preserve FIFO history associations across missing entry events, and fail the wrapper closed if that mandatory synchronization cannot be completed.
* perf(hub,web): emit structured patches for session todos/teamState/metadata/agentState writes (#895, closes second half of #884)
Today the four CLI handlers in `sessionHandlers.ts` that write session-scoped
state (TodoWrite messages -> setSessionTodos; team-state deltas ->
setSessionTeamState; update-metadata RPC; update-state RPC) emit
`session-updated` events with no `data` payload. `syncEngine.handleRealtimeEvent`
intercepts each one, re-reads the row from SQLite, and broadcasts the entire
~5KB Session via SSE. That works (the web client's `isSessionRecord` shortcut
keeps the cache patched), but it costs a DB read and a full-payload SSE
fan-out per write, and any failure mode that drops the broadcast data falls
through to `useSSE.ts:509-512` and triggers per-session REST refetches - the
storm vector documented in #884.
This is the architectural follow-up to #885. #885 added `staleTime` on the
detail query (eliminates focus / mount refetches inside a 30s window). This
PR removes the structural reason these four writes touch the REST path at all.
`SessionPatchSchema` learns four optional structured fields:
- `todos` (array)
- `teamState` (object)
- `metadata` (versioned `{ version, value }` wrapper)
- `agentState` (versioned `{ version, value }` wrapper)
`.strict()` preserved so unknown keys still throw. The versioned wrappers
mirror the existing socket.io `update-session` broadcast at lines 211 / 259 so
metadata and agentState always travel as an atomic (version, value) pair -
caches need the version to reject stale patches.
Each of the four emit-sites now carries a structured `data` payload with the
delta it just wrote. `syncEngine.handleRealtimeEvent` for `session-updated`
events with non-empty patch data: applies the patch to the in-memory Session
in place via the new `sessionCache.applySessionPatch`, then forwards the event
as-is. Empty patches, no-data events, and patches against uncached sessions
all fall back to the legacy `refreshSession` path so behavior for other
emitters (e.g. `cursor/codexDesktop.ts`) is unchanged. Dedup hook against
agent-session-id changes preserved on the fast path.
`patchSessionDetail` is no longer a blanket spread - it enumerates each field
explicitly so the versioned metadata / agentState patches can be unwrapped
into the Session's flat (metadata, metadataVersion) and (agentState,
agentStateVersion) pairs. Spreading the patch wholesale would have written a
`{ version, value }` object into `session.metadata` and corrupted the cache.
`patchSessionSummary` recomputes the touched derivations - `todoProgress` from
todos, `pendingRequestsCount` / `pendingRequestKinds` from agentState,
SessionSummaryMetadata from metadata - via three new pure helpers exposed
from `shared/src/sessionSummary.ts` (`computeTodoProgress`,
`computePendingRequestKinds`, `toSessionSummaryMetadata`). `toSessionSummary`
is refactored to use these helpers - identical output, single source of
truth.
- shared: `SessionPatchSchema` parses each new patch shape, stays strict,
rejects empty metadata without `version`, rejects full Session payloads
(those go through `isSessionRecord`).
- shared: summary derivation helpers covered against bare AgentState /
Metadata inputs (the shape the SSE patch path provides).
- hub: each emit-site asserted to carry the expected structured payload.
- hub: `applySessionPatch` unit-tests cover todos / metadata / agentState
application, empty-patch rejection (forces caller back to refreshSession),
cross-namespace guard, and missing-session fallback.
Empirical wire round-trip verifies each patch shape survives `JSON.stringify`
intact and routes the web client through `getSessionPatch` (non-empty result)
instead of the REST invalidation fallback.
Per #884 expectation: with this fix on top of #885, idle GET /api/sessions/<id>
rate is expected to drop to near-zero on the reporter's 100+ session install.
Operator (heavygee) will attach the live-measured before / after to the PR
post-merge.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(hub): snapshot metadata reference before applySessionPatch mutation so dedup-on-id-change fires
The structured-patch fast path added in 05147a6a (closes#884 second half)
broke the dedup-on-metadata-change trigger in handleRealtimeEvent.
Root cause: applySessionPatch MUTATES the cached Session in place
(reassigns session.metadata = patch.metadata.value). The dedup check
compares before vs after agent session IDs, but `before = getSession(id)`
and `after = getSession(id)` returned the SAME object reference, so
before.metadata had already been overwritten by the time the check ran.
hasSameAgentSessionIds always returned true and dedup silently never
fired on the fast path.
The legacy refreshSession path got dedup for free because it REPLACES
the cache map entry with a new Session object, leaving the pre-refresh
reference intact for the comparator.
Fix: capture beforeMetadata before applySessionPatch runs; use it for
both branches so the comparison contract is identical.
Adds syncEngineHandleRealtimeEvent.test.ts with three regression guards:
- structured metadata patch with changed cursorSessionId fires dedup
- todos-only patch does NOT fire dedup (no false positives)
- legacy refresh path (no patch data) still fires dedup
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(schemas): reorder SessionPatchSchema fields so soup-merge with codex-usage layer conflicts cleanly
Pure reorder (no semantic change). feat/codex-usage-indicator-rebased adds
a flat `metadata: MetadataSchema.nullable().optional()` + `metadataVersion`
to SessionPatchSchema in the same line range upstream/main has the model/
modelReasoningEffort fields. My branch added the versioned `metadata` field
at the END of the object, so git 3-way merge silently auto-merged both,
producing an invalid object literal with duplicate `metadata` keys.
By placing my `metadata` / `agentState` / `todos` / `teamState` insertions
in the SAME line range codex inserts (between updatedAt and model), git
now raises an explicit CONFLICT during the soup merge, which can be
resolved correctly once and replayed by rerere. No behavior change on a
clean upstream/main merge.
Pure cosmetic; no test or runtime impact.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(sse): propagate TeamDelete clear through structured patch path
Closes PR #897 Major review (HAPI Bot, 2026-06-13): TeamDelete events
drove `applyTeamStateDelta` to return `null`, but the emit-site
coalesced that to `undefined`. JSON serialization then dropped the key,
the hub cache skipped its assignment branch (`patch.teamState !==
undefined` was false), and the web client saw an empty patch and fell
back to REST invalidation — exactly the storm path this PR was supposed
to close. Sidebar / NotificationHub / dedup all served stale team state
until the next full refresh.
Fix in four coordinated places (wire ↔ cache contract):
- shared/src/schemas.ts: `teamState: TeamStateSchema.nullable().optional()`
so `null` is a valid wire shape meaning "cleared". Comment documents
the discriminator contract for consumers.
- hub/src/socket/handlers/cli/sessionHandlers.ts: drop the
`?? undefined` coalesce so `null` survives JSON serialization.
- hub/src/sync/sessionCache.ts (applySessionPatch): use
`Object.prototype.hasOwnProperty.call(patch, 'teamState')` to
discriminate "field absent" from "field is null", then map null →
undefined to match the cached `Session.teamState` type.
- web/src/hooks/useSSE.ts (patchSessionDetail): same
hasOwnProperty discriminator + null → undefined mapping.
Regression tests:
- schemas.sessionPatch.test.ts: `{ teamState: null }` parses
successfully (locks the wire contract).
- sessionCache.applySessionPatch.test.ts: TeamDelete clears cached
teamState; todos-only patch leaves teamState untouched (guards the
hasOwnProperty branch against a regression back to `!== undefined`).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(sse): version-gate metadata/agentState patches against cache regression
Closes PR #897 follow-up Major review (HAPI Bot, 2026-06-16): the new
structured SSE patch path unwraps versioned metadata/agentState fields
without checking the cached metadataVersion/agentStateVersion. SSE
reconnects + the existing per-query invalidation can leave a detail
cache repopulated by a fresh REST refetch BEFORE a buffered older patch
replays. Without the gate the older patch overwrites the newer cache,
regressing resume / session-id / pending-requests state.
Mirrors the hub-side CLI room handler contract (`incoming.version >
currentVersion`, `web/src/hooks/useSSE.ts`):
- `patchSessionDetail`: gate metadata/agentState assignment behind
`isNewerVersionedPatch(patch.version, nextSession.<field>Version)`.
The pre-patch version is captured by `{ ...previous.session }` so
the comparison is against the cache-at-write-time.
- `patchSessionSummary`: read the detail cache (via queryClient) for
the canonical metadataVersion / agentStateVersion. Use `>=` (not `>`)
because the callsite runs `patchSessionDetail` first — when detail
accepts a newer patch the cache already holds the new version, so
matching `>=` keeps summary aligned with detail's acceptance; when
detail rejects, `>=` aligns summary with detail's rejection.
- Exported `isNewerVersionedPatch(patchVersion, currentVersion)` as a
pure helper so the rule is unit-testable in isolation.
- Test: `useSSE.test.ts` pins the 4 cases (newer ✓ / older ✗ /
same-version ✗ / first-write currentVersion=0 ✓).
Hub-side `applySessionPatch` does NOT need the same gate: in-process
events from `handleUpdateMetadata` / `handleUpdateState` are emitted
only AFTER the optimistic-concurrency check at the store layer
succeeds, and `syncEngine.handleRealtimeEvent` consumes them
synchronously in order. The vulnerability is the SSE
reconnect/replay window on the web client.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(sse): include updatedAt in structured patches + pendingRequests summary
Closes PR #897 post-rebase bot review (HAPI Bot, 2026-06-18):
Major — structured patches dropped session.updatedAt. TodoWrite,
teamState, metadata, and agentState DB writes all touch sessions.updated_at,
but the fast path forwarded only field deltas. Hub/web caches and session
list ordering stayed stale until a full refresh. All four emit-sites in
sessionHandlers now reload the stored row after a successful write and
include updatedAt in the SSE patch payload (applySessionPatch already
applies it via Math.max).
Minor — agentState summary patches updated pendingRequestsCount/kinds but
left pendingRequests stale, so SessionAttentionIndicator tooltips showed
old request tools after an SSE patch. patchSessionSummary now uses
computePendingRequestsCount + computePendingRequests alongside the
existing kinds helper.
Tests: sessionHandlers.test.ts asserts updatedAt on todos/metadata/agentState
patches.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web,hub): apply serviceTier in structured session patch path
Closes PR #897 bot Minor (2026-06-18): field-by-field patchSessionDetail
stopped copying serviceTier after the spread refactor, so Codex Fast/
Standard could show stale tier until a full refetch. Mirror nullable
hasOwnProperty handling in patchSessionDetail and hub applySessionPatch.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(hub): allow same-ms updatedAt on structured patch emit asserts
Date.now() resolution makes create+update land on the same millisecond in
unit tests; the store still touches updated_at. Use >= so CI is not flaky.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): refuse versioned summary SSE patches without detail version source
When session detail is not cached, defaulting metadata/agentState versions to
0 let stale buffered patches overwrite a freshly refetched list and suppress
list invalidation. Bail out so the list refetches instead.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): keep updatedAt monotonic when applying SSE session patches
Stale versioned metadata/agentState replays can still carry an older
updatedAt. Use Math.max on detail and summary paths so rejected replays
cannot rewind list/detail clocks while patched=true suppresses invalidation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: retrigger Codex PR review after infra stream failure
Prior pr-review run died on reconnect (stream closed before
response.completed); no code findings. Empty commit to re-fire
pull_request_target.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): compare all summary metadata fields in keep-alive skip
isRenderIrrelevantPatch omitted path/machineId/flavor/worktree, so a
same-ms metadata patch could be dropped while summaryPatched stayed true
and list invalidation never repaired grouping/icon/path.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(sse): version-wrap todos/teamState patches for dual-SSE races
Global + session EventSources can deliver out of order. Carry store
todos_updated_at / team_state_updated_at as patch versions, gate web
applies, and tighten keep-alive skip compares (metadata + request tool/kind).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): put SSE version watermarks on SessionSummary
Requiring a detail query to apply versioned list patches forced O(N)
/sessions invalidation on every global SSE write. Gate against summary
watermarks instead; skip no-op detail clones on duplicate deliveries.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(hub): ratchet todosUpdatedAt on rewind rebuild
replaceSessionTodos was stamping the remaining TodoWrite's older
createdAt, so a lagged pre-rewind structured SSE patch could resurrect
deleted todos. Advance the watermark on force-replace instead.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): apply copilotAgentMode in structured detail SSE patches
Field-by-field detail mapper dropped the new Copilot keep-alive field,
so detailPatched suppressed invalidation and SessionChat kept a stale mode.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Debian <heavygee@oos-linux.in.lockhouse>
* feat(web): in-place cursor variant drill-down (closes#48)
Rebased onto upstream/main: iOS-style nested picker keeps overlay open on
multi-variant base pick, applies default variant immediately, dismisses on
variant selection; preserves upstream Pi model panels and Codex Fast mode.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web+cli): accept bare Cursor ACP model ids in picker catalog
Current Cursor ACP returns bare bases (composer-2.5, …) with empty
cliModelSkus. The bracket-only wire gate emptied the catalog so the
picker showed only Default. Treat bare non-default ACP ids as catalog
rows, keep CLI effort/speed SKUs as variants, and widen SKU enrichment
the same way. Closes#1129.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): ignore stale selectedModelVariant during Cursor base drill-down
Only highlight a session variant when it is still among the visible
rows, so a multi-variant base switch uses the new default until parent
state catches up (Codex Minor on #947).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli+shared): do not attach CLI variant SKUs to bare ACP catalogs
Bare ACP bases cannot express effort/speed (apply is model+fast on
parameterized wires). Drop suffixed SKUs unless a base has bracket
wires, and refuse matchCliSkuToAcpWireId collapse onto bare-only rows.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): serialize Cursor model applies across base/variant picks
Drill-down default apply and a quick variant click could race setModel
RPCs; last-finisher wins. Queue Cursor applies in SessionChat so the
explicit variant cannot be overwritten by a late default.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(web): align cursor picker auto-row label with upstream Auto
Rebase onto main picked up Default→Auto rename; keep #1129 coverage.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Debian <heavygee@oos-linux.in.lockhouse>
* fix codex stale terminal recovery
* fix(codex): ignore stale retry failures
* fix(codex): ignore stale retry terminal failures
Only task completion may bypass stale-turn duplicate handling during same-thread recovery, preventing delayed failed events from finalizing the active retry.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(codex): separate stale turn recovery guard
Limit matching-thread status events to missing turn IDs so delayed status failures cannot affect an active retry turn.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(codex): scope stale completion recovery turn
Accept a stale completion only for the immediately finalized turn, so older retries cannot finalize the active turn.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Ignore Cursor's Using worktree stdout banner without masking other
non-JSON ACP frames (markClosed + kill). Skip --cursor-worktree when
spawn directory is already a linked git worktree so ACP can initialize.
Fixes#1085
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(cli): add GitHub Copilot CLI agent support via ACP
Wrap `copilot --acp --stdio` for remote sessions and spawn the native TUI locally, with full hub/web integration for spawn, resume, and permissions.
Fixestiann/hapi#362
Co-Authored-By: HAPI <noreply@hapi.run>
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(copilot): agent modes, models, slash/file UX, local session sync
Add Interactive/Plan/Autopilot (fleet is slash-only), subscription-aware
model discovery, web StatusBar/permission UX, @ file mentions, and fix
local Safe Yolo plus session-id locator for handoff/resume.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: re-trigger Codex PR review after auth outage
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: retry Codex PR review
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): preserve agent mode on resume and apply via ACP set_mode
Resume was dropping copilotAgentMode so Plan/Autopilot reset to interactive.
Also switch local/remote mode application to --mode / session set_mode instead of slash prompts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): wake remote loop when agent mode changes
Empty isolated queue tick lets setMode apply without inventing a user prompt.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): confirm mode changes before persisting
Await Copilot mode changes and expose discovered models so session state reflects backend acceptance.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): guard mode discovery and slash updates
Keep model probes within runner roots and preserve active sessions when mode switching is unavailable or rejected.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): preserve resume and auto semantics
Deduplicate Copilot resume rows, apply Auto explicitly, and fail closed on denied permissions.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): close permission and model discovery gaps
Keep write-capable commands pending in read-only mode, extend model probe RPCs, and preserve explicit model validation before session creation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): persist runtime model and agent mode
Fallback to ACP model options when direct model switching is unavailable and retain Copilot agent mode across hub restarts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): normalize composer auto selection
Use the null session sentinel for Copilot Auto so the composer selects and resets default models consistently.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): reject local permission mode changes
* style(copilot): remove trailing blank line
* fix(copilot): secure local config handoffs
* fix(copilot): reject local agent mode slashes
* fix(copilot): reject mode changes during turns
* fix(copilot): consume rejected slash updates
* fix(copilot): preserve thinking across slash handling
* fix(copilot): stabilize async config changes
* fix(copilot): roll back rejected startup model
* fix(copilot): preserve cancellation and file mentions
* fix(copilot): hide local permission controls
* fix(deps): support clean workspace installs
* test(copilot): account for spawn mode argument
* fix(copilot): attribute usage to active model
---------
Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Cursor <cursoragent@cursor.com>
The public relay used to accept a shared auth key compiled into every
hub, so its bandwidth was open to anyone. The relay now issues a
per-hub credential it can meter and revoke, and hubs obtain one on
their own.
- --relay resolves an auth key at startup: HAPI_RELAY_AUTH env, then a
key persisted in settings.json, then a fresh key from the relay's
/issue endpoint. There is no shared-key fallback; if no key can be
obtained the tunnel does not start and the hub says why.
- A persisted key rejected by the relay (HTTP 403 after revocation or a
secret rotation) is discarded and replaced once, then the tunnel is
restarted, so a revoked hub recovers without manual edits. Keys given
explicitly through the environment are never overwritten.
- Issuance is rate-limited per public IP; HTTP 429 is reported with the
retry hint instead of being retried blindly, which matters for users
sharing a CGNAT or corporate egress address.
- The tunnel URL now comes from upstream tunwg's slog JSON on stderr
(msg="listener started"), replacing the fork's custom --json event,
and --log_level=0 keeps per-request logs out of the hub console.
Requires a relay running tunwg with TUNWG_AUTH_SECRET configured.
Restores directory glanceability by default after #1315. Settings → Display
adds a toggle next to Active sessions only that re-enables the pinned section.
Fixes#1347
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): re-subscribe push when VAPID key changes (stale hub subscriptions)
* fix(web): prune stale push endpoint from the hub after VAPID re-subscribe
* fix(web): record VAPID key only after hub registration succeeds
* fix(web): preserve push registration on unsubscribe failure
via [HAPI](https://hapi.run)\n\nCo-Authored-By: HAPI <noreply@hapi.run>
* feat: add cache-aware token usage dashboard
Track normalized Claude, Codex, and ACP usage with incremental SQLite backfill. Exclude imported transcript history, rebuild usage after history rewrites, and expose an owner-only dashboard with cache-aware totals and breakdowns.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix: preserve usage model and local dates
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix: normalize cached usage and timezone buckets
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
---------
Co-authored-by: HAPI <noreply@hapi.run>
ElevenLabs only passed bootstrap context through dynamicVariables without
a matching {{initialConversationContext}} prompt placeholder, so Brief me
connected with no session history. Stream deferred chunks then push bootstrap
on all backends; add the placeholder for newly created ConvAI agents.
Co-authored-by: Cursor <cursoragent@cursor.com>
Settings truncated read-only fixtures to 800 chars so scrolling never
revealed the rest. Default preview is now the full document; explicit
caps remain for tests.
Closes#1341
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(web): show hidden directories in workspace browser
Add optional includeHidden param to the machine list-directory RPC so the
WorkspaceBrowser can toggle hidden (dot-prefixed) entries. Default remains
filtered for backward compatibility; the toggle persists via localStorage.
* fix(web): disable show-hidden toggle while directory loading
Prevent overlapping list-directory requests with opposite includeHidden
values; the toggle is now disabled while a directory load is active.
* fix(web): migrate chat-path attachments on scratchlist park (#1226)
When an image is attached via the normal upload adapter before scratchlist
mode is enabled, toggling mode swapped adapters and send() dropped the
metadata — park stored text-only and cleared chips. Migrate pending
chat-path files into hub scratchlist storage on send, and fail closed if
non-hub paths still reach the park wrapper.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): defer chat-path cleanup until scratchlist park succeeds
send() migrates before scratchlist.add; deleting the original upload
there left retries pointing at a missing chat blob when park failed.
Stamp migratedFromPath and clean up only after the park attempt result.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): park scratchlist before composer.send clears chips
assistant-ui empties text/attachments before onNew, so return false from
park could not restore retryable state and rejected cleanup deleted the
migrated hub blob. Intercept park from a live snapshot; clear only after
accept; releaseWithoutDelete so clearAttachments keeps parked hubs.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): lock composer while scratchlist park is in flight
Disable input/send and hide chip remove during migrate+add so mid-flight
edits are not wiped on success and hub blobs are not deleted out from
under the accepted entry.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): do not clear composer if park snapshot changed mid-flight
Compare post-await composer state to the pre-park snapshot before
clearing; disable DragDropZone and scratchlist promote while parking
so parent paths cannot add chips the clear would silently drop.
Addresses Codex Major on #1227 (preserve post-snapshot composer changes).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): defer migrated chat-path cleanup until park snapshot clears
Return ScratchlistParkResult.beforeClear from onParkScratchlist so
finalizeMigratedScratchlistParkCleanup runs only after HappyComposer
confirms the composer was unchanged mid-flight.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): flush rich mentions before scratchlist park snapshot
Park snapshots composer.text after flushSerializedText so session
@-mention chips serialize to markdown links before scratchlist add.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): validate park snapshot before scratchlist add
Split prepare/commit/abort so mid-flight composer edits abort orphan
hub blobs instead of parking a duplicate. Reuse restored hub paths in
prepareScratchlistParkAttachments so remounted chips do not re-upload.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): ignore scratchlist toggle hotkey while park is in flight
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: add message-level conversation fork and rewind
Expose native Codex/Grok/Claude history controls through hub REST+RPC and web ConfirmDialog actions, without file rewind or composed forks. Also reconcile the duplicate hub V14→V15 migration so typecheck can pass.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: hydrate fork transcript and consume Claude --fork-session
Forked HAPI children now copy the source transcript prefix so navigation is not a blank thread, and Claude drops --fork-session after the first launch so relaunches do not branch again.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: harden fork/rewind concurrency and durable history points
Skip pending scheduled rows when hydrating fork transcripts, serialize fork/rewind per session, and persist conversation history points/indexes across existing-session bootstrap and Grok relaunches.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: close remaining fork/rewind races and UI anchoring
Block sends and scheduled maturation while history actions run, order fork prefixes by invocation time, inherit history locators into children, and only offer Fork current on the live tail boundary.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: address remaining fork/rewind bot findings
Materialize Claude --fork-session before the first child prompt, validate
HAPI history boundaries before native RPC, expose forkCurrent on a latest
user boundary, fully demote unsupported conversationHistory capabilities,
and fix the truncate test setup order.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: align fork-current ids and Claude fork bootstrap
Compare the latest fork boundary in assistant-ui threadMessageId space,
spawn Claude forks with the persisted session mode, and preserve
forkedFrom across existing-session bootstrap.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: close fork/rewind consistency holes at the contract layer
Hold the source history lock until Claude child binds a distinct native
id, persist Codex localId→turnId locators, and mark/block diverged
sessions when native rewind outruns HAPI truncate.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: use Codex stable lastTurnId for historical fork
Map HAPI's exclusive boundary to the previous turn's inclusive
lastTurnId so native fork context matches the hydrated transcript.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: require exact Grok native resume for fork children
Reject newSession fallback when forkedFrom is set, and keep the hub
history lock until the child binds the forked grokSessionId.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: kill active fork children before failed-fork cleanup
Bind/readiness failures can leave the child process running; deleteSession
rejects active rows, so terminate first then remove the HAPI session.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: close remaining fork lock, hydrate, and todos gaps
Reject mode switches during history actions, batch-copy fork
transcripts in one SQLite transaction, and rebuild todos after
fork hydrate / rewind truncate.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: allow Codex historical fork before the first turn
Use experimental beforeTurnId when there is no previous turn for the
stable inclusive lastTurnId boundary.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: mark Grok history busy immediately after dequeue
Hub idle checks clear once messages-consumed fires; hold the busy flag
across permission sync and rewind-points lookup before prompt starts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: encode copied conversation history content
* fix(web): hide local conversation history actions
* style(codex): remove trailing whitespace
* fix(fork): preserve children when cleanup is unconfirmed
* fix(history): confirm cleanup and guard rewind divergence
* fix(history): probe capabilities before advertising
---------
Co-authored-by: Cursor <cursoragent@cursor.com>