-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathVsCodeExtension.ts
More file actions
692 lines (601 loc) · 22.2 KB
/
VsCodeExtension.ts
File metadata and controls
692 lines (601 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
import fs from "fs";
import path from "path";
import { IContextProvider } from "core";
import { ConfigHandler } from "core/config/ConfigHandler";
import { EXTENSION_NAME, getControlPlaneEnv } from "core/control-plane/env";
import { Core } from "core/core";
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
import { InProcessMessenger } from "core/protocol/messenger";
import {
getConfigJsonPath,
getConfigTsPath,
getConfigYamlPath,
getContinueGlobalPath,
} from "core/util/paths";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { ContinueCompletionProvider } from "../autocomplete/completionProvider";
import {
monitorBatteryChanges,
setupStatusBar,
StatusBarStatus,
} from "../autocomplete/statusBar";
import { registerAllCommands } from "../commands";
import { ContinueConsoleWebviewViewProvider } from "../ContinueConsoleWebviewViewProvider";
import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
import { registerAllPromptFilesCompletionProviders } from "../lang-server/promptFileCompletions";
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
import { setupRemoteConfigSync } from "../stubs/activation";
import { UriEventHandler } from "../stubs/uriHandler";
import {
getControlPlaneSessionInfo,
WorkOsAuthProvider,
} from "../stubs/WorkOsAuthProvider";
import { Battery } from "../util/battery";
import { FileSearch } from "../util/FileSearch";
import { VsCodeIdeUtils } from "../util/ideUtils";
import { VsCodeIde } from "../VsCodeIde";
import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider";
import { setupPromptLogging } from "./setupPromptLogging";
import { VsCodeMessenger } from "./VsCodeMessenger";
import { modelSupportsNextEdit } from "core/llm/autodetect";
import { NEXT_EDIT_MODELS } from "core/llm/constants";
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
import { isNextEditTest } from "core/nextEdit/utils";
import { JumpManager } from "../activation/JumpManager";
import setupNextEditWindowManager, {
NextEditWindowManager,
} from "../activation/NextEditWindowManager";
import {
HandlerPriority,
SelectionChangeManager,
} from "../activation/SelectionChangeManager";
import { GhostTextAcceptanceTracker } from "../autocomplete/GhostTextAcceptanceTracker";
import { getDefinitionsFromLsp } from "../autocomplete/lsp";
import {
clearDocumentContentCache,
handleTextDocumentChange,
initDocumentContentCache,
} from "../util/editLoggingUtils";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
export class VsCodeExtension {
// Currently some of these are public so they can be used in testing (test/test-suites)
private configHandler: ConfigHandler;
private extensionContext: vscode.ExtensionContext;
private ide: VsCodeIde;
private ideUtils: VsCodeIdeUtils;
private consoleView: ContinueConsoleWebviewViewProvider;
private sidebar: ContinueGUIWebviewViewProvider;
private windowId: string;
private editDecorationManager: EditDecorationManager;
private verticalDiffManager: VerticalDiffManager;
webviewProtocolPromise: Promise<VsCodeWebviewProtocol>;
private core: Core;
private battery: Battery;
private workOsAuthProvider: WorkOsAuthProvider;
private fileSearch: FileSearch;
private uriHandler = new UriEventHandler();
private completionProvider: ContinueCompletionProvider;
private ARBITRARY_TYPING_DELAY = 2000;
/**
* This is how you turn next edit on or off at the extension level.
* This is called on config reload and autocomplete menu updates.
* This is also the place you want to check to enable/disable next edit during e2e tests,
* because it tends to stain other e2e tests and make them fail.
*/
private async updateNextEditState(
context: vscode.ExtensionContext,
): Promise<void> {
const { config: continueConfig } = await this.configHandler.loadConfig();
const autocompleteModel = continueConfig?.selectedModelByRole.autocomplete;
const vscodeConfig = vscode.workspace.getConfiguration(EXTENSION_NAME);
const modelSupportsNext =
autocompleteModel &&
modelSupportsNextEdit(
autocompleteModel.capabilities,
autocompleteModel.model,
autocompleteModel.title,
);
// Use smart defaults.
let nextEditEnabled = vscodeConfig.get<boolean>("enableNextEdit");
if (nextEditEnabled === undefined) {
// First time - set smart default.
nextEditEnabled = modelSupportsNext ?? false;
await vscodeConfig.update(
"enableNextEdit",
nextEditEnabled,
vscode.ConfigurationTarget.Global,
);
}
// Check if Next Edit is enabled but model doesn't support it.
if (
nextEditEnabled &&
!modelSupportsNext &&
!isNextEditTest() &&
process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST === "true"
) {
vscode.window
.showWarningMessage(
`The current autocomplete model (${autocompleteModel?.title || "unknown"}) does not support Next Edit.`,
"Disable Next Edit",
"Select different model",
)
.then((selection) => {
if (selection === "Disable Next Edit") {
vscodeConfig.update(
"enableNextEdit",
false,
vscode.ConfigurationTarget.Global,
);
} else if (selection === "Select different model") {
vscode.commands.executeCommand(
"continue.openTabAutocompleteConfigMenu",
);
}
});
}
const shouldEnableNextEdit =
(modelSupportsNext && nextEditEnabled) || isNextEditTest();
if (shouldEnableNextEdit) {
await setupNextEditWindowManager(context);
this.activateNextEdit();
await NextEditWindowManager.freeTabAndEsc();
const jumpManager = JumpManager.getInstance();
jumpManager.registerSelectionChangeHandler();
const ghostTextAcceptanceTracker =
GhostTextAcceptanceTracker.getInstance();
ghostTextAcceptanceTracker.registerSelectionChangeHandler();
const nextEditWindowManager = NextEditWindowManager.getInstance();
nextEditWindowManager.registerSelectionChangeHandler();
} else {
NextEditWindowManager.clearInstance();
this.deactivateNextEdit();
await NextEditWindowManager.freeTabAndEsc();
JumpManager.clearInstance();
GhostTextAcceptanceTracker.clearInstance();
}
}
constructor(context: vscode.ExtensionContext) {
// Register auth provider
this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
void this.workOsAuthProvider.refreshSessions();
context.subscriptions.push(this.workOsAuthProvider);
this.editDecorationManager = new EditDecorationManager(context);
let resolveWebviewProtocol: any = undefined;
this.webviewProtocolPromise = new Promise<VsCodeWebviewProtocol>(
(resolve) => {
resolveWebviewProtocol = resolve;
},
);
this.ide = new VsCodeIde(this.webviewProtocolPromise, context);
this.ideUtils = new VsCodeIdeUtils();
this.extensionContext = context;
this.windowId = uuidv4();
// Check if model supports next edit to determine if we should use full file diff.
const getUsingFullFileDiff = async () => {
const { config } = await this.configHandler.loadConfig();
const autocompleteModel = config?.selectedModelByRole.autocomplete;
if (!autocompleteModel) {
return false;
}
if (
!modelSupportsNextEdit(
autocompleteModel.capabilities,
autocompleteModel.model,
autocompleteModel.title,
)
) {
return false;
}
if (autocompleteModel.model.includes(NEXT_EDIT_MODELS.INSTINCT)) {
return false;
}
return true;
};
const usingFullFileDiff = true;
const selectionManager = SelectionChangeManager.getInstance();
selectionManager.initialize(this.ide, usingFullFileDiff);
selectionManager.registerListener(
"typing",
async (e, state) => {
const timeSinceLastDocChange =
Date.now() - state.lastDocumentChangeTime;
if (
state.isTypingSession &&
timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY &&
!NextEditWindowManager.getInstance().hasAccepted()
) {
// console.debug(
// "VsCodeExtension: typing in progress, preserving chain",
// );
return true;
}
return false;
},
HandlerPriority.NORMAL,
);
// Dependencies of core
let resolveVerticalDiffManager: any = undefined;
const verticalDiffManagerPromise = new Promise<VerticalDiffManager>(
(resolve) => {
resolveVerticalDiffManager = resolve;
},
);
let resolveConfigHandler: any = undefined;
const configHandlerPromise = new Promise<ConfigHandler>((resolve) => {
resolveConfigHandler = resolve;
});
this.sidebar = new ContinueGUIWebviewViewProvider(
this.windowId,
this.extensionContext,
);
// Sidebar
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(
"continue.continueGUIView",
this.sidebar,
{
webviewOptions: { retainContextWhenHidden: true },
},
),
);
resolveWebviewProtocol(this.sidebar.webviewProtocol);
const inProcessMessenger = new InProcessMessenger<
ToCoreProtocol,
FromCoreProtocol
>();
new VsCodeMessenger(
inProcessMessenger,
this.sidebar.webviewProtocol,
this.ide,
verticalDiffManagerPromise,
configHandlerPromise,
this.workOsAuthProvider,
this.editDecorationManager,
context,
this,
);
this.core = new Core(inProcessMessenger, this.ide);
context.subscriptions.push(setupPromptLogging(this.core.llmLogger));
this.configHandler = this.core.configHandler;
resolveConfigHandler?.(this.configHandler);
void this.configHandler.loadConfig();
this.verticalDiffManager = new VerticalDiffManager(
this.sidebar.webviewProtocol,
this.editDecorationManager,
this.ide,
);
resolveVerticalDiffManager?.(this.verticalDiffManager);
void setupRemoteConfigSync(() =>
this.configHandler.reloadConfig.bind(this.configHandler)(
"Remote config sync",
),
);
void this.configHandler.loadConfig().then(async ({ config }) => {
const shouldUseFullFileDiff = await getUsingFullFileDiff();
this.completionProvider.updateUsingFullFileDiff(shouldUseFullFileDiff);
selectionManager.updateUsingFullFileDiff(shouldUseFullFileDiff);
const { verticalDiffCodeLens } = registerAllCodeLensProviders(
context,
this.verticalDiffManager.fileUriToCodeLens,
config,
);
this.verticalDiffManager.refreshCodeLens =
verticalDiffCodeLens.refresh.bind(verticalDiffCodeLens);
});
this.configHandler.onConfigUpdate(
async ({ config: newConfig, configLoadInterrupted }) => {
const shouldUseFullFileDiff = await getUsingFullFileDiff();
this.completionProvider.updateUsingFullFileDiff(shouldUseFullFileDiff);
selectionManager.updateUsingFullFileDiff(shouldUseFullFileDiff);
await this.updateNextEditState(context);
if (configLoadInterrupted) {
// Show error in status bar
setupStatusBar(undefined, undefined, true);
} else if (newConfig) {
setupStatusBar(undefined, undefined, false);
registerAllCodeLensProviders(
context,
this.verticalDiffManager.fileUriToCodeLens,
newConfig,
);
}
},
);
// Tab autocomplete
const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
const enabled = config.get<boolean>("enableTabAutocomplete");
// Register inline completion provider
setupStatusBar(
enabled ? StatusBarStatus.Enabled : StatusBarStatus.Disabled,
);
this.completionProvider = new ContinueCompletionProvider(
this.configHandler,
this.ide,
this.sidebar.webviewProtocol,
usingFullFileDiff,
);
context.subscriptions.push(
vscode.languages.registerInlineCompletionItemProvider(
[{ pattern: "**" }],
this.completionProvider,
),
);
// Handle uri events
this.uriHandler.event((uri) => {
const queryParams = new URLSearchParams(uri.query);
let profileId = queryParams.get("profile_id");
let orgId = queryParams.get("org_id");
this.core.invoke("config/refreshProfiles", {
reason: "VS Code deep link",
selectOrgId: orgId === "null" ? undefined : (orgId ?? undefined),
selectProfileId:
profileId === "null" ? undefined : (profileId ?? undefined),
});
});
// Battery
this.battery = new Battery();
context.subscriptions.push(this.battery);
context.subscriptions.push(monitorBatteryChanges(this.battery));
// FileSearch
this.fileSearch = new FileSearch(this.ide);
registerAllPromptFilesCompletionProviders(
context,
this.fileSearch,
this.ide,
);
const quickEdit = new QuickEdit(
this.verticalDiffManager,
this.configHandler,
this.sidebar.webviewProtocol,
this.ide,
context,
this.fileSearch,
);
// LLM Log view
this.consoleView = new ContinueConsoleWebviewViewProvider(
this.windowId,
this.extensionContext,
this.core.llmLogger,
);
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(
"continue.continueConsoleView",
this.consoleView,
),
);
// Commands
registerAllCommands(
context,
this.ide,
context,
this.sidebar,
this.consoleView,
this.configHandler,
this.verticalDiffManager,
this.battery,
quickEdit,
this.core,
this.editDecorationManager,
);
// Disabled due to performance issues
// registerDebugTracker(this.sidebar.webviewProtocol, this.ide);
// Listen for file saving - use global file watcher so that changes
// from outside the window are also caught
fs.watchFile(getConfigJsonPath(), { interval: 1000 }, async (stats) => {
if (stats.size === 0) {
return;
}
await this.configHandler.reloadConfig(
"Global JSON config updated - fs file watch",
);
});
fs.watchFile(
getConfigYamlPath("vscode"),
{ interval: 1000 },
async (stats) => {
if (stats.size === 0) {
return;
}
await this.configHandler.reloadConfig(
"Global YAML config updated - fs file watch",
);
},
);
fs.watchFile(getConfigTsPath(), { interval: 1000 }, (stats) => {
if (stats.size === 0) {
return;
}
void this.configHandler.reloadConfig("config.ts updated - fs file watch");
});
// watch global rules directory for changes
const globalRulesDir = path.join(getContinueGlobalPath(), "rules");
if (fs.existsSync(globalRulesDir)) {
fs.watch(globalRulesDir, { recursive: true }, (eventType, filename) => {
if (filename && filename.endsWith(".md")) {
void this.configHandler.reloadConfig(
"Global rules directory updated - fs file watch",
);
}
});
}
// Initialize document content cache for tracking pre-edit content
vscode.workspace.onDidOpenTextDocument((document) => {
initDocumentContentCache(document);
});
// Initialize cache for all currently open documents
for (const document of vscode.workspace.textDocuments) {
initDocumentContentCache(document);
}
vscode.workspace.onDidChangeTextDocument(async (event) => {
if (event.contentChanges.length > 0) {
selectionManager.documentChanged();
}
const editInfo = await handleTextDocumentChange(
event,
this.configHandler,
this.ide,
this.completionProvider,
getDefinitionsFromLsp,
);
if (editInfo) this.core.invoke("files/smallEdit", editInfo);
});
vscode.workspace.onDidSaveTextDocument(async (event) => {
this.core.invoke("files/changed", {
uris: [event.uri.toString()],
});
});
vscode.workspace.onDidDeleteFiles(async (event) => {
this.core.invoke("files/deleted", {
uris: event.files.map((uri) => uri.toString()),
});
});
vscode.workspace.onDidCloseTextDocument(async (event) => {
clearDocumentContentCache(event.uri.toString());
this.core.invoke("files/closed", {
uris: [event.uri.toString()],
});
});
vscode.workspace.onDidCreateFiles(async (event) => {
this.core.invoke("files/created", {
uris: event.files.map((uri) => uri.toString()),
});
});
vscode.workspace.onDidChangeWorkspaceFolders(async (event) => {
const dirs = vscode.workspace.workspaceFolders?.map(
(folder) => folder.uri,
);
this.ideUtils.setWokspaceDirectories(dirs);
this.core.invoke("index/forceReIndex", {
dirs: [
...event.added.map((folder) => folder.uri.toString()),
...event.removed.map((folder) => folder.uri.toString()),
],
});
});
// TODO merge this and re-enable https://github.com/continuedev/continue/pull/8364
// vscode.workspace.onDidOpenTextDocument(async (event) => {
// const ast = await getAst(event.fileName, event.getText());
// if (ast) {
// DocumentHistoryTracker.getInstance().addDocument(
// localPathOrUriToPath(event.fileName),
// event.getText(),
// ast,
// );
// }
// });
// When GitHub sign-in status changes, reload config
vscode.authentication.onDidChangeSessions(async (e) => {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
if (e.provider.id === env.AUTH_TYPE) {
void vscode.commands.executeCommand(
"setContext",
"continue.isSignedInToControlPlane",
true,
);
const sessionInfo = await getControlPlaneSessionInfo(true, false);
void this.core.invoke("didChangeControlPlaneSessionInfo", {
sessionInfo,
});
} else {
void vscode.commands.executeCommand(
"setContext",
"continue.isSignedInToControlPlane",
false,
);
if (e.provider.id === "github") {
this.configHandler.reloadConfig("Github sign-in status changed");
}
}
});
// Listen for editor changes to clean up decorations when editor closes.
vscode.window.onDidChangeVisibleTextEditors(async () => {
// If our active editor is no longer visible, clear decorations.
console.log("deleteChain called from onDidChangeVisibleTextEditors");
await NextEditProvider.getInstance().deleteChain();
});
// Listen for selection changes to hide tooltip when cursor moves.
vscode.window.onDidChangeTextEditorSelection(async (e) => {
await selectionManager.handleSelectionChange(e);
});
// Refresh index when branch is changed
void this.ide.getWorkspaceDirs().then((dirs) =>
dirs.forEach(async (dir) => {
const repo = await this.ide.getRepo(dir);
if (repo) {
repo.state.onDidChange(() => {
// args passed to this callback are always undefined, so keep track of previous branch
const currentBranch = repo?.state?.HEAD?.name;
if (currentBranch) {
if (this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) {
if (
currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]
) {
// Trigger refresh of index only in this directory
this.core.invoke("index/forceReIndex", { dirs: [dir] });
}
}
this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = currentBranch;
}
});
}
}),
);
// Register a content provider for the readonly virtual documents
const documentContentProvider = new (class
implements vscode.TextDocumentContentProvider
{
// emitter and its event
onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
onDidChange = this.onDidChangeEmitter.event;
provideTextDocumentContent(uri: vscode.Uri): string {
return uri.query;
}
})();
context.subscriptions.push(
vscode.workspace.registerTextDocumentContentProvider(
VsCodeExtension.continueVirtualDocumentScheme,
documentContentProvider,
),
);
const linkProvider = vscode.languages.registerDocumentLinkProvider(
{ language: "yaml" },
new ConfigYamlDocumentLinkProvider(),
);
context.subscriptions.push(linkProvider);
this.ide.onDidChangeActiveTextEditor((filepath) => {
void this.core.invoke("files/opened", { uris: [filepath] });
});
// initializes openedFileLruCache with files that are already open when the extension is activated
let initialOpenedFilePaths = this.ideUtils
.getOpenFiles()
.map((uri) => uri.toString());
this.core.invoke("files/opened", { uris: initialOpenedFilePaths });
// This is how you would enable/disable next edit in the autocomplete menu.
// See extensions/vscode/src/autocomplete/statusBar.ts.
vscode.workspace.onDidChangeConfiguration(async (event) => {
if (event.affectsConfiguration(EXTENSION_NAME)) {
const settings = await this.ide.getIdeSettings();
void this.core.invoke("config/ideSettingsUpdate", settings);
if (event.affectsConfiguration(`${EXTENSION_NAME}.enableNextEdit`)) {
await this.updateNextEditState(context);
}
}
});
}
static continueVirtualDocumentScheme = EXTENSION_NAME;
// eslint-disable-next-line @typescript-eslint/naming-convention
private PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = {};
registerCustomContextProvider(contextProvider: IContextProvider) {
this.configHandler.registerCustomContextProvider(contextProvider);
}
public activateNextEdit() {
this.completionProvider.activateNextEdit();
}
public deactivateNextEdit() {
this.completionProvider.deactivateNextEdit();
}
}