Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 12.6 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.configHandler,
134 this.sidebar.webviewProtocol,
135 this.editDecorationManager,
136 );
137 resolveVerticalDiffManager?.(this.verticalDiffManager);
138
139 setupRemoteConfigSync(
140 this.configHandler.reloadConfig.bind(this.configHandler),
141 );
142
143 this.configHandler.loadConfig().then(({ config }) => {
144 const { verticalDiffCodeLens } = registerAllCodeLensProviders(
145 context,
146 this.verticalDiffManager.fileUriToCodeLens,
147 config,
148 );
149
150 this.verticalDiffManager.refreshCodeLens =
151 verticalDiffCodeLens.refresh.bind(verticalDiffCodeLens);
152 });
153
154 this.configHandler.onConfigUpdate(
155 async ({ config: newConfig, configLoadInterrupted }) => {
156 if (configLoadInterrupted) {
157 // Show error in status bar
158 setupStatusBar(undefined, undefined, true);
159 } else if (newConfig) {
160 setupStatusBar(undefined, undefined, false);
161
162 registerAllCodeLensProviders(
163 context,
164 this.verticalDiffManager.fileUriToCodeLens,
165 newConfig,
166 );
167 }
168 },
169 );
170
171 // Tab autocomplete
172 const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
173 const enabled = config.get<boolean>("enableTabAutocomplete");
174
175 // Register inline completion provider
176 setupStatusBar(
177 enabled ? StatusBarStatus.Enabled : StatusBarStatus.Disabled,
178 );
179 context.subscriptions.push(
180 vscode.languages.registerInlineCompletionItemProvider(
181 [{ pattern: "**" }],
182 new ContinueCompletionProvider(
183 this.configHandler,
184 this.ide,
185 this.sidebar.webviewProtocol,
186 ),
187 ),
188 );
189
190 // Handle uri events
191 this.uriHandler.event((uri) => {
192 const queryParams = new URLSearchParams(uri.query);
193 let profileId = queryParams.get("profile_id");
194 let orgId = queryParams.get("org_id");
195
196 this.core.invoke("config/refreshProfiles", {
197 selectOrgId: orgId === "null" ? undefined : (orgId ?? undefined),
198 selectProfileId:
199 profileId === "null" ? undefined : (profileId ?? undefined),
200 });
201 });
202
203 // Battery
204 this.battery = new Battery();
205 context.subscriptions.push(this.battery);
206 context.subscriptions.push(monitorBatteryChanges(this.battery));
207
208 // FileSearch
209 this.fileSearch = new FileSearch(this.ide);
210 registerAllPromptFilesCompletionProviders(
211 context,
212 this.fileSearch,
213 this.ide,
214 );
215
216 const quickEdit = new QuickEdit(
217 this.verticalDiffManager,
218 this.configHandler,
219 this.sidebar.webviewProtocol,
220 this.ide,
221 context,
222 this.fileSearch,
223 );
224
225 // LLM Log view
226 this.consoleView = new ContinueConsoleWebviewViewProvider(
227 this.windowId,
228 this.extensionContext,
229 this.core.llmLogger,
230 );
231
232 context.subscriptions.push(
233 vscode.window.registerWebviewViewProvider(
234 "continue.continueConsoleView",
235 this.consoleView,
236 ),
237 );
238
239 // Commands
240 registerAllCommands(
241 context,
242 this.ide,
243 context,
244 this.sidebar,
245 this.consoleView,
246 this.configHandler,
247 this.verticalDiffManager,
248 this.core.continueServerClientPromise,
249 this.battery,
250 quickEdit,
251 this.core,
252 this.editDecorationManager,
253 );
254
255 // Disabled due to performance issues
256 // registerDebugTracker(this.sidebar.webviewProtocol, this.ide);
257
258 // Listen for file saving - use global file watcher so that changes
259 // from outside the window are also caught
260 fs.watchFile(getConfigJsonPath(), { interval: 1000 }, async (stats) => {
261 if (stats.size === 0) {
262 return;
263 }
264 await this.configHandler.reloadConfig();
265 });
266
267 fs.watchFile(
268 getConfigYamlPath("vscode"),
269 { interval: 1000 },
270 async (stats) => {
271 if (stats.size === 0) {
272 return;
273 }
274 await this.configHandler.reloadConfig();
275 },
276 );
277
278 fs.watchFile(getConfigTsPath(), { interval: 1000 }, (stats) => {
279 if (stats.size === 0) {
280 return;
281 }
282 this.configHandler.reloadConfig();
283 });
284
285 vscode.workspace.onDidSaveTextDocument(async (event) => {
286 this.ide.updateLastFileSaveTimestamp();
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("didChangeActiveTextEditor", { filepath });
389 });
390
391 vscode.workspace.onDidChangeConfiguration(async (event) => {
392 if (event.affectsConfiguration(EXTENSION_NAME)) {
393 const settings = await this.ide.getIdeSettings();
394 void this.core.invoke("config/ideSettingsUpdate", settings);
395 }
396 });
397 }
398
399 static continueVirtualDocumentScheme = EXTENSION_NAME;
400
401 // eslint-disable-next-line @typescript-eslint/naming-convention
402 private PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = {};
403
404 registerCustomContextProvider(contextProvider: IContextProvider) {
405 this.configHandler.registerCustomContextProvider(contextProvider);
406 }
407}