From 9348e91f6f88f6132f1429d83578edc93764efd8 Mon Sep 17 00:00:00 2001 From: Alex Ross <38270282+alexr00@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:30:41 +0100 Subject: [PATCH] Move min supported GHE version and allow projects Fixes #8253 --- README.md | 2 + src/github/createPRViewProvider.ts | 12 +- src/github/credentials.ts | 64 ++++- src/github/folderRepositoryManager.ts | 14 +- src/github/githubRepository.ts | 39 ++- src/github/issueOverview.ts | 24 +- src/github/queriesLimited.gql | 32 ++- src/github/quickPicks.ts | 83 +++--- src/test/github/authIssuers.test.ts | 243 +++++++++++++++++- src/test/github/createPRViewProvider.test.ts | 41 +++ .../github/folderRepositoryManager.test.ts | 43 ++++ src/test/github/issueOverview.test.ts | 120 +++++++++ webviews/components/sidebar.tsx | 35 ++- webviews/editorWebview/test/overview.test.tsx | 37 +++ 14 files changed, 703 insertions(+), 86 deletions(-) diff --git a/README.md b/README.md index 65dca6d819..8148a8bc8b 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ There are several settings that can be used to configure the extension. VS Code 1.141 or later is required. If you use Insiders, keep it updated to the latest build. +GitHub Enterprise Server 3.15 or later is required. Upgrade to a version currently supported by GitHub. + Configure GHE.com and GitHub Enterprise Server instances using the built-in GitHub Authentication setting: ```json diff --git a/src/github/createPRViewProvider.ts b/src/github/createPRViewProvider.ts index 3c13cfb8b5..8c5db68efa 100644 --- a/src/github/createPRViewProvider.ts +++ b/src/github/createPRViewProvider.ts @@ -496,16 +496,18 @@ export abstract class BaseCreatePullRequestViewProvider((resolve) => { - getProjectFromQuickPick(this._folderRepositoryManager, githubRepo, this.projects, async (projects) => { + try { + const projects = await getProjectFromQuickPick(this._folderRepositoryManager, githubRepo, this.projects); + if (projects) { this.projects = projects; this._postMessage({ command: 'set-projects', params: { projects: this.projects } }); - resolve(); - }); - }); + } + } catch (error) { + vscode.window.showErrorMessage(vscode.l10n.t('Failed to add project: {0}', formatError(error))); + } } private labels: DisplayLabel[] = []; diff --git a/src/github/credentials.ts b/src/github/credentials.ts index 8d41071f82..16473ceb51 100644 --- a/src/github/credentials.ts +++ b/src/github/credentials.ts @@ -18,6 +18,7 @@ import { Disposable } from '../common/lifecycle'; import Logger from '../common/logger'; import * as PersistentState from '../common/persistentState'; import { ITelemetry } from '../common/telemetry'; +import { formatError, isObject } from '../common/utils'; import { EXTENSION_ID } from '../constants'; import { agent } from '../env/node/net'; @@ -142,6 +143,7 @@ export class CredentialStore extends Disposable { private _handlingAuthError: Map> = new Map(); private _lastAuthErrorHandledAt: Map = new Map(); private _currentUserRequests: WeakMap> = new WeakMap(); + private _warnedEnterpriseServers = new Set(); private _hasOfferedAccountPreferences: boolean = false; // Cooldown long enough to absorb retries from in-flight requests that were // issued with the now-invalid token, but short enough that a token that @@ -638,17 +640,17 @@ export class CredentialStore extends Disposable { public async getIsEmu(authProviderId: AuthProvider): Promise { const github = this.getHub(authProviderId); - await this.ensureCurrentUser(github); + await this.ensureCurrentUser(github, authProviderId); return !!github?.isEmu; } public async getCurrentUser(authProviderId: AuthProvider): Promise { const github = this.getHub(authProviderId); - await this.ensureCurrentUser(github); + await this.ensureCurrentUser(github, authProviderId); return github?.currentUser!; } - private ensureCurrentUser(github: GitHub | undefined): Promise { + private ensureCurrentUser(github: GitHub | undefined, authProviderId: AuthProvider): Promise { if (!github || (github.currentUser && github.isEmu !== undefined)) { return Promise.resolve(); } @@ -658,7 +660,7 @@ export class CredentialStore extends Disposable { return existingRequest; } - const request = this.setCurrentUser(github); + const request = this.setCurrentUser(github, authProviderId); this._currentUserRequests.set(github, request); const clearRequest = () => { if (this._currentUserRequests.get(github) === request) { @@ -669,11 +671,53 @@ export class CredentialStore extends Disposable { return request; } - private async setCurrentUser(github: GitHub): Promise { + private warnUnsupportedEnterpriseVersion(serverUri: vscode.Uri, version: string): void { + const match = /^(?:enterprise-server@)?(?\d+)\.(?\d+)(?:\.\d+)?(?:[-+][\w.-]+)?$/i.exec(version); + if (!match?.groups) { + Logger.warn(`Unable to parse GitHub Enterprise version: ${version}`, CredentialStore.ID); + return; + } + + const major = Number(match.groups.major); + const minor = Number(match.groups.minor); + const server = serverUri.toString(); + if ((major > 3 || (major === 3 && minor >= 15)) || this._warnedEnterpriseServers.has(server)) { + return; + } + + this._warnedEnterpriseServers.add(server); + void vscode.window.showWarningMessage(vscode.l10n.t( + 'GitHub Enterprise Server {0} at {1} is not supported by GitHub Pull Requests. Upgrade to a currently supported version (3.15 or later).', + version.replace(/^enterprise-server@/i, ''), + server, + )); + } + + private async checkEnterpriseVersionFromMeta(github: GitHub): Promise { + try { + const result = await github.octokit.call(github.octokit.api.meta.get, {}); + const data: unknown = result.data; + if (isObject(data) && typeof data.installed_version === 'string') { + this.warnUnsupportedEnterpriseVersion(github.serverUri, data.installed_version); + } + } catch (error) { + Logger.warn(`Unable to determine GitHub Enterprise version: ${formatError(error)}`, CredentialStore.ID); + } + } + + private async setCurrentUser(github: GitHub, authProviderId: AuthProvider): Promise { Logger.debug('Getting current user', CredentialStore.ID); try { const result = await github.octokit.call(github.octokit.api.users.getAuthenticated, {}); Logger.debug(`Got current user ${result.data.login}`, CredentialStore.ID); + const enterpriseVersion = result.headers?.['x-github-enterprise-version']; + if (isEnterprise(authProviderId)) { + if (typeof enterpriseVersion === 'string') { + this.warnUnsupportedEnterpriseVersion(github.serverUri, enterpriseVersion); + } else if (!isGheHost(github.serverUri)) { + void this.checkEnterpriseVersionFromMeta(github); + } + } github.currentUser = convertRESTUserToAccount(result.data); github.isEmu = result.data.plan?.name === 'emu_user'; } catch (e) { @@ -707,8 +751,7 @@ export class CredentialStore extends Disposable { const serverUri = getSessionGitHubUri(authProviderId, session); let baseUrl = 'https://api.github.com'; const enterpriseServerUri = isEnterprise(authProviderId) ? serverUri : undefined; - const hostname = new URL(serverUri.toString()).hostname.toLowerCase(); - const isGhe = hostname === 'ghe.com' || hostname.endsWith('.ghe.com'); + const isGhe = isGheHost(serverUri); Logger.appendLine(`Creating hub for ${isEnterprise(authProviderId) ? 'enterprise' : '.com'}`, CredentialStore.ID); if (enterpriseServerUri) { Logger.appendLine(`Enterprise server authority ${enterpriseServerUri.authority}`, CredentialStore.ID); @@ -759,7 +802,7 @@ export class CredentialStore extends Disposable { octokit: new LoggingOctokit(octokit, rateLogger), graphql: new LoggingApolloClient(graphql, rateLogger), }; - void this.ensureCurrentUser(github).catch(() => undefined); + void this.ensureCurrentUser(github, authProviderId).catch(() => undefined); return github; } } @@ -779,6 +822,11 @@ const link = (url: string, token: string) => }), ); +function isGheHost(serverUri: vscode.Uri): boolean { + const hostname = new URL(serverUri.toString()).hostname.toLowerCase(); + return hostname === 'ghe.com' || hostname.endsWith('.ghe.com'); +} + function getGitHubSuffix(authProviderId: AuthProvider) { return !isEnterprise(authProviderId) ? '' : ' Enterprise'; } diff --git a/src/github/folderRepositoryManager.ts b/src/github/folderRepositoryManager.ts index 7c728e0397..3a88c3e92f 100644 --- a/src/github/folderRepositoryManager.ts +++ b/src/github/folderRepositoryManager.ts @@ -1019,8 +1019,18 @@ export class FolderRepositoryManager extends Disposable { async getAllProjects(githubRepository: GitHubRepository, clearOrgCache?: boolean): Promise { const isInOrganization = !!(await githubRepository.getMetadata()).organization; - const [repoProjects, orgProjects] = (await Promise.all([githubRepository.getProjects(), (isInOrganization ? this.getOrgProjects(clearOrgCache) : undefined)])); - return [...(repoProjects ?? []), ...(orgProjects ? orgProjects[githubRepository.remote.remoteName] : [])]; + const projectsAvailable = await githubRepository.canGetProjectsNow(); + const repoProjectsPromise = githubRepository.getProjects(); + const orgProjectsPromise = !isInOrganization ? undefined + : (projectsAvailable + ? this.getOrgProjects(clearOrgCache) + : repoProjectsPromise.then(async () => ( + (await githubRepository.canGetProjectsNow()) + ? this.getOrgProjects(true) + : undefined + ))); + const [repoProjects, orgProjects] = await Promise.all([repoProjectsPromise, orgProjectsPromise]); + return [...(repoProjects ?? []), ...(orgProjects?.[githubRepository.remote.remoteName] ?? [])]; } async getOrgTeamsCount(repository: GitHubRepository): Promise { diff --git a/src/github/githubRepository.ts b/src/github/githubRepository.ts index d8c8fa9a99..77fc305dc8 100644 --- a/src/github/githubRepository.ts +++ b/src/github/githubRepository.ts @@ -113,6 +113,14 @@ export const PULL_REQUEST_PAGE_SIZE = 20; const GRAPHQL_COMPONENT_ID = 'GraphQL'; +// The GraphQL loader adds a document for each named operation. +const projectQueries = extraSchema.default as DocumentNode & { + GetRepoProjects: DocumentNode; + GetOrgProjects: DocumentNode; + AddPullRequestToProject: DocumentNode; + RemovePullRequestFromProject: DocumentNode; +}; + export interface ItemsData { items: T[]; hasMorePages: boolean; @@ -450,6 +458,28 @@ export class GitHubRepository extends Disposable { } } + private projectVariables(document: DocumentNode, variables: OperationVariables | undefined): OperationVariables | undefined { + const operation = document.definitions.find(definition => definition.kind === 'OperationDefinition'); + if (operation?.variableDefinitions?.some(variable => variable.variable.name.value === 'includeProjects')) { + return { ...variables, includeProjects: this._credentialStore.areScopesExtra(this.remote.authProviderId) }; + } + return variables; + } + + private useLimitedSchema(): void { + this._areQueriesLimited = true; + const schema = mergeQuerySchemaWithShared(sharedSchema.default, limitedSchema.default); + this._queriesSchema = this._credentialStore.areScopesExtra(this.remote.authProviderId) + ? { + ...schema, + GetRepoProjects: projectQueries.GetRepoProjects, + GetOrgProjects: projectQueries.GetOrgProjects, + AddPullRequestToProject: projectQueries.AddPullRequestToProject, + RemovePullRequestFromProject: projectQueries.RemovePullRequestFromProject, + } + : schema; + } + query = async (query: QueryOptions, ignoreSamlErrors: boolean = false, legacyFallback?: { query: DocumentNode, variables: OperationVariables }, allowLimitedFallback: boolean = true): Promise> => { const gql = this.authMatchesServer && this.hub && this.hub.graphql; if (!gql) { @@ -464,6 +494,7 @@ export class GitHubRepository extends Disposable { return empty; } + query.variables = this.projectVariables(query.query, query.variables); let rsp; try { rsp = await gql.query(query); @@ -480,9 +511,9 @@ export class GitHubRepository extends Disposable { if (allowLimitedFallback && gqlErrors && gqlErrors.length && (gqlErrors.some(error => error.extensions?.code === 'undefinedField')) && !this._areQueriesLimited) { // We're running against a GitHub server that doesn't support the query we're trying to run. // Switch to the limited schema and try again. - this._areQueriesLimited = true; - this._queriesSchema = mergeQuerySchemaWithShared(sharedSchema.default, limitedSchema.default); + this.useLimitedSchema(); query.query = this.schema[(query.query.definitions[0] as { name: { value: string } }).name.value]; + query.variables = this.projectVariables(query.query, query.variables); rsp = await gql.query(query); } else if (ignoreSamlErrors && isSamlError(e)) { // Some queries just result in SAML errors. @@ -509,6 +540,7 @@ export class GitHubRepository extends Disposable { return empty; } + mutation.variables = this.projectVariables(mutation.mutation, mutation.variables); let rsp: FetchResult; try { rsp = await gql.mutate(mutation); @@ -624,8 +656,7 @@ export class GitHubRepository extends Disposable { // A session event may have already refreshed the hub before ensure(). if (this._hub) { if (this._areQueriesLimited || this._credentialStore.areScopesOld(this.remote.authProviderId) || (this.remote.authProviderId === AuthProvider.githubEnterprise)) { - this._areQueriesLimited = true; - this._queriesSchema = mergeQuerySchemaWithShared(sharedSchema.default, limitedSchema.default); + this.useLimitedSchema(); } else { if (this._credentialStore.areScopesExtra(this.remote.authProviderId)) { this._queriesSchema = mergeQuerySchemaWithShared(sharedSchema.default, extraSchema.default); diff --git a/src/github/issueOverview.ts b/src/github/issueOverview.ts index c537a045dc..75efee67a3 100644 --- a/src/github/issueOverview.ts +++ b/src/github/issueOverview.ts @@ -1015,7 +1015,29 @@ export class IssueOverviewPanel extends W } private async changeProjects(message: IRequestMessage): Promise { - return getProjectFromQuickPick(this._folderRepositoryManager, this._item.githubRepository, this._item.item.projectItems?.map(item => item.project), (project) => this.updateProjects(project, message)); + const repository = this._item.githubRepository; + try { + if (!(await repository.canGetProjectsNow())) { + await repository.ensureAdditionalScopes(); + if (!(await repository.canGetProjectsNow())) { + return this._replyMessage(message, { projectItems: this._item.item.projectItems }); + } + const refreshed = await this.resolveModel(this._identity); + if (!refreshed) { + throw new Error(vscode.l10n.t('Unable to load current project associations.')); + } + this._item = refreshed; + } + const projects = await getProjectFromQuickPick(this._folderRepositoryManager, this._item.githubRepository, this._item.item.projectItems?.map(item => item.project)); + if (!projects) { + return this._replyMessage(message, { projectItems: this._item.item.projectItems }); + } + return await this.updateProjects(projects, message); + } catch (error) { + const errorMessage = vscode.l10n.t('Unable to load or update projects: {0}', formatError(error)); + vscode.window.showErrorMessage(errorMessage); + return this._throwError(message, errorMessage); + } } private async updateProjects(projects: IProject[] | undefined, message: IRequestMessage) { diff --git a/src/github/queriesLimited.gql b/src/github/queriesLimited.gql index 247397191a..601bf14fb9 100644 --- a/src/github/queriesLimited.gql +++ b/src/github/queriesLimited.gql @@ -100,6 +100,15 @@ fragment IssueBase on Issue { } url } + projectItems(first: 100) @include(if: $includeProjects) { + nodes { + id + project { + title + id + } + } + } } fragment IssueFragment on Issue { @@ -171,6 +180,15 @@ fragment PullRequestFragment on PullRequest { totalCount } ...Reactable + projectItems(first: 100) @include(if: $includeProjects) { + nodes { + id + project { + title + id + } + } + } comments(first: 1) { totalCount } @@ -239,7 +257,7 @@ fragment PullRequestFragment on PullRequest { } } -query Issue($owner: String!, $name: String!, $number: Int!) { +query Issue($owner: String!, $name: String!, $number: Int!, $includeProjects: Boolean! = false) { repository(owner: $owner, name: $name) { issue(number: $number) { ...IssueFragment @@ -250,7 +268,7 @@ query Issue($owner: String!, $name: String!, $number: Int!) { } } -query IssueWithComments($owner: String!, $name: String!, $number: Int!) { +query IssueWithComments($owner: String!, $name: String!, $number: Int!, $includeProjects: Boolean! = false) { repository(owner: $owner, name: $name) { issue(number: $number) { ...IssueWithCommentsFragment @@ -261,7 +279,7 @@ query IssueWithComments($owner: String!, $name: String!, $number: Int!) { } } -query Issues($query: String!) { +query Issues($query: String!, $includeProjects: Boolean! = false) { search(first: 100, type: ISSUE, query: $query) { issueCount pageInfo { @@ -279,7 +297,7 @@ query Issues($query: String!) { } } -query PullRequest($owner: String!, $name: String!, $number: Int!) { +query PullRequest($owner: String!, $name: String!, $number: Int!, $includeProjects: Boolean! = false) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { ...PullRequestFragment @@ -290,7 +308,7 @@ query PullRequest($owner: String!, $name: String!, $number: Int!) { } } -query PullRequestForHead($owner: String!, $name: String!, $headRefName: String!) { +query PullRequestForHead($owner: String!, $name: String!, $headRefName: String!, $includeProjects: Boolean! = false) { repository(owner: $owner, name: $name) { openPullRequests: pullRequests(first: 3, headRefName: $headRefName, states: [OPEN], orderBy: { field: CREATED_AT, direction: DESC }) { nodes { @@ -655,7 +673,7 @@ query LatestIssueUpdates($owner: String!, $name: String!, $number: Int!, $since: } } -mutation CreatePullRequest($input: CreatePullRequestInput!) { +mutation CreatePullRequest($input: CreatePullRequestInput!, $includeProjects: Boolean! = false) { createPullRequest(input: $input) { pullRequest { ...PullRequestFragment @@ -663,7 +681,7 @@ mutation CreatePullRequest($input: CreatePullRequestInput!) { } } -mutation RevertPullRequest($input: RevertPullRequestInput!) { +mutation RevertPullRequest($input: RevertPullRequestInput!, $includeProjects: Boolean! = false) { revertPullRequest(input: $input) { revertPullRequest { ...PullRequestFragment diff --git a/src/github/quickPicks.ts b/src/github/quickPicks.ts index 52f681d4f4..972906dc38 100644 --- a/src/github/quickPicks.ts +++ b/src/github/quickPicks.ts @@ -18,7 +18,7 @@ import { COPILOT_REVIEWER, COPILOT_REVIEWER_ACCOUNT, COPILOT_SWE_AGENT } from '. import { emojify, ensureEmojis } from '../common/emoji'; import Logger from '../common/logger'; import { DataUri } from '../common/uri'; -import { formatError } from '../common/utils'; +import { asPromise, formatError } from '../common/utils'; import { RECENTLY_USED_BRANCHES, RecentlyUsedBranchesState } from '../extensionState'; export async function chooseItem( @@ -260,41 +260,47 @@ function isProjectQuickPickItem(x: vscode.QuickPickItem | ProjectQuickPickItem): return !!(x as ProjectQuickPickItem).id && !!(x as ProjectQuickPickItem).project; } -export async function getProjectFromQuickPick(folderRepoManager: FolderRepositoryManager, githubRepository: GitHubRepository, currentProjects: IProject[] | undefined, callback: (projects: IProject[]) => Promise): Promise { - try { - let selectedItems: vscode.QuickPickItem[] = []; - async function getProjectOptions(): Promise<(ProjectQuickPickItem | vscode.QuickPickItem)[]> { - const projects = await folderRepoManager.getAllProjects(githubRepository); - if (!projects || !projects.length) { - return [ - { - label: vscode.l10n.t('No projects created for this repository.'), - }, - ]; - } - - const projectItems: (ProjectQuickPickItem | vscode.QuickPickItem)[] = projects.map(result => { - const item = { - iconPath: new vscode.ThemeIcon('github-project'), - label: result.title, - id: result.id, - project: result - }; - if (currentProjects && currentProjects.find(project => project.id === result.id)) { - selectedItems.push(item); - } - return item; - }); - return projectItems; +export async function getProjectFromQuickPick(folderRepoManager: FolderRepositoryManager, githubRepository: GitHubRepository, currentProjects: IProject[] | undefined): Promise { + const selectedItems: vscode.QuickPickItem[] = []; + async function getProjectOptions(): Promise<(ProjectQuickPickItem | vscode.QuickPickItem)[]> { + const projects = await folderRepoManager.getAllProjects(githubRepository); + if (!projects || !projects.length) { + return [ + { + label: vscode.l10n.t('No projects created for this repository.'), + }, + ]; } - const quickPick = vscode.window.createQuickPick(); + return projects.map(result => { + const item = { + iconPath: new vscode.ThemeIcon('github-project'), + label: result.title, + id: result.id, + project: result + }; + if (currentProjects?.find(project => project.id === result.id)) { + selectedItems.push(item); + } + return item; + }); + } + + const quickPick = vscode.window.createQuickPick(); + try { quickPick.busy = true; quickPick.canSelectMany = true; quickPick.title = vscode.l10n.t('Set projects'); quickPick.ignoreFocusOut = true; + const hidePromise = asPromise(quickPick.onDidHide).then(() => undefined); quickPick.show(); - quickPick.items = await getProjectOptions(); + const projectOptionsPromise = getProjectOptions(); + const items = await Promise.race([projectOptionsPromise, hidePromise]); + if (!items) { + void projectOptionsPromise.catch(error => Logger.warn(`Loading projects after picker closed failed: ${formatError(error)}`, 'QuickPicks')); + return undefined; + } + quickPick.items = items; quickPick.ignoreFocusOut = false; if (quickPick.items.length === 1) { quickPick.canSelectMany = false; @@ -303,16 +309,15 @@ export async function getProjectFromQuickPick(folderRepoManager: FolderRepositor quickPick.busy = false; // Kick off a cache refresh - folderRepoManager.getOrgProjects(true); - quickPick.onDidAccept(async () => { - quickPick.hide(); - const projectsToAdd = quickPick.selectedItems.map(item => isProjectQuickPickItem(item) ? item.project : undefined).filter(project => project !== undefined) as IProject[]; - if (projectsToAdd) { - await callback(projectsToAdd); - } - }); - } catch (e) { - vscode.window.showErrorMessage(`Failed to add project: ${formatError(e)}`); + void Promise.resolve() + .then(() => githubRepository.canGetProjectsNow()) + .then(canGetProjects => canGetProjects ? folderRepoManager.getOrgProjects(true) : undefined) + .catch(error => Logger.warn(`Refreshing organization projects failed: ${formatError(error)}`, 'QuickPicks')); + const acceptPromise = asPromise(quickPick.onDidAccept).then(() => + quickPick.selectedItems.filter(isProjectQuickPickItem).map(item => item.project)); + return await Promise.race([acceptPromise, hidePromise]); + } finally { + quickPick.dispose(); } } diff --git a/src/test/github/authIssuers.test.ts b/src/test/github/authIssuers.test.ts index a8a927094a..974d52f460 100644 --- a/src/test/github/authIssuers.test.ts +++ b/src/test/github/authIssuers.test.ts @@ -4,20 +4,26 @@ *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; -import { gql } from 'apollo-boost'; +import { DocumentNode, gql, NetworkStatus } from 'apollo-boost'; import { Response } from 'cross-fetch'; +import { print } from 'graphql'; import { createSandbox, SinonSandbox, SinonStub } from 'sinon'; import * as vscode from 'vscode'; import { GitHubManager } from '../../authentication/githubServer'; import * as enterpriseConfiguration from '../../authentication/configuration'; import { AuthenticationError, AuthProvider, GitHubServerType } from '../../common/authentication'; +import Logger from '../../common/logger'; import { GitHubRemote, parseRemote } from '../../common/remote'; +import { isObject } from '../../common/utils'; import { GithubRemoteSourceProvider } from '../../gitExtensionIntegration'; import { CredentialStore, CredentialStoreSessionsChangeEvent, GitHub } from '../../github/credentials'; import { GitHubRepository } from '../../github/githubRepository'; -import { LoggingOctokit } from '../../github/loggingOctokit'; +import { IssueModel } from '../../github/issueModel'; +import { LoggingApolloClient, LoggingOctokit } from '../../github/loggingOctokit'; import { RepositoriesManager } from '../../github/repositoriesManager'; import * as utils from '../../github/utils'; +import { PullRequestBuilder as GraphQLPullRequestBuilder } from '../builders/graphql/pullRequestBuilder'; +import { RepositoryBuilder } from '../builders/rest/repoBuilder'; import { MockExtensionContext } from '../mocks/mockExtensionContext'; import { MockTelemetry } from '../mocks/mockTelemetry'; @@ -148,6 +154,239 @@ describe('authIssuers', function () { }); } + describe('Enterprise server version warning', function () { + for (const [version, unsupported] of [ + ['3.9.9', true], + ['3.14.9', true], + ['enterprise-server@3.14.1', true], + ['3.15.0', false], + ['enterprise-server@3.20.2', false], + ['4.0.0', false], + ['unknown', false], + [undefined, false], + ] as const) { + it(`${unsupported ? 'warns' : 'does not warn'} for ${version ?? 'a missing version header'}`, async function () { + const warning = sinon.stub(vscode.window, 'showWarningMessage').resolves(undefined); + apiCall.resolves({ + data: { login: 'octocat', node_id: 'user', html_url: `${hostB}/octocat`, avatar_url: '', type: 'User' }, + headers: version ? { 'x-github-enterprise-version': version } : {}, + }); + selected.set(AuthProvider.githubEnterprise, session(`${hostB}/login/oauth`)); + + await store.create({ silent: true }); + await store.getCurrentUser(AuthProvider.githubEnterprise); + + assert.strictEqual(warning.callCount, unsupported ? 1 : 0); + if (unsupported) { + assert.match(warning.firstCall.args[0], /GitHub Enterprise Server .*host-b\.example.*3\.15 or later/); + } + }); + } + + it('warns once per Enterprise server, including after an account refresh', async function () { + const warning = sinon.stub(vscode.window, 'showWarningMessage').resolves(undefined); + apiCall.resolves({ + data: { login: 'octocat', node_id: 'user', html_url: `${hostB}/octocat`, avatar_url: '', type: 'User' }, + headers: { 'x-github-enterprise-version': '3.14.0' }, + }); + selected.set(AuthProvider.githubEnterprise, session(`${hostB}/login/oauth`)); + await store.create({ silent: true }); + await store.getCurrentUser(AuthProvider.githubEnterprise); + await refreshSession(session(`${hostB}/login/oauth`, { accessToken: 'refreshed-token' })); + await store.getCurrentUser(AuthProvider.githubEnterprise); + await refreshSession(session(`${hostA}/login/oauth`)); + await store.getCurrentUser(AuthProvider.githubEnterprise); + + assert.strictEqual(warning.callCount, 2); + assert.match(warning.firstCall.args[0], /host-b\.example/); + assert.match(warning.secondCall.args[0], /host-a\.example/); + }); + + it('does not warn for a GitHub.com session', async function () { + const warning = sinon.stub(vscode.window, 'showWarningMessage').resolves(undefined); + apiCall.resolves({ + data: { login: 'octocat', node_id: 'user', html_url: 'https://github.com/octocat', avatar_url: '', type: 'User' }, + headers: { 'x-github-enterprise-version': '3.14.0' }, + }); + selected.set(AuthProvider.github, session()); + await store.create({ silent: true }); + await store.getCurrentUser(AuthProvider.github); + sinon.assert.notCalled(warning); + }); + + it('checks metadata when the Enterprise version header is not exposed', async function () { + const warning = sinon.stub(vscode.window, 'showWarningMessage').resolves(undefined); + apiCall.onFirstCall().resolves({ + data: { login: 'octocat', node_id: 'user', html_url: `${hostB}/octocat`, avatar_url: '', type: 'User' }, + headers: {}, + }); + apiCall.onSecondCall().resolves({ data: { installed_version: '3.14.2' } }); + selected.set(AuthProvider.githubEnterprise, session(`${hostB}/login/oauth`)); + + await store.create({ silent: true }); + await store.getCurrentUser(AuthProvider.githubEnterprise); + await new Promise(resolve => setImmediate(resolve)); + + sinon.assert.calledOnce(warning); + assert.match(warning.firstCall.args[0], /3\.14\.2.*3\.15 or later/); + }); + + it('keeps the user available if the Enterprise metadata request fails', async function () { + const warning = sinon.stub(Logger, 'warn'); + apiCall.onFirstCall().resolves({ + data: { login: 'octocat', node_id: 'user', html_url: `${hostB}/octocat`, avatar_url: '', type: 'User' }, + headers: {}, + }); + apiCall.onSecondCall().rejects(new Error('Metadata unavailable')); + selected.set(AuthProvider.githubEnterprise, session(`${hostB}/login/oauth`)); + + await store.create({ silent: true }); + assert.strictEqual((await store.getCurrentUser(AuthProvider.githubEnterprise)).login, 'octocat'); + await new Promise(resolve => setImmediate(resolve)); + + assert.ok(warning.calledWithMatch(/Unable to determine GitHub Enterprise version.*Metadata unavailable/)); + }); + + it('does not request metadata for GHE.com hosts when the version header is absent', async function () { + const warning = sinon.stub(vscode.window, 'showWarningMessage').resolves(undefined); + apiCall.resolves({ + data: { login: 'octocat', node_id: 'user', html_url: 'https://tenant.ghe.com/octocat', avatar_url: '', type: 'User' }, + headers: {}, + }); + selected.set(AuthProvider.githubEnterprise, session('https://tenant.ghe.com/login/oauth')); + + await store.create({ silent: true }); + await store.getCurrentUser(AuthProvider.githubEnterprise); + await new Promise(resolve => setImmediate(resolve)); + + sinon.assert.calledOnce(apiCall); + sinon.assert.notCalled(warning); + }); + }); + + it('loads and updates Enterprise projects after granting additional scopes', async function () { + const existing = { id: 'existing-item', project: { id: 'existing-project', title: 'Existing project' } }; + const replacement = { id: 'new-project', title: 'New project' }; + const organization = { id: 'org-project', title: 'Organization project' }; + const source = new GraphQLPullRequestBuilder().build(); + assert.ok(source.repository); + const rawItem = source.repository.pullRequest; + const requests: { operationName: string; query: string; variables: Record }[] = []; + const respond = (document: DocumentNode, variables: unknown) => { + const operation = document.definitions.find(definition => definition.kind === 'OperationDefinition'); + assert.ok(operation?.name); + assert.ok(isObject(variables)); + const request = { operationName: operation.name.value, query: print(document), variables }; + requests.push(request); + const item = { ...rawItem, projectItems: request.variables.includeProjects ? { nodes: [existing] } : undefined }; + switch (request.operationName) { + case 'PullRequest': + return { repository: { pullRequest: item } }; + case 'Issue': + return { repository: { issue: item } }; + case 'GetRepoProjects': + return { repository: { projectsV2: { nodes: [replacement] } } }; + case 'GetOrgProjects': + return { organization: { projectsV2: { nodes: [organization] } } }; + case 'RemovePullRequestFromProject': + return { deleteProjectV2Item: { deletedItemId: existing.id } }; + case 'AddPullRequestToProject': + return { addProjectV2ItemById: { item: { id: 'new-item' } } }; + case 'CreatePullRequest': + return { createPullRequest: { pullRequest: item } }; + case 'RevertPullRequest': + return { revertPullRequest: { revertPullRequest: item } }; + default: + throw new Error(`Unexpected GraphQL operation ${request.operationName}`); + } + }; + sinon.stub(LoggingApolloClient.prototype, 'query').callsFake(async options => ({ + data: respond(options.query, options.variables), loading: false, networkStatus: NetworkStatus.ready, stale: false, + })); + sinon.stub(LoggingApolloClient.prototype, 'mutate').callsFake(async options => ({ + data: respond(options.mutation, options.variables), + })); + selected.set(AuthProvider.githubEnterprise, session(`${hostB}/login/oauth`)); + await store.create({ silent: true }); + const remote = parseRemote('origin', `${hostB}/owner/repo`); + assert.ok(remote); + const repo = new GitHubRepository(1, GitHubRemote.remoteAsGitHub(remote, GitHubServerType.Enterprise), context.extensionUri, store, new MockTelemetry(), true); + context.subscriptions.push(repo); + + const before = await repo.getPullRequest(1347, 'test', false, false, 'overview'); + assert.ok(before); + assert.strictEqual(before.item.projectItems, undefined); + assert.strictEqual(requests[0].variables.includeProjects, false); + assert.strictEqual(await repo.canGetProjectsNow(), false); + assert.strictEqual(repo.areQueriesLimited, true); + + const revertedWithoutScopes = await repo.revertPullRequest('pr', 'Revert', '', false); + assert.strictEqual(revertedWithoutScopes.item.projectItems, undefined); + assert.strictEqual(requests[requests.length - 1].variables.includeProjects, false); + + selected.set(AuthProvider.githubEnterprise, session(`${hostB}/login/oauth`, { id: 'upgraded', scopes: additionalScopes })); + await store.getHubEnsureAdditionalScopes(AuthProvider.githubEnterprise); + const pullRequest = await repo.getPullRequest(1347, 'test', false, false, 'overview'); + assert.ok(pullRequest); + assert.deepStrictEqual(pullRequest.item.projectItems, [existing]); + const upgradedRequest = requests.find(request => request.operationName === 'PullRequest' && request.variables.includeProjects); + assert.ok(upgradedRequest); + assert.match(upgradedRequest.query, /projectItems/); + assert.doesNotMatch(upgradedRequest.query, /stackEntry|assignedActors/); + assert.strictEqual(await repo.canGetProjectsNow(), true); + assert.deepStrictEqual(await repo.getProjects(), [replacement]); + assert.deepStrictEqual(await repo.getOrgProjects(), [organization]); + + sinon.stub(repo, 'getMaxIssue').resolves(1347); + sinon.stub(repo, 'getMaxPullRequest').resolves(1347); + sinon.stub(IssueModel.prototype, 'getLastUpdateTime').callsFake(async time => time); + const issue = await repo.getIssue(1347); + assert.deepStrictEqual(issue?.item.projectItems, [existing]); + assert.strictEqual(requests.find(request => request.operationName === 'Issue')?.variables.includeProjects, true); + + assert.deepStrictEqual(await pullRequest.updateProjects([replacement]), [{ id: 'new-item', project: replacement }]); + assert.deepStrictEqual(requests.slice(-2).map(request => request.operationName), ['RemovePullRequestFromProject', 'AddPullRequestToProject']); + + sinon.stub(repo, 'getMetadata').resolves({ ...new RepositoryBuilder().build(), node_id: 'repository' }); + const created = await repo.createPullRequest({ owner: 'owner', repo: 'repo', base: 'main', head: 'branch', title: 'New PR' }); + assert.deepStrictEqual(created.item.projectItems, [existing]); + const reverted = await repo.revertPullRequest('pr', 'Revert', '', false); + assert.deepStrictEqual(reverted.item.projectItems, [existing]); + assert.deepStrictEqual(requests.slice(-2).map(request => [request.operationName, request.variables.includeProjects]), [ + ['CreatePullRequest', true], ['RevertPullRequest', true], + ]); + }); + + it('keeps project access when a query falls back to the limited schema', async function () { + const requests: { query: string; variables: Record }[] = []; + sinon.stub(LoggingApolloClient.prototype, 'query').callsFake(async options => { + assert.ok(isObject(options.variables)); + requests.push({ query: print(options.query), variables: { ...options.variables } }); + if (requests.length === 1) { + throw Object.assign(new Error('Unsupported field'), { + graphQLErrors: [{ extensions: { code: 'undefinedField' } }], + }); + } + return { data: { repository: {} }, loading: false, networkStatus: NetworkStatus.ready, stale: false }; + }); + selected.set(AuthProvider.github, session(undefined, { scopes: additionalScopes })); + await store.create({ silent: true }); + const remote = parseRemote('origin', 'https://github.com/owner/repo'); + assert.ok(remote); + const repo = new GitHubRepository(1, GitHubRemote.remoteAsGitHub(remote, GitHubServerType.GitHubDotCom), context.extensionUri, store, new MockTelemetry(), true); + context.subscriptions.push(repo); + await repo.ensure(); + + await repo.query({ query: repo.schema.PullRequest, variables: { owner: 'owner', name: 'repo', number: 1 } }); + + assert.strictEqual(requests.length, 2); + assert.match(requests[0].query, /stackEntry/); + assert.doesNotMatch(requests[1].query, /stackEntry/); + assert.strictEqual(requests[1].variables.includeProjects, true); + assert.strictEqual(repo.areQueriesLimited, true); + assert.strictEqual(await repo.canGetProjectsNow(), true); + }); + it('preserves public environment-token authentication', async function () { process.env.GITHUB_OAUTH_TOKEN = 'public-test-token'; await store.create({ silent: true }); diff --git a/src/test/github/createPRViewProvider.test.ts b/src/test/github/createPRViewProvider.test.ts index 0a8170aa71..d211da0aea 100644 --- a/src/test/github/createPRViewProvider.test.ts +++ b/src/test/github/createPRViewProvider.test.ts @@ -130,6 +130,47 @@ describe('Create pull request stack', function () { sinon.restore(); }); + it('applies projects selected in the create pull request picker', async function () { + const project = { id: 'project', title: 'Roadmap' }; + sinon.stub(githubRepository, 'canGetProjectsNow').resolves(true); + sinon.stub(folderManager, 'getAllProjects').resolves([project]); + const getOrgProjects = sinon.stub(folderManager, 'getOrgProjects').resolves({}); + const quickPick = vscode.window.createQuickPick(); + const accept = new vscode.EventEmitter(); + context.subscriptions.push(quickPick, accept); + sinon.stub(vscode.window, 'createQuickPick').returns(quickPick); + sinon.stub(quickPick, 'show'); + sinon.stub(quickPick, 'onDidAccept').value(accept.event); + const postMessage = sinon.stub(provider, '_postMessage').resolves(); + + const result = provider.addProjects(); + await new Promise(resolve => setImmediate(resolve)); + quickPick.selectedItems = quickPick.items; + accept.fire(); + await result; + + assert(getOrgProjects.calledOnceWithExactly(true)); + assert(postMessage.calledOnceWithExactly({ command: 'set-projects', params: { projects: [project] } })); + }); + + it('finishes without changing projects when the create pull request picker is canceled', async function () { + sinon.stub(githubRepository, 'canGetProjectsNow').resolves(false); + sinon.stub(folderManager, 'getAllProjects').resolves([{ id: 'project', title: 'Roadmap' }]); + const getOrgProjects = sinon.stub(folderManager, 'getOrgProjects').resolves({}); + const quickPick = vscode.window.createQuickPick(); + context.subscriptions.push(quickPick); + sinon.stub(vscode.window, 'createQuickPick').returns(quickPick); + const postMessage = sinon.stub(provider, '_postMessage').resolves(); + + const result = provider.addProjects(); + await new Promise(resolve => setImmediate(resolve)); + quickPick.hide(); + await result; + + sinon.assert.notCalled(getOrgProjects); + sinon.assert.notCalled(postMessage); + }); + describe('pull request template variables', function () { beforeEach(function () { const configuration: vscode.WorkspaceConfiguration = { diff --git a/src/test/github/folderRepositoryManager.test.ts b/src/test/github/folderRepositoryManager.test.ts index 12c21df2a6..a83a3e5a1a 100644 --- a/src/test/github/folderRepositoryManager.test.ts +++ b/src/test/github/folderRepositoryManager.test.ts @@ -62,6 +62,49 @@ describe('PullRequestManager', function () { sinon.restore(); }); + describe('project selection', function () { + it('loads organization projects after additional permissions are granted', async function () { + const url = 'https://github.com/owner/repo'; + const remote = new GitHubRemote('origin', url, new Protocol(url), GitHubServerType.GitHubDotCom); + const repo = new MockGitHubRepository(remote, manager.credentialStore, telemetry, sinon); + const repositoryProject = { id: 'repo-project', title: 'Repository project' }; + const organizationProject = { id: 'org-project', title: 'Organization project' }; + const available = sinon.stub(repo, 'canGetProjectsNow'); + available.onFirstCall().resolves(false); + available.onSecondCall().resolves(true); + let resolveProjects!: (projects: typeof repositoryProject[]) => void; + sinon.stub(repo, 'getProjects').returns(new Promise(resolve => resolveProjects = resolve)); + const getOrgProjects = sinon.stub(manager, 'getOrgProjects').resolves({ origin: [organizationProject] }); + + try { + const projects = manager.getAllProjects(repo); + await new Promise(resolve => setImmediate(resolve)); + sinon.assert.notCalled(getOrgProjects); + resolveProjects([repositoryProject]); + assert.deepStrictEqual(await projects, [repositoryProject, organizationProject]); + assert(getOrgProjects.calledOnceWithExactly(true)); + } finally { + repo.dispose(); + } + }); + + it('does not request organization projects when the permissions upgrade is canceled', async function () { + const url = 'https://github.com/owner/repo'; + const remote = new GitHubRemote('origin', url, new Protocol(url), GitHubServerType.GitHubDotCom); + const repo = new MockGitHubRepository(remote, manager.credentialStore, telemetry, sinon); + sinon.stub(repo, 'canGetProjectsNow').resolves(false); + sinon.stub(repo, 'getProjects').resolves(undefined); + const getOrgProjects = sinon.stub(manager, 'getOrgProjects'); + + try { + assert.deepStrictEqual(await manager.getAllProjects(repo), []); + sinon.assert.notCalled(getOrgProjects); + } finally { + repo.dispose(); + } + }); + }); + describe('overview resolution', function () { const metadata = { ...new RepositoryBuilder().build(), currentUser: new UserBuilder().build() }; diff --git a/src/test/github/issueOverview.test.ts b/src/test/github/issueOverview.test.ts index 2fcacfe0c0..a341cc9635 100644 --- a/src/test/github/issueOverview.test.ts +++ b/src/test/github/issueOverview.test.ts @@ -8,8 +8,10 @@ import { createSandbox, SinonSandbox, SinonStub } from 'sinon'; import * as vscode from 'vscode'; import { GitApiImpl } from '../../api/api1'; import { GitHubServerType } from '../../common/authentication'; +import Logger from '../../common/logger'; import { Protocol } from '../../common/protocol'; import { GitHubRemote } from '../../common/remote'; +import { IRequestMessage } from '../../common/webview'; import { EXTENSION_ID } from '../../constants'; import { CredentialStore } from '../../github/credentials'; import { FolderRepositoryManager } from '../../github/folderRepositoryManager'; @@ -53,6 +55,18 @@ class TestIssueOverviewPanel extends IssueOverviewPanel { public override _postMessage(message: { command: string; isCurrentlyCheckedOut?: boolean }): Promise { return super._postMessage(message); } + + public override _onDidReceiveMessage(message: IRequestMessage) { + return super._onDidReceiveMessage(message); + } + + public override _replyMessage(message: IRequestMessage, response: unknown): Promise { + return super._replyMessage(message, response); + } + + public override _throwError(message: IRequestMessage | undefined, error: string): Promise { + return super._throwError(message, error); + } } describe('IssueOverview remote-only manager upgrades', function () { @@ -147,6 +161,112 @@ describe('IssueOverview remote-only manager upgrades', function () { sandbox.assert.notCalled(postMessage); }); + it('selects existing projects after upgrading permissions', async function () { + const repo = issue.githubRepository; + const project = { id: 'project', title: 'Roadmap' }; + const refreshed = new IssueModel(new MockTelemetry(), repo, issue.remote, { + ...issue.item, + projectItems: [{ id: 'item', project }], + }); + context.subscriptions.push(refreshed); + const available = sandbox.stub(repo, 'canGetProjectsNow').resolves(true); + available.onFirstCall().resolves(false); + sandbox.stub(repo, 'ensureAdditionalScopes').resolves(repo); + const resolve = sandbox.stub(panel, 'resolveModel').resolves(refreshed); + sandbox.stub(temporaryManager, 'getAllProjects').resolves([project]); + sandbox.stub(temporaryManager, 'getOrgProjects').resolves({}); + const quickPick = vscode.window.createQuickPick(); + context.subscriptions.push(quickPick); + sandbox.stub(vscode.window, 'createQuickPick').returns(quickPick); + const reply = sandbox.stub(panel, '_replyMessage').resolves(); + const message = { req: '1', command: 'pr.change-projects', args: undefined }; + + const result = panel._onDidReceiveMessage(message); + await new Promise(resolve => setImmediate(resolve)); + + sandbox.assert.calledOnce(resolve); + assert.deepStrictEqual(quickPick.selectedItems.map(item => item.label), [project.title]); + quickPick.hide(); + await result; + assert(reply.calledOnceWithExactly(message, { projectItems: refreshed.item.projectItems })); + }); + + it('replies without opening the picker when the permissions upgrade is canceled', async function () { + const repo = issue.githubRepository; + sandbox.stub(repo, 'canGetProjectsNow').resolves(false); + sandbox.stub(repo, 'ensureAdditionalScopes').resolves(repo); + const reply = sandbox.stub(panel, '_replyMessage').resolves(); + const picker = sandbox.stub(vscode.window, 'createQuickPick'); + const message = { req: '1', command: 'pr.change-projects', args: undefined }; + + await panel._onDidReceiveMessage(message); + + assert(reply.calledOnceWithExactly(message, { projectItems: issue.item.projectItems })); + sandbox.assert.notCalled(picker); + }); + + it('replies if the project picker is canceled while projects are loading', async function () { + sandbox.stub(issue.githubRepository, 'canGetProjectsNow').resolves(true); + let rejectProjects: (error: Error) => void; + sandbox.stub(temporaryManager, 'getAllProjects').returns(new Promise((_resolve, reject) => rejectProjects = reject)); + const warning = sandbox.stub(Logger, 'warn'); + const quickPick = vscode.window.createQuickPick(); + context.subscriptions.push(quickPick); + sandbox.stub(vscode.window, 'createQuickPick').returns(quickPick); + const reply = sandbox.stub(panel, '_replyMessage').resolves(); + const message = { req: '1', command: 'pr.change-projects', args: undefined }; + + const result = panel._onDidReceiveMessage(message); + await new Promise(resolve => setImmediate(resolve)); + quickPick.hide(); + await result; + rejectProjects!(new Error('Late loading error')); + await new Promise(resolve => setImmediate(resolve)); + + assert(reply.calledOnceWithExactly(message, { projectItems: issue.item.projectItems })); + assert.ok(warning.calledWithMatch(/Late loading error/)); + }); + + it('updates projects when the picker is accepted', async function () { + const project = { id: 'project', title: 'Roadmap' }; + const projectItems = [{ id: 'item', project }]; + sandbox.stub(issue.githubRepository, 'canGetProjectsNow').resolves(true); + sandbox.stub(temporaryManager, 'getAllProjects').resolves([project]); + sandbox.stub(temporaryManager, 'getOrgProjects').resolves({}); + const update = sandbox.stub(issue, 'updateProjects').resolves(projectItems); + const quickPick = vscode.window.createQuickPick(); + const accept = new vscode.EventEmitter(); + context.subscriptions.push(quickPick, accept); + sandbox.stub(vscode.window, 'createQuickPick').returns(quickPick); + sandbox.stub(quickPick, 'show'); + sandbox.stub(quickPick, 'onDidAccept').value(accept.event); + const reply = sandbox.stub(panel, '_replyMessage').resolves(); + const message = { req: '1', command: 'pr.change-projects', args: undefined }; + + const result = panel._onDidReceiveMessage(message); + await new Promise(resolve => setImmediate(resolve)); + quickPick.selectedItems = quickPick.items; + accept.fire(); + await result; + + assert(update.calledOnceWithExactly([project])); + assert(reply.calledOnceWithExactly(message, { projectItems })); + }); + + it('reports a project picker loading failure to the webview', async function () { + sandbox.stub(issue.githubRepository, 'canGetProjectsNow').resolves(true); + sandbox.stub(temporaryManager, 'getAllProjects').rejects(new Error('Projects unavailable')); + const showError = sandbox.stub(vscode.window, 'showErrorMessage').resolves(undefined); + const reply = sandbox.stub(panel, '_throwError').resolves(); + const message = { req: '1', command: 'pr.change-projects', args: undefined }; + + await panel._onDidReceiveMessage(message); + + sandbox.assert.calledOnce(showError); + assert.strictEqual(reply.firstCall.args[0], message); + assert.match(reply.firstCall.args[1], /Projects unavailable/); + }); + it('retains its local manager without looking it up again', function () { discovered = true; assert.strictEqual(panel.folderRepositoryManager, localManager); diff --git a/webviews/components/sidebar.tsx b/webviews/components/sidebar.tsx index e5743bfc1d..a81a263bfd 100644 --- a/webviews/components/sidebar.tsx +++ b/webviews/components/sidebar.tsx @@ -98,7 +98,8 @@ export default function Sidebar({ reviewers, labels, closingIssues = [], hasWrit const shouldShowCopilotButton = canAssignCopilot && assignees.every(assignee => !COPILOT_LOGINS.includes(assignee.login)); const shouldShowCopilotReviewButton = canRequestCopilotReview && reviewers.every(reviewer => !isITeam(reviewer.reviewer) && !COPILOT_LOGINS.includes(reviewer.reviewer.login)); - const updateProjects = async () => { + const updateProjects = async (event?: React.MouseEvent) => { + event?.stopPropagation(); const newProjects = await changeProjects(); updatePR({ ...newProjects }); }; @@ -260,23 +261,21 @@ export default function Sidebar({ reviewers, labels, closingIssues = [], hasWrit )} - {!pr!.isEnterprise && ( -
- {!projects ? - Sign in with more permissions to see projects - : (projects.length > 0) - ? projects.map(project => ( - - )) : -
None yet
- } -
- )} +
+ {!projects ? + Sign in with more permissions to see projects + : (projects.length > 0) + ? projects.map(project => ( + + )) : +
None yet
+ } +
{ + it(`shows and edits projects on an Enterprise ${isIssue ? 'issue' : 'pull request'}`, async function () { + const project = { id: 'item-1', project: { id: 'project-1', title: 'Enterprise roadmap' } }; + const pr = new PullRequestBuilder().isEnterprise(true).isIssue(isIssue).projectItems([project]).build(); + const context = new PRContext(pr); + const changeProjects = sinon.stub(context, 'changeProjects').resolves({ projectItems: [project] }); + const removeProject = sinon.stub(context, 'removeProject').resolves(); + const out = render( + + + , + ); + + assert(out.container.querySelector('#project')?.textContent?.includes(project.project.title)); + fireEvent.click(out.getByTitle('Add Project')); + await wait(() => assert(changeProjects.calledOnce)); + fireEvent.click(out.getByTitle('Remove from project')); + await wait(() => assert(removeProject.calledOnce)); + assert.strictEqual(removeProject.firstCall.args[0].id, project.id); + assert.deepStrictEqual(removeProject.firstCall.args[0].project, project.project); + }); + }); + + it('offers additional project permissions for Enterprise', async function () { + const pr = new PullRequestBuilder().isEnterprise(true).projectItems(undefined).build(); + const context = new PRContext(pr); + const changeProjects = sinon.stub(context, 'changeProjects').resolves({ projectItems: [] }); + const out = render( + + + , + ); + + fireEvent.click(out.getByText('Sign in with more permissions to see projects')); + await wait(() => assert(changeProjects.calledOnce)); + }); + it('opens PR number links on GitHub', function () { const pr = new PullRequestBuilder().build(); const context = new PRContext(pr);