Elffuss BraidHub

kikocis/continue public

Merge pull request #6012 from continuedev/feature/view-context/base-copy

[Updated PR] [Feature] Autocomplete context from other tabs open in the editor
Changesetfe4ed82781c78b7b2757d49031d4c452d731f08ede2c03e4d8a39b1a1f5df297
AuthorAdarsh Iyer <76015889+adarshramiyer@users.noreply.github.com> · 2025-06-11 16:25 -07:00
CommitterGitHub <noreply@github.com> · 2025-06-11 16:25 -07:00
Parents567b310f6477, 1cfd9a0cd983

Browse the files at this changeset

19 files changed

modified core/autocomplete/snippets/getAllSnippets.ts +64 −0
@@ -3,6 +3,7 @@
33 import { ContextRetrievalService } from "../context/ContextRetrievalService";
44 import { GetLspDefinitionsFunction } from "../types";
55 import { HelperVars } from "../util/HelperVars";
6+import { openedFilesLruCache } from "../util/openedFilesLruCache";
67 import { getDiffsFromCache } from "./gitDiffCache";
78
89 import {
@@ -22,6 +23,7 @@
2223 recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[];
2324 diffSnippets: AutocompleteDiffSnippet[];
2425 clipboardSnippets: AutocompleteClipboardSnippet[];
26+ recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
2527 }
2628
2729 function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
@@ -103,6 +105,65 @@
103105 });
104106 };
105107
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+
106167 export const getAllSnippets = async ({
107168 helper,
108169 ide,
@@ -123,6 +184,7 @@
123184 ideSnippets,
124185 diffSnippets,
125186 clipboardSnippets,
187+ recentlyOpenedFileSnippets,
126188 ] = await Promise.all([
127189 racePromise(contextRetrievalService.getRootPathSnippets(helper)),
128190 racePromise(
@@ -133,6 +195,7 @@
133195 : [],
134196 [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
135197 racePromise(getClipboardSnippets(ide)),
198+ racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
136199 ]);
137200
138201 return {
@@ -143,5 +206,6 @@
143206 diffSnippets,
144207 clipboardSnippets,
145208 recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
209+ recentlyOpenedFileSnippets,
146210 };
147211 };
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 @@
55 AutocompleteSnippet,
66 } from "../snippets/types";
77 import { HelperVars } from "../util/HelperVars";
8+import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
89
910 import { isValidSnippet } from "./validation";
1011
@@ -47,6 +48,7 @@
4748 recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets,
4849 recentlyEditedRanges: payload.recentlyEditedRangeSnippets,
4950 diff: payload.diffSnippets,
51+ recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
5052 base: shuffleArray(
5153 filterSnippetsAlreadyInCaretWindow(
5254 [...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
@@ -68,11 +70,17 @@
6870 defaultPriority: 1,
6971 snippets: payload.clipboardSnippets,
7072 },
73+ {
74+ key: "recentlyOpenedFiles",
75+ enabledOrPriority: helper.options.useRecentlyOpened,
76+ defaultPriority: 2,
77+ snippets: payload.recentlyOpenedFileSnippets,
78+ },
7179 {
7280 key: "recentlyVisitedRanges",
7381 enabledOrPriority:
7482 helper.options.experimental_includeRecentlyVisitedRanges,
75- defaultPriority: 2,
83+ defaultPriority: 3,
7684 snippets: payload.recentlyVisitedRangesSnippets,
7785 /* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
7886 if they are visible. We should handle them separately so that we can control their priority
@@ -82,13 +90,13 @@
8290 key: "recentlyEditedRanges",
8391 enabledOrPriority:
8492 helper.options.experimental_includeRecentlyEditedRanges,
85- defaultPriority: 3,
93+ defaultPriority: 4,
8694 snippets: payload.recentlyEditedRangeSnippets,
8795 },
8896 {
8997 key: "diff",
9098 enabledOrPriority: helper.options.experimental_includeDiff,
91- defaultPriority: 4,
99+ defaultPriority: 5,
92100 snippets: payload.diffSnippets,
93101 // TODO: diff is commonly too large, thus anything lower in priority is not included.
94102 },
@@ -119,46 +127,70 @@
119127 }))
120128 .sort((a, b) => a.priority - b.priority);
121129
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-
146130 const finalSnippets = [];
147131 let remainingTokenCount = getRemainingTokenCount(helper);
148132
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+ }
153190 }
154191
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;
162194 }
163195
164196 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 @@
44 import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
55 import { HelperVars } from "../util/HelperVars";
66
7+import { getUriPathBasename } from "../../util/uri";
78 import { SnippetPayload } from "../snippets";
89 import {
910 AutocompleteTemplate,
1011 getTemplateForModel,
1112 } from "./AutocompleteTemplate";
1213 import { getSnippets } from "./filtering";
13-import { getUriPathBasename } from "../../util/uri";
1414 import { formatSnippets } from "./formatting";
1515 import { getStopTokens } from "./getStopTokens";
1616
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 @@
22 import nlp from "wink-nlp-utils";
33
44 import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
5+import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
56 import { chunkDocument } from "../../../indexing/chunk/chunk";
67 import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
78 import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
8-import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
99
1010 const DEFAULT_CHUNK_SIZE = 384;
1111
@@ -98,7 +98,7 @@
9898 n: number,
9999 ): Promise<Chunk[]> {
100100 const recentlyEditedFilesSlice = Array.from(
101- recentlyEditedFilesCache.keys(),
101+ openedFilesLruCache.keys(),
102102 ).slice(0, n);
103103
104104 // 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 @@
33 import { v4 as uuidv4 } from "uuid";
44
55 import { CompletionProvider } from "./autocomplete/CompletionProvider";
6+import {
7+ openedFilesLruCache,
8+ prevFilepaths,
9+} from "./autocomplete/util/openedFilesLruCache";
610 import { ConfigHandler } from "./config/ConfigHandler";
711 import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
812 import { addModel, deleteModel } from "./config/util";
913 import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
1014 import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
11-import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
1215 import { ContinueServerClient } from "./continueServer/stubs/client";
1316 import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
1417 import { getControlPlaneEnv } from "./control-plane/env";
@@ -619,6 +622,32 @@
619622 });
620623
621624 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+
622651 if (data.uris) {
623652 this.messenger.send("didCloseFiles", {
624653 uris: data.uris,
@@ -626,7 +655,26 @@
626655 }
627656 });
628657
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+ });
630678
631679 // Docs, etc. indexing
632680 on("indexing/reindex", async (msg) => {
@@ -682,19 +730,6 @@
682730 return { url };
683731 });
684732
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-
698733 on("tools/call", async ({ data: { toolCall } }) => {
699734 const { config } = await this.configHandler.loadConfig();
700735 if (!config) {
modified core/index.d.ts +1 −0
@@ -1112,6 +1112,7 @@
11121112 useCache: boolean;
11131113 onlyMyCode: boolean;
11141114 useRecentlyEdited: boolean;
1115+ useRecentlyOpened: boolean;
11151116 disableInFiles?: string[];
11161117 useImports?: boolean;
11171118 showWhateverWeHaveAtXMs?: number;
modified core/protocol/messenger/messageIde.ts +5 −0
@@ -40,9 +40,11 @@
4040 fileExists(fileUri: string): Promise<boolean> {
4141 return this.request("fileExists", { filepath: fileUri });
4242 }
43+
4344 async gotoDefinition(location: Location): Promise<RangeInFile[]> {
4445 return this.request("gotoDefinition", { location });
4546 }
47+
4648 onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
4749 this.on("didChangeActiveTextEditor", (data) => callback(data.filepath));
4850 }
@@ -50,12 +52,14 @@
5052 getIdeSettings(): Promise<IdeSettings> {
5153 return this.request("getIdeSettings", undefined);
5254 }
55+
5356 getFileStats(files: string[]): Promise<FileStatsMap> {
5457 return this.request("getFileStats", { files });
5558 }
5659 getGitRootPath(dir: string): Promise<string | undefined> {
5760 return this.request("getGitRootPath", { dir });
5861 }
62+
5963 listDir(dir: string): Promise<[string, FileType][]> {
6064 return this.request("listDir", { dir });
6165 }
@@ -164,6 +168,7 @@
164168 async saveFile(fileUri: string): Promise<void> {
165169 await this.request("saveFile", { filepath: fileUri });
166170 }
171+
167172 async readFile(fileUri: string): Promise<string> {
168173 return await this.request("readFile", { filepath: fileUri });
169174 }
modified core/util/filesystem.ts +5 −0
@@ -34,6 +34,7 @@
3434 ): Promise<void> {
3535 return Promise.resolve();
3636 }
37+
3738 fileExists(fileUri: string): Promise<boolean> {
3839 const filepath = fileURLToPath(fileUri);
3940 return Promise.resolve(fs.existsSync(filepath));
@@ -42,6 +43,7 @@
4243 gotoDefinition(location: Location): Promise<RangeInFile[]> {
4344 return Promise.resolve([]);
4445 }
46+
4547 onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
4648 return;
4749 }
@@ -55,6 +57,7 @@
5557 pauseCodebaseIndexOnStart: false,
5658 };
5759 }
60+
5861 async getFileStats(fileUris: string[]): Promise<FileStatsMap> {
5962 const result: FileStatsMap = {};
6063 for (const uri of fileUris) {
@@ -71,9 +74,11 @@
7174 }
7275 return result;
7376 }
77+
7478 getGitRootPath(dir: string): Promise<string | undefined> {
7579 return Promise.resolve(dir);
7680 }
81+
7782 async listDir(dir: string): Promise<[string, FileType][]> {
7883 const filepath = fileURLToPath(dir);
7984 const all: [string, FileType][] = fs
modified core/util/parameters.ts +1 −0
@@ -15,6 +15,7 @@
1515 useCache: true,
1616 onlyMyCode: true,
1717 useRecentlyEdited: true,
18+ useRecentlyOpened: true,
1819 disableInFiles: undefined,
1920 useImports: true,
2021 transform: true,
modified extensions/vscode/src/VsCodeIde.ts +0 −2
@@ -3,8 +3,6 @@
33
44 import { Range } from "core";
55 import { EXTENSION_NAME } from "core/control-plane/env";
6-import { GetGhTokenArgs } from "core/protocol/ide";
7-import { editConfigFile, getConfigJsonPath } from "core/util/paths";
86 import * as URI from "uri-js";
97 import * as vscode from "vscode";
108
modified extensions/vscode/src/extension/VsCodeExtension.ts +10 −1
@@ -41,6 +41,7 @@
4141 import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider";
4242 import { VsCodeMessenger } from "./VsCodeMessenger";
4343
44+import { VsCodeIdeUtils } from "../util/ideUtils";
4445 import type { VsCodeWebviewProtocol } from "../webviewProtocol";
4546
4647 export class VsCodeExtension {
@@ -49,6 +50,7 @@
4950 private configHandler: ConfigHandler;
5051 private extensionContext: vscode.ExtensionContext;
5152 private ide: VsCodeIde;
53+ private ideUtils: VsCodeIdeUtils;
5254 private consoleView: ContinueConsoleWebviewViewProvider;
5355 private sidebar: ContinueGUIWebviewViewProvider;
5456 private windowId: string;
@@ -76,6 +78,7 @@
7678 },
7779 );
7880 this.ide = new VsCodeIde(this.webviewProtocolPromise, context);
81+ this.ideUtils = new VsCodeIdeUtils();
7982 this.extensionContext = context;
8083 this.windowId = uuidv4();
8184
@@ -382,9 +385,15 @@
382385 context.subscriptions.push(linkProvider);
383386
384387 this.ide.onDidChangeActiveTextEditor((filepath) => {
385- void this.core.invoke("didChangeActiveTextEditor", { filepath });
388+ void this.core.invoke("files/opened", { uris: [filepath] });
386389 });
387390
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+
388397 vscode.workspace.onDidChangeConfiguration(async (event) => {
389398 if (event.affectsConfiguration(EXTENSION_NAME)) {
390399 const settings = await this.ide.getIdeSettings();
modified extensions/vscode/src/util/ideUtils.ts +7 −8
@@ -269,14 +269,13 @@
269269
270270 getOpenFiles(): vscode.Uri[] {
271271 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);
280279 }
281280
282281 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 @@
1515 return self
1616
1717 def get_result(self):
18- return self.result
18+ return self.result
No newline at the end of the file