diff --git a/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderQuotaService.swift b/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderQuotaService.swift index 6202e345..f646815b 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderQuotaService.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderQuotaService.swift @@ -22,6 +22,7 @@ final class CapacityDockProviderQuotaService { // network by omitting a field. var refreshClinePass: @Sendable (String) async throws -> QuotaSummary var refreshCursor: @Sendable () async throws -> QuotaSummary + var refreshGrok: @Sendable () async throws -> QuotaSummary var refreshZai: @Sendable (String?) async throws -> QuotaSummary static let live = Dependencies( @@ -31,6 +32,9 @@ final class CapacityDockProviderQuotaService { refreshCursor: { try await CursorSubscriptionService.refresh() }, + refreshGrok: { + try await GrokBuildSubscriptionService.refresh() + }, refreshZai: { apiKey in try await ZaiSubscriptionService.refresh(apiKey: apiKey) } @@ -58,6 +62,14 @@ final class CapacityDockProviderQuotaService { } catch { throw CapacityDockProviderFetchFailure(error: error) } + case "grok": + do { + return try await dependencies.refreshGrok() + } catch is CancellationError { + throw CancellationError() + } catch { + throw CapacityDockProviderFetchFailure(error: error) + } case "clinepass": guard let apiKey = credential.sanitizedOverride.apiKey else { throw CapacityDockProviderFetchFailure( @@ -133,6 +145,14 @@ struct CapacityDockProviderFetchFailure: LocalizedError, Equatable, Sendable { return .transient } } + if let error = error as? GrokBuildSubscriptionService.FetchError { + switch error.classification { + case .terminalAuth: + return .terminal + case .transient, .parseFailure: + return .transient + } + } if let error = error as? ZaiSubscriptionService.FetchError { switch error.classification { case .terminalAuth: diff --git a/mac/Sources/CodeBurnMenubar/Data/GrokBuildSubscriptionService.swift b/mac/Sources/CodeBurnMenubar/Data/GrokBuildSubscriptionService.swift new file mode 100644 index 00000000..6e86915a --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/Data/GrokBuildSubscriptionService.swift @@ -0,0 +1,367 @@ +import Foundation + +/// Read-only access to the login that Grok Build owns in `$GROK_HOME/auth.json`. +/// CodeBurn keeps the bearer in memory only and never copies it into Keychain, +/// UserDefaults, logs, or its support directory. +enum GrokBuildCredentialStore { + struct Credential: Equatable, Sendable { + let accessToken: String + let authMode: String? + let expiresAt: Date? + + func isExpired(at date: Date) -> Bool { + guard let expiresAt else { return false } + return expiresAt <= date + } + } + + enum ReadError: Error, Equatable { + case malformed + case missingToken + } + + private struct Entry: Decodable { + let key: String? + let authMode: String? + let expiresAt: String? + + enum CodingKeys: String, CodingKey { + case key + case authMode = "auth_mode" + case expiresAt = "expires_at" + } + } + + static func load( + environment: [String: String] = ProcessInfo.processInfo.environment, + home: URL = FileManager.default.homeDirectoryForCurrentUser + ) throws -> Credential? { + let grokHome: URL + if let configured = cleaned(environment["GROK_HOME"]) { + grokHome = URL( + fileURLWithPath: (configured as NSString).expandingTildeInPath, + isDirectory: true + ) + } else { + grokHome = home.appendingPathComponent(".grok", isDirectory: true) + } + let authURL = grokHome.appendingPathComponent("auth.json", isDirectory: false) + guard FileManager.default.fileExists(atPath: authURL.path) else { return nil } + return try decode(SafeFile.read(from: authURL.path, maxBytes: 128 * 1024)) + } + + static func decode(_ data: Data) throws -> Credential { + let entries: [String: Entry] + do { + entries = try JSONDecoder().decode([String: Entry].self, from: data) + } catch { + throw ReadError.malformed + } + + let usable = entries.compactMap { scope, entry -> (scope: String, entry: Entry, token: String)? in + guard let token = cleaned(entry.key) else { return nil } + return (scope, entry, token) + } + let selected = usable.sorted { lhs, rhs in + let lhsRank = credentialRank(scope: lhs.scope) + let rhsRank = credentialRank(scope: rhs.scope) + return lhsRank == rhsRank ? lhs.scope < rhs.scope : lhsRank < rhsRank + }.first + guard let selected else { throw ReadError.missingToken } + + return Credential( + accessToken: selected.token, + authMode: cleaned(selected.entry.authMode), + expiresAt: parseDate(selected.entry.expiresAt) + ) + } + + private static func credentialRank(scope: String) -> Int { + if scope.hasPrefix("https://auth.x.ai::") { return 0 } + if scope.contains("/sign-in") { return 1 } + return 2 + } + + private static func cleaned(_ raw: String?) -> String? { + guard let value = raw?.trimmingCharacters(in: .whitespacesAndNewlines), + !value.isEmpty else { return nil } + return value + } + + private static func parseDate(_ raw: String?) -> Date? { + guard let raw = cleaned(raw) else { return nil } + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + if let date = formatter.date(from: raw) { return date } + formatter.formatOptions = [.withInternetDateTime] + return formatter.date(from: raw) + } +} + +/// Live Grok Build subscription usage obtained with the OAuth login already +/// managed by the Grok CLI. Requests use an ephemeral, cookie-free session and +/// the bearer is released after each refresh. +enum GrokBuildSubscriptionService { + static let billingURL = URL(string: "https://cli-chat-proxy.grok.com/v1/billing?format=credits")! + static let settingsURL = URL(string: "https://cli-chat-proxy.grok.com/v1/settings")! + private static let timeoutSeconds: TimeInterval = 15 + + enum FetchError: Error, Equatable, LocalizedError, Sendable { + case noCredentials + case expiredSession + case credentialDataUnreadable + case authenticationRejected + case rateLimited + case providerUnavailable + case parseFailure + case network + + enum Classification: Equatable, Sendable { + case terminalAuth + case transient + case parseFailure + } + + var classification: Classification { + switch self { + case .noCredentials, .expiredSession, .credentialDataUnreadable, .authenticationRejected: + .terminalAuth + case .rateLimited, .providerUnavailable, .network: + .transient + case .parseFailure: + .parseFailure + } + } + + var errorDescription: String? { + switch self { + case .noCredentials: + "Run `grok login`, then click Retry." + case .expiredSession: + "The Grok Build login has expired. Run `grok login`, then click Retry." + case .credentialDataUnreadable: + "Could not read Grok Build's local login. Run `grok login` again, then click Retry." + case .authenticationRejected: + "Grok rejected the current Grok Build login. Run `grok login`, then click Retry." + case .rateLimited: + "Grok rate-limited the quota request." + case .providerUnavailable: + "Grok quota is temporarily unavailable." + case .parseFailure: + "Grok returned an unrecognized quota response." + case .network: + "Network error fetching Grok quota." + } + } + } + + struct Deps: Sendable { + var loadCredential: @Sendable () throws -> GrokBuildCredentialStore.Credential? + var fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + + static let live = Deps( + loadCredential: { try GrokBuildCredentialStore.load() }, + fetch: { request in + let configuration = URLSessionConfiguration.ephemeral + configuration.httpCookieStorage = nil + configuration.httpShouldSetCookies = false + configuration.urlCache = nil + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + let session = URLSession(configuration: configuration) + defer { session.invalidateAndCancel() } + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse else { throw FetchError.network } + return (data, http) + } + ) + } + + @MainActor + static func refresh(deps: Deps = .live, now: Date = Date()) async throws -> QuotaSummary { + let loadCredential = deps.loadCredential + let credential: GrokBuildCredentialStore.Credential + do { + guard let loaded = try await Task.detached(operation: loadCredential).value else { + throw FetchError.noCredentials + } + credential = loaded + } catch let error as FetchError { + throw error + } catch let error as GrokBuildCredentialStore.ReadError { + switch error { + case .missingToken: throw FetchError.noCredentials + case .malformed: throw FetchError.credentialDataUnreadable + } + } catch { + throw FetchError.credentialDataUnreadable + } + guard !credential.isExpired(at: now) else { throw FetchError.expiredSession } + + let billingData = try await fetchRequired( + url: billingURL, + credential: credential, + deps: deps + ) + let billing = try decodeBilling(billingData) + let settingsPlan = try await fetchPlan(credential: credential, deps: deps) + let plan = normalizedPlan(settingsPlan) ?? normalizedPlan(billing.subscriptionTier) + let window = QuotaSummary.Window( + label: windowLabel(resetsAt: billing.resetsAt, now: now), + percent: billing.usedPercent, + resetsAt: billing.resetsAt + ) + return QuotaSummary( + providerFilter: .grok, + connection: .connected, + primary: window, + details: [window], + planLabel: plan, + footerLines: ["Source: Grok Build"] + ) + } + + private struct BillingSnapshot { + let usedPercent: Double + let resetsAt: Date? + let subscriptionTier: String? + } + + private struct BillingEnvelope: Decodable { + let config: BillingConfig? + let subscriptionTier: String? + } + + private struct BillingConfig: Decodable { + let creditUsagePercent: Double? + let currentPeriod: CurrentPeriod? + let billingPeriodEnd: String? + let onDemandCap: Amount? + let onDemandUsed: Amount? + let subscriptionTier: String? + } + + private struct CurrentPeriod: Decodable { let end: String? } + private struct Amount: Decodable { let val: Double? } + private struct SettingsEnvelope: Decodable { + let subscriptionTierDisplay: String? + + enum CodingKeys: String, CodingKey { + case subscriptionTierDisplay = "subscription_tier_display" + } + } + + private static func decodeBilling(_ data: Data) throws -> BillingSnapshot { + let envelope: BillingEnvelope + do { + envelope = try JSONDecoder().decode(BillingEnvelope.self, from: data) + } catch { + throw FetchError.parseFailure + } + guard let config = envelope.config else { throw FetchError.parseFailure } + + let rawPercent: Double? + if let percent = config.creditUsagePercent, percent.isFinite { + rawPercent = percent + } else if let used = config.onDemandUsed?.val, + let cap = config.onDemandCap?.val, + used.isFinite, cap.isFinite, used >= 0, cap > 0 { + rawPercent = used / cap * 100 + } else { + rawPercent = nil + } + guard let rawPercent else { throw FetchError.parseFailure } + + let reset = parseDate(config.currentPeriod?.end ?? config.billingPeriodEnd) + return BillingSnapshot( + usedPercent: min(1, max(0, rawPercent / 100)), + resetsAt: reset, + subscriptionTier: config.subscriptionTier ?? envelope.subscriptionTier + ) + } + + private static func fetchRequired( + url: URL, + credential: GrokBuildCredentialStore.Credential, + deps: Deps + ) async throws -> Data { + let request = authorizedRequest(url: url, credential: credential) + let data: Data + let response: HTTPURLResponse + do { + (data, response) = try await deps.fetch(request) + } catch let error as FetchError { + throw error + } catch is CancellationError { + throw CancellationError() + } catch { + throw FetchError.network + } + switch response.statusCode { + case 200: return data + case 401, 403: throw FetchError.authenticationRejected + case 429: throw FetchError.rateLimited + case 500...599: throw FetchError.providerUnavailable + default: throw FetchError.parseFailure + } + } + + private static func fetchPlan( + credential: GrokBuildCredentialStore.Credential, + deps: Deps + ) async throws -> String? { + let request = authorizedRequest(url: settingsURL, credential: credential) + let data: Data + let response: HTTPURLResponse + do { + (data, response) = try await deps.fetch(request) + } catch is CancellationError { + throw CancellationError() + } catch { + return nil + } + guard response.statusCode == 200, + let settings = try? JSONDecoder().decode(SettingsEnvelope.self, from: data) else { return nil } + return settings.subscriptionTierDisplay + } + + private static func authorizedRequest( + url: URL, + credential: GrokBuildCredentialStore.Credential + ) -> URLRequest { + var request = URLRequest(url: url) + request.httpMethod = "GET" + request.timeoutInterval = timeoutSeconds + request.setValue("Bearer \(credential.accessToken)", forHTTPHeaderField: "Authorization") + request.setValue("xai-grok-cli", forHTTPHeaderField: "x-xai-token-auth") + request.setValue("application/json", forHTTPHeaderField: "Accept") + request.setValue("CodeBurn", forHTTPHeaderField: "User-Agent") + return request + } + + private static func parseDate(_ raw: String?) -> Date? { + guard let raw, !raw.isEmpty else { return nil } + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + if let date = formatter.date(from: raw) { return date } + formatter.formatOptions = [.withInternetDateTime] + return formatter.date(from: raw) + } + + private static func normalizedPlan(_ raw: String?) -> String? { + guard let value = raw?.trimmingCharacters(in: .whitespacesAndNewlines), + !value.isEmpty else { return nil } + switch value.lowercased().filter(\.isLetter) { + case "supergrokheavy", "heavy": return "SuperGrok Heavy" + case "supergrok": return "SuperGrok" + default: return value + } + } + + private static func windowLabel(resetsAt: Date?, now: Date) -> String { + guard let resetsAt else { return "Credits" } + let days = Int((resetsAt.timeIntervalSince(now) / 86_400).rounded()) + if (4...12).contains(days) { return "Weekly" } + if (20...45).contains(days) { return "Monthly" } + return "Credits" + } +} diff --git a/mac/Sources/CodeBurnMenubar/Data/ProviderConnectionCatalog.swift b/mac/Sources/CodeBurnMenubar/Data/ProviderConnectionCatalog.swift index 091918a2..0095c6c1 100644 --- a/mac/Sources/CodeBurnMenubar/Data/ProviderConnectionCatalog.swift +++ b/mac/Sources/CodeBurnMenubar/Data/ProviderConnectionCatalog.swift @@ -117,8 +117,8 @@ enum ProviderConnectionCatalog { entry("qoder", "Qoder", [.automatic, .web], [.cookieOrWebSession]), entry("stepfun", "StepFun", [.automatic, .web], [.cookieOrWebSession]), entry("bedrock", "AWS Bedrock", [.automatic, .api], [.apiTokenOrCloudCredentials]), - entry("grok", "Grok", [.automatic, .cli, .oauth, .web], - [.localAppOrCLI, .oauth, .cookieOrWebSession]), + entry("grok", "Grok", [.automatic, .cli, .oauth], + [.localAppOrCLI, .oauth], live: true), entry("groq", "Groq", [.automatic, .web, .api], [.cookieOrWebSession, .apiTokenOrCloudCredentials]), entry("llmproxy", "LLM Proxy", [.automatic, .api], [.apiTokenOrCloudCredentials]), diff --git a/mac/Tests/CodeBurnMenubarTests/CapacityDockPresentationTests.swift b/mac/Tests/CodeBurnMenubarTests/CapacityDockPresentationTests.swift index 07af5c33..6cab85c4 100644 --- a/mac/Tests/CodeBurnMenubarTests/CapacityDockPresentationTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/CapacityDockPresentationTests.swift @@ -360,6 +360,18 @@ struct CapacityDockPresentationTests { "Sign in to Command Code in a supported browser, then click Retry.") } + @Test("Grok Build offers direct one-click local login discovery") + func grokBuildConnectionGuidance() { + let provider = CapacityDockProvider(rawValue: "grok")! + #expect(ProviderConnectionGuidance.instruction(for: provider) == + "Sign in with the Grok app or CLI, then click Retry.") + #expect(ProviderConnectionSubmissionPolicy.resolve( + credential: CapacityDockProviderCredential(), + savedCredential: CapacityDockProviderCredential(), + requiresExplicitCredential: false + ) == .connect) + } + @Test("Connect saves edited credentials before fetching") func connectionSubmissionPolicy() { let empty = CapacityDockProviderCredential() diff --git a/mac/Tests/CodeBurnMenubarTests/CapacityDockProviderQuotaServiceTests.swift b/mac/Tests/CodeBurnMenubarTests/CapacityDockProviderQuotaServiceTests.swift index 62385042..1908bd6e 100644 --- a/mac/Tests/CodeBurnMenubarTests/CapacityDockProviderQuotaServiceTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/CapacityDockProviderQuotaServiceTests.swift @@ -11,6 +11,10 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() } + nonisolated private static let unusedGrok: @Sendable () async throws -> QuotaSummary = { + Issue.record("Wrong adapter dispatched") + return Self.summary() + } nonisolated private static let unusedZai: @Sendable (String?) async throws -> QuotaSummary = { _ in Issue.record("Wrong adapter dispatched") return Self.summary() @@ -26,6 +30,7 @@ struct CapacityDockProviderQuotaServiceTests { return expected }, refreshCursor: Self.unusedCursor, + refreshGrok: Self.unusedGrok, refreshZai: Self.unusedZai )) let provider = try #require(CapacityDockProvider(rawValue: "clinepass")) @@ -51,6 +56,7 @@ struct CapacityDockProviderQuotaServiceTests { return Self.summary() }, refreshCursor: Self.unusedCursor, + refreshGrok: Self.unusedGrok, refreshZai: { apiKey in if let apiKey { await capture.record(apiKey) } return expected @@ -77,6 +83,7 @@ struct CapacityDockProviderQuotaServiceTests { return Self.summary() }, refreshCursor: { expected }, + refreshGrok: Self.unusedGrok, refreshZai: Self.unusedZai )) let provider = try #require(CapacityDockProvider(rawValue: "cursor")) @@ -89,6 +96,28 @@ struct CapacityDockProviderQuotaServiceTests { #expect(result == expected) } + @Test("Grok dispatches through passive Grok Build login discovery") + func dispatchesGrok() async throws { + let expected = Self.summary(percent: 0.21) + let service = CapacityDockProviderQuotaService(dependencies: .init( + refreshClinePass: { _ in + Issue.record("Wrong adapter dispatched") + return Self.summary() + }, + refreshCursor: Self.unusedCursor, + refreshGrok: { expected }, + refreshZai: Self.unusedZai + )) + let provider = try #require(CapacityDockProvider(rawValue: "grok")) + + let result = try await service.fetch( + provider: provider, + credential: CapacityDockProviderCredential() + ) + + #expect(result == expected) + } + @Test("ClinePass requires its own saved API key") func requiresClinePassKey() async throws { let service = CapacityDockProviderQuotaService(dependencies: .init( @@ -97,6 +126,7 @@ struct CapacityDockProviderQuotaServiceTests { return Self.summary() }, refreshCursor: Self.unusedCursor, + refreshGrok: Self.unusedGrok, refreshZai: Self.unusedZai )) let provider = try #require(CapacityDockProvider(rawValue: "clinepass")) @@ -128,6 +158,7 @@ struct CapacityDockProviderQuotaServiceTests { return Self.summary() }, refreshCursor: Self.unusedCursor, + refreshGrok: Self.unusedGrok, refreshZai: Self.unusedZai )) let provider = try #require(CapacityDockProvider(rawValue: "openrouter")) @@ -150,6 +181,7 @@ struct CapacityDockProviderQuotaServiceTests { let service = CapacityDockProviderQuotaService(dependencies: .init( refreshClinePass: { _ in throw ClinePassSubscriptionService.FetchError.authenticationRejected }, refreshCursor: Self.unusedCursor, + refreshGrok: Self.unusedGrok, refreshZai: Self.unusedZai )) let provider = try #require(CapacityDockProvider(rawValue: "clinepass")) @@ -175,6 +207,7 @@ struct CapacityDockProviderQuotaServiceTests { let service = CapacityDockProviderQuotaService(dependencies: .init( refreshClinePass: { _ in throw error }, refreshCursor: Self.unusedCursor, + refreshGrok: Self.unusedGrok, refreshZai: Self.unusedZai )) do { @@ -193,6 +226,40 @@ struct CapacityDockProviderQuotaServiceTests { ) == .transient) } + @Test("Grok login failures stop retries while quota outages preserve the connection") + func classifiesGrokFailures() async throws { + let provider = try #require(CapacityDockProvider(rawValue: "grok")) + let cases: [(GrokBuildSubscriptionService.FetchError, CapacityDockProviderFetchFailureDisposition)] = [ + (.noCredentials, .terminal), + (.authenticationRejected, .terminal), + (.rateLimited, .transient), + (.providerUnavailable, .transient), + (.parseFailure, .transient), + ] + + for (error, expectedDisposition) in cases { + let service = CapacityDockProviderQuotaService(dependencies: .init( + refreshClinePass: { _ in + Issue.record("Wrong adapter dispatched") + return Self.summary() + }, + refreshCursor: Self.unusedCursor, + refreshGrok: { throw error }, + refreshZai: Self.unusedZai + )) + do { + _ = try await service.fetch( + provider: provider, + credential: CapacityDockProviderCredential() + ) + Issue.record("Expected \(error) to fail") + } catch let failure as CapacityDockProviderFetchFailure { + #expect(failure.disposition == expectedDisposition) + #expect(failure.message == error.localizedDescription) + } + } + } + @Test("disconnect invalidates an in-flight provider refresh") func disconnectWinsOverInFlightRefresh() async throws { let provider = try #require(CapacityDockProvider(rawValue: "clinepass")) @@ -209,6 +276,7 @@ struct CapacityDockProviderQuotaServiceTests { return Self.summary(percent: 0.73) }, refreshCursor: Self.unusedCursor, + refreshGrok: Self.unusedGrok, refreshZai: Self.unusedZai )) diff --git a/mac/Tests/CodeBurnMenubarTests/GrokBuildSubscriptionServiceTests.swift b/mac/Tests/CodeBurnMenubarTests/GrokBuildSubscriptionServiceTests.swift new file mode 100644 index 00000000..6a5f4ec2 --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/GrokBuildSubscriptionServiceTests.swift @@ -0,0 +1,230 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +@Suite("Grok Build subscription service") +@MainActor +struct GrokBuildSubscriptionServiceTests { + @Test("Grok Build credential discovery prefers the current OIDC login") + func prefersOIDCCredential() throws { + let data = Data(#""" + { + "https://accounts.x.ai/sign-in": { + "key": "synthetic-legacy-token", + "expires_at": "2026-09-08T10:00:00Z" + }, + "https://auth.x.ai::synthetic-principal": { + "key": "synthetic-oidc-token", + "auth_mode": "oidc", + "expires_at": "2026-09-09T10:00:00Z" + } + } + """#.utf8) + + let credential = try GrokBuildCredentialStore.decode(data) + + #expect(credential.accessToken == "synthetic-oidc-token") + #expect(credential.authMode == "oidc") + #expect(credential.expiresAt == ISO8601DateFormatter().date(from: "2026-09-09T10:00:00Z")) + } + + @Test("one refresh reuses Grok Build login for quota and plan") + func refreshesWithExistingLogin() async throws { + let requests = RequestCapture() + let credential = GrokBuildCredentialStore.Credential( + accessToken: "synthetic-oidc-token", + authMode: "oidc", + expiresAt: ISO8601DateFormatter().date(from: "2026-09-09T10:00:00Z") + ) + let deps = GrokBuildSubscriptionService.Deps( + loadCredential: { credential }, + fetch: { request in + await requests.record(request) + let body: String + switch request.url?.path { + case "/v1/billing": + body = #""" + {"config":{"creditUsagePercent":2,"currentPeriod":{"end":"2026-09-06T17:52:03Z"}}} + """# + case "/v1/settings": + body = #"{"subscription_tier_display":"SuperGrok Heavy"}"# + default: + Issue.record("Unexpected Grok endpoint") + body = "{}" + } + return ( + Data(body.utf8), + HTTPURLResponse( + url: request.url!, + statusCode: 200, + httpVersion: nil, + headerFields: nil + )! + ) + } + ) + + let result = try await GrokBuildSubscriptionService.refresh( + deps: deps, + now: ISO8601DateFormatter().date(from: "2026-09-01T10:00:00Z")! + ) + let captured = await requests.values + + #expect(result.connection == .connected) + #expect(result.primary?.label == "Weekly") + #expect(result.primary?.percent == 0.02) + #expect(result.primary?.resetsAt == ISO8601DateFormatter().date(from: "2026-09-06T17:52:03Z")) + #expect(result.planLabel == "SuperGrok Heavy") + #expect(result.footerLines == ["Source: Grok Build"]) + #expect(captured.map(\.url?.path) == ["/v1/billing", "/v1/settings"]) + #expect(captured.allSatisfy { + $0.value(forHTTPHeaderField: "Authorization") == "Bearer synthetic-oidc-token" + && $0.value(forHTTPHeaderField: "x-xai-token-auth") == "xai-grok-cli" + }) + } + + @Test("missing and expired Grok Build logins never reach the network") + func rejectsUnavailableLoginBeforeFetching() async throws { + let requests = RequestCapture() + let fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) = { request in + await requests.record(request) + return ( + Data("{}".utf8), + HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + ) + } + let now = ISO8601DateFormatter().date(from: "2026-09-01T10:00:00Z")! + + do { + _ = try await GrokBuildSubscriptionService.refresh( + deps: .init(loadCredential: { nil }, fetch: fetch), + now: now + ) + Issue.record("Expected a missing-login failure") + } catch let error as GrokBuildSubscriptionService.FetchError { + #expect(error == .noCredentials) + } + + let expired = GrokBuildCredentialStore.Credential( + accessToken: "synthetic-expired-token", + authMode: "oidc", + expiresAt: now.addingTimeInterval(-1) + ) + do { + _ = try await GrokBuildSubscriptionService.refresh( + deps: .init(loadCredential: { expired }, fetch: fetch), + now: now + ) + Issue.record("Expected an expired-login failure") + } catch let error as GrokBuildSubscriptionService.FetchError { + #expect(error == .expiredSession) + } + + #expect(await requests.values.isEmpty) + } + + @Test("Grok billing failures retain actionable classifications") + func classifiesBillingFailures() async throws { + let credential = GrokBuildCredentialStore.Credential( + accessToken: "synthetic-oidc-token", + authMode: "oidc", + expiresAt: nil + ) + let cases: [(Int, GrokBuildSubscriptionService.FetchError)] = [ + (401, .authenticationRejected), + (403, .authenticationRejected), + (429, .rateLimited), + (503, .providerUnavailable), + (418, .parseFailure), + ] + + for (status, expected) in cases { + let deps = GrokBuildSubscriptionService.Deps( + loadCredential: { credential }, + fetch: { request in + ( + Data("{}".utf8), + HTTPURLResponse( + url: request.url!, + statusCode: status, + httpVersion: nil, + headerFields: nil + )! + ) + } + ) + do { + _ = try await GrokBuildSubscriptionService.refresh(deps: deps) + Issue.record("Expected HTTP \(status) to fail") + } catch let error as GrokBuildSubscriptionService.FetchError { + #expect(error == expected) + } + } + } + + @Test("on-demand billing is a safe fallback when percent is absent") + func usesOnDemandFallback() async throws { + let credential = GrokBuildCredentialStore.Credential( + accessToken: "synthetic-oidc-token", + authMode: "oidc", + expiresAt: nil + ) + let deps = GrokBuildSubscriptionService.Deps( + loadCredential: { credential }, + fetch: { request in + let body: String + let status: Int + if request.url?.path == "/v1/billing" { + body = #"{"config":{"onDemandUsed":{"val":25},"onDemandCap":{"val":100},"billingPeriodEnd":"2026-10-01T10:00:00Z","subscriptionTier":"supergrok"}}"# + status = 200 + } else { + body = "{}" + status = 503 + } + return ( + Data(body.utf8), + HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)! + ) + } + ) + + let result = try await GrokBuildSubscriptionService.refresh( + deps: deps, + now: ISO8601DateFormatter().date(from: "2026-09-01T10:00:00Z")! + ) + + #expect(result.primary?.percent == 0.25) + #expect(result.primary?.label == "Monthly") + #expect(result.planLabel == "SuperGrok") + } + + @Test("cancellation during the optional plan request cancels the refresh") + func cancellationWinsDuringPlanFetch() async throws { + let credential = GrokBuildCredentialStore.Credential( + accessToken: "synthetic-oidc-token", + authMode: "oidc", + expiresAt: nil + ) + let deps = GrokBuildSubscriptionService.Deps( + loadCredential: { credential }, + fetch: { request in + if request.url?.path == "/v1/settings" { + throw CancellationError() + } + return ( + Data(#"{"config":{"creditUsagePercent":2}}"#.utf8), + HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + ) + } + ) + + await #expect(throws: CancellationError.self) { + try await GrokBuildSubscriptionService.refresh(deps: deps) + } + } + + private actor RequestCapture { + private(set) var values: [URLRequest] = [] + func record(_ request: URLRequest) { values.append(request) } + } +} diff --git a/mac/Tests/CodeBurnMenubarTests/ProviderConnectionCatalogTests.swift b/mac/Tests/CodeBurnMenubarTests/ProviderConnectionCatalogTests.swift index c8a7395d..9ac84597 100644 --- a/mac/Tests/CodeBurnMenubarTests/ProviderConnectionCatalogTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/ProviderConnectionCatalogTests.swift @@ -34,7 +34,7 @@ struct ProviderConnectionCatalogTests { func pinnedSourceModeCoverage() { let providers = ProviderConnectionCatalog.providers #expect(providers.count(with: .automatic) == 69) - #expect(providers.count(with: .web) == 31) + #expect(providers.count(with: .web) == 30) #expect(providers.count(with: .cli) == 14) #expect(providers.count(with: .oauth) == 5) #expect(providers.count(with: .api) == 44) @@ -46,7 +46,7 @@ struct ProviderConnectionCatalogTests { .filter(\.hasLiveCodeBurnQuotaAdapter) .map(\.id) .sorted() - #expect(live == ["antigravity", "claude", "clinepass", "codex", "copilot", "cursor", "gemini", "kimi", "zai"]) + #expect(live == ["antigravity", "claude", "clinepass", "codex", "copilot", "cursor", "gemini", "grok", "kimi", "zai"]) } }