Skip to content

Implement context provider #7921

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
66 changes: 66 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@
"extensionDependencies": [
"ms-dotnettools.vscode-dotnet-runtime"
],
"dependencies": {
"dependencies": {
"@github/copilot-language-server": "1.256.0",
"@microsoft/servicehub-framework": "4.2.99-beta",
"@octokit/rest": "^20.0.1",
"@types/cross-spawn": "6.0.2",
Expand Down
168 changes: 112 additions & 56 deletions src/lsptoolshost/copilot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { CodeSnippet, ContextProviderApiV1 } from '@github/copilot-language-server';
import * as vscode from 'vscode';
import { CSharpExtensionId } from '../constants/csharpExtensionId';
import { CopilotRelatedDocumentsReport, CopilotRelatedDocumentsRequest } from './roslynProtocol';
import { RoslynLanguageServer } from './roslynLanguageServer';
import { UriConverter } from './uriConverter';
import { TextDocumentIdentifier } from 'vscode-languageserver-protocol';
import { getCSharpDevKit } from '../utils/getCSharpDevKit';

interface CopilotTrait {
name: string;
Expand All @@ -17,7 +18,7 @@ interface CopilotTrait {
promptTextOverride?: string;
}

interface CopilotRelatedFilesProviderRegistration {
interface CopilotAPIs {
registerRelatedFilesProvider(
providerId: { extensionId: string; languageId: string },
callback: (
Expand All @@ -26,74 +27,129 @@ interface CopilotRelatedFilesProviderRegistration {
cancellationToken?: vscode.CancellationToken
) => Promise<{ entries: vscode.Uri[]; traits?: CopilotTrait[] }>
): vscode.Disposable;
getContextProviderAPI(version: string): Promise<ContextProviderApiV1 | undefined>;
}

export function registerCopilotExtension(languageServer: RoslynLanguageServer, channel: vscode.LogOutputChannel) {
async function getCopilotAPIsAsync(): Promise<CopilotAPIs | undefined> {
const ext = vscode.extensions.getExtension('github.copilot');
if (!ext) {
channel.debug('GitHub Copilot extension not installed. Skip registeration of C# related files provider.');
return;
return undefined;
Copy link
Member

Choose a reason for hiding this comment

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

I would keep the log messages if possible (trace/debug only though)

}
ext.activate().then(() => {
const relatedAPI = ext.exports as CopilotRelatedFilesProviderRegistration | undefined;
if (!relatedAPI) {
channel.debug(
'Incompatible GitHub Copilot extension installed. Skip registeration of C# related files provider.'
);
return;
}

channel.debug('registration of C# related files provider for GitHub Copilot extension succeeded.');
if (!ext.isActive) {
try {
return await ext.activate();
} catch {
return undefined;
Copy link
Member

Choose a reason for hiding this comment

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

Is the catch necessary here? There is already a .catch in the caller which also logs the error.
If you're keeping this catch here, it definitely needs to log the error.

}
} else {
Copy link
Member

Choose a reason for hiding this comment

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

no need for the if else here. activate should no-op if already active

return ext.exports as CopilotAPIs | undefined;
Copy link
Member

Choose a reason for hiding this comment

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

guessing this fails if the interface definition doesn't match? e.g. the version of the extension doesn't have a getContextProviderAPI export?

}
}

const id = {
extensionId: CSharpExtensionId,
languageId: 'csharp',
};
function registerCopilotRelatedFilesProvider(
languageServer: RoslynLanguageServer,
copilotAPIs: CopilotAPIs,
channel: vscode.LogOutputChannel
): CopilotAPIs {
const id = {
extensionId: CSharpExtensionId,
languageId: 'csharp',
};

relatedAPI.registerRelatedFilesProvider(id, async (uri, _, token) => {
const buildResult = (
activeDocumentUri: vscode.Uri,
reports: CopilotRelatedDocumentsReport[],
builder: vscode.Uri[]
) => {
if (reports) {
for (const report of reports) {
if (report._vs_file_paths) {
for (const filePath of report._vs_file_paths) {
// The Roslyn related document service would return the active document as related file to itself
// if the code contains reference to the types defined in the same document. Skip it so the active file
// won't be used as additonal context.
const relatedUri = vscode.Uri.file(filePath);
if (relatedUri.fsPath !== activeDocumentUri.fsPath) {
builder.push(relatedUri);
}
copilotAPIs.registerRelatedFilesProvider(id, async (uri, _, token) => {
const buildResult = (
activeDocumentUri: vscode.Uri,
reports: CopilotRelatedDocumentsReport[],
builder: vscode.Uri[]
) => {
if (reports) {
for (const report of reports) {
if (report._vs_file_paths) {
for (const filePath of report._vs_file_paths) {
// The Roslyn related document service would return the active document as related file to itself
// if the code contains reference to the types defined in the same document. Skip it so the active file
// won't be used as additonal context.
const relatedUri = vscode.Uri.file(filePath);
if (relatedUri.fsPath !== activeDocumentUri.fsPath) {
builder.push(relatedUri);
}
}
}
}
};
const relatedFiles: vscode.Uri[] = [];
const uriString = UriConverter.serialize(uri);
const textDocument = TextDocumentIdentifier.create(uriString);
try {
await languageServer.sendRequestWithProgress(
CopilotRelatedDocumentsRequest.type,
{
_vs_textDocument: textDocument,
position: {
line: 0,
character: 0,
},
}
};
const relatedFiles: vscode.Uri[] = [];
const uriString = UriConverter.serialize(uri);
const textDocument = TextDocumentIdentifier.create(uriString);
try {
await languageServer.sendRequestWithProgress(
CopilotRelatedDocumentsRequest.type,
{
_vs_textDocument: textDocument,
position: {
line: 0,
character: 0,
},
async (r) => buildResult(uri, r, relatedFiles),
token
},
async (r) => buildResult(uri, r, relatedFiles),
token
);
} catch (e) {
if (e instanceof Error) {
channel.appendLine(e.message);
}
}
return { entries: relatedFiles };
});

channel.debug('registration of C# related files provider for GitHub Copilot extension succeeded.');
return copilotAPIs;
}

async function registerCopilotContextProvider(
languageServer: RoslynLanguageServer,
copilotAPIs: CopilotAPIs,
channel: vscode.LogOutputChannel
) {
// Only register the context provider if the C# DevKit extension is available.
const csharpDevkitExtension = getCSharpDevKit();
if (!csharpDevkitExtension) {
return;
}

const contextAPI = await copilotAPIs.getContextProviderAPI('v1');
if (!contextAPI) {
channel.debug('Failed to get context provider API from GitHub Copilot extension.');
return;
}

contextAPI.registerContextProvider<CodeSnippet>({
id: 'csharpContextProvider',
selector: [{ language: 'csharp' }],
resolver: {
resolve: async (request, token) => {
return [{ uri: 'testUri', value: 'testValue', additionalUris: [] }];
Copy link
Member

Choose a reason for hiding this comment

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

assuming this is the part that will eventually call out to the server

},
},
});

channel.debug('registration of C# context provider for GitHub Copilot extension succeeded.');
}

export function registerCopilotExtension(languageServer: RoslynLanguageServer, channel: vscode.LogOutputChannel) {
getCopilotAPIsAsync()
.then(async (copilotAPIs) => {
if (!copilotAPIs) {
channel.debug(
'Failed activating GitHub Copilot extension. Skip registeration of C# Copilot providers.'
);
} catch (e) {
if (e instanceof Error) {
channel.appendLine(e.message);
}
return;
}
return { entries: relatedFiles };
registerCopilotRelatedFilesProvider(languageServer, copilotAPIs, channel);
await registerCopilotContextProvider(languageServer, copilotAPIs, channel);
})
.catch((error) => {
channel.debug('Failed registering C# Copilot providers. Error: ' + error);
});
});
}