-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathTask.spec.ts
More file actions
2265 lines (1933 loc) · 66.3 KB
/
Task.spec.ts
File metadata and controls
2265 lines (1933 loc) · 66.3 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
// npx vitest core/task/__tests__/Task.spec.ts
import * as os from "os"
import * as path from "path"
import * as vscode from "vscode"
import { Anthropic } from "@anthropic-ai/sdk"
import type { GlobalState, ProviderSettings, ModelInfo } from "@roo-code/types"
import { TelemetryService } from "@roo-code/telemetry"
import { Task } from "../Task"
import { ClineProvider } from "../../webview/ClineProvider"
import { ApiStreamChunk } from "../../../api/transform/stream"
import { ContextProxy } from "../../config/ContextProxy"
import { processUserContentMentions } from "../../mentions/processUserContentMentions"
import { MultiSearchReplaceDiffStrategy } from "../../diff/strategies/multi-search-replace"
// Mock delay before any imports that might use it
vi.mock("delay", () => ({
__esModule: true,
default: vi.fn().mockResolvedValue(undefined),
}))
import delay from "delay"
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()) as Record<string, any>
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()),
}))
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: any) => defaultValue })),
},
env: {
uriScheme: "vscode",
language: "en",
},
EventEmitter: vi.fn().mockImplementation(() => 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("../../ignore/RooIgnoreController")
vi.mock("../../condense", async (importOriginal) => {
const actual = (await importOriginal()) as any
return {
...actual,
summarizeConversation: vi.fn().mockResolvedValue({
messages: [{ role: "user", content: [{ type: "text", text: "continued" }], ts: Date.now() }],
summary: "summary",
cost: 0,
newContextTokens: 1,
}),
}
})
// 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",
},
]
describe("Cline", () => {
let mockProvider: any
let mockApiConfig: ProviderSettings
let mockOutputChannel: any
let mockExtensionContext: vscode.ExtensionContext
beforeEach(() => {
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 = {
appendLine: vi.fn(),
append: 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),
) as any
// Setup mock API configuration
mockApiConfig = {
apiProvider: "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.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(),
},
],
}))
})
describe("constructor", () => {
it("should always have diff strategy defined", async () => {
const cline = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
startTask: false,
})
// Diff is always enabled - diffStrategy should be defined
expect(cline.diffStrategy).toBeDefined()
})
it("should use default consecutiveMistakeLimit when not provided", () => {
const cline = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
startTask: false,
})
expect(cline.consecutiveMistakeLimit).toBe(3)
})
it("should respect provided consecutiveMistakeLimit", () => {
const cline = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
consecutiveMistakeLimit: 5,
task: "test task",
startTask: false,
})
expect(cline.consecutiveMistakeLimit).toBe(5)
})
it("should keep consecutiveMistakeLimit of 0 as 0 for unlimited", () => {
const cline = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
consecutiveMistakeLimit: 0,
task: "test task",
startTask: false,
})
expect(cline.consecutiveMistakeLimit).toBe(0)
})
it("should pass 0 to ToolRepetitionDetector for unlimited mode", () => {
const cline = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
consecutiveMistakeLimit: 0,
task: "test task",
startTask: false,
})
// The toolRepetitionDetector should be initialized with 0 for unlimited mode
expect(cline.toolRepetitionDetector).toBeDefined()
// Verify the limit remains as 0
expect(cline.consecutiveMistakeLimit).toBe(0)
})
it("should pass consecutiveMistakeLimit to ToolRepetitionDetector", () => {
const cline = new Task({
provider: mockProvider,
apiConfiguration: mockApiConfig,
consecutiveMistakeLimit: 5,
task: "test task",
startTask: false,
})
// The toolRepetitionDetector should be initialized with the same limit
expect(cline.toolRepetitionDetector).toBeDefined()
expect(cline.consecutiveMistakeLimit).toBe(5)
})
it("should require either task or historyItem", () => {
expect(() => {
new Task({ provider: mockProvider, apiConfiguration: mockApiConfig })
}).toThrow("Either historyItem or task/images must be provided")
})
})
describe("getEnvironmentDetails", () => {
describe("API conversation handling", () => {
it.skip("should clean conversation history before sending to API", async () => {
// Cline.create will now use our mocked getEnvironmentDetails
const [cline, task] = Task.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
})
cline.abandoned = true
await task
// Set up mock stream.
const mockStreamForClean = (async function* () {
yield { type: "text", text: "test response" }
})()
// Set up spy.
const cleanMessageSpy = vi.fn().mockReturnValue(mockStreamForClean)
vi.spyOn(cline.api, "createMessage").mockImplementation(cleanMessageSpy)
// Add test message to conversation history.
cline.apiConversationHistory = [
{
role: "user" as const,
content: [{ type: "text" as const, text: "test message" }],
ts: Date.now(),
},
]
// Mock abort state
Object.defineProperty(cline, "abort", {
get: () => false,
set: () => {},
configurable: true,
})
// Add a message with extra properties to the conversation history
const messageWithExtra = {
role: "user" as const,
content: [{ type: "text" as const, text: "test message" }],
ts: Date.now(),
extraProp: "should be removed",
}
cline.apiConversationHistory = [messageWithExtra]
// Trigger an API request
await cline.recursivelyMakeClineRequests([{ type: "text", text: "test request" }], false)
// Get the conversation history from the first API call
expect(cleanMessageSpy.mock.calls.length).toBeGreaterThan(0)
const history = cleanMessageSpy.mock.calls[0]?.[1]
expect(history).toBeDefined()
expect(history.length).toBeGreaterThan(0)
// Find our test message
const cleanedMessage = history.find((msg: { content?: Array<{ text: string }> }) =>
msg.content?.some((content) => content.text === "test message"),
)
expect(cleanedMessage).toBeDefined()
expect(cleanedMessage).toEqual({
role: "user",
content: [{ type: "text", text: "test message" }],
})
// Verify extra properties were removed
expect(Object.keys(cleanedMessage!)).toEqual(["role", "content"])
})
it.skip("should handle image blocks based on model capabilities", async () => {
// Create two configurations - one with image support, one without
const configWithImages = {
...mockApiConfig,
apiModelId: "claude-3-sonnet",
}
const configWithoutImages = {
...mockApiConfig,
apiModelId: "gpt-3.5-turbo",
}
// Create test conversation history with mixed content
const conversationHistory: (Anthropic.MessageParam & { ts?: number })[] = [
{
role: "user" as const,
content: [
{
type: "text" as const,
text: "Here is an image",
} satisfies Anthropic.TextBlockParam,
{
type: "image" as const,
source: {
type: "base64" as const,
media_type: "image/jpeg",
data: "base64data",
},
} satisfies Anthropic.ImageBlockParam,
],
},
{
role: "assistant" as const,
content: [
{
type: "text" as const,
text: "I see the image",
} satisfies Anthropic.TextBlockParam,
],
},
]
// Test with model that supports images
const [clineWithImages, taskWithImages] = Task.create({
provider: mockProvider,
apiConfiguration: configWithImages,
task: "test task",
})
// Mock the model info to indicate image support
vi.spyOn(clineWithImages.api, "getModel").mockReturnValue({
id: "claude-3-sonnet",
info: {
supportsImages: true,
supportsPromptCache: true,
contextWindow: 200000,
maxTokens: 4096,
inputPrice: 0.25,
outputPrice: 0.75,
} as ModelInfo,
})
clineWithImages.apiConversationHistory = conversationHistory
// Test with model that doesn't support images
const [clineWithoutImages, taskWithoutImages] = Task.create({
provider: mockProvider,
apiConfiguration: configWithoutImages,
task: "test task",
})
// Mock the model info to indicate no image support
vi.spyOn(clineWithoutImages.api, "getModel").mockReturnValue({
id: "gpt-3.5-turbo",
info: {
supportsImages: false,
supportsPromptCache: false,
contextWindow: 16000,
maxTokens: 2048,
inputPrice: 0.1,
outputPrice: 0.2,
} as ModelInfo,
})
clineWithoutImages.apiConversationHistory = conversationHistory
// Mock abort state for both instances
Object.defineProperty(clineWithImages, "abort", {
get: () => false,
set: () => {},
configurable: true,
})
Object.defineProperty(clineWithoutImages, "abort", {
get: () => false,
set: () => {},
configurable: true,
})
// Set up mock streams
const mockStreamWithImages = (async function* () {
yield { type: "text", text: "test response" }
})()
const mockStreamWithoutImages = (async function* () {
yield { type: "text", text: "test response" }
})()
// Set up spies
const imagesSpy = vi.fn().mockReturnValue(mockStreamWithImages)
const noImagesSpy = vi.fn().mockReturnValue(mockStreamWithoutImages)
vi.spyOn(clineWithImages.api, "createMessage").mockImplementation(imagesSpy)
vi.spyOn(clineWithoutImages.api, "createMessage").mockImplementation(noImagesSpy)
// Set up conversation history with images
clineWithImages.apiConversationHistory = [
{
role: "user",
content: [
{ type: "text", text: "Here is an image" },
{ type: "image", source: { type: "base64", media_type: "image/jpeg", data: "base64data" } },
],
},
]
clineWithImages.abandoned = true
await taskWithImages.catch(() => {})
clineWithoutImages.abandoned = true
await taskWithoutImages.catch(() => {})
// Trigger API requests
await clineWithImages.recursivelyMakeClineRequests([{ type: "text", text: "test request" }])
await clineWithoutImages.recursivelyMakeClineRequests([{ type: "text", text: "test request" }])
// Get the calls
const imagesCalls = imagesSpy.mock.calls
const noImagesCalls = noImagesSpy.mock.calls
// Verify model with image support preserves image blocks
expect(imagesCalls.length).toBeGreaterThan(0)
if (imagesCalls[0]?.[1]?.[0]?.content) {
expect(imagesCalls[0][1][0].content).toHaveLength(2)
expect(imagesCalls[0][1][0].content[0]).toEqual({ type: "text", text: "Here is an image" })
expect(imagesCalls[0][1][0].content[1]).toHaveProperty("type", "image")
}
// Verify model without image support converts image blocks to text
expect(noImagesCalls.length).toBeGreaterThan(0)
if (noImagesCalls[0]?.[1]?.[0]?.content) {
expect(noImagesCalls[0][1][0].content).toHaveLength(2)
expect(noImagesCalls[0][1][0].content[0]).toEqual({ type: "text", text: "Here is an image" })
expect(noImagesCalls[0][1][0].content[1]).toEqual({
type: "text",
text: "[Referenced image in conversation]",
})
}
})
it.skip("should handle API retry with countdown", async () => {
const [cline, task] = Task.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
})
// Mock delay to track countdown timing
const mockDelay = vi.fn().mockResolvedValue(undefined)
vi.spyOn(await import("delay"), "default").mockImplementation(mockDelay)
// Mock say to track messages
const saySpy = vi.spyOn(cline, "say")
// Create a stream that fails on first chunk
const mockError = new Error("API Error")
const mockFailedStream = {
// eslint-disable-next-line require-yield
async *[Symbol.asyncIterator]() {
throw mockError
},
async next() {
throw mockError
},
async return() {
return { done: true, value: undefined }
},
async throw(e: any) {
throw e
},
async [Symbol.asyncDispose]() {
// Cleanup
},
} as AsyncGenerator<ApiStreamChunk>
// Create a successful stream for retry
const mockSuccessStream = {
async *[Symbol.asyncIterator]() {
yield { type: "text", text: "Success" }
},
async next() {
return { done: true, value: { type: "text", text: "Success" } }
},
async return() {
return { done: true, value: undefined }
},
async throw(e: any) {
throw e
},
async [Symbol.asyncDispose]() {
// Cleanup
},
} as AsyncGenerator<ApiStreamChunk>
// Mock createMessage to fail first then succeed
let firstAttempt = true
vi.spyOn(cline.api, "createMessage").mockImplementation(() => {
if (firstAttempt) {
firstAttempt = false
return mockFailedStream
}
return mockSuccessStream
})
// Set up mock state
mockProvider.getState = vi.fn().mockResolvedValue({})
// Mock previous API request message
cline.clineMessages = [
{
ts: Date.now(),
type: "say",
say: "api_req_started",
text: JSON.stringify({
tokensIn: 100,
tokensOut: 50,
cacheWrites: 0,
cacheReads: 0,
}),
},
]
// Trigger API request
const iterator = cline.attemptApiRequest(0)
await iterator.next()
// Calculate expected delay for first retry
const baseDelay = 3 // test retry delay
// Verify countdown messages
for (let i = baseDelay; i > 0; i--) {
expect(saySpy).toHaveBeenCalledWith(
"api_req_retry_delayed",
expect.stringContaining(`Retrying in ${i} seconds`),
undefined,
true,
)
}
expect(saySpy).toHaveBeenCalledWith(
"api_req_retry_delayed",
expect.stringContaining("Retrying now"),
undefined,
false,
)
// Calculate expected delay calls for countdown
const totalExpectedDelays = baseDelay // One delay per second for countdown
expect(mockDelay).toHaveBeenCalledTimes(totalExpectedDelays)
expect(mockDelay).toHaveBeenCalledWith(1000)
// Verify error message content
const errorMessage = saySpy.mock.calls.find((call) => call[1]?.includes(mockError.message))?.[1]
expect(errorMessage).toBe(
`${mockError.message}\n\nRetry attempt 1\nRetrying in ${baseDelay} seconds...`,
)
await cline.abortTask(true)
await task.catch(() => {})
})
it.skip("should not apply retry delay twice", async () => {
const [cline, task] = Task.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
})
// Mock delay to track countdown timing
const mockDelay = vi.fn().mockResolvedValue(undefined)
vi.spyOn(await import("delay"), "default").mockImplementation(mockDelay)
// Mock say to track messages
const saySpy = vi.spyOn(cline, "say")
// Create a stream that fails on first chunk
const mockError = new Error("API Error")
const mockFailedStream = {
// eslint-disable-next-line require-yield
async *[Symbol.asyncIterator]() {
throw mockError
},
async next() {
throw mockError
},
async return() {
return { done: true, value: undefined }
},
async throw(e: any) {
throw e
},
async [Symbol.asyncDispose]() {
// Cleanup
},
} as AsyncGenerator<ApiStreamChunk>
// Create a successful stream for retry
const mockSuccessStream = {
async *[Symbol.asyncIterator]() {
yield { type: "text", text: "Success" }
},
async next() {
return { done: true, value: { type: "text", text: "Success" } }
},
async return() {
return { done: true, value: undefined }
},
async throw(e: any) {
throw e
},
async [Symbol.asyncDispose]() {
// Cleanup
},
} as AsyncGenerator<ApiStreamChunk>
// Mock createMessage to fail first then succeed
let firstAttempt = true
vi.spyOn(cline.api, "createMessage").mockImplementation(() => {
if (firstAttempt) {
firstAttempt = false
return mockFailedStream
}
return mockSuccessStream
})
// Set up mock state
mockProvider.getState = vi.fn().mockResolvedValue({})
// Mock previous API request message
cline.clineMessages = [
{
ts: Date.now(),
type: "say",
say: "api_req_started",
text: JSON.stringify({
tokensIn: 100,
tokensOut: 50,
cacheWrites: 0,
cacheReads: 0,
}),
},
]
// Trigger API request
const iterator = cline.attemptApiRequest(0)
await iterator.next()
// Verify delay is only applied for the countdown
const baseDelay = 3 // test retry delay
const expectedDelayCount = baseDelay // One delay per second for countdown
expect(mockDelay).toHaveBeenCalledTimes(expectedDelayCount)
expect(mockDelay).toHaveBeenCalledWith(1000) // Each delay should be 1 second
// Verify countdown messages were only shown once
const retryMessages = saySpy.mock.calls.filter(
(call) => call[0] === "api_req_retry_delayed" && call[1]?.includes("Retrying in"),
)
expect(retryMessages).toHaveLength(baseDelay)
// Verify the retry message sequence
for (let i = baseDelay; i > 0; i--) {
expect(saySpy).toHaveBeenCalledWith(
"api_req_retry_delayed",
expect.stringContaining(`Retrying in ${i} seconds`),
undefined,
true,
)
}
// Verify final retry message
expect(saySpy).toHaveBeenCalledWith(
"api_req_retry_delayed",
expect.stringContaining("Retrying now"),
undefined,
false,
)
await cline.abortTask(true)
await task.catch(() => {})
})
describe("processUserContentMentions", () => {
it("should process mentions in user_message tags", async () => {
const [cline, task] = Task.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
})
const userContent = [
{
type: "text",
text: "Regular text with 'some/path' (see below for file content)",
} as const,
{
type: "text",
text: "<user_message>Text with 'some/path' (see below for file content) in user_message tags</user_message>",
} as const,
{
type: "tool_result",
tool_use_id: "test-id",
content: [
{
type: "text",
text: "<user_message>Check 'some/path' (see below for file content)</user_message>",
},
],
} as Anthropic.ToolResultBlockParam,
{
type: "tool_result",
tool_use_id: "test-id-2",
content: [
{
type: "text",
text: "Regular tool result with 'path' (see below for file content)",
},
],
} as Anthropic.ToolResultBlockParam,
]
const { content: processedContent } = await processUserContentMentions({
userContent,
cwd: cline.cwd,
fileContextTracker: cline.fileContextTracker,
})
// Regular text should not be processed
expect((processedContent[0] as Anthropic.TextBlockParam).text).toBe(
"Regular text with 'some/path' (see below for file content)",
)
// Text within user_message tags should be processed
expect((processedContent[1] as Anthropic.TextBlockParam).text).toContain("processed:")
expect((processedContent[1] as Anthropic.TextBlockParam).text).toContain(
"<user_message>Text with 'some/path' (see below for file content) in user_message tags</user_message>",
)
// user_message tag content should be processed
const toolResult1 = processedContent[2] as Anthropic.ToolResultBlockParam
const content1 = Array.isArray(toolResult1.content) ? toolResult1.content[0] : toolResult1.content
expect((content1 as Anthropic.TextBlockParam).text).toContain("processed:")
expect((content1 as Anthropic.TextBlockParam).text).toContain(
"<user_message>Check 'some/path' (see below for file content)</user_message>",
)
// Regular tool result should not be processed
const toolResult2 = processedContent[3] as Anthropic.ToolResultBlockParam
const content2 = Array.isArray(toolResult2.content) ? toolResult2.content[0] : toolResult2.content
expect((content2 as Anthropic.TextBlockParam).text).toBe(
"Regular tool result with 'path' (see below for file content)",
)
await cline.abortTask(true)
await task.catch(() => {})
})
})
})
describe("Subtask Rate Limiting", () => {
let mockProvider: any
let mockApiConfig: any
let mockDelay: ReturnType<typeof vi.fn>
beforeEach(() => {
vi.clearAllMocks()
// Reset the global timestamp before each test
Task.resetGlobalApiRequestTime()
mockApiConfig = {
apiProvider: "anthropic",
apiKey: "test-key",
rateLimitSeconds: 5,
}
mockProvider = {
context: {
globalStorageUri: { fsPath: "/test/storage" },
globalState: {
get: vi.fn().mockImplementation(() => undefined),
update: vi.fn().mockResolvedValue(undefined),
keys: vi.fn().mockReturnValue([]),
},
},
getState: vi.fn().mockResolvedValue({
apiConfiguration: mockApiConfig,
mcpEnabled: false,
}),
getMcpHub: vi.fn().mockReturnValue(undefined),
getSkillsManager: vi.fn().mockReturnValue(undefined),
say: vi.fn(),
postStateToWebview: vi.fn().mockResolvedValue(undefined),
postStateToWebviewWithoutTaskHistory: vi.fn().mockResolvedValue(undefined),
postMessageToWebview: vi.fn().mockResolvedValue(undefined),
updateTaskHistory: vi.fn().mockResolvedValue(undefined),
}
// Get the mocked delay function
mockDelay = delay as ReturnType<typeof vi.fn>
mockDelay.mockClear()
})
afterEach(() => {
// Clean up the global state after each test
Task.resetGlobalApiRequestTime()
})
it("should enforce rate limiting across parent and subtask", async () => {
// Add a spy to track getState calls
const getStateSpy = vi.spyOn(mockProvider, "getState")
// Create parent task
const parent = new Task({