This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathClineProvider.sticky-mode.spec.ts
More file actions
1308 lines (1106 loc) · 37.8 KB
/
Copy pathClineProvider.sticky-mode.spec.ts
File metadata and controls
1308 lines (1106 loc) · 37.8 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.sticky-mode.spec.ts
import * as vscode from "vscode"
import { TelemetryService } from "@roo-code/telemetry"
import { ClineProvider } from "../ClineProvider"
import { ContextProxy } from "../../config/ContextProxy"
import { Task } from "../../task/Task"
import type { HistoryItem, ProviderName } from "@roo-code/types"
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() })),
},
env: {
uriScheme: "vscode",
language: "en",
appName: "Visual Studio Code",
},
ExtensionMode: {
Production: 1,
Development: 2,
Test: 3,
},
version: "1.85.0",
}))
// Create a counter for unique task IDs.
let taskIdCounter = 0
vi.mock("../../task/Task", () => ({
Task: vi.fn().mockImplementation((options) => ({
taskId: options.taskId || `test-task-id-${++taskIdCounter}`,
saveClineMessages: vi.fn(),
clineMessages: [],
apiConversationHistory: [],
overwriteClineMessages: vi.fn(),
overwriteApiConversationHistory: vi.fn(),
abortTask: vi.fn(),
handleWebviewAskResponse: vi.fn(),
getTaskNumber: vi.fn().mockReturnValue(0),
setTaskNumber: vi.fn(),
setParentTask: vi.fn(),
setRootTask: vi.fn(),
emit: vi.fn(),
parentTask: options.parentTask,
updateApiConfiguration: vi.fn(),
})),
}))
vi.mock("../../prompts/sections/custom-instructions")
vi.mock("../../../utils/safeWriteJson")
vi.mock("../../../api", () => ({
buildApiHandler: vi.fn().mockReturnValue({
getModel: vi.fn().mockReturnValue({
id: "claude-3-sonnet",
}),
}),
}))
vi.mock("../../../integrations/workspace/WorkspaceTracker", () => ({
default: vi.fn().mockImplementation(() => ({
initializeFilePaths: vi.fn(),
dispose: vi.fn(),
})),
}))
vi.mock("../../diff/strategies/multi-search-replace", () => ({
MultiSearchReplaceDiffStrategy: vi.fn().mockImplementation(() => ({
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),
}
},
},
getRooCodeApiUrl: vi.fn().mockReturnValue("https://app.roocode.com"),
}))
vi.mock("../../../shared/modes", () => ({
modes: [
{
slug: "code",
name: "Code Mode",
roleDefinition: "You are a code assistant",
groups: ["read", "edit"],
},
{
slug: "architect",
name: "Architect Mode",
roleDefinition: "You are an architect",
groups: ["read", "edit"],
},
],
getModeBySlug: vi.fn().mockReturnValue({
slug: "code",
name: "Code Mode",
roleDefinition: "You are a code assistant",
groups: ["read", "edit"],
}),
defaultModeSlug: "code",
}))
vi.mock("../../prompts/system", () => ({
SYSTEM_PROMPT: vi.fn().mockResolvedValue("mocked system prompt"),
codeMode: "code",
}))
vi.mock("../../../api/providers/fetchers/modelCache", () => ({
getModels: vi.fn().mockResolvedValue({}),
flushModels: vi.fn(),
getModelsFromCache: vi.fn().mockReturnValue(undefined),
}))
vi.mock("../../../integrations/misc/extract-text", () => ({
extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"),
}))
vi.mock("p-wait-for", () => ({
default: vi.fn().mockImplementation(async () => Promise.resolve()),
}))
vi.mock("fs/promises", () => ({
mkdir: vi.fn().mockResolvedValue(undefined),
writeFile: vi.fn().mockResolvedValue(undefined),
readFile: vi.fn().mockResolvedValue(""),
readdir: vi.fn().mockResolvedValue([]),
unlink: vi.fn().mockResolvedValue(undefined),
rmdir: vi.fn().mockResolvedValue(undefined),
access: vi.fn().mockResolvedValue(undefined),
rm: vi.fn().mockResolvedValue(undefined),
}))
vi.mock("../../../utils/storage", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../../utils/storage")>()
return {
...actual,
getStorageBasePath: vi.fn().mockImplementation((defaultPath: string) => defaultPath),
getSettingsDirectoryPath: vi.fn().mockResolvedValue("/test/settings/path"),
getTaskDirectoryPath: vi.fn().mockResolvedValue("/test/task/path"),
}
})
vi.mock("@roo-code/telemetry", () => ({
TelemetryService: {
hasInstance: vi.fn().mockReturnValue(true),
createInstance: vi.fn(),
get instance() {
return {
trackEvent: vi.fn(),
trackError: vi.fn(),
setProvider: vi.fn(),
captureModeSwitch: vi.fn(),
}
},
},
}))
describe("ClineProvider - Sticky Mode", () => {
let provider: ClineProvider
let mockContext: vscode.ExtensionContext
let mockOutputChannel: vscode.OutputChannel
let mockWebviewView: vscode.WebviewView
let mockPostMessage: any
beforeEach(async () => {
vi.clearAllMocks()
if (!TelemetryService.hasInstance()) {
TelemetryService.createInstance([])
}
const globalState: Record<string, string | undefined> = {
mode: "code",
currentApiConfigName: "test-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
return Promise.resolve()
}),
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
return Promise.resolve()
}),
delete: vi.fn().mockImplementation((key: string) => {
delete secrets[key]
return Promise.resolve()
}),
},
workspaceState: {
get: vi.fn().mockReturnValue(undefined),
update: vi.fn().mockResolvedValue(undefined),
keys: vi.fn().mockReturnValue([]),
},
subscriptions: [],
extension: {
packageJSON: { version: "1.0.0" },
},
globalStorageUri: {
fsPath: "/test/storage/path",
},
} as unknown as vscode.ExtensionContext
mockOutputChannel = {
appendLine: vi.fn(),
clear: vi.fn(),
dispose: vi.fn(),
} as unknown as vscode.OutputChannel
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))
// Wait for the async TaskHistoryStore initialization to complete
await new Promise((resolve) => setTimeout(resolve, 10))
// Mock getMcpHub method
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([]),
})
})
describe("handleModeSwitch", () => {
beforeEach(async () => {
await provider.resolveWebviewView(mockWebviewView)
})
it("should save mode to task metadata when switching modes", async () => {
// Create a mock task
const mockTask = new Task({
provider,
apiConfiguration: { apiProvider: "openrouter" },
})
// Get the actual taskId from the mock
const taskId = (mockTask as any).taskId || "test-task-id"
// Mock getGlobalState to return task history
vi.spyOn(provider as any, "getGlobalState").mockReturnValue([
{
id: taskId,
ts: Date.now(),
task: "Test task",
number: 1,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0,
},
])
// Mock updateTaskHistory to track calls
const updateTaskHistorySpy = vi
.spyOn(provider, "updateTaskHistory")
.mockImplementation(() => Promise.resolve([]))
// Add task to provider stack
await provider.addClineToStack(mockTask)
// Switch mode
await provider.handleModeSwitch("architect")
// Verify mode was updated in global state
expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "architect")
// Verify task history was updated with new mode
expect(updateTaskHistorySpy).toHaveBeenCalledWith(
expect.objectContaining({
id: taskId,
mode: "architect",
}),
)
})
it("should update task's taskMode property when switching modes", async () => {
// Create a mock task with initial mode
const mockTask = {
taskId: "test-task-id",
taskMode: "code", // Initial mode
emit: vi.fn(),
saveClineMessages: vi.fn(),
clineMessages: [],
apiConversationHistory: [],
updateApiConfiguration: vi.fn(),
}
// Add task to provider stack
await provider.addClineToStack(mockTask as any)
// Mock getGlobalState to return task history
vi.spyOn(provider as any, "getGlobalState").mockReturnValue([
{
id: mockTask.taskId,
ts: Date.now(),
task: "Test task",
number: 1,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0,
},
])
// Mock updateTaskHistory
vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => Promise.resolve([]))
// Switch mode
await provider.handleModeSwitch("architect")
// Verify task's _taskMode property was updated (using private property)
expect((mockTask as any)._taskMode).toBe("architect")
// Verify emit was called with taskModeSwitched event
expect(mockTask.emit).toHaveBeenCalledWith("taskModeSwitched", mockTask.taskId, "architect")
})
it("should update task history with new mode when active task exists", async () => {
// Create a mock task with history
const mockTask = new Task({
provider,
apiConfiguration: { apiProvider: "openrouter" },
})
// Get the actual taskId from the mock
const taskId = (mockTask as any).taskId || "test-task-id"
// Mock getGlobalState to return task history
vi.spyOn(provider as any, "getGlobalState").mockReturnValue([
{
id: taskId,
ts: Date.now(),
task: "Test task",
number: 1,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0,
},
])
// Mock updateTaskHistory to track calls
const updateTaskHistorySpy = vi
.spyOn(provider, "updateTaskHistory")
.mockImplementation(() => Promise.resolve([]))
// Add task to provider stack
await provider.addClineToStack(mockTask)
// Switch mode
await provider.handleModeSwitch("architect")
// Verify updateTaskHistory was called with mode in the history item
expect(updateTaskHistorySpy).toHaveBeenCalledWith(
expect.objectContaining({
id: taskId,
mode: "architect",
}),
)
})
})
describe("createTaskWithHistoryItem", () => {
it("should restore mode from history item when reopening task", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Create a history item with saved mode
const historyItem: HistoryItem = {
id: "test-task-id",
number: 1,
ts: Date.now(),
task: "Test task",
tokensIn: 100,
tokensOut: 200,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0.001,
mode: "architect", // Saved mode
}
// Mock updateGlobalState to track mode updates
const updateGlobalStateSpy = vi.spyOn(provider as any, "updateGlobalState").mockResolvedValue(undefined)
// Initialize task with history item
await provider.createTaskWithHistoryItem(historyItem)
// Verify mode was restored via updateGlobalState
expect(updateGlobalStateSpy).toHaveBeenCalledWith("mode", "architect")
})
it("should use current mode if history item has no saved mode", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Set current mode
mockContext.globalState.get = vi.fn().mockImplementation((key: string) => {
if (key === "mode") return "code"
return undefined
})
// Create a history item without saved mode
const historyItem: HistoryItem = {
id: "test-task-id",
number: 1,
ts: Date.now(),
task: "Test task",
tokensIn: 100,
tokensOut: 200,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0.001,
// No mode field
}
// Mock getTaskWithId
vi.spyOn(provider, "getTaskWithId").mockResolvedValue({
historyItem,
taskDirPath: "/test/path",
apiConversationHistoryFilePath: "/test/path/api_history.json",
uiMessagesFilePath: "/test/path/ui_messages.json",
apiConversationHistory: [],
})
// Mock handleModeSwitch to track calls
const handleModeSwitchSpy = vi.spyOn(provider, "handleModeSwitch").mockResolvedValue()
// Initialize task with history item
await provider.createTaskWithHistoryItem(historyItem)
// Verify mode was not changed (should use current mode)
expect(handleModeSwitchSpy).not.toHaveBeenCalled()
})
})
describe("Task metadata persistence", () => {
it("should include mode in task metadata when creating history items", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Set current mode
await provider.setValue("mode", "debug")
// Create a mock task
const mockTask = new Task({
provider,
apiConfiguration: { apiProvider: "openrouter" },
})
// Get the actual taskId from the mock
const taskId = (mockTask as any).taskId || "test-task-id"
// Mock getGlobalState to return task history with our task
vi.spyOn(provider as any, "getGlobalState").mockReturnValue([
{
id: taskId,
ts: Date.now(),
task: "Test task",
number: 1,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0,
},
])
// Mock updateTaskHistory to capture the updated history item
let updatedHistoryItem: any
vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => {
updatedHistoryItem = item
return Promise.resolve([item])
})
// Add task to provider stack
await provider.addClineToStack(mockTask)
// Trigger a mode switch
await provider.handleModeSwitch("debug")
// Verify mode was included in the updated history item
expect(updatedHistoryItem).toBeDefined()
expect(updatedHistoryItem.mode).toBe("debug")
})
})
describe("Integration with new_task tool", () => {
it("should preserve parent task mode when creating subtasks", async () => {
await provider.resolveWebviewView(mockWebviewView)
// This test verifies that when using the new_task tool to create a subtask,
// the parent task's mode is preserved and not changed by the subtask's mode switch
// Set initial mode to architect
await provider.setValue("mode", "architect")
// Create parent task
const parentTask = new Task({
provider,
apiConfiguration: { apiProvider: "openrouter" },
})
// Get the actual taskId from the mock
const parentTaskId = (parentTask as any).taskId || "parent-task-id"
// Create a simple task history tracking object
const taskModes: Record<string, string> = {
[parentTaskId]: "architect", // Parent starts with architect mode
}
// Mock getGlobalState to return task history
const getGlobalStateMock = vi.spyOn(provider as any, "getGlobalState")
getGlobalStateMock.mockImplementation((key) => {
if (key === "taskHistory") {
return Object.entries(taskModes).map(([id, mode]) => ({
id,
ts: Date.now(),
task: `Task ${id}`,
number: 1,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0,
mode,
}))
}
// Return empty array for other keys
return []
})
// Mock updateTaskHistory to track mode changes
const updateTaskHistoryMock = vi.spyOn(provider, "updateTaskHistory")
updateTaskHistoryMock.mockImplementation((item) => {
// The handleModeSwitch method updates the task history for the current task
// We should only update the task that matches the item.id
if (item.id && item.mode !== undefined) {
taskModes[item.id] = item.mode
}
return Promise.resolve([])
})
// Add parent task to stack
await provider.addClineToStack(parentTask)
// Create a subtask (simulating new_task tool behavior)
const subtask = new Task({
provider,
apiConfiguration: { apiProvider: "openrouter" },
parentTask: parentTask,
})
const subtaskId = (subtask as any).taskId || "subtask-id"
// Initialize subtask with parent's mode
taskModes[subtaskId] = "architect"
// Mock getCurrentTask to return the parent task initially
const getCurrentTaskMock = vi.spyOn(provider, "getCurrentTask")
getCurrentTaskMock.mockReturnValue(parentTask as any)
// Add subtask to stack
await provider.addClineToStack(subtask)
// Now mock getCurrentTask to return the subtask (simulating stack behavior)
getCurrentTaskMock.mockReturnValue(subtask as any)
// Switch subtask to code mode - this should only affect the subtask
await provider.handleModeSwitch("code")
// Verify that the parent task's mode is still architect
expect(taskModes[parentTaskId]).toBe("architect")
// Verify the subtask has code mode
expect(taskModes[subtaskId]).toBe("code")
})
})
describe("Error handling", () => {
it("should handle errors gracefully when saving mode fails", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Create a mock task that throws on save
const mockTask = new Task({
provider,
apiConfiguration: { apiProvider: "openrouter" },
})
vi.spyOn(mockTask as any, "saveClineMessages").mockRejectedValue(new Error("Save failed"))
// Add task to provider stack
await provider.addClineToStack(mockTask)
// Switch mode - should not throw
await expect(provider.handleModeSwitch("architect")).resolves.not.toThrow()
// Verify mode was still updated in global state
expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "architect")
})
it("should handle null/undefined mode gracefully", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Create a history item with null mode
const historyItem: HistoryItem = {
id: "test-task-id",
number: 1,
ts: Date.now(),
task: "Test task",
tokensIn: 100,
tokensOut: 200,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0.001,
mode: null as any, // Invalid mode
}
// Mock getTaskWithId
vi.spyOn(provider, "getTaskWithId").mockResolvedValue({
historyItem,
taskDirPath: "/test/path",
apiConversationHistoryFilePath: "/test/path/api_history.json",
uiMessagesFilePath: "/test/path/ui_messages.json",
apiConversationHistory: [],
})
// Mock handleModeSwitch to track calls
const handleModeSwitchSpy = vi.spyOn(provider, "handleModeSwitch").mockResolvedValue()
// Initialize task with history item - should not throw
await expect(provider.createTaskWithHistoryItem(historyItem)).resolves.not.toThrow()
// Verify mode switch was not called with null
expect(handleModeSwitchSpy).not.toHaveBeenCalledWith(null)
})
it("should restore API configuration when restoring task from history with mode", async () => {
// Setup: Configure different API configs for different modes
const codeApiConfig = { apiProvider: "anthropic" as ProviderName, anthropicApiKey: "code-key" }
const architectApiConfig = { apiProvider: "openai" as ProviderName, openAiApiKey: "architect-key" }
// Save API configs
await provider.upsertProviderProfile("code-config", codeApiConfig)
await provider.upsertProviderProfile("architect-config", architectApiConfig)
// Get the config IDs
const codeConfigId = provider.getProviderProfileEntry("code-config")?.id
const architectConfigId = provider.getProviderProfileEntry("architect-config")?.id
// Associate configs with modes
await provider.providerSettingsManager.setModeConfig("code", codeConfigId!)
await provider.providerSettingsManager.setModeConfig("architect", architectConfigId!)
// Start in code mode with code config
await provider.handleModeSwitch("code")
// Create a history item with architect mode
const historyItem: HistoryItem = {
id: "test-task-id",
number: 1,
ts: Date.now(),
task: "Test task",
tokensIn: 100,
tokensOut: 200,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0.001,
mode: "architect", // Task was created in architect mode
}
// Restore the task from history
await provider.createTaskWithHistoryItem(historyItem)
// Verify that the mode was restored
const state = await provider.getState()
expect(state.mode).toBe("architect")
// Verify that the API configuration was also restored
expect(state.currentApiConfigName).toBe("architect-config")
expect(state.apiConfiguration.apiProvider).toBe("openai")
})
it("should handle mode deletion between sessions", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Create a history item with a mode that no longer exists
const historyItem: HistoryItem = {
id: "test-task-id",
number: 1,
ts: Date.now(),
task: "Test task",
tokensIn: 100,
tokensOut: 200,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0.001,
mode: "deleted-mode", // Mode that doesn't exist
}
// Mock getModeBySlug to return undefined for deleted mode
const { getModeBySlug } = await import("../../../shared/modes")
vi.mocked(getModeBySlug).mockReturnValue(undefined)
// Mock getTaskWithId
vi.spyOn(provider, "getTaskWithId").mockResolvedValue({
historyItem,
taskDirPath: "/test/path",
apiConversationHistoryFilePath: "/test/path/api_history.json",
uiMessagesFilePath: "/test/path/ui_messages.json",
apiConversationHistory: [],
})
// Mock handleModeSwitch to track calls
const handleModeSwitchSpy = vi.spyOn(provider, "handleModeSwitch").mockResolvedValue()
// Initialize task with history item - should not throw
await expect(provider.createTaskWithHistoryItem(historyItem)).resolves.not.toThrow()
// Verify mode switch was not called with deleted mode
expect(handleModeSwitchSpy).not.toHaveBeenCalledWith("deleted-mode")
})
})
describe("Concurrent mode switches", () => {
it("should handle concurrent mode switches on the same task", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Create a mock task
const mockTask = {
taskId: "test-task-id",
_taskMode: "code",
emit: vi.fn(),
saveClineMessages: vi.fn(),
clineMessages: [],
apiConversationHistory: [],
updateApiConfiguration: vi.fn(),
}
// Add task to provider stack
await provider.addClineToStack(mockTask as any)
// Mock getGlobalState to return task history
vi.spyOn(provider as any, "getGlobalState").mockReturnValue([
{
id: mockTask.taskId,
ts: Date.now(),
task: "Test task",
number: 1,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0,
},
])
// Mock updateTaskHistory
const updateTaskHistorySpy = vi
.spyOn(provider, "updateTaskHistory")
.mockImplementation(() => Promise.resolve([]))
// Clear previous calls to globalState.update
vi.mocked(mockContext.globalState.update).mockClear()
// Simulate concurrent mode switches
const switches = [
provider.handleModeSwitch("architect"),
provider.handleModeSwitch("debug"),
provider.handleModeSwitch("code"),
]
await Promise.all(switches)
// Find the last mode update call
const modeCalls = vi.mocked(mockContext.globalState.update).mock.calls.filter((call) => call[0] === "mode")
const lastModeCall = modeCalls[modeCalls.length - 1]
// Verify the last mode switch wins
expect(lastModeCall).toEqual(["mode", "code"])
// Verify task history was updated with final mode
const lastCall = updateTaskHistorySpy.mock.calls[updateTaskHistorySpy.mock.calls.length - 1]
expect(lastCall[0]).toMatchObject({
id: mockTask.taskId,
mode: "code",
})
})
it("should handle mode switches during task save operations", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Create a mock task with slow save operation
const mockTask = {
taskId: "test-task-id",
_taskMode: "code",
emit: vi.fn(),
saveClineMessages: vi.fn().mockImplementation(async () => {
// Simulate slow save
await new Promise((resolve) => setTimeout(resolve, 100))
}),
clineMessages: [],
apiConversationHistory: [],
updateApiConfiguration: vi.fn(),
}
// Add task to provider stack
await provider.addClineToStack(mockTask as any)
// Mock getGlobalState
vi.spyOn(provider as any, "getGlobalState").mockReturnValue([
{
id: mockTask.taskId,
ts: Date.now(),
task: "Test task",
number: 1,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0,
mode: "code",
},
])
// Mock updateTaskHistory
vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => Promise.resolve([]))
// Start a save operation
const savePromise = mockTask.saveClineMessages()
// Switch mode during save
await provider.handleModeSwitch("architect")
// Wait for save to complete
await savePromise
// Task should have the new mode
expect((mockTask as any)._taskMode).toBe("architect")
})
})
describe("Mode switch failure scenarios", () => {
it("should handle invalid mode gracefully", async () => {
await provider.resolveWebviewView(mockWebviewView)
// The provider actually does switch to invalid modes
// This test should verify that behavior
const mockTask = {
taskId: "test-task-id",
_taskMode: "code",
emit: vi.fn(),
saveClineMessages: vi.fn(),
clineMessages: [],
apiConversationHistory: [],
updateApiConfiguration: vi.fn(),
}
// Add task to provider stack
await provider.addClineToStack(mockTask as any)
// Clear previous calls
vi.mocked(mockContext.globalState.update).mockClear()
// Try to switch to invalid mode - it will actually switch
await provider.handleModeSwitch("invalid-mode" as any)
// The mode WILL be updated to invalid-mode (this is the actual behavior)
expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "invalid-mode")
})
it("should handle errors during mode switch gracefully", async () => {
await provider.resolveWebviewView(mockWebviewView)
// Create a mock task that throws on emit only for specific events
let emitCallCount = 0
const mockTask = {
taskId: "test-task-id",
_taskMode: "code",
emit: vi.fn().mockImplementation((event) => {
emitCallCount++
// Only throw on the second emit call (taskModeSwitched event)
// The first call is for TaskFocused in addClineToStack
if (emitCallCount === 2 && event === "taskModeSwitched") {
throw new Error("Emit failed")
}
}),
saveClineMessages: vi.fn(),
clineMessages: [],
apiConversationHistory: [],
updateApiConfiguration: vi.fn(),
}
// Add task to provider stack
await provider.addClineToStack(mockTask as any)
// Mock getGlobalState to return task history
vi.spyOn(provider as any, "getGlobalState").mockReturnValue([
{
id: mockTask.taskId,
ts: Date.now(),
task: "Test task",
number: 1,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
totalCost: 0,
},
])
// Mock updateTaskHistory
vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => Promise.resolve([]))
// Mock console.error to suppress error output
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
// Clear previous mock calls to isolate this test
vi.mocked(mockContext.globalState.update).mockClear()
// The handleModeSwitch method doesn't catch errors from emit, so it will throw
// The error is thrown before the task's mode is updated
await expect(provider.handleModeSwitch("architect")).rejects.toThrow("Emit failed")
// Since the error is thrown before updating the task's _taskMode,
// neither the task mode nor global state are updated
const modeCalls = vi.mocked(mockContext.globalState.update).mock.calls.filter((call) => call[0] === "mode")
expect(modeCalls.length).toBe(0)
// The task's mode should NOT have been updated since the error occurred first
expect(mockTask._taskMode).toBe("code")
consoleErrorSpy.mockRestore()