mirror of
https://github.com/wu736139669/hapi.git
synced 2026-10-08 19:19:42 +00:00
17ee052d9a9063b332508a47e3bd56d784c09ba7
197
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
17ee052d9a |
fix(web): preserve the visible chat window during rewind (#1766)
* fix(web): preserve chat window during rewind * fix(web): scope rewind invalidation preservation * fix(web): clear unknown rewind boundaries * fix(web): deduplicate rewind invalidations * fix(web): retain rewind dedupe history |
||
|
|
3873e58496 |
fix(web): keep streamed reasoning/text block ids stable across snapshot rows (#1741)
* fix(web): keep streamed reasoning/text block ids stable across snapshot rows
Streaming snapshots of one stream (pi/codex reasoning and text) arrive as
separate message rows, and the window store retires older rows as newer
snapshots land. The timeline derived the block id from whichever row was
first seen, so the id (and the threadMessageId built from it) churned on
every snapshot, remounting the rendered reasoning panel mid-stream and
replaying its open animation — the panel visibly flashed/re-rendered on
every snapshot tick.
Derive the block id from the stream id when present (unique per stream,
stable across snapshot rows) so the block is updated in place and the
smooth streaming keeps appending to the previous text. Row-derived ids
remain the fallback for content without a stream id.
Also rerun gen:fixtures to refresh the two golden fixtures affected by
the new id shape.
* fix(ios,android): mirror stream-stable block ids in native chat ports
The native HapiKit (Swift) and protocol (Kotlin) chat pipelines are ports
of the web reducerTimeline and are pinned by the same golden fixtures in
shared/fixtures/chat. After the web-side change to derive streamed
reasoning/text block ids from the stream id, the ports still produced
row-derived ids, so the iOS/Android fixture conformance suites went red
on the two refreshed fixtures.
Apply the same streamId-first id derivation (row-derived fallback kept)
to both ports so all three pipelines project identical block ids.
* fix(web,ios,android): reject blank stream ids as block identity
Blank ('' or whitespace-only) stream ids are not streams per the wire
semantics in shared/src/messages.ts (readReasoningStreamId trims before
accepting). The previous nullish fallback let accepted payloads carrying
blank ids through, so every such row shared one empty block id: the
merge maps collided and assistant-ui occurrence suffixes churned with
list position, reintroducing remounts.
Normalize with a trim guard in all three pipelines (web, HapiKit,
protocol) and add a web regression test covering both empty and
whitespace-only ids.
* fix(ios): use normalized stream id for block construction identity
The blank-id guard was applied to lookup and map insertion but block
construction still read the raw optional, so accepted payloads carrying
blank/whitespace ids produced blocks sharing one blank SwiftUI identity
instead of falling back to row-derived ids (web/Android already used the
normalized local). Hoist the nonBlankStreamId result and reuse it for
lookup, block identity, and insertion in both the text and reasoning
branches.
Also add native coverage for stream identity: stream-id derivation for
text/reasoning plus blank ('' and whitespace-only) fallbacks, which the
golden fixtures do not exercise.
* fix(web): pin blank stream-id identity contract in golden fixtures
Update the two stale fixture descriptions (stream-keyed blocks are now
keyed by the stream id, not the first message) and add a generated
conformance fixture covering empty and whitespace-only codex data.id
values for both reasoning and text: blank ids are not stream identities,
so each payload keeps its own row-derived block id instead of collapsing
onto a shared blank identity. Web, iOS, and Android all run this same
golden fixture.
* feat(hub): make title provider max_tokens and timeout env-tunable
Reasoning models used as title providers (e.g. GLM thinking models) need
more than 64 completion tokens and more than the hardcoded 10s timeout to
emit a title, and the only workaround was patching the compiled binary
after every install.
Expose both knobs via HAPI_TITLE_PROVIDER_MAX_TOKENS and
HAPI_TITLE_PROVIDER_TIMEOUT_MS, following the existing
HAPI_TITLE_SUGGESTION_RATE_LIMIT pattern; defaults are unchanged.
* docs(hub): document title provider max_tokens/timeout env knobs
Add the two new HAPI_TITLE_PROVIDER_* variables to the title-provider
configuration table in the installation guide, and extend the provider
test to cover the timeout abort path (the signal fires and rejects the
in-flight request).
---------
Co-authored-by: HongChenGG <HongChenGG@users.noreply.github.com>
|
||
|
|
aa0c1dc808 |
fix(codex): fail closed on ambiguous Web Rewind boundaries (#1707)
* fix(codex): fail closed on ambiguous Web Rewind boundaries * fix(codex): reject malformed native rewind history * fix(codex): reject duplicate rewind identifiers * feat(codex): offer Fork fallback for ambiguous rewind * fix(codex): gate rewind Fork fallback on exact native boundary * fix(codex): reject unresolved rewind boundaries safely * chore: trigger PR checks * fix(codex): gate safe rewind fallback on fork support * fix(codex): require complete user ids for rewind fallback |
||
|
|
ec08959f07 |
fix(agy): show Gemini 3.7 Flash in the agy model list (#1585)
* refactor(agy): extract the agy models probe from the fetch flow
One invocation and the decision of what to do with its output were
tangled in a single promise. Split them so the probe can be given
different arguments, and run more than once, without duplicating the
stream and timeout handling.
No behaviour change: the same argument vector, timeout, stream
handling and fallbacks remain, and the existing tests are untouched.
* fix(agy): read the model list from agy's structured output
The picker recovered ids and labels from `agy models`, whose table is
meant for people to read: it has emitted display names only, then
bare ids, then tab-separated id/label pairs over the 1.1.x line, and
each shape change silently sent the probe back to the hardcoded
mirror. Since agy started offering Gemini 3.7 Flash, that mirror is
what users see, so the three new entries never appear.
agy publishes the same listing as a structured payload, so read that
instead: `agy --output-format=json models` returns
`command.data.models[] = {id, label}`. The flag is global, so it goes
before the subcommand and takes its `=` form.
Releases that predate the flag ignore it and print the table, so the
text parser stays as the fallback, and it now also understands the
tab-separated shape. Every release checked, 1.0.16 through 1.1.13,
ignores the flag rather than rejecting it; a build that rejected it
would emit no models at all, so ask once more without the flag when
the first invocation yields nothing either parser can read.
* fix(agy): follow the Gemini 3.7 Flash row in the model picker
agy now lists Gemini 3.7 Flash as the top row of the `/model` TUI
picker, but the hardcoded row table still starts at 3.6 Flash. A
session whose current model is that row can never change its model:
the picker cannot identify the current row and the change is
rejected.
Add the 3.7 row to MODEL_ROWS/TARGETS. Every existing row shifts
down by one, which leaves their relative deltas, and therefore the
navigation keys emitted between them, unchanged. Mirror the three
new ids into AGY_MODEL_LABELS so the session pickers offer them too.
|
||
|
|
e5a8212f4a | feat(session): validate agents and browse workspace directories | ||
|
|
be1ef2a2e4 |
feat(dsh): integrate DeepSeek Harness through ACP (#1632)
* feat(dsh): add DeepSeek Harness ACP flavor * fix(dsh): update mobile flavor catalogs * fix(dsh): keep mobile spawn policy managed * fix(dsh): keep managed policy and prompt retry * fix(dsh): suppress unsupported runner policy flags * fix(dsh): align native managed-policy UX |
||
|
|
fdf4fdaa38 |
feat(web,hub): make large conversation export warning-only (#1648)
* feat(export): warn before large session downloads * fix(export): surface server size errors |
||
|
|
0aebf39c78 |
fix(opencode): keep one stored message per reasoning stream (#1643)
* fix(acp): carry the live reasoning marker on the wire payload ACP agents stream thoughts a token at a time, so the handler coalesces them into a buffer and re-sends the whole buffer under a stable stream id every 250ms. The converter dropped the marker that says a payload is one of those throttled snapshots, leaving the hub unable to tell a replaceable snapshot from the settled message that closes the stream. Mirrors how the text variant already forwards streamSnapshot. * fix(hub): keep one stored message per reasoning stream OpenCode reasoning arrives as a series of growing snapshots sharing one stream id, and every snapshot was persisted as its own message. A 26h session reached 48,844 rows and 63MB, and because the web budgets a fixed number of messages, its 400-message window covered barely three minutes of conversation — scrolling up walked through duplicate snapshots instead of history. Retire a stream's earlier live snapshots once their replacement is stored. Sweeping only after the insert matters: the two statements are separate transactions, so clearing first would leave a window where a crash takes the whole stream. Only rows marked live are eligible and the replacement is spared, so a stream always keeps at least one row and the settled message that closes it is never removed. Live rendering is unchanged: the web still receives every snapshot and already folds them by stream id. * fix(web): spend the message window on conversation, not repeated snapshots The window budgets raw messages, but a reasoning stream renders as a single folded block no matter how many snapshots it arrived in. On sessions recorded before the hub started retiring them, those snapshots fill the window on their own: in one 26h session the newest 400 messages covered 202 seconds, so scrolling up paged through duplicates instead of history. Collapse each stream to its newest snapshot before trimming. Rendering is unchanged — the timeline already folds them by stream id — and rows without a stream id are never touched. * fix(ios,android): port reasoning-snapshot compaction to the native windows The window logic in HapiProtocol and :core:protocol is a one-to-one port of the web store, so collapsing superseded reasoning snapshots only on the web left the native windows budgeting raw snapshot rows. The hub stores one row per stream now, but a client that already holds the older snapshots still spends its window on them. Add the same stream-id reader and compaction to both ports, in the shape each already uses for agent-run rows, and pin the behaviour with a pagination fixture. Both fixture suites enumerate shared/fixtures/pagination from disk, so the ports cannot drift from the web again without CI saying so. |
||
|
|
0f7a3da68b |
feat(cursor): mid-turn Steer via concurrent ACP session/prompt (#888) (#1609)
* feat(shared): steer capability gates and live steered signal schemas - STEERING_SUPPORTED_FLAVORS / isSteeringSupportedForSession gate which agents can deliver queued messages into the active turn (pi, codex, cursor ACP; legacy stream-json cursor excluded) - AgentState.steeringActive, DecryptedMessage.steered and messages-consumed live signal (never persisted by the hub) * feat(cli): queue reservations and steered messages-consumed option - MessageQueue2 gains takeByLocalId/restoreReservation/ beginReservationDispatch/commitReservation so an async steer can reserve a queued row without racing the main loop's turn/start drain - emitMessagesConsumed accepts steered: true to mark mid-turn delivery * feat(codex): mid-turn steer via app-server turn/steer (#888) - CodexAppServerClient.steerTurn + TurnSteerParams/Response types - CodexRemoteLauncher registers the steer-queued-message RPC handler: reserves the queued row, validates it against the active turn (no control commands, matching mode hash), injects via turn/steer with an epoch guard that invalidates in-flight steers on abort/cleanup - steeringActive agent state tracks the active-turn window - hub syncEngine gate opens to codex; messages-consumed relays steered * feat(web): Steered badge and steer gating for codex sessions - HappyUserMessage shows a ↳ Steered badge fed by the live messages-consumed steered signal, preserved across server echoes and refetches (mergeMessages carries the optimistic marker) - SessionChat gates canSteer via isSteeringSupportedForSession instead of the pi-only check - clearStaleQueuedStatus normalizes a queued status on an invoked message - fix(web): drop duplicate showSessionSummaryInChat in markdown test (upstream typecheck breakage) * feat(acp): split request dispatch from completion and add soft steer - AcpStdioTransport.sendRequestWithDispatch separates stdin-accepted dispatch from the JSON-RPC response, keeping sendRequest behavior unchanged - AcpSdkBackend tracks concurrent session/prompt requests with an activePromptRequests counter (main prompt + soft steers); response completion stays pending until every concurrent prompt settles - beginSoftSteerPrompt kicks off a concurrent session/prompt (Cursor GUI Send semantics — no cancel, no handler swap) returning {dispatched, completed}; softSteerPrompt awaits the full response for direct callers * feat(cursor): mid-turn soft steer via concurrent session/prompt (#888) - CursorAcpRemoteLauncher registers the steer-queued-message RPC handler: reserves the queued row, rejects control commands and mode mismatches, then soft-injects via beginSoftSteerPrompt without canceling the in-flight turn - Acks the hub once stdin accepts the inject (not on turn completion) to stay inside the 30s RPC window; the launcher stays busy until the concurrent prompt settles so handlers are not swapped mid-inject - steeringActive agent state mirrors the active-turn window; abort and cleanup reset it and invalidate pending steers - Legacy stream-json Cursor sessions register a steer handler that reports unsupported * fix(codex,shared): address bot findings on steer gate and ambiguous turn/steer - STEERING_SUPPORTED_FLAVORS / isSteeringSupportedForSession advertise codex and pi only; cursor joins when its soft-steer handler lands (#1609) - turn/steer now splits dispatch (stdin accepted) from completion (turn finished): the hub RPC acks once dispatch succeeds — never on the concurrent turn's completion, which can exceed the 30s RPC window - queue row commits only after the turn settles; a rejected/aborted steer restores the row so the message still delivers via turn/start, and a dispatched steer is never restored (no duplicate delivery) - steer carries clientUserMessageId (echoed as userMessage.clientId) so ambiguous transport failures can reconcile the thread later - client tests cover dispatch/complete split and stdin-write failure * feat(shared): advertise cursor in the steer gate now that its handler lands Cursor ACP sessions pass the web and hub steer gates; legacy stream-json cursor sessions stay excluded. * fix(codex): reconcile dispatched steers before restoring; align error copy - A dispatched turn/steer whose completion fails (disconnect / protocol error) is now reconciled via thread/read by clientUserMessageId before the queued row is restored — the instruction is only re-delivered by turn/start when the thread never received it - Reconcile targets the pinned steer thread, not whichever turn is current when completion fails - syncEngine unsupported-flavor error now matches the capability gate (Pi and Codex only until the cursor handler lands) - launcher tests cover steer success (ack on dispatch), reconcile-accepted and reconcile-rejected outcomes * fix(codex): consume the row at dispatch; drop background reconcile - The hub RPC acks and the queue row is consumed as soon as stdin accepts turn/steer; completion is background-only logging. A dispatched steer is never restored, so the same localId cannot be re-delivered via turn/start after the caller was told the steer succeeded - Dispatch failure (stdin write error) still restores the row and reports failure - steer.completed rejection is always handled (no unhandled rejection on the dispatch-failure path) - tests updated: completion failure after dispatch keeps the row consumed; dispatch failure restores it * fix(cursor): consume the row at dispatch; keep waiters for prompt gating - The hub RPC acks and the queue row is consumed as soon as stdin accepts the concurrent session/prompt; completion is background-only. A dispatched steer is never restored (no duplicate via the next prompt) - softSteerWaiters are registered before awaiting dispatch so the main loop's finally cannot start the next prompt mid-inject; they still gate prompt handover on completion - tests updated: post-dispatch ACP rejection keeps the row consumed * fix(cursor,hub): never hang teardown on unresolved soft steer; align diagnostics - Prompt-finally waits for soft-steer completion only when not exiting; the outer finally no longer waits at all — cleanup() disconnects the ACP transport, which rejects pending requests and settles the waiters - syncEngine gate diagnostics and JSDoc name all supported flavors (Pi, Codex, Cursor ACP) - regression test: Switch with an unresolved soft-steer completion still reaches teardown * fix(codex): distinguish definite rejection from indeterminate completion - Transport-level failures (timeout, abort, disconnect, spawn, protocol) carry an indeterminate marker; explicit JSON-RPC error responses do not - After a dispatched steer, turn completion resolves → commit + consumed; a definite app-server rejection restores the row (instruction was never accepted, so turn/start cannot duplicate it); an indeterminate outcome leaves the row reserved so it can never be delivered twice - Completion handling registers before awaiting dispatch so the dispatch-failure path cannot leak an unhandled rejection - client/launcher tests cover explicit rejection (restore), indeterminate outcome (row stays reserved) and dispatch failure * fix(codex): reconcile indeterminate steers instead of a permanent reservation - After an indeterminate completion (disconnect/protocol), reconcile the thread by clientUserMessageId immediately: accepted → commit + consumed, provably rejected → restore, still unreadable → keep the reservation and retry from the main-loop top on later passes (post-reconnect) - A row never sits in dispatching forever: the hub cannot stamp it invoked while the instruction may never have been accepted - tests: indeterminate keeps reserved while thread unreadable; accepted reconciliation consumes; rejected path restores * fix(cursor): abort drops soft-steer waiters so the next prompt never blocks - Ordinary Abort (shouldExit false) now clears softSteerWaiters: the prompt finally cannot wait forever on a soft steer whose completion is unbounded; the ACP cancel rejects in-flight requests, and cleanup() settles leftovers on session end - regression test: unresolved soft-steer completion after Abort no longer blocks the next prompt * fix(codex): accept all thread item shapes; retry reconcile; ack through abort - Reconcile matcher accepts userMessage/user_message with clientId/ client_id, matching the shapes the thread parser supports — an accepted steer can no longer be misclassified as rejected - A pending reconciliation schedules a wakeLoop retry, so a temporary app-server outage cannot strand the reservation behind waitForTurnOrRecovery - The success-path ACK no longer checks the steer epoch: the hub already reported steered on dispatch, so commit + messages-consumed must reach it even when an abort resets the queue in between * fix(cursor,acp): abort force-settles soft-steer bookkeeping - AcpSdkBackend.abortSoftSteers() drops the concurrent-prompt counter and notifies response-complete so the next turn's waitForResponseComplete() cannot block on a soft steer that will never settle after abort - handleAbort calls it before clearing the waiters; the main prompt's own finishPromptRequest stays guarded by Math.max(0, ...) - unit tests cover counter release and no-op when idle * fix(codex): reinit reconnected app-server; keep reconcile retries alive - thread/read after a disconnect auto-connects a fresh app-server, which must be initialized before any request — reconcile now ensures connect + initialize (isConnected getter added to the client) - every still-unknown loop-top reconciliation schedules the next retry, so recovery without external traffic is eventually observed - launcher mock gains isConnected * test(acp): match finishPromptRequest epoch signature in whitebox test * fix(codex): timer-driven reconciliation; init tracking; abort-safe ACK - Reconciliation runs on a self-rescheduling 1s timer independent of the main loop (wakes it too), so idle loops and waitForTurnOrRecovery still observe app-server recovery; abort clears nothing implicitly — the ACK path commits and consumes even when the reservation was cancelled - Absence of a durable client id is ambiguous: unmatched reads stay 'unknown' and keep retrying instead of restoring the row - CodexAppServerClient tracks initialized state (reset on disconnect/exit) so ensureAppServerInitialized re-initializes a fresh process before thread/read; initialize failures leave the flag false for the next retry - tests: accepted reconciliation via scheduled timer, indeterminate keeps reserved, explicit rejection restores * fix(codex): bind reconciliation to the launcher lifecycle - runSteerReconciliation clears any armed retry timer on entry and never installs a second one, so loop-top and timer-driven passes cannot multiply - shuttingDown is set when the main loop ends: timers are cleared and the pending map is dropped, so an unresolved steer can never respawn an app-server after cleanup (remote-to-local switch included) * fix(cursor): abort releases an in-progress soft-steer wait - The prompt-finally wait races Promise.allSettled against the abort signal: an Abort that clears the waiters now also releases a wait that already started, so the launcher always reaches the next queued prompt * fix(codex): report steered only after app-server acceptance - The handler now awaits steer.completed (the inject-acceptance response): an explicit JSON-RPC rejection surfaces as failed and restores the row for the normal turn/start path instead of a false steered - Transport failure after dispatch reports 'Steer outcome is being reconciled' and keeps the row reserved while the timer-driven thread reconciliation runs - dispatch-failure path also swallows the paired completion rejection * fix(cursor,acp): commit on ACP acceptance; distinguish transport failures - AcpStdioTransport marks transport-level failures (timeout, closed, stdin write) as indeterminate; explicit JSON-RPC error responses are not - The steer handler commits + consumes on completion (ACP acceptance) and restores the row on an explicit rejection; an indeterminate transport failure keeps the row reserved so a delivered instruction is never re-sent, and the ACK reaches the hub even when abort reset the queue - launcher/transport tests updated for the three outcomes * fix(steer): tri-state cancel, clear-safe reservations, bounded acceptance wait - MessageQueue2.cancelByLocalId returns 'in-flight' for a dispatching steer reservation: the hub neither deletes the row nor stamps invoked_at (new CancelMessageResponse 'busy' status; web restores the optimistic row); pushIsolateAndClear and reset/close share cancelReservations so /clear-style commands cannot have a rejected steer resurrect a discarded prompt - turn/steer acceptance wait bounded at 25s (< hub 30s RPC timeout): a lost response is indeterminate and funnels into thread reconciliation instead of stranding the reservation - tests updated for the tri-state cancel contract * test(cursor): match tri-state cancel contract for dispatching steers * fix(cursor): drop duplicate promptInFlight declaration after upstream merge * fix(codex,web): busy-aware edit flow; bound reconciliation reads - QueuedMessagesBar edit flow treats a 'busy' cancel as unsuccessful: it never prefills the composer when the row is inside an async steer, so a second client cannot send a duplicate - reconcileSteerByClientId bounds thread/read with a 5s timeout so a connected-but-silent app-server cannot hold the reservation in-flight indefinitely * fix(steer): inFlight-dominated cancel acks; bounded reconciliation - hub cancel-queued-message acks check inFlight before removed: a stale duplicate socket reporting removed can no longer delete the durable row while another socket is dispatching the steer - reconciliation entries expire after 60s and mark delivered: after the rejection window, a dispatched steer that the app-server never proved (client ids dropped on restart) is committed instead of polling thread/read forever - pre-dispatch failures (abort before write included) never enter reconciliation — they restore the row and report failure * fix(cursor,acp,web): indeterminate close marks, steer gating precision - AcpStdioTransport.rejectAllPending marks close/protocol failures indeterminate, so an accepted-but-close-interrupted soft steer restores nothing (no duplicate delivery) - the abort race in the soft-steer wait removes its listener in finally (no accumulation across repeated waits) - SessionChat gates the Steer button on agentState.steeringActive for codex/cursor instead of the queued-grace thinking flag, so Steer is not exposed before the launcher can accept it - codex pre-dispatch abort never enters reconciliation (merged from #1606) * fix(steer): persist indeterminate outcomes without replay * fix(cursor): hold ambiguous steers for explicit resolution * fix(steer): make ambiguous delivery restart-safe * fix(cursor): make ambiguous delivery restart-safe * fix(steer): recover crash-held rows and preserve retry dedup * fix(steer): ack retries and bound stdin dispatch * fix(cursor): reject steers when prompt generation changes * fix(steer): reconcile indeterminate dispatches and serialize retries * fix(cursor): preserve soft-steer reservations across abort * fix(codex): classify stdin callback failures as indeterminate * fix(steer): recheck indeterminate cancels after ACK * fix(steer): close retry and abort races * fix(cursor): hold ambiguous dispatch failures * fix(steer): serialize live retries and abort admission * fix(steer): distinguish live dispatching from unknown * fix(cursor): bound ACP dispatch acknowledgements * fix(steer): keep ACK failures held and reconcile busy cancel * fix(cursor): preserve state when dispatch ACK is uncertain * fix(steer): distinguish held cancel from removal * fix(store): combine schema v24 migrations * fix(cursor): distinguish held cancel from removal * fix(store): reserve schema v25 for steer delivery state * fix(cursor): suppress late ACP updates after abort * fix(steer): keep held cancel state and notify requeue * fix(cursor): isolate late updates after abort * fix(steer): release explicitly cancelled unknown reservations * test(cursor): cover explicit held cancellation * fix(codex): reject cancelled reservations before native steer * fix(cursor): reject cancelled reservations before ACP steer * fix(codex): make reservation restore atomic with state * fix(cursor): make reservation restore atomic with state * fix(codex): terminate abandoned transport writes * fix(cursor): hard-stop abandoned writes and update native queue state * fix(steer): own abandoned app-server lifecycle and consume races * fix(cursor): isolate aborts and add native retry resolution * fix(codex): confirm dispatch and recover abandoned turns * test(codex): mock abandoned transport callback * fix(native): reconcile retry responses * fix(codex): clear visible turn state on transport loss * fix(steer): claim retries and cover native delivery state * fix(native): resync busy cancel outcomes * fix(native): preserve indeterminate state on Android hydration * fix(steer): make retry claims single-winner * fix(cursor): hold restore failures for explicit resolution * fix(steer): serialize concurrent retry claims * fix(socket): tolerate missing steer-state ACK callbacks * fix(native): serialize retry operations * docs(web): document unknown steer delivery and retry controls * fix(steer): handle retry failures and abort-before-connect * fix(cursor): drain foreground prompt after soft-steer abort * fix(steer): reinitialize after transport loss and finish iOS retry errors * fix(steer): preserve indeterminate rows across reconnect gaps * test(web): mock indeterminate queued recovery state * fix(steer): recover consumed ACK tombstones * fix(steer): expose consumed cancel tombstones * fix(cursor): drain soft steers before handler replacement * fix(cursor): preserve buffered output on abort |
||
|
|
1f5602ad6a | Release version 0.29.0 | ||
|
|
f0e5ba9c0f |
feat(codex): mid-turn Steer via app-server turn/steer (#888) (#1606)
* feat(shared): steer capability gates and live steered signal schemas - STEERING_SUPPORTED_FLAVORS / isSteeringSupportedForSession gate which agents can deliver queued messages into the active turn (pi, codex, cursor ACP; legacy stream-json cursor excluded) - AgentState.steeringActive, DecryptedMessage.steered and messages-consumed live signal (never persisted by the hub) * feat(cli): queue reservations and steered messages-consumed option - MessageQueue2 gains takeByLocalId/restoreReservation/ beginReservationDispatch/commitReservation so an async steer can reserve a queued row without racing the main loop's turn/start drain - emitMessagesConsumed accepts steered: true to mark mid-turn delivery * feat(codex): mid-turn steer via app-server turn/steer (#888) - CodexAppServerClient.steerTurn + TurnSteerParams/Response types - CodexRemoteLauncher registers the steer-queued-message RPC handler: reserves the queued row, validates it against the active turn (no control commands, matching mode hash), injects via turn/steer with an epoch guard that invalidates in-flight steers on abort/cleanup - steeringActive agent state tracks the active-turn window - hub syncEngine gate opens to codex; messages-consumed relays steered * feat(web): Steered badge and steer gating for codex sessions - HappyUserMessage shows a ↳ Steered badge fed by the live messages-consumed steered signal, preserved across server echoes and refetches (mergeMessages carries the optimistic marker) - SessionChat gates canSteer via isSteeringSupportedForSession instead of the pi-only check - clearStaleQueuedStatus normalizes a queued status on an invoked message - fix(web): drop duplicate showSessionSummaryInChat in markdown test (upstream typecheck breakage) * fix(codex,shared): address bot findings on steer gate and ambiguous turn/steer - STEERING_SUPPORTED_FLAVORS / isSteeringSupportedForSession advertise codex and pi only; cursor joins when its soft-steer handler lands (#1609) - turn/steer now splits dispatch (stdin accepted) from completion (turn finished): the hub RPC acks once dispatch succeeds — never on the concurrent turn's completion, which can exceed the 30s RPC window - queue row commits only after the turn settles; a rejected/aborted steer restores the row so the message still delivers via turn/start, and a dispatched steer is never restored (no duplicate delivery) - steer carries clientUserMessageId (echoed as userMessage.clientId) so ambiguous transport failures can reconcile the thread later - client tests cover dispatch/complete split and stdin-write failure * fix(codex): reconcile dispatched steers before restoring; align error copy - A dispatched turn/steer whose completion fails (disconnect / protocol error) is now reconciled via thread/read by clientUserMessageId before the queued row is restored — the instruction is only re-delivered by turn/start when the thread never received it - Reconcile targets the pinned steer thread, not whichever turn is current when completion fails - syncEngine unsupported-flavor error now matches the capability gate (Pi and Codex only until the cursor handler lands) - launcher tests cover steer success (ack on dispatch), reconcile-accepted and reconcile-rejected outcomes * fix(codex): consume the row at dispatch; drop background reconcile - The hub RPC acks and the queue row is consumed as soon as stdin accepts turn/steer; completion is background-only logging. A dispatched steer is never restored, so the same localId cannot be re-delivered via turn/start after the caller was told the steer succeeded - Dispatch failure (stdin write error) still restores the row and reports failure - steer.completed rejection is always handled (no unhandled rejection on the dispatch-failure path) - tests updated: completion failure after dispatch keeps the row consumed; dispatch failure restores it * fix(codex): distinguish definite rejection from indeterminate completion - Transport-level failures (timeout, abort, disconnect, spawn, protocol) carry an indeterminate marker; explicit JSON-RPC error responses do not - After a dispatched steer, turn completion resolves → commit + consumed; a definite app-server rejection restores the row (instruction was never accepted, so turn/start cannot duplicate it); an indeterminate outcome leaves the row reserved so it can never be delivered twice - Completion handling registers before awaiting dispatch so the dispatch-failure path cannot leak an unhandled rejection - client/launcher tests cover explicit rejection (restore), indeterminate outcome (row stays reserved) and dispatch failure * fix(codex): reconcile indeterminate steers instead of a permanent reservation - After an indeterminate completion (disconnect/protocol), reconcile the thread by clientUserMessageId immediately: accepted → commit + consumed, provably rejected → restore, still unreadable → keep the reservation and retry from the main-loop top on later passes (post-reconnect) - A row never sits in dispatching forever: the hub cannot stamp it invoked while the instruction may never have been accepted - tests: indeterminate keeps reserved while thread unreadable; accepted reconciliation consumes; rejected path restores * fix(codex): accept all thread item shapes; retry reconcile; ack through abort - Reconcile matcher accepts userMessage/user_message with clientId/ client_id, matching the shapes the thread parser supports — an accepted steer can no longer be misclassified as rejected - A pending reconciliation schedules a wakeLoop retry, so a temporary app-server outage cannot strand the reservation behind waitForTurnOrRecovery - The success-path ACK no longer checks the steer epoch: the hub already reported steered on dispatch, so commit + messages-consumed must reach it even when an abort resets the queue in between * fix(codex): reinit reconnected app-server; keep reconcile retries alive - thread/read after a disconnect auto-connects a fresh app-server, which must be initialized before any request — reconcile now ensures connect + initialize (isConnected getter added to the client) - every still-unknown loop-top reconciliation schedules the next retry, so recovery without external traffic is eventually observed - launcher mock gains isConnected * fix(codex): timer-driven reconciliation; init tracking; abort-safe ACK - Reconciliation runs on a self-rescheduling 1s timer independent of the main loop (wakes it too), so idle loops and waitForTurnOrRecovery still observe app-server recovery; abort clears nothing implicitly — the ACK path commits and consumes even when the reservation was cancelled - Absence of a durable client id is ambiguous: unmatched reads stay 'unknown' and keep retrying instead of restoring the row - CodexAppServerClient tracks initialized state (reset on disconnect/exit) so ensureAppServerInitialized re-initializes a fresh process before thread/read; initialize failures leave the flag false for the next retry - tests: accepted reconciliation via scheduled timer, indeterminate keeps reserved, explicit rejection restores * fix(codex): bind reconciliation to the launcher lifecycle - runSteerReconciliation clears any armed retry timer on entry and never installs a second one, so loop-top and timer-driven passes cannot multiply - shuttingDown is set when the main loop ends: timers are cleared and the pending map is dropped, so an unresolved steer can never respawn an app-server after cleanup (remote-to-local switch included) * fix(codex): report steered only after app-server acceptance - The handler now awaits steer.completed (the inject-acceptance response): an explicit JSON-RPC rejection surfaces as failed and restores the row for the normal turn/start path instead of a false steered - Transport failure after dispatch reports 'Steer outcome is being reconciled' and keeps the row reserved while the timer-driven thread reconciliation runs - dispatch-failure path also swallows the paired completion rejection * fix(steer): tri-state cancel, clear-safe reservations, bounded acceptance wait - MessageQueue2.cancelByLocalId returns 'in-flight' for a dispatching steer reservation: the hub neither deletes the row nor stamps invoked_at (new CancelMessageResponse 'busy' status; web restores the optimistic row); pushIsolateAndClear and reset/close share cancelReservations so /clear-style commands cannot have a rejected steer resurrect a discarded prompt - turn/steer acceptance wait bounded at 25s (< hub 30s RPC timeout): a lost response is indeterminate and funnels into thread reconciliation instead of stranding the reservation - tests updated for the tri-state cancel contract * fix(codex,web): busy-aware edit flow; bound reconciliation reads - QueuedMessagesBar edit flow treats a 'busy' cancel as unsuccessful: it never prefills the composer when the row is inside an async steer, so a second client cannot send a duplicate - reconcileSteerByClientId bounds thread/read with a 5s timeout so a connected-but-silent app-server cannot hold the reservation in-flight indefinitely * fix(steer): inFlight-dominated cancel acks; bounded reconciliation - hub cancel-queued-message acks check inFlight before removed: a stale duplicate socket reporting removed can no longer delete the durable row while another socket is dispatching the steer - reconciliation entries expire after 60s and mark delivered: after the rejection window, a dispatched steer that the app-server never proved (client ids dropped on restart) is committed instead of polling thread/read forever - pre-dispatch failures (abort before write included) never enter reconciliation — they restore the row and report failure * fix(steer): persist indeterminate outcomes without replay * fix(steer): make ambiguous delivery restart-safe * fix(steer): recover crash-held rows and preserve retry dedup * fix(steer): ack retries and bound stdin dispatch * fix(steer): reconcile indeterminate dispatches and serialize retries * fix(codex): classify stdin callback failures as indeterminate * fix(steer): recheck indeterminate cancels after ACK * fix(steer): close retry and abort races * fix(steer): serialize live retries and abort admission * fix(steer): distinguish live dispatching from unknown * fix(steer): keep ACK failures held and reconcile busy cancel * fix(steer): distinguish held cancel from removal * fix(store): combine schema v24 migrations * fix(store): reserve schema v25 for steer delivery state * fix(steer): keep held cancel state and notify requeue * fix(steer): release explicitly cancelled unknown reservations * fix(codex): reject cancelled reservations before native steer * fix(codex): make reservation restore atomic with state * fix(codex): terminate abandoned transport writes * fix(steer): own abandoned app-server lifecycle and consume races * fix(codex): confirm dispatch and recover abandoned turns * test(codex): mock abandoned transport callback * fix(codex): clear visible turn state on transport loss * fix(steer): claim retries and cover native delivery state * fix(native): preserve indeterminate state on Android hydration * fix(steer): make retry claims single-winner * fix(steer): serialize concurrent retry claims * fix(socket): tolerate missing steer-state ACK callbacks * fix(native): serialize retry operations * docs(web): document unknown steer delivery and retry controls * fix(steer): handle retry failures and abort-before-connect * fix(steer): reinitialize after transport loss and finish iOS retry errors * fix(steer): preserve indeterminate rows across reconnect gaps * test(web): mock indeterminate queued recovery state * fix(steer): recover consumed ACK tombstones * fix(steer): expose consumed cancel tombstones |
||
|
|
1ad78f409a | feat(hub): iOS push channel — direct APNs + relay with E2E envelope (P1) | ||
|
|
f110845be6 |
merge: K6 fixtures batch 2 (events, permissions, sidechains, flavors, catalogs)
# Conflicts: # shared/fixtures/README.md # web/scripts/fixtures/generate.ts |
||
|
|
e1bfdd6265 |
feat(fixtures): SSE patch + pagination scenario fixtures (K7)
Two new golden-fixture suites, expectations machine-generated from the web
implementation (same source-of-truth principle as the chat suite):
- shared/fixtures/sse/ (12 cases): session-updated versioned-patch
application via applySessionDetailPatch — strict version gates for
metadata/agentState/todos/teamState, out-of-order arrival, teamState:null
clear, max-monotonic updatedAt, flat last-write-wins fields, sub-minute
activeAt keep-alive drop, scratchlistUpdatedAt trigger, and the pinned
actual behavior that activeTurnStartedAt is NOT applied by the patch path.
Inputs are stored schema-normalized and validated against SessionSchema /
strict SessionPatchSchema at generation time; per-patch applied/unchanged
verdicts are part of the contract.
- shared/fixtures/pagination/ (11 cases): op scripts driving the real
message-window store with a scripted ApiClient — latest page + SSE ingest,
before-cursor older pages, epoch-mismatch reset (window discard + recorded
internal latest request), reset:true replace preserving optimistic rows,
localId echo reconciliation, messages-consumed invokedAt stamping (no
cursor advance), message-cancelled removal, cancel-too-late invoked-row
ingest, hidden-row cursor advance, 400-row trim preserving queued rows,
and queued-state gap recovery. Documents pin the exact requests the store
issued, older-load outcomes, reconcile candidates, and a minimal window
projection (ids/order, queued/optimistic flags, hasMore, epoch, viewMode,
compound cursors).
Generator: web/scripts/fixtures/{sse,pagination}/ extend the K5 framework
(canonical serialization reused; suites pruned of stale files). Web
self-conformance tests replay every fixture against the real implementation
in bun run test:web. README documents schemas, projections, replay
contracts, and native consumption for both suites.
No time injection needed: the store's only Date.now() reads gate
notification throttling, which never reaches persisted or projected state.
|
||
|
|
c1ecb4798e |
feat(fixtures): batch 2 — events, permissions, sidechains, flavors, catalogs (K6)
34 new golden chat fixtures generated from the web pipeline, plus a machine-generated modes catalog: - Claude output: away_summary/microcompact_boundary/compact_boundary system subtypes, <task-notification> summary extraction, multi-block assistant message with an array-of-parts (text+image) tool_result - AgentEvent union completed: switch/message/error/title-changed(+dedupe)/ limit-warning(pipe text)/api-error folding/turn-duration/compact-summary/ abort-restore/unknown-type passthrough; thread-goal updated+cleared (silent) - Permission lifecycle via agentState.completedRequests: approved_for_session (mode+allowTools), denied with reason, canceled, AskUserQuestion flat answers, request_user_input nested answers (all with explicit createdAt) - Sidechain: Task tool_use with parentToolUseId-grouped subagent children - codex family: error, context_compacted, generated-image, review JSON, thread-goal messages, CodexBash call/result pair, exploration tool group - cli-output: cli-origin command block + stdout merge - agy flavor (output envelope): agy_message, agy_tool_action run_command mapping; cursor ACP plan snapshot (copilot skipped: identical codex shapes) - generator now also emits shared/fixtures/catalogs/modes.json from shared/src/modes.ts (per-flavor permission modes with labels/tones); self-conformance test covers it; README documents the catalogs contract |
||
|
|
9479f667b5 | feat(fixtures): golden chat fixtures generated from web pipeline (K4+K5) | ||
|
|
12847ddd0f | Release version 0.28.0 | ||
|
|
a6feb6e8ba |
feat: unified agent configuration descriptors (session config consolidation) (#1469)
* feat(config): add agent config descriptor protocol and advertise via runner capability Introduce shared agent configuration descriptors covering model, effort, permission, and secondary settings per agent flavor, plus the canonical HAPI YOLO -> native permission mode mapping. Runners advertise the builtin descriptors through the runner-state capability so hubs and web can render configuration without hardcoded flavor branches. Migrate the OpenCode create-session model picker from a bespoke radio list to the shared SelectControl combobox. * feat(web): render create-session permission from agent config descriptor Replace the flavor-branched Grok/Codex-family/YOLO permission block with a descriptor-driven PermissionField. Pi now reports permission as managed instead of silently ignoring the YOLO toggle, and YOLO-only flavors show the native permission mode the preference maps to. Removes the superseded GrokPermissionModeSelector and CodexFamilyPermissionModeSelector components. * ci: retry flaky claudeRemote 5s-timeout failure * fix(web): persist explicit OpenCode Default selection instead of restoring a concrete model The parent initialization effect treated every null selected model as 'uninitialized' and auto-picked a concrete advertised model, clobbering the user's explicit Default choice (and a restored Default preference). null now means explicit Default and is preserved; only undefined (no choice made yet) triggers probe-based initialization. Add parent-level regression tests for Default persistence and remembered-model restore. * fix(web): accept undefined selected model in OpencodeModelSelector props * feat(web+cli+hub): unify create-session model/effort fields and add Pi model/effort support Pi's agent config descriptor now advertises model (machine) and effort (static thinking levels) for create AND session availability: - cli: ListPiModelsForMachine RPC runs 'pi --list-models' (cached, inflight deduped) and parses the provider/model table; startup model match accepts provider-qualified ids - hub: GET /api/machines/:id/pi-models route + rpcGateway/syncEngine passthrough - web: NewSession renders Pi models grouped by provider through the generic ModelSelector and a new descriptor-driven EffortField (replaces the per-flavor LaunchEffortSelector/ReasoningEffortSelector pair); launch payload forwards Pi model + thinking-level effort (runner already supported --model/ --effort for pi) * fix(web): render Pi provider groups in ModelSelector and scope Grok availability warning - ModelSelector now renders grouped options as <optgroup> (Pi models are provider-grouped; identical modelIds from different providers stay distinct) - PermissionField only receives autoPermissionModeSupported for Grok — a cached Grok probe result no longer leaks the Grok warning onto other agents Addresses HAPI Bot Minor findings on #1469. * fix(web): drop Object.groupBy from ModelSelector; revalidate restored Pi models against the catalog - ModelSelector buckets options with a reduce instead of Object.groupBy (Safari < 17.4 has no polyfill — New Session would throw on those clients) - Pi restored model/effort are cleared when the value is absent from the live machine catalog, and Create waits for the catalog while a non-default Pi choice is being validated (mirrors Codex/Grok/Copilot handling) Addresses HAPI Bot findings on #1469. * fix(pi+web): serialize startup model before thinking level; hide Pi launch controls during history import - PiSession gains startupModelSettled; the startup set_thinking_level waits for the requested model's set_model attempt to settle first, so a level the default model rejects is not lost before the requested model is confirmed (set_model and set_thinking_level were already serialized by the runtime mutation lock; this pins the model-first ordering) - Create Session hides Pi model/effort controls while a Pi history import is selected — the import reopens the native session as-is and would silently ignore launch-only model/effort values Addresses HAPI Bot findings on #1469. * fix(pi): settle startup-model gate when model discovery fails or returns no models A failed or empty get_available_models response would leave the startupModelSettled gate unresolved, stranding a requested startup effort indefinitely. Resolve the gate on the error path and the empty-models path; adds regression tests for both. |
||
|
|
7909c46fff |
feat(search): support wildcard patterns across search fields (#1571)
* feat(search): add wildcard matching to search fields * fix(search): harden wildcard matching and file globs * fix(search): align file matching with shared wildcard semantics * fix(search): bound file wildcard search in runner * fix(search): normalize outline queries through shared matcher * fix(web): remove duplicate markdown test context field |
||
|
|
5c81ed69e2 |
fix(runner) preserve native instructions (#1557)
* fix(codex): preserve native instructions Keep HAPI guidance in the developer layer so app-server retains Codex persistence rules. Align long-running goal states with the Codex 0.147 protocol. * fix(codex): filter new goal statuses |
||
|
|
901f17d0ca |
feat(pi): support Pi slash commands from HAPI web (compact/session/model/help) (#1570)
* feat(pi): support Pi slash commands from HAPI web (compact/session/model/help)
Pi runs as 'pi --mode rpc' over piped stdio, so TUI slash commands typed in
web chat previously fell through to the LLM as plain text and silently did
nothing (notably /compact).
- shared: add Pi builtin slash command list (help/compact/session/model) so
the web / menu exposes them; web test updated to match
- cli: intercept Pi builtin commands in runPi's user-message path
* /compact [instructions] -> Pi compact RPC (120s timeout, works while
streaming; summary + token delta reported back as chat messages)
* /session -> get_session_stats formatted stats
* /model [modelId] -> list/switch via set_model
* /help -> supported-commands list
* other Pi TUI builtins (/tree, /export, /reload, ...) -> explicit
terminal-only notice instead of silent LLM pass-through
* unknown slash text still passes through (extension commands, skills,
templates keep working)
- gate the prompt pump with piCompactInFlight so queued prompts are not
rejected by Pi mid-compaction; buffer commands until ready like prompts
- ListSlashCommands RPC merges HAPI builtins with Pi extension commands
- tests: parser unit tests + runPi integration tests (compact execution,
streaming steer interception, failure reporting, FIFO blocking, model
switch, unsupported commands, slash list merge)
- docs: document Pi slash command support in docs/guide/agents.md
* fix(pi): address review findings on slash command lifecycle
- compact timeout: fail the session (indeterminate outcome, runtime lease
poisoned) instead of reopening the prompt FIFO into a possibly-compacting
Pi; pump only when cleanup has not been initiated
- special commands: release the cancellation reservation before executing so
a cancel landing mid-command is not acknowledged (hub would delete the
queued row while the command still runs)
- tests: drop the duplicated slash-command describe block; add focused tests
for compaction timeout with a queued prompt and cancellation during an
in-flight special command
* fix(pi): route slash commands through the prompt FIFO and reject ambiguous models
- slash commands now share the prompt FIFO with ordinary messages: a
/compact or /model typed after a queued prompt dispatches only after it
(and after the active turn settles), instead of jumping the queue from
the preparation chain
- the pump dispatches special entries out-of-band while piSpecialCommandInFlight
keeps the FIFO blocked; steer promotion refuses slash commands
- /model <id> prefers an exact provider/modelId match and reports bare IDs
shared by multiple providers as ambiguous instead of picking the first
- tests: FIFO ordering (queued prompt before /compact), steer-delivered
/compact queued until settle, ambiguous/qualified model selection
* fix(pi): keep /compact interruptible, honor extension precedence, require token boundary
- head-of-line /compact dispatches even while Pi is streaming (Pi's
compact() aborts the active generation itself); every other queued item
still waits for the stream to settle, preserving FIFO order
- discovered extension commands / prompt templates override same-name
builtins at message time, matching the slash-list merge precedence
- parsePiSpecialCommand requires a command-token boundary, so path-like
text such as /compact.md or /model/config stays an ordinary prompt
- tests: interrupt rule, extension collision, reserved-name path prefixes,
non-compact commands waiting for stream settle
* fix(pi): honor cancellation acknowledged during slash-command discovery
A cancel arriving while the chain awaits get_commands (cold cache) was
acknowledged via the preparing reservation but never re-checked, so a
canceled /compact could still execute. Re-check the cancellation marker
after discovery and drop the message before dispatch.
* fix(pi): qualify /model selectors and report failed slash RPCs once
- /model lists provider-qualified selectors (openai/gpt-5.2) so duplicate
bare IDs remain usable and copy-pasteable; current model is qualified too
- compact/set_model failures are owned by the awaited slash/config handlers:
the common response handler no longer emits the raw Pi error a second time
- tests: qualified listing with duplicate providers, single-message failure
reporting for rejected /compact and /model
* fix(pi): consume slash-command queue row at dispatch
Special commands (/compact, /session, /model, /help) are executed by HAPI
itself and never delivered to Pi as prompts. Consumption was deferred until
the command finished, so a /compact run — an LLM summarization pass that can
take minutes — left the row stuck in the web queued bar for its whole
duration, then surfaced as a sent message. Consume the row the moment
dispatch starts; failures still surface via the explicit event message.
* fix(pi): guard special-command dispatch against unexpected rejections
* ci: retry Codex PR Review after infra failure (proxy 503)
* fix(pi): keep session queued-thinking grace during /compact dispatch
The queued-thinking grace is session-scoped, so clearing it while
acknowledging a dispatch-time /compact row also drops the grace for any
prompt queued behind it. /compact keeps running for minutes without
toggling Pi thinking state, which would leave the web session looking idle
while compaction and the following prompt are still pending. Only the
fast, synchronous commands (/session, /model, /help) clear the grace.
* fix(pi): render compaction summary as a dedicated chat block
The manual /compact RPC result was reported as two plain message
events ("📦 Compaction completed (tokens: …)" + "📦 Compaction
summary: …"), which the web chat renders as tiny centered status
lines — unusable for a real summary payload. Emit a structured
compact-summary event instead (summary + token delta) and render
it as an independent block: header with the delta and the summary
markdown in a scrollable panel.
Also emit the same structured event when importing Pi session
files (compaction entries), and queue the event lossless like
other user-visible messages so a disconnect cannot drop it.
Verified: bun typecheck clean; bun run test exit 0 (cli 2481
passed, web 2451 passed, hub/shared clean); runPi/loop/apiSession/
piSessions/presentation suites green.
* fix(pi): address HAPI Bot findings on compact dispatch and import
- Track compaction as thinking for its whole duration: /compact runs for
minutes without a Pi streaming event, so the 15s queued-thinking grace
alone left the web session looking idle while compaction and any queued
prompts were still pending (updateThinkingState around the compact RPC).
- Imported Pi compaction summaries must use the event envelope
(content.type: 'event') like the live wrapper's compact RPC result; the
codex payload envelope is dropped by the web normalizer. Extend
CodexImportedMessageSchema with the event variant.
* fix(pi): /model retries discovery when the model cache is empty
Startup model discovery can be late or fail once; using only the cached
catalog made /model report valid models as unknown. getPiModels() falls
back to the get_available_models RPC on an empty cache, used for both
listing and switching.
* fix(pi): interrupt in-flight /compact on Abort; surface startup model rejection
- The Abort action no longer waits on the runtime-mutation lease when a
manual /compact is in flight (compaction can hold it for up to 120s,
blowing the 25s abort deadline and failing closed). It sends the abort
RPC directly so Pi cancels its compaction AbortController; the compact
RPC's 'Compaction cancelled' error is not double-reported as a failure
since Pi already emits the compaction_end(aborted) lifecycle event.
- A rejected detached startup set_model now emits a visible ⚠️ event into
chat instead of only a debug log, restoring the pre-existing behavior.
* fix(pi): close the Abort race when /compact is queued on the mutation lock
Abort previously assumed an in-flight /compact always had its RPC issued;
the command is marked active at queue dispatch, but the compact RPC is sent
only after the runtime-mutation lock is acquired. An Abort landing in that
gap acknowledged success while the compact RPC still ran afterwards.
Track the compact's rpcStarted/cancelled state: Abort cancels a not-yet-
started compact in place (the queued callback skips it), and interrupts a
started one via the abort RPC as before.
* fix(pi): persist provider-qualified selection after /model switch
The success path updated currentModel/currentProvider and keepalive with a
bare model ID, leaving metadata.piSelectedModel on the previous provider.
The web picker prefers that metadata for selection, context-window
resolution, and effort options, so a switch like openai/gpt-5.2 ->
azure/gpt-5.2 was invisible. Persist piSelectedModel with the full
provider/modelId pair on every confirmed switch.
* fix(pi): retire pending extension UI requests when /compact interrupts a turn
The streaming-interrupt path sent the compact RPC without cancelling
pending extension UI requests first, unlike the Abort path. Editor
requests have no timeout, so the web could stay stuck on a stale
input/permission card and a later answer could be routed to the aborted
turn. Cancel all pending requests (with a response) before compacting.
* fix(pi): fail closed when the direct compact-abort RPC times out
The in-flight /compact abort branch awaited the abort RPC without the
ordinary Abort path's timeout handling: an unanswered abort left the
compaction outcome indeterminate (the compact RPC keeps the mutation
lease for up to 120s) while the wrapper still looked live. Fail the
session on PiRpcTimeoutError, mirroring the standard abort fail-closed
path.
---------
Co-authored-by: swear01 <swear01@users.noreply.github.com>
|
||
|
|
ad72229923 |
feat(sessions): add on-demand AI title suggestions (#1577)
* feat(sessions): add on-demand AI title suggestions * fix(sessions): address title suggestion review feedback * fix(web): ignore stale title generation results |
||
|
|
df1a56e1db |
fix(cursor): exclusive agent spawn lease for list-models vs ACP (#1529)
* fix(cursor): exclusive agent spawn lease for list-models vs ACP (#1520) Add a proper-lockfile spawn lease beside agent-acp-active so model probes and ACP transport acquire mutual exclusion atomically before spawning agent children, closing the post-#1518 check-then-act overlap window. Fixes #1520 Co-authored-by: Cursor <cursoragent@cursor.com> * chore(web): fix markdown-a test HappyChatContext mock for typecheck Adds showSessionSummaryInChat to chatContext() so CI typecheck passes on the PR branch (pre-existing main breakage unrelated to #1520). Co-authored-by: Cursor <cursoragent@cursor.com> * Revert "chore(web): fix markdown-a test HappyChatContext mock for typecheck" This reverts commit 4973f321a31fda772e8990ea6cda20517ca906aa. * fix(cursor): scope spawn lease to agent spawn window only (#1520) Hold agent-cli.spawn only around spawn('agent') in AcpStdioTransport, not for the full ACP session. Restores N concurrent cursor sessions per host; list-models probe lease unchanged. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): tighten spawn lease lifecycle for babysit (#1520) Acquire spawn lease before ACP marker publish; unregister on spawn failure. Hold list-models probe lease until child exit on timeout. Add missing showSessionSummaryInChat to markdown-a test mock (unblocks CI typecheck). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): re-check ACP marker after spawn lease acquire (#1520) Close check-then-act window where ACP could publish its marker between the inactive guard read and list-models spawn. Add regression test. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cursor): fix ACP-after-acquire mock call order (#1520) Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): async spawn lease + force-kill probe timeout (#1520) Add acquireAgentCliSpawnLease (setTimeout yields) for ACP create path; AcpStdioTransport.create() async factory. Probe timeout uses killProcessByChildProcess(force) while holding lease until child exit. Addresses Bugbot Majors: session-lifetime mutex (fe07b708d), probe lease release, post-acquire re-check (137baa779), sync loop starvation, timeout escalation. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(acp): coalesce concurrent initialize() transport spawns (#1520) Await shared bootstrapTransport promise so overlapping initialize calls do not spawn duplicate ACP children while create() is in flight. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
fea42212ea | Release version 0.27.3 | ||
|
|
51ae260a3f |
feat(web): settings for AGENT_NOTIFY_SUMMARY chat display (default hide) (#1477)
* feat(web): render AGENT_NOTIFY_SUMMARY as compact metadata * fix(web): defer summary rendering until completion * fix(shared): preserve indentation when splitting summaries * fix(web): guard unknown summary statuses * feat(web): settings for AGENT_NOTIFY_SUMMARY chat display (default hide) Add hub setting sibling to emit (#1376): show compact NotifySummaryText when on; strip footer from chat/copy when off. Store/parse/FCM unchanged. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): address #1477 Majors for display setting Allow any namespace to GET hub-settings (PUT stays owner-only) so sessionSummaryInChat applies hub-wide. Reject whitespace-delimited AGENT_NOTIFY_SUMMARY examples so default-hide does not eat prose. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(shared): allow indented AGENT_NOTIFY_SUMMARY footers Keep rejecting whitespace-delimited prose examples, but accept a standalone footer whose only prefix is leading indentation. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): poll hub display setting; hide empty notify footers Refetch sessionSummaryInChat so open clients pick up owner toggles. When display is on, recognized footers without status/summary/action still strip raw JSON instead of falling back to MarkdownText. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): poll notify display once in chat shell Move hub-settings refetchInterval off per-message hooks into HappyThread context. Strip well-formed footers while streaming when display is off. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web,hub): QueryClient for HappyThread tests; atomic hub-settings Wrap HappyThread mobile-scroll tests in QueryClientProvider after the chat-shell hub-settings poll. Read/write both hub setting flags in one settings.json snapshot under the shared lock. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Ananovo <78636812+techotaku39@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
d396e9d6d4 |
feat(voice): curate dictation credential presets to ElevenLabs, OpenAI, Groq (#1474)
* feat(voice): curate dictation credential presets to ElevenLabs, OpenAI, Groq Groq transcription was already wired end-to-end (GROQ_API_KEY, whisper-large-v3, standard mode), but the credential onboarding panel listed five providers with no hint that Groq is supported, so mobile users could not discover it. - Curate Settings > Voice > Dictation credential presets to ElevenLabs, OpenAI, and Groq (Deepgram / OpenAI-compatible remain fully supported via env and stay listed when configured) - Name the three presets in the empty-state and manage hints (en + zh-CN) - Lock the curated list in with a web preset test, a hub route test for the Groq whisper-large-v3 proxy, and shared provider-listing coverage - Note the presets and no-restart save behavior in voice-assistant.md Verified: bun typecheck (cli+web+hub) and targeted suites pass; full test gate green except pre-existing load-sensitive runner stress tests. * fix(voice): keep legacy dictation providers manageable when configured HAPI Bot review finding (Major): curating the onboard panel to the three presets made settings-managed Deepgram / OpenAI-compatible credentials impossible to rotate or clear from the UI. - Re-add deepgram / openai-compatible to the onboard provider list conditionally when credentials exist, restoring update/clear controls - Fall back to the first preset if the selected provider leaves the list - Cover the conditional list in the preset test * fix(voice): surface partial OpenAI-compatible credentials in onboard panel HAPI Bot follow-up finding (Major): hub marks openaiCompatible.configured only when both base URL and model exist, so api-key-only or endpoint-only stored settings lost the UI path to rotate or clear them. - Gate the openai-compatible onboard entry on any stored field (base URL, model, or API key) via hasOpenAICompatibleCredentials() - Cover api-key-only / base-url-only / model-only cases in tests |
||
|
|
e6b9fd68e6 |
feat(pi): queue mid-turn messages by default; steer only via explicit per-message Steer button (#1480)
* feat(pi): queue mid-turn messages by default; steer only via explicit per-message Steer button Pi (PyAgent) was the only flavor whose ordinary composer submission while streaming bypassed the queue: the web resolved it to deliveryMode 'steer' and the CLI dispatched a native steer into the running turn immediately, with no waiting state. This makes Pi match Codex/Claude behavior (issue #1466): mid-turn messages wait in the queue by default, and the operator delivers one into the running turn with the new per-queued-message Steer button. - web: resolveMessageDeliveryMode now queues for every flavor; QueuedMessagesBar gains a Steer button (pi + thinking + remote-controlled + immediate rows) backed by a new useSteerQueuedMessage hook + api.steerMessage. - hub: POST /sessions/:id/messages/:messageId/steer -> syncEngine.steerQueuedMessage (pi-only gate, remote-only, scheduled/absent/invoked rejection) -> RPC. - cli: pi runner registers 'steer-queued-message'; a queued message is promoted into the active turn via the existing PiSteerDispatcher (target generation captured at promote time; turn-ended steers fall back to the prompt FIFO). Steers requested while the message is still preparing are deferred and promoted right after preparation completes. - Removed the now-dead Alt+Enter / touch-hold queue gesture (its only purpose was opting out of the removed automatic steer). Verified: bun typecheck; cli/hub/web/shared suites (env-dependent runner integration + kimi wire-locator flakes reproduce on pristine upstream and are unrelated to this diff). * fix(pi): preserve queued messages on rejected steers and pin the steering generation Addresses both Major findings from the HAPI Bot review of PR #1480. - steerDispatcher: a deterministic native rejection (Pi responded error) now degrades the message to the ordinary prompt FIFO instead of emitting messages-consumed. A promoted queued message must not be lost just because the steer was rejected; the hub row stays queued until the FIFO delivers it. The indeterminate-timeout path keeps its fail-closed consume + escalate behavior (a duplicate delivery would be worse). - runPi: the deferred-steer path now captures the streaming generation at RPC request time (Map<localId, generation>) instead of reading it after preparation completes, so a steer requested against turn G1 can never be injected into a turn G2 that started while the message was preparing — the dispatcher's generation-mismatch check degrades it to the FIFO. Regression coverage: negative steer response preserves the entry via the FIFO (no consume); generation rollover while preparing delivers as a normal prompt at the next settle (no steer into the new turn). Verified: bun typecheck; cli pi suites (48 tests), hub 1041, web 2301, shared 240 — all green; only the pre-existing environment-dependent runner integration test fails locally (reproduces on pristine upstream). * fix(pi): reject all scheduled steers and always clear deferred-steer bookkeeping Addresses the two Minor findings from the HAPI Bot follow-up review. - hub: steerQueuedMessage rejects every scheduled row — mature ones included — aligning the endpoint with the web UI (Steer is never offered on scheduled rows) and preserving scheduled-FIFO delivery semantics. - cli: the deferred-steer bookkeeping map is now cleared in a finally on the preparation chain, covering the early exits (cancellation before/after attachment I/O, empty prepared message, preparation failure) that previously could leave a stale generation entry behind for the session lifetime. Regression coverage: hub steer gate tests (mature scheduled row stays queued, non-pi flavor rejected) and a runPi test proving cancellation wins over a deferred steer (no steer/prompt/consume after preparation completes). Verified: bun typecheck; hub 1043 pass, cli 2421 pass (only the pre-existing environment-dependent runner integration suite fails locally), web 2301 and shared 240 unchanged since their green runs. * fix(web): reconcile stale queued rows when a steer returns invoked Addresses the remaining Minor finding from the HAPI Bot follow-up review: when the steer endpoint reports the message was already invoked and the messages-consumed SSE was missed while the row was still queued, the hook now marks the row consumed locally (mirroring useCancelQueuedMessage) so the queued bar cannot keep a stale actionable row until the next sync. Regression coverage: steer returning status 'invoked' reconciles the row via markMessagesConsumed and shows no toast. Verified: bun typecheck; web 2302 pass (hub/cli/shared unchanged since their green runs). |
||
|
|
1cd4d1137a |
feat(hub,cli,web): fleet runner version governance (skew, self-upgrade, soft-fail reopen) (#1108)
* fix(hub): govern runner capabilities so Cursor reopen soft-fails on skew Hub↔runner protocol drift was reported as missing Cursor chat data when cursor-chat-store-status was unregistered. Soft-fail reopen on probe errors, advertise required machine capabilities, surface an unmissable upgrade banner, and stop-runner when a newer CLI binary is already on disk. Fixes #1084 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web,hub): make runner skew banner dismissible; gate auto-upgrade Compact the out-of-date banner (minimize + 1h snooze + per-host Restart) so it no longer blocks the session list. Auto stop-runner on skew stays opt-in via HAPI_AUTO_UPGRADE_RUNNERS / autoUpgradeRunners (default off). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): tolerate full sessionStorage on skew banner minimize QuotaExceededError from setItem aborted minimize before React state updated, leaving the banner stuck over the session list. Persist to memory when storage fails; only enable Restart when a newer CLI is already on disk; clarify opt-in is stop-runner only, not package push. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): drop redundant autoUpgradeRunners; runners already self-restart CLI version handoff already reloads the runner when the on-disk binary mtime changes. Hub-driven stop-runner on skew duplicated that. Keep the skew banner and manual Restart only as a stuck/disabled-handoff escape. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli,hub,web): runner-only caps ads; gate Restart on supervisor Address #1108 bot Majors on the thin tip: terminal/lazy bootstraps no longer merge CURRENT_MACHINE_CAPABILITIES into the machine row (only asRunner registration does). Banner Restart refuses unsupervised hosts so stop-runner cannot leave a detached laptop offline; supervised runners advertise supervisedRestart via HAPI_RUNNER_SUPERVISED=1. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub,cli,web): clear sticky runner ads; docs SUPERVISED; i18n skew label Omit-means-clear on runner registration so rollback cannot leave supervisedRestart/capabilities sticky; always advertise boolean supervisedRestart from asRunner. Document HAPI_RUNNER_SUPERVISED=1 and localize MachineSelector UPDATE REQUIRED. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Debian <heavygee@oos-linux.in.lockhouse> Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
ad12eeb5d6 |
feat(a2a): P3 AGENT_NOTIFY_SUMMARY → work-graph status ingest (#1467)
* feat(a2a): P3 AGENT_NOTIFY_SUMMARY → work-graph status ingest Land A0 events/event_links substrate (aligned with #1374 contracts) plus thin P3 ingest so opt-in notify footers become durable work_ad rows. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(a2a): address #1467 cold pass-1 Majors on notify ingest Populate expires_at from message ts+TTL, persist message timestamps on insert, pin append-only ledger survival, and defer project column to P4. * test(hub): cover notify ingest via syncEngine message-received Pins the display-never-gates-capture invariant on the real handleRealtimeEvent wiring path (cold pass-1 minor 12). * fix(a2a): address #1467 Sol cold Majors on notify ingest Support AGY agy_message text extraction, bind audit principal to session id, map stalled→blocked (never self-stale), and cap work-graph POST bodies. * fix(a2a): validate work-graph creates at store insert (Sol S4) Notify ingest built WorkGraphEventCreate and inserted without schema bounds; oversized footer summaries could land past HTTP Zod limits. Validate WorkGraphEventCreateSchema in insertWorkGraphEvent, clamp untrusted notify strings at elevation, and regress 2049-char summaries. * fix(a2a): reject fractional work-graph list limit Bot Minor: limit=1.5 passed Number.isFinite and hit SQLite LIMIT as a non-integer, surfacing as 500. Require Number.isInteger before query. * fix(a2a): keep notify elevation inside payload budget Drop duplicated notify_summary nesting that could exceed the 32 KiB payload_json cap after per-field clamps, and measure the cap in UTF-8 bytes via TextEncoder instead of UTF-16 string.length. * fix(a2a): clamp notify footer fields by UTF-8 bytes Per-field string.length clamps still let CJK footers exceed the UTF-8 payload_json budget and silent-drop elevation. Truncate action/project/ agent/summary (and tags) to the ledger byte caps before insert. * fix(a2a): clamp notify payload fields by JSON-escaped UTF-8 Raw UTF-8 clamps still let backslash-heavy footers expand past the payload_json budget after JSON.stringify. Budget the escaped form so elevation inserts instead of silent-dropping. --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
044d72fdc0 | fix(web): show file metadata in preview header (#1450) | ||
|
|
fe4d51043c |
fix(cli): remap bracketed Cursor wires onto bare/SKU catalogs (#1430)
* fix(cli): remap bracketed Cursor wires onto bare/SKU catalogs #1271 only handled the grok-4.5 legacy alias family. Persisted wires like gpt-5.3-codex[fast=false] still failed agent --model on resume against today's bare ACP catalogs. Remap non-legacy wires to bare bases / CLI SKUs (and nearest configOption wires), and prefer spawn-safe ids in session state. Fixes #1428 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): harden Cursor stale-model remap against silent wrong picks Address Codex Major review on #1430: prefer spawn-safe ids even on exact bracket cache hits, require explicit wire params when ranking configOption candidates, and stop downgrading unavailable CLI SKU variants. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve desired Cursor variant across spawn-safe remap Do not overwrite session.model with the bare/SKU spawn id before ACP apply, and keep spawn-safe requested ids in wireIdForCursorSessionState so apply does not re-poison hub state with bracket wires. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): remap-retry Cursor session/new on stale model reject Initialize and session/load already retried once after Cannot use this model; session/new had the same failure mode with an empty shared cache. Mirror the one-shot remap+respawn path and cover it with a launcher test. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): resolve Cursor apply against ACP option values first Spawn-safe remap prefers bare/SKU ids, but set_config_option may only accept full bracket wires. Resolve against the model option list before falling back to metadata so apply does not pick a rejected bare base. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): fail Cursor launch when remapped spawn cannot restore model When --model was remapped for spawn, restoring the original desired variant via ACP is mandatory. Soft-failing left sessions running on the wrong model. Cover success and hard-fail paths in launcher tests. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
df958ae349 |
fix(shared): parse AGENT_NOTIFY_SUMMARY with glued last-line prose (#1426)
* fix(shared): parse AGENT_NOTIFY_SUMMARY with glued last-line prose Agents sometimes omit the newline before the footer. Accept an optional prefix on the last non-empty line when it still ends with a well-formed AGENT_NOTIFY_SUMMARY JSON payload. Mid-body quotes stay ignored. Fixes #1425 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(shared): prefer first valid AGENT_NOTIFY_SUMMARY JSON match lastIndexOf broke footers whose string values mentioned the token. Scan left-to-right and accept the first occurrence with parseable JSON. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
cde0507bad | fix(codex): harden model discovery fallback | ||
|
|
3da9f7780a |
feat(web): support project and global pinned sessions (#1115)
* feat(web): support persistent pinned sessions * fix(web): preserve project hierarchy for pinned sessions * fix(web): preserve pins during session deduplication * fix(hub): preserve pins when merging sessions * fix(hub): migrate session pins from schema v15 * chore: retrigger PR review * chore: retrigger PR review * chore: retrigger PR review * chore: retrigger PR review * fix: align pinning with schema and sidebar filters * fix(web): expose pinning in session header menu * test(hub): expect schema v17 after pin migration * fix(web): report pin action failures * chore: retrigger PR review * chore: retrigger PR review * chore: retrigger PR review * chore: retrigger PR review * fix: address pinning review regressions * fix(web): scope pin error toast to session rows * test(hub): expect schema v20 after migration * fix(hub): preserve latest source pin during merge * test(hub): expect schema v22 after pin migration * feat(web): add project and global session pin modes Support mutually exclusive project vs global pins, surface both in the session action menu, and render globally pinned sessions in a top-level sidebar group with project path labels. * fix(web): polish pinned section icon and divider alignment * fix(web): tighten pinned section title icon alignment * fix(web): restore original pinned section pin icon shape * fix(web): rename pinned section to pinned sessions * fix(hub): prefer stronger pin mode when merging sessions Keep global pins over project pins during consolidation so a project-pinned source cannot downgrade an already or concurrently global-pinned target. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): keep inactive project-pinned groups expanded Pinned sessions should stay easy to find after reload; do not hide them behind the default inactive-group collapse. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): keep project pins in directory groups --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
e95e111a5c | Release version 0.27.2 | ||
|
|
b7f52f58ca |
feat(media): add audio and file display (#1405)
* feat(cli): cross-flavor inline image display via MCP and ACP Share display_image prompt across MCP-bridge flavors (Cursor, Gemini, Kimi, Codex, Claude, OpenCode), auto-approve the tool in buildHapiMcpBridge, handle ACP image content blocks, and harden generated-image registration with content sniffing. Closes tiann/hapi#956 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): render generated-image cards reliably in chat Keep object URLs stable across refetch, upscale tiny inline images, fetch generated-image bytes with cache no-store (avoid empty 304 bodies), and load hapiMcpUrl from per-session API in hapi-display-image tooling. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(cli+web): display_video MCP for inline mp4/webm (#956) Add display_video alongside display_image, video MIME sniffing with avif guard, web GeneratedImageCard video player, and hapi-display-image auto-routing. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(cli+web): cross-flavor display_video parity with images (#956) Share display_video prompts across MCP-bridge flavors, auto-approve the tool, register mp4/webm via path sniffing, render inline video in web on the existing generated-image RPC path, and restore robust media card fetch. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): ACP image ordering and inline media source provenance Flush buffered assistant text before async generated_image emit from ACP image blocks (PR #958 review Major). Add optional source metadata on generated-image wire messages (ingress, flavor, toolCallId, toolName) for MCP, ACP, and Codex tool-result paths. Seeds artifact-event follow-up #966. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli+web): address PR #958 review Majors on media order and stale blobs Queue ACP session updates and await async image registration before later events; clear GeneratedImageCard blob state when imageId changes. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): await ACP queue after late-drain before turn_complete Straggler session/update during drainLateBuffers can queue async image registration; re-await sessionUpdateQueue so generated_image is not emitted after turn_complete. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(scripts): route AVIF ftyp brands to display_image in helper Match server-side detectImageMimeType so .avif files are not sent to display_video and rejected as unsupported video. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(#956): agent inline-media doctor and discovery fixes - hapi doctor inline-media: probe bridges, print per-session inline commands - Expose hapiMcpUrl on session list summaries (stops false "no MCP" scans) - Helper script: match cursorSessionId prefixes; HAPI_SESSION_ID path-only mode - ACP bridge prompt: shell fallback + HAPI session id vs agent id rule Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): allow immutable cache for generated media blobs Drop cache: no-store on generated-image fetch so browser can reuse hub immutable responses; on 304 re-read via force-cache (#927, PR review). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#956): Cursor native MCP overlay; drop user-turn bridge prepend Cursor ACP ignores session/new mcpServers. Write .cursor/mcp.json and run agent mcp enable hapi instead. Remove HAPI_MCP_BRIDGE_PROMPT from user turns on ACP remotes; enrich MCP tool descriptions for discovery. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve non-HAPI mcp.json keys on Cursor overlay cleanup Cleanup only removes or restores the hapi MCP entry instead of rewriting the full pre-session snapshot, so concurrent edits to other servers survive. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): handle generated_image in Grok ACP launcher switch Upstream Grok launcher exhaustiveness broke after AgentMessage gained generated_image for cross-flavor inline media. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): rebase fallout for display_video + OpenCode skill lookup Gate display_video in the STDIO bridge, restore OpenCode first-prompt TITLE_INSTRUCTION (skill_lookup), and update tool-list test expectations. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): leave user-owned hapi MCP entry alone on overlay cleanup Only undo mcpServers.hapi when it still matches the exact entry this session installed; concurrent Cursor/user edits of that key survive. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): exact-match auto-approve for display_image and display_video Move media tools off substring name/id hints onto the exact-name set so forged lookalike tools are not approved in default permission mode. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): drop dead Cursor bridge prompt; put guidance in MCP descriptions Cursor must not get a user-turn media prepend (prompt-taint). Remove unused HAPI_MCP_BRIDGE_PROMPT_CURSOR and embed DISPLAY_*_PROMPT_CURSOR in the display_image/display_video MCP tool descriptions instead. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): require user approval for display_image and display_video Those tools read arbitrary local paths into chat; keep them on MCP approval_mode prompt and out of default-mode auto-approve exact names. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: re-trigger Codex PR review after provider 503 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): ignore URI-only ACP image blocks that read local disk Passive ACP agentMessageChunk handling must not load file:// or bare paths; local media goes through prompt-gated display_image/display_video. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): allowlist MP4 ftyp brands for video sniffing Reject HEIC/HEIF and other non-video ISO-BMFF containers instead of treating every non-AVIF ftyp as video/mp4. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): keep Cursor ACP startup if MCP overlay fails Wrap installCursorMcpOverlay so a malformed project .cursor/mcp.json cannot abort the session; continue without inline media tools. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): fail doctor inline-media when checks fail Exit non-zero whenever required checks fail, even if an active hapiMcpUrl bridge is present. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): expect display_video when change_title is disabled Native ACP title mode still exposes display_image and display_video; update startHappyServer test after rebase onto 0.23.4. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): keep ACP title sync synchronous outside media queue session_info_update title forwarding (#1028) must not wait on the async message-handler queue used for inline media ordering. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): sniff media headers only; advertise OpenCode display_video Read 16 bytes for detectMediaTool instead of the whole file, and include hapi_display_video in OPENCODE_NATIVE_TOOL_INSTRUCTION for remote ACP. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): show Cursor generate_image inline in HAPI chat cursor/generate_image only emitted a tool card; register filePath or base64 imageData into generatedImages and emit generated_image so the web chat card renders (issue #956 / swear01 report). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): ignore path-only Cursor generate_image reads Path-only filePath registration bypassed permission-gated display_image / display_video MCP tools. Keep base64 imageData only; local paths must go through MCP approval. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): gate inline media base64 length before decode Reject oversized ACP/Cursor base64 payloads by character count so the CLI never allocates past the 25 MB generated-image cap. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): require EBML DocType webm for inline video sniff Bare EBML magic matches Matroska/MKV too; only accept DocType webm. Also restore annotated Playwright cursor in annotatedVideoUseOption. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(scripts): read 128-byte header for WebM DocType sniff detectMediaTool only loaded 16 bytes, so EBML DocType webm was often missing and valid WebM files fell through to display_image. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): compare generated-image source by value in reconcile Wire normalization allocates a fresh source object each pass; reference equality forced media-card recomputation on every reload/SSE refresh. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): inject Cursor MCP enable for overlay unit tests installCursorMcpOverlay always spawned `agent mcp enable`; tests now pass a noop so the suite never shells out to a real Cursor binary. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): shell-quote doctor inline-media helper command Paths and session prefixes with spaces/metacharacters broke the copied snippet; JSON.stringify each interpolated argument. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): fix doctor inline-media quote path expectation Repo root from scriptPath is three levels up (cli/), not the parent of cli. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli/web): per-session Cursor MCP overlay id and bound tiny-image scale Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): redact generate_image base64 from logs and fix doctor MCP ids Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): harden inline-media doctor for packaged installs and hub headers Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): lock Cursor mcp.json updates and bound ACP media filenames Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve mcp.json mode and token-scoped overlay locks Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): publish Cursor MCP lock owners via link(2) and treat EPERM as alive Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): fail closed on stale MCP locks; keep concurrent mcp.json top-level keys Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): roll back Cursor MCP overlay when agent mcp enable fails Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): await ACP session queue in suppressUpdatesDuring tests #958 queues handleUpdate for media registration; upstream compact tests assumed sync delivery after restore. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): capture ACP handler at enqueue; keep display_video manual Close two Major review findings on #958: suppress queue leak after restore, and Claude --allowedTools auto-approving local-path video. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: write through symlinked mcp.json; lazy-load inline video Preserve user Cursor MCP symlinks on atomic overlay writes, and require explicit Load video before fetching large generated-video blobs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): use valid TerminalToolDisplayMode in media card test Co-authored-by: Cursor <cursoragent@cursor.com> * fix(scripts): require unique session prefix in display helper Reject ambiguous prefix matches so images/videos cannot land in the wrong HAPI chat when multiple agent session ids share a prefix. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): always cleanup Cursor MCP overlay on teardown Run overlay cleanup in finally so cancelAll/disconnect failures cannot leave a dead hapi-<sessionId> entry in .cursor/mcp.json. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): handle Copilot generated_image; refuse MCP symlinks Unblock typecheck after Antigravity/Copilot merge, and fail closed when .cursor/mcp.json or .cursor is a project-controlled symlink. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: abort restore deliveryMode; prune dead Cursor MCP overlays Unblock web typecheck after steer merge, and recover orphaned hapi-* mcp.json entries via HAPI_MCP_OVERLAY_PID ownership stamps. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): recover dead-PID Cursor MCP overlay locks Token-matched unlock so a crash mid-lock no longer permanently disables inline media; keep live-owner waits identity-safe. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): serialize Cursor MCP stale-lock recovery Acquire an exclusive recovery lock before token-matched unlink so two recoverers cannot remove a successor's live mcp.json lock. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): fail closed on stale Cursor MCP overlay locks Withdraw racy auto-recovery: pathname check-then-unlink/rename can steal a successor lock. Stale locks throw with an explicit rm hint instead. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): drop duplicate deliveryMode on abort restore Merge left both steer and queue; keep queue so retries after abort do not re-bind to a later Pi turn. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): bound inline media reads on open fd Close TOCTOU between pathname size check and readFile for display_image / display_video and registerGeneratedImageFromPath. Also preserve non-PID env edits on Cursor MCP overlay cleanup. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): repair happyMcpStdioBridge test syntax after merge Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): write Cursor MCP overlay to ~/.cursor, not the project Keep ephemeral hapi-<sessionId> bridges out of the checked-out tree so agents cannot git-add a live loopback URL. Tests inject mcpConfigDir. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): point Cursor MCP diagnostics at ~/.cursor/mcp.json Co-authored-by: Cursor <cursoragent@cursor.com> * feat(media): add audio and file display --------- Co-authored-by: HeavyGee <133152184+heavygee@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Debian <heavygee@oos-linux.in.lockhouse> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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 |
||
|
|
828e984508 | Release version 0.27.1 | ||
|
|
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> |
||
|
|
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. |
||
|
|
0a037c9812 | Release version 0.27.0 | ||
|
|
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 |
||
|
|
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> |
||
|
|
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 |
||
|
|
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 |
||
|
|
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. |
||
|
|
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> |
||
|
|
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> |