Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions Sources/CodeCaps/MiMoQuotaSettings.swift
Original file line number Diff line number Diff line change
@@ -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." }
}
}
Comment thread
swu-jet[bot] marked this conversation as resolved.
Resolved

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." }
}
}
}
11 changes: 11 additions & 0 deletions Sources/CodeCaps/MonitorModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
Expand Down
9 changes: 6 additions & 3 deletions Sources/CodeCaps/SettingsViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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"),
]
}

Expand Down Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions Sources/QuotaCore/LocalQuotaReaderRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)
},
])
}
}
Comment thread
swu-jet[bot] marked this conversation as resolved.
Resolved
16 changes: 14 additions & 2 deletions Sources/QuotaCore/QuotaModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ public enum QuotaLocalScope {
fleet: [QuotaWindow],
adopted: [QuotaWindow],
localProviders: Set<String>,
expectedKeys: [String] = expectedQuotaProviderKeys
expectedKeys: [String] = fleetFallbackQuotaProviderKeys
) -> (fallback: [QuotaWindow], superseded: [QuotaWindow]) {
var fallback: [QuotaWindow] = []
var superseded: [QuotaWindow] = []
Expand Down Expand Up @@ -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" {
Expand Down Expand Up @@ -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
}
}

Expand All @@ -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)
}
Expand Down
6 changes: 3 additions & 3 deletions Sources/QuotaCore/QuotaReaderPreferences.swift
Original file line number Diff line number Diff line change
@@ -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]
Expand All @@ -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) {
Expand Down
Loading
Loading