Elffuss BraidHub

kikocis/continue public

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