Elffuss BraidHub

kikocis/continue public

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