diff --git a/MobileChat/GlobalChatScreen.swift b/MobileChat/GlobalChatScreen.swift index 83f3c12c..79c00c36 100644 --- a/MobileChat/GlobalChatScreen.swift +++ b/MobileChat/GlobalChatScreen.swift @@ -332,6 +332,7 @@ struct GlobalChatScreen: View { else { Text(verbatim: provider.title) } } .disabled(!snapshot.provider.canSelect(provider, ownerChoice: snapshot.providerChoice)) + .accessibilityAddTraits(snapshot.provider == provider ? .isSelected : []) } } diff --git a/Sources/GitMetadataProber.swift b/Sources/GitMetadataProber.swift index 5070c10a..753c75bb 100644 --- a/Sources/GitMetadataProber.swift +++ b/Sources/GitMetadataProber.swift @@ -736,6 +736,7 @@ struct GitMetadataProber { let branch: String? let isDirty: Bool let pullRequest: WorkspacePullRequestSnapshot + var pullRequestProbedAt: ContinuousClock.Instant? = nil } struct GitHubPullRequestProbeItem: Decodable, Equatable { @@ -745,6 +746,7 @@ struct GitMetadataProber { let updatedAt: String? var headRefOid: String? = nil var isCrossRepository: Bool? = nil + var isDraft: Bool? = nil } private struct GitHubPullRequestCheckItem: Decodable { @@ -766,6 +768,8 @@ struct GitMetadataProber { private nonisolated static let pullRequestLookupInitialBackoff: TimeInterval = 5 private nonisolated static let pullRequestLookupCacheLimit = 256 + private typealias PullRequestLookup = (snapshot: WorkspacePullRequestSnapshot, probedAt: ContinuousClock.Instant?) + /// Wait before retrying `gh` after `failures` consecutive transient failures: /// 5 s, 10 s, 20 s, ... capped at 10 minutes. Starts short so the startup retry burst /// (TabManager's initial probe delays) can still recover from one slow first call. @@ -778,7 +782,7 @@ struct GitMetadataProber { private final class PullRequestLookupThrottle: @unchecked Sendable { struct Entry { let branch: String - var snapshot: WorkspacePullRequestSnapshot + let lookup: PullRequestLookup var lastAttemptAt: Date var consecutiveFailures: Int } @@ -787,18 +791,18 @@ struct GitMetadataProber { private var entries: [String: Entry] = [:] /// The cached answer when a fresh `gh` lookup is not due yet, else nil. - func cachedSnapshot(directory: String, branch: String, now: Date) -> WorkspacePullRequestSnapshot? { + func cachedLookup(directory: String, branch: String, now: Date) -> PullRequestLookup? { lock.lock() defer { lock.unlock() } guard let entry = entries[directory], entry.branch == branch else { return nil } let wait = entry.consecutiveFailures > 0 ? GitMetadataProber.pullRequestLookupBackoff(failures: entry.consecutiveFailures) : GitMetadataProber.pullRequestLookupRefreshInterval - return now.timeIntervalSince(entry.lastAttemptAt) < wait ? entry.snapshot : nil + return now.timeIntervalSince(entry.lastAttemptAt) < wait ? entry.lookup : nil } func record( - _ snapshot: WorkspacePullRequestSnapshot, + _ lookup: PullRequestLookup, directory: String, branch: String, now: Date, @@ -807,20 +811,16 @@ struct GitMetadataProber { lock.lock() defer { lock.unlock() } let previous = entries[directory].flatMap { $0.branch == branch ? $0 : nil } - if case .transientFailure = snapshot { + if case .transientFailure = lookup.snapshot { // Keep showing the last good answer during the backoff. - let lastGood = previous.map(\.snapshot).flatMap { cached -> WorkspacePullRequestSnapshot? in - if case .transientFailure = cached { return nil } - return cached - } entries[directory] = Entry( branch: branch, - snapshot: lastGood ?? .transientFailure, + lookup: previous?.lookup ?? lookup, lastAttemptAt: now, consecutiveFailures: (previous?.consecutiveFailures ?? 0) + 1 ) } else { - entries[directory] = Entry(branch: branch, snapshot: snapshot, lastAttemptAt: now, consecutiveFailures: 0) + entries[directory] = Entry(branch: branch, lookup: lookup, lastAttemptAt: now, consecutiveFailures: 0) } if entries.count > limit, let oldest = entries.min(by: { $0.value.lastAttemptAt < $1.value.lastAttemptAt })?.key { @@ -862,7 +862,9 @@ struct GitMetadataProber { ) let isDirty = !(statusOutput?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true) let pullRequest = workspacePullRequestSnapshot(directory: directory, branch: branch) - return InitialWorkspaceGitMetadataSnapshot(branch: branch, isDirty: isDirty, pullRequest: pullRequest) + return InitialWorkspaceGitMetadataSnapshot( + branch: branch, isDirty: isDirty, pullRequest: pullRequest.snapshot, pullRequestProbedAt: pullRequest.probedAt + ) } private nonisolated static func runGitCommand(directory: String, arguments: [String]) -> String? { @@ -877,24 +879,26 @@ struct GitMetadataProber { private nonisolated static func workspacePullRequestSnapshot( directory: String, branch: String - ) -> WorkspacePullRequestSnapshot { + ) -> PullRequestLookup { guard !shouldSkipWorkspacePullRequestLookup(branch: branch) else { - return .notFound + return (.notFound, nil) } let now = Date() - if let cached = pullRequestLookupThrottle.cachedSnapshot(directory: directory, branch: branch, now: now) { + if let cached = pullRequestLookupThrottle.cachedLookup(directory: directory, branch: branch, now: now) { return cached } + let probedAt = ContinuousClock.now let snapshot = uncachedWorkspacePullRequestSnapshot(directory: directory, branch: branch) + let lookup: PullRequestLookup = (snapshot, probedAt) pullRequestLookupThrottle.record( - snapshot, + lookup, directory: directory, branch: branch, now: now, limit: pullRequestLookupCacheLimit ) - return snapshot + return lookup } private nonisolated static func uncachedWorkspacePullRequestSnapshot( @@ -934,7 +938,7 @@ struct GitMetadataProber { "--repo", repoSlug, "--state", "all", "--head", branch, - "--json", "number,state,url,updatedAt,headRefOid,isCrossRepository", + "--json", "number,state,url,updatedAt,headRefOid,isCrossRepository,isDraft", ], timeout: workspacePullRequestProbeTimeout ) @@ -1020,16 +1024,18 @@ struct GitMetadataProber { status: status, branch: branch, checks: checks, - headSHA: shippableHead(pullRequest, directory: directory), + headSHA: shippableHead(pullRequest, checkedOut: checkedOutCommit(directory: directory)), source: .probe(repoSlug: repoSlug, directory: directory) ) ) } - enum ShipVerdict: Sendable { + enum ShipVerdict: Equatable, Sendable { case ready - /// No longer open, or its head or the checkout moved off the commit. - case changed + case merged + case closed + case temporarilyUnavailable + case headMoved case checksNotPassing /// `gh` or `git` gave no usable answer. case unverified @@ -1044,7 +1050,9 @@ struct GitMetadataProber { /// failing; and whether `directory` still has that commit checked out. Blocks; call off-main. nonisolated static func shipVerdict(number: Int, repoSlug: String, directory: String, headSHA: String) -> ShipVerdict { guard let checkedOut = checkedOutCommit(directory: directory) else { return .unverified } - guard checkedOut == headSHA else { return .changed } + guard checkedOut == headSHA else { + return classifyShip(headSHA: headSHA, checkedOut: checkedOut, pullRequestHead: nil, readiness: nil) + } let result = runCommandResult( directory: directory, executable: "gh", @@ -1056,7 +1064,21 @@ struct GitMetadataProber { let readiness = ReviewMergeReadinessProber.parse(pullRequestJSON: output, reviewThreadsJSON: nil) else { return .unverified } - guard readiness.state == .open, head.headRefOid == headSHA else { return .changed } + return classifyShip(headSHA: headSHA, checkedOut: checkedOut, pullRequestHead: head.headRefOid, readiness: readiness) + } + + nonisolated static func classifyShip( + headSHA: String, checkedOut: String, pullRequestHead: String?, readiness: ReviewMergeReadiness? + ) -> ShipVerdict { + guard checkedOut == headSHA else { return .temporarilyUnavailable } + guard let readiness else { return .unverified } + switch readiness.state { + case .merged: return .merged + case .closed: return .closed + case .open, .draft: break + } + guard pullRequestHead == headSHA else { return .headMoved } + guard readiness.state == .open else { return .temporarilyUnavailable } guard readiness.failingCheckNames.isEmpty, readiness.pendingCheckCount == 0, readiness.passingCheckCount > 0 else { return .checksNotPassing } @@ -1066,9 +1088,9 @@ struct GitMetadataProber { /// The head commit Ship may pin, or nil. `--head` matches the branch name in every fork, so a /// cross-repository pull request (or one whose origin `gh` did not report) is never shippable, /// though the sidebar still shows it; nor is one whose head is not the checked-out commit. - private nonisolated static func shippableHead(_ pullRequest: GitHubPullRequestProbeItem, directory: String) -> String? { - guard pullRequest.isCrossRepository == false, let head = pullRequest.headRefOid, - head == checkedOutCommit(directory: directory) else { return nil } + nonisolated static func shippableHead(_ pullRequest: GitHubPullRequestProbeItem, checkedOut: @autoclosure () -> String?) -> String? { + guard pullRequest.isDraft != true, pullRequest.isCrossRepository == false, + let head = pullRequest.headRefOid, head == checkedOut() else { return nil } return head } diff --git a/Sources/GlobalChatCards.swift b/Sources/GlobalChatCards.swift index 0051abdb..1cd26026 100644 --- a/Sources/GlobalChatCards.swift +++ b/Sources/GlobalChatCards.swift @@ -32,10 +32,11 @@ final class GlobalChatCards { /// only after the probe has seen them not passing too, and then passing. A press that found the /// pull request at another commit keeps the old commit from being offered while the probe still /// shows it. - enum ShipRecheck { + enum ShipRecheck: Equatable { case awaitingProbe case probeSawChecksFail case headMoved + case temporarilyUnavailable(since: ContinuousClock.Instant) } private struct Terminal: Hashable { @@ -57,7 +58,6 @@ final class GlobalChatCards { /// The `owner/name` a Ship card was offered for. Its pull request is checked, merged and /// looked up only there. var repoSlug: String? - /// Set when the card failed with `.checksNotPassing`. var recheck: ShipRecheck? } @@ -182,8 +182,9 @@ final class GlobalChatCards { if let recheck = outcome.recheck, let index = entries.firstIndex(where: { $0.card.id == card.id }) { entries[index].recheck = recheck } - } else if entry.recheck == .headMoved, let repoSlug = entry.repoSlug, - Self.endsHeadMovedRefresh(status: workspaces.pullRequest(workspaceID: ship.workspaceID, repoSlug: repoSlug, number: ship.number)?.status), + } else if card.state == .superseded, Self.wantsShipRefresh(state: card.state, recheck: entry.recheck), + let repoSlug = entry.repoSlug, + Self.endsShipRefresh(status: workspaces.pullRequest(workspaceID: ship.workspaceID, repoSlug: repoSlug, number: ship.number)?.status), let index = entries.firstIndex(where: { $0.card.id == card.id }) { entries[index].recheck = nil } @@ -225,8 +226,13 @@ final class GlobalChatCards { /// terminal moved on, because GitHub could not be asked, or on checks the probe has since seen /// fail, does not. One GitHub found at another commit does, since the probe may still show the /// old commit until its next lookup. - nonisolated static func holdsShipOffer(state: GlobalChatCardState, recheck: ShipRecheck?) -> Bool { - (state != .superseded || recheck == .headMoved) && state != .failed(.unverified) && recheck != .probeSawChecksFail + nonisolated static func holdsShipOffer( + state: GlobalChatCardState, recheck: ShipRecheck?, probedAt: ContinuousClock.Instant? = nil + ) -> Bool { + if case let .temporarilyUnavailable(since: press) = recheck { + return probedAt.map { $0 <= press } ?? true + } + return (state != .superseded || recheck == .headMoved) && state != .failed(.unverified) && recheck != .probeSawChecksFail } /// Whether a Ship card keeps its terminal's pull request state refreshed while the app is in the @@ -235,7 +241,11 @@ final class GlobalChatCards { nonisolated static func wantsShipRefresh(state: GlobalChatCardState, recheck: ShipRecheck?) -> Bool { switch state { case .pending, .answered: true - case .superseded: recheck == .headMoved + case .superseded: + switch recheck { + case .headMoved, .temporarilyUnavailable: true + default: false + } case .replaced, .closed, .shipped, .dismissed, .failed: false } } @@ -248,24 +258,32 @@ final class GlobalChatCards { state.isPending ? (.superseded, .headMoved) : nil } - /// Whether a Ship card GitHub found at another commit stops keeping its terminal refreshed, - /// given the pull request's status as last probed. A missing status is a probe that has not - /// answered, not an end. - nonisolated static func endsHeadMovedRefresh(status: SidebarPullRequestStatus?) -> Bool { + nonisolated static func endsShipRefresh(status: SidebarPullRequestStatus?) -> Bool { status == .merged || status == .closed } /// Asks each terminal behind a Ship card still waiting on its pull request to re-probe it, which the sidebar's - /// polls do not do while the app is in the background. + /// polls do not do while the app is in the background. A card that GitHub found temporarily unavailable + /// holds the offer for every terminal showing that commit, so those terminals are asked too: otherwise + /// closing the card's own terminal would leave the others' older probes holding it. private func refreshOpenShipTerminals() { let now = ContinuousClock.now lastShipRefreshes = lastShipRefreshes.filter { now - $0.value < Self.shipRefreshInterval } for entry in entries where Self.wantsShipRefresh(state: entry.card.state, recheck: entry.recheck) { guard case let .ship(ship) = entry.card.content else { continue } - let terminal = Terminal(workspaceID: ship.workspaceID, surfaceID: ship.surfaceID) - guard Self.isShipRefreshDue(lastRequest: lastShipRefreshes[terminal], now: now), - workspaces.refreshPullRequest(workspaceID: ship.workspaceID, surfaceID: ship.surfaceID) else { continue } - lastShipRefreshes[terminal] = now + var surfaceIDs = [ship.surfaceID] + if case .temporarilyUnavailable = entry.recheck { + surfaceIDs += workspaces.shipCandidates(workspaceID: ship.workspaceID).compactMap { candidate in + candidate.binding.repoSlug == entry.repoSlug && candidate.binding.number == ship.number + && candidate.binding.headSHA == ship.headSHA && candidate.surfaceID != ship.surfaceID ? candidate.surfaceID : nil + } + } + for surfaceID in surfaceIDs { + let terminal = Terminal(workspaceID: ship.workspaceID, surfaceID: surfaceID) + guard Self.isShipRefreshDue(lastRequest: lastShipRefreshes[terminal], now: now), + workspaces.refreshPullRequest(workspaceID: ship.workspaceID, surfaceID: surfaceID) else { continue } + lastShipRefreshes[terminal] = now + } } } @@ -287,15 +305,19 @@ final class GlobalChatCards { default: return nil } guard visible, let repoSlug = entry.repoSlug else { return (.superseded, nil) } + let canSupersede = state.isPending && !shipsInFlight.contains(entry.card.id) guard let pullRequest = workspaces.pullRequest(workspaceID: ship.workspaceID, repoSlug: repoSlug, number: ship.number) else { - return state.isPending ? (.superseded, nil) : nil + return canSupersede ? (.superseded, nil) : nil } switch pullRequest.status { case .merged: return (.shipped, nil) case .closed: return (.closed, nil) case .open: - if pullRequest.headSHA != ship.headSHA { return Self.settleOnMovedHead(state: state) } - return state.isPending && binding(for: entry, ship: ship) == nil ? (.superseded, nil) : nil + guard let probedHead = pullRequest.headSHA else { + return canSupersede ? (.superseded, .temporarilyUnavailable(since: .now)) : nil + } + if probedHead != ship.headSHA { return Self.settleOnMovedHead(state: state) } + return canSupersede && binding(for: entry, ship: ship) == nil ? (.superseded, nil) : nil } } @@ -310,10 +332,10 @@ final class GlobalChatCards { /// Offered only for a terminal that reported the pull request, and only while an agent runs there. private func offerShip(in workspace: GlobalChatWorkspace) { - for (surfaceID, binding) in workspaces.shipCandidates(workspaceID: workspace.id) { + for (surfaceID, binding, probedAt) in workspaces.shipCandidates(workspaceID: workspace.id) { let offered = entries.contains { entry in guard case let .ship(ship) = entry.card.content, - Self.holdsShipOffer(state: entry.card.state, recheck: entry.recheck) else { return false } + Self.holdsShipOffer(state: entry.card.state, recheck: entry.recheck, probedAt: probedAt) else { return false } return ship.workspaceID == workspace.id && entry.repoSlug == binding.repoSlug && ship.number == binding.number && ship.headSHA == binding.headSHA } @@ -352,19 +374,29 @@ final class GlobalChatCards { let verdict = await Task.detached(priority: .userInitiated) { GitMetadataProber.shipVerdict(number: number, repoSlug: repoSlug, directory: directory, headSHA: headSHA) }.value + // Only a probe that starts after GitHub answered can be newer than this answer. + let answeredAt = ContinuousClock.now guard await isAuthorized() else { return .stale } // Nothing awaits from here to the keystrokes. The card or the terminal may have moved while // GitHub answered. guard let current = entries.first(where: { $0.card.id == id }), current.card.state.isPending else { return .stale } - guard self.binding(for: current, ship: ship) == binding else { + guard verdict == .temporarilyUnavailable || verdict == .headMoved || self.binding(for: current, ship: ship) == binding else { + // A probe during the press may have seen a draft or another checkout, which reconcile + // leaves to the press. Hold the offer until a later probe, and keep it refreshed. settle(id, as: .superseded) + if let index = entries.firstIndex(where: { $0.card.id == id }) { + entries[index].recheck = .temporarilyUnavailable(since: answeredAt) + } + workspaces.refreshPullRequest(workspaceID: ship.workspaceID, surfaceID: ship.surfaceID) return .settled } switch verdict { case .ready: break - case .changed: + case .merged, .closed, .temporarilyUnavailable, .headMoved: settle(id, as: .superseded) - if let index = entries.firstIndex(where: { $0.card.id == id }) { entries[index].recheck = .headMoved } + if let index = entries.firstIndex(where: { $0.card.id == id }) { + entries[index].recheck = verdict == .temporarilyUnavailable ? .temporarilyUnavailable(since: answeredAt) : .headMoved + } workspaces.refreshPullRequest(workspaceID: ship.workspaceID, surfaceID: ship.surfaceID) return .settled case .checksNotPassing: diff --git a/Sources/GlobalWorkspaceAccess.swift b/Sources/GlobalWorkspaceAccess.swift index 105d63da..212a2541 100644 --- a/Sources/GlobalWorkspaceAccess.swift +++ b/Sources/GlobalWorkspaceAccess.swift @@ -52,6 +52,7 @@ final class GlobalWorkspaceAccess { private var prompts: [Target: Prompt] = [:] private var hookSessions: [Target: AgentSessionKey] = [:] private var leases: [UUID: Lease] = [:] + private var shipProbeTimes: [Target: ContinuousClock.Instant] = [:] private init() {} @@ -342,7 +343,7 @@ final class GlobalWorkspaceAccess { /// Each open, passing pull request in sidebar order with the first terminal that could ship it. /// One no terminal can ship, such as a fork's or one in a pane with no agent, is left out rather /// than hiding the rest. - func shipCandidates(workspaceID: UUID) -> [(surfaceID: UUID, binding: ShipBinding)] { + func shipCandidates(workspaceID: UUID) -> [(surfaceID: UUID, binding: ShipBinding, probedAt: ContinuousClock.Instant?)] { guard let workspace = AppDelegate.shared?.workspaceFor(tabId: workspaceID), !workspace.isWorktreeFolder, !isPrivate(workspace) else { return [] } let panels = TerminalController.shared.orderedPanels(in: workspace).map(\.id) @@ -350,13 +351,18 @@ final class GlobalWorkspaceAccess { guard pullRequest.status == .open, pullRequest.checks == .pass else { return nil } for surfaceID in panels where workspace.panelPullRequests[surfaceID] == pullRequest { if let binding = shipBinding(workspaceID: workspaceID, surfaceID: surfaceID), binding.isReady { - return (surfaceID, binding) + let target = Target(workspaceID: workspaceID, surfaceID: surfaceID) + return (surfaceID, binding, shipProbeTimes[target]) } } return nil } } + func noteShipProbe(workspaceID: UUID, surfaceID: UUID, probedAt: ContinuousClock.Instant?) { + shipProbeTimes[Target(workspaceID: workspaceID, surfaceID: surfaceID)] = probedAt + } + /// `owner/name` as `^[A-Za-z0-9-]+/[A-Za-z0-9._-]+$`, since Ship types it after `--repo`. private static func isRepositorySlug(_ slug: String) -> Bool { let parts = slug.split(separator: "/", omittingEmptySubsequences: false) diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 657accdf..c0fbaabf 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -927,6 +927,9 @@ class TabManager: ObservableObject { switch snapshot.pullRequest { case .resolved(let pullRequest): + GlobalWorkspaceAccess.shared.noteShipProbe( + workspaceID: probeKey.workspaceId, surfaceID: probeKey.panelId, probedAt: snapshot.pullRequestProbedAt + ) workspace.updatePanelPullRequest( panelId: probeKey.panelId, number: pullRequest.number, @@ -938,6 +941,7 @@ class TabManager: ObservableObject { source: pullRequest.source ) case .notFound: + GlobalWorkspaceAccess.shared.noteShipProbe(workspaceID: probeKey.workspaceId, surfaceID: probeKey.panelId, probedAt: nil) if workspace.panelPullRequests[probeKey.panelId] != nil { workspace.clearPanelPullRequest(panelId: probeKey.panelId) } diff --git a/Sources/Workspace+Bonsplit.swift b/Sources/Workspace+Bonsplit.swift index 76da868e..7d15046b 100644 --- a/Sources/Workspace+Bonsplit.swift +++ b/Sources/Workspace+Bonsplit.swift @@ -717,6 +717,7 @@ extension Workspace: @preconcurrency BonsplitDelegate { resolvedPanelDirectories.removeValue(forKey: panelId) panelGitBranches.removeValue(forKey: panelId) panelPullRequests.removeValue(forKey: panelId) + GlobalWorkspaceAccess.shared.noteShipProbe(workspaceID: id, surfaceID: panelId, probedAt: nil) reviewTurns.removeValue(forKey: panelId) panelTitles.removeValue(forKey: panelId) panelsHoldingRestoredTitle.remove(panelId) diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index f332f05f..670daf2b 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -1187,6 +1187,7 @@ final class Workspace: Identifiable, ObservableObject { let panelEntries = Array(panels) for (panelId, panel) in panelEntries { panelSubscriptions.removeValue(forKey: panelId) + GlobalWorkspaceAccess.shared.noteShipProbe(workspaceID: id, surfaceID: panelId, probedAt: nil) PortsHubStore.shared.panelClosed(workspaceId: id, panelId: panelId) PortScanner.shared.unregisterPanel(workspaceId: id, panelId: panelId) panel.close() diff --git a/programaTests/GlobalChatDispatchTests.swift b/programaTests/GlobalChatDispatchTests.swift index b44ccdd5..7b3cca00 100644 --- a/programaTests/GlobalChatDispatchTests.swift +++ b/programaTests/GlobalChatDispatchTests.swift @@ -743,10 +743,10 @@ final class GlobalChatDispatchTests: XCTestCase { @MainActor func testAMovedShipCardStopsRefreshingOnceItsPullRequestEnds() { - XCTAssertTrue(GlobalChatCards.endsHeadMovedRefresh(status: .merged)) - XCTAssertTrue(GlobalChatCards.endsHeadMovedRefresh(status: .closed)) - XCTAssertFalse(GlobalChatCards.endsHeadMovedRefresh(status: .open)) - XCTAssertFalse(GlobalChatCards.endsHeadMovedRefresh(status: nil), "a probe that has not answered yet is not an end") + XCTAssertTrue(GlobalChatCards.endsShipRefresh(status: .merged)) + XCTAssertTrue(GlobalChatCards.endsShipRefresh(status: .closed)) + XCTAssertFalse(GlobalChatCards.endsShipRefresh(status: .open)) + XCTAssertFalse(GlobalChatCards.endsShipRefresh(status: nil), "a probe that has not answered yet is not an end") } private let shipWorkspace = UUID() @@ -814,4 +814,56 @@ final class GlobalChatDispatchTests: XCTestCase { XCTAssertTrue(GlobalChatCards.holdsShipOffer(state: .failed(.checksNotPassing), recheck: .awaitingProbe)) XCTAssertTrue(GlobalChatCards.holdsShipOffer(state: .pending, recheck: nil)) } + + func testShipPressDistinguishesDraftCheckoutMismatchAndMovedHead() throws { + let open = try shipReadiness(state: "OPEN") + let draft = try shipReadiness(state: "OPEN", isDraft: true) + XCTAssertEqual(GitMetadataProber.classifyShip(headSHA: "a", checkedOut: "a", pullRequestHead: "a", readiness: draft), .temporarilyUnavailable) + XCTAssertEqual(GitMetadataProber.classifyShip(headSHA: "a", checkedOut: "b", pullRequestHead: nil, readiness: nil), .temporarilyUnavailable) + XCTAssertEqual(GitMetadataProber.classifyShip(headSHA: "a", checkedOut: "a", pullRequestHead: "b", readiness: open), .headMoved) + XCTAssertEqual(GitMetadataProber.classifyShip(headSHA: "a", checkedOut: "a", pullRequestHead: "b", readiness: draft), .headMoved) + XCTAssertEqual(GitMetadataProber.classifyShip(headSHA: "a", checkedOut: "a", pullRequestHead: "a", readiness: open), .ready) + } + + func testShipPressDistinguishesMergedClosedAndChecksNotPassing() throws { + let merged = try shipReadiness(state: "MERGED") + let closed = try shipReadiness(state: "CLOSED") + let pending = try shipReadiness(state: "OPEN", check: #"{"status":"IN_PROGRESS"}"#) + XCTAssertEqual(GitMetadataProber.classifyShip(headSHA: "a", checkedOut: "a", pullRequestHead: "a", readiness: merged), .merged) + XCTAssertEqual(GitMetadataProber.classifyShip(headSHA: "a", checkedOut: "a", pullRequestHead: "a", readiness: closed), .closed) + XCTAssertEqual(GitMetadataProber.classifyShip(headSHA: "a", checkedOut: "a", pullRequestHead: "a", readiness: pending), .checksNotPassing) + XCTAssertEqual(GitMetadataProber.classifyShip(headSHA: "a", checkedOut: "a", pullRequestHead: nil, readiness: nil), .unverified) + } + + func testOnlyAReadyPullRequestAtTheCheckoutIsEligibleForAnOffer() { + var pullRequest = GitMetadataProber.GitHubPullRequestProbeItem( + number: 102, state: "OPEN", url: "https://github.com/acme/api/pull/102", updatedAt: nil, + headRefOid: "a", isCrossRepository: false, isDraft: true + ) + XCTAssertNil(GitMetadataProber.shippableHead(pullRequest, checkedOut: "a")) + pullRequest.isDraft = false + XCTAssertNil(GitMetadataProber.shippableHead(pullRequest, checkedOut: "b")) + XCTAssertEqual(GitMetadataProber.shippableHead(pullRequest, checkedOut: "a"), "a") + } + + func testTemporarilyUnavailableShipOfferWaitsForANewerProbe() { + let press = ContinuousClock.now + let recheck = GlobalChatCards.ShipRecheck.temporarilyUnavailable(since: press) + XCTAssertTrue(GlobalChatCards.holdsShipOffer(state: .superseded, recheck: recheck)) + XCTAssertTrue(GlobalChatCards.holdsShipOffer(state: .superseded, recheck: recheck, probedAt: press - .seconds(1))) + XCTAssertTrue(GlobalChatCards.holdsShipOffer(state: .superseded, recheck: recheck, probedAt: press)) + XCTAssertFalse(GlobalChatCards.holdsShipOffer(state: .superseded, recheck: recheck, probedAt: press + .seconds(1))) + XCTAssertTrue(GlobalChatCards.wantsShipRefresh(state: .superseded, recheck: recheck)) + XCTAssertTrue(GlobalChatCards.holdsShipOffer(state: .superseded, recheck: .headMoved, probedAt: press + .seconds(1))) + XCTAssertTrue(GlobalChatCards.holdsShipOffer(state: .dismissed, recheck: nil, probedAt: press + .seconds(1))) + } + + private func shipReadiness( + state: String, isDraft: Bool = false, check: String = #"{"status":"COMPLETED","conclusion":"SUCCESS"}"# + ) throws -> ReviewMergeReadiness { + let json = """ + {"state":"\(state)","isDraft":\(isDraft),"statusCheckRollup":[\(check)]} + """ + return try XCTUnwrap(ReviewMergeReadinessProber.parse(pullRequestJSON: json, reviewThreadsJSON: nil)) + } }