Elffuss BraidHub

kikocis/continue public

main · 20.8 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 { VsCodeIdeUtils } from "../util/ideUtils";
40import { VsCodeIde } from "../VsCodeIde";
41
42import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider";
43import { VsCodeMessenger } from "./VsCodeMessenger";
44
45import { getAst } from "core/autocomplete/util/ast";
46import { modelSupportsNextEdit } from "core/llm/autodetect";
47import { NEXT_EDIT_MODELS } from "core/llm/constants";
48import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker";
49import { NextEditProvider } from "core/nextEdit/NextEditProvider";
50import { isNextEditTest } from "core/nextEdit/utils";
51import { localPathOrUriToPath } from "core/util/pathToUri";
52import { JumpManager } from "../activation/JumpManager";
53import setupNextEditWindowManager, {
54 NextEditWindowManager,
55} from "../activation/NextEditWindowManager";
56import {
57 HandlerPriority,
58 SelectionChangeManager,
59} from "../activation/SelectionChangeManager";
60import { GhostTextAcceptanceTracker } from "../autocomplete/GhostTextAcceptanceTracker";
61import { getDefinitionsFromLsp } from "../autocomplete/lsp";
62import { handleTextDocumentChange } from "../util/editLoggingUtils";
63import type { VsCodeWebviewProtocol } from "../webviewProtocol";
64
65export class VsCodeExtension {
66 // Currently some of these are public so they can be used in testing (test/test-suites)
67
68 private configHandler: ConfigHandler;
69 private extensionContext: vscode.ExtensionContext;
70 private ide: VsCodeIde;
71 private ideUtils: VsCodeIdeUtils;
72 private consoleView: ContinueConsoleWebviewViewProvider;
73 private sidebar: ContinueGUIWebviewViewProvider;
74 private windowId: string;
75 private editDecorationManager: EditDecorationManager;
76 private verticalDiffManager: VerticalDiffManager;
77 webviewProtocolPromise: Promise<VsCodeWebviewProtocol>;
78 private core: Core;
79 private battery: Battery;
80 private workOsAuthProvider: WorkOsAuthProvider;
81 private fileSearch: FileSearch;
82 private uriHandler = new UriEventHandler();
83 private completionProvider: ContinueCompletionProvider;
84
85 private ARBITRARY_TYPING_DELAY = 2000;
86
87 /**
88 * This is how you turn next edit on or off at the extension level.
89 * This is called on config reload and autocomplete menu updates.
90 * This is also the place you want to check to enable/disable next edit during e2e tests,
91 * because it tends to stain other e2e tests and make them fail.
92 */
93 private async updateNextEditState(
94 context: vscode.ExtensionContext,
95 ): Promise<void> {
96 const { config: continueConfig } = await this.configHandler.loadConfig();
97 const autocompleteModel = continueConfig?.selectedModelByRole.autocomplete;
98 const vscodeConfig = vscode.workspace.getConfiguration(EXTENSION_NAME);
99
100 const modelSupportsNext =
101 autocompleteModel &&
102 modelSupportsNextEdit(
103 autocompleteModel.capabilities,
104 autocompleteModel.model,
105 autocompleteModel.title,
106 );
107
108 // Use smart defaults.
109 let nextEditEnabled = vscodeConfig.get<boolean>("enableNextEdit");
110 if (nextEditEnabled === undefined) {
111 // First time - set smart default.
112 nextEditEnabled = modelSupportsNext ?? false;
113 await vscodeConfig.update(
114 "enableNextEdit",
115 nextEditEnabled,
116 vscode.ConfigurationTarget.Global,
117 );
118 }
119
120 // Check if Next Edit is enabled but model doesn't support it.
121 if (
122 nextEditEnabled &&
123 !modelSupportsNext &&
124 !isNextEditTest() &&
125 process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST === "true"
126 ) {
127 vscode.window
128 .showWarningMessage(
129 `The current autocomplete model (${autocompleteModel?.title || "unknown"}) does not support Next Edit.`,
130 "Disable Next Edit",
131 "Select different model",
132 )
133 .then((selection) => {
134 if (selection === "Disable Next Edit") {
135 vscodeConfig.update(
136 "enableNextEdit",
137 false,
138 vscode.ConfigurationTarget.Global,
139 );
140 } else if (selection === "Select different model") {
141 vscode.commands.executeCommand(
142 "continue.openTabAutocompleteConfigMenu",
143 );
144 }
145 });
146 }
147
148 const shouldEnableNextEdit =
149 (modelSupportsNext && nextEditEnabled) || isNextEditTest();
150
151 if (shouldEnableNextEdit) {
152 await setupNextEditWindowManager(context);
153 this.activateNextEdit();
154 await NextEditWindowManager.freeTabAndEsc();
155
156 const jumpManager = JumpManager.getInstance();
157 jumpManager.registerSelectionChangeHandler();
158
159 const ghostTextAcceptanceTracker =
160 GhostTextAcceptanceTracker.getInstance();
161 ghostTextAcceptanceTracker.registerSelectionChangeHandler();
162
163 const nextEditWindowManager = NextEditWindowManager.getInstance();
164 nextEditWindowManager.registerSelectionChangeHandler();
165 } else {
166 NextEditWindowManager.clearInstance();
167 this.deactivateNextEdit();
168 await NextEditWindowManager.freeTabAndEsc();
169
170 JumpManager.clearInstance();
171 GhostTextAcceptanceTracker.clearInstance();
172 }
173 }
174
175 constructor(context: vscode.ExtensionContext) {
176 // Register auth provider
177 this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
178
179 void this.workOsAuthProvider.refreshSessions();
180 context.subscriptions.push(this.workOsAuthProvider);
181
182 this.editDecorationManager = new EditDecorationManager(context);
183
184 let resolveWebviewProtocol: any = undefined;
185 this.webviewProtocolPromise = new Promise<VsCodeWebviewProtocol>(
186 (resolve) => {
187 resolveWebviewProtocol = resolve;
188 },
189 );
190 this.ide = new VsCodeIde(this.webviewProtocolPromise, context);
191 this.ideUtils = new VsCodeIdeUtils();
192 this.extensionContext = context;
193 this.windowId = uuidv4();
194
195 // Check if model supports next edit to determine if we should use full file diff.
196 const getUsingFullFileDiff = async () => {
197 const { config } = await this.configHandler.loadConfig();
198 const autocompleteModel = config?.selectedModelByRole.autocomplete;
199
200 if (!autocompleteModel) {
201 return false;
202 }
203
204 if (
205 !modelSupportsNextEdit(
206 autocompleteModel.capabilities,
207 autocompleteModel.model,
208 autocompleteModel.title,
209 )
210 ) {
211 return false;
212 }
213
214 if (autocompleteModel.model.includes(NEXT_EDIT_MODELS.INSTINCT)) {
215 return false;
216 }
217
218 return true;
219 };
220
221 const usingFullFileDiff = true;
222 const selectionManager = SelectionChangeManager.getInstance();
223 selectionManager.initialize(this.ide, usingFullFileDiff);
224
225 selectionManager.registerListener(
226 "typing",
227 async (e, state) => {
228 const timeSinceLastDocChange =
229 Date.now() - state.lastDocumentChangeTime;
230 if (
231 state.isTypingSession &&
232 timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY &&
233 !NextEditWindowManager.getInstance().hasAccepted()
234 ) {
235 console.log("VsCodeExtension: typing in progress, preserving chain");
236 return true;
237 }
238
239 return false;
240 },
241 HandlerPriority.NORMAL,
242 );
243
244 // Dependencies of core
245 let resolveVerticalDiffManager: any = undefined;
246 const verticalDiffManagerPromise = new Promise<VerticalDiffManager>(
247 (resolve) => {
248 resolveVerticalDiffManager = resolve;
249 },
250 );
251 let resolveConfigHandler: any = undefined;
252 const configHandlerPromise = new Promise<ConfigHandler>((resolve) => {
253 resolveConfigHandler = resolve;
254 });
255 this.sidebar = new ContinueGUIWebviewViewProvider(
256 this.windowId,
257 this.extensionContext,
258 );
259
260 // Sidebar
261 context.subscriptions.push(
262 vscode.window.registerWebviewViewProvider(
263 "continue.continueGUIView",
264 this.sidebar,
265 {
266 webviewOptions: { retainContextWhenHidden: true },
267 },
268 ),
269 );
270 resolveWebviewProtocol(this.sidebar.webviewProtocol);
271
272 const inProcessMessenger = new InProcessMessenger<
273 ToCoreProtocol,
274 FromCoreProtocol
275 >();
276
277 new VsCodeMessenger(
278 inProcessMessenger,
279 this.sidebar.webviewProtocol,
280 this.ide,
281 verticalDiffManagerPromise,
282 configHandlerPromise,
283 this.workOsAuthProvider,
284 this.editDecorationManager,
285 context,
286 this,
287 );
288
289 this.core = new Core(inProcessMessenger, this.ide);
290 this.configHandler = this.core.configHandler;
291 resolveConfigHandler?.(this.configHandler);
292
293 void this.configHandler.loadConfig();
294
295 this.verticalDiffManager = new VerticalDiffManager(
296 this.sidebar.webviewProtocol,
297 this.editDecorationManager,
298 this.ide,
299 );
300 resolveVerticalDiffManager?.(this.verticalDiffManager);
301
302 void setupRemoteConfigSync(() =>
303 this.configHandler.reloadConfig.bind(this.configHandler)(
304 "Remote config sync",
305 ),
306 );
307
308 void this.configHandler.loadConfig().then(async ({ config }) => {
309 const shouldUseFullFileDiff = await getUsingFullFileDiff();
310 this.completionProvider.updateUsingFullFileDiff(shouldUseFullFileDiff);
311 selectionManager.updateUsingFullFileDiff(shouldUseFullFileDiff);
312
313 const { verticalDiffCodeLens } = registerAllCodeLensProviders(
314 context,
315 this.verticalDiffManager.fileUriToCodeLens,
316 config,
317 );
318
319 this.verticalDiffManager.refreshCodeLens =
320 verticalDiffCodeLens.refresh.bind(verticalDiffCodeLens);
321 });
322
323 this.configHandler.onConfigUpdate(
324 async ({ config: newConfig, configLoadInterrupted }) => {
325 const shouldUseFullFileDiff = await getUsingFullFileDiff();
326 this.completionProvider.updateUsingFullFileDiff(shouldUseFullFileDiff);
327 selectionManager.updateUsingFullFileDiff(shouldUseFullFileDiff);
328
329 await this.updateNextEditState(context);
330
331 if (configLoadInterrupted) {
332 // Show error in status bar
333 setupStatusBar(undefined, undefined, true);
334 } else if (newConfig) {
335 setupStatusBar(undefined, undefined, false);
336
337 registerAllCodeLensProviders(
338 context,
339 this.verticalDiffManager.fileUriToCodeLens,
340 newConfig,
341 );
342 }
343 },
344 );
345
346 // Tab autocomplete
347 const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
348 const enabled = config.get<boolean>("enableTabAutocomplete");
349
350 // Register inline completion provider
351 setupStatusBar(
352 enabled ? StatusBarStatus.Enabled : StatusBarStatus.Disabled,
353 );
354 this.completionProvider = new ContinueCompletionProvider(
355 this.configHandler,
356 this.ide,
357 this.sidebar.webviewProtocol,
358 usingFullFileDiff,
359 );
360 context.subscriptions.push(
361 vscode.languages.registerInlineCompletionItemProvider(
362 [{ pattern: "**" }],
363 this.completionProvider,
364 ),
365 );
366
367 // Handle uri events
368 this.uriHandler.event((uri) => {
369 const queryParams = new URLSearchParams(uri.query);
370 let profileId = queryParams.get("profile_id");
371 let orgId = queryParams.get("org_id");
372
373 this.core.invoke("config/refreshProfiles", {
374 reason: "VS Code deep link",
375 selectOrgId: orgId === "null" ? undefined : (orgId ?? undefined),
376 selectProfileId:
377 profileId === "null" ? undefined : (profileId ?? undefined),
378 });
379 });
380
381 // Battery
382 this.battery = new Battery();
383 context.subscriptions.push(this.battery);
384 context.subscriptions.push(monitorBatteryChanges(this.battery));
385
386 // FileSearch
387 this.fileSearch = new FileSearch(this.ide);
388 registerAllPromptFilesCompletionProviders(
389 context,
390 this.fileSearch,
391 this.ide,
392 );
393
394 const quickEdit = new QuickEdit(
395 this.verticalDiffManager,
396 this.configHandler,
397 this.sidebar.webviewProtocol,
398 this.ide,
399 context,
400 this.fileSearch,
401 );
402
403 // LLM Log view
404 this.consoleView = new ContinueConsoleWebviewViewProvider(
405 this.windowId,
406 this.extensionContext,
407 this.core.llmLogger,
408 );
409
410 context.subscriptions.push(
411 vscode.window.registerWebviewViewProvider(
412 "continue.continueConsoleView",
413 this.consoleView,
414 ),
415 );
416
417 // Commands
418 registerAllCommands(
419 context,
420 this.ide,
421 context,
422 this.sidebar,
423 this.consoleView,
424 this.configHandler,
425 this.verticalDiffManager,
426 this.battery,
427 quickEdit,
428 this.core,
429 this.editDecorationManager,
430 );
431
432 // Disabled due to performance issues
433 // registerDebugTracker(this.sidebar.webviewProtocol, this.ide);
434
435 // Listen for file saving - use global file watcher so that changes
436 // from outside the window are also caught
437 fs.watchFile(getConfigJsonPath(), { interval: 1000 }, async (stats) => {
438 if (stats.size === 0) {
439 return;
440 }
441 await this.configHandler.reloadConfig(
442 "Global JSON config updated - fs file watch",
443 );
444 });
445
446 fs.watchFile(
447 getConfigYamlPath("vscode"),
448 { interval: 1000 },
449 async (stats) => {
450 if (stats.size === 0) {
451 return;
452 }
453 await this.configHandler.reloadConfig(
454 "Global YAML config updated - fs file watch",
455 );
456 },
457 );
458
459 fs.watchFile(getConfigTsPath(), { interval: 1000 }, (stats) => {
460 if (stats.size === 0) {
461 return;
462 }
463 void this.configHandler.reloadConfig("config.ts updated - fs file watch");
464 });
465
466 vscode.workspace.onDidChangeTextDocument(async (event) => {
467 if (event.contentChanges.length > 0) {
468 selectionManager.documentChanged();
469 }
470
471 const editInfo = await handleTextDocumentChange(
472 event,
473 this.configHandler,
474 this.ide,
475 this.completionProvider,
476 getDefinitionsFromLsp,
477 );
478
479 if (editInfo) this.core.invoke("files/smallEdit", editInfo);
480 });
481
482 vscode.workspace.onDidSaveTextDocument(async (event) => {
483 this.core.invoke("files/changed", {
484 uris: [event.uri.toString()],
485 });
486 });
487
488 vscode.workspace.onDidDeleteFiles(async (event) => {
489 this.core.invoke("files/deleted", {
490 uris: event.files.map((uri) => uri.toString()),
491 });
492 });
493
494 vscode.workspace.onDidCloseTextDocument(async (event) => {
495 this.core.invoke("files/closed", {
496 uris: [event.uri.toString()],
497 });
498 });
499
500 vscode.workspace.onDidCreateFiles(async (event) => {
501 this.core.invoke("files/created", {
502 uris: event.files.map((uri) => uri.toString()),
503 });
504 });
505
506 vscode.workspace.onDidOpenTextDocument(async (event) => {
507 console.log("onDidOpenTextDocument");
508 const ast = await getAst(event.fileName, event.getText());
509 if (ast) {
510 DocumentHistoryTracker.getInstance().addDocument(
511 localPathOrUriToPath(event.fileName),
512 event.getText(),
513 ast,
514 );
515 }
516 });
517
518 // When GitHub sign-in status changes, reload config
519 vscode.authentication.onDidChangeSessions(async (e) => {
520 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
521 if (e.provider.id === env.AUTH_TYPE) {
522 void vscode.commands.executeCommand(
523 "setContext",
524 "continue.isSignedInToControlPlane",
525 true,
526 );
527
528 const sessionInfo = await getControlPlaneSessionInfo(true, false);
529 void this.core.invoke("didChangeControlPlaneSessionInfo", {
530 sessionInfo,
531 });
532 } else {
533 void vscode.commands.executeCommand(
534 "setContext",
535 "continue.isSignedInToControlPlane",
536 false,
537 );
538
539 if (e.provider.id === "github") {
540 this.configHandler.reloadConfig("Github sign-in status changed");
541 }
542 }
543 });
544
545 // Listen for editor changes to clean up decorations when editor closes.
546 vscode.window.onDidChangeVisibleTextEditors(async () => {
547 // If our active editor is no longer visible, clear decorations.
548 console.log("deleteChain called from onDidChangeVisibleTextEditors");
549 await NextEditProvider.getInstance().deleteChain();
550 });
551
552 // Listen for selection changes to hide tooltip when cursor moves.
553 vscode.window.onDidChangeTextEditorSelection(async (e) => {
554 await selectionManager.handleSelectionChange(e);
555 });
556
557 // Refresh index when branch is changed
558 void this.ide.getWorkspaceDirs().then((dirs) =>
559 dirs.forEach(async (dir) => {
560 const repo = await this.ide.getRepo(dir);
561 if (repo) {
562 repo.state.onDidChange(() => {
563 // args passed to this callback are always undefined, so keep track of previous branch
564 const currentBranch = repo?.state?.HEAD?.name;
565 if (currentBranch) {
566 if (this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) {
567 if (
568 currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]
569 ) {
570 // Trigger refresh of index only in this directory
571 this.core.invoke("index/forceReIndex", { dirs: [dir] });
572 }
573 }
574
575 this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = currentBranch;
576 }
577 });
578 }
579 }),
580 );
581
582 // Register a content provider for the readonly virtual documents
583 const documentContentProvider = new (class
584 implements vscode.TextDocumentContentProvider
585 {
586 // emitter and its event
587 onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
588 onDidChange = this.onDidChangeEmitter.event;
589
590 provideTextDocumentContent(uri: vscode.Uri): string {
591 return uri.query;
592 }
593 })();
594 context.subscriptions.push(
595 vscode.workspace.registerTextDocumentContentProvider(
596 VsCodeExtension.continueVirtualDocumentScheme,
597 documentContentProvider,
598 ),
599 );
600
601 const linkProvider = vscode.languages.registerDocumentLinkProvider(
602 { language: "yaml" },
603 new ConfigYamlDocumentLinkProvider(),
604 );
605 context.subscriptions.push(linkProvider);
606
607 this.ide.onDidChangeActiveTextEditor((filepath) => {
608 void this.core.invoke("files/opened", { uris: [filepath] });
609 });
610
611 // initializes openedFileLruCache with files that are already open when the extension is activated
612 let initialOpenedFilePaths = this.ideUtils
613 .getOpenFiles()
614 .map((uri) => uri.toString());
615 this.core.invoke("files/opened", { uris: initialOpenedFilePaths });
616
617 // This is how you would enable/disable next edit in the autocomplete menu.
618 // See extensions/vscode/src/autocomplete/statusBar.ts.
619 vscode.workspace.onDidChangeConfiguration(async (event) => {
620 if (event.affectsConfiguration(EXTENSION_NAME)) {
621 const settings = await this.ide.getIdeSettings();
622 void this.core.invoke("config/ideSettingsUpdate", settings);
623
624 if (event.affectsConfiguration(`${EXTENSION_NAME}.enableNextEdit`)) {
625 await this.updateNextEditState(context);
626 }
627 }
628 });
629 }
630
631 static continueVirtualDocumentScheme = EXTENSION_NAME;
632
633 // eslint-disable-next-line @typescript-eslint/naming-convention
634 private PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = {};
635
636 registerCustomContextProvider(contextProvider: IContextProvider) {
637 this.configHandler.registerCustomContextProvider(contextProvider);
638 }
639
640 public activateNextEdit() {
641 this.completionProvider.activateNextEdit();
642 }
643
644 public deactivateNextEdit() {
645 this.completionProvider.deactivateNextEdit();
646 }
647}