1178 Commits
Author SHA1 Message Date
wushenghuaandCodex e3ebecf0e2 Merge upstream/main into main
Co-Authored-By: Codex <noreply@anthropic.com>
2026-08-08 11:31:28 +08:00
TEEKandGitHub cfca9d210d fix(web): prevent near-bottom chat scroll jump (#1358)
* fix(web): prevent near-bottom chat scroll jump

* fix(web): preserve explicit tail scroll intent
2026-08-07 13:20:26 +08:00
28df974edd feat(settings): onboard hub provider credentials for dictation and voice (#1392)
* feat(settings): onboard hub transcription provider credentials in UI

Env-only keys made dictation invisible; Settings can now add/edit/clear
hub-side credentials (masked), with env still winning as override.
Refs tiann/hapi#1384.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(settings): onboard voice-assistant backends alongside dictation

Same Settings credential surface now covers ElevenLabs, Gemini Live, and
Qwen Realtime (alias env pairs), not only transcription providers.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): address PR #1392 Major credential onboard findings

Alias env locks, non-destructive Save (omit empty fields), and
owner-only settings.json permissions for hub-stored provider secrets.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): harden credential onboard for second-pass Majors

Owner-namespace gate, stage-then-sync env after persist, and
per-field OpenAI-compatible editability under mixed env locks.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): serialize settings RMW and clear partial compatible creds

Per-file settings lock for concurrent credential PUTs, and Clear shown
for partial OpenAI-compatible entries (key/url/model alone).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): serialize all settings writers via updateSettings

Route credentials, relay auth, generators, server settings, and CLI
token persistence through a locked RMW helper; reset Clear form state.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): share cross-process settings lock with CLI

Extract withSettingsFileLock for hub+CLI, keep owner-only 0o600
rewrites, and race hub credential updates against CLI-style writers.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): keep UI secrets out of process.env; PID-own settings locks

Settings-backed provider credentials now live in an in-memory overlay
(getProviderEnvironment) so tunnel/ACP/Codex children do not inherit them.
Settings file locks record pid+token and only reclaim dead or legacy locks.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): never reclaim ownerless settings lock sidecars

wx creates the lock path before the owner JSON is visible; unlinking
null owners let a waiter steal a live acquisition and collide on
settings.json.tmp (CI ENOENT). Only reclaim parsed owners with dead PIDs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): reclaim dead locks via rename; clean up failed publishes

Stale reclaim renames the sidecar to a unique break path and re-verifies
the expected dead owner before deleting it, so a loser cannot unlink a
successor's live lock. Failed owner writes unlink the wx sidecar.
Reclaim uses a sync owner read so contenders do not all observe one
dead owner across an await and race the exclusive create.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): reclaim dead locks under exclusive reaper sidecar

Stale reclaim now takes a fixed settings.json.lock.reap lock, re-validates
pid+token, then unlinks — so a delayed contender cannot move a successor's
live lock aside. Also document providerCredentials in settings.schema.json.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): fail closed on corrupt CLI settings; backoff busy reaper

CLI updateSettings now uses a strict read that rejects invalid JSON
instead of treating errors as {}, which could wipe providerCredentials.
Settings lock reclaim sleeps when another process holds .reap so retries
are not burned synchronously.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): publish locks via candidate+link; fix CLI vitest hoist

Acquire settings locks by writing a complete candidate then linkSync to
the fixed path so a crash cannot leave an empty live sidecar. Fix the
CLI persistence regression test to create its temp dir inside vi.hoisted.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): replace bespoke lock with proper-lockfile; hide tenant creds UI

Codex kept finding crash windows in hand-rolled lock sidecars. Switch the
shared settings lock to proper-lockfile's mkdir + mtime lease. Hide the
owner-only credentials editor from non-default namespaces on the voice page.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): adapt sessionSummaryContract to outcome updateSettings

Rebase onto main brought #1376 unique tmp + outcome-shaped writers;
wire sessionSummaryContract and the write-failure credential test to match.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: retrigger CI after rebase onto upstream/main

Empty commit — Meta reported no checks on da0c6c258 after tip-forward rebase.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 13:20:03 +08:00
a020c73629 feat(web): interactive storage usage pie in Settings (#1383)
* feat(web): interactive storage usage pie in Settings

Show relative DB/WAL/SHM share beside absolute sizes on the
Storage settings page, with hover/legend selection and no new
chart dependency.

Fixes #1382

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): lead Settings Storage with relative-share donut

Put the interactive chart above exact byte rows so mobile users
see proportions first and scroll for drill-down sizes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): drop duplicate Exact sizes table on Storage

Keep one interactive donut + legend (bytes/%) beside or below the
chart; total and path stay as non-redundant footer lines.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): storage pie legend roving tabindex + empty footers

Address Codex review: one Tab stop via roving tabindex, total outside
the listbox, and keep total/path when all slices are zero.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 09:48:44 +08:00
KorenKritaandGitHub 0a05fada00 fix(web): coordinate reasoning panel scrolling (#1398) 2026-08-07 09:48:25 +08:00
KorenKritaandGitHub feb4099731 fix(web): stabilize fork boundary while streaming (#1399) 2026-08-07 09:47:55 +08:00
f399aa0222 feat(web): transient Unread-only session list filter (#1400)
* feat(web): opt-in needs-attention session list filter

Add a default-off sidebar filter (and Settings → Display toggle) that
keeps permission/input/unread rows while excluding background-only busy
work, mirroring the active-only preference pattern from #903.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): make needs-attention filter a transient sidebar toggle

Drop the Settings → Display preference and localStorage persistence.
This is an inbox lens: toggle in the session list, rows fall away as
they're seen, and a reload clears the filter.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): unread-only sidebar lens, not needs-attention

Rename the transient toggle to Unread only and filter solely on
updatedAt > lastSeenAt. Permission/input attention stays on row dots;
this is not Overseer review inbox.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): use unread-dot shape for unread filter toggle

Match the session-row unread indicator instead of an inbox tray so
Overseer can own inbox chrome later without competing metaphors.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): apply unread filter after machine scope

Keep machineFilters derived from the unfiltered sidebar set so a
persisted machine selection is not cleared when that machine has no
unread rows. Unread intersects with the selected machine instead.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): snapshot last-seen once for unread filter pass

Avoid N localStorage read/parse calls while the unread lens is on by
loading the store once per memoized filter pass.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 09:47:39 +08:00
AnanovoandGitHub b57fb35867 fix(web): collapse expanded composer after successful send (#1368)
* fix(web): collapse expanded composer after send

* fix(web): wait for send result before collapsing composer

* fix(web): match composer collapse to send settlement
2026-08-06 14:37:18 +01:00
988f8f183f feat: settings toggle for AGENT_NOTIFY_SUMMARY contract injection (#1376)
* feat: settings toggle for AGENT_NOTIFY_SUMMARY contract injection

Add a hub-persisted, default-off Settings control so operators can opt agents into emitting the trailing AGENT_NOTIFY_SUMMARY line. Propagate the resolved flag on CLI session bootstrap and inject at call time for Claude, Codex, OpenCode, and Grok (Cursor still unsupported).

Closes #1375

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: lock hub settings RMW and restore abort deliveryMode

Serialize settings.json updates with the shared .lock protocol and unique
temp files so the new hub toggle cannot clobber CLI/relay fields under
concurrency. Also supply deliveryMode on abort send-error restore so web
typecheck (and CI) pass.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): wrap SettingsGeneralPage tests with QueryClientProvider

The hub-settings toggle uses TanStack Query; the settings page suite
was rendering without a QueryClient and blew up CI.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): defer summary-contract toggle until settings load

Avoid rendering an interactive false switch while the hub GET is still
in flight, which could overwrite an enabled preference on early click.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): clarify Grok coverage for summary-contract toggle

Local Grok has no instruction inject path; settings copy now matches
remote-only Grok support (and still excludes Cursor).

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 18:51:35 +08:00
KorenKritaandGitHub 5e7e930713 fix(web): fit composer placeholder to available width (#1388) 2026-08-06 18:51:02 +08:00
KorenKritaandGitHub 256ad98ece fix: normalize cache token usage semantics (#1390)
Normalize usage input at parse time, mark inclusive producers, rebuild derived usage indexes, and preserve valid primary usage when cache partitions are malformed.

Fixes #1389
2026-08-06 18:50:49 +08:00
6ffc125b1a fix(web): show truncated query on collapsed session search (#1391)
* fix(web): show truncated query on collapsed session search

Collapsed SessionListSearch only showed an indicator dot for active
filters, hiding the terms operators need. Render a compact truncated
query chip when text filter is set (Fixes tiann/hapi#1356).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): use chat-user chip colors for active search chip

--app-link/15 washes to near-gray in default light mode (link is
near-black). Use --app-chat-user-chip-* so the collapsed query chip
stays a visible blue highlight when text truncates away.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 18:50:27 +08:00
weishu 828e984508 Release version 0.27.1 2026-08-05 23:06:09 +08:00
weishu 97c7412434 fix(codex): forward lifecycle hooks without allow decision 2026-08-05 23:04:10 +08:00
KorenKritaandGitHub e532ff259b feat(web): add setting to keep reasoning collapsed by default (#1385) 2026-08-05 23:02:45 +08:00
AnanovoandGitHub 3eff0ec688 fix(web): keep session date filter directly accessible (#1367)
* fix(web): keep session date filter directly accessible

* fix(web): announce active session date range
2026-08-05 22:26:38 +08:00
c0b30bf916 feat(cli): MCP list_peers + runner hub auth for peer discovery (#1372)
* feat(cli): MCP list_peers + runner hub auth inheritance

Runner-spawned agents could not discover same-hub peers without
sitting on the hub host or pasting a session id. Add MCP list_peers
(in-process credentials), export HAPI_API_URL/CLI_API_TOKEN after
auth init for shell fallbacks, and clearer auth failure hints.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): do not export default hub URL into HAPI_API_URL

exportHapiHubAuthEnv was writing the implicit localhost default into
process.env, which made maybeAutoStartServer skip starting the bundled
hub. Only export HAPI_API_URL when the URL came from env or settings;
always still export CLI_API_TOKEN. Also fill missing deliveryMode on
abort restore so web typecheck matches RawSendError (main tip unblock).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): widen initializeApiUrl mock return type in test

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): never export CLI_API_TOKEN; exclude self from list_peers

Keep settings/prompt-backed hub secrets out of wrapped agent env so
shell JWT+curl cannot bypass peer-tool approval. Fresh hapi re-reads
settings; env-backed tokens already inherit. list_peers omits the
calling session from the shortlist.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): resolve peer labels via summary/path like web titles

list_peers was showing (unnamed) for ordinary sessions because titles
live in metadata.summary.text. Match web getSessionTitle and collapse
whitespace so each peer stays one agent-readable line.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli,hub): emit full peer ids and honor GET /sessions?limit

Short 8-char prefixes collide across UUID namespaces; print full ids so
resolveSessionByPrefix stays unambiguous. Honor optional limit after sort
so listPeerSessions stops loading the whole namespace for scheduled counts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub): type sessions limit test mock as Map<string, number>

CI tsc rejected Map<string, null> for getNextScheduledAtBySessionIds.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli,hub): unbounded ping resolve; peer list order=updatedAt

Keep GET /sessions?limit only for discovery callers. ping/inspect omit
limit so full UUIDs outside the first 500 stay resolvable. Peer lists
pass order=updatedAt so truncation matches newest-first. Basename
fallback splits Windows paths.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): auto-approve ACP title List Peer Sessions

Permission derivation prefers request.title; match the MCP tool title
form so default-mode ACP sessions do not prompt on discovery.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): pad list_peers fetch; split hub URL vs token hints

Fetch limit+2 when excluding the caller so overflow still surfaces at
limit=100. Clarify that auth login only saves the token, not HAPI_API_URL.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): use boolean overflow for ping-peer --list

Match MCP list_peers: fetch limit+1 and mark hasMore instead of claiming
an exact omitted count from a 200-row sample.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub): tolerate mocked machineCache without expireInactive

CI flake: 5s inactivity tick hit test doubles that only stubbed
getOnlineMachinesByNamespace. Optional-call + stub the method.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 22:16:04 +08:00
KorenKritaandGitHub 3aff832246 fix(pi): advertise runner capabilities at registration and on connect (#1386)
* fix(pi): advertise runner capabilities at registration and on connect

The hub only persists registration-time runner state for brand-new
machines, and the socket heartbeat replays only what the hub already
persisted. A runner upgraded in place (e.g. to 0.27.0, which adds
piExistingSessionResume) never gets its new capabilities observed: the
stale runner_state stays in the hub DB and Pi resume fails with
"Pi resume requires an upgraded runner".

- shared: RUNNER_CAPABILITIES single source of truth
- runner: advertise capabilities again on every socket connect, so a
  reconnected runner self-heals without a hub-side change
- hub: merge registration-time capabilities into an existing machine's
  runner_state, leaving live fields (status/pid/startedAt) socket-owned

* fix(hub): backfill runner capabilities when metadata also changes

The existing-machine registration path returned early after the metadata
merge, skipping the capabilities backfill whenever registration changed
metadata too. An upgraded runner necessarily changes happyCliVersion, so
its first upgraded registration missed the backfill and Pi resume could
still fail until the async socket state update landed.

Merge both fields in the same call and return the latest row; add a test
covering metadata and capabilities changing together.
2026-08-05 22:12:04 +08:00
weishu 0a037c9812 Release version 0.27.0 2026-08-05 19:27:32 +08:00
KorenKritaandGitHub 0201b9f6d4 feat(pi): import and reconcile local sessions (#1365)
* feat(pi): expose local session transcripts over machine rpc

* feat(pi): import and incrementally reconcile local sessions

* feat(web): import and resume local Pi sessions

* build(web): precache the expanded app bundle

* fix(pi): harden imported history reconciliation

* fix(pi): persist import cursors and media placeholders

* docs(web): warn about concurrent native Pi writers

* feat(pi): sync native history from session menu

* fix(pi): address import review findings

* fix(web): preserve delivery mode for abort restores

* test(hub): use the Bun test runtime

* fix(pi): preserve custom names during sync

* docs(pi): clarify concurrent session guidance

* perf(hub): index imported Pi sessions once

* perf(hub): reuse Pi import lookup for batches

* fix(web): ignore stale Pi session scans
2026-08-05 16:08:08 +08:00
weishu 5122a3fc5f fix(hub): reindex usage events to backfill model attribution
#1359's session-model fallback only applies to events indexed after
the upgrade. Clear usage_scan_state in a V19→V20 migration so the
lazy re-index re-derives legacy rows instead of leaving them
bucketed as "unknown".
2026-08-05 15:44:23 +08:00
wushenghuaandGitHub f157d29b20 fix: preserve fallback models for legacy usage events (#1359)
* fix: preserve fallback models for legacy usage events

Use the session model when historical usage lacks event-level metadata, while retaining indexed attribution across model changes and epoch rebuilds. Explicit event models remain authoritative.\n\nvia [HAPI](https://hapi.run)\n\nCo-Authored-By: Codex <noreply@anthropic.com>

* fix: persist explicit usage models on replay
2026-08-05 15:25:08 +08:00
c7e38e872c feat(a2a): steer session citations toward inspect_peer (#1373)
* feat(a2a): steer session citations toward inspect_peer

Copy-reference prose and markdown /sessions/<id> links both parse to hub
ids; MCP/CLI descriptions and flavor prompts forbid treating them as local
FS paths so agents call inspect_peer first (tiann/hapi#1370).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): fail closed on ambiguous session citations

Codex #1373: do not silently pick ids[0] when a paste contains multiple
/sessions/ links (shared by inspect_peer and ping_peer). Also strip
trailing prose punctuation from bare citation ids.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): prefer Copy-reference path over title /sessions/

Codex #1373 MINOR: titles containing /sessions/<other> must not make
normalizeSessionIdPrefix fail closed on an otherwise valid paste.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): do not short-circuit multi-citation Copy-reference pastes

Codex #1373 MAJOR: only treat parenthesized Copy-reference as canonical
when the paste is that citation alone (plus optional steer suffix).

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 15:05:38 +08:00
KorenKritaandGitHub 8c4d4198a8 fix(web): preserve manual scroll during initial settling (#1377)
* fix(web): preserve manual scroll during initial settling

* fix: remove duplicate Windows lockfile entry

* fix(web): capture scrollbar input during settling
2026-08-05 15:04:48 +08:00
KorenKritaandGitHub e50099e4a4 fix(pi): keep running state through active RPC turns (#1379)
* fix(pi): keep running state through active RPC turns

* test(pi): cover pre-settlement state snapshots
2026-08-05 15:03:57 +08:00
9b4b9ec9d4 fix(web): avoid React #185 from MessageActions useAuiState object snapshot (#1381)
#1306 returned a fresh object from useAuiState on every call. useSyncExternalStore
compares snapshots with Object.is, so that looped re-renders and crashed every
session chat with minified React error #185. Split into primitive selectors and
add regression coverage. Fixes #1380.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 15:03:45 +08:00
weishu 46fc83d211 feat: cut relay tunnel bandwidth with compression and SSE replay
Relay-metered traffic drops on every channel that carried avoidable
bytes; binary payloads (attachments, voice audio) are unchanged.

Hub:
- gzip /api/* JSON responses, gated by q-aware Accept-Encoding
  negotiation (explicit gzip;q=0 beats a wildcard in either order;
  hono's compress() alone matches by substring)
- enable WebSocket permessage-deflate and default flagless ws.send()
  to compressed frames - Bun negotiates the extension but compresses
  nothing unless each send opts in, and @socket.io/bun-engine never
  passes the flag (measured 96 KB terminal payload -> 608 B on wire)
- replay missed SSE events on reconnect: 256-event/2MB ring buffer,
  per-process epoch ids bound to the authenticated namespace so a
  token swap can never resume from a foreign cursor, standard
  Last-Event-ID header preferred over the ?lastEventId fallback,
  live broadcasts queued until the replay flushes to preserve order

Web:
- skip the full sessions/details/messages resync when the hub answers
  resume:ok - a phone unlock now costs a handshake plus the gap delta
  instead of refetching everything
- own every EventSource retry path: take over browser-native
  CONNECTING retries, defer reconnects while the tab is hidden, and
  raise the backoff ceiling to 5 min after repeated failures
- drop the 30s skills/slash-commands polling; refresh on demand
  without blocking the suggestion menu behind a stalled CLI RPC
- remember the websocket upgrade across terminal socket reconnects
2026-08-05 14:59:31 +08:00
27bc6bade3 fix(web): drop Idle session-list badge (keep working/pending) (#1366)
* 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>
2026-08-05 09:16:41 +08:00
Junmo KimandGitHub 229766dd21 fix(agy): make conversation discovery deterministic at session start (#1369)
* 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.
2026-08-05 07:56:40 +08:00
weishu b7503d9309 docs: restructure docs site and fix drift against code
- split installation.md into installation/deployment/notifications
- merge cursor/grok guides into new agents.md with full support matrix
- sidebar: grouped sections; add namespace, deployment, notifications,
  native companion contract
- fix license footer (AGPL-3.0), settings schema fields and $id
- fix drift in pwa, faq, namespace, how-it-works, voice-assistant,
  quick-start, native-companion-contract
- move mermaid lightbox dogfood doc to localdocs (untracked)
- README: complete agent list, replace dead cursor/grok links
2026-08-05 07:51:16 +08:00
weishu de5fa4aecd docs: update voice assistant guide for multi-backend support 2026-08-05 06:46:26 +08:00
weishu b31c5a8e76 fix(web): skip filler br element in contenteditable composer 2026-08-05 00:01:38 +08:00
807fa72aaa fix(opencode): surface stall errors and clear thinking spinner (#869)
* 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>
2026-08-04 11:19:02 +08:00
3556c7d7f1 Support macOS Codex Desktop restart from Hapi (#912)
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>
2026-08-04 11:18:41 +08:00
f6da005b50 feat(web): FUE + composer hint for session @-mentions (#1274)
* 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>
2026-08-04 11:18:21 +08:00
AnanovoandGitHub a0c676818f fix(web): sync share metadata and active-turn availability (#1306)
* fix(web): align sharing with session state

* fix(web): keep share state in sync

* fix(web): fail closed for trimmed active turns

* fix(web): refresh prepared share images

* fix(web): preserve sharing during queued thinking

* fix: track a stable active turn boundary

* fix: anchor active turns to persisted messages

* fix(web): include Pi reasoning in share metadata

* fix(hub): refresh queued thinking grace on retry

* test(web): isolate mobile thread scroll setup

* fix(hub): advance queued turn boundaries

* fix(hub): guard queued boundary advancement

* perf(web): precompute running turn sharing

* fix(hub): use hub time for turn boundaries

* perf(web): pause closed share metadata timer
2026-08-04 11:18:08 +08:00
Junmo KimandGitHub c3bed919b8 fix(opencode): verify persisted compaction results (#1357) 2026-08-04 11:15:42 +08:00
KorenKritaandGitHub 021b5c194b feat(pi): complete RPC parity, native steer, and history controls (#1353)
* 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.
2026-08-04 11:01:00 +08:00
李余通andGitHub a03bad15e3 fix: resolveCodexImportMachineId fails with multiple online machines (#1147) 2026-08-04 11:00:01 +08:00
8e34e7599b perf(hub,web): emit structured patches for session todos/teamState/metadata/agentState writes (closes #895, second half of #884) (#897)
* 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>
2026-08-04 10:59:35 +08:00
3c83fe58c9 fix(web+cli): Cursor model picker empty on bare ACP ids + nested variant drill-down (#947)
* 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>
2026-08-04 10:59:06 +08:00
00e8fc3a47 fix(codex): recover ready after stale terminal event (#997)
* 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>
2026-08-04 10:58:49 +08:00
79f91e4b45 fix(acp/runner): Cursor worktree banner + skip nested --worktree hang (#1087)
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>
2026-08-04 10:58:24 +08:00
wushenghua 5f2326168d Merge upstream/main into main 2026-08-04 10:56:26 +08:00
Junmo KimandGitHub e35c06b36a feat(agy): add Antigravity as an interactive PTY agent (#1320) 2026-08-04 10:50:03 +08:00
weishu 3ce73769c7 Release version 0.26.0 2026-08-04 08:33:19 +08:00
KorenKritaandGitHub c1b32b51fe fix(web): make browser-local speech probing Android-safe (#1349)
* fix(web): guard browser-local speech probes

* test(web): cover concurrent speech probes

* docs: clarify browser-local speech probing
2026-08-04 08:19:56 +08:00
f10fbc7496 feat(cli): add GitHub Copilot CLI agent support via ACP (#1245)
* 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.

Fixes tiann/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>
2026-08-04 08:19:12 +08:00
weishu b67f4e56e5 feat(hub): per-hub relay auth keys with automatic recovery
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.
2026-08-04 08:18:17 +08:00
SSU-WEI HUANGandGitHub cc8cc914bc fix(web): initialize session unread baseline (#1346)
* fix(web): initialize session unread baseline

* fix: complete unread baseline migration

* test: restore standard CLI coverage

* fix(web): scope unread baseline by hub
2026-08-04 08:05:34 +08:00