Elffuss BraidHub

kikocis/continue public

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