Elffuss BraidHub

kikocis/continue public

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