From 2a72b49cec311faa81eb58df429a050f7a4a0c98 Mon Sep 17 00:00:00 2001 From: Roomote Date: Wed, 25 Nov 2026 14:51:23 +0000 Subject: [PATCH 1/4] fix(task): keep one saved tool-result turn across empty-response retries (#2691) --- .../tla/ToolResultRetry.Current.cfg | 8 + docs/architecture/tla/ToolResultRetry.cfg | 8 + docs/architecture/tla/ToolResultRetry.tla | 180 ++++++ src/core/task/Task.ts | 40 +- src/core/task/__tests__/Task.spec.ts | 11 +- .../__tests__/empty-response-history.spec.ts | 594 ++++++++++++++++++ src/core/task/apiConversationHistory.ts | 23 +- 7 files changed, 854 insertions(+), 10 deletions(-) create mode 100644 docs/architecture/tla/ToolResultRetry.Current.cfg create mode 100644 docs/architecture/tla/ToolResultRetry.cfg create mode 100644 docs/architecture/tla/ToolResultRetry.tla create mode 100644 src/core/task/__tests__/empty-response-history.spec.ts diff --git a/docs/architecture/tla/ToolResultRetry.Current.cfg b/docs/architecture/tla/ToolResultRetry.Current.cfg new file mode 100644 index 00000000000..a83b69e80d4 --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.Current.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "Fresh" + MaxCalls = 1 + MaxEmpty = 2 + MaxMints = 4 +INVARIANTS TypeOK OneResultPerCall ResultNeverLost +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.cfg b/docs/architecture/tla/ToolResultRetry.cfg new file mode 100644 index 00000000000..cee59f4c5a5 --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "Stable" + MaxCalls = 1 + MaxEmpty = 2 + MaxMints = 4 +INVARIANTS TypeOK OneResultPerCall ResultNeverLost +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.tla b/docs/architecture/tla/ToolResultRetry.tla new file mode 100644 index 00000000000..a499175923a --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.tla @@ -0,0 +1,180 @@ +---- MODULE ToolResultRetry ---- +\* Models the empty-assistant-response retry in recursivelyMakeClineRequests +\* (src/core/task/Task.ts) and the merge save in saveApiMessages and +\* mergeApiMessageSnapshots (src/core/task-persistence/mergeMessageSnapshots.ts). +\* Source: the retry pops the saved user tool-result turn from memory and re-adds +\* it. Decline restores it too. Sink: a reload turns every saved user-result +\* record into one outgoing tool_result block (mergeConsecutiveApiMessages then +\* convertToOpenAiMessages). The conversion is one-to-one on records, so the +\* model counts records. +\* Failure: the retry mints a fresh message identity, so the merge save keeps the +\* disk-only record. The reloaded history then sends two tool_result blocks for +\* one tool_use id and the provider returns HTTP 400 (issue 2691). +\* Invariant OneResultPerCall: no tool call has two saved result records. +\* Invariant ResultNeverLost: when the turn ends, every issued call still has its +\* saved result, so the fix cannot repair the duplicate by losing the result. +\* Modes: Fresh mints a new identity on every retry and decline (the code before +\* the fix). Stable restores the popped record with its identity (the fix). +\* Expected before the run: Fresh fails OneResultPerCall at the retry save. The +\* trace is NewTurn, Result, EmptyResponse, RetryReAdd. Stable holds every +\* invariant. +\* Configs: ToolResultRetry.cfg (Stable) must pass. ToolResultRetry.Current.cfg +\* (Fresh) must fail. +\* Not modeled: message content, timestamps beyond identity order, condense and +\* truncation tags, the first-chunk and mid-stream retry paths (they never +\* recreate the turn), and the two flush defects of issue 2691. Those need a +\* different fix and stay in the issue. +\* Cost: each run takes under 5 seconds. Agent time is not measured. +\* Result: ToolResultRetry.cfg (Stable) holds with 10 distinct states. +\* ToolResultRetry.Current.cfg (Fresh) fails OneResultPerCall at the retry save, +\* in 5 states. The counterexample is AddAssistant, AddUserResult, EmptyResponse, +\* RetryReAdd with a fresh identity. It matches the issue replay steps 1 and +\* 3 to 5 on the real code. ResultNeverLost holds in both modes, so the fix +\* must merge by identity, not discard results. +\* Findings: 0 covered, 1 added (the retry identity choice), 0 gap. The failing +\* replay and the stable-identity control were recreated from the issue, so no +\* prior finding exists to cover. + +EXTENDS Naturals, FiniteSets, Sequences + +CONSTANTS Mode, MaxCalls, MaxEmpty, MaxMints + +URec(c, m) == [kind |-> "u", call |-> c, mid |-> m] +ARec(m) == [kind |-> "a", call |-> 0, mid |-> m] +NoRec == [kind |-> "none", call |-> 0, mid |-> 0] + +RecordSet == + {ARec(m) : m \in 0..(MaxMints - 1)} + \cup {URec(c, m) : c \in 1..MaxCalls, m \in 0..(MaxMints - 1)} + +VARIABLES mem, disk, popped, nextMid, empties, done +vars == <> + +MemMids(mm) == {mm[i].mid : i \in 1..Len(mm)} +MemSet(mm) == {mm[i] : i \in 1..Len(mm)} + +\* The ordinary merge save: a memory record replaces its disk match by identity, +\* and records that exist only on disk stay. +MergeSave(memN) == {r \in disk : ~r.mid \in MemMids(memN)} \cup MemSet(memN) + +\* A new assistant turn with a tool call is saved. +AddAssistant == + /\ ~done + /\ Len(mem) = 0 + /\ nextMid < MaxMints + /\ mem' = Append(mem, ARec(nextMid)) + /\ nextMid' = nextMid + 1 + /\ disk' = MergeSave(mem') + /\ UNCHANGED <> + +\* The tool ran. The user turn with its tool result is saved. A fresh turn is +\* minted only when no removed turn awaits restoration; mid-retry the only +\* user-turn add is the restore. +AddUserResult(c) == + /\ ~done + /\ Len(mem) = 1 + /\ popped = NoRec + /\ nextMid < MaxMints + /\ mem' = Append(mem, URec(c, nextMid)) + /\ nextMid' = nextMid + 1 + /\ disk' = MergeSave(mem') + /\ UNCHANGED <> + +\* The model sent no assistant content. The saved user turn is popped from +\* memory. The disk copy stays. +EmptyResponse == + /\ ~done + /\ empties < MaxEmpty + /\ Len(mem) >= 2 + /\ mem[Len(mem)].kind = "u" + /\ popped' = mem[Len(mem)] + /\ empties' = empties + 1 + /\ mem' = SubSeq(mem, 1, Len(mem) - 1) + /\ UNCHANGED <> + +\* The retry re-adds the turn and saves. Stable keeps the saved identity, so the +\* merge save replaces the disk record. Fresh mints a new identity, so the merge +\* save keeps both records. +RetryReAdd(c) == + /\ ~done + /\ popped # NoRec + /\ LET restored == IF Mode = "Stable" THEN popped ELSE URec(c, nextMid) + replaced == IF Mode = "Stable" THEN popped.mid ELSE nextMid + IN /\ Mode = "Stable" \/ nextMid < MaxMints + /\ mem' = Append(mem, restored) + /\ nextMid' = IF Mode = "Stable" THEN nextMid ELSE nextMid + 1 + /\ disk' = {r \in disk : r.mid # replaced} \cup MemSet(mem') + /\ popped' = NoRec + /\ UNCHANGED <> + +\* The user declines the retry. The popped turn is restored with its identity, +\* then a synthetic failure turn is saved and the turn ends. +RetryDeclined(c) == + /\ ~done + /\ popped # NoRec + /\ nextMid + 1 < MaxMints + /\ LET restored == IF Mode = "Stable" THEN popped ELSE URec(c, nextMid) + nextAfter == IF Mode = "Stable" THEN nextMid ELSE nextMid + 1 + afterRestore == Append(Append(mem, restored), ARec(nextAfter)) + IN /\ mem' = afterRestore + /\ nextMid' = nextAfter + 1 + /\ disk' = {r \in disk : ~r.mid \in MemMids(mem')} \cup MemSet(mem') + /\ popped' = NoRec + /\ done' = TRUE + /\ UNCHANGED <> + +\* The retry gets a real assistant response. The turn ends. +CompleteTurn == + /\ ~done + /\ Len(mem) >= 2 + /\ mem[Len(mem)].kind = "u" + /\ nextMid < MaxMints + /\ mem' = Append(mem, ARec(nextMid)) + /\ nextMid' = nextMid + 1 + /\ disk' = MergeSave(mem') + /\ done' = TRUE + /\ UNCHANGED <> + +Init == + /\ mem = <<>> + /\ disk = {} + /\ popped = NoRec + /\ nextMid = 0 + /\ empties = 0 + /\ done = FALSE + +Next == + \/ AddAssistant + \/ \E c \in 1..MaxCalls : + \/ AddUserResult(c) + \/ RetryReAdd(c) + \/ RetryDeclined(c) + \/ EmptyResponse + \/ CompleteTurn + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ \A i \in 1..Len(mem) : mem[i] \in RecordSet + /\ disk \subseteq RecordSet + /\ popped \in RecordSet \cup {NoRec} + /\ nextMid \in Nat + /\ nextMid =< MaxMints + /\ empties \in Nat + /\ empties =< MaxEmpty + /\ done \in BOOLEAN + +\* The opposite of the failure: the saved history holds at most one result +\* record per tool call, so a reload sends one tool_result per tool_use id. +OneResultPerCall == + \A c \in 1..MaxCalls : + Cardinality({r \in disk : r.kind = "u" /\ r.call = c}) <= 1 + +\* The fix must not lose the result: when the turn ends, every issued call +\* still has its saved result. +ResultNeverLost == + done => + \A c \in 1..MaxCalls : + Cardinality({r \in disk : r.kind = "u" /\ r.call = c}) = 1 + +==== diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 3b2771ddfa7..e5939ad2db3 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -1451,7 +1451,11 @@ export class Task extends EventEmitter implements TaskLike { * Appends an API turn and records whether an assistant turn reached persistent storage. * If the message resolves a pending action, retries the save on initial failure before clearing the action. */ - private async addToApiConversationHistory(message: Anthropic.MessageParam, reasoning?: string): Promise { + private async addToApiConversationHistory( + message: Anthropic.MessageParam, + reasoning?: string, + options?: { identity?: { messageId?: string; ts?: number } }, + ): Promise { const resolvesPendingAction = this.pendingAction && message.role === "user" && @@ -1466,6 +1470,7 @@ export class Task extends EventEmitter implements TaskLike { api: this.api, apiConfiguration: this.apiConfiguration, apiConversationHistory: this.apiConversationHistory, + identity: options?.identity, }), ) @@ -4013,6 +4018,7 @@ export class Task extends EventEmitter implements TaskLike { includeFileDetails: boolean retryAttempt?: number userMessageWasRemoved?: boolean // Track if user message was removed due to empty response + removedUserMessage?: ApiMessage // The saved record removed for the empty-response retry, restored with its identity } const stack: StackItem[] = [ @@ -4126,7 +4132,17 @@ export class Task extends EventEmitter implements TaskLike { userMessageWasRemoved: currentItem.userMessageWasRemoved, }) if (shouldAddUserMessage) { - await this.addToApiConversationHistory({ role: "user", content: finalUserContent }) + if (currentItem.removedUserMessage) { + await this.addToApiConversationHistory({ role: "user", content: finalUserContent }, undefined, { + // A retry after an empty assistant response restores a turn that is + // still saved on disk. Reusing its identity makes the merge save + // replace that record instead of keeping both turns, so the + // reloaded history holds exactly one result per tool_use id. + identity: currentItem.removedUserMessage, + }) + } else { + await this.addToApiConversationHistory({ role: "user", content: finalUserContent }) + } this.messageCounts.user++ } @@ -5268,9 +5284,14 @@ export class Task extends EventEmitter implements TaskLike { // or flushPendingToolResultsToHistory message) there is nothing to // remove, and popping would corrupt history. let removedCurrentUserMessage = false + let removedUserMessage: ApiMessage | undefined if (shouldAddUserMessage && this.apiConversationHistory.length > 0) { const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1] if (lastMessage.role === "user") { + // Keep the saved record: the retry restores this exact identity so + // the merge save replaces the on-disk copy instead of adding a + // second turn with the same tool results (issue #2691). + removedUserMessage = lastMessage this.apiConversationHistory.pop() this.messageCounts.user-- removedCurrentUserMessage = true @@ -5304,6 +5325,7 @@ export class Task extends EventEmitter implements TaskLike { includeFileDetails: false, retryAttempt: (currentItem.retryAttempt ?? 0) + 1, userMessageWasRemoved: removedCurrentUserMessage, + removedUserMessage, }) // Continue to retry the request @@ -5325,6 +5347,7 @@ export class Task extends EventEmitter implements TaskLike { includeFileDetails: false, retryAttempt: (currentItem.retryAttempt ?? 0) + 1, userMessageWasRemoved: removedCurrentUserMessage, + removedUserMessage, }) // Continue to retry the request @@ -5333,10 +5356,15 @@ export class Task extends EventEmitter implements TaskLike { // User declined to retry. Re-add the user message only if this // iteration removed one, so the history and counter stay consistent. if (removedCurrentUserMessage) { - await this.addToApiConversationHistory({ - role: "user", - content: currentUserContent, - }) + // Restore the already saved record with its original identity so + // the merge save keeps one copy of the turn on disk. + await this.addToApiConversationHistory( + removedUserMessage + ? { role: "user", content: removedUserMessage.content } + : { role: "user", content: currentUserContent }, + undefined, + { identity: removedUserMessage }, + ) this.messageCounts.user++ } diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index cea34e05d1c..e644e2bce09 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -535,8 +535,17 @@ describe("Cline", () => { const result = await task.recursivelyMakeClineRequests([{ type: "text", text: "original user request" }]) expect(result).toBe(false) + // The decline path restores the exact record that was saved for the failed + // attempt (original identity and content, including the environment-details + // block) so persistence keeps one copy of the turn (issue #2691). expect(task.apiConversationHistory).toMatchObject([ - { role: "user", content: [{ type: "text", text: "original user request" }] }, + { + role: "user", + content: [ + { type: "text", text: "original user request" }, + { type: "text", text: "" }, + ], + }, { role: "assistant", content: [{ type: "text", text: "Failure: I did not provide a response." }] }, ]) expect(task.messageCounts).toEqual({ user: 1, assistant: 1 }) diff --git a/src/core/task/__tests__/empty-response-history.spec.ts b/src/core/task/__tests__/empty-response-history.spec.ts new file mode 100644 index 00000000000..60e2692a8c5 --- /dev/null +++ b/src/core/task/__tests__/empty-response-history.spec.ts @@ -0,0 +1,594 @@ +import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker" +// cd src && npx vitest run core/task/__tests__/empty-response-history.spec.ts +// +// Regression for issue 2691: an empty assistant response pops the saved user +// tool-result turn from memory and the retry re-adds it. The retry must restore +// the saved identity so the merge save keeps one copy of the turn on disk, and +// the reloaded history must convert to exactly one tool_result per tool_use id. +// The suite drives the real retry branch in recursivelyMakeClineRequests with +// real temporary-file saves and readback; the provider stream is stubbed at +// attemptApiRequest. + +import * as fsp from "fs/promises" +import * as os from "os" +import * as path from "path" + +import * as vscode from "vscode" +import type { Anthropic } from "@anthropic-ai/sdk" +import type OpenAI from "openai" + +import { providerIdentifiers, type GlobalState, type ModelInfo, type ProviderSettings } from "@roo-code/types" +import { TelemetryService } from "@roo-code/telemetry" + +import { Task } from "../Task" +import { ClineProvider } from "../../webview/ClineProvider" +import { ContextProxy } from "../../config/ContextProxy" +import { readApiMessages, type ApiMessage } from "../../task-persistence" +import { getEffectiveApiHistory } from "../../condense" +import { mergeConsecutiveApiMessages } from "../mergeConsecutiveApiMessages" +import { convertToOpenAiMessages } from "../../../api/transform/openai-format" +import { setAbortLatch } from "../../../test-utils/run-state" +import type { ApiStreamChunk } from "../../../api/transform/stream" +import * as safeWriteJsonModule from "../../../utils/safeWriteJson" + +vi.mock("delay", () => ({ + __esModule: true, + default: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("execa", () => ({ + execa: vi.fn(), +})) + +// Task tests do not exercise indexing; keep workspace resolution and its cache out of this suite. +vi.mock("../../../services/code-index/code-index-manager-registry", () => ({ + CodeIndexManagerRegistry: { + getOrCreate: vi.fn().mockReturnValue(undefined), + getAllInstances: vi.fn().mockReturnValue([]), + disposeAll: vi.fn(), + }, +})) + +vi.mock("p-wait-for", () => ({ + default: vi.fn().mockImplementation(async () => Promise.resolve()), +})) + +vi.mock("vscode", () => { + const mockDisposable = { dispose: vi.fn() } + const mockEventEmitter = { event: vi.fn(), fire: vi.fn() } + const mockTextDocument = { uri: { fsPath: "/mock/workspace/path/file.ts" } } + const mockTextEditor = { document: mockTextDocument } + const mockTab = { input: { uri: { fsPath: "/mock/workspace/path/file.ts" } } } + const mockTabGroup = { tabs: [mockTab] } + + return { + TabInputTextDiff: vi.fn(), + CodeActionKind: { + QuickFix: { value: "quickfix" }, + RefactorRewrite: { value: "refactor.rewrite" }, + }, + window: { + createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }), + visibleTextEditors: [mockTextEditor], + tabGroups: { + all: [mockTabGroup], + close: vi.fn(), + onDidChangeTabs: vi.fn(() => ({ dispose: vi.fn() })), + }, + showErrorMessage: vi.fn(), + }, + workspace: { + workspaceFolders: [ + { + uri: { fsPath: "/mock/workspace/path" }, + name: "mock-workspace", + index: 0, + }, + ], + createFileSystemWatcher: vi.fn(() => ({ + onDidCreate: vi.fn(() => mockDisposable), + onDidDelete: vi.fn(() => mockDisposable), + onDidChange: vi.fn(() => mockDisposable), + dispose: vi.fn(), + })), + fs: { + stat: vi.fn().mockResolvedValue({ type: 1 }), + }, + onDidSaveTextDocument: vi.fn(() => mockDisposable), + getConfiguration: vi.fn(() => ({ get: (_key: string, defaultValue: unknown) => defaultValue })), + }, + env: { + uriScheme: "vscode", + language: "en", + }, + EventEmitter: vi.fn().mockImplementation(function () { + return mockEventEmitter + }), + Disposable: { + from: vi.fn(), + }, + TabInputText: vi.fn(), + } +}) + +vi.mock("../../mentions", () => ({ + parseMentions: vi.fn().mockImplementation((text: string) => { + return Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] }) + }), + openMention: vi.fn(), + getLatestTerminalOutput: vi.fn(), +})) + +vi.mock("../../../integrations/misc/extract-text", () => ({ + extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"), +})) + +vi.mock("../../environment/getEnvironmentDetails", () => ({ + getEnvironmentDetails: vi.fn().mockResolvedValue(""), +})) + +vi.mock("../../ignore/RooIgnoreController") + +type TaskRetryProbe = { + addToApiConversationHistory: (message: Anthropic.MessageParam, reasoning?: string) => Promise + safeEnsureModelFetched: () => Promise + backoffAndAnnounce: (retryAttempt: number, error: unknown) => Promise + globalStoragePath: string +} + +// Private members the replay drives directly; the double provides only these. +const probe = (task: Task): TaskRetryProbe => task as unknown as TaskRetryProbe + +type TaskAskResult = Awaited> +type ProviderState = Awaited> + +const stubModelInfo: ModelInfo = { + contextWindow: 200_000, + maxTokens: 8_192, + supportsPromptCache: true, +} + +const TOOL_USE_ID = "toolu_retry_01" + +function stream(chunks: ApiStreamChunk[]): AsyncGenerator { + return (async function* () { + yield* chunks + })() +} + +/** The tool_use assistant turn and its saved user result turn in the disk history. */ +function findResultMessage(messages: ApiMessage[], toolUseId: string): ApiMessage | undefined { + return messages.find( + (message) => + message.role === "user" && + Array.isArray(message.content) && + message.content.some((block) => block.type === "tool_result" && block.tool_use_id === toolUseId), + ) +} + +function countSavedResults(messages: ApiMessage[], toolUseId: string): number { + return messages.reduce((count, message) => { + if (message.role !== "user" || !Array.isArray(message.content)) { + return count + } + return ( + count + + message.content.filter((block) => block.type === "tool_result" && block.tool_use_id === toolUseId).length + ) + }, 0) +} + +/** The sink chain a resumed task uses: effective history, user-turn merge, then the provider conversion. */ +function outgoingToolResultCount(messages: ApiMessage[], toolUseId: string): number { + const effective = getEffectiveApiHistory(messages) + const merged = mergeConsecutiveApiMessages(effective, { roles: ["user"] }) + const payload: OpenAI.Chat.ChatCompletionMessageParam[] = convertToOpenAiMessages(merged) + return payload.filter((message) => message.role === "tool" && message.tool_call_id === toolUseId).length +} + +async function readDiskHistory(task: Task): Promise { + return readApiMessages({ taskId: task.taskId, globalStoragePath: probe(task).globalStoragePath }) +} + +describe("empty-response history persistence (issue 2691)", () => { + let tempRoot: string + let mockProvider: ClineProvider + let mockApiConfig: ProviderSettings + let mockOutputChannel: vscode.OutputChannel + let mockExtensionContext: vscode.ExtensionContext + let baseProviderState: ProviderState + + const providerStateWith = (overrides: Partial = {}): ProviderState => ({ + ...baseProviderState, + mcpEnabled: false, + ...overrides, + }) + + beforeEach(async () => { + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + + tempRoot = await fsp.mkdtemp(path.join(os.tmpdir(), "empty-response-history-")) + + mockExtensionContext = { + globalState: { + get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined), + update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()), + keys: vi.fn().mockReturnValue([]), + }, + globalStorageUri: { fsPath: tempRoot }, + workspaceState: { + get: vi.fn().mockImplementation((_key) => undefined), + update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()), + keys: vi.fn().mockReturnValue([]), + }, + secrets: { + get: vi.fn().mockImplementation((_key) => Promise.resolve(undefined)), + store: vi.fn().mockImplementation((_key, _value) => Promise.resolve()), + delete: vi.fn().mockImplementation((_key) => Promise.resolve()), + }, + extensionUri: { fsPath: path.join(tempRoot, "extension") }, + extension: { + packageJSON: { + version: "1.0.0", + }, + }, + } as unknown as vscode.ExtensionContext + + mockOutputChannel = { + name: "test-output", + appendLine: vi.fn(), + append: vi.fn(), + replace: vi.fn(), + clear: vi.fn(), + show: vi.fn(), + hide: vi.fn(), + dispose: vi.fn(), + } as unknown as vscode.OutputChannel + + // The provider double overrides every webview and history method the loop + // touches; no real webview exists in vitest. + mockProvider = new ClineProvider( + mockExtensionContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockExtensionContext), + new WebviewFocusTracker(), + ) as unknown as ClineProvider + const providerDouble = mockProvider as unknown as Record + providerDouble.postMessageToWebview = vi.fn().mockResolvedValue(undefined) + providerDouble.postStateToWebview = vi.fn().mockResolvedValue(undefined) + providerDouble.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined) + providerDouble.postStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined) + providerDouble.flushPostStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined) + providerDouble.updateTaskHistory = vi.fn().mockResolvedValue(undefined) + providerDouble.log = vi.fn() + providerDouble.getTaskWithId = vi.fn() + + baseProviderState = providerStateWith(await mockProvider.getState()) + + mockApiConfig = { + apiProvider: providerIdentifiers.anthropic, + apiModelId: "claude-3-5-sonnet-20241022", + apiKey: "test-api-key", + } + }) + + afterEach(async () => { + await fsp.rm(tempRoot, { recursive: true, force: true }) + }) + + interface SeedOptions { + autoApprovalEnabled: boolean + } + + /** Seeds user -> assistant(tool_use) through the production history path with real saves. */ + async function createTaskWithSavedToolUse({ autoApprovalEnabled }: SeedOptions): Promise { + vi.spyOn(mockProvider, "getState").mockResolvedValue( + providerStateWith({ autoApprovalEnabled, requestDelaySeconds: 0 }), + ) + + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "empty-response history replay", + startTask: false, + }) + + vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined) + vi.spyOn(probe(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo) + + await probe(task).addToApiConversationHistory({ + role: "user", + content: [{ type: "text", text: "read the config file" }], + }) + await probe(task).addToApiConversationHistory({ + role: "assistant", + content: [{ type: "tool_use", id: TOOL_USE_ID, name: "read_file", input: { path: "config.json" } }], + }) + return task + } + + /** The mid-task loop entry: the pending tool result turn for the saved tool call. */ + function toolResultUserContent(): Anthropic.Messages.ContentBlockParam[] { + return [{ type: "tool_result", tool_use_id: TOOL_USE_ID, content: "file contents" }] + } + + /** + * First-attempt stream that reads the saved result turn from disk while it is + * being consumed, which is before any empty-response pop can run. The identity + * reader is valid once the attempt has started. + */ + function firstAttemptCapturingSavedIdentity( + task: Task, + chunks: ApiStreamChunk[], + ): { + body: AsyncGenerator + identity: () => { messageId?: string; ts?: number } + } { + let captured: { messageId?: string; ts?: number } | undefined + const body = (async function* () { + const saved = findResultMessage(await readDiskHistory(task), TOOL_USE_ID) + captured = { messageId: saved?.messageId, ts: saved?.ts } + yield* chunks + })() + return { + body, + identity: () => { + expect(captured).toBeDefined() + return captured as { messageId?: string; ts?: number } + }, + } + } + + it("persists one result turn across an automatic empty-response retry with real files", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) + + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementationOnce(() => stream([{ type: "text", text: "retry succeeded" }])) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests(toolResultUserContent()) + + const beforeRetry = firstAttempt.identity() + + // One empty attempt, one retried attempt, then the no-tool-use continuation + // request that the final stub stops with a swallowed error. + expect(attemptApiRequestSpy).toHaveBeenCalledTimes(3) + // The retry reaches the request seam with its own incremented retry count. + expect(attemptApiRequestSpy).toHaveBeenNthCalledWith( + 2, + 1, + expect.objectContaining({ skipProviderRateLimit: true }), + ) + + const disk = await readDiskHistory(task) + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + // The restored turn keeps the identity it was saved with, so the merge save + // replaced the disk record instead of adding a second copy. + const afterRetry = findResultMessage(disk, TOOL_USE_ID) + expect(afterRetry?.messageId).toBe(beforeRetry.messageId) + expect(afterRetry?.ts).toBe(beforeRetry.ts) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + // The pop/restore cycle stays balanced: the retried turn counts once, plus + // the separate no-tool-use continuation turn. + expect(task.messageCounts.user).toBe(2) + }) + + it("keeps one result turn across repeated empty responses", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) + + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementationOnce(() => stream([])) + .mockImplementationOnce(() => stream([])) + .mockImplementationOnce(() => stream([{ type: "text", text: "finally answered" }])) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests(toolResultUserContent()) + + const beforeRetry = firstAttempt.identity() + + // Three empty attempts, one retried attempt, then the stopped continuation. + expect(attemptApiRequestSpy).toHaveBeenCalledTimes(5) + + const disk = await readDiskHistory(task) + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + const afterRetry = findResultMessage(disk, TOOL_USE_ID) + expect(afterRetry?.messageId).toBe(beforeRetry.messageId) + expect(afterRetry?.ts).toBe(beforeRetry.ts) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + }) + + it("keeps one result turn when the retry is declined and records the failure", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: false }) + + vi.spyOn(task, "ask").mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult) + vi.spyOn(task, "attemptApiRequest").mockImplementation(() => stream([])) + + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + const attemptSpy = vi.spyOn(task, "attemptApiRequest") + attemptSpy.mockImplementationOnce(() => firstAttempt.body) + attemptSpy.mockImplementation(() => stream([])) + + const result = await task.recursivelyMakeClineRequests(toolResultUserContent()) + + const beforeDecline = firstAttempt.identity() + expect(result).toBe(false) + + const disk = await readDiskHistory(task) + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + const restored = findResultMessage(disk, TOOL_USE_ID) + expect(restored?.messageId).toBe(beforeDecline.messageId) + expect(restored?.ts).toBe(beforeDecline.ts) + // The synthetic failure turn follows the restored user turn. + expect(disk.at(-1)).toMatchObject({ + role: "assistant", + content: [{ type: "text", text: "Failure: I did not provide a response." }], + }) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + expect(task.messageCounts).toEqual({ user: 1, assistant: 1 }) + }) + + it("keeps one result turn when the user confirms an explicit retry", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: false }) + + vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } satisfies TaskAskResult) + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementationOnce(() => stream([{ type: "text", text: "explicit retry worked" }])) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests(toolResultUserContent()) + + // One empty attempt, one retried attempt, then the stopped continuation. + expect(attemptApiRequestSpy).toHaveBeenCalledTimes(3) + + const disk = await readDiskHistory(task) + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + }) + + it("keeps the saved history valid when no empty response occurs (control)", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) + + const firstAttempt = firstAttemptCapturingSavedIdentity(task, [{ type: "text", text: "answered first try" }]) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementation(() => { + throw new Error("stop after first response") + }) + + await task.recursivelyMakeClineRequests(toolResultUserContent()) + + const beforeSave = firstAttempt.identity() + + // One answered attempt, then the no-tool-use continuation that the stub stops. + expect(attemptApiRequestSpy).toHaveBeenCalledTimes(2) + + const disk = await readDiskHistory(task) + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + const saved = findResultMessage(disk, TOOL_USE_ID) + expect(saved?.messageId).toBe(beforeSave.messageId) + expect(saved?.ts).toBe(beforeSave.ts) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + }) + + /** + * Fails the Nth save of the API conversation history (1-based, counting from + * now). The API history writes go through safeWriteJson, so a rejection there + * reaches saveApiConversationHistory without touching unrelated files. + */ + function injectApiHistorySaveFailure(failingWrite: number): { restore: () => void } { + const originalSafeWriteJson = safeWriteJsonModule.safeWriteJson + let apiHistoryWrites = 0 + const writeSpy = vi.spyOn(safeWriteJsonModule, "safeWriteJson") + writeSpy.mockImplementation(async (filePath, data, options) => { + if (String(filePath).includes("api_conversation_history.json")) { + apiHistoryWrites += 1 + if (apiHistoryWrites === failingWrite) { + throw Object.assign(new Error("injected save failure"), { code: "EACCES" }) + } + } + return originalSafeWriteJson(filePath, data, options) + }) + return { + restore: () => writeSpy.mockRestore(), + } + } + + it("keeps a single saved result when the retry restore save fails (fault injection)", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) + + // API-history saves from here: the first iteration's user turn, then the + // restore save after the empty-response pop. Fail the restore save. + const injection = injectApiHistorySaveFailure(2) + + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + vi.spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementationOnce(() => stream([{ type: "text", text: "retry succeeded" }])) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests(toolResultUserContent()) + + const beforeRetry = firstAttempt.identity() + injection.restore() + + const disk = await readDiskHistory(task) + // The failed restore still re-added the turn in memory, and the next merge + // save matched the original disk record by identity: one copy, result kept. + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + const afterRetry = findResultMessage(disk, TOOL_USE_ID) + expect(afterRetry?.messageId).toBe(beforeRetry.messageId) + expect(afterRetry?.ts).toBe(beforeRetry.ts) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + }) + + it("keeps a single saved result when a declined retry also hits a failed save (fault injection)", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: false }) + + // Fail the decline restore save; the synthetic failure turn save follows. + const injection = injectApiHistorySaveFailure(2) + + vi.spyOn(task, "ask").mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult) + + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + const attemptSpy = vi.spyOn(task, "attemptApiRequest") + attemptSpy.mockImplementationOnce(() => firstAttempt.body) + attemptSpy.mockImplementation(() => stream([])) + + const result = await task.recursivelyMakeClineRequests(toolResultUserContent()) + + const beforeDecline = firstAttempt.identity() + expect(result).toBe(false) + injection.restore() + + const disk = await readDiskHistory(task) + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + const restored = findResultMessage(disk, TOOL_USE_ID) + expect(restored?.messageId).toBe(beforeDecline.messageId) + expect(restored?.ts).toBe(beforeDecline.ts) + expect(disk.at(-1)).toMatchObject({ + role: "assistant", + content: [{ type: "text", text: "Failure: I did not provide a response." }], + }) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + }) + + it("keeps the saved history valid when the task is cancelled during the retry backoff", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) + + // Cancel during the automatic retry backoff, before the restore can run. + vi.spyOn(probe(task), "backoffAndAnnounce").mockImplementation(async () => { + setAbortLatch(task, true) + }) + vi.spyOn(task, "attemptApiRequest").mockImplementation(() => stream([])) + + const result = await task.recursivelyMakeClineRequests(toolResultUserContent()) + + expect(result).toBe(false) + + const disk = await readDiskHistory(task) + // The cancelled cycle restored nothing: the original saved turn stays alone. + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + }) +}) diff --git a/src/core/task/apiConversationHistory.ts b/src/core/task/apiConversationHistory.ts index cb358949f52..91f0a0d9ea7 100644 --- a/src/core/task/apiConversationHistory.ts +++ b/src/core/task/apiConversationHistory.ts @@ -22,6 +22,14 @@ interface PrepareApiConversationMessageOptions { api: ApiHandler apiConfiguration: ProviderSettings apiConversationHistory: ApiMessage[] + /** + * Reuse the identity (messageId + ts) of an already saved user turn instead + * of minting a fresh one. The empty-assistant-response retry restores a + * turn that is still on disk; a fresh identity would make the ordinary + * merge save retain both copies, and the reloaded history would then send + * two tool_result blocks for one tool_use id. + */ + identity?: { messageId?: string; ts?: number } } export function prepareApiConversationMessage({ @@ -30,12 +38,13 @@ export function prepareApiConversationMessage({ api, apiConfiguration, apiConversationHistory, + identity, }: PrepareApiConversationMessageOptions): ApiMessage { if (message.role === "assistant") { return prepareAssistantMessage(message, reasoning, api as ApiHistoryHandler, apiConfiguration) } - return prepareUserMessage(message, apiConversationHistory) + return prepareUserMessage(message, apiConversationHistory, identity) } function prepareAssistantMessage( @@ -118,7 +127,11 @@ function prepareAssistantMessage( return messageWithTs } -function prepareUserMessage(message: Anthropic.MessageParam, apiConversationHistory: ApiMessage[]): ApiMessage { +function prepareUserMessage( + message: Anthropic.MessageParam, + apiConversationHistory: ApiMessage[], + identity?: { messageId?: string; ts?: number }, +): ApiMessage { const effectiveHistoryForValidation = getEffectiveApiHistory(apiConversationHistory) const lastEffective = effectiveHistoryForValidation[effectiveHistoryForValidation.length - 1] const historyForValidation = lastEffective?.role === "assistant" ? effectiveHistoryForValidation : [] @@ -139,7 +152,11 @@ function prepareUserMessage(message: Anthropic.MessageParam, apiConversationHist } const validatedMessage = validateAndFixToolResultIds(messageToAdd, historyForValidation) - return { ...validatedMessage, messageId: crypto.randomUUID(), ts: Date.now() } + return { + ...validatedMessage, + messageId: identity?.messageId ?? crypto.randomUUID(), + ts: identity?.ts ?? Date.now(), + } } function prependContentBlock(message: any, block: any): void { From 5ea248d4d1ba09cb6d281ec458ed00df1aa4fb55 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Thu, 26 Nov 2026 05:23:48 +0000 Subject: [PATCH 2/4] fix: preserve user turn identity across empty-response retries --- .../tla/ToolResultRetry.Current.cfg | 3 +- .../tla/ToolResultRetry.Summary.cfg | 9 ++ docs/architecture/tla/ToolResultRetry.cfg | 3 +- docs/architecture/tla/ToolResultRetry.tla | 98 ++++++++++++------ src/core/task/Task.ts | 99 +++++++------------ src/core/task/__tests__/Task.spec.ts | 2 + .../__tests__/apiConversationHistory.spec.ts | 24 +++++ .../__tests__/empty-response-history.spec.ts | 88 ++++++++++++----- 8 files changed, 202 insertions(+), 124 deletions(-) create mode 100644 docs/architecture/tla/ToolResultRetry.Summary.cfg diff --git a/docs/architecture/tla/ToolResultRetry.Current.cfg b/docs/architecture/tla/ToolResultRetry.Current.cfg index a83b69e80d4..9aff3702db5 100644 --- a/docs/architecture/tla/ToolResultRetry.Current.cfg +++ b/docs/architecture/tla/ToolResultRetry.Current.cfg @@ -1,8 +1,9 @@ SPECIFICATION Spec CONSTANTS + PopSummary = FALSE Mode = "Fresh" MaxCalls = 1 MaxEmpty = 2 MaxMints = 4 -INVARIANTS TypeOK OneResultPerCall ResultNeverLost +INVARIANTS TypeOK OneResultPerCall ResultNeverLost SummarySurvives CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.Summary.cfg b/docs/architecture/tla/ToolResultRetry.Summary.cfg new file mode 100644 index 00000000000..a19edefb48a --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.Summary.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CONSTANTS + PopSummary = TRUE + Mode = "Stable" + MaxCalls = 1 + MaxEmpty = 2 + MaxMints = 4 +INVARIANTS TypeOK OneResultPerCall ResultNeverLost SummarySurvives +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.cfg b/docs/architecture/tla/ToolResultRetry.cfg index cee59f4c5a5..a340d9e19fd 100644 --- a/docs/architecture/tla/ToolResultRetry.cfg +++ b/docs/architecture/tla/ToolResultRetry.cfg @@ -1,8 +1,9 @@ SPECIFICATION Spec CONSTANTS + PopSummary = FALSE Mode = "Stable" MaxCalls = 1 MaxEmpty = 2 MaxMints = 4 -INVARIANTS TypeOK OneResultPerCall ResultNeverLost +INVARIANTS TypeOK OneResultPerCall ResultNeverLost SummarySurvives CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.tla b/docs/architecture/tla/ToolResultRetry.tla index a499175923a..45282b876bc 100644 --- a/docs/architecture/tla/ToolResultRetry.tla +++ b/docs/architecture/tla/ToolResultRetry.tla @@ -12,43 +12,61 @@ \* one tool_use id and the provider returns HTTP 400 (issue 2691). \* Invariant OneResultPerCall: no tool call has two saved result records. \* Invariant ResultNeverLost: when the turn ends, every issued call still has its -\* saved result, so the fix cannot repair the duplicate by losing the result. +\* saved result outside a summary, so the fix cannot repair the duplicate by losing the result. \* Modes: Fresh mints a new identity on every retry and decline (the code before \* the fix). Stable restores the popped record with its identity (the fix). \* Expected before the run: Fresh fails OneResultPerCall at the retry save. The -\* trace is NewTurn, Result, EmptyResponse, RetryReAdd. Stable holds every +\* trace is AddAssistant, AddUserResult, EmptyResponse, RetryReAdd. Stable holds every \* invariant. \* Configs: ToolResultRetry.cfg (Stable) must pass. ToolResultRetry.Current.cfg -\* (Fresh) must fail. -\* Not modeled: message content, timestamps beyond identity order, condense and -\* truncation tags, the first-chunk and mid-stream retry paths (they never -\* recreate the turn), and the two flush defects of issue 2691. Those need a +\* (Fresh) must fail. ToolResultRetry.Summary.cfg removes the summary guard and must fail. +\* Not modeled: message content, timestamp order, truncation tags, and stream retries +\* that do not recreate the turn, and the two flush defects of issue 2691. Those need a \* different fix and stay in the issue. -\* Cost: each run takes under 5 seconds. Agent time is not measured. -\* Result: ToolResultRetry.cfg (Stable) holds with 10 distinct states. -\* ToolResultRetry.Current.cfg (Fresh) fails OneResultPerCall at the retry save, -\* in 5 states. The counterexample is AddAssistant, AddUserResult, EmptyResponse, -\* RetryReAdd with a fresh identity. It matches the issue replay steps 1 and -\* 3 to 5 on the real code. ResultNeverLost holds in both modes, so the fix -\* must merge by identity, not discard results. -\* Findings: 0 covered, 1 added (the retry identity choice), 0 gap. The failing -\* replay and the stable-identity control were recreated from the issue, so no -\* prior finding exists to cover. +\* Review ratchet for PR #2701, supplied review summary (no thread URL supplied). +\* Expected: removing the identity guard can replace a summary with a plain turn. +\* Condense maps overwriteApiConversationHistory to a summary save before pop or during backoff. +\* Added: SummarySurvives models findings 1 and 3. Findings 8 and 9 are covered. +\* Gap: 2 is a separate output-limit retry. 4 to 7 and 10 to 14 concern tests or text. +\* Finding 15 needs no change. Counts: 3 covered, 2 added, 10 gap. +\* The first invariants predate this review. The new invariant follows the review. +\* Cost: each run takes under 5 seconds. This review pass took about 8 agent minutes. +\* Result: the fixed config holds with 20 distinct states. +\* Fresh fails OneResultPerCall with 8 distinct states and a 5-state trace. +\* Summary sabotage fails SummarySurvives with 11 distinct states and a 6-state trace. +\* Its last actions are Condense, EmptyResponse, RetryReAdd. +\* Replay: the before-pop summary test fails on the old guard and passes on the fix. +\* The backoff summary test passes in both versions. This is a null result. +\* No new code defect was found beyond the supplied review findings. +\* The phase table test checks summary preservation on the real persistence path. +\* Initial findings before review: 0 covered, 1 added, 0 gap. + +\* Runtime simplification: derive the removed flag from popped, as this model does. +\* Both retry decisions use RetryReAdd. Keep one queue step in recursivelyMakeClineRequests. +\* Failure to prevent: a retry adds a second saved result or replaces a summary. +\* Expected: the same invariants and sabotage checks hold with no model transition change. +\* Result: 20 fixed states pass. Fresh and summary sabotage fail with 8 and 11 distinct states. +\* No new defect was found. The existing phase-table tests pass on the runtime refactor. +\* Cost: this simplification pass took about 3 agent minutes. +\* The model does not check the prompt or backoff order. Runtime tests check those paths. + EXTENDS Naturals, FiniteSets, Sequences -CONSTANTS Mode, MaxCalls, MaxEmpty, MaxMints +CONSTANTS Mode, PopSummary, MaxCalls, MaxEmpty, MaxMints URec(c, m) == [kind |-> "u", call |-> c, mid |-> m] ARec(m) == [kind |-> "a", call |-> 0, mid |-> m] +PRec == [kind |-> "plain", call |-> 0, mid |-> MaxMints] +SRec == [kind |-> "summary", call |-> 0, mid |-> MaxMints] NoRec == [kind |-> "none", call |-> 0, mid |-> 0] RecordSet == - {ARec(m) : m \in 0..(MaxMints - 1)} - \cup {URec(c, m) : c \in 1..MaxCalls, m \in 0..(MaxMints - 1)} + {SRec, PRec} \cup {ARec(m) : m \in 0..MaxMints} + \cup {URec(c, m) : c \in 1..MaxCalls, m \in 0..MaxMints} -VARIABLES mem, disk, popped, nextMid, empties, done -vars == <> +VARIABLES mem, disk, popped, nextMid, empties, done, summarized +vars == <> MemMids(mm) == {mm[i].mid : i \in 1..Len(mm)} MemSet(mm) == {mm[i] : i \in 1..Len(mm)} @@ -65,10 +83,10 @@ AddAssistant == /\ mem' = Append(mem, ARec(nextMid)) /\ nextMid' = nextMid + 1 /\ disk' = MergeSave(mem') - /\ UNCHANGED <> + /\ UNCHANGED <> \* The tool ran. The user turn with its tool result is saved. A fresh turn is -\* minted only when no removed turn awaits restoration; mid-retry the only +\* minted only when no removed turn awaits restoration. During a retry the only \* user-turn add is the restore. AddUserResult(c) == /\ ~done @@ -78,7 +96,7 @@ AddUserResult(c) == /\ mem' = Append(mem, URec(c, nextMid)) /\ nextMid' = nextMid + 1 /\ disk' = MergeSave(mem') - /\ UNCHANGED <> + /\ UNCHANGED <> \* The model sent no assistant content. The saved user turn is popped from \* memory. The disk copy stays. @@ -86,11 +104,11 @@ EmptyResponse == /\ ~done /\ empties < MaxEmpty /\ Len(mem) >= 2 - /\ mem[Len(mem)].kind = "u" + /\ (mem[Len(mem)].kind = "u" \/ (PopSummary /\ mem[Len(mem)] = SRec)) /\ popped' = mem[Len(mem)] /\ empties' = empties + 1 /\ mem' = SubSeq(mem, 1, Len(mem) - 1) - /\ UNCHANGED <> + /\ UNCHANGED <> \* The retry re-adds the turn and saves. Stable keeps the saved identity, so the \* merge save replaces the disk record. Fresh mints a new identity, so the merge @@ -98,14 +116,14 @@ EmptyResponse == RetryReAdd(c) == /\ ~done /\ popped # NoRec - /\ LET restored == IF Mode = "Stable" THEN popped ELSE URec(c, nextMid) + /\ LET restored == IF Mode = "Stable" THEN (IF popped = SRec THEN PRec ELSE popped) ELSE URec(c, nextMid) replaced == IF Mode = "Stable" THEN popped.mid ELSE nextMid IN /\ Mode = "Stable" \/ nextMid < MaxMints /\ mem' = Append(mem, restored) /\ nextMid' = IF Mode = "Stable" THEN nextMid ELSE nextMid + 1 /\ disk' = {r \in disk : r.mid # replaced} \cup MemSet(mem') /\ popped' = NoRec - /\ UNCHANGED <> + /\ UNCHANGED <> \* The user declines the retry. The popped turn is restored with its identity, \* then a synthetic failure turn is saved and the turn ends. @@ -113,7 +131,7 @@ RetryDeclined(c) == /\ ~done /\ popped # NoRec /\ nextMid + 1 < MaxMints - /\ LET restored == IF Mode = "Stable" THEN popped ELSE URec(c, nextMid) + /\ LET restored == IF Mode = "Stable" THEN (IF popped = SRec THEN PRec ELSE popped) ELSE URec(c, nextMid) nextAfter == IF Mode = "Stable" THEN nextMid ELSE nextMid + 1 afterRestore == Append(Append(mem, restored), ARec(nextAfter)) IN /\ mem' = afterRestore @@ -121,7 +139,7 @@ RetryDeclined(c) == /\ disk' = {r \in disk : ~r.mid \in MemMids(mem')} \cup MemSet(mem') /\ popped' = NoRec /\ done' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> \* The retry gets a real assistant response. The turn ends. CompleteTurn == @@ -133,7 +151,21 @@ CompleteTurn == /\ nextMid' = nextMid + 1 /\ disk' = MergeSave(mem') /\ done' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> + +\* Context management replaces the saved history before the pop or during backoff. +Condense == + /\ ~done + /\ SRec \notin disk + /\ Len(mem) >= 1 + /\ nextMid >= 2 + /\ mem' = Append(mem, SRec) + /\ disk' = {SRec} + /\ summarized' = TRUE + /\ UNCHANGED <> + +\* Once context management saves a summary, a retry must keep its metadata. +SummarySurvives == summarized => SRec \in disk Init == /\ mem = <<>> @@ -142,8 +174,10 @@ Init == /\ nextMid = 0 /\ empties = 0 /\ done = FALSE + /\ summarized = FALSE Next == + \/ Condense \/ AddAssistant \/ \E c \in 1..MaxCalls : \/ AddUserResult(c) @@ -173,7 +207,7 @@ OneResultPerCall == \* The fix must not lose the result: when the turn ends, every issued call \* still has its saved result. ResultNeverLost == - done => + done /\ SRec \notin disk => \A c \in 1..MaxCalls : Cardinality({r \in disk : r.kind = "u" /\ r.call = c}) = 1 diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index e5939ad2db3..1b3e35c9594 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -4017,7 +4017,6 @@ export class Task extends EventEmitter implements TaskLike { pendingContent?: Promise // Resolved after the request row shows includeFileDetails: boolean retryAttempt?: number - userMessageWasRemoved?: boolean // Track if user message was removed due to empty response removedUserMessage?: ApiMessage // The saved record removed for the empty-response retry, restored with its identity } @@ -4129,20 +4128,15 @@ export class Task extends EventEmitter implements TaskLike { const shouldAddUserMessage = shouldAddUserMessageToHistory({ retryAttempt: currentItem.retryAttempt, isEmptyUserContent, - userMessageWasRemoved: currentItem.userMessageWasRemoved, + userMessageWasRemoved: currentItem.removedUserMessage !== undefined, }) + let addedUserMessageId: string | undefined if (shouldAddUserMessage) { - if (currentItem.removedUserMessage) { - await this.addToApiConversationHistory({ role: "user", content: finalUserContent }, undefined, { - // A retry after an empty assistant response restores a turn that is - // still saved on disk. Reusing its identity makes the merge save - // replace that record instead of keeping both turns, so the - // reloaded history holds exactly one result per tool_use id. - identity: currentItem.removedUserMessage, - }) - } else { - await this.addToApiConversationHistory({ role: "user", content: finalUserContent }) - } + // Reuse the saved identity so the merge save replaces the original turn. + await this.addToApiConversationHistory({ role: "user", content: finalUserContent }, undefined, { + identity: currentItem.removedUserMessage, + }) + addedUserMessageId = this.apiConversationHistory.at(-1)?.messageId this.messageCounts.user++ } @@ -5274,32 +5268,24 @@ export class Task extends EventEmitter implements TaskLike { await this.say("error", "MODEL_NO_ASSISTANT_MESSAGES") } - // IMPORTANT: We already added the user message to - // apiConversationHistory at line 1876. Since the assistant failed to respond, - // we need to remove that message before retrying to avoid having two consecutive - // user messages (which would cause tool_result validation errors). const state = await this.providerRef.deref()?.getState() - // Only pop the user message that this iteration added. When - // shouldAddUserMessage is false (empty continuation, resumed history, - // or flushPendingToolResultsToHistory message) there is nothing to - // remove, and popping would corrupt history. - let removedCurrentUserMessage = false + // Context management can replace the added turn with a summary. + // Remove only the turn that this iteration added. let removedUserMessage: ApiMessage | undefined - if (shouldAddUserMessage && this.apiConversationHistory.length > 0) { - const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1] - if (lastMessage.role === "user") { - // Keep the saved record: the retry restores this exact identity so - // the merge save replaces the on-disk copy instead of adding a - // second turn with the same tool results (issue #2691). - removedUserMessage = lastMessage - this.apiConversationHistory.pop() - this.messageCounts.user-- - removedCurrentUserMessage = true - } + const lastMessage = this.apiConversationHistory.at(-1) + if ( + addedUserMessageId !== undefined && + lastMessage?.messageId === addedUserMessageId && + lastMessage.role === "user" && + !lastMessage.isSummary + ) { + // The retry must reuse this identity to replace the saved disk record. + removedUserMessage = lastMessage + this.apiConversationHistory.pop() + this.messageCounts.user-- } - // Check if we should auto-retry or prompt the user - // Reuse the state variable from above + // Wait for the automatic retry or ask the user for a retry decision. if (state?.autoApprovalEnabled) { // Auto-retry with backoff - don't persist failure message when retrying await this.backoffAndAnnounce( @@ -5316,20 +5302,6 @@ export class Task extends EventEmitter implements TaskLike { ) break } - - // Push the same content back onto the stack to retry, incrementing the retry attempt counter. - // Only mark userMessageWasRemoved when we actually removed one -- the - // restore branch in shouldAddUserMessageToHistory must only fire once. - stack.push({ - userContent: currentUserContent, - includeFileDetails: false, - retryAttempt: (currentItem.retryAttempt ?? 0) + 1, - userMessageWasRemoved: removedCurrentUserMessage, - removedUserMessage, - }) - - // Continue to retry the request - continue } else { // Prompt the user for retry decision const { response } = await this.ask( @@ -5339,29 +5311,14 @@ export class Task extends EventEmitter implements TaskLike { if (response === "yesButtonClicked") { await this.say("api_req_retried") - - // Push the same content back to retry. Only mark userMessageWasRemoved - // when we actually removed one so the restore fires exactly once. - stack.push({ - userContent: currentUserContent, - includeFileDetails: false, - retryAttempt: (currentItem.retryAttempt ?? 0) + 1, - userMessageWasRemoved: removedCurrentUserMessage, - removedUserMessage, - }) - - // Continue to retry the request - continue } else { // User declined to retry. Re-add the user message only if this // iteration removed one, so the history and counter stay consistent. - if (removedCurrentUserMessage) { + if (removedUserMessage) { // Restore the already saved record with its original identity so // the merge save keeps one copy of the turn on disk. await this.addToApiConversationHistory( - removedUserMessage - ? { role: "user", content: removedUserMessage.content } - : { role: "user", content: currentUserContent }, + { role: "user", content: removedUserMessage.content }, undefined, { identity: removedUserMessage }, ) @@ -5381,8 +5338,18 @@ export class Task extends EventEmitter implements TaskLike { content: [{ type: "text", text: "Failure: I did not provide a response." }], }) this.messageCounts.assistant++ + return false } } + + // Both retry paths restore the same saved record on the next iteration. + stack.push({ + userContent: currentUserContent, + includeFileDetails: false, + retryAttempt: (currentItem.retryAttempt ?? 0) + 1, + removedUserMessage, + }) + continue } // If we reach here without continuing, return false (will always be false for now) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index e644e2bce09..de794652e51 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7280,6 +7280,8 @@ describe("Cline", () => { expect.objectContaining({ content: expect.arrayContaining([{ type: "text", text: "expanded input" }]), }), + undefined, + { identity: undefined }, ) }) diff --git a/src/core/task/__tests__/apiConversationHistory.spec.ts b/src/core/task/__tests__/apiConversationHistory.spec.ts index 5e737c4ef1f..9e40858b3aa 100644 --- a/src/core/task/__tests__/apiConversationHistory.spec.ts +++ b/src/core/task/__tests__/apiConversationHistory.spec.ts @@ -14,6 +14,30 @@ describe("prepareApiConversationMessage", () => { vi.useRealTimers() }) + it.each([{ messageId: "saved-turn", ts: 123 }, { ts: 123 }, { messageId: "saved-turn" }, undefined])( + "uses each supplied user identity field: %j", + (identity) => { + const api = { + createMessage: vi.fn(), + getModel: vi.fn(), + countTokens: vi.fn(), + getModelCacheScope: vi.fn(), + } + const options = { api, apiConfiguration: {}, apiConversationHistory: [], identity } + const user = prepareApiConversationMessage({ ...options, message: { role: "user", content: "turn" } }) + expect(user.ts).toBe(identity?.ts ?? Date.now()) + if (identity?.messageId) expect(user.messageId).toBe(identity.messageId) + else expect(user.messageId).toMatch(/^[0-9a-f-]{36}$/) + const assistant = prepareApiConversationMessage({ + ...options, + message: { role: "assistant", content: "answer" }, + }) + expect(assistant.ts).toBe(Date.now()) + expect(assistant.messageId).toMatch(/^[0-9a-f-]{36}$/) + expect(assistant.messageId).not.toBe(identity?.messageId) + }, + ) + it("prepends Anthropic thinking blocks with thought signatures", () => { const result = prepareApiConversationMessage({ message: { role: "assistant", content: "answer" }, diff --git a/src/core/task/__tests__/empty-response-history.spec.ts b/src/core/task/__tests__/empty-response-history.spec.ts index 60e2692a8c5..bdcaec7192e 100644 --- a/src/core/task/__tests__/empty-response-history.spec.ts +++ b/src/core/task/__tests__/empty-response-history.spec.ts @@ -28,6 +28,7 @@ import { getEffectiveApiHistory } from "../../condense" import { mergeConsecutiveApiMessages } from "../mergeConsecutiveApiMessages" import { convertToOpenAiMessages } from "../../../api/transform/openai-format" import { setAbortLatch } from "../../../test-utils/run-state" +import { asyncStreamFrom } from "../../../test-utils/stream" import type { ApiStreamChunk } from "../../../api/transform/stream" import * as safeWriteJsonModule from "../../../utils/safeWriteJson" @@ -150,12 +151,6 @@ const stubModelInfo: ModelInfo = { const TOOL_USE_ID = "toolu_retry_01" -function stream(chunks: ApiStreamChunk[]): AsyncGenerator { - return (async function* () { - yield* chunks - })() -} - /** The tool_use assistant turn and its saved user result turn in the disk history. */ function findResultMessage(messages: ApiMessage[], toolUseId: string): ApiMessage | undefined { return messages.find( @@ -329,7 +324,7 @@ describe("empty-response history persistence (issue 2691)", () => { } { let captured: { messageId?: string; ts?: number } | undefined const body = (async function* () { - const saved = findResultMessage(await readDiskHistory(task), TOOL_USE_ID) + const saved = findResultMessage(task.apiConversationHistory, TOOL_USE_ID) captured = { messageId: saved?.messageId, ts: saved?.ts } yield* chunks })() @@ -349,7 +344,7 @@ describe("empty-response history persistence (issue 2691)", () => { const attemptApiRequestSpy = vi .spyOn(task, "attemptApiRequest") .mockImplementationOnce(() => firstAttempt.body) - .mockImplementationOnce(() => stream([{ type: "text", text: "retry succeeded" }])) + .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "retry succeeded" }])) .mockImplementation(() => { throw new Error("stop after retry response") }) @@ -388,9 +383,9 @@ describe("empty-response history persistence (issue 2691)", () => { const attemptApiRequestSpy = vi .spyOn(task, "attemptApiRequest") .mockImplementationOnce(() => firstAttempt.body) - .mockImplementationOnce(() => stream([])) - .mockImplementationOnce(() => stream([])) - .mockImplementationOnce(() => stream([{ type: "text", text: "finally answered" }])) + .mockImplementationOnce(() => asyncStreamFrom([])) + .mockImplementationOnce(() => asyncStreamFrom([])) + .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "finally answered" }])) .mockImplementation(() => { throw new Error("stop after retry response") }) @@ -414,12 +409,10 @@ describe("empty-response history persistence (issue 2691)", () => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: false }) vi.spyOn(task, "ask").mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult) - vi.spyOn(task, "attemptApiRequest").mockImplementation(() => stream([])) - const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) const attemptSpy = vi.spyOn(task, "attemptApiRequest") attemptSpy.mockImplementationOnce(() => firstAttempt.body) - attemptSpy.mockImplementation(() => stream([])) + attemptSpy.mockImplementation(() => asyncStreamFrom([])) const result = await task.recursivelyMakeClineRequests(toolResultUserContent()) @@ -448,7 +441,9 @@ describe("empty-response history persistence (issue 2691)", () => { const attemptApiRequestSpy = vi .spyOn(task, "attemptApiRequest") .mockImplementationOnce(() => firstAttempt.body) - .mockImplementationOnce(() => stream([{ type: "text", text: "explicit retry worked" }])) + .mockImplementationOnce(() => + asyncStreamFrom([{ type: "text", text: "explicit retry worked" }]), + ) .mockImplementation(() => { throw new Error("stop after retry response") }) @@ -460,6 +455,8 @@ describe("empty-response history persistence (issue 2691)", () => { const disk = await readDiskHistory(task) expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + expect(findResultMessage(disk, TOOL_USE_ID)).toMatchObject(firstAttempt.identity()) + expect(findResultMessage(disk, TOOL_USE_ID)?.content).toEqual(expect.arrayContaining(toolResultUserContent())) expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) }) @@ -494,14 +491,16 @@ describe("empty-response history persistence (issue 2691)", () => { * now). The API history writes go through safeWriteJson, so a rejection there * reaches saveApiConversationHistory without touching unrelated files. */ - function injectApiHistorySaveFailure(failingWrite: number): { restore: () => void } { + function injectApiHistorySaveFailure(failingWrite: number): { restore: () => void; failures: () => number } { const originalSafeWriteJson = safeWriteJsonModule.safeWriteJson let apiHistoryWrites = 0 + let failures = 0 const writeSpy = vi.spyOn(safeWriteJsonModule, "safeWriteJson") writeSpy.mockImplementation(async (filePath, data, options) => { if (String(filePath).includes("api_conversation_history.json")) { apiHistoryWrites += 1 if (apiHistoryWrites === failingWrite) { + failures++ throw Object.assign(new Error("injected save failure"), { code: "EACCES" }) } } @@ -509,20 +508,21 @@ describe("empty-response history persistence (issue 2691)", () => { }) return { restore: () => writeSpy.mockRestore(), + failures: () => failures, } } - it("keeps a single saved result when the retry restore save fails (fault injection)", async () => { + it.each([1, 2])("keeps a single saved result when save %i fails", async (failingWrite) => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) // API-history saves from here: the first iteration's user turn, then the - // restore save after the empty-response pop. Fail the restore save. - const injection = injectApiHistorySaveFailure(2) + // restore save after the empty-response pop. Fail each save in turn. + const injection = injectApiHistorySaveFailure(failingWrite) const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) vi.spyOn(task, "attemptApiRequest") .mockImplementationOnce(() => firstAttempt.body) - .mockImplementationOnce(() => stream([{ type: "text", text: "retry succeeded" }])) + .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "retry succeeded" }])) .mockImplementation(() => { throw new Error("stop after retry response") }) @@ -530,11 +530,11 @@ describe("empty-response history persistence (issue 2691)", () => { await task.recursivelyMakeClineRequests(toolResultUserContent()) const beforeRetry = firstAttempt.identity() + expect(injection.failures()).toBe(1) injection.restore() const disk = await readDiskHistory(task) - // The failed restore still re-added the turn in memory, and the next merge - // save matched the original disk record by identity: one copy, result kept. + // A later save must keep one copy with the original identity. expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) const afterRetry = findResultMessage(disk, TOOL_USE_ID) expect(afterRetry?.messageId).toBe(beforeRetry.messageId) @@ -553,12 +553,13 @@ describe("empty-response history persistence (issue 2691)", () => { const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) const attemptSpy = vi.spyOn(task, "attemptApiRequest") attemptSpy.mockImplementationOnce(() => firstAttempt.body) - attemptSpy.mockImplementation(() => stream([])) + attemptSpy.mockImplementation(() => asyncStreamFrom([])) const result = await task.recursivelyMakeClineRequests(toolResultUserContent()) const beforeDecline = firstAttempt.identity() expect(result).toBe(false) + expect(injection.failures()).toBe(1) injection.restore() const disk = await readDiskHistory(task) @@ -573,6 +574,45 @@ describe("empty-response history persistence (issue 2691)", () => { expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) }) + it.each(["before pop", "during backoff"])("keeps a summary saved %s", async (phase) => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) + const summary: ApiMessage = { + role: "user", + content: "Saved summary", + messageId: "summary-1", + ts: Date.now() + 100, + isSummary: true, + condenseId: "condense-1", + } + const condense = async () => { + await task.overwriteApiConversationHistory([ + ...task.apiConversationHistory.map((message) => ({ ...message, condenseParent: "condense-1" })), + summary, + ]) + } + if (phase === "during backoff") { + vi.spyOn(probe(task), "backoffAndAnnounce").mockImplementation(condense) + } + vi.spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => + (async function* () { + if (phase === "before pop") await condense() + yield* asyncStreamFrom([]) + })(), + ) + .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "done" }])) + .mockImplementation(() => { + throw new Error("stop after retry") + }) + + await task.recursivelyMakeClineRequests(toolResultUserContent()) + + const disk = await readDiskHistory(task) + expect(disk.find((message) => message.messageId === summary.messageId)).toEqual(summary) + expect(getEffectiveApiHistory(disk)).toContainEqual(summary) + expect(getEffectiveApiHistory(disk).some((message) => message.condenseParent === "condense-1")).toBe(false) + }) + it("keeps the saved history valid when the task is cancelled during the retry backoff", async () => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) @@ -580,7 +620,7 @@ describe("empty-response history persistence (issue 2691)", () => { vi.spyOn(probe(task), "backoffAndAnnounce").mockImplementation(async () => { setAbortLatch(task, true) }) - vi.spyOn(task, "attemptApiRequest").mockImplementation(() => stream([])) + vi.spyOn(task, "attemptApiRequest").mockImplementation(() => asyncStreamFrom([])) const result = await task.recursivelyMakeClineRequests(toolResultUserContent()) From ddd180533657cbd331fde340183281492c73a64b Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Fri, 27 Nov 2026 01:02:24 +0000 Subject: [PATCH 3/4] fix: keep saved tool-result turns across empty-response retries --- .../tla/ToolResultRetry.LoseDecline.cfg | 9 + .../tla/ToolResultRetry.LosePending.cfg | 9 + .../tla/ToolResultRetry.LoseRetry.cfg | 9 + .../tla/ToolResultRetry.Popped.cfg | 9 + docs/architecture/tla/ToolResultRetry.cfg | 6 +- docs/architecture/tla/ToolResultRetry.tla | 165 +++++++++--------- src/core/task/Task.ts | 51 +----- src/core/task/__tests__/Task.spec.ts | 2 - .../__tests__/apiConversationHistory.spec.ts | 39 ++--- .../__tests__/empty-response-history.spec.ts | 150 +++++++++++----- .../task/__tests__/messageCounting.spec.ts | 79 +-------- src/core/task/apiConversationHistory.ts | 21 +-- src/core/task/messageCounting.ts | 16 +- 13 files changed, 268 insertions(+), 297 deletions(-) create mode 100644 docs/architecture/tla/ToolResultRetry.LoseDecline.cfg create mode 100644 docs/architecture/tla/ToolResultRetry.LosePending.cfg create mode 100644 docs/architecture/tla/ToolResultRetry.LoseRetry.cfg create mode 100644 docs/architecture/tla/ToolResultRetry.Popped.cfg diff --git a/docs/architecture/tla/ToolResultRetry.LoseDecline.cfg b/docs/architecture/tla/ToolResultRetry.LoseDecline.cfg new file mode 100644 index 00000000000..c5ee80de072 --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.LoseDecline.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CONSTANTS + PopSummary = FALSE + Mode = "LoseDecline" + MaxCalls = 2 + MaxEmpty = 2 + MaxMints = 4 +INVARIANTS TypeOK ResultNeverLost +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.LosePending.cfg b/docs/architecture/tla/ToolResultRetry.LosePending.cfg new file mode 100644 index 00000000000..7e184954f16 --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.LosePending.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CONSTANTS + PopSummary = FALSE + Mode = "LosePending" + MaxCalls = 2 + MaxEmpty = 2 + MaxMints = 4 +INVARIANTS TypeOK ResultNeverLost +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.LoseRetry.cfg b/docs/architecture/tla/ToolResultRetry.LoseRetry.cfg new file mode 100644 index 00000000000..95e9ea3a08c --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.LoseRetry.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CONSTANTS + PopSummary = FALSE + Mode = "LoseRetry" + MaxCalls = 2 + MaxEmpty = 2 + MaxMints = 4 +INVARIANTS TypeOK ResultNeverLost +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.Popped.cfg b/docs/architecture/tla/ToolResultRetry.Popped.cfg new file mode 100644 index 00000000000..0962550b44e --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.Popped.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CONSTANTS + PopSummary = FALSE + Mode = "Stable" + MaxCalls = 2 + MaxEmpty = 2 + MaxMints = 4 +INVARIANTS TypeOK ResultInMemory +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.cfg b/docs/architecture/tla/ToolResultRetry.cfg index a340d9e19fd..3b9d1478529 100644 --- a/docs/architecture/tla/ToolResultRetry.cfg +++ b/docs/architecture/tla/ToolResultRetry.cfg @@ -1,9 +1,9 @@ SPECIFICATION Spec CONSTANTS PopSummary = FALSE - Mode = "Stable" - MaxCalls = 1 + Mode = "Retain" + MaxCalls = 2 MaxEmpty = 2 MaxMints = 4 -INVARIANTS TypeOK OneResultPerCall ResultNeverLost SummarySurvives +INVARIANTS TypeOK OneResultPerCall ResultNeverLost SummarySurvives ResultInMemory CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.tla b/docs/architecture/tla/ToolResultRetry.tla index 45282b876bc..94535308b39 100644 --- a/docs/architecture/tla/ToolResultRetry.tla +++ b/docs/architecture/tla/ToolResultRetry.tla @@ -1,55 +1,46 @@ ---- MODULE ToolResultRetry ---- -\* Models the empty-assistant-response retry in recursivelyMakeClineRequests -\* (src/core/task/Task.ts) and the merge save in saveApiMessages and -\* mergeApiMessageSnapshots (src/core/task-persistence/mergeMessageSnapshots.ts). -\* Source: the retry pops the saved user tool-result turn from memory and re-adds -\* it. Decline restores it too. Sink: a reload turns every saved user-result -\* record into one outgoing tool_result block (mergeConsecutiveApiMessages then -\* convertToOpenAiMessages). The conversion is one-to-one on records, so the -\* model counts records. -\* Failure: the retry mints a fresh message identity, so the merge save keeps the -\* disk-only record. The reloaded history then sends two tool_result blocks for -\* one tool_use id and the provider returns HTTP 400 (issue 2691). -\* Invariant OneResultPerCall: no tool call has two saved result records. -\* Invariant ResultNeverLost: when the turn ends, every issued call still has its -\* saved result outside a summary, so the fix cannot repair the duplicate by losing the result. -\* Modes: Fresh mints a new identity on every retry and decline (the code before -\* the fix). Stable restores the popped record with its identity (the fix). -\* Expected before the run: Fresh fails OneResultPerCall at the retry save. The -\* trace is AddAssistant, AddUserResult, EmptyResponse, RetryReAdd. Stable holds every -\* invariant. -\* Configs: ToolResultRetry.cfg (Stable) must pass. ToolResultRetry.Current.cfg -\* (Fresh) must fail. ToolResultRetry.Summary.cfg removes the summary guard and must fail. -\* Not modeled: message content, timestamp order, truncation tags, and stream retries -\* that do not recreate the turn, and the two flush defects of issue 2691. Those need a -\* different fix and stay in the issue. -\* Review ratchet for PR #2701, supplied review summary (no thread URL supplied). -\* Expected: removing the identity guard can replace a summary with a plain turn. -\* Condense maps overwriteApiConversationHistory to a summary save before pop or during backoff. -\* Added: SummarySurvives models findings 1 and 3. Findings 8 and 9 are covered. -\* Gap: 2 is a separate output-limit retry. 4 to 7 and 10 to 14 concern tests or text. -\* Finding 15 needs no change. Counts: 3 covered, 2 added, 10 gap. -\* The first invariants predate this review. The new invariant follows the review. -\* Cost: each run takes under 5 seconds. This review pass took about 8 agent minutes. -\* Result: the fixed config holds with 20 distinct states. -\* Fresh fails OneResultPerCall with 8 distinct states and a 5-state trace. -\* Summary sabotage fails SummarySurvives with 11 distinct states and a 6-state trace. -\* Its last actions are Condense, EmptyResponse, RetryReAdd. -\* Replay: the before-pop summary test fails on the old guard and passes on the fix. -\* The backoff summary test passes in both versions. This is a null result. -\* No new code defect was found beyond the supplied review findings. -\* The phase table test checks summary preservation on the real persistence path. -\* Initial findings before review: 0 covered, 1 added, 0 gap. - -\* Runtime simplification: derive the removed flag from popped, as this model does. -\* Both retry decisions use RetryReAdd. Keep one queue step in recursivelyMakeClineRequests. -\* Failure to prevent: a retry adds a second saved result or replaces a summary. -\* Expected: the same invariants and sabotage checks hold with no model transition change. -\* Result: 20 fixed states pass. Fresh and summary sabotage fail with 8 and 11 distinct states. -\* No new defect was found. The existing phase-table tests pass on the runtime refactor. -\* Cost: this simplification pass took about 3 agent minutes. -\* The model does not check the prompt or backoff order. Runtime tests check those paths. - +\* Source: recursivelyMakeClineRequests in Task.ts retains a saved turn across retries. +\* Sink: saveApiMessages and mergeApiMessageSnapshots retain disk-only identities. +\* Reload and provider conversion send one result block per saved result record. +\* Failure: a retry duplicates or loses a result, or replaces a saved summary. +\* Invariants: OneResultPerCall limits duplicates. ResultNeverLost retains each +\* issued result until Condense replaces it. SummarySurvives retains summary metadata. +\* Retain leaves the saved turn in place. Stable models the earlier identity restore. +\* Fresh mints identity. PopSummary removes the earlier pop guard. +\* LosePending deletes the disk result at pop. LoseRetry and LoseDecline replace +\* the restored result with a plain record at their respective save boundaries. +\* Expected: Retain passes all invariants. Stable passes the disk invariants. +\* Stable fails ResultInMemory. All sabotage modes fail. +\* Condense abstracts overwriteApiConversationHistory before retry or during backoff. +\* Not modeled: payload parsing, timestamps, message counters, ask delivery, prompt +\* order, save failures, cancellation, rewind, deletion, output-limit retries, or concurrency. +\* Initial invariants predate this review. This pass extends them from the findings. +\* PR #2701 review ratchet (supplied summary, no thread URL): 1 covered, 2 added, +\* 4 gap. Covered: identity guard. Added: loss checks and summarized type. Gaps: +\* summary test strength, ask delivery, header prose, and test helper prose. +\* Earlier checks: Fresh failed duplication. PopSummary failed summary retention. +\* Policy requires cost and findings here. These are model results, not a code proof. +\* Earlier result: Stable passed with 38 states. Fresh and PopSummary failed with 8 and 11. +\* Earlier loss checks failed LosePending, LoseRetry, and LoseDecline with 6, 12, and 13 states. +\* Replay: disk overwrite at pop and plain-text restore mutations fail real-file tests. +\* Unconditional restore and missing identity-guard mutations fail the summary tests. +\* Empty-array restore is repaired by validation. Assistant restore leaves the old +\* disk record. These are false alarms for result loss, so the loss modes use plain records. +\* Property test: retry counts 1 to 3 retain one saved result with its identity. +\* Null result: no new production defect was found beyond the review findings. +\* Simplification expectation: no pop needs no restore, identity option, or counter adjustment. +\* Condense covers the retained turn before or during backoff. No plain copy follows it. +\* Ask polling and input cardinality remain gaps. Real polling and retry-count tests cover them. +\* Added ResultInMemory: the saved result stays in memory until Condense covers it. +\* SummarySurvives now checks memory and disk. Both are required by the retained-turn design. +\* Expected sabotage: Stable fails ResultInMemory at EmptyResponse; the real backoff test must fail. +\* Result: Retain passes with 44 states. Stable fails ResultInMemory with 6 states. +\* Fresh fails with 9 states. Summary sabotage fails with 7 states. +\* Loss sabotage fails pending, retry, and decline with 6, 13, and 14 states. +\* Replay: adding a pop to the new runtime fails backoff, pending ask, and cancellation tests. +\* The real ask wait now stays pending across polling until the handler receives a response. +\* Null result: no new production bug was found. The design removes the transient missing turn. +\* Cost: about eight agent minutes for this simplification; TLC runs take under five seconds. EXTENDS Naturals, FiniteSets, Sequences @@ -62,11 +53,11 @@ SRec == [kind |-> "summary", call |-> 0, mid |-> MaxMints] NoRec == [kind |-> "none", call |-> 0, mid |-> 0] RecordSet == - {SRec, PRec} \cup {ARec(m) : m \in 0..MaxMints} + {SRec} \cup {[kind |-> "plain", call |-> 0, mid |-> m] : m \in 0..MaxMints} \cup {ARec(m) : m \in 0..MaxMints} \cup {URec(c, m) : c \in 1..MaxCalls, m \in 0..MaxMints} -VARIABLES mem, disk, popped, nextMid, empties, done, summarized -vars == <> +VARIABLES mem, disk, popped, nextMid, empties, done, summarized, issued +vars == <> MemMids(mm) == {mm[i].mid : i \in 1..Len(mm)} MemSet(mm) == {mm[i] : i \in 1..Len(mm)} @@ -83,7 +74,7 @@ AddAssistant == /\ mem' = Append(mem, ARec(nextMid)) /\ nextMid' = nextMid + 1 /\ disk' = MergeSave(mem') - /\ UNCHANGED <> + /\ UNCHANGED <> \* The tool ran. The user turn with its tool result is saved. A fresh turn is \* minted only when no removed turn awaits restoration. During a retry the only @@ -96,19 +87,22 @@ AddUserResult(c) == /\ mem' = Append(mem, URec(c, nextMid)) /\ nextMid' = nextMid + 1 /\ disk' = MergeSave(mem') + /\ issued' = issued \cup {c} /\ UNCHANGED <> -\* The model sent no assistant content. The saved user turn is popped from -\* memory. The disk copy stays. +\* No assistant content arrived. Retain leaves memory unchanged. Legacy modes pop +\* the saved turn. The popped record also marks a pending retry decision in this model. EmptyResponse == /\ ~done /\ empties < MaxEmpty /\ Len(mem) >= 2 - /\ (mem[Len(mem)].kind = "u" \/ (PopSummary /\ mem[Len(mem)] = SRec)) + /\ popped = NoRec + /\ (mem[Len(mem)].kind = "u" \/ ((PopSummary \/ Mode = "Retain") /\ mem[Len(mem)] = SRec)) /\ popped' = mem[Len(mem)] /\ empties' = empties + 1 - /\ mem' = SubSeq(mem, 1, Len(mem) - 1) - /\ UNCHANGED <> + /\ mem' = IF Mode = "Retain" THEN mem ELSE SubSeq(mem, 1, Len(mem) - 1) + /\ disk' = IF Mode = "LosePending" THEN {r \in disk : r.kind # "u"} ELSE disk + /\ UNCHANGED <> \* The retry re-adds the turn and saves. Stable keeps the saved identity, so the \* merge save replaces the disk record. Fresh mints a new identity, so the merge @@ -116,14 +110,15 @@ EmptyResponse == RetryReAdd(c) == /\ ~done /\ popped # NoRec - /\ LET restored == IF Mode = "Stable" THEN (IF popped = SRec THEN PRec ELSE popped) ELSE URec(c, nextMid) - replaced == IF Mode = "Stable" THEN popped.mid ELSE nextMid - IN /\ Mode = "Stable" \/ nextMid < MaxMints - /\ mem' = Append(mem, restored) - /\ nextMid' = IF Mode = "Stable" THEN nextMid ELSE nextMid + 1 + /\ LET restored == IF Mode = "LoseRetry" THEN [kind |-> "plain", call |-> 0, mid |-> popped.mid] + ELSE IF Mode # "Fresh" THEN (IF popped = SRec THEN PRec ELSE popped) ELSE URec(c, nextMid) + replaced == IF Mode # "Fresh" THEN popped.mid ELSE nextMid + IN /\ Mode # "Fresh" \/ nextMid < MaxMints + /\ mem' = IF Mode = "Retain" THEN mem ELSE Append(mem, restored) + /\ nextMid' = IF Mode # "Fresh" THEN nextMid ELSE nextMid + 1 /\ disk' = {r \in disk : r.mid # replaced} \cup MemSet(mem') /\ popped' = NoRec - /\ UNCHANGED <> + /\ UNCHANGED <> \* The user declines the retry. The popped turn is restored with its identity, \* then a synthetic failure turn is saved and the turn ends. @@ -131,29 +126,31 @@ RetryDeclined(c) == /\ ~done /\ popped # NoRec /\ nextMid + 1 < MaxMints - /\ LET restored == IF Mode = "Stable" THEN (IF popped = SRec THEN PRec ELSE popped) ELSE URec(c, nextMid) - nextAfter == IF Mode = "Stable" THEN nextMid ELSE nextMid + 1 - afterRestore == Append(Append(mem, restored), ARec(nextAfter)) + /\ LET restored == IF Mode = "LoseDecline" THEN [kind |-> "plain", call |-> 0, mid |-> popped.mid] + ELSE IF Mode # "Fresh" THEN (IF popped = SRec THEN PRec ELSE popped) ELSE URec(c, nextMid) + nextAfter == IF Mode # "Fresh" THEN nextMid ELSE nextMid + 1 + afterRestore == Append(IF Mode = "Retain" THEN mem ELSE Append(mem, restored), ARec(nextAfter)) IN /\ mem' = afterRestore /\ nextMid' = nextAfter + 1 /\ disk' = {r \in disk : ~r.mid \in MemMids(mem')} \cup MemSet(mem') /\ popped' = NoRec /\ done' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> \* The retry gets a real assistant response. The turn ends. CompleteTurn == /\ ~done /\ Len(mem) >= 2 - /\ mem[Len(mem)].kind = "u" + /\ popped = NoRec + /\ mem[Len(mem)].kind \in {"u", "summary"} /\ nextMid < MaxMints /\ mem' = Append(mem, ARec(nextMid)) /\ nextMid' = nextMid + 1 /\ disk' = MergeSave(mem') /\ done' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> -\* Context management replaces the saved history before the pop or during backoff. +\* Context management covers the saved history before retry or during backoff. Condense == /\ ~done /\ SRec \notin disk @@ -162,10 +159,10 @@ Condense == /\ mem' = Append(mem, SRec) /\ disk' = {SRec} /\ summarized' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> \* Once context management saves a summary, a retry must keep its metadata. -SummarySurvives == summarized => SRec \in disk +SummarySurvives == summarized => SRec \in disk /\ SRec \in MemSet(mem) Init == /\ mem = <<>> @@ -175,6 +172,7 @@ Init == /\ empties = 0 /\ done = FALSE /\ summarized = FALSE + /\ issued = {} Next == \/ Condense @@ -197,6 +195,8 @@ TypeOK == /\ empties \in Nat /\ empties =< MaxEmpty /\ done \in BOOLEAN + /\ summarized \in BOOLEAN + /\ issued \subseteq 1..MaxCalls \* The opposite of the failure: the saved history holds at most one result \* record per tool call, so a reload sends one tool_result per tool_use id. @@ -204,11 +204,16 @@ OneResultPerCall == \A c \in 1..MaxCalls : Cardinality({r \in disk : r.kind = "u" /\ r.call = c}) <= 1 -\* The fix must not lose the result: when the turn ends, every issued call -\* still has its saved result. +\* Retain keeps every saved result in memory while a retry or ask is pending. +\* The earlier Stable protocol violates this property between pop and restore. +ResultInMemory == + ~summarized => + issued \subseteq {mem[i].call : i \in {j \in 1..Len(mem) : mem[j].kind = "u"}} + +\* Once saved, each issued result stays on disk, including during the pop. +\* Condense deliberately replaces results with a summary and ends this obligation. ResultNeverLost == - done /\ SRec \notin disk => - \A c \in 1..MaxCalls : - Cardinality({r \in disk : r.kind = "u" /\ r.call = c}) = 1 + ~summarized => + issued \subseteq {r.call : r \in {d \in disk : d.kind = "u"}} ==== diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 1b3e35c9594..39c7daf2c92 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -1451,11 +1451,7 @@ export class Task extends EventEmitter implements TaskLike { * Appends an API turn and records whether an assistant turn reached persistent storage. * If the message resolves a pending action, retries the save on initial failure before clearing the action. */ - private async addToApiConversationHistory( - message: Anthropic.MessageParam, - reasoning?: string, - options?: { identity?: { messageId?: string; ts?: number } }, - ): Promise { + private async addToApiConversationHistory(message: Anthropic.MessageParam, reasoning?: string): Promise { const resolvesPendingAction = this.pendingAction && message.role === "user" && @@ -1470,7 +1466,6 @@ export class Task extends EventEmitter implements TaskLike { api: this.api, apiConfiguration: this.apiConfiguration, apiConversationHistory: this.apiConversationHistory, - identity: options?.identity, }), ) @@ -4017,7 +4012,6 @@ export class Task extends EventEmitter implements TaskLike { pendingContent?: Promise // Resolved after the request row shows includeFileDetails: boolean retryAttempt?: number - removedUserMessage?: ApiMessage // The saved record removed for the empty-response retry, restored with its identity } const stack: StackItem[] = [ @@ -4123,20 +4117,14 @@ export class Task extends EventEmitter implements TaskLike { // Add environment details as its own text block, separate from tool // results. const finalUserContent = [...contentWithoutEnvDetails, { type: "text" as const, text: environmentDetails }] - // See shouldAddUserMessageToHistory for the full add/skip rules (retry/empty/removed). + // Retries reuse the saved turn. Empty content can resume a turn already in history. const isEmptyUserContent = currentUserContent.length === 0 const shouldAddUserMessage = shouldAddUserMessageToHistory({ retryAttempt: currentItem.retryAttempt, isEmptyUserContent, - userMessageWasRemoved: currentItem.removedUserMessage !== undefined, }) - let addedUserMessageId: string | undefined if (shouldAddUserMessage) { - // Reuse the saved identity so the merge save replaces the original turn. - await this.addToApiConversationHistory({ role: "user", content: finalUserContent }, undefined, { - identity: currentItem.removedUserMessage, - }) - addedUserMessageId = this.apiConversationHistory.at(-1)?.messageId + await this.addToApiConversationHistory({ role: "user", content: finalUserContent }) this.messageCounts.user++ } @@ -5269,22 +5257,7 @@ export class Task extends EventEmitter implements TaskLike { } const state = await this.providerRef.deref()?.getState() - // Context management can replace the added turn with a summary. - // Remove only the turn that this iteration added. - let removedUserMessage: ApiMessage | undefined - const lastMessage = this.apiConversationHistory.at(-1) - if ( - addedUserMessageId !== undefined && - lastMessage?.messageId === addedUserMessageId && - lastMessage.role === "user" && - !lastMessage.isSummary - ) { - // The retry must reuse this identity to replace the saved disk record. - removedUserMessage = lastMessage - this.apiConversationHistory.pop() - this.messageCounts.user-- - } - + // Keep the saved user turn in place for retry, decline, or cancellation. // Wait for the automatic retry or ask the user for a retry decision. if (state?.autoApprovalEnabled) { // Auto-retry with backoff - don't persist failure message when retrying @@ -5312,19 +5285,6 @@ export class Task extends EventEmitter implements TaskLike { if (response === "yesButtonClicked") { await this.say("api_req_retried") } else { - // User declined to retry. Re-add the user message only if this - // iteration removed one, so the history and counter stay consistent. - if (removedUserMessage) { - // Restore the already saved record with its original identity so - // the merge save keeps one copy of the turn on disk. - await this.addToApiConversationHistory( - { role: "user", content: removedUserMessage.content }, - undefined, - { identity: removedUserMessage }, - ) - this.messageCounts.user++ - } - await this.say( "error", "Unexpected API Response: The language model did not provide any assistant messages. This may indicate an issue with the API or the model's output.", @@ -5342,12 +5302,11 @@ export class Task extends EventEmitter implements TaskLike { } } - // Both retry paths restore the same saved record on the next iteration. + // Retry the request without adding the saved user turn again. stack.push({ userContent: currentUserContent, includeFileDetails: false, retryAttempt: (currentItem.retryAttempt ?? 0) + 1, - removedUserMessage, }) continue } diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index de794652e51..e644e2bce09 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7280,8 +7280,6 @@ describe("Cline", () => { expect.objectContaining({ content: expect.arrayContaining([{ type: "text", text: "expanded input" }]), }), - undefined, - { identity: undefined }, ) }) diff --git a/src/core/task/__tests__/apiConversationHistory.spec.ts b/src/core/task/__tests__/apiConversationHistory.spec.ts index 9e40858b3aa..7f2e4201fcf 100644 --- a/src/core/task/__tests__/apiConversationHistory.spec.ts +++ b/src/core/task/__tests__/apiConversationHistory.spec.ts @@ -14,29 +14,22 @@ describe("prepareApiConversationMessage", () => { vi.useRealTimers() }) - it.each([{ messageId: "saved-turn", ts: 123 }, { ts: 123 }, { messageId: "saved-turn" }, undefined])( - "uses each supplied user identity field: %j", - (identity) => { - const api = { - createMessage: vi.fn(), - getModel: vi.fn(), - countTokens: vi.fn(), - getModelCacheScope: vi.fn(), - } - const options = { api, apiConfiguration: {}, apiConversationHistory: [], identity } - const user = prepareApiConversationMessage({ ...options, message: { role: "user", content: "turn" } }) - expect(user.ts).toBe(identity?.ts ?? Date.now()) - if (identity?.messageId) expect(user.messageId).toBe(identity.messageId) - else expect(user.messageId).toMatch(/^[0-9a-f-]{36}$/) - const assistant = prepareApiConversationMessage({ - ...options, - message: { role: "assistant", content: "answer" }, - }) - expect(assistant.ts).toBe(Date.now()) - expect(assistant.messageId).toMatch(/^[0-9a-f-]{36}$/) - expect(assistant.messageId).not.toBe(identity?.messageId) - }, - ) + it("creates a fresh identity for each user turn", () => { + const api = { + createMessage: vi.fn(), + getModel: vi.fn(), + countTokens: vi.fn(), + getModelCacheScope: vi.fn(), + } + const options = { api, apiConfiguration: {}, apiConversationHistory: [] } + const first = prepareApiConversationMessage({ ...options, message: { role: "user", content: "first" } }) + const second = prepareApiConversationMessage({ ...options, message: { role: "user", content: "second" } }) + expect(first.ts).toBe(Date.now()) + expect(second.ts).toBe(Date.now()) + expect(first.messageId).toMatch(/^[0-9a-f-]{36}$/) + expect(second.messageId).toMatch(/^[0-9a-f-]{36}$/) + expect(second.messageId).not.toBe(first.messageId) + }) it("prepends Anthropic thinking blocks with thought signatures", () => { const result = prepareApiConversationMessage({ diff --git a/src/core/task/__tests__/empty-response-history.spec.ts b/src/core/task/__tests__/empty-response-history.spec.ts index bdcaec7192e..c2ddd878864 100644 --- a/src/core/task/__tests__/empty-response-history.spec.ts +++ b/src/core/task/__tests__/empty-response-history.spec.ts @@ -1,9 +1,8 @@ import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker" // cd src && npx vitest run core/task/__tests__/empty-response-history.spec.ts // -// Regression for issue 2691: an empty assistant response pops the saved user -// tool-result turn from memory and the retry re-adds it. The retry must restore -// the saved identity so the merge save keeps one copy of the turn on disk, and +// Regression for issue 2691: an empty response must keep the saved user turn. +// Retries must not pop, restore, or add another copy of the tool-result turn, and // the reloaded history must convert to exactly one tool_result per tool_use id. // The suite drives the real retry branch in recursivelyMakeClineRequests with // real temporary-file saves and readback; the provider stream is stubbed at @@ -50,10 +49,6 @@ vi.mock("../../../services/code-index/code-index-manager-registry", () => ({ }, })) -vi.mock("p-wait-for", () => ({ - default: vi.fn().mockImplementation(async () => Promise.resolve()), -})) - vi.mock("vscode", () => { const mockDisposable = { dispose: vi.fn() } const mockEventEmitter = { event: vi.fn(), fire: vi.fn() } @@ -134,13 +129,13 @@ type TaskRetryProbe = { addToApiConversationHistory: (message: Anthropic.MessageParam, reasoning?: string) => Promise safeEnsureModelFetched: () => Promise backoffAndAnnounce: (retryAttempt: number, error: unknown) => Promise + presentAssistantMessageSafe: () => void globalStoragePath: string } // Private members the replay drives directly; the double provides only these. const probe = (task: Task): TaskRetryProbe => task as unknown as TaskRetryProbe -type TaskAskResult = Awaited> type ProviderState = Awaited> const stubModelInfo: ModelInfo = { @@ -292,6 +287,10 @@ describe("empty-response history persistence (issue 2691)", () => { }) vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined) + // Stream rendering is outside this suite. Complete it without replacing ask polling. + vi.spyOn(probe(task), "presentAssistantMessageSafe").mockImplementation(() => { + task.userMessageContentReady = true + }) vi.spyOn(probe(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo) await probe(task).addToApiConversationHistory({ @@ -311,8 +310,8 @@ describe("empty-response history persistence (issue 2691)", () => { } /** - * First-attempt stream that reads the saved result turn from disk while it is - * being consumed, which is before any empty-response pop can run. The identity + * First-attempt stream that reads the saved result turn from memory while it is + * being consumed, which is before any empty-response retry can run. The identity * reader is valid once the attempt has started. */ function firstAttemptCapturingSavedIdentity( @@ -337,6 +336,26 @@ describe("empty-response history persistence (issue 2691)", () => { } } + /** Keep the real ask wait pending across a poll, then deliver the webview response. */ + async function runWithRetryResponse(task: Task, response: "yesButtonClicked" | "noButtonClicked") { + let settled = false + const run = task.recursivelyMakeClineRequests(toolResultUserContent()).finally(() => { + settled = true + }) + try { + await vi.waitFor(() => expect(task.clineMessages.at(-1)?.ask).toBe("api_req_failed")) + // ask() polls every 100 ms. It must stay pending without a response. + await new Promise((resolve) => setTimeout(resolve, 150)) + expect(settled).toBe(false) + expect(countSavedResults(task.apiConversationHistory, TOOL_USE_ID)).toBe(1) + expect(task.messageCounts.user).toBe(1) + } finally { + task.handleWebviewAskResponse(response) + await run + } + return run + } + it("persists one result turn across an automatic empty-response retry with real files", async () => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) @@ -365,26 +384,30 @@ describe("empty-response history persistence (issue 2691)", () => { const disk = await readDiskHistory(task) expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) - // The restored turn keeps the identity it was saved with, so the merge save - // replaced the disk record instead of adding a second copy. + // The retry leaves the saved turn and its identity unchanged. const afterRetry = findResultMessage(disk, TOOL_USE_ID) expect(afterRetry?.messageId).toBe(beforeRetry.messageId) expect(afterRetry?.ts).toBe(beforeRetry.ts) expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) - // The pop/restore cycle stays balanced: the retried turn counts once, plus + // The saved turn counts once, plus // the separate no-tool-use continuation turn. expect(task.messageCounts.user).toBe(2) }) - it("keeps one result turn across repeated empty responses", async () => { + it.each([1, 2, 3])("keeps one result turn across %i empty responses", async (emptyCount) => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) - const attemptApiRequestSpy = vi - .spyOn(task, "attemptApiRequest") - .mockImplementationOnce(() => firstAttempt.body) - .mockImplementationOnce(() => asyncStreamFrom([])) - .mockImplementationOnce(() => asyncStreamFrom([])) + vi.spyOn(probe(task), "backoffAndAnnounce").mockImplementation(async () => { + expect(countSavedResults(task.apiConversationHistory, TOOL_USE_ID)).toBe(1) + expect(findResultMessage(task.apiConversationHistory, TOOL_USE_ID)).toMatchObject(firstAttempt.identity()) + expect(task.messageCounts.user).toBe(1) + }) + const attemptApiRequestSpy = vi.spyOn(task, "attemptApiRequest").mockImplementationOnce(() => firstAttempt.body) + for (let attempt = 1; attempt < emptyCount; attempt++) { + attemptApiRequestSpy.mockImplementationOnce(() => asyncStreamFrom([])) + } + attemptApiRequestSpy .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "finally answered" }])) .mockImplementation(() => { throw new Error("stop after retry response") @@ -394,8 +417,8 @@ describe("empty-response history persistence (issue 2691)", () => { const beforeRetry = firstAttempt.identity() - // Three empty attempts, one retried attempt, then the stopped continuation. - expect(attemptApiRequestSpy).toHaveBeenCalledTimes(5) + // Empty attempts, one answered attempt, then the stopped continuation. + expect(attemptApiRequestSpy).toHaveBeenCalledTimes(emptyCount + 2) const disk = await readDiskHistory(task) expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) @@ -408,23 +431,23 @@ describe("empty-response history persistence (issue 2691)", () => { it("keeps one result turn when the retry is declined and records the failure", async () => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: false }) - vi.spyOn(task, "ask").mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult) const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) const attemptSpy = vi.spyOn(task, "attemptApiRequest") attemptSpy.mockImplementationOnce(() => firstAttempt.body) attemptSpy.mockImplementation(() => asyncStreamFrom([])) - const result = await task.recursivelyMakeClineRequests(toolResultUserContent()) + const result = await runWithRetryResponse(task, "noButtonClicked") const beforeDecline = firstAttempt.identity() expect(result).toBe(false) const disk = await readDiskHistory(task) expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) - const restored = findResultMessage(disk, TOOL_USE_ID) - expect(restored?.messageId).toBe(beforeDecline.messageId) - expect(restored?.ts).toBe(beforeDecline.ts) - // The synthetic failure turn follows the restored user turn. + const retained = findResultMessage(disk, TOOL_USE_ID) + expect(retained?.messageId).toBe(beforeDecline.messageId) + expect(retained?.ts).toBe(beforeDecline.ts) + expect(retained?.content).toEqual(expect.arrayContaining(toolResultUserContent())) + // The synthetic failure turn follows the retained user turn. expect(disk.at(-1)).toMatchObject({ role: "assistant", content: [{ type: "text", text: "Failure: I did not provide a response." }], @@ -436,7 +459,6 @@ describe("empty-response history persistence (issue 2691)", () => { it("keeps one result turn when the user confirms an explicit retry", async () => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: false }) - vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } satisfies TaskAskResult) const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) const attemptApiRequestSpy = vi .spyOn(task, "attemptApiRequest") @@ -448,7 +470,7 @@ describe("empty-response history persistence (issue 2691)", () => { throw new Error("stop after retry response") }) - await task.recursivelyMakeClineRequests(toolResultUserContent()) + await runWithRetryResponse(task, "yesButtonClicked") // One empty attempt, one retried attempt, then the stopped continuation. expect(attemptApiRequestSpy).toHaveBeenCalledTimes(3) @@ -460,6 +482,27 @@ describe("empty-response history persistence (issue 2691)", () => { expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) }) + it("retries an empty-content resume without adding the saved result again", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) + await probe(task).addToApiConversationHistory({ role: "user", content: toolResultUserContent() }) + task.messageCounts.user = 1 + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + vi.spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "resumed" }])) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests([]) + + const disk = await readDiskHistory(task) + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + expect(findResultMessage(disk, TOOL_USE_ID)).toMatchObject(firstAttempt.identity()) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + expect(task.messageCounts.user).toBe(2) + }) + it("keeps the saved history valid when no empty response occurs (control)", async () => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) @@ -515,8 +558,7 @@ describe("empty-response history persistence (issue 2691)", () => { it.each([1, 2])("keeps a single saved result when save %i fails", async (failingWrite) => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) - // API-history saves from here: the first iteration's user turn, then the - // restore save after the empty-response pop. Fail each save in turn. + // Fail the initial result save or the assistant response save after retry. const injection = injectApiHistorySaveFailure(failingWrite) const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) @@ -545,17 +587,15 @@ describe("empty-response history persistence (issue 2691)", () => { it("keeps a single saved result when a declined retry also hits a failed save (fault injection)", async () => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: false }) - // Fail the decline restore save; the synthetic failure turn save follows. - const injection = injectApiHistorySaveFailure(2) - - vi.spyOn(task, "ask").mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult) + // Fail the initial result save. The synthetic failure turn save flushes it. + const injection = injectApiHistorySaveFailure(1) const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) const attemptSpy = vi.spyOn(task, "attemptApiRequest") attemptSpy.mockImplementationOnce(() => firstAttempt.body) attemptSpy.mockImplementation(() => asyncStreamFrom([])) - const result = await task.recursivelyMakeClineRequests(toolResultUserContent()) + const result = await runWithRetryResponse(task, "noButtonClicked") const beforeDecline = firstAttempt.identity() expect(result).toBe(false) @@ -564,9 +604,10 @@ describe("empty-response history persistence (issue 2691)", () => { const disk = await readDiskHistory(task) expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) - const restored = findResultMessage(disk, TOOL_USE_ID) - expect(restored?.messageId).toBe(beforeDecline.messageId) - expect(restored?.ts).toBe(beforeDecline.ts) + const retained = findResultMessage(disk, TOOL_USE_ID) + expect(retained?.messageId).toBe(beforeDecline.messageId) + expect(retained?.ts).toBe(beforeDecline.ts) + expect(retained?.content).toEqual(expect.arrayContaining(toolResultUserContent())) expect(disk.at(-1)).toMatchObject({ role: "assistant", content: [{ type: "text", text: "Failure: I did not provide a response." }], @@ -574,7 +615,7 @@ describe("empty-response history persistence (issue 2691)", () => { expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) }) - it.each(["before pop", "during backoff"])("keeps a summary saved %s", async (phase) => { + it.each(["before retry", "during backoff"])("keeps a summary saved %s", async (phase) => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) const summary: ApiMessage = { role: "user", @@ -593,10 +634,12 @@ describe("empty-response history persistence (issue 2691)", () => { if (phase === "during backoff") { vi.spyOn(probe(task), "backoffAndAnnounce").mockImplementation(condense) } + let original: ApiMessage | undefined vi.spyOn(task, "attemptApiRequest") .mockImplementationOnce(() => (async function* () { - if (phase === "before pop") await condense() + original = findResultMessage(task.apiConversationHistory, TOOL_USE_ID) + if (phase === "before retry") await condense() yield* asyncStreamFrom([]) })(), ) @@ -609,14 +652,33 @@ describe("empty-response history persistence (issue 2691)", () => { const disk = await readDiskHistory(task) expect(disk.find((message) => message.messageId === summary.messageId)).toEqual(summary) + expect(task.apiConversationHistory.find((message) => message.messageId === summary.messageId)).toEqual(summary) expect(getEffectiveApiHistory(disk)).toContainEqual(summary) expect(getEffectiveApiHistory(disk).some((message) => message.condenseParent === "condense-1")).toBe(false) + expect(original?.messageId).toBeDefined() + const retained = disk.filter((message) => message.messageId === original?.messageId) + expect(retained).toHaveLength(1) + expect(retained[0].ts).toBe(original?.ts) + const effective = getEffectiveApiHistory(disk) + const summaryIndex = effective.findIndex((message) => message.messageId === summary.messageId) + // Condensation covers the retained result in either phase. No copy follows the summary. + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(0) + expect(disk.indexOf(retained[0])).toBeLessThan( + disk.findIndex((message) => message.messageId === summary.messageId), + ) + expect(retained[0].content).toEqual(expect.arrayContaining(toolResultUserContent())) + expect(effective).not.toContainEqual(retained[0]) + expect(effective[summaryIndex + 1]?.role).toBe("assistant") + // The summary and the no-tool-use continuation are the only effective user turns. + expect(effective.filter((message) => message.role === "user")).toHaveLength(2) + expect(task.messageCounts.user).toBe(2) }) it("keeps the saved history valid when the task is cancelled during the retry backoff", async () => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) - // Cancel during the automatic retry backoff, before the restore can run. + // Cancel during the automatic retry backoff with the result still in history. vi.spyOn(probe(task), "backoffAndAnnounce").mockImplementation(async () => { setAbortLatch(task, true) }) @@ -627,8 +689,10 @@ describe("empty-response history persistence (issue 2691)", () => { expect(result).toBe(false) const disk = await readDiskHistory(task) - // The cancelled cycle restored nothing: the original saved turn stays alone. + // Cancellation keeps the original saved result in memory and on disk. expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + expect(countSavedResults(task.apiConversationHistory, TOOL_USE_ID)).toBe(1) + expect(task.messageCounts.user).toBe(1) }) }) diff --git a/src/core/task/__tests__/messageCounting.spec.ts b/src/core/task/__tests__/messageCounting.spec.ts index 6e49473201d..27f2f6c582d 100644 --- a/src/core/task/__tests__/messageCounting.spec.ts +++ b/src/core/task/__tests__/messageCounting.spec.ts @@ -1,75 +1,14 @@ -// npx vitest run core/task/__tests__/messageCounting.spec.ts - import { shouldAddUserMessageToHistory } from "../messageCounting" describe("shouldAddUserMessageToHistory", () => { - it("adds the message on a first attempt with non-empty content", () => { - expect( - shouldAddUserMessageToHistory({ - retryAttempt: 0, - isEmptyUserContent: false, - userMessageWasRemoved: false, - }), - ).toBe(true) - }) - - it("adds the message when retryAttempt is undefined (treated as first attempt) with non-empty content", () => { - expect( - shouldAddUserMessageToHistory({ - retryAttempt: undefined, - isEmptyUserContent: false, - userMessageWasRemoved: undefined, - }), - ).toBe(true) - }) - - it("skips an empty-content first attempt (delegation resume - already in history)", () => { - expect( - shouldAddUserMessageToHistory({ - retryAttempt: 0, - isEmptyUserContent: true, - userMessageWasRemoved: false, - }), - ).toBe(false) - }) - - it("skips a retry attempt (retryAttempt > 0) with non-empty content", () => { - expect( - shouldAddUserMessageToHistory({ - retryAttempt: 1, - isEmptyUserContent: false, - userMessageWasRemoved: false, - }), - ).toBe(false) - }) - - it("re-adds the message on a retry attempt if it was previously removed", () => { - expect( - shouldAddUserMessageToHistory({ - retryAttempt: 2, - isEmptyUserContent: false, - userMessageWasRemoved: true, - }), - ).toBe(true) - }) - - it("re-adds an empty-content message if it was previously removed", () => { - expect( - shouldAddUserMessageToHistory({ - retryAttempt: 0, - isEmptyUserContent: true, - userMessageWasRemoved: true, - }), - ).toBe(true) - }) - - it("skips a retry attempt with empty content that was not removed", () => { - expect( - shouldAddUserMessageToHistory({ - retryAttempt: 3, - isEmptyUserContent: true, - userMessageWasRemoved: false, - }), - ).toBe(false) + it.each([ + { retryAttempt: undefined, expected: true }, + { retryAttempt: 0, expected: true }, + { retryAttempt: 1, expected: false }, + { retryAttempt: 2, expected: false }, + { retryAttempt: 3, expected: false }, + ])("adds non-empty content at attempt $retryAttempt: $expected", ({ retryAttempt, expected }) => { + expect(shouldAddUserMessageToHistory({ retryAttempt, isEmptyUserContent: false })).toBe(expected) + expect(shouldAddUserMessageToHistory({ retryAttempt, isEmptyUserContent: true })).toBe(false) }) }) diff --git a/src/core/task/apiConversationHistory.ts b/src/core/task/apiConversationHistory.ts index 91f0a0d9ea7..39775f24b86 100644 --- a/src/core/task/apiConversationHistory.ts +++ b/src/core/task/apiConversationHistory.ts @@ -22,14 +22,6 @@ interface PrepareApiConversationMessageOptions { api: ApiHandler apiConfiguration: ProviderSettings apiConversationHistory: ApiMessage[] - /** - * Reuse the identity (messageId + ts) of an already saved user turn instead - * of minting a fresh one. The empty-assistant-response retry restores a - * turn that is still on disk; a fresh identity would make the ordinary - * merge save retain both copies, and the reloaded history would then send - * two tool_result blocks for one tool_use id. - */ - identity?: { messageId?: string; ts?: number } } export function prepareApiConversationMessage({ @@ -38,13 +30,12 @@ export function prepareApiConversationMessage({ api, apiConfiguration, apiConversationHistory, - identity, }: PrepareApiConversationMessageOptions): ApiMessage { if (message.role === "assistant") { return prepareAssistantMessage(message, reasoning, api as ApiHistoryHandler, apiConfiguration) } - return prepareUserMessage(message, apiConversationHistory, identity) + return prepareUserMessage(message, apiConversationHistory) } function prepareAssistantMessage( @@ -127,11 +118,7 @@ function prepareAssistantMessage( return messageWithTs } -function prepareUserMessage( - message: Anthropic.MessageParam, - apiConversationHistory: ApiMessage[], - identity?: { messageId?: string; ts?: number }, -): ApiMessage { +function prepareUserMessage(message: Anthropic.MessageParam, apiConversationHistory: ApiMessage[]): ApiMessage { const effectiveHistoryForValidation = getEffectiveApiHistory(apiConversationHistory) const lastEffective = effectiveHistoryForValidation[effectiveHistoryForValidation.length - 1] const historyForValidation = lastEffective?.role === "assistant" ? effectiveHistoryForValidation : [] @@ -154,8 +141,8 @@ function prepareUserMessage( const validatedMessage = validateAndFixToolResultIds(messageToAdd, historyForValidation) return { ...validatedMessage, - messageId: identity?.messageId ?? crypto.randomUUID(), - ts: identity?.ts ?? Date.now(), + messageId: crypto.randomUUID(), + ts: Date.now(), } } diff --git a/src/core/task/messageCounting.ts b/src/core/task/messageCounting.ts index 11a886d6197..98ba0c4904b 100644 --- a/src/core/task/messageCounting.ts +++ b/src/core/task/messageCounting.ts @@ -1,20 +1,10 @@ /** - * Whether the current turn's user message should be added to API conversation - * history (and counted towards the per-task message-count telemetry summary). - * - * Only added when: - * 1. This is the first attempt (retryAttempt === 0) AND the content is non-empty, OR - * 2. The message was removed in a previous iteration (userMessageWasRemoved === true) - * - * Empty content on a first attempt signals a delegation resume, where the user message - * with tool_result and env details is already in history -- adding it again would create - * a duplicate (and inflate the message count). + * Add non-empty user content on the first attempt. Retries keep the saved turn. + * Empty initial content resumes a turn that is already in history. */ export function shouldAddUserMessageToHistory(params: { retryAttempt: number | undefined isEmptyUserContent: boolean - userMessageWasRemoved: boolean | undefined }): boolean { - const { retryAttempt, isEmptyUserContent, userMessageWasRemoved } = params - return ((retryAttempt ?? 0) === 0 && !isEmptyUserContent) || Boolean(userMessageWasRemoved) + return (params.retryAttempt ?? 0) === 0 && !params.isEmptyUserContent } From 2961f784a2d3683336c059646dc770ebe13e1878 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Fri, 27 Nov 2026 02:03:03 +0000 Subject: [PATCH 4/4] test: cover retry declines and cancellation, update TLA review notes --- docs/architecture/tla/ToolResultRetry.tla | 67 +++++++------------ src/core/task/__tests__/Task.spec.ts | 8 +-- .../__tests__/empty-response-history.spec.ts | 56 ++++++++++++++-- .../task/__tests__/messageCounting.spec.ts | 2 +- 4 files changed, 81 insertions(+), 52 deletions(-) diff --git a/docs/architecture/tla/ToolResultRetry.tla b/docs/architecture/tla/ToolResultRetry.tla index 94535308b39..e84d341b4a1 100644 --- a/docs/architecture/tla/ToolResultRetry.tla +++ b/docs/architecture/tla/ToolResultRetry.tla @@ -1,46 +1,29 @@ ---- MODULE ToolResultRetry ---- -\* Source: recursivelyMakeClineRequests in Task.ts retains a saved turn across retries. -\* Sink: saveApiMessages and mergeApiMessageSnapshots retain disk-only identities. -\* Reload and provider conversion send one result block per saved result record. -\* Failure: a retry duplicates or loses a result, or replaces a saved summary. -\* Invariants: OneResultPerCall limits duplicates. ResultNeverLost retains each -\* issued result until Condense replaces it. SummarySurvives retains summary metadata. -\* Retain leaves the saved turn in place. Stable models the earlier identity restore. -\* Fresh mints identity. PopSummary removes the earlier pop guard. -\* LosePending deletes the disk result at pop. LoseRetry and LoseDecline replace -\* the restored result with a plain record at their respective save boundaries. -\* Expected: Retain passes all invariants. Stable passes the disk invariants. -\* Stable fails ResultInMemory. All sabotage modes fail. -\* Condense abstracts overwriteApiConversationHistory before retry or during backoff. -\* Not modeled: payload parsing, timestamps, message counters, ask delivery, prompt -\* order, save failures, cancellation, rewind, deletion, output-limit retries, or concurrency. -\* Initial invariants predate this review. This pass extends them from the findings. -\* PR #2701 review ratchet (supplied summary, no thread URL): 1 covered, 2 added, -\* 4 gap. Covered: identity guard. Added: loss checks and summarized type. Gaps: -\* summary test strength, ask delivery, header prose, and test helper prose. -\* Earlier checks: Fresh failed duplication. PopSummary failed summary retention. -\* Policy requires cost and findings here. These are model results, not a code proof. -\* Earlier result: Stable passed with 38 states. Fresh and PopSummary failed with 8 and 11. -\* Earlier loss checks failed LosePending, LoseRetry, and LoseDecline with 6, 12, and 13 states. -\* Replay: disk overwrite at pop and plain-text restore mutations fail real-file tests. -\* Unconditional restore and missing identity-guard mutations fail the summary tests. -\* Empty-array restore is repaired by validation. Assistant restore leaves the old -\* disk record. These are false alarms for result loss, so the loss modes use plain records. -\* Property test: retry counts 1 to 3 retain one saved result with its identity. -\* Null result: no new production defect was found beyond the review findings. -\* Simplification expectation: no pop needs no restore, identity option, or counter adjustment. -\* Condense covers the retained turn before or during backoff. No plain copy follows it. -\* Ask polling and input cardinality remain gaps. Real polling and retry-count tests cover them. -\* Added ResultInMemory: the saved result stays in memory until Condense covers it. -\* SummarySurvives now checks memory and disk. Both are required by the retained-turn design. -\* Expected sabotage: Stable fails ResultInMemory at EmptyResponse; the real backoff test must fail. -\* Result: Retain passes with 44 states. Stable fails ResultInMemory with 6 states. -\* Fresh fails with 9 states. Summary sabotage fails with 7 states. -\* Loss sabotage fails pending, retry, and decline with 6, 13, and 14 states. -\* Replay: adding a pop to the new runtime fails backoff, pending ask, and cancellation tests. -\* The real ask wait now stays pending across polling until the handler receives a response. -\* Null result: no new production bug was found. The design removes the transient missing turn. -\* Cost: about eight agent minutes for this simplification; TLC runs take under five seconds. +\* Source: Task.recursivelyMakeClineRequests retains the saved user turn on retry. +\* Sink: saveApiMessages and mergeApiMessageSnapshots merge records by identity. +\* Failure: retry duplicates or loses a result, or removes a saved summary. +\* Invariants: OneResultPerCall prevents duplicates. ResultNeverLost retains disk +\* results. ResultInMemory retains memory results. SummarySurvives keeps summaries. +\* Expected: Retain passes. Legacy pop and loss sabotage violate retention. +\* Config modes: base=Retain, Current=Fresh (pre-fix), Popped=Stable, +\* Summary=Stable with PopSummary; LosePending/LoseRetry/LoseDecline use named modes. +\* Results: base passes 44 states; Current fails 9; Popped fails 6; Summary fails 7. +\* LosePending, LoseRetry, and LoseDecline fail with 6, 13, and 14 states. +\* Code checks: retry counts 1 to 3, decline responses, and cancellation retain results. +\* Pop sabotage fails the real-file tests. Plain-record restore loses results; +\* empty-array restore is repaired by validation and was a false alarm. +\* Not modeled: payload parsing, timestamps, counters, ask delivery, environment +\* details, save failures, cancellation signals, rewind, deletion, output-limit +\* retries, request ordering, or concurrent writes. Cancellation leaves model state unchanged. +\* PR #2701 prior review: 1 covered, 2 added, 4 gap. +\* PR #2701 supplied review summary, findings 1-11: 2 covered, 0 added, 9 gap. +\* Covered: #3 decline, #4 pending retention. +\* Gaps: #1 PR prose, #2 header, #5 retry bounds/environment, #7 test names, +\* #6 save failures, #8 counters/overwrite, #9 rewind, #10 consumers, #11 style. +\* Expect no new model defect from these test and documentation changes. +\* Null result: no new production defect found. Tests check boundaries outside the model. +\* Cost: prior simplification about eight agent minutes; this review about ten. +\* TLC runs take under five seconds. These bounded results do not prove the code. EXTENDS Naturals, FiniteSets, Sequences diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index e644e2bce09..6b955d34009 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -490,7 +490,7 @@ describe("Cline", () => { } describe("empty-response retries", () => { - it("restores the user message before a confirmed empty-response retry", async () => { + it("keeps the saved user message before a confirmed empty-response retry", async () => { const task = await createTaskWithManualRetries() let retryHistory: ApiMessage[] | undefined let retryUserMessageCount: number | undefined @@ -526,7 +526,7 @@ describe("Cline", () => { expect(retryUserMessageCount).toBe(1) }) - it("restores the user message and records the failure when retry is declined", async () => { + it("keeps the saved user message and records the failure when retry is declined", async () => { const task = await createTaskWithManualRetries() vi.spyOn(task, "ask").mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult) @@ -535,9 +535,7 @@ describe("Cline", () => { const result = await task.recursivelyMakeClineRequests([{ type: "text", text: "original user request" }]) expect(result).toBe(false) - // The decline path restores the exact record that was saved for the failed - // attempt (original identity and content, including the environment-details - // block) so persistence keeps one copy of the turn (issue #2691). + // The decline keeps the saved user turn before the failure record (issue #2691). expect(task.apiConversationHistory).toMatchObject([ { role: "user", diff --git a/src/core/task/__tests__/empty-response-history.spec.ts b/src/core/task/__tests__/empty-response-history.spec.ts index c2ddd878864..6dd8061075c 100644 --- a/src/core/task/__tests__/empty-response-history.spec.ts +++ b/src/core/task/__tests__/empty-response-history.spec.ts @@ -28,6 +28,7 @@ import { mergeConsecutiveApiMessages } from "../mergeConsecutiveApiMessages" import { convertToOpenAiMessages } from "../../../api/transform/openai-format" import { setAbortLatch } from "../../../test-utils/run-state" import { asyncStreamFrom } from "../../../test-utils/stream" +import { getEnvironmentDetails } from "../../environment/getEnvironmentDetails" import type { ApiStreamChunk } from "../../../api/transform/stream" import * as safeWriteJsonModule from "../../../utils/safeWriteJson" @@ -195,6 +196,7 @@ describe("empty-response history persistence (issue 2691)", () => { }) beforeEach(async () => { + vi.mocked(getEnvironmentDetails).mockResolvedValue("") if (!TelemetryService.hasInstance()) { TelemetryService.createInstance([]) } @@ -337,7 +339,11 @@ describe("empty-response history persistence (issue 2691)", () => { } /** Keep the real ask wait pending across a poll, then deliver the webview response. */ - async function runWithRetryResponse(task: Task, response: "yesButtonClicked" | "noButtonClicked") { + async function runWithRetryResponse( + task: Task, + response: "yesButtonClicked" | "noButtonClicked" | "messageResponse", + text?: string, + ) { let settled = false const run = task.recursivelyMakeClineRequests(toolResultUserContent()).finally(() => { settled = true @@ -350,7 +356,7 @@ describe("empty-response history persistence (issue 2691)", () => { expect(countSavedResults(task.apiConversationHistory, TOOL_USE_ID)).toBe(1) expect(task.messageCounts.user).toBe(1) } finally { - task.handleWebviewAskResponse(response) + task.handleWebviewAskResponse(response, text) await run } return run @@ -428,7 +434,10 @@ describe("empty-response history persistence (issue 2691)", () => { expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) }) - it("keeps one result turn when the retry is declined and records the failure", async () => { + it.each([ + { response: "noButtonClicked" as const, text: undefined }, + { response: "messageResponse" as const, text: "Stop retrying" }, + ])("keeps one result turn on $response decline and records the failure", async ({ response, text }) => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: false }) const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) @@ -436,7 +445,7 @@ describe("empty-response history persistence (issue 2691)", () => { attemptSpy.mockImplementationOnce(() => firstAttempt.body) attemptSpy.mockImplementation(() => asyncStreamFrom([])) - const result = await runWithRetryResponse(task, "noButtonClicked") + const result = await runWithRetryResponse(task, response, text) const beforeDecline = firstAttempt.identity() expect(result).toBe(false) @@ -613,6 +622,7 @@ describe("empty-response history persistence (issue 2691)", () => { content: [{ type: "text", text: "Failure: I did not provide a response." }], }) expect(outgoingToolResultCount(disk, TOOL_USE_ID)).toBe(1) + expect(task.messageCounts).toEqual({ user: 1, assistant: 1 }) }) it.each(["before retry", "during backoff"])("keeps a summary saved %s", async (phase) => { @@ -675,6 +685,44 @@ describe("empty-response history persistence (issue 2691)", () => { expect(task.messageCounts.user).toBe(2) }) + it("keeps the saved result when cancelled during a pending manual retry ask", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: false }) + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + const attempt = vi.spyOn(task, "attemptApiRequest").mockImplementationOnce(() => firstAttempt.body) + const run = task.recursivelyMakeClineRequests(toolResultUserContent()) + try { + await vi.waitFor(() => expect(task.clineMessages.at(-1)?.ask).toBe("api_req_failed")) + } finally { + setAbortLatch(task, true) + await run + } + expect(attempt).toHaveBeenCalledOnce() + for (const history of [task.apiConversationHistory, await readDiskHistory(task)]) { + expect(countSavedResults(history, TOOL_USE_ID)).toBe(1) + expect(findResultMessage(history, TOOL_USE_ID)).toMatchObject(firstAttempt.identity()) + } + expect(task.messageCounts.user).toBe(1) + }) + + it("retains the original environment details across a retry", async () => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) + vi.mocked(getEnvironmentDetails) + .mockResolvedValueOnce("original environment") + .mockResolvedValue("updated environment") + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + let retryContent: ApiMessage["content"] | undefined + vi.spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementationOnce(() => { + retryContent = findResultMessage(task.apiConversationHistory, TOOL_USE_ID)?.content + setAbortLatch(task, true) + return asyncStreamFrom([]) + }) + await task.recursivelyMakeClineRequests(toolResultUserContent()) + expect(retryContent).toContainEqual({ type: "text", text: "original environment" }) + expect(retryContent).not.toContainEqual({ type: "text", text: "updated environment" }) + }) + it("keeps the saved history valid when the task is cancelled during the retry backoff", async () => { const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) diff --git a/src/core/task/__tests__/messageCounting.spec.ts b/src/core/task/__tests__/messageCounting.spec.ts index 27f2f6c582d..b2ba24e90a4 100644 --- a/src/core/task/__tests__/messageCounting.spec.ts +++ b/src/core/task/__tests__/messageCounting.spec.ts @@ -7,7 +7,7 @@ describe("shouldAddUserMessageToHistory", () => { { retryAttempt: 1, expected: false }, { retryAttempt: 2, expected: false }, { retryAttempt: 3, expected: false }, - ])("adds non-empty content at attempt $retryAttempt: $expected", ({ retryAttempt, expected }) => { + ])("attempt $retryAttempt adds non-empty content: $expected; skips empty content", ({ retryAttempt, expected }) => { expect(shouldAddUserMessageToHistory({ retryAttempt, isEmptyUserContent: false })).toBe(expected) expect(shouldAddUserMessageToHistory({ retryAttempt, isEmptyUserContent: true })).toBe(false) })