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.apiHandlerRebuild.spec.ts
More file actions
583 lines (517 loc) · 17.1 KB
/
Copy pathClineProvider.apiHandlerRebuild.spec.ts
File metadata and controls
583 lines (517 loc) · 17.1 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
// npx vitest core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts
import * as vscode from "vscode"
import { TelemetryService } from "@roo-code/telemetry"
import { getModelId } from "@roo-code/types"
import { ContextProxy } from "../../config/ContextProxy"
import { Task, TaskOptions } from "../../task/Task"
import { ClineProvider } from "../ClineProvider"
// Mock setup
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("../../../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("p-wait-for", () => ({
__esModule: true,
default: vi.fn().mockResolvedValue(undefined),
}))
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 }
})
vi.mock("vscode", () => ({
ExtensionContext: vi.fn(),
OutputChannel: vi.fn(),
WebviewView: vi.fn(),
Uri: {
joinPath: vi.fn(),
file: vi.fn(),
},
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(),
})),
},
env: {
uriScheme: "vscode",
language: "en",
appName: "Visual Studio Code",
},
ExtensionMode: {
Production: 1,
Development: 2,
Test: 3,
},
version: "1.85.0",
}))
vi.mock("../../../utils/tts", () => ({
setTtsEnabled: vi.fn(),
setTtsSpeed: vi.fn(),
}))
vi.mock("../../../api", () => ({
buildApiHandler: vi.fn(),
}))
vi.mock("../../../integrations/workspace/WorkspaceTracker", () => {
return {
default: vi.fn().mockImplementation(() => ({
initializeFilePaths: vi.fn(),
dispose: vi.fn(),
})),
}
})
vi.mock("../../task/Task", () => ({
Task: vi.fn().mockImplementation((options) => {
const mockTask = {
api: undefined,
abortTask: vi.fn(),
handleWebviewAskResponse: vi.fn(),
clineMessages: [],
apiConversationHistory: [],
overwriteClineMessages: vi.fn(),
overwriteApiConversationHistory: vi.fn(),
taskId: options?.historyItem?.id || "test-task-id",
emit: vi.fn(),
updateApiConfiguration: vi.fn().mockImplementation(function (this: any, newConfig: any) {
this.apiConfiguration = newConfig
}),
}
// Define apiConfiguration as a property so tests can read it
Object.defineProperty(mockTask, "apiConfiguration", {
value: options?.apiConfiguration || { apiProvider: "openrouter", openRouterModelId: "openai/gpt-4" },
writable: true,
configurable: true,
})
return mockTask
}),
}))
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"),
}))
describe("ClineProvider - API Handler Rebuild Guard", () => {
let provider: ClineProvider
let mockContext: vscode.ExtensionContext
let mockOutputChannel: vscode.OutputChannel
let mockWebviewView: vscode.WebviewView
let mockPostMessage: any
let defaultTaskOptions: TaskOptions
let buildApiHandlerMock: any
beforeEach(async () => {
vi.clearAllMocks()
if (!TelemetryService.hasInstance()) {
TelemetryService.createInstance([])
}
const globalState: Record<string, any> = {
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: any) => (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]),
onDidChange: vi.fn().mockReturnValue({ dispose: vi.fn() }),
},
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(),
},
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))
// Mock providerSettingsManager
;(provider as any).providerSettingsManager = {
saveConfig: vi.fn().mockResolvedValue("test-id"),
listConfig: vi
.fn()
.mockResolvedValue([
{ name: "test-config", id: "test-id", apiProvider: "openrouter", modelId: "openai/gpt-4" },
]),
setModeConfig: vi.fn(),
activateProfile: vi.fn().mockResolvedValue({
name: "test-config",
id: "test-id",
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
}),
getProfile: vi.fn().mockResolvedValue({
name: "test-config",
id: "test-id",
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
}),
}
// Get the buildApiHandler mock
const { buildApiHandler } = await import("../../../api")
buildApiHandlerMock = vi.mocked(buildApiHandler)
// Setup default mock implementation
buildApiHandlerMock.mockReturnValue({
getModel: vi.fn().mockReturnValue({
id: "openai/gpt-4",
info: { contextWindow: 128000 },
}),
})
defaultTaskOptions = {
provider,
apiConfiguration: {
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
},
}
await provider.resolveWebviewView(mockWebviewView)
})
describe("upsertProviderProfile", () => {
test("calls updateApiConfiguration when provider/model unchanged but profile settings changed (explicit save)", async () => {
// Create a task with the current config
const mockTask = new Task({
...defaultTaskOptions,
apiConfiguration: {
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
},
})
mockTask.api = {
getModel: vi.fn().mockReturnValue({
id: "openai/gpt-4",
info: { contextWindow: 128000 },
}),
} as any
await provider.addClineToStack(mockTask)
// Save settings with SAME provider and model (simulating Save button click)
await provider.upsertProviderProfile(
"test-config",
{
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
// Other settings that might change
rateLimitSeconds: 5,
modelTemperature: 0.7,
},
true,
)
// Verify updateApiConfiguration was called because we force rebuild on explicit save/switch
expect(mockTask.updateApiConfiguration).toHaveBeenCalledWith(
expect.objectContaining({
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
rateLimitSeconds: 5,
modelTemperature: 0.7,
}),
)
// Verify task.apiConfiguration was synchronized
expect((mockTask as any).apiConfiguration.openRouterModelId).toBe("openai/gpt-4")
expect((mockTask as any).apiConfiguration.rateLimitSeconds).toBe(5)
expect((mockTask as any).apiConfiguration.modelTemperature).toBe(0.7)
})
test("calls updateApiConfiguration when provider changes", async () => {
const mockTask = new Task({
...defaultTaskOptions,
apiConfiguration: {
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
},
})
mockTask.api = {
getModel: vi.fn().mockReturnValue({
id: "openai/gpt-4",
info: { contextWindow: 128000 },
}),
} as any
await provider.addClineToStack(mockTask)
// Change provider to anthropic
await provider.upsertProviderProfile(
"test-config",
{
apiProvider: "anthropic",
apiModelId: "claude-3-5-sonnet-20241022",
},
true,
)
// Verify updateApiConfiguration was called since provider changed
expect(mockTask.updateApiConfiguration).toHaveBeenCalledWith(
expect.objectContaining({
apiProvider: "anthropic",
apiModelId: "claude-3-5-sonnet-20241022",
}),
)
})
test("calls updateApiConfiguration when model changes", async () => {
const mockTask = new Task({
...defaultTaskOptions,
apiConfiguration: {
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
},
})
mockTask.api = {
getModel: vi.fn().mockReturnValue({
id: "openai/gpt-4",
info: { contextWindow: 128000 },
}),
} as any
await provider.addClineToStack(mockTask)
// Change model to different model
await provider.upsertProviderProfile(
"test-config",
{
apiProvider: "openrouter",
openRouterModelId: "anthropic/claude-3-5-sonnet-20241022",
},
true,
)
// Verify updateApiConfiguration was called since model changed
expect(mockTask.updateApiConfiguration).toHaveBeenCalledWith(
expect.objectContaining({
apiProvider: "openrouter",
openRouterModelId: "anthropic/claude-3-5-sonnet-20241022",
}),
)
})
test("does nothing when no task is running", async () => {
// Don't add any task to stack
buildApiHandlerMock.mockClear()
await provider.upsertProviderProfile(
"test-config",
{
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
},
true,
)
// Should not call buildApiHandler when there's no task
expect(buildApiHandlerMock).not.toHaveBeenCalled()
})
})
describe("activateProviderProfile", () => {
test("calls updateApiConfiguration when provider/model unchanged but settings differ (explicit profile switch)", async () => {
const mockTask = new Task({
...defaultTaskOptions,
apiConfiguration: {
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
modelTemperature: 0.3,
},
})
mockTask.api = {
getModel: vi.fn().mockReturnValue({
id: "openai/gpt-4",
info: { contextWindow: 128000 },
}),
} as any
await provider.addClineToStack(mockTask)
// Mock activateProfile to return same provider/model but different non-model setting
;(provider as any).providerSettingsManager.activateProfile = vi.fn().mockResolvedValue({
name: "test-config",
id: "test-id",
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
modelTemperature: 0.9,
rateLimitSeconds: 7,
})
await provider.activateProviderProfile({ name: "test-config" })
// Verify updateApiConfiguration was called due to forced rebuild on explicit switch
expect(mockTask.updateApiConfiguration).toHaveBeenCalledWith(
expect.objectContaining({
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
}),
)
// Verify task.apiConfiguration was synchronized
expect((mockTask as any).apiConfiguration.openRouterModelId).toBe("openai/gpt-4")
expect((mockTask as any).apiConfiguration.modelTemperature).toBe(0.9)
expect((mockTask as any).apiConfiguration.rateLimitSeconds).toBe(7)
})
test("calls updateApiConfiguration when provider changes and syncs task.apiConfiguration", async () => {
const mockTask = new Task({
...defaultTaskOptions,
apiConfiguration: {
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
},
})
mockTask.api = {
getModel: vi.fn().mockReturnValue({
id: "openai/gpt-4",
info: { contextWindow: 128000 },
}),
} as any
await provider.addClineToStack(mockTask)
// Mock activateProfile to return different provider
;(provider as any).providerSettingsManager.activateProfile = vi.fn().mockResolvedValue({
name: "anthropic-config",
id: "anthropic-id",
apiProvider: "anthropic",
apiModelId: "claude-3-5-sonnet-20241022",
})
await provider.activateProviderProfile({ name: "anthropic-config" })
// Verify updateApiConfiguration was called
expect(mockTask.updateApiConfiguration).toHaveBeenCalledWith(
expect.objectContaining({
apiProvider: "anthropic",
apiModelId: "claude-3-5-sonnet-20241022",
}),
)
// And task.apiConfiguration synced
expect((mockTask as any).apiConfiguration.apiProvider).toBe("anthropic")
expect((mockTask as any).apiConfiguration.apiModelId).toBe("claude-3-5-sonnet-20241022")
})
test("calls updateApiConfiguration when model changes and syncs task.apiConfiguration", async () => {
const mockTask = new Task({
...defaultTaskOptions,
apiConfiguration: {
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
},
})
mockTask.api = {
getModel: vi.fn().mockReturnValue({
id: "openai/gpt-4",
info: { contextWindow: 128000 },
}),
} as any
await provider.addClineToStack(mockTask)
// Mock activateProfile to return different model
;(provider as any).providerSettingsManager.activateProfile = vi.fn().mockResolvedValue({
name: "test-config",
id: "test-id",
apiProvider: "openrouter",
openRouterModelId: "anthropic/claude-3-5-sonnet-20241022",
})
await provider.activateProviderProfile({ name: "test-config" })
// Verify updateApiConfiguration was called
expect(mockTask.updateApiConfiguration).toHaveBeenCalledWith(
expect.objectContaining({
apiProvider: "openrouter",
openRouterModelId: "anthropic/claude-3-5-sonnet-20241022",
}),
)
// And task.apiConfiguration synced
expect((mockTask as any).apiConfiguration.apiProvider).toBe("openrouter")
expect((mockTask as any).apiConfiguration.openRouterModelId).toBe("anthropic/claude-3-5-sonnet-20241022")
})
})
describe("profile switching sequence", () => {
test("A -> B -> A updates task.apiConfiguration each time", async () => {
const mockTask = new Task({
...defaultTaskOptions,
apiConfiguration: {
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
},
})
mockTask.api = {
getModel: vi.fn().mockReturnValue({
id: "openai/gpt-4",
info: { contextWindow: 128000 },
}),
} as any
await provider.addClineToStack(mockTask)
// First switch: A -> B (openrouter -> anthropic)
;(provider as any).providerSettingsManager.activateProfile = vi.fn().mockResolvedValue({
name: "anthropic-config",
id: "anthropic-id",
apiProvider: "anthropic",
apiModelId: "claude-3-5-sonnet-20241022",
})
await provider.activateProviderProfile({ name: "anthropic-config" })
expect(mockTask.updateApiConfiguration).toHaveBeenCalled()
expect((mockTask as any).apiConfiguration.apiProvider).toBe("anthropic")
expect((mockTask as any).apiConfiguration.apiModelId).toBe("claude-3-5-sonnet-20241022")
// Second switch: B -> A (anthropic -> openrouter gpt-4)
;(mockTask.updateApiConfiguration as any).mockClear()
;(provider as any).providerSettingsManager.activateProfile = vi.fn().mockResolvedValue({
name: "test-config",
id: "test-id",
apiProvider: "openrouter",
openRouterModelId: "openai/gpt-4",
})
await provider.activateProviderProfile({ name: "test-config" })
// updateApiConfiguration called again, and apiConfiguration must be updated
expect(mockTask.updateApiConfiguration).toHaveBeenCalled()
expect((mockTask as any).apiConfiguration.apiProvider).toBe("openrouter")
expect((mockTask as any).apiConfiguration.openRouterModelId).toBe("openai/gpt-4")
})
})
describe("getModelId helper", () => {
test("correctly extracts model ID from different provider configurations", () => {
expect(getModelId({ apiProvider: "openrouter", openRouterModelId: "openai/gpt-4" })).toBe("openai/gpt-4")
expect(getModelId({ apiProvider: "anthropic", apiModelId: "claude-3-5-sonnet-20241022" })).toBe(
"claude-3-5-sonnet-20241022",
)
expect(getModelId({ apiProvider: "openai", openAiModelId: "gpt-4-turbo" })).toBe("gpt-4-turbo")
expect(getModelId({ apiProvider: "bedrock", apiModelId: "anthropic.claude-v2" })).toBe(
"anthropic.claude-v2",
)
})
test("returns undefined when no model ID is present", () => {
expect(getModelId({ apiProvider: "anthropic" })).toBeUndefined()
expect(getModelId({})).toBeUndefined()
})
})
})