Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for copilot-generated summaries in quick info. (On-the-fly docs) #12552

Open
wants to merge 40 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
0eac8bf
initial on-the-fly docs implementation for vscode
spebl Aug 5, 2024
93d7bb0
merge from main
spebl Aug 5, 2024
2667ec5
add localization support
spebl Aug 6, 2024
fb310c8
add support for icons in hover
spebl Aug 7, 2024
433f22d
add support for feature flag control
spebl Aug 7, 2024
7ec62d9
add setting and strings
spebl Aug 7, 2024
7a41841
fix settings when copilot models load later and fix showing copilot w…
spebl Aug 8, 2024
db42258
'otf docs' -> 'copilot hover' in naming conventions and strings. fixe…
spebl Aug 14, 2024
c73a589
fix spacing
spebl Aug 14, 2024
aa6779c
merge from main
spebl Aug 14, 2024
28390f1
reset vscode version
spebl Aug 14, 2024
3d5b7db
merge from main
spebl Aug 26, 2024
bd1eb43
merge from main
spebl Sep 3, 2024
d9c74c3
merge from main
spebl Sep 10, 2024
c31c4ab
merge from main
spebl Sep 12, 2024
9742465
fix formatting
spebl Sep 24, 2024
3bb4f1f
merge from main
spebl Sep 24, 2024
1cf0785
merge from main
spebl Sep 25, 2024
6076ca9
swap to using new copilot hover provider as to not interfere with exi…
spebl Sep 28, 2024
fd7095d
Add RAI disclaimers
benmcmorran Oct 9, 2024
9e1a547
merge from vscode
spebl Oct 10, 2024
d6a340f
merge from upstream
spebl Oct 10, 2024
f8cdde6
Copilot summary should now only show up when there is already hover c…
spebl Oct 11, 2024
713f430
Merge branch 'main' into dev/spebl/otfdocs
spebl Oct 11, 2024
10fb3cf
move AI inaccuracy warning to hover tooltip, add sparkle to load, che…
spebl Oct 11, 2024
3a0b8d8
prompt user to reload workspace when changing copilot hover option
spebl Oct 11, 2024
1be1fcc
merge from upstream
spebl Oct 11, 2024
ceb9f8e
merge from main
spebl Oct 18, 2024
9376135
merge from main
spebl Oct 21, 2024
ba5f149
merge from main
spebl Oct 22, 2024
8707994
Merge branch 'main' into dev/spebl/otfdocs
spebl Oct 22, 2024
1b37fd1
track and pass cancellation token + fix copilot hover showing up befo…
spebl Oct 24, 2024
f8fc500
Merge branch 'dev/spebl/otfdocs' of https://github.com/Microsoft/vsco…
spebl Oct 24, 2024
223d52b
better handling of intentional cancellation by user
spebl Oct 28, 2024
c055ce2
ensure tokens and cancellation are all in sync between copilot hover …
spebl Oct 28, 2024
3af533d
Merge branch 'main' into dev/spebl/otfdocs
spebl Oct 29, 2024
ad991c6
Merge branch 'main' into dev/spebl/otfdocs
spebl Oct 30, 2024
76000c7
swap to use same params for copilot hover info as text document posit…
spebl Nov 13, 2024
0fc52ed
Merge branch 'main' of https://github.com/Microsoft/vscode-cpptools i…
spebl Nov 13, 2024
1788813
Merge branch 'dev/spebl/otfdocs' of https://github.com/Microsoft/vsco…
spebl Nov 13, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion Extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
},
"license": "SEE LICENSE IN LICENSE.txt",
"engines": {
"vscode": "^1.67.0"
"vscode": "^1.90.0"
spebl marked this conversation as resolved.
Show resolved Hide resolved
},
"bugs": {
"url": "https://github.com/Microsoft/vscode-cpptools/issues",
Expand Down Expand Up @@ -3286,6 +3286,17 @@
"default": false,
"markdownDescription": "%c_cpp.configuration.addNodeAddonIncludePaths.markdownDescription%",
"scope": "application"
},
"C_Cpp.onTheFlyDocsEnabled": {
spebl marked this conversation as resolved.
Show resolved Hide resolved
"type": "string",
"enum": [
"default",
"enabled",
"disabled"
],
"default": "default",
"markdownDescription": "%c_cpp.configuration.otfDocsEnabled.markdownDescription%",
"scope": "window"
}
}
}
Expand Down
6 changes: 6 additions & 0 deletions Extension/package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,12 @@
"Markdown text between `` should not be translated or localized (they represent literal text) and the capitalization, spacing, and punctuation (including the ``) should not be altered."
]
},
"c_cpp.configuration.otfDocsEnabled.markdownDescription": {
"message": "If `enabled`, the Hover tooltip will display an option to generate a summary of the symbol with copilot. If `disabled`, the option will not be displayed.",
spebl marked this conversation as resolved.
Show resolved Hide resolved
spebl marked this conversation as resolved.
Show resolved Hide resolved
"comment": [
"Markdown text between `` should not be translated or localized (they represent literal text) and the capitalization, spacing, and punctuation (including the ``) should not be altered."
]
},
"c_cpp.configuration.renameRequiresIdentifier.markdownDescription": {
"message": "If `true`, 'Rename Symbol' will require a valid C/C++ identifier.",
"comment": [
Expand Down
45 changes: 42 additions & 3 deletions Extension/src/LanguageServer/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,21 @@ interface GetIncludesResult
includedFiles: string[];
}

interface ShowOTFDocsParams
{
content: string;
}

interface ShowOTFDocsResult
{
hoverPos: Position;
}

interface GetOTFDocsInfoResult
{
content: string;
}

// Requests
const PreInitializationRequest: RequestType<void, string, void> = new RequestType<void, string, void>('cpptools/preinitialize');
const InitializationRequest: RequestType<CppInitializationParams, void, void> = new RequestType<CppInitializationParams, void, void>('cpptools/initialize');
Expand All @@ -562,6 +577,8 @@ const GoToDirectiveInGroupRequest: RequestType<GoToDirectiveInGroupParams, Posit
const GenerateDoxygenCommentRequest: RequestType<GenerateDoxygenCommentParams, GenerateDoxygenCommentResult | undefined, void> = new RequestType<GenerateDoxygenCommentParams, GenerateDoxygenCommentResult, void>('cpptools/generateDoxygenComment');
const ChangeCppPropertiesRequest: RequestType<CppPropertiesParams, void, void> = new RequestType<CppPropertiesParams, void, void>('cpptools/didChangeCppProperties');
const IncludesRequest: RequestType<GetIncludesParams, GetIncludesResult, void> = new RequestType<GetIncludesParams, GetIncludesResult, void>('cpptools/getIncludes');
const GetOTFDocsInfoRequest: RequestType<void, GetOTFDocsInfoResult, void> = new RequestType<void, GetOTFDocsInfoResult, void>('cpptools/getOTFDocsInfo');
const ShowOTFDocsRequest: RequestType<ShowOTFDocsParams, ShowOTFDocsResult, void> = new RequestType<ShowOTFDocsParams, ShowOTFDocsResult, void>('cpptools/showOTFDocs');

// Notifications to the server
const DidOpenNotification: NotificationType<DidOpenTextDocumentParams> = new NotificationType<DidOpenTextDocumentParams>('textDocument/didOpen');
Expand Down Expand Up @@ -792,6 +809,8 @@ export interface Client {
setShowConfigureIntelliSenseButton(show: boolean): void;
addTrustedCompiler(path: string): Promise<void>;
getIncludes(maxDepth: number): Promise<GetIncludesResult>;
showOTFDocs(content: string): Promise<ShowOTFDocsResult>;
getOTFDocsInfo(): Promise<GetOTFDocsInfoResult>;
}

export function createClient(workspaceFolder?: vscode.WorkspaceFolder): Client {
Expand Down Expand Up @@ -1446,7 +1465,7 @@ export class DefaultClient implements Client {
return workspaceFolderSettingsParams;
}

private getAllSettings(): SettingsParams {
private async getAllSettings(): Promise<SettingsParams> {
const workspaceSettings: CppSettings = new CppSettings();
const workspaceOtherSettings: OtherSettings = new OtherSettings();
const workspaceFolderSettingsParams: WorkspaceFolderSettingsParams[] = this.getAllWorkspaceFolderSettings();
Expand All @@ -1472,6 +1491,7 @@ export class DefaultClient implements Client {
codeAnalysisMaxConcurrentThreads: workspaceSettings.codeAnalysisMaxConcurrentThreads,
codeAnalysisMaxMemory: workspaceSettings.codeAnalysisMaxMemory,
codeAnalysisUpdateDelay: workspaceSettings.codeAnalysisUpdateDelay,
otfDocsEnabled: await workspaceSettings.otfDocsEnabled,
workspaceFolderSettings: workspaceFolderSettingsParams
};
}
Expand Down Expand Up @@ -1541,7 +1561,7 @@ export class DefaultClient implements Client {
resetDatabase: resetDatabase,
edgeMessagesDirectory: path.join(util.getExtensionFilePath("bin"), "messages", getLocaleId()),
localizedStrings: localizedStrings,
settings: this.getAllSettings()
settings: await this.getAllSettings()
spebl marked this conversation as resolved.
Show resolved Hide resolved
};

this.loggingLevel = util.getNumericLoggingLevel(cppInitializationParams.settings.loggingLevel);
Expand Down Expand Up @@ -1582,6 +1602,12 @@ export class DefaultClient implements Client {
// We manually restart the language server so tell the LanguageClient not to do it automatically for us.
return { action: CloseAction.DoNotRestart, message };
}
},
markdown: {
isTrusted: true
// TODO: support for icons in markdown is not yet in the released version of vscode-languageclient.
// Based on PR (https://github.com/microsoft/vscode-languageserver-node/pull/1504)
//supportThemeIcons: true
}

// TODO: should I set the output channel? Does this sort output between servers?
Expand All @@ -1607,7 +1633,7 @@ export class DefaultClient implements Client {
public async sendDidChangeSettings(): Promise<void> {
// Send settings json to native side
await this.ready;
await this.languageClient.sendNotification(DidChangeSettingsNotification, this.getAllSettings());
await this.languageClient.sendNotification(DidChangeSettingsNotification, await this.getAllSettings());
}

public async onDidChangeSettings(_event: vscode.ConfigurationChangeEvent): Promise<Record<string, string>> {
Expand Down Expand Up @@ -3978,6 +4004,17 @@ export class DefaultClient implements Client {
compilerDefaults = await this.requestCompiler(path);
DebugConfigurationProvider.ClearDetectedBuildTasks();
}

public async showOTFDocs(content: string): Promise<ShowOTFDocsResult> {
const params: ShowOTFDocsParams = {content: content};
await this.ready;
return this.languageClient.sendRequest(ShowOTFDocsRequest, params);
}

public async getOTFDocsInfo(): Promise<GetOTFDocsInfoResult> {
await this.ready;
return this.languageClient.sendRequest(GetOTFDocsInfoRequest, null);
}
}

function getLanguageServerFileName(): string {
Expand Down Expand Up @@ -4090,4 +4127,6 @@ class NullClient implements Client {
setShowConfigureIntelliSenseButton(show: boolean): void { }
addTrustedCompiler(path: string): Promise<void> { return Promise.resolve(); }
getIncludes(): Promise<GetIncludesResult> { return Promise.resolve({} as GetIncludesResult); }
showOTFDocs(content: string): Promise<ShowOTFDocsResult> { return Promise.resolve({} as ShowOTFDocsResult); }
getOTFDocsInfo(): Promise<GetOTFDocsInfoResult> { return Promise.resolve({} as GetOTFDocsInfoResult); }
}
65 changes: 65 additions & 0 deletions Extension/src/LanguageServer/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { CodeActionDiagnosticInfo, CodeAnalysisDiagnosticIdentifiersAndUri, code
import { CppBuildTaskProvider } from './cppBuildTaskProvider';
import { getCustomConfigProviders } from './customProviders';
import { getLanguageConfig } from './languageConfig';
import { getLocaleId } from './localization';
import { PersistentState } from './persistentState';
import { NodeType, TreeNode } from './referencesModel';
import { CppSettings } from './settings';
Expand Down Expand Up @@ -404,6 +405,7 @@ export function registerCommands(enabled: boolean): void {
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ExtractToMemberFunction', enabled ? () => onExtractToFunction(false, true) : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ExpandSelection', enabled ? (r: Range) => onExpandSelection(r) : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.getIncludes', enabled ? (maxDepth: number) => getIncludes(maxDepth) : () => Promise.resolve()));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.OTFDocs', enabled ? onOTFDocs : onDisabledCommand));
spebl marked this conversation as resolved.
Show resolved Hide resolved
}

function onDisabledCommand() {
Expand Down Expand Up @@ -1379,3 +1381,66 @@ export async function getIncludes(maxDepth: number): Promise<any> {
const includes = await clients.ActiveClient.getIncludes(maxDepth);
return includes;
}

async function onOTFDocs(): Promise<void> {
const response = await clients.ActiveClient.getOTFDocsInfo();
spebl marked this conversation as resolved.
Show resolved Hide resolved

// Ensure the content is valid before proceeding.
const request = response.content;

if (request.length === 0) {
return;
}

const locale = getLocaleId();

const messages = [
vscode.LanguageModelChatMessage
.User(request + locale)];

const [model] = await vscode.lm.selectChatModels({
vendor: 'copilot',
family: 'gpt-4'
spebl marked this conversation as resolved.
Show resolved Hide resolved
});

let chatResponse: vscode.LanguageModelChatResponse | undefined;
try {
chatResponse = await model.sendRequest(
messages,
{},
new vscode.CancellationTokenSource().token
);
} catch (err) {
if (err instanceof vscode.LanguageModelError) {
console.log(err.message, err.code, err.cause);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure what standard practice is in cpptools, but should we be sending some error telemetry here too?

} else {
throw err;
}
return;
}

let content: string = '';

try {
for await (const fragment of chatResponse.text) {
content += fragment;
}
} catch (err) {
return;
}

const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}

// Prepare the client to show the content on next hover.
const result = await clients.ActiveClient.showOTFDocs(content);
// Make sure the editor has focus.
await vscode.commands.executeCommand('workbench.action.focusActiveEditorGroup');
// Move the cursor to the position of the open hover.
editor.selection = new vscode.Selection(result.hoverPos.line, result.hoverPos.character, result.hoverPos.line, result.hoverPos.character);
// Trigger a hover event to show the new content. This is necessary because the content isn't updated if the hover isn't closed and then reopened.
// API proposal to update hover content: "editorHoverVerbosityLevel". (https://github.com/microsoft/vscode/issues/195394)
await vscode.commands.executeCommand('editor.action.showHover', { focus: 'noAutoFocus'});
}
11 changes: 10 additions & 1 deletion Extension/src/LanguageServer/protocolFilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,16 @@ export function createProtocolFilter(): Middleware {
provideHover: async (document, position, token, next: (document: any, position: any, token: any) => any) => clients.ActiveClient.enqueue(async () => {
const me: Client = clients.getClientFor(document.uri);
if (me.TrackedDocuments.has(document.uri.toString())) {
return next(document, position, token);
const result: Thenable<vscode.Hover> = next(document, position, token);
// Needed to support theme icons in markdown hover content until vscode-languageclient is updated.
return result.then((value: vscode.Hover) => {
value.contents.forEach((content) => {
if (content instanceof vscode.MarkdownString) {
content.supportThemeIcons = true;
}
});
return value;
});
}
return null;
}),
Expand Down
29 changes: 29 additions & 0 deletions Extension/src/LanguageServer/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import * as nls from 'vscode-nls';
import * as which from 'which';
import { getCachedClangFormatPath, getCachedClangTidyPath, getExtensionFilePath, setCachedClangFormatPath, setCachedClangTidyPath } from '../common';
import { isWindows } from '../constants';
import { isFlightEnabled } from '../telemetry';
import { DefaultClient, cachedEditorConfigLookups, cachedEditorConfigSettings, hasTrustedCompilerPaths } from './client';
import { clients } from './extension';
import { CommentPattern } from './languageConfig';
Expand Down Expand Up @@ -159,6 +160,7 @@ export interface SettingsParams {
codeAnalysisMaxMemory: number | null | undefined;
codeAnalysisUpdateDelay: number | undefined;
workspaceFolderSettings: WorkspaceFolderSettingsParams[];
otfDocsEnabled: boolean | undefined;
}

function getTarget(): vscode.ConfigurationTarget {
Expand Down Expand Up @@ -461,6 +463,33 @@ export class CppSettings extends Settings {
return super.Section.get<boolean>("inlayHints.referenceOperator.showSpace") === true;
}

public get otfDocsEnabled(): PromiseLike<boolean> {
// Check if the user has access to copilot.
return vscode.lm.selectChatModels({vendor: "copilot"}).then((models) => {
spebl marked this conversation as resolved.
Show resolved Hide resolved
// Check if the setting is explicitly set to enabled or disabled.
const setting = super.Section.get<string>("onTheFlyDocsEnabled");
spebl marked this conversation as resolved.
Show resolved Hide resolved

// If no models are returned, the user doesn't have access to copilot.
if (models.length === 0) {
// Register to update this setting if the user gains access to copilot.
vscode.lm.onDidChangeChatModels(() => {
clients.ActiveClient.sendDidChangeSettings();
});
return false;
}

if (setting === "enabled") {
return true;
}
if (setting === "disabled") {
return false;
}

// Check for the feature flag.
return isFlightEnabled("cpp.otfDocs");
spebl marked this conversation as resolved.
Show resolved Hide resolved
});
}

public get enhancedColorization(): boolean {
return super.Section.get<string>("enhancedColorization")?.toLowerCase() !== "disabled"
&& this.intelliSenseEngine === "default"
Expand Down
3 changes: 2 additions & 1 deletion Extension/src/nativeStrings.json
Original file line number Diff line number Diff line change
Expand Up @@ -478,5 +478,6 @@
"refactor_extract_reference_return_c_code": "The function would have to return a value by reference. C code cannot return references.",
"refactor_extract_xborder_jump": "Jumps between the selected code and the surrounding code are present.",
"refactor_extract_missing_return": "In the selected code, some control paths exit without setting the return value. This is supported only for scalar, numeric, and pointer return types.",
"expand_selection": "Expand selection (to enable 'Extract to function')"
"expand_selection": "Expand selection (to enable 'Extract to function')",
"otf_docs_link": "Generate Copilot summary"
}
4 changes: 4 additions & 0 deletions Extension/src/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ export async function isExperimentEnabled(experimentName: string): Promise<boole
if (new CppSettings().experimentalFeatures) {
return true;
}
return isFlightEnabled(experimentName);
}

export async function isFlightEnabled(experimentName: string): Promise<boolean> {
const experimentationService: IExperimentationService | undefined = await getExperimentationService();
const isEnabled: boolean | undefined = experimentationService?.getTreatmentVariable<boolean>("vscode", experimentName);
return isEnabled ?? false;
Expand Down
Loading