From 9794e94e449a279f9700efd59587706f2bc2f67a Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Wed, 9 Sep 2026 16:17:15 +0530 Subject: [PATCH 1/4] fix(mac): preserve explicit Copilot disconnect across refreshes --- mac/Sources/CodeBurnMenubar/AppStore.swift | 52 ++++- .../Data/CopilotExplicitDisconnect.swift | 39 ++++ .../Views/HeatmapSection.swift | 4 +- .../CodeBurnMenubar/Views/SettingsView.swift | 8 +- .../AppStoreCopilotDisconnectTests.swift | 207 ++++++++++++++++++ 5 files changed, 297 insertions(+), 13 deletions(-) create mode 100644 mac/Sources/CodeBurnMenubar/Data/CopilotExplicitDisconnect.swift create mode 100644 mac/Tests/CodeBurnMenubarTests/AppStoreCopilotDisconnectTests.swift diff --git a/mac/Sources/CodeBurnMenubar/AppStore.swift b/mac/Sources/CodeBurnMenubar/AppStore.swift index db1d527d..9b8134ec 100644 --- a/mac/Sources/CodeBurnMenubar/AppStore.swift +++ b/mac/Sources/CodeBurnMenubar/AppStore.swift @@ -166,8 +166,9 @@ final class AppStore { var copilotError: String? // Same file-based activation as Kimi/Gemini — reading // Copilot discovery never raises a keychain prompt, so we start dormant and - // auto-activate on the first refresh tick. - var copilotLoadState: SubscriptionLoadState = CopilotSubscriptionService.hasCredential ? .dormant : .notBootstrapped + // auto-activate on the first refresh tick unless the user explicitly + // disconnected. That opt-out is persisted and applied in `init`. + var copilotLoadState: SubscriptionLoadState = .notBootstrapped var antigravityUsage: AntigravityUsage? var antigravityError: String? @@ -201,6 +202,19 @@ final class AppStore { (CapacityDockProvider) -> Void = { CapacityDockPreferences.removeProvider($0) } + @ObservationIgnored var copilotQuotaRuntime: CopilotQuotaRuntime + + init(copilotQuotaRuntime: CopilotQuotaRuntime = .live) { + self.copilotQuotaRuntime = copilotQuotaRuntime + copilotLoadState = Self.initialCopilotLoadState(runtime: copilotQuotaRuntime) + } + + private static func initialCopilotLoadState(runtime: CopilotQuotaRuntime) -> SubscriptionLoadState { + if CopilotExplicitDisconnect.isSet(defaults: runtime.defaults) { + return .notBootstrapped + } + return runtime.hasCredential() ? .dormant : .notBootstrapped + } /// Generation tokens for the in-flight refresh tasks. Incremented on every /// disconnect / reset so a fetch that started before the disconnect cannot @@ -1708,56 +1722,79 @@ final class AppStore { /// Same prompt-free activation as Kimi/Gemini: the whole Copilot discovery /// chain is prompt-free, so the first refresh tick activates dormant state. + /// Automatic cadence must not clear an explicit disconnect; that happens + /// only in `connectCopilot`. func bootstrapCopilot() async { + if CopilotExplicitDisconnect.isSet(defaults: copilotQuotaRuntime.defaults) { + copilotLoadState = .notBootstrapped + return + } // Capture the generation before the await so a disconnect that lands // mid-fetch cannot be resurrected into .loaded when the fetch returns. let gen = copilotRefreshGen copilotLoadState = .bootstrapping do { - let usage = try await CopilotSubscriptionService.refresh() + let usage = try await copilotQuotaRuntime.refresh() guard gen == copilotRefreshGen else { return } + if CopilotExplicitDisconnect.isSet(defaults: copilotQuotaRuntime.defaults) { return } copilotUsage = usage copilotError = nil copilotLoadState = .loaded } catch let err as CopilotSubscriptionService.FetchError { guard gen == copilotRefreshGen else { return } + if CopilotExplicitDisconnect.isSet(defaults: copilotQuotaRuntime.defaults) { return } applyCopilotFetchError(err) } catch { guard gen == copilotRefreshGen else { return } + if CopilotExplicitDisconnect.isSet(defaults: copilotQuotaRuntime.defaults) { return } copilotError = sanitizeForUI(error.localizedDescription) copilotLoadState = .failed } } + /// User-initiated Connect / Reconnect / Load Quota. Clears persisted + /// explicit disconnect so discovery may run again. + func connectCopilot() async { + CopilotExplicitDisconnect.clear(defaults: copilotQuotaRuntime.defaults) + await bootstrapCopilot() + } + func refreshCopilot() async { _ = await refreshCopilotReportingSuccess() } @discardableResult func refreshCopilotReportingSuccess() async -> Bool { + if CopilotExplicitDisconnect.isSet(defaults: copilotQuotaRuntime.defaults) { + if copilotLoadState != .notBootstrapped { copilotLoadState = .notBootstrapped } + return false + } if case .dormant = copilotLoadState { await bootstrapCopilot() return copilotLoadState == .loaded } - guard CopilotSubscriptionService.hasCredential else { + guard copilotQuotaRuntime.hasCredential() else { if copilotLoadState != .notBootstrapped { copilotLoadState = .notBootstrapped } return false } let gen = copilotRefreshGen if copilotUsage == nil { copilotLoadState = .loading } do { - let usage = try await CopilotSubscriptionService.refresh() + let usage = try await copilotQuotaRuntime.refresh() guard gen == copilotRefreshGen else { return false } + if CopilotExplicitDisconnect.isSet(defaults: copilotQuotaRuntime.defaults) { return false } copilotUsage = usage copilotError = nil copilotLoadState = .loaded return true } catch let err as CopilotSubscriptionService.FetchError { guard gen == copilotRefreshGen else { return false } + if CopilotExplicitDisconnect.isSet(defaults: copilotQuotaRuntime.defaults) { return false } applyCopilotFetchError(err) return false } catch { guard gen == copilotRefreshGen else { return false } + if CopilotExplicitDisconnect.isSet(defaults: copilotQuotaRuntime.defaults) { return false } copilotError = sanitizeForUI(error.localizedDescription) copilotLoadState = .failed return false @@ -1765,7 +1802,8 @@ final class AppStore { } func disconnectCopilot() { - CopilotSubscriptionService.disconnect() + copilotQuotaRuntime.disconnectService() + CopilotExplicitDisconnect.mark(defaults: copilotQuotaRuntime.defaults) copilotRefreshGen &+= 1 copilotUsage = nil copilotError = nil @@ -2217,7 +2255,7 @@ final class AppStore { case .codex: await bootstrapCodex() case .kimiCode: await bootstrapKimi() case .gemini: await bootstrapGemini() - case .copilot: await bootstrapCopilot() + case .copilot: await connectCopilot() case .antigravity: await bootstrapAntigravity() default: break } diff --git a/mac/Sources/CodeBurnMenubar/Data/CopilotExplicitDisconnect.swift b/mac/Sources/CodeBurnMenubar/Data/CopilotExplicitDisconnect.swift new file mode 100644 index 00000000..930b647d --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/Data/CopilotExplicitDisconnect.swift @@ -0,0 +1,39 @@ +import Foundation + +/// Persisted opt-out for live Copilot quota tracking after an explicit +/// Disconnect. Credentials stay untouched; this flag only stops automatic +/// discovery from bringing quota tracking back on the next refresh or relaunch. +/// Absent key is false, so first-use autodiscovery is unchanged. +enum CopilotExplicitDisconnect { + static let defaultsKey = "codeburn.copilot.explicitlyDisconnected" + + static func isSet(defaults: UserDefaults = .standard) -> Bool { + defaults.bool(forKey: defaultsKey) + } + + static func mark(defaults: UserDefaults = .standard) { + defaults.set(true, forKey: defaultsKey) + } + + static func clear(defaults: UserDefaults = .standard) { + defaults.removeObject(forKey: defaultsKey) + } +} + +/// Injectable Copilot quota I/O for AppStore. Production uses `.live`; +/// tests pass an ephemeral UserDefaults suite and stubbed fetch/credential +/// checks so they never touch installed prefs, Keychain, or `gh`. +@MainActor +struct CopilotQuotaRuntime { + var hasCredential: () -> Bool + var refresh: @Sendable () async throws -> CopilotUsage + var disconnectService: () -> Void + var defaults: UserDefaults + + static let live = CopilotQuotaRuntime( + hasCredential: { CopilotSubscriptionService.hasCredential }, + refresh: { try await CopilotSubscriptionService.refresh() }, + disconnectService: { CopilotSubscriptionService.disconnect() }, + defaults: .standard + ) +} diff --git a/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift b/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift index 5e34964a..8c087ba5 100644 --- a/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift +++ b/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift @@ -2470,7 +2470,7 @@ private struct CopilotPlanInsight: View { PlanNoCredentialsView( title: "No Copilot credentials found", message: "Sign in via an editor's Copilot plugin first. Then click Try Again." - ) { Task { await store.bootstrapCopilot() } } + ) { Task { await store.connectCopilot() } } case .loading: PlanLoadingView(message: "Reading Copilot credentials...") case .failed: @@ -2486,7 +2486,7 @@ private struct CopilotPlanInsight: View { title: "Refresh Copilot login", reason: reason, fallback: "Your Copilot sign-in has expired. Sign in via an editor's Copilot plugin again, then click Reconnect." - ) { Task { await store.bootstrapCopilot() } } + ) { Task { await store.connectCopilot() } } case let .usage(idle): if let usage = store.copilotUsage { loadedBody(usage: usage, idle: idle) diff --git a/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift b/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift index 0e15161c..4109fd08 100644 --- a/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift +++ b/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift @@ -1428,7 +1428,7 @@ private struct CopilotTokenSection: View { ) token = "" CopilotSubscriptionService.resetProbeCache() - await store.bootstrapCopilot() + await store.connectCopilot() } catch { errorText = error.localizedDescription } @@ -1529,13 +1529,13 @@ private struct CopilotConnectionRow: View { Text("CodeBurn will stop tracking Copilot quota. Every credential it read stays untouched, and your Copilot clients keep working.") } case .terminalFailure, .noCredentials, .failed: - Button("Reconnect") { Task { await store.bootstrapCopilot() } } + Button("Reconnect") { Task { await store.connectCopilot() } } .buttonStyle(.borderedProminent) case .dormant: - Button("Load Quota") { Task { await store.bootstrapCopilot() } } + Button("Load Quota") { Task { await store.connectCopilot() } } .buttonStyle(.borderedProminent) case .notBootstrapped: - Button("Connect") { Task { await store.bootstrapCopilot() } } + Button("Connect") { Task { await store.connectCopilot() } } .buttonStyle(.borderedProminent) case .bootstrapping: ProgressView().controlSize(.small) diff --git a/mac/Tests/CodeBurnMenubarTests/AppStoreCopilotDisconnectTests.swift b/mac/Tests/CodeBurnMenubarTests/AppStoreCopilotDisconnectTests.swift new file mode 100644 index 00000000..9d064ad2 --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/AppStoreCopilotDisconnectTests.swift @@ -0,0 +1,207 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +@Suite("AppStore Copilot explicit disconnect") +@MainActor +struct AppStoreCopilotDisconnectTests { + @Test("explicit disconnect blocks the next refresh fetch") + func disconnectThenRefreshDoesNotFetch() async throws { + try await withIsolatedCopilotStore(hasCredential: true) { store, fetch, defaults in + #expect(store.copilotLoadState == .dormant) + + store.disconnectCopilot() + + #expect(store.copilotLoadState == .notBootstrapped) + #expect(store.copilotUsage == nil) + #expect(CopilotExplicitDisconnect.isSet(defaults: defaults)) + + let fetched = await store.refreshCopilotReportingSuccess() + + #expect(fetched == false) + #expect(await fetch.recordedCount() == 0) + #expect(store.copilotLoadState == .notBootstrapped) + #expect(store.copilotUsage == nil) + } + } + + @Test("relaunch honors persisted Copilot opt-out") + func relaunchRemainsDisconnected() async throws { + try await withIsolatedCopilotStore(hasCredential: true) { store, fetch, defaults in + store.disconnectCopilot() + #expect(CopilotExplicitDisconnect.isSet(defaults: defaults)) + + let relaunched = AppStore(copilotQuotaRuntime: CopilotQuotaRuntime( + hasCredential: { true }, + refresh: { await fetch.next() }, + disconnectService: {}, + defaults: defaults + )) + + #expect(relaunched.copilotLoadState == .notBootstrapped) + + let fetched = await relaunched.refreshCopilotReportingSuccess() + + #expect(fetched == false) + #expect(await fetch.recordedCount() == 0) + #expect(relaunched.copilotLoadState == .notBootstrapped) + #expect(relaunched.copilotUsage == nil) + } + } + + @Test("explicit reconnect clears opt-out and fetches") + func explicitReconnectResumes() async throws { + try await withIsolatedCopilotStore(hasCredential: true) { store, fetch, defaults in + store.disconnectCopilot() + #expect(CopilotExplicitDisconnect.isSet(defaults: defaults)) + + await store.connectCopilot() + + #expect(!CopilotExplicitDisconnect.isSet(defaults: defaults)) + #expect(await fetch.recordedCount() == 1) + #expect(store.copilotLoadState == .loaded) + #expect(store.copilotUsage?.plan == "Individual") + } + } + + @Test("first-use with credentials still auto-discovers") + func firstUseAutodiscoveryFetches() async throws { + try await withIsolatedCopilotStore(hasCredential: true) { store, fetch, defaults in + #expect(!CopilotExplicitDisconnect.isSet(defaults: defaults)) + #expect(store.copilotLoadState == .dormant) + + let fetched = await store.refreshCopilotReportingSuccess() + + #expect(fetched == true) + #expect(await fetch.recordedCount() == 1) + #expect(store.copilotLoadState == .loaded) + #expect(!CopilotExplicitDisconnect.isSet(defaults: defaults)) + } + } + + @Test("first-use without credentials does not fetch") + func firstUseWithoutCredentialsStaysIdle() async throws { + try await withIsolatedCopilotStore(hasCredential: false) { store, fetch, defaults in + #expect(store.copilotLoadState == .notBootstrapped) + #expect(!CopilotExplicitDisconnect.isSet(defaults: defaults)) + + let fetched = await store.refreshCopilotReportingSuccess() + + #expect(fetched == false) + #expect(await fetch.recordedCount() == 0) + #expect(store.copilotLoadState == .notBootstrapped) + } + } + + @Test("disconnect discards an in-flight Copilot fetch") + func inFlightFetchCannotResurrectAfterDisconnect() async throws { + try await withIsolatedCopilotStore(hasCredential: true) { store, fetch, defaults in + await fetch.setParkNext(true) + let refresh = Task { await store.refreshCopilotReportingSuccess() } + try #require(await fetch.waitUntilParked()) + + store.disconnectCopilot() + await fetch.open() + let fetched = await refresh.value + + #expect(fetched == false) + #expect(store.copilotLoadState == .notBootstrapped) + #expect(store.copilotUsage == nil) + #expect(CopilotExplicitDisconnect.isSet(defaults: defaults)) + } + } + + @Test("automatic bootstrap does not clear persisted opt-out") + func automaticBootstrapLeavesOptOut() async throws { + try await withIsolatedCopilotStore(hasCredential: true) { store, fetch, defaults in + store.disconnectCopilot() + await store.bootstrapCopilot() + + #expect(CopilotExplicitDisconnect.isSet(defaults: defaults)) + #expect(await fetch.recordedCount() == 0) + #expect(store.copilotLoadState == .notBootstrapped) + } + } + + @Test("disconnect wins over an in-flight explicit connect") + func disconnectWinsOverPendingConnect() async throws { + try await withIsolatedCopilotStore(hasCredential: true) { store, fetch, defaults in + store.disconnectCopilot() + await fetch.setParkNext(true) + let connect = Task { await store.connectCopilot() } + try #require(await fetch.waitUntilParked()) + + store.disconnectCopilot() + await fetch.open() + await connect.value + + #expect(CopilotExplicitDisconnect.isSet(defaults: defaults)) + #expect(store.copilotLoadState == .notBootstrapped) + #expect(store.copilotUsage == nil) + } + } +} + +@MainActor +private func withIsolatedCopilotStore( + hasCredential: Bool, + _ body: @MainActor (AppStore, CopilotFetchStub, UserDefaults) async throws -> Void +) async throws { + let suiteName = "codeburn.copilot.disconnect.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.removePersistentDomain(forName: suiteName) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let fetch = CopilotFetchStub() + let store = AppStore(copilotQuotaRuntime: CopilotQuotaRuntime( + hasCredential: { hasCredential }, + refresh: { await fetch.next() }, + disconnectService: {}, + defaults: defaults + )) + try await body(store, fetch, defaults) +} + +private actor CopilotFetchStub { + private(set) var count = 0 + private var parkNext = false + private var parked: CheckedContinuation? + private var isParked = false + + func recordedCount() -> Int { count } + + func setParkNext(_ value: Bool) { + parkNext = value + } + + func next() async -> CopilotUsage { + count += 1 + if parkNext { + parkNext = false + isParked = true + await withCheckedContinuation { parked = $0 } + } + return CopilotUsage( + details: [ + CopilotUsage.Window(label: "Premium requests", usedPercent: 30, resetsAt: nil) + ], + plan: "Individual", + fetchedAt: Date(timeIntervalSince1970: 1_786_000_000) + ) + } + + func waitUntilParked() async -> Bool { + let deadline = ContinuousClock.now + .seconds(2) + while !isParked { + if ContinuousClock.now >= deadline { return false } + try? await Task.sleep(for: .milliseconds(10)) + } + return true + } + + func open() { + parked?.resume() + parked = nil + isParked = false + } +} From 94218bf173dafd2cc12241e184524caa91b0eadd Mon Sep 17 00:00:00 2001 From: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Date: Wed, 9 Sep 2026 22:59:56 +0530 Subject: [PATCH 2/4] fix(mac): show honest Copilot copy after explicit disconnect Plan and Settings treated sticky .notBootstrapped after Disconnect as missing credentials. Keep first-use and real noCredentials sign-in copy; disconnected state says quota tracking is off, credentials untouched, and Connect resumes. --- .../Data/CopilotQuotaPresentation.swift | 32 +++++++++- .../Views/HeatmapSection.swift | 15 ++++- .../CodeBurnMenubar/Views/SettingsView.swift | 8 ++- .../CopilotQuotaPresentationTests.swift | 60 ++++++++++++++++++- 4 files changed, 106 insertions(+), 9 deletions(-) diff --git a/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift b/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift index ab4bd38e..cc81885f 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift @@ -9,11 +9,18 @@ import Foundation /// with a quiet caption instead of flapping to a reconnect screen; the /// reconnect screen is reserved for the no-data case, where there is /// genuinely nothing to show. +/// +/// Explicit Disconnect is different from missing credentials: the store keeps +/// `.notBootstrapped` while credentials stay on disk. Plan and Settings copy +/// therefore take the persisted opt-out flag and must not claim the token is +/// gone. enum CopilotQuotaPresentation { /// Which Plan-tab subview to render, given the load state and whether a /// last-known snapshot exists. enum PlanContent: Equatable { case noCredentials + /// Explicit Disconnect: quota tracking is off, credentials untouched. + case disconnected case loading case failed case transientFailed @@ -24,9 +31,26 @@ enum CopilotQuotaPresentation { case usage(idle: Bool) } - static func planContent(loadState: SubscriptionLoadState, hasUsage: Bool) -> PlanContent { + static let noCredentialsPlanTitle = "No Copilot credentials found" + static let noCredentialsPlanMessage = + "Sign in via an editor's Copilot plugin first. Then click Try Again." + static let disconnectedPlanTitle = "Copilot quota tracking disconnected" + static let disconnectedPlanMessage = + "Your Copilot credentials are untouched. Click Connect to resume." + static let noCredentialsSettingsDetail = + "Usage tracking still works. For live quota, sign in with the Copilot CLI or gh auth login, or paste a token below, then click Connect." + static let disconnectedSettingsDetail = + "Quota tracking disconnected. Credentials are untouched. Click Connect to resume." + + static func planContent( + loadState: SubscriptionLoadState, + hasUsage: Bool, + explicitlyDisconnected: Bool = false + ) -> PlanContent { switch loadState { - case .notBootstrapped, .noCredentials: + case .notBootstrapped: + return explicitlyDisconnected ? .disconnected : .noCredentials + case .noCredentials: return .noCredentials case .dormant, .bootstrapping: return .loading @@ -41,6 +65,10 @@ enum CopilotQuotaPresentation { } } + static func settingsNotConnectedDetail(explicitlyDisconnected: Bool) -> String { + explicitlyDisconnected ? disconnectedSettingsDetail : noCredentialsSettingsDetail + } + /// Snapshot age past which a loaded view stamps an "as of