diff --git a/packages/cli/src/acp-integration/session/Session.review-lease.test.ts b/packages/cli/src/acp-integration/session/Session.review-lease.test.ts index 803944b452..656cd1beb5 100644 --- a/packages/cli/src/acp-integration/session/Session.review-lease.test.ts +++ b/packages/cli/src/acp-integration/session/Session.review-lease.test.ts @@ -95,6 +95,7 @@ describe('Session review-worktree lease sweep', () => { beginManagedAutoMemoryRecall: vi.fn(), consumeManagedAutoMemoryRecall: vi.fn().mockResolvedValue(null), finishManagedAutoMemoryRecall: vi.fn(), + captureCacheSafeParams: vi.fn(), recordCompletedToolCall: vi.fn(), }; diff --git a/packages/cli/src/acp-integration/session/Session.test.ts b/packages/cli/src/acp-integration/session/Session.test.ts index 843171779f..2c13f53be6 100644 --- a/packages/cli/src/acp-integration/session/Session.test.ts +++ b/packages/cli/src/acp-integration/session/Session.test.ts @@ -555,6 +555,7 @@ describe('Session', () => { beginManagedAutoMemoryRecall: ReturnType; consumeManagedAutoMemoryRecall: ReturnType; finishManagedAutoMemoryRecall: ReturnType; + captureCacheSafeParams: ReturnType; recordCompletedToolCall: ReturnType; }; let mockMemoryManager: { @@ -809,6 +810,7 @@ describe('Session', () => { beginManagedAutoMemoryRecall: vi.fn(), consumeManagedAutoMemoryRecall: vi.fn().mockResolvedValue(null), finishManagedAutoMemoryRecall: vi.fn(), + captureCacheSafeParams: vi.fn(), recordCompletedToolCall: vi.fn(), }; mockMemoryManager = { @@ -2944,6 +2946,15 @@ describe('Session', () => { expect.any(AbortSignal), ); expect(textParts(firstSentMessage())).toEqual([memoryPrompt, 'hello']); + // Captured twice: once inside `#recordPromptCompletionEffects` (before + // `scheduleExtract`, pinned below) and once at the turn boundary that + // feeds the follow-up suggestion. + expect(mockLlmClient.captureCacheSafeParams).toHaveBeenCalledTimes(2); + expect( + mockLlmClient.captureCacheSafeParams.mock.invocationCallOrder[0], + ).toBeLessThan( + mockMemoryManager.scheduleExtract.mock.invocationCallOrder[0]!, + ); expect(mockMemoryManager.scheduleExtract).toHaveBeenCalledWith({ projectRoot: '/repo', sessionId: 'test-session-id', @@ -3040,6 +3051,11 @@ describe('Session', () => { expect(mockLlmClient.beginManagedAutoMemoryRecall).not.toHaveBeenCalled(); expect(mockMemoryManager.scheduleExtract).not.toHaveBeenCalled(); expect(mockMemoryManager.scheduleDream).not.toHaveBeenCalled(); + // A retry skips managed auto-memory, but the turn still ends `end_turn`, + // so the follow-up suggestion fires and reads the process-global + // cache-safe slot. The turn boundary has to refresh it anyway, or the + // suggestion is generated from a transcript missing this turn. + expect(mockLlmClient.captureCacheSafeParams).toHaveBeenCalledOnce(); mockChat.sendMessageStream = vi .fn() @@ -3054,6 +3070,9 @@ describe('Session', () => { expect(mockLlmClient.beginManagedAutoMemoryRecall).toHaveBeenCalledOnce(); expect(mockMemoryManager.scheduleExtract).not.toHaveBeenCalled(); expect(mockMemoryManager.scheduleDream).not.toHaveBeenCalled(); + // A failed turn never reaches the success path, so it must not publish + // its partial transcript as cache-safe. + expect(mockLlmClient.captureCacheSafeParams).toHaveBeenCalledOnce(); expect( mockLlmClient.finishManagedAutoMemoryRecall, ).toHaveBeenCalledOnce(); diff --git a/packages/cli/src/acp-integration/session/Session.ts b/packages/cli/src/acp-integration/session/Session.ts index 31781d1df9..dc2d95bb62 100644 --- a/packages/cli/src/acp-integration/session/Session.ts +++ b/packages/cli/src/acp-integration/session/Session.ts @@ -5361,6 +5361,19 @@ export class Session implements SessionContext { // Drain any cron prompts that queued while the prompt was active void this.#drainCronQueue(); void this.#drainNotificationQueue(); + // Refresh the process-global cache-safe slot at the turn boundary. + // `#recordPromptCompletionEffects` only captures on a fresh user turn + // with managed auto-memory on, but the slot's other consumer — + // `generatePromptSuggestion`, reached through + // `#maybeEmitFollowupSuggestion` below — has no freshness check and + // prefers the slot over the live history tail it is handed. Without + // this, a continue/retry turn that still ends `end_turn` would get a + // suggestion generated from a transcript missing that turn. Mirrors the + // interactive path, which captures on every main turn in + // `LlmClient.sendMessageStream`. + if (completedResult.stopReason === 'end_turn') { + this.config.getLlmClient().captureCacheSafeParams(); + } this.#maybeEmitFollowupSuggestion(completedResult); if (channelDelivery && completedResult.stopReason === 'end_turn') { this.#scheduleChannelDelivery({ @@ -8760,6 +8773,7 @@ export class Session implements SessionContext { ) { return; } + this.config.getLlmClient().captureCacheSafeParams(); const memoryManager = this.config.getMemoryManager(); const history = this.#getCurrentChat().getHistoryShallow(); void memoryManager diff --git a/packages/cli/src/acp-integration/session/Session.worktree.test.ts b/packages/cli/src/acp-integration/session/Session.worktree.test.ts index bee652dfcf..d99608b02a 100644 --- a/packages/cli/src/acp-integration/session/Session.worktree.test.ts +++ b/packages/cli/src/acp-integration/session/Session.worktree.test.ts @@ -106,6 +106,7 @@ describe('Session.pendingWorktreeNotice', () => { beginManagedAutoMemoryRecall: vi.fn(), consumeManagedAutoMemoryRecall: vi.fn().mockResolvedValue(null), finishManagedAutoMemoryRecall: vi.fn(), + captureCacheSafeParams: vi.fn(), recordCompletedToolCall: vi.fn(), }; diff --git a/packages/core/src/core/client.ts b/packages/core/src/core/client.ts index 3a043672b3..f59c7895ad 100644 --- a/packages/core/src/core/client.ts +++ b/packages/core/src/core/client.ts @@ -1355,6 +1355,26 @@ export class LlmClient { } } + /** @internal */ + captureCacheSafeParams(): void { + try { + const chat = this.getChat(); + const historyForCache = this.getHistoryTailShallow(40, true); + const cachedHistory = slimCompactionInput( + historyForCache, + this.config.getEffectiveInputModalities(), + ).slimmedHistory; + saveCacheSafeParams( + chat.getGenerationConfig(), + cachedHistory, + this.config.getModel(), + this.config.getSessionId(), + ); + } catch { + // Best-effort — don't block the main flow + } + } + /** @internal */ consumeManagedAutoMemoryRecall( deliveryPoint: 'initial' | 'tool_result', @@ -4836,26 +4856,7 @@ export class LlmClient { // Save cache-safe params here — before any early return — so that // background readers calling getCacheSafeParams(sessionId) can see the // current turn's history regardless of which path exits below. - try { - const chat = this.getChat(); - const maxHistoryForCache = 40; - const historyForCache = this.getHistoryTailShallow( - maxHistoryForCache, - true, - ); - const cachedHistory = slimCompactionInput( - historyForCache, - this.config.getEffectiveInputModalities(), - ).slimmedHistory; - saveCacheSafeParams( - chat.getGenerationConfig(), - cachedHistory, - this.config.getModel(), - this.config.getSessionId(), - ); - } catch { - // Best-effort — don't block the main flow - } + this.captureCacheSafeParams(); if (this.config.getSkipNextSpeakerCheck()) { if (!isGoalRuntimeTurn) { diff --git a/packages/core/src/memory/manager.test.ts b/packages/core/src/memory/manager.test.ts index d91210befb..5ac3972b0c 100644 --- a/packages/core/src/memory/manager.test.ts +++ b/packages/core/src/memory/manager.test.ts @@ -127,6 +127,36 @@ describe('MemoryManager', () => { await fs.rm(tempDir, { recursive: true, force: true }); }); + it('does not emit an unhandled rejection when the caller handles a failed extraction', async () => { + const failure = new Error('extract failed'); + const unhandled = vi.fn(); + vi.mocked(runAutoMemoryExtract).mockRejectedValueOnce(failure); + process.on('unhandledRejection', unhandled); + + try { + const mgr = new MemoryManager(); + await expect( + mgr.scheduleExtract({ + projectRoot, + sessionId: 'sess', + history: [{ role: 'user', parts: [{ text: 'hi' }] }], + }), + ).rejects.toBe(failure); + await new Promise((resolve) => setImmediate(resolve)); + + expect(unhandled).not.toHaveBeenCalled(); + // The rejection handler must still untrack the task. Hollowing it out + // to `() => {}` keeps the assertion above green while the settled + // promise and its task id leak for the process lifetime — `inFlight` + // has no other delete site and no `clear()`. + expect( + (mgr as unknown as { inFlight: Map }).inFlight.size, + ).toBe(0); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + it('runs extract and records a completed task', async () => { vi.mocked(runAutoMemoryExtract).mockResolvedValue({ touchedTopics: ['user'], diff --git a/packages/core/src/memory/manager.ts b/packages/core/src/memory/manager.ts index 5f171fb745..55a8dcd477 100644 --- a/packages/core/src/memory/manager.ts +++ b/packages/core/src/memory/manager.ts @@ -582,7 +582,10 @@ export class MemoryManager { private track(taskId: string, promise: Promise): Promise { this.inFlight.set(taskId, promise); - void promise.finally(() => this.inFlight.delete(taskId)); + void promise.then( + () => this.inFlight.delete(taskId), + () => this.inFlight.delete(taskId), + ); return promise; }