Skip to content

Commit ba7c3d9

Browse files
PierrunoYTclaude
andcommitted
fix(task): keep history attempt separate from the mid-stream auto-retry count
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 0f1085b commit ba7c3d9

2 files changed

Lines changed: 55 additions & 8 deletions

File tree

‎src/core/task/Task.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3866,6 +3866,9 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
38663866
userContent: Anthropic.Messages.ContentBlockParam[]
38673867
includeFileDetails: boolean
38683868
retryAttempt?: number
3869+
// Automatic retries of a mid-stream failure. Kept apart from `retryAttempt`, which also
3870+
// tells shouldAddUserMessageToHistory that the user message is already in history.
3871+
midStreamAutoRetries?: number
38693872
userMessageWasRemoved?: boolean // Track if user message was removed due to empty response
38703873
}
38713874

@@ -4674,7 +4677,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
46744677
continue
46754678
} else {
46764679
const stateForBackoff = await this.providerRef.deref()?.getState()
4677-
const midStreamRetryAttempt = currentItem.retryAttempt ?? 0
4680+
const midStreamRetryAttempt = currentItem.midStreamAutoRetries ?? 0
46784681

46794682
// Without auto-approval, or once automatic retries are exhausted, a
46804683
// persistently failing stream (e.g. an upstream idle timeout) would
@@ -4690,10 +4693,13 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
46904693
}
46914694

46924695
await this.say("api_req_retried")
4696+
// The user message is already in history, so keep the history attempt positive
4697+
// and only reset the automatic-retry count.
46934698
stack.push({
46944699
userContent: currentUserContent,
46954700
includeFileDetails: false,
4696-
retryAttempt: 0,
4701+
retryAttempt: (currentItem.retryAttempt ?? 0) + 1,
4702+
midStreamAutoRetries: 0,
46974703
})
46984704
continue
46994705
}
@@ -4704,7 +4710,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
47044710
)
47054711

47064712
// Apply exponential backoff similar to first-chunk errors
4707-
await this.backoffAndAnnounce(currentItem.retryAttempt ?? 0, error)
4713+
await this.backoffAndAnnounce(midStreamRetryAttempt, error)
47084714

47094715
// Check if task was aborted during the backoff
47104716
if (this.abort) {
@@ -4721,6 +4727,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
47214727
userContent: currentUserContent,
47224728
includeFileDetails: false,
47234729
retryAttempt: (currentItem.retryAttempt ?? 0) + 1,
4730+
midStreamAutoRetries: midStreamRetryAttempt + 1,
47244731
})
47254732

47264733
// Continue to retry the request

‎src/core/task/__tests__/Task.spec.ts‎

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -631,11 +631,11 @@ describe("Cline", () => {
631631

632632
// 5 is MAX_MID_STREAM_AUTO_RETRIES: the first attempt plus 5 automatic retries.
633633
it.each([
634-
{ autoApprovalEnabled: true, expectedAttempts: 6, expectedBackoffs: 5 },
635-
{ autoApprovalEnabled: false, expectedAttempts: 1, expectedBackoffs: 0 },
634+
{ autoApprovalEnabled: true, expectedAttempts: 6, expectedBackoffAttempts: [0, 1, 2, 3, 4] },
635+
{ autoApprovalEnabled: false, expectedAttempts: 1, expectedBackoffAttempts: [] },
636636
])(
637637
"asks the user instead of retrying forever (autoApprovalEnabled=$autoApprovalEnabled)",
638-
async ({ autoApprovalEnabled, expectedAttempts, expectedBackoffs }) => {
638+
async ({ autoApprovalEnabled, expectedAttempts, expectedBackoffAttempts }) => {
639639
vi.spyOn(mockProvider, "getState").mockResolvedValue(
640640
providerStateWith({ autoApprovalEnabled, requestDelaySeconds: 0 }),
641641
)
@@ -656,14 +656,54 @@ describe("Cline", () => {
656656
.spyOn(task, "attemptApiRequest")
657657
.mockImplementation(() => idleTimeoutStream())
658658

659-
await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]).catch(() => {})
659+
// Declining ends the turn: the "API request failed" error is handled inside the loop,
660+
// so the call resolves rather than rejecting.
661+
await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }])).resolves.toBe(
662+
true,
663+
)
660664

661665
expect(attemptApiRequestSpy).toHaveBeenCalledTimes(expectedAttempts)
662-
expect(backoffSpy).toHaveBeenCalledTimes(expectedBackoffs)
666+
expect(backoffSpy.mock.calls.map(([attempt]) => attempt)).toEqual(expectedBackoffAttempts)
663667
expect(askSpy).toHaveBeenCalledOnce()
664668
expect(askSpy).toHaveBeenCalledWith("api_req_failed", expect.stringContaining("idle timeout"))
665669
},
666670
)
671+
672+
it("does not add the user message to history again when the user confirms a retry", async () => {
673+
vi.spyOn(mockProvider, "getState").mockResolvedValue(
674+
providerStateWith({ autoApprovalEnabled: false, requestDelaySeconds: 0 }),
675+
)
676+
const task = new Task({
677+
provider: mockProvider,
678+
apiConfiguration: mockApiConfig,
679+
task: "test task",
680+
startTask: false,
681+
})
682+
vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined)
683+
vi.spyOn(getTaskTestAccess(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
684+
vi.spyOn(getTaskTestAccess(task), "presentAssistantMessageSafe").mockImplementation(() => {})
685+
const historySpy = vi
686+
.spyOn(getTaskTestAccess(task), "addToApiConversationHistory")
687+
.mockResolvedValue(undefined)
688+
const askSpy = vi
689+
.spyOn(task, "ask")
690+
.mockResolvedValueOnce({ response: "yesButtonClicked" } satisfies TaskAskResult)
691+
.mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult)
692+
const attemptApiRequestSpy = vi
693+
.spyOn(task, "attemptApiRequest")
694+
.mockImplementation(() => idleTimeoutStream())
695+
696+
await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }])).resolves.toBe(
697+
true,
698+
)
699+
700+
expect(askSpy).toHaveBeenCalledTimes(2)
701+
expect(attemptApiRequestSpy).toHaveBeenCalledTimes(2)
702+
const userMessages = historySpy.mock.calls.filter(
703+
([message]) => (message as { role: string }).role === "user",
704+
)
705+
expect(userMessages).toHaveLength(1)
706+
})
667707
})
668708

669709
describe("native tool-call request isolation", () => {

0 commit comments

Comments
 (0)