Changesets · Branches · Tags · Compare
| Changeset | fe4ed82781c78b7b2757d49031d4c452d731f08ede2c03e4d8a39b1a1f5df297 |
|---|---|
| Author | Adarsh Iyer <76015889+adarshramiyer@users.noreply.github.com> · 2025-06-11 16:25 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-06-11 16:25 -07:00 |
| Parents | 567b310f6477, 1cfd9a0cd983 |
19 files changed
modified core/autocomplete/snippets/getAllSnippets.ts +64 −0
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | import { ContextRetrievalService } from "../context/ContextRetrievalService"; |
| 4 | 4 | import { GetLspDefinitionsFunction } from "../types"; |
| 5 | 5 | import { HelperVars } from "../util/HelperVars"; |
| 6 | +import { openedFilesLruCache } from "../util/openedFilesLruCache"; | |
| 6 | 7 | import { getDiffsFromCache } from "./gitDiffCache"; |
| 7 | 8 | |
| 8 | 9 | import { |
| @@ -22,6 +23,7 @@ | ||
| 22 | 23 | recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[]; |
| 23 | 24 | diffSnippets: AutocompleteDiffSnippet[]; |
| 24 | 25 | clipboardSnippets: AutocompleteClipboardSnippet[]; |
| 26 | + recentlyOpenedFileSnippets: AutocompleteCodeSnippet[]; | |
| 25 | 27 | } |
| 26 | 28 | |
| 27 | 29 | function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> { |
| @@ -103,6 +105,65 @@ | ||
| 103 | 105 | }); |
| 104 | 106 | }; |
| 105 | 107 | |
| 108 | +const getSnippetsFromRecentlyOpenedFiles = async ( | |
| 109 | + helper: HelperVars, | |
| 110 | + ide: IDE, | |
| 111 | +): Promise<AutocompleteCodeSnippet[]> => { | |
| 112 | + if (helper.options.useRecentlyOpened === false) { | |
| 113 | + return []; | |
| 114 | + } | |
| 115 | + | |
| 116 | + try { | |
| 117 | + const currentFileUri = `${helper.filepath}`; | |
| 118 | + | |
| 119 | + // Get all file URIs excluding the current file | |
| 120 | + const fileUrisToRead = [...openedFilesLruCache.entriesDescending()] | |
| 121 | + .filter(([fileUri, _]) => fileUri !== currentFileUri) | |
| 122 | + .map(([fileUri, _]) => fileUri); | |
| 123 | + | |
| 124 | + // Create an array of promises that each read a file with timeout | |
| 125 | + const fileReadPromises = fileUrisToRead.map((fileUri) => { | |
| 126 | + // Create a promise that resolves to a snippet or null | |
| 127 | + const readPromise = new Promise<AutocompleteCodeSnippet | null>( | |
| 128 | + (resolve) => { | |
| 129 | + ide | |
| 130 | + .readFile(fileUri) | |
| 131 | + .then((fileContent) => { | |
| 132 | + if (!fileContent || fileContent.trim() === "") { | |
| 133 | + resolve(null); | |
| 134 | + return; | |
| 135 | + } | |
| 136 | + | |
| 137 | + resolve({ | |
| 138 | + filepath: fileUri, | |
| 139 | + content: fileContent, | |
| 140 | + type: AutocompleteSnippetType.Code, | |
| 141 | + }); | |
| 142 | + }) | |
| 143 | + .catch((e) => { | |
| 144 | + console.error(`Failed to read file ${fileUri}:`, e); | |
| 145 | + resolve(null); | |
| 146 | + }); | |
| 147 | + }, | |
| 148 | + ); | |
| 149 | + // Cut off at 80ms via racing promises | |
| 150 | + return Promise.race([ | |
| 151 | + readPromise, | |
| 152 | + new Promise<null>((resolve) => setTimeout(() => resolve(null), 80)), | |
| 153 | + ]); | |
| 154 | + }); | |
| 155 | + | |
| 156 | + // Execute all file reads in parallel | |
| 157 | + const results = await Promise.all(fileReadPromises); | |
| 158 | + | |
| 159 | + // Filter out null results | |
| 160 | + return results.filter(Boolean) as AutocompleteCodeSnippet[]; | |
| 161 | + } catch (e) { | |
| 162 | + console.error("Error processing opened files cache:", e); | |
| 163 | + return []; | |
| 164 | + } | |
| 165 | +}; | |
| 166 | + | |
| 106 | 167 | export const getAllSnippets = async ({ |
| 107 | 168 | helper, |
| 108 | 169 | ide, |
| @@ -123,6 +184,7 @@ | ||
| 123 | 184 | ideSnippets, |
| 124 | 185 | diffSnippets, |
| 125 | 186 | clipboardSnippets, |
| 187 | + recentlyOpenedFileSnippets, | |
| 126 | 188 | ] = await Promise.all([ |
| 127 | 189 | racePromise(contextRetrievalService.getRootPathSnippets(helper)), |
| 128 | 190 | racePromise( |
| @@ -133,6 +195,7 @@ | ||
| 133 | 195 | : [], |
| 134 | 196 | [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, |
| 135 | 197 | racePromise(getClipboardSnippets(ide)), |
| 198 | + racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete | |
| 136 | 199 | ]); |
| 137 | 200 | |
| 138 | 201 | return { |
| @@ -143,5 +206,6 @@ | ||
| 143 | 206 | diffSnippets, |
| 144 | 207 | clipboardSnippets, |
| 145 | 208 | recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, |
| 209 | + recentlyOpenedFileSnippets, | |
| 146 | 210 | }; |
| 147 | 211 | }; |
added core/autocomplete/templating/__tests__/formatOpenedFilesContext.test.ts +434 −0
| @@ -0,0 +1,434 @@ | ||
| 1 | +/** | |
| 2 | + * Comprehensive tests for formatOpenedFilesContext.ts | |
| 3 | + * | |
| 4 | + */ | |
| 5 | + | |
| 6 | +import { | |
| 7 | + AutocompleteCodeSnippet, | |
| 8 | + AutocompleteDiffSnippet, | |
| 9 | + AutocompleteSnippetType, | |
| 10 | +} from "../../snippets/types"; | |
| 11 | +import { HelperVars } from "../../util/HelperVars"; | |
| 12 | +import { formatOpenedFilesContext } from "../formatOpenedFilesContext"; | |
| 13 | + | |
| 14 | +// Import the now-exported internal functions | |
| 15 | +import { | |
| 16 | + getRecencyAndSizeScore, | |
| 17 | + rankByScore, | |
| 18 | + setLogStats, | |
| 19 | + trimSnippetForContext, | |
| 20 | +} from "../formatOpenedFilesContext"; | |
| 21 | + | |
| 22 | +describe("formatOpenedFilesContext main function tests", () => { | |
| 23 | + const mockHelper = { | |
| 24 | + modelName: "test-model", | |
| 25 | + } as HelperVars; | |
| 26 | + | |
| 27 | + const TOKEN_BUFFER = 50; | |
| 28 | + | |
| 29 | + // Create sample code snippets with various sizes | |
| 30 | + const createCodeSnippet = ( | |
| 31 | + filepath: string, | |
| 32 | + content: string, | |
| 33 | + ): AutocompleteCodeSnippet => ({ | |
| 34 | + type: AutocompleteSnippetType.Code, | |
| 35 | + filepath, | |
| 36 | + content, | |
| 37 | + }); | |
| 38 | + | |
| 39 | + const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({ | |
| 40 | + type: AutocompleteSnippetType.Diff, | |
| 41 | + content, | |
| 42 | + }); | |
| 43 | + | |
| 44 | + test("should return empty array when no snippets are provided", () => { | |
| 45 | + const result = formatOpenedFilesContext( | |
| 46 | + [], | |
| 47 | + 1000, | |
| 48 | + mockHelper, | |
| 49 | + [], | |
| 50 | + TOKEN_BUFFER, | |
| 51 | + ); | |
| 52 | + expect(result).toEqual([]); | |
| 53 | + }); | |
| 54 | + | |
| 55 | + test("should handle zero remaining token count", () => { | |
| 56 | + const snippets = [ | |
| 57 | + createCodeSnippet("file1.ts", "content of file 1"), | |
| 58 | + createCodeSnippet("file2.ts", "content of file 2"), | |
| 59 | + ]; | |
| 60 | + | |
| 61 | + const result = formatOpenedFilesContext( | |
| 62 | + snippets, | |
| 63 | + 0, | |
| 64 | + mockHelper, | |
| 65 | + [], | |
| 66 | + TOKEN_BUFFER, | |
| 67 | + ); | |
| 68 | + | |
| 69 | + expect(result).toEqual([]); | |
| 70 | + }); | |
| 71 | + | |
| 72 | + test("should handle snippets with empty content", () => { | |
| 73 | + const emptySnippets = [ | |
| 74 | + createCodeSnippet("empty1.ts", ""), | |
| 75 | + createCodeSnippet("empty2.ts", ""), | |
| 76 | + ]; | |
| 77 | + | |
| 78 | + const result = formatOpenedFilesContext( | |
| 79 | + emptySnippets, | |
| 80 | + 1000, | |
| 81 | + mockHelper, | |
| 82 | + [], | |
| 83 | + TOKEN_BUFFER, | |
| 84 | + ); | |
| 85 | + | |
| 86 | + expect(result.length).toBe(emptySnippets.length); | |
| 87 | + }); | |
| 88 | + | |
| 89 | + test("should return all snippets when they all fit within token limit", () => { | |
| 90 | + const smallSnippets = [ | |
| 91 | + createCodeSnippet("small1.ts", "a"), | |
| 92 | + createCodeSnippet("small2.ts", "b"), | |
| 93 | + createCodeSnippet("small3.ts", "c"), | |
| 94 | + ]; | |
| 95 | + | |
| 96 | + const result = formatOpenedFilesContext( | |
| 97 | + smallSnippets, | |
| 98 | + 1000, | |
| 99 | + mockHelper, | |
| 100 | + [], | |
| 101 | + TOKEN_BUFFER, | |
| 102 | + ); | |
| 103 | + | |
| 104 | + expect(result.length).toBe(smallSnippets.length); | |
| 105 | + }); | |
| 106 | + | |
| 107 | + test("should handle limited token count", () => { | |
| 108 | + const snippets = Array(10) | |
| 109 | + .fill(0) | |
| 110 | + .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 111 | + | |
| 112 | + const result = formatOpenedFilesContext( | |
| 113 | + snippets, | |
| 114 | + 1, // Extremely small token count | |
| 115 | + mockHelper, | |
| 116 | + [], | |
| 117 | + TOKEN_BUFFER, | |
| 118 | + ); | |
| 119 | + | |
| 120 | + expect(Array.isArray(result)).toBe(true); | |
| 121 | + }); | |
| 122 | + | |
| 123 | + test("should accept valid inputs with adequate token count", () => { | |
| 124 | + const snippets = [ | |
| 125 | + createCodeSnippet("file1.ts", "Some content here"), | |
| 126 | + createCodeSnippet("file2.ts", "More content here"), | |
| 127 | + ]; | |
| 128 | + | |
| 129 | + const result = formatOpenedFilesContext( | |
| 130 | + snippets, | |
| 131 | + 1000, | |
| 132 | + mockHelper, | |
| 133 | + [], | |
| 134 | + TOKEN_BUFFER, | |
| 135 | + ); | |
| 136 | + | |
| 137 | + expect(result.length).toBeGreaterThan(0); | |
| 138 | + }); | |
| 139 | + | |
| 140 | + test("should handle already added snippets parameter", () => { | |
| 141 | + const snippets = [ | |
| 142 | + createCodeSnippet("file1.ts", "content of file 1"), | |
| 143 | + createCodeSnippet("file2.ts", "content of file 2"), | |
| 144 | + ]; | |
| 145 | + | |
| 146 | + const alreadyAddedSnippets = [createDiffSnippet("diff content")]; | |
| 147 | + | |
| 148 | + const result = formatOpenedFilesContext( | |
| 149 | + snippets, | |
| 150 | + 1000, | |
| 151 | + mockHelper, | |
| 152 | + alreadyAddedSnippets, | |
| 153 | + TOKEN_BUFFER, | |
| 154 | + ); | |
| 155 | + | |
| 156 | + expect(result.length).toBe(snippets.length); | |
| 157 | + }); | |
| 158 | + | |
| 159 | + test("should handle large snippets by trimming them", () => { | |
| 160 | + const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000)); | |
| 161 | + | |
| 162 | + const result = formatOpenedFilesContext( | |
| 163 | + [largeSnippet], | |
| 164 | + 200, | |
| 165 | + mockHelper, | |
| 166 | + [], | |
| 167 | + TOKEN_BUFFER, | |
| 168 | + ); | |
| 169 | + | |
| 170 | + expect(result.length).toBe(1); | |
| 171 | + expect(result[0].filepath).toBe(largeSnippet.filepath); | |
| 172 | + expect(result[0].content.length).toBeLessThan(largeSnippet.content.length); | |
| 173 | + }); | |
| 174 | + | |
| 175 | + test("should prioritize more recent snippets when not all fit", () => { | |
| 176 | + const snippets = [ | |
| 177 | + createCodeSnippet("recent1.ts", "a".repeat(10)), | |
| 178 | + createCodeSnippet("recent2.ts", "b".repeat(10000)), | |
| 179 | + createCodeSnippet("recent3.ts", "c".repeat(10000)), | |
| 180 | + ]; | |
| 181 | + | |
| 182 | + const result = formatOpenedFilesContext( | |
| 183 | + snippets, | |
| 184 | + 200, | |
| 185 | + mockHelper, | |
| 186 | + [], | |
| 187 | + TOKEN_BUFFER, | |
| 188 | + ); | |
| 189 | + | |
| 190 | + expect(result.length).toBeGreaterThan(0); | |
| 191 | + expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true); | |
| 192 | + }); | |
| 193 | + | |
| 194 | + test("should handle a mix of large and small snippets effectively", () => { | |
| 195 | + const mixedSnippets = [ | |
| 196 | + createCodeSnippet("small1.ts", "a".repeat(10)), | |
| 197 | + createCodeSnippet("large1.ts", "b".repeat(5000)), | |
| 198 | + createCodeSnippet("small2.ts", "c".repeat(10)), | |
| 199 | + createCodeSnippet("large2.ts", "d".repeat(5000)), | |
| 200 | + ]; | |
| 201 | + | |
| 202 | + const result = formatOpenedFilesContext( | |
| 203 | + mixedSnippets, | |
| 204 | + 500, | |
| 205 | + mockHelper, | |
| 206 | + [], | |
| 207 | + TOKEN_BUFFER, | |
| 208 | + ); | |
| 209 | + | |
| 210 | + expect(result.length).toBeGreaterThan(0); | |
| 211 | + expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true); | |
| 212 | + }); | |
| 213 | + | |
| 214 | + test("should respect minimum token threshold when trimming", () => { | |
| 215 | + const largeSnippets = [ | |
| 216 | + createCodeSnippet("large1.ts", "a".repeat(5000)), | |
| 217 | + createCodeSnippet("large2.ts", "b".repeat(5000)), | |
| 218 | + ]; | |
| 219 | + | |
| 220 | + const result = formatOpenedFilesContext( | |
| 221 | + largeSnippets, | |
| 222 | + 150, | |
| 223 | + mockHelper, | |
| 224 | + [], | |
| 225 | + TOKEN_BUFFER, | |
| 226 | + ); | |
| 227 | + | |
| 228 | + expect(result.length).toBeLessThanOrEqual(1); | |
| 229 | + | |
| 230 | + if (result.length > 0) { | |
| 231 | + expect(result[0].content.length).toBeLessThan( | |
| 232 | + largeSnippets[0].content.length, | |
| 233 | + ); | |
| 234 | + } | |
| 235 | + }); | |
| 236 | +}); | |
| 237 | + | |
| 238 | +// Tests for rankByScore function | |
| 239 | +describe("rankByScore function", () => { | |
| 240 | + const createCodeSnippet = ( | |
| 241 | + filepath: string, | |
| 242 | + content: string, | |
| 243 | + ): AutocompleteCodeSnippet => ({ | |
| 244 | + type: AutocompleteSnippetType.Code, | |
| 245 | + filepath, | |
| 246 | + content, | |
| 247 | + }); | |
| 248 | + | |
| 249 | + test("should return empty array when given empty array", () => { | |
| 250 | + const result = rankByScore([]); | |
| 251 | + expect(result).toEqual([]); | |
| 252 | + }); | |
| 253 | + | |
| 254 | + test("should rank snippets by score", () => { | |
| 255 | + // Initialize logMin and logMax by calling setLogStats first | |
| 256 | + const snippets = [ | |
| 257 | + createCodeSnippet("file1.ts", "a".repeat(10)), | |
| 258 | + createCodeSnippet("file2.ts", "b".repeat(1000)), | |
| 259 | + createCodeSnippet("file3.ts", "c".repeat(100)), | |
| 260 | + ]; | |
| 261 | + setLogStats(snippets); | |
| 262 | + | |
| 263 | + const result = rankByScore(snippets); | |
| 264 | + | |
| 265 | + expect(Array.isArray(result)).toBe(true); | |
| 266 | + expect(result.length).toBeGreaterThan(0); | |
| 267 | + | |
| 268 | + // The snippets should be ranked in some order, which may not match input order | |
| 269 | + expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual( | |
| 270 | + snippets.map((s) => s.filepath), | |
| 271 | + ); | |
| 272 | + }); | |
| 273 | + | |
| 274 | + test("should limit the number of ranked snippets to defaultNumFilesUsed", () => { | |
| 275 | + // Create more snippets than the default limit | |
| 276 | + const manySnippets = Array(10) | |
| 277 | + .fill(0) | |
| 278 | + .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 279 | + setLogStats(manySnippets); | |
| 280 | + | |
| 281 | + const result = rankByScore(manySnippets); | |
| 282 | + | |
| 283 | + // The function should limit the number of snippets (defaultNumFilesUsed is 5) | |
| 284 | + expect(result.length).toBeLessThanOrEqual(5); | |
| 285 | + }); | |
| 286 | +}); | |
| 287 | + | |
| 288 | +// Tests for getRecencyAndSizeScore function | |
| 289 | +describe("getRecencyAndSizeScore function", () => { | |
| 290 | + const createCodeSnippet = ( | |
| 291 | + filepath: string, | |
| 292 | + content: string, | |
| 293 | + ): AutocompleteCodeSnippet => ({ | |
| 294 | + type: AutocompleteSnippetType.Code, | |
| 295 | + filepath, | |
| 296 | + content, | |
| 297 | + }); | |
| 298 | + | |
| 299 | + test("recency score should decrease with higher index", () => { | |
| 300 | + // Initialize log stats first | |
| 301 | + const snippets = [ | |
| 302 | + createCodeSnippet("file1.ts", "a".repeat(100)), | |
| 303 | + createCodeSnippet("file2.ts", "b".repeat(100)), | |
| 304 | + ]; | |
| 305 | + setLogStats(snippets); | |
| 306 | + | |
| 307 | + // Test that score decreases with increasing index | |
| 308 | + const score0 = getRecencyAndSizeScore(0, snippets[0]); | |
| 309 | + const score1 = getRecencyAndSizeScore(1, snippets[0]); | |
| 310 | + const score2 = getRecencyAndSizeScore(2, snippets[0]); | |
| 311 | + | |
| 312 | + expect(score0).toBeGreaterThan(score1); | |
| 313 | + expect(score1).toBeGreaterThan(score2); | |
| 314 | + }); | |
| 315 | + | |
| 316 | + test("size score should be higher for smaller snippets", () => { | |
| 317 | + // Initialize log stats first | |
| 318 | + const snippets = [ | |
| 319 | + createCodeSnippet("small.ts", "a".repeat(50)), | |
| 320 | + createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 321 | + createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 322 | + ]; | |
| 323 | + setLogStats(snippets); | |
| 324 | + | |
| 325 | + // Test with same recency index but different sizes | |
| 326 | + const smallScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 327 | + const mediumScore = getRecencyAndSizeScore(0, snippets[1]); | |
| 328 | + const largeScore = getRecencyAndSizeScore(0, snippets[2]); | |
| 329 | + | |
| 330 | + // Scores should reflect preference for smaller snippets | |
| 331 | + expect(smallScore).toBeGreaterThanOrEqual(mediumScore); | |
| 332 | + expect(mediumScore).toBeGreaterThanOrEqual(largeScore); | |
| 333 | + }); | |
| 334 | + | |
| 335 | + test("recency and size both affect the score with recency having more weight", () => { | |
| 336 | + // Initialize log stats first | |
| 337 | + const snippets = [ | |
| 338 | + createCodeSnippet("recent_large.ts", "a".repeat(1000)), | |
| 339 | + createCodeSnippet("old_small.ts", "b".repeat(50)), | |
| 340 | + ]; | |
| 341 | + setLogStats(snippets); | |
| 342 | + | |
| 343 | + // Test that recency and size both contribute to the score | |
| 344 | + const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 345 | + const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]); | |
| 346 | + | |
| 347 | + // We're not making a direct comparison, just verifying the scoring mechanism works | |
| 348 | + expect(recentLargeScore).toBeGreaterThan(0); | |
| 349 | + expect(oldSmallScore).toBeGreaterThan(0); | |
| 350 | + expect(oldSmallScore).toBeLessThan(1); | |
| 351 | + }); | |
| 352 | +}); | |
| 353 | + | |
| 354 | +// Tests for setLogStats function | |
| 355 | +describe("setLogStats function", () => { | |
| 356 | + const createCodeSnippet = ( | |
| 357 | + filepath: string, | |
| 358 | + content: string, | |
| 359 | + ): AutocompleteCodeSnippet => ({ | |
| 360 | + type: AutocompleteSnippetType.Code, | |
| 361 | + filepath, | |
| 362 | + content, | |
| 363 | + }); | |
| 364 | + | |
| 365 | + test("should set logMin and logMax based on snippet sizes", () => { | |
| 366 | + const snippets = [ | |
| 367 | + createCodeSnippet("small.ts", "a".repeat(50)), | |
| 368 | + createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 369 | + createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 370 | + ]; | |
| 371 | + | |
| 372 | + // We can't directly test logMin and logMax as they're private | |
| 373 | + // but we can verify that the function runs without errors | |
| 374 | + expect(() => setLogStats(snippets)).not.toThrow(); | |
| 375 | + }); | |
| 376 | + | |
| 377 | + test("should handle empty snippets", () => { | |
| 378 | + const emptySnippets = [ | |
| 379 | + createCodeSnippet("empty1.ts", ""), | |
| 380 | + createCodeSnippet("empty2.ts", ""), | |
| 381 | + ]; | |
| 382 | + | |
| 383 | + expect(() => setLogStats(emptySnippets)).not.toThrow(); | |
| 384 | + }); | |
| 385 | + | |
| 386 | + test("should handle single snippet", () => { | |
| 387 | + const singleSnippet = [createCodeSnippet("single.ts", "content")]; | |
| 388 | + | |
| 389 | + expect(() => setLogStats(singleSnippet)).not.toThrow(); | |
| 390 | + }); | |
| 391 | +}); | |
| 392 | + | |
| 393 | +// Tests for trimSnippetForContext function | |
| 394 | +describe("trimSnippetForContext function", () => { | |
| 395 | + const createCodeSnippet = ( | |
| 396 | + filepath: string, | |
| 397 | + content: string, | |
| 398 | + ): AutocompleteCodeSnippet => ({ | |
| 399 | + type: AutocompleteSnippetType.Code, | |
| 400 | + filepath, | |
| 401 | + content, | |
| 402 | + }); | |
| 403 | + | |
| 404 | + test("should return original snippet if it fits within token limit", () => { | |
| 405 | + const snippet = createCodeSnippet("small.ts", "small content"); | |
| 406 | + const modelName = "test-model"; | |
| 407 | + const maxTokens = 1000; // Large enough to fit the snippet | |
| 408 | + | |
| 409 | + const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 410 | + | |
| 411 | + // Should return the original snippet with its token count | |
| 412 | + expect(result.newSnippet).toEqual(snippet); | |
| 413 | + expect(typeof result.newTokens).toBe("number"); | |
| 414 | + expect(result.newTokens).toBeGreaterThan(0); | |
| 415 | + }); | |
| 416 | + | |
| 417 | + test("should trim snippet content if it exceeds token limit", () => { | |
| 418 | + const snippet = createCodeSnippet("large.ts", "a".repeat(1000)); | |
| 419 | + const modelName = "test-model"; | |
| 420 | + const maxTokens = 10; // Small enough to require trimming | |
| 421 | + | |
| 422 | + const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 423 | + | |
| 424 | + // Should return a trimmed snippet | |
| 425 | + expect(result.newSnippet.filepath).toBe(snippet.filepath); | |
| 426 | + expect(result.newSnippet.type).toBe(snippet.type); | |
| 427 | + expect(result.newSnippet.content.length).toBeLessThanOrEqual( | |
| 428 | + snippet.content.length, | |
| 429 | + ); | |
| 430 | + | |
| 431 | + // Token count should be less than or equal to maxTokens | |
| 432 | + expect(result.newTokens).toBeLessThanOrEqual(maxTokens); | |
| 433 | + }); | |
| 434 | +}); |
modified core/autocomplete/templating/filtering.ts +70 −38
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | AutocompleteSnippet, |
| 6 | 6 | } from "../snippets/types"; |
| 7 | 7 | import { HelperVars } from "../util/HelperVars"; |
| 8 | +import { formatOpenedFilesContext } from "./formatOpenedFilesContext"; | |
| 8 | 9 | |
| 9 | 10 | import { isValidSnippet } from "./validation"; |
| 10 | 11 | |
| @@ -47,6 +48,7 @@ | ||
| 47 | 48 | recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets, |
| 48 | 49 | recentlyEditedRanges: payload.recentlyEditedRangeSnippets, |
| 49 | 50 | diff: payload.diffSnippets, |
| 51 | + recentlyOpenedFiles: payload.recentlyOpenedFileSnippets, | |
| 50 | 52 | base: shuffleArray( |
| 51 | 53 | filterSnippetsAlreadyInCaretWindow( |
| 52 | 54 | [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], |
| @@ -68,11 +70,17 @@ | ||
| 68 | 70 | defaultPriority: 1, |
| 69 | 71 | snippets: payload.clipboardSnippets, |
| 70 | 72 | }, |
| 73 | + { | |
| 74 | + key: "recentlyOpenedFiles", | |
| 75 | + enabledOrPriority: helper.options.useRecentlyOpened, | |
| 76 | + defaultPriority: 2, | |
| 77 | + snippets: payload.recentlyOpenedFileSnippets, | |
| 78 | + }, | |
| 71 | 79 | { |
| 72 | 80 | key: "recentlyVisitedRanges", |
| 73 | 81 | enabledOrPriority: |
| 74 | 82 | helper.options.experimental_includeRecentlyVisitedRanges, |
| 75 | - defaultPriority: 2, | |
| 83 | + defaultPriority: 3, | |
| 76 | 84 | snippets: payload.recentlyVisitedRangesSnippets, |
| 77 | 85 | /* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output |
| 78 | 86 | if they are visible. We should handle them separately so that we can control their priority |
| @@ -82,13 +90,13 @@ | ||
| 82 | 90 | key: "recentlyEditedRanges", |
| 83 | 91 | enabledOrPriority: |
| 84 | 92 | helper.options.experimental_includeRecentlyEditedRanges, |
| 85 | - defaultPriority: 3, | |
| 93 | + defaultPriority: 4, | |
| 86 | 94 | snippets: payload.recentlyEditedRangeSnippets, |
| 87 | 95 | }, |
| 88 | 96 | { |
| 89 | 97 | key: "diff", |
| 90 | 98 | enabledOrPriority: helper.options.experimental_includeDiff, |
| 91 | - defaultPriority: 4, | |
| 99 | + defaultPriority: 5, | |
| 92 | 100 | snippets: payload.diffSnippets, |
| 93 | 101 | // TODO: diff is commonly too large, thus anything lower in priority is not included. |
| 94 | 102 | }, |
| @@ -119,46 +127,70 @@ | ||
| 119 | 127 | })) |
| 120 | 128 | .sort((a, b) => a.priority - b.priority); |
| 121 | 129 | |
| 122 | - // Log the snippet order for debugging - uncomment if needed | |
| 123 | - /* console.log( | |
| 124 | - 'Snippet processing order:', | |
| 125 | - snippetOrder | |
| 126 | - .map(({ key, priority }) => `${key} (priority: ${priority})`).join("\n") | |
| 127 | - ); */ | |
| 128 | - | |
| 129 | - // Convert configs to prioritized snippets | |
| 130 | - let prioritizedSnippets = snippetOrder | |
| 131 | - .flatMap(({ key, priority }) => | |
| 132 | - snippets[key].map((snippet) => ({ snippet, priority })), | |
| 133 | - ) | |
| 134 | - .sort((a, b) => a.priority - b.priority) | |
| 135 | - .map(({ snippet }) => snippet); | |
| 136 | - | |
| 137 | - // Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature | |
| 138 | - // while looking at the prompts in the Continue's output | |
| 139 | - prioritizedSnippets = prioritizedSnippets.filter( | |
| 140 | - (snippet) => | |
| 141 | - !(snippet as AutocompleteCodeSnippet).filepath?.startsWith( | |
| 142 | - "output:extension-output-Continue.continue", | |
| 143 | - ), | |
| 144 | - ); | |
| 145 | - | |
| 146 | 130 | const finalSnippets = []; |
| 147 | 131 | let remainingTokenCount = getRemainingTokenCount(helper); |
| 148 | 132 | |
| 149 | - while (remainingTokenCount > 0 && prioritizedSnippets.length > 0) { | |
| 150 | - const snippet = prioritizedSnippets.shift(); | |
| 151 | - if (!snippet || !isValidSnippet(snippet)) { | |
| 152 | - continue; | |
| 133 | + // Process snippets in priority order | |
| 134 | + for (const { key } of snippetOrder) { | |
| 135 | + // Special handling for recentlyOpenedFiles | |
| 136 | + if (key === "recentlyOpenedFiles" && helper.options.useRecentlyOpened) { | |
| 137 | + const recentlyOpenedFilesSnippets = | |
| 138 | + payload.recentlyOpenedFileSnippets.filter( | |
| 139 | + (snippet) => | |
| 140 | + !(snippet as AutocompleteCodeSnippet).filepath?.startsWith( | |
| 141 | + "output:extension-output-Continue.continue", | |
| 142 | + ), | |
| 143 | + ); | |
| 144 | + | |
| 145 | + // Custom trimming | |
| 146 | + const processedSnippets = formatOpenedFilesContext( | |
| 147 | + recentlyOpenedFilesSnippets, | |
| 148 | + remainingTokenCount, | |
| 149 | + helper, | |
| 150 | + finalSnippets, | |
| 151 | + TOKEN_BUFFER, | |
| 152 | + ); | |
| 153 | + | |
| 154 | + // Add processed snippets to finalSnippets respecting token limits | |
| 155 | + for (const snippet of processedSnippets) { | |
| 156 | + if (!isValidSnippet(snippet)) continue; | |
| 157 | + | |
| 158 | + const snippetSize = | |
| 159 | + countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER; | |
| 160 | + | |
| 161 | + if (remainingTokenCount >= snippetSize) { | |
| 162 | + finalSnippets.push(snippet); | |
| 163 | + remainingTokenCount -= snippetSize; | |
| 164 | + } else { | |
| 165 | + break; // Out of tokens | |
| 166 | + } | |
| 167 | + } | |
| 168 | + } else { | |
| 169 | + // Normal processing for other snippet types | |
| 170 | + const snippetsToProcess = snippets[key].filter( | |
| 171 | + (snippet) => | |
| 172 | + !(snippet as AutocompleteCodeSnippet).filepath?.startsWith( | |
| 173 | + "output:extension-output-Continue.continue", | |
| 174 | + ), | |
| 175 | + ); | |
| 176 | + | |
| 177 | + for (const snippet of snippetsToProcess) { | |
| 178 | + if (!isValidSnippet(snippet)) continue; | |
| 179 | + | |
| 180 | + const snippetSize = | |
| 181 | + countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER; | |
| 182 | + | |
| 183 | + if (remainingTokenCount >= snippetSize) { | |
| 184 | + finalSnippets.push(snippet); | |
| 185 | + remainingTokenCount -= snippetSize; | |
| 186 | + } else { | |
| 187 | + break; // Out of tokens | |
| 188 | + } | |
| 189 | + } | |
| 153 | 190 | } |
| 154 | 191 | |
| 155 | - const snippetSize = | |
| 156 | - countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER; | |
| 157 | - | |
| 158 | - if (remainingTokenCount >= snippetSize) { | |
| 159 | - finalSnippets.push(snippet); | |
| 160 | - remainingTokenCount -= snippetSize; | |
| 161 | - } | |
| 192 | + // If we're out of tokens, no need to process more snippet types | |
| 193 | + if (remainingTokenCount <= 0) break; | |
| 162 | 194 | } |
| 163 | 195 | |
| 164 | 196 | return finalSnippets; |
added core/autocomplete/templating/formatOpenedFilesContext.ts +172 −0
| @@ -0,0 +1,172 @@ | ||
| 1 | +import { countTokens, pruneStringFromBottom } from "../../llm/countTokens"; | |
| 2 | +import { | |
| 3 | + AutocompleteCodeSnippet, | |
| 4 | + AutocompleteSnippet, | |
| 5 | +} from "../snippets/types"; | |
| 6 | +import { HelperVars } from "../util/HelperVars"; | |
| 7 | + | |
| 8 | +let logMin: number; | |
| 9 | +let logMax: number; | |
| 10 | + | |
| 11 | +const numFilesConsidered = 10; | |
| 12 | +const defaultNumFilesUsed = 5; | |
| 13 | +const recencyWeight = 0.6; | |
| 14 | +const sizeWeight = 0.4; | |
| 15 | +const minSize = 10; | |
| 16 | +const minTokensInSnippet = 125; | |
| 17 | + | |
| 18 | +// Fits opened-file snippets into the remaining amount of prompt tokens | |
| 19 | +export function formatOpenedFilesContext( | |
| 20 | + recentlyOpenedFilesSnippets: AutocompleteCodeSnippet[], | |
| 21 | + remainingTokenCount: number, | |
| 22 | + helper: HelperVars, | |
| 23 | + alreadyAddedSnippets: AutocompleteSnippet[], // TODO use this to deduplicate context | |
| 24 | + TOKEN_BUFFER: number, | |
| 25 | +): AutocompleteCodeSnippet[] { | |
| 26 | + if (recentlyOpenedFilesSnippets.length === 0) { | |
| 27 | + return []; | |
| 28 | + } | |
| 29 | + | |
| 30 | + // Calculate how many full snippets would fit within the remaining token count | |
| 31 | + let numSnippetsThatFit = 0; | |
| 32 | + let totalTokens = 0; | |
| 33 | + | |
| 34 | + const numFilesUsed = Math.min( | |
| 35 | + defaultNumFilesUsed, | |
| 36 | + recentlyOpenedFilesSnippets.length, | |
| 37 | + ); | |
| 38 | + | |
| 39 | + for (let i = 0; i < recentlyOpenedFilesSnippets.length; i++) { | |
| 40 | + const snippetTokens = countTokens( | |
| 41 | + recentlyOpenedFilesSnippets[i].content, | |
| 42 | + helper.modelName, | |
| 43 | + ); | |
| 44 | + if (totalTokens + snippetTokens < remainingTokenCount - TOKEN_BUFFER) { | |
| 45 | + totalTokens += snippetTokens; | |
| 46 | + numSnippetsThatFit++; | |
| 47 | + } else { | |
| 48 | + break; | |
| 49 | + } | |
| 50 | + } | |
| 51 | + | |
| 52 | + // if all the untrimmed snippets, or more than a default value, fit, return the untrimmed snippets | |
| 53 | + if (numSnippetsThatFit >= numFilesUsed) { | |
| 54 | + return recentlyOpenedFilesSnippets.slice(0, numSnippetsThatFit); | |
| 55 | + } | |
| 56 | + | |
| 57 | + // If they don't fit, adaptively trim them. | |
| 58 | + setLogStats(recentlyOpenedFilesSnippets); | |
| 59 | + const topScoredSnippets = rankByScore(recentlyOpenedFilesSnippets); | |
| 60 | + let N = topScoredSnippets.length; | |
| 61 | + while (remainingTokenCount - TOKEN_BUFFER < N * minTokensInSnippet) { | |
| 62 | + topScoredSnippets.pop(); | |
| 63 | + N = topScoredSnippets.length; | |
| 64 | + if (N === 0) break; | |
| 65 | + } | |
| 66 | + | |
| 67 | + let trimmedSnippets = new Array<AutocompleteCodeSnippet>(); | |
| 68 | + | |
| 69 | + while (N > 0) { | |
| 70 | + let W = 2 / (N + 1); | |
| 71 | + let snippetTokenLimit = Math.floor( | |
| 72 | + minTokensInSnippet + | |
| 73 | + W * (remainingTokenCount - TOKEN_BUFFER - N * minTokensInSnippet), | |
| 74 | + ); | |
| 75 | + | |
| 76 | + let trimmedSnippetAndTokenCount = trimSnippetForContext( | |
| 77 | + topScoredSnippets[0], | |
| 78 | + snippetTokenLimit, | |
| 79 | + helper.modelName, | |
| 80 | + ); | |
| 81 | + trimmedSnippets.push(trimmedSnippetAndTokenCount.newSnippet); | |
| 82 | + remainingTokenCount -= trimmedSnippetAndTokenCount.newTokens; | |
| 83 | + topScoredSnippets.shift(); | |
| 84 | + N = topScoredSnippets.length; | |
| 85 | + } | |
| 86 | + | |
| 87 | + return trimmedSnippets; | |
| 88 | +} | |
| 89 | + | |
| 90 | +// Rank snippets by recency and size | |
| 91 | +const rankByScore = ( | |
| 92 | + snippets: AutocompleteCodeSnippet[], | |
| 93 | +): AutocompleteCodeSnippet[] => { | |
| 94 | + if (snippets.length === 0) return []; | |
| 95 | + | |
| 96 | + const topSnippets = snippets.slice(0, numFilesConsidered); | |
| 97 | + | |
| 98 | + // Sort by score (using original index for recency calculation) | |
| 99 | + const scoredSnippets = topSnippets.map((snippet, i) => ({ | |
| 100 | + snippet, | |
| 101 | + originalIndex: i, | |
| 102 | + score: getRecencyAndSizeScore(i, snippet), | |
| 103 | + })); | |
| 104 | + | |
| 105 | + // Uncomment to debug. Logs the table of snippets with their scores (in order of recency). | |
| 106 | + /* console.table( | |
| 107 | + topSnippets.map((snippet, i) => ({ | |
| 108 | + filepath: "filepath" in snippet ? snippet.filepath : "unknown", | |
| 109 | + recencyAndSizeScore: getRecencyAndSizeScore(i, snippet), | |
| 110 | + })), | |
| 111 | + ); */ | |
| 112 | + | |
| 113 | + scoredSnippets.sort((a, b) => b.score - a.score); | |
| 114 | + | |
| 115 | + return scoredSnippets | |
| 116 | + .slice(0, Math.min(defaultNumFilesUsed, scoredSnippets.length)) | |
| 117 | + .map((item) => item.snippet); | |
| 118 | +}; | |
| 119 | + | |
| 120 | +// Returns linear combination of recency and size scores | |
| 121 | +// recency score is exponential decay over recency; log normalized score is used for size | |
| 122 | +const getRecencyAndSizeScore = ( | |
| 123 | + index: number, | |
| 124 | + snippet: AutocompleteSnippet, | |
| 125 | +): number => { | |
| 126 | + const recencyScore = Math.pow(1.15, -1 * index); | |
| 127 | + | |
| 128 | + const logCurrent = Math.log(Math.max(snippet.content.length, minSize)); | |
| 129 | + const sizeScore = | |
| 130 | + logMax === logMin ? 0.5 : 1 - (logCurrent - logMin) / (logMax - logMin); | |
| 131 | + | |
| 132 | + return recencyWeight * recencyScore + sizeWeight * sizeScore; | |
| 133 | +}; | |
| 134 | + | |
| 135 | +const setLogStats = (snippets: AutocompleteSnippet[]): void => { | |
| 136 | + let contentSizes = snippets | |
| 137 | + .slice(0, 10) | |
| 138 | + .map((snippet) => snippet.content.length); | |
| 139 | + logMin = Math.log(Math.max(Math.min(...contentSizes), minSize)); | |
| 140 | + logMax = Math.log(Math.max(Math.max(...contentSizes), minSize)); | |
| 141 | + return; | |
| 142 | +}; | |
| 143 | + | |
| 144 | +function trimSnippetForContext( | |
| 145 | + snippet: AutocompleteCodeSnippet, | |
| 146 | + maxTokens: number, | |
| 147 | + modelName: string, | |
| 148 | +): { newSnippet: AutocompleteCodeSnippet; newTokens: number } { | |
| 149 | + let numTokensInSnippet = countTokens(snippet.content, modelName); | |
| 150 | + if (numTokensInSnippet <= maxTokens) { | |
| 151 | + return { newSnippet: snippet, newTokens: numTokensInSnippet }; | |
| 152 | + } | |
| 153 | + | |
| 154 | + let trimmedCode = pruneStringFromBottom( | |
| 155 | + modelName, | |
| 156 | + maxTokens, | |
| 157 | + snippet.content, | |
| 158 | + ); | |
| 159 | + | |
| 160 | + return { | |
| 161 | + newSnippet: { ...snippet, content: trimmedCode }, | |
| 162 | + newTokens: countTokens(trimmedCode, modelName), | |
| 163 | + }; | |
| 164 | +} | |
| 165 | + | |
| 166 | +// Uncomment for testing | |
| 167 | +export { | |
| 168 | + getRecencyAndSizeScore, | |
| 169 | + rankByScore, | |
| 170 | + setLogStats, | |
| 171 | + trimSnippetForContext, | |
| 172 | +}; |
modified core/autocomplete/templating/index.ts +1 −1
| @@ -4,13 +4,13 @@ | ||
| 4 | 4 | import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; |
| 5 | 5 | import { HelperVars } from "../util/HelperVars"; |
| 6 | 6 | |
| 7 | +import { getUriPathBasename } from "../../util/uri"; | |
| 7 | 8 | import { SnippetPayload } from "../snippets"; |
| 8 | 9 | import { |
| 9 | 10 | AutocompleteTemplate, |
| 10 | 11 | getTemplateForModel, |
| 11 | 12 | } from "./AutocompleteTemplate"; |
| 12 | 13 | import { getSnippets } from "./filtering"; |
| 13 | -import { getUriPathBasename } from "../../util/uri"; | |
| 14 | 14 | import { formatSnippets } from "./formatting"; |
| 15 | 15 | import { getStopTokens } from "./getStopTokens"; |
| 16 | 16 |
added core/autocomplete/util/openedFilesLruCache.ts +20 −0
| @@ -0,0 +1,20 @@ | ||
| 1 | +import QuickLRU from "quick-lru"; | |
| 2 | + | |
| 3 | +// The cache key and value are both a filepath string | |
| 4 | +export type cacheElementType = string; | |
| 5 | + | |
| 6 | +// maximum number of open files that can be cached | |
| 7 | +const MAX_NUM_OPEN_CONTEXT_FILES = 20; | |
| 8 | + | |
| 9 | +// stores which files are currently open in the IDE, in viewing order | |
| 10 | +export const openedFilesLruCache = new QuickLRU< | |
| 11 | + cacheElementType, | |
| 12 | + cacheElementType | |
| 13 | +>({ | |
| 14 | + maxSize: MAX_NUM_OPEN_CONTEXT_FILES, | |
| 15 | +}); | |
| 16 | + | |
| 17 | +// used in core/core.ts to handle removals from the cache | |
| 18 | +export const prevFilepaths = { | |
| 19 | + filepaths: [] as string[], | |
| 20 | +}; |
modified core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +2 −2
| @@ -2,10 +2,10 @@ | ||
| 2 | 2 | import nlp from "wink-nlp-utils"; |
| 3 | 3 | |
| 4 | 4 | import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../"; |
| 5 | +import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache"; | |
| 5 | 6 | import { chunkDocument } from "../../../indexing/chunk/chunk"; |
| 6 | 7 | import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; |
| 7 | 8 | import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; |
| 8 | -import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache"; | |
| 9 | 9 | |
| 10 | 10 | const DEFAULT_CHUNK_SIZE = 384; |
| 11 | 11 | |
| @@ -98,7 +98,7 @@ | ||
| 98 | 98 | n: number, |
| 99 | 99 | ): Promise<Chunk[]> { |
| 100 | 100 | const recentlyEditedFilesSlice = Array.from( |
| 101 | - recentlyEditedFilesCache.keys(), | |
| 101 | + openedFilesLruCache.keys(), | |
| 102 | 102 | ).slice(0, n); |
| 103 | 103 | |
| 104 | 104 | // If the number of recently edited files is less than the retrieval limit, |
deleted core/context/retrieval/recentlyEditedFilesCache.ts +0 −16
| @@ -1,16 +0,0 @@ | ||
| 1 | -import QuickLRU from "quick-lru"; | |
| 2 | - | |
| 3 | -import { ToWebviewOrCoreFromIdeProtocol } from "../../protocol/ide.js"; | |
| 4 | - | |
| 5 | -// The cache key and value are both a filepath string | |
| 6 | -export type RecentlyEditedFilesCacheKeyAndValue = | |
| 7 | - ToWebviewOrCoreFromIdeProtocol["didChangeActiveTextEditor"][0]["filepath"]; | |
| 8 | - | |
| 9 | -const MAX_NUM_RECENTLY_EDITED_FILES = 100; | |
| 10 | - | |
| 11 | -export const recentlyEditedFilesCache = new QuickLRU< | |
| 12 | - RecentlyEditedFilesCacheKeyAndValue, | |
| 13 | - RecentlyEditedFilesCacheKeyAndValue | |
| 14 | ->({ | |
| 15 | - maxSize: MAX_NUM_RECENTLY_EDITED_FILES, | |
| 16 | -}); |
modified core/core.ts +50 −15
| @@ -3,12 +3,15 @@ | ||
| 3 | 3 | import { v4 as uuidv4 } from "uuid"; |
| 4 | 4 | |
| 5 | 5 | import { CompletionProvider } from "./autocomplete/CompletionProvider"; |
| 6 | +import { | |
| 7 | + openedFilesLruCache, | |
| 8 | + prevFilepaths, | |
| 9 | +} from "./autocomplete/util/openedFilesLruCache"; | |
| 6 | 10 | import { ConfigHandler } from "./config/ConfigHandler"; |
| 7 | 11 | import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles"; |
| 8 | 12 | import { addModel, deleteModel } from "./config/util"; |
| 9 | 13 | import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; |
| 10 | 14 | import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; |
| 11 | -import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; | |
| 12 | 15 | import { ContinueServerClient } from "./continueServer/stubs/client"; |
| 13 | 16 | import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; |
| 14 | 17 | import { getControlPlaneEnv } from "./control-plane/env"; |
| @@ -619,6 +622,32 @@ | ||
| 619 | 622 | }); |
| 620 | 623 | |
| 621 | 624 | on("files/closed", async ({ data }) => { |
| 625 | + try { | |
| 626 | + const fileUris = await this.ide.getOpenFiles(); | |
| 627 | + if (fileUris) { | |
| 628 | + const filepaths = fileUris.map((uri) => uri.toString()); | |
| 629 | + | |
| 630 | + if (!prevFilepaths.filepaths.length) { | |
| 631 | + prevFilepaths.filepaths = filepaths; | |
| 632 | + } | |
| 633 | + | |
| 634 | + // If there is a removal, including if the number of tabs is the same (which can happen with temp tabs) | |
| 635 | + if (filepaths.length <= prevFilepaths.filepaths.length) { | |
| 636 | + // Remove files from cache that are no longer open (i.e. in the cache but not in the list of opened tabs) | |
| 637 | + for (const [key, _] of openedFilesLruCache.entriesDescending()) { | |
| 638 | + if (!filepaths.includes(key)) { | |
| 639 | + openedFilesLruCache.delete(key); | |
| 640 | + } | |
| 641 | + } | |
| 642 | + } | |
| 643 | + prevFilepaths.filepaths = filepaths; | |
| 644 | + } | |
| 645 | + } catch (e) { | |
| 646 | + console.error( | |
| 647 | + `didChangeVisibleTextEditors: failed to update openedFilesLruCache`, | |
| 648 | + ); | |
| 649 | + } | |
| 650 | + | |
| 622 | 651 | if (data.uris) { |
| 623 | 652 | this.messenger.send("didCloseFiles", { |
| 624 | 653 | uris: data.uris, |
| @@ -626,7 +655,26 @@ | ||
| 626 | 655 | } |
| 627 | 656 | }); |
| 628 | 657 | |
| 629 | - on("files/opened", async () => {}); | |
| 658 | + on("files/opened", async ({ data: { uris } }) => { | |
| 659 | + if (uris) { | |
| 660 | + for (const filepath of uris) { | |
| 661 | + try { | |
| 662 | + const ignore = await shouldIgnore(filepath, this.ide); | |
| 663 | + if (!ignore) { | |
| 664 | + // Set the active file as most recently used (need to force recency update by deleting and re-adding) | |
| 665 | + if (openedFilesLruCache.has(filepath)) { | |
| 666 | + openedFilesLruCache.delete(filepath); | |
| 667 | + } | |
| 668 | + openedFilesLruCache.set(filepath, filepath); | |
| 669 | + } | |
| 670 | + } catch (e) { | |
| 671 | + console.error( | |
| 672 | + `files/opened: failed to update openedFiles cache for ${filepath}`, | |
| 673 | + ); | |
| 674 | + } | |
| 675 | + } | |
| 676 | + } | |
| 677 | + }); | |
| 630 | 678 | |
| 631 | 679 | // Docs, etc. indexing |
| 632 | 680 | on("indexing/reindex", async (msg) => { |
| @@ -682,19 +730,6 @@ | ||
| 682 | 730 | return { url }; |
| 683 | 731 | }); |
| 684 | 732 | |
| 685 | - on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { | |
| 686 | - try { | |
| 687 | - const ignore = await shouldIgnore(filepath, this.ide); | |
| 688 | - if (!ignore) { | |
| 689 | - recentlyEditedFilesCache.set(filepath, filepath); | |
| 690 | - } | |
| 691 | - } catch (e) { | |
| 692 | - console.error( | |
| 693 | - `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, | |
| 694 | - ); | |
| 695 | - } | |
| 696 | - }); | |
| 697 | - | |
| 698 | 733 | on("tools/call", async ({ data: { toolCall } }) => { |
| 699 | 734 | const { config } = await this.configHandler.loadConfig(); |
| 700 | 735 | if (!config) { |
modified core/index.d.ts +1 −0
| @@ -1112,6 +1112,7 @@ | ||
| 1112 | 1112 | useCache: boolean; |
| 1113 | 1113 | onlyMyCode: boolean; |
| 1114 | 1114 | useRecentlyEdited: boolean; |
| 1115 | + useRecentlyOpened: boolean; | |
| 1115 | 1116 | disableInFiles?: string[]; |
| 1116 | 1117 | useImports?: boolean; |
| 1117 | 1118 | showWhateverWeHaveAtXMs?: number; |
modified core/protocol/messenger/messageIde.ts +5 −0
| @@ -40,9 +40,11 @@ | ||
| 40 | 40 | fileExists(fileUri: string): Promise<boolean> { |
| 41 | 41 | return this.request("fileExists", { filepath: fileUri }); |
| 42 | 42 | } |
| 43 | + | |
| 43 | 44 | async gotoDefinition(location: Location): Promise<RangeInFile[]> { |
| 44 | 45 | return this.request("gotoDefinition", { location }); |
| 45 | 46 | } |
| 47 | + | |
| 46 | 48 | onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { |
| 47 | 49 | this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); |
| 48 | 50 | } |
| @@ -50,12 +52,14 @@ | ||
| 50 | 52 | getIdeSettings(): Promise<IdeSettings> { |
| 51 | 53 | return this.request("getIdeSettings", undefined); |
| 52 | 54 | } |
| 55 | + | |
| 53 | 56 | getFileStats(files: string[]): Promise<FileStatsMap> { |
| 54 | 57 | return this.request("getFileStats", { files }); |
| 55 | 58 | } |
| 56 | 59 | getGitRootPath(dir: string): Promise<string | undefined> { |
| 57 | 60 | return this.request("getGitRootPath", { dir }); |
| 58 | 61 | } |
| 62 | + | |
| 59 | 63 | listDir(dir: string): Promise<[string, FileType][]> { |
| 60 | 64 | return this.request("listDir", { dir }); |
| 61 | 65 | } |
| @@ -164,6 +168,7 @@ | ||
| 164 | 168 | async saveFile(fileUri: string): Promise<void> { |
| 165 | 169 | await this.request("saveFile", { filepath: fileUri }); |
| 166 | 170 | } |
| 171 | + | |
| 167 | 172 | async readFile(fileUri: string): Promise<string> { |
| 168 | 173 | return await this.request("readFile", { filepath: fileUri }); |
| 169 | 174 | } |
modified core/util/filesystem.ts +5 −0
| @@ -34,6 +34,7 @@ | ||
| 34 | 34 | ): Promise<void> { |
| 35 | 35 | return Promise.resolve(); |
| 36 | 36 | } |
| 37 | + | |
| 37 | 38 | fileExists(fileUri: string): Promise<boolean> { |
| 38 | 39 | const filepath = fileURLToPath(fileUri); |
| 39 | 40 | return Promise.resolve(fs.existsSync(filepath)); |
| @@ -42,6 +43,7 @@ | ||
| 42 | 43 | gotoDefinition(location: Location): Promise<RangeInFile[]> { |
| 43 | 44 | return Promise.resolve([]); |
| 44 | 45 | } |
| 46 | + | |
| 45 | 47 | onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { |
| 46 | 48 | return; |
| 47 | 49 | } |
| @@ -55,6 +57,7 @@ | ||
| 55 | 57 | pauseCodebaseIndexOnStart: false, |
| 56 | 58 | }; |
| 57 | 59 | } |
| 60 | + | |
| 58 | 61 | async getFileStats(fileUris: string[]): Promise<FileStatsMap> { |
| 59 | 62 | const result: FileStatsMap = {}; |
| 60 | 63 | for (const uri of fileUris) { |
| @@ -71,9 +74,11 @@ | ||
| 71 | 74 | } |
| 72 | 75 | return result; |
| 73 | 76 | } |
| 77 | + | |
| 74 | 78 | getGitRootPath(dir: string): Promise<string | undefined> { |
| 75 | 79 | return Promise.resolve(dir); |
| 76 | 80 | } |
| 81 | + | |
| 77 | 82 | async listDir(dir: string): Promise<[string, FileType][]> { |
| 78 | 83 | const filepath = fileURLToPath(dir); |
| 79 | 84 | const all: [string, FileType][] = fs |
modified core/util/parameters.ts +1 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | useCache: true, |
| 16 | 16 | onlyMyCode: true, |
| 17 | 17 | useRecentlyEdited: true, |
| 18 | + useRecentlyOpened: true, | |
| 18 | 19 | disableInFiles: undefined, |
| 19 | 20 | useImports: true, |
| 20 | 21 | transform: true, |
modified extensions/vscode/src/VsCodeIde.ts +0 −2
| @@ -3,8 +3,6 @@ | ||
| 3 | 3 | |
| 4 | 4 | import { Range } from "core"; |
| 5 | 5 | import { EXTENSION_NAME } from "core/control-plane/env"; |
| 6 | -import { GetGhTokenArgs } from "core/protocol/ide"; | |
| 7 | -import { editConfigFile, getConfigJsonPath } from "core/util/paths"; | |
| 8 | 6 | import * as URI from "uri-js"; |
| 9 | 7 | import * as vscode from "vscode"; |
| 10 | 8 |
modified extensions/vscode/src/extension/VsCodeExtension.ts +10 −1
| @@ -41,6 +41,7 @@ | ||
| 41 | 41 | import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; |
| 42 | 42 | import { VsCodeMessenger } from "./VsCodeMessenger"; |
| 43 | 43 | |
| 44 | +import { VsCodeIdeUtils } from "../util/ideUtils"; | |
| 44 | 45 | import type { VsCodeWebviewProtocol } from "../webviewProtocol"; |
| 45 | 46 | |
| 46 | 47 | export class VsCodeExtension { |
| @@ -49,6 +50,7 @@ | ||
| 49 | 50 | private configHandler: ConfigHandler; |
| 50 | 51 | private extensionContext: vscode.ExtensionContext; |
| 51 | 52 | private ide: VsCodeIde; |
| 53 | + private ideUtils: VsCodeIdeUtils; | |
| 52 | 54 | private consoleView: ContinueConsoleWebviewViewProvider; |
| 53 | 55 | private sidebar: ContinueGUIWebviewViewProvider; |
| 54 | 56 | private windowId: string; |
| @@ -76,6 +78,7 @@ | ||
| 76 | 78 | }, |
| 77 | 79 | ); |
| 78 | 80 | this.ide = new VsCodeIde(this.webviewProtocolPromise, context); |
| 81 | + this.ideUtils = new VsCodeIdeUtils(); | |
| 79 | 82 | this.extensionContext = context; |
| 80 | 83 | this.windowId = uuidv4(); |
| 81 | 84 | |
| @@ -382,9 +385,15 @@ | ||
| 382 | 385 | context.subscriptions.push(linkProvider); |
| 383 | 386 | |
| 384 | 387 | this.ide.onDidChangeActiveTextEditor((filepath) => { |
| 385 | - void this.core.invoke("didChangeActiveTextEditor", { filepath }); | |
| 388 | + void this.core.invoke("files/opened", { uris: [filepath] }); | |
| 386 | 389 | }); |
| 387 | 390 | |
| 391 | + // initializes openedFileLruCache with files that are already open when the extension is activated | |
| 392 | + let initialOpenedFilePaths = this.ideUtils | |
| 393 | + .getOpenFiles() | |
| 394 | + .map((uri) => uri.toString()); | |
| 395 | + this.core.invoke("files/opened", { uris: initialOpenedFilePaths }); | |
| 396 | + | |
| 388 | 397 | vscode.workspace.onDidChangeConfiguration(async (event) => { |
| 389 | 398 | if (event.affectsConfiguration(EXTENSION_NAME)) { |
| 390 | 399 | const settings = await this.ide.getIdeSettings(); |
modified extensions/vscode/src/util/ideUtils.ts +7 −8
| @@ -269,14 +269,13 @@ | ||
| 269 | 269 | |
| 270 | 270 | getOpenFiles(): vscode.Uri[] { |
| 271 | 271 | return vscode.window.tabGroups.all |
| 272 | - .map((group) => { | |
| 273 | - return group.tabs.map((tab) => { | |
| 274 | - return (tab.input as any)?.uri; | |
| 275 | - }); | |
| 276 | - }) | |
| 277 | - .flat() | |
| 278 | - .filter(Boolean) // filter out undefined values | |
| 279 | - .filter((uri) => this.documentIsCode(uri)); // Filter out undesired documents | |
| 272 | + .flatMap((group) => group.tabs) | |
| 273 | + .filter( | |
| 274 | + (tab) => | |
| 275 | + tab.input instanceof vscode.TabInputText && | |
| 276 | + this.documentIsCode((tab.input as vscode.TabInputText).uri), | |
| 277 | + ) | |
| 278 | + .map((tab) => (tab.input as vscode.TabInputText).uri); | |
| 280 | 279 | } |
| 281 | 280 | |
| 282 | 281 | saveFile(uri: vscode.Uri) { |
added manual-testing-sandbox/calculator_test/Calculator.java +21 −0
| @@ -0,0 +1,21 @@ | ||
| 1 | +public class Calculator { | |
| 2 | + public int myAddition(int a, int b, int c) { | |
| 3 | + return a + b + c; | |
| 4 | + } | |
| 5 | + | |
| 6 | + public int subtract(int a, int b) { | |
| 7 | + return a - b; | |
| 8 | + } | |
| 9 | + | |
| 10 | + public int multiply(int a, int b) { | |
| 11 | + return a * b; | |
| 12 | + } | |
| 13 | + | |
| 14 | + public double divide(int a, int b) { | |
| 15 | + if (b != 0) { | |
| 16 | + return (double) a / b; | |
| 17 | + } else { | |
| 18 | + throw new IllegalArgumentException("Division by zero is not allowed."); | |
| 19 | + } | |
| 20 | + } | |
| 21 | +} |
added manual-testing-sandbox/calculator_test/Main.java +7 −0
| @@ -0,0 +1,7 @@ | ||
| 1 | +public class Main { | |
| 2 | + public static void main(String[] args) { | |
| 3 | + Calculator calculator = new Calculator(); | |
| 4 | + calculator.myAddition(1, 2, 3); | |
| 5 | + | |
| 6 | + } | |
| 7 | +} |
modified manual-testing-sandbox/test.py +1 −1
| @@ -15,4 +15,4 @@ | ||
| 15 | 15 | return self |
| 16 | 16 | |
| 17 | 17 | def get_result(self): |
| 18 | - return self.result | |
| 18 | + return self.result | |
| No newline at the end of the file |