Elffuss BraidHub

kikocis/continue public

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