From 39b9b3adcd5eb7bbc852e1bc9105466f852695db Mon Sep 17 00:00:00 2001 From: Resham Joshi <65915470+iamtoruk@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:34:31 +0200 Subject: [PATCH] feat(quota): Command Code quota and ClinePass from the Cline sign-in (#1682) * feat(quota): Command Code quota and ClinePass from the Cline sign-in Command Code: reads the CLI's ~/.commandcode/auth.json key and the billing credits and subscription endpoints. 5-hour and weekly windows as used of cap, remaining credits as a note, plan from planId. Live in the Mac dock from the local CLI, in codeburn quota and the Windows dock. ClinePass: without a saved or env key, falls back to the Cline CLI's providers.json session (accessToken, then apiKey, then auth.apiKey, with Cline's path overrides). Read-only; an expired session stops before the network and says to run cline. The Mac catalog adds the local CLI source so Automatic connects without a key. * fix(quota): keep retrying after an expired Cline sign-in Running cline refreshes the session file CodeBurn only reads, so an expired or rejected Cline session is now a retryable failure that keeps the last quota and shows the guidance, on the Mac and in the CLI. A rejected API key and a missing credential stay terminal. * test(quota): build expected Cline paths with path.join for Windows --- app/renderer/lib/menubarProviders.ts | 1 + .../Data/CapacityDockPreferences.swift | 1 + .../CapacityDockProviderQuotaService.swift | 30 ++- .../Data/ClinePassSubscriptionService.swift | 101 +++++++++- .../Data/CommandCodeSubscriptionService.swift | 182 ++++++++++++++++++ .../Data/ProviderConnectionCatalog.swift | 9 +- .../Resources/en.lproj/Localizable.strings | 1 + .../Resources/fr.lproj/Localizable.strings | 1 + .../Resources/ja.lproj/Localizable.strings | 1 + .../Resources/ko.lproj/Localizable.strings | 1 + .../zh-Hans.lproj/Localizable.strings | 1 + .../zh-Hant.lproj/Localizable.strings | 1 + .../CapacityDockConnectionActionTests.swift | 10 +- .../CapacityDockPresentationTests.swift | 12 +- ...apacityDockProviderQuotaServiceTests.swift | 109 +++++++++-- .../ClinePassQuotaTests.swift | 95 ++++++++- .../CommandCodeQuotaTests.swift | 108 +++++++++++ .../ProviderConnectionCatalogTests.swift | 6 +- src/quota/clinepass.ts | 70 ++++++- src/quota/commandcode.ts | 140 ++++++++++++++ src/quota/index.ts | 2 + src/quota/types.ts | 2 +- tests/quota-clinepass.test.ts | 61 +++++- tests/quota-commandcode.test.ts | 112 +++++++++++ windows/src/Settings.tsx | 3 +- windows/src/providerIcons.tsx | 13 +- windows/src/settings/ProviderPane.tsx | 6 +- 27 files changed, 1019 insertions(+), 60 deletions(-) create mode 100644 mac/Sources/CodeBurnMenubar/Data/CommandCodeSubscriptionService.swift create mode 100644 mac/Tests/CodeBurnMenubarTests/CommandCodeQuotaTests.swift create mode 100644 src/quota/commandcode.ts create mode 100644 tests/quota-commandcode.test.ts diff --git a/app/renderer/lib/menubarProviders.ts b/app/renderer/lib/menubarProviders.ts index 53a5ca1e..82ac4187 100644 --- a/app/renderer/lib/menubarProviders.ts +++ b/app/renderer/lib/menubarProviders.ts @@ -21,6 +21,7 @@ export const MENUBAR_QUOTA_PROVIDERS = [ 'Z.ai', 'ZCode', 'Kimi Code', + 'Command Code', 'Grok', 'Grok Bot', ] as const diff --git a/mac/Sources/CodeBurnMenubar/Data/CapacityDockPreferences.swift b/mac/Sources/CodeBurnMenubar/Data/CapacityDockPreferences.swift index cd3fb86e..f4946d80 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CapacityDockPreferences.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CapacityDockPreferences.swift @@ -73,6 +73,7 @@ struct CapacityDockProvider: RawRepresentable, CaseIterable, Identifiable, Hasha // The ClinePass plan pays for both Cline surfaces, and the CLI records // the extension and the command line tool as separate rows. case "clinepass": ["cline", "cline-cli"] + case "commandcode": ["command-code"] default: [payloadProviderID] } } diff --git a/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderQuotaService.swift b/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderQuotaService.swift index 35a684ef..f3d2ac34 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderQuotaService.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderQuotaService.swift @@ -20,7 +20,8 @@ final class CapacityDockProviderQuotaService { // No defaults here: only `.live` may reach the real adapters, so a // test can never silently read the local Cursor session or hit the // network by omitting a field. - var refreshClinePass: @Sendable (String) async throws -> QuotaSummary + var refreshClinePass: @Sendable (String?) async throws -> QuotaSummary + var refreshCommandCode: @Sendable () async throws -> QuotaSummary var refreshCursor: @Sendable () async throws -> QuotaSummary var refreshDevin: @Sendable () async throws -> QuotaSummary var refreshGrok: @Sendable () async throws -> QuotaSummary @@ -32,6 +33,9 @@ final class CapacityDockProviderQuotaService { refreshClinePass: { apiKey in try await ClinePassSubscriptionService.refresh(apiKey: apiKey) }, + refreshCommandCode: { + try await CommandCodeSubscriptionService.refresh() + }, refreshCursor: { try await CursorSubscriptionService.refresh() }, @@ -99,14 +103,16 @@ final class CapacityDockProviderQuotaService { throw CapacityDockProviderFetchFailure(error: error) } case "clinepass": - guard let apiKey = credential.sanitizedOverride.apiKey else { - throw CapacityDockProviderFetchFailure( - message: ClinePassSubscriptionService.FetchError.noCredentials.localizedDescription, - disposition: .terminal - ) - } do { - return try await dependencies.refreshClinePass(apiKey) + return try await dependencies.refreshClinePass(credential.sanitizedOverride.apiKey) + } catch is CancellationError { + throw CancellationError() + } catch { + throw CapacityDockProviderFetchFailure(error: error) + } + case "commandcode": + do { + return try await dependencies.refreshCommandCode() } catch is CancellationError { throw CancellationError() } catch { @@ -173,6 +179,14 @@ struct CapacityDockProviderFetchFailure: LocalizedError, Equatable, Sendable { return .transient } } + if let error = error as? CommandCodeSubscriptionService.FetchError { + switch error.classification { + case .terminalAuth: + return .terminal + case .transient, .parseFailure: + return .transient + } + } if let error = error as? CursorSubscriptionService.FetchError { switch error.classification { case .terminalAuth: diff --git a/mac/Sources/CodeBurnMenubar/Data/ClinePassSubscriptionService.swift b/mac/Sources/CodeBurnMenubar/Data/ClinePassSubscriptionService.swift index 2ff17c50..c3031631 100644 --- a/mac/Sources/CodeBurnMenubar/Data/ClinePassSubscriptionService.swift +++ b/mac/Sources/CodeBurnMenubar/Data/ClinePassSubscriptionService.swift @@ -2,7 +2,9 @@ import Foundation /// Live ClinePass quota from the public usage-limits HTTP contract. /// GET https://api.cline.bot/api/v1/users/me/plan/usage-limits with a bearer -/// API key. The caller supplies the key; this adapter never reads Keychain. +/// token: the caller's saved key, else CLINEPASS_API_KEY / CLINE_API_KEY, else +/// the session the Cline CLI keeps in ~/.cline/data/settings/providers.json. +/// That file is only read, never refreshed or written. Never reads Keychain. enum ClinePassSubscriptionService { static let usageURL = URL(string: "https://api.cline.bot/api/v1/users/me/plan/usage-limits")! private static let timeoutSeconds: TimeInterval = 15 @@ -10,6 +12,7 @@ enum ClinePassSubscriptionService { enum FetchError: Error, Equatable, LocalizedError, Sendable { case noCredentials case authenticationRejected + case signInExpired case rateLimited case providerUnavailable case parseFailure @@ -25,7 +28,9 @@ enum ClinePassSubscriptionService { switch self { case .noCredentials, .authenticationRejected: return .terminalAuth - case .rateLimited, .providerUnavailable, .network: + // Running cline refreshes the session file this only reads, so the + // next scheduled read picks it up; keep the last quota until then. + case .signInExpired, .rateLimited, .providerUnavailable, .network: return .transient case .parseFailure: return .parseFailure @@ -37,9 +42,11 @@ enum ClinePassSubscriptionService { var errorDescription: String? { switch self { case .noCredentials: - return "Enter a ClinePass API key or token, then press Save & Connect." + return "Sign in with Cline, or enter a ClinePass API key, then click Retry." case .authenticationRejected: return "ClinePass rejected this API key." + case .signInExpired: + return "Cline sign-in expired. Run cline to refresh it." case .rateLimited: return "ClinePass rate-limited the quota request." case .providerUnavailable: @@ -52,8 +59,16 @@ enum ClinePassSubscriptionService { } } + struct Credential: Equatable, Sendable { + let token: String + let isOAuth: Bool + let expiresAt: Date? + } + struct Deps: Sendable { var fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + var loadAmbientCredential: @Sendable () -> Credential? + var now: @Sendable () -> Date static let live = Deps( fetch: { request in @@ -62,20 +77,88 @@ enum ClinePassSubscriptionService { throw FetchError.network } return (data, http) - } + }, + loadAmbientCredential: { ambientCredential(environment: ProcessInfo.processInfo.environment) }, + now: { Date() } ) } + static func ambientCredential(environment: [String: String]) -> Credential? { + for name in ["CLINEPASS_API_KEY", "CLINE_API_KEY"] { + if let key = cleaned(environment[name]) { + return Credential(token: key, isOAuth: false, expiresAt: nil) + } + } + guard let data = try? Data(contentsOf: providersFileURL(environment: environment)) else { return nil } + return fileCredential(data) + } + + /// Cline's own lookup order: a settings file override, then a data dir, then a Cline dir. + static func providersFileURL( + environment: [String: String], + home: URL = FileManager.default.homeDirectoryForCurrentUser + ) -> URL { + func path(_ name: String) -> URL? { + guard let value = cleaned(environment[name]) else { return nil } + if value == "~" { return home } + if value.hasPrefix("~/") { return home.appendingPathComponent(String(value.dropFirst(2))) } + return URL(fileURLWithPath: value) + } + if let file = path("CLINE_PROVIDER_SETTINGS_PATH") { return file } + let dataDir = path("CLINE_DATA_DIR") + ?? (path("CLINE_DIR") ?? home.appendingPathComponent(".cline")).appendingPathComponent("data") + return dataDir.appendingPathComponent("settings/providers.json") + } + + /// Matches Cline's getApiKey: the OAuth access token wins over keys kept in the same entry. + static func fileCredential(_ data: Data) -> Credential? { + guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let providers = root["providers"] as? [String: Any], + let cline = providers["cline"] as? [String: Any], + let settings = cline["settings"] as? [String: Any] else { return nil } + let auth = settings["auth"] as? [String: Any] + if let access = cleaned(auth?["accessToken"] as? String) { + let expiresAt = (auth?["expiresAt"] as? NSNumber).map { Date(timeIntervalSince1970: $0.doubleValue / 1000) } + return Credential( + token: access.hasPrefix("workos:") ? access : "workos:\(access)", + isOAuth: true, + expiresAt: expiresAt + ) + } + guard let key = cleaned(settings["apiKey"] as? String) ?? cleaned(auth?["apiKey"] as? String) else { + return nil + } + return Credential(token: key, isOAuth: false, expiresAt: nil) + } + + private static func cleaned(_ value: String?) -> String? { + guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty else { + return nil + } + return trimmed + } + @MainActor - static func refresh(apiKey: String, deps: Deps = .live) async throws -> QuotaSummary { - let trimmed = apiKey.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { throw FetchError.noCredentials } + static func refresh(apiKey: String?, deps: Deps = .live) async throws -> QuotaSummary { + let credential: Credential + if let key = cleaned(apiKey) { + credential = Credential(token: key, isOAuth: false, expiresAt: nil) + } else { + let load = deps.loadAmbientCredential + guard let ambient = await Task.detached(operation: { load() }).value else { + throw FetchError.noCredentials + } + credential = ambient + } + if credential.isOAuth, let expiresAt = credential.expiresAt, expiresAt <= deps.now() { + throw FetchError.signInExpired + } var request = URLRequest(url: usageURL) request.httpMethod = "GET" request.timeoutInterval = timeoutSeconds request.setValue("application/json", forHTTPHeaderField: "Accept") - request.setValue("Bearer \(trimmed)", forHTTPHeaderField: "Authorization") + request.setValue("Bearer \(credential.token)", forHTTPHeaderField: "Authorization") let data: Data let response: HTTPURLResponse @@ -91,7 +174,7 @@ enum ClinePassSubscriptionService { case 200: break case 401, 403: - throw FetchError.authenticationRejected + throw credential.isOAuth ? FetchError.signInExpired : FetchError.authenticationRejected case 429: throw FetchError.rateLimited case 500...599: diff --git a/mac/Sources/CodeBurnMenubar/Data/CommandCodeSubscriptionService.swift b/mac/Sources/CodeBurnMenubar/Data/CommandCodeSubscriptionService.swift new file mode 100644 index 00000000..4859c64a --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/Data/CommandCodeSubscriptionService.swift @@ -0,0 +1,182 @@ +import Foundation + +/// Live Command Code quota from its billing endpoints, with the API key the +/// Command Code CLI keeps in ~/.commandcode/auth.json (read-only, never logged). +/// GET /alpha/billing/credits carries the 5-hour and weekly windows as USD +/// credits used of a cap (resetAt epoch ms, 0 while no window is open) plus +/// the remaining credits; GET /alpha/billing/subscriptions carries the plan id. +/// Mirrors src/quota/commandcode.ts. +enum CommandCodeSubscriptionService { + static let creditsURL = URL(string: "https://api.commandcode.ai/alpha/billing/credits")! + static let subscriptionsURL = URL(string: "https://api.commandcode.ai/alpha/billing/subscriptions")! + private static let timeoutSeconds: TimeInterval = 15 + + enum FetchError: Error, Equatable, LocalizedError, Sendable { + case noCredentials + 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, .authenticationRejected: .terminalAuth + case .rateLimited, .providerUnavailable, .network: .transient + case .parseFailure: .parseFailure + } + } + + var errorDescription: String? { + switch self { + case .noCredentials: + "Sign in with the Command Code CLI, then click Retry." + case .authenticationRejected: + "Command Code session expired. Sign in with the Command Code CLI again." + case .rateLimited: + "Command Code rate-limited the quota request." + case .providerUnavailable: + "Command Code is temporarily unavailable." + case .parseFailure: + "Command Code quota response was malformed." + case .network: + "Network error fetching Command Code quota." + } + } + } + + struct Deps: Sendable { + var loadAPIKey: @Sendable () -> String? + var fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + + static let live = Deps( + loadAPIKey: { + let override = ProcessInfo.processInfo.environment["CODEBURN_COMMANDCODE_DIR"] ?? "" + let root = override.isEmpty + ? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".commandcode") + : URL(fileURLWithPath: override) + return apiKey(fromAuthFile: root.appendingPathComponent("auth.json")) + }, + fetch: { request in + let (data, response) = try await URLSession.shared.data(for: request) + guard let http = response as? HTTPURLResponse else { throw FetchError.network } + return (data, http) + } + ) + } + + static func apiKey(fromAuthFile url: URL) -> String? { + guard let data = try? Data(contentsOf: url), + let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let key = (root["apiKey"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines), + !key.isEmpty else { return nil } + return key + } + + @MainActor + static func refresh(deps: Deps = .live) async throws -> QuotaSummary { + let loadAPIKey = deps.loadAPIKey + guard let key = await Task.detached(operation: { loadAPIKey() }).value else { + throw FetchError.noCredentials + } + + func request(_ url: URL) -> URLRequest { + var request = URLRequest(url: url) + request.httpMethod = "GET" + request.timeoutInterval = timeoutSeconds + request.setValue("application/json", forHTTPHeaderField: "Accept") + request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") + // The API refuses requests without a User-Agent it recognizes. + request.setValue("CodeBurn", forHTTPHeaderField: "User-Agent") + return request + } + + let fetch = deps.fetch + async let subscription = try? fetch(request(subscriptionsURL)) + let data: Data + let response: HTTPURLResponse + do { + (data, response) = try await fetch(request(creditsURL)) + } catch let error as FetchError { + throw error + } catch { + throw FetchError.network + } + + switch response.statusCode { + case 200: break + case 401, 403: throw FetchError.authenticationRejected + case 429: throw FetchError.rateLimited + case 500...599: throw FetchError.providerUnavailable + default: throw FetchError.parseFailure + } + + var planID: String? + if let (body, http) = await subscription, http.statusCode == 200, + let root = try? JSONSerialization.jsonObject(with: body) as? [String: Any] { + planID = (root["data"] as? [String: Any])?["planId"] as? String + } + return try decode(data, planID: planID) + } + + static func decode(_ data: Data, planID: String? = nil) throws -> QuotaSummary { + guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { + throw FetchError.parseFailure + } + let limits = root["windowLimits"] as? [String: Any] ?? [:] + let fiveHour = window("5-hour", limits["fiveHour"]) + let weekly = window("Weekly", limits["weekly"]) + let details = [fiveHour, weekly].compactMap { $0 } + guard !details.isEmpty else { throw FetchError.parseFailure } + return QuotaSummary( + providerFilter: .all, + connection: .connected, + primary: weekly ?? fiveHour, + details: details, + planLabel: planLabel(planID), + footerLines: creditsLine(root["credits"]).map { [$0] } ?? [] + ) + } + + /// "individual-go-v1" -> "Go". Unknown shapes pass through unchanged. + static func planLabel(_ planID: String?) -> String? { + guard var core = planID?.trimmingCharacters(in: .whitespacesAndNewlines), !core.isEmpty else { return nil } + if core.hasPrefix("individual-") { core.removeFirst("individual-".count) } + if let range = core.range(of: "-v[0-9]+$", options: .regularExpression) { core.removeSubrange(range) } + return core.prefix(1).uppercased() + core.dropFirst() + } + + private static func window(_ label: String, _ raw: Any?) -> QuotaSummary.Window? { + guard let row = raw as? [String: Any], + let used = number(row["used"]), + let cap = number(row["cap"]), cap > 0 else { return nil } + let resetAt = number(row["resetAt"]) ?? 0 + return QuotaSummary.Window( + label: label, + percent: min(1, max(0, used / cap)), + resetsAt: resetAt > 0 ? Date(timeIntervalSince1970: resetAt / 1000) : nil + ) + } + + private static func creditsLine(_ raw: Any?) -> String? { + guard let credits = raw as? [String: Any] else { return nil } + let parts = [("monthlyCredits", "monthly"), ("purchasedCredits", "purchased"), ("freeCredits", "free")] + .compactMap { key, name in number(credits[key]).map { (name, $0) } } + guard !parts.isEmpty else { return nil } + let shown = parts.filter { $0.1 > 0 } + guard !shown.isEmpty else { return "Credits left: $0.00" } + return "Credits left: " + shown.map { String(format: "$%.2f %@", $0.1, $0.0) }.joined(separator: ", ") + } + + private static func number(_ value: Any?) -> Double? { + guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil } + let double = number.doubleValue + return double.isFinite ? double : nil + } +} diff --git a/mac/Sources/CodeBurnMenubar/Data/ProviderConnectionCatalog.swift b/mac/Sources/CodeBurnMenubar/Data/ProviderConnectionCatalog.swift index 9e12c0d4..39d96d07 100644 --- a/mac/Sources/CodeBurnMenubar/Data/ProviderConnectionCatalog.swift +++ b/mac/Sources/CodeBurnMenubar/Data/ProviderConnectionCatalog.swift @@ -54,7 +54,8 @@ enum ProviderConnectionCatalog { entry("azureopenai", "Azure OpenAI", [.automatic, .api], [.apiTokenOrCloudCredentials]), entry("claude", "Claude", [.automatic, .api, .web, .cli, .oauth], [.localAppOrCLI, .oauth, .apiTokenOrCloudCredentials, .cookieOrWebSession], live: true), - entry("clinepass", "ClinePass", [.automatic, .api], [.apiTokenOrCloudCredentials], live: true), + entry("clinepass", "ClinePass", [.automatic, .api, .cli], + [.localAppOrCLI, .apiTokenOrCloudCredentials], live: true), entry("cursor", "Cursor", [.automatic, .cli, .web], [.localAppOrCLI, .cookieOrWebSession], live: true), entry("opencode", "OpenCode", [.automatic, .web], [.cookieOrWebSession]), entry("opencodego", "OpenCode Go", [.automatic, .api, .web], @@ -115,7 +116,7 @@ enum ProviderConnectionCatalog { [.localAppOrCLI, .apiTokenOrCloudCredentials]), entry("crof", "Crof", [.automatic, .api], [.apiTokenOrCloudCredentials]), entry("venice", "Venice", [.automatic, .api], [.apiTokenOrCloudCredentials]), - entry("commandcode", "Command Code", [.automatic, .web], [.cookieOrWebSession]), + entry("commandcode", "Command Code", [.automatic, .cli], [.localAppOrCLI], live: true), entry("qoder", "Qoder", [.automatic, .web], [.cookieOrWebSession]), entry("stepfun", "StepFun", [.automatic, .web], [.cookieOrWebSession]), entry("bedrock", "AWS Bedrock", [.automatic, .api], [.apiTokenOrCloudCredentials]), @@ -166,6 +167,10 @@ enum ProviderConnectionCatalog { enum ProviderConnectionGuidance { static func instruction(for provider: CapacityDockProvider) -> String { let methods = provider.catalogEntry.authMethods + // ClinePass rides on the Cline sign-in; there is no ClinePass app. + if provider.id == "clinepass" { + return L("Sign in with Cline, or enter a ClinePass API key below, then click Retry.") + } if methods == [.apiTokenOrCloudCredentials] { return L("Enter an API key or token below, then press Save & Connect.") } diff --git a/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings index 983e1a90..abda7d2e 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings @@ -117,6 +117,7 @@ "Enter an API key or token below, then press Save & Connect." = "Enter an API key or token below, then press Save & Connect."; "Sign in to %@ in a supported browser, then click Retry." = "Sign in to %@ in a supported browser, then click Retry."; "Sign in with the %@ app or CLI, then click Retry." = "Sign in with the %@ app or CLI, then click Retry."; +"Sign in with Cline, or enter a ClinePass API key below, then click Retry." = "Sign in with Cline, or enter a ClinePass API key below, then click Retry."; "Complete %@ OAuth, then click Retry." = "Complete %@ OAuth, then click Retry."; "Start the local %@ service, then click Retry." = "Start the local %@ service, then click Retry."; "Enter the required API or cloud credentials below, then press Save & Connect." = "Enter the required API or cloud credentials below, then press Save & Connect."; diff --git a/mac/Sources/CodeBurnMenubar/Resources/fr.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/fr.lproj/Localizable.strings index 8b9e374d..7f4d32dc 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/fr.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/fr.lproj/Localizable.strings @@ -110,6 +110,7 @@ "Enter an API key or token below, then press Save & Connect." = "Entrez une clé API ou un jeton ci-dessous, puis appuyez sur Enregistrer et connecter."; "Sign in to %@ in a supported browser, then click Retry." = "Connectez-vous à %@ dans un navigateur pris en charge, puis cliquez sur Réessayer."; "Sign in with the %@ app or CLI, then click Retry." = "Connectez-vous via l'app ou la CLI %@, puis cliquez sur Réessayer."; +"Sign in with Cline, or enter a ClinePass API key below, then click Retry." = "Connectez-vous avec Cline, ou entrez une clé API ClinePass ci-dessous, puis cliquez sur Réessayer."; "Complete %@ OAuth, then click Retry." = "Terminez l'authentification OAuth %@, puis cliquez sur Réessayer."; "Start the local %@ service, then click Retry." = "Démarrez le service local %@, puis cliquez sur Réessayer."; "Enter the required API or cloud credentials below, then press Save & Connect." = "Entrez les identifiants API ou cloud requis ci-dessous, puis appuyez sur Enregistrer et connecter."; diff --git a/mac/Sources/CodeBurnMenubar/Resources/ja.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/ja.lproj/Localizable.strings index 6556f95d..2f9136ca 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/ja.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/ja.lproj/Localizable.strings @@ -110,6 +110,7 @@ "Enter an API key or token below, then press Save & Connect." = "下にAPIキーまたはトークンを入力し、「保存して接続」を押してください。"; "Sign in to %@ in a supported browser, then click Retry." = "対応ブラウザで%@にサインインし、「再試行」をクリックしてください。"; "Sign in with the %@ app or CLI, then click Retry." = "%@のアプリまたはCLIでサインインし、「再試行」をクリックしてください。"; +"Sign in with Cline, or enter a ClinePass API key below, then click Retry." = "Clineでサインインするか、下にClinePassのAPIキーを入力して、「再試行」をクリックしてください。"; "Complete %@ OAuth, then click Retry." = "%@のOAuth認証を完了し、「再試行」をクリックしてください。"; "Start the local %@ service, then click Retry." = "ローカルの%@サービスを起動し、「再試行」をクリックしてください。"; "Enter the required API or cloud credentials below, then press Save & Connect." = "下に必要なAPIまたはクラウド認証情報を入力し、「保存して接続」を押してください。"; diff --git a/mac/Sources/CodeBurnMenubar/Resources/ko.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/ko.lproj/Localizable.strings index cef0fd60..605c3c24 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/ko.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/ko.lproj/Localizable.strings @@ -110,6 +110,7 @@ "Enter an API key or token below, then press Save & Connect." = "아래에 API 키 또는 토큰을 입력한 다음 “저장 및 연결”을 누르세요."; "Sign in to %@ in a supported browser, then click Retry." = "지원되는 브라우저에서 %@에 로그인한 다음 “재시도”를 클릭하세요."; "Sign in with the %@ app or CLI, then click Retry." = "%@ 앱 또는 CLI로 로그인한 다음 “재시도”를 클릭하세요."; +"Sign in with Cline, or enter a ClinePass API key below, then click Retry." = "Cline으로 로그인하거나 아래에 ClinePass API 키를 입력한 다음 “재시도”를 클릭하세요."; "Complete %@ OAuth, then click Retry." = "%@ OAuth 인증을 완료한 다음 “재시도”를 클릭하세요."; "Start the local %@ service, then click Retry." = "로컬 %@ 서비스를 실행한 다음 “재시도”를 클릭하세요."; "Enter the required API or cloud credentials below, then press Save & Connect." = "아래에 필요한 API 또는 클라우드 자격 증명을 입력한 다음 “저장 및 연결”을 누르세요."; diff --git a/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings index 9f467e24..2dd43645 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings @@ -111,6 +111,7 @@ "Enter an API key or token below, then press Save & Connect." = "在下方输入 API 密钥或令牌,然后点按“存储并连接”。"; "Sign in to %@ in a supported browser, then click Retry." = "在受支持的浏览器中登录 %@,然后点按“重试”。"; "Sign in with the %@ app or CLI, then click Retry." = "通过 %@ 应用或命令行工具登录,然后点按“重试”。"; +"Sign in with Cline, or enter a ClinePass API key below, then click Retry." = "通过 Cline 登录,或在下方输入 ClinePass API 密钥,然后点按“重试”。"; "Complete %@ OAuth, then click Retry." = "完成 %@ 的 OAuth 授权,然后点按“重试”。"; "Start the local %@ service, then click Retry." = "启动本地 %@ 服务,然后点按“重试”。"; "Enter the required API or cloud credentials below, then press Save & Connect." = "在下方填入所需的 API 或云凭证,然后点按“存储并连接”。"; diff --git a/mac/Sources/CodeBurnMenubar/Resources/zh-Hant.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/zh-Hant.lproj/Localizable.strings index d980ac37..0ede088a 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/zh-Hant.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/zh-Hant.lproj/Localizable.strings @@ -110,6 +110,7 @@ "Enter an API key or token below, then press Save & Connect." = "在下方輸入 API 金鑰或權杖,然後點按“儲存並連線”。"; "Sign in to %@ in a supported browser, then click Retry." = "在受支援的瀏覽器中登入 %@,然後點按“重試”。"; "Sign in with the %@ app or CLI, then click Retry." = "透過 %@ 應用或命令列工具登入,然後點按“重試”。"; +"Sign in with Cline, or enter a ClinePass API key below, then click Retry." = "透過 Cline 登入,或在下方輸入 ClinePass API 金鑰,然後點按“重試”。"; "Complete %@ OAuth, then click Retry." = "完成 %@ 的 OAuth 授權,然後點按“重試”。"; "Start the local %@ service, then click Retry." = "啟動本地 %@ 服務,然後點按“重試”。"; "Enter the required API or cloud credentials below, then press Save & Connect." = "在下方填入所需的 API 或雲憑證,然後點按“儲存並連線”。"; diff --git a/mac/Tests/CodeBurnMenubarTests/CapacityDockConnectionActionTests.swift b/mac/Tests/CodeBurnMenubarTests/CapacityDockConnectionActionTests.swift index 32287ed0..ac08f995 100644 --- a/mac/Tests/CodeBurnMenubarTests/CapacityDockConnectionActionTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/CapacityDockConnectionActionTests.swift @@ -18,12 +18,20 @@ struct CapacityDockConnectionActionTests { @Test("API-only providers route the dock action to credential entry") func apiCredentialActionTitle() { - let provider = CapacityDockProvider(rawValue: "clinepass")! + let provider = CapacityDockProvider(rawValue: "openrouter")! #expect(CapacityDockConnectionAction.reconnect.title(for: provider) == "Add API Key") #expect(ProviderConnectionGuidance.dockInstruction(for: provider) == "Add an API key or token in Provider Settings.") } + @Test("ClinePass reconnects through the Cline sign-in, with a key as the alternative") + func clinePassActionTitle() { + let provider = CapacityDockProvider(rawValue: "clinepass")! + #expect(CapacityDockConnectionAction.reconnect.title(for: provider) == CapacityDockConnectionAction.reconnect.title) + #expect(ProviderConnectionGuidance.dockInstruction(for: provider) == + "Sign in with Cline, or enter a ClinePass API key below, then click Retry.") + } + @Test("active and automatically recovering states do not offer a connection action") func noActionWhileActive() { let states: [QuotaSummary.Connection] = [ diff --git a/mac/Tests/CodeBurnMenubarTests/CapacityDockPresentationTests.swift b/mac/Tests/CodeBurnMenubarTests/CapacityDockPresentationTests.swift index 53234d76..6ab27846 100644 --- a/mac/Tests/CodeBurnMenubarTests/CapacityDockPresentationTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/CapacityDockPresentationTests.swift @@ -413,16 +413,24 @@ struct CapacityDockPresentationTests { @Test("Credential-only providers receive an actionable connection instruction") func apiCredentialGuidance() { - let provider = CapacityDockProvider(rawValue: "clinepass")! + let provider = CapacityDockProvider(rawValue: "openrouter")! #expect(ProviderConnectionGuidance.instruction(for: provider) == "Enter an API key or token below, then press Save & Connect.") } @Test("Browser-session providers receive an actionable connection instruction") func browserSessionGuidance() { + let provider = CapacityDockProvider(rawValue: "qoder")! + #expect(ProviderConnectionGuidance.instruction(for: provider) == + "Sign in to Qoder in a supported browser, then click Retry.") + } + + @Test("Command Code connects from its CLI sign-in") + func commandCodeGuidance() { let provider = CapacityDockProvider(rawValue: "commandcode")! #expect(ProviderConnectionGuidance.instruction(for: provider) == - "Sign in to Command Code in a supported browser, then click Retry.") + "Sign in with the Command Code app or CLI, then click Retry.") + #expect(provider.payloadProviderIDs == ["command-code"]) } @Test("Grok Build offers direct one-click local login discovery") diff --git a/mac/Tests/CodeBurnMenubarTests/CapacityDockProviderQuotaServiceTests.swift b/mac/Tests/CodeBurnMenubarTests/CapacityDockProviderQuotaServiceTests.swift index 6aa44354..f8ea7c79 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 unusedCommandCode: @Sendable () async throws -> QuotaSummary = { + Issue.record("Wrong adapter dispatched") + return Self.summary() + } nonisolated private static let unusedDevin: @Sendable () async throws -> QuotaSummary = { Issue.record("Wrong adapter dispatched") return Self.summary() @@ -38,9 +42,10 @@ struct CapacityDockProviderQuotaServiceTests { let expected = Self.summary(percent: 0.42) let service = CapacityDockProviderQuotaService(dependencies: .init( refreshClinePass: { apiKey in - await capture.record(apiKey) + await capture.record(apiKey ?? "") return expected }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -70,6 +75,7 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -100,6 +106,7 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: { expected }, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -125,6 +132,7 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: { expected }, @@ -150,6 +158,7 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -175,6 +184,7 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -208,6 +218,7 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: refresh, refreshGrok: Self.unusedGrok, @@ -225,13 +236,15 @@ struct CapacityDockProviderQuotaServiceTests { } } - @Test("ClinePass requires its own saved API key") - func requiresClinePassKey() async throws { + @Test("ClinePass without a saved key falls back to the Cline sign-in") + func clinePassWithoutSavedKey() async throws { + let capture = SecretCapture() let service = CapacityDockProviderQuotaService(dependencies: .init( - refreshClinePass: { _ in - Issue.record("Adapter must not run without a key") - return Self.summary() + refreshClinePass: { apiKey in + await capture.record(apiKey ?? "") + throw ClinePassSubscriptionService.FetchError.noCredentials }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -241,22 +254,80 @@ struct CapacityDockProviderQuotaServiceTests { )) let provider = try #require(CapacityDockProvider(rawValue: "clinepass")) - await #expect(throws: CapacityDockProviderFetchFailure.self) { - try await service.fetch( - provider: provider, - credential: CapacityDockProviderCredential(sourceMode: "api", apiKey: " ") - ) - } - do { _ = try await service.fetch( provider: provider, - credential: CapacityDockProviderCredential(sourceMode: "api", apiKey: "") + credential: CapacityDockProviderCredential(sourceMode: "api", apiKey: " ") ) - Issue.record("Expected a terminal missing-key failure") + Issue.record("Expected a terminal missing-credential failure") } catch let failure as CapacityDockProviderFetchFailure { #expect(failure.disposition == .terminal) - #expect(failure.message == "Enter a ClinePass API key or token, then press Save & Connect.") + #expect(failure.message == "Sign in with Cline, or enter a ClinePass API key, then click Retry.") + } + #expect(await capture.values == [""]) + } + + @Test("An expired Cline sign-in is retried with its guidance; a rejected key is terminal") + func clinePassExpiredSignInIsTransient() async throws { + let provider = try #require(CapacityDockProvider(rawValue: "clinepass")) + let cases: [(ClinePassSubscriptionService.FetchError, CapacityDockProviderFetchFailureDisposition)] = [ + (.signInExpired, .transient), + (.authenticationRejected, .terminal), + (.noCredentials, .terminal), + ] + for (error, expectedDisposition) in cases { + let service = CapacityDockProviderQuotaService(dependencies: .init( + refreshClinePass: { _ in throw error }, + refreshCommandCode: Self.unusedCommandCode, + refreshCursor: Self.unusedCursor, + refreshDevin: Self.unusedDevin, + refreshGrok: Self.unusedGrok, + refreshGrokBot: Self.unusedGrokBot, + refreshZai: Self.unusedZai, + refreshZcode: Self.unusedZcode + )) + 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("Command Code dispatches to the CLI key and an expired session is terminal") + func dispatchesCommandCode() async throws { + let expected = Self.summary(percent: 0.5) + let provider = try #require(CapacityDockProvider(rawValue: "commandcode")) + let cases: [(@Sendable () async throws -> QuotaSummary, CapacityDockProviderFetchFailureDisposition?)] = [ + ({ expected }, nil), + ({ throw CommandCodeSubscriptionService.FetchError.noCredentials }, .terminal), + ({ throw CommandCodeSubscriptionService.FetchError.authenticationRejected }, .terminal), + ({ throw CommandCodeSubscriptionService.FetchError.network }, .transient), + ({ throw CommandCodeSubscriptionService.FetchError.parseFailure }, .transient), + ] + for (refresh, expectedDisposition) in cases { + let service = CapacityDockProviderQuotaService(dependencies: .init( + refreshClinePass: { _ in + Issue.record("Wrong adapter dispatched") + return Self.summary() + }, + refreshCommandCode: refresh, + refreshCursor: Self.unusedCursor, + refreshDevin: Self.unusedDevin, + refreshGrok: Self.unusedGrok, + refreshGrokBot: Self.unusedGrokBot, + refreshZai: Self.unusedZai, + refreshZcode: Self.unusedZcode + )) + do { + let result = try await service.fetch(provider: provider, credential: CapacityDockProviderCredential()) + #expect(expectedDisposition == nil) + #expect(result == expected) + } catch let failure as CapacityDockProviderFetchFailure { + #expect(failure.disposition == expectedDisposition) + } } } @@ -267,6 +338,7 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -293,6 +365,7 @@ struct CapacityDockProviderQuotaServiceTests { func classifiesAuthenticationFailure() async throws { let service = CapacityDockProviderQuotaService(dependencies: .init( refreshClinePass: { _ in throw ClinePassSubscriptionService.FetchError.authenticationRejected }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -322,6 +395,7 @@ struct CapacityDockProviderQuotaServiceTests { for error in errors { let service = CapacityDockProviderQuotaService(dependencies: .init( refreshClinePass: { _ in throw error }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -362,6 +436,7 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: { throw error }, @@ -399,6 +474,7 @@ struct CapacityDockProviderQuotaServiceTests { Issue.record("Wrong adapter dispatched") return Self.summary() }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, @@ -434,6 +510,7 @@ struct CapacityDockProviderQuotaServiceTests { await gate.pause() return Self.summary(percent: 0.73) }, + refreshCommandCode: Self.unusedCommandCode, refreshCursor: Self.unusedCursor, refreshDevin: Self.unusedDevin, refreshGrok: Self.unusedGrok, diff --git a/mac/Tests/CodeBurnMenubarTests/ClinePassQuotaTests.swift b/mac/Tests/CodeBurnMenubarTests/ClinePassQuotaTests.swift index b2d2a081..0c5bede5 100644 --- a/mac/Tests/CodeBurnMenubarTests/ClinePassQuotaTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/ClinePassQuotaTests.swift @@ -39,16 +39,109 @@ final class ClinePassQuotaTests: XCTestCase { private static func makeDeps( recorder: RequestRecorder, + ambient: ClinePassSubscriptionService.Credential? = nil, respond: @escaping @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) ) -> ClinePassSubscriptionService.Deps { ClinePassSubscriptionService.Deps( fetch: { request in recorder.record(request) return try await respond(request) - } + }, + loadAmbientCredential: { ambient }, + now: { Date(timeIntervalSince1970: 1_800_000_000) } ) } + private static func providersFile(_ settings: String) -> Data { + #"{"providers":{"cline":{"settings":\#(settings)},"anthropic":{"settings":{"apiKey":"other"}}}}"# + .data(using: .utf8)! + } + + func testCredentialFilePrefersAccessTokenThenApiKeyThenAuthApiKey() { + let oauth = ClinePassSubscriptionService.fileCredential(Self.providersFile( + #"{"apiKey":"k1","auth":{"accessToken":"workos:tok","apiKey":"k2","expiresAt":1800000060000}}"#)) + XCTAssertEqual(oauth, .init(token: "workos:tok", isOAuth: true, expiresAt: Date(timeIntervalSince1970: 1_800_000_060))) + XCTAssertEqual( + ClinePassSubscriptionService.fileCredential(Self.providersFile(#"{"auth":{"accessToken":"bare"}}"#))?.token, + "workos:bare") + XCTAssertEqual( + ClinePassSubscriptionService.fileCredential(Self.providersFile(#"{"apiKey":"k1","auth":{"apiKey":"k2"}}"#)), + .init(token: "k1", isOAuth: false, expiresAt: nil)) + XCTAssertEqual( + ClinePassSubscriptionService.fileCredential(Self.providersFile(#"{"auth":{"apiKey":"k2"}}"#))?.token, "k2") + XCTAssertNil(ClinePassSubscriptionService.fileCredential(Self.providersFile(#"{"provider":"cline"}"#))) + } + + func testProvidersFileFollowsClineOverrides() { + let home = URL(fileURLWithPath: "/home/u") + let path = { (env: [String: String]) in + ClinePassSubscriptionService.providersFileURL(environment: env, home: home).path + } + XCTAssertEqual(path([:]), "/home/u/.cline/data/settings/providers.json") + XCTAssertEqual(path(["CLINE_DIR": "~/c"]), "/home/u/c/data/settings/providers.json") + XCTAssertEqual(path(["CLINE_DIR": "/c", "CLINE_DATA_DIR": "/d"]), "/d/settings/providers.json") + XCTAssertEqual(path(["CLINE_DATA_DIR": "/d", "CLINE_PROVIDER_SETTINGS_PATH": "/f.json"]), "/f.json") + } + + func testWithoutSavedKeyUsesTheClineSession() async throws { + let recorder = RequestRecorder() + let deps = Self.makeDeps( + recorder: recorder, + ambient: .init(token: "workos:session", isOAuth: true, expiresAt: Date(timeIntervalSince1970: 1_800_000_060)) + ) { request in + (Self.successBody.data(using: .utf8)!, Self.httpResponse(request, status: 200)) + } + _ = try await ClinePassSubscriptionService.refresh(apiKey: " ", deps: deps) + _ = try await ClinePassSubscriptionService.refresh(apiKey: Self.syntheticKey, deps: deps) + XCTAssertEqual( + recorder.requests.map { $0.value(forHTTPHeaderField: "Authorization") }, + ["Bearer workos:session", "Bearer \(Self.syntheticKey)"]) + } + + func testExpiredClineSessionStopsBeforeTheNetwork() async { + let recorder = RequestRecorder() + let deps = Self.makeDeps( + recorder: recorder, + ambient: .init(token: "workos:old", isOAuth: true, expiresAt: Date(timeIntervalSince1970: 1_799_999_999)) + ) { request in + (Self.successBody.data(using: .utf8)!, Self.httpResponse(request, status: 200)) + } + do { + _ = try await ClinePassSubscriptionService.refresh(apiKey: nil, deps: deps) + XCTFail("Expected an expired sign-in") + } catch { + XCTAssertEqual(error as? ClinePassSubscriptionService.FetchError, .signInExpired) + XCTAssertEqual(error.localizedDescription, "Cline sign-in expired. Run cline to refresh it.") + XCTAssertEqual((error as? ClinePassSubscriptionService.FetchError)?.classification, .transient) + } + XCTAssertTrue(recorder.requests.isEmpty) + } + + func testRejectedClineSessionReadsAsExpiredAndMissingCredentialIsTerminal() async { + let recorder = RequestRecorder() + let rejected = Self.makeDeps( + recorder: recorder, + ambient: .init(token: "workos:revoked", isOAuth: true, expiresAt: nil) + ) { request in + (Data("{}".utf8), Self.httpResponse(request, status: 401)) + } + do { + _ = try await ClinePassSubscriptionService.refresh(apiKey: nil, deps: rejected) + XCTFail("Expected an expired sign-in") + } catch { + XCTAssertEqual(error as? ClinePassSubscriptionService.FetchError, .signInExpired) + } + let none = Self.makeDeps(recorder: recorder) { request in + (Data("{}".utf8), Self.httpResponse(request, status: 200)) + } + do { + _ = try await ClinePassSubscriptionService.refresh(apiKey: nil, deps: none) + XCTFail("Expected missing credentials") + } catch { + XCTAssertEqual(error as? ClinePassSubscriptionService.FetchError, .noCredentials) + } + } + func testSuccessfulPayloadMapsFiveHourWeeklyAndMonthlyWindows() async throws { let recorder = RequestRecorder() let deps = Self.makeDeps(recorder: recorder) { request in diff --git a/mac/Tests/CodeBurnMenubarTests/CommandCodeQuotaTests.swift b/mac/Tests/CodeBurnMenubarTests/CommandCodeQuotaTests.swift new file mode 100644 index 00000000..a1184acd --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/CommandCodeQuotaTests.swift @@ -0,0 +1,108 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +@Suite("Command Code quota") +@MainActor +struct CommandCodeQuotaTests { + private final class RequestRecorder: @unchecked Sendable { + private(set) var requests: [URLRequest] = [] + func record(_ request: URLRequest) { requests.append(request) } + } + + nonisolated private static let creditsBody = """ + {"credits":{"monthlyCredits":3.9706645399,"purchasedCredits":0,"freeCredits":0}, + "windowLimits":{"limited":true,"exceeded":"weekly", + "fiveHour":{"used":0.75,"cap":3,"exceeded":false,"resetAt":0}, + "weekly":{"used":6.0293354601,"cap":6,"exceeded":true,"resetAt":1791653049551}}} + """ + nonisolated private static let subscriptionBody = #"{"success":true,"data":{"status":"active","planId":"individual-go-v1"}}"# + + nonisolated private static func response(_ request: URLRequest, _ status: Int) -> HTTPURLResponse { + HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)! + } + + private static func deps( + key: String? = "synthetic-commandcode-key", + recorder: RequestRecorder = RequestRecorder(), + respond: @escaping @Sendable (URLRequest) throws -> (Data, HTTPURLResponse) + ) -> CommandCodeSubscriptionService.Deps { + CommandCodeSubscriptionService.Deps( + loadAPIKey: { key }, + fetch: { request in + recorder.record(request) + return try respond(request) + } + ) + } + + @Test("maps both windows, the plan and the remaining credits") + func decodesLiveShape() async throws { + let recorder = RequestRecorder() + let summary = try await CommandCodeSubscriptionService.refresh(deps: Self.deps(recorder: recorder) { request in + let body = request.url == CommandCodeSubscriptionService.creditsURL ? Self.creditsBody : Self.subscriptionBody + return (Data(body.utf8), Self.response(request, 200)) + }) + #expect(summary.details.map(\.label) == ["5-hour", "Weekly"]) + #expect(summary.details.map(\.percent) == [0.25, 1]) + #expect(summary.details[0].resetsAt == nil) + #expect(summary.details[1].resetsAt == Date(timeIntervalSince1970: 1_791_653_049.551)) + #expect(summary.primary?.label == "Weekly") + #expect(summary.planLabel == "Go") + #expect(summary.footerLines == ["Credits left: $3.97 monthly"]) + #expect(recorder.requests.count == 2) + for request in recorder.requests { + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer synthetic-commandcode-key") + #expect(request.value(forHTTPHeaderField: "User-Agent") == "CodeBurn") + } + } + + @Test("a failed subscription call only drops the plan label") + func subscriptionFailureKeepsWindows() async throws { + let summary = try await CommandCodeSubscriptionService.refresh(deps: Self.deps { request in + request.url == CommandCodeSubscriptionService.creditsURL + ? (Data(Self.creditsBody.utf8), Self.response(request, 200)) + : (Data("{}".utf8), Self.response(request, 500)) + }) + #expect(summary.planLabel == nil) + #expect(summary.details.count == 2) + } + + @Test("missing key, rejected key and bad bodies map to their errors") + func errors() async { + let noKey = Self.deps(key: nil) { _ in + Issue.record("must not fetch without a key") + throw URLError(.badURL) + } + await #expect(throws: CommandCodeSubscriptionService.FetchError.noCredentials) { + try await CommandCodeSubscriptionService.refresh(deps: noKey) + } + let cases: [(Int, String, CommandCodeSubscriptionService.FetchError)] = [ + (401, "{}", .authenticationRejected), + (429, "{}", .rateLimited), + (503, "{}", .providerUnavailable), + (200, #"{"windowLimits":{}}"#, .parseFailure), + ] + for (status, body, expected) in cases { + await #expect(throws: expected) { + try await CommandCodeSubscriptionService.refresh(deps: Self.deps { request in + (Data(body.utf8), Self.response(request, status)) + }) + } + } + await #expect(throws: CommandCodeSubscriptionService.FetchError.network) { + try await CommandCodeSubscriptionService.refresh(deps: Self.deps { _ in throw URLError(.notConnectedToInternet) }) + } + } + + @Test("plan labels and the auth file") + func planLabelAndAuthFile() throws { + #expect(CommandCodeSubscriptionService.planLabel("individual-pro-v1") == "Pro") + #expect(CommandCodeSubscriptionService.planLabel("") == nil) + let file = FileManager.default.temporaryDirectory.appendingPathComponent("cc-auth-\(UUID().uuidString).json") + defer { try? FileManager.default.removeItem(at: file) } + try Data(#"{"apiKey":" synthetic ","userName":"x"}"#.utf8).write(to: file) + #expect(CommandCodeSubscriptionService.apiKey(fromAuthFile: file) == "synthetic") + #expect(CommandCodeSubscriptionService.apiKey(fromAuthFile: file.appendingPathExtension("missing")) == nil) + } +} diff --git a/mac/Tests/CodeBurnMenubarTests/ProviderConnectionCatalogTests.swift b/mac/Tests/CodeBurnMenubarTests/ProviderConnectionCatalogTests.swift index 03fd8e08..51b76902 100644 --- a/mac/Tests/CodeBurnMenubarTests/ProviderConnectionCatalogTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/ProviderConnectionCatalogTests.swift @@ -34,8 +34,8 @@ struct ProviderConnectionCatalogTests { func pinnedSourceModeCoverage() { let providers = ProviderConnectionCatalog.providers #expect(providers.count(with: .automatic) == 71) - #expect(providers.count(with: .web) == 29) - #expect(providers.count(with: .cli) == 17) + #expect(providers.count(with: .web) == 28) + #expect(providers.count(with: .cli) == 19) #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", "devin", "gemini", "grok", "grokbot", "kimi", "zai", "zcode"]) + #expect(live == ["antigravity", "claude", "clinepass", "codex", "commandcode", "copilot", "cursor", "devin", "gemini", "grok", "grokbot", "kimi", "zai", "zcode"]) } } diff --git a/src/quota/clinepass.ts b/src/quota/clinepass.ts index 37eb8c48..a8dd7458 100644 --- a/src/quota/clinepass.ts +++ b/src/quota/clinepass.ts @@ -4,16 +4,20 @@ // - GET https://api.cline.bot/api/v1/users/me/plan/usage-limits // Bearer API key, one 5-hour / weekly / monthly window each. // -// Credential: ClinePass has no local login file to read; the key is one the -// user supplies. On the Mac that is a CodeBurn Keychain entry, and the CLI's -// equivalent is the environment: CLINEPASS_API_KEY, then CLINE_API_KEY. The +// Credential: CLINEPASS_API_KEY, then CLINE_API_KEY, then the session the +// Cline CLI keeps in ~/.cline/data/settings/providers.json (read-only, never +// refreshed or written; an expired session asks the user to run cline). The // key is used for one request and never persisted or logged. -import { quotaRequestSignal, sanitizeError } from './security.js' +import os from 'node:os' +import path from 'node:path' + +import { quotaRequestSignal, readSecureFile, sanitizeError } from './security.js' import type { QuotaProvider, QuotaWindow } from './types.js' const USAGE_ENDPOINT = 'https://api.cline.bot/api/v1/users/me/plan/usage-limits' const API_KEY_VARS = ['CLINEPASS_API_KEY', 'CLINE_API_KEY'] as const const REJECTED_FOOTER = ['ClinePass rejected this API key.'] +const EXPIRED_FOOTER = ['Cline sign-in expired. Run cline to refresh it.'] const RATE_LIMITED_FOOTER = ['ClinePass rate-limited the quota request.'] const UNAVAILABLE_FOOTER = ['ClinePass is temporarily unavailable.'] const PARSE_FOOTER = ['ClinePass quota response was malformed.'] @@ -23,10 +27,13 @@ const WINDOW_LABELS: Record = { five_hour: '5-hour', weekly: 'We export type ClinePassDeps = { fetch: typeof fetch env: NodeJS.ProcessEnv + readFile: typeof readSecureFile + homeDir: string + now: () => number } function defaultDeps(): ClinePassDeps { - return { fetch: globalThis.fetch, env: process.env } + return { fetch: globalThis.fetch, env: process.env, readFile: readSecureFile, homeDir: os.homedir(), now: Date.now } } function empty(connection: QuotaProvider['connection'], footerLines: string[] = []): QuotaProvider { @@ -41,6 +48,41 @@ export function clinePassApiKey(env: NodeJS.ProcessEnv): string | null { return null } +/** Cline's own lookup order: a settings file override, then a data dir, then a Cline dir. */ +export function clineProvidersPath(env: NodeJS.ProcessEnv, homeDir: string): string { + const resolve = (name: string): string | null => { + const value = env[name]?.trim() + if (!value) return null + if (value === '~') return homeDir + return value.startsWith('~/') ? path.join(homeDir, value.slice(2)) : value + } + const file = resolve('CLINE_PROVIDER_SETTINGS_PATH') + if (file) return file + const dataDir = resolve('CLINE_DATA_DIR') ?? path.join(resolve('CLINE_DIR') ?? path.join(homeDir, '.cline'), 'data') + return path.join(dataDir, 'settings', 'providers.json') +} + +export type ClineFileCredential = { token: string; oauth: boolean; expiresAt: number | null } + +/** Matches Cline's getApiKey: the OAuth access token wins over keys kept in the same entry. */ +export function parseClineProviders(raw: string): ClineFileCredential | null { + const root = JSON.parse(raw) as { providers?: { cline?: { settings?: Record } } } + const settings = root?.providers?.cline?.settings + if (!settings || typeof settings !== 'object') return null + const auth = settings['auth'] && typeof settings['auth'] === 'object' ? settings['auth'] : {} + const clean = (value: unknown) => typeof value === 'string' && value.trim() ? value.trim() : null + const access = clean(auth.accessToken) + if (access) { + return { + token: access.startsWith('workos:') ? access : `workos:${access}`, + oauth: true, + expiresAt: num(auth.expiresAt), + } + } + const key = clean(settings['apiKey']) ?? clean(auth.apiKey) + return key ? { token: key, oauth: false, expiresAt: null } : null +} + function num(value: unknown): number | null { return typeof value === 'number' && Number.isFinite(value) ? value : null } @@ -97,15 +139,23 @@ export type ClinePassResult = { quota: QuotaProvider; retryAfterSeconds?: number export async function fetchClinePassQuota(options: Partial & { signal?: AbortSignal } = {}): Promise { const deps = { ...defaultDeps(), ...options } - const key = clinePassApiKey(deps.env) - if (!key) return { quota: empty('disconnected') } - try { + const envKey = clinePassApiKey(deps.env) + const file = envKey ? null : await deps.readFile(clineProvidersPath(deps.env, deps.homeDir), 1024 * 1024) + const credential = envKey ? { token: envKey, oauth: false, expiresAt: null } : file ? parseClineProviders(file) : null + if (!credential) return { quota: empty('disconnected') } + // Not terminal: running cline refreshes the session file this only reads, + // so the next scheduled read recovers on its own. + if (credential.oauth && credential.expiresAt !== null && credential.expiresAt <= deps.now()) { + return { quota: empty('transientFailure', EXPIRED_FOOTER) } + } const response = await deps.fetch(USAGE_ENDPOINT, { method: 'GET', signal: quotaRequestSignal(options.signal), - headers: { Accept: 'application/json', Authorization: `Bearer ${key}`, 'User-Agent': 'CodeBurn' }, + headers: { Accept: 'application/json', Authorization: `Bearer ${credential.token}`, 'User-Agent': 'CodeBurn' }, }) - if (response.status === 401 || response.status === 403) return { quota: empty('terminalFailure', REJECTED_FOOTER) } + if (response.status === 401 || response.status === 403) { + return { quota: credential.oauth ? empty('transientFailure', EXPIRED_FOOTER) : empty('terminalFailure', REJECTED_FOOTER) } + } if (response.status === 429) { const raw = response.headers.get('Retry-After') const seconds = raw === null ? NaN : Number(raw) diff --git a/src/quota/commandcode.ts b/src/quota/commandcode.ts new file mode 100644 index 00000000..49b66faf --- /dev/null +++ b/src/quota/commandcode.ts @@ -0,0 +1,140 @@ +// Live Command Code quota from its billing endpoints: +// +// - GET https://api.commandcode.ai/alpha/billing/credits +// windowLimits.{fiveHour,weekly}.{used,cap,resetAt}: USD credits spent of +// the window's cap; resetAt is epoch ms, 0 while no window is open. +// credits.{monthlyCredits,purchasedCredits,freeCredits}: USD remaining. +// - GET https://api.commandcode.ai/alpha/billing/subscriptions +// data.planId for the plan label; optional, a failure only drops the label. +// +// Credential: the CLI's own ~/.commandcode/auth.json `apiKey`, read-only. +// The API refuses requests without a User-Agent, so one is always sent. +import os from 'node:os' +import path from 'node:path' + +import { fraction, quotaRequestSignal, readSecureFile, sanitizeError } from './security.js' +import type { QuotaProvider, QuotaWindow } from './types.js' + +const API_BASE = 'https://api.commandcode.ai/alpha/billing' +const EXPIRED_FOOTER = ['Command Code session expired. Sign in with the Command Code CLI again.'] +const RATE_LIMITED_FOOTER = ['Command Code rate-limited the quota request.'] +const UNAVAILABLE_FOOTER = ['Command Code is temporarily unavailable.'] +const PARSE_FOOTER = ['Command Code quota response was malformed.'] + +export type CommandCodeDeps = { + fetch: typeof fetch + authPath: string + readFile: typeof readSecureFile +} + +function defaultDeps(): CommandCodeDeps { + const root = process.env['CODEBURN_COMMANDCODE_DIR'] || path.join(os.homedir(), '.commandcode') + return { fetch: globalThis.fetch, authPath: path.join(root, 'auth.json'), readFile: readSecureFile } +} + +function empty(connection: QuotaProvider['connection'], footerLines: string[] = []): QuotaProvider { + return { provider: 'commandcode', connection, primary: null, details: [], planLabel: null, footerLines } +} + +function num(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) ? value : null +} + +function windowOf(label: string, raw: unknown): QuotaWindow | null { + if (!raw || typeof raw !== 'object') return null + const row = raw as Record + const used = num(row['used']) + const cap = num(row['cap']) + if (used === null || cap === null || cap <= 0) return null + const resetAt = num(row['resetAt']) + return { + label, + percent: fraction(used / cap * 100)!, + resetsAt: resetAt !== null && resetAt > 0 ? new Date(resetAt).toISOString() : null, + } +} + +/** "individual-go-v1" -> "Go". Unknown shapes pass through unchanged. */ +export function commandCodePlanLabel(planId: unknown): string | null { + if (typeof planId !== 'string' || !planId.trim()) return null + const core = planId.trim().replace(/^individual-/, '').replace(/-v\d+$/, '') + return core.charAt(0).toUpperCase() + core.slice(1) +} + +function creditsNote(raw: unknown): string | null { + if (!raw || typeof raw !== 'object') return null + const credits = raw as Record + const parts = ([['monthlyCredits', 'monthly'], ['purchasedCredits', 'purchased'], ['freeCredits', 'free']] as const) + .map(([key, name]) => ({ name, value: num(credits[key]) })) + .filter((part): part is { name: typeof part.name; value: number } => part.value !== null) + if (parts.length === 0) return null + const shown = parts.filter(part => part.value > 0) + if (shown.length === 0) return 'Credits left: $0.00' + return `Credits left: ${shown.map(part => `$${part.value.toFixed(2)} ${part.name}`).join(', ')}` +} + +/** `null` when neither window is readable. */ +export function decodeCommandCodeCredits(body: unknown, planId?: unknown): QuotaProvider | null { + if (!body || typeof body !== 'object') return null + const root = body as Record + const limits = root['windowLimits'] && typeof root['windowLimits'] === 'object' + ? root['windowLimits'] as Record + : {} + const fiveHour = windowOf('5-hour', limits['fiveHour']) + const weekly = windowOf('Weekly', limits['weekly']) + const details = [fiveHour, weekly].filter((row): row is QuotaWindow => row !== null) + if (details.length === 0) return null + const note = creditsNote(root['credits']) + return { + provider: 'commandcode', connection: 'connected', + primary: weekly ?? fiveHour!, + details, + planLabel: commandCodePlanLabel(planId), + footerLines: note ? [note] : [], + ...(note ? { notes: [note] } : {}), + } +} + +async function readApiKey(deps: CommandCodeDeps): Promise { + const raw = await deps.readFile(deps.authPath, 64 * 1024) + if (!raw) return null + const key = (JSON.parse(raw) as Record)['apiKey'] + return typeof key === 'string' && key.trim() ? key.trim() : null +} + +export type CommandCodeResult = { quota: QuotaProvider; retryAfterSeconds?: number } + +export async function fetchCommandCodeQuota(options: Partial & { signal?: AbortSignal } = {}): Promise { + const deps = { ...defaultDeps(), ...options } + try { + const key = await readApiKey(deps) + if (!key) return { quota: empty('disconnected') } + + const signal = quotaRequestSignal(options.signal) + const get = (endpoint: string) => deps.fetch(`${API_BASE}/${endpoint}`, { + method: 'GET', signal, + headers: { Accept: 'application/json', Authorization: `Bearer ${key}`, 'User-Agent': 'CodeBurn' }, + }) + const [credits, subscription] = await Promise.all([get('credits'), get('subscriptions').catch(() => null)]) + if (credits.status === 401 || credits.status === 403) return { quota: empty('terminalFailure', EXPIRED_FOOTER) } + if (credits.status === 429) { + const raw = credits.headers.get('Retry-After') + const seconds = raw === null ? NaN : Number(raw) + return { + quota: { ...empty('transientFailure', RATE_LIMITED_FOOTER), rateLimited: true }, + retryAfterSeconds: Math.max(Number.isFinite(seconds) ? Math.ceil(seconds) : 300, 60), + } + } + if (credits.status >= 500) return { quota: empty('transientFailure', UNAVAILABLE_FOOTER) } + if (!credits.ok) return { quota: empty('transientFailure', PARSE_FOOTER) } + // Never log either body - they carry account data. + const planId = subscription?.ok + ? await subscription.json().then(body => (body as { data?: { planId?: unknown } })?.data?.planId, () => undefined) + : undefined + const quota = decodeCommandCodeCredits(await credits.json(), planId) + return { quota: quota ?? empty('transientFailure', PARSE_FOOTER) } + } catch (error) { + console.warn(`Command Code quota unavailable: ${sanitizeError(error)}`) + return { quota: empty('transientFailure') } + } +} diff --git a/src/quota/index.ts b/src/quota/index.ts index 22f573a7..51f501bc 100644 --- a/src/quota/index.ts +++ b/src/quota/index.ts @@ -17,6 +17,7 @@ import { fetchAntigravityQuota } from './antigravity.js' import { fetchClaudeQuota } from './claude.js' import { fetchClinePassQuota } from './clinepass.js' import { fetchCodexQuota } from './codex.js' +import { fetchCommandCodeQuota } from './commandcode.js' import { fetchCopilotQuota } from './copilot.js' import { fetchCursorQuota } from './cursor.js' import { fetchDevinQuota } from './devin.js' @@ -90,6 +91,7 @@ const READERS: { id: ProviderName; name: string; read: ProviderReader }[] = [ { id: 'grokbot', name: 'Grok Bot', read: async signal => (await fetchGrokbotQuota({ signal })).quota }, { id: 'clinepass', name: 'ClinePass', read: async signal => (await fetchClinePassQuota({ signal })).quota }, { id: 'devin', name: 'Devin', read: async () => (await fetchDevinQuota()).quota }, + { id: 'commandcode', name: 'Command Code', read: async signal => (await fetchCommandCodeQuota({ signal })).quota }, ] /** Grok Bot is an optional desktop app rather than a signed-in account. With diff --git a/src/quota/types.ts b/src/quota/types.ts index abdd95a7..6c8d6ede 100644 --- a/src/quota/types.ts +++ b/src/quota/types.ts @@ -5,7 +5,7 @@ export type QuotaWindow = { } export type QuotaProvider = { - provider: 'claude' | 'codex' | 'gemini' | 'copilot' | 'antigravity' | 'kimi' | 'cursor' | 'zai' | 'zcode' | 'grok' | 'grokbot' | 'clinepass' | 'devin' + provider: 'claude' | 'codex' | 'gemini' | 'copilot' | 'antigravity' | 'kimi' | 'cursor' | 'zai' | 'zcode' | 'grok' | 'grokbot' | 'clinepass' | 'devin' | 'commandcode' connection: 'connected' | 'disconnected' | 'accessDenied' | 'loading' | 'stale' | 'transientFailure' | 'terminalFailure' primary: QuotaWindow | null details: QuotaWindow[] diff --git a/tests/quota-clinepass.test.ts b/tests/quota-clinepass.test.ts index a3d81045..5857bb1c 100644 --- a/tests/quota-clinepass.test.ts +++ b/tests/quota-clinepass.test.ts @@ -1,12 +1,22 @@ // Fixture-driven coverage for the ClinePass quota adapter, ported from the // menubar's ClinePassQuotaTests. The key is synthetic and every request goes // through the injected fetch. +import { join } from 'node:path' + import { describe, expect, it } from 'vitest' -import { clinePassApiKey, decodeClinePassUsage, fetchClinePassQuota } from '../src/quota/clinepass.js' +import { + clinePassApiKey, clineProvidersPath, decodeClinePassUsage, fetchClinePassQuota, parseClineProviders, +} from '../src/quota/clinepass.js' const neverFetch = (() => { throw new Error('the test must not reach the network') }) as unknown as typeof fetch const SYNTHETIC_KEY = 'synthetic-clinepass-test-key' +const noFile = async () => null +const NOW = 1_800_000_000_000 + +function providersFile(settings: unknown): string { + return JSON.stringify({ version: 1, providers: { cline: { settings }, anthropic: { settings: { apiKey: 'other-provider-key' } } } }) +} const successBody = { success: true, @@ -32,9 +42,56 @@ describe('ClinePass credential discovery', () => { }) it('reports disconnected with no key and never fetches', async () => { - const result = await fetchClinePassQuota({ env: {}, fetch: neverFetch }) + const result = await fetchClinePassQuota({ env: {}, fetch: neverFetch, readFile: noFile }) expect(result.quota.connection).toBe('disconnected') }) + + it('follows Cline\'s settings path overrides', () => { + expect(clineProvidersPath({}, '/home/u')).toBe(join('/home/u', '.cline', 'data', 'settings', 'providers.json')) + expect(clineProvidersPath({ CLINE_DIR: '~/c' }, '/home/u')).toBe(join('/home/u', 'c', 'data', 'settings', 'providers.json')) + expect(clineProvidersPath({ CLINE_DIR: '/c', CLINE_DATA_DIR: '/d' }, '/home/u')).toBe(join('/d', 'settings', 'providers.json')) + expect(clineProvidersPath({ CLINE_DATA_DIR: '/d', CLINE_PROVIDER_SETTINGS_PATH: '/f.json' }, '/home/u')).toBe('/f.json') + }) + + it('prefers the OAuth access token, then apiKey, then auth.apiKey', () => { + expect(parseClineProviders(providersFile({ apiKey: 'k1', auth: { accessToken: 'workos:tok', apiKey: 'k2', expiresAt: NOW } }))) + .toEqual({ token: 'workos:tok', oauth: true, expiresAt: NOW }) + expect(parseClineProviders(providersFile({ auth: { accessToken: 'bare' } }))?.token).toBe('workos:bare') + expect(parseClineProviders(providersFile({ apiKey: 'k1', auth: { apiKey: 'k2' } }))).toEqual({ token: 'k1', oauth: false, expiresAt: null }) + expect(parseClineProviders(providersFile({ auth: { apiKey: 'k2' } }))?.token).toBe('k2') + expect(parseClineProviders(providersFile({ provider: 'cline' }))).toBeNull() + expect(parseClineProviders(JSON.stringify({ providers: {} }))).toBeNull() + }) + + it('sends the Cline session token when no key is set, and a key wins over it', async () => { + const seen: string[] = [] + const file = providersFile({ auth: { accessToken: 'workos:session-token', expiresAt: NOW + 60_000 } }) + const fetchSpy = (async (_url: string, init: RequestInit) => { + seen.push((init.headers as Record)['Authorization']!) + return jsonResponse(successBody) + }) as unknown as typeof fetch + const viaFile = await fetchClinePassQuota({ env: {}, fetch: fetchSpy, readFile: async () => file, now: () => NOW }) + expect(viaFile.quota.connection).toBe('connected') + await fetchClinePassQuota({ env: { CLINE_API_KEY: SYNTHETIC_KEY }, fetch: fetchSpy, readFile: async () => file, now: () => NOW }) + expect(seen).toEqual(['Bearer workos:session-token', `Bearer ${SYNTHETIC_KEY}`]) + }) + + it('stops at an expired Cline session without fetching, as a retryable failure', async () => { + const file = providersFile({ auth: { accessToken: 'workos:old', expiresAt: NOW - 1 } }) + const result = await fetchClinePassQuota({ env: {}, fetch: neverFetch, readFile: async () => file, now: () => NOW }) + expect(result.quota.connection).toBe('transientFailure') + expect(result.quota.footerLines).toEqual(['Cline sign-in expired. Run cline to refresh it.']) + }) + + it('reads a rejected session token as an expired sign-in', async () => { + const file = providersFile({ auth: { accessToken: 'workos:revoked' } }) + const result = await fetchClinePassQuota({ + env: {}, readFile: async () => file, now: () => NOW, + fetch: (async () => jsonResponse({}, 401)) as unknown as typeof fetch, + }) + expect(result.quota.connection).toBe('transientFailure') + expect(result.quota.footerLines).toEqual(['Cline sign-in expired. Run cline to refresh it.']) + }) }) describe('ClinePass quota decoding', () => { diff --git a/tests/quota-commandcode.test.ts b/tests/quota-commandcode.test.ts new file mode 100644 index 00000000..d414c892 --- /dev/null +++ b/tests/quota-commandcode.test.ts @@ -0,0 +1,112 @@ +// Fixture-driven coverage for the Command Code quota adapter. The key is +// synthetic and every request goes through the injected fetch. +import { describe, expect, it } from 'vitest' + +import { commandCodePlanLabel, decodeCommandCodeCredits, fetchCommandCodeQuota } from '../src/quota/commandcode.js' + +const neverFetch = (() => { throw new Error('the test must not reach the network') }) as unknown as typeof fetch +const AUTH = JSON.stringify({ apiKey: 'synthetic-commandcode-key', userName: 'someone' }) +const RESET_MS = 1_791_653_049_551 + +const creditsBody = { + credits: { belowThreshold: false, creditThreshold: 0, monthlyCredits: 3.9706645399, purchasedCredits: 0, freeCredits: 0 }, + windowLimits: { + limited: true, + exceeded: 'weekly', + fiveHour: { used: 0.75, cap: 3, exceeded: false, resetAt: 0 }, + weekly: { used: 6.0293354601, cap: 6, exceeded: true, resetAt: RESET_MS }, + }, +} +const subscriptionBody = { success: true, data: { status: 'active', planId: 'individual-go-v1', currentPeriodEnd: '2026-11-01T10:38:29.000Z' } } + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) +} + +describe('Command Code quota decoding', () => { + it('maps the 5-hour and weekly windows as used of cap, clamped', () => { + const quota = decodeCommandCodeCredits(creditsBody, 'individual-go-v1') + expect(quota?.connection).toBe('connected') + expect(quota?.details).toEqual([ + { label: '5-hour', percent: 0.25, resetsAt: null }, + { label: 'Weekly', percent: 1, resetsAt: new Date(RESET_MS).toISOString() }, + ]) + expect(quota?.primary?.label).toBe('Weekly') + expect(quota?.planLabel).toBe('Go') + expect(quota?.notes).toEqual(['Credits left: $3.97 monthly']) + }) + + it('skips an unreadable window and rejects a body with none', () => { + const quota = decodeCommandCodeCredits({ windowLimits: { fiveHour: { used: 1, cap: 0 }, weekly: { used: 3, cap: 6, resetAt: 0 } } }) + expect(quota?.details).toEqual([{ label: 'Weekly', percent: 0.5, resetsAt: null }]) + expect(quota?.notes).toBeUndefined() + expect(decodeCommandCodeCredits({ windowLimits: {} })).toBeNull() + expect(decodeCommandCodeCredits({ credits: {} })).toBeNull() + expect(decodeCommandCodeCredits(null)).toBeNull() + }) + + it('labels plans from their id', () => { + expect(commandCodePlanLabel('individual-pro-v1')).toBe('Pro') + expect(commandCodePlanLabel('team-max')).toBe('Team-max') + expect(commandCodePlanLabel('')).toBeNull() + expect(commandCodePlanLabel(undefined)).toBeNull() + }) +}) + +describe('Command Code quota fetch', () => { + it('is disconnected without an auth file and never fetches', async () => { + const result = await fetchCommandCodeQuota({ authPath: '/nope', readFile: async () => null, fetch: neverFetch }) + expect(result.quota.connection).toBe('disconnected') + }) + + it('sends the key as a bearer with a User-Agent to both billing endpoints', async () => { + const seen: { url: string; headers: Record }[] = [] + const result = await fetchCommandCodeQuota({ + authPath: '/auth.json', readFile: async () => AUTH, + fetch: (async (url: string, init: RequestInit) => { + seen.push({ url, headers: init.headers as Record }) + return jsonResponse(url.endsWith('/credits') ? creditsBody : subscriptionBody) + }) as unknown as typeof fetch, + }) + expect(result.quota.connection).toBe('connected') + expect(result.quota.planLabel).toBe('Go') + expect(seen.map(row => row.url).sort()).toEqual([ + 'https://api.commandcode.ai/alpha/billing/credits', + 'https://api.commandcode.ai/alpha/billing/subscriptions', + ]) + for (const row of seen) { + expect(row.headers['Authorization']).toBe('Bearer synthetic-commandcode-key') + expect(row.headers['User-Agent']).toBe('CodeBurn') + } + }) + + it('keeps the windows when only the subscription call fails', async () => { + const result = await fetchCommandCodeQuota({ + authPath: '/auth.json', readFile: async () => AUTH, + fetch: (async (url: string) => url.endsWith('/credits') ? jsonResponse(creditsBody) : jsonResponse({}, 500)) as unknown as typeof fetch, + }) + expect(result.quota.connection).toBe('connected') + expect(result.quota.planLabel).toBeNull() + }) + + it('maps HTTP failures', async () => { + const respond = (status: number) => fetchCommandCodeQuota({ + authPath: '/auth.json', readFile: async () => AUTH, + fetch: (async () => jsonResponse({}, status)) as unknown as typeof fetch, + }) + const expired = await respond(401) + expect(expired.quota.connection).toBe('terminalFailure') + expect(expired.quota.footerLines).toEqual(['Command Code session expired. Sign in with the Command Code CLI again.']) + expect((await respond(429)).quota.rateLimited).toBe(true) + expect((await respond(503)).quota.connection).toBe('transientFailure') + expect((await respond(200)).quota.footerLines).toEqual(['Command Code quota response was malformed.']) + }) + + it('treats a network error as transient', async () => { + const result = await fetchCommandCodeQuota({ + authPath: '/auth.json', readFile: async () => AUTH, + fetch: (async () => { throw new TypeError('fetch failed') }) as unknown as typeof fetch, + }) + expect(result.quota.connection).toBe('transientFailure') + }) +}) diff --git a/windows/src/Settings.tsx b/windows/src/Settings.tsx index c4d573f4..08d62070 100644 --- a/windows/src/Settings.tsx +++ b/windows/src/Settings.tsx @@ -16,7 +16,7 @@ import { AboutPane } from './settings/AboutPane' /// provider search, General and About, then one row per provider that has a live quota /// adapter, driving a detail pane on the right. -/// The twelve readers `codeburn quota` registers, in the CLI's own order. Only a fallback: the +/// The fourteen readers `codeburn quota` registers, in the CLI's own order. Only a fallback: the /// quota store's answer is what the sidebar normally lists, so a provider the CLI grows /// appears here without a code change. const KNOWN_PROVIDERS: Array<{ id: string; name: string }> = [ @@ -31,6 +31,7 @@ const KNOWN_PROVIDERS: Array<{ id: string; name: string }> = [ { id: 'grok', name: 'Grok' }, { id: 'clinepass', name: 'ClinePass' }, { id: 'devin', name: 'Devin' }, + { id: 'commandcode', name: 'Command Code' }, ] const MAIN_PANES = ['general', 'about'] diff --git a/windows/src/providerIcons.tsx b/windows/src/providerIcons.tsx index 9aae10b1..0253c3ec 100644 --- a/windows/src/providerIcons.tsx +++ b/windows/src/providerIcons.tsx @@ -14,6 +14,8 @@ type Glyph = { d: string | string[] transform?: string fillRule?: 'evenodd' | 'nonzero' + /** Stroke width for a mark drawn as an outline rather than a fill. */ + stroke?: number } const GLYPHS: Record = { @@ -62,6 +64,11 @@ const GLYPHS: Record = { viewBox: '0 0 466.73 487.04', d: 'M463.6,275.08l-29.26-58.75v-33.83c0-56.08-45.01-101.5-100.53-101.5h-50.01c3.62-7.43,5.61-15.79,5.61-24.61,0-31.17-25.08-56.39-56.07-56.39s-56.07,25.22-56.07,56.39c0,8.82,1.99,17.17,5.61,24.61h-50.01c-55.51,0-100.52,45.42-100.52,101.5v33.83l-29.87,58.59c-3.01,5.9-3.01,12.92,0,18.81l29.87,57.93v33.83c0,56.08,45.01,101.5,100.52,101.5h200.95c55.51,0,100.53-45.42,100.53-101.5v-33.83l29.21-58.13c2.9-5.79,2.9-12.61.05-18.46ZM202.75,322.96c0,25.48-20.54,46.14-45.88,46.14s-45.88-20.66-45.88-46.14v-82.02c0-25.48,20.54-46.14,45.88-46.14s45.88,20.66,45.88,46.14v82.02ZM350.58,322.96c0,25.48-20.54,46.14-45.88,46.14s-45.88-20.66-45.88-46.14v-82.02c0-25.48,20.54-46.14,45.88-46.14s45.88,20.66,45.88,46.14v82.02Z', }, + commandcode: { + viewBox: '0 0 100 100', + d: 'M38 38H27C20.925 38 16 33.075 16 27C16 20.925 20.925 16 27 16C33.075 16 38 20.925 38 27V73C38 79.075 33.075 84 27 84C20.925 84 16 79.075 16 73C16 66.925 20.925 62 27 62H73C79.075 62 84 66.925 84 73C84 79.075 79.075 84 73 84C66.925 84 62 79.075 62 73V27C62 20.925 66.925 16 73 16C79.075 16 84 20.925 84 27C84 33.075 79.075 38 73 38H38V62', + stroke: 9, + }, devin: { viewBox: "0 0 24 24", d: "M12 2.25c1.18 0 2.18.76 2.54 1.82a8.1 8.1 0 0 1 2.04.85 2.68 2.68 0 0 1 3.08.5 2.68 2.68 0 0 1 .5 3.08c.4.64.69 1.33.85 2.04A2.68 2.68 0 0 1 22.75 13c0 1.18-.76 2.18-1.82 2.54a8.1 8.1 0 0 1-.85 2.04 2.68 2.68 0 0 1-.5 3.08 2.68 2.68 0 0 1-3.08.5 8.1 8.1 0 0 1-2.04.85A2.68 2.68 0 0 1 12 23.75a2.68 2.68 0 0 1-2.54-1.82 8.1 8.1 0 0 1-2.04-.85 2.68 2.68 0 0 1-3.08-.5 2.68 2.68 0 0 1-.5-3.08 8.1 8.1 0 0 1-.85-2.04A2.68 2.68 0 0 1 1.25 13c0-1.18.76-2.18 1.82-2.54.16-.71.45-1.4.85-2.04a2.68 2.68 0 0 1 .5-3.08 2.68 2.68 0 0 1 3.08-.5c.64-.4 1.33-.69 2.04-.85A2.68 2.68 0 0 1 12 2.25Zm0 3.5a6.25 6.25 0 1 0 0 12.5 6.25 6.25 0 0 0 0-12.5Zm0 3.25a3 3 0 1 1 0 6 3 3 0 0 1 0-6Z", @@ -110,6 +117,7 @@ const ALIASES: Record = { 'kilo-code': 'kilo', 'ibm-bob': 'ibmbob', + 'command-code': 'commandcode', kimicode: 'kimi', 'cursor-agent': 'cursor', @@ -197,8 +205,9 @@ export function ProviderGlyph({ id, size }: { id: string; size: number }) { key={d.slice(0, 24)} d={d} transform={glyph.transform} - fill="currentColor" - fillRule={glyph.fillRule ?? 'evenodd'} + {...(glyph.stroke + ? { fill: 'none', stroke: 'currentColor', strokeWidth: glyph.stroke, strokeLinecap: 'round' as const, strokeLinejoin: 'round' as const } + : { fill: 'currentColor', fillRule: glyph.fillRule ?? 'evenodd' })} /> ))} diff --git a/windows/src/settings/ProviderPane.tsx b/windows/src/settings/ProviderPane.tsx index d3a2d58d..393aedb3 100644 --- a/windows/src/settings/ProviderPane.tsx +++ b/windows/src/settings/ProviderPane.tsx @@ -27,8 +27,9 @@ const GUIDANCE: Record = { cursor: 'Sign in to the Cursor app, then click Retry.', zai: 'Sign in with the Pi CLI, or set ZAI_API_KEY, then click Retry.', grok: 'Sign in with the Grok CLI, then click Retry.', - clinepass: 'Set CLINEPASS_API_KEY, then click Retry.', + clinepass: 'Sign in with Cline (run `cline auth`), or set CLINEPASS_API_KEY, then click Retry.', devin: 'Run the Devin CLI once to sign in, then click Retry.', + commandcode: 'Sign in with the Command Code CLI, then click Retry.', } /// The mac's "How it works" sections, with the Windows paths. Every one of these is @@ -43,8 +44,9 @@ const HOW_IT_WORKS: Record = { cursor: 'Cursor quota opens the Cursor editor state database read-only for its access token, then asks cursor.com. Nothing is written back, so an expired token can only be refreshed by signing in to Cursor again.', zai: 'Z.ai quota uses a supplied API key if there is one, and otherwise the Z.ai login the Pi CLI keeps in %USERPROFILE%\\.pi\\agent\\auth.json.', grok: 'Grok Build quota reads %USERPROFILE%\\.grok\\auth.json, preferring the current OIDC scope over an older sign-in entry.', - clinepass: 'ClinePass has no local login file, so the only credential is an API key.', + clinepass: 'ClinePass quota uses CLINEPASS_API_KEY or CLINE_API_KEY if set, and otherwise the Cline sign-in in %USERPROFILE%\\.cline\\data\\settings\\providers.json, read-only. Only Cline refreshes that sign-in, so if it shows as expired, run cline once and click Retry.', devin: 'Devin quota reads the plan status the Devin CLI caches in %USERPROFILE%\\.cache\\devin\\cli, read-only. Nothing is sent anywhere and no API key is used, so the numbers are as fresh as the CLI\'s last run.', + commandcode: 'Command Code quota reads the API key the Command Code CLI keeps in %USERPROFILE%\\.commandcode\\auth.json, read-only, and asks Command Code for the 5-hour and weekly windows and the credits left.', } type Props = {