Repository navigation
Expand file tree
/
Copy pathTask.spec.ts
More file actions
8321 lines (7306 loc) · 290 KB
/
Copy pathTask.spec.ts
File metadata and controls
8321 lines (7306 loc) · 290 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker"
// npx vitest core/task/__tests__/Task.spec.ts
import * as fsReal from "fs"
import * as os from "os"
import * as path from "path"
import * as vscode from "vscode"
import { Anthropic } from "@anthropic-ai/sdk"
import type { Mock } from "vitest"
import {
providerIdentifiers,
RooCodeEventName,
type ClineMessage,
type GlobalState,
type HistoryItem,
type ModeConfig,
type ProviderSettings,
type ModelInfo,
type TaskLike,
} from "@roo-code/types"
import { TelemetryService } from "@roo-code/telemetry"
import { MODEL_FETCH_TIMEOUT_MS, Task } from "../Task"
import { SYSTEM_PROMPT } from "../../prompts/system"
import { createRateLimitClock } from "../RateLimitClock"
import { summarizeConversation } from "../../condense"
import { getEnvironmentDetails } from "../../environment/getEnvironmentDetails"
import { ClineProvider } from "../../webview/ClineProvider"
import { ApiStreamChunk } from "../../../api/transform/stream"
import { OutputTokenLimitError } from "../../../api/providers/utils/output-token-limit-error"
import { ContextProxy } from "../../config/ContextProxy"
import { processUserContentMentions } from "../../mentions/processUserContentMentions"
import { MultiSearchReplaceDiffStrategy } from "../../diff/strategies/multi-search-replace"
import type { ApiMessage } from "../../task-persistence"
import type { RequestPolicySnapshot } from "../../prompts/tools/effective-tool-policy"
import { asyncStreamFrom } from "../../../test-utils/stream"
import { McpHub } from "../../../services/mcp/McpHub"
import { McpServerManager } from "../../../services/mcp/McpServerManager"
import { readFileTool } from "../../tools/ReadFileTool"
import { writeToFileTool } from "../../tools/WriteToFileTool"
type TaskTestAccess = {
getSystemPrompt: (requestState: ProviderState | undefined, requestModelInfo?: ModelInfo) => Promise<string>
handleContextWindowExceededError: (requestModelInfo: ModelInfo) => Promise<void>
getEnabledMcpToolsCount: () => Promise<{ enabledToolCount: number; enabledServerCount: number }>
initiateTaskLoop: (userContent: Anthropic.Messages.ContentBlockParam[]) => Promise<void>
startTask: (task?: string, images?: string[]) => Promise<void>
resumeTaskFromHistory: () => Promise<void>
presentAssistantMessageSafe: () => void
hasCompleteToolResultsForCurrentTurn: () => boolean
addToClineMessages: (message: import("@roo-code/types").ClineMessage) => Promise<void>
updateClineMessage: (message: import("@roo-code/types").ClineMessage) => Promise<void>
saveClineMessages: () => Promise<boolean>
safeEnsureModelFetched: () => Promise<ModelInfo>
backoffAndAnnounce: (retryAttempt: number, error: unknown) => Promise<void>
requestPolicySnapshot?: RequestPolicySnapshot
getFilesReadByRooSafely: (context: string) => Promise<string[] | undefined>
addToApiConversationHistory: (message: unknown, reasoning?: string) => Promise<void>
resetAssistantMessagePersistence: () => void
buildCleanConversationHistory: (
messages: ApiMessage[],
requestModelInfo: ModelInfo,
) => Array<{ role: string; content: unknown } | { type: "reasoning"; encrypted_content: string }>
attemptApiRequestWithActiveApi: () => AsyncGenerator<ApiStreamChunk>
condenseContextWithActiveApi: () => Promise<void>
retiredApis: Set<unknown>
}
type TaskAskResult = Awaited<ReturnType<Task["ask"]>>
type ProviderState = Awaited<ReturnType<ClineProvider["getState"]>>
type MockedClineProvider = ClineProvider & {
getState: Mock<ClineProvider["getState"]> & {
mockResolvedValue: (value: Partial<ProviderState>) => void
}
}
type RateLimitedProviderSettings = ProviderSettings & {
rateLimitSeconds: number
}
function getTaskTestAccess(task: Task): TaskTestAccess {
return task as unknown as TaskTestAccess
}
function requireDefined<T>(value: T | null | undefined): T {
if (value == null) {
throw new Error("Expected test value to be defined")
}
return value
}
// Mock delay before any imports that might use it
vi.mock("delay", () => ({
__esModule: true,
default: vi.fn().mockResolvedValue(undefined),
}))
import delay from "delay"
import pWaitFor from "p-wait-for"
vi.mock("uuid", async (importOriginal) => {
const actual = await importOriginal<typeof import("uuid")>()
return {
...actual,
v7: vi.fn(() => "00000000-0000-7000-8000-000000000000"),
}
})
vi.mock("execa", () => ({
execa: vi.fn(),
}))
vi.mock("fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("fs/promises")>()
const mockFunctions = {
mkdir: vi.fn().mockResolvedValue(undefined),
writeFile: vi.fn().mockResolvedValue(undefined),
readFile: vi.fn().mockImplementation((filePath) => {
if (filePath.includes("ui_messages.json")) {
return Promise.resolve(JSON.stringify(mockMessages))
}
if (filePath.includes("api_conversation_history.json")) {
return Promise.resolve(
JSON.stringify([
{
role: "user",
content: [{ type: "text", text: "historical task" }],
ts: Date.now(),
},
{
role: "assistant",
content: [{ type: "text", text: "I'll help you with that task." }],
ts: Date.now(),
},
]),
)
}
return Promise.resolve("[]")
}),
unlink: vi.fn().mockResolvedValue(undefined),
rmdir: vi.fn().mockResolvedValue(undefined),
stat: vi.fn().mockRejectedValue({ code: "ENOENT" }),
readdir: vi.fn().mockResolvedValue([]),
}
return {
...actual,
...mockFunctions,
default: mockFunctions,
}
})
vi.mock("p-wait-for", () => ({
default: vi.fn().mockImplementation(async () => Promise.resolve()),
}))
// 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 }), // FileType.File = 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) => {
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("../../mentions/processUserContentMentions", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../mentions/processUserContentMentions")>()
return {
...actual,
processUserContentMentions: vi.fn().mockImplementation(actual.processUserContentMentions),
}
})
vi.mock("../../ignore/RooIgnoreController")
vi.mock("../../../i18n", () => {
return {
t: (key: string, args?: Record<string, unknown>) => {
if (key === "tools:missingToolParameterWithPath") {
return `${args?.toolName}|${args?.relPath}|${args?.paramName}`
}
if (key === "tools:missingToolParameter") {
return `${args?.toolName}|${args?.paramName}`
}
return key
},
}
})
vi.mock("../../condense", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../condense")>()
return {
...actual,
summarizeConversation: vi.fn().mockResolvedValue({
messages: [{ role: "user", content: [{ type: "text", text: "continued" }], ts: Date.now() }],
summary: "summary",
cost: 0,
newContextTokens: 1,
}),
}
})
vi.mock("../../prompts/system", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../prompts/system")>()
return {
...actual,
SYSTEM_PROMPT: vi.fn(actual.SYSTEM_PROMPT),
}
})
// Mock storagePathManager to prevent dynamic import issues.
vi.mock("../../../utils/storage", () => ({
getTaskDirectoryPath: vi
.fn()
.mockImplementation((globalStoragePath, taskId) => Promise.resolve(`${globalStoragePath}/tasks/${taskId}`)),
getSettingsDirectoryPath: vi
.fn()
.mockImplementation((globalStoragePath) => Promise.resolve(`${globalStoragePath}/settings`)),
}))
vi.mock("../../../utils/fs", () => ({
fileExistsAtPath: vi.fn().mockImplementation((filePath) => {
return filePath.includes("ui_messages.json") || filePath.includes("api_conversation_history.json")
}),
}))
const mockMessages = [
{
ts: Date.now(),
type: "say",
say: "text",
text: "historical task",
},
]
// Model-info stand-in for tests that stub safeEnsureModelFetched and only need
// the settled snapshot to be a defined ModelInfo.
const stubModelInfo: ModelInfo = {
contextWindow: 200_000,
maxTokens: 4096,
supportsPromptCache: true,
}
describe("Cline", () => {
let mockProvider: ClineProvider
let mockApiConfig: ProviderSettings
let mockOutputChannel: vscode.OutputChannel
let mockExtensionContext: vscode.ExtensionContext
// Builds provider-state doubles on top of the real getState() result
// captured before any test stubs it, so required fields stay
// compile-checked while each test states only its own overrides.
// mcpEnabled defaults to false so doubles skip the MCP-hub path unless a
// test opts in.
let baseProviderState: ProviderState
const providerStateWith = (overrides: Partial<ProviderState> = {}): ProviderState => ({
...baseProviderState,
mcpEnabled: false,
...overrides,
})
beforeEach(async () => {
if (!TelemetryService.hasInstance()) {
TelemetryService.createInstance([])
}
// Setup mock extension context
const storageUri = {
fsPath: path.join(os.tmpdir(), "test-storage"),
}
mockExtensionContext = {
globalState: {
get: vi.fn().mockImplementation((key: keyof GlobalState) => {
if (key === "taskHistory") {
return [
{
id: "123",
number: 0,
ts: Date.now(),
task: "historical task",
tokensIn: 100,
tokensOut: 200,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0.001,
},
]
}
return undefined
}),
update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
keys: vi.fn().mockReturnValue([]),
},
globalStorageUri: storageUri,
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: "/mock/extension/path",
},
extension: {
packageJSON: {
version: "1.0.0",
},
},
} as unknown as vscode.ExtensionContext
// Setup mock output channel
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(),
}
// Setup mock provider with output channel
mockProvider = new ClineProvider(
mockExtensionContext,
mockOutputChannel,
"sidebar",
new ContextProxy(mockExtensionContext),
new WebviewFocusTracker(),
)
// Setup mock API configuration
mockApiConfig = {
apiProvider: providerIdentifiers.anthropic,
apiModelId: "claude-3-5-sonnet-20241022",
apiKey: "test-api-key", // Add API key to mock config
}
// Mock provider methods
mockProvider.postMessageToWebview = vi.fn().mockResolvedValue(undefined)
mockProvider.postStateToWebview = vi.fn().mockResolvedValue(undefined)
mockProvider.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined)
mockProvider.postStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
mockProvider.flushPostStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
mockProvider.getTaskWithId = vi.fn().mockImplementation(async (id) => ({
historyItem: {
id,
ts: Date.now(),
task: "historical task",
tokensIn: 100,
tokensOut: 200,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0.001,
},
taskDirPath: "/mock/storage/path/tasks/123",
apiConversationHistoryFilePath: "/mock/storage/path/tasks/123/api_conversation_history.json",
uiMessagesFilePath: "/mock/storage/path/tasks/123/ui_messages.json",
apiConversationHistory: [
{
role: "user",
content: [{ type: "text", text: "historical task" }],
ts: Date.now(),
},
{
role: "assistant",
content: [{ type: "text", text: "I'll help you with that task." }],
ts: Date.now(),
},
],
}))
baseProviderState = await mockProvider.getState()
})
function stream(chunks: ApiStreamChunk[]): AsyncGenerator<ApiStreamChunk> {
return (async function* () {
yield* chunks
})()
}
async function createTaskWithManualRetries() {
const task = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
startTask: false,
})
const state = await mockProvider.getState()
vi.spyOn(mockProvider, "getState").mockResolvedValue({
...state,
apiConfiguration: mockApiConfig,
autoApprovalEnabled: false,
})
vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined)
return task
}
describe("empty-response retries", () => {
it("restores the user message before a confirmed empty-response retry", async () => {
const task = await createTaskWithManualRetries()
let retryHistory: ApiMessage[] | undefined
let retryUserMessageCount: number | undefined
vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } satisfies TaskAskResult)
const attemptApiRequestSpy = vi
.spyOn(task, "attemptApiRequest")
.mockImplementationOnce(() => stream([]))
.mockImplementationOnce(() => {
retryHistory = structuredClone(task.apiConversationHistory)
retryUserMessageCount = task.messageCounts.user
return stream([{ type: "text", text: "retry succeeded" }])
})
.mockImplementation(() => {
throw new Error("stop after retry response")
})
await task.recursivelyMakeClineRequests([{ type: "text", text: "original user request" }])
expect(retryHistory).toHaveLength(1)
// The retry iteration must reach the request seam with its own incremented
// retry count; passing the initial-attempt value instead would make retries
// indistinguishable from the first attempt downstream.
expect(attemptApiRequestSpy).toHaveBeenNthCalledWith(
2,
1,
expect.objectContaining({ skipProviderRateLimit: true }),
)
expect(retryHistory?.[0]).toMatchObject({
role: "user",
content: expect.arrayContaining([expect.objectContaining({ text: "original user request" })]),
})
expect(retryUserMessageCount).toBe(1)
})
it("restores the user message and records the failure when retry is declined", async () => {
const task = await createTaskWithManualRetries()
vi.spyOn(task, "ask").mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult)
vi.spyOn(task, "attemptApiRequest").mockImplementation(() => stream([]))
const result = await task.recursivelyMakeClineRequests([{ type: "text", text: "original user request" }])
expect(result).toBe(false)
expect(task.apiConversationHistory).toMatchObject([
{ role: "user", content: [{ type: "text", text: "original user request" }] },
{ role: "assistant", content: [{ type: "text", text: "Failure: I did not provide a response." }] },
])
expect(task.messageCounts).toEqual({ user: 1, assistant: 1 })
})
})
describe("request continuation", () => {
it("sends the no-tool-use reminder in a second request when the first response has no tool use", async () => {
const task = await createTaskWithManualRetries()
let secondRequestHistory: ApiMessage[] | undefined
const attemptApiRequestSpy = vi
.spyOn(task, "attemptApiRequest")
.mockImplementationOnce(() => stream([{ type: "text", text: "no tool here" }]))
.mockImplementationOnce(() => {
secondRequestHistory = structuredClone(task.apiConversationHistory)
throw new Error("stop after continuation request")
})
await task.recursivelyMakeClineRequests([{ type: "text", text: "original user request" }])
expect(attemptApiRequestSpy).toHaveBeenCalledTimes(2)
expect(secondRequestHistory).toMatchObject([
{
role: "user",
content: expect.arrayContaining([expect.objectContaining({ text: "original user request" })]),
},
{ role: "assistant", content: [{ type: "text", text: "no tool here" }] },
{
role: "user",
content: expect.arrayContaining([
expect.objectContaining({
text: expect.stringContaining("You did not use a tool in your previous response"),
}),
]),
},
])
})
})
describe("output token limit mid-stream", () => {
async function* truncatedStream(): AsyncGenerator<ApiStreamChunk> {
yield { type: "text", text: "partial answer" }
throw new OutputTokenLimitError()
}
async function createAutoApprovedTask() {
vi.spyOn(mockProvider, "getState").mockResolvedValue(
providerStateWith({ autoApprovalEnabled: true, requestDelaySeconds: 0 }),
)
const task = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
startTask: false,
})
vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined)
vi.spyOn(getTaskTestAccess(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
vi.spyOn(getTaskTestAccess(task), "presentAssistantMessageSafe").mockImplementation(() => {})
return task
}
it("asks once instead of auto-retrying, even with auto-approval", async () => {
const task = await createAutoApprovedTask()
const askSpy = vi
.spyOn(task, "ask")
.mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult)
const backoffSpy = vi.spyOn(getTaskTestAccess(task), "backoffAndAnnounce")
const attemptApiRequestSpy = vi.spyOn(task, "attemptApiRequest").mockImplementation(() => truncatedStream())
await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }])
expect(attemptApiRequestSpy).toHaveBeenCalledOnce()
expect(backoffSpy).not.toHaveBeenCalled()
expect(askSpy).toHaveBeenCalledWith("api_req_failed", expect.stringContaining("Output token limit reached"))
})
it("retries from a fresh attempt count when the user confirms", async () => {
const task = await createAutoApprovedTask()
vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } satisfies TaskAskResult)
const attemptApiRequestSpy = vi
.spyOn(task, "attemptApiRequest")
.mockImplementationOnce(() => truncatedStream())
.mockImplementationOnce(() => asyncStreamFrom<ApiStreamChunk>([{ type: "text", text: "done" }]))
.mockImplementation(() => {
throw new Error("stop after retry response")
})
await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }])
expect(attemptApiRequestSpy.mock.calls.slice(0, 2).map(([retryAttempt]) => retryAttempt)).toEqual([0, 0])
})
})
describe("native tool-call request isolation", () => {
it("derives readiness only from a closed, idle, fully paired tool turn", () => {
const task = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "tool turn readiness test",
startTask: false,
})
const readiness = () => getTaskTestAccess(task).hasCompleteToolResultsForCurrentTurn()
task.assistantMessageContent = [
{
type: "tool_use",
id: "call_ready",
name: "read_file",
params: {},
nativeArgs: { path: "README.md" },
partial: false,
},
]
task.userMessageContent = [{ type: "tool_result", tool_use_id: "call_ready", content: "finished" }]
task.currentStreamingContentIndex = task.assistantMessageContent.length
expect(readiness()).toBe(false)
task.didCompleteReadingStream = true
expect(readiness()).toBe(true)
task.presentAssistantMessageLocked = true
expect(readiness()).toBe(false)
task.presentAssistantMessageLocked = false
expect(readiness()).toBe(true)
task.assistantMessageContent[0].partial = true
expect(readiness()).toBe(false)
task.assistantMessageContent[0].partial = false
task.userMessageContent = [{ type: "tool_result", tool_use_id: "different_call", content: "finished" }]
expect(readiness()).toBe(false)
task.userMessageContent = [{ type: "tool_result", tool_use_id: "call_ready", content: "finished" }]
expect(readiness()).toBe(true)
})
it("requires a result for every tool call in the turn", () => {
const task = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "multi tool readiness test",
startTask: false,
})
const readiness = () => getTaskTestAccess(task).hasCompleteToolResultsForCurrentTurn()
task.didCompleteReadingStream = true
task.assistantMessageContent = [
{ type: "tool_use", id: "call_first", name: "read_file", params: {}, partial: false },
{ type: "tool_use", id: "call_middle", name: "read_file", params: {}, partial: false },
{ type: "tool_use", id: "call_last", name: "read_file", params: {}, partial: false },
]
const resultsFor = (...ids: string[]): Anthropic.ToolResultBlockParam[] =>
ids.map((id) => ({ type: "tool_result", tool_use_id: id, content: "finished" }))
task.userMessageContent = resultsFor("call_first")
expect(readiness()).toBe(false)
task.userMessageContent = resultsFor("call_last")
expect(readiness()).toBe(false)
task.userMessageContent = resultsFor("call_first", "call_last")
expect(readiness()).toBe(false)
task.userMessageContent = resultsFor("call_first", "call_middle", "call_last")
expect(readiness()).toBe(true)
})
it("does not strand a paired tool turn after a presenter failure", () => {
const task = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "presenter failure readiness test",
startTask: false,
})
task.didCompleteReadingStream = true
task.presentAssistantMessageLocked = false
task.assistantMessageContent = [
{
type: "tool_use",
id: "call_ready",
name: "read_file",
params: {},
partial: false,
},
{ type: "text", content: "presenter failed here", partial: false },
]
task.currentStreamingContentIndex = 1
task.userMessageContent = [{ type: "tool_result", tool_use_id: "call_ready", content: "finished" }]
expect(getTaskTestAccess(task).hasCompleteToolResultsForCurrentTurn()).toBe(true)
})
it("requires an identifiable tool call and matches sanitized result IDs", () => {
const task = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "tool turn identity test",
startTask: false,
})
const readiness = () => getTaskTestAccess(task).hasCompleteToolResultsForCurrentTurn()
task.didCompleteReadingStream = true
task.assistantMessageContent = [{ type: "text", content: "finished", partial: false }]
expect(readiness()).toBe(false)
// An empty result ID must not satisfy a tool call that has no ID.
task.userMessageContent = [{ type: "tool_result", tool_use_id: "", content: "finished" }]
task.assistantMessageContent = [
{
type: "tool_use",
name: "read_file",
params: {},
partial: false,
},
]
expect(readiness()).toBe(false)
task.assistantMessageContent = [
{
type: "mcp_tool_use",
id: "",
name: "mcp_server_tool",
serverName: "server",
toolName: "tool",
arguments: {},
partial: false,
},
]
expect(readiness()).toBe(false)
const mcpToolUse = task.assistantMessageContent[0]
if (mcpToolUse.type !== "mcp_tool_use") {
throw new Error("Expected MCP tool use fixture")
}
mcpToolUse.id = "functions.read_file:0"
task.userMessageContent = [
{ type: "tool_result", tool_use_id: "functions.read_file:0", content: "finished" },
]
expect(readiness()).toBe(false)
task.userMessageContent = [
{ type: "tool_result", tool_use_id: "functions_read_file_0", content: "finished" },
]
expect(readiness()).toBe(true)
})
it("continues after a complete read_file result when the readiness flag update is lost", async () => {
const task = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "read file continuation test",
startTask: false,
})
vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined)
vi.spyOn(getTaskTestAccess(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
vi.spyOn(getTaskTestAccess(task), "presentAssistantMessageSafe").mockImplementation(() => {
const completedRead = task.assistantMessageContent.find(
(block) => block.type === "tool_use" && block.name === "read_file" && !block.partial,
)
if (!completedRead || completedRead.type !== "tool_use" || !completedRead.id) return
task.pushToolResultToUserContent({
type: "tool_result",
tool_use_id: completedRead.id,
content: "File: README.md\nfinished",
})
// Reproduce the persisted field symptom: the tool result exists and
// presentation consumed the completed block, but the one-shot readiness
// latch never flips, so the old loop waits forever before the next request.
task.currentStreamingContentIndex = task.assistantMessageContent.length
task.userMessageContentReady = false
})
let continuationUserContent: Anthropic.Messages.ContentBlockParam[] | undefined
const attemptApiRequestSpy = vi
.spyOn(task, "attemptApiRequest")
.mockImplementationOnce(() =>
asyncStreamFrom<ApiStreamChunk>([
{ type: "tool_call_partial", index: 0, id: "call_read", name: "read_file" },
{ type: "tool_call_partial", index: 0, arguments: '{"path":"README.md"}' },
]),
)
.mockImplementationOnce(() => {
const continuationMessage = task.apiConversationHistory.at(-1)
continuationUserContent =
continuationMessage?.role === "user" && Array.isArray(continuationMessage.content)
? continuationMessage.content
: undefined
throw new Error("continuation request reached")
})
vi.mocked(pWaitFor).mockImplementation(async (condition) => {
if (!(await condition())) {
throw new Error("read_file continuation would stall")
}
})
try {
await task.recursivelyMakeClineRequests([{ type: "text", text: "read a file, then continue" }])
expect(attemptApiRequestSpy).toHaveBeenCalledTimes(2)
expect(continuationUserContent?.filter((block) => block.type === "tool_result")).toEqual([
expect.objectContaining({
type: "tool_result",
tool_use_id: "call_read",
content: "File: README.md\nfinished",
}),
])
} finally {
vi.mocked(pWaitFor).mockImplementation(async () => {})
}
})
it("continues after the real presenter leaves a complete tool result behind a non-abort failure", async () => {
const task = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "real presenter continuation test",
startTask: false,
})
vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined)
vi.spyOn(getTaskTestAccess(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
const readFileHandleSpy = vi
.spyOn(readFileTool, "handle")
.mockImplementation(async (_task, block, callbacks) => {
if (!block.partial) callbacks.pushToolResult(`File: ${block.params.path}\nfinished`)
})
const say = task.say.bind(task)
const saySpy = vi.spyOn(task, "say").mockImplementation(async (...args) => {
const [type, _text, _images, partial] = args
if (type === "text" && partial === false) {
throw new Error("presenter text failed")
}
return say(...args)
})
const readiness = getTaskTestAccess(task).hasCompleteToolResultsForCurrentTurn.bind(task)
let sawCompleteToolTurn = false
const readinessSpy = vi
.spyOn(getTaskTestAccess(task), "hasCompleteToolResultsForCurrentTurn")
.mockImplementation(() => {
const ready = readiness()
if (ready) sawCompleteToolTurn = true
return ready
})
let continuationUserContent: Anthropic.Messages.ContentBlockParam[] | undefined
const attemptApiRequestSpy = vi
.spyOn(task, "attemptApiRequest")
.mockImplementationOnce(() => {
// The real generator publishes the request policy snapshot that
// presentAssistantMessage requires; with the generator replaced
// wholesale, the mock must publish one too or the presenter's
// entry guard throws before any block is processed.
getTaskTestAccess(task).requestPolicySnapshot = {
disabledTools: [],
customModes: [],
modelInfo: stubModelInfo,
}
return asyncStreamFrom<ApiStreamChunk>([
{ type: "tool_call_partial", index: 0, id: "call_read_first", name: "read_file" },
{ type: "tool_call_partial", index: 0, arguments: '{"path":"README.md"}' },
{ type: "tool_call_partial", index: 1, id: "call_read_second", name: "read_file" },
{ type: "tool_call_partial", index: 1, arguments: '{"path":"package.json"}' },
{ type: "text", text: "present this after the tool" },
])
})
.mockImplementationOnce(() => {
const continuationMessage = task.apiConversationHistory.at(-1)
continuationUserContent =
continuationMessage?.role === "user" && Array.isArray(continuationMessage.content)
? continuationMessage.content
: undefined
throw new Error("continuation request reached")
})
const { default: realPWaitFor } = await vi.importActual<typeof import("p-wait-for")>("p-wait-for")
vi.mocked(pWaitFor).mockImplementation((condition) =>
realPWaitFor(condition, { interval: 1, timeout: 1_000 }),
)
try {
await task.recursivelyMakeClineRequests([{ type: "text", text: "read a file, then continue" }])
expect(attemptApiRequestSpy).toHaveBeenCalledTimes(2)
expect(continuationUserContent?.filter((block) => block.type === "tool_result")).toEqual([
expect.objectContaining({
type: "tool_result",
tool_use_id: "call_read_first",
content: "File: README.md\nfinished",
}),
expect.objectContaining({
type: "tool_result",
tool_use_id: "call_read_second",
content: "File: package.json\nfinished",
}),
])
expect(task.presentAssistantMessageLocked).toBe(false)
expect(sawCompleteToolTurn).toBe(true)
} finally {
vi.mocked(pWaitFor).mockImplementation(async () => {})
readinessSpy.mockRestore()
readFileHandleSpy.mockRestore()
saySpy.mockRestore()
}
})
it("waits for a running tool handler even when its result is already pushed", async () => {
const task = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "running handler continuation test",
startTask: false,
})
vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined)
vi.spyOn(getTaskTestAccess(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
let releaseHandler: (() => void) | undefined
const handlerGate = new Promise<void>((resolve) => {
releaseHandler = resolve
})
let handlerPushedResult: (() => void) | undefined
const resultPushed = new Promise<void>((resolve) => {
handlerPushedResult = resolve
})
const readFileHandleSpy = vi
.spyOn(readFileTool, "handle")
.mockImplementation(async (_task, block, callbacks) => {
if (block.partial) return
callbacks.pushToolResult("File: README.md\nfinished")
handlerPushedResult?.()
// The handler keeps running after it pushes the result, for example while it waits for approval.
await handlerGate
})
const attemptApiRequestSpy = vi
.spyOn(task, "attemptApiRequest")
.mockImplementationOnce(() => {
// The real generator publishes the request policy snapshot that
// presentAssistantMessage requires; with the generator replaced
// wholesale, the mock must publish one too or the presenter's
// entry guard throws before any block is processed.
getTaskTestAccess(task).requestPolicySnapshot = {
disabledTools: [],
customModes: [],
modelInfo: stubModelInfo,
}
return asyncStreamFrom<ApiStreamChunk>([
{ type: "tool_call_partial", index: 0, id: "call_read", name: "read_file" },
{ type: "tool_call_partial", index: 0, arguments: '{"path":"README.md"}' },
])
})
.mockImplementationOnce(() => {
throw new Error("continuation request reached")
})
const { default: realPWaitFor } = await vi.importActual<typeof import("p-wait-for")>("p-wait-for")
vi.mocked(pWaitFor).mockImplementation((condition) =>
realPWaitFor(condition, { interval: 1, timeout: 1_000 }),
)
try {
const run = task.recursivelyMakeClineRequests([{ type: "text", text: "read a file, then wait" }])
await resultPushed
// Give the request loop several poll intervals to continue early.
await new Promise((resolve) => setTimeout(resolve, 50))
expect(task.presentAssistantMessageLocked).toBe(true)
expect(attemptApiRequestSpy).toHaveBeenCalledTimes(1)
releaseHandler?.()
await run
expect(attemptApiRequestSpy).toHaveBeenCalledTimes(2)
expect(task.presentAssistantMessageLocked).toBe(false)
} finally {
releaseHandler?.()
vi.mocked(pWaitFor).mockImplementation(async () => {})
readFileHandleSpy.mockRestore()
}
})
it("lets abort win when the real presenter leaves a complete tool result", async () => {
const task = new Task({