Elffuss BraidHub

kikocis/continue public

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