Elffuss BraidHub

kikocis/continue public

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