diff --git a/macgit/App/GitProviderAccountController.swift b/macgit/App/GitProviderAccountController.swift index 5a4d2581..3810c21d 100644 --- a/macgit/App/GitProviderAccountController.swift +++ b/macgit/App/GitProviderAccountController.swift @@ -193,14 +193,18 @@ final class GitProviderAccountController: ObservableObject { } } + /// `atlassianEmail` is optional: Git works without it, but Bitbucket's REST API (issues) + /// authenticates API tokens with the Atlassian account email. It is kept with the token only. func connectBitbucket( username: String, apiToken: String, + atlassianEmail: String = "", replacing existingAccount: GitProviderAccount? = nil ) async { errorMessage = nil let normalizedUsername = username.trimmingCharacters(in: .whitespacesAndNewlines) let normalizedToken = apiToken.trimmingCharacters(in: .whitespacesAndNewlines) + let normalizedEmail = atlassianEmail.trimmingCharacters(in: .whitespacesAndNewlines) guard !normalizedUsername.isEmpty else { errorMessage = "Enter your case-sensitive Bitbucket username." return @@ -227,7 +231,7 @@ final class GitProviderAccountController: ObservableObject { username: normalizedUsername, displayName: nil, avatarURL: nil, - scopes: ["read:repository:bitbucket", "write:repository:bitbucket"], + scopes: ["read:repository:bitbucket", "write:repository:bitbucket", "read:issue:bitbucket", "write:issue:bitbucket"], permissions: [:], tokenStatus: .valid, transportProtocol: .https, @@ -243,7 +247,8 @@ final class GitProviderAccountController: ObservableObject { accessToken: normalizedToken, refreshToken: nil, expiresAt: nil, - tokenType: "Basic" + tokenType: "Basic", + apiUsername: normalizedEmail.isEmpty ? nil : normalizedEmail ), replacing: existingAccount ) @@ -252,6 +257,11 @@ final class GitProviderAccountController: ObservableObject { } } + /// The Atlassian email saved with a Bitbucket account's API token, to prefill the edit sheet. + func savedAPIUsername(for account: GitProviderAccount) -> String? { + (try? tokenVault.readToken(for: account))?.apiUsername + } + /// Connects one Azure DevOps organization with a personal access token. func connectAzureDevOps( organization organizationInput: String, diff --git a/macgit/App/HostedIssueController.swift b/macgit/App/HostedIssueController.swift new file mode 100644 index 00000000..2e7c59fd --- /dev/null +++ b/macgit/App/HostedIssueController.swift @@ -0,0 +1,527 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import Combine +import Foundation + +protocol HostedIssuePreferenceStoring { + func remoteName(forRepositoryKey key: String) async -> String? + func saveRemoteName(_ name: String, forRepositoryKey key: String) async + func filter(forRepositoryKey key: String, remote: String) async -> HostedIssueFilter? + func save(_ filter: HostedIssueFilter, forRepositoryKey key: String, remote: String) async +} + +/// Remembers each repository's chosen issue remote and per-remote filter on this Mac. +/// Search text is never stored. +final class LocalHostedIssuePreferenceStore: HostedIssuePreferenceStoring { + static let remoteCollection = "hostedIssueRemotes" + static let filterCollection = "hostedIssueFilters" + private let dataStore: LocalDataStore + + private struct StoredRemote: Codable { + var name: String + } + + init(dataStore: LocalDataStore? = nil) { + self.dataStore = dataStore ?? .shared + } + + func remoteName(forRepositoryKey key: String) async -> String? { + try? await dataStore.readValue(StoredRemote.self, in: Self.remoteCollection, id: key)?.name + } + + func saveRemoteName(_ name: String, forRepositoryKey key: String) async { + _ = try? await dataStore.transaction { transaction in + try transaction.set(StoredRemote(name: name), in: Self.remoteCollection, id: key) + } + } + + func filter(forRepositoryKey key: String, remote: String) async -> HostedIssueFilter? { + try? await dataStore.readValue(HostedIssueFilter.self, in: Self.filterCollection, id: Self.filterID(key, remote)) + } + + func save(_ filter: HostedIssueFilter, forRepositoryKey key: String, remote: String) async { + let id = Self.filterID(key, remote) + _ = try? await dataStore.transaction { transaction in + if filter.isDefault { + transaction.remove(in: Self.filterCollection, id: id) + } else { + try transaction.set(filter, in: Self.filterCollection, id: id) + } + } + } + + private static func filterID(_ key: String, _ remote: String) -> String { + key + "\n" + remote + } +} + +/// A remote whose provider has an issue tracker Commit+ supports. +struct HostedIssueRemote: Equatable, Identifiable { + var name: String + var provider: HostedIssueProvider + var repository: GitRepositoryIdentity + + var id: String { name } +} + +/// Why the list cannot load with a provider account, and which host to connect. +enum HostedIssueAccountProblem: Equatable { + case noAccount(GitProviderHost) + case reconnect(GitProviderHost) +} + +/// The hosted issue screen for one repository window. +@MainActor +final class HostedIssueController: ObservableObject { + static let listCacheTTL: TimeInterval = 60 + static let detailCacheTTL: TimeInterval = 300 + + @Published private(set) var remotes: [HostedIssueRemote] = [] + @Published private(set) var selectedRemote: HostedIssueRemote? + @Published private(set) var hasDiscoveredRemotes = false + @Published private(set) var items: [HostedIssueSummary] = [] + @Published private(set) var next: HostedIssueCursor? + @Published private(set) var isLoading = false + @Published private(set) var isLoadingMore = false + @Published private(set) var hasLoadedList = false + @Published private(set) var error: HostedIssueError? + @Published private(set) var accountProblem: HostedIssueAccountProblem? + @Published private(set) var filter = HostedIssueFilter.default + @Published var searchText = "" { + didSet { + guard searchText != oldValue else { return } + scheduleSearch() + } + } + @Published private(set) var selectedIssueNumber: Int? + @Published private(set) var detail: HostedIssueDetail? + @Published private(set) var isLoadingDetail = false + @Published private(set) var detailError: HostedIssueError? + @Published private(set) var isWriting = false + @Published private(set) var writeError: HostedIssueError? + @Published private(set) var workItemTypes: [String] = [] + + /// Re-checks plan access before a write; set by the window that owns the controller. + var authorizeWrite: () async -> Bool = { true } + + var provider: HostedIssueProvider? { selectedRemote?.provider } + var isFiltered: Bool { !filter.isDefault || !searchText.trimmingCharacters(in: .whitespaces).isEmpty } + + private let repositoryURL: URL + private let repositoryKey: String + private let credentialResolver: GitProviderAPICredentialResolver + private let services: [HostedIssueProvider: any HostedIssueProviding] + private let preferenceStore: HostedIssuePreferenceStoring + private let remoteNamesProvider: (URL) async -> [String] + private let remoteURLProvider: (URL, String) async -> String? + private let searchDebounce: Duration + private let now: () -> Date + + private var isActive = false + private var restoredRemoteName: String?? + private var generation = 0 + private var detailGeneration = 0 + private var loadTask: Task? + private var searchTask: Task? + private var lastLoadedAt: Date? + private var loadedKey: String? + private var listCache: [String: (page: HostedIssuePage, loadedAt: Date)] = [:] + private var detailCache: [String: (detail: HostedIssueDetail, loadedAt: Date)] = [:] + private var accountID: String? + private var observers: [AnyCancellable] = [] + + init( + repositoryURL: URL, + credentialResolver: GitProviderAPICredentialResolver, + services: [HostedIssueProvider: any HostedIssueProviding], + preferenceStore: HostedIssuePreferenceStoring = LocalHostedIssuePreferenceStore(), + remoteNamesProvider: @escaping (URL) async -> [String] = { await GitStatusService.shared.remotes(in: $0) }, + remoteURLProvider: @escaping (URL, String) async -> String? = { repositoryURL, remote in + let url = await GitStatusService.shared.remoteURL(remote: remote, in: repositoryURL) + return url.isEmpty ? nil : url + }, + searchDebounce: Duration = .milliseconds(400), + notificationCenter: NotificationCenter = .default, + now: @escaping () -> Date = Date.init + ) { + self.repositoryURL = repositoryURL + self.repositoryKey = repositoryURL.standardizedFileURL.path + self.credentialResolver = credentialResolver + self.services = services + self.preferenceStore = preferenceStore + self.remoteNamesProvider = remoteNamesProvider + self.remoteURLProvider = remoteURLProvider + self.searchDebounce = searchDebounce + self.now = now + for name in [Notification.Name.repositoryRemoteRefsDidRefresh, .repositoryDidChange] { + notificationCenter.publisher(for: name) + .sink { [weak self] notification in + // Other windows post for their own repositories. + guard let url = notification.userInfo?["repositoryURL"] as? URL, + url.standardizedFileURL == repositoryURL.standardizedFileURL else { return } + Task { @MainActor in await self?.discoverRemotes() } + } + .store(in: &observers) + } + } + + // MARK: - Remotes + + /// Finds remotes with a supported tracker: `origin` first, then the rest in Git's order. + func discoverRemotes() async { + let names = await remoteNamesProvider(repositoryURL) + var found: [HostedIssueRemote] = [] + for name in names { + guard let url = await remoteURLProvider(repositoryURL, name), + let repository = credentialResolver.repository(forRemoteURL: url) else { continue } + found.append(HostedIssueRemote(name: name, provider: HostedIssueProvider(repository.provider), repository: repository)) + } + found = found.filter { $0.name == "origin" } + found.filter { $0.name != "origin" } + if restoredRemoteName == nil { + restoredRemoteName = .some(await preferenceStore.remoteName(forRepositoryKey: repositoryKey)) + } + let stored: String? = restoredRemoteName ?? nil + let preferred = selectedRemote?.name ?? stored + let selection = found.first { $0.name == preferred } ?? found.first + remotes = found + hasDiscoveredRemotes = true + guard selection != selectedRemote else { return } + await applyRemote(selection) + } + + func selectRemote(named name: String) { + guard let remote = remotes.first(where: { $0.name == name }), remote != selectedRemote else { return } + let preferenceStore = preferenceStore + let repositoryKey = repositoryKey + Task { + await preferenceStore.saveRemoteName(name, forRepositoryKey: repositoryKey) + await applyRemote(remote) + } + } + + private func applyRemote(_ remote: HostedIssueRemote?) async { + selectedRemote = remote + filter = .default + if let remote { + filter = await preferenceStore.filter(forRepositoryKey: repositoryKey, remote: remote.name) ?? .default + } + guard remote == selectedRemote else { return } + items = [] + next = nil + hasLoadedList = false + workItemTypes = [] + clearSelection() + if isActive { reload(useCache: true) } + } + + // MARK: - Screen lifecycle + + /// Called while the screen is shown and access is allowed. + func activate() async { + // Discover first so choosing the initial remote does not start a second load. + if !hasDiscoveredRemotes { await discoverRemotes() } + isActive = true + let stale = lastLoadedAt.map { now().timeIntervalSince($0) > Self.listCacheTTL } ?? true + if !hasLoadedList || stale { reload(useCache: !stale) } + } + + func deactivate() { + isActive = false + } + + /// Reloads the list and the open issue; Refresh is the way to bypass both caches. + func refresh() { + detailCache.removeAll() + reload(useCache: false) + if let number = selectedIssueNumber { loadDetail(number) } + } + + func updateFilter(_ update: (inout HostedIssueFilter) -> Void) { + var updated = filter + update(&updated) + guard updated != filter, let remote = selectedRemote else { return } + filter = updated + let preferenceStore = preferenceStore + let repositoryKey = repositoryKey + Task { await preferenceStore.save(updated, forRepositoryKey: repositoryKey, remote: remote.name) } + reload(useCache: true) + } + + func resetFilters() { + searchTask?.cancel() + if !searchText.isEmpty { + searchText = "" + searchTask?.cancel() + } + if filter.isDefault { reload(useCache: false) } else { updateFilter { $0 = .default } } + } + + // MARK: - Loading + + private struct Context { + var remote: HostedIssueRemote + var service: any HostedIssueProviding + var account: GitProviderAccount + var token: GitProviderToken + } + + private func context() -> Context? { + guard let remote = selectedRemote, let service = services[remote.provider] else { return nil } + let accounts = credentialResolver.matchingAccounts(for: remote.repository) + let host = GitProviderHost(kind: remote.repository.provider, baseURL: remote.repository.hostURL).normalized + guard !accounts.isEmpty else { + accountProblem = .noAccount(host) + return nil + } + guard let credential = credentialResolver.credential(for: accounts, preferredAccountID: accountID) else { + accountProblem = accounts.contains(where: GitProviderAPICredentialResolver.supportsProviderAPI) + ? .reconnect(host) : .noAccount(host) + return nil + } + accountProblem = nil + accountID = credential.account.id + return Context(remote: remote, service: service, account: credential.account, token: credential.token) + } + + private func cacheKey(_ context: Context, search: String) -> String { + [context.remote.name, context.account.id, filter.state.rawValue, filter.relationship.rawValue, search].joined(separator: "\n") + } + + private func reload(useCache: Bool, keeping pinned: HostedIssueSummary? = nil) { + loadTask?.cancel() + generation += 1 + let generation = generation + guard let context = context() else { + items = [] + next = nil + error = nil + isLoading = false + isLoadingMore = false + return + } + let search = searchText.trimmingCharacters(in: .whitespacesAndNewlines) + let key = cacheKey(context, search: search) + if useCache, pinned == nil, let cached = listCache[key], now().timeIntervalSince(cached.loadedAt) <= Self.listCacheTTL { + apply(cached.page, key: key, loadedAt: cached.loadedAt, pinned: nil) + return + } + let filter = filter + isLoading = true + isLoadingMore = false + loadTask = Task { + defer { if generation == self.generation { isLoading = false } } + do { + let page = try await context.service.listIssues( + repository: context.remote.repository, account: context.account, token: context.token, + filter: filter, search: search, cursor: nil + ) + guard generation == self.generation else { return } + let loadedAt = now() + listCache[key] = (page, loadedAt) + apply(page, key: key, loadedAt: loadedAt, pinned: pinned) + } catch { + guard generation == self.generation, !(error is CancellationError) else { return } + self.error = Self.issueError(error) + } + } + } + + private func apply(_ page: HostedIssuePage, key: String, loadedAt: Date, pinned: HostedIssueSummary?) { + var items = page.items + // A just-written issue stays visible until the next refresh even if it left the filter. + if let pinned { + if let index = items.firstIndex(where: { $0.number == pinned.number }) { + items[index] = pinned + } else { + let oldIndex = self.items.firstIndex { $0.number == pinned.number } ?? 0 + items.insert(pinned, at: min(oldIndex, items.count)) + } + } + self.items = items + next = page.next + error = nil + hasLoadedList = true + loadedKey = key + lastLoadedAt = loadedAt + } + + func loadMore() { + guard let cursor = next, !isLoading, !isLoadingMore, error == nil, let context = context() else { return } + let generation = generation + let filter = filter + let search = searchText.trimmingCharacters(in: .whitespacesAndNewlines) + isLoadingMore = true + loadTask = Task { + defer { if generation == self.generation { isLoadingMore = false } } + do { + let page = try await context.service.listIssues( + repository: context.remote.repository, account: context.account, token: context.token, + filter: filter, search: search, cursor: cursor + ) + guard generation == self.generation else { return } + items += page.items.filter { issue in !items.contains { $0.number == issue.number } } + next = page.next + } catch { + guard generation == self.generation, !(error is CancellationError) else { return } + self.error = Self.issueError(error) + } + } + } + + private func scheduleSearch() { + searchTask?.cancel() + let delay = searchDebounce + searchTask = Task { + try? await Task.sleep(for: delay) + guard !Task.isCancelled else { return } + reload(useCache: true) + } + } + + // MARK: - Detail + + func select(_ number: Int?) { + guard number != selectedIssueNumber else { return } + detailGeneration += 1 + selectedIssueNumber = number + writeError = nil + detail = nil + detailError = nil + isLoadingDetail = false + guard let number else { return } + // Going back to an issue seen in the last few minutes shows it without a request. + if let key = detailKey(number), let cached = detailCache[key], + now().timeIntervalSince(cached.loadedAt) <= Self.detailCacheTTL { + detail = cached.detail + return + } + loadDetail(number) + } + + private func detailKey(_ number: Int) -> String? { + guard let remote = selectedRemote else { return nil } + return [remote.name, accountID ?? "", String(number)].joined(separator: "\n") + } + + private func storeDetail(_ detail: HostedIssueDetail, number: Int) { + guard let key = detailKey(number) else { return } + detailCache[key] = (detail, now()) + } + + private func clearSelection() { + detailGeneration += 1 + selectedIssueNumber = nil + detail = nil + detailError = nil + writeError = nil + isLoadingDetail = false + } + + private func loadDetail(_ number: Int) { + detailGeneration += 1 + let generation = detailGeneration + guard let context = context() else { return } + isLoadingDetail = true + Task { + defer { if generation == detailGeneration { isLoadingDetail = false } } + do { + let detail = try await context.service.issueDetail(number: number, repository: context.remote.repository, token: context.token) + guard generation == detailGeneration else { return } + storeDetail(detail, number: number) + self.detail = detail + detailError = nil + } catch { + guard generation == detailGeneration, !(error is CancellationError) else { return } + detailError = Self.issueError(error) + } + } + } + + func loadWorkItemTypes() async { + guard provider?.supportsWorkItemTypes == true, workItemTypes.isEmpty, let context = context() else { return } + workItemTypes = (try? await context.service.workItemTypes(repository: context.remote.repository, token: context.token)) ?? [] + } + + // MARK: - Writes + + /// Creates an issue and selects it. Returns whether it succeeded so the sheet can close. + @discardableResult + func createIssue(_ draft: HostedIssueDraft) async -> Bool { + let title = draft.title.trimmingCharacters(in: .whitespacesAndNewlines) + guard !title.isEmpty else { return false } + var draft = draft + draft.title = title + guard let summary = await write({ context in + try await context.service.createIssue(draft, repository: context.remote.repository, token: context.token) + }) else { return false } + selectedIssueNumber = summary.number + detail = nil + loadDetail(summary.number) + reload(useCache: false, keeping: summary) + return true + } + + /// Posts a comment on the selected issue. Returns whether it succeeded so the composer can clear. + @discardableResult + func addComment(_ body: String) async -> Bool { + let text = body.trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty, let number = selectedIssueNumber else { return false } + guard await write({ context in + try await context.service.addComment(text, number: number, repository: context.remote.repository, token: context.token) + }) != nil else { return false } + await reloadAfterWrite(number) + return true + } + + func setState(_ state: HostedIssueState) async { + guard let number = selectedIssueNumber else { return } + guard await write({ context in + try await context.service.setState(state, number: number, repository: context.remote.repository, token: context.token) + }) != nil else { return } + await reloadAfterWrite(number) + } + + private func write(_ operation: (Context) async throws -> Result) async -> Result? { + guard !isWriting else { return nil } + // Claimed before the access check suspends, so a second write cannot slip in meanwhile. + isWriting = true + defer { isWriting = false } + writeError = nil + guard await authorizeWrite(), let context = context() else { return nil } + do { + return try await operation(context) + } catch { + writeError = Self.issueError(error) + return nil + } + } + + private func reloadAfterWrite(_ number: Int) async { + guard let context = context() else { return } + detailGeneration += 1 + let generation = detailGeneration + do { + let detail = try await context.service.issueDetail(number: number, repository: context.remote.repository, token: context.token) + storeDetail(detail, number: number) + guard generation == detailGeneration, selectedIssueNumber == number else { return } + self.detail = detail + reload(useCache: false, keeping: detail.summary) + } catch { + guard generation == detailGeneration else { return } + detailError = Self.issueError(error) + reload(useCache: false) + } + } + + func clearWriteError() { + writeError = nil + } + + static func issueError(_ error: Error) -> HostedIssueError { + if let error = error as? HostedIssueError { return error } + if error is DecodingError { + return .providerMessage("The provider returned a response Commit+ could not read.") + } + return .providerMessage(error.localizedDescription) + } +} diff --git a/macgit/App/PullRequestController.swift b/macgit/App/PullRequestController.swift index 4de93b9d..f8af6677 100644 --- a/macgit/App/PullRequestController.swift +++ b/macgit/App/PullRequestController.swift @@ -111,7 +111,7 @@ final class PullRequestController: ObservableObject { @Published private(set) var accountConnectionHost: GitProviderHost? private let providerAccountController: GitProviderAccountController - private let tokenVault: GitProviderTokenVault + private let credentialResolver: GitProviderAPICredentialResolver private let services: [GitProviderKind: any PullRequestProviding] private let remoteNameProvider: (URL) async -> String? private let remoteURLProvider: (URL, String) async -> String? @@ -219,7 +219,10 @@ final class PullRequestController: ObservableObject { diskCache: PullRequestDiskCache? = nil ) { self.providerAccountController = providerAccountController - self.tokenVault = tokenVault + self.credentialResolver = GitProviderAPICredentialResolver( + providerAccountController: providerAccountController, + tokenVault: tokenVault + ) self.services = services self.remoteNameProvider = remoteNameProvider self.remoteURLProvider = remoteURLProvider @@ -323,24 +326,11 @@ final class PullRequestController: ObservableObject { detailErrorMessage = "No remotes configured." return } - guard let remoteIdentity = GitRemoteIdentityResolver.identity( - from: remoteURLString, - knownGitLabHosts: connectedGitLabHosts, - knownHosts: providerAccountController.accounts.map { - GitProviderHost(kind: $0.provider, baseURL: $0.hostURL) - } - ) else { + guard let repository = credentialResolver.repository(forRemoteURL: remoteURLString) else { detailErrorMessage = PullRequestProviderError.unsupportedProvider.localizedDescription return } - - let repository = GitRepositoryIdentity( - provider: remoteIdentity.provider, - hostURL: remoteIdentity.hostURL, - owner: remoteIdentity.ownerPath, - name: remoteIdentity.repositoryName - ) - let matchingAccounts = matchingAccounts(for: repository) + let matchingAccounts = credentialResolver.matchingAccounts(for: repository) guard !matchingAccounts.isEmpty else { accountConnectionHost = GitProviderHost( kind: repository.provider, @@ -349,12 +339,12 @@ final class PullRequestController: ObservableObject { detailErrorMessage = "Connect Account..." return } - guard let apiCredential = apiCredential(for: matchingAccounts) else { + guard let apiCredential = credentialResolver.credential(for: matchingAccounts, preferredAccountID: selectedProviderAccountID) else { accountConnectionHost = GitProviderHost( kind: repository.provider, baseURL: repository.hostURL ).normalized - detailErrorMessage = matchingAccounts.contains(where: supportsProviderAPI) + detailErrorMessage = matchingAccounts.contains(where: GitProviderAPICredentialResolver.supportsProviderAPI) ? "Reconnect..." : "Connect Account..." return @@ -409,11 +399,7 @@ final class PullRequestController: ObservableObject { accountConnectionHost = nil defer { if listLoadID == loadID { isLoading = false } } - guard let remoteIdentity = GitRemoteIdentityResolver.identity( - from: remoteURLString, - knownGitLabHosts: connectedGitLabHosts, - knownHosts: providerAccountController.accounts.map { GitProviderHost(kind: $0.provider, baseURL: $0.hostURL) } - ) else { + guard let repository = credentialResolver.repository(forRemoteURL: remoteURLString) else { hasLoadedList = false displayedListKey = nil items = [] @@ -425,16 +411,9 @@ final class PullRequestController: ObservableObject { errorMessage = PullRequestProviderError.unsupportedProvider.localizedDescription return } - - let repository = GitRepositoryIdentity( - provider: remoteIdentity.provider, - hostURL: remoteIdentity.hostURL, - owner: remoteIdentity.ownerPath, - name: remoteIdentity.repositoryName - ) activeRemoteURLString = remoteURLString - let matchingAccounts = matchingAccounts(for: repository) + let matchingAccounts = credentialResolver.matchingAccounts(for: repository) guard !matchingAccounts.isEmpty else { hasLoadedList = false displayedListKey = nil @@ -448,7 +427,7 @@ final class PullRequestController: ObservableObject { return } - guard let apiCredential = apiCredential(for: matchingAccounts) else { + guard let apiCredential = credentialResolver.credential(for: matchingAccounts, preferredAccountID: selectedProviderAccountID) else { hasLoadedList = false displayedListKey = nil items = [] @@ -457,7 +436,7 @@ final class PullRequestController: ObservableObject { activeRepository = nil activeToken = nil accountConnectionHost = GitProviderHost(kind: repository.provider, baseURL: repository.hostURL).normalized - errorMessage = matchingAccounts.contains(where: supportsProviderAPI) ? "Reconnect..." : "Connect Account..." + errorMessage = matchingAccounts.contains(where: GitProviderAPICredentialResolver.supportsProviderAPI) ? "Reconnect..." : "Connect Account..." return } if selectedProviderAccountID != apiCredential.account.id @@ -592,23 +571,10 @@ final class PullRequestController: ObservableObject { guard let remoteURLString = await remoteURLProvider(repositoryURL, remoteName) else { throw PullRequestProviderError.repositoryUnavailable } - guard let remoteIdentity = GitRemoteIdentityResolver.identity( - from: remoteURLString, - knownGitLabHosts: connectedGitLabHosts, - knownHosts: providerAccountController.accounts.map { - GitProviderHost(kind: $0.provider, baseURL: $0.hostURL) - } - ) else { + guard let repository = credentialResolver.repository(forRemoteURL: remoteURLString) else { throw PullRequestProviderError.unsupportedProvider } - - let repository = GitRepositoryIdentity( - provider: remoteIdentity.provider, - hostURL: remoteIdentity.hostURL, - owner: remoteIdentity.ownerPath, - name: remoteIdentity.repositoryName - ) - guard let credential = apiCredential(for: matchingAccounts(for: repository)) else { + guard let credential = credentialResolver.credential(for: credentialResolver.matchingAccounts(for: repository), preferredAccountID: selectedProviderAccountID) else { throw PullRequestProviderError.reauthorizationRequired } guard let service = services[repository.provider] else { @@ -1121,13 +1087,6 @@ final class PullRequestController: ObservableObject { } } - private func matchingAccounts(for repository: GitRepositoryIdentity) -> [GitProviderAccount] { - let repositoryHost = normalizedHost(repository.hostURL) - return providerAccountController.accounts.filter { account in - account.provider == repository.provider && normalizedHost(account.hostURL) == repositoryHost - } - } - private func apply(_ page: PullRequestListPage) { items = page.items currentPage = page.page @@ -1179,54 +1138,12 @@ final class PullRequestController: ObservableObject { clearSelectedDetail() } - private func apiCredential(for accounts: [GitProviderAccount]) -> ( - account: GitProviderAccount, - token: GitProviderToken - )? { - let prioritizedAccounts = prioritizedAccounts(accounts) - for account in prioritizedAccounts { - guard supportsProviderAPI(account) else { continue } - do { - guard let token = try tokenVault.readToken(for: account), !token.accessToken.isEmpty else { - continue - } - return (account, token) - } catch { - continue - } - } - return nil - } - - private func prioritizedAccounts(_ accounts: [GitProviderAccount]) -> [GitProviderAccount] { - guard let selectedProviderAccountID, - let selected = accounts.first(where: { $0.id == selectedProviderAccountID }) else { - return accounts - } - return [selected] + accounts.filter { $0.id != selected.id } - } - - private func supportsProviderAPI(_ account: GitProviderAccount) -> Bool { - account.transportProtocol == .https || account.permissions["authentication"] == "personalAccessToken" || !account.scopes.isEmpty - } - private func resetPagination() { currentPage = 1 hasPreviousPage = false hasNextPage = false } - private var connectedGitLabHosts: Set { - Set(providerAccountController.accounts.compactMap { account in - guard account.provider == .gitlab else { return nil } - return normalizedHost(account.hostURL) - }) - } - - private func normalizedHost(_ url: URL) -> String { - GitProviderHost.identityKey(url) - } - private func suggestedTitle(for branch: String) -> String { let branchSuffix = branch.split(separator: "/").last.map(String.init) ?? branch let words = branchSuffix diff --git a/macgit/Models/FeatureAccessNotice.swift b/macgit/Models/FeatureAccessNotice.swift index 2b82081c..4e617c2b 100644 --- a/macgit/Models/FeatureAccessNotice.swift +++ b/macgit/Models/FeatureAccessNotice.swift @@ -105,6 +105,8 @@ extension PlanFeature { "PR-based merge detection" case .jiraIssues: "Jira Issues" + case .hostedIssues: + "Issue tracking" } } } diff --git a/macgit/Models/FeatureAccessPolicy.swift b/macgit/Models/FeatureAccessPolicy.swift index dc9b4d55..148f0bfe 100644 --- a/macgit/Models/FeatureAccessPolicy.swift +++ b/macgit/Models/FeatureAccessPolicy.swift @@ -31,6 +31,7 @@ enum PlanFeature: String, CaseIterable, Codable, Hashable { case multipleProviderAccounts case branchMergeDetection case jiraIssues + case hostedIssues } enum FeatureRepositoryScope: String, Codable, Equatable { @@ -79,7 +80,7 @@ struct FeatureAccessPolicy: Codable, Equatable { static let bundled = FeatureAccessPolicy( schemaVersion: supportedSchemaVersion, - revision: 8, + revision: 9, features: [ .privateRepositories: FeaturePolicyRule( enabled: true, @@ -108,7 +109,12 @@ struct FeatureAccessPolicy: Codable, Equatable { .aiBringYourOwnKey: proOnlyRule, .multipleProviderAccounts: proOnlyRule, .branchMergeDetection: proOnlyRule, - .jiraIssues: proOnlyRule + .jiraIssues: proOnlyRule, + .hostedIssues: FeaturePolicyRule( + enabled: true, + free: PlanFeatureRule(enabled: true, repositoryScope: .public), + pro: PlanFeatureRule(enabled: true, repositoryScope: .all) + ) ] ) diff --git a/macgit/Models/GitProviderAccountModels.swift b/macgit/Models/GitProviderAccountModels.swift index 74b33a8c..ff936d4a 100644 --- a/macgit/Models/GitProviderAccountModels.swift +++ b/macgit/Models/GitProviderAccountModels.swift @@ -226,6 +226,9 @@ struct GitProviderToken: Equatable, Codable { var refreshToken: String? var expiresAt: Date? var tokenType: String + /// The Basic-auth user for REST calls when it differs from the Git username. Bitbucket API + /// tokens authenticate with the Atlassian account email. Kept with the token, never synced. + var apiUsername: String? } struct GitRepositoryIdentity: Equatable, Codable { diff --git a/macgit/Models/HostedIssueModels.swift b/macgit/Models/HostedIssueModels.swift new file mode 100644 index 00000000..265b2414 --- /dev/null +++ b/macgit/Models/HostedIssueModels.swift @@ -0,0 +1,284 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +import Foundation + +/// The issue tracker that belongs to a recognized remote's provider. +enum HostedIssueProvider: String, Codable, Equatable { + case github + case gitlab + case bitbucket + case azureBoards + + init(_ kind: GitProviderKind) { + switch kind { + case .github: self = .github + case .gitlab: self = .gitlab + case .bitbucket: self = .bitbucket + case .azureDevOps: self = .azureBoards + } + } + + var sidebarTitle: String { + switch self { + case .github: "GitHub Issues" + case .gitlab: "GitLab Issues" + case .bitbucket: "Bitbucket Issues" + case .azureBoards: "Azure Boards" + } + } + + /// Asset-catalog image shared with the repository picker. + var iconName: String { + switch self { + case .github: "github" + case .gitlab: "gitlab" + case .bitbucket: "bitbucket" + case .azureBoards: "azure" + } + } + + var accountKind: GitProviderKind { + switch self { + case .github: .github + case .gitlab: .gitlab + case .bitbucket: .bitbucket + case .azureBoards: .azureDevOps + } + } + + /// `AB#42` is how Azure DevOps links work items from commits and pull requests. + func reference(for number: Int) -> String { + self == .azureBoards ? "AB#\(number)" : "#\(number)" + } + + /// Azure work items belong to a project; the other trackers belong to the repository. + var supportsWorkItemTypes: Bool { self == .azureBoards } +} + +enum HostedIssueState: String, Codable, Equatable { + case open + case closed +} + +enum HostedIssueStateFilter: String, Codable, CaseIterable, Identifiable { + case open + case closed + case all + + var id: String { rawValue } + + var title: String { + switch self { + case .open: "Open" + case .closed: "Closed" + case .all: "All" + } + } +} + +enum HostedIssueRelationship: String, Codable, CaseIterable, Identifiable { + case all + case assignedToMe + case createdByMe + + var id: String { rawValue } + + var title: String { + switch self { + case .all: "All" + case .assignedToMe: "Assigned to Me" + case .createdByMe: "Created by Me" + } + } +} + +/// Persisted per repository and remote; search text is never part of it. +struct HostedIssueFilter: Codable, Equatable { + var state: HostedIssueStateFilter = .open + var relationship: HostedIssueRelationship = .all + + static let `default` = HostedIssueFilter() + + var isDefault: Bool { self == .default } +} + +struct HostedIssuePerson: Codable, Equatable, Hashable { + var id: String + var displayName: String + var avatarURL: URL? +} + +struct HostedIssueLabel: Codable, Equatable, Hashable { + var name: String + /// Hex without `#`, when the provider has one. + var color: String? +} + +enum HostedIssueTextFormat: String, Codable, Equatable { + case markdown + case html +} + +struct HostedIssueSummary: Identifiable, Equatable, Codable { + var id: Int { number } + var number: Int + var title: String + var state: HostedIssueState + /// The provider's own state name when it says more than open/closed, such as "On hold" or "Active". + var stateName: String? + var workItemType: String? + var author: HostedIssuePerson? + var assignees: [HostedIssuePerson] + var labels: [HostedIssueLabel] + var createdAt: Date? + var updatedAt: Date? + var webURL: URL? +} + +struct HostedIssueComment: Identifiable, Equatable, Codable { + var id: String + var author: HostedIssuePerson? + var body: String + var format: HostedIssueTextFormat + var createdAt: Date? +} + +struct HostedIssueDetail: Equatable, Codable { + var summary: HostedIssueSummary + var body: String + var bodyFormat: HostedIssueTextFormat + var comments: [HostedIssueComment] + /// Set when the comments endpoint failed but the issue itself loaded. + var commentsUnavailable = false +} + +/// Where the next page starts. Each provider paginates differently. +enum HostedIssueCursor: Equatable { + case page(Int) + case url(URL) + /// Azure answers a query with every matching ID up front; details are fetched in chunks. + case workItemIDs([Int]) +} + +struct HostedIssuePage: Equatable { + var items: [HostedIssueSummary] + var next: HostedIssueCursor? +} + +struct HostedIssueDraft: Equatable { + var title: String + var body: String + var workItemType: String? +} + +enum HostedIssueError: LocalizedError, Equatable { + case trackerDisabled + /// A phrase completing "The connected account needs …", such as "the Work Items scope". + case missingScope(String) + case organizationAccessRequired + case reauthorizationRequired + case rateLimited(retryAfter: Date?) + case notFound + case closeUnavailable(String) + /// The saved account lacks something the issue API needs, fixed by editing it in Settings → Connections. + case accountUpdateRequired(String) + case providerMessage(String) + + var errorDescription: String? { + switch self { + case .trackerDisabled: + "Issues are turned off for this repository." + case .missingScope(let requirement): + "The connected account needs \(requirement)." + case .organizationAccessRequired: + "The repository's organization has not granted Commit+ access." + case .reauthorizationRequired: + "The Git provider account needs to be connected again." + case .rateLimited(let retryAfter): + if let retryAfter { + "The provider is busy. Try again \(retryAfter.formatted(.relative(presentation: .named)))." + } else { + "The provider is busy. Try again in a moment." + } + case .notFound: + "The issue or repository could not be found with the connected account." + case .closeUnavailable(let reason), .accountUpdateRequired(let reason): + reason + case .providerMessage(let message): + message + } + } +} + +protocol HostedIssueProviding { + func listIssues( + repository: GitRepositoryIdentity, + account: GitProviderAccount, + token: GitProviderToken, + filter: HostedIssueFilter, + search: String, + cursor: HostedIssueCursor? + ) async throws -> HostedIssuePage + + func issueDetail( + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueDetail + + func workItemTypes(repository: GitRepositoryIdentity, token: GitProviderToken) async throws -> [String] + + func createIssue( + _ draft: HostedIssueDraft, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueSummary + + func addComment( + _ body: String, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws + + func setState( + _ state: HostedIssueState, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws +} + +extension HostedIssueProviding { + func workItemTypes(repository: GitRepositoryIdentity, token: GitProviderToken) async throws -> [String] { + [] + } +} + +extension JSONDecoder { + /// ISO 8601 with or without fractional seconds. GitLab sends milliseconds and Azure sends + /// up to seven fractional digits, which `ISO8601DateFormatter` rejects, so they are cut to three. + static func hostedIssueDecoder() -> JSONDecoder { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .custom { decoder in + let value = try decoder.singleValueContainer().decode(String.self) + if let date = parseHostedIssueDate(value) { return date } + throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Invalid date \(value)")) + } + return decoder + } +} + +func parseHostedIssueDate(_ value: String) -> Date? { + let plain = ISO8601DateFormatter() + if let date = plain.date(from: value) { return date } + var trimmed = value + if let dot = value.firstIndex(of: ".") { + let fractionEnd = value[dot...].dropFirst().firstIndex { !$0.isNumber } ?? value.endIndex + let digits = value[value.index(after: dot)..-` branch names for Jira issues, e.g. `PROJ-123-fix-login-crash`. -enum JiraBranchNameSuggester { +enum IssueBranchNameSuggester { static let maxLength = 60 static func name(key: String, summary: String) -> String { @@ -42,7 +42,7 @@ enum JiraBranchNameSuggester { } /// How a branch is started from a Jira issue: a plain branch, or a Git Flow topic. -enum JiraBranchTarget: Hashable, Identifiable { +enum IssueBranchTarget: Hashable, Identifiable { case plainBranch case gitFlow(GitFlowTopicKind) @@ -61,12 +61,12 @@ enum JiraBranchTarget: Hashable, Identifiable { } /// Release topics are named after versions, not issues, so they are not offered. - static func options(gitFlowEnabled: Bool) -> [JiraBranchTarget] { + static func options(gitFlowEnabled: Bool) -> [IssueBranchTarget] { guard gitFlowEnabled else { return [.plainBranch] } return [.gitFlow(.feature), .gitFlow(.bugfix), .gitFlow(.hotfix), .plainBranch] } - static func suggested(forIssueType issueTypeName: String, gitFlowEnabled: Bool) -> JiraBranchTarget { + static func suggested(forIssueType issueTypeName: String, gitFlowEnabled: Bool) -> IssueBranchTarget { guard gitFlowEnabled else { return .plainBranch } switch issueTypeName.lowercased() { case "bug", "defect": return .gitFlow(.bugfix) diff --git a/macgit/Models/RepositoryBookmarkRemote.swift b/macgit/Models/RepositoryBookmarkRemote.swift index 6e18ab36..9aa65bc7 100644 --- a/macgit/Models/RepositoryBookmarkRemote.swift +++ b/macgit/Models/RepositoryBookmarkRemote.swift @@ -16,8 +16,9 @@ struct RepositoryBookmarkRemote: Identifiable, Equatable { switch identity.provider { case .github, .bitbucket: webURL.appending(path: "issues") case .gitlab: webURL.appending(path: "-/issues") - // Azure Repos has no per-repository issues page. - case .azureDevOps, .generic: nil + // Azure tracks work items per project: `{org}/{project}/_git/{repo}` → `{org}/{project}/_workitems`. + case .azureDevOps: webURL.deletingLastPathComponent().deletingLastPathComponent().appending(path: "_workitems") + case .generic: nil } } diff --git a/macgit/Services/AzureBoardsWorkItemService.swift b/macgit/Services/AzureBoardsWorkItemService.swift new file mode 100644 index 00000000..5965424c --- /dev/null +++ b/macgit/Services/AzureBoardsWorkItemService.swift @@ -0,0 +1,440 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +import Foundation + +/// Azure DevOps Services work items of the remote's project (REST api-version 7.1). +/// `repository.hostURL` is the organization URL and `repository.owner` the project. +struct AzureBoardsWorkItemService: HostedIssueProviding { + static let apiVersion = "7.1" + /// Work item comments are still a preview API; pinned here so one place changes. + static let commentsAPIVersion = "7.1-preview.4" + /// The maximum `workitemsbatch` accepts; also one list page. + static let batchSize = 200 + static let readScope = "a valid personal access token with the Work Items (Read) scope" + static let writeScope = "a personal access token with the Work Items (Read & write) scope" + + private let httpClient: GitProviderHTTPClient + private let decoder = JSONDecoder.hostedIssueDecoder() + + init(httpClient: GitProviderHTTPClient = URLSessionGitProviderHTTPClient()) { + self.httpClient = httpClient + } + + func listIssues( + repository: GitRepositoryIdentity, + account: GitProviderAccount, + token: GitProviderToken, + filter: HostedIssueFilter, + search: String, + cursor: HostedIssueCursor? + ) async throws -> HostedIssuePage { + let states = try await stateCatalog(repository: repository, token: token) + let ids: [Int] + if case .workItemIDs(let remaining) = cursor { + ids = remaining + } else { + let query = Self.wiql(filter: filter, search: search, closedStates: states.closedStateNames) + let request = try jsonRequest(url: projectURL(repository, ["wiql"]), token: token, method: "POST", body: ["query": query]) + let (data, _) = try await send(request) + ids = try decoder.decode(AzureWIQLResponse.self, from: data).workItems.map(\.id) + } + let pageIDs = Array(ids.prefix(Self.batchSize)) + let rest = Array(ids.dropFirst(Self.batchSize)) + guard !pageIDs.isEmpty else { return HostedIssuePage(items: [], next: nil) } + + let request = try jsonRequest(url: organizationURL(repository, ["wit", "workitemsbatch"]), token: token, method: "POST", body: [ + "ids": pageIDs, + "fields": AzureWorkItemResponse.listFields, + ]) + let (data, _) = try await send(request) + let byID = Dictionary( + try decoder.decode(AzureListResponse.self, from: data).value.map { ($0.id, $0) }, + uniquingKeysWith: { first, _ in first } + ) + // The batch endpoint does not keep the query's order. + let items = pageIDs.compactMap { byID[$0]?.summary(repository: repository, states: states) } + return HostedIssuePage(items: items, next: rest.isEmpty ? nil : .workItemIDs(rest)) + } + + func issueDetail( + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueDetail { + let states = try await stateCatalog(repository: repository, token: token) + let item = try await workItem(number, repository: repository, token: token) + + var comments: [HostedIssueComment] = [] + var commentsUnavailable = false + do { + let url = try projectURL(repository, ["workItems", String(number), "comments"], + query: [URLQueryItem(name: "order", value: "asc")], + apiVersion: Self.commentsAPIVersion) + let (data, _) = try await send(AzureDevOpsProviderAuthService.apiRequest(url: url, token: token)) + comments = try decoder.decode(AzureCommentsResponse.self, from: data).comments.map(\.comment) + } catch let error as HostedIssueError where error == .reauthorizationRequired { + throw error + } catch { + commentsUnavailable = true + } + return HostedIssueDetail( + summary: item.summary(repository: repository, states: states), + body: item.fields.description ?? "", + bodyFormat: .html, + comments: comments, + commentsUnavailable: commentsUnavailable + ) + } + + func workItemTypes(repository: GitRepositoryIdentity, token: GitProviderToken) async throws -> [String] { + try await types(repository: repository, token: token).filter { !($0.isDisabled ?? false) }.map(\.name) + } + + func createIssue( + _ draft: HostedIssueDraft, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueSummary { + guard let type = draft.workItemType, !type.isEmpty else { + throw HostedIssueError.providerMessage("Choose a work item type.") + } + var operations: [[String: Any]] = [["op": "add", "path": "/fields/System.Title", "value": draft.title]] + if !draft.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + operations.append(["op": "add", "path": "/fields/System.Description", "value": HostedIssueHTMLText.html(fromPlainText: draft.body)]) + } + let request = try patchRequest(url: projectURL(repository, ["workitems", "$" + type]), token: token, method: "POST", operations: operations) + let (data, _) = try await send(request, write: true) + let states = try await stateCatalog(repository: repository, token: token) + return try decoder.decode(AzureWorkItemResponse.self, from: data).summary(repository: repository, states: states) + } + + func addComment( + _ body: String, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws { + let url = try projectURL(repository, ["workItems", String(number), "comments"], apiVersion: Self.commentsAPIVersion) + let request = try jsonRequest(url: url, token: token, method: "POST", body: ["text": HostedIssueHTMLText.html(fromPlainText: body)]) + _ = try await send(request, write: true) + } + + func setState( + _ state: HostedIssueState, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws { + let item = try await workItem(number, repository: repository, token: token) + let types = try await types(repository: repository, token: token) + let type = item.fields.workItemType ?? "" + let wanted: AzureStateCategory = state == .closed ? .completed : .proposed + guard let target = types.first(where: { $0.name == type })?.states?.first(where: { $0.category == wanted }) else { + throw HostedIssueError.closeUnavailable(state == .closed + ? "\(type) work items have no Completed state, so Commit+ cannot close this one." + : "\(type) work items have no Proposed state, so Commit+ cannot reopen this one.") + } + let request = try patchRequest( + url: projectURL(repository, ["workitems", String(number)]), + token: token, + method: "PATCH", + operations: [["op": "add", "path": "/fields/System.State", "value": target.name]] + ) + _ = try await send(request, write: true) + } + + // MARK: - Queries + + static func wiql(filter: HostedIssueFilter, search: String, closedStates: [String]) -> String { + var clauses = ["[System.TeamProject] = @project"] + let closedList = closedStates.map(quoted).joined(separator: ", ") + switch filter.state { + case .open where !closedStates.isEmpty: clauses.append("[System.State] NOT IN (\(closedList))") + case .closed where !closedStates.isEmpty: clauses.append("[System.State] IN (\(closedList))") + // No Completed or Removed states at all: every work item is open. + case .closed: clauses.append("[System.Id] < 0") + case .open, .all: break + } + switch filter.relationship { + case .assignedToMe: clauses.append("[System.AssignedTo] = @Me") + case .createdByMe: clauses.append("[System.CreatedBy] = @Me") + case .all: break + } + let text = search.trimmingCharacters(in: .whitespacesAndNewlines) + if !text.isEmpty { + let number = text.replacingOccurrences(of: "AB#", with: "", options: .caseInsensitive) + .trimmingCharacters(in: CharacterSet(charactersIn: "#")) + if let id = Int(number) { + clauses.append("[System.Id] = \(id)") + } else { + clauses.append("[System.Title] CONTAINS \(quoted(text))") + } + } + return "SELECT [System.Id] FROM WorkItems WHERE " + clauses.joined(separator: " AND ") + + " ORDER BY [System.ChangedDate] DESC" + } + + private static func quoted(_ value: String) -> String { + "'" + value.replacingOccurrences(of: "'", with: "''") + "'" + } + + private func stateCatalog(repository: GitRepositoryIdentity, token: GitProviderToken) async throws -> AzureStateCatalog { + AzureStateCatalog(types: try await types(repository: repository, token: token)) + } + + private func types(repository: GitRepositoryIdentity, token: GitProviderToken) async throws -> [AzureWorkItemTypeResponse] { + let (data, _) = try await send(AzureDevOpsProviderAuthService.apiRequest(url: projectURL(repository, ["workitemtypes"]), token: token)) + return try decoder.decode(AzureListResponse.self, from: data).value + } + + private func workItem(_ id: Int, repository: GitRepositoryIdentity, token: GitProviderToken) async throws -> AzureWorkItemResponse { + let url = try projectURL(repository, ["workitems", String(id)]) + let (data, _) = try await send(AzureDevOpsProviderAuthService.apiRequest(url: url, token: token)) + return try decoder.decode(AzureWorkItemResponse.self, from: data) + } + + // MARK: - Requests + + private func projectURL(_ repository: GitRepositoryIdentity, _ path: [String], query: [URLQueryItem] = [], + apiVersion: String = Self.apiVersion) throws -> URL { + try url(repository.hostURL.appending(path: repository.owner).appending(path: "_apis/wit"), path, query: query, apiVersion: apiVersion) + } + + private func organizationURL(_ repository: GitRepositoryIdentity, _ path: [String]) throws -> URL { + try url(repository.hostURL.appending(path: "_apis"), path, query: [], apiVersion: Self.apiVersion) + } + + private func url(_ base: URL, _ path: [String], query: [URLQueryItem], apiVersion: String) throws -> URL { + var url = base + for component in path { url = url.appending(path: component) } + guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { throw HostedIssueError.notFound } + components.queryItems = query + [URLQueryItem(name: "api-version", value: apiVersion)] + guard let result = components.url else { throw HostedIssueError.notFound } + return result + } + + private func jsonRequest(url: URL, token: GitProviderToken, method: String, body: [String: Any]) throws -> URLRequest { + var request = AzureDevOpsProviderAuthService.apiRequest(url: url, token: token) + request.httpMethod = method + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [.sortedKeys]) + return request + } + + private func patchRequest(url: URL, token: GitProviderToken, method: String, operations: [[String: Any]]) throws -> URLRequest { + var request = AzureDevOpsProviderAuthService.apiRequest(url: url, token: token) + request.httpMethod = method + request.setValue("application/json-patch+json", forHTTPHeaderField: "Content-Type") + request.httpBody = try JSONSerialization.data(withJSONObject: operations, options: [.sortedKeys]) + return request + } + + private func send(_ request: URLRequest, write: Bool = false) async throws -> (Data, HTTPURLResponse) { + let (data, response) = try await httpClient.data(for: request) + let contentType = response.value(forHTTPHeaderField: "Content-Type")?.lowercased() ?? "" + // 203 or an HTML page is how Azure DevOps answers a token it no longer accepts. + if response.statusCode == 203 || ((200..<300).contains(response.statusCode) && contentType.contains("text/html")) { + throw HostedIssueError.reauthorizationRequired + } + guard !(200..<300).contains(response.statusCode) else { return (data, response) } + let message = (try? decoder.decode(AzureErrorResponse.self, from: data))?.message ?? "" + switch response.statusCode { + // The token already passed the organization check when it was connected, so a 401 or 403 + // here almost always means the PAT lacks the Work Items scope. + case 401, 403: + throw HostedIssueError.missingScope(write ? Self.writeScope : Self.readScope) + case 404: + throw HostedIssueError.notFound + case 429: + let retryAfter = response.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init) + throw HostedIssueError.rateLimited(retryAfter: retryAfter.map { Date(timeIntervalSinceNow: $0) }) + default: + throw HostedIssueError.providerMessage( + message.isEmpty ? "Azure DevOps work item request failed (HTTP \(response.statusCode))." : message + ) + } + } +} + +/// Azure HTML shown as text: tags dropped, images never loaded, entities decoded. +enum HostedIssueHTMLText { + static func plainText(fromHTML html: String) -> String { + var text = html + let replacements: [(String, String)] = [ + ("(?i)", "\n"), + ("(?i)", "\n"), + ("(?i)]*>", "\n• "), + ("(?is)<(script|style)[^>]*>.*?", ""), + ("(?s)<[^>]+>", ""), + ] + for (pattern, replacement) in replacements { + text = text.replacingOccurrences(of: pattern, with: replacement, options: .regularExpression) + } + text = decodeEntities(text) + text = text.replacingOccurrences(of: "[ \\t]+\\n", with: "\n", options: .regularExpression) + .replacingOccurrences(of: "\\n{3,}", with: "\n\n", options: .regularExpression) + return text.trimmingCharacters(in: .whitespacesAndNewlines) + } + + static func html(fromPlainText text: String) -> String { + text.replacingOccurrences(of: "&", with: "&") + .replacingOccurrences(of: "<", with: "<") + .replacingOccurrences(of: ">", with: ">") + .replacingOccurrences(of: "\n", with: "
") + } + + private static func decodeEntities(_ text: String) -> String { + var result = text + for (entity, value) in [(" ", " "), ("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("'", "'")] { + result = result.replacingOccurrences(of: entity, with: value) + } + if let regex = try? NSRegularExpression(pattern: "&#(x?)([0-9a-fA-F]+);") { + for match in regex.matches(in: result, range: NSRange(result.startIndex..., in: result)).reversed() { + guard let range = Range(match.range, in: result), + let hexRange = Range(match.range(at: 1), in: result), + let digitsRange = Range(match.range(at: 2), in: result), + let code = UInt32(result[digitsRange], radix: result[hexRange].isEmpty ? 10 : 16), + let scalar = Unicode.Scalar(code) else { continue } + result.replaceSubrange(range, with: String(Character(scalar))) + } + } + // Last, so "&lt;" stays "<". + return result.replacingOccurrences(of: "&", with: "&") + } +} + +private enum AzureStateCategory: String, Decodable { + case proposed = "Proposed" + case inProgress = "InProgress" + case resolved = "Resolved" + case completed = "Completed" + case removed = "Removed" + case other + + init(from decoder: Decoder) throws { + self = AzureStateCategory(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .other + } +} + +private struct AzureWorkItemTypeResponse: Decodable { + struct State: Decodable { + var name: String + var category: AzureStateCategory? + } + + var name: String + var isDisabled: Bool? + var states: [State]? +} + +private struct AzureStateCatalog { + private var closedByType: [String: Set] = [:] + private(set) var closedStateNames: [String] = [] + + init(types: [AzureWorkItemTypeResponse]) { + var names = Set() + for type in types { + let closed = Set((type.states ?? []).filter { $0.category == .completed || $0.category == .removed }.map(\.name)) + closedByType[type.name] = closed + names.formUnion(closed) + } + closedStateNames = names.sorted() + } + + func isClosed(state: String, type: String) -> Bool { + closedByType[type]?.contains(state) ?? closedStateNames.contains(state) + } +} + +private struct AzureListResponse: Decodable { + var value: [Value] +} + +private struct AzureWIQLResponse: Decodable { + struct Reference: Decodable { var id: Int } + var workItems: [Reference] +} + +private struct AzureErrorResponse: Decodable { + var message: String +} + +private struct AzureIdentity: Decodable { + var id: String? + var displayName: String? + var uniqueName: String? + var imageUrl: URL? + + var person: HostedIssuePerson { + HostedIssuePerson(id: id ?? uniqueName ?? displayName ?? "", displayName: displayName ?? uniqueName ?? "", avatarURL: nil) + } +} + +private struct AzureWorkItemResponse: Decodable { + static let listFields = [ + "System.Id", "System.Title", "System.State", "System.WorkItemType", "System.CreatedBy", + "System.AssignedTo", "System.Tags", "System.CreatedDate", "System.ChangedDate", + ] + + struct Fields: Decodable { + var title: String? + var state: String? + var workItemType: String? + var createdBy: AzureIdentity? + var assignedTo: AzureIdentity? + var tags: String? + var createdDate: Date? + var changedDate: Date? + var description: String? + + enum CodingKeys: String, CodingKey { + case title = "System.Title" + case state = "System.State" + case workItemType = "System.WorkItemType" + case createdBy = "System.CreatedBy" + case assignedTo = "System.AssignedTo" + case tags = "System.Tags" + case createdDate = "System.CreatedDate" + case changedDate = "System.ChangedDate" + case description = "System.Description" + } + } + + var id: Int + var fields: Fields + + func summary(repository: GitRepositoryIdentity, states: AzureStateCatalog) -> HostedIssueSummary { + let state = fields.state ?? "" + let type = fields.workItemType ?? "" + return HostedIssueSummary( + number: id, + title: fields.title ?? "", + state: states.isClosed(state: state, type: type) ? .closed : .open, + stateName: state.isEmpty ? nil : state, + workItemType: type.isEmpty ? nil : type, + author: fields.createdBy?.person, + assignees: fields.assignedTo.map { [$0.person] } ?? [], + labels: (fields.tags ?? "").split(separator: ";") + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + .map { HostedIssueLabel(name: $0, color: nil) }, + createdAt: fields.createdDate, + updatedAt: fields.changedDate, + webURL: repository.hostURL.appending(path: repository.owner).appending(path: "_workitems/edit/\(id)") + ) + } +} + +private struct AzureCommentsResponse: Decodable { + struct Comment: Decodable { + var id: Int + var text: String? + var createdBy: AzureIdentity? + var createdDate: Date? + + var comment: HostedIssueComment { + HostedIssueComment(id: String(id), author: createdBy?.person, body: text ?? "", format: .html, createdAt: createdDate) + } + } + + var comments: [Comment] +} diff --git a/macgit/Services/BitbucketIssueService.swift b/macgit/Services/BitbucketIssueService.swift new file mode 100644 index 00000000..59123b7e --- /dev/null +++ b/macgit/Services/BitbucketIssueService.swift @@ -0,0 +1,312 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +import Foundation + +/// Bitbucket Cloud repository issues through the 2.0 REST API. +struct BitbucketIssueService: HostedIssueProviding { + static let pageSize = 30 + static let openStates = ["new", "open", "on hold"] + static let closedStates = ["resolved", "invalid", "duplicate", "wontfix", "closed"] + static let missingEmailMessage = "Add your Atlassian account email to the Bitbucket account in Settings → Connections to use Bitbucket Issues." + + private let httpClient: GitProviderHTTPClient + private let apiBaseURL: URL + private let decoder = JSONDecoder.hostedIssueDecoder() + + init( + httpClient: GitProviderHTTPClient = URLSessionGitProviderHTTPClient(), + apiBaseURL: URL = GitProviderHost.bitbucketDotOrg.apiURL + ) { + self.httpClient = httpClient + self.apiBaseURL = apiBaseURL + } + + func listIssues( + repository: GitRepositoryIdentity, + account: GitProviderAccount, + token: GitProviderToken, + filter: HostedIssueFilter, + search: String, + cursor: HostedIssueCursor? + ) async throws -> HostedIssuePage { + let url: URL + if case .url(let next) = cursor { + url = next + } else { + var clauses: [String] = [] + switch filter.state { + case .open: clauses.append(Self.stateClause(Self.openStates)) + case .closed: clauses.append(Self.stateClause(Self.closedStates)) + case .all: break + } + if filter.relationship != .all { + let uuid = try await currentUserUUID(token: token) + let field = filter.relationship == .assignedToMe ? "assignee" : "reporter" + clauses.append("\(field).uuid=\(Self.quoted(uuid))") + } + let text = search.trimmingCharacters(in: .whitespacesAndNewlines) + if !text.isEmpty { + if let id = Int(text.trimmingCharacters(in: CharacterSet(charactersIn: "#"))) { + clauses.append("id=\(id)") + } else { + clauses.append("title~\(Self.quoted(text))") + } + } + var query = [ + URLQueryItem(name: "sort", value: "-updated_on"), + URLQueryItem(name: "pagelen", value: String(Self.pageSize)), + ] + if !clauses.isEmpty { + query.append(URLQueryItem(name: "q", value: clauses.joined(separator: " AND "))) + } + url = try issuesURL(repository, query: query) + } + let (data, _) = try await send(makeRequest(url: url, token: token)) + let page = try decoder.decode(BitbucketPage.self, from: data) + return HostedIssuePage(items: page.values.map(\.summary), next: page.next.map(HostedIssueCursor.url)) + } + + func issueDetail( + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueDetail { + let (data, _) = try await send(makeRequest(url: issuesURL(repository, path: [String(number)]), token: token)) + let issue = try decoder.decode(BitbucketIssueResponse.self, from: data) + + var comments: [HostedIssueComment] = [] + var commentsUnavailable = false + do { + var next: URL? = try issuesURL(repository, path: [String(number), "comments"], + query: [URLQueryItem(name: "pagelen", value: "100")]) + var pages = 0 + while let url = next, pages < 10 { + let (data, _) = try await send(makeRequest(url: url, token: token)) + let page = try decoder.decode(BitbucketPage.self, from: data) + // Entries without text record field changes, not comments. + comments += page.values.compactMap(\.comment) + next = page.next + pages += 1 + } + } catch let error as HostedIssueError where error == .reauthorizationRequired { + throw error + } catch { + commentsUnavailable = true + } + return HostedIssueDetail( + summary: issue.summary, + body: issue.content?.raw ?? "", + bodyFormat: .markdown, + comments: comments, + commentsUnavailable: commentsUnavailable + ) + } + + func createIssue( + _ draft: HostedIssueDraft, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueSummary { + let request = try makeJSONRequest(url: issuesURL(repository), token: token, method: "POST", body: [ + "title": draft.title, + "content": ["raw": draft.body], + ]) + let (data, _) = try await send(request, write: true) + return try decoder.decode(BitbucketIssueResponse.self, from: data).summary + } + + func addComment( + _ body: String, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws { + let request = try makeJSONRequest( + url: issuesURL(repository, path: [String(number), "comments"]), + token: token, + method: "POST", + body: ["content": ["raw": body]] + ) + _ = try await send(request, write: true) + } + + func setState( + _ state: HostedIssueState, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws { + let request = try makeJSONRequest( + url: issuesURL(repository, path: [String(number)]), + token: token, + method: "PUT", + body: ["state": state == .closed ? "resolved" : "open"] + ) + _ = try await send(request, write: true) + } + + // MARK: - Requests + + private func currentUserUUID(token: GitProviderToken) async throws -> String { + let (data, _) = try await send(makeRequest(url: apiBaseURL.appendingPathComponent("user"), token: token)) + return try decoder.decode(BitbucketUser.self, from: data).uuid ?? "" + } + + private static func stateClause(_ states: [String]) -> String { + "(" + states.map { "state=\(quoted($0))" }.joined(separator: " OR ") + ")" + } + + private static func quoted(_ value: String) -> String { + "\"" + value.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" + } + + private func issuesURL(_ repository: GitRepositoryIdentity, path: [String] = [], query: [URLQueryItem] = []) throws -> URL { + var url = apiBaseURL + .appendingPathComponent("repositories") + .appendingPathComponent(repository.owner) + .appendingPathComponent(repository.name) + .appendingPathComponent("issues") + for component in path { url.appendPathComponent(component) } + guard !query.isEmpty else { return url } + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) + components?.queryItems = query + guard let result = components?.url else { throw HostedIssueError.notFound } + return result + } + + private func makeRequest(url: URL, token: GitProviderToken) throws -> URLRequest { + guard let email = token.apiUsername?.trimmingCharacters(in: .whitespacesAndNewlines), !email.isEmpty else { + throw HostedIssueError.accountUpdateRequired(Self.missingEmailMessage) + } + var request = URLRequest(url: url) + request.setValue("application/json", forHTTPHeaderField: "Accept") + request.setValue("Basic " + Data("\(email):\(token.accessToken)".utf8).base64EncodedString(), forHTTPHeaderField: "Authorization") + return request + } + + private func makeJSONRequest(url: URL, token: GitProviderToken, method: String, body: [String: Any]) throws -> URLRequest { + var request = try makeRequest(url: url, token: token) + request.httpMethod = method + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [.sortedKeys]) + return request + } + + private func send(_ request: URLRequest, write: Bool = false) async throws -> (Data, HTTPURLResponse) { + let (data, response) = try await httpClient.data(for: request) + guard !(200..<300).contains(response.statusCode) else { return (data, response) } + let message = (try? decoder.decode(BitbucketErrorResponse.self, from: data))?.error.message ?? "" + switch response.statusCode { + case 401: + throw HostedIssueError.reauthorizationRequired + case 403: + throw HostedIssueError.missingScope(write + ? "an API token with the write:issue:bitbucket scope" + : "an API token with the read:issue:bitbucket scope") + case 404 where message.localizedCaseInsensitiveContains("issue tracker"): + throw HostedIssueError.trackerDisabled + case 404: + throw HostedIssueError.notFound + case 429: + let retryAfter = response.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init) + throw HostedIssueError.rateLimited(retryAfter: retryAfter.map { Date(timeIntervalSinceNow: $0) }) + default: + throw HostedIssueError.providerMessage( + message.isEmpty ? "Bitbucket issue request failed (HTTP \(response.statusCode))." : message + ) + } + } +} + +private struct BitbucketPage: Decodable { + var values: [Value] + var next: URL? +} + +private struct BitbucketErrorResponse: Decodable { + struct Detail: Decodable { var message: String } + var error: Detail +} + +private struct BitbucketUser: Decodable { + struct Links: Decodable { + struct Link: Decodable { var href: URL? } + var avatar: Link? + } + + var uuid: String? + var displayName: String? + var nickname: String? + var links: Links? + + enum CodingKeys: String, CodingKey { + case uuid, nickname, links + case displayName = "display_name" + } + + var person: HostedIssuePerson { + HostedIssuePerson(id: uuid ?? nickname ?? "", displayName: displayName ?? nickname ?? "", avatarURL: links?.avatar?.href) + } +} + +private struct BitbucketContent: Decodable { + var raw: String? +} + +private struct BitbucketIssueResponse: Decodable { + struct Links: Decodable { + struct Link: Decodable { var href: URL? } + var html: Link? + } + + var id: Int + var title: String + var state: String + var kind: String? + var priority: String? + var content: BitbucketContent? + var reporter: BitbucketUser? + var assignee: BitbucketUser? + var createdOn: Date? + var updatedOn: Date? + var links: Links? + + enum CodingKeys: String, CodingKey { + case id, title, state, kind, priority, content, reporter, assignee, links + case createdOn = "created_on" + case updatedOn = "updated_on" + } + + var summary: HostedIssueSummary { + let closed = BitbucketIssueService.closedStates.contains(state) + return HostedIssueSummary( + number: id, + title: title, + state: closed ? .closed : .open, + stateName: state.prefix(1).uppercased() + state.dropFirst(), + workItemType: nil, + author: reporter?.person, + assignees: assignee.map { [$0.person] } ?? [], + labels: [kind, priority].compactMap { $0 }.map { HostedIssueLabel(name: $0, color: nil) }, + createdAt: createdOn, + updatedAt: updatedOn, + webURL: links?.html?.href + ) + } +} + +private struct BitbucketCommentResponse: Decodable { + var id: Int + var content: BitbucketContent? + var user: BitbucketUser? + var createdOn: Date? + + enum CodingKeys: String, CodingKey { + case id, content, user + case createdOn = "created_on" + } + + var comment: HostedIssueComment? { + guard let raw = content?.raw, !raw.isEmpty else { return nil } + return HostedIssueComment(id: String(id), author: user?.person, body: raw, format: .markdown, createdAt: createdOn) + } +} diff --git a/macgit/Services/FeaturePolicyStore.swift b/macgit/Services/FeaturePolicyStore.swift index d65aa9c7..19826b57 100644 --- a/macgit/Services/FeaturePolicyStore.swift +++ b/macgit/Services/FeaturePolicyStore.swift @@ -96,7 +96,7 @@ enum FeaturePolicyDocumentDecoder { private extension PlanFeature { var requiresRepositoryScope: Bool { switch self { - case .privateRepositories, .pullRequests, .gitFlow, .gitLFS: + case .privateRepositories, .pullRequests, .gitFlow, .gitLFS, .hostedIssues: true case .aiCommitMessage, .repositoryChat, .repositoryAIActions, .aiConflictResolution, .aiBringYourOwnKey, .multipleProviderAccounts, .branchMergeDetection, .jiraIssues: diff --git a/macgit/Services/GitHubIssueService.swift b/macgit/Services/GitHubIssueService.swift new file mode 100644 index 00000000..638b8b7d --- /dev/null +++ b/macgit/Services/GitHubIssueService.swift @@ -0,0 +1,328 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +import Foundation + +/// GitHub.com and GitHub Enterprise Server issues through the REST API. +struct GitHubIssueService: HostedIssueProviding { + static let pageSize = 30 + + private let httpClient: GitProviderHTTPClient + private let apiBaseURL: URL + private let decoder: JSONDecoder + + init( + httpClient: GitProviderHTTPClient = URLSessionGitProviderHTTPClient(), + apiBaseURL: URL = URL(string: "https://api.github.com")! + ) { + self.httpClient = httpClient + self.apiBaseURL = apiBaseURL + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + self.decoder = decoder + } + + func listIssues( + repository: GitRepositoryIdentity, + account: GitProviderAccount, + token: GitProviderToken, + filter: HostedIssueFilter, + search: String, + cursor: HostedIssueCursor? + ) async throws -> HostedIssuePage { + let page: Int = if case .page(let value) = cursor { value } else { 1 } + let query = search.trimmingCharacters(in: .whitespacesAndNewlines) + // The issues endpoint has no text search; the search endpoint does, with a lower rate limit. + if !query.isEmpty { + var terms = ["repo:\(repository.owner)/\(repository.name)", "is:issue"] + switch filter.state { + case .open: terms.append("is:open") + case .closed: terms.append("is:closed") + case .all: break + } + switch filter.relationship { + case .assignedToMe: terms.append("assignee:\(account.username)") + case .createdByMe: terms.append("author:\(account.username)") + case .all: break + } + terms.append(query) + let url = try url(apiURL(for: repository).appendingPathComponent("search/issues"), query: [ + "q": terms.joined(separator: " "), + "sort": "updated", + "order": "desc", + "per_page": String(Self.pageSize), + "page": String(page), + ]) + let (data, response) = try await send(makeRequest(url: url, token: token)) + let result = try decoder.decode(GitHubIssueSearchResponse.self, from: data) + return HostedIssuePage( + items: result.items.filter { $0.pullRequest == nil }.map(\.summary), + next: hasNextPage(response) ? .page(page + 1) : nil + ) + } + + var items: [String: String] = [ + "state": filter.state.rawValue, + "sort": "updated", + "direction": "desc", + "per_page": String(Self.pageSize), + "page": String(page), + ] + switch filter.relationship { + case .assignedToMe: items["assignee"] = account.username + case .createdByMe: items["creator"] = account.username + case .all: break + } + let url = try url(issuesURL(for: repository), query: items) + let (data, response) = try await send(makeRequest(url: url, token: token)) + // The issues endpoint also returns pull requests. + let issues = try decoder.decode([GitHubIssueResponse].self, from: data).filter { $0.pullRequest == nil } + return HostedIssuePage(items: issues.map(\.summary), next: hasNextPage(response) ? .page(page + 1) : nil) + } + + func issueDetail( + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueDetail { + let issueURL = issuesURL(for: repository).appendingPathComponent(String(number)) + let (data, _) = try await send(makeRequest(url: issueURL, token: token)) + let issue = try decoder.decode(GitHubIssueResponse.self, from: data) + + var comments: [HostedIssueComment] = [] + var commentsUnavailable = false + var page = 1 + do { + while page <= 10 { + let url = try url(issueURL.appendingPathComponent("comments"), query: [ + "per_page": "100", + "page": String(page), + ]) + let (data, response) = try await send(makeRequest(url: url, token: token)) + comments += try decoder.decode([GitHubIssueCommentResponse].self, from: data).map(\.comment) + guard hasNextPage(response) else { break } + page += 1 + } + } catch let error as HostedIssueError where error == .reauthorizationRequired { + throw error + } catch { + commentsUnavailable = true + } + return HostedIssueDetail( + summary: issue.summary, + body: issue.body ?? "", + bodyFormat: .markdown, + comments: comments, + commentsUnavailable: commentsUnavailable + ) + } + + func createIssue( + _ draft: HostedIssueDraft, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueSummary { + let request = try makeJSONRequest( + url: issuesURL(for: repository), + token: token, + method: "POST", + body: ["title": draft.title, "body": draft.body] + ) + let (data, _) = try await send(request, write: true) + return try decoder.decode(GitHubIssueResponse.self, from: data).summary + } + + func addComment( + _ body: String, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws { + let request = try makeJSONRequest( + url: issuesURL(for: repository).appendingPathComponent(String(number)).appendingPathComponent("comments"), + token: token, + method: "POST", + body: ["body": body] + ) + _ = try await send(request, write: true) + } + + func setState( + _ state: HostedIssueState, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws { + let request = try makeJSONRequest( + url: issuesURL(for: repository).appendingPathComponent(String(number)), + token: token, + method: "PATCH", + body: ["state": state.rawValue] + ) + _ = try await send(request, write: true) + } + + // MARK: - Requests + + private func apiURL(for repository: GitRepositoryIdentity) -> URL { + let host = GitProviderHost(kind: .github, baseURL: repository.hostURL) + return host.normalized.baseURL == GitProviderHost.githubDotCom.baseURL ? apiBaseURL : host.apiURL + } + + private func issuesURL(for repository: GitRepositoryIdentity) -> URL { + apiURL(for: repository) + .appendingPathComponent("repos") + .appendingPathComponent(repository.owner) + .appendingPathComponent(repository.name) + .appendingPathComponent("issues") + } + + private func url(_ base: URL, query: [String: String]) throws -> URL { + var components = URLComponents(url: base, resolvingAgainstBaseURL: false) + components?.queryItems = query.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } + guard let url = components?.url else { throw HostedIssueError.notFound } + return url + } + + private func makeRequest(url: URL, token: GitProviderToken) -> URLRequest { + var request = URLRequest(url: url) + request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept") + request.setValue("Bearer \(token.accessToken)", forHTTPHeaderField: "Authorization") + return request + } + + private func makeJSONRequest( + url: URL, + token: GitProviderToken, + method: String, + body: [String: String] + ) throws -> URLRequest { + var request = makeRequest(url: url, token: token) + request.httpMethod = method + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try JSONEncoder().encode(body) + return request + } + + private func send(_ request: URLRequest, write: Bool = false) async throws -> (Data, HTTPURLResponse) { + let (data, response) = try await httpClient.data(for: request) + guard !(200..<300).contains(response.statusCode) else { return (data, response) } + throw Self.error(for: response, data: data, write: write, decoder: decoder) + } + + private func hasNextPage(_ response: HTTPURLResponse) -> Bool { + response.value(forHTTPHeaderField: "Link")? + .split(separator: ",") + .contains { $0.range(of: "rel=\"next\"") != nil } ?? false + } + + static func error(for response: HTTPURLResponse, data: Data, write: Bool, decoder: JSONDecoder) -> HostedIssueError { + let message = (try? decoder.decode(GitHubIssueErrorResponse.self, from: data).message) ?? "" + let remaining = response.value(forHTTPHeaderField: "x-ratelimit-remaining") + if response.statusCode == 429 || (response.statusCode == 403 && (remaining == "0" || message.localizedCaseInsensitiveContains("rate limit"))) { + if let retryAfter = response.value(forHTTPHeaderField: "retry-after").flatMap(TimeInterval.init) { + return .rateLimited(retryAfter: Date(timeIntervalSinceNow: retryAfter)) + } + let reset = response.value(forHTTPHeaderField: "x-ratelimit-reset").flatMap(TimeInterval.init) + return .rateLimited(retryAfter: reset.map(Date.init(timeIntervalSince1970:))) + } + switch response.statusCode { + case 401: + return .reauthorizationRequired + case 403 where message.localizedCaseInsensitiveContains("OAuth App access restrictions") + || message.localizedCaseInsensitiveContains("SAML"): + return .organizationAccessRequired + case 403 where write, 404 where write: + return .missingScope("write access to this repository") + case 404: + return .notFound + case 410: + return .trackerDisabled + default: + return .providerMessage(message.isEmpty ? "GitHub issue request failed (HTTP \(response.statusCode))." : message) + } + } +} + +private struct GitHubIssueErrorResponse: Decodable { + var message: String +} + +private struct GitHubIssueSearchResponse: Decodable { + var items: [GitHubIssueResponse] +} + +private struct GitHubIssueUser: Decodable { + var login: String + var avatarURL: URL? + + enum CodingKeys: String, CodingKey { + case login + case avatarURL = "avatar_url" + } + + var person: HostedIssuePerson { + HostedIssuePerson(id: login, displayName: login, avatarURL: avatarURL) + } +} + +private struct GitHubIssueResponse: Decodable { + struct Label: Decodable { + var name: String + var color: String? + } + + struct PullRequestMarker: Decodable {} + + var number: Int + var title: String + var state: String + var stateReason: String? + var body: String? + var htmlURL: URL? + var user: GitHubIssueUser? + var assignees: [GitHubIssueUser]? + var labels: [Label]? + var createdAt: Date? + var updatedAt: Date? + var pullRequest: PullRequestMarker? + + enum CodingKeys: String, CodingKey { + case number, title, state, body, user, assignees, labels + case stateReason = "state_reason" + case htmlURL = "html_url" + case createdAt = "created_at" + case updatedAt = "updated_at" + case pullRequest = "pull_request" + } + + var summary: HostedIssueSummary { + HostedIssueSummary( + number: number, + title: title, + state: state == "closed" ? .closed : .open, + stateName: stateReason == "not_planned" ? "Not planned" : nil, + workItemType: nil, + author: user?.person, + assignees: assignees?.map(\.person) ?? [], + labels: labels?.map { HostedIssueLabel(name: $0.name, color: $0.color) } ?? [], + createdAt: createdAt, + updatedAt: updatedAt, + webURL: htmlURL + ) + } +} + +private struct GitHubIssueCommentResponse: Decodable { + var id: Int + var body: String? + var user: GitHubIssueUser? + var createdAt: Date? + + enum CodingKeys: String, CodingKey { + case id, body, user + case createdAt = "created_at" + } + + var comment: HostedIssueComment { + HostedIssueComment(id: String(id), author: user?.person, body: body ?? "", format: .markdown, createdAt: createdAt) + } +} diff --git a/macgit/Services/GitLabIssueService.swift b/macgit/Services/GitLabIssueService.swift new file mode 100644 index 00000000..288b20b9 --- /dev/null +++ b/macgit/Services/GitLabIssueService.swift @@ -0,0 +1,286 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +import Foundation + +/// GitLab.com and self-managed GitLab issues through the v4 REST API. +struct GitLabIssueService: HostedIssueProviding { + static let pageSize = 30 + + private let httpClient: GitProviderHTTPClient + private let decoder = JSONDecoder.hostedIssueDecoder() + + init(httpClient: GitProviderHTTPClient = URLSessionGitProviderHTTPClient()) { + self.httpClient = httpClient + } + + func listIssues( + repository: GitRepositoryIdentity, + account: GitProviderAccount, + token: GitProviderToken, + filter: HostedIssueFilter, + search: String, + cursor: HostedIssueCursor? + ) async throws -> HostedIssuePage { + let page: Int = if case .page(let value) = cursor { value } else { 1 } + var query = [ + URLQueryItem(name: "order_by", value: "updated_at"), + URLQueryItem(name: "sort", value: "desc"), + URLQueryItem(name: "per_page", value: String(Self.pageSize)), + URLQueryItem(name: "page", value: String(page)), + ] + switch filter.state { + case .open: query.append(URLQueryItem(name: "state", value: "opened")) + case .closed: query.append(URLQueryItem(name: "state", value: "closed")) + case .all: break + } + let scope = switch filter.relationship { + case .all: "all" + case .assignedToMe: "assigned_to_me" + case .createdByMe: "created_by_me" + } + query.append(URLQueryItem(name: "scope", value: scope)) + let text = search.trimmingCharacters(in: .whitespacesAndNewlines) + if !text.isEmpty { + // A bare number is an IID; GitLab's text search does not match it. + if let iid = Int(text.trimmingCharacters(in: CharacterSet(charactersIn: "#"))) { + query.append(URLQueryItem(name: "iids[]", value: String(iid))) + } else { + query.append(URLQueryItem(name: "search", value: text)) + } + } + let url = try projectURL(repository, ["issues"], query: query) + let (data, response) = try await send(makeRequest(url: url, token: token)) + let issues = try decoder.decode([GitLabIssueResponse].self, from: data) + let nextPage = response.value(forHTTPHeaderField: "X-Next-Page").flatMap(Int.init) + return HostedIssuePage(items: issues.map(\.summary), next: nextPage.map(HostedIssueCursor.page)) + } + + func issueDetail( + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueDetail { + let (data, _) = try await send(makeRequest(url: projectURL(repository, ["issues", String(number)]), token: token)) + let issue = try decoder.decode(GitLabIssueResponse.self, from: data) + + var comments: [HostedIssueComment] = [] + var commentsUnavailable = false + var page = 1 + do { + while page <= 10 { + let url = try projectURL(repository, ["issues", String(number), "notes"], query: [ + URLQueryItem(name: "sort", value: "asc"), + URLQueryItem(name: "order_by", value: "created_at"), + URLQueryItem(name: "per_page", value: "100"), + URLQueryItem(name: "page", value: String(page)), + ]) + let (data, response) = try await send(makeRequest(url: url, token: token)) + comments += try decoder.decode([GitLabIssueNoteResponse].self, from: data) + .filter { !$0.system } + .map(\.comment) + guard let next = response.value(forHTTPHeaderField: "X-Next-Page").flatMap(Int.init) else { break } + page = next + } + } catch let error as HostedIssueError where error == .reauthorizationRequired { + throw error + } catch { + commentsUnavailable = true + } + return HostedIssueDetail( + summary: issue.summary, + body: issue.description ?? "", + bodyFormat: .markdown, + comments: comments, + commentsUnavailable: commentsUnavailable + ) + } + + func createIssue( + _ draft: HostedIssueDraft, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws -> HostedIssueSummary { + let request = try makeJSONRequest( + url: projectURL(repository, ["issues"]), + token: token, + method: "POST", + body: ["title": draft.title, "description": draft.body] + ) + let (data, _) = try await send(request, write: true) + return try decoder.decode(GitLabIssueResponse.self, from: data).summary + } + + func addComment( + _ body: String, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws { + let request = try makeJSONRequest( + url: projectURL(repository, ["issues", String(number), "notes"]), + token: token, + method: "POST", + body: ["body": body] + ) + _ = try await send(request, write: true) + } + + func setState( + _ state: HostedIssueState, + number: Int, + repository: GitRepositoryIdentity, + token: GitProviderToken + ) async throws { + let request = try makeJSONRequest( + url: projectURL(repository, ["issues", String(number)]), + token: token, + method: "PUT", + body: ["state_event": state == .closed ? "close" : "reopen"] + ) + _ = try await send(request, write: true) + } + + // MARK: - Requests + + private func projectURL(_ repository: GitRepositoryIdentity, _ path: [String], query: [URLQueryItem] = []) throws -> URL { + let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~")) + guard let project = "\(repository.owner)/\(repository.name)".addingPercentEncoding(withAllowedCharacters: allowed), + var components = URLComponents(url: repository.hostURL, resolvingAgainstBaseURL: false) else { + throw HostedIssueError.notFound + } + let base = components.percentEncodedPath.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + let suffix = path.map { "/\($0)" }.joined() + components.percentEncodedPath = (base.isEmpty ? "" : "/" + base) + "/api/v4/projects/\(project)\(suffix)" + components.queryItems = query.isEmpty ? nil : query + guard let url = components.url else { throw HostedIssueError.notFound } + return url + } + + private func makeRequest(url: URL, token: GitProviderToken) -> URLRequest { + var request = URLRequest(url: url) + request.setValue("application/json", forHTTPHeaderField: "Accept") + request.setValue("Bearer \(token.accessToken)", forHTTPHeaderField: "Authorization") + return request + } + + private func makeJSONRequest(url: URL, token: GitProviderToken, method: String, body: [String: String]) throws -> URLRequest { + var request = makeRequest(url: url, token: token) + request.httpMethod = method + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try JSONEncoder().encode(body) + return request + } + + private func send(_ request: URLRequest, write: Bool = false) async throws -> (Data, HTTPURLResponse) { + let (data, response) = try await httpClient.data(for: request) + guard !(200..<300).contains(response.statusCode) else { return (data, response) } + let message = (try? decoder.decode(GitLabIssueErrorResponse.self, from: data))?.text ?? "" + switch response.statusCode { + case 401: + throw HostedIssueError.reauthorizationRequired + case 403 where write: + throw HostedIssueError.missingScope("write access to this repository") + // GitLab answers 403 for a project whose issues feature is turned off or limited to members. + case 403: + throw HostedIssueError.trackerDisabled + case 404: + throw HostedIssueError.notFound + case 429: + let retryAfter = response.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init) + .map { Date(timeIntervalSinceNow: $0) } + ?? response.value(forHTTPHeaderField: "RateLimit-Reset").flatMap(TimeInterval.init) + .map(Date.init(timeIntervalSince1970:)) + throw HostedIssueError.rateLimited(retryAfter: retryAfter) + default: + throw HostedIssueError.providerMessage( + message.isEmpty ? "GitLab issue request failed (HTTP \(response.statusCode))." : message + ) + } + } +} + +private struct GitLabIssueErrorResponse: Decodable { + var message: String? + var error: String? + + var text: String? { message ?? error } + + enum CodingKeys: String, CodingKey { case message, error } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + // `message` is a string or an object of field errors. + message = (try? container.decode(String.self, forKey: .message)) + ?? (try? container.decode([String: [String]].self, forKey: .message))? + .map { "\($0.key) \($0.value.joined(separator: ", "))" }.sorted().joined(separator: "; ") + error = try? container.decode(String.self, forKey: .error) + } +} + +private struct GitLabIssueUser: Decodable { + var id: Int + var username: String + var name: String? + var avatarURL: URL? + + enum CodingKeys: String, CodingKey { + case id, username, name + case avatarURL = "avatar_url" + } + + var person: HostedIssuePerson { + HostedIssuePerson(id: username, displayName: name ?? username, avatarURL: avatarURL) + } +} + +private struct GitLabIssueResponse: Decodable { + var iid: Int + var title: String + var state: String + var description: String? + var webURL: URL? + var author: GitLabIssueUser? + var assignees: [GitLabIssueUser]? + var labels: [String]? + var createdAt: Date? + var updatedAt: Date? + + enum CodingKeys: String, CodingKey { + case iid, title, state, description, author, assignees, labels + case webURL = "web_url" + case createdAt = "created_at" + case updatedAt = "updated_at" + } + + var summary: HostedIssueSummary { + HostedIssueSummary( + number: iid, + title: title, + state: state == "closed" ? .closed : .open, + stateName: nil, + workItemType: nil, + author: author?.person, + assignees: assignees?.map(\.person) ?? [], + labels: labels?.map { HostedIssueLabel(name: $0, color: nil) } ?? [], + createdAt: createdAt, + updatedAt: updatedAt, + webURL: webURL + ) + } +} + +private struct GitLabIssueNoteResponse: Decodable { + var id: Int + var body: String + var system: Bool + var author: GitLabIssueUser? + var createdAt: Date? + + enum CodingKeys: String, CodingKey { + case id, body, system, author + case createdAt = "created_at" + } + + var comment: HostedIssueComment { + HostedIssueComment(id: String(id), author: author?.person, body: body, format: .markdown, createdAt: createdAt) + } +} diff --git a/macgit/Services/GitProviderAPICredentialResolver.swift b/macgit/Services/GitProviderAPICredentialResolver.swift new file mode 100644 index 00000000..ce20c73e --- /dev/null +++ b/macgit/Services/GitProviderAPICredentialResolver.swift @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +import Foundation + +/// Maps a remote to a provider repository and picks the connected account whose token +/// can call that provider's API. Shared by pull requests and hosted issues. +@MainActor +struct GitProviderAPICredentialResolver { + let accounts: () -> [GitProviderAccount] + let tokenVault: GitProviderTokenVault + + init(providerAccountController: GitProviderAccountController, tokenVault: GitProviderTokenVault) { + self.init(accounts: { [weak providerAccountController] in providerAccountController?.accounts ?? [] }, + tokenVault: tokenVault) + } + + init(accounts: @escaping () -> [GitProviderAccount], tokenVault: GitProviderTokenVault) { + self.accounts = accounts + self.tokenVault = tokenVault + } + + func repository(forRemoteURL remoteURLString: String) -> GitRepositoryIdentity? { + let accounts = accounts() + guard let identity = GitRemoteIdentityResolver.identity( + from: remoteURLString, + knownGitLabHosts: Set(accounts.compactMap { account in + account.provider == .gitlab ? Self.normalizedHost(account.hostURL) : nil + }), + knownHosts: accounts.map { GitProviderHost(kind: $0.provider, baseURL: $0.hostURL) } + ) else { return nil } + return GitRepositoryIdentity( + provider: identity.provider, + hostURL: identity.hostURL, + owner: identity.ownerPath, + name: identity.repositoryName + ) + } + + func matchingAccounts(for repository: GitRepositoryIdentity) -> [GitProviderAccount] { + let repositoryHost = Self.normalizedHost(repository.hostURL) + return accounts().filter { account in + account.provider == repository.provider && Self.normalizedHost(account.hostURL) == repositoryHost + } + } + + /// The first usable account, trying `preferredAccountID` first. + func credential( + for accounts: [GitProviderAccount], + preferredAccountID: String? = nil + ) -> (account: GitProviderAccount, token: GitProviderToken)? { + var prioritized = accounts + if let preferredAccountID, let selected = accounts.first(where: { $0.id == preferredAccountID }) { + prioritized = [selected] + accounts.filter { $0.id != selected.id } + } + for account in prioritized { + guard Self.supportsProviderAPI(account) else { continue } + guard let token = try? tokenVault.readToken(for: account), !token.accessToken.isEmpty else { continue } + return (account, token) + } + return nil + } + + static func supportsProviderAPI(_ account: GitProviderAccount) -> Bool { + account.transportProtocol == .https || account.permissions["authentication"] == "personalAccessToken" || !account.scopes.isEmpty + } + + static func normalizedHost(_ url: URL) -> String { + GitProviderHost.identityKey(url) + } +} diff --git a/macgit/Views/Account/GitProviderAddAccountSheet.swift b/macgit/Views/Account/GitProviderAddAccountSheet.swift index b0ed263e..6c3f8119 100644 --- a/macgit/Views/Account/GitProviderAddAccountSheet.swift +++ b/macgit/Views/Account/GitProviderAddAccountSheet.swift @@ -35,6 +35,7 @@ struct GitProviderAddAccountSheet: View { @State private var connectedUsername = "" @State private var bitbucketUsername = "" @State private var bitbucketAPIToken = "" + @State private var bitbucketEmail = "" @State private var azureOrganization = "" @State private var sshKeyPath = "" @State private var connectionTask: Task? @@ -89,6 +90,7 @@ struct GitProviderAddAccountSheet: View { personalAccessToken = "" bitbucketUsername = "" bitbucketAPIToken = "" + bitbucketEmail = "" azureOrganization = "" selectedAuthType = GitProviderAddAccountPresentationPolicy.usesTokenOnly(selectedHost) ? .personalAccessToken : .oauth } @@ -155,7 +157,9 @@ struct GitProviderAddAccountSheet: View { .disabled(editingAccount != nil) if selectedProtocol == .https { SecureField("API Token", text: $bitbucketAPIToken, prompt: savedTokenPrompt) - Text("Requires read:repository:bitbucket and write:repository:bitbucket scopes.") + TextField("Atlassian Email", text: $bitbucketEmail, prompt: Text(verbatim: "Optional, for Bitbucket Issues")) + .textContentType(.emailAddress) + Text("Requires read:repository:bitbucket and write:repository:bitbucket scopes. For Bitbucket Issues, also add read:issue:bitbucket and write:issue:bitbucket and enter your Atlassian account email; it stays on this Mac with the token.") .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) Button("Get API Token", action: openBitbucketAPITokenPage) @@ -478,6 +482,7 @@ struct GitProviderAddAccountSheet: View { await controller.connectBitbucket( username: bitbucketUsername, apiToken: bitbucketAPIToken, + atlassianEmail: bitbucketEmail, replacing: editingAccount ) if controller.errorMessage == nil { @@ -611,6 +616,9 @@ struct GitProviderAddAccountSheet: View { } private func loadExistingSSHKey() { + if let editingAccount, editingAccount.provider == .bitbucket, bitbucketEmail.isEmpty { + bitbucketEmail = controller.savedAPIUsername(for: editingAccount) ?? "" + } guard let editingAccount, let key = try? controller.sshKey(for: editingAccount) else { return diff --git a/macgit/Views/Common/ProUpgradeSheet.swift b/macgit/Views/Common/ProUpgradeSheet.swift index a53e912f..b820e790 100644 --- a/macgit/Views/Common/ProUpgradeSheet.swift +++ b/macgit/Views/Common/ProUpgradeSheet.swift @@ -168,7 +168,7 @@ struct ProUpgradeSheet: View { private var upgradeDescription: String { switch feature { - case .pullRequests, .gitFlow, .gitLFS: + case .pullRequests, .gitFlow, .gitLFS, .hostedIssues: "Upgrade to Commit+ Pro to use \(feature.displayName) in private repositories, plus advanced workflows and AI tools across your Macs." case .aiCommitMessage, .repositoryChat, .repositoryAIActions, .aiConflictResolution, .aiBringYourOwnKey, .multipleProviderAccounts, .branchMergeDetection, .jiraIssues: diff --git a/macgit/Views/Issues/HostedIssueDetailView.swift b/macgit/Views/Issues/HostedIssueDetailView.swift new file mode 100644 index 00000000..aa3afc08 --- /dev/null +++ b/macgit/Views/Issues/HostedIssueDetailView.swift @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import AppKit +import SwiftUI + +/// The selected issue's description and comments, with comment, close/reopen, and branch actions. +struct HostedIssueDetailView: View { + static let minimumWidth: CGFloat = 300 + static let defaultWidth: CGFloat = 420 + static let maximumWidth: CGFloat = 720 + + @Environment(\.appTextScale) private var textScale + @ObservedObject var controller: HostedIssueController + let provider: HostedIssueProvider + let summary: HostedIssueSummary? + let gitFlowEnabled: Bool + let onOpenConnections: () -> Void + let onCreateBranch: (HostedIssueSummary, IssueBranchTarget) -> Void + let onClose: () -> Void + @State private var commentDraft = "" + @State private var commentSelection: TextSelection? + + var body: some View { + VStack(spacing: 0) { + toolbar + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 14) { + if let summary { + header(summary) + } + if let error = controller.writeError { + writeErrorBanner(error) + } + if controller.isLoadingDetail, controller.detail == nil { + ProgressView() + .frame(maxWidth: .infinity) + } else if let error = controller.detailError, controller.detail == nil { + Label(error.localizedDescription, systemImage: "exclamationmark.triangle") + .foregroundStyle(.secondary) + } else if let detail = controller.detail { + body(of: detail) + comments(of: detail) + } + } + .padding(16) + .frame(maxWidth: .infinity, alignment: .leading) + } + Divider() + composer + } + .background(Color(nsColor: .textBackgroundColor)) + // Nothing inside the panel may draw over the issue list. + .clipped() + } + + // MARK: - Sections + + private var toolbar: some View { + HStack(spacing: 8) { + if let summary { + Menu { + HostedIssueActionsMenu(issue: summary, provider: provider, gitFlowEnabled: gitFlowEnabled) { + onCreateBranch(summary, $0) + } + } label: { + Label("Actions", systemImage: "ellipsis.circle") + } + .menuStyle(.borderlessButton) + .fixedSize() + Spacer() + stateButton(summary) + } else { + Spacer() + } + Button("Close Details", systemImage: "xmark", action: onClose) + .buttonStyle(.borderless) + .labelStyle(.iconOnly) + .help("Close") + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + } + + @ViewBuilder + private func stateButton(_ summary: HostedIssueSummary) -> some View { + let closing = summary.state == .open + Button(closing ? "Close Issue" : "Reopen Issue", systemImage: closing ? "checkmark.circle" : "arrow.uturn.backward.circle") { + Task { await controller.setState(closing ? .closed : .open) } + } + .disabled(controller.isWriting) + .help(closing ? "Close this issue on the tracker" : "Reopen this issue on the tracker") + } + + private func header(_ summary: HostedIssueSummary) -> some View { + VStack(alignment: .leading, spacing: 6) { + Text(summary.title) + .font(.title3.weight(.semibold).scaled(by: textScale)) + .textSelection(.enabled) + HStack(spacing: 6) { + Text(provider.reference(for: summary.number)) + .font(.callout.monospaced().scaled(by: textScale)) + .foregroundStyle(.secondary) + Text(summary.stateName ?? (summary.state == .open ? "Open" : "Closed")) + .font(.caption.weight(.medium).scaled(by: textScale)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background((summary.state == .open ? Color.green : Color.purple).opacity(0.15), in: Capsule()) + .foregroundStyle(summary.state == .open ? Color.green : Color.purple) + if let type = summary.workItemType { + Text(type) + .font(.caption.scaled(by: textScale)) + .foregroundStyle(.secondary) + } + } + metadataRow("Author", summary.author.map { [$0.displayName] } ?? []) + metadataRow("Assignees", summary.assignees.map(\.displayName)) + if !summary.labels.isEmpty { + HostedIssueLabelLayout(wraps: true) { + ForEach(summary.labels, id: \.self) { HostedIssueLabelChip(label: $0) } + } + } + if let createdAt = summary.createdAt { + Text("Created \(createdAt.formatted(date: .abbreviated, time: .shortened))" + + (summary.updatedAt.map { " · Updated \($0.formatted(.relative(presentation: .named)))" } ?? "")) + .font(.caption.scaled(by: textScale)) + .foregroundStyle(.secondary) + } + } + } + + @ViewBuilder + private func metadataRow(_ title: String, _ values: [String]) -> some View { + if !values.isEmpty { + Text("\(title): \(values.joined(separator: ", "))") + .font(.caption.scaled(by: textScale)) + .foregroundStyle(.secondary) + } + } + + @ViewBuilder + private func body(of detail: HostedIssueDetail) -> some View { + Divider() + if detail.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + Text("No description.") + .foregroundStyle(.secondary) + .italic() + } else { + richText(detail.body, format: detail.bodyFormat) + } + } + + @ViewBuilder + private func comments(of detail: HostedIssueDetail) -> some View { + Divider() + Text(detail.comments.isEmpty ? "No comments" : "\(detail.comments.count) comment\(detail.comments.count == 1 ? "" : "s")") + .font(.headline.scaled(by: textScale)) + if detail.commentsUnavailable { + Label("Comments could not be loaded.", systemImage: "exclamationmark.triangle") + .font(.callout.scaled(by: textScale)) + .foregroundStyle(.secondary) + } + ForEach(detail.comments) { comment in + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + Text(comment.author?.displayName ?? "Unknown") + .font(.callout.weight(.semibold).scaled(by: textScale)) + if let createdAt = comment.createdAt { + Text(createdAt.formatted(.relative(presentation: .named))) + .font(.caption.scaled(by: textScale)) + .foregroundStyle(.secondary) + } + } + richText(comment.body, format: comment.format) + } + .padding(10) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 8)) + } + } + + @ViewBuilder + private func richText(_ text: String, format: HostedIssueTextFormat) -> some View { + switch format { + case .markdown: + PullRequestMarkdownContent(content: text, baseURL: summary?.webURL ?? URL(string: "about:blank")!, textScale: textScale) + case .html: + // Azure HTML is shown as text so no remote content or script runs. + Text(HostedIssueHTMLText.plainText(fromHTML: text)) + .font(.body.scaled(by: textScale)) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + private func writeErrorBanner(_ error: HostedIssueError) -> some View { + HStack(alignment: .top, spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.orange) + Text(error.localizedDescription) + .font(.callout.scaled(by: textScale)) + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + switch error { + case .missingScope, .reauthorizationRequired, .accountUpdateRequired: + Button("Open Connections…", action: onOpenConnections) + .buttonStyle(.link) + default: + Button("Dismiss", action: controller.clearWriteError) + .buttonStyle(.link) + } + } + .padding(8) + .background(Color.orange.opacity(0.08), in: RoundedRectangle(cornerRadius: 6)) + } + + /// One line by default, growing with the draft up to three lines before it scrolls. + private var composer: some View { + HStack(alignment: .bottom, spacing: 8) { + TextField("Add a comment", text: $commentDraft, selection: $commentSelection, axis: .vertical) + .lineLimit(1...3) + // Shift-Return starts a new line, like chat apps; ⌘Return posts. + .onKeyPress(.return, phases: .down) { press in + guard press.modifiers.contains(.shift) else { return .ignored } + insertCommentNewline() + return .handled + } + .textFieldStyle(.plain) + .font(.body.scaled(by: textScale)) + .padding(.horizontal, 8) + .padding(.vertical, 6) + .background(Color.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6)) + if controller.isWriting { + ProgressView().controlSize(.small) + .padding(.bottom, 4) + } + Button("Comment", action: postComment) + .keyboardShortcut(.return, modifiers: .command) + .disabled(!canPostComment) + .padding(.bottom, 2) + } + .padding(12) + } + + /// Replaces the selection (or inserts at the caret) with a line break and keeps the caret after it. + private func insertCommentNewline() { + var range = commentDraft.endIndex.. Void + let onOpenGitHubOrganizationAccess: () -> Void + let gitFlowEnabled: Bool + let onCreateBranch: (String, String, IssueBranchTarget) -> Void + @State private var isCreatingIssue = false + @AppStorage("hostedIssues.detailPanelWidth") private var storedDetailPanelWidth = Double(HostedIssueDetailView.defaultWidth) + + private static let issueListMinimumWidth: CGFloat = 360 + + var body: some View { + VStack(spacing: 0) { + header + Divider() + if controller.accountProblem == nil, controller.selectedRemote != nil { + filterBar + Divider() + } + content + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + .task(id: isActive) { + if isActive { + await controller.activate() + } else { + controller.deactivate() + } + } + .sheet(isPresented: $isCreatingIssue) { + NewHostedIssueSheet(controller: controller) + } + } + + private var provider: HostedIssueProvider? { controller.provider } + + // MARK: - Header and filters + + private var header: some View { + HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 1) { + Text(provider?.sidebarTitle ?? "Issues") + .font(.headline.scaled(by: textScale)) + if let remote = controller.selectedRemote { + Text(subtitle(for: remote)) + .font(.caption.scaled(by: textScale)) + .foregroundStyle(.secondary) + } + } + Spacer() + if controller.accountProblem == nil, controller.selectedRemote != nil { + TextField("Search title or number", text: $controller.searchText) + .textFieldStyle(.roundedBorder) + .font(.body.scaled(by: textScale)) + .frame(width: 220 * textScale) + if controller.isLoading, controller.hasLoadedList { + ProgressView() + .controlSize(.small) + } + Button("Refresh Issues", systemImage: "arrow.clockwise", action: controller.refresh) + .buttonStyle(.borderless) + .labelStyle(.iconOnly) + .disabled(controller.isLoading) + .help("Refresh") + Button("New Issue…", systemImage: "plus") { isCreatingIssue = true } + .disabled(controller.error == .trackerDisabled) + .help("Create an issue on \(provider?.sidebarTitle ?? "the tracker")") + } + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .background(Color(nsColor: .controlBackgroundColor)) + } + + private func subtitle(for remote: HostedIssueRemote) -> String { + let path = remote.provider == .azureBoards + ? "Project \(remote.repository.owner)" + : "\(remote.repository.owner)/\(remote.repository.name)" + return "\(path) · \(remote.name)" + } + + private var filterBar: some View { + HStack(spacing: 6) { + if controller.remotes.count > 1 { + Menu { + Picker("Remote", selection: remoteBinding) { + ForEach(controller.remotes) { remote in + Text("\(remote.name) – \(remote.provider.sidebarTitle)").tag(remote.name) + } + } + .pickerStyle(.inline) + .labelsHidden() + } label: { + Label("Remote: \(controller.selectedRemote?.name ?? "")", systemImage: "network") + } + .modifier(HostedIssueFilterPill(isActive: controller.selectedRemote?.name != "origin")) + } + Menu { + Picker("State", selection: filterBinding(\.state)) { + ForEach(HostedIssueStateFilter.allCases) { Text($0.title).tag($0) } + } + .pickerStyle(.inline) + .labelsHidden() + } label: { + Label("State: \(controller.filter.state.title)", systemImage: "circle.dashed") + } + .modifier(HostedIssueFilterPill(isActive: controller.filter.state != .open)) + Menu { + Picker("Show", selection: filterBinding(\.relationship)) { + ForEach(HostedIssueRelationship.allCases) { Text($0.title).tag($0) } + } + .pickerStyle(.inline) + .labelsHidden() + } label: { + Label(controller.filter.relationship.title, systemImage: "person") + } + .modifier(HostedIssueFilterPill(isActive: controller.filter.relationship != .all)) + Spacer(minLength: 0) + if controller.isFiltered { + Button("Reset Filters", systemImage: "xmark.circle.fill", action: controller.resetFilters) + .buttonStyle(.borderless) + .foregroundStyle(.secondary) + } + } + .font(.callout.scaled(by: textScale)) + .menuStyle(.borderlessButton) + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 16) + .padding(.vertical, 7) + } + + private var remoteBinding: Binding { + Binding( + get: { controller.selectedRemote?.name ?? "" }, + set: { controller.selectRemote(named: $0) } + ) + } + + private func filterBinding(_ keyPath: WritableKeyPath) -> Binding { + Binding( + get: { controller.filter[keyPath: keyPath] }, + set: { value in controller.updateFilter { $0[keyPath: keyPath] = value } } + ) + } + + // MARK: - Content + + @ViewBuilder + private var content: some View { + if !controller.hasDiscoveredRemotes { + ProgressView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if controller.selectedRemote == nil { + ContentUnavailableView( + "No Issue Tracker", + systemImage: "checklist", + description: Text("Add a GitHub, GitLab, Bitbucket, or Azure Repos remote to see its issues here.") + ) + } else if let problem = controller.accountProblem { + accountProblemView(problem) + } else if controller.isLoading, !controller.hasLoadedList { + ProgressView("Loading issues…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let error = controller.error, controller.items.isEmpty { + errorView(error) + } else if controller.items.isEmpty { + emptyState + } else { + VStack(spacing: 0) { + if let error = controller.error { + errorBanner(error) + } + issueBrowser + } + } + } + + private func accountProblemView(_ problem: HostedIssueAccountProblem) -> some View { + let providerName = provider?.accountKind.displayName ?? "provider" + return ContentUnavailableView { + switch problem { + case .noAccount: + Label("Connect \(providerName)", systemImage: "person.crop.circle.badge.plus") + case .reconnect: + Label("Reconnect \(providerName)", systemImage: "exclamationmark.triangle") + } + } description: { + switch problem { + case .noAccount(let host): + Text("Connect a \(providerName) account for \(host.baseURL.host() ?? host.baseURL.absoluteString) to see this repository's issues.") + case .reconnect: + Text("The saved \(providerName) account needs to be connected again.") + } + } actions: { + switch problem { + case .noAccount: Button("Connect \(providerName)…", action: onOpenConnections) + case .reconnect: Button("Open Connections…", action: onOpenConnections) + } + } + } + + @ViewBuilder + private func errorView(_ error: HostedIssueError) -> some View { + ContentUnavailableView { + Label(errorTitle(error), systemImage: errorSymbol(error)) + } description: { + Text(error.localizedDescription) + } actions: { + errorActions(error) + } + } + + @ViewBuilder + private func errorActions(_ error: HostedIssueError) -> some View { + switch error { + case .trackerDisabled: + if let url = repositoryWebURL { + Button("Open Repository in Browser") { NSWorkspace.shared.open(url) } + } + case .missingScope, .reauthorizationRequired, .accountUpdateRequired: + Button("Open Connections…", action: onOpenConnections) + case .organizationAccessRequired: + if canManageGitHubOrganizationAccess { + Button("Manage Organization Access…", action: onOpenGitHubOrganizationAccess) + } + Button("Retry", action: controller.refresh) + default: + Button("Retry", action: controller.refresh) + } + } + + private func errorTitle(_ error: HostedIssueError) -> String { + switch error { + case .trackerDisabled: "Issues Are Turned Off" + case .missingScope: "More Access Needed" + case .organizationAccessRequired: "Organization Access Needed" + case .reauthorizationRequired: "Reconnect Account" + case .accountUpdateRequired: "Account Details Needed" + case .rateLimited: "\(provider?.accountKind.displayName ?? "Provider") Is Busy" + case .notFound: "Repository Not Found" + case .closeUnavailable, .providerMessage: "Issues Unavailable" + } + } + + private func errorSymbol(_ error: HostedIssueError) -> String { + switch error { + case .trackerDisabled: "checklist.unchecked" + case .missingScope, .organizationAccessRequired, .reauthorizationRequired, .accountUpdateRequired: "lock" + case .rateLimited: "hourglass" + default: "wifi.exclamationmark" + } + } + + private var repositoryWebURL: URL? { + guard let remote = controller.selectedRemote else { return nil } + let repository = remote.repository + switch remote.provider { + case .github, .gitlab: + return repository.hostURL.appending(path: repository.owner).appending(path: repository.name) + case .bitbucket: + return URL(string: "https://bitbucket.org")!.appending(path: repository.owner).appending(path: repository.name) + case .azureBoards: + return repository.hostURL.appending(path: repository.owner).appending(path: "_workitems") + } + } + + @ViewBuilder + private var emptyState: some View { + if controller.isFiltered { + ContentUnavailableView { + Label("No Matching Issues", systemImage: "line.3.horizontal.decrease.circle") + } description: { + Text("No issues match these filters.") + } actions: { + Button("Reset Filters", action: controller.resetFilters) + } + } else { + ContentUnavailableView( + "No Open Issues", + systemImage: "checkmark.circle", + description: Text("This tracker has no open issues.") + ) + } + } + + private func errorBanner(_ error: HostedIssueError) -> some View { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.orange) + Text(error.localizedDescription) + .foregroundStyle(.secondary) + Spacer() + Button("Retry", action: controller.refresh) + .buttonStyle(.link) + } + .font(.callout.scaled(by: textScale)) + .padding(.horizontal, 16) + .padding(.vertical, 6) + .background(Color.orange.opacity(0.08)) + } + + // MARK: - List and detail + + private var selectionBinding: Binding { + Binding(get: { controller.selectedIssueNumber }, set: { controller.select($0) }) + } + + private var issueBrowser: some View { + GeometryReader { proxy in + let maximumWidth = max( + HostedIssueDetailView.minimumWidth, + min(HostedIssueDetailView.maximumWidth, proxy.size.width - Self.issueListMinimumWidth) + ) + let width = Binding( + get: { min(maximumWidth, max(HostedIssueDetailView.minimumWidth, CGFloat(storedDetailPanelWidth))) }, + set: { storedDetailPanelWidth = Double($0) } + ) + HStack(spacing: 0) { + issueList + .frame(minWidth: Self.issueListMinimumWidth, maxWidth: .infinity, maxHeight: .infinity) + if let number = controller.selectedIssueNumber, let provider { + HostedIssueDetailView( + controller: controller, + provider: provider, + summary: controller.detail?.summary ?? controller.items.first { $0.number == number }, + gitFlowEnabled: gitFlowEnabled, + onOpenConnections: onOpenConnections, + onCreateBranch: { summary, target in onCreateBranch(String(summary.number), summary.title, target) }, + onClose: { controller.select(nil) } + ) + .id(number) + .frame(width: width.wrappedValue) + .frame(maxHeight: .infinity) + .overlay(alignment: .leading) { + RepositoryAIChatResizeHandle( + panelWidth: width, + minimumWidth: HostedIssueDetailView.minimumWidth, + maximumWidth: maximumWidth, + accessibilityLabel: "Resize Issue Details", + lineInset: 0 + ) + .frame(width: 8) + } + } + } + } + } + + private var issueList: some View { + List(selection: selectionBinding) { + ForEach(controller.items) { issue in + HostedIssueRow(issue: issue, provider: provider ?? .github) + .tag(issue.number) + .onAppear { + if issue.number == controller.items.last?.number { controller.loadMore() } + } + } + if controller.isLoadingMore { + HStack { + Spacer() + ProgressView().controlSize(.small) + Spacer() + } + } + } + .listStyle(.inset) + .contextMenu(forSelectionType: Int.self) { numbers in + if let issue = issue(for: numbers), let provider { + HostedIssueActionsMenu(issue: issue, provider: provider, gitFlowEnabled: gitFlowEnabled) { target in + onCreateBranch(String(issue.number), issue.title, target) + } + } + } primaryAction: { numbers in + if let url = issue(for: numbers)?.webURL { NSWorkspace.shared.open(url) } + } + } + + private func issue(for numbers: Set) -> HostedIssueSummary? { + guard let number = numbers.first else { return nil } + return controller.items.first { $0.number == number } + } +} + +/// Open, copy, and branch actions shared by the row menu and the detail pane. +struct HostedIssueActionsMenu: View { + let issue: HostedIssueSummary + let provider: HostedIssueProvider + let gitFlowEnabled: Bool + let onCreateBranch: (IssueBranchTarget) -> Void + + var body: some View { + if let url = issue.webURL { + Button("Open in Browser") { NSWorkspace.shared.open(url) } + } + Button("Copy Number") { HostedIssueClipboard.copy(provider.reference(for: issue.number)) } + Button("Copy Reference and Title") { + HostedIssueClipboard.copy("\(provider.reference(for: issue.number)) \(issue.title)") + } + Divider() + HostedIssueBranchMenu(issue: issue, gitFlowEnabled: gitFlowEnabled, onCreateBranch: onCreateBranch) + } +} + +struct HostedIssueBranchMenu: View { + let issue: HostedIssueSummary + let gitFlowEnabled: Bool + let onCreateBranch: (IssueBranchTarget) -> Void + + var body: some View { + let typeName = issue.workItemType ?? (issue.labels.contains { $0.name.lowercased() == "bug" } ? "Bug" : "") + let suggested = IssueBranchTarget.suggested(forIssueType: typeName, gitFlowEnabled: gitFlowEnabled) + let others = IssueBranchTarget.options(gitFlowEnabled: gitFlowEnabled).filter { $0 != suggested } + if others.isEmpty { + Button("Create Branch…") { onCreateBranch(suggested) } + } else { + Menu("Create Branch") { + Button(suggested.title) { onCreateBranch(suggested) } + Divider() + ForEach(others) { target in + Button(target.title) { onCreateBranch(target) } + } + } + } + } +} + +enum HostedIssueClipboard { + static func copy(_ text: String) { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(text, forType: .string) + } +} + +private struct HostedIssueRow: View { + @Environment(\.appTextScale) private var textScale + let issue: HostedIssueSummary + let provider: HostedIssueProvider + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: issue.state == .open ? "circle.circle" : "checkmark.circle") + .foregroundStyle(issue.state == .open ? Color.green : Color.purple) + .frame(width: 16) + .help(issue.stateName ?? (issue.state == .open ? "Open" : "Closed")) + // The title owns the first line; labels only use what is left of the second. + VStack(alignment: .leading, spacing: 3) { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(provider.reference(for: issue.number)) + .font(.body.monospaced().scaled(by: textScale)) + .foregroundStyle(.secondary) + .fixedSize() + Text(issue.title) + .font(.body.scaled(by: textScale)) + .lineLimit(1) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + if let stateName = issue.stateName { + Text(stateName) + .font(.caption.weight(.medium).scaled(by: textScale)) + .foregroundStyle(.secondary) + .fixedSize() + } + } + HStack(spacing: 8) { + if !metadata.isEmpty { + Text(metadata) + .font(.caption.scaled(by: textScale)) + .foregroundStyle(.secondary) + .lineLimit(1) + .layoutPriority(1) + } + if !issue.labels.isEmpty { + HostedIssueLabelLayout(wraps: false) { + ForEach(issue.labels, id: \.self) { HostedIssueLabelChip(label: $0) } + } + .clipped() + } + } + } + } + .padding(.vertical, 3) + } + + private var metadata: String { + var parts: [String] = [] + if let type = issue.workItemType { parts.append(type) } + if let author = issue.author?.displayName, !author.isEmpty { parts.append(author) } + if let updatedAt = issue.updatedAt { + parts.append("updated \(updatedAt.formatted(.relative(presentation: .named)))") + } + return parts.joined(separator: " · ") + } +} + +struct HostedIssueLabelChip: View { + @Environment(\.appTextScale) private var textScale + @Environment(\.backgroundProminence) private var backgroundProminence + let label: HostedIssueLabel + + var body: some View { + let tint = backgroundProminence == .increased ? Color.primary : (Color(hostedIssueHex: label.color) ?? .secondary) + Text(label.name) + .font(.caption.scaled(by: textScale)) + .lineLimit(1) + .padding(.horizontal, 6) + .padding(.vertical, 1) + .background(tint.opacity(0.15), in: Capsule()) + .foregroundStyle(tint) + .fixedSize() + } +} + +/// Lays out label chips without ever growing past the offered width. Wrapping layouts flow onto +/// more lines; single-line layouts drop the chips that do not fit instead of truncating the title. +struct HostedIssueLabelLayout: Layout { + var wraps: Bool + var spacing: CGFloat = 4 + + private struct Line { + var indices: [Int] = [] + var width: CGFloat = 0 + var height: CGFloat = 0 + } + + private func lines(for width: CGFloat, subviews: Subviews) -> [Line] { + var lines = [Line()] + for index in subviews.indices { + let size = subviews[index].sizeThatFits(.unspecified) + let needed = lines[lines.count - 1].indices.isEmpty ? size.width : lines[lines.count - 1].width + spacing + size.width + if needed > width, !lines[lines.count - 1].indices.isEmpty { + guard wraps else { break } + lines.append(Line()) + } else if needed > width, !wraps { + break + } + var line = lines[lines.count - 1] + line.width = line.indices.isEmpty ? size.width : line.width + spacing + size.width + line.height = max(line.height, size.height) + line.indices.append(index) + lines[lines.count - 1] = line + } + return lines + } + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let width = proposal.width ?? .infinity + let lines = lines(for: width, subviews: subviews) + let usedWidth = lines.map(\.width).max() ?? 0 + let height = lines.map(\.height).reduce(0, +) + spacing * CGFloat(max(0, lines.count - 1)) + let rowHeight = subviews.first?.sizeThatFits(.unspecified).height ?? 0 + return CGSize(width: proposal.width.map { min($0, usedWidth) } ?? usedWidth, height: max(height, wraps ? 0 : rowHeight)) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + let lines = lines(for: bounds.width, subviews: subviews) + var placed = Set() + var y = bounds.minY + for line in lines { + var x = bounds.minX + for index in line.indices { + let size = subviews[index].sizeThatFits(.unspecified) + subviews[index].place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size)) + x += size.width + spacing + placed.insert(index) + } + y += line.height + spacing + } + // Chips keep their own size, so ones that do not fit go past the edge; callers clip. + for index in subviews.indices where !placed.contains(index) { + subviews[index].place(at: CGPoint(x: bounds.maxX + 10_000, y: bounds.minY), proposal: .unspecified) + } + } +} + +/// Capsule chrome around a filter menu; tinted while the filter narrows the results. +private struct HostedIssueFilterPill: ViewModifier { + let isActive: Bool + + func body(content: Content) -> some View { + let tint = isActive ? Color.accentColor : Color.primary + content + .fixedSize() + .padding(.leading, 9) + .padding(.trailing, 7) + .padding(.vertical, 3) + .background(Capsule().fill(tint.opacity(isActive ? 0.12 : 0.05))) + .overlay(Capsule().strokeBorder(tint.opacity(isActive ? 0.35 : 0.12), lineWidth: 0.5)) + .contentShape(Capsule()) + } +} + +extension Color { + init?(hostedIssueHex hex: String?) { + guard let hex, hex.count == 6, let value = UInt32(hex, radix: 16) else { return nil } + self.init( + red: Double((value >> 16) & 0xFF) / 255, + green: Double((value >> 8) & 0xFF) / 255, + blue: Double(value & 0xFF) / 255 + ) + } +} diff --git a/macgit/Views/Issues/NewHostedIssueSheet.swift b/macgit/Views/Issues/NewHostedIssueSheet.swift new file mode 100644 index 00000000..59f077a4 --- /dev/null +++ b/macgit/Views/Issues/NewHostedIssueSheet.swift @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import SwiftUI + +/// Creates an issue on the selected remote's tracker. Nothing is sent until the user chooses Create. +struct NewHostedIssueSheet: View { + @Environment(\.dismiss) private var dismiss + @Environment(\.appTextScale) private var textScale + @ObservedObject var controller: HostedIssueController + @State private var title = "" + @State private var description = "" + @State private var workItemType = "" + @State private var isLoadingTypes = false + + private var needsType: Bool { controller.provider?.supportsWorkItemTypes == true } + + private var canCreate: Bool { + !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + && (!needsType || !workItemType.isEmpty) + && !controller.isWriting + } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("New Issue") + .font(.headline.scaled(by: textScale)) + if let remote = controller.selectedRemote { + Text(remote.provider == .azureBoards + ? "Creates a work item in project \(remote.repository.owner)." + : "Creates an issue in \(remote.repository.owner)/\(remote.repository.name).") + .font(.callout.scaled(by: textScale)) + .foregroundStyle(.secondary) + } + Form { + if needsType { + Picker("Type", selection: $workItemType) { + Text("Choose…").tag("") + ForEach(controller.workItemTypes, id: \.self) { Text($0).tag($0) } + } + .disabled(isLoadingTypes) + } + TextField("Title", text: $title) + } + .formStyle(.columns) + Text(needsType ? "Description" : "Description (Markdown)") + .font(.callout.scaled(by: textScale)) + .foregroundStyle(.secondary) + TextEditor(text: $description) + .font(.body.scaled(by: textScale)) + .frame(minHeight: 140) + .scrollContentBackground(.hidden) + .padding(4) + .background(Color.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6)) + if let error = controller.writeError { + Label(error.localizedDescription, systemImage: "exclamationmark.triangle.fill") + .font(.callout.scaled(by: textScale)) + .foregroundStyle(.orange) + .fixedSize(horizontal: false, vertical: true) + } + HStack { + if controller.isWriting { + ProgressView().controlSize(.small) + } + Spacer() + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + Button("Create") { + Task { + let draft = HostedIssueDraft(title: title, body: description, + workItemType: needsType ? workItemType : nil) + if await controller.createIssue(draft) { dismiss() } + } + } + .keyboardShortcut(.defaultAction) + .disabled(!canCreate) + } + } + .padding(20) + .frame(width: 520) + .task { + controller.clearWriteError() + guard needsType else { return } + isLoadingTypes = true + await controller.loadWorkItemTypes() + isLoadingTypes = false + if workItemType.isEmpty { + workItemType = ["Issue", "Bug", "User Story", "Task"].first(where: controller.workItemTypes.contains) ?? "" + } + } + } +} diff --git a/macgit/Views/Jira/JiraIssueListView.swift b/macgit/Views/Jira/JiraIssueListView.swift index ae8ea95a..2a321d66 100644 --- a/macgit/Views/Jira/JiraIssueListView.swift +++ b/macgit/Views/Jira/JiraIssueListView.swift @@ -11,7 +11,7 @@ struct JiraIssueListView: View { let isActive: Bool let onOpenJiraSettings: () -> Void let gitFlowEnabled: Bool - let onCreateBranch: (JiraIssue, JiraBranchTarget) -> Void + let onCreateBranch: (JiraIssue, IssueBranchTarget) -> Void @State private var selection: JiraIssue.ID? @AppStorage("jira.detailPanelWidth") private var storedDetailPanelWidth = Double(JiraIssueDetailPanel.defaultWidth) @@ -361,8 +361,8 @@ struct JiraIssueListView: View { @ViewBuilder private func createBranchMenu(for issue: JiraIssue) -> some View { - let suggested = JiraBranchTarget.suggested(forIssueType: issue.issueTypeName, gitFlowEnabled: gitFlowEnabled) - let others = JiraBranchTarget.options(gitFlowEnabled: gitFlowEnabled).filter { $0 != suggested } + let suggested = IssueBranchTarget.suggested(forIssueType: issue.issueTypeName, gitFlowEnabled: gitFlowEnabled) + let others = IssueBranchTarget.options(gitFlowEnabled: gitFlowEnabled).filter { $0 != suggested } if others.isEmpty { Button("Create Branch…") { onCreateBranch(issue, suggested) } } else { @@ -508,16 +508,16 @@ private struct JiraIssueDetailPanel: View { let onOpen: () -> Void let onCopyKey: () -> Void let onCopyKeyAndSummary: () -> Void - let onCreateBranch: (JiraBranchTarget) -> Void + let onCreateBranch: (IssueBranchTarget) -> Void let onClose: () -> Void @State private var otherTypesAnchor: NSView? - private var suggestedTarget: JiraBranchTarget { - JiraBranchTarget.suggested(forIssueType: issue.issueTypeName, gitFlowEnabled: gitFlowEnabled) + private var suggestedTarget: IssueBranchTarget { + IssueBranchTarget.suggested(forIssueType: issue.issueTypeName, gitFlowEnabled: gitFlowEnabled) } - private var otherTargets: [JiraBranchTarget] { - JiraBranchTarget.options(gitFlowEnabled: gitFlowEnabled).filter { $0 != suggestedTarget } + private var otherTargets: [IssueBranchTarget] { + IssueBranchTarget.options(gitFlowEnabled: gitFlowEnabled).filter { $0 != suggestedTarget } } var body: some View { diff --git a/macgit/Views/MainWindow/MainWindowView+HostedIssues.swift b/macgit/Views/MainWindow/MainWindowView+HostedIssues.swift new file mode 100644 index 00000000..365d21a6 --- /dev/null +++ b/macgit/Views/MainWindow/MainWindowView+HostedIssues.swift @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import Foundation + +extension MainWindowView { + /// Hosted issues follow the repository's visibility, like pull requests. + func authorizeHostedIssueAccess( + forceRefresh: Bool = false, + presentNotice: Bool = true + ) async -> Bool { + let decision = await repositoryVisibilityController.accessDecision( + for: .hostedIssues, + repositoryURL: repositoryURL, + accounts: providerAccountController.accounts, + entitlement: accountController.entitlement, + policy: featureAccessController.policy, + forceRefresh: forceRefresh + ) + guard !Task.isCancelled else { return false } + hostedIssueAccessDecision = decision + if case .denied(let denial) = decision, presentNotice { + if denial == .requiresPro { + proUpgradeErrorMessage = nil + proUpgradePresentation = ProUpgradePresentation(feature: .hostedIssues) + } else { + featureAccessNotice = FeatureAccessNotice(feature: .hostedIssues, denial: denial) + } + } + return decision.isAllowed + } +} diff --git a/macgit/Views/MainWindow/MainWindowView+Jira.swift b/macgit/Views/MainWindow/MainWindowView+Jira.swift index 952e18eb..8f41b51e 100644 --- a/macgit/Views/MainWindow/MainWindowView+Jira.swift +++ b/macgit/Views/MainWindow/MainWindowView+Jira.swift @@ -3,9 +3,10 @@ import Foundation extension MainWindowView { - /// Opens the existing branch or Git Flow start flow with a name suggested from the issue; nothing is written to Jira. - func prepareCreateBranch(from issue: JiraIssue, target: JiraBranchTarget) { - let name = JiraBranchNameSuggester.name(key: issue.key, summary: issue.summary) + /// Opens the existing branch or Git Flow start flow with a name suggested from an issue; + /// nothing is written to the issue tracker. + func prepareCreateBranch(key: String, summary: String, target: IssueBranchTarget) { + let name = IssueBranchNameSuggester.name(key: key, summary: summary) switch target { case .gitFlow(let kind) where gitFlowConfiguration.isEnabled: pendingGitFlowStart = GitFlowStartPresentation(kind: kind, initialTopicName: name) diff --git a/macgit/Views/MainWindow/MainWindowView.swift b/macgit/Views/MainWindow/MainWindowView.swift index c1236a51..87d67ef7 100644 --- a/macgit/Views/MainWindow/MainWindowView.swift +++ b/macgit/Views/MainWindow/MainWindowView.swift @@ -167,12 +167,19 @@ struct MainWindowView: View { @State private var hasOpenedPullRequests = false @State private var hasOpenedGitLFS = false @State private var hasOpenedJira = false + @State private var hasOpenedHostedIssues = false @StateObject var syncState = SyncState() @StateObject var undoManager = GitUndoManager() @StateObject var pullRequestController: PullRequestController @StateObject var jiraIssueListController: JiraIssueListController + @StateObject var hostedIssueController: HostedIssueController @StateObject var branchMergeDetectionController: BranchMergeDetectionController @State var pullRequestAccessDecision: FeatureAccessDecision? + /// The plan, policy, and accounts the current decision was made for. + @State private var pullRequestAccessContext: String? + @State var hostedIssueAccessDecision: FeatureAccessDecision? + /// The plan, policy, and remote the current decision was made for. + @State private var hostedIssueAccessContext: String? @State var featureAccessNotice: FeatureAccessNotice? @State var proUpgradePresentation: ProUpgradePresentation? @State var proUpgradeErrorMessage: String? @@ -286,6 +293,19 @@ struct MainWindowView: View { repositoryURL: repositoryURL, connectionController: jiraConnectionController )) + _hostedIssueController = StateObject(wrappedValue: HostedIssueController( + repositoryURL: repositoryURL, + credentialResolver: GitProviderAPICredentialResolver( + providerAccountController: providerAccountController, + tokenVault: KeychainGitProviderTokenVault() + ), + services: [ + .github: GitHubIssueService(), + .gitlab: GitLabIssueService(), + .bitbucket: BitbucketIssueService(), + .azureBoards: AzureBoardsWorkItemService(), + ] + )) _branchMergeDetectionController = StateObject(wrappedValue: BranchMergeDetectionController( providerAccountController: providerAccountController )) @@ -800,9 +820,28 @@ struct MainWindowView: View { } .task(id: pullRequestAccessTaskID) { guard selectedItem == .item(.pullRequests) else { return } - pullRequestAccessDecision = nil + // Coming back to the screen re-checks quietly so the list is not torn down; + // only a plan, policy, or account change starts from a blank check. + if pullRequestAccessContext != pullRequestAccessContextKey { + pullRequestAccessDecision = nil + pullRequestAccessContext = pullRequestAccessContextKey + } _ = await authorizePullRequestAccess(presentNotice: false) } + .task(id: hostedIssueAccessTaskID) { + guard selectedItem == .item(.hostedIssues) else { return } + // Coming back to the screen re-checks quietly so the list is not torn down; + // only a new remote, plan, or policy starts from a blank check. + if hostedIssueAccessContext != hostedIssueAccessContextKey { + hostedIssueAccessDecision = nil + hostedIssueAccessContext = hostedIssueAccessContextKey + } + _ = await authorizeHostedIssueAccess(presentNotice: false) + } + .task(id: repositoryURL) { + hostedIssueController.authorizeWrite = { await authorizeHostedIssueAccess(presentNotice: false) } + await hostedIssueController.discoverRemotes() + } } private var mainContent: some View { @@ -817,7 +856,16 @@ struct MainWindowView: View { } .onChange(of: appState.showIssues) { _, isVisible in // A hidden sidebar row cannot stay selected. - if !isVisible, selectedItem == .item(.jira) { selectedItem = .item(.fileStatus) } + if !isVisible, selectedItem == .item(.jira) || selectedItem == .item(.hostedIssues) { + selectedItem = .item(.fileStatus) + } + } + .onChange(of: hostedIssueController.provider) { _, provider in + if provider == nil, selectedItem == .item(.hostedIssues) { selectedItem = .item(.fileStatus) } + } + .onChange(of: providerAccountController.accounts.map(\.id)) { + // Self-managed hosts are recognized only once an account for them exists. + Task { await hostedIssueController.discoverRemotes() } } .onChange(of: selectedItem) { _, newItem in if newItem != .item(.gitLFS) { lfsTrackingPath = nil } @@ -1075,6 +1123,7 @@ struct MainWindowView: View { canUpdateCurrentBranch: canUpdateCurrentBranch, branchMergeDetectionController: branchMergeDetectionController, showMergedBranchHints: repoSettings.showMergedBranchHints, + hostedIssueProvider: hostedIssueController.provider, onRequestCheckout: { ref, isTag in if isTag { tagToCheckout = ref @@ -1476,7 +1525,7 @@ struct MainWindowView: View { } case .item(.reflog): EmptyView() - case .item(.pullRequests), .item(.jira): + case .item(.pullRequests), .item(.jira), .item(.hostedIssues): EmptyView() case .stash(let ref): StashView( @@ -1567,7 +1616,9 @@ struct MainWindowView: View { isActive: selectedItem == .item(.jira), onOpenJiraSettings: accountController.presentIntegrations, gitFlowEnabled: gitFlowConfiguration.isEnabled, - onCreateBranch: prepareCreateBranch(from:target:) + onCreateBranch: { issue, target in + prepareCreateBranch(key: issue.key, summary: issue.summary, target: target) + } ) case .denied(let denial): FeatureAccessUnavailableView( @@ -1583,6 +1634,40 @@ struct MainWindowView: View { .repositoryScreenVisibility(isActive: selectedItem == .item(.jira)) } + if selectedItem == .item(.hostedIssues) || hasOpenedHostedIssues { + Group { + switch hostedIssueAccessDecision { + case .allowed: + HostedIssueListView( + controller: hostedIssueController, + isActive: selectedItem == .item(.hostedIssues), + canManageGitHubOrganizationAccess: providerAccountController.canManageGitHubOrganizationAccess, + onOpenConnections: onOpenConnections, + onOpenGitHubOrganizationAccess: providerAccountController.openGitHubOrganizationAccess, + gitFlowEnabled: gitFlowConfiguration.isEnabled, + onCreateBranch: { key, summary, target in + prepareCreateBranch(key: key, summary: summary, target: target) + } + ) + case .denied(let denial): + FeatureAccessUnavailableView( + notice: FeatureAccessNotice(feature: .hostedIssues, denial: denial), + isSignedIn: accountController.account != nil, + onAccountAction: { presentFeatureAccessAccountAction(for: .hostedIssues) }, + onRetry: { + Task { _ = await authorizeHostedIssueAccess(forceRefresh: true, presentNotice: false) } + } + ) + case nil: + ProgressView("Checking Issue access…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .onAppear { hasOpenedHostedIssues = true } + .repositoryScreenVisibility(isActive: selectedItem == .item(.hostedIssues)) + } + if selectedItem == .item(.gitLFS) || hasOpenedGitLFS { GitLFSAccessView(repositoryURL: repositoryURL) { authorize in GitLFSView(repositoryURL: repositoryURL, initialPath: lfsTrackingPath, credentialResolver: { @MainActor remote in @@ -1709,12 +1794,29 @@ struct MainWindowView: View { } } + private var hostedIssueAccessTaskID: String { + String(describing: selectedItem) + "|" + hostedIssueAccessContextKey + } + + private var hostedIssueAccessContextKey: String { + [ + String(featureAccessController.policy.revision), + String(describing: featureAccessController.policy.rule(for: .hostedIssues)), + accountController.entitlement.plan.rawValue, + accountController.entitlement.access.rawValue, + hostedIssueController.selectedRemote?.name ?? "", + ].joined(separator: "|") + } + private var pullRequestAccessTaskID: String { + String(describing: selectedItem) + "|" + pullRequestAccessContextKey + } + + private var pullRequestAccessContextKey: String { let accounts = providerAccountController.accounts.map { "\($0.id)-\(String(describing: $0.tokenStatus))" }.joined(separator: ",") return [ - String(describing: selectedItem), String(featureAccessController.policy.revision), String(describing: featureAccessController.policy.rule(for: .pullRequests)), accountController.entitlement.plan.rawValue, @@ -1775,6 +1877,10 @@ struct MainWindowView: View { Task { _ = await authorizeGitFlowAccess(forceRefresh: true) } + case .hostedIssues: + Task { + _ = await authorizeHostedIssueAccess(forceRefresh: true) + } case .privateRepositories, .gitLFS, .aiCommitMessage, .repositoryChat, .repositoryAIActions, .aiConflictResolution, .aiBringYourOwnKey, .multipleProviderAccounts, .branchMergeDetection, .jiraIssues: diff --git a/macgit/Views/MainWindow/Sidebar/SidebarItem.swift b/macgit/Views/MainWindow/Sidebar/SidebarItem.swift index a5680a60..c01d386f 100644 --- a/macgit/Views/MainWindow/Sidebar/SidebarItem.swift +++ b/macgit/Views/MainWindow/Sidebar/SidebarItem.swift @@ -22,6 +22,8 @@ enum SidebarItem: String, CaseIterable, Identifiable { case reflog = "Reflog" case pullRequests = "Pull Requests" case jira = "Jira" + /// The repository's hosted tracker; its title and icon come from `HostedIssueProvider`. + case hostedIssues = "Issues" case search = "Search" case gitLFS = "Git LFS" case gitFlow = "Git Flow" @@ -36,6 +38,7 @@ enum SidebarItem: String, CaseIterable, Identifiable { case .pullRequests: return "arrow.triangle.pull" // An asset-catalog image, not an SF Symbol. case .jira: return "jira" + case .hostedIssues: return "checklist" case .search: return "magnifyingglass" case .gitLFS: return "externaldrive" case .gitFlow: return "point.3.connected.trianglepath.dotted" diff --git a/macgit/Views/MainWindow/Sidebar/SidebarNativeInput.swift b/macgit/Views/MainWindow/Sidebar/SidebarNativeInput.swift index 50bb8965..f0683dfe 100644 --- a/macgit/Views/MainWindow/Sidebar/SidebarNativeInput.swift +++ b/macgit/Views/MainWindow/Sidebar/SidebarNativeInput.swift @@ -27,6 +27,7 @@ struct SidebarNativeInput: Equatable { var mergeAssessments: [String: BranchMergeAssessment] = [:] var showMergedBranchHints = true var fileStatusCounts: [Int] = [] + var hostedIssueProvider: HostedIssueProvider? } extension SidebarView { @@ -58,6 +59,7 @@ extension SidebarView { dataRepositoryURL: sidebarDataRepositoryURL, mergeAssessments: branchMergeDetectionController.assessments, showMergedBranchHints: displaysMergedBranchHints, - fileStatusCounts: [stagedFileCount, changedFileCount]) + fileStatusCounts: [stagedFileCount, changedFileCount], + hostedIssueProvider: hostedIssueProvider) } } diff --git a/macgit/Views/MainWindow/Sidebar/SidebarSection.swift b/macgit/Views/MainWindow/Sidebar/SidebarSection.swift index 174dd332..0aebc8d4 100644 --- a/macgit/Views/MainWindow/Sidebar/SidebarSection.swift +++ b/macgit/Views/MainWindow/Sidebar/SidebarSection.swift @@ -85,7 +85,7 @@ enum SidebarSection: String, CaseIterable { case .workspace: return [.fileStatus, .history, .reflog, .pullRequests, .gitLFS, .search] case .issues: - return [.jira] + return [.jira, .hostedIssues] default: return [] } @@ -102,4 +102,12 @@ enum SidebarSection: String, CaseIterable { } } } + + /// ISSUES rows with their titles and icons; the hosted row needs a recognized remote. + static func issueRows(hostedProvider: HostedIssueProvider?) -> [(item: SidebarItem, title: String, icon: String)] { + issues.items.compactMap { item in + guard item == .hostedIssues else { return (item, item.rawValue, item.icon) } + return hostedProvider.map { (item, $0.sidebarTitle, $0.iconName) } + } + } } diff --git a/macgit/Views/MainWindow/SidebarView+NativeRows.swift b/macgit/Views/MainWindow/SidebarView+NativeRows.swift index 2e60e43f..18cd3da6 100644 --- a/macgit/Views/MainWindow/SidebarView+NativeRows.swift +++ b/macgit/Views/MainWindow/SidebarView+NativeRows.swift @@ -79,9 +79,9 @@ extension SidebarView { if appState.showIssues { header(.issues, expanded: sectionStates.issuesExpanded) if sectionStates.issuesExpanded { - for item in SidebarSection.issues.items { + for (item, title, icon) in SidebarSection.issueRows(hostedProvider: hostedIssueProvider) { result.append(.init(id: .init(section: .issues, kind: "item", key: item.rawValue), - appearance: .init(title: item.rawValue, icon: item.icon), selection: .item(item), + appearance: .init(title: title, icon: icon), selection: .item(item), select: { if selection != .item(item) { selection = .item(item) } })) } } diff --git a/macgit/Views/MainWindow/SidebarView.swift b/macgit/Views/MainWindow/SidebarView.swift index 7bdf601e..0776e509 100644 --- a/macgit/Views/MainWindow/SidebarView.swift +++ b/macgit/Views/MainWindow/SidebarView.swift @@ -34,6 +34,7 @@ struct SidebarView: View { @ObservedObject var branchMergeDetectionController: BranchMergeDetectionController @State var mergeEvidenceAssessment: BranchMergeAssessment? var showMergedBranchHints = true + var hostedIssueProvider: HostedIssueProvider? let repositoryURL: URL @Binding var selection: SidebarSelection? @@ -235,6 +236,7 @@ struct SidebarView: View { canUpdateCurrentBranch: Bool = true, branchMergeDetectionController: BranchMergeDetectionController, showMergedBranchHints: Bool = true, + hostedIssueProvider: HostedIssueProvider? = nil, onRequestCheckout: @escaping (String, Bool) -> Void, onRequestRemoteBranchCheckout: @escaping (RemoteBranchCheckoutTarget) -> Void, onRequestFetchBranch: @escaping (String) -> Void, @@ -318,6 +320,7 @@ struct SidebarView: View { self.canUpdateCurrentBranch = canUpdateCurrentBranch self.branchMergeDetectionController = branchMergeDetectionController self.showMergedBranchHints = showMergedBranchHints + self.hostedIssueProvider = hostedIssueProvider self.onRequestCheckout = onRequestCheckout self.onRequestRemoteBranchCheckout = onRequestRemoteBranchCheckout self.onRequestFetchBranch = onRequestFetchBranch diff --git a/macgitTests/AzureBoardsWorkItemServiceTests.swift b/macgitTests/AzureBoardsWorkItemServiceTests.swift new file mode 100644 index 00000000..4da64782 --- /dev/null +++ b/macgitTests/AzureBoardsWorkItemServiceTests.swift @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import XCTest +@testable import macgit + +final class AzureBoardsWorkItemServiceTests: XCTestCase { + private let repository = HostedIssueFixtures.repository(.azureDevOps, host: "https://dev.azure.com/contoso", owner: "ChatApp", name: "ChatApp") + private let account = HostedIssueFixtures.account(.azureDevOps, host: "https://dev.azure.com/contoso") + private let token = HostedIssueFixtures.token + + private let typesJSON = """ + {"value": [ + {"name": "Bug", "states": [{"name": "New", "category": "Proposed"}, {"name": "Active", "category": "InProgress"}, + {"name": "Resolved", "category": "Resolved"}, {"name": "Closed", "category": "Completed"}]}, + {"name": "Task", "states": [{"name": "To Do", "category": "Proposed"}, {"name": "Done", "category": "Completed"}, + {"name": "Removed", "category": "Removed"}]}, + {"name": "Note", "states": [{"name": "Open", "category": "InProgress"}]}, + {"name": "Legacy", "isDisabled": true, "states": []} + ]} + """ + + private func workItemJSON(_ id: Int, type: String = "Bug", state: String = "Active") -> String { + """ + {"id": \(id), "fields": {"System.Title": "Item \(id)", "System.State": "\(state)", "System.WorkItemType": "\(type)", + "System.CreatedBy": {"displayName": "Alice", "uniqueName": "alice@contoso.com"}, + "System.Tags": "ui; login", "System.ChangedDate": "2026-07-06T10:11:12.1234567Z", + "System.Description": "

Steps
1 & 2

"}} + """ + } + + func testWIQLUsesProjectStateCategoriesAndMe() { + let open = AzureBoardsWorkItemService.wiql( + filter: HostedIssueFilter(state: .open, relationship: .assignedToMe), search: "", closedStates: ["Closed", "Done"]) + XCTAssertEqual(open, "SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = @project AND [System.State] NOT IN ('Closed', 'Done') AND [System.AssignedTo] = @Me ORDER BY [System.ChangedDate] DESC") + + let closed = AzureBoardsWorkItemService.wiql( + filter: HostedIssueFilter(state: .closed, relationship: .createdByMe), search: "it's", closedStates: ["Done"]) + XCTAssertTrue(closed.contains("[System.State] IN ('Done')")) + XCTAssertTrue(closed.contains("[System.CreatedBy] = @Me")) + XCTAssertTrue(closed.contains("[System.Title] CONTAINS 'it''s'")) + + let byNumber = AzureBoardsWorkItemService.wiql(filter: HostedIssueFilter(state: .all), search: "AB#42", closedStates: []) + XCTAssertTrue(byNumber.contains("[System.Id] = 42")) + XCTAssertFalse(byNumber.contains("[System.State]")) + } + + func testListChunksIDsAndKeepsQueryOrder() async throws { + let ids = Array(1...250) + let wiql = #"{"workItems": ["# + ids.map { #"{"id": \#($0)}"# }.joined(separator: ",") + "]}" + let batch = #"{"value": [\#(workItemJSON(2, type: "Task", state: "Done")), \#(workItemJSON(1))]}"# + let client = StubHostedIssueHTTPClient([.json(200, typesJSON), .json(200, wiql), .json(200, batch)]) + let page = try await AzureBoardsWorkItemService(httpClient: client).listIssues( + repository: repository, account: account, token: token, + filter: HostedIssueFilter(state: .all, relationship: .all), search: "", cursor: nil + ) + + XCTAssertEqual(client.requests[0].url?.path, "/contoso/ChatApp/_apis/wit/workitemtypes") + XCTAssertEqual(client.query(0)["api-version"], "7.1") + XCTAssertEqual(client.requests[1].url?.path, "/contoso/ChatApp/_apis/wit/wiql") + XCTAssertEqual(client.requests[2].url?.path, "/contoso/_apis/wit/workitemsbatch") + XCTAssertEqual((client.jsonBody(2)["ids"] as? [Int])?.count, 200) + XCTAssertEqual(page.items.map(\.number), [1, 2]) + XCTAssertEqual(page.items[0].state, .open) + XCTAssertEqual(page.items[0].stateName, "Active") + XCTAssertEqual(page.items[1].state, .closed) + XCTAssertEqual(page.items[0].labels.map(\.name), ["ui", "login"]) + XCTAssertNotNil(page.items[0].updatedAt) + XCTAssertEqual(page.items[0].webURL?.absoluteString, "https://dev.azure.com/contoso/ChatApp/_workitems/edit/1") + XCTAssertEqual(page.next, .workItemIDs(Array(201...250))) + XCTAssertEqual(client.requests[0].value(forHTTPHeaderField: "Authorization"), + "Basic " + Data(":secret-token".utf8).base64EncodedString()) + } + + func testNextCursorSkipsQuery() async throws { + let client = StubHostedIssueHTTPClient([.json(200, typesJSON), .json(200, #"{"value": [\#(workItemJSON(201))]}"#)]) + let page = try await AzureBoardsWorkItemService(httpClient: client).listIssues( + repository: repository, account: account, token: token, filter: .default, search: "", cursor: .workItemIDs([201]) + ) + + XCTAssertEqual(page.items.map(\.number), [201]) + XCTAssertNil(page.next) + XCTAssertEqual(client.requests.count, 2) + } + + func testDetailAndHTMLText() async throws { + let client = StubHostedIssueHTTPClient([ + .json(200, typesJSON), + .json(200, workItemJSON(7)), + .json(200, #"{"comments": [{"id": 3, "text": "
Looks good
", "createdBy": {"displayName": "Bob"}, "createdDate": "2026-07-07T00:00:00.12Z"}]}"#) + ]) + let detail = try await AzureBoardsWorkItemService(httpClient: client).issueDetail(number: 7, repository: repository, token: token) + + XCTAssertEqual(detail.bodyFormat, .html) + XCTAssertEqual(HostedIssueHTMLText.plainText(fromHTML: detail.body), "Steps\n1 & 2") + XCTAssertEqual(detail.comments.map(\.body), ["
Looks good
"]) + XCTAssertEqual(client.query(2)["api-version"], AzureBoardsWorkItemService.commentsAPIVersion) + XCTAssertEqual(client.query(2)["order"], "asc") + } + + func testHTMLTextDropsImagesAndScripts() { + let html = #"

See here

  • One
  • Two é
"# + XCTAssertEqual(HostedIssueHTMLText.plainText(fromHTML: html), "See here\n\n• One\n• Two é") + XCTAssertEqual(HostedIssueHTMLText.html(fromPlainText: "a < b\nc & d"), "a < b
c & d") + } + + func testWorkItemTypesSkipDisabled() async throws { + let client = StubHostedIssueHTTPClient([.json(200, typesJSON)]) + let types = try await AzureBoardsWorkItemService(httpClient: client).workItemTypes(repository: repository, token: token) + XCTAssertEqual(types, ["Bug", "Task", "Note"]) + } + + func testCreateCommentAndStateTransitions() async throws { + let client = StubHostedIssueHTTPClient([ + .json(200, workItemJSON(9, state: "New")), .json(200, typesJSON), + .json(200, "{}"), + .json(200, workItemJSON(9)), .json(200, typesJSON), .json(200, "{}"), + .json(200, workItemJSON(9, state: "Closed")), .json(200, typesJSON), .json(200, "{}"), + ]) + let service = AzureBoardsWorkItemService(httpClient: client) + let created = try await service.createIssue( + HostedIssueDraft(title: "Crash", body: "a", headers: ["Content-Type": "text/html"]), .reauthorizationRequired), + (.json(404, #"{"message": "TF200016: The project does not exist."}"#), .notFound), + ] { + let client = StubHostedIssueHTTPClient([response]) + do { + _ = try await AzureBoardsWorkItemService(httpClient: client).listIssues( + repository: repository, account: account, token: token, filter: .default, search: "", cursor: nil + ) + XCTFail("Expected \(expected)") + } catch { + XCTAssertEqual(error as? HostedIssueError, expected) + } + } + + let client = StubHostedIssueHTTPClient([.json(401, "{}")]) + do { + try await AzureBoardsWorkItemService(httpClient: client).addComment("x", number: 1, repository: repository, token: token) + XCTFail("Expected an error") + } catch { + XCTAssertEqual(error as? HostedIssueError, .missingScope(AzureBoardsWorkItemService.writeScope)) + } + } +} diff --git a/macgitTests/BitbucketIssueServiceTests.swift b/macgitTests/BitbucketIssueServiceTests.swift new file mode 100644 index 00000000..04656f2e --- /dev/null +++ b/macgitTests/BitbucketIssueServiceTests.swift @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import XCTest +@testable import macgit + +final class BitbucketIssueServiceTests: XCTestCase { + private let repository = HostedIssueFixtures.repository(.bitbucket, host: "https://bitbucket.org", owner: "team", name: "app") + private let account = HostedIssueFixtures.account(.bitbucket, host: "https://bitbucket.org", username: "alice") + private var token: GitProviderToken { + var token = HostedIssueFixtures.token + token.apiUsername = "alice@example.com" + return token + } + + private let issueJSON = """ + {"id": 7, "title": "Broken build", "state": "on hold", "kind": "bug", "priority": "major", + "content": {"raw": "Fails on CI"}, "reporter": {"uuid": "{u1}", "display_name": "Alice"}, + "assignee": {"uuid": "{u2}", "display_name": "Bob"}, + "created_on": "2026-07-01T09:10:11.123456+00:00", "updated_on": "2026-07-06T10:11:12.654321+00:00", + "links": {"html": {"href": "https://bitbucket.org/team/app/issues/7"}}} + """ + + func testListBuildsBBQLAndUsesEmailBasicAuth() async throws { + let client = StubHostedIssueHTTPClient([ + .json(200, #"{"uuid": "{u2}"}"#), + .json(200, #"{"values": [\#(issueJSON)], "next": "https://api.bitbucket.org/2.0/repositories/team/app/issues?page=2"}"#) + ]) + let page = try await BitbucketIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: token, + filter: HostedIssueFilter(state: .open, relationship: .assignedToMe), search: "build", cursor: nil + ) + + XCTAssertEqual(page.items.map(\.number), [7]) + XCTAssertEqual(page.items.first?.state, .open) + XCTAssertEqual(page.items.first?.stateName, "On hold") + XCTAssertEqual(page.items.first?.labels.map(\.name), ["bug", "major"]) + XCTAssertNotNil(page.items.first?.updatedAt) + XCTAssertEqual(page.next, .url(URL(string: "https://api.bitbucket.org/2.0/repositories/team/app/issues?page=2")!)) + XCTAssertEqual(client.requests[0].url?.path, "/2.0/user") + XCTAssertEqual(client.requests[1].url?.path, "/2.0/repositories/team/app/issues") + XCTAssertEqual(client.query(1)["q"], + #"(state="new" OR state="open" OR state="on hold") AND assignee.uuid="{u2}" AND title~"build""#) + XCTAssertEqual(client.query(1)["sort"], "-updated_on") + let expectedAuth = "Basic " + Data("alice@example.com:secret-token".utf8).base64EncodedString() + XCTAssertEqual(client.requests[1].value(forHTTPHeaderField: "Authorization"), expectedAuth) + } + + func testNextCursorIsFollowedAsIs() async throws { + let next = URL(string: "https://api.bitbucket.org/2.0/repositories/team/app/issues?page=2")! + let client = StubHostedIssueHTTPClient([.json(200, #"{"values": []}"#)]) + let page = try await BitbucketIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: token, filter: .default, search: "", cursor: .url(next) + ) + + XCTAssertNil(page.next) + XCTAssertEqual(client.requests[0].url, next) + } + + func testClosedStatesAndNumberSearch() async throws { + let client = StubHostedIssueHTTPClient([.json(200, #"{"values": []}"#)]) + _ = try await BitbucketIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: token, + filter: HostedIssueFilter(state: .closed, relationship: .all), search: "#12", cursor: nil + ) + + XCTAssertEqual(client.query(0)["q"], + #"(state="resolved" OR state="invalid" OR state="duplicate" OR state="wontfix" OR state="closed") AND id=12"#) + } + + func testMissingEmailAsksForAccountUpdateWithoutRequest() async { + let client = StubHostedIssueHTTPClient([]) + do { + _ = try await BitbucketIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: HostedIssueFixtures.token, + filter: .default, search: "", cursor: nil + ) + XCTFail("Expected an error") + } catch { + XCTAssertEqual(error as? HostedIssueError, .accountUpdateRequired(BitbucketIssueService.missingEmailMessage)) + } + XCTAssertTrue(client.requests.isEmpty) + } + + func testDetailSkipsChangeOnlyComments() async throws { + let client = StubHostedIssueHTTPClient([ + .json(200, issueJSON), + .json(200, #"{"values": [{"id": 1, "content": {"raw": ""}}, {"id": 2, "content": {"raw": "On it"}, "user": {"display_name": "Bob"}}]}"#) + ]) + let detail = try await BitbucketIssueService(httpClient: client).issueDetail(number: 7, repository: repository, token: token) + + XCTAssertEqual(detail.body, "Fails on CI") + XCTAssertEqual(detail.comments.map(\.body), ["On it"]) + } + + func testWritesSendExpectedRequests() async throws { + let client = StubHostedIssueHTTPClient([.json(201, issueJSON), .json(201, "{}"), .json(200, "{}"), .json(200, "{}")]) + let service = BitbucketIssueService(httpClient: client) + _ = try await service.createIssue(HostedIssueDraft(title: "Broken build", body: "Fails"), repository: repository, token: token) + try await service.addComment("On it", number: 7, repository: repository, token: token) + try await service.setState(.closed, number: 7, repository: repository, token: token) + try await service.setState(.open, number: 7, repository: repository, token: token) + + XCTAssertEqual((client.jsonBody(0)["content"] as? [String: String])?["raw"], "Fails") + XCTAssertEqual(client.requests[1].url?.path, "/2.0/repositories/team/app/issues/7/comments") + XCTAssertEqual(client.requests[2].httpMethod, "PUT") + XCTAssertEqual(client.jsonBody(2)["state"] as? String, "resolved") + XCTAssertEqual(client.jsonBody(3)["state"] as? String, "open") + } + + func testErrorMapping() async throws { + for (response, expected) in [ + (StubHostedIssueHTTPClient.Response.json(404, #"{"error": {"message": "Repository has no issue tracker."}}"#), HostedIssueError.trackerDisabled), + (.json(404, #"{"error": {"message": "Repository team/app not found"}}"#), .notFound), + (.json(403, #"{"error": {"message": "Forbidden"}}"#), .missingScope("an API token with the read:issue:bitbucket scope")), + (.json(401, "{}"), .reauthorizationRequired), + ] { + let client = StubHostedIssueHTTPClient([response]) + do { + _ = try await BitbucketIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: token, filter: .default, search: "", cursor: nil + ) + XCTFail("Expected \(expected)") + } catch { + XCTAssertEqual(error as? HostedIssueError, expected) + } + } + + let client = StubHostedIssueHTTPClient([.json(403, "{}")]) + do { + try await BitbucketIssueService(httpClient: client).addComment("x", number: 7, repository: repository, token: token) + XCTFail("Expected an error") + } catch { + XCTAssertEqual(error as? HostedIssueError, .missingScope("an API token with the write:issue:bitbucket scope")) + } + } +} diff --git a/macgitTests/BranchSheetInitialStateTests.swift b/macgitTests/BranchSheetInitialStateTests.swift index 9ca249ad..049831a7 100644 --- a/macgitTests/BranchSheetInitialStateTests.swift +++ b/macgitTests/BranchSheetInitialStateTests.swift @@ -21,7 +21,7 @@ import XCTest @MainActor final class BranchSheetInitialStateTests: XCTestCase { func testInitialBranchNameIsPrefilledAndAlreadySanitized() { - let suggested = JiraBranchNameSuggester.name(key: "PROJ-123", summary: "Fix login crash") + let suggested = IssueBranchNameSuggester.name(key: "PROJ-123", summary: "Fix login crash") let state = BranchSheetView.initialNameState(suggested) XCTAssertEqual(state.input, "PROJ-123-fix-login-crash") diff --git a/macgitTests/FeatureAccessNoticeTests.swift b/macgitTests/FeatureAccessNoticeTests.swift index acf17a17..64a05e55 100644 --- a/macgitTests/FeatureAccessNoticeTests.swift +++ b/macgitTests/FeatureAccessNoticeTests.swift @@ -67,6 +67,13 @@ final class FeatureAccessNoticeTests: XCTestCase { XCTAssertFalse(notice.message(isSignedIn: true).contains("repository")) } + func testHostedIssuesNoticeUsesRepositoryScopedUpgradeWording() { + let notice = FeatureAccessNotice(feature: .hostedIssues, denial: .requiresPro) + + XCTAssertEqual(notice.message(isSignedIn: false), "Sign in to Commit+ to use issue tracking.") + XCTAssertTrue(notice.message(isSignedIn: true).contains("Issue tracking is not available for this repository on the Free plan")) + } + func testDisabledNoticeDoesNotSuggestUpgrade() { let notice = FeatureAccessNotice(feature: .pullRequests, denial: .featureDisabled) diff --git a/macgitTests/FeatureAccessPolicyTests.swift b/macgitTests/FeatureAccessPolicyTests.swift index 338b6301..456455e9 100644 --- a/macgitTests/FeatureAccessPolicyTests.swift +++ b/macgitTests/FeatureAccessPolicyTests.swift @@ -328,6 +328,34 @@ final class FeatureAccessPolicyTests: XCTestCase { XCTAssertEqual(resolver.decision(for: .jiraIssues, entitlement: activePro), .denied(.featureDisabled)) } + func testHostedIssuesFollowsPullRequestRepositoryScope() { + let resolver = FeatureAccessResolver(policy: .bundled) + XCTAssertEqual(resolver.decision(for: .hostedIssues, entitlement: .free, repositoryVisibility: .public), .allowed) + XCTAssertEqual(resolver.decision(for: .hostedIssues, entitlement: .free, repositoryVisibility: .private), .denied(.requiresPro)) + XCTAssertEqual(resolver.decision(for: .hostedIssues, entitlement: activePro, repositoryVisibility: .private), .allowed) + XCTAssertEqual(FeatureAccessPolicy.bundled.rule(for: .hostedIssues), FeatureAccessPolicy.bundled.rule(for: .pullRequests)) + } + + func testRemotePolicyWithoutHostedIssuesUsesBundledRule() { + let policy = FeaturePolicyDocumentDecoder.decode(document()) + + XCTAssertEqual(policy?.rule(for: .hostedIssues), FeatureAccessPolicy.bundled.rule(for: .hostedIssues)) + } + + func testHostedIssuesRemoteKillSwitchDisablesEveryPlan() { + let policy = FeaturePolicyDocumentDecoder.decode(document(overrides: ["hostedIssues": [ + "enabled": false, + "plans": [ + "free": ["enabled": true, "repositoryScope": "public"], + "pro": ["enabled": true, "repositoryScope": "all"] + ] + ]])) + let resolver = FeatureAccessResolver(policy: policy!) + + XCTAssertEqual(resolver.decision(for: .hostedIssues, entitlement: .free, repositoryVisibility: .public), .denied(.featureDisabled)) + XCTAssertEqual(resolver.decision(for: .hostedIssues, entitlement: activePro, repositoryVisibility: .private), .denied(.featureDisabled)) + } + private var inactivePro: AccountEntitlement { AccountEntitlement(plan: .pro, access: .inactive, billingStatus: .canceled) } diff --git a/macgitTests/GitHubIssueServiceTests.swift b/macgitTests/GitHubIssueServiceTests.swift new file mode 100644 index 00000000..a4cd5935 --- /dev/null +++ b/macgitTests/GitHubIssueServiceTests.swift @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import XCTest +@testable import macgit + +final class GitHubIssueServiceTests: XCTestCase { + private let repository = HostedIssueFixtures.repository(.github, host: "https://github.com", owner: "octocat", name: "Hello-World") + private let account = HostedIssueFixtures.account(.github, host: "https://github.com") + private let token = HostedIssueFixtures.token + + private let issueJSON = """ + {"number": 42, "title": "Fix login", "state": "open", "body": "Steps", "html_url": "https://github.com/octocat/Hello-World/issues/42", + "user": {"login": "hubot"}, "assignees": [{"login": "octocat"}], "labels": [{"name": "bug", "color": "d73a4a"}], + "created_at": "2026-07-01T09:10:11Z", "updated_at": "2026-07-06T10:11:12Z"} + """ + + func testListDropsPullRequestsAndFollowsLinkHeader() async throws { + let client = StubHostedIssueHTTPClient([ + .json(200, """ + [\(issueJSON), + {"number": 43, "title": "A PR", "state": "open", "pull_request": {"url": "x"}}] + """, headers: ["Link": "; rel=\"next\""]) + ]) + let page = try await GitHubIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: token, filter: .default, search: "", cursor: nil + ) + + XCTAssertEqual(page.items.map(\.number), [42]) + XCTAssertEqual(page.next, .page(2)) + XCTAssertEqual(page.items.first?.labels, [HostedIssueLabel(name: "bug", color: "d73a4a")]) + XCTAssertEqual(page.items.first?.assignees.map(\.id), ["octocat"]) + XCTAssertEqual(client.requests[0].url?.path, "/repos/octocat/Hello-World/issues") + XCTAssertEqual(client.query(0)["state"], "open") + XCTAssertEqual(client.query(0)["sort"], "updated") + XCTAssertEqual(client.requests[0].value(forHTTPHeaderField: "Authorization"), "Bearer secret-token") + } + + func testRelationshipFiltersUseConnectedLogin() async throws { + let client = StubHostedIssueHTTPClient([.json(200, "[]"), .json(200, "[]")]) + let service = GitHubIssueService(httpClient: client) + _ = try await service.listIssues(repository: repository, account: account, token: token, + filter: HostedIssueFilter(state: .closed, relationship: .assignedToMe), search: "", cursor: nil) + _ = try await service.listIssues(repository: repository, account: account, token: token, + filter: HostedIssueFilter(state: .all, relationship: .createdByMe), search: "", cursor: .page(3)) + + XCTAssertEqual(client.query(0)["assignee"], "octocat") + XCTAssertEqual(client.query(0)["state"], "closed") + XCTAssertEqual(client.query(1)["creator"], "octocat") + XCTAssertEqual(client.query(1)["page"], "3") + } + + func testSearchUsesSearchEndpointQualifiers() async throws { + let client = StubHostedIssueHTTPClient([.json(200, #"{"items": [\#(issueJSON)]}"#)]) + let page = try await GitHubIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: token, + filter: HostedIssueFilter(state: .open, relationship: .createdByMe), search: " login ", cursor: nil + ) + + XCTAssertEqual(page.items.count, 1) + XCTAssertNil(page.next) + XCTAssertEqual(client.requests[0].url?.path, "/search/issues") + XCTAssertEqual(client.query(0)["q"], "repo:octocat/Hello-World is:issue is:open author:octocat login") + } + + func testEnterpriseUsesServerAPIBase() async throws { + let enterprise = HostedIssueFixtures.repository(.github, host: "https://ghe.example.com", owner: "team", name: "app") + let client = StubHostedIssueHTTPClient([.json(200, "[]")]) + _ = try await GitHubIssueService(httpClient: client).listIssues( + repository: enterprise, account: account, token: token, filter: .default, search: "", cursor: nil + ) + + XCTAssertEqual(client.requests[0].url?.host, "ghe.example.com") + XCTAssertEqual(client.requests[0].url?.path, "/api/v3/repos/team/app/issues") + } + + func testDetailLoadsComments() async throws { + let client = StubHostedIssueHTTPClient([ + .json(200, issueJSON), + .json(200, #"[{"id": 7, "body": "Same here", "user": {"login": "hubot"}, "created_at": "2026-07-02T00:00:00Z"}]"#) + ]) + let detail = try await GitHubIssueService(httpClient: client).issueDetail(number: 42, repository: repository, token: token) + + XCTAssertEqual(detail.body, "Steps") + XCTAssertEqual(detail.bodyFormat, .markdown) + XCTAssertEqual(detail.comments.map(\.body), ["Same here"]) + XCTAssertFalse(detail.commentsUnavailable) + XCTAssertEqual(client.requests[1].url?.path, "/repos/octocat/Hello-World/issues/42/comments") + } + + func testWritesSendExpectedRequests() async throws { + let client = StubHostedIssueHTTPClient([.json(201, issueJSON), .json(201, "{}"), .json(200, "{}")]) + let service = GitHubIssueService(httpClient: client) + let created = try await service.createIssue(HostedIssueDraft(title: "Fix login", body: "Steps"), repository: repository, token: token) + try await service.addComment("Fixed in main", number: 42, repository: repository, token: token) + try await service.setState(.closed, number: 42, repository: repository, token: token) + + XCTAssertEqual(created.number, 42) + XCTAssertEqual(client.requests[0].httpMethod, "POST") + XCTAssertEqual(client.jsonBody(0)["title"] as? String, "Fix login") + XCTAssertEqual(client.requests[1].url?.path, "/repos/octocat/Hello-World/issues/42/comments") + XCTAssertEqual(client.jsonBody(1)["body"] as? String, "Fixed in main") + XCTAssertEqual(client.requests[2].httpMethod, "PATCH") + XCTAssertEqual(client.jsonBody(2)["state"] as? String, "closed") + } + + func testErrorMapping() async { + await assertListError(.json(410, #"{"message": "Issues are disabled for this repo"}"#), .trackerDisabled) + await assertListError(.json(401, "{}"), .reauthorizationRequired) + await assertListError(.json(404, "{}"), .notFound) + await assertListError( + .json(403, #"{"message": "Although you appear to have the correct authorization credentials, the org organization has enabled OAuth App access restrictions"}"#), + .organizationAccessRequired + ) + await assertListError( + .json(403, #"{"message": "API rate limit exceeded"}"#, headers: ["x-ratelimit-remaining": "0", "x-ratelimit-reset": "2000000000"]), + .rateLimited(retryAfter: Date(timeIntervalSince1970: 2_000_000_000)) + ) + } + + func testWritePermissionDeniedNamesRepositoryAccess() async { + let client = StubHostedIssueHTTPClient([.json(403, #"{"message": "Resource not accessible by integration"}"#)]) + do { + try await GitHubIssueService(httpClient: client).addComment("x", number: 1, repository: repository, token: token) + XCTFail("Expected an error") + } catch { + XCTAssertEqual(error as? HostedIssueError, .missingScope("write access to this repository")) + } + } + + private func assertListError(_ response: StubHostedIssueHTTPClient.Response, _ expected: HostedIssueError, + line: UInt = #line) async { + let client = StubHostedIssueHTTPClient([response]) + do { + _ = try await GitHubIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: token, filter: .default, search: "", cursor: nil + ) + XCTFail("Expected \(expected)", line: line) + } catch { + XCTAssertEqual(error as? HostedIssueError, expected, line: line) + } + } +} diff --git a/macgitTests/GitLabIssueServiceTests.swift b/macgitTests/GitLabIssueServiceTests.swift new file mode 100644 index 00000000..e0c36ed1 --- /dev/null +++ b/macgitTests/GitLabIssueServiceTests.swift @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import XCTest +@testable import macgit + +final class GitLabIssueServiceTests: XCTestCase { + private let repository = HostedIssueFixtures.repository(.gitlab, host: "https://gitlab.com", owner: "group/sub", name: "app") + private let account = HostedIssueFixtures.account(.gitlab, host: "https://gitlab.com") + private let token = HostedIssueFixtures.token + + private let issueJSON = """ + {"iid": 5, "title": "Crash on launch", "state": "opened", "description": "Trace", + "web_url": "https://gitlab.com/group/sub/app/-/issues/5", + "author": {"id": 1, "username": "alice", "name": "Alice"}, "assignees": [], "labels": ["bug"], + "created_at": "2026-07-01T09:10:11.123Z", "updated_at": "2026-07-06T10:11:12.456Z"} + """ + + func testListUsesStateScopeAndPagination() async throws { + let client = StubHostedIssueHTTPClient([.json(200, "[\(issueJSON)]", headers: ["X-Next-Page": "2"])]) + let page = try await GitLabIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: token, + filter: HostedIssueFilter(state: .open, relationship: .assignedToMe), search: "", cursor: nil + ) + + XCTAssertEqual(page.items.map(\.number), [5]) + XCTAssertEqual(page.items.first?.state, .open) + XCTAssertEqual(page.items.first?.author?.displayName, "Alice") + XCTAssertNotNil(page.items.first?.updatedAt) + XCTAssertEqual(page.next, .page(2)) + XCTAssertEqual(client.requests[0].url?.absoluteString.contains("/api/v4/projects/group%2Fsub%2Fapp/issues"), true) + XCTAssertEqual(client.query(0)["state"], "opened") + XCTAssertEqual(client.query(0)["scope"], "assigned_to_me") + XCTAssertEqual(client.query(0)["order_by"], "updated_at") + } + + func testAllStateOmitsStateAndSearchIsSent() async throws { + let client = StubHostedIssueHTTPClient([.json(200, "[]"), .json(200, "[]")]) + let service = GitLabIssueService(httpClient: client) + let page = try await service.listIssues(repository: repository, account: account, token: token, + filter: HostedIssueFilter(state: .all, relationship: .createdByMe), search: "login", cursor: .page(4)) + _ = try await service.listIssues(repository: repository, account: account, token: token, + filter: .default, search: "#12", cursor: nil) + + XCTAssertNil(page.next) + XCTAssertNil(client.query(0)["state"]) + XCTAssertEqual(client.query(0)["scope"], "created_by_me") + XCTAssertEqual(client.query(0)["search"], "login") + XCTAssertEqual(client.query(0)["page"], "4") + XCTAssertEqual(client.query(1)["iids[]"], "12") + XCTAssertNil(client.query(1)["search"]) + } + + func testSelfManagedSubpathHost() async throws { + let selfManaged = HostedIssueFixtures.repository(.gitlab, host: "https://git.example.com/gitlab", owner: "team", name: "app") + let client = StubHostedIssueHTTPClient([.json(200, "[]")]) + _ = try await GitLabIssueService(httpClient: client).listIssues( + repository: selfManaged, account: account, token: token, filter: .default, search: "", cursor: nil + ) + + XCTAssertEqual(client.requests[0].url?.host, "git.example.com") + XCTAssertTrue(client.requests[0].url!.absoluteString.contains("/gitlab/api/v4/projects/team%2Fapp/issues")) + } + + func testDetailSkipsSystemNotes() async throws { + let client = StubHostedIssueHTTPClient([ + .json(200, issueJSON), + .json(200, """ + [{"id": 1, "body": "changed the description", "system": true}, + {"id": 2, "body": "Looking", "system": false, "author": {"id": 2, "username": "bob"}, "created_at": "2026-07-02T00:00:00Z"}] + """) + ]) + let detail = try await GitLabIssueService(httpClient: client).issueDetail(number: 5, repository: repository, token: token) + + XCTAssertEqual(detail.body, "Trace") + XCTAssertEqual(detail.comments.map(\.body), ["Looking"]) + } + + func testWritesSendExpectedRequests() async throws { + let client = StubHostedIssueHTTPClient([.json(201, issueJSON), .json(201, "{}"), .json(200, "{}"), .json(200, "{}")]) + let service = GitLabIssueService(httpClient: client) + _ = try await service.createIssue(HostedIssueDraft(title: "Crash on launch", body: "Trace"), repository: repository, token: token) + try await service.addComment("Fixed", number: 5, repository: repository, token: token) + try await service.setState(.closed, number: 5, repository: repository, token: token) + try await service.setState(.open, number: 5, repository: repository, token: token) + + XCTAssertEqual(client.jsonBody(0)["description"] as? String, "Trace") + XCTAssertTrue(client.requests[1].url!.absoluteString.hasSuffix("/issues/5/notes")) + XCTAssertEqual(client.requests[2].httpMethod, "PUT") + XCTAssertEqual(client.jsonBody(2)["state_event"] as? String, "close") + XCTAssertEqual(client.jsonBody(3)["state_event"] as? String, "reopen") + } + + func testErrorMapping() async throws { + for (response, expected) in [ + (StubHostedIssueHTTPClient.Response.json(401, "{}"), HostedIssueError.reauthorizationRequired), + (.json(403, #"{"message": "403 Forbidden"}"#), .trackerDisabled), + (.json(404, #"{"message": "404 Project Not Found"}"#), .notFound), + (.json(500, #"{"message": "boom"}"#), .providerMessage("boom")), + ] { + let client = StubHostedIssueHTTPClient([response]) + do { + _ = try await GitLabIssueService(httpClient: client).listIssues( + repository: repository, account: account, token: token, filter: .default, search: "", cursor: nil + ) + XCTFail("Expected \(expected)") + } catch { + XCTAssertEqual(error as? HostedIssueError, expected) + } + } + + let client = StubHostedIssueHTTPClient([.json(403, #"{"message": "403 Forbidden"}"#)]) + do { + try await GitLabIssueService(httpClient: client).setState(.closed, number: 5, repository: repository, token: token) + XCTFail("Expected an error") + } catch { + XCTAssertEqual(error as? HostedIssueError, .missingScope("write access to this repository")) + } + } +} diff --git a/macgitTests/GitProviderAccountControllerTests.swift b/macgitTests/GitProviderAccountControllerTests.swift index 7b69f4dc..d362534c 100644 --- a/macgitTests/GitProviderAccountControllerTests.swift +++ b/macgitTests/GitProviderAccountControllerTests.swift @@ -445,6 +445,34 @@ final class GitProviderAccountControllerTests: XCTestCase { ) } + func testConnectBitbucketKeepsAtlassianEmailWithTokenOnly() async throws { + let store = FakeGitProviderAccountStore() + let vault = FakeGitProviderTokenVault() + let controller = GitProviderAccountController(store: store, tokenVault: vault) + await controller.updateMacgitAccount(makeMacgitAccount(uid: "macgit-user-1"), cloudSyncEnabled: true) + + await controller.connectBitbucket( + username: "Trantienthanh2412", + apiToken: "bitbucket-api-token", + atlassianEmail: " me@example.com " + ) + + let account = try XCTUnwrap(controller.accounts.first) + XCTAssertEqual(try vault.readToken(for: account)?.apiUsername, "me@example.com") + XCTAssertEqual(controller.savedAPIUsername(for: account), "me@example.com") + XCTAssertTrue(account.scopes.contains("read:issue:bitbucket")) + // The synced metadata carries no email. + let encoded = String(decoding: try JSONEncoder().encode(account), as: UTF8.self) + XCTAssertFalse(encoded.contains("me@example.com")) + } + + func testTokenSavedBeforeEmailFieldStillDecodes() throws { + let legacy = #"{"accessToken": "t", "tokenType": "Basic"}"# + let token = try JSONDecoder().decode(GitProviderToken.self, from: Data(legacy.utf8)) + XCTAssertEqual(token.accessToken, "t") + XCTAssertNil(token.apiUsername) + } + func testConnectBitbucketRejectsEmptyTokenWithoutSavingAccount() async { let events = EventRecorder() let controller = GitProviderAccountController( diff --git a/macgitTests/HostedIssueControllerTests.swift b/macgitTests/HostedIssueControllerTests.swift new file mode 100644 index 00000000..555feda0 --- /dev/null +++ b/macgitTests/HostedIssueControllerTests.swift @@ -0,0 +1,357 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import XCTest +@testable import macgit + +@MainActor +final class HostedIssueControllerTests: XCTestCase { + private let repositoryURL = URL(fileURLWithPath: "/tmp/hosted-issue-repo") + private let githubAccount = HostedIssueFixtures.account(.github, host: "https://github.com") + private var remotes: [String: String] = [:] + private var remoteOrder: [String] = [] + private var accounts: [GitProviderAccount] = [] + private var vault = HostedIssueTokenVault() + private var preferences = MemoryHostedIssuePreferences() + private var provider = FakeHostedIssueProvider() + private var center = NotificationCenter() + private var clock = Date(timeIntervalSince1970: 1_000) + + override func setUp() { + super.setUp() + remotes = ["origin": "https://github.com/me/app.git", "upstream": "https://github.com/org/app.git"] + remoteOrder = ["upstream", "origin"] + accounts = [githubAccount] + vault = HostedIssueTokenVault() + vault.tokens[githubAccount.id] = HostedIssueFixtures.token + preferences = MemoryHostedIssuePreferences() + provider = FakeHostedIssueProvider() + center = NotificationCenter() + } + + private func makeController() -> HostedIssueController { + HostedIssueController( + repositoryURL: repositoryURL, + credentialResolver: GitProviderAPICredentialResolver(accounts: { [unowned self] in accounts }, tokenVault: vault), + services: [.github: provider, .gitlab: provider], + preferenceStore: preferences, + remoteNamesProvider: { [unowned self] _ in remoteOrder }, + remoteURLProvider: { [unowned self] _, name in remotes[name] }, + searchDebounce: .milliseconds(1), + notificationCenter: center, + now: { [unowned self] in clock } + ) + } + + private func waitUntil(_ condition: @escaping () -> Bool, file: StaticString = #filePath, line: UInt = #line) async { + for _ in 0..<200 where !condition() { + try? await Task.sleep(for: .milliseconds(5)) + } + XCTAssertTrue(condition(), "Timed out", file: file, line: line) + } + + func testDefaultsToOriginAndOpenFilter() async { + provider.pages = [HostedIssuePage(items: [.fixture(1), .fixture(2)], next: .page(2))] + let controller = makeController() + await controller.activate() + await waitUntil { controller.hasLoadedList } + + XCTAssertEqual(controller.remotes.map(\.name), ["origin", "upstream"]) + XCTAssertEqual(controller.selectedRemote?.name, "origin") + XCTAssertEqual(controller.provider, .github) + XCTAssertEqual(controller.items.map(\.number), [1, 2]) + XCTAssertEqual(controller.next, .page(2)) + XCTAssertEqual(provider.listCalls.first?.filter, .default) + XCTAssertEqual(provider.listCalls.first?.repository.owner, "me") + } + + func testReturningAfterAMinuteRefreshes() async { + let controller = makeController() + await controller.activate() + await waitUntil { controller.hasLoadedList } + controller.deactivate() + + clock.addTimeInterval(30) + await controller.activate() + XCTAssertEqual(provider.listCalls.count, 1) + + controller.deactivate() + clock.addTimeInterval(31) + await controller.activate() + await waitUntil { self.provider.listCalls.count == 2 } + } + + func testRememberedRemoteAndFilterAreRestored() async { + preferences.remote = "upstream" + preferences.filters["upstream"] = HostedIssueFilter(state: .closed, relationship: .assignedToMe) + let controller = makeController() + await controller.activate() + await waitUntil { controller.hasLoadedList } + + XCTAssertEqual(controller.selectedRemote?.name, "upstream") + XCTAssertEqual(controller.filter, HostedIssueFilter(state: .closed, relationship: .assignedToMe)) + XCTAssertEqual(provider.listCalls.last?.repository.owner, "org") + } + + func testSelectingRemoteSavesChoice() async { + let controller = makeController() + await controller.activate() + controller.selectRemote(named: "upstream") + await waitUntil { controller.selectedRemote?.name == "upstream" } + + XCTAssertEqual(preferences.remote, "upstream") + } + + func testFilterChangeIsSavedPerRemote() async { + let controller = makeController() + await controller.activate() + await waitUntil { controller.hasLoadedList } + controller.updateFilter { $0.relationship = .createdByMe } + await waitUntil { self.preferences.filters["origin"]?.relationship == .createdByMe } + await waitUntil { self.provider.listCalls.last?.filter.relationship == .createdByMe } + } + + func testNoAccountMakesNoRequest() async { + accounts = [] + let controller = makeController() + await controller.activate() + + XCTAssertEqual(controller.accountProblem, .noAccount(GitProviderHost(kind: .github, baseURL: URL(string: "https://github.com")!).normalized)) + XCTAssertTrue(provider.listCalls.isEmpty) + } + + func testMissingTokenAsksToReconnect() async { + vault.tokens = [:] + let controller = makeController() + await controller.activate() + + guard case .reconnect = controller.accountProblem else { return XCTFail("Expected reconnect") } + XCTAssertTrue(provider.listCalls.isEmpty) + } + + func testStaleResponseIsDropped() async { + provider.delays = [.milliseconds(150), .zero] + provider.pages = [HostedIssuePage(items: [.fixture(1)], next: nil), HostedIssuePage(items: [.fixture(9)], next: nil)] + let controller = makeController() + await controller.activate() + controller.updateFilter { $0.state = .closed } + await waitUntil { controller.items.map(\.number) == [9] } + try? await Task.sleep(for: .milliseconds(200)) + + XCTAssertEqual(controller.items.map(\.number), [9]) + } + + func testListErrorIsShown() async { + provider.listError = HostedIssueError.trackerDisabled + let controller = makeController() + await controller.activate() + await waitUntil { controller.error != nil } + + XCTAssertEqual(controller.error, .trackerDisabled) + } + + func testReselectingIssueUsesCachedDetailUntilRefresh() async { + provider.pages = [HostedIssuePage(items: [.fixture(1), .fixture(2)], next: nil)] + let controller = makeController() + await controller.activate() + await waitUntil { controller.hasLoadedList } + + controller.select(1) + await waitUntil { controller.detail?.summary.number == 1 } + controller.select(2) + await waitUntil { controller.detail?.summary.number == 2 } + controller.select(1) + + XCTAssertEqual(controller.detail?.summary.number, 1) + XCTAssertEqual(provider.detailCalls, [1, 2]) + + clock.addTimeInterval(HostedIssueController.detailCacheTTL + 1) + controller.select(2) + await waitUntil { self.provider.detailCalls == [1, 2, 2] } + + controller.refresh() + await waitUntil { self.provider.detailCalls == [1, 2, 2, 2] } + } + + func testFailedCommentKeepsStateAndIsNotRetried() async { + provider.pages = [HostedIssuePage(items: [.fixture(1)], next: nil)] + provider.writeError = HostedIssueError.providerMessage("offline") + let controller = makeController() + await controller.activate() + await waitUntil { controller.hasLoadedList } + controller.select(1) + + let posted = await controller.addComment("Fixed in main") + + XCTAssertFalse(posted) + XCTAssertEqual(controller.writeError, .providerMessage("offline")) + XCTAssertEqual(provider.comments.count, 1) + } + + func testClosedIssueStaysVisibleUnderOpenFilter() async { + provider.pages = [ + HostedIssuePage(items: [.fixture(1), .fixture(2)], next: nil), + HostedIssuePage(items: [.fixture(2)], next: nil), + ] + var closed = HostedIssueSummary.fixture(1) + closed.state = .closed + provider.details[1] = HostedIssueDetail(summary: closed, body: "", bodyFormat: .markdown, comments: []) + let controller = makeController() + await controller.activate() + await waitUntil { controller.hasLoadedList } + controller.select(1) + + await controller.setState(.closed) + await waitUntil { self.provider.listCalls.count == 2 && !controller.isLoading } + + XCTAssertEqual(provider.states.first?.state, .closed) + XCTAssertEqual(controller.items.map(\.number), [1, 2]) + XCTAssertEqual(controller.items.first?.state, .closed) + XCTAssertEqual(controller.selectedIssueNumber, 1) + } + + func testCreatedIssueIsSelected() async { + provider.created = .fixture(77) + let controller = makeController() + await controller.activate() + await waitUntil { controller.hasLoadedList } + + let created = await controller.createIssue(HostedIssueDraft(title: " Crash ", body: "")) + + XCTAssertTrue(created) + XCTAssertEqual(provider.drafts.first?.title, "Crash") + XCTAssertEqual(controller.selectedIssueNumber, 77) + await waitUntil { controller.items.contains { $0.number == 77 } } + } + + func testSecondWriteDuringAccessCheckIsIgnored() async { + let controller = makeController() + await controller.activate() + await waitUntil { controller.hasLoadedList } + controller.authorizeWrite = { + try? await Task.sleep(for: .milliseconds(50)) + return true + } + + async let first = controller.createIssue(HostedIssueDraft(title: "Crash", body: "")) + async let second = controller.createIssue(HostedIssueDraft(title: "Crash", body: "")) + let results = await [first, second] + + XCTAssertEqual(results.filter { $0 }.count, 1) + XCTAssertEqual(provider.drafts.count, 1) + } + + func testBlankTitleAndDeniedAccessSendNothing() async { + let controller = makeController() + await controller.activate() + let blank = await controller.createIssue(HostedIssueDraft(title: " ", body: "")) + controller.authorizeWrite = { false } + let denied = await controller.createIssue(HostedIssueDraft(title: "Crash", body: "")) + + XCTAssertFalse(blank) + XCTAssertFalse(denied) + XCTAssertTrue(provider.drafts.isEmpty) + } + + func testNotificationsForOtherRepositoriesAreIgnored() async { + let controller = makeController() + await controller.activate() + remotes["origin"] = "https://gitlab.com/me/app.git" + + center.post(name: .repositoryRemoteRefsDidRefresh, object: nil, userInfo: ["repositoryURL": URL(fileURLWithPath: "/tmp/other")]) + try? await Task.sleep(for: .milliseconds(50)) + XCTAssertEqual(controller.provider, .github) + + center.post(name: .repositoryRemoteRefsDidRefresh, object: nil, userInfo: ["repositoryURL": repositoryURL]) + await waitUntil { controller.provider == .gitlab } + } + + func testAddedRemotePublishesProvider() async { + remotes = [:] + remoteOrder = [] + let controller = makeController() + await controller.discoverRemotes() + XCTAssertNil(controller.provider) + + remotes = ["origin": "git@gitlab.com:me/app.git"] + remoteOrder = ["origin"] + center.post(name: .repositoryDidChange, object: nil, userInfo: ["repositoryURL": repositoryURL]) + await waitUntil { controller.provider == .gitlab } + } +} + +extension HostedIssueSummary { + static func fixture(_ number: Int, state: HostedIssueState = .open) -> HostedIssueSummary { + HostedIssueSummary(number: number, title: "Issue \(number)", state: state, stateName: nil, workItemType: nil, + author: nil, assignees: [], labels: [], createdAt: nil, updatedAt: nil, webURL: nil) + } +} + +final class HostedIssueTokenVault: GitProviderTokenVault { + var tokens: [String: GitProviderToken] = [:] + func readToken(for account: GitProviderAccount) throws -> GitProviderToken? { tokens[account.id] } + func saveToken(_ token: GitProviderToken, for account: GitProviderAccount) throws { tokens[account.id] = token } + func deleteToken(for account: GitProviderAccount) throws { tokens[account.id] = nil } +} + +final class MemoryHostedIssuePreferences: HostedIssuePreferenceStoring, @unchecked Sendable { + var remote: String? + var filters: [String: HostedIssueFilter] = [:] + func remoteName(forRepositoryKey key: String) async -> String? { remote } + func saveRemoteName(_ name: String, forRepositoryKey key: String) async { remote = name } + func filter(forRepositoryKey key: String, remote: String) async -> HostedIssueFilter? { filters[remote] } + func save(_ filter: HostedIssueFilter, forRepositoryKey key: String, remote: String) async { filters[remote] = filter } +} + +final class FakeHostedIssueProvider: HostedIssueProviding, @unchecked Sendable { + struct ListCall { + var repository: GitRepositoryIdentity + var filter: HostedIssueFilter + var search: String + var cursor: HostedIssueCursor? + } + + var pages: [HostedIssuePage] = [] + var delays: [Duration] = [] + var listError: Error? + var writeError: Error? + var details: [Int: HostedIssueDetail] = [:] + var created: HostedIssueSummary = .fixture(100) + private(set) var listCalls: [ListCall] = [] + private(set) var drafts: [HostedIssueDraft] = [] + private(set) var comments: [(body: String, number: Int)] = [] + private(set) var states: [(state: HostedIssueState, number: Int)] = [] + + func listIssues(repository: GitRepositoryIdentity, account: GitProviderAccount, token: GitProviderToken, + filter: HostedIssueFilter, search: String, cursor: HostedIssueCursor?) async throws -> HostedIssuePage { + listCalls.append(ListCall(repository: repository, filter: filter, search: search, cursor: cursor)) + let page = pages.isEmpty ? HostedIssuePage(items: [], next: nil) : pages.removeFirst() + let delay = delays.isEmpty ? .zero : delays.removeFirst() + // A late response that ignores cancellation, like a request already on the wire. + if delay > .zero { await Task.detached { try? await Task.sleep(for: delay) }.value } + if let listError { throw listError } + return page + } + + private(set) var detailCalls: [Int] = [] + + func issueDetail(number: Int, repository: GitRepositoryIdentity, token: GitProviderToken) async throws -> HostedIssueDetail { + detailCalls.append(number) + return details[number] ?? HostedIssueDetail(summary: .fixture(number), body: "", bodyFormat: .markdown, comments: []) + } + + func createIssue(_ draft: HostedIssueDraft, repository: GitRepositoryIdentity, token: GitProviderToken) async throws -> HostedIssueSummary { + drafts.append(draft) + if let writeError { throw writeError } + return created + } + + func addComment(_ body: String, number: Int, repository: GitRepositoryIdentity, token: GitProviderToken) async throws { + comments.append((body, number)) + if let writeError { throw writeError } + } + + func setState(_ state: HostedIssueState, number: Int, repository: GitRepositoryIdentity, token: GitProviderToken) async throws { + states.append((state, number)) + if let writeError { throw writeError } + } +} diff --git a/macgitTests/HostedIssueModelsTests.swift b/macgitTests/HostedIssueModelsTests.swift new file mode 100644 index 00000000..42439d2f --- /dev/null +++ b/macgitTests/HostedIssueModelsTests.swift @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import XCTest +@testable import macgit + +final class HostedIssueModelsTests: XCTestCase { + func testReferenceFormatPerProvider() { + XCTAssertEqual(HostedIssueProvider.github.reference(for: 42), "#42") + XCTAssertEqual(HostedIssueProvider.gitlab.reference(for: 42), "#42") + XCTAssertEqual(HostedIssueProvider.bitbucket.reference(for: 42), "#42") + XCTAssertEqual(HostedIssueProvider.azureBoards.reference(for: 42), "AB#42") + } + + func testProviderFollowsAccountKind() { + XCTAssertEqual(HostedIssueProvider(.azureDevOps), .azureBoards) + XCTAssertEqual(HostedIssueProvider(.gitlab).sidebarTitle, "GitLab Issues") + XCTAssertEqual(HostedIssueProvider.azureBoards.sidebarTitle, "Azure Boards") + XCTAssertEqual(HostedIssueProvider.azureBoards.accountKind, .azureDevOps) + } + + func testFilterDefaultsAndRoundTrip() throws { + XCTAssertEqual(HostedIssueFilter.default.state, .open) + XCTAssertEqual(HostedIssueFilter.default.relationship, .all) + XCTAssertTrue(HostedIssueFilter().isDefault) + + let filter = HostedIssueFilter(state: .closed, relationship: .assignedToMe) + let data = try JSONEncoder().encode(filter) + XCTAssertEqual(try JSONDecoder().decode(HostedIssueFilter.self, from: data), filter) + XCTAssertFalse(filter.isDefault) + } +} diff --git a/macgitTests/HostedIssueTestSupport.swift b/macgitTests/HostedIssueTestSupport.swift new file mode 100644 index 00000000..582ad10d --- /dev/null +++ b/macgitTests/HostedIssueTestSupport.swift @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import XCTest +@testable import macgit + +final class StubHostedIssueHTTPClient: GitProviderHTTPClient, @unchecked Sendable { + struct Response { + var statusCode: Int + var data: Data + var headers: [String: String] + + static func json(_ statusCode: Int, _ body: String, headers: [String: String] = [:]) -> Response { + Response(statusCode: statusCode, data: Data(body.utf8), headers: headers) + } + } + + private(set) var requests: [URLRequest] = [] + private var responses: [Response] + + init(_ responses: [Response]) { + self.responses = responses + } + + func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) { + requests.append(request) + guard !responses.isEmpty else { + XCTFail("Unexpected request \(request.httpMethod ?? "GET") \(request.url?.absoluteString ?? "")") + throw URLError(.badServerResponse) + } + let response = responses.removeFirst() + let httpResponse = try XCTUnwrap(HTTPURLResponse( + url: request.url!, + statusCode: response.statusCode, + httpVersion: nil, + headerFields: response.headers + )) + return (response.data, httpResponse) + } + + func query(_ index: Int) -> [String: String] { + let items = URLComponents(url: requests[index].url!, resolvingAgainstBaseURL: false)?.queryItems ?? [] + return Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value ?? "") }) + } + + func jsonBody(_ index: Int) -> [String: Any] { + guard let data = requests[index].httpBody, + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [:] } + return object + } +} + +enum HostedIssueFixtures { + static let token = GitProviderToken(accessToken: "secret-token", refreshToken: nil, expiresAt: nil, tokenType: "bearer") + + static func repository(_ provider: GitProviderKind, host: String, owner: String, name: String) -> GitRepositoryIdentity { + GitRepositoryIdentity(provider: provider, hostURL: URL(string: host)!, owner: owner, name: name) + } + + static func account(_ provider: GitProviderKind, host: String, username: String = "octocat", userID: String = "1") -> GitProviderAccount { + GitProviderAccount( + id: "\(provider.rawValue)-\(username)", + macgitUID: "uid", + provider: provider, + hostURL: URL(string: host)!, + providerUserID: userID, + username: username, + displayName: nil, + avatarURL: nil, + scopes: ["repo"], + permissions: [:], + tokenStatus: .valid, + connectedAt: Date(timeIntervalSince1970: 0), + lastValidatedAt: nil + ) + } +} diff --git a/macgitTests/JiraBranchNameSuggesterTests.swift b/macgitTests/IssueBranchNameSuggesterTests.swift similarity index 69% rename from macgitTests/JiraBranchNameSuggesterTests.swift rename to macgitTests/IssueBranchNameSuggesterTests.swift index e64d8781..14e35b87 100644 --- a/macgitTests/JiraBranchNameSuggesterTests.swift +++ b/macgitTests/IssueBranchNameSuggesterTests.swift @@ -3,15 +3,19 @@ import XCTest @testable import macgit -final class JiraBranchNameSuggesterTests: XCTestCase { +final class IssueBranchNameSuggesterTests: XCTestCase { private func name(_ summary: String, key: String = "PROJ-123") -> String { - JiraBranchNameSuggester.name(key: key, summary: summary) + IssueBranchNameSuggester.name(key: key, summary: summary) } func testKeyAndSlug() { XCTAssertEqual(name("Fix login crash"), "PROJ-123-fix-login-crash") } + func testHostedIssueNumberAsKey() { + XCTAssertEqual(name("Fix login on Safari", key: "42"), "42-fix-login-on-safari") + } + func testPunctuationCollapsesToSingleHyphens() { XCTAssertEqual(name(" [iOS] Fix: login -- crash (again)! "), "PROJ-123-ios-fix-login-crash-again") } @@ -32,7 +36,7 @@ final class JiraBranchNameSuggesterTests: XCTestCase { func testLongSummaryIsCutAtHyphenAndKeepsKey() { let result = name("Refactor the repository synchronization pipeline to support incremental background refreshes") - XCTAssertLessThanOrEqual(result.count, JiraBranchNameSuggester.maxLength) + XCTAssertLessThanOrEqual(result.count, IssueBranchNameSuggester.maxLength) XCTAssertTrue(result.hasPrefix("PROJ-123-refactor-the-repository")) XCTAssertFalse(result.hasSuffix("-")) XCTAssertTrue("Refactor the repository synchronization pipeline to support incremental background refreshes" @@ -45,19 +49,19 @@ final class JiraBranchNameSuggesterTests: XCTestCase { } func testBugsSuggestBugfixAndOtherTypesSuggestFeature() { - XCTAssertEqual(JiraBranchTarget.suggested(forIssueType: "Bug", gitFlowEnabled: true), .gitFlow(.bugfix)) - XCTAssertEqual(JiraBranchTarget.suggested(forIssueType: "Defect", gitFlowEnabled: true), .gitFlow(.bugfix)) - XCTAssertEqual(JiraBranchTarget.suggested(forIssueType: "Story", gitFlowEnabled: true), .gitFlow(.feature)) - XCTAssertEqual(JiraBranchTarget.suggested(forIssueType: "Task", gitFlowEnabled: true), .gitFlow(.feature)) + XCTAssertEqual(IssueBranchTarget.suggested(forIssueType: "Bug", gitFlowEnabled: true), .gitFlow(.bugfix)) + XCTAssertEqual(IssueBranchTarget.suggested(forIssueType: "Defect", gitFlowEnabled: true), .gitFlow(.bugfix)) + XCTAssertEqual(IssueBranchTarget.suggested(forIssueType: "Story", gitFlowEnabled: true), .gitFlow(.feature)) + XCTAssertEqual(IssueBranchTarget.suggested(forIssueType: "Task", gitFlowEnabled: true), .gitFlow(.feature)) } func testWithoutGitFlowOnlyPlainBranchIsOffered() { - XCTAssertEqual(JiraBranchTarget.suggested(forIssueType: "Bug", gitFlowEnabled: false), .plainBranch) - XCTAssertEqual(JiraBranchTarget.options(gitFlowEnabled: false), [.plainBranch]) + XCTAssertEqual(IssueBranchTarget.suggested(forIssueType: "Bug", gitFlowEnabled: false), .plainBranch) + XCTAssertEqual(IssueBranchTarget.options(gitFlowEnabled: false), [.plainBranch]) } func testGitFlowOptionsExcludeReleaseAndKeepPlainBranch() { - let options = JiraBranchTarget.options(gitFlowEnabled: true) + let options = IssueBranchTarget.options(gitFlowEnabled: true) XCTAssertEqual(options, [.gitFlow(.feature), .gitFlow(.bugfix), .gitFlow(.hotfix), .plainBranch]) XCTAssertEqual(options.map(\.title), ["Start Feature…", "Start Bugfix…", "Start Hotfix…", "New Branch…"]) } diff --git a/macgitTests/RepositoryBookmarkTests.swift b/macgitTests/RepositoryBookmarkTests.swift index 24b228a3..1ae97c71 100644 --- a/macgitTests/RepositoryBookmarkTests.swift +++ b/macgitTests/RepositoryBookmarkTests.swift @@ -381,7 +381,10 @@ final class RepositoryBookmarkTests: XCTestCase { remote.pullRequestsURL?.absoluteString, "https://dev.azure.com/Trantienthanh1998/ChatApp/_git/ChatApp/pullrequests" ) - XCTAssertNil(remote.issuesURL) + XCTAssertEqual( + remote.issuesURL?.absoluteString, + "https://dev.azure.com/Trantienthanh1998/ChatApp/_workitems" + ) } func testDocumentListSkipsBookmarksForUnknownProviders() throws { diff --git a/macgitTests/RepositoryVisibilityControllerTests.swift b/macgitTests/RepositoryVisibilityControllerTests.swift index 77505ec7..311e0520 100644 --- a/macgitTests/RepositoryVisibilityControllerTests.swift +++ b/macgitTests/RepositoryVisibilityControllerTests.swift @@ -32,6 +32,20 @@ final class RepositoryVisibilityControllerTests: XCTestCase { XCTAssertTrue(service.receivedTokens.isEmpty) } + func testHostedIssuesFollowRepositoryVisibility() async { + let publicController = makeController(service: FakeRepositoryVisibilityProvider(results: [.success(.public)])) + let publicDecision = await publicController.accessDecision( + for: .hostedIssues, repositoryURL: repositoryURL, accounts: [], entitlement: .free, policy: .bundled + ) + XCTAssertEqual(publicDecision, .allowed) + + let privateController = makeController(service: FakeRepositoryVisibilityProvider(results: [.success(.private)])) + let privateDecision = await privateController.accessDecision( + for: .hostedIssues, repositoryURL: repositoryURL, accounts: [], entitlement: .free, policy: .bundled + ) + XCTAssertEqual(privateDecision, .denied(.requiresPro)) + } + func testAnonymousPublicResultIsCached() async { let service = FakeRepositoryVisibilityProvider(results: [.success(.public)]) let cache = FakeRepositoryVisibilityCache() diff --git a/macgitTests/SidebarNativeListTests.swift b/macgitTests/SidebarNativeListTests.swift index 67807984..311c8f03 100644 --- a/macgitTests/SidebarNativeListTests.swift +++ b/macgitTests/SidebarNativeListTests.swift @@ -46,6 +46,25 @@ final class SidebarNativeListTests: XCTestCase { return (owner, table) } + func testIssueRowsFollowHostedProvider() { + XCTAssertEqual(SidebarSection.issueRows(hostedProvider: nil).map(\.item), [.jira]) + for (provider, title) in [(HostedIssueProvider.github, "GitHub Issues"), (.gitlab, "GitLab Issues"), + (.bitbucket, "Bitbucket Issues"), (.azureBoards, "Azure Boards")] { + let rows = SidebarSection.issueRows(hostedProvider: provider) + XCTAssertEqual(rows.map(\.item), [.jira, .hostedIssues]) + XCTAssertEqual(rows.last?.title, title) + XCTAssertEqual(rows.last?.icon, provider.iconName) + } + } + + func testHostedProviderChangeInvalidatesNativeInput() { + var github = input(branch: "main") + github.hostedIssueProvider = .github + var gitlab = github + gitlab.hostedIssueProvider = .gitlab + XCTAssertNotEqual(github, gitlab) + } + func testIssuesSectionIsVisibleByDefaultAndJiraIsNotAWorkspaceRow() { let suiteName = "SidebarNativeListTests.\(UUID().uuidString)" let defaults = UserDefaults(suiteName: suiteName)! diff --git a/macgitTests/SidebarViewStashTests.swift b/macgitTests/SidebarViewStashTests.swift index bc22ec17..4de58d59 100644 --- a/macgitTests/SidebarViewStashTests.swift +++ b/macgitTests/SidebarViewStashTests.swift @@ -79,7 +79,7 @@ final class SidebarViewStashTests: XCTestCase { func testJiraMovesFromWorkspaceToIssuesSection() { XCTAssertFalse(SidebarSection.workspace.items.contains(.jira)) - XCTAssertEqual(SidebarSection.issues.items, [.jira]) + XCTAssertEqual(SidebarSection.issues.items, [.jira, .hostedIssues]) } func testSidebarSettingsStorePersistsSubmodulesSectionToggle() { diff --git a/openspec/changes/add-hosted-issue-trackers/.openspec.yaml b/openspec/changes/add-hosted-issue-trackers/.openspec.yaml new file mode 100644 index 00000000..aa079bc5 --- /dev/null +++ b/openspec/changes/add-hosted-issue-trackers/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-31 diff --git a/openspec/changes/add-hosted-issue-trackers/design.md b/openspec/changes/add-hosted-issue-trackers/design.md new file mode 100644 index 00000000..2334a7f3 --- /dev/null +++ b/openspec/changes/add-hosted-issue-trackers/design.md @@ -0,0 +1,130 @@ +# Design + +## Context + +- The ISSUES sidebar section, the single `AppState.showIssues` setting (persisted under the existing `showWorkspaceJira` UserDefaults and Firestore key), and its collapse state (`SidebarSectionState.issuesExpanded`) are already in the working tree. The work that remains is the hosted tracker row and everything behind it. +- Pull requests already solve the problems issues need solved: + - `GitRemoteIdentityResolver` maps a remote URL to a `GitRepositoryIdentity` (provider, host, owner, name). + - `PullRequestController` picks the remote (`origin`, else the first), finds matching `GitProviderAccount`s by provider and host, and obtains a fresh `GitProviderToken` from `GitProviderTokenVault`. That account-matching and credential-resolution logic is private to `PullRequestController`. + - Each provider has a stateless `*PullRequestService: PullRequestProviding`. + - `RepositoryVisibilityController.accessDecision(for:)` combines the policy, entitlement, and repository visibility. + - Markdown renders through `PullRequestMarkdownContent`. +- Jira contributes the screen shape: + - `JiraIssueListController` handles per-repository filter persistence through `LocalDataStore` and paged loading. + - `JiraBranchNameSuggester` builds the branch name. + - `MainWindowView.prepareCreateBranch(from:target:)` opens the branch or Git Flow start sheet. +- Provider credentials today: + - GitHub OAuth has the `repo` scope and GitLab has `api`. Both already cover reading and writing issues. + - Bitbucket API tokens are created with only the repository scopes. + - Azure PATs are validated with any scope (`connectionData`). + + So Bitbucket and Azure can fail with a permission error even for a connected account. +- There is no Bitbucket visibility service, so `RepositoryVisibilityController` reports `.unknown` for Bitbucket remotes. + +## Goals / Non-Goals + +**Goals:** +- One controller and view serve all four providers. Provider differences live in services and in a small capability description. +- Reuse the provider-account matching and token refresh used by pull requests, without copying it. +- Every provider error maps to a typed error the view can explain (see `hosted-issue-list` and `hosted-issue-actions` specs). + +**Non-Goals:** +- Changing how pull requests resolve accounts, beyond extracting the shared helper. +- A Bitbucket repository-visibility service. Free users on Bitbucket remotes get the same `repositoryVisibilityUnavailable` outcome as other visibility-gated features. +- Disk caching of issues. An in-memory cache per window is enough. + +## Decisions + +### 1. Extract provider credential resolution from `PullRequestController` +Move `matchingAccounts(for:)`, `apiCredential(for:)`, and the token refresh path into `GitProviderAPICredentialResolver`, a `@MainActor` struct initialized with `GitProviderAccountController` and `GitProviderTokenVault`. Both `PullRequestController` and the new issue controller call it. This also gives both features the same reconnect and connect messaging. +- *Alternative:* have the issue controller call into `PullRequestController`. Rejected because it ties the issue screen to the PR screen's lifecycle and published state. +- *Alternative:* duplicate the logic. Rejected because token refresh and account selection would drift apart. + +### 2. `HostedIssueProviding` protocol plus four stateless services +Mirror `PullRequestProviding`. The protocol has these operations: +- `capabilities(repository:token:)` returns the tracker's capabilities: enabled or disabled, work item types, and the state map. +- `listIssues(repository:token:filter:cursor:)` returns a page of results. +- `issueDetail` +- `createIssue` +- `addComment` +- `setState(open|closed)` + +Each service owns its provider details: + +| Provider | List | Filters | Pagination | Notes | +|---|---|---|---|---| +| GitHub (`GitHubIssueService`) | `/repos/{o}/{r}/issues` | `state`, `assignee=`, `creator=` | `Link` header | Drops items that have `pull_request`. When search text is present it uses `/search/issues?q=repo:o/r is:issue …`, which has its own rate limit. The base URL comes from the account host, so GitHub Enterprise Server works. `410 Gone` means issues are disabled. | +| GitLab (`GitLabIssueService`) | `/projects/:id/issues` | `state=opened\|closed`, `scope=assigned_to_me\|created_by_me\|all`, `search=` | `page` and `per_page` (`X-Next-Page`) | Close and reopen use `state_event`. Comments are notes. | +| Bitbucket (`BitbucketIssueService`) | `/2.0/repositories/{ws}/{slug}/issues` | BBQL `q=` with `state IN (...)`, `assignee.uuid=` and `reporter.uuid=` | The `next` URL | Open means `new`, `open`, or `on hold`. Closed means any other state. Close and reopen set `resolved` and `open`. A 404 with "no issue tracker" means disabled. 403 means a missing `read:issue:bitbucket` or `write:issue:bitbucket` scope. | +| Azure Boards (`AzureBoardsWorkItemService`) | WIQL scoped to `[System.TeamProject]`, with `@Me` for assigned or created | — | IDs come in one WIQL response, then details are fetched with `workitemsbatch` in chunks of 200. Pagination works over the ID list. | Before filtering by state, it calls `workitemtypes/{type}/states` to map states to categories. Open means Proposed, InProgress, or Resolved. Closed means Completed or Removed. Close moves to the first Completed state and Reopen to the first Proposed state. Comments use the work item comments API (preview version pinned). Descriptions are HTML. | + +Each service maps provider errors to `HostedIssueError`: +- `trackerDisabled` +- `missingScope(String)` +- `organizationAccessRequired` +- `reauthorizationRequired` +- `rateLimited(retryAfter:)` +- `notFound` +- `providerMessage` +- *Alternative:* add issue methods to `PullRequestProviding`. Rejected because the two features have different lifecycles and Bitbucket has no PR service. + +### 3. `HostedIssueController`: one per window, owned by `MainWindowView` +`HostedIssueController` is a `@MainActor ObservableObject` created next to `PullRequestController` and `JiraIssueListController` in `MainWindowView.init`. It owns: +- remote discovery (recognized remotes and the chosen remote) +- filter state +- paged items +- selection and detail +- the write-in-progress state +- an in-memory list cache with a 60 s TTL + +Filters and the chosen remote are persisted through a `LocalDataStore` collection keyed by repository path. Filters are additionally keyed by remote name. This follows `LocalJiraIssueFilterStore`. Loads use a load-ID guard, the same pattern as `PullRequestController`, so stale responses are dropped. After a successful write, it reloads detail and the current page, keeps the selection, and marks the written issue as pinned until the next refresh. +- The controller listens for `.repositoryRemoteRefsDidRefresh` and `.repositoryDidChange` for its own repository URL to rediscover remotes. These notifications already carry the repository; the controller ignores other repositories, so the behavior is window-scoped. + +### 4. Sidebar row: one `SidebarItem.hostedIssues` with a dynamic title +Add `SidebarItem.hostedIssues` to `SidebarSection.issues.items` after `.jira`. Today `SidebarView+NativeRows` uses `item.rawValue` as the title. For the issues section it will take the title and icon from `HostedIssueProvider` (derived from the chosen remote's `GitProviderKind`), which `SidebarView` receives as an input. That value is also added to `SidebarNativeInput.flags`/a new field, so the row rebuilds when it changes. This avoids the bug fixed earlier, where a missing input left the list stale. The row is omitted when no remote is recognized. `MainWindowView` already resets the selection on `showIssues` changes; extend that `onChange` so it also resets when the provider becomes nil. +- *Alternative:* one `SidebarItem` case per provider. Rejected because selection, routing, and screen caching would need four identical cases. + +### 5. Gating: `PlanFeature.hostedIssues`, repository-scoped +- Add the case to `PlanFeature`. +- Give it a bundled rule identical to `.pullRequests`: Free `.public`, Pro `.all`. +- Add it to `requiresRepositoryScope` in `FeaturePolicyStore`. +- Add display text in `FeatureAccessNotice` and the Pro upgrade sheet. + +`MainWindowView` gets `authorizeHostedIssueAccess()`, mirroring `authorizePullRequestAccess()` through `repositoryVisibilityController.accessDecision(for: .hostedIssues, …)`. The screen block in `cachedRepositoryScreens` follows the pull request block: allowed shows the view, denied shows `FeatureAccessUnavailableView`, and nil shows progress. Write actions call the same authorization again before sending. + +### 6. Views +- `Views/Issues/HostedIssueListView` is a split view: a list with a filter bar and a remote picker, next to a detail pane. +- `HostedIssueDetailView` reuses `PullRequestMarkdownContent` and the conversation block styling. +- `NewHostedIssueSheet` holds the title, description, and (Azure only) the type picker. + +Azure HTML is converted to plain text with `NSAttributedString(html:)` options that disable remote resource loading, or a stripping fallback if needed. It is never shown in a web view. "New Issue…" is a button in the screen's toolbar, not a menu command, so no `FocusedValues` or notification routing is added. + +### 7. Branch naming +Rename `JiraBranchNameSuggester` to `IssueBranchNameSuggester`. Its `name(key:summary:)` stays as it is, and hosted issues pass the bare number as `key`. Rename `JiraBranchTarget` to `IssueBranchTarget`. `prepareCreateBranch(from:target:)` takes `(key, summary)` so Jira and hosted issues share it. + +### 8. Undo and refresh +Issue writes do not touch the repository, so they are not registered with `GitUndoManager` and do not go through `SyncState`. Refresh after a write is local to `HostedIssueController`, as the `hosted-issue-actions` spec describes. + +### 9. Bitbucket connection: Atlassian email and issue scopes +Bitbucket REST calls authenticate an API token with HTTP Basic `email:token`. The Git username stored on the account does not work for REST, and the app made no Bitbucket REST calls before this change. +- Add an optional `apiUsername` field to `GitProviderToken`. It is optional and `Codable`, so existing Keychain items still decode. It is filled from a new "Atlassian email" field in the Bitbucket section of `GitProviderAddAccountSheet` and passed through `GitProviderAccountController.connectBitbucket`. +- Keeping the email in the Keychain token, rather than in `GitProviderAccount.permissions`, keeps it off Firestore. Provider-account sync stores `permissions` as a synced map. +- When a Bitbucket token has no `apiUsername`, `BitbucketIssueService` throws `HostedIssueError.accountUpdateRequired`, and the screen offers Settings → Connections. +- Update the connect sheet text to list the issue scopes (`read:issue:bitbucket`, `write:issue:bitbucket`) and add them to the scopes recorded for new connections. Existing tokens keep working for Git and hit `accountUpdateRequired` or `missingScope` only on the issue screen. + +## Risks / Trade-offs + +- [GitHub search API limit (30 requests/min) when searching] → Debounce search by 400 ms and search only on server-side text input. On `rateLimited`, show the retry time. +- [The Azure comments API is a preview version] → Pin the version in one place. On a 400 or 404 from that endpoint, show the comments as unavailable instead of failing the whole detail. +- [Azure state categories differ per process template] → Read them from the states API for each type and cache them for the session. Never hard-code names like "Closed" or "Done". +- [Bitbucket issue trackers are often turned off] → The `trackerDisabled` state explains this and links to the repository settings page. +- [Free users on Bitbucket remotes are denied because visibility is unknown] → This matches existing visibility-gated features. Note it as a follow-up (a Bitbucket visibility service), not a blocker. +- [`hostedIssues` missing from the published policy] → The bundled rule applies. Publishing the policy is a separate authorized rollout step. +- [GitHub Enterprise or self-managed GitLab running old API versions] → Use only long-stable v3/v4 endpoints, and surface `providerMessage` as is. + +## Migration Plan + +1. Ship the app with the bundled `hostedIssues` rule. No settings or data migration is needed; "Show Issues" already reuses the synced key. +2. In `../landing-page`, add `hostedIssues` to `admin/lib/schemas.ts` and `scripts/firebase/set-feature-policy.mjs` (next revision, same rule as `pullRequests`). Publish the policy only with explicit user authorization. +3. Update the `add-jira-sprint-issues` delta so it defers placement to `repository-issues-section` before archiving either change. +4. Rollback: a remote policy entry `hostedIssues.enabled = false` hides the feature without an app update. diff --git a/openspec/changes/add-hosted-issue-trackers/proposal.md b/openspec/changes/add-hosted-issue-trackers/proposal.md new file mode 100644 index 00000000..24392777 --- /dev/null +++ b/openspec/changes/add-hosted-issue-trackers/proposal.md @@ -0,0 +1,52 @@ +# Proposal + +## Why + +Commit+ already connects to GitHub, GitLab, Bitbucket, and Azure DevOps for cloning, pushing, and pull requests, but users still switch to the browser to find the issue they are working on, retype its number into a branch name, or post a quick comment. The sidebar now has a dedicated ISSUES section (currently holding only Jira), so hosted issue trackers can join it without mixing integration data into the Workspace section. + +## What Changes + +- The sidebar ISSUES section gains one row for the repository's hosted issue tracker, labeled by provider: "GitHub Issues", "GitLab Issues", "Bitbucket Issues", or "Azure Boards". It appears only when one of the repository's remotes is recognized as one of these providers. Jira stays in the same section. The single "Show Issues" setting (General settings and the sidebar context menu) hides or shows the whole section. +- Selecting the row opens an issue list for that repository. By default it shows open issues from the repository's tracker. Azure Boards shows work items from the repository's project. Filters: state (open, closed, all), relationship (all, assigned to me, created by me), and text search. A remote picker appears when more than one remote has a supported tracker, for example a fork with an `upstream` remote. The filter and remote choice are remembered per repository. +- An issue detail pane shows the description, labels or tags, assignees, and comments, and offers: open in browser, copy number/key, copy reference with title, and create a branch from the issue (same flow as Jira, prefilled `-`). +- Basic write actions: create an issue (title and description; on Azure, also the work item type), add a comment, and close or reopen an issue. Each write needs an explicit user action, is sent with the connected provider account, and refreshes the list and detail when it succeeds. Commit+ does not edit titles, descriptions, labels, assignees, or milestones, and does not delete issues. +- Gate the feature behind a new plan feature, `hostedIssues`, with the same rule as `pullRequests`: Free for public repositories, Pro for all repositories. When the remote policy is unavailable, the bundled rule applies. +- Provider coverage: + - **GitHub**: GitHub.com and GitHub Enterprise Server. + - **GitLab**: GitLab.com and self-managed GitLab. + - **Bitbucket**: Bitbucket Cloud. The repository's issue tracker must be turned on, and the API token must include issue scopes. + - **Azure Boards**: Azure DevOps Services work items. The PAT must include Work Items scope. + + When the tracker is turned off or the credential lacks the needed scope, the screen says so instead of showing an empty list. +- Azure Repos remotes now offer an issues link that opens the project's Boards work items page. Previously no issues link was offered. +- Out of scope: Repository AI tools for issues, linking commits or PRs to issues automatically, notifications, issue boards or iterations, editing issue fields, GitHub Projects, Bitbucket Data Center, Azure DevOps Server (on-premises), and offline caching beyond the session. + +## Capabilities + +### New Capabilities +- `repository-issues-section`: The sidebar ISSUES section. Covers which rows it contains (Jira and the hosted tracker row), when the hosted row appears and how it is labeled, the "Show Issues" setting, collapse state, and selection fallback when a row disappears. +- `hosted-issue-list`: The plan-gated hosted issue screen. Covers provider and remote resolution, access gating, connection and permission guidance, the list, filters, detail pane, and read-only actions including branch creation. +- `hosted-issue-actions`: Creating issues, commenting, and closing or reopening issues on the hosted tracker. Covers the required permissions, confirmation and error behavior, and the refresh that follows. + +### Modified Capabilities +- `azure-repos-remote-recognition`: "Azure repositories open in the browser" changes from "no issues link" to an issues link that opens the project's Boards work items page. + +## Impact + +- **Native app (`macgit`)**: + - New `PlanFeature.hostedIssues`, repository-scoped, with a bundled rule mirroring `pullRequests`. + - A new `SidebarItem` for the hosted tracker row, with a provider-specific title. + - A new per-window issue controller and four provider services (GitHub, GitLab, Bitbucket, Azure Boards) that reuse the existing provider accounts, `GitProviderTokenVault`, and remote identity resolution. + - The branch-name suggester is generalized from Jira. + - Updates to `MainWindowView` screen routing and gating, `RepositoryBookmarkRemote.issuesURL`, and the Bitbucket connect-sheet guidance (issue scopes). +- **External APIs**: + - GitHub REST (`/repos/{owner}/{repo}/issues`, `/search/issues`, comments). + - GitLab REST v4 (`/projects/:id/issues`, notes). + - Bitbucket Cloud 2.0 (`/repositories/{workspace}/{slug}/issues`, comments). + - Azure DevOps REST (WIQL, `workitemsbatch`, work item types and states, comments). +- **Synced settings**: none. "Show Issues" reuses the existing synced `showWorkspaceJira` field. +- **Cross-repository (`../landing-page`)**: + - Add `hostedIssues` to the feature-policy schema (`admin/lib/schemas.ts`) and to the provisioning script (`scripts/firebase/set-feature-policy.mjs`, next revision). Until that policy is published, the app uses its bundled rule. + - Publishing the policy requires explicit authorization. + - No Firestore rules, indexes, or Cloud Functions change. +- **In-flight change `add-jira-sprint-issues`**: its requirement "Jira appears in the sidebar Workspace section" no longer matches the app. Placement is now defined by `repository-issues-section`, and that delta must be updated before either change is archived. diff --git a/openspec/changes/add-hosted-issue-trackers/specs/azure-repos-remote-recognition/spec.md b/openspec/changes/add-hosted-issue-trackers/specs/azure-repos-remote-recognition/spec.md new file mode 100644 index 00000000..a50e9235 --- /dev/null +++ b/openspec/changes/add-hosted-issue-trackers/specs/azure-repos-remote-recognition/spec.md @@ -0,0 +1,18 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Azure repositories open in the browser +For an Azure Repos remote, the app SHALL open the repository web page at the canonical URL and the pull request list at `{canonical}/pullrequests`. The issues link SHALL open the project's Boards work items page at `https://dev.azure.com/{org}/{project}/_workitems`, because Azure DevOps tracks work items per project rather than per repository. + +#### Scenario: Open remote in browser +- **WHEN** the user opens an Azure Repos remote in the browser, including an SSH remote +- **THEN** `https://dev.azure.com/{org}/{project}/_git/{repo}` opens + +#### Scenario: Bookmark links +- **WHEN** the user views links for an Azure Repos bookmark +- **THEN** a pull requests link and an issues link are offered + +#### Scenario: Issues link opens project work items +- **WHEN** the user opens the issues link for a remote in organization `Trantienthanh1998` and project `ChatApp` +- **THEN** `https://dev.azure.com/Trantienthanh1998/ChatApp/_workitems` opens diff --git a/openspec/changes/add-hosted-issue-trackers/specs/hosted-issue-actions/spec.md b/openspec/changes/add-hosted-issue-trackers/specs/hosted-issue-actions/spec.md new file mode 100644 index 00000000..c324c60f --- /dev/null +++ b/openspec/changes/add-hosted-issue-trackers/specs/hosted-issue-actions/spec.md @@ -0,0 +1,76 @@ +# Spec Delta + +## Purpose + +Defines the write actions on hosted issue trackers available from the hosted issue screen: creating an issue, commenting, and closing or reopening, each performed with the user's connected provider account. + +## ADDED Requirements + +### Requirement: Write actions follow the screen's access +Write actions SHALL be available only when the hosted issue screen is allowed for the repository. Every write SHALL use the same remote and provider account as the list. Each write SHALL start only from an explicit user action, and the app SHALL NOT send writes in the background or retry them automatically. + +#### Scenario: Access denied +- **WHEN** `hostedIssues` is denied for the repository +- **THEN** no create, comment, close, or reopen action is offered + +#### Scenario: Failed write is not retried +- **WHEN** posting a comment fails because of a network error +- **THEN** the error is shown, the draft text is kept, and nothing is sent until the user tries again + +### Requirement: Create an issue +The screen SHALL offer "New Issue…", which opens a sheet with a required title and an optional Markdown description. For Azure Boards, the sheet SHALL also require a work item type chosen from the project's types. Creating SHALL be disabled while the title is blank or a request is in progress. On success, the new issue SHALL be selected in the list. + +#### Scenario: Create on GitHub +- **WHEN** the user creates an issue titled "Crash on launch" in GitHub Issues +- **THEN** the issue is created on the repository and appears selected in the list + +#### Scenario: Azure work item type +- **WHEN** the user opens "New Issue…" on Azure Boards +- **THEN** the sheet lists the project's work item types and requires one + +#### Scenario: Blank title +- **WHEN** the title is empty or whitespace +- **THEN** Create is disabled + +#### Scenario: Cancel keeps nothing +- **WHEN** the user cancels the sheet +- **THEN** no request is sent + +### Requirement: Comment on an issue +The detail pane SHALL offer a comment field with a Comment action. Posting SHALL be disabled while the text is blank or a request is in progress. On success, the field SHALL clear and the new comment SHALL appear in the detail. + +#### Scenario: Post a comment +- **WHEN** the user posts "Fixed in main" on issue #42 +- **THEN** the comment appears at the end of the issue's comments + +### Requirement: Close and reopen an issue +The detail pane SHALL offer Close for an open issue and Reopen for a closed one. On Azure Boards, Close SHALL move the work item to the first state of its type in the Completed category, and Reopen SHALL move it to the first state in the Proposed category. On Bitbucket, Close SHALL set the state to resolved and Reopen SHALL set it to open. + +#### Scenario: Close and undo by reopening +- **WHEN** the user closes issue #42 and then chooses Reopen +- **THEN** the issue is open again on the tracker + +#### Scenario: Azure type without a Completed state +- **WHEN** a work item's type has no state in the Completed category +- **THEN** Close is unavailable for that work item and the reason is shown + +### Requirement: Results refresh after a write +After a successful write, the affected issue's detail and the list SHALL be reloaded from the tracker, keeping the user's selection and scroll position. A row that no longer matches the active filter SHALL stay visible until the next refresh, so it does not vanish while the user is looking at it. + +#### Scenario: Close under the Open filter +- **WHEN** the user closes an issue while the list shows Open issues +- **THEN** the issue stays selected and shows Closed until the list is next refreshed + +### Requirement: Write permission errors are explained +When the tracker rejects a write because the account lacks permission, the screen SHALL say which permission is missing, such as Bitbucket issue write scope, Azure DevOps Work Items (Read & write) scope, or repository access on GitHub or GitLab. The user's input SHALL be kept. + +#### Scenario: Read-only Azure PAT +- **WHEN** the Azure PAT has Work Items (Read) but not (Read & write) and the user posts a comment +- **THEN** the screen says the token needs Work Items (Read & write) and the comment text is kept + +### Requirement: Issue writes are not app undo actions +Issue writes SHALL NOT be added to the repository undo history, because they change the tracker and not the repository. Close and Reopen SHALL be the way to reverse each other. + +#### Scenario: Undo after closing an issue +- **WHEN** the user closes an issue and then chooses Edit → Undo +- **THEN** the issue is not reopened, and the most recent repository action, if any, is undone instead diff --git a/openspec/changes/add-hosted-issue-trackers/specs/hosted-issue-list/spec.md b/openspec/changes/add-hosted-issue-trackers/specs/hosted-issue-list/spec.md new file mode 100644 index 00000000..a573360c --- /dev/null +++ b/openspec/changes/add-hosted-issue-trackers/specs/hosted-issue-list/spec.md @@ -0,0 +1,159 @@ +# Spec Delta + +## Purpose + +Defines the hosted issue screen opened from the ISSUES section, which lists and shows issues from the repository's GitHub, GitLab, Bitbucket, or Azure Boards tracker using the user's connected provider account. + +## ADDED Requirements + +### Requirement: Supported trackers +The screen SHALL support GitHub.com and GitHub Enterprise Server issues, GitLab.com and self-managed GitLab issues, Bitbucket Cloud repository issues, and Azure DevOps Services work items. For Azure Repos remotes, the screen SHALL show work items of the remote's project rather than of the repository. + +#### Scenario: Azure project scope +- **WHEN** the user opens Azure Boards for a remote in project `ChatApp` +- **THEN** the list shows work items of project `ChatApp`, including ones not linked to this repository + +### Requirement: Hosted issues are gated like pull requests +Opening the screen SHALL require plan feature `hostedIssues`. Its bundled rule SHALL allow Free for public repositories and Pro for all repositories. When the remote policy lacks a valid entry or cannot load, the bundled rule SHALL apply. When access is denied, the screen SHALL show the feature-access view and SHALL NOT contact the provider. + +#### Scenario: Free user, public repository +- **WHEN** a Free user opens GitHub Issues for a public GitHub repository +- **THEN** the issue list is shown + +#### Scenario: Free user, private repository +- **WHEN** a Free user opens issues for a private repository +- **THEN** the screen offers Upgrade and makes no issue request + +#### Scenario: Policy predates the feature +- **WHEN** the published feature policy has no `hostedIssues` entry +- **THEN** access follows the bundled rule + +#### Scenario: Remote kill switch +- **WHEN** the published feature policy disables `hostedIssues` +- **THEN** the screen shows that the feature is unavailable for every plan + +### Requirement: Issues load with the matching provider account +The screen SHALL use the connected provider account that the app already uses for this remote's pull requests and Git operations. When no matching account is connected or it needs reconnection, the screen SHALL say so and offer to open Settings → Connections. Credentials SHALL NOT appear in logs or error messages. + +#### Scenario: No account +- **WHEN** the user opens GitLab Issues and no GitLab account matches the remote's host +- **THEN** the screen offers "Connect GitLab" and makes no issue request + +#### Scenario: Expired token +- **WHEN** the provider rejects the saved token +- **THEN** the screen says the account needs to be reconnected and offers to open Settings → Connections + +### Requirement: Bitbucket issues need the Atlassian account email +Bitbucket's REST API authenticates an API token with the Atlassian account email, not the Bitbucket username used for Git. The Bitbucket connection sheet SHALL offer an "Atlassian email" field, stored with the API token on this Mac only and never synced. When a Bitbucket account has no saved email, the issue screen SHALL say so and offer to open Settings → Connections; Git operations SHALL keep working without it. + +#### Scenario: Account without email +- **WHEN** the user opens Bitbucket Issues with an account connected before the email field existed +- **THEN** the screen asks to add the Atlassian email to the Bitbucket account and makes no issue request + +#### Scenario: Email is local +- **WHEN** the user saves an Atlassian email on one Mac and signs in on another Mac +- **THEN** the other Mac does not receive the email + +### Requirement: Missing scope or disabled tracker is explained +When the provider reports that the tracker is turned off for the repository, the screen SHALL say so instead of showing an empty list. When the credential lacks the needed permission, the screen SHALL name the missing permission: Bitbucket issue scopes, Azure DevOps Work Items scope, or organization access for GitHub. + +#### Scenario: GitHub issues disabled +- **WHEN** issues are turned off for the GitHub repository +- **THEN** the screen says issues are turned off for this repository and offers to open the repository in the browser + +#### Scenario: Bitbucket token without issue scope +- **WHEN** the Bitbucket API token lacks issue read access +- **THEN** the screen says the token needs issue scopes and offers to open Settings → Connections + +#### Scenario: Azure PAT without Work Items scope +- **WHEN** the Azure DevOps PAT cannot read work items +- **THEN** the screen says the token needs the Work Items scope + +#### Scenario: GitHub organization restricts the app +- **WHEN** a GitHub organization blocks Commit+'s access to the repository +- **THEN** the screen explains that organization access must be granted and offers the existing organization access action + +### Requirement: Remote choice for repositories with several trackers +When more than one remote has a supported tracker, the screen SHALL offer a remote picker that shows each remote's name and provider. The choice SHALL be remembered per repository on this Mac. The default SHALL be `origin`, otherwise the first recognized remote. + +#### Scenario: Fork with upstream +- **WHEN** a repository has `origin` (the user's fork) and `upstream`, both on GitHub +- **THEN** the screen shows `origin` issues and offers a picker to switch to `upstream` + +#### Scenario: Remembered choice +- **WHEN** the user picks `upstream` and later reopens the repository +- **THEN** the screen shows `upstream` issues + +### Requirement: Default list and ordering +By default the list SHALL show open issues of the tracker, most recently updated first. Each row SHALL show the number or key, title, author, state, update time, and labels or tags when present. GitHub pull requests SHALL NOT appear as issues. + +#### Scenario: Default list +- **WHEN** the user opens the screen for the first time +- **THEN** open issues are listed, most recently updated first + +#### Scenario: GitHub pull requests are excluded +- **WHEN** a GitHub repository has open pull requests and open issues +- **THEN** only the issues are listed + +#### Scenario: Many issues +- **WHEN** more issues match than one provider response contains +- **THEN** further results load as the user scrolls to the end + +### Requirement: Filters +The screen SHALL filter by state (Open, Closed, All), relationship (All, Assigned to me, Created by me), and text search on title, number, or key. The state and relationship filters SHALL be remembered per repository and remote. Search text SHALL NOT be stored. + +#### Scenario: Assigned to me +- **WHEN** the user chooses "Assigned to me" +- **THEN** only issues assigned to the connected account are listed + +#### Scenario: Azure closed state +- **WHEN** the user chooses Closed on Azure Boards +- **THEN** work items whose state belongs to the Completed or Removed category are listed + +#### Scenario: Search +- **WHEN** the user types `login` into search +- **THEN** the list shows matching issues from the tracker, not only already loaded rows + +#### Scenario: Filtered empty result +- **WHEN** no issue matches the filters +- **THEN** the screen says no issues match and offers to clear the filters + +### Requirement: Issue detail +Selecting an issue SHALL show its title, number or key, state, author, assignees, labels or tags, created and updated times, description, and comments in chronological order. Markdown SHALL render for GitHub, GitLab, and Bitbucket. Azure HTML descriptions and comments SHALL show as readable text without running scripts or loading remote content automatically. + +#### Scenario: Open detail +- **WHEN** the user selects issue #42 +- **THEN** the detail pane shows its description and comments + +#### Scenario: Azure description +- **WHEN** an Azure work item description contains HTML formatting and an image +- **THEN** the text is readable and the image is not loaded automatically + +### Requirement: Read-only issue actions +For any issue, the screen SHALL offer: open in browser, copy number or key, and copy reference with title. The number format SHALL be `#42` for GitHub, GitLab, and Bitbucket, and `AB#42` for Azure Boards. + +#### Scenario: Copy reference +- **WHEN** the user copies the reference of GitHub issue 42 titled "Fix login" +- **THEN** the clipboard contains `#42 Fix login` + +### Requirement: Create a branch from an issue +The screen SHALL offer to create a branch from an issue. The branch name SHALL be prefilled as `-`, limited to 60 characters at a word boundary, and SHALL always keep the number. When Git Flow is configured, Git Flow start actions SHALL be offered with the same name. Nothing SHALL be written to the tracker. + +#### Scenario: Plain branch +- **WHEN** the user creates a branch from issue 42 titled "Fix login on Safari" +- **THEN** the new branch sheet opens with `42-fix-login-on-safari` + +#### Scenario: Git Flow feature +- **WHEN** Git Flow is configured and the user starts a feature from that issue +- **THEN** the Git Flow start sheet opens with topic `42-fix-login-on-safari` + +### Requirement: Loading, errors, and refresh +The screen SHALL show progress while loading, keep the current rows while refreshing, and offer Retry after a failure. A rate-limit response SHALL say the provider is busy and when to retry if known. The screen SHALL refresh when it becomes visible again after more than one minute, and on demand. + +#### Scenario: Rate limited +- **WHEN** GitHub returns a rate-limit response +- **THEN** the screen says GitHub is busy and offers Retry + +#### Scenario: Refresh keeps rows +- **WHEN** the user refreshes a loaded list +- **THEN** existing rows stay visible until new results arrive diff --git a/openspec/changes/add-hosted-issue-trackers/specs/repository-issues-section/spec.md b/openspec/changes/add-hosted-issue-trackers/specs/repository-issues-section/spec.md new file mode 100644 index 00000000..56d1006b --- /dev/null +++ b/openspec/changes/add-hosted-issue-trackers/specs/repository-issues-section/spec.md @@ -0,0 +1,74 @@ +# Spec Delta + +## Purpose + +Defines the ISSUES section of the repository sidebar, which groups issue-tracker integrations (Jira and the repository's hosted issue tracker) separately from the repository's own Workspace items. + +## ADDED Requirements + +### Requirement: Issue trackers have their own sidebar section +The repository sidebar SHALL show an ISSUES section directly below the Workspace section. Issue-tracker rows, including Jira, SHALL appear only in this section and SHALL NOT appear in the Workspace section. + +#### Scenario: Section placement +- **WHEN** the user opens a repository window with Show Issues on +- **THEN** the ISSUES section appears between Workspace and Branches +- **AND** Workspace does not list Jira + +### Requirement: One setting controls the ISSUES section +A single "Show Issues" setting SHALL hide or show the whole ISSUES section in every repository window. It SHALL be available in General settings under Repository Sidebar and in the sidebar background context menu. It SHALL default to on, and SHALL use the existing synced Jira visibility value so that earlier choices carry over. There SHALL be no per-row visibility toggles. + +#### Scenario: Default +- **WHEN** the user has never changed Show Issues +- **THEN** the ISSUES section is shown + +#### Scenario: Hide from settings +- **WHEN** the user turns off "Show Issues" in General settings +- **THEN** the ISSUES section disappears from every open repository window and stays hidden after relaunch + +#### Scenario: Earlier Jira choice carries over +- **WHEN** a user who had hidden Jira in an earlier version updates +- **THEN** Show Issues is off + +#### Scenario: Toggle from the sidebar +- **WHEN** the user chooses "Show Issues" in the sidebar background context menu +- **THEN** the section's visibility flips and General settings reflects the change + +### Requirement: The ISSUES section collapses like other sections +Clicking the ISSUES header SHALL collapse or expand the section. The expanded state SHALL be remembered per repository and SHALL default to expanded. + +#### Scenario: Collapse +- **WHEN** the user clicks the ISSUES header while it is expanded +- **THEN** its rows are hidden immediately and stay hidden when the repository is reopened + +### Requirement: Rows in the ISSUES section +The section SHALL list Jira, followed by one hosted tracker row when the repository has a remote recognized as GitHub, GitLab, Bitbucket, or Azure Repos. The hosted row SHALL be titled "GitHub Issues", "GitLab Issues", "Bitbucket Issues", or "Azure Boards" and use that provider's icon. Without a recognized remote, the hosted row SHALL be absent. + +#### Scenario: GitHub repository +- **WHEN** the repository's `origin` remote points to github.com +- **THEN** the section lists "Jira" and "GitHub Issues" + +#### Scenario: Local-only repository +- **WHEN** the repository has no remote +- **THEN** the section lists only "Jira" + +#### Scenario: Remote added later +- **WHEN** the user adds a GitLab remote to a repository that had none +- **THEN** a "GitLab Issues" row appears without reopening the window + +### Requirement: The hosted row follows the preferred remote +When several remotes are recognized, the hosted row SHALL use the provider of the remote chosen for the issue screen: the remembered choice for this repository, otherwise `origin`, otherwise the first recognized remote. + +#### Scenario: Remotes on different providers +- **WHEN** `origin` is a GitLab remote and `mirror` is a GitHub remote, and no choice is remembered +- **THEN** the hosted row is titled "GitLab Issues" + +### Requirement: A disappearing row cannot stay selected +When the selected row in the ISSUES section disappears, the window SHALL select File status. This applies when Show Issues is turned off and when the hosted row is removed. + +#### Scenario: Hide while viewing issues +- **WHEN** the user turns off Show Issues while the GitHub Issues screen is selected +- **THEN** the window selects File status + +#### Scenario: Remote removed +- **WHEN** the only recognized remote is removed while its issue screen is selected +- **THEN** the hosted row disappears and the window selects File status diff --git a/openspec/changes/add-hosted-issue-trackers/tasks.md b/openspec/changes/add-hosted-issue-trackers/tasks.md new file mode 100644 index 00000000..3d3ad62e --- /dev/null +++ b/openspec/changes/add-hosted-issue-trackers/tasks.md @@ -0,0 +1,71 @@ +# Tasks + +## 1. ISSUES section and Show Issues setting (committed in 7dd65914) + +- [x] 1.1 Add `SidebarSection.issues` with collapse state `issuesExpanded`, move `.jira` out of Workspace, and include both values in `SidebarNativeInput`. Verified by `SidebarViewStashTests` (collapse decode and toggle, Jira not in Workspace). +- [x] 1.2 Replace the per-row Jira toggle with `AppState.showIssues`, stored under the existing `showWorkspaceJira` key. Add "Show Issues" to General settings → Repository Sidebar and to the sidebar background menu. Verified by `AppSettingsSnapshotTests`, `CloudSettingsDocumentTests`, and `SidebarNativeListTests`. + +## 2. Shared foundations + +- [x] 2.1 Extract `matchingAccounts(for:)`, `apiCredential(for:)`, and token refresh from `PullRequestController` into `GitProviderAPICredentialResolver`, and switch `PullRequestController` to use it. Verify that `PullRequestControllerTests` still pass unchanged. +- [x] 2.2 Rename `JiraBranchNameSuggester` to `IssueBranchNameSuggester` and `JiraBranchTarget` to `IssueBranchTarget`. Change `prepareCreateBranch(from:target:)` to take `(key, summary)`. Verify that the renamed `IssueBranchNameSuggesterTests` pass, with an added case for a bare number key (`42-fix-login-on-safari`). +- [x] 2.3 Add `PlanFeature.hostedIssues` with a bundled rule equal to `.pullRequests`, add it to `requiresRepositoryScope`, and add its `FeatureAccessNotice` and upgrade-sheet text. Verify with `FeatureAccessPolicyTests` (bundled rule, missing remote entry, kill switch) and `FeatureAccessNoticeTests`. +- [x] 2.4 Add the `HostedIssue` models (summary, detail, comment, filter, state, page cursor, tracker capabilities), the `HostedIssueError` mapping, and the `HostedIssueProviding` protocol. Verify a `HostedIssueModelsTests` class for reference formatting (`#42` and `AB#42`) and filter persistence encoding. + +## 3. Provider services (each with URLProtocol-stubbed unit tests) + +- [x] 3.1 Implement `GitHubIssueService`: list, search, detail and comments, create, comment, close and reopen. Verify `GitHubIssueServiceTests`: PRs filtered out, `Link` pagination, assignee and creator filters, search query, `410` → `trackerDisabled`, org restriction → `organizationAccessRequired`, rate limit → `rateLimited`, and an Enterprise base URL. +- [x] 3.2 Implement `GitLabIssueService`. Verify `GitLabIssueServiceTests`: the state, scope, and search parameters, `X-Next-Page` pagination, `state_event` close and reopen, notes as comments, a self-managed host, and 403/404 mapping. +- [x] 3.3 Implement `BitbucketIssueService`. Verify `BitbucketIssueServiceTests`: the BBQL state and relationship query, `next` pagination, the open/closed state mapping, resolved/open transitions, no tracker → `trackerDisabled`, and 403 → `missingScope("issue")`. +- [x] 3.4 Implement `AzureBoardsWorkItemService`: WIQL, `workitemsbatch` chunking, the state-category map from the type states API, type list, create, comments, and close/reopen state selection. Verify `AzureBoardsWorkItemServiceTests`: the project-scoped WIQL with `@Me`, chunks of 200, Completed/Proposed state choice, a type with no Completed state → close unavailable, 401/403 → `missingScope("Work Items")`, and HTML description conversion that loads no remote content. + +## 4. Controller and remote handling + +- [x] 4.1 Implement `HostedIssueController`: + - remote discovery (`origin` first, then other recognized remotes) and the remembered remote choice + - per-repository and per-remote filter persistence in `LocalDataStore` + - paged loading with a load-ID guard and a 60 s in-memory TTL + - selection and detail + - refresh when the screen becomes visible again after 60 s + + Verify `HostedIssueControllerTests` with a stub provider: default open filter, remembered remote and filter, stale responses dropped, no request when there is no account, and connect/reconnect states. +- [x] 4.2 Add the write flow: create, comment, close and reopen. Each write re-authorizes, keeps the draft on failure, never retries automatically, reloads detail and list on success, and keeps the written issue visible until the next refresh. Verify in `HostedIssueControllerTests`: the draft is kept after an error, the issue stays visible after closing under the Open filter, and a created issue is selected. +- [x] 4.3 Rediscover remotes on `.repositoryRemoteRefsDidRefresh` and `.repositoryDidChange` for the controller's own repository only. Verify in `HostedIssueControllerTests` that a notification for another repository URL is ignored and that adding a remote publishes a provider. + +## 5. Sidebar row, routing, and gating + +- [x] 5.1 Add `SidebarItem.hostedIssues` after `.jira` in `SidebarSection.issues.items`. Render it with the provider title and icon, add the provider to `SidebarNativeInput`, and omit the row when there is no recognized remote. Verify in `SidebarNativeListTests`: rows for GitHub/GitLab/Bitbucket/Azure titles, no row for a local-only repository, and a row rebuild when the provider changes. +- [x] 5.2 In `MainWindowView`, create `HostedIssueController` and add `authorizeHostedIssueAccess()` using `accessDecision(for: .hostedIssues)`. Add the cached screen block (allowed → view, denied → `FeatureAccessUnavailableView`, nil → progress). Reset the selection to File status when the provider becomes nil. Verify that the build succeeds and that the `RepositoryVisibilityControllerTests` case for `.hostedIssues` passes. +- [x] 5.3 Change `RepositoryBookmarkRemote.issuesURL` to return `https://dev.azure.com/{org}/{project}/_workitems` for Azure Repos. Verify with an updated `PullRequestURLBuilderTests` or bookmark remote test case for Azure. +- [x] 5.4 Add an optional "Atlassian email" field to the Bitbucket connect/edit sheet, saved as `GitProviderToken.apiUsername` in the Keychain only. Update the sheet guidance and the recorded scopes to include `read:issue:bitbucket` and `write:issue:bitbucket`. Verify in `GitProviderAccountControllerTests` that the email is saved with the token and is absent from the synced account, and that a token saved without it still decodes. + +## 6. Views + +- [x] 6.1 Build `HostedIssueListView`: filter bar, remote picker shown only with more than one tracker, rows, infinite scroll, and empty, filtered-empty, disabled-tracker, missing-scope, org-access, rate-limited, and error states, with Retry. Verify that the build succeeds. +- [x] 6.2 Build `HostedIssueDetailView`: metadata, Markdown body through `PullRequestMarkdownContent`, Azure plain-text body, comments, the comment composer, Close/Reopen, open in browser, copy number, copy reference, and the create-branch menu (plain branch and Git Flow targets). Verify that the build succeeds. +- [x] 6.3 Build `NewHostedIssueSheet`: required title, Markdown description, and an Azure type picker; Create disabled while blank or in flight. Verify that the build succeeds. + +## 7. Integration checks + +- [x] 7.1 Run `xcodebuild … -only-testing:macgitTests/GitHubIssueServiceTests -only-testing:macgitTests/GitLabIssueServiceTests -only-testing:macgitTests/BitbucketIssueServiceTests -only-testing:macgitTests/AzureBoardsWorkItemServiceTests -only-testing:macgitTests/HostedIssueControllerTests -only-testing:macgitTests/HostedIssueModelsTests -only-testing:macgitTests/IssueBranchNameSuggesterTests -only-testing:macgitTests/PullRequestControllerTests -only-testing:macgitTests/FeatureAccessPolicyTests -only-testing:macgitTests/FeatureAccessNoticeTests -only-testing:macgitTests/RepositoryVisibilityControllerTests -only-testing:macgitTests/SidebarNativeListTests -only-testing:macgitTests/SidebarViewStashTests -only-testing:macgitTests/JiraIssueListControllerTests test` and confirm that all tests pass. +- [ ] 7.2 Manual UI review in the running app: + - the ISSUES section with Jira and a hosted row for a GitHub, a GitLab, a Bitbucket, and an Azure repository + - collapse and Show Issues + - the remote picker on a fork + - list and detail layout at narrow and wide window sizes + - create, comment, close and reopen on a test repository + - a missing-scope message for a Bitbucket token without issue scopes and an Azure PAT without Work Items + - Free-plan gating on a private repository + + Record anything not checked. +- [x] 7.3 Update the `add-jira-sprint-issues` delta so its Workspace placement requirement defers to `repository-issues-section`, and run `openspec validate add-jira-sprint-issues` and `openspec validate add-hosted-issue-trackers`. +- [x] 7.4 Run `git diff --check` and confirm there is no output. + +## 8. Cross-repository rollout (`../landing-page`) + +- [ ] 8.1 Add `hostedIssues` to `admin/lib/schemas.ts` and to the next revision of `scripts/firebase/set-feature-policy.mjs`, with the same rule as `pullRequests`. Verify that the repository's own build and type check pass, per its `AGENTS.md`, without running emulator tests. +- [ ] 8.2 Publish the updated feature policy to production only after explicit user authorization. Verify CLI success for the intended project, and report separately what is local, committed, pushed, and published. + +## Workflow follow-up + +- Archive this change with `/opsx:archive` after implementation and validation, after `add-jira-sprint-issues` has been reconciled. diff --git a/openspec/changes/add-jira-sprint-issues/proposal.md b/openspec/changes/add-jira-sprint-issues/proposal.md index 0d4a457e..a7967e32 100644 --- a/openspec/changes/add-jira-sprint-issues/proposal.md +++ b/openspec/changes/add-jira-sprint-issues/proposal.md @@ -7,7 +7,7 @@ Developers using Commit+ track their sprint work in Jira and switch to the brows ## What Changes - Add a Jira Cloud connection in Settings → Integrations using the user's site URL, Atlassian account email, and an Atlassian API token. This mirrors the existing Bitbucket connection, which also uses an Atlassian API token (it is not OAuth). A Bitbucket token cannot be reused: Jira needs its own token with Jira access. The connection is stored on this Mac only (metadata locally, token in the Keychain) and is not synced through Firebase. -- Add a "Jira" item to the sidebar Workspace section, which the user can hide from "Customize Workspace" like Reflog, Pull Requests, and Git LFS. +- Add a "Jira" item to the sidebar. It now lives in the ISSUES section, whose single "Show Issues" setting is defined by `add-hosted-issue-trackers` (`repository-issues-section`). - Selecting it opens a Jira issues screen: a flat list (no board) of issues assigned to the connected user, defaulting to issues in open sprints that are not done. - Filters: sprint (open sprints, a specific sprint, backlog, or any), status category, project, issue type, and text search on key or summary. The filter is remembered per repository. - Issue actions: open in Jira, copy key, copy key and summary, and create a branch from the issue. Branch creation prefills a name from the issue key and summary and uses the existing Git Flow start sheet when Git Flow is configured, otherwise the existing branch sheet. Nothing is written to Jira. @@ -18,7 +18,7 @@ Developers using Commit+ track their sprint work in Jira and switch to the brows ### New Capabilities - `jira-account-connection`: Connecting, validating, reconnecting, and removing a Jira Cloud site with an Atlassian API token in Settings → Integrations, and keeping the credential local to this Mac. -- `jira-issue-list`: The Pro-gated Jira item in the sidebar Workspace section and its issue list screen: which issues are shown, filtering, loading/error/empty states, and per-issue actions including creating a branch from an issue. +- `jira-issue-list`: The Pro-gated Jira item in the sidebar ISSUES section and its issue list screen: which issues are shown, filtering, loading/error/empty states, and per-issue actions including creating a branch from an issue. ### Modified Capabilities diff --git a/openspec/changes/add-jira-sprint-issues/specs/jira-issue-list/spec.md b/openspec/changes/add-jira-sprint-issues/specs/jira-issue-list/spec.md index 70c14e9e..62741b60 100644 --- a/openspec/changes/add-jira-sprint-issues/specs/jira-issue-list/spec.md +++ b/openspec/changes/add-jira-sprint-issues/specs/jira-issue-list/spec.md @@ -2,23 +2,19 @@ ## Purpose -Defines the Pro-gated Jira item in the repository sidebar's Workspace section and its issue list screen, which shows the connected user's own Jira issues as a filterable flat list and lets them start a branch from an issue. +Defines the Pro-gated Jira item in the repository sidebar's ISSUES section and its issue list screen, which shows the connected user's own Jira issues as a filterable flat list and lets them start a branch from an issue. ## ADDED Requirements -### Requirement: Jira appears in the sidebar Workspace section -The repository sidebar's Workspace section SHALL include a "Jira" item, shown by default. "Customize Workspace" SHALL include a "Jira" toggle that hides or shows it, and the choice SHALL persist across launches like the other Workspace toggles. +### Requirement: Jira appears in the sidebar ISSUES section +The repository sidebar SHALL list a "Jira" item first in the ISSUES section. Its visibility follows the single "Show Issues" setting, and selection falls back to File status when it disappears. Both are defined by the `repository-issues-section` capability. Jira SHALL NOT appear in the Workspace section. #### Scenario: Default visibility -- **WHEN** the user opens a repository window for the first time after updating -- **THEN** the Workspace section lists "Jira" +- **WHEN** the user opens a repository window with Show Issues on +- **THEN** the ISSUES section lists "Jira" and the Workspace section does not -#### Scenario: Hide Jira -- **WHEN** the user turns off "Jira" in "Customize Workspace" -- **THEN** the Jira item disappears from the Workspace section in every repository window and stays hidden after relaunch - -#### Scenario: Hidden while selected -- **WHEN** the user hides Jira while the Jira screen is selected +#### Scenario: Hidden with the section +- **WHEN** the user turns off Show Issues while the Jira screen is selected - **THEN** the window selects File status ### Requirement: The Jira issues screen requires Commit+ Pro