diff --git a/docs/architecture/tla/ToolResultRetry.Current.cfg b/docs/architecture/tla/ToolResultRetry.Current.cfg new file mode 100644 index 0000000000..9aff3702db --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.Current.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CONSTANTS + PopSummary = FALSE + Mode = "Fresh" + MaxCalls = 1 + MaxEmpty = 2 + MaxMints = 4 +INVARIANTS TypeOK OneResultPerCall ResultNeverLost SummarySurvives +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.LoseDecline.cfg b/docs/architecture/tla/ToolResultRetry.LoseDecline.cfg new file mode 100644 index 0000000000..c5ee80de07 --- /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 0000000000..7e184954f1 --- /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 0000000000..95e9ea3a08 --- /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 0000000000..0962550b44 --- /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.Summary.cfg b/docs/architecture/tla/ToolResultRetry.Summary.cfg new file mode 100644 index 0000000000..a19edefb48 --- /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 new file mode 100644 index 0000000000..3b9d147852 --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.cfg @@ -0,0 +1,9 @@ +SPECIFICATION Spec +CONSTANTS + PopSummary = FALSE + Mode = "Retain" + MaxCalls = 2 + MaxEmpty = 2 + MaxMints = 4 +INVARIANTS TypeOK OneResultPerCall ResultNeverLost SummarySurvives ResultInMemory +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/ToolResultRetry.tla b/docs/architecture/tla/ToolResultRetry.tla new file mode 100644 index 0000000000..e84d341b4a --- /dev/null +++ b/docs/architecture/tla/ToolResultRetry.tla @@ -0,0 +1,202 @@ +---- MODULE ToolResultRetry ---- +\* 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 + +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 == + {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, issued +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. During a 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') + /\ issued' = issued \cup {c} + /\ UNCHANGED <> + +\* 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 + /\ popped = NoRec + /\ (mem[Len(mem)].kind = "u" \/ ((PopSummary \/ Mode = "Retain") /\ mem[Len(mem)] = SRec)) + /\ popped' = mem[Len(mem)] + /\ empties' = empties + 1 + /\ 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 +\* save keeps both records. +RetryReAdd(c) == + /\ ~done + /\ popped # NoRec + /\ 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 <> + +\* 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 = "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 <> + +\* The retry gets a real assistant response. The turn ends. +CompleteTurn == + /\ ~done + /\ Len(mem) >= 2 + /\ 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 <> + +\* Context management covers the saved history before retry 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 /\ SRec \in MemSet(mem) + +Init == + /\ mem = <<>> + /\ disk = {} + /\ popped = NoRec + /\ nextMid = 0 + /\ empties = 0 + /\ done = FALSE + /\ summarized = FALSE + /\ issued = {} + +Next == + \/ Condense + \/ 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 + /\ 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. +OneResultPerCall == + \A c \in 1..MaxCalls : + Cardinality({r \in disk : r.kind = "u" /\ r.call = c}) <= 1 + +\* 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 == + ~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 3b2771ddfa..39c7daf2c9 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -4012,7 +4012,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 } const stack: StackItem[] = [ @@ -4118,12 +4117,11 @@ 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.userMessageWasRemoved, }) if (shouldAddUserMessage) { await this.addToApiConversationHistory({ role: "user", content: finalUserContent }) @@ -5258,27 +5256,9 @@ 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 - if (shouldAddUserMessage && this.apiConversationHistory.length > 0) { - const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1] - if (lastMessage.role === "user") { - this.apiConversationHistory.pop() - this.messageCounts.user-- - removedCurrentUserMessage = true - } - } - - // Check if we should auto-retry or prompt the user - // Reuse the state variable from above + // 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 await this.backoffAndAnnounce( @@ -5295,19 +5275,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, - }) - - // Continue to retry the request - continue } else { // Prompt the user for retry decision const { response } = await this.ask( @@ -5317,29 +5284,7 @@ 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, - }) - - // 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) { - await this.addToApiConversationHistory({ - role: "user", - content: currentUserContent, - }) - 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.", @@ -5353,8 +5298,17 @@ export class Task extends EventEmitter implements TaskLike { content: [{ type: "text", text: "Failure: I did not provide a response." }], }) this.messageCounts.assistant++ + return false } } + + // Retry the request without adding the saved user turn again. + stack.push({ + userContent: currentUserContent, + includeFileDetails: false, + retryAttempt: (currentItem.retryAttempt ?? 0) + 1, + }) + 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 cea34e05d1..6b955d3400 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,8 +535,15 @@ describe("Cline", () => { const result = await task.recursivelyMakeClineRequests([{ type: "text", text: "original user request" }]) expect(result).toBe(false) + // The decline keeps the saved user turn before the failure record (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__/apiConversationHistory.spec.ts b/src/core/task/__tests__/apiConversationHistory.spec.ts index 5e737c4ef1..7f2e4201fc 100644 --- a/src/core/task/__tests__/apiConversationHistory.spec.ts +++ b/src/core/task/__tests__/apiConversationHistory.spec.ts @@ -14,6 +14,23 @@ describe("prepareApiConversationMessage", () => { vi.useRealTimers() }) + 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({ 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 new file mode 100644 index 0000000000..6dd8061075 --- /dev/null +++ b/src/core/task/__tests__/empty-response-history.spec.ts @@ -0,0 +1,746 @@ +import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker" +// cd src && npx vitest run core/task/__tests__/empty-response-history.spec.ts +// +// 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 +// 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 { asyncStreamFrom } from "../../../test-utils/stream" +import { getEnvironmentDetails } from "../../environment/getEnvironmentDetails" +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("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 + 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 ProviderState = Awaited> + +const stubModelInfo: ModelInfo = { + contextWindow: 200_000, + maxTokens: 8_192, + supportsPromptCache: true, +} + +const TOOL_USE_ID = "toolu_retry_01" + +/** 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 () => { + vi.mocked(getEnvironmentDetails).mockResolvedValue("") + 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) + // 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({ + 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 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( + 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(task.apiConversationHistory, 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 } + }, + } + } + + /** Keep the real ask wait pending across a poll, then deliver the webview response. */ + async function runWithRetryResponse( + task: Task, + response: "yesButtonClicked" | "noButtonClicked" | "messageResponse", + text?: string, + ) { + 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, text) + 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 }) + + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementationOnce(() => asyncStreamFrom([{ 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 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 saved turn counts once, plus + // the separate no-tool-use continuation turn. + expect(task.messageCounts.user).toBe(2) + }) + + 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, []) + 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") + }) + + await task.recursivelyMakeClineRequests(toolResultUserContent()) + + const beforeRetry = firstAttempt.identity() + + // 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) + 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.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, []) + const attemptSpy = vi.spyOn(task, "attemptApiRequest") + attemptSpy.mockImplementationOnce(() => firstAttempt.body) + attemptSpy.mockImplementation(() => asyncStreamFrom([])) + + const result = await runWithRetryResponse(task, response, text) + + const beforeDecline = firstAttempt.identity() + expect(result).toBe(false) + + const disk = await readDiskHistory(task) + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + 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." }], + }) + 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 }) + + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementationOnce(() => + asyncStreamFrom([{ type: "text", text: "explicit retry worked" }]), + ) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await runWithRetryResponse(task, "yesButtonClicked") + + // 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(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) + }) + + 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 }) + + 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; 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" }) + } + } + return originalSafeWriteJson(filePath, data, options) + }) + return { + restore: () => writeSpy.mockRestore(), + failures: () => failures, + } + } + + it.each([1, 2])("keeps a single saved result when save %i fails", async (failingWrite) => { + const task = await createTaskWithSavedToolUse({ autoApprovalEnabled: true }) + + // Fail the initial result save or the assistant response save after retry. + const injection = injectApiHistorySaveFailure(failingWrite) + + const firstAttempt = firstAttemptCapturingSavedIdentity(task, []) + vi.spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => firstAttempt.body) + .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "retry succeeded" }])) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests(toolResultUserContent()) + + const beforeRetry = firstAttempt.identity() + expect(injection.failures()).toBe(1) + injection.restore() + + const disk = await readDiskHistory(task) + // 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) + 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 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 runWithRetryResponse(task, "noButtonClicked") + + const beforeDecline = firstAttempt.identity() + expect(result).toBe(false) + expect(injection.failures()).toBe(1) + injection.restore() + + const disk = await readDiskHistory(task) + expect(countSavedResults(disk, TOOL_USE_ID)).toBe(1) + 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." }], + }) + 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) => { + 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) + } + let original: ApiMessage | undefined + vi.spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => + (async function* () { + original = findResultMessage(task.apiConversationHistory, TOOL_USE_ID) + if (phase === "before retry") 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(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 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 }) + + // Cancel during the automatic retry backoff with the result still in history. + vi.spyOn(probe(task), "backoffAndAnnounce").mockImplementation(async () => { + setAbortLatch(task, true) + }) + vi.spyOn(task, "attemptApiRequest").mockImplementation(() => asyncStreamFrom([])) + + const result = await task.recursivelyMakeClineRequests(toolResultUserContent()) + + expect(result).toBe(false) + + const disk = await readDiskHistory(task) + // 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 6e49473201..b2ba24e90a 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 }, + ])("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) }) }) diff --git a/src/core/task/apiConversationHistory.ts b/src/core/task/apiConversationHistory.ts index cb358949f5..39775f24b8 100644 --- a/src/core/task/apiConversationHistory.ts +++ b/src/core/task/apiConversationHistory.ts @@ -139,7 +139,11 @@ function prepareUserMessage(message: Anthropic.MessageParam, apiConversationHist } const validatedMessage = validateAndFixToolResultIds(messageToAdd, historyForValidation) - return { ...validatedMessage, messageId: crypto.randomUUID(), ts: Date.now() } + return { + ...validatedMessage, + messageId: crypto.randomUUID(), + ts: Date.now(), + } } function prependContentBlock(message: any, block: any): void { diff --git a/src/core/task/messageCounting.ts b/src/core/task/messageCounting.ts index 11a886d619..98ba0c4904 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 }