-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathCloudService.test.ts
More file actions
655 lines (531 loc) · 20.3 KB
/
Copy pathCloudService.test.ts
File metadata and controls
655 lines (531 loc) · 20.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
// npx vitest run src/__tests__/CloudService.test.ts
import * as vscode from "vscode"
import { TelemetryEventName } from "@roo-code/types"
import type { ClineMessage, TelemetryEvent } from "@roo-code/types"
import { TaskNotFoundError } from "../errors.js"
import { CloudService } from "../CloudService.js"
import { WebAuthService } from "../WebAuthService.js"
import { CloudSettingsService } from "../CloudSettingsService.js"
import { CloudShareService } from "../CloudShareService.js"
import { CloudTelemetryClient as TelemetryClient } from "../TelemetryClient.js"
vi.mock("vscode", () => ({
ExtensionContext: vi.fn(),
window: {
showInformationMessage: vi.fn(),
showErrorMessage: vi.fn(),
},
env: {
openExternal: vi.fn(),
},
Uri: {
parse: vi.fn(),
},
}))
vi.mock("../WebAuthService")
vi.mock("../CloudSettingsService")
vi.mock("../CloudShareService")
vi.mock("../TelemetryClient")
describe("CloudService", () => {
let mockContext: vscode.ExtensionContext
let mockAuthService: {
initialize: ReturnType<typeof vi.fn>
broadcast: ReturnType<typeof vi.fn>
login: ReturnType<typeof vi.fn>
logout: ReturnType<typeof vi.fn>
isAuthenticated: ReturnType<typeof vi.fn>
hasActiveSession: ReturnType<typeof vi.fn>
hasOrIsAcquiringActiveSession: ReturnType<typeof vi.fn>
getUserInfo: ReturnType<typeof vi.fn>
getState: ReturnType<typeof vi.fn>
getSessionToken: ReturnType<typeof vi.fn>
handleCallback: ReturnType<typeof vi.fn>
getStoredOrganizationId: ReturnType<typeof vi.fn>
on: ReturnType<typeof vi.fn>
off: ReturnType<typeof vi.fn>
once: ReturnType<typeof vi.fn>
emit: ReturnType<typeof vi.fn>
}
let mockSettingsService: {
initialize: ReturnType<typeof vi.fn>
getSettings: ReturnType<typeof vi.fn>
getAllowList: ReturnType<typeof vi.fn>
isTaskSyncEnabled: ReturnType<typeof vi.fn>
dispose: ReturnType<typeof vi.fn>
on: ReturnType<typeof vi.fn>
off: ReturnType<typeof vi.fn>
}
let mockShareService: {
shareTask: ReturnType<typeof vi.fn>
canShareTask: ReturnType<typeof vi.fn>
}
let mockTelemetryClient: {
backfillMessages: ReturnType<typeof vi.fn>
}
beforeEach(() => {
CloudService.resetInstance()
mockContext = {
subscriptions: [],
workspaceState: {
get: vi.fn(),
update: vi.fn(),
keys: vi.fn().mockReturnValue([]),
},
secrets: {
get: vi.fn(),
store: vi.fn(),
delete: vi.fn(),
onDidChange: vi.fn().mockReturnValue({ dispose: vi.fn() }),
},
globalState: {
get: vi.fn(),
update: vi.fn(),
setKeysForSync: vi.fn(),
keys: vi.fn().mockReturnValue([]),
},
extensionUri: { scheme: "file", path: "/mock/path" },
extensionPath: "/mock/path",
extensionMode: 1,
asAbsolutePath: vi.fn((relativePath: string) => `/mock/path/${relativePath}`),
storageUri: { scheme: "file", path: "/mock/storage" },
extension: {
packageJSON: {
version: "1.0.0",
},
},
} as unknown as vscode.ExtensionContext
mockAuthService = {
initialize: vi.fn().mockResolvedValue(undefined),
broadcast: vi.fn(),
login: vi.fn(),
logout: vi.fn(),
isAuthenticated: vi.fn().mockReturnValue(false),
hasActiveSession: vi.fn().mockReturnValue(false),
hasOrIsAcquiringActiveSession: vi.fn().mockReturnValue(false),
getUserInfo: vi.fn(),
getState: vi.fn().mockReturnValue("logged-out"),
getSessionToken: vi.fn(),
handleCallback: vi.fn(),
getStoredOrganizationId: vi.fn().mockReturnValue(null),
on: vi.fn(),
off: vi.fn(),
once: vi.fn(),
emit: vi.fn(),
}
mockSettingsService = {
initialize: vi.fn(),
getSettings: vi.fn(),
getAllowList: vi.fn(),
isTaskSyncEnabled: vi.fn().mockReturnValue(true),
dispose: vi.fn(),
on: vi.fn(),
off: vi.fn(),
}
mockShareService = {
shareTask: vi.fn(),
canShareTask: vi.fn().mockResolvedValue(true),
}
mockTelemetryClient = {
backfillMessages: vi.fn().mockResolvedValue(undefined),
}
vi.mocked(WebAuthService).mockImplementation(function () {
return mockAuthService as unknown as WebAuthService
})
vi.mocked(CloudSettingsService).mockImplementation(function () {
return mockSettingsService as unknown as CloudSettingsService
})
vi.mocked(CloudShareService).mockImplementation(function () {
return mockShareService as unknown as CloudShareService
})
vi.mocked(TelemetryClient).mockImplementation(function () {
return mockTelemetryClient as unknown as TelemetryClient
})
})
afterEach(() => {
vi.clearAllMocks()
CloudService.resetInstance()
})
describe("createInstance", () => {
it("should create and initialize CloudService instance", async () => {
const mockLog = vi.fn()
const cloudService = await CloudService.createInstance(mockContext, mockLog)
expect(cloudService).toBeInstanceOf(CloudService)
expect(WebAuthService).toHaveBeenCalledWith(mockContext, expect.any(Function))
expect(CloudSettingsService).toHaveBeenCalledWith(mockContext, mockAuthService, expect.any(Function))
})
it("should set up event listeners for CloudSettingsService", async () => {
const mockLog = vi.fn()
await CloudService.createInstance(mockContext, mockLog)
expect(mockSettingsService.on).toHaveBeenCalledWith("settings-updated", expect.any(Function))
})
it("should throw error if instance already exists", async () => {
await CloudService.createInstance(mockContext)
await expect(CloudService.createInstance(mockContext)).rejects.toThrow(
"CloudService instance already created",
)
})
it("should reset the singleton when initialization fails", async () => {
mockAuthService.initialize.mockRejectedValueOnce(new Error("init failed"))
await expect(CloudService.createInstance(mockContext)).rejects.toThrow("init failed")
expect(CloudService.hasInstance()).toBe(false)
})
})
describe("authentication methods", () => {
let cloudService: CloudService
beforeEach(async () => {
cloudService = await CloudService.createInstance(mockContext)
})
it("should delegate login to AuthService", async () => {
await cloudService.login()
expect(mockAuthService.login).toHaveBeenCalled()
})
it("should delegate logout to AuthService", async () => {
await cloudService.logout()
expect(mockAuthService.logout).toHaveBeenCalled()
})
it("should delegate isAuthenticated to AuthService", () => {
const result = cloudService.isAuthenticated()
expect(mockAuthService.isAuthenticated).toHaveBeenCalled()
expect(result).toBe(false)
})
it("always disables cloud telemetry gating in compatibility mode", () => {
expect(CloudService.isEnabled()).toBe(false)
})
it("should delegate hasActiveSession to AuthService", () => {
const result = cloudService.hasActiveSession()
expect(mockAuthService.hasActiveSession).toHaveBeenCalled()
expect(result).toBe(false)
})
it("should delegate getUserInfo to AuthService", async () => {
await cloudService.getUserInfo()
expect(mockAuthService.getUserInfo).toHaveBeenCalled()
})
it("should return organization ID from user info", () => {
const mockUserInfo = {
name: "Test User",
email: "test@example.com",
organizationId: "org_123",
organizationName: "Test Org",
organizationRole: "admin",
}
mockAuthService.getUserInfo.mockReturnValue(mockUserInfo)
const result = cloudService.getOrganizationId()
expect(mockAuthService.getUserInfo).toHaveBeenCalled()
expect(result).toBe("org_123")
})
it("should return null when no organization ID available", () => {
mockAuthService.getUserInfo.mockReturnValue(null)
const result = cloudService.getOrganizationId()
expect(result).toBe(null)
})
it("should return organization name from user info", () => {
const mockUserInfo = {
name: "Test User",
email: "test@example.com",
organizationId: "org_123",
organizationName: "Test Org",
organizationRole: "admin",
}
mockAuthService.getUserInfo.mockReturnValue(mockUserInfo)
const result = cloudService.getOrganizationName()
expect(mockAuthService.getUserInfo).toHaveBeenCalled()
expect(result).toBe("Test Org")
})
it("should return null when no organization name available", () => {
mockAuthService.getUserInfo.mockReturnValue(null)
const result = cloudService.getOrganizationName()
expect(result).toBe(null)
})
it("should return organization role from user info", () => {
const mockUserInfo = {
name: "Test User",
email: "test@example.com",
organizationId: "org_123",
organizationName: "Test Org",
organizationRole: "admin",
}
mockAuthService.getUserInfo.mockReturnValue(mockUserInfo)
const result = cloudService.getOrganizationRole()
expect(mockAuthService.getUserInfo).toHaveBeenCalled()
expect(result).toBe("admin")
})
it("should return null when no organization role available", () => {
mockAuthService.getUserInfo.mockReturnValue(null)
const result = cloudService.getOrganizationRole()
expect(result).toBe(null)
})
it("should delegate getAuthState to AuthService", () => {
const result = cloudService.getAuthState()
expect(mockAuthService.getState).toHaveBeenCalled()
expect(result).toBe("logged-out")
})
it("should delegate handleAuthCallback to AuthService", async () => {
await cloudService.handleAuthCallback("code", "state")
expect(mockAuthService.handleCallback).toHaveBeenCalledWith("code", "state", undefined, undefined)
})
it("should delegate handleAuthCallback with organizationId to AuthService", async () => {
await cloudService.handleAuthCallback("code", "state", "org_123")
expect(mockAuthService.handleCallback).toHaveBeenCalledWith("code", "state", "org_123", undefined)
})
it("should delegate handleAuthCallback with providerModel to AuthService", async () => {
await cloudService.handleAuthCallback("code", "state", "org_123", "xai/grok-code-fast-1")
expect(mockAuthService.handleCallback).toHaveBeenCalledWith(
"code",
"state",
"org_123",
"xai/grok-code-fast-1",
)
})
it("should return stored organization ID from AuthService", () => {
mockAuthService.getStoredOrganizationId.mockReturnValue("org_456")
const result = cloudService.getStoredOrganizationId()
expect(mockAuthService.getStoredOrganizationId).toHaveBeenCalled()
expect(result).toBe("org_456")
})
it("should return null when no stored organization ID available", () => {
mockAuthService.getStoredOrganizationId.mockReturnValue(null)
const result = cloudService.getStoredOrganizationId()
expect(result).toBe(null)
})
it("should return true when stored organization ID exists", () => {
mockAuthService.getStoredOrganizationId.mockReturnValue("org_789")
const result = cloudService.hasStoredOrganizationId()
expect(result).toBe(true)
})
it("should return false when no stored organization ID exists", () => {
mockAuthService.getStoredOrganizationId.mockReturnValue(null)
const result = cloudService.hasStoredOrganizationId()
expect(result).toBe(false)
})
})
describe("organization settings methods", () => {
let cloudService: CloudService
beforeEach(async () => {
cloudService = await CloudService.createInstance(mockContext)
})
it("should delegate getAllowList to SettingsService", () => {
cloudService.getAllowList()
expect(mockSettingsService.getAllowList).toHaveBeenCalled()
})
it("should delegate isTaskSyncEnabled to SettingsService", () => {
const result = cloudService.isTaskSyncEnabled()
expect(mockSettingsService.isTaskSyncEnabled).toHaveBeenCalled()
expect(result).toBe(true)
})
})
describe("error handling", () => {
it("should throw error when accessing methods before initialization", () => {
expect(() => CloudService.instance.login()).toThrow("CloudService not initialized")
})
it("should throw error when accessing instance before creation", () => {
expect(() => CloudService.instance).toThrow("CloudService not initialized")
})
})
describe("hasInstance", () => {
it("should return false when no instance exists", () => {
expect(CloudService.hasInstance()).toBe(false)
})
it("should return true when instance exists and is initialized", async () => {
await CloudService.createInstance(mockContext)
expect(CloudService.hasInstance()).toBe(true)
})
})
describe("dispose", () => {
it("should dispose of all services and clean up", async () => {
const cloudService = await CloudService.createInstance(mockContext)
cloudService.dispose()
expect(mockSettingsService.dispose).toHaveBeenCalled()
})
it("should remove event listeners from CloudSettingsService", async () => {
// Create a mock that will pass the instanceof check
const mockCloudSettingsService = Object.create(CloudSettingsService.prototype)
Object.assign(mockCloudSettingsService, {
initialize: vi.fn(),
getSettings: vi.fn(),
getAllowList: vi.fn(),
dispose: vi.fn(),
on: vi.fn(),
off: vi.fn(),
})
// Override the mock to return our properly typed instance
vi.mocked(CloudSettingsService).mockImplementation(function () {
return mockCloudSettingsService
})
const cloudService = await CloudService.createInstance(mockContext)
// Verify the listener was added
expect(mockCloudSettingsService.on).toHaveBeenCalledWith("settings-updated", expect.any(Function))
// Get the listener function that was registered
const registeredListener = mockCloudSettingsService.on.mock.calls.find(
(call: unknown[]) => call[0] === "settings-updated",
)?.[1]
cloudService.dispose()
// Verify the listener was removed with the same function
expect(mockCloudSettingsService.off).toHaveBeenCalledWith("settings-updated", registeredListener)
})
it("should handle disposal when using StaticSettingsService", async () => {
// Reset the instance first
CloudService.resetInstance()
// Mock a StaticSettingsService (which doesn't extend CloudSettingsService)
const mockStaticSettingsService = {
initialize: vi.fn(),
getSettings: vi.fn(),
getAllowList: vi.fn(),
dispose: vi.fn(),
on: vi.fn(), // Add on method to avoid initialization error
off: vi.fn(), // Add off method for disposal
}
// Override the mock to return a service that won't pass instanceof check
vi.mocked(CloudSettingsService).mockImplementation(function () {
return mockStaticSettingsService as unknown as CloudSettingsService
})
// This should not throw even though the service doesn't pass instanceof check
const _cloudService = await CloudService.createInstance(mockContext)
// Should not throw when disposing
expect(() => _cloudService.dispose()).not.toThrow()
// Should still call dispose on the settings service
expect(mockStaticSettingsService.dispose).toHaveBeenCalled()
// Should NOT call off method since it's not a CloudSettingsService instance
expect(mockStaticSettingsService.off).not.toHaveBeenCalled()
})
})
describe("settings event handling", () => {
let _cloudService: CloudService
beforeEach(async () => {
_cloudService = await CloudService.createInstance(mockContext)
})
it("should emit settings-updated event when settings are updated", async () => {
const settingsListener = vi.fn()
_cloudService.on("settings-updated", settingsListener)
// Get the settings listener that was registered with the settings service
const serviceSettingsListener = mockSettingsService.on.mock.calls.find(
(call: string[]) => call[0] === "settings-updated",
)?.[1]
expect(serviceSettingsListener).toBeDefined()
// Simulate settings update event
const settingsData = {
settings: {
version: 2,
defaultSettings: {},
allowList: { allowAll: true, providers: {} },
},
previousSettings: {
version: 1,
defaultSettings: {},
allowList: { allowAll: true, providers: {} },
},
}
serviceSettingsListener(settingsData)
expect(settingsListener).toHaveBeenCalledWith(settingsData)
})
})
describe("shareTask with ClineMessage retry logic", () => {
let cloudService: CloudService
beforeEach(async () => {
// Reset mocks for shareTask tests
vi.clearAllMocks()
// Reset authentication state for shareTask tests
mockAuthService.isAuthenticated.mockReturnValue(true)
mockAuthService.hasActiveSession.mockReturnValue(true)
mockAuthService.hasOrIsAcquiringActiveSession.mockReturnValue(true)
mockAuthService.getState.mockReturnValue("active")
cloudService = await CloudService.createInstance(mockContext)
})
it("should call shareTask without retry when successful", async () => {
const taskId = "test-task-id"
const visibility = "organization"
const clineMessages: ClineMessage[] = [
{
ts: Date.now(),
type: "say",
say: "text",
text: "Hello world",
},
]
const expectedResult = {
success: true,
shareUrl: "https://example.com/share/123",
}
mockShareService.shareTask.mockResolvedValue(expectedResult)
const result = await cloudService.shareTask(taskId, visibility, clineMessages)
expect(mockShareService.shareTask).toHaveBeenCalledTimes(1)
expect(mockShareService.shareTask).toHaveBeenCalledWith(taskId, visibility)
expect(mockTelemetryClient.backfillMessages).not.toHaveBeenCalled()
expect(result).toEqual(expectedResult)
})
it("should retry with backfill when TaskNotFoundError occurs", async () => {
const taskId = "test-task-id"
const visibility = "organization"
const clineMessages: ClineMessage[] = [
{
ts: Date.now(),
type: "say",
say: "text",
text: "Hello world",
},
]
const expectedResult = {
success: true,
shareUrl: "https://example.com/share/123",
}
// First call throws TaskNotFoundError, second call succeeds
mockShareService.shareTask
.mockRejectedValueOnce(new TaskNotFoundError(taskId))
.mockResolvedValueOnce(expectedResult)
const result = await cloudService.shareTask(taskId, visibility, clineMessages)
expect(mockShareService.shareTask).toHaveBeenCalledTimes(2)
expect(mockShareService.shareTask).toHaveBeenNthCalledWith(1, taskId, visibility)
expect(mockShareService.shareTask).toHaveBeenNthCalledWith(2, taskId, visibility)
expect(mockTelemetryClient.backfillMessages).toHaveBeenCalledTimes(1)
expect(mockTelemetryClient.backfillMessages).toHaveBeenCalledWith(clineMessages, taskId)
expect(result).toEqual(expectedResult)
})
it("should not retry when TaskNotFoundError occurs but no clineMessages provided", async () => {
const taskId = "test-task-id"
const visibility = "organization"
const taskNotFoundError = new TaskNotFoundError(taskId)
mockShareService.shareTask.mockRejectedValue(taskNotFoundError)
await expect(cloudService.shareTask(taskId, visibility)).rejects.toThrow(TaskNotFoundError)
expect(mockShareService.shareTask).toHaveBeenCalledTimes(1)
expect(mockTelemetryClient.backfillMessages).not.toHaveBeenCalled()
})
it("should not retry when non-TaskNotFoundError occurs", async () => {
const taskId = "test-task-id"
const visibility = "organization"
const clineMessages: ClineMessage[] = [
{
ts: Date.now(),
type: "say",
say: "text",
text: "Hello world",
},
]
const genericError = new Error("Some other error")
mockShareService.shareTask.mockRejectedValue(genericError)
await expect(cloudService.shareTask(taskId, visibility, clineMessages)).rejects.toThrow(genericError)
expect(mockShareService.shareTask).toHaveBeenCalledTimes(1)
expect(mockTelemetryClient.backfillMessages).not.toHaveBeenCalled()
})
it("should work with default parameters", async () => {
const taskId = "test-task-id"
const expectedResult = {
success: true,
shareUrl: "https://example.com/share/123",
}
mockShareService.shareTask.mockResolvedValue(expectedResult)
const result = await cloudService.shareTask(taskId)
expect(mockShareService.shareTask).toHaveBeenCalledTimes(1)
expect(mockShareService.shareTask).toHaveBeenCalledWith(taskId, "organization")
expect(result).toEqual(expectedResult)
})
it("captureEvent is a no-op in compatibility mode", async () => {
const log = vi.fn()
const compatService = cloudService
vi.spyOn(compatService as unknown as { log: (...args: unknown[]) => void }, "log").mockImplementation(log)
const telemetryEvent: TelemetryEvent = {
event: TelemetryEventName.TASK_CREATED,
properties: { taskId: "task-123" },
}
compatService.captureEvent(telemetryEvent)
expect(log).toHaveBeenCalledWith("[CloudService] Skipping cloud telemetry capture in compatibility mode")
})
})
})