Elffuss BraidHub

kikocis/continue public

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