Elffuss BraidHub

kikocis/continue public

4e263ad457a7 · 8.8 KiBRawPermalink
1import { beforeEach, describe, expect, it, vi } from "vitest";
2import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
3import { HelperVars } from "../autocomplete/util/HelperVars.js";
4import { ConfigHandler } from "../config/ConfigHandler.js";
5import { IDE, ILLM } from "../index.js";
6import { NextEditProvider } from "./NextEditProvider.js";
7
8// Mock the countTokens function
9vi.mock("../llm/countTokens.js", () => ({
10 countTokens: (text: string) => {
11 // Simple mock that counts 1 token per character for predictable tests
12 return text.length;
13 },
14}));
15
16// Create a helper function to set up the test context
17function createMockHelper(
18 fileContents: string,
19 cursorLine: number,
20): HelperVars {
21 const fileLines = fileContents.split("\n");
22
23 return {
24 fileLines,
25 fileContents,
26 pos: { line: cursorLine, character: 0 },
27 modelName: "gpt-4",
28 lang: { name: "typescript" },
29 filepath: "test/file.ts",
30 workspaceUris: ["test/workspace"],
31 options: {},
32 input: { completionId: "test-completion-id" },
33 } as unknown as HelperVars;
34}
35
36// TODO: Add more tests for other methods.
37describe("_calculateOptimalEditableRegion", () => {
38 let nextEditProvider: NextEditProvider;
39 let mockConfigHandler: ConfigHandler;
40 let mockIde: IDE;
41 let mockGetLlm: () => Promise<ILLM | undefined>;
42 let mockOnError: (e: any) => void;
43 let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction;
44
45 beforeEach(() => {
46 // Create comprehensive mocks for all dependencies
47 mockConfigHandler = {
48 loadConfig: vi.fn().mockResolvedValue({ config: {} }),
49 } as unknown as ConfigHandler;
50
51 mockIde = {
52 readFile: vi.fn().mockResolvedValue(""),
53 getWorkspaceDirs: vi.fn().mockResolvedValue([]),
54 getRepoName: vi.fn().mockResolvedValue("test-repo"),
55 getUniqueId: vi.fn().mockResolvedValue("test-id"),
56 getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }),
57 onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => {
58 // Return a disposable object that does nothing when disposed
59 return {
60 dispose: () => {},
61 };
62 }),
63 } as unknown as IDE;
64
65 mockGetLlm = vi.fn().mockResolvedValue({
66 model: "gpt-4",
67 providerName: "openai",
68 underlyingProviderName: "openai",
69 completionOptions: {},
70 chat: vi.fn(),
71 });
72
73 mockOnError = vi.fn();
74 mockGetDefinitionsFromLsp = vi.fn();
75
76 // Initialize NextEditProvider with mocked dependencies
77 nextEditProvider = NextEditProvider.initialize(
78 mockConfigHandler,
79 mockIde,
80 mockGetLlm,
81 mockOnError,
82 mockGetDefinitionsFromLsp,
83 "default",
84 );
85
86 // Expose the private method for testing
87 // This is a bit of a hack, but necessary for testing private methods
88 (nextEditProvider as any)._calculateOptimalEditableRegion = (
89 NextEditProvider.prototype as any
90 )._calculateOptimalEditableRegion.bind(nextEditProvider);
91 });
92
93 // Test cases remain the same as before...
94 it("should include only the cursor line when it already exceeds token limit", () => {
95 // Create a mock helper with a very long cursor line (>500 characters)
96 const longLine = "X".repeat(600);
97 const helper = createMockHelper(longLine, 0);
98
99 //@ts-ignore
100 const result = nextEditProvider._calculateOptimalEditableRegion(
101 helper,
102 "tokenizer",
103 );
104
105 expect(result.editableRegionStartLine).toBe(0);
106 expect(result.editableRegionEndLine).toBe(0);
107 });
108
109 it("should expand symmetrically when possible", () => {
110 // Create content with identical lines and cursor in the middle
111 const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each
112 const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5)
113
114 //@ts-ignore
115 const result = nextEditProvider._calculateOptimalEditableRegion(
116 helper,
117 "tokenizer",
118 );
119
120 // Should expand 5 lines in each direction (total 11 lines) for symmetry
121 expect(result.editableRegionStartLine).toBe(0);
122 expect(result.editableRegionEndLine).toBe(10);
123 });
124
125 it("should expand asymmetrically when hitting a file boundary", () => {
126 // Create content with cursor near the top
127 const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each
128 const helper = createMockHelper(lines, 1); // Cursor near the top (line 1)
129
130 //@ts-ignore
131 const result = nextEditProvider._calculateOptimalEditableRegion(
132 helper,
133 "tokenizer",
134 );
135
136 // Should include more lines below since it can't expand much above
137 expect(result.editableRegionStartLine).toBe(0);
138 // Should include many more lines below to reach token limit
139 expect(result.editableRegionEndLine).toBeGreaterThan(10);
140 });
141
142 it("should handle files with varying line lengths", () => {
143 // Create content with varying line lengths
144 const fileContents = [
145 "Short line", // 10 chars
146 "A".repeat(100), // 100 chars
147 "Medium length line here", // 24 chars
148 "B".repeat(200), // 200 chars
149 "Another typical line of code", // 28 chars
150 ].join("\n");
151
152 const helper = createMockHelper(fileContents, 2); // Cursor on the medium line
153
154 //@ts-ignore
155 const result = nextEditProvider._calculateOptimalEditableRegion(
156 helper,
157 "tokenizer",
158 );
159
160 // Should include all lines since total tokens < 500
161 expect(result.editableRegionStartLine).toBe(0);
162 expect(result.editableRegionEndLine).toBe(4);
163 });
164
165 it("should respect the token limit and not include too many lines", () => {
166 // Create content with many small lines (10 chars each)
167 const lines = Array(600).fill("C".repeat(10)).join("\n");
168 const helper = createMockHelper(lines, 300); // Cursor in the middle
169
170 //@ts-ignore
171 const result = nextEditProvider._calculateOptimalEditableRegion(
172 helper,
173 "tokenizer",
174 );
175
176 // Each line is 10 chars = 10 tokens per line with our mock.
177 // So with 500 token limit, we should get 50 lines total.
178 // 25 above, 25 below, +1 current
179 const totalLines =
180 result.editableRegionEndLine - result.editableRegionStartLine + 1;
181 expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line)
182 });
183
184 it("should use character approximation when using fourChars heuristic", () => {
185 // In this test, we're setting up a situation where tiktoken and fourChars would give different results
186 // Creating 5 lines, each 100 characters
187 const lines = Array(10).fill("D".repeat(100)).join("\n");
188 const helper = createMockHelper(lines, 2); // Cursor in the middle
189
190 // Mock for tiktoken counting (1 char = 1 token)
191 //@ts-ignore
192 const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion(
193 helper,
194 "tokenizer",
195 );
196
197 // Mock for fourChars counting (1 token = 4 chars)
198 // This should include more lines since each line is counted as 25 tokens instead of 100
199 //@ts-ignore
200 const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion(
201 helper,
202 "fourChars",
203 );
204
205 // The fourChars approach should include more lines since it estimates fewer tokens per line
206 expect(
207 fourCharsResult.editableRegionEndLine -
208 fourCharsResult.editableRegionStartLine,
209 ).toBeGreaterThan(
210 tokenizerResult.editableRegionEndLine -
211 tokenizerResult.editableRegionStartLine,
212 );
213 });
214
215 it("should include the entire file if it's within token limit", () => {
216 // Create a small file
217 const smallFile = "Small file\nwith just\na few lines\nof text";
218 const helper = createMockHelper(smallFile, 1);
219
220 //@ts-ignore
221 const result = nextEditProvider._calculateOptimalEditableRegion(
222 helper,
223 "tokenizer",
224 );
225
226 // Should include all lines
227 expect(result.editableRegionStartLine).toBe(0);
228 expect(result.editableRegionEndLine).toBe(3);
229 });
230
231 it("should prioritize balanced context when token limit allows", () => {
232 // Create content with alternating long and short lines
233 const fileContents = [
234 "Short", // 5 chars
235 "E".repeat(80), // 80 chars
236 "Also short", // 10 chars
237 "F".repeat(80), // 80 chars
238 "Another short one", // 17 chars
239 "G".repeat(80), // 80 chars
240 "Final short line", // 16 chars
241 ].join("\n");
242
243 const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3)
244
245 //@ts-ignore
246 const result = nextEditProvider._calculateOptimalEditableRegion(
247 helper,
248 "tokenizer",
249 );
250
251 // Should try to include equal number of lines above and below cursor
252 const linesAbove = result.editableRegionStartLine;
253 const linesBelow =
254 helper.fileLines.length - 1 - result.editableRegionEndLine;
255
256 // Difference between lines above and below should be minimal
257 expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1);
258 });
259});