Elffuss BraidHub

kikocis/continue public

b9ead350df1d · 16.4 KiBRawPermalink
1import { NextEditProvider } from "core/nextEdit/NextEditProvider";
2import { NextEditOutcome } from "core/nextEdit/types";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4import * as vscode from "vscode";
5import { CompletionDataForAfterJump, JumpManager } from "./JumpManager";
6
7// Mock VSCode API
8vi.mock("vscode", () => {
9 return {
10 window: {
11 activeTextEditor: {
12 document: {
13 lineAt: vi.fn().mockReturnValue({
14 text: "Sample line text",
15 lineNumber: 0,
16 }),
17 getText: vi.fn().mockReturnValue("Sample document text"),
18 lineCount: 5,
19 },
20 selection: {
21 active: { line: 0, character: 0 },
22 },
23 setDecorations: vi.fn(),
24 revealRange: vi.fn(),
25 visibleRanges: [
26 {
27 start: { line: 0, character: 0 },
28 end: { line: 4, character: 0 }, // Changed to be within document bounds
29 },
30 ],
31 },
32 createTextEditorDecorationType: vi.fn().mockReturnValue({
33 dispose: vi.fn(),
34 }),
35 onDidChangeTextEditorSelection: vi.fn().mockReturnValue({
36 dispose: vi.fn(),
37 }),
38 },
39 Position: class {
40 constructor(
41 public line: number,
42 public character: number,
43 ) {}
44 isEqual(other: any) {
45 return this.line === other.line && this.character === other.character;
46 }
47 },
48 Selection: class {
49 constructor(
50 public anchor: any,
51 public active: any,
52 ) {}
53 },
54 Range: class {
55 constructor(
56 public start: any,
57 public end: any,
58 ) {}
59 },
60 TextEditorRevealType: {
61 InCenter: 2,
62 },
63 ThemeColor: class {
64 constructor(public id: string) {}
65 },
66 commands: {
67 executeCommand: vi.fn(),
68 registerCommand: vi.fn().mockReturnValue({
69 dispose: vi.fn(),
70 }),
71 },
72 };
73});
74
75// Mock NextEditProvider
76vi.mock("core/nextEdit/NextEditProvider", () => {
77 const mockDeleteChain = vi.fn();
78 const mockGetInstance = vi.fn(() => ({
79 deleteChain: mockDeleteChain,
80 }));
81
82 return {
83 NextEditProvider: {
84 getInstance: mockGetInstance,
85 },
86 };
87});
88
89const createMockNextEditOutcome = (
90 overrides: Partial<NextEditOutcome> = {},
91): NextEditOutcome => {
92 return {
93 // TabAutocompleteOptions properties
94 disable: false,
95 maxPromptTokens: 2048,
96 debounceDelay: 300,
97 modelTimeout: 5000,
98 maxSuffixPercentage: 0.5,
99 prefixPercentage: 0.8,
100 transform: true,
101 template: "default",
102 multilineCompletions: "auto",
103 slidingWindowPrefixPercentage: 0.5,
104 slidingWindowSize: 100,
105 useCache: true,
106 onlyMyCode: false,
107 useRecentlyEdited: true,
108 useRecentlyOpened: true,
109 disableInFiles: [".env", "node_modules/**"],
110 useImports: true,
111 showWhateverWeHaveAtXMs: 2000,
112 experimental_includeClipboard: true,
113 experimental_includeRecentlyVisitedRanges: true,
114 experimental_includeRecentlyEditedRanges: true,
115 experimental_includeDiff: true,
116 experimental_enableStaticContextualization: false,
117 // Base properties
118 elapsed: 1500,
119 modelProvider: "openai",
120 modelName: "gpt-4",
121 completionOptions: {
122 temperature: 0.7,
123 max_tokens: 1000,
124 },
125 completionId: "comp_12345abcde",
126 uniqueId: "ne_67890fghij",
127 timestamp: Date.now(),
128 gitRepo: "continuedev/continue",
129
130 // NextEdit specific properties
131 fileUri: "file:///workspace/project/src/main.ts",
132 workspaceDirUri: "file:///workspace/project",
133 prompt: "Add error handling to this function",
134 userEdits: "// I added a try/catch block",
135 userExcerpts: "function example() { ... }",
136 originalEditableRange: "function example() {\n return fetch(url);\n}",
137 completion:
138 "function example() {\n try {\n return fetch(url);\n } catch (error) {\n console.error('Fetch failed:', error);\n throw error;\n }\n}",
139 cursorPosition: { line: 2, character: 10 },
140 finalCursorPosition: { line: 4, character: 5 },
141 accepted: true,
142 editableRegionStartLine: 1,
143 editableRegionEndLine: 3,
144 diffLines: [],
145
146 // Apply any overrides
147 ...overrides,
148 };
149};
150
151describe("JumpManager", () => {
152 let jumpManager: JumpManager;
153
154 beforeEach(() => {
155 // Reset mocks
156 vi.resetAllMocks();
157
158 // Re-setup the lineAt mock after reset
159 const mockLineAt = vi.fn().mockReturnValue({
160 text: "Sample line text",
161 lineNumber: 0,
162 });
163
164 // Ensure our mock is properly set up after reset
165 if (vscode.window.activeTextEditor?.document) {
166 vi.mocked(
167 vscode.window.activeTextEditor.document.lineAt,
168 ).mockImplementation(mockLineAt);
169 }
170
171 // Clear any existing instance
172 JumpManager.clearInstance();
173
174 // Get a fresh instance
175 jumpManager = JumpManager.getInstance();
176 });
177
178 afterEach(() => {
179 jumpManager.dispose();
180 });
181
182 describe("getInstance", () => {
183 it("should return the same instance on multiple calls", () => {
184 const instance1 = JumpManager.getInstance();
185 const instance2 = JumpManager.getInstance();
186 expect(instance1).toBe(instance2);
187 });
188 });
189
190 describe("clearInstance", () => {
191 it("should dispose the current instance and clear it", () => {
192 const instance = JumpManager.getInstance();
193 const disposeSpy = vi.spyOn(instance, "dispose");
194
195 JumpManager.clearInstance();
196
197 expect(disposeSpy).toHaveBeenCalled();
198
199 // Get a new instance
200 const newInstance = JumpManager.getInstance();
201 expect(newInstance).not.toBe(instance);
202 });
203 });
204
205 describe("suggestJump", () => {
206 it("should set jumpInProgress to true", async () => {
207 const currentPosition = new vscode.Position(1, 0);
208 const nextJumpLocation = new vscode.Position(3, 0);
209
210 await jumpManager.suggestJump(currentPosition, nextJumpLocation);
211
212 expect(jumpManager.isJumpInProgress()).toBe(true);
213 });
214
215 it("should not suggest jump if completion content matches document content", async () => {
216 const currentPosition = new vscode.Position(1, 0);
217 const nextJumpLocation = new vscode.Position(3, 0);
218 const completionContent = "Test line content";
219
220 // Mock document content to match the completion content
221 const mockLineAt = vi.fn().mockReturnValue({
222 text: "Test line content",
223 lineNumber: 3,
224 });
225
226 // Override the mock for this specific test
227 vi.mocked(
228 vscode.window.activeTextEditor!.document.lineAt,
229 ).mockImplementation(mockLineAt);
230
231 const result = await jumpManager.suggestJump(
232 currentPosition,
233 nextJumpLocation,
234 completionContent,
235 );
236
237 // Jump should not be suggested
238 expect(result).toBe(false);
239 expect(jumpManager.isJumpInProgress()).toBe(false);
240 // Decorations should not be created
241 expect(
242 vscode.window.createTextEditorDecorationType,
243 ).not.toHaveBeenCalled();
244 });
245
246 it("should render decoration for jump location outside visible range (below)", async () => {
247 const currentPosition = new vscode.Position(1, 0);
248 const nextJumpLocation = new vscode.Position(8, 0); // Outside visible range (below)
249
250 await jumpManager.suggestJump(currentPosition, nextJumpLocation);
251
252 // Should create decoration
253 expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled();
254 // Should set context
255 expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
256 "setContext",
257 "continue.jumpDecorationVisible",
258 true,
259 );
260 // Should register key listeners
261 expect(vscode.commands.registerCommand).toHaveBeenCalledWith(
262 "continue.acceptJump",
263 expect.any(Function),
264 );
265 expect(vscode.commands.registerCommand).toHaveBeenCalledWith(
266 "continue.rejectJump",
267 expect.any(Function),
268 );
269 });
270
271 it("should render decoration for jump location outside visible range (above)", async () => {
272 // Set visible range to be below the jump target
273 const mockEditor = vscode.window.activeTextEditor!;
274 Object.defineProperty(mockEditor, "visibleRanges", {
275 value: [{ start: { line: 5 }, end: { line: 10 } }],
276 writable: true,
277 });
278
279 const currentPosition = new vscode.Position(6, 0);
280 const nextJumpLocation = new vscode.Position(2, 0); // Outside visible range (above)
281
282 await jumpManager.suggestJump(currentPosition, nextJumpLocation);
283
284 // Should create decoration
285 expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled();
286 });
287
288 it("should render decoration for jump location within visible range", async () => {
289 const currentPosition = new vscode.Position(1, 0);
290 const nextJumpLocation = new vscode.Position(2, 0); // Within visible range (0-4)
291
292 await jumpManager.suggestJump(currentPosition, nextJumpLocation);
293
294 // Should create decoration
295 expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled();
296 // Should reveal range
297 expect(vscode.window.activeTextEditor!.revealRange).toHaveBeenCalled();
298 });
299 });
300
301 describe("registerKeyListeners", () => {
302 it("should register acceptJump command that moves cursor", async () => {
303 // Setup private method access
304 const privateJumpManager = jumpManager as any;
305
306 // Mock context
307 privateJumpManager._jumpDecorationVisible = true;
308
309 // Create editor mock that matches the expected interface
310 const editor = vscode.window.activeTextEditor!;
311
312 // Create jump position
313 const jumpPosition = new vscode.Position(3, 5);
314
315 // Call the private method
316 await privateJumpManager.registerKeyListeners(editor, jumpPosition);
317
318 // Find the command handler
319 const commandArgs = vi
320 .mocked(vscode.commands.registerCommand)
321 .mock.calls.find((call: any) => call[0] === "continue.acceptJump");
322 expect(commandArgs).toBeDefined();
323 const acceptJumpHandler = commandArgs![1];
324
325 // Clear previous executeCommand calls
326 vi.mocked(vscode.commands.executeCommand).mockClear();
327
328 // Call the handler
329 await acceptJumpHandler();
330
331 // Expect selection to be updated
332 expect(editor.selection).toEqual(
333 new vscode.Selection(jumpPosition, jumpPosition),
334 );
335 // Expect decoration to be cleared
336 expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
337 "setContext",
338 "continue.jumpDecorationVisible",
339 false,
340 );
341 // Expect inline suggest to be triggered
342 expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
343 "editor.action.inlineSuggest.trigger",
344 );
345 });
346
347 it("should register rejectJump command that deletes the chain", async () => {
348 // Setup private method access
349 const privateJumpManager = jumpManager as any;
350
351 // Mock context
352 privateJumpManager._jumpDecorationVisible = true;
353
354 // Get a reference to the mocked deleteChain
355 const mockDeleteChain = vi.mocked(
356 NextEditProvider.getInstance().deleteChain,
357 );
358 mockDeleteChain.mockClear();
359
360 // Call the private method
361 await privateJumpManager.registerKeyListeners(
362 vscode.window.activeTextEditor!,
363 new vscode.Position(0, 0),
364 );
365
366 // Find the command handler
367 const commandArgs = vi
368 .mocked(vscode.commands.registerCommand)
369 .mock.calls.find((call: any) => call[0] === "continue.rejectJump");
370 expect(commandArgs).toBeDefined();
371 const rejectJumpHandler = commandArgs![1];
372 expect(rejectJumpHandler).toBeDefined();
373
374 // Reset executeCommand mock
375 vi.mocked(vscode.commands.executeCommand).mockClear();
376
377 // Call the handler
378 await rejectJumpHandler();
379
380 // Expect NextEditProvider.deleteChain to be called
381 expect(mockDeleteChain).toHaveBeenCalled();
382
383 // Expect decoration to be cleared
384 expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
385 "setContext",
386 "continue.jumpDecorationVisible",
387 false,
388 );
389 });
390
391 it("should register selection change listener that rejects jump on cursor movement", async () => {
392 const privateJumpManager = jumpManager as any;
393 privateJumpManager._jumpDecorationVisible = true;
394 privateJumpManager._oldCursorPosition = new vscode.Position(1, 0);
395
396 const jumpPosition = new vscode.Position(3, 0);
397
398 await privateJumpManager.registerKeyListeners(
399 vscode.window.activeTextEditor!,
400 jumpPosition,
401 );
402
403 // Find the selection change listener
404 expect(vscode.window.onDidChangeTextEditorSelection).toHaveBeenCalled();
405 const selectionChangeListener = vi.mocked(
406 vscode.window.onDidChangeTextEditorSelection,
407 ).mock.calls[0][0];
408
409 // Mock a selection change event that moves cursor away from both old and jump positions
410 const newPosition = new vscode.Position(5, 0);
411 const mockEvent = {
412 textEditor: vscode.window.activeTextEditor!,
413 kind: undefined, // Can be undefined according to VSCode API
414 selections: [new vscode.Selection(newPosition, newPosition)], // Use proper Selection object
415 };
416
417 // Reset executeCommand mock
418 vi.mocked(vscode.commands.executeCommand).mockClear();
419
420 // Call the selection change listener
421 selectionChangeListener(mockEvent);
422
423 // Should trigger reject jump
424 expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
425 "continue.rejectJump",
426 );
427 });
428 });
429
430 describe("setCompletionAfterJump", () => {
431 it("should store completion data", () => {
432 const completionData: CompletionDataForAfterJump = {
433 completionId: "test-id",
434 outcome: createMockNextEditOutcome(),
435 currentPosition: new vscode.Position(1, 0),
436 };
437
438 // Set the completion data
439 jumpManager.setCompletionAfterJump(completionData);
440
441 // Verify the completion data was stored correctly
442 expect((jumpManager as any)._completionAfterJump).toEqual(completionData);
443 });
444
445 it("should process completion data when jump is completed", async () => {
446 const completionData: CompletionDataForAfterJump = {
447 completionId: "test-id",
448 outcome: createMockNextEditOutcome(),
449 currentPosition: new vscode.Position(1, 0),
450 };
451
452 // Set the completion data
453 jumpManager.setCompletionAfterJump(completionData);
454
455 // Verify the completion data was set correctly
456 expect((jumpManager as any)._completionAfterJump).toEqual(completionData);
457
458 // Reset executeCommand mock to clear previous calls
459 vi.mocked(vscode.commands.executeCommand).mockClear();
460
461 // Directly simulate what happens when a jump is completed
462 // by manipulating the internal state
463 (jumpManager as any)._jumpInProgress = false;
464
465 // Now directly call the method that would show the completion
466 // We need to manually implement what the callback would do
467 if ((jumpManager as any)._completionAfterJump) {
468 vscode.commands.executeCommand(
469 "continue.showNextEditAfterJump",
470 (jumpManager as any)._completionAfterJump,
471 );
472 (jumpManager as any)._completionAfterJump = null;
473 }
474
475 // Verify that the command was called with the completion data
476 expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
477 "continue.showNextEditAfterJump",
478 completionData,
479 );
480
481 // Verify that _completionAfterJump was reset to null
482 expect((jumpManager as any)._completionAfterJump).toBeNull();
483 });
484 });
485
486 describe("clearJumpDecoration", () => {
487 it("should dispose decoration and reset state", async () => {
488 // Setup private method access
489 const privateJumpManager = jumpManager as any;
490
491 // Create a mock decoration with a spy on dispose
492 const mockDispose = vi.fn();
493 privateJumpManager._jumpDecoration = {
494 dispose: mockDispose,
495 };
496 privateJumpManager._jumpDecorationVisible = true;
497
498 // Reset executeCommand mock
499 vi.mocked(vscode.commands.executeCommand).mockClear();
500
501 // Call the method
502 await privateJumpManager.clearJumpDecoration();
503
504 // Expect dispose to have been called
505 expect(mockDispose).toHaveBeenCalled();
506
507 // Expect decoration to be undefined after clearing
508 expect(privateJumpManager._jumpDecoration).toBeUndefined();
509 expect(privateJumpManager._jumpDecorationVisible).toBe(false);
510
511 // Expect context to be reset
512 expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
513 "setContext",
514 "continue.jumpDecorationVisible",
515 false,
516 );
517 });
518 });
519});