Elffuss BraidHub

kikocis/continue public

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