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

[Updated PR] [Feature] Autocomplete context from other tabs open in the editor
This commit is contained in:
Adarsh Iyer 2025-06-11 16:25:04 -07:00 • committed by GitHub
commit 3f595eceb4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 871 additions and 84 deletions

View file

@ -3,6 +3,7 @@ import { findUriInDirs } from "../../util/uri";
import { ContextRetrievalService } from "../context/ContextRetrievalService";
import { GetLspDefinitionsFunction } from "../types";
import { HelperVars } from "../util/HelperVars";
import { openedFilesLruCache } from "../util/openedFilesLruCache";
import { getDiffsFromCache } from "./gitDiffCache";
import {
@ -22,6 +23,7 @@ export interface SnippetPayload {
recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[];
diffSnippets: AutocompleteDiffSnippet[];
clipboardSnippets: AutocompleteClipboardSnippet[];
recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
}
function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
@ -103,6 +105,65 @@ const getDiffSnippets = async (
});
};
const getSnippetsFromRecentlyOpenedFiles = async (
helper: HelperVars,
ide: IDE,
): Promise<AutocompleteCodeSnippet[]> => {
if (helper.options.useRecentlyOpened === false) {
return [];
}
try {
const currentFileUri = `${helper.filepath}`;
// Get all file URIs excluding the current file
const fileUrisToRead = [...openedFilesLruCache.entriesDescending()]
.filter(([fileUri, _]) => fileUri !== currentFileUri)
.map(([fileUri, _]) => fileUri);
// Create an array of promises that each read a file with timeout
const fileReadPromises = fileUrisToRead.map((fileUri) => {
// Create a promise that resolves to a snippet or null
const readPromise = new Promise<AutocompleteCodeSnippet | null>(
(resolve) => {
ide
.readFile(fileUri)
.then((fileContent) => {
if (!fileContent || fileContent.trim() === "") {
resolve(null);
return;
}
resolve({
filepath: fileUri,
content: fileContent,
type: AutocompleteSnippetType.Code,
});
})
.catch((e) => {
console.error(`Failed to read file ${fileUri}:`, e);
resolve(null);
});
},
);
// Cut off at 80ms via racing promises
return Promise.race([
readPromise,
new Promise<null>((resolve) => setTimeout(() => resolve(null), 80)),
]);
});
// Execute all file reads in parallel
const results = await Promise.all(fileReadPromises);
// Filter out null results
return results.filter(Boolean) as AutocompleteCodeSnippet[];
} catch (e) {
console.error("Error processing opened files cache:", e);
return [];
}
};
export const getAllSnippets = async ({
helper,
ide,
@ -123,6 +184,7 @@ export const getAllSnippets = async ({
ideSnippets,
diffSnippets,
clipboardSnippets,
recentlyOpenedFileSnippets,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
racePromise(
@ -133,6 +195,7 @@ export const getAllSnippets = async ({
: [],
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
racePromise(getClipboardSnippets(ide)),
racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
]);
return {
@ -143,5 +206,6 @@ export const getAllSnippets = async ({
diffSnippets,
clipboardSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
recentlyOpenedFileSnippets,
};
};

View file

@ -0,0 +1,434 @@
/**
* Comprehensive tests for formatOpenedFilesContext.ts
*
*/
import {
AutocompleteCodeSnippet,
AutocompleteDiffSnippet,
AutocompleteSnippetType,
} from "../../snippets/types";
import { HelperVars } from "../../util/HelperVars";
import { formatOpenedFilesContext } from "../formatOpenedFilesContext";
// Import the now-exported internal functions
import {
getRecencyAndSizeScore,
rankByScore,
setLogStats,
trimSnippetForContext,
} from "../formatOpenedFilesContext";
describe("formatOpenedFilesContext main function tests", () => {
const mockHelper = {
modelName: "test-model",
} as HelperVars;
const TOKEN_BUFFER = 50;
// Create sample code snippets with various sizes
const createCodeSnippet = (
filepath: string,
content: string,
): AutocompleteCodeSnippet => ({
type: AutocompleteSnippetType.Code,
filepath,
content,
});
const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({
type: AutocompleteSnippetType.Diff,
content,
});
test("should return empty array when no snippets are provided", () => {
const result = formatOpenedFilesContext(
[],
1000,
mockHelper,
[],
TOKEN_BUFFER,
);
expect(result).toEqual([]);
});
test("should handle zero remaining token count", () => {
const snippets = [
createCodeSnippet("file1.ts", "content of file 1"),
createCodeSnippet("file2.ts", "content of file 2"),
];
const result = formatOpenedFilesContext(
snippets,
0,
mockHelper,
[],
TOKEN_BUFFER,
);
expect(result).toEqual([]);
});
test("should handle snippets with empty content", () => {
const emptySnippets = [
createCodeSnippet("empty1.ts", ""),
createCodeSnippet("empty2.ts", ""),
];
const result = formatOpenedFilesContext(
emptySnippets,
1000,
mockHelper,
[],
TOKEN_BUFFER,
);
expect(result.length).toBe(emptySnippets.length);
});
test("should return all snippets when they all fit within token limit", () => {
const smallSnippets = [
createCodeSnippet("small1.ts", "a"),
createCodeSnippet("small2.ts", "b"),
createCodeSnippet("small3.ts", "c"),
];
const result = formatOpenedFilesContext(
smallSnippets,
1000,
mockHelper,
[],
TOKEN_BUFFER,
);
expect(result.length).toBe(smallSnippets.length);
});
test("should handle limited token count", () => {
const snippets = Array(10)
.fill(0)
.map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
const result = formatOpenedFilesContext(
snippets,
1, // Extremely small token count
mockHelper,
[],
TOKEN_BUFFER,
);
expect(Array.isArray(result)).toBe(true);
});
test("should accept valid inputs with adequate token count", () => {
const snippets = [
createCodeSnippet("file1.ts", "Some content here"),
createCodeSnippet("file2.ts", "More content here"),
];
const result = formatOpenedFilesContext(
snippets,
1000,
mockHelper,
[],
TOKEN_BUFFER,
);
expect(result.length).toBeGreaterThan(0);
});
test("should handle already added snippets parameter", () => {
const snippets = [
createCodeSnippet("file1.ts", "content of file 1"),
createCodeSnippet("file2.ts", "content of file 2"),
];
const alreadyAddedSnippets = [createDiffSnippet("diff content")];
const result = formatOpenedFilesContext(
snippets,
1000,
mockHelper,
alreadyAddedSnippets,
TOKEN_BUFFER,
);
expect(result.length).toBe(snippets.length);
});
test("should handle large snippets by trimming them", () => {
const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000));
const result = formatOpenedFilesContext(
[largeSnippet],
200,
mockHelper,
[],
TOKEN_BUFFER,
);
expect(result.length).toBe(1);
expect(result[0].filepath).toBe(largeSnippet.filepath);
expect(result[0].content.length).toBeLessThan(largeSnippet.content.length);
});
test("should prioritize more recent snippets when not all fit", () => {
const snippets = [
createCodeSnippet("recent1.ts", "a".repeat(10)),
createCodeSnippet("recent2.ts", "b".repeat(10000)),
createCodeSnippet("recent3.ts", "c".repeat(10000)),
];
const result = formatOpenedFilesContext(
snippets,
200,
mockHelper,
[],
TOKEN_BUFFER,
);
expect(result.length).toBeGreaterThan(0);
expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true);
});
test("should handle a mix of large and small snippets effectively", () => {
const mixedSnippets = [
createCodeSnippet("small1.ts", "a".repeat(10)),
createCodeSnippet("large1.ts", "b".repeat(5000)),
createCodeSnippet("small2.ts", "c".repeat(10)),
createCodeSnippet("large2.ts", "d".repeat(5000)),
];
const result = formatOpenedFilesContext(
mixedSnippets,
500,
mockHelper,
[],
TOKEN_BUFFER,
);
expect(result.length).toBeGreaterThan(0);
expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true);
});
test("should respect minimum token threshold when trimming", () => {
const largeSnippets = [
createCodeSnippet("large1.ts", "a".repeat(5000)),
createCodeSnippet("large2.ts", "b".repeat(5000)),
];
const result = formatOpenedFilesContext(
largeSnippets,
150,
mockHelper,
[],
TOKEN_BUFFER,
);
expect(result.length).toBeLessThanOrEqual(1);
if (result.length > 0) {
expect(result[0].content.length).toBeLessThan(
largeSnippets[0].content.length,
);
}
});
});
// Tests for rankByScore function
describe("rankByScore function", () => {
const createCodeSnippet = (
filepath: string,
content: string,
): AutocompleteCodeSnippet => ({
type: AutocompleteSnippetType.Code,
filepath,
content,
});
test("should return empty array when given empty array", () => {
const result = rankByScore([]);
expect(result).toEqual([]);
});
test("should rank snippets by score", () => {
// Initialize logMin and logMax by calling setLogStats first
const snippets = [
createCodeSnippet("file1.ts", "a".repeat(10)),
createCodeSnippet("file2.ts", "b".repeat(1000)),
createCodeSnippet("file3.ts", "c".repeat(100)),
];
setLogStats(snippets);
const result = rankByScore(snippets);
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBeGreaterThan(0);
// The snippets should be ranked in some order, which may not match input order
expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual(
snippets.map((s) => s.filepath),
);
});
test("should limit the number of ranked snippets to defaultNumFilesUsed", () => {
// Create more snippets than the default limit
const manySnippets = Array(10)
.fill(0)
.map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
setLogStats(manySnippets);
const result = rankByScore(manySnippets);
// The function should limit the number of snippets (defaultNumFilesUsed is 5)
expect(result.length).toBeLessThanOrEqual(5);
});
});
// Tests for getRecencyAndSizeScore function
describe("getRecencyAndSizeScore function", () => {
const createCodeSnippet = (
filepath: string,
content: string,
): AutocompleteCodeSnippet => ({
type: AutocompleteSnippetType.Code,
filepath,
content,
});
test("recency score should decrease with higher index", () => {
// Initialize log stats first
const snippets = [
createCodeSnippet("file1.ts", "a".repeat(100)),
createCodeSnippet("file2.ts", "b".repeat(100)),
];
setLogStats(snippets);
// Test that score decreases with increasing index
const score0 = getRecencyAndSizeScore(0, snippets[0]);
const score1 = getRecencyAndSizeScore(1, snippets[0]);
const score2 = getRecencyAndSizeScore(2, snippets[0]);
expect(score0).toBeGreaterThan(score1);
expect(score1).toBeGreaterThan(score2);
});
test("size score should be higher for smaller snippets", () => {
// Initialize log stats first
const snippets = [
createCodeSnippet("small.ts", "a".repeat(50)),
createCodeSnippet("medium.ts", "b".repeat(200)),
createCodeSnippet("large.ts", "c".repeat(1000)),
];
setLogStats(snippets);
// Test with same recency index but different sizes
const smallScore = getRecencyAndSizeScore(0, snippets[0]);
const mediumScore = getRecencyAndSizeScore(0, snippets[1]);
const largeScore = getRecencyAndSizeScore(0, snippets[2]);
// Scores should reflect preference for smaller snippets
expect(smallScore).toBeGreaterThanOrEqual(mediumScore);
expect(mediumScore).toBeGreaterThanOrEqual(largeScore);
});
test("recency and size both affect the score with recency having more weight", () => {
// Initialize log stats first
const snippets = [
createCodeSnippet("recent_large.ts", "a".repeat(1000)),
createCodeSnippet("old_small.ts", "b".repeat(50)),
];
setLogStats(snippets);
// Test that recency and size both contribute to the score
const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]);
const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]);
// We're not making a direct comparison, just verifying the scoring mechanism works
expect(recentLargeScore).toBeGreaterThan(0);
expect(oldSmallScore).toBeGreaterThan(0);
expect(oldSmallScore).toBeLessThan(1);
});
});
// Tests for setLogStats function
describe("setLogStats function", () => {
const createCodeSnippet = (
filepath: string,
content: string,
): AutocompleteCodeSnippet => ({
type: AutocompleteSnippetType.Code,
filepath,
content,
});
test("should set logMin and logMax based on snippet sizes", () => {
const snippets = [
createCodeSnippet("small.ts", "a".repeat(50)),
createCodeSnippet("medium.ts", "b".repeat(200)),
createCodeSnippet("large.ts", "c".repeat(1000)),
];
// We can't directly test logMin and logMax as they're private
// but we can verify that the function runs without errors
expect(() => setLogStats(snippets)).not.toThrow();
});
test("should handle empty snippets", () => {
const emptySnippets = [
createCodeSnippet("empty1.ts", ""),
createCodeSnippet("empty2.ts", ""),
];
expect(() => setLogStats(emptySnippets)).not.toThrow();
});
test("should handle single snippet", () => {
const singleSnippet = [createCodeSnippet("single.ts", "content")];
expect(() => setLogStats(singleSnippet)).not.toThrow();
});
});
// Tests for trimSnippetForContext function
describe("trimSnippetForContext function", () => {
const createCodeSnippet = (
filepath: string,
content: string,
): AutocompleteCodeSnippet => ({
type: AutocompleteSnippetType.Code,
filepath,
content,
});
test("should return original snippet if it fits within token limit", () => {
const snippet = createCodeSnippet("small.ts", "small content");
const modelName = "test-model";
const maxTokens = 1000; // Large enough to fit the snippet
const result = trimSnippetForContext(snippet, maxTokens, modelName);
// Should return the original snippet with its token count
expect(result.newSnippet).toEqual(snippet);
expect(typeof result.newTokens).toBe("number");
expect(result.newTokens).toBeGreaterThan(0);
});
test("should trim snippet content if it exceeds token limit", () => {
const snippet = createCodeSnippet("large.ts", "a".repeat(1000));
const modelName = "test-model";
const maxTokens = 10; // Small enough to require trimming
const result = trimSnippetForContext(snippet, maxTokens, modelName);
// Should return a trimmed snippet
expect(result.newSnippet.filepath).toBe(snippet.filepath);
expect(result.newSnippet.type).toBe(snippet.type);
expect(result.newSnippet.content.length).toBeLessThanOrEqual(
snippet.content.length,
);
// Token count should be less than or equal to maxTokens
expect(result.newTokens).toBeLessThanOrEqual(maxTokens);
});
});

View file

@ -5,6 +5,7 @@ import {
AutocompleteSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
import { isValidSnippet } from "./validation";
@ -47,6 +48,7 @@ export const getSnippets = (
recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets,
recentlyEditedRanges: payload.recentlyEditedRangeSnippets,
diff: payload.diffSnippets,
recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
base: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
@ -68,11 +70,17 @@ export const getSnippets = (
defaultPriority: 1,
snippets: payload.clipboardSnippets,
},
{
key: "recentlyOpenedFiles",
enabledOrPriority: helper.options.useRecentlyOpened,
defaultPriority: 2,
snippets: payload.recentlyOpenedFileSnippets,
},
{
key: "recentlyVisitedRanges",
enabledOrPriority:
helper.options.experimental_includeRecentlyVisitedRanges,
defaultPriority: 2,
defaultPriority: 3,
snippets: payload.recentlyVisitedRangesSnippets,
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
if they are visible. We should handle them separately so that we can control their priority
@ -82,13 +90,13 @@ export const getSnippets = (
key: "recentlyEditedRanges",
enabledOrPriority:
helper.options.experimental_includeRecentlyEditedRanges,
defaultPriority: 3,
defaultPriority: 4,
snippets: payload.recentlyEditedRangeSnippets,
},
{
key: "diff",
enabledOrPriority: helper.options.experimental_includeDiff,
defaultPriority: 4,
defaultPriority: 5,
snippets: payload.diffSnippets,
// TODO: diff is commonly too large, thus anything lower in priority is not included.
},
@ -119,46 +127,70 @@ export const getSnippets = (
}))
.sort((a, b) => a.priority - b.priority);
// Log the snippet order for debugging - uncomment if needed
/* console.log(
'Snippet processing order:',
snippetOrder
.map(({ key, priority }) => `${key} (priority: ${priority})`).join("\n")
); */
// Convert configs to prioritized snippets
let prioritizedSnippets = snippetOrder
.flatMap(({ key, priority }) =>
snippets[key].map((snippet) => ({ snippet, priority })),
)
.sort((a, b) => a.priority - b.priority)
.map(({ snippet }) => snippet);
// Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
// while looking at the prompts in the Continue's output
prioritizedSnippets = prioritizedSnippets.filter(
(snippet) =>
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith(
"output:extension-output-Continue.continue",
),
);
const finalSnippets = [];
let remainingTokenCount = getRemainingTokenCount(helper);
while (remainingTokenCount > 0 && prioritizedSnippets.length > 0) {
const snippet = prioritizedSnippets.shift();
if (!snippet || !isValidSnippet(snippet)) {
continue;
// Process snippets in priority order
for (const { key } of snippetOrder) {
// Special handling for recentlyOpenedFiles
if (key === "recentlyOpenedFiles" && helper.options.useRecentlyOpened) {
const recentlyOpenedFilesSnippets =
payload.recentlyOpenedFileSnippets.filter(
(snippet) =>
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith(
"output:extension-output-Continue.continue",
),
);
// Custom trimming
const processedSnippets = formatOpenedFilesContext(
recentlyOpenedFilesSnippets,
remainingTokenCount,
helper,
finalSnippets,
TOKEN_BUFFER,
);
// Add processed snippets to finalSnippets respecting token limits
for (const snippet of processedSnippets) {
if (!isValidSnippet(snippet)) continue;
const snippetSize =
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
if (remainingTokenCount >= snippetSize) {
finalSnippets.push(snippet);
remainingTokenCount -= snippetSize;
} else {
break; // Out of tokens
}
}
} else {
// Normal processing for other snippet types
const snippetsToProcess = snippets[key].filter(
(snippet) =>
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith(
"output:extension-output-Continue.continue",
),
);
for (const snippet of snippetsToProcess) {
if (!isValidSnippet(snippet)) continue;
const snippetSize =
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
if (remainingTokenCount >= snippetSize) {
finalSnippets.push(snippet);
remainingTokenCount -= snippetSize;
} else {
break; // Out of tokens
}
}
}
const snippetSize =
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
if (remainingTokenCount >= snippetSize) {
finalSnippets.push(snippet);
remainingTokenCount -= snippetSize;
}
// If we're out of tokens, no need to process more snippet types
if (remainingTokenCount <= 0) break;
}
return finalSnippets;

View file

@ -0,0 +1,172 @@
import { countTokens, pruneStringFromBottom } from "../../llm/countTokens";
import {
AutocompleteCodeSnippet,
AutocompleteSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
let logMin: number;
let logMax: number;
const numFilesConsidered = 10;
const defaultNumFilesUsed = 5;
const recencyWeight = 0.6;
const sizeWeight = 0.4;
const minSize = 10;
const minTokensInSnippet = 125;
// Fits opened-file snippets into the remaining amount of prompt tokens
export function formatOpenedFilesContext(
recentlyOpenedFilesSnippets: AutocompleteCodeSnippet[],
remainingTokenCount: number,
helper: HelperVars,
alreadyAddedSnippets: AutocompleteSnippet[], // TODO use this to deduplicate context
TOKEN_BUFFER: number,
): AutocompleteCodeSnippet[] {
if (recentlyOpenedFilesSnippets.length === 0) {
return [];
}
// Calculate how many full snippets would fit within the remaining token count
let numSnippetsThatFit = 0;
let totalTokens = 0;
const numFilesUsed = Math.min(
defaultNumFilesUsed,
recentlyOpenedFilesSnippets.length,
);
for (let i = 0; i < recentlyOpenedFilesSnippets.length; i++) {
const snippetTokens = countTokens(
recentlyOpenedFilesSnippets[i].content,
helper.modelName,
);
if (totalTokens + snippetTokens < remainingTokenCount - TOKEN_BUFFER) {
totalTokens += snippetTokens;
numSnippetsThatFit++;
} else {
break;
}
}
// if all the untrimmed snippets, or more than a default value, fit, return the untrimmed snippets
if (numSnippetsThatFit >= numFilesUsed) {
return recentlyOpenedFilesSnippets.slice(0, numSnippetsThatFit);
}
// If they don't fit, adaptively trim them.
setLogStats(recentlyOpenedFilesSnippets);
const topScoredSnippets = rankByScore(recentlyOpenedFilesSnippets);
let N = topScoredSnippets.length;
while (remainingTokenCount - TOKEN_BUFFER < N * minTokensInSnippet) {
topScoredSnippets.pop();
N = topScoredSnippets.length;
if (N === 0) break;
}
let trimmedSnippets = new Array<AutocompleteCodeSnippet>();
while (N > 0) {
let W = 2 / (N + 1);
let snippetTokenLimit = Math.floor(
minTokensInSnippet +
W * (remainingTokenCount - TOKEN_BUFFER - N * minTokensInSnippet),
);
let trimmedSnippetAndTokenCount = trimSnippetForContext(
topScoredSnippets[0],
snippetTokenLimit,
helper.modelName,
);
trimmedSnippets.push(trimmedSnippetAndTokenCount.newSnippet);
remainingTokenCount -= trimmedSnippetAndTokenCount.newTokens;
topScoredSnippets.shift();
N = topScoredSnippets.length;
}
return trimmedSnippets;
}
// Rank snippets by recency and size
const rankByScore = (
snippets: AutocompleteCodeSnippet[],
): AutocompleteCodeSnippet[] => {
if (snippets.length === 0) return [];
const topSnippets = snippets.slice(0, numFilesConsidered);
// Sort by score (using original index for recency calculation)
const scoredSnippets = topSnippets.map((snippet, i) => ({
snippet,
originalIndex: i,
score: getRecencyAndSizeScore(i, snippet),
}));
// Uncomment to debug. Logs the table of snippets with their scores (in order of recency).
/* console.table(
topSnippets.map((snippet, i) => ({
filepath: "filepath" in snippet ? snippet.filepath : "unknown",
recencyAndSizeScore: getRecencyAndSizeScore(i, snippet),
})),
); */
scoredSnippets.sort((a, b) => b.score - a.score);
return scoredSnippets
.slice(0, Math.min(defaultNumFilesUsed, scoredSnippets.length))
.map((item) => item.snippet);
};
// Returns linear combination of recency and size scores
// recency score is exponential decay over recency; log normalized score is used for size
const getRecencyAndSizeScore = (
index: number,
snippet: AutocompleteSnippet,
): number => {
const recencyScore = Math.pow(1.15, -1 * index);
const logCurrent = Math.log(Math.max(snippet.content.length, minSize));
const sizeScore =
logMax === logMin ? 0.5 : 1 - (logCurrent - logMin) / (logMax - logMin);
return recencyWeight * recencyScore + sizeWeight * sizeScore;
};
const setLogStats = (snippets: AutocompleteSnippet[]): void => {
let contentSizes = snippets
.slice(0, 10)
.map((snippet) => snippet.content.length);
logMin = Math.log(Math.max(Math.min(...contentSizes), minSize));
logMax = Math.log(Math.max(Math.max(...contentSizes), minSize));
return;
};
function trimSnippetForContext(
snippet: AutocompleteCodeSnippet,
maxTokens: number,
modelName: string,
): { newSnippet: AutocompleteCodeSnippet; newTokens: number } {
let numTokensInSnippet = countTokens(snippet.content, modelName);
if (numTokensInSnippet <= maxTokens) {
return { newSnippet: snippet, newTokens: numTokensInSnippet };
}
let trimmedCode = pruneStringFromBottom(
modelName,
maxTokens,
snippet.content,
);
return {
newSnippet: { ...snippet, content: trimmedCode },
newTokens: countTokens(trimmedCode, modelName),
};
}
// Uncomment for testing
export {
getRecencyAndSizeScore,
rankByScore,
setLogStats,
trimSnippetForContext,
};

View file

@ -4,13 +4,13 @@ import { CompletionOptions } from "../..";
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
import { HelperVars } from "../util/HelperVars";
import { getUriPathBasename } from "../../util/uri";
import { SnippetPayload } from "../snippets";
import {
AutocompleteTemplate,
getTemplateForModel,
} from "./AutocompleteTemplate";
import { getSnippets } from "./filtering";
import { getUriPathBasename } from "../../util/uri";
import { formatSnippets } from "./formatting";
import { getStopTokens } from "./getStopTokens";

View file

@ -0,0 +1,20 @@
import QuickLRU from "quick-lru";
// The cache key and value are both a filepath string
export type cacheElementType = string;
// maximum number of open files that can be cached
const MAX_NUM_OPEN_CONTEXT_FILES = 20;
// stores which files are currently open in the IDE, in viewing order
export const openedFilesLruCache = new QuickLRU<
cacheElementType,
cacheElementType
>({
maxSize: MAX_NUM_OPEN_CONTEXT_FILES,
});
// used in core/core.ts to handle removals from the cache
export const prevFilepaths = {
filepaths: [] as string[],
};

View file

@ -2,10 +2,10 @@
import nlp from "wink-nlp-utils";
import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
import { chunkDocument } from "../../../indexing/chunk/chunk";
import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
const DEFAULT_CHUNK_SIZE = 384;
@ -98,7 +98,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
n: number,
): Promise<Chunk[]> {
const recentlyEditedFilesSlice = Array.from(
recentlyEditedFilesCache.keys(),
openedFilesLruCache.keys(),
).slice(0, n);
// If the number of recently edited files is less than the retrieval limit,

View file

@ -1,16 +0,0 @@
import QuickLRU from "quick-lru";
import { ToWebviewOrCoreFromIdeProtocol } from "../../protocol/ide.js";
// The cache key and value are both a filepath string
export type RecentlyEditedFilesCacheKeyAndValue =
ToWebviewOrCoreFromIdeProtocol["didChangeActiveTextEditor"][0]["filepath"];
const MAX_NUM_RECENTLY_EDITED_FILES = 100;
export const recentlyEditedFilesCache = new QuickLRU<
RecentlyEditedFilesCacheKeyAndValue,
RecentlyEditedFilesCacheKeyAndValue
>({
maxSize: MAX_NUM_RECENTLY_EDITED_FILES,
});

View file

@ -3,12 +3,15 @@ import * as URI from "uri-js";
import { v4 as uuidv4 } from "uuid";
import { CompletionProvider } from "./autocomplete/CompletionProvider";
import {
openedFilesLruCache,
prevFilepaths,
} from "./autocomplete/util/openedFilesLruCache";
import { ConfigHandler } from "./config/ConfigHandler";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
import { addModel, deleteModel } from "./config/util";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { getControlPlaneEnv } from "./control-plane/env";
@ -619,6 +622,32 @@ export class Core {
});
on("files/closed", async ({ data }) => {
try {
const fileUris = await this.ide.getOpenFiles();
if (fileUris) {
const filepaths = fileUris.map((uri) => uri.toString());
if (!prevFilepaths.filepaths.length) {
prevFilepaths.filepaths = filepaths;
}
// If there is a removal, including if the number of tabs is the same (which can happen with temp tabs)
if (filepaths.length <= prevFilepaths.filepaths.length) {
// Remove files from cache that are no longer open (i.e. in the cache but not in the list of opened tabs)
for (const [key, _] of openedFilesLruCache.entriesDescending()) {
if (!filepaths.includes(key)) {
openedFilesLruCache.delete(key);
}
}
}
prevFilepaths.filepaths = filepaths;
}
} catch (e) {
console.error(
`didChangeVisibleTextEditors: failed to update openedFilesLruCache`,
);
}
if (data.uris) {
this.messenger.send("didCloseFiles", {
uris: data.uris,
@ -626,7 +655,26 @@ export class Core {
}
});
on("files/opened", async () => {});
on("files/opened", async ({ data: { uris } }) => {
if (uris) {
for (const filepath of uris) {
try {
const ignore = await shouldIgnore(filepath, this.ide);
if (!ignore) {
// Set the active file as most recently used (need to force recency update by deleting and re-adding)
if (openedFilesLruCache.has(filepath)) {
openedFilesLruCache.delete(filepath);
}
openedFilesLruCache.set(filepath, filepath);
}
} catch (e) {
console.error(
`files/opened: failed to update openedFiles cache for ${filepath}`,
);
}
}
}
});
// Docs, etc. indexing
on("indexing/reindex", async (msg) => {
@ -682,19 +730,6 @@ export class Core {
return { url };
});
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
try {
const ignore = await shouldIgnore(filepath, this.ide);
if (!ignore) {
recentlyEditedFilesCache.set(filepath, filepath);
}
} catch (e) {
console.error(
`didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`,
);
}
});
on("tools/call", async ({ data: { toolCall } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {

1
core/index.d.ts vendored
View file

@ -1112,6 +1112,7 @@ export interface TabAutocompleteOptions {
useCache: boolean;
onlyMyCode: boolean;
useRecentlyEdited: boolean;
useRecentlyOpened: boolean;
disableInFiles?: string[];
useImports?: boolean;
showWhateverWeHaveAtXMs?: number;

View file

@ -40,9 +40,11 @@ export class MessageIde implements IDE {
fileExists(fileUri: string): Promise<boolean> {
return this.request("fileExists", { filepath: fileUri });
}
async gotoDefinition(location: Location): Promise<RangeInFile[]> {
return this.request("gotoDefinition", { location });
}
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
this.on("didChangeActiveTextEditor", (data) => callback(data.filepath));
}
@ -50,12 +52,14 @@ export class MessageIde implements IDE {
getIdeSettings(): Promise<IdeSettings> {
return this.request("getIdeSettings", undefined);
}
getFileStats(files: string[]): Promise<FileStatsMap> {
return this.request("getFileStats", { files });
}
getGitRootPath(dir: string): Promise<string | undefined> {
return this.request("getGitRootPath", { dir });
}
listDir(dir: string): Promise<[string, FileType][]> {
return this.request("listDir", { dir });
}
@ -164,6 +168,7 @@ export class MessageIde implements IDE {
async saveFile(fileUri: string): Promise<void> {
await this.request("saveFile", { filepath: fileUri });
}
async readFile(fileUri: string): Promise<string> {
return await this.request("readFile", { filepath: fileUri });
}

View file

@ -34,6 +34,7 @@ class FileSystemIde implements IDE {
): Promise<void> {
return Promise.resolve();
}
fileExists(fileUri: string): Promise<boolean> {
const filepath = fileURLToPath(fileUri);
return Promise.resolve(fs.existsSync(filepath));
@ -42,6 +43,7 @@ class FileSystemIde implements IDE {
gotoDefinition(location: Location): Promise<RangeInFile[]> {
return Promise.resolve([]);
}
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
return;
}
@ -55,6 +57,7 @@ class FileSystemIde implements IDE {
pauseCodebaseIndexOnStart: false,
};
}
async getFileStats(fileUris: string[]): Promise<FileStatsMap> {
const result: FileStatsMap = {};
for (const uri of fileUris) {
@ -71,9 +74,11 @@ class FileSystemIde implements IDE {
}
return result;
}
getGitRootPath(dir: string): Promise<string | undefined> {
return Promise.resolve(dir);
}
async listDir(dir: string): Promise<[string, FileType][]> {
const filepath = fileURLToPath(dir);
const all: [string, FileType][] = fs

View file

@ -15,6 +15,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
useCache: true,
onlyMyCode: true,
useRecentlyEdited: true,
useRecentlyOpened: true,
disableInFiles: undefined,
useImports: true,
transform: true,

View file

@ -3,8 +3,6 @@ import { exec } from "node:child_process";
import { Range } from "core";
import { EXTENSION_NAME } from "core/control-plane/env";
import { GetGhTokenArgs } from "core/protocol/ide";
import { editConfigFile, getConfigJsonPath } from "core/util/paths";
import * as URI from "uri-js";
import * as vscode from "vscode";

View file

@ -41,6 +41,7 @@ import { VsCodeIde } from "../VsCodeIde";
import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider";
import { VsCodeMessenger } from "./VsCodeMessenger";
import { VsCodeIdeUtils } from "../util/ideUtils";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
export class VsCodeExtension {
@ -49,6 +50,7 @@ export class VsCodeExtension {
private configHandler: ConfigHandler;
private extensionContext: vscode.ExtensionContext;
private ide: VsCodeIde;
private ideUtils: VsCodeIdeUtils;
private consoleView: ContinueConsoleWebviewViewProvider;
private sidebar: ContinueGUIWebviewViewProvider;
private windowId: string;
@ -76,6 +78,7 @@ export class VsCodeExtension {
},
);
this.ide = new VsCodeIde(this.webviewProtocolPromise, context);
this.ideUtils = new VsCodeIdeUtils();
this.extensionContext = context;
this.windowId = uuidv4();
@ -382,9 +385,15 @@ export class VsCodeExtension {
context.subscriptions.push(linkProvider);
this.ide.onDidChangeActiveTextEditor((filepath) => {
void this.core.invoke("didChangeActiveTextEditor", { filepath });
void this.core.invoke("files/opened", { uris: [filepath] });
});
// initializes openedFileLruCache with files that are already open when the extension is activated
let initialOpenedFilePaths = this.ideUtils
.getOpenFiles()
.map((uri) => uri.toString());
this.core.invoke("files/opened", { uris: initialOpenedFilePaths });
vscode.workspace.onDidChangeConfiguration(async (event) => {
if (event.affectsConfiguration(EXTENSION_NAME)) {
const settings = await this.ide.getIdeSettings();

View file

@ -269,14 +269,13 @@ export class VsCodeIdeUtils {
getOpenFiles(): vscode.Uri[] {
return vscode.window.tabGroups.all
.map((group) => {
return group.tabs.map((tab) => {
return (tab.input as any)?.uri;
});
})
.flat()
.filter(Boolean) // filter out undefined values
.filter((uri) => this.documentIsCode(uri)); // Filter out undesired documents
.flatMap((group) => group.tabs)
.filter(
(tab) =>
tab.input instanceof vscode.TabInputText &&
this.documentIsCode((tab.input as vscode.TabInputText).uri),
)
.map((tab) => (tab.input as vscode.TabInputText).uri);
}
saveFile(uri: vscode.Uri) {

View file

@ -0,0 +1,21 @@
public class Calculator {
public int myAddition(int a, int b, int c) {
return a + b + c;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public double divide(int a, int b) {
if (b != 0) {
return (double) a / b;
} else {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
}
}

View file

@ -0,0 +1,7 @@
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.myAddition(1, 2, 3);
}
}

View file

@ -15,4 +15,4 @@ class Calculator:
return self
def get_result(self):
return self.result
return self.result