From 8ae7f0aa7b850c74d2e617409ca9c864f24309ed Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Wed, 28 Oct 2026 04:09:00 +0000 Subject: [PATCH] fix(cursor): in-place relaunch when switching live session to Auto (#1909) * fix(cursor): in-place relaunch when switching live session to Auto When ACP does not advertise literal auto, switch to Auto by respawning the same hub session under --model auto + session/load instead of rejecting. Keeps #1819 CLI Auto pin semantics. Fixes #1908. Co-authored-by: Cursor * fix(cursor): widen in-place relaunch spawn model typing Allow null/undefined rollback spawn models from resolveCursorSpawnModel. Co-authored-by: Cursor * fix(cursor): re-pin ACP session id after in-place relaunch load If session/load returns a different agent id, update hub metadata the same way as a fresh session so resume stays recoverable. Co-authored-by: Cursor * fix(cursor): coordinate message loop with in-place Auto relaunch Await relaunch completion before prompting, re-read the live backend after model apply, and publish this.backend only after session/load. Addresses tip bot Majors on #1909. Co-authored-by: Cursor * fix(cursor): harden Auto relaunch against prompt races and cleanup Hold promptInFlight before mode apply, end the loop if backend restore fails instead of requeue-spinning, and discard late replacement backends when session teardown has started. Addresses tip bot Majors on #1909. Co-authored-by: Cursor * fix(cursor): avoid continue-in-try circular typing; finish relaunch harden Refactor mismatch requeue off continue-inside-try so typecheck passes, keeping promptInFlight hold and teardown discard for #1909 tip bot Majors. Co-authored-by: Cursor * fix(cursor): preserve queued turns and Auto-review across relaunch failure Requeue dequeued batches before ending when restore fails, and still record Auto-review (slash after publish) when mode flips while backend is null mid-relaunch. Addresses tip bot Majors on #1909 @ 9e5f241f1. Co-authored-by: Cursor * fix(cursor): defer hub ack until Auto relaunch has a live backend Avoid acknowledging queued turns before a usable ACP process exists, and reset Auto-review slash bookkeeping on in-place process replacement. Co-authored-by: Cursor * fix(cursor): recompute Auto-review spawn flag for replacement ACP Slash bookkeeping after in-place relaunch must use the replacement process's --auto-review arg, not the prior process's sticky flag. Co-authored-by: Cursor * fix(cursor): drop queued Auto-review slash when replacement has --auto-review Cursor treats /auto-review as a toggle; leave no leftover slash for a spawn that already enabled Auto-review via the CLI flag. Co-authored-by: Cursor * fix(cursor): discard held Auto-review toggle after --auto-review relaunch Mark internal toggles so queue reconcile and post-relaunch dispatch drop only HAPI-generated /auto-review slashes, preserving user-sent commands. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- .../cursor/cursorAcpRemoteLauncher.test.ts | 732 +++++++++++++++++- cli/src/cursor/cursorAcpRemoteLauncher.ts | 472 +++++++++-- cli/src/utils/MessageQueue2.ts | 56 +- web/README.md | 2 +- web/src/components/SessionChat.tsx | 6 +- web/src/lib/locales/en.ts | 1 - web/src/lib/locales/zh-CN.ts | 1 - web/src/lib/sessionChatCursorModel.test.ts | 15 +- 8 files changed, 1164 insertions(+), 121 deletions(-) diff --git a/cli/src/cursor/cursorAcpRemoteLauncher.test.ts b/cli/src/cursor/cursorAcpRemoteLauncher.test.ts index bc283a72..6fc23bb0 100644 --- a/cli/src/cursor/cursorAcpRemoteLauncher.test.ts +++ b/cli/src/cursor/cursorAcpRemoteLauncher.test.ts @@ -44,7 +44,15 @@ const harness = vi.hoisted(() => ({ stderrErrorHandler: null as ((error: { type: string; message: string; raw?: string }) => void) | null, disconnectError: null as Error | null, overlayCleanup: null as ReturnType | null, - agentActivityListener: null as ((thinking: boolean) => void) | null + agentActivityListener: null as ((thinking: boolean) => void) | null, + /** When set, the next backend.initialize() rejects once, then clears. */ + failNextInitialize: null as Error | null, + /** When > 0, the next N backend.initialize() calls reject. */ + failInitializeTimes: 0, + /** When set, the next backend.initialize() awaits this before completing. */ + deferNextInitialize: null as Promise | null, + /** Spawn flags passed to createCursorAcpBackend (newest last). */ + spawnAutoReviewFlags: [] as boolean[] })); const legacyLauncher = vi.hoisted(() => vi.fn()); @@ -55,7 +63,7 @@ vi.mock('./cursorLegacyRemoteLauncher', () => ({ vi.mock('./utils/cursorAcpBackend', () => ({ CURSOR_ACP_REQUIRED_MESSAGE: 'Cursor ACP mode is required for new Cursor remote sessions.', - createCursorAcpBackend: vi.fn((opts?: { model?: string | null }) => { + createCursorAcpBackend: vi.fn((opts?: { model?: string | null; autoReview?: boolean }) => { const args = ['acp']; const model = opts?.model?.trim(); const spawn = !model @@ -64,10 +72,28 @@ vi.mock('./utils/cursorAcpBackend', () => ({ if (spawn) { args.unshift('--model', spawn); } + if (opts?.autoReview) { + args.unshift('--auto-review'); + } + harness.spawnAutoReviewFlags.push(Boolean(opts?.autoReview)); harness.backendArgs = { command: 'agent', args }; return { initialize: vi.fn(async () => { harness.initializeAttempts += 1; + if (harness.failNextInitialize) { + const error = harness.failNextInitialize; + harness.failNextInitialize = null; + throw error; + } + if (harness.failInitializeTimes > 0) { + harness.failInitializeTimes -= 1; + throw new Error('initialize failed'); + } + if (harness.deferNextInitialize) { + const deferred = harness.deferNextInitialize; + harness.deferNextInitialize = null; + await deferred; + } if (harness.initializeError && harness.initializeAttempts === 1) { harness.stderrErrorHandler?.({ type: 'model_not_found', @@ -333,6 +359,10 @@ describe('cursorAcpRemoteLauncher', () => { harness.disconnectError = null; harness.overlayCleanup = null; harness.agentActivityListener = null; + harness.failNextInitialize = null; + harness.failInitializeTimes = 0; + harness.deferNextInitialize = null; + harness.spawnAutoReviewFlags = []; legacyLauncher.mockClear(); process.stdin.isTTY = false; process.stdout.isTTY = false; @@ -1566,7 +1596,7 @@ describe('cursorAcpRemoteLauncher', () => { await runPromise; }); - it('does not claim live Auto when ACP has no auto option', async () => { + it('relaunches via setModel Auto when ACP has no auto option', async () => { const queue = new MessageQueue2((mode) => mode.permissionMode); const client = { rpcHandlerManager: { registerHandler: vi.fn() }, @@ -1575,7 +1605,7 @@ describe('cursorAcpRemoteLauncher', () => { sendSessionEvent: vi.fn(), sendAgentMessage: vi.fn(), keepAlive: vi.fn(), - emitSessionReady: vi.fn() + emitSessionReady: vi.fn() } as unknown as ApiSessionClient; const session = new CursorSession({ @@ -1591,7 +1621,9 @@ describe('cursorAcpRemoteLauncher', () => { startingMode: 'remote', permissionMode: 'default' }); - session.onSessionFoundWithProtocol = vi.fn(); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); queue.push('hold-open', { permissionMode: 'default' }); const runPromise = cursorAcpRemoteLauncher(session); @@ -1608,13 +1640,14 @@ describe('cursorAcpRemoteLauncher', () => { }); harness.setConfigOptionCalls.length = 0; + harness.loadSessionCalled = false; session.setModel('auto'); await vi.waitFor(() => { - expect(session.model).toBe('composer-2.5[fast=false]'); + expect(session.model).toBe('auto'); }); - await new Promise((resolve) => setTimeout(resolve, 30)); - expect(session.model).toBe('composer-2.5[fast=false]'); + expect(harness.backendArgs).toEqual({ command: 'agent', args: ['--model', 'auto', 'acp'] }); + expect(harness.loadSessionCalled).toBe(true); expect(harness.setConfigOptionCalls.filter((call) => call.configId === 'model-opt')).toEqual([]); queue.close(); @@ -1665,7 +1698,7 @@ describe('cursorAcpRemoteLauncher', () => { await runPromise; }); - it('rejects live applyModelConfig Auto when ACP has no auto option', async () => { + it('relaunches in place with --model auto when ACP has no auto option', async () => { const queue = new MessageQueue2((mode) => mode.permissionMode); const client = { rpcHandlerManager: { registerHandler: vi.fn() }, @@ -1690,7 +1723,9 @@ describe('cursorAcpRemoteLauncher', () => { startingMode: 'remote', permissionMode: 'default' }); - session.onSessionFoundWithProtocol = vi.fn(); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); queue.push('hold-open', { permissionMode: 'default' }); const runPromise = cursorAcpRemoteLauncher(session); @@ -1699,13 +1734,639 @@ describe('cursorAcpRemoteLauncher', () => { await session.applyModelConfig('composer-2.5[fast=false]'); harness.setConfigOptionCalls.length = 0; + harness.loadSessionCalled = false; + const createCallsBefore = vi.mocked(createCursorAcpBackend).mock.calls.length; - await expect(session.applyModelConfig('auto')).rejects.toThrow( - 'Cursor Auto requires restarting with --model auto' + await session.applyModelConfig('auto'); + + expect(session.model).toBe('auto'); + expect(harness.backendArgs).toEqual({ command: 'agent', args: ['--model', 'auto', 'acp'] }); + expect(harness.loadSessionCalled).toBe(true); + expect(vi.mocked(createCursorAcpBackend).mock.calls.length).toBeGreaterThan(createCallsBefore); + expect(harness.setConfigOptionCalls.filter((call) => call.configId === 'model-opt')).toEqual([]); + + queue.close(); + await runPromise; + }); + + it('restores the prior ACP spawn when Auto relaunch initialize fails', async () => { + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + + await session.applyModelConfig('composer-2.5[fast=false]'); + expect(session.model).toBe('composer-2.5[fast=false]'); + + harness.failNextInitialize = new Error('auto spawn refused'); + await expect(session.applyModelConfig('auto')).rejects.toThrow(/relaunch with --model auto failed/i); + expect(session.model).toBe('composer-2.5[fast=false]'); + + // Prior spawn restored — concrete model apply still works. + await session.applyModelConfig('composer-2.5[fast=true]'); + expect(session.model).toBe('composer-2.5[fast=true]'); + + queue.close(); + await runPromise; + }); + + it('requeues a pending message when Auto relaunch and restore both fail', async () => { + const queue = new MessageQueue2((mode) => mode.permissionMode); + const emitMessagesConsumed = vi.fn(); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn(), + emitMessagesConsumed + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + await session.applyModelConfig('composer-2.5[fast=false]'); + emitMessagesConsumed.mockClear(); + + harness.failInitializeTimes = 2; + const autoSwitch = session.applyModelConfig('auto'); + queue.push('must-survive-double-failure', { permissionMode: 'default' }, 'turn-local-1'); + await expect(autoSwitch).rejects.toThrow(/relaunch with --model auto failed/i); + + await vi.waitFor(() => expect(queue.size()).toBeGreaterThan(0)); + expect(queue.hasMessageMatching((message) => message === 'must-survive-double-failure')).toBe(true); + expect(emitMessagesConsumed).not.toHaveBeenCalledWith( + expect.arrayContaining(['turn-local-1']) ); + queue.close(); + await runPromise; + }); + + it('re-queues Auto-review slash after relaunch when leaving and re-entering Auto-review', async () => { + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn(), + emitMessagesConsumed: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + + session.setPermissionMode('autoReview'); + await vi.waitFor(() => { + expect(queue.hasMessageMatching((message) => message === '/auto-review')).toBe(true); + }); + // Consume the slash so the old-process flag would otherwise block a re-queue. + await vi.waitFor(() => { + expect( + harness.prompts.some((prompt) => JSON.stringify(prompt).includes('/auto-review')) + ).toBe(true); + }); + + session.setPermissionMode('default'); + await session.applyModelConfig('composer-2.5[fast=false]'); + await session.applyModelConfig('auto'); + session.setPermissionMode('autoReview'); + + await vi.waitFor(() => { + expect( + harness.prompts.filter((prompt) => JSON.stringify(prompt).includes('/auto-review')).length + ).toBeGreaterThanOrEqual(2); + }); + + queue.close(); + await runPromise; + }); + + it('queues Auto-review slash after Auto relaunch when session started with --auto-review', async () => { + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn(), + emitMessagesConsumed: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'autoReview' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + queue.push('hold-open', { permissionMode: 'autoReview' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + expect(harness.spawnAutoReviewFlags[0]).toBe(true); + // Spawned with --auto-review — no slash needed yet. + expect(queue.hasMessageMatching((message) => message === '/auto-review')).toBe(false); + + session.setPermissionMode('default'); + await session.applyModelConfig('composer-2.5[fast=false]'); + await session.applyModelConfig('auto'); + + await vi.waitFor(() => { + expect(harness.spawnAutoReviewFlags.at(-1)).toBe(false); + }); + + session.setPermissionMode('autoReview'); + await vi.waitFor(() => { + expect( + harness.prompts.some((prompt) => JSON.stringify(prompt).includes('/auto-review')) + || queue.hasMessageMatching((message) => message === '/auto-review') + ).toBe(true); + }); + + queue.close(); + await runPromise; + }); + + it('drops queued Auto-review slash when Auto relaunch spawns with --auto-review', async () => { + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn(), + emitMessagesConsumed: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + await session.applyModelConfig('composer-2.5[fast=false]'); + + // Mode is Auto-review before relaunch so the replacement gets --auto-review. + session.setPermissionMode('autoReview'); + await vi.waitFor(() => { + expect( + harness.prompts.some((prompt) => JSON.stringify(prompt).includes('/auto-review')) + ).toBe(true); + }); + // Wait until the slash prompt finishes so relaunch is not blocked by promptInFlight. + await vi.waitFor(() => { + expect(queue.hasMessageMatching((message) => message === '/auto-review')).toBe(false); + }); + + let releaseInitialize!: () => void; + harness.deferNextInitialize = new Promise((resolve) => { + releaseInitialize = resolve; + }); + const autoSwitch = session.applyModelConfig('auto'); + await vi.waitFor(() => expect(harness.deferNextInitialize).toBeNull()); + + // Leftover toggle from the old process still queued while replacement starts + // with --auto-review. Insert without waking the waiter so the message loop + // cannot dequeue it before bindFresh reconciles (mode+model race). + queue.queue.push({ + message: '/auto-review', + mode: { permissionMode: 'autoReview', model: session.model }, + modeHash: queue.modeHasher({ permissionMode: 'autoReview', model: session.model }), + isolate: true, + internal: true, + enqueueOrder: 9999 + }); + expect(queue.hasMessageMatching((message) => message === '/auto-review')).toBe(true); + + const promptsBeforeBind = harness.prompts.filter( + (prompt) => JSON.stringify(prompt).includes('/auto-review') + ).length; + releaseInitialize(); + await autoSwitch; + + expect(harness.spawnAutoReviewFlags.at(-1)).toBe(true); + expect(queue.hasMessageMatching((message) => message === '/auto-review')).toBe(false); + expect( + harness.prompts.filter((prompt) => JSON.stringify(prompt).includes('/auto-review')).length + ).toBe(promptsBeforeBind); + + queue.close(); + await runPromise; + }); + + it('discards a dequeued internal Auto-review toggle held across Auto relaunch', async () => { + const queue = new MessageQueue2((mode) => + `${mode.permissionMode}:${mode.model ?? ''}` + ); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn(), + emitMessagesConsumed: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + await session.applyModelConfig('composer-2.5[fast=false]'); + + session.setPermissionMode('autoReview'); + const slash = queue.queue.find((entry) => entry.message === '/auto-review'); + expect(slash?.internal).toBe(true); + // Force the held batch to trigger Auto relaunch while dequeued (tip-bot Major). + slash!.mode = { permissionMode: 'autoReview', model: 'auto' }; + slash!.modeHash = queue.modeHasher(slash!.mode); + + await vi.waitFor(() => { + expect(harness.spawnAutoReviewFlags.at(-1)).toBe(true); + }); + await vi.waitFor(() => expect(session.model).toBe('auto')); + + // Internal toggle must not be prompted on a --auto-review replacement. + expect( + harness.prompts.filter((prompt) => JSON.stringify(prompt).includes('/auto-review')).length + ).toBe(0); + + queue.close(); + await runPromise; + }); + + it('preserves a user-sent /auto-review across Auto relaunch with --auto-review', async () => { + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn(), + emitMessagesConsumed: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + await session.applyModelConfig('composer-2.5[fast=false]'); + + session.setPermissionMode('autoReview'); + await vi.waitFor(() => { + expect( + harness.prompts.some((prompt) => JSON.stringify(prompt).includes('/auto-review')) + ).toBe(true); + }); + await vi.waitFor(() => { + expect(queue.hasMessageMatching((message) => message === '/auto-review')).toBe(false); + }); + + let releaseInitialize!: () => void; + harness.deferNextInitialize = new Promise((resolve) => { + releaseInitialize = resolve; + }); + const autoSwitch = session.applyModelConfig('auto'); + await vi.waitFor(() => expect(harness.deferNextInitialize).toBeNull()); + + // User-authored command (no internal flag) must survive bindFresh reconcile. + queue.queue.push({ + message: '/auto-review', + mode: { permissionMode: 'autoReview', model: session.model }, + modeHash: queue.modeHasher({ permissionMode: 'autoReview', model: session.model }), + isolate: true, + localId: 'user-auto-review-1', + enqueueOrder: 9999 + }); + const promptsBeforeUserSlash = harness.prompts.filter( + (prompt) => JSON.stringify(prompt).includes('/auto-review') + ).length; + + releaseInitialize(); + await autoSwitch; + expect(harness.spawnAutoReviewFlags.at(-1)).toBe(true); + expect(queue.hasMessageMatching((message) => message === '/auto-review')).toBe(true); + + // Silent insert during relaunch did not wake the idle waiter — nudge the loop. + queue.push('wake-loop', { permissionMode: 'default' }); + + await vi.waitFor(() => { + expect( + harness.prompts.filter((prompt) => JSON.stringify(prompt).includes('/auto-review')).length + ).toBeGreaterThan(promptsBeforeUserSlash); + }); + expect(queue.hasMessageMatching((message) => message === '/auto-review')).toBe(false); + expect(vi.mocked(client.emitMessagesConsumed)).toHaveBeenCalledWith( + expect.arrayContaining(['user-auto-review-1']) + ); + + queue.close(); + await runPromise; + }); + + it('queues Auto-review slash when mode flips during Auto relaunch', async () => { + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn(), + emitMessagesConsumed: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + await session.applyModelConfig('composer-2.5[fast=false]'); + + let releaseInitialize!: () => void; + harness.deferNextInitialize = new Promise((resolve) => { + releaseInitialize = resolve; + }); + const autoSwitch = session.applyModelConfig('auto'); + await vi.waitFor(() => expect(harness.deferNextInitialize).toBeNull()); + + session.setPermissionMode('autoReview'); + releaseInitialize(); + await autoSwitch; + + await vi.waitFor(() => { + expect( + harness.prompts.some((prompt) => JSON.stringify(prompt).includes('/auto-review')) + || (queue as unknown as { queue: Array<{ message: string }> }).queue + ?.some((item) => item.message === '/auto-review') + ).toBe(true); + }); + + queue.close(); + await runPromise; + }); + + it('prompts a queued Auto-mode batch on the relaunched backend', async () => { + const queue = new MessageQueue2((mode) => + `${mode.permissionMode}:${mode.model ?? ''}` + ); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn(), + emitMessagesConsumed: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + + await session.applyModelConfig('composer-2.5[fast=false]'); expect(session.model).toBe('composer-2.5[fast=false]'); - expect(harness.setConfigOptionCalls.filter((call) => call.configId === 'model-opt')).toEqual([]); + harness.promptCalls = 0; + harness.loadSessionCalled = false; + + queue.push('switch-to-auto-turn', { permissionMode: 'default', model: 'auto' }); + queue.close(); + + await runPromise; + + expect(session.model).toBe('auto'); + expect(harness.backendArgs).toEqual({ command: 'agent', args: ['--model', 'auto', 'acp'] }); + expect(harness.loadSessionCalled).toBe(true); + expect(harness.promptCalls).toBeGreaterThanOrEqual(1); + expect(harness.prompts.at(-1)).toEqual([{ type: 'text', text: 'switch-to-auto-turn' }]); + }); + + it('keeps the launcher alive when a message arrives mid Auto relaunch', async () => { + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn(), + emitMessagesConsumed: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + await session.applyModelConfig('composer-2.5[fast=false]'); + + let releaseInitialize!: () => void; + harness.deferNextInitialize = new Promise((resolve) => { + releaseInitialize = resolve; + }); + const autoSwitch = session.applyModelConfig('auto'); + await vi.waitFor(() => expect(harness.deferNextInitialize).toBeNull()); + + queue.push('arrived-during-relaunch', { permissionMode: 'default' }); + await new Promise((resolve) => setTimeout(resolve, 20)); + releaseInitialize(); + await autoSwitch; + + expect(session.model).toBe('auto'); + await vi.waitFor(() => { + expect(harness.prompts.some( + (prompt) => JSON.stringify(prompt).includes('arrived-during-relaunch') + )).toBe(true); + }); queue.close(); await runPromise; @@ -1760,7 +2421,7 @@ describe('cursorAcpRemoteLauncher', () => { await runPromise; }); - it('rejects applyModelConfig Auto when advertised auto cannot be set', async () => { + it('falls back to in-place relaunch when advertised auto cannot be set via ACP', async () => { harness.modelOptionValues = ['auto', 'composer-2.5[fast=false]']; harness.failSetConfigOption = true; const queue = new MessageQueue2((mode) => mode.permissionMode); @@ -1787,23 +2448,25 @@ describe('cursorAcpRemoteLauncher', () => { startingMode: 'remote', permissionMode: 'default' }); - session.onSessionFoundWithProtocol = vi.fn(); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); queue.push('hold-open', { permissionMode: 'default' }); const runPromise = cursorAcpRemoteLauncher(session); await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); - await expect(session.applyModelConfig('auto')).rejects.toThrow( - 'Cursor auto model is not available via ACP' - ); - expect(session.model).not.toBe('auto'); + await session.applyModelConfig('auto'); + expect(session.model).toBe('auto'); + expect(harness.backendArgs).toEqual({ command: 'agent', args: ['--model', 'auto', 'acp'] }); + expect(harness.loadSessionCalled).toBe(true); queue.close(); await runPromise; }); - it.each([[false, false], [true, false], [false, true], [true, true]])('rejects Auto after an Auto-spawned concrete switch (partial=%s, concurrent=%s)', async (partial, concurrent) => { + it.each([[false, false], [true, false], [false, true], [true, true]])('relaunches Auto after an Auto-spawned concrete switch (partial=%s, concurrent=%s)', async (partial, concurrent) => { const queue = new MessageQueue2((mode) => mode.permissionMode); const client = { rpcHandlerManager: { registerHandler: vi.fn() }, @@ -1829,7 +2492,9 @@ describe('cursorAcpRemoteLauncher', () => { permissionMode: 'default', model: 'auto' }); - session.onSessionFoundWithProtocol = vi.fn(); + session.onSessionFoundWithProtocol = vi.fn((id: string) => { + session.sessionId = id; + }); queue.push('hold-open', { permissionMode: 'default' }); const runPromise = cursorAcpRemoteLauncher(session); @@ -1865,17 +2530,22 @@ describe('cursorAcpRemoteLauncher', () => { await concreteRequest; } if (autoRequest) { - expect((await autoRequest).error?.message).toContain('Cursor Auto requires restarting with --model auto'); - } - const concreteModel = partial ? 'composer-2.5' : 'composer-2.5[fast=false]'; - expect(session.model).toBe(concreteModel); - harness.setConfigOptionCalls.length = 0; + const result = await autoRequest; + expect(result.error).toBeNull(); + expect(result.value).toBe('auto'); + expect(session.model).toBe('auto'); + } else { + const concreteModel = partial ? 'composer-2.5' : 'composer-2.5[fast=false]'; + expect(session.model).toBe(concreteModel); + harness.setConfigOptionCalls.length = 0; + harness.loadSessionCalled = false; - await expect(session.applyModelConfig('auto')).rejects.toThrow( - 'Cursor Auto requires restarting with --model auto' - ); - expect(session.model).toBe(concreteModel); - expect(harness.setConfigOptionCalls.filter((call) => call.configId === 'model-opt')).toEqual([]); + await session.applyModelConfig('auto'); + expect(session.model).toBe('auto'); + expect(harness.backendArgs).toEqual({ command: 'agent', args: ['--model', 'auto', 'acp'] }); + expect(harness.loadSessionCalled).toBe(true); + expect(harness.setConfigOptionCalls.filter((call) => call.configId === 'model-opt')).toEqual([]); + } queue.close(); await runPromise; diff --git a/cli/src/cursor/cursorAcpRemoteLauncher.ts b/cli/src/cursor/cursorAcpRemoteLauncher.ts index ce0ae085..3d4b31f0 100644 --- a/cli/src/cursor/cursorAcpRemoteLauncher.ts +++ b/cli/src/cursor/cursorAcpRemoteLauncher.ts @@ -78,6 +78,13 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { private spawnedWithAutoReview = false; /** True when this ACP process was spawned with `--model auto`. */ private spawnedWithCliAuto = false; + /** + * Resolves when an in-place ACP relaunch finishes (success or failed restore). + * The message loop awaits this instead of exiting when `backend` is briefly null. + */ + private acpRelaunchPromise: Promise | null = null; + /** Set when cleanup begins so a late relaunch cannot publish a live backend. */ + private sessionTeardownStarted = false; /** Avoid re-queueing `/auto-review` on every mid-session mode sync. */ private autoReviewSlashQueued = false; private cursorMcpOverlay: CursorMcpOverlayHandle | null = null; @@ -411,7 +418,7 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { && spawnModel && spawnModel !== desiredModel ); - await this.applyLiveModel(backend, acpSessionId, modelToApply, previousSetModel, { + await this.applyLiveModel(modelToApply, previousSetModel, { optimistic: false, throwOnFailure: mustRestoreDesiredModel }); @@ -419,7 +426,7 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { this.pushModelStatusLine(this.currentBackendModel); } - this.installLiveSessionConfigSync(backend, acpSessionId, previousSetModel); + this.installLiveSessionConfigSync(previousSetModel); this.applyDisplayMode(session.getPermissionMode() as PermissionMode); @@ -585,7 +592,33 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { try { while (!this.shouldExit) { const waitSignal = this.abortController.signal; - const batch = await session.queue.waitForMessagesAndGetAsString(waitSignal); + if (this.acpRelaunchPromise) { + await this.acpRelaunchPromise; + } + + // Do not dequeue (and hub-ack) while the ACP backend is missing — + // wait for an in-flight relaunch, or end without consuming the queue. + if (!this.backend || !this.acpSessionId) { + if (this.acpRelaunchPromise) { + continue; + } + if (!this.shouldExit) { + this.surfacePromptFailure( + 'Cursor ACP backend unavailable after model switch; ending session.' + ); + } + break; + } + + // Defer hub ack until we confirm a live backend can take the turn. + const acknowledgeBatch = this.session.queue.onBatchConsumed; + this.session.queue.onBatchConsumed = null; + let batch: Awaited>; + try { + batch = await session.queue.waitForMessagesAndGetAsString(waitSignal); + } finally { + this.session.queue.onBatchConsumed = acknowledgeBatch; + } if (!batch) { if (waitSignal.aborted && !this.shouldExit) { @@ -603,8 +636,6 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { ); if (modelChanged) { const appliedModel = await this.applyLiveModel( - backend, - acpSessionId, requestedModel, previousSetModel, { optimistic: false, throwOnFailure: false } @@ -612,68 +643,122 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { batch.mode.model = appliedModel ?? this.currentBackendModel ?? undefined; } - await applyCursorAcpMode(backend, acpSessionId, batch.mode.permissionMode as PermissionMode); - this.applyDisplayMode(batch.mode.permissionMode as PermissionMode); - - const specialCommand = parseCursorSpecialCommand(batch.message); - if (specialCommand.type === 'pass-through') { - messageBuffer.addMessage(cursorPassThroughStatusMessage(specialCommand.command), 'status'); + if (this.acpRelaunchPromise) { + await this.acpRelaunchPromise; } - messageBuffer.addMessage(batch.message, 'user'); - // skill_lookup discovery lives on the MCP tool description — do not - // prepend instructions onto user turns (prompt-injection false positive). - const promptContent: PromptContent[] = [{ - type: 'text', - text: batch.message - }]; + // Re-read after model apply / concurrent relaunch - do not prompt on a + // backend captured before an in-place Auto respawn (#1908 bot Majors). + const liveBackend = this.backend; + const liveSessionId: string | null = this.acpSessionId; + if (!liveBackend || !liveSessionId) { + // Never hub-acked — put the turn back for resume/recovery. + for (let i = batch.items.length - 1; i >= 0; i -= 1) { + const item = batch.items[i]!; + if (batch.isolate) { + session.queue.unshiftIsolated(item.message, batch.mode, item.localId, { + internal: item.internal + }); + } else { + session.queue.unshift(item.message, batch.mode, item.localId); + } + } + if (!this.shouldExit) { + this.surfacePromptFailure( + 'Cursor ACP backend unavailable after model switch; ending session.' + ); + } + break; + } + // Internal Auto-review toggle already dequeued, then held across an + // in-place relaunch that spawned with --auto-review: prompting would + // toggle Auto-review off while HAPI still displays it. + if ( + this.spawnedWithAutoReview + && batch.items.length > 0 + && batch.items.every( + (item) => item.internal === true && item.message.trim() === '/auto-review' + ) + ) { + continue; + } + + const consumedLocalIds = batch.items + .map((item) => item.localId) + .filter((id): id is string => typeof id === 'string'); + if (consumedLocalIds.length > 0) { + acknowledgeBatch?.(consumedLocalIds); + } + + // Hold promptInFlight before mode apply so a concurrent Auto relaunch + // cannot disconnect this backend mid-dispatch. session.onThinkingChange(true); this.promptInFlight = true; session.client.updateAgentState?.((state) => ({ ...state, steeringActive: true })); this.activePromptModeHash = batch.hash; + this.userAbortRequested = false; + let requeueBatch = false; try { - this.promptInFlight = true; - this.userAbortRequested = false; - for (let retryAttempt = 0; retryAttempt <= CURSOR_AUTO_RETRY_LIMIT; retryAttempt += 1) { - this.pendingRetryableError = null; - this.pendingRetryableFromStderr = false; - this.pendingInlineRetryableError = false; - this.attemptProducedToolActivity = false; - let turnCompleted = false; - try { - await backend.prompt(acpSessionId, promptContent, (message) => { - if (message.type === 'turn_complete') turnCompleted = true; - this.handleAgentMessage(message); - }); - if (this.userAbortRequested) break; - if (turnCompleted && this.pendingRetryableFromStderr && !this.pendingInlineRetryableError) { - this.pendingRetryableError = null; - } - if (!this.pendingRetryableError) { - void backend.refreshSessionInfo(acpSessionId, session.path); - break; - } - } catch (error) { - logger.warn('[cursor-acp] prompt failed', error); - if (this.userAbortRequested) break; - if (!isRetryableCursorError(error)) { - this.surfacePromptFailure(error instanceof Error ? error.message : String(error)); - break; - } - this.pendingRetryableError = error instanceof Error ? error.message : String(error); - } + if (this.backend !== liveBackend || this.acpSessionId !== liveSessionId) { + requeueBatch = true; + } else { + await applyCursorAcpMode(liveBackend, liveSessionId, batch.mode.permissionMode as PermissionMode); + this.applyDisplayMode(batch.mode.permissionMode as PermissionMode); - if (this.attemptProducedToolActivity) { - this.surfacePromptFailure('Cursor connection interrupted after tool activity; the prompt was not retried.'); - break; + const specialCommand = parseCursorSpecialCommand(batch.message); + if (specialCommand.type === 'pass-through') { + messageBuffer.addMessage(cursorPassThroughStatusMessage(specialCommand.command), 'status'); } - if (retryAttempt < CURSOR_AUTO_RETRY_LIMIT) { - this.surfaceRetry(retryAttempt + 1); - continue; + messageBuffer.addMessage(batch.message, 'user'); + + // skill_lookup discovery lives on the MCP tool description — do not + // prepend instructions onto user turns (prompt-injection false positive). + const promptContent: PromptContent[] = [{ + type: 'text', + text: batch.message + }]; + + for (let retryAttempt = 0; retryAttempt <= CURSOR_AUTO_RETRY_LIMIT; retryAttempt += 1) { + this.pendingRetryableError = null; + this.pendingRetryableFromStderr = false; + this.pendingInlineRetryableError = false; + this.attemptProducedToolActivity = false; + let turnCompleted = false; + try { + await liveBackend.prompt(liveSessionId, promptContent, (message) => { + if (message.type === 'turn_complete') turnCompleted = true; + this.handleAgentMessage(message); + }); + if (this.userAbortRequested) break; + if (turnCompleted && this.pendingRetryableFromStderr && !this.pendingInlineRetryableError) { + this.pendingRetryableError = null; + } + if (!this.pendingRetryableError) { + void liveBackend.refreshSessionInfo(liveSessionId, session.path); + break; + } + } catch (error) { + logger.warn('[cursor-acp] prompt failed', error); + if (this.userAbortRequested) break; + if (!isRetryableCursorError(error)) { + this.surfacePromptFailure(error instanceof Error ? error.message : String(error)); + break; + } + this.pendingRetryableError = error instanceof Error ? error.message : String(error); + } + + if (this.attemptProducedToolActivity) { + this.surfacePromptFailure('Cursor connection interrupted after tool activity; the prompt was not retried.'); + break; + } + if (retryAttempt < CURSOR_AUTO_RETRY_LIMIT) { + this.surfaceRetry(retryAttempt + 1); + continue; + } + this.surfacePromptFailure(`Cursor Agent failed after ${CURSOR_AUTO_RETRY_LIMIT} retries.`); } - this.surfacePromptFailure(`Cursor Agent failed after ${CURSOR_AUTO_RETRY_LIMIT} retries.`); } } finally { this.promptInFlight = false; @@ -713,6 +798,20 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { sendReady(); } } + + if (requeueBatch) { + for (let i = batch.items.length - 1; i >= 0; i -= 1) { + const item = batch.items[i]!; + if (batch.isolate) { + session.queue.unshiftIsolated(item.message, batch.mode, item.localId, { + internal: item.internal + }); + } else { + session.queue.unshift(item.message, batch.mode, item.localId); + } + } + continue; + } } } finally { // No wait here: Exit/Switch must reach cleanup() promptly; it @@ -726,6 +825,7 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { // cancelAll/disconnect cannot leave a dead hapi-* entry in ~/.cursor/mcp.json. const overlay = this.cursorMcpOverlay; this.cursorMcpOverlay = null; + this.sessionTeardownStarted = true; try { this.clearAbortHandlers(this.session.client.rpcHandlerManager); @@ -739,6 +839,10 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { this.unregisterModelApplyHandler?.(); this.unregisterModelApplyHandler = null; + if (this.acpRelaunchPromise) { + await this.acpRelaunchPromise.catch(() => {}); + } + if (this.permissionAdapter) { await this.permissionAdapter.cancelAll('Session ended'); this.permissionAdapter = null; @@ -917,14 +1021,20 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { } private installLiveSessionConfigSync( - backend: AcpSdkBackend, - acpSessionId: string, previousSetModel: CursorSession['setModel'] ): void { const session = this.session; const previousSetPermissionMode = session.setPermissionMode.bind(session); session.setPermissionMode = (mode: PermissionMode) => { previousSetPermissionMode(mode); + const backend = this.backend; + const acpSessionId = this.acpSessionId; + if (!backend || !acpSessionId) { + // Relaunch may have nulled the backend; still record Auto-review so + // maybeQueueAutoReviewSlash can fire once the replacement is ready. + this.maybeQueueAutoReviewSlash(mode); + return; + } void applyCursorAcpMode(backend, acpSessionId, mode).then(() => { this.applyDisplayMode(mode); }); @@ -932,14 +1042,14 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { }; this.unregisterModelApplyHandler = session.registerModelApplyHandler(async (model) => ( - await this.applyLiveModel(backend, acpSessionId, model, previousSetModel, { + await this.applyLiveModel(model, previousSetModel, { optimistic: false, throwOnFailure: true }) )); session.setModel = (model: string | null | undefined) => { - void this.applyLiveModel(backend, acpSessionId, model, previousSetModel, { + void this.applyLiveModel(model, previousSetModel, { optimistic: true, throwOnFailure: false }).catch((error) => { @@ -949,23 +1059,28 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { } private async applyLiveModel( - backend: AcpSdkBackend, - acpSessionId: string, model: string | null | undefined, previousSetModel: CursorSession['setModel'], options: { optimistic: boolean; throwOnFailure: boolean } ): Promise { return this.modelApplyLock.inLock(() => - this.applyLiveModelLocked(backend, acpSessionId, model, previousSetModel, options)); + this.applyLiveModelLocked(model, previousSetModel, options)); } private async applyLiveModelLocked( - backend: AcpSdkBackend, - acpSessionId: string, model: string | null | undefined, previousSetModel: CursorSession['setModel'], options: { optimistic: boolean; throwOnFailure: boolean } ): Promise { + const backend = this.backend; + const acpSessionId = this.acpSessionId; + if (!backend || !acpSessionId) { + if (options.throwOnFailure) { + throw new Error('Cursor ACP session is not ready'); + } + return this.currentBackendModel ?? this.session.model ?? null; + } + const requested = model?.trim(); const previousModel = this.currentBackendModel ?? this.session.model ?? null; @@ -982,25 +1097,35 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { appliedLive = true; } catch (error) { logger.debug('[cursor-acp] Failed to set auto model via ACP', error); - if (options.throwOnFailure) { - throw new Error('Cursor auto model is not available via ACP'); - } + // Fall through to in-place relaunch with CLI `--model auto`. } } // Live ACP catalogs usually advertise `default[]`, which is not CLI - // Auto (#1817). Only acknowledge Auto after a confirmed spawn or ACP - // `auto` option. In-session Auto without either requires a restart. + // Auto (#1817). When ACP cannot confirm Auto, relaunch the same hub + // session under `--model auto` + session/load (#1908). if (!appliedLive && !this.spawnedWithCliAuto) { - if (options.throwOnFailure) { - throw new Error('Cursor Auto requires restarting with --model auto'); + try { + await this.relaunchAcpWithSpawnModel(CURSOR_AUTO_MODEL_ID); + } catch (error) { + logger.warn('[cursor-acp] In-place Auto relaunch failed', error); + if (options.throwOnFailure) { + const detail = error instanceof Error ? error.message : String(error); + throw new Error( + `Cursor Auto relaunch with --model auto failed: ${detail}` + ); + } + return previousModel; } - return previousModel; } previousSetModel(CURSOR_AUTO_MODEL_ID); this.currentBackendModel = CURSOR_AUTO_MODEL_ID; this.pushModelStatusLine(CURSOR_AUTO_MODEL_ID); this.session.pushKeepAlive(); - syncCursorModelsFromAcp(backend, acpSessionId); + const liveBackend = this.backend; + const liveSessionId = this.acpSessionId; + if (liveBackend && liveSessionId) { + syncCursorModelsFromAcp(liveBackend, liveSessionId); + } return CURSOR_AUTO_MODEL_ID; } @@ -1057,6 +1182,203 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { return sessionWire; } + /** + * Disconnect the live ACP process and spawn a replacement under the same hub + * session, loading the existing agent session id (CLI Auto pin, #1908). + * On failure after disconnect, best-effort restore the prior spawn so the + * launcher is not left without a backend. + */ + private async relaunchAcpWithSpawnModel(spawnModel: string): Promise { + if (this.acpRelaunchPromise) { + await this.acpRelaunchPromise; + if (this.spawnedWithCliAuto && cursorSpawnModelId(spawnModel) === CURSOR_AUTO_MODEL_ID) { + return; + } + } + + let settleRelaunch!: () => void; + const relaunchDone = new Promise((resolve) => { + settleRelaunch = resolve; + }); + this.acpRelaunchPromise = relaunchDone; + + try { + await this.relaunchAcpWithSpawnModelLocked(spawnModel); + } finally { + settleRelaunch(); + if (this.acpRelaunchPromise === relaunchDone) { + this.acpRelaunchPromise = null; + } + } + } + + private async relaunchAcpWithSpawnModelLocked(spawnModel: string): Promise { + const session = this.session; + const resumeSessionId = this.acpSessionId ?? session.sessionId; + if (!resumeSessionId) { + throw new Error('No Cursor ACP session id available for in-place relaunch'); + } + if (this.promptInFlight) { + throw new Error('Cannot relaunch Cursor ACP while a prompt is in flight'); + } + if (this.sessionTeardownStarted || this.shouldExit) { + throw new Error('Cannot relaunch Cursor ACP while the session is ending'); + } + if (this.softSteerWaiters.length > 0) { + await Promise.allSettled([...this.softSteerWaiters]); + this.softSteerWaiters = []; + } + + const rollbackSpawnModel = this.spawnedWithCliAuto + ? CURSOR_AUTO_MODEL_ID + : resolveCursorSpawnModel(this.currentBackendModel ?? session.model); + const rollbackAutoReview = this.spawnedWithAutoReview; + const autoReview = isCursorAutoReviewMode(session.getPermissionMode() as PermissionMode); + + const previousBackend = this.backend; + if (previousBackend) { + await previousBackend.disconnect().catch((error) => { + logger.debug('[cursor-acp] Prior ACP disconnect during relaunch', error); + }); + } + this.backend = null; + + try { + await this.bindFreshAcpBackend({ + spawnModel, + autoReview, + resumeSessionId + }); + this.spawnedWithAutoReview = autoReview; + this.spawnedWithCliAuto = cursorSpawnModelId(spawnModel) === CURSOR_AUTO_MODEL_ID; + logger.info( + `[cursor-acp] In-place relaunch with --model ${cursorSpawnModelId(spawnModel) ?? spawnModel} (session=${this.acpSessionId})` + ); + } catch (error) { + logger.warn('[cursor-acp] In-place relaunch failed; attempting prior-spawn restore', error); + try { + await this.bindFreshAcpBackend({ + spawnModel: rollbackSpawnModel, + autoReview: rollbackAutoReview, + resumeSessionId + }); + this.spawnedWithAutoReview = rollbackAutoReview; + this.spawnedWithCliAuto = cursorSpawnModelId(rollbackSpawnModel) === CURSOR_AUTO_MODEL_ID; + } catch (restoreError) { + logger.warn('[cursor-acp] Prior-spawn restore after failed relaunch also failed', restoreError); + } + throw error; + } + } + + private async bindFreshAcpBackend(args: { + spawnModel: string | null | undefined; + autoReview: boolean; + resumeSessionId: string; + }): Promise { + const session = this.session; + let recentStderrHint: string | null = null; + const backend = createCursorAcpBackend({ + cwd: session.path, + model: args.spawnModel, + autoReview: args.autoReview, + worktree: session.cursorWorktree, + addDirs: session.cursorAddDirs + }); + // Publish this.backend only after initialize + session/load so the + // message loop cannot prompt against a half-ready process. + registerAcpSessionTitleSync(backend, session.client); + backend.setUsageUpdateListener((message) => this.handleAgentMessage(message)); + this.wireAgentActivityThinking(backend, session); + this.wireStderrErrorListener(backend, (hint) => { + recentStderrHint = hint; + }); + + try { + await backend.initialize(); + await backend.authenticateIfAvailable('cursor_login'); + } catch (error) { + const message = classifyCursorAcpLoadError(error, { + recentStderr: recentStderrHint, + action: 'start' + }); + await backend.disconnect().catch(() => {}); + throw new Error(message); + } + + this.extensionAdapter = new CursorExtensionAdapter( + session.client, + backend, + (message) => this.handleAgentMessage(message), + () => this.handleCreatePlanAccepted() + ); + this.permissionAdapter = new PermissionAdapter( + session.client, + backend, + () => session.getPermissionMode(), + (response) => this.handlePermissionResponse(this.extensionAdapter!, response) + ); + + if (!backend.supportsLoadSession()) { + await backend.disconnect().catch(() => {}); + throw new Error( + 'Cursor ACP session/load is not supported by this agent build; cannot relaunch in place' + ); + } + + let acpSessionId: string; + try { + acpSessionId = await backend.loadSession({ + sessionId: args.resumeSessionId, + cwd: session.path, + mcpServers: [] + }); + } catch (error) { + logger.warn('[cursor-acp] session/load failed during in-place relaunch', formatAcpLoadError(error)); + const message = classifyCursorAcpLoadError(error, { recentStderr: recentStderrHint }); + await backend.disconnect().catch(() => {}); + throw new Error(message); + } + + if (acpSessionId !== args.resumeSessionId) { + session.onSessionFoundWithProtocol(acpSessionId, 'acp'); + await session.client.flushMetadata(); + } + + if (this.sessionTeardownStarted || this.shouldExit) { + await backend.disconnect().catch(() => {}); + throw new Error('Session ending; discarding replacement ACP backend'); + } + + this.backend = backend; + this.acpSessionId = acpSessionId; + + // Fresh ACP process — bookkeeping must reflect THIS spawn's flags, not + // the prior process (e.g. started with --auto-review, relaunched without). + this.spawnedWithAutoReview = args.autoReview; + if (args.autoReview) { + // `/auto-review` is a toggle; drop any *internal* queued slash that was + // meant for the old process so we do not turn Auto-review off on a + // spawn that already has --auto-review. Preserve user-sent commands. + this.session.queue.removeItemsMatching( + (item) => item.internal === true && item.message.trim() === '/auto-review' + ); + this.autoReviewSlashQueued = true; + } else { + this.autoReviewSlashQueued = this.session.queue.hasMessageMatching( + (message) => message.trim() === '/auto-review' + ); + } + + // Apply current mode after publish so Auto-review changes made while the + // backend was null during relaunch still take effect (slash if needed). + const modeAfterLoad = session.getPermissionMode() as PermissionMode; + await applyCursorAcpMode(backend, acpSessionId, modeAfterLoad); + syncCursorModelsFromAcp(backend, acpSessionId); + this.applyDisplayMode(modeAfterLoad); + this.maybeQueueAutoReviewSlash(modeAfterLoad); + } + private pushModelStatusLine(model: string | null | undefined): void { const trimmed = model?.trim(); if (!trimmed || isCursorAutoModelId(trimmed)) { @@ -1090,7 +1412,9 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { { permissionMode: mode, model: this.session.model - } + }, + undefined, + { internal: true } ); this.messageBuffer.addMessage(cursorPassThroughStatusMessage('auto-review'), 'status'); } diff --git a/cli/src/utils/MessageQueue2.ts b/cli/src/utils/MessageQueue2.ts index 6c724ba1..b4423dd6 100644 --- a/cli/src/utils/MessageQueue2.ts +++ b/cli/src/utils/MessageQueue2.ts @@ -8,8 +8,17 @@ export interface QueueItem { isolate?: boolean; // If true, this message must be processed alone /** 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. + */ + internal?: boolean; } +export type QueueItemOptions = { + internal?: boolean; +}; + export type QueueReservation = { item: QueueItem; index: number; @@ -137,7 +146,7 @@ export class MessageQueue2 { * Use this when a slash command must run alone but earlier prompts must * still be delivered in order. */ - pushIsolated(message: string, mode: T, localId?: string): void { + pushIsolated(message: string, mode: T, localId?: string, options?: QueueItemOptions): void { if (this.closed) { throw new Error('Cannot push to closed queue'); } @@ -151,6 +160,7 @@ export class MessageQueue2 { modeHash, localId, isolate: true, + internal: options?.internal, enqueueOrder: this.nextEnqueueOrder++ }; Object.defineProperty(item, 'enqueueOrder', { value: item.enqueueOrder, enumerable: false, writable: true }); @@ -261,7 +271,7 @@ export class MessageQueue2 { * that failed transiently and must retry without batching against sibling * prompts). */ - unshiftIsolated(message: string, mode: T, localId?: string): void { + unshiftIsolated(message: string, mode: T, localId?: string, options?: QueueItemOptions): void { if (this.closed) { throw new Error('Cannot unshift to closed queue'); } @@ -275,6 +285,7 @@ export class MessageQueue2 { modeHash, localId, isolate: true, + internal: options?.internal, enqueueOrder: this.previousEnqueueOrder-- }; Object.defineProperty(item, 'enqueueOrder', { value: item.enqueueOrder, enumerable: false, writable: true }); @@ -517,6 +528,37 @@ export class MessageQueue2 { .filter((id): id is string => typeof id === 'string'); } + /** True if any pending (not yet dequeued) message matches the predicate. */ + hasMessageMatching(predicate: (message: string) => boolean): boolean { + return this.queue.some((item) => predicate(item.message)); + } + + /** + * Drop pending items matching the predicate (e.g. reconcile an internal + * slash that a fresh spawn already satisfies). Does not hub-ack. + */ + removeItemsMatching(predicate: (item: QueueItem) => boolean): number { + const kept: QueueItem[] = []; + let removed = 0; + for (const item of this.queue) { + if (!predicate(item)) { + kept.push(item); + continue; + } + removed += 1; + if (item.localId) { + const reservation = this.reservations.get(item.localId); + if (reservation) { + reservation.cancelReason = 'explicit'; + reservation.state = 'cancelled'; + this.reservations.delete(item.localId); + } + } + } + this.queue = kept; + return removed; + } + /** * Close the queue - no more messages can be pushed */ @@ -551,7 +593,7 @@ export class MessageQueue2 { * 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 }> } | null> { + async waitForMessagesAndGetAsString(abortSignal?: AbortSignal): Promise<{ message: string, mode: T, isolate: boolean, hash: string, items: Array<{ message: string, localId?: string, internal?: boolean }> } | null> { // If we have messages, return them immediately if (this.queue.length > 0) { return this.collectBatch(); @@ -575,7 +617,7 @@ export class MessageQueue2 { /** * 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 }> } | null { + private collectBatch(): { message: string, mode: T, hash: string, isolate: boolean, items: Array<{ message: string, localId?: string, internal?: boolean }> } | null { if (this.queue.length === 0) { return null; } @@ -587,7 +629,7 @@ export class MessageQueue2 { // `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 }> = []; + const items: Array<{ message: string, localId?: string, internal?: boolean }> = []; let mode = firstItem.mode; let isolate = firstItem.isolate ?? false; const targetModeHash = firstItem.modeHash; @@ -596,7 +638,7 @@ export class MessageQueue2 { if (firstItem.isolate) { const item = this.queue.shift()!; sameModeMessages.push(item.message); - items.push({ message: item.message, localId: item.localId }); + items.push({ message: item.message, localId: item.localId, internal: item.internal }); if (item.localId) consumedLocalIds.push(item.localId); logger.debug(`[MessageQueue2] Collected isolated message with mode hash: ${targetModeHash}`); } else { @@ -606,7 +648,7 @@ export class MessageQueue2 { !this.queue[0].isolate) { const item = this.queue.shift()!; sameModeMessages.push(item.message); - items.push({ message: item.message, localId: item.localId }); + items.push({ message: item.message, localId: item.localId, internal: item.internal }); if (item.localId) consumedLocalIds.push(item.localId); } logger.debug(`[MessageQueue2] Collected batch of ${sameModeMessages.length} messages with mode hash: ${targetModeHash}`); diff --git a/web/README.md b/web/README.md index ff30e448..42ecdcd4 100644 --- a/web/README.md +++ b/web/README.md @@ -65,7 +65,7 @@ See `src/router.tsx` for route definitions. - Message thread with infinite scroll. - Composer for sending messages. - Permission mode and model selection for supported agents. - Cursor Auto uses CLI Auto for new/resumed sessions configured with Auto. When ACP does not advertise a literal Auto option, the session picker warns that switching back from a concrete model requires a restart; HAPI does not automatically restart an active session. + Cursor Auto uses CLI Auto for new/resumed sessions configured with Auto. Switching a live session to Auto when ACP does not advertise a literal Auto option relaunches the Cursor ACP process in place under `--model auto` while preserving the hub session id. - Session abort and handoff controls. - Codex **Continue planning** hides the current proposal's action menu locally and focuses the composer without sending a message or replacing its draft. diff --git a/web/src/components/SessionChat.tsx b/web/src/components/SessionChat.tsx index f6d77ceb..d9d59073 100644 --- a/web/src/components/SessionChat.tsx +++ b/web/src/components/SessionChat.tsx @@ -1156,8 +1156,7 @@ function SessionChatInner(props: SessionChatProps) { machineModels: machineCursorModelsState.availableModels, cliModelSkus: sessionCliModelSkus, sessionModel: props.session.model, - sessionCurrentModelId: cursorModelsState.currentModelId, - autoRestartLabel: t('session.modelChange.cursorAutoRestart') + sessionCurrentModelId: cursorModelsState.currentModelId }) }, [ agentFlavor, @@ -1165,8 +1164,7 @@ function SessionChatInner(props: SessionChatProps) { cursorModelsState.currentModelId, machineCursorModelsState.availableModels, sessionCliModelSkus, - props.session.model, - t + props.session.model ]) const agyModelsState = useAgyModels({ api: props.api, diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index c0c2c445..7d6a8070 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -184,7 +184,6 @@ export default { 'session.item.model': 'model', 'session.item.machine': 'machine', 'session.modelChange.pending': 'Changing…', - 'session.modelChange.cursorAutoRestart': 'Auto (switching back requires restart)', 'session.modelChange.pendingTooltip': 'The model will change when the current task finishes.', 'session.item.worktree': 'worktree', 'session.item.pending': 'pending', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 04c1f5f6..ad6bb153 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -184,7 +184,6 @@ export default { 'session.item.model': '模型', 'session.item.machine': '机器', 'session.modelChange.pending': '更改中…', - 'session.modelChange.cursorAutoRestart': 'Auto(切回需要重启)', 'session.modelChange.pendingTooltip': '当前任务完成后将更改模型。', 'session.item.worktree': '工作树', 'session.item.pending': '待处理', diff --git a/web/src/lib/sessionChatCursorModel.test.ts b/web/src/lib/sessionChatCursorModel.test.ts index 7bf1992e..ab1a2c9a 100644 --- a/web/src/lib/sessionChatCursorModel.test.ts +++ b/web/src/lib/sessionChatCursorModel.test.ts @@ -16,16 +16,27 @@ const sessionModels = [ ] as const describe('resolveSessionCursorModelChange', () => { - it.each([false, true])('labels the live Auto limitation only without native Auto (native=%s)', (nativeAuto) => { + it.each([false, true])('keeps Auto label without a restart warning (native=%s)', (nativeAuto) => { const picker = buildSessionCursorPickerState({ sessionModels: [{ modelId: nativeAuto ? 'auto' : 'default' }, ...sessionModels], machineModels: [{ modelId: 'auto' }], sessionModel: 'composer-2.5[fast=true]', + sessionCurrentModelId: 'composer-2.5[fast=true]' + }) + expect(picker.modelOptions.find(option => option.value === 'auto')?.label) + .toBe('Auto') + }) + + it('still supports an optional Auto restart label for callers that need it', () => { + const picker = buildSessionCursorPickerState({ + sessionModels: [{ modelId: 'default' }, ...sessionModels], + machineModels: [{ modelId: 'auto' }], + sessionModel: 'composer-2.5[fast=true]', sessionCurrentModelId: 'composer-2.5[fast=true]', autoRestartLabel: 'Auto (switching back requires restart)' }) expect(picker.modelOptions.find(option => option.value === 'auto')?.label) - .toBe(nativeAuto ? 'Auto' : 'Auto (switching back requires restart)') + .toBe('Auto (switching back requires restart)') }) const picker = buildSessionCursorPickerState({