Elffuss BraidHub

kikocis/continue public

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