diff --git a/src/notifications/notificationsManager.ts b/src/notifications/notificationsManager.ts index d288c7fd93..00a17e668b 100644 --- a/src/notifications/notificationsManager.ts +++ b/src/notifications/notificationsManager.ts @@ -5,14 +5,14 @@ import * as vscode from 'vscode'; import { isNotificationTreeItem, NotificationTreeDataItem, NotificationTreeItem } from './notificationItem'; -import { NotificationsProvider } from './notificationsProvider'; +import { isSameNotificationSource, NotificationsProvider } from './notificationsProvider'; import { commands, contexts } from '../common/executeCommands'; import { Disposable } from '../common/lifecycle'; import Logger from '../common/logger'; import { ISSUES_SETTINGS_NAMESPACE, NOTIFICATION_SETTING, NotificationVariants, PR_SETTINGS_NAMESPACE, SHOW_ISSUE_NUMBER_IN_TREE, SHOW_PULL_REQUEST_NUMBER_IN_TREE } from '../common/settingKeys'; import { EventType, TimelineEvent } from '../common/timelineEvent'; import { toNotificationUri } from '../common/uri'; -import { CredentialStore } from '../github/credentials'; +import { CredentialStore, GitHub } from '../github/credentials'; import { AccountType, NotificationSubjectType } from '../github/interface'; import { IssueModel } from '../github/issueModel'; import { issueMarkdown } from '../github/markdownUtils'; @@ -49,6 +49,8 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP private _dateTime: Date = new Date(); private _fetchNotifications: boolean = false; private _notifications = new Map(); + // The account that the cached notifications, and their pagination, belong to. + private _source: GitHub | undefined; private _pollingDuration: number = 60; // Default polling duration private _pollingHandler: NodeJS.Timeout | null; @@ -81,6 +83,13 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP this._register(PullRequestOverviewPanel.onVisible(e => { this.markPrNotificationsAsRead(e); })); + const refreshIfSourceChanged = () => { + if (this._source && !isSameNotificationSource(this._source, this._notificationProvider.getSource())) { + this.refresh(); + } + }; + this._register(this._repositoriesManager.onDidChangeAnyGitHubRepository(refreshIfSourceChanged)); + this._register(this._repositoriesManager.onDidChangeFolderRepositories(refreshIfSourceChanged)); } //#region TreeDataProvider @@ -227,12 +236,27 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP } public async getNotifications(): Promise { - const notificationsCache = this._notifications; + let notificationsCache = this._notifications; let pollInterval = this._pollingDuration; let lastModified = this._pollingLastModified; if (this._fetchNotifications) { + const source = this._notificationProvider.getSource(); + if (!source) { + return undefined; + } + if (!isSameNotificationSource(this._source, source)) { + // Cached notifications and pages belong to the previous account. Replacing the cache also + // invalidates fetches that are still in flight for the previous account. + const updates = this.clearNotifications(); + if (updates.length > 0) { + this._onDidChangeNotifications.fire(updates); + } + notificationsCache = this._notifications; + } + this._source = source; + // Get raw notifications - const notificationsData = await this._notificationProvider.getNotifications(this._dateTime.toISOString(), this._pageCount); + const notificationsData = await this._notificationProvider.getNotifications(source, this._dateTime.toISOString(), this._pageCount); if (!notificationsData) { return undefined; } @@ -316,6 +340,7 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP private clearNotifications(): NotificationTreeItem[] { const updates = Array.from(this._notifications.values()); this._pageCount = 1; + this._hasNextPage = false; this._dateTime = new Date(); this._notifications = new Map(); this._updateContext(); @@ -324,6 +349,7 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP public clear(): void { const updates = this.clearNotifications(); + this._source = undefined; this._fetchNotifications = false; this._onDidChangeNotifications.fire(updates); this._onDidChangeTreeData.fire(); @@ -347,8 +373,8 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP public async markAsRead(notificationIdentifier: { threadId: string, notificationKey: string }): Promise { const notification = this._notifications.get(notificationIdentifier.notificationKey); - if (notification) { - await this._notificationProvider.markAsRead(notificationIdentifier); + if (notification && this._source) { + await this._notificationProvider.markAsRead(this._source, notificationIdentifier.threadId); this._onDidChangeNotifications.fire([notification]); this._notifications.delete(notificationIdentifier.notificationKey); @@ -360,8 +386,8 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP public async markAsDone(notificationIdentifier: { threadId: string, notificationKey: string }): Promise { const notification = this._notifications.get(notificationIdentifier.notificationKey); - if (notification) { - await this._notificationProvider.markAsDone(notificationIdentifier); + if (notification && this._source) { + await this._notificationProvider.markAsDone(this._source, notificationIdentifier.threadId); this._onDidChangeNotifications.fire([notification]); this._notifications.delete(notificationIdentifier.notificationKey); @@ -415,6 +441,10 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP } public async markPullRequests(markAsDone: boolean = false): Promise { + const source = this._source; + if (!source) { + return; + } const filteredNotifications = Array.from(this._notifications.values()).filter(notification => notification.notification.subject.type === NotificationSubjectType.PullRequest); const timelines = await Promise.all(filteredNotifications.map(notification => (notification.model as PullRequestModel).getActivityTimelineEvents())); @@ -442,9 +472,9 @@ export class NotificationsManager extends Disposable implements vscode.TreeDataP if (!nonUserLastEvent || (userLastEvent && (userLastEvent.getTime() > nonUserLastEvent.getTime()))) { if (markAsDone) { - markPromises.push(this._notificationProvider.markAsDone({ threadId: notification.notification.id, notificationKey: notification.notification.key })); + markPromises.push(this._notificationProvider.markAsDone(source, notification.notification.id)); } else { - markPromises.push(this._notificationProvider.markAsRead({ threadId: notification.notification.id, notificationKey: notification.notification.key })); + markPromises.push(this._notificationProvider.markAsRead(source, notification.notification.id)); } this._notifications.delete(notification.notification.key); } diff --git a/src/notifications/notificationsProvider.ts b/src/notifications/notificationsProvider.ts index 251603f523..f58bef6b65 100644 --- a/src/notifications/notificationsProvider.ts +++ b/src/notifications/notificationsProvider.ts @@ -31,63 +31,50 @@ export interface INotificationPriority { readonly priorityReasoning: string | undefined; } +export function isSameNotificationSource(first: GitHub | undefined, second: GitHub | undefined): boolean { + return first === second || (!!first && !!second + && first.serverUri.toString() === second.serverUri.toString() + && first.session?.account.id === second.session?.account.id); +} + export class NotificationsProvider extends Disposable { private static readonly ID = 'NotificationsProvider'; - private _authProvider: AuthProvider | undefined; constructor( private readonly _credentialStore: CredentialStore, private readonly _repositoriesManager: RepositoriesManager ) { super(); - const setAuthProvider = () => { - if (_credentialStore.isAuthenticated(AuthProvider.githubEnterprise)) { - this._authProvider = AuthProvider.githubEnterprise; - } else if (_credentialStore.isAuthenticated(AuthProvider.github)) { - this._authProvider = AuthProvider.github; - } else { - this._authProvider = undefined; - } - }; - setAuthProvider(); - this._register( - _credentialStore.onDidChangeSessions(_ => { - setAuthProvider(); - }) - ); } - private _getGitHub(): GitHub | undefined { - return (this._authProvider !== undefined) ? - this._credentialStore.getHub(this._authProvider) : - undefined; + /** + * The account whose notifications are shown. Notifications are fetched from a single account at a time. + */ + public getSource(): GitHub | undefined { + const enterprise = this._credentialStore.getHub(AuthProvider.githubEnterprise); + const github = this._credentialStore.getHub(AuthProvider.github); + // An enterprise session can exist without any enterprise repositories in the workspace, + // so only prefer it when a workspace repository is hosted on that enterprise server. + if (enterprise && this._repositoriesManager.folderManagers.some(folderManager => + folderManager.gitHubRepositories.some(repo => repo.remote.isEnterprise && repo.remote.matchesServerUri(enterprise.serverUri)))) { + return enterprise; + } + return github ?? enterprise; } - public async markAsRead(notificationIdentifier: { threadId: string, notificationKey: string }): Promise { - const gitHub = this._getGitHub(); - if (gitHub === undefined) { - return undefined; - } - await gitHub.octokit.call(gitHub.octokit.api.activity.markThreadAsRead, { - thread_id: Number(notificationIdentifier.threadId) + public async markAsRead(source: GitHub, threadId: string): Promise { + await source.octokit.call(source.octokit.api.activity.markThreadAsRead, { + thread_id: Number(threadId) }); } - public async markAsDone(notificationIdentifier: { threadId: string, notificationKey: string }): Promise { - const gitHub = this._getGitHub(); - if (gitHub === undefined) { - return undefined; - } - await gitHub.octokit.call(gitHub.octokit.api.activity.markThreadAsDone, { - thread_id: Number(notificationIdentifier.threadId) + public async markAsDone(source: GitHub, threadId: string): Promise { + await source.octokit.call(source.octokit.api.activity.markThreadAsDone, { + thread_id: Number(threadId) }); } - public async getNotifications(before: string, page: number): Promise { - const gitHub = this._getGitHub(); - if (gitHub === undefined) { - return undefined; - } + public async getNotifications(gitHub: GitHub, before: string, page: number): Promise { if (this._repositoriesManager.folderManagers.length === 0) { return undefined; } diff --git a/src/test/notifications/notificationsManager.test.ts b/src/test/notifications/notificationsManager.test.ts index 1724787bcd..8a739e3937 100644 --- a/src/test/notifications/notificationsManager.test.ts +++ b/src/test/notifications/notificationsManager.test.ts @@ -4,35 +4,79 @@ *--------------------------------------------------------------------------------------------*/ import { default as assert } from 'assert'; -import { createSandbox, SinonSandbox } from 'sinon'; -import { CredentialStore } from '../../github/credentials'; +import { createSandbox, SinonSandbox, SinonStub } from 'sinon'; +import * as vscode from 'vscode'; +import { CredentialStore, GitHub } from '../../github/credentials'; +import { FolderRepositoryManager } from '../../github/folderRepositoryManager'; +import { Notification, NotificationSubjectType } from '../../github/interface'; +import { IssueModel } from '../../github/issueModel'; import { RepositoriesManager } from '../../github/repositoriesManager'; import { NotificationTreeItem } from '../../notifications/notificationItem'; import { NotificationsManager } from '../../notifications/notificationsManager'; -import { NotificationsProvider } from '../../notifications/notificationsProvider'; +import { INotifications, NotificationsProvider } from '../../notifications/notificationsProvider'; import { MockCommandRegistry } from '../mocks/mockCommandRegistry'; import { MockExtensionContext } from '../mocks/mockExtensionContext'; describe('NotificationsManager', function () { + const github = { serverUri: vscode.Uri.parse('https://github.com') } as GitHub; + const enterprise = { serverUri: vscode.Uri.parse('https://octo.ghe.com') } as GitHub; + let sinon: SinonSandbox; let manager: NotificationsManager; + let source: GitHub | undefined; + let getNotifications: SinonStub; + let markAsRead: SinonStub; + let onDidChangeAnyGitHubRepository: vscode.EventEmitter; beforeEach(function () { sinon = createSandbox(); MockCommandRegistry.install(sinon); + source = github; + getNotifications = sinon.stub(); + markAsRead = sinon.stub().resolves(); + const provider: Pick = { + getSource: () => source, + getNotifications, + getNotificationModel: async () => ({} as IssueModel), + markAsRead, + }; + onDidChangeAnyGitHubRepository = new vscode.EventEmitter(); + const repositoriesManager: Pick = { + onDidChangeAnyGitHubRepository: onDidChangeAnyGitHubRepository.event, + onDidChangeFolderRepositories: new vscode.EventEmitter<{ added?: FolderRepositoryManager }>().event, + }; manager = new NotificationsManager( - {} as NotificationsProvider, + provider as NotificationsProvider, {} as CredentialStore, - {} as RepositoriesManager, + repositoriesManager as RepositoriesManager, new MockExtensionContext(), ); }); afterEach(function () { manager.dispose(); + onDidChangeAnyGitHubRepository.dispose(); sinon.restore(); }); + function notificationsResult(...keys: string[]): INotifications { + return { + notifications: keys.map(key => ({ + key, + id: key, + updatedAt: new Date(), + subject: { title: key, type: NotificationSubjectType.PullRequest, url: 'https://api.github.com/repos/o/r/pulls/1' }, + } as Notification)), + hasNextPage: true, + pollInterval: 60, + lastModified: '', + }; + } + + function cachedKeys(): string[] { + return manager.getAllNotifications().map(item => item.notification.key); + } + it('clears cached notifications without fetching', function () { const notification = {} as NotificationTreeItem; const internal = manager as unknown as { @@ -55,24 +99,11 @@ describe('NotificationsManager', function () { }); it('does not publish notifications into a replacement cache', async function () { - let resolveNotifications: (notifications: { - notifications: []; - hasNextPage: boolean; - pollInterval: number; - lastModified: string; - }) => void; - const notifications = new Promise<{ - notifications: []; - hasNextPage: boolean; - pollInterval: number; - lastModified: string; - }>(resolve => resolveNotifications = resolve); - const getNotifications = sinon.stub().returns(notifications); + let resolveNotifications: (notifications: INotifications) => void; + getNotifications.returns(new Promise(resolve => resolveNotifications = resolve)); const internal = manager as unknown as { - _notificationProvider: { getNotifications: typeof getNotifications }; _fetchNotifications: boolean; }; - internal._notificationProvider = { getNotifications }; internal._fetchNotifications = true; const pendingNotifications = manager.getNotifications(); @@ -88,4 +119,45 @@ describe('NotificationsManager', function () { assert.deepStrictEqual(manager.getAllNotifications(), []); assert.strictEqual(internal._fetchNotifications, false); }); + + it('restarts pagination and drops in-flight results when the account changes', async function () { + let resolveGitHubNotifications: (notifications: INotifications) => void; + getNotifications.withArgs(github).returns(new Promise(resolve => resolveGitHubNotifications = resolve)); + getNotifications.withArgs(enterprise).resolves(notificationsResult('enterprise')); + manager.refresh(); + const pendingGitHubNotifications = manager.getNotifications(); + + source = enterprise; + manager.loadMore(); + await manager.getNotifications(); + resolveGitHubNotifications!(notificationsResult('github')); + + assert.strictEqual(await pendingGitHubNotifications, undefined); + assert.strictEqual(getNotifications.withArgs(enterprise).firstCall.args[2], 1); + assert.deepStrictEqual(cachedKeys(), ['enterprise']); + }); + + it('marks notifications on the account they were fetched from', async function () { + getNotifications.resolves(notificationsResult('github')); + manager.refresh(); + await manager.getNotifications(); + + source = enterprise; + await manager.markAsRead({ threadId: 'github', notificationKey: 'github' }); + + assert.strictEqual(markAsRead.calledOnceWith(github, 'github'), true); + }); + + it('refreshes when a repository change selects a different account', async function () { + getNotifications.resolves(notificationsResult('github')); + manager.refresh(); + await manager.getNotifications(); + + onDidChangeAnyGitHubRepository.fire({} as FolderRepositoryManager); + assert.deepStrictEqual(cachedKeys(), ['github']); + + source = enterprise; + onDidChangeAnyGitHubRepository.fire({} as FolderRepositoryManager); + assert.deepStrictEqual(cachedKeys(), []); + }); }); diff --git a/src/test/notifications/notificationsProvider.test.ts b/src/test/notifications/notificationsProvider.test.ts new file mode 100644 index 0000000000..e3751f03dd --- /dev/null +++ b/src/test/notifications/notificationsProvider.test.ts @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { default as assert } from 'assert'; +import * as vscode from 'vscode'; +import { AuthProvider } from '../../common/authentication'; +import { Protocol } from '../../common/protocol'; +import { Remote } from '../../common/remote'; +import { CredentialStore, GitHub } from '../../github/credentials'; +import { FolderRepositoryManager } from '../../github/folderRepositoryManager'; +import { GitHubRepository } from '../../github/githubRepository'; +import { RepositoriesManager } from '../../github/repositoriesManager'; +import { NotificationsProvider } from '../../notifications/notificationsProvider'; + +describe('NotificationsProvider', function () { + const github = { serverUri: vscode.Uri.parse('https://github.com') } as GitHub; + const enterprise = { serverUri: vscode.Uri.parse('https://octo.ghe.com') } as GitHub; + + function createProvider(remoteUrls: string[]): NotificationsProvider { + const hubs: Record = { [AuthProvider.github]: github, [AuthProvider.githubEnterprise]: enterprise }; + const credentialStore = { getHub: (authProviderId: AuthProvider) => hubs[authProviderId] } as CredentialStore; + const gitHubRepositories = remoteUrls.map(url => ({ remote: new Remote('origin', url, new Protocol(url)) } as GitHubRepository)); + const repositoriesManager = { folderManagers: [{ gitHubRepositories } as FolderRepositoryManager] } as RepositoriesManager; + return new NotificationsProvider(credentialStore, repositoriesManager); + } + + it('uses the GitHub.com account when the enterprise session has no workspace repositories', function () { + const provider = createProvider(['https://github.com/microsoft/vscode.git']); + + assert.strictEqual(provider.getSource(), github); + provider.dispose(); + }); + + it('uses the enterprise account when a workspace repository is on the enterprise server', function () { + const provider = createProvider(['https://octo.ghe.com/microsoft/vscode.git']); + + assert.strictEqual(provider.getSource(), enterprise); + provider.dispose(); + }); +});