-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathClineProvider.spec.ts
More file actions
3909 lines (3287 loc) · 128 KB
/
ClineProvider.spec.ts
File metadata and controls
3909 lines (3287 loc) · 128 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/webview/__tests__/ClineProvider.spec.ts
import Anthropic from "@anthropic-ai/sdk"
import * as vscode from "vscode"
import axios from "axios"
import { type ProviderSettingsEntry, type ClineMessage, ORGANIZATION_ALLOW_ALL } from "@roo-code/types"
import { TelemetryService } from "@roo-code/telemetry"
import { ExtensionMessage, ExtensionState } from "../../../shared/ExtensionMessage"
import { defaultModeSlug } from "../../../shared/modes"
import { experimentDefault } from "../../../shared/experiments"
import { setTtsEnabled } from "../../../utils/tts"
import { ContextProxy } from "../../config/ContextProxy"
import { Task, TaskOptions } from "../../task/Task"
import { safeWriteJson } from "../../../utils/safeWriteJson"
import { ClineProvider } from "../ClineProvider"
// Mock setup must come before imports.
vi.mock("../../prompts/sections/custom-instructions")
vi.mock("p-wait-for", () => ({
__esModule: true,
default: vi.fn().mockResolvedValue(undefined),
}))
vi.mock("fs/promises", () => ({
mkdir: vi.fn().mockResolvedValue(undefined),
writeFile: vi.fn().mockResolvedValue(undefined),
readFile: vi.fn().mockResolvedValue(""),
unlink: vi.fn().mockResolvedValue(undefined),
rmdir: vi.fn().mockResolvedValue(undefined),
}))
vi.mock("axios", () => ({
default: {
get: vi.fn().mockResolvedValue({ data: { data: [] } }),
post: vi.fn(),
create: vi.fn(),
interceptors: {
request: vi.fn(),
response: vi.fn(),
},
},
get: vi.fn().mockResolvedValue({ data: { data: [] } }),
post: vi.fn(),
interceptors: {
request: vi.fn(),
response: vi.fn(),
},
}))
vi.mock("../../../utils/safeWriteJson")
vi.mock("../../../utils/storage", () => ({
getSettingsDirectoryPath: vi.fn().mockResolvedValue("/test/settings/path"),
getTaskDirectoryPath: vi.fn().mockResolvedValue("/test/task/path"),
getGlobalStoragePath: vi.fn().mockResolvedValue("/test/storage/path"),
}))
vi.mock("@modelcontextprotocol/sdk/types.js", () => ({
CallToolResultSchema: {},
ListResourcesResultSchema: {},
ListResourceTemplatesResultSchema: {},
ListToolsResultSchema: {},
ReadResourceResultSchema: {},
ErrorCode: {
InvalidRequest: "InvalidRequest",
MethodNotFound: "MethodNotFound",
InternalError: "InternalError",
},
McpError: class McpError extends Error {
code: string
constructor(code: string, message: string) {
super(message)
this.code = code
this.name = "McpError"
}
},
}))
vi.mock("../../../services/browser/BrowserSession", () => ({
BrowserSession: vi.fn().mockImplementation(() => ({
testConnection: vi.fn().mockImplementation(async (url) => {
if (url === "http://localhost:9222") {
return {
success: true,
message: "Successfully connected to Chrome",
endpoint: "ws://localhost:9222/devtools/browser/123",
}
} else {
return {
success: false,
message: "Failed to connect to Chrome",
endpoint: undefined,
}
}
}),
})),
}))
vi.mock("../../../services/browser/browserDiscovery", () => ({
discoverChromeHostUrl: vi.fn().mockResolvedValue("http://localhost:9222"),
tryChromeHostUrl: vi.fn().mockImplementation(async (url) => {
return url === "http://localhost:9222"
}),
testBrowserConnection: vi.fn(),
}))
// Remove duplicate mock - it's already defined below.
const mockAddCustomInstructions = vi.fn().mockResolvedValue("Combined instructions")
;(vi.mocked(await import("../../prompts/sections/custom-instructions")) as any).addCustomInstructions =
mockAddCustomInstructions
vi.mock("delay", () => {
const delayFn = (_ms: number) => Promise.resolve()
delayFn.createDelay = () => delayFn
delayFn.reject = () => Promise.reject(new Error("Delay rejected"))
delayFn.range = () => Promise.resolve()
return { default: delayFn }
})
// MCP-related modules are mocked once above (lines 87-109).
vi.mock("@modelcontextprotocol/sdk/client/index.js", () => ({
Client: vi.fn().mockImplementation(() => ({
connect: vi.fn().mockResolvedValue(undefined),
close: vi.fn().mockResolvedValue(undefined),
listTools: vi.fn().mockResolvedValue({ tools: [] }),
callTool: vi.fn().mockResolvedValue({ content: [] }),
})),
}))
vi.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({
StdioClientTransport: vi.fn().mockImplementation(() => ({
connect: vi.fn().mockResolvedValue(undefined),
close: vi.fn().mockResolvedValue(undefined),
})),
}))
vi.mock("vscode", () => ({
ExtensionContext: vi.fn(),
OutputChannel: vi.fn(),
WebviewView: vi.fn(),
Uri: {
joinPath: vi.fn(),
file: vi.fn(),
},
CodeActionKind: {
QuickFix: { value: "quickfix" },
RefactorRewrite: { value: "refactor.rewrite" },
},
commands: {
executeCommand: vi.fn().mockResolvedValue(undefined),
},
window: {
showInformationMessage: vi.fn(),
showWarningMessage: vi.fn(),
showErrorMessage: vi.fn(),
onDidChangeActiveTextEditor: vi.fn(() => ({ dispose: vi.fn() })),
},
workspace: {
getConfiguration: vi.fn().mockReturnValue({
get: vi.fn().mockReturnValue([]),
update: vi.fn(),
}),
onDidChangeConfiguration: vi.fn().mockImplementation(() => ({
dispose: vi.fn(),
})),
onDidSaveTextDocument: vi.fn(() => ({ dispose: vi.fn() })),
onDidChangeTextDocument: vi.fn(() => ({ dispose: vi.fn() })),
onDidOpenTextDocument: vi.fn(() => ({ dispose: vi.fn() })),
onDidCloseTextDocument: vi.fn(() => ({ dispose: vi.fn() })),
createFileSystemWatcher: vi.fn().mockReturnValue({
onDidCreate: vi.fn().mockReturnValue({ dispose: vi.fn() }),
onDidChange: vi.fn().mockReturnValue({ dispose: vi.fn() }),
onDidDelete: vi.fn().mockReturnValue({ dispose: vi.fn() }),
dispose: vi.fn(),
}),
},
env: {
uriScheme: "vscode",
language: "en",
appName: "Visual Studio Code",
},
ExtensionMode: {
Production: 1,
Development: 2,
Test: 3,
},
RelativePattern: vi.fn().mockImplementation((base, pattern) => ({ base, pattern })),
version: "1.85.0",
}))
vi.mock("../../../utils/tts", () => ({
setTtsEnabled: vi.fn(),
setTtsSpeed: vi.fn(),
}))
vi.mock("../../../api", () => ({
buildApiHandler: vi.fn(),
}))
vi.mock("../../prompts/system", () => ({
SYSTEM_PROMPT: vi.fn().mockImplementation(async () => "mocked system prompt"),
codeMode: "code",
}))
vi.mock("../../../integrations/workspace/WorkspaceTracker", () => {
return {
default: vi.fn().mockImplementation(() => ({
initializeFilePaths: vi.fn(),
dispose: vi.fn(),
})),
}
})
vi.mock("../../task/Task", () => ({
Task: vi
.fn()
.mockImplementation(
(_provider, _apiConfiguration, _customInstructions, _diffEnabled, _fuzzyMatchThreshold, _task, taskId) => ({
api: undefined,
abortTask: vi.fn(),
handleWebviewAskResponse: vi.fn(),
clineMessages: [],
apiConversationHistory: [],
overwriteClineMessages: vi.fn(),
overwriteApiConversationHistory: vi.fn(),
getTaskNumber: vi.fn().mockReturnValue(0),
setTaskNumber: vi.fn(),
setParentTask: vi.fn(),
setRootTask: vi.fn(),
taskId: taskId || "test-task-id",
emit: vi.fn(),
}),
),
}))
vi.mock("../../../integrations/misc/extract-text", () => ({
extractTextFromFile: vi.fn().mockImplementation(async (_filePath: string) => {
const content = "const x = 1;\nconst y = 2;\nconst z = 3;"
const lines = content.split("\n")
return lines.map((line, index) => `${index + 1} | ${line}`).join("\n")
}),
}))
vi.mock("../../../api/providers/fetchers/modelCache", () => ({
getModels: vi.fn().mockResolvedValue({}),
flushModels: vi.fn(),
}))
vi.mock("../../../shared/modes", () => ({
modes: [
{
slug: "code",
name: "Code Mode",
roleDefinition: "You are a code assistant",
groups: ["read", "edit", "browser"],
},
{
slug: "architect",
name: "Architect Mode",
roleDefinition: "You are an architect",
groups: ["read", "edit"],
},
{
slug: "ask",
name: "Ask Mode",
roleDefinition: "You are a helpful assistant",
groups: ["read"],
},
],
getModeBySlug: vi.fn().mockReturnValue({
slug: "code",
name: "Code Mode",
roleDefinition: "You are a code assistant",
groups: ["read", "edit", "browser"],
}),
getGroupName: vi.fn().mockImplementation((group: string) => {
// Return appropriate group names for different tool groups
switch (group) {
case "read":
return "Read Tools"
case "edit":
return "Edit Tools"
case "browser":
return "Browser Tools"
case "mcp":
return "MCP Tools"
default:
return "General Tools"
}
}),
defaultModeSlug: "code",
}))
vi.mock("../../prompts/system", () => ({
SYSTEM_PROMPT: vi.fn().mockResolvedValue("mocked system prompt"),
codeMode: "code",
}))
vi.mock("../../../api", () => ({
buildApiHandler: vi.fn().mockReturnValue({
getModel: vi.fn().mockReturnValue({
id: "claude-3-sonnet",
info: { supportsComputerUse: false },
}),
}),
}))
vi.mock("../../../integrations/misc/extract-text", () => ({
extractTextFromFile: vi.fn().mockImplementation(async (_filePath: string) => {
const content = "const x = 1;\nconst y = 2;\nconst z = 3;"
const lines = content.split("\n")
return lines.map((line, index) => `${index + 1} | ${line}`).join("\n")
}),
}))
vi.mock("../../../api/providers/fetchers/modelCache", () => ({
getModels: vi.fn().mockResolvedValue({}),
flushModels: vi.fn(),
}))
vi.mock("../diff/strategies/multi-search-replace", () => ({
MultiSearchReplaceDiffStrategy: vi.fn().mockImplementation(() => ({
getToolDescription: () => "test",
getName: () => "test-strategy",
applyDiff: vi.fn(),
})),
}))
vi.mock("@roo-code/cloud", () => ({
CloudService: {
hasInstance: vi.fn().mockReturnValue(true),
get instance() {
return {
isAuthenticated: vi.fn().mockReturnValue(false),
}
},
},
BridgeOrchestrator: {
isEnabled: vi.fn().mockReturnValue(false),
},
getRooCodeApiUrl: vi.fn().mockReturnValue("https://app.roocode.com"),
}))
afterAll(() => {
vi.restoreAllMocks()
})
describe("ClineProvider", () => {
let defaultTaskOptions: TaskOptions
let provider: ClineProvider
let mockContext: vscode.ExtensionContext
let mockOutputChannel: vscode.OutputChannel
let mockWebviewView: vscode.WebviewView
let mockPostMessage: any
let updateGlobalStateSpy: any
beforeEach(() => {
vi.clearAllMocks()
if (!TelemetryService.hasInstance()) {
TelemetryService.createInstance([])
}
const globalState: Record<string, string | undefined> = {
mode: "architect",
currentApiConfigName: "current-config",
}
const secrets: Record<string, string | undefined> = {}
mockContext = {
extensionPath: "/test/path",
extensionUri: {} as vscode.Uri,
globalState: {
get: vi.fn().mockImplementation((key: string) => globalState[key]),
update: vi
.fn()
.mockImplementation((key: string, value: string | undefined) => (globalState[key] = value)),
keys: vi.fn().mockImplementation(() => Object.keys(globalState)),
},
secrets: {
get: vi.fn().mockImplementation((key: string) => secrets[key]),
store: vi.fn().mockImplementation((key: string, value: string | undefined) => (secrets[key] = value)),
delete: vi.fn().mockImplementation((key: string) => delete secrets[key]),
},
subscriptions: [],
extension: {
packageJSON: { version: "1.0.0" },
},
globalStorageUri: {
fsPath: "/test/storage/path",
},
} as unknown as vscode.ExtensionContext
// Mock CustomModesManager
const mockCustomModesManager = {
updateCustomMode: vi.fn().mockResolvedValue(undefined),
getCustomModes: vi.fn().mockResolvedValue([]),
dispose: vi.fn(),
}
// Mock output channel
mockOutputChannel = {
appendLine: vi.fn(),
clear: vi.fn(),
dispose: vi.fn(),
} as unknown as vscode.OutputChannel
// Mock webview
mockPostMessage = vi.fn()
mockWebviewView = {
webview: {
postMessage: mockPostMessage,
html: "",
options: {},
onDidReceiveMessage: vi.fn(),
asWebviewUri: vi.fn(),
cspSource: "vscode-webview://test-csp-source",
},
visible: true,
onDidDispose: vi.fn().mockImplementation((callback) => {
callback()
return { dispose: vi.fn() }
}),
onDidChangeVisibility: vi.fn().mockImplementation(() => ({ dispose: vi.fn() })),
} as unknown as vscode.WebviewView
provider = new ClineProvider(mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext))
defaultTaskOptions = {
provider,
apiConfiguration: {
apiProvider: "openrouter",
},
}
// @ts-ignore - Access private property for testing
updateGlobalStateSpy = vi.spyOn(provider.contextProxy, "setValue")
// @ts-ignore - Accessing private property for testing.
provider.customModesManager = mockCustomModesManager
// Mock getMcpHub method for generateSystemPrompt
provider.getMcpHub = vi.fn().mockReturnValue({
listTools: vi.fn().mockResolvedValue([]),
callTool: vi.fn().mockResolvedValue({ content: [] }),
listResources: vi.fn().mockResolvedValue([]),
readResource: vi.fn().mockResolvedValue({ contents: [] }),
getAllServers: vi.fn().mockReturnValue([]),
})
})
test("constructor initializes correctly", () => {
expect(provider).toBeInstanceOf(ClineProvider)
// Since getVisibleInstance returns the last instance where view.visible is true
// @ts-ignore - accessing private property for testing
provider.view = mockWebviewView
expect(ClineProvider.getVisibleInstance()).toBe(provider)
})
test("resolveWebviewView sets up webview correctly", async () => {
await provider.resolveWebviewView(mockWebviewView)
expect(mockWebviewView.webview.options).toEqual({
enableScripts: true,
localResourceRoots: [mockContext.extensionUri],
})
expect(mockWebviewView.webview.html).toContain("<!DOCTYPE html>")
})
test("resolveWebviewView sets up webview correctly in development mode even if local server is not running", async () => {
provider = new ClineProvider(
{ ...mockContext, extensionMode: vscode.ExtensionMode.Development },
mockOutputChannel,
"sidebar",
new ContextProxy(mockContext),
)
;(axios.get as any).mockRejectedValueOnce(new Error("Network error"))
await provider.resolveWebviewView(mockWebviewView)
expect(mockWebviewView.webview.options).toEqual({
enableScripts: true,
localResourceRoots: [mockContext.extensionUri],
})
expect(mockWebviewView.webview.html).toContain("<!DOCTYPE html>")
// Verify Content Security Policy contains the necessary PostHog domains
expect(mockWebviewView.webview.html).toContain(
"connect-src vscode-webview://test-csp-source https://avatars.githubusercontent.com https://openrouter.ai https://api.requesty.ai https://us.i.posthog.com https://us-assets.i.posthog.com;",
)
// Extract the script-src directive section and verify required security elements
const html = mockWebviewView.webview.html
const scriptSrcMatch = html.match(/script-src[^;]*;/)
expect(scriptSrcMatch).not.toBeNull()
expect(scriptSrcMatch![0]).toContain("'nonce-")
// Verify wasm-unsafe-eval is present for Shiki syntax highlighting
expect(scriptSrcMatch![0]).toContain("'wasm-unsafe-eval'")
})
test("postMessageToWebview sends message to webview", async () => {
await provider.resolveWebviewView(mockWebviewView)
const mockState: ExtensionState = {
version: "1.0.0",
clineMessages: [],
taskHistory: [],
shouldShowAnnouncement: false,
apiConfiguration: {
apiProvider: "openrouter",
},
customInstructions: undefined,
alwaysAllowReadOnly: false,
alwaysAllowReadOnlyOutsideWorkspace: false,
alwaysAllowWrite: false,
codebaseIndexConfig: {
codebaseIndexEnabled: true,
codebaseIndexQdrantUrl: "",
codebaseIndexEmbedderProvider: "openai",
codebaseIndexEmbedderBaseUrl: "",
codebaseIndexEmbedderModelId: "",
},
alwaysAllowWriteOutsideWorkspace: false,
alwaysAllowExecute: false,
alwaysAllowBrowser: false,
alwaysAllowMcp: false,
uriScheme: "vscode",
soundEnabled: false,
ttsEnabled: false,
diffEnabled: false,
enableCheckpoints: false,
writeDelayMs: 1000,
browserViewportSize: "900x600",
fuzzyMatchThreshold: 1.0,
mcpEnabled: true,
enableMcpServerCreation: false,
requestDelaySeconds: 5,
mode: defaultModeSlug,
customModes: [],
experiments: experimentDefault,
maxOpenTabsContext: 20,
maxWorkspaceFiles: 200,
browserToolEnabled: true,
// telemetrySetting: "disabled",
// showRooIgnoredFiles: true,
telemetrySetting: "disabled",
showRooIgnoredFiles: false,
renderContext: "sidebar",
maxReadFileLine: 500,
maxImageFileSize: 5,
maxTotalImageSize: 20,
cloudUserInfo: null,
organizationAllowList: ORGANIZATION_ALLOW_ALL,
autoCondenseContext: true,
autoCondenseContextPercent: 100,
cloudIsAuthenticated: false,
sharingEnabled: false,
profileThresholds: {},
hasOpenedModeSelector: false,
diagnosticsEnabled: true,
openRouterImageApiKey: undefined,
openRouterImageGenerationSelectedModel: undefined,
}
const message: ExtensionMessage = {
type: "state",
state: mockState,
}
await provider.postMessageToWebview(message)
expect(mockPostMessage).toHaveBeenCalledWith(message)
})
test("handles webviewDidLaunch message", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Get the message handler from onDidReceiveMessage
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
// Simulate webviewDidLaunch message
await messageHandler({ type: "webviewDidLaunch" })
// Should post state and theme to webview
expect(mockPostMessage).toHaveBeenCalled()
})
test("clearTask aborts current task", async () => {
// Setup Cline instance with auto-mock from the top of the file
const mockCline = new Task(defaultTaskOptions) // Create a new mocked instance
// add the mock object to the stack
await provider.addClineToStack(mockCline)
// get the stack size before the abort call
const stackSizeBeforeAbort = provider.getTaskStackSize()
// call the removeClineFromStack method so it will call the current cline abort and remove it from the stack
await provider.removeClineFromStack()
// get the stack size after the abort call
const stackSizeAfterAbort = provider.getTaskStackSize()
// check if the abort method was called
expect(mockCline.abortTask).toHaveBeenCalled()
// check if the stack size was decreased
expect(stackSizeBeforeAbort - stackSizeAfterAbort).toBe(1)
})
describe("clearTask message handler", () => {
beforeEach(async () => {
await provider.resolveWebviewView(mockWebviewView)
})
test("calls clearTask when there is no parent task", async () => {
// Setup a single task without parent
const mockCline = new Task(defaultTaskOptions)
// No need to set parentTask - it's undefined by default
// Mock the provider methods
const clearTaskSpy = vi.spyOn(provider, "clearTask").mockResolvedValue(undefined)
const finishSubTaskSpy = vi.spyOn(provider, "finishSubTask").mockResolvedValue(undefined)
const postStateToWebviewSpy = vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
// Add task to stack
await provider.addClineToStack(mockCline)
// Get the message handler
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
// Trigger clearTask message
await messageHandler({ type: "clearTask" })
// Verify clearTask was called (not finishSubTask)
expect(clearTaskSpy).toHaveBeenCalled()
expect(finishSubTaskSpy).not.toHaveBeenCalled()
expect(postStateToWebviewSpy).toHaveBeenCalled()
})
test("calls finishSubTask when there is a parent task", async () => {
// Setup parent and child tasks
const parentTask = new Task(defaultTaskOptions)
const childTask = new Task(defaultTaskOptions)
// Set up parent-child relationship by setting the parentTask property
// The mock allows us to set properties directly
;(childTask as any).parentTask = parentTask
;(childTask as any).rootTask = parentTask
// Mock the provider methods
const clearTaskSpy = vi.spyOn(provider, "clearTask").mockResolvedValue(undefined)
const finishSubTaskSpy = vi.spyOn(provider, "finishSubTask").mockResolvedValue(undefined)
const postStateToWebviewSpy = vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
// Add both tasks to stack (parent first, then child)
await provider.addClineToStack(parentTask)
await provider.addClineToStack(childTask)
// Get the message handler
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
// Trigger clearTask message
await messageHandler({ type: "clearTask" })
// Verify finishSubTask was called (not clearTask)
expect(finishSubTaskSpy).toHaveBeenCalledWith(expect.stringContaining("canceled"))
expect(clearTaskSpy).not.toHaveBeenCalled()
expect(postStateToWebviewSpy).toHaveBeenCalled()
})
test("handles case when no current task exists", async () => {
// Don't add any tasks to the stack
// Mock the provider methods
const clearTaskSpy = vi.spyOn(provider, "clearTask").mockResolvedValue(undefined)
const finishSubTaskSpy = vi.spyOn(provider, "finishSubTask").mockResolvedValue(undefined)
const postStateToWebviewSpy = vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
// Get the message handler
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
// Trigger clearTask message
await messageHandler({ type: "clearTask" })
// When there's no current task, clearTask is still called (it handles the no-task case internally)
expect(clearTaskSpy).toHaveBeenCalled()
expect(finishSubTaskSpy).not.toHaveBeenCalled()
// State should still be posted
expect(postStateToWebviewSpy).toHaveBeenCalled()
})
test("correctly identifies subtask scenario for issue #4602", async () => {
// This test specifically validates the fix for issue #4602
// where canceling during API retry was incorrectly treating a single task as a subtask
const mockCline = new Task(defaultTaskOptions)
// No parent task by default - no need to explicitly set
// Mock the provider methods
const clearTaskSpy = vi.spyOn(provider, "clearTask").mockResolvedValue(undefined)
const finishSubTaskSpy = vi.spyOn(provider, "finishSubTask").mockResolvedValue(undefined)
// Add only one task to stack
await provider.addClineToStack(mockCline)
// Verify stack size is 1
expect(provider.getTaskStackSize()).toBe(1)
// Get the message handler
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
// Trigger clearTask message (simulating cancel during API retry)
await messageHandler({ type: "clearTask" })
// The fix ensures clearTask is called, not finishSubTask
expect(clearTaskSpy).toHaveBeenCalled()
expect(finishSubTaskSpy).not.toHaveBeenCalled()
})
})
test("addClineToStack adds multiple Cline instances to the stack", async () => {
// Setup Cline instance with auto-mock from the top of the file
const mockCline1 = new Task(defaultTaskOptions) // Create a new mocked instance
const mockCline2 = new Task(defaultTaskOptions) // Create a new mocked instance
Object.defineProperty(mockCline1, "taskId", { value: "test-task-id-1", writable: true })
Object.defineProperty(mockCline2, "taskId", { value: "test-task-id-2", writable: true })
// add Cline instances to the stack
await provider.addClineToStack(mockCline1)
await provider.addClineToStack(mockCline2)
// verify cline instances were added to the stack
expect(provider.getTaskStackSize()).toBe(2)
// verify current cline instance is the last one added
expect(provider.getCurrentTask()).toBe(mockCline2)
})
test("getState returns correct initial state", async () => {
const state = await provider.getState()
expect(state).toHaveProperty("apiConfiguration")
expect(state.apiConfiguration).toHaveProperty("apiProvider")
expect(state).toHaveProperty("customInstructions")
expect(state).toHaveProperty("alwaysAllowReadOnly")
expect(state).toHaveProperty("alwaysAllowWrite")
expect(state).toHaveProperty("alwaysAllowExecute")
expect(state).toHaveProperty("alwaysAllowBrowser")
expect(state).toHaveProperty("taskHistory")
expect(state).toHaveProperty("soundEnabled")
expect(state).toHaveProperty("ttsEnabled")
expect(state).toHaveProperty("diffEnabled")
expect(state).toHaveProperty("writeDelayMs")
})
test("language is set to VSCode language", async () => {
// Mock VSCode language as Spanish
;(vscode.env as any).language = "pt-BR"
const state = await provider.getState()
expect(state.language).toBe("pt-BR")
})
test("diffEnabled defaults to true when not set", async () => {
// Mock globalState.get to return undefined for diffEnabled
;(mockContext.globalState.get as any).mockReturnValue(undefined)
const state = await provider.getState()
expect(state.diffEnabled).toBe(true)
})
test("writeDelayMs defaults to 1000ms", async () => {
// Mock globalState.get to return undefined for writeDelayMs
;(mockContext.globalState.get as any).mockImplementation((key: string) =>
key === "writeDelayMs" ? undefined : null,
)
const state = await provider.getState()
expect(state.writeDelayMs).toBe(1000)
})
test("handles writeDelayMs message", async () => {
await provider.resolveWebviewView(mockWebviewView)
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
await messageHandler({ type: "writeDelayMs", value: 2000 })
expect(updateGlobalStateSpy).toHaveBeenCalledWith("writeDelayMs", 2000)
expect(mockContext.globalState.update).toHaveBeenCalledWith("writeDelayMs", 2000)
expect(mockPostMessage).toHaveBeenCalled()
})
test("updates sound utility when sound setting changes", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Get the message handler from onDidReceiveMessage
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
// Simulate setting sound to enabled
await messageHandler({ type: "soundEnabled", bool: true })
expect(updateGlobalStateSpy).toHaveBeenCalledWith("soundEnabled", true)
expect(mockContext.globalState.update).toHaveBeenCalledWith("soundEnabled", true)
expect(mockPostMessage).toHaveBeenCalled()
// Simulate setting sound to disabled
await messageHandler({ type: "soundEnabled", bool: false })
expect(mockContext.globalState.update).toHaveBeenCalledWith("soundEnabled", false)
expect(mockPostMessage).toHaveBeenCalled()
// Simulate setting tts to enabled
await messageHandler({ type: "ttsEnabled", bool: true })
expect(setTtsEnabled).toHaveBeenCalledWith(true)
expect(mockContext.globalState.update).toHaveBeenCalledWith("ttsEnabled", true)
expect(mockPostMessage).toHaveBeenCalled()
// Simulate setting tts to disabled
await messageHandler({ type: "ttsEnabled", bool: false })
expect(setTtsEnabled).toHaveBeenCalledWith(false)
expect(mockContext.globalState.update).toHaveBeenCalledWith("ttsEnabled", false)
expect(mockPostMessage).toHaveBeenCalled()
})
test("requestDelaySeconds defaults to 10 seconds", async () => {
// Mock globalState.get to return undefined for requestDelaySeconds
;(mockContext.globalState.get as any).mockImplementation((key: string) => {
if (key === "requestDelaySeconds") {
return undefined
}
return null
})
const state = await provider.getState()
expect(state.requestDelaySeconds).toBe(10)
})
test("alwaysApproveResubmit defaults to false", async () => {
// Mock globalState.get to return undefined for alwaysApproveResubmit
;(mockContext.globalState.get as any).mockReturnValue(undefined)
const state = await provider.getState()
expect(state.alwaysApproveResubmit).toBe(false)
})
test("autoCondenseContext defaults to true", async () => {
// Mock globalState.get to return undefined for autoCondenseContext
;(mockContext.globalState.get as any).mockImplementation((key: string) =>
key === "autoCondenseContext" ? undefined : null,
)
const state = await provider.getState()
expect(state.autoCondenseContext).toBe(true)
})
test("handles autoCondenseContext message", async () => {
await provider.resolveWebviewView(mockWebviewView)
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
await messageHandler({ type: "autoCondenseContext", bool: false })
expect(updateGlobalStateSpy).toHaveBeenCalledWith("autoCondenseContext", false)
expect(mockContext.globalState.update).toHaveBeenCalledWith("autoCondenseContext", false)
expect(mockPostMessage).toHaveBeenCalled()
})
test("autoCondenseContextPercent defaults to 100", async () => {
// Mock globalState.get to return undefined for autoCondenseContextPercent
;(mockContext.globalState.get as any).mockImplementation((key: string) =>
key === "autoCondenseContextPercent" ? undefined : null,
)
const state = await provider.getState()
expect(state.autoCondenseContextPercent).toBe(100)
})
test("handles autoCondenseContextPercent message", async () => {
await provider.resolveWebviewView(mockWebviewView)
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
await messageHandler({ type: "autoCondenseContextPercent", value: 75 })
expect(updateGlobalStateSpy).toHaveBeenCalledWith("autoCondenseContextPercent", 75)
expect(mockContext.globalState.update).toHaveBeenCalledWith("autoCondenseContextPercent", 75)
expect(mockPostMessage).toHaveBeenCalled()
})
it("loads saved API config when switching modes", async () => {
await provider.resolveWebviewView(mockWebviewView)
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
const profile: ProviderSettingsEntry = { name: "test-config", id: "test-id", apiProvider: "anthropic" }
;(provider as any).providerSettingsManager = {
getModeConfigId: vi.fn().mockResolvedValue("test-id"),
listConfig: vi.fn().mockResolvedValue([profile]),
activateProfile: vi.fn().mockResolvedValue(profile),
setModeConfig: vi.fn(),
} as any
// Switch to architect mode
await messageHandler({ type: "mode", text: "architect" })
// Should load the saved config for architect mode
expect(provider.providerSettingsManager.getModeConfigId).toHaveBeenCalledWith("architect")
expect(provider.providerSettingsManager.activateProfile).toHaveBeenCalledWith({ name: "test-config" })
expect(mockContext.globalState.update).toHaveBeenCalledWith("currentApiConfigName", "test-config")
})
it("saves current config when switching to mode without config", async () => {
await provider.resolveWebviewView(mockWebviewView)
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
;(provider as any).providerSettingsManager = {
getModeConfigId: vi.fn().mockResolvedValue(undefined),
listConfig: vi
.fn()
.mockResolvedValue([{ name: "current-config", id: "current-id", apiProvider: "anthropic" }]),
setModeConfig: vi.fn(),
} as any
provider.setValue("currentApiConfigName", "current-config")
// Switch to architect mode
await messageHandler({ type: "mode", text: "architect" })
// Should save current config as default for architect mode
expect(provider.providerSettingsManager.setModeConfig).toHaveBeenCalledWith("architect", "current-id")
})
it("saves config as default for current mode when loading config", async () => {
await provider.resolveWebviewView(mockWebviewView)
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
const profile: ProviderSettingsEntry = { apiProvider: "anthropic", id: "new-id", name: "new-config" }
;(provider as any).providerSettingsManager = {
activateProfile: vi.fn().mockResolvedValue(profile),
listConfig: vi.fn().mockResolvedValue([profile]),
setModeConfig: vi.fn(),
getModeConfigId: vi.fn().mockResolvedValue(undefined),
} as any
// First set the mode
await messageHandler({ type: "mode", text: "architect" })
// Then load the config
await messageHandler({ type: "loadApiConfiguration", text: "new-config" })
// Should save new config as default for architect mode
expect(provider.providerSettingsManager.setModeConfig).toHaveBeenCalledWith("architect", "new-id")
})
it("load API configuration by ID works and updates mode config", async () => {
await provider.resolveWebviewView(mockWebviewView)
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
const profile: ProviderSettingsEntry = {
name: "config-by-id",
id: "config-id-123",
apiProvider: "anthropic",
}
;(provider as any).providerSettingsManager = {
activateProfile: vi.fn().mockResolvedValue(profile),
listConfig: vi.fn().mockResolvedValue([profile]),
setModeConfig: vi.fn(),
getModeConfigId: vi.fn().mockResolvedValue(undefined),
} as any
// First set the mode
await messageHandler({ type: "mode", text: "architect" })
// Then load the config by ID
await messageHandler({ type: "loadApiConfigurationById", text: "config-id-123" })
// Should save new config as default for architect mode
expect(provider.providerSettingsManager.setModeConfig).toHaveBeenCalledWith("architect", "config-id-123")
// Ensure the `activateProfile` method was called with the correct ID
expect(provider.providerSettingsManager.activateProfile).toHaveBeenCalledWith({ id: "config-id-123" })
})
test("handles browserToolEnabled setting", async () => {
await provider.resolveWebviewView(mockWebviewView)
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0]
// Test browserToolEnabled
await messageHandler({ type: "browserToolEnabled", bool: true })
expect(mockContext.globalState.update).toHaveBeenCalledWith("browserToolEnabled", true)
expect(mockPostMessage).toHaveBeenCalled()