feat(cursor): detect inline model errors, surface, notify, and bridge (#878) (#987)

Cursor ACP sessions can fail mid-turn with a transient model error that the
agent reports inline rather than as an RPC rejection. HAPI treated those turns
as successful, so the session went quiet with no banner, no push, and no way to
resume without retyping the prompt.

This adds the full path:

- detect: classify inline/stderr model errors from the Cursor ACP stream,
  requiring strong signatures before typing a failure as a model error
- surface: persist `lastModelError` on session metadata; render a chat banner
  and a session-list indicator, with the prompt text kept out of list/SSE
  summaries so they never ship up to 32 KB of user prompt
- notify: deliver a push for an unacknowledged error, watermarked on the hub
  copy so a restart does not re-page the same eventId
- bridge & retry: offer a one-shot recovery prompt that replays the failed
  turn, bound to the originating eventId and gated so a real user turn always
  supersedes it. Auto-bridge is opt-in and defaults to OFF, persisted in hub
  settings and fanned out to live Cursor CLIs.

Re-cut onto current upstream/main. The branch had accumulated 108 iterative
hardening commits against a 289-commit-older base; replaying them individually
would have re-resolved the same conflicts ~100 times. The pre-re-cut tip was
2c28a1365 if the granular history is ever needed.

Absorbing upstream required adapting to three refactors that landed meanwhile:

- `MessageQueue2` grew an `internal?: boolean` control-message flag upstream
  while this branch added richer `internal` provenance. Unified on a tagged
  `QueueItemInternal` union (`control` | `model-error-bridge`) so one field
  carries one concept. `hasPendingNonBridgeTurn()` now treats *any* internal
  item as non-user: otherwise a queued `/auto-review` control slash would have
  counted as a user turn and wrongly superseded a live bridge.
- `AcpSdkBackend.prompt()` gained a `timing` callback upstream; merged it with
  this branch's `shouldSend` gate into a single options object.
- The hub settings route moved to a unified `updateSettings` transaction.
  `autoBridgeTransientModelErrors` is applied outside that transaction because
  SyncEngine owns its CLI fan-out and rollback under its own lock.

via [HAPI](https://hapi.run)

Co-authored-by: HAPI <noreply@hapi.run>
This commit is contained in:
HeavyGee
2026-11-13 18:50:09 +08:00
committed by GitHub
co-authored by HAPI
parent a7e472bb39
commit f0ab4ba79d
87 changed files with 9410 additions and 257 deletions
+56 -7
View File
@@ -1,5 +1,15 @@
import { logger } from "@/ui/logger";
/**
* Queue-owned provenance for items HAPI enqueued itself, rather than a
* user-authored turn. Tagged so each internal producer stays distinguishable:
* `control` is a plain control message (e.g. the Cursor Auto-review toggle
* slash); `model-error-bridge` carries the event it is recovering.
*/
export type QueueItemInternal =
| { kind: 'model-error-bridge'; eventId: string }
| { kind: 'control' };
export interface QueueItem<T> {
message: string;
mode: T;
@@ -9,14 +19,14 @@ export interface QueueItem<T> {
/** Stable FIFO key used when an async reservation is restored later. */
enqueueOrder?: number;
/**
* True when HAPI enqueued this item as an internal control message
* (e.g. Cursor Auto-review toggle slash), not a user-authored turn.
* Set when HAPI enqueued this item itself, not a user-authored turn.
* Queue-owned provenance — never inferred from caller localId.
*/
internal?: boolean;
internal?: QueueItemInternal;
}
export type QueueItemOptions = {
internal?: boolean;
internal?: QueueItemInternal;
};
export type QueueReservation<T> = {
@@ -30,6 +40,12 @@ export type QueueReservation<T> = {
state: 'reserved' | 'dispatching' | 'indeterminate' | 'cancelled';
};
export type CollectedQueueItem = {
message: string
localId?: string
internal?: QueueItemInternal
};
/**
* A mode-aware message queue that stores messages with their modes.
* Returns consistent batches of messages with the same mode.
@@ -306,6 +322,39 @@ export class MessageQueue2<T> {
logger.debug(`[MessageQueue2] unshiftIsolated() completed. Queue size: ${this.queue.length}`);
}
/**
* True when a user/API turn is already waiting (queued or reserved).
* Only items with no `internal` provenance count: every internal kind —
* the bridge itself and HAPI-enqueued control slashes alike — is ours,
* not a newer user instruction that should supersede a bridge.
*/
hasPendingNonBridgeTurn(): boolean {
if (this.queue.some((item) => item.internal === undefined)) {
return true;
}
// Soft-steer takeByLocalId removes the row from queue before
// turnHasSteeredInput / softSteerWaiters are set — Bridge guards must
// still see that newer instruction while the reservation is live.
for (const { item, state } of this.reservations.values()) {
if (state === 'cancelled') continue;
if (item.internal !== undefined) continue;
return true;
}
return false;
}
/** Drop a pending model-error bridge by its eventId (queue-owned provenance). */
cancelModelErrorBridge(eventId: string): boolean {
if (!eventId) return false;
const idx = this.queue.findIndex(
(item) => item.internal?.kind === 'model-error-bridge'
&& item.internal.eventId === eventId
);
if (idx === -1) return false;
this.queue.splice(idx, 1);
return true;
}
/**
* Remove the first queued message that matches the given localId.
* Returns true if a message was removed, false if not found.
@@ -598,7 +647,7 @@ export class MessageQueue2<T> {
* Wait for messages and return all messages with the same mode as a single string
* Returns { message: string, mode: T } or null if aborted/closed
*/
async waitForMessagesAndGetAsString(abortSignal?: AbortSignal): Promise<{ message: string, mode: T, isolate: boolean, hash: string, items: Array<{ message: string, localId?: string, internal?: boolean }> } | null> {
async waitForMessagesAndGetAsString(abortSignal?: AbortSignal): Promise<{ message: string, mode: T, isolate: boolean, hash: string, items: CollectedQueueItem[] } | null> {
// If we have messages, return them immediately
if (this.queue.length > 0) {
return this.collectBatch();
@@ -622,7 +671,7 @@ export class MessageQueue2<T> {
/**
* Collect a batch of messages with the same mode, respecting isolation requirements
*/
private collectBatch(): { message: string, mode: T, hash: string, isolate: boolean, items: Array<{ message: string, localId?: string, internal?: boolean }> } | null {
private collectBatch(): { message: string, mode: T, hash: string, isolate: boolean, items: CollectedQueueItem[] } | null {
if (this.queue.length === 0) {
return null;
}
@@ -636,7 +685,7 @@ export class MessageQueue2<T> {
// `message` string below so callers that need to requeue individual
// messages (e.g. restoring a failed batch with each item's own
// localId intact) don't have to re-split an already-joined string.
const items: Array<{ message: string, localId?: string, internal?: boolean }> = [];
const items: CollectedQueueItem[] = [];
let mode = firstItem.mode;
let isolate = firstItem.isolate ?? false;
const targetModeHash = firstItem.modeHash;