Elffuss BraidHub

kikocis/continue public

972ea8cfaef0 · 13.0 KiBRawPermalink
1import fs from "fs";
2
3import { IContextProvider } from "core";
4import { ConfigHandler } from "core/config/ConfigHandler";
5import { EXTENSION_NAME, getControlPlaneEnv } from "core/control-plane/env";
6import { Core } from "core/core";
7import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
8import { InProcessMessenger } from "core/protocol/messenger";
9import {
10 getConfigJsonPath,
11 getConfigTsPath,
12 getConfigYamlPath,
13} from "core/util/paths";
14import { v4 as uuidv4 } from "uuid";
15import * as vscode from "vscode";
16
17import { ContinueCompletionProvider } from "../autocomplete/completionProvider";
18import {
19 monitorBatteryChanges,
20 setupStatusBar,
21 StatusBarStatus,
22} from "../autocomplete/statusBar";
23import { registerAllCommands } from "../commands";
24import { ContinueConsoleWebviewViewProvider } from "../ContinueConsoleWebviewViewProvider";
25import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
26import { VerticalDiffManager } from "../diff/vertical/manager";
27import { registerAllCodeLensProviders } from "../lang-server/codeLens";
28import { registerAllPromptFilesCompletionProviders } from "../lang-server/promptFileCompletions";
29import EditDecorationManager from "../quickEdit/EditDecorationManager";
30import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
31import { setupRemoteConfigSync } from "../stubs/activation";
32import { UriEventHandler } from "../stubs/uriHandler";
33import {
34 getControlPlaneSessionInfo,
35 WorkOsAuthProvider,
36} from "../stubs/WorkOsAuthProvider";
37import { Battery } from "../util/battery";
38import { FileSearch } from "../util/FileSearch";
39import { VsCodeIde } from "../VsCodeIde";
40
41import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider";
42import { VsCodeMessenger } from "./VsCodeMessenger";
43
44import type { VsCodeWebviewProtocol } from "../webviewProtocol";
45
46export class VsCodeExtension {
47 // Currently some of these are public so they can be used in testing (test/test-suites)
48
49 private configHandler: ConfigHandler;
50 private extensionContext: vscode.ExtensionContext;
51 private ide: VsCodeIde;
52 private consoleView: ContinueConsoleWebviewViewProvider;
53 private sidebar: ContinueGUIWebviewViewProvider;
54 private windowId: string;
55 private editDecorationManager: EditDecorationManager;
56 private verticalDiffManager: VerticalDiffManager;
57 webviewProtocolPromise: Promise<VsCodeWebviewProtocol>;
58 private core: Core;
59 private battery: Battery;
60 private workOsAuthProvider: WorkOsAuthProvider;
61 private fileSearch: FileSearch;
62 private uriHandler = new UriEventHandler();
63
64 constructor(context: vscode.ExtensionContext) {
65 // Register auth provider
66 this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
67 this.workOsAuthProvider.refreshSessions();
68 context.subscriptions.push(this.workOsAuthProvider);
69
70 this.editDecorationManager = new EditDecorationManager(context);
71
72 let resolveWebviewProtocol: any = undefined;
73 this.webviewProtocolPromise = new Promise<VsCodeWebviewProtocol>(
74 (resolve) => {
75 resolveWebviewProtocol = resolve;
76 },
77 );
78 this.ide = new VsCodeIde(this.webviewProtocolPromise, context);
79 this.extensionContext = context;
80 this.windowId = uuidv4();
81
82 // Dependencies of core
83 let resolveVerticalDiffManager: any = undefined;
84 const verticalDiffManagerPromise = new Promise<VerticalDiffManager>(
85 (resolve) => {
86 resolveVerticalDiffManager = resolve;
87 },
88 );
89 let resolveConfigHandler: any = undefined;
90 const configHandlerPromise = new Promise<ConfigHandler>((resolve) => {
91 resolveConfigHandler = resolve;
92 });
93 this.sidebar = new ContinueGUIWebviewViewProvider(
94 configHandlerPromise,
95 this.windowId,
96 this.extensionContext,
97 );
98
99 // Sidebar
100 context.subscriptions.push(
101 vscode.window.registerWebviewViewProvider(
102 "continue.continueGUIView",
103 this.sidebar,
104 {
105 webviewOptions: { retainContextWhenHidden: true },
106 },
107 ),
108 );
109 resolveWebviewProtocol(this.sidebar.webviewProtocol);
110
111 const inProcessMessenger = new InProcessMessenger<
112 ToCoreProtocol,
113 FromCoreProtocol
114 >();
115
116 new VsCodeMessenger(
117 inProcessMessenger,
118 this.sidebar.webviewProtocol,
119 this.ide,
120 verticalDiffManagerPromise,
121 configHandlerPromise,
122 this.workOsAuthProvider,
123 this.editDecorationManager,
124 );
125
126 this.core = new Core(inProcessMessenger, this.ide);
127 this.configHandler = this.core.configHandler;
128 resolveConfigHandler?.(this.configHandler);
129
130 this.configHandler.loadConfig();
131
132 this.verticalDiffManager = new VerticalDiffManager(
133 this.sidebar.webviewProtocol,
134 this.editDecorationManager,
135 );
136 resolveVerticalDiffManager?.(this.verticalDiffManager);
137
138 setupRemoteConfigSync(
139 this.configHandler.reloadConfig.bind(this.configHandler),
140 );
141
142 this.configHandler.loadConfig().then(({ config }) => {
143 const { verticalDiffCodeLens } = registerAllCodeLensProviders(
144 context,
145 this.verticalDiffManager.fileUriToCodeLens,
146 config,
147 );
148
149 this.verticalDiffManager.refreshCodeLens =
150 verticalDiffCodeLens.refresh.bind(verticalDiffCodeLens);
151 });
152
153 this.configHandler.onConfigUpdate(
154 async ({ config: newConfig, configLoadInterrupted }) => {
155 if (configLoadInterrupted) {
156 // Show error in status bar
157 setupStatusBar(undefined, undefined, true);
158 } else if (newConfig) {
159 setupStatusBar(undefined, undefined, false);
160
161 registerAllCodeLensProviders(
162 context,
163 this.verticalDiffManager.fileUriToCodeLens,
164 newConfig,
165 );
166 }
167 },
168 );
169
170 // Tab autocomplete
171 const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
172 const enabled = config.get<boolean>("enableTabAutocomplete");
173
174 // Register inline completion provider
175 setupStatusBar(
176 enabled ? StatusBarStatus.Enabled : StatusBarStatus.Disabled,
177 );
178 context.subscriptions.push(
179 vscode.languages.registerInlineCompletionItemProvider(
180 [{ pattern: "**" }],
181 new ContinueCompletionProvider(
182 this.configHandler,
183 this.ide,
184 this.sidebar.webviewProtocol,
185 ),
186 ),
187 );
188
189 // Handle uri events
190 this.uriHandler.event((uri) => {
191 const queryParams = new URLSearchParams(uri.query);
192 let profileId = queryParams.get("profile_id");
193 let orgId = queryParams.get("org_id");
194
195 this.core.invoke("config/refreshProfiles", {
196 selectOrgId: orgId === "null" ? undefined : (orgId ?? undefined),
197 selectProfileId:
198 profileId === "null" ? undefined : (profileId ?? undefined),
199 });
200 });
201
202 // Battery
203 this.battery = new Battery();
204 context.subscriptions.push(this.battery);
205 context.subscriptions.push(monitorBatteryChanges(this.battery));
206
207 // FileSearch
208 this.fileSearch = new FileSearch(this.ide);
209 registerAllPromptFilesCompletionProviders(
210 context,
211 this.fileSearch,
212 this.ide,
213 );
214
215 const quickEdit = new QuickEdit(
216 this.verticalDiffManager,
217 this.configHandler,
218 this.sidebar.webviewProtocol,
219 this.ide,
220 context,
221 this.fileSearch,
222 );
223
224 // LLM Log view
225 this.consoleView = new ContinueConsoleWebviewViewProvider(
226 this.windowId,
227 this.extensionContext,
228 this.core.llmLogger,
229 );
230
231 context.subscriptions.push(
232 vscode.window.registerWebviewViewProvider(
233 "continue.continueConsoleView",
234 this.consoleView,
235 ),
236 );
237
238 // Commands
239 registerAllCommands(
240 context,
241 this.ide,
242 context,
243 this.sidebar,
244 this.consoleView,
245 this.configHandler,
246 this.verticalDiffManager,
247 this.battery,
248 quickEdit,
249 this.core,
250 this.editDecorationManager,
251 );
252
253 // Disabled due to performance issues
254 // registerDebugTracker(this.sidebar.webviewProtocol, this.ide);
255
256 // Listen for file saving - use global file watcher so that changes
257 // from outside the window are also caught
258 fs.watchFile(getConfigJsonPath(), { interval: 1000 }, async (stats) => {
259 if (stats.size === 0) {
260 return;
261 }
262 await this.configHandler.reloadConfig();
263 });
264
265 fs.watchFile(
266 getConfigYamlPath("vscode"),
267 { interval: 1000 },
268 async (stats) => {
269 if (stats.size === 0) {
270 return;
271 }
272 await this.configHandler.reloadConfig();
273 },
274 );
275
276 fs.watchFile(getConfigTsPath(), { interval: 1000 }, (stats) => {
277 if (stats.size === 0) {
278 return;
279 }
280 this.configHandler.reloadConfig();
281 });
282
283 vscode.workspace.onDidSaveTextDocument(async (event) => {
284 this.core.invoke("files/changed", {
285 uris: [event.uri.toString()],
286 });
287 });
288
289 vscode.workspace.onDidDeleteFiles(async (event) => {
290 this.core.invoke("files/deleted", {
291 uris: event.files.map((uri) => uri.toString()),
292 });
293 });
294
295 vscode.workspace.onDidCloseTextDocument(async (event) => {
296 this.core.invoke("files/closed", {
297 uris: [event.uri.toString()],
298 });
299 });
300
301 vscode.workspace.onDidCreateFiles(async (event) => {
302 this.core.invoke("files/created", {
303 uris: event.files.map((uri) => uri.toString()),
304 });
305 });
306
307 // When GitHub sign-in status changes, reload config
308 vscode.authentication.onDidChangeSessions(async (e) => {
309 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
310 if (e.provider.id === env.AUTH_TYPE) {
311 vscode.commands.executeCommand(
312 "setContext",
313 "continue.isSignedInToControlPlane",
314 true,
315 );
316
317 const sessionInfo = await getControlPlaneSessionInfo(true, false);
318 void this.core.invoke("didChangeControlPlaneSessionInfo", {
319 sessionInfo,
320 });
321 } else {
322 vscode.commands.executeCommand(
323 "setContext",
324 "continue.isSignedInToControlPlane",
325 false,
326 );
327
328 if (e.provider.id === "github") {
329 this.configHandler.reloadConfig();
330 }
331 }
332 });
333
334 // Refresh index when branch is changed
335 this.ide.getWorkspaceDirs().then((dirs) =>
336 dirs.forEach(async (dir) => {
337 const repo = await this.ide.getRepo(dir);
338 if (repo) {
339 repo.state.onDidChange(() => {
340 // args passed to this callback are always undefined, so keep track of previous branch
341 const currentBranch = repo?.state?.HEAD?.name;
342 if (currentBranch) {
343 if (this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) {
344 if (
345 currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]
346 ) {
347 // Trigger refresh of index only in this directory
348 this.core.invoke("index/forceReIndex", { dirs: [dir] });
349 }
350 }
351
352 this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = currentBranch;
353 }
354 });
355 }
356 }),
357 );
358
359 // Register a content provider for the readonly virtual documents
360 const documentContentProvider = new (class
361 implements vscode.TextDocumentContentProvider
362 {
363 // emitter and its event
364 onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
365 onDidChange = this.onDidChangeEmitter.event;
366
367 provideTextDocumentContent(uri: vscode.Uri): string {
368 return uri.query;
369 }
370 })();
371 context.subscriptions.push(
372 vscode.workspace.registerTextDocumentContentProvider(
373 VsCodeExtension.continueVirtualDocumentScheme,
374 documentContentProvider,
375 ),
376 );
377
378 const linkProvider = vscode.languages.registerDocumentLinkProvider(
379 { language: "yaml" },
380 new ConfigYamlDocumentLinkProvider(),
381 );
382 context.subscriptions.push(linkProvider);
383
384 this.ide.onDidChangeActiveTextEditor((filepath) => {
385 void this.core.invoke("didChangeActiveTextEditor", { filepath });
386 });
387
388 this.ide.onDidCloseTextDocument((filepaths) => {
389 void this.core.invoke("didCloseTextDocument", { filepaths });
390 });
391
392 // initializes openedFileLruCache with files that are already open when the extension is activated
393 let initialOpenedFilePaths = vscode.window.tabGroups.all
394 .flatMap((group) => group.tabs)
395 .filter((tab) => tab.input instanceof vscode.TabInputText)
396 .map((tab) => (tab.input as vscode.TabInputText).uri.fsPath);
397 this.core.invoke("initializeOpenedFileCache", { initialOpenedFilePaths });
398
399 vscode.workspace.onDidChangeConfiguration(async (event) => {
400 if (event.affectsConfiguration(EXTENSION_NAME)) {
401 const settings = await this.ide.getIdeSettings();
402 void this.core.invoke("config/ideSettingsUpdate", settings);
403 }
404 });
405 }
406
407 static continueVirtualDocumentScheme = EXTENSION_NAME;
408
409 // eslint-disable-next-line @typescript-eslint/naming-convention
410 private PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = {};
411
412 registerCustomContextProvider(contextProvider: IContextProvider) {
413 this.configHandler.registerCustomContextProvider(contextProvider);
414 }
415}