diff --git a/Sources/CodeCaps/MiMoQuotaSettings.swift b/Sources/CodeCaps/MiMoQuotaSettings.swift new file mode 100644 index 00000000..909ef8ce --- /dev/null +++ b/Sources/CodeCaps/MiMoQuotaSettings.swift @@ -0,0 +1,90 @@ +import Foundation +import SwiftUI +import QuotaCore + +actor MiMoQuotaCredentialStore { + static let shared = MiMoQuotaCredentialStore() + private let account = "quota-api-key-v1" + private let service = TokenStore.serviceName(suffix: "mimo-quota-api-key", bundleIdentifier: Bundle.main.bundleIdentifier) + private lazy var cache = TokenCache(calls: .live, bounds: .init(), ownServices: [service], log: { _ in }) + + func load() async -> MiMoTokenPlanCredential? { + guard let raw = await cache.token(server: account, service: service), + let credential = try? JSONDecoder().decode(MiMoTokenPlanCredential.self, from: Data(raw.utf8)), + credential.isValid else { return nil } + return credential + } + + func save(_ credential: MiMoTokenPlanCredential) async throws { + guard credential.isValid else { throw CredentialError.invalid } + let raw = String(decoding: try JSONEncoder().encode(credential), as: UTF8.self) + try await cache.save(raw, server: account, service: service) + } + + enum CredentialError: Error { case invalid } + + func clear() async throws { + try await cache.delete(server: account, service: service) + } +} + +@MainActor +struct MiMoQuotaSettings: View { + @ObservedObject var model: MonitorModel + @State private var draft = "" + @State private var region = MiMoTokenPlanRegion.singapore + @State private var message: String? + @State private var busy = false + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + Picker("MiMo Token Plan region", selection: $region) { + ForEach(MiMoTokenPlanRegion.allCases, id: \.self) { value in + Text(value.title).tag(value) + } + } + SecureField("Individual Token Plan key", text: $draft) + HStack { + Button("Save MiMo Key") { save() } + .disabled(busy || !MiMoTokenPlanCredential(key: draft, region: region).isValid) + Button("Remove MiMo Key") { clear() } + .disabled(busy) + } + if let message { Text(message).font(.caption) } + Text("The key stays in this Mac’s Keychain. Choose the region shown on your MiMo Token Plan page.") + .font(.caption) + .foregroundStyle(.secondary) + } + .task { + if let saved = await MiMoQuotaCredentialStore.shared.load() { region = saved.region } + } + } + + private func save() { + let credential = MiMoTokenPlanCredential(key: draft, region: region) + guard credential.isValid else { return } + busy = true + Task { @MainActor in + defer { busy = false } + do { + try await MiMoQuotaCredentialStore.shared.save(credential) + draft = "" + model.tokenPlanCredentialChanged(enabled: true) + message = "MiMo key saved." + } catch { message = "CodeCaps could not save the MiMo key in Keychain." } + } + } + + private func clear() { + busy = true + Task { @MainActor in + defer { busy = false } + do { + try await MiMoQuotaCredentialStore.shared.clear() + draft = "" + model.tokenPlanCredentialChanged(enabled: false) + message = "MiMo key removed." + } catch { message = "CodeCaps could not remove the MiMo key from Keychain." } + } + } +} diff --git a/Sources/CodeCaps/MonitorModel.swift b/Sources/CodeCaps/MonitorModel.swift index 81dca0cc..ad31511f 100644 --- a/Sources/CodeCaps/MonitorModel.swift +++ b/Sources/CodeCaps/MonitorModel.swift @@ -1368,6 +1368,15 @@ final class MonitorModel: ObservableObject { if providerChecksEnabled || serverEnabled { refreshProviderChecks() } } + func tokenPlanCredentialChanged(enabled: Bool) { + let readerID = "mimo-token-plan" + if isOptionalQuotaReaderEnabled(readerID) { + // Flush the prior account's reading before showing a replacement. + setOptionalQuotaReaderEnabled(false, readerID: readerID) + } + if enabled { setOptionalQuotaReaderEnabled(true, readerID: readerID) } + } + private func zAIQuotaSetupChanged() { invalidateRefresh() if let providerResult { @@ -3842,6 +3851,8 @@ final class MonitorModel: ObservableObject { ) async -> LocalQuotaResult { let registry = LocalQuotaReaderRegistry.configured(zCodeCredentialProvider: { await ZAIQuotaCredentialStore.shared.load() + }, mimoCredentialProvider: { + await MiMoQuotaCredentialStore.shared.load() }) async let registered = registry.read(preferences: preferences) async let antigravity = AntigravitySummaryReader().read() diff --git a/Sources/CodeCaps/SettingsViews.swift b/Sources/CodeCaps/SettingsViews.swift index 4444035f..2c4ef1cc 100644 --- a/Sources/CodeCaps/SettingsViews.swift +++ b/Sources/CodeCaps/SettingsViews.swift @@ -483,6 +483,7 @@ struct SettingsSourcesFleetPage: View { ForEach(ReaderStatus.all, id: \.providerKey) { reader in readerRow(reader) if reader.optionalReaderID == "zcode" { ZAIQuotaSettingsView(controller: model.zAIQuotaSetup) } + if reader.optionalReaderID == "mimo-token-plan" { MiMoQuotaSettings(model: model) } } } header: { Eyebrow("THIS MAC") @@ -1019,6 +1020,8 @@ struct ReaderStatus { ReaderStatus(providerKey: "minimax", label: "MiniMax", source: "MiniMax CLI credentials"), ReaderStatus(providerKey: "kimi", label: "Kimi", source: "Kimi Code credentials", optionalReaderID: "kimi"), ReaderStatus(providerKey: "zcode", label: "Z.ai / ZCode", source: "ZCode credentials", optionalReaderID: "zcode"), + ReaderStatus(providerKey: "alibaba-token-plan", label: "Alibaba Token Plan", source: "Bailian CLI console sign-in", optionalReaderID: "alibaba-token-plan"), + ReaderStatus(providerKey: "mimo-token-plan", label: "Xiaomi MiMo Token Plan", source: "MiMo Token Plan key", optionalReaderID: "mimo-token-plan"), ] } @@ -1987,14 +1990,14 @@ struct SettingsInfisicalPage: View { let client = clientId.trimmingCharacters(in: .whitespacesAndNewlines) let retained = authentication == .serviceToken ? existing?.serviceToken : (existing?.clientId == client ? existing?.clientSecret : nil) - let secret = credential.isEmpty ? (retained ?? "") : credential.trimmingCharacters(in: .whitespacesAndNewlines) + let selectedCredential = credential.isEmpty ? (retained ?? "") : credential.trimmingCharacters(in: .whitespacesAndNewlines) var binding = InfisicalBinding(id: editingID ?? UUID().uuidString, label: label.trimmingCharacters(in: .whitespacesAndNewlines), siteURL: url, projectId: projectId.trimmingCharacters(in: .whitespacesAndNewlines), environment: environment.trimmingCharacters(in: .whitespacesAndNewlines), secretPath: folder.trimmingCharacters(in: .whitespacesAndNewlines), authentication: authentication, access: access) - if authentication == .serviceToken { binding.serviceToken = secret } - else { binding.clientId = client; binding.clientSecret = secret } + if authentication == .serviceToken { binding.serviceToken = selectedCredential } + else { binding.clientId = client; binding.clientSecret = selectedCredential } var candidate = latest candidate.bindings.removeAll { $0.id == binding.id } candidate.bindings.append(binding) diff --git a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift index a513a55a..e88032ef 100644 --- a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift +++ b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift @@ -88,6 +88,13 @@ public struct LocalQuotaReaderRegistry: Sendable { /// The optional Z.ai factory resolves its saved regional key when selected, otherwise using the ZCode sign-in chain. public static func configured( zCodeCredentialProvider: @escaping @Sendable () async -> ZCodeQuotaCredential? + ) -> LocalQuotaReaderRegistry { + configured(zCodeCredentialProvider: zCodeCredentialProvider, mimoCredentialProvider: { nil }) + } + + public static func configured( + zCodeCredentialProvider: @escaping @Sendable () async -> ZCodeQuotaCredential?, + mimoCredentialProvider: @escaping @Sendable () async -> MiMoTokenPlanCredential? ) -> LocalQuotaReaderRegistry { LocalQuotaReaderRegistry(registrations: [ LocalQuotaReaderRegistration(id: "local-primary", label: "Built-In Provider Sessions", @@ -112,6 +119,12 @@ public struct LocalQuotaReaderRegistry: Sendable { LocalQuotaReaderRegistration(id: "zcode", label: "Z.ai / ZCode", configurationMetadata: ["providerKey": "zcode"], isOptional: true) { ZCodeQuotaReader(credential: zCodeCredentialProvider) }, + LocalQuotaReaderRegistration(id: "alibaba-token-plan", label: "Alibaba Token Plan", isOptional: true) { + AlibabaTokenPlanReader() + }, + LocalQuotaReaderRegistration(id: "mimo-token-plan", label: "Xiaomi MiMo Token Plan", isOptional: true) { + MiMoTokenPlanReader(credential: mimoCredentialProvider) + }, ]) } } diff --git a/Sources/QuotaCore/QuotaModels.swift b/Sources/QuotaCore/QuotaModels.swift index e63b1ff0..f69ee650 100644 --- a/Sources/QuotaCore/QuotaModels.swift +++ b/Sources/QuotaCore/QuotaModels.swift @@ -508,7 +508,7 @@ public enum QuotaLocalScope { fleet: [QuotaWindow], adopted: [QuotaWindow], localProviders: Set, - expectedKeys: [String] = expectedQuotaProviderKeys + expectedKeys: [String] = fleetFallbackQuotaProviderKeys ) -> (fallback: [QuotaWindow], superseded: [QuotaWindow]) { var fallback: [QuotaWindow] = [] var superseded: [QuotaWindow] = [] @@ -1136,6 +1136,13 @@ enum QuotaProviders { Expected(key: "zcode", label: "ZCode", via: nil), ] + // Recognize these windows without creating permanent "no report" rows for + // users who have not opted into their local readers. + static let optionalTokenPlanLabels: [String: String] = [ + "alibaba-token-plan": "Alibaba Token Plan", + "mimo-token-plan": "Xiaomi MiMo Token Plan", + ] + static func canonicalKey(provider: String, providerKey: String?, via: String?) -> String { if let viaLower = via?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { if viaLower == "antigravity" { @@ -1177,7 +1184,7 @@ enum QuotaProviders { } static func label(for key: String) -> String { - expected.first(where: { $0.key == key })?.label ?? key + expected.first(where: { $0.key == key })?.label ?? optionalTokenPlanLabels[key] ?? key } } @@ -1186,6 +1193,11 @@ enum QuotaProviders { public let expectedQuotaProviderKeys: [String] = QuotaProviders.expected.map(\.key) public let EXPECTED_QUOTA_PROVIDERS: [String] = expectedQuotaProviderKeys +/// Providers that may show an actual fleet reading without requiring a +/// permanent placeholder on devices that have not configured the reader. +public let fleetFallbackQuotaProviderKeys: [String] = + expectedQuotaProviderKeys + QuotaProviders.optionalTokenPlanLabels.keys.sorted() + public func quotaProviderKey(_ provider: String, providerKey: String? = nil, via: String? = nil) -> String { QuotaProviders.canonicalKey(provider: provider, providerKey: providerKey, via: via) } diff --git a/Sources/QuotaCore/QuotaReaderPreferences.swift b/Sources/QuotaCore/QuotaReaderPreferences.swift index 04ce1ec8..b6f7c109 100644 --- a/Sources/QuotaCore/QuotaReaderPreferences.swift +++ b/Sources/QuotaCore/QuotaReaderPreferences.swift @@ -1,8 +1,8 @@ import Foundation /// Per-device choices for optional local quota readers. Missing entries stay -/// enabled so existing installations and readers added by a later app version -/// keep the current automatic-read behavior until the owner changes it. +/// enabled for established readers. New Token Plan readers require explicit +/// opt-in because they invoke a signed-in CLI or use a stored provider key. public struct QuotaReaderPreferences: Codable, Equatable, Sendable { public static let defaultsKey = "optionalQuotaReaders" public var enabledByReaderID: [String: Bool] @@ -12,7 +12,7 @@ public struct QuotaReaderPreferences: Codable, Equatable, Sendable { } public func isEnabled(_ readerID: String) -> Bool { - enabledByReaderID[readerID] ?? true + enabledByReaderID[readerID] ?? !["alibaba-token-plan", "mimo-token-plan"].contains(readerID) } public mutating func setEnabled(_ enabled: Bool, for readerID: String) { diff --git a/Sources/QuotaCore/TokenPlanQuotaReader.swift b/Sources/QuotaCore/TokenPlanQuotaReader.swift new file mode 100644 index 00000000..e3680ae0 --- /dev/null +++ b/Sources/QuotaCore/TokenPlanQuotaReader.swift @@ -0,0 +1,184 @@ +import Foundation + +public enum MiMoTokenPlanRegion: String, Codable, CaseIterable, Sendable { + case china = "cn", singapore = "sgp", europe = "ams" + + public var title: String { + switch self { + case .china: return "China" + case .singapore: return "Singapore" + case .europe: return "Europe" + } + } + + // Only Xiaomi's documented cluster hosts can receive the key. + var quotaURL: URL { + URL(string: "https://token-plan-\(rawValue).xiaomimimo.com/v1/platform/token_plan")! + } +} + +public struct MiMoTokenPlanCredential: Codable, Sendable { + public let key: String + public let region: MiMoTokenPlanRegion + + public init(key: String, region: MiMoTokenPlanRegion) { + self.key = key.trimmingCharacters(in: .whitespacesAndNewlines) + self.region = region + } + + public var isValid: Bool { + key.hasPrefix("tp-") && (4...512).contains(key.utf8.count) + && key.utf8.allSatisfy { + (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) + || $0 == 45 || $0 == 95 + } + } +} + +struct MiMoTokenPlanReader: LocalQuotaReading { + let credential: @Sendable () async -> MiMoTokenPlanCredential? + + func read() async -> LocalQuotaResult { + let id = "mimo-token-plan" + guard let credential = await credential(), credential.isValid else { + return LocalQuotaResult(issues: [id: "Save an individual MiMo Token Plan key in Sources & Fleet."]) + } + var request = URLRequest(url: credential.region.quotaURL) + request.httpMethod = "GET" + request.setValue("Bearer \(credential.key)", forHTTPHeaderField: "Authorization") + request.setValue("application/json", forHTTPHeaderField: "Accept") + do { + let (data, response) = try await BoundedHTTPFetch.data(for: request, timeout: 8, maxBytes: 32_768) + if [401, 403].contains(response.statusCode) { + return LocalQuotaResult(issues: [id: "MiMo rejected the plan key. Check its selected region and validity."]) + } + if (200..<300).contains(response.statusCode), + let window = TokenPlanQuotaParser.mimo(data, now: Date()) { + return LocalQuotaResult(windows: [window]) + } + } catch {} + return LocalQuotaResult(issues: [id: "MiMo did not return a current Token Plan quota."]) + } +} + +struct AlibabaTokenPlanReader: LocalQuotaReading { + func read() async -> LocalQuotaResult { + let id = "alibaba-token-plan" + let home = FileManager.default.homeDirectoryForCurrentUser + let paths = [home.appendingPathComponent(".local/bin/bl").path, "/opt/homebrew/bin/bl", "/usr/local/bin/bl"] + guard let path = paths.first(where: { FileManager.default.isExecutableFile(atPath: $0) }) else { + return LocalQuotaResult(issues: [id: "Install the official Bailian CLI and sign in to its console."]) + } + do { + let data = try await BoundedQuotaProcess().run( + path: path, arguments: ["usage", "token-plan", "--output", "json"], + home: home, timeout: 15, maxBytes: 32_768) + let windows = TokenPlanQuotaParser.alibaba(data, now: Date()) + if !windows.isEmpty { return LocalQuotaResult(windows: windows) } + } catch {} + return LocalQuotaResult(issues: [id: "Bailian did not report a current Token Plan quota. Check its console login."]) + } +} + +enum TokenPlanQuotaParser { + private struct MiMoResponse: Decodable { + let object: String + let period: Period + let quota: Quota + + struct Period: Decodable { + let startAt: String + let endAt: String + } + + struct Quota: Decodable { + let totalCredits: Int64 + let usedCredits: Int64 + let remainingCredits: Int64 + } + } + + static func mimo(_ data: Data, now: Date) -> QuotaWindow? { + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + guard let payload = try? decoder.decode(MiMoResponse.self, from: data), payload.object == "token_plan", + let start = utcDate(payload.period.startAt), let end = utcDate(payload.period.endAt), + start <= now, now < end else { return nil } + let q = payload.quota + guard q.totalCredits > 0, q.usedCredits >= 0, q.remainingCredits >= 0, + q.remainingCredits == max(0, q.totalCredits - q.usedCredits) else { return nil } + let remaining = 100 * Double(q.remainingCredits) / Double(q.totalCredits) + let id = "mimo-token-plan" + return QuotaWindow( + id: id + ":cycle", provider: id, providerKey: id, providerLabel: "Xiaomi MiMo Token Plan", + label: "Billing cycle", remainingPercent: remaining, absoluteRemaining: Double(q.remainingCredits), + absoluteLimit: Double(q.totalCredits), quotaUnit: "credits", isExhausted: remaining == 0, + resetAt: iso(end), window: "billing cycle", status: .derived(remainingPercent: remaining), + occurredAt: iso(now), source: "mimo-token-plan-api", periodStart: iso(start)) + } + + static func alibaba(_ data: Data, now: Date) -> [QuotaWindow] { + guard let payload = try? JSONDecoder().decode([String: JSONValue].self, from: data), + payload["hasQuotaData"]?.value != .boolean(false) else { return [] } + let id = "alibaba-token-plan" + let patterns = try? NSRegularExpression(pattern: "^per([1-9][0-9]{0,2})(Hour|Day|Week|Month)Percentage$") + guard let patterns else { return [] } + return payload.keys.sorted().compactMap { key in + guard let match = patterns.firstMatch(in: key, range: NSRange(key.startIndex.. 0, ms < 10_000_000_000_000 else { return nil } + let date = Date(timeIntervalSince1970: ms / 1000) + guard date > now else { return nil } + reset = iso(date) + } else { + reset = nil + } + let label = count == "1" && unit == "month" ? "Monthly" : "\(count) \(unit)\(count == "1" ? "" : "s")" + let remaining = 100 * (1 - used) + return QuotaWindow( + id: id + ":" + suffix, provider: id, providerKey: id, providerLabel: "Alibaba Token Plan", + label: label, remainingPercent: remaining, isExhausted: remaining == 0, + resetAt: reset, window: label.lowercased(), status: .derived(remainingPercent: remaining), + occurredAt: iso(now), source: "bailian-cli") + } + } + + private struct JSONValue: Decodable { + enum Value: Equatable { case boolean(Bool), number(Double), other } + let value: Value + + var number: Double? { + if case .number(let amount) = value { return amount } + return nil + } + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let result = try? container.decode(Bool.self) { value = .boolean(result) } + else if let result = try? container.decode(Double.self) { value = .number(result) } + else { value = .other } + } + } + + private static func utcDate(_ raw: String) -> Date? { + if let date = ISO8601DateFormatter().date(from: raw) { return date } + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" + formatter.isLenient = false + guard let date = formatter.date(from: raw), formatter.string(from: date) == raw else { return nil } + return date + } + + private static func iso(_ date: Date) -> String { + ISO8601DateFormatter().string(from: date) + } +} diff --git a/Tests/QuotaCoreTests/TokenPlanQuotaReaderTests.swift b/Tests/QuotaCoreTests/TokenPlanQuotaReaderTests.swift new file mode 100644 index 00000000..3507eb74 --- /dev/null +++ b/Tests/QuotaCoreTests/TokenPlanQuotaReaderTests.swift @@ -0,0 +1,82 @@ +import Foundation +import XCTest +@testable import QuotaCore + +final class TokenPlanQuotaReaderTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + func testAlibabaUsesOnlyReportedWindows() throws { + let data = Data(#"{"per1MonthPercentage":0.4,"per1MonthResetTime":1800964800000,"hasQuotaData":true}"#.utf8) + let window = try XCTUnwrap(TokenPlanQuotaParser.alibaba(data, now: now).first) + XCTAssertEqual(window.remainingPercent, 60) + XCTAssertEqual(window.label, "Monthly") + XCTAssertNotNil(window.resetAt) + XCTAssertEqual(TokenPlanQuotaParser.alibaba(data, now: now).count, 1) + XCTAssertNil(window.absoluteLimit) + } + + func testAlibabaMissingQuotaOrMalformedWindowDoesNotLookFull() { + for raw in [ + #"{"hasQuotaData":false,"per1MonthPercentage":0}"#, + #"{"per1MonthPercentage":true}"#, + #"{"per1MonthPercentage":0,"per1MonthResetTime":1790000000000}"#, + #"{"per1MonthPercentage":1.1}"#, + ] { + XCTAssertTrue(TokenPlanQuotaParser.alibaba(Data(raw.utf8), now: now).isEmpty) + } + } + + func testMiMoKeepsCreditsAndVendorPeriod() throws { + let data = Data(#"{"object":"token_plan","period":{"start_at":"2026-09-21 23:59:59","end_at":"2027-09-21 23:59:59"},"quota":{"total_credits":4100000000,"used_credits":1025000000,"remaining_credits":3075000000}}"#.utf8) + let window = try XCTUnwrap(TokenPlanQuotaParser.mimo(data, now: now)) + XCTAssertEqual(window.remainingPercent, 75) + XCTAssertEqual(window.absoluteLimit, 4_100_000_000) + XCTAssertEqual(window.periodStart, "2026-09-21T23:59:59Z") + XCTAssertEqual(window.resetAt, "2027-09-21T23:59:59Z") + XCTAssertEqual(window.quotaUnit, "credits") + } + + func testMiMoRefusesInvalidCreditsAndExpiredCycle() { + let data = Data(#"{"object":"token_plan","period":{"start_at":"2026-09-21 23:59:59","end_at":"2027-09-21 23:59:59"},"quota":{"total_credits":100,"used_credits":30,"remaining_credits":99}}"#.utf8) + XCTAssertNil(TokenPlanQuotaParser.mimo(data, now: now)) + let exhausted = Data(#"{"object":"token_plan","period":{"start_at":"2026-09-21 23:59:59","end_at":"2027-09-21 23:59:59"},"quota":{"total_credits":100,"used_credits":120,"remaining_credits":0}}"#.utf8) + XCTAssertEqual(TokenPlanQuotaParser.mimo(exhausted, now: now)?.status, .exhausted) + XCTAssertNil(TokenPlanQuotaParser.mimo(exhausted, now: Date(timeIntervalSince1970: 2_000_000_000))) + } + + func testMiMoRequestHostsAreFixedRegionalXiaomiOrigins() { + let hosts = MiMoTokenPlanRegion.allCases.map { $0.quotaURL.host ?? "" } + XCTAssertEqual(Set(hosts), [ + "token-plan-cn.xiaomimimo.com", "token-plan-sgp.xiaomimimo.com", "token-plan-ams.xiaomimimo.com", + ]) + XCTAssertTrue(MiMoTokenPlanRegion.allCases.allSatisfy { $0.quotaURL.path == "/v1/platform/token_plan" }) + } + + func testTokenPlanLabelsAndFleetFallbackDoNotCreateAlwaysVisibleProviders() { + let labels = [ + "alibaba-token-plan": "Alibaba Token Plan", + "mimo-token-plan": "Xiaomi MiMo Token Plan", + ] + let windows = labels.keys.sorted().map { key in + QuotaWindow(id: key + ":sample", provider: key, providerKey: key, + label: "Quota", remainingPercent: 75, occurredAt: "2026-11-25T00:00:00Z") + } + for (key, label) in labels { + XCTAssertEqual(quotaProviderLabel(key), label) + XCTAssertFalse(expectedQuotaProviderKeys.contains(key)) + } + let fallback = QuotaLocalScope.fleetFallback(fleet: windows, adopted: [], localProviders: []) + XCTAssertEqual(Set(fallback.fallback.map(\.canonicalProviderKey)), Set(labels.keys)) + let withLocalRead = QuotaLocalScope.fleetFallback( + fleet: windows, adopted: [], localProviders: ["mimo-token-plan"]) + XCTAssertEqual(withLocalRead.fallback.map(\.canonicalProviderKey), ["alibaba-token-plan"]) + } + + func testNewReadersAreOptInWithoutChangingExistingDefaults() { + let prefs = QuotaReaderPreferences() + XCTAssertFalse(prefs.isEnabled("alibaba-token-plan")) + XCTAssertFalse(prefs.isEnabled("mimo-token-plan")) + XCTAssertTrue(prefs.isEnabled("zcode")) + XCTAssertTrue(QuotaReaderPreferences(enabledByReaderID: ["mimo-token-plan": true]).isEnabled("mimo-token-plan")) + } +} diff --git a/docs/TOKEN-PLAN-SOURCES.md b/docs/TOKEN-PLAN-SOURCES.md new file mode 100644 index 00000000..7602b889 --- /dev/null +++ b/docs/TOKEN-PLAN-SOURCES.md @@ -0,0 +1,21 @@ +# Alibaba and Xiaomi MiMo Token Plan quota sources + +In **Settings → Sources & Fleet**, enable Alibaba Token Plan after installing the +[official Bailian CLI](https://www.alibabacloud.com/help/en/model-studio/cli/installation) +and signing in to the appropriate console site. Check +`bl usage token-plan --output json` locally first. CodeCaps runs only that bounded +[quota command](https://www.alibabacloud.com/help/en/model-studio/cli/usage-quota). +A successful command without usage windows is unavailable, not a full allowance. +Availability depends on the console site and plan; no browser profile is read. + +For Xiaomi, choose the region shown on the MiMo Token Plan dashboard and save the +individual plan key in CodeCaps. CodeCaps keeps that key in the local macOS +Keychain, checks only the matching Xiaomi region’s +[credits endpoint](https://mimo.mi.com/docs/en-US/api/asset/credits-get), and never +performs inference. Team and pay-as-you-go keys are not supported. The poll +preserves Xiaomi’s reported credit balance and exact billing-cycle end rather +than assuming it is monthly. Do not paste the key into a support report. + +Use both with signed-in test subscriptions to verify the Mac settings and quota +meters. The fixtures do not prove any specific account or region is eligible. +The iPhone companion still uses synced snapshots, not these local collectors.