Elffuss BraidHub

kikocis/continue public

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