Elffuss BraidHub

kikocis/continue public

main · 4.1 KiBRawPermalink
1import { IDE } from "core";
2import {
3 AutocompleteCodeSnippet,
4 AutocompleteSnippetType,
5} from "core/autocomplete/snippets/types";
6import { isSecurityConcern } from "core/indexing/ignore";
7import { PosthogFeatureFlag, Telemetry } from "core/util/posthog";
8import { LRUCache } from "lru-cache";
9import * as vscode from "vscode";
10
11/**
12 * Service to keep track of recently visited ranges in files.
13 */
14export class RecentlyVisitedRangesService {
15 private cache: LRUCache<
16 string,
17 Array<AutocompleteCodeSnippet & { timestamp: number }>
18 >;
19 // Default value, we override in initWithPostHog
20 private numSurroundingLines = 20;
21 private maxRecentFiles = 3;
22 private maxSnippetsPerFile = 3;
23 private isEnabled = true;
24
25 constructor(private readonly ide: IDE) {
26 this.cache = new LRUCache<
27 string,
28 Array<AutocompleteCodeSnippet & { timestamp: number }>
29 >({
30 max: this.maxRecentFiles,
31 });
32
33 void this.initWithPostHog();
34 }
35
36 private async initWithPostHog() {
37 const recentlyVisitedRangesNumSurroundingLines =
38 await Telemetry.getValueForFeatureFlag(
39 PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines,
40 );
41
42 if (recentlyVisitedRangesNumSurroundingLines) {
43 this.isEnabled = true;
44 this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines;
45 }
46
47 vscode.window.onDidChangeTextEditorSelection(
48 this.cacheCurrentSelectionContext,
49 );
50 }
51
52 private cacheCurrentSelectionContext = async (
53 event: vscode.TextEditorSelectionChangeEvent,
54 ) => {
55 const fsPath = event.textEditor.document.fileName;
56 if (isSecurityConcern(fsPath)) {
57 return;
58 }
59 const filepath = event.textEditor.document.uri.toString();
60 const line = event.selections[0].active.line;
61 const startLine = Math.max(0, line - this.numSurroundingLines);
62 const endLine = Math.min(
63 line + this.numSurroundingLines,
64 event.textEditor.document.lineCount - 1,
65 );
66
67 try {
68 const fileContents = await this.ide.readFile(filepath);
69 const lines = fileContents.split("\n");
70 const relevantLines = lines
71 .slice(startLine, endLine + 1)
72 .join("\n")
73 .trim();
74
75 const snippet: AutocompleteCodeSnippet & { timestamp: number } = {
76 filepath,
77 content: relevantLines,
78 type: AutocompleteSnippetType.Code,
79 timestamp: Date.now(),
80 };
81
82 const existing = this.cache.get(filepath) || [];
83 const newSnippets = [...existing, snippet]
84 .sort((a, b) => b.timestamp - a.timestamp)
85 .slice(0, this.maxSnippetsPerFile);
86
87 this.cache.set(filepath, newSnippets);
88 } catch (err) {
89 console.error(
90 "Error caching recently visited ranges for autocomplete: ",
91 err,
92 );
93 return;
94 }
95 };
96
97 /**
98 * Returns up to {@link maxSnippetsPerFile} snippets from the {@link maxRecentFiles} most recently visited files.
99 * Excludes snippets from the currently active file.
100 * @returns Array of code snippets from recently visited files
101 */
102 public getSnippets(): AutocompleteCodeSnippet[] {
103 if (!this.isEnabled) {
104 return [];
105 }
106
107 const currentFilepath =
108 vscode.window.activeTextEditor?.document.uri.toString();
109 let allSnippets: Array<AutocompleteCodeSnippet & { timestamp: number }> =
110 [];
111
112 // Get most recent snippets from each file in cache
113 for (const filepath of Array.from(this.cache.keys())) {
114 const snippets = (this.cache.get(filepath) || [])
115 .sort((a, b) => b.timestamp - a.timestamp)
116 .slice(0, this.maxSnippetsPerFile);
117 allSnippets = [...allSnippets, ...snippets];
118 }
119
120 return allSnippets
121 .filter(
122 (s) =>
123 !currentFilepath ||
124 (s.filepath !== currentFilepath &&
125 // Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
126 // while looking at the prompts in the Continue's output
127 !s.filepath.startsWith(
128 "output:extension-output-Continue.continue",
129 )),
130 )
131 .sort((a, b) => b.timestamp - a.timestamp)
132 .map(({ timestamp, ...snippet }) => snippet);
133 }
134}