mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
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:
@@ -508,6 +508,7 @@ describe('ApiClient auth proxy redirect', () => {
|
||||
run: (api) => api.getGeneratedImageBlob('session-1', 'image-1')
|
||||
},
|
||||
{ name: 'migrateCursorSessionToAcp', run: (api) => api.migrateCursorSessionToAcp('session-1') },
|
||||
{ name: 'bridgeModelError', run: (api) => api.bridgeModelError('session-1', 'evt-1') },
|
||||
{
|
||||
name: 'fetchScratchlistAttachmentBlob',
|
||||
run: (api) => api.fetchScratchlistAttachmentBlob('session-1', 'attachment-1')
|
||||
@@ -533,4 +534,39 @@ describe('ApiClient auth proxy redirect', () => {
|
||||
await expect(api.getGeneratedImageBlob('session-1', 'image-1')).rejects.toBeInstanceOf(AuthProxyRedirectError)
|
||||
expect(fetchMock.mock.calls[1][1]).toMatchObject({ cache: 'force-cache', redirect: 'manual' })
|
||||
})
|
||||
|
||||
// An auth gateway can answer a POST with an HTML sign-in page at status
|
||||
// 200. Treating that as a successful enqueue latches the banner into
|
||||
// "Bridging…" forever while no CLI request was ever made.
|
||||
it('bridgeModelError rejects a 200 HTML response instead of reporting ok', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response('<!doctype html><title>Sign in</title>', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/html' }
|
||||
})
|
||||
)
|
||||
|
||||
const api = new ApiClient('test-token', { baseUrl: 'https://hub.example' })
|
||||
await expect(api.bridgeModelError('session-1', 'evt-1')).rejects.toBeInstanceOf(ApiError)
|
||||
})
|
||||
|
||||
it('bridgeModelError returns the hub refusal outcome on 409', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ ok: false, reason: 'not_bridgeable' }), { status: 409 })
|
||||
)
|
||||
|
||||
const api = new ApiClient('test-token', { baseUrl: 'https://hub.example' })
|
||||
await expect(api.bridgeModelError('session-1', 'evt-1'))
|
||||
.resolves.toEqual({ ok: false, reason: 'not_bridgeable' })
|
||||
})
|
||||
|
||||
it('bridgeModelError reports success only for the hub ok envelope', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ ok: true }), { status: 200 })
|
||||
)
|
||||
|
||||
const api = new ApiClient('test-token', { baseUrl: 'https://hub.example' })
|
||||
await expect(api.bridgeModelError('session-1', 'evt-1'))
|
||||
.resolves.toEqual({ ok: true, reason: undefined })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -790,6 +790,86 @@ export class ApiClient {
|
||||
})
|
||||
}
|
||||
|
||||
async acknowledgeModelError(sessionId: string, eventId: string): Promise<void> {
|
||||
await this.request(`/api/sessions/${encodeURIComponent(sessionId)}/model-error/acknowledge`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ eventId })
|
||||
})
|
||||
}
|
||||
|
||||
async bridgeModelError(sessionId: string, eventId: string): Promise<{ ok: boolean; reason?: string }> {
|
||||
const path = `/api/sessions/${encodeURIComponent(sessionId)}/model-error/bridge`
|
||||
const tryOnce = async (overrideToken: string | null): Promise<Response> => {
|
||||
const headers = new Headers({ 'content-type': 'application/json' })
|
||||
const liveToken = this.getToken ? this.getToken() : null
|
||||
const authToken = overrideToken ?? liveToken ?? this.token
|
||||
if (authToken) {
|
||||
headers.set('authorization', `Bearer ${authToken}`)
|
||||
}
|
||||
return fetchThroughAuthProxy(this.buildUrl(path), {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ eventId })
|
||||
})
|
||||
}
|
||||
|
||||
let res = await tryOnce(null)
|
||||
if (res.status === 401 && this.onUnauthorized) {
|
||||
const refreshed = await this.onUnauthorized()
|
||||
if (refreshed) {
|
||||
this.token = refreshed
|
||||
res = await tryOnce(refreshed)
|
||||
}
|
||||
}
|
||||
if (res.status === 401) {
|
||||
throw new Error('Session expired. Please sign in again.')
|
||||
}
|
||||
|
||||
const text = await res.text()
|
||||
let body: { ok?: boolean; reason?: string; error?: string } | null = null
|
||||
try {
|
||||
body = text ? JSON.parse(text) as { ok?: boolean; reason?: string; error?: string } : null
|
||||
} catch {
|
||||
body = null
|
||||
}
|
||||
|
||||
if (res.status === 409 && body && typeof body.ok === 'boolean') {
|
||||
return { ok: body.ok, reason: body.reason }
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const detail = body?.error ?? text
|
||||
throw new ApiError(
|
||||
`HTTP ${res.status} ${res.statusText}: ${detail}`,
|
||||
res.status,
|
||||
undefined,
|
||||
detail || undefined
|
||||
)
|
||||
}
|
||||
|
||||
// A 2xx that is not the hub's `{ ok }` envelope never reached the hub:
|
||||
// an auth gateway can answer with an HTML sign-in page at status 200.
|
||||
// Reporting ok:true there makes SessionChat latch the event as pending,
|
||||
// leaving "Bridging…" disabled forever while no CLI request was made.
|
||||
if (!body || typeof body.ok !== 'boolean') {
|
||||
throw new ApiError(
|
||||
`HTTP ${res.status} ${res.statusText}: unexpected bridge response`,
|
||||
res.status,
|
||||
undefined,
|
||||
text || undefined
|
||||
)
|
||||
}
|
||||
|
||||
return { ok: body.ok, reason: body.reason }
|
||||
}
|
||||
|
||||
async setModelErrorAutoBridge(sessionId: string, enabled: boolean): Promise<void> {
|
||||
await this.request(`/api/sessions/${encodeURIComponent(sessionId)}/model-error/auto-bridge-setting`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ enabled })
|
||||
})
|
||||
}
|
||||
|
||||
async reopenSession(sessionId: string): Promise<ReopenSessionResponse> {
|
||||
return await this.request<ReopenSessionResponse>(
|
||||
`/api/sessions/${encodeURIComponent(sessionId)}/reopen`,
|
||||
|
||||
Reference in New Issue
Block a user