-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathCopilotHoverProvider.ts
More file actions
220 lines (195 loc) · 9.63 KB
/
CopilotHoverProvider.ts
File metadata and controls
220 lines (195 loc) · 9.63 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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import * as vscode from 'vscode';
import { Position, ResponseError } from 'vscode-languageclient';
import * as nls from 'vscode-nls';
import { getVSCodeLanguageModel } from '../../common';
import { modelSelector } from '../../constants';
import * as telemetry from '../../telemetry';
import { DefaultClient, GetCopilotHoverInfoParams, GetCopilotHoverInfoRequest, GetCopilotHoverInfoResult } from '../client';
import { RequestCancelled, ServerCancelled } from '../protocolFilter';
import { CppSettings } from '../settings';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
export class CopilotHoverProvider implements vscode.HoverProvider {
private client: DefaultClient;
private currentDocument: vscode.TextDocument | undefined;
private currentPosition: vscode.Position | undefined;
private currentCancellationToken: vscode.CancellationToken | undefined;
private waiting: boolean = false;
private ready: boolean = false;
private cancelled: boolean = false;
private cancelledDocument: vscode.TextDocument | undefined;
private cancelledPosition: vscode.Position | undefined;
private content: string | undefined;
private chatModel: vscode.LanguageModelChat | undefined;
private chatModelId: string | undefined; // Save the selected model ID to avoid trying the same unavailable model repeatedly.
// Flag to avoid querying the LanguageModelChat repeatedly if no model is found
private checkedChatModel: boolean = false;
constructor(client: DefaultClient) {
this.client = client;
}
public async getCachedChatModel(): Promise<vscode.LanguageModelChat | undefined> {
if (this.checkedChatModel) {
return this.chatModel;
}
const vscodelm = getVSCodeLanguageModel();
if (vscodelm) {
try {
let model: vscode.LanguageModelChat | undefined;
if (this.chatModelId === undefined) {
// First look for GPT-4o which should be available to all
// users and have a 0x multiplier on paid plans.
// GPT-4o is faster than the x0 GPT-5-mini (which seems too slow for hover, e.g. 10+ seconds).
this.chatModelId = 'gpt-4o';
[model] = await vscodelm.selectChatModels({ ...modelSelector, id: this.chatModelId });
if (!model) {
// If GPT-4o is not available, fallback to GPT-5.4-mini (x0.33 and fast).
this.chatModelId = 'gpt-5.4-mini';
[model] = await vscodelm.selectChatModels({ ...modelSelector, id: this.chatModelId });
}
if (!model) {
// If GPT-5.4-mini is not available, fallback to the first available model.
this.chatModelId = 'default';
[model] = await vscodelm.selectChatModels(modelSelector);
}
} else {
if (this.chatModelId === 'default') {
[model] = await vscodelm.selectChatModels(modelSelector);
} else {
[model] = await vscodelm.selectChatModels({ ...modelSelector, id: this.chatModelId });
}
}
if (!model) {
telemetry.logLanguageServerEvent('CopilotHoverNoModelSelected', { remoteName: vscode.env.remoteName || 'local' });
} else {
this.chatModel = model;
}
} catch (e: any) {
const exceptionType = e?.name || e?.constructor?.name || typeof e;
telemetry.logLanguageServerEvent('CopilotHoverSelectModelFailed', {
remoteName: vscode.env.remoteName || 'local',
exceptionType: String(exceptionType)
});
}
}
this.checkedChatModel = true;
return this.chatModel;
}
public async refreshCachedChatModel(): Promise<vscode.LanguageModelChat | undefined> {
this.chatModel = undefined;
this.checkedChatModel = false;
return this.getCachedChatModel();
}
public async provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<vscode.Hover | undefined> {
await this.client.ready;
const settings: CppSettings = new CppSettings(vscode.workspace.getWorkspaceFolder(document.uri)?.uri);
const workspaceSettings: CppSettings = new CppSettings();
if (settings.hover === "disabled" ||
workspaceSettings.copilotHover === "disabled" ||
(workspaceSettings.copilotHover === "default" && await telemetry.isFlightEnabled("CppCopilotHoverDisabled"))) {
// Either disabled by the user or by the flight.
return undefined;
}
// Ensure the user has access to Copilot.
const model = await this.getCachedChatModel();
if (!model) {
return undefined;
}
const newHover = this.isNewHover(document, position);
if (newHover) {
this.reset();
}
// Wait for the main hover provider to finish and confirm it has content.
const hoverProvider = this.client.getHoverProvider();
if (!await hoverProvider?.contentReady) {
return undefined;
}
if (token.isCancellationRequested) {
throw new vscode.CancellationError();
}
this.currentCancellationToken = token;
if (!newHover) {
if (this.ready) {
const contentMarkdown = new vscode.MarkdownString(`$(sparkle) Copilot\n\n${this.content}`, true);
return new vscode.Hover(contentMarkdown);
}
if (this.waiting) {
const loadingMarkdown = new vscode.MarkdownString("$(sparkle) $(loading~spin)", true);
return new vscode.Hover(loadingMarkdown);
}
}
this.currentDocument = document;
this.currentPosition = position;
const commandString = "$(sparkle) [" + localize("generate.copilot.description", "Generate Copilot summary") + "](command:C_Cpp.ShowCopilotHover \"" + localize("copilot.disclaimer", "AI-generated content may be incorrect.") + "\")";
const commandMarkdown = new vscode.MarkdownString(commandString);
commandMarkdown.supportThemeIcons = true;
commandMarkdown.isTrusted = { enabledCommands: ["C_Cpp.ShowCopilotHover"] };
return new vscode.Hover(commandMarkdown);
}
public showWaiting(): void {
this.waiting = true;
}
public showContent(content: string): void {
this.ready = true;
this.content = content;
}
public getCurrentHoverDocument(): vscode.TextDocument | undefined {
return this.currentDocument;
}
public getCurrentHoverPosition(): vscode.Position | undefined {
return this.currentPosition;
}
public getCurrentHoverCancellationToken(): vscode.CancellationToken | undefined {
return this.currentCancellationToken;
}
public async getRequestInfo(document: vscode.TextDocument, position: vscode.Position): Promise<GetCopilotHoverInfoResult> {
let response: GetCopilotHoverInfoResult;
const params: GetCopilotHoverInfoParams = {
textDocument: { uri: document.uri.toString() },
position: Position.create(position.line, position.character)
};
await this.client.ready;
if (this.currentCancellationToken?.isCancellationRequested) {
throw new vscode.CancellationError();
}
try {
response = await this.client.languageClient.sendRequest(GetCopilotHoverInfoRequest, params, this.currentCancellationToken);
} catch (e: any) {
if (e instanceof ResponseError && (e.code === RequestCancelled || e.code === ServerCancelled)) {
throw new vscode.CancellationError();
}
throw e;
}
return response;
}
public isCancelled(document: vscode.TextDocument, position: vscode.Position): boolean {
if (this.cancelled && this.cancelledDocument === document && this.cancelledPosition === position) {
// Cancellation is being acknowledged.
this.cancelled = false;
this.cancelledDocument = undefined;
this.cancelledPosition = undefined;
return true;
}
return false;
}
public reset(): void {
// If there was a previous call, cancel it.
if (this.waiting) {
this.cancelled = true;
this.cancelledDocument = this.currentDocument;
this.cancelledPosition = this.currentPosition;
}
this.waiting = false;
this.ready = false;
this.content = undefined;
this.currentDocument = undefined;
this.currentPosition = undefined;
this.currentCancellationToken = undefined;
}
public isNewHover(document: vscode.TextDocument, position: vscode.Position): boolean {
return !(this.currentDocument === document && this.currentPosition?.line === position.line && (this.currentPosition?.character === position.character || this.currentPosition?.character === position.character - 1));
}
}