From 98cad2a759dfb34a88cc4c975b3f1d46284fdb02 Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:21:14 +0000 Subject: [PATCH 01/12] Add Muse monitoring, provider registration, and configurable alert delivery --- Sources/CodeCaps/AppDelegate.swift | 73 ++- Sources/CodeCaps/AutoUpdate.swift | 8 + Sources/CodeCaps/CodeCapsAlertChannels.swift | 69 +++ Sources/CodeCaps/ConsoleViews.swift | 47 +- Sources/CodeCaps/MonitorModel.swift | 452 +++++++++++++++++- .../CodeCaps/MuseCodeBridgeCheckpoint.swift | 28 ++ Sources/CodeCaps/MuseCodePlugin.swift | 28 ++ Sources/CodeCaps/MuseCodePluginView.swift | 290 +++++++++++ Sources/CodeCaps/QuitConfirmation.swift | 33 ++ Sources/CodeCaps/ResetAlarmManager.swift | 2 + Sources/CodeCaps/SMSAlertController.swift | 137 ++++++ Sources/CodeCaps/SMSSettingsView.swift | 80 ++++ Sources/CodeCaps/SettingsViews.swift | 36 +- Sources/CodeCaps/TokenStore.swift | 14 +- Sources/CodeCaps/TwilioCredentialStore.swift | 60 +++ .../QuotaCore/LocalQuotaReaderRegistry.swift | 104 ++++ Sources/QuotaCore/MuseCodeBurnMonitor.swift | 134 ++++++ Sources/QuotaCore/MuseCodeSessionIngest.swift | 208 ++++++++ Sources/QuotaCore/MuseCodeSessionReader.swift | 405 ++++++++++++++++ .../MuseCodeStandardSessionDetector.swift | 154 ++++++ 20 files changed, 2319 insertions(+), 43 deletions(-) create mode 100644 Sources/CodeCaps/CodeCapsAlertChannels.swift create mode 100644 Sources/CodeCaps/MuseCodeBridgeCheckpoint.swift create mode 100644 Sources/CodeCaps/MuseCodePlugin.swift create mode 100644 Sources/CodeCaps/MuseCodePluginView.swift create mode 100644 Sources/CodeCaps/QuitConfirmation.swift create mode 100644 Sources/CodeCaps/SMSAlertController.swift create mode 100644 Sources/CodeCaps/SMSSettingsView.swift create mode 100644 Sources/CodeCaps/TwilioCredentialStore.swift create mode 100644 Sources/QuotaCore/LocalQuotaReaderRegistry.swift create mode 100644 Sources/QuotaCore/MuseCodeBurnMonitor.swift create mode 100644 Sources/QuotaCore/MuseCodeSessionIngest.swift create mode 100644 Sources/QuotaCore/MuseCodeSessionReader.swift create mode 100644 Sources/QuotaCore/MuseCodeStandardSessionDetector.swift diff --git a/Sources/CodeCaps/AppDelegate.swift b/Sources/CodeCaps/AppDelegate.swift index 91019d80..239bf189 100644 --- a/Sources/CodeCaps/AppDelegate.swift +++ b/Sources/CodeCaps/AppDelegate.swift @@ -1,5 +1,6 @@ import AppKit import Combine +import Carbon import QuotaCore import SwiftUI import UserNotifications @@ -57,6 +58,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe let model = MonitorModel() let consoleState = ConsoleState() private var statusItem: NSStatusItem? + private var keepsMenuBarAccessAfterBackgroundChoice = false + private var userConfirmedQuit = false private var planWarningCycle = PlanWarningCycle() private var navigatingPlanWarning = false private var planWarningCheckPending = false @@ -366,12 +369,54 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe private let snapshotTerminationDrain = SnapshotTerminationDrain() func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { - // This app has no cancelled-quit/resume path: every request replies true. + let systemTerminationReason = NSAppleEventManager.shared().currentAppleEvent? + .paramDescriptor(forKeyword: kAEQuitReason)?.typeCodeValue + if !userConfirmedQuit && QuitConfirmationPolicy.shouldConfirm( + systemTerminationReason: systemTerminationReason, + automaticInstallInProgress: AppUpdater.shared.isAutomaticInstallInProgress) { + switch confirmQuitChoice() { + case .closeAndKeepRunning: + closeWindowsAndKeepRunning() + return .terminateCancel + case .quit: + userConfirmedQuit = true + case .cancel: + return .terminateCancel + } + } + beginTerminationDrain(replyTo: sender) + return .terminateLater + } + + private func confirmQuitChoice() -> QuitConfirmationChoice { + let alert = NSAlert() + alert.messageText = "Quit CodeCaps?" + alert.informativeText = "Close the windows and keep CodeCaps running in the menu bar so quota checks and alerts continue." + alert.alertStyle = .informational + alert.addButton(withTitle: "Close Window And Keep Running") + alert.addButton(withTitle: "Quit CodeCaps") + alert.addButton(withTitle: "Cancel") + alert.buttons.first?.keyEquivalent = "\r" + alert.buttons.last?.keyEquivalent = "\u{1b}" + NSApp.activate(ignoringOtherApps: true) + return QuitConfirmationChoice(response: alert.runModal()) + } + + private func closeWindowsAndKeepRunning() { + keepsMenuBarAccessAfterBackgroundChoice = true + ensureStatusItem() + updateStatus() + popover.performClose(nil) + lowerConsole() + for window in NSApp.windows { window.orderOut(nil) } + applyActivationPolicy() + } + + private func beginTerminationDrain(replyTo sender: NSApplication) { snapshotTerminationDrain.request( stop: { model.stop() }, flush: { [self] in await model.flushSnapshotWrites() }, reply: { sender.reply(toApplicationShouldTerminate: true) }) - return .terminateLater } func applicationWillTerminate(_ notification: Notification) { model.stop() } @@ -384,24 +429,32 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe private func apply(_ mode: DisplayMode) { // AppKit owns only activation and status-item lifetime; content remains SwiftUI. - if mode != .dock && statusItem == nil { - let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) - item.button?.target = self - item.button?.action = #selector(statusItemClicked) - item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp]) - statusItem = item + if QuitConfirmationPolicy.shouldShowStatusItem(displayMode: mode, + keepRunningOverride: keepsMenuBarAccessAfterBackgroundChoice) { + ensureStatusItem() } NSApp.setActivationPolicy(mode == .menuBar ? .accessory : .regular) if mode == .menuBar { consoleWindow?.orderOut(nil) } if mode == .dock { popover.performClose(nil) - if let item = statusItem { NSStatusBar.system.removeStatusItem(item) } - statusItem = nil + if !keepsMenuBarAccessAfterBackgroundChoice { + if let item = statusItem { NSStatusBar.system.removeStatusItem(item) } + statusItem = nil + } showConsole(page: nil) } updateStatus() } + private func ensureStatusItem() { + guard statusItem == nil else { return } + let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) + item.button?.target = self + item.button?.action = #selector(statusItemClicked) + item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp]) + statusItem = item + } + /// Keeps the warning window in step with the model. Called on every /// publish; the controller is a no-op unless the popup is actually showing. private func updateExhaustionPopup() { diff --git a/Sources/CodeCaps/AutoUpdate.swift b/Sources/CodeCaps/AutoUpdate.swift index 50769252..ab9d60b2 100644 --- a/Sources/CodeCaps/AutoUpdate.swift +++ b/Sources/CodeCaps/AutoUpdate.swift @@ -103,6 +103,8 @@ final class AppUpdater: NSObject, ObservableObject, SPUUpdaterDelegate { private var canCheckObservation: NSKeyValueObservation? private var resignActiveObserver: NSObjectProtocol? private var pendingInstall: (() -> Void)? + private var becameActiveObserver: NSObjectProtocol? + private(set) var isAutomaticInstallInProgress = false private override init() { availability = AutoUpdateAvailability.evaluate(info: Bundle.main.infoDictionary, @@ -125,6 +127,11 @@ final class AppUpdater: NSObject, ObservableObject, SPUUpdaterDelegate { ) { [weak self] _ in MainActor.assumeIsolated { self?.installPendingUpdateIfIdle() } } + becameActiveObserver = NotificationCenter.default.addObserver( + forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.isAutomaticInstallInProgress = false } + } } /// The "Check For Updates…" command. An accessory app is never frontmost @@ -150,6 +157,7 @@ final class AppUpdater: NSObject, ObservableObject, SPUUpdaterDelegate { guard let install = pendingInstall, !NSApp.isActive else { return } pendingInstall = nil UpdateRelaunchMarker().mark() + isAutomaticInstallInProgress = true install() } } diff --git a/Sources/CodeCaps/CodeCapsAlertChannels.swift b/Sources/CodeCaps/CodeCapsAlertChannels.swift new file mode 100644 index 00000000..b1560527 --- /dev/null +++ b/Sources/CodeCaps/CodeCapsAlertChannels.swift @@ -0,0 +1,69 @@ +import Foundation +import QuotaCore + +/// One alert occurrence on its way to a delivery channel. +/// +/// Every event carries its stable `UsageAlertKind` identifier, so channels +/// select by kind — never by which producer emitted the event — and a +/// future per-kind channel opt-in needs no producer changes. +public struct CodeCapsAlertEvent: Equatable, Sendable { + public let kind: UsageAlertKind + public let title: String + public let body: String + public let identifier: String + public let occurredAt: Date + + public init(kind: UsageAlertKind, title: String, body: String, + identifier: String, occurredAt: Date) { + self.kind = kind + self.title = title + self.body = body + self.identifier = identifier + self.occurredAt = occurredAt + } +} + +/// A delivery channel for app-level alert events. +/// +/// The seam is deliberately at the app level, not inside any plugin: a new +/// channel registers once with the dispatcher and receives every producer's +/// events. The planned Twilio SMS channel is the expected second channel — +/// app-level, selecting a deliberately small set of kinds — and it slots in +/// here without reworking any monitor. +@MainActor +public protocol CodeCapsAlertChannel: AnyObject { + func deliver(_ event: CodeCapsAlertEvent) +} + +/// App-level fan-out for alert events. Producers emit here, never to a +/// channel directly. +@MainActor +public final class CodeCapsAlertDispatcher { + private var channels: [CodeCapsAlertChannel] = [] + + public init() {} + + public func register(_ channel: CodeCapsAlertChannel) { + channels.append(channel) + } + + public func emit(_ event: CodeCapsAlertEvent) { + for channel in channels { channel.deliver(event) } + } +} + +/// The only channel today: CodeCaps' own alert surface, through the same +/// per-kind preferences and delivery path as every other usage alert. +@MainActor +public final class LocalAlertChannel: CodeCapsAlertChannel { + private weak var manager: ResetAlarmManager? + + public init(manager: ResetAlarmManager) { + self.manager = manager + } + + public func deliver(_ event: CodeCapsAlertEvent) { + manager?.deliverUsageAlert(kind: event.kind, title: event.title, + body: event.body, identifier: event.identifier) + } +} diff --git a/Sources/CodeCaps/ConsoleViews.swift b/Sources/CodeCaps/ConsoleViews.swift index f21388e4..7436b114 100644 --- a/Sources/CodeCaps/ConsoleViews.swift +++ b/Sources/CodeCaps/ConsoleViews.swift @@ -8,6 +8,7 @@ enum ConsolePage: Hashable { case allPlatforms case platform(String) case runawayAlerts + case plugin(String) case settingsMenuBar case settingsPlatforms case settingsLogoStyle @@ -19,7 +20,7 @@ enum ConsolePage: Hashable { var isSettings: Bool { switch self { - case .allPlatforms, .platform, .runawayAlerts: return false + case .allPlatforms, .platform, .runawayAlerts, .plugin: return false default: return true } } @@ -29,6 +30,7 @@ enum ConsolePage: Hashable { case .allPlatforms: return "allPlatforms" case .platform(let providerKey): return "platform:" + providerKey case .runawayAlerts: return "runawayAlerts" + case .plugin(let pluginId): return "plugin:" + pluginId case .settingsMenuBar: return "settingsMenuBar" case .settingsPlatforms: return "settingsPlatforms" case .settingsLogoStyle: return "settingsLogoStyle" @@ -53,6 +55,9 @@ enum ConsolePage: Hashable { case "settingsInfisical": return .settingsInfisical case "settingsAbout": return .settingsAbout default: + if value.hasPrefix("plugin:") { + return .plugin(String(value.dropFirst(7))) + } guard value.hasPrefix("platform:") else { return nil } return .platform(String(value.dropFirst(9))) } @@ -63,6 +68,7 @@ enum ConsolePage: Hashable { switch self { case .allPlatforms: return "All Platforms" case .runawayAlerts: return "Runaway Alerts" + case .plugin(let pluginId): return CodeCapsPlugin.named(pluginId)?.title ?? "Plugin" case .settingsMenuBar: return "Menu Bar & PiP" case .settingsPlatforms: return "Platforms" case .settingsLogoStyle: return "Logo Style" @@ -79,6 +85,7 @@ enum ConsolePage: Hashable { switch self { case .allPlatforms: return "square.grid.2x2" case .runawayAlerts: return "flame.fill" + case .plugin(let pluginId): return CodeCapsPlugin.named(pluginId)?.symbol ?? "puzzlepiece.extension" case .settingsMenuBar: return "menubar.rectangle" case .settingsPlatforms: return "square.grid.2x2" case .settingsLogoStyle: return "photo.on.rectangle.angled" @@ -94,6 +101,8 @@ enum ConsolePage: Hashable { static let settingsPages: [ConsolePage] = [ .settingsMenuBar, .settingsPlatforms, .settingsLogoStyle, .settingsSourcesFleet, .settingsNotifications, .settingsAppearance, .settingsInfisical, .settingsAbout, ] + + static let pluginPages: [ConsolePage] = CodeCapsPlugin.allCases.map { .plugin($0.id) } } struct AlertNavigation: Equatable { @@ -192,6 +201,13 @@ final class ConsoleState: ObservableObject { awaitingInitialSelection = false return } + if case .plugin = page { + // A plugin page is local: it never waits on a quota read, and no + // source disappearing can invalidate it. + pendingStoredKey = nil + awaitingInitialSelection = false + return + } if page.isSettings && !awaitingInitialSelection { return } if sections.isEmpty && !readCompleted { return } isReconciling = true @@ -335,6 +351,9 @@ struct ConsoleView: View { case .runawayAlerts: RunawayAlertsPage(model: model, state: state) .padding(Metrics.pagePadding) + case .plugin(let pluginId): + MuseCodePluginPage(model: model, pluginId: pluginId) + .padding(Metrics.pagePadding) case .platform(let key): PlatformDetailPage(model: model, state: state, providerKey: key) .padding(Metrics.pagePadding) @@ -482,6 +501,7 @@ struct ConsoleSidebar: View { private var allPages: [ConsolePage] { var pages: [ConsolePage] = [.allPlatforms, .runawayAlerts] pages.append(contentsOf: model.displaySections.map { .platform($0.id) }) + pages.append(contentsOf: ConsolePage.pluginPages) pages.append(contentsOf: ConsolePage.settingsPages) return pages } @@ -539,6 +559,31 @@ struct ConsoleSidebar: View { } header: { Eyebrow("QUOTAS") } + Section { + ForEach(ConsolePage.pluginPages, id: \.self) { page in + sidebarRow(page: page) { + HStack(spacing: 8) { + Image(systemName: page.symbol) + .font(.system(size: 13)) + .foregroundStyle(model.museCodeBurnAlert == nil ? Theme.ink : Theme.warning) + .frame(width: 18) + Text(page.settingsTitle) + .font(.system(size: 13, weight: .medium)) + Spacer(minLength: 4) + if model.museCodeBurnAlert != nil { + Text("1") + .font(.system(size: 10, weight: .bold)) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Theme.warning, in: Capsule()) + } + } + } + } + } header: { + Eyebrow("PLUGINS") + } Section { ForEach(ConsolePage.settingsPages, id: \.self) { page in sidebarRow(page: page) { diff --git a/Sources/CodeCaps/MonitorModel.swift b/Sources/CodeCaps/MonitorModel.swift index 586743fd..8dbded8b 100644 --- a/Sources/CodeCaps/MonitorModel.swift +++ b/Sources/CodeCaps/MonitorModel.swift @@ -354,6 +354,63 @@ final class MonitorModel: ObservableObject { dismissedPlanChangeIds.insert(id) } @Published public private(set) var runawayAlertHistory: [RunawayAlertRecord] = [] + + // MARK: - Muse Plugin + + /// Latest Muse session-store reading, for the Plugins section. + @Published private(set) var museCodeReport: MuseCodeSessionReport? + @Published private(set) var museCodeIssue: String? + /// The alerts the current reading produces. Both stay visible on the + /// plugin page whether or not their delivery is inside a cooldown. + @Published private(set) var museCodeBurnAlert: MuseCodeBurnMonitor.BurnAlert? + /// The most recent standard-session event the detector fired. Unlike + /// the burn alert this is an event, not a state: it stays on the page + /// (with its observed time in the body) until a newer event replaces it. + @Published private(set) var museCodeStandardSessionAlert: MuseCodeStandardSessionEvent? + @Published private(set) var museCodeBridgeStatus: String? + /// Token threshold for the burn alert in the trailing 90-minute window. + /// A per-user tunable, so it stays in UserDefaults like the burn-rate + /// multipliers (see INFISICAL.md), never in Infisical. + @Published var museCodeBurnThresholdTokens: Int { + didSet { + defaults.set(museCodeBurnThresholdTokens, forKey: "museCodeBurnThresholdTokens") + if let museCodeReport { evaluateMuseCodeAlerts(report: museCodeReport) } + } + } + /// Ships on: the warning is the feature the plugin exists for. Either + /// alert kind can still be turned off on its own in Alerts & Alarms. + @Published var museCodeBurnAlertsEnabled: Bool { + didSet { + defaults.set(museCodeBurnAlertsEnabled, forKey: "museCodeBurnAlertsEnabled") + if museCodeBurnAlertsEnabled { + Task { await alarmManager.requestNotificationPermission() } + if let museCodeReport { evaluateMuseCodeAlerts(report: museCodeReport) } + } else { + museCodeBurnAlert = nil + museCodeStandardSessionAlert = nil + } + } + } + /// Whether the plugin also posts its session token events to Usage + /// Monitor through the sync endpoint. Off by default: the local monitor + /// is the feature; the bridge is provenance for the server. + @Published var museCodeUsageBridgeEnabled: Bool { + didSet { + defaults.set(museCodeUsageBridgeEnabled, forKey: "museCodeUsageBridgeEnabled") + guard oldValue != museCodeUsageBridgeEnabled else { return } + museCodeBridgeGeneration &+= 1 + if museCodeUsageBridgeEnabled, let museCodeReport { + enqueueMuseCodeBridge(report: museCodeReport) + } else { + museCodePendingBridgeReport = nil + museCodeBridgeStatus = "Bridge off." + } + } + } + @Published private(set) var museCodeHasSavedIngestToken: Bool + @Published private(set) var museCodeIngestTokenStatus: String? + @Published private(set) var museCodeIngestTokenBusy = false + public var resetAlertHistory: [ResetAlertRecord] { alarmManager.alertHistory } @@ -552,8 +609,20 @@ final class MonitorModel: ObservableObject { @Published var disabledSources: Set { didSet { defaults.set(Array(disabledSources), forKey: "disabledSources") } } + @Published private(set) var optionalQuotaReaderPreferences: QuotaReaderPreferences public let alarmManager: ResetAlarmManager + let smsAlerts: SMSAlertController + + /// App-level alert fan-out. Producers emit `CodeCapsAlertEvent`s here + /// and registered channels deliver them; today the only channel is the + /// local alert surface, and a future channel registers here once rather + /// than inside any producer. + lazy var alertDispatcher: CodeCapsAlertDispatcher = { + let dispatcher = CodeCapsAlertDispatcher() + dispatcher.register(LocalAlertChannel(manager: alarmManager)) + return dispatcher + }() private let presentsPipWindows: Bool private let defaults: UserDefaults @@ -577,6 +646,28 @@ final class MonitorModel: ObservableObject { var settingsWriteForTesting: (@MainActor (String, String) async throws -> Void)? var pushForTesting: (@MainActor ([QuotaWindow], URL, String?, QuotaSyncFormat) async throws -> QuotaPublishResult)? var runawayNotificationForTesting: ((BurnRateNotification) -> Void)? + var museCodeReadForTesting: (@MainActor () async -> MuseCodeSessionResult?)? + var museCodePublishForTesting: (@MainActor ([[String: Any]], URL, String?) async throws -> MuseCodeIngestSummary)? + var museCodeTokenReadForTesting: (@MainActor () async -> String?)? + var museCodeTokenSaveForTesting: (@MainActor (String) async throws -> Void)? + var museCodeTokenDeleteForTesting: (@MainActor () async throws -> Void)? + var museCodeTokenReauthorizeForTesting: (@MainActor () async -> String?)? + private var museCodeBridgeGeneration: UInt64 = 0 + private var museCodeBridgeTask: Task? + private var museCodePendingBridgeReport: MuseCodeSessionReport? + var museCodeBridgeTaskForTesting: Task? { museCodeBridgeTask } + private var lastMuseCodeBurnAlertAt: Double = 0 + /// The standard-session detector's tracked state, persisted across + /// launches with the same JSON-in-UserDefaults pattern as the bridge + /// baselines, so a session already reported does not refire after a + /// restart. An earlier build persisted a + /// `museCodeContributorBelow100Active` bool for the share-based edge + /// trigger; that key is abandoned unread. + private var museCodeStandardSessionDetector = MuseCodeStandardSessionDetector() + private static let museCodeDetectorKey = "museCodeStandardSessionDetector" + private var museCodeRequest: Task? + private var museCodeReadGeneration: UInt64 = 0 + private let museCodePoster = MuseCodeSessionPoster() var exhaustionNotificationForTesting: ((String, String) -> Void)? var exhaustionHistoryURLForTesting: URL? var skipsSnapshotIOForTesting = false @@ -611,6 +702,7 @@ final class MonitorModel: ObservableObject { /// Re-publishes the alarm manager's changes, so a view that observes this /// model redraws when All or a provider's bell flips. private var alarmChanges: AnyCancellable? + private var smsChanges: AnyCancellable? /// Re-checks the saved-token states when `TokenStore` gains a token nobody /// was waiting for, so the Re-Authorize button clears without a refresh. private var tokenChanges: AnyCancellable? @@ -700,6 +792,7 @@ final class MonitorModel: ObservableObject { sourceRank = [:] } disabledSources = Set((defaults.stringArray(forKey: "disabledSources") ?? [])) + optionalQuotaReaderPreferences = QuotaReaderPreferences.load(from: defaults) localEnabled = defaults.object(forKey: "localEnabled") as? Bool ?? true glanceLogosFollowAccent = defaults.bool(forKey: "glanceLogosFollowAccent") pipBackground = PipBackground(rawValue: defaults.string(forKey: "pipBackground") ?? "") ?? .black @@ -719,8 +812,19 @@ final class MonitorModel: ObservableObject { syncEndpoint = defaults.string(forKey: "syncEndpoint") ?? "" syncFormat = QuotaSyncFormat(rawValue: defaults.string(forKey: "syncFormat") ?? "") ?? .usageMonitorV2 remoteAlertRelayEnabled = defaults.bool(forKey: "remoteAlertRelayEnabled") + museCodeBurnThresholdTokens = defaults.object(forKey: "museCodeBurnThresholdTokens") as? Int + ?? MuseCodeBurnMonitor.defaultThresholdTokens + museCodeBurnAlertsEnabled = defaults.object(forKey: "museCodeBurnAlertsEnabled") as? Bool ?? true + museCodeUsageBridgeEnabled = defaults.bool(forKey: "museCodeUsageBridgeEnabled") + museCodeHasSavedIngestToken = defaults.bool(forKey: "museCodeHasSavedIngestToken") + lastMuseCodeBurnAlertAt = defaults.double(forKey: "museCodeBurnLastSent") + if let data = defaults.data(forKey: Self.museCodeDetectorKey), + let saved = try? JSONDecoder().decode(MuseCodeStandardSessionDetector.self, from: data) { + museCodeStandardSessionDetector = saved + } alarmManager = ResetAlarmManager(defaults: defaults) + smsAlerts = SMSAlertController(defaults: defaults) appearance = AppAppearance(rawValue: defaults.string(forKey: "appearance") ?? "") ?? .system glanceView = GlanceViewMode(rawValue: defaults.string(forKey: "glanceView") ?? "") ?? .fromMac @@ -737,6 +841,12 @@ final class MonitorModel: ObservableObject { alarmChanges = alarmManager.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() } + smsChanges = smsAlerts.objectWillChange.sink { [weak self] _ in + self?.objectWillChange.send() + } + alarmManager.additionalDelivery = { [weak self] kind, title, body, identifier in + self?.smsAlerts.deliver(kind: kind.rawValue, title: title, body: body, eventID: identifier) + } tokenChanges = NotificationCenter.default.publisher(for: TokenStore.tokenBecameAvailable) .receive(on: DispatchQueue.main) .sink { [weak self] _ in @@ -1106,6 +1216,28 @@ final class MonitorModel: ObservableObject { sourceRank[key] = current } + func isOptionalQuotaReaderEnabled(_ readerID: String) -> Bool { + optionalQuotaReaderPreferences.isEnabled(readerID) + } + + func setOptionalQuotaReaderEnabled(_ enabled: Bool, readerID: String) { + guard LocalQuotaReaderRegistry.builtIn.optionalRegistrations.contains(where: { $0.id == readerID }), + optionalQuotaReaderPreferences.isEnabled(readerID) != enabled else { return } + var preferences = optionalQuotaReaderPreferences + preferences.setEnabled(enabled, for: readerID) + optionalQuotaReaderPreferences = preferences + preferences.save(to: defaults) + invalidateRefresh() + if !enabled, let providerResult { + self.providerResult = LocalQuotaResult( + windows: providerResult.windows.filter { $0.canonicalProviderKey != readerID }, + issues: providerResult.issues.filter { $0.key != readerID }, + consentNeeded: providerResult.consentNeeded.subtracting([readerID])) + rebuildLocalState(recordSamples: false) + } + if providerChecksEnabled || serverEnabled { refreshProviderChecks() } + } + func setSourceEnabled(_ enabled: Bool, _ source: String, for providerKey: String) { var disabled = disabledSources if enabled { disabled.remove(source) } else { disabled.insert(source) } @@ -1782,6 +1914,9 @@ final class MonitorModel: ObservableObject { /// instead of waiting for a save. func setLocalEnabled(_ value: Bool) { guard value != localEnabled else { return } + museCodeReadGeneration &+= 1 + museCodeRequest?.cancel() + museCodeRequest = nil invalidateRefresh() invalidateSessionFileRefresh() localEnabled = value @@ -2121,7 +2256,9 @@ final class MonitorModel: ObservableObject { } else if let localResultForTesting { windowsToPush = AntigravityQuotaGroups.normalize(localResultForTesting.windows) } else { - windowsToPush = AntigravityQuotaGroups.normalize(await Self.readLocalSources().windows) + let readerPreferences = optionalQuotaReaderPreferences + windowsToPush = AntigravityQuotaGroups.normalize( + await Self.readLocalSources(preferences: readerPreferences).windows) } guard isCurrentPushSettings(generation, endpoint: targetEndpoint, format: targetFormat) else { return (false, "Push cancelled because sharing was disabled or its settings changed.") @@ -2290,6 +2427,7 @@ final class MonitorModel: ObservableObject { let useLocal = localEnabled && providerChecksEnabled let useServer = serverEnabled let currentEndpoint = endpoint + let readerPreferences = optionalQuotaReaderPreferences request = Task { [weak self] in let resultForTesting = self?.localResultForTesting let localReadForTesting = self?.localReadForTesting @@ -2297,7 +2435,8 @@ final class MonitorModel: ObservableObject { async let localRead: LocalQuotaResult? = { guard useLocal else { return nil } if let localReadForTesting { return await localReadForTesting() } - return await Self.readLocalResult(useLocal: useLocal, testingResult: resultForTesting) + return await Self.readLocalResult(useLocal: useLocal, testingResult: resultForTesting, + preferences: readerPreferences) }() var newServer: QuotaResponse? var failure: String? @@ -2457,6 +2596,7 @@ final class MonitorModel: ObservableObject { let widgetCandidates = unifiedMerged + split.groups.flatMap(\.windows) self.publishWidgetSnapshot(candidates: widgetCandidates) self.refreshRunawayUsageState(recordSamples: local != nil) + self.refreshMuseCodePlugin() self.refreshExhaustionWarnings(windows: widgetCandidates, now: self.now) self.alarmManager.evaluate(observations: self.resetAlarmObservationsForCurrentReadings(), now: self.now) self.evaluatePipLowQuota() @@ -2628,6 +2768,7 @@ final class MonitorModel: ObservableObject { let widgetCandidates = unifiedMerged + split.groups.flatMap(\.windows) publishWidgetSnapshot(candidates: widgetCandidates) refreshRunawayUsageState(recordSamples: recordSamples) + refreshMuseCodePlugin() refreshExhaustionWarnings(windows: widgetCandidates, now: now) alarmManager.evaluate(observations: resetAlarmObservationsForCurrentReadings(), now: now) evaluatePipLowQuota() @@ -3031,6 +3172,282 @@ final class MonitorModel: ObservableObject { defaults.set(lastRunawayAlertAt, forKey: "runawayAlertLastSent") } + // MARK: - Muse Plugin Evaluation + + /// Reads the Muse session store alongside the quota refresh paths and + /// applies the result. Mirrors the session-file reader's test guard: an + /// injected quota read must not silently start a real file scan in an + /// offline test. + func refreshMuseCodePlugin() { + guard localEnabled else { + museCodeReport = nil + museCodeIssue = nil + museCodeBurnAlert = nil + museCodeStandardSessionAlert = nil + return + } + if museCodeReadForTesting == nil, + skipsSnapshotIOForTesting || localReadForTesting != nil || localResultForTesting != nil + || sessionFileReadForTesting != nil || sessionAccountIDForTesting != nil + || serverFetchForTesting != nil { return } + guard museCodeRequest == nil else { return } + let generation = museCodeReadGeneration + let readForTesting = museCodeReadForTesting + museCodeRequest = Task { [weak self] in + let result: MuseCodeSessionResult? + if let readForTesting { + result = await readForTesting() + } else { + result = await Task.detached(priority: .utility) { + MuseCodeSessionReader().read() + }.value + } + guard let self else { return } + guard generation == self.museCodeReadGeneration else { return } + self.museCodeRequest = nil + guard !Task.isCancelled, self.localEnabled else { return } + if let result { self.applyMuseCodeResult(result) } + } + } + + /// Applies one session-store reading: page state first, then the alert + /// events, then the optional Usage Monitor bridge. + func applyMuseCodeResult(_ result: MuseCodeSessionResult) { + museCodeReport = result.report + museCodeIssue = result.issue + guard let report = result.report else { + museCodeBurnAlert = nil + museCodeStandardSessionAlert = nil + return + } + evaluateMuseCodeAlerts(report: report) + if museCodeUsageBridgeEnabled { enqueueMuseCodeBridge(report: report) } + } + + private func evaluateMuseCodeAlerts(report: MuseCodeSessionReport) { + guard museCodeBurnAlertsEnabled else { + museCodeBurnAlert = nil + museCodeStandardSessionAlert = nil + return + } + let burn = MuseCodeBurnMonitor.evaluateBurn(report: report, + thresholdTokens: museCodeBurnThresholdTokens) + museCodeBurnAlert = burn + if let burn, + now.timeIntervalSince1970 - lastMuseCodeBurnAlertAt >= MuseCodeBurnMonitor.alertCooldown { + lastMuseCodeBurnAlertAt = now.timeIntervalSince1970 + defaults.set(lastMuseCodeBurnAlertAt, forKey: "museCodeBurnLastSent") + guard defaults.synchronize() else { return } + alertDispatcher.emit(CodeCapsAlertEvent( + kind: .museCodeBurn, title: burn.title, body: burn.body, + identifier: "codecaps.musecode.burn." + UUID().uuidString, occurredAt: report.generatedAt)) + } + // The contributor finding is its own alert kind, independent of the + // burn threshold, and it is an event, not a share: the detector + // fires once when a session starts on a standard model or switches + // to one, and re-arms per session when it returns to a contributor + // model, so a channel that subscribes to the finding itself (the + // planned SMS channel is the expected one) never has to piggyback + // on the burn alert. Each event carries its own notification + // identifier, so two sessions' events never replace each other. + let events = museCodeStandardSessionDetector.observe( + report.currentModelObservations) + guard saveMuseCodeDetectorState() else { return } + if let latest = events.last { + museCodeStandardSessionAlert = latest + } + for event in events { + alertDispatcher.emit(CodeCapsAlertEvent( + kind: .museCodeStandardSession, title: event.title, body: event.body, + identifier: "codecaps.musecode.standard-session.\(event.sessionId)." + UUID().uuidString, + occurredAt: event.observedAt)) + } + } + + private func saveMuseCodeDetectorState() -> Bool { + guard let data = try? JSONEncoder().encode(museCodeStandardSessionDetector) else { return false } + defaults.set(data, forKey: Self.museCodeDetectorKey) + return defaults.synchronize() + } + + /// One worker plans, posts, and commits baselines in order. + private func enqueueMuseCodeBridge(report: MuseCodeSessionReport) { + guard museCodeUsageBridgeEnabled else { return } + if museCodePendingBridgeReport == nil || report.generatedAt >= museCodePendingBridgeReport!.generatedAt { + museCodePendingBridgeReport = report + } + guard museCodeBridgeTask == nil, !museCodeIngestTokenBusy else { return } + museCodeBridgeTask = Task { [weak self] in + guard let self else { return } + while self.museCodeUsageBridgeEnabled, !self.museCodeIngestTokenBusy, + let next = self.museCodePendingBridgeReport { + self.museCodePendingBridgeReport = nil + let generation = self.museCodeBridgeGeneration + let completed = await self.postMuseCodeBridge(report: next, generation: generation) + // Failure waits for a later refresh; it never retries immediately. + if !completed { break } + } + self.museCodeBridgeTask = nil + } + } + + private func canPostMuseCodeBridge(generation: UInt64) -> Bool { + museCodeUsageBridgeEnabled && !museCodeIngestTokenBusy && generation == museCodeBridgeGeneration + } + + /// The pending plan is saved before I/O and replayed with its exact event IDs. + /// A newer snapshot cannot change the quantity of an uncertain earlier post. + private func postMuseCodeBridge(report: MuseCodeSessionReport, generation: UInt64, + showNoNewStatus: Bool = true) async -> Bool { + guard canPostMuseCodeBridge(generation: generation) else { return true } + do { + var checkpoint = try loadMuseCodeBridgeCheckpoint() + let replayingPending = checkpoint.pending != nil + if checkpoint.pending == nil { + let plan = MuseCodeDeltaPlanner.plan(observations: report.latestObservations, + previous: checkpoint.observations) + guard !plan.events.isEmpty else { + checkpoint.observations = plan.updated + try saveMuseCodeBridgeCheckpoint(checkpoint) + if showNoNewStatus { + museCodeBridgeStatus = report.latestObservations.isEmpty + ? "No Muse sessions to post." : "No new Muse tokens to post." + } + return true + } + checkpoint.pending = MuseCodeBridgeCheckpoint.Pending(events: plan.events, updated: plan.updated) + try saveMuseCodeBridgeCheckpoint(checkpoint) + } + guard let pending = checkpoint.pending else { return false } + let token: String? + if let museCodeTokenReadForTesting { token = await museCodeTokenReadForTesting() } + else { + token = await TokenStore.read(server: MuseCodeSessionIngest.endpoint.absoluteString, + service: TokenStore.museCodeIngestService) + } + guard canPostMuseCodeBridge(generation: generation) else { return true } + guard let token = token.map(sanitizedToken(_:)), !token.isEmpty else { + museCodeBridgeStatus = "Save the Muse ingest token in the bridge setup." + return false + } + let events = pending.events.map { MuseCodeSessionIngest.event(observation: $0.observation, delta: $0.delta) } + let summary: MuseCodeIngestSummary + if let museCodePublishForTesting { + summary = try await museCodePublishForTesting(events, MuseCodeSessionIngest.endpoint, token) + } else { + summary = try await museCodePoster.publish(events: events, to: MuseCodeSessionIngest.endpoint, token: token, + shouldContinue: { [weak self] in + await self?.canPostMuseCodeBridge(generation: generation) == true + }) + } + guard summary.sent == events.count, summary.rejected == 0 else { + if canPostMuseCodeBridge(generation: generation) { + museCodeBridgeStatus = "Usage Monitor rejected token events.\u{00A0} Pending events were retained." + } + return false + } + // Baselines belong to the immutable receiver and producer, not its token. + // Acknowledged old-token work must not be counted again after rotation. + checkpoint.observations = pending.updated + checkpoint.pending = nil + try saveMuseCodeBridgeCheckpoint(checkpoint) + guard canPostMuseCodeBridge(generation: generation) else { return true } + museCodeBridgeStatus = "Posted \(summary.sent) token events: \(summary.persisted) persisted, \(summary.duplicates) duplicates, \(summary.rejected) rejected." + if replayingPending { + return await postMuseCodeBridge(report: report, generation: generation, showNoNewStatus: false) + } + return true + } catch { + guard canPostMuseCodeBridge(generation: generation) else { return true } + museCodeBridgeStatus = "Bridge submission could not be confirmed.\u{00A0} The saved pending events will be checked on the next refresh." + return false + } + } + + private func loadMuseCodeBridgeCheckpoint() throws -> MuseCodeBridgeCheckpoint { + if let data = defaults.data(forKey: "museCodeIngestCheckpoint") { + guard data.count <= 8_388_608 else { throw MuseCodeBridgeCheckpoint.Failure.invalid } + let checkpoint = try JSONDecoder().decode(MuseCodeBridgeCheckpoint.self, from: data) + guard checkpoint.hasExpectedScope else { throw MuseCodeBridgeCheckpoint.Failure.invalid } + return checkpoint + } + var checkpoint = MuseCodeBridgeCheckpoint() + if let data = defaults.data(forKey: "museCodeIngestObservations") { + checkpoint.observations = try JSONDecoder().decode([String: MuseCodeSessionObservation].self, from: data) + } + guard checkpoint.hasExpectedScope else { throw MuseCodeBridgeCheckpoint.Failure.invalid } + return checkpoint + } + + private func saveMuseCodeBridgeCheckpoint(_ checkpoint: MuseCodeBridgeCheckpoint) throws { + defaults.set(try JSONEncoder().encode(checkpoint), forKey: "museCodeIngestCheckpoint") + guard defaults.synchronize() else { throw MuseCodeBridgeCheckpoint.Failure.persistence } + } + + @discardableResult + func saveMuseCodeIngestToken(_ raw: String) async -> Bool { + guard !museCodeIngestTokenBusy else { return false } + let token = sanitizedToken(raw) + guard !token.isEmpty else { museCodeIngestTokenStatus = "Enter the Muse ingest token."; return false } + museCodeIngestTokenBusy = true + museCodeBridgeGeneration &+= 1 + defer { finishMuseCodeTokenChange() } + do { + if let museCodeTokenSaveForTesting { try await museCodeTokenSaveForTesting(token) } + else { + try await TokenStore.save(token, server: MuseCodeSessionIngest.endpoint.absoluteString, + service: TokenStore.museCodeIngestService) + } + museCodeHasSavedIngestToken = true + defaults.set(true, forKey: "museCodeHasSavedIngestToken") + museCodeIngestTokenStatus = "Muse ingest token saved." + return true + } catch { museCodeIngestTokenStatus = "Keychain could not save the Muse ingest token."; return false } + } + + func reauthorizeMuseCodeIngestToken() async { + guard !museCodeIngestTokenBusy else { return } + museCodeIngestTokenBusy = true + museCodeBridgeGeneration &+= 1 + defer { finishMuseCodeTokenChange() } + let token: String? + if let museCodeTokenReauthorizeForTesting { token = await museCodeTokenReauthorizeForTesting() } + else { + token = await TokenStore.readAllowingInteraction(server: MuseCodeSessionIngest.endpoint.absoluteString, + service: TokenStore.museCodeIngestService) + } + guard let token, !sanitizedToken(token).isEmpty else { + museCodeIngestTokenStatus = "The saved Muse ingest token is unavailable in Keychain." + return + } + museCodeHasSavedIngestToken = true + defaults.set(true, forKey: "museCodeHasSavedIngestToken") + museCodeIngestTokenStatus = "Saved Muse ingest token authorized." + } + + func forgetMuseCodeIngestToken() async { + guard !museCodeIngestTokenBusy else { return } + museCodeIngestTokenBusy = true + museCodeBridgeGeneration &+= 1 + defer { finishMuseCodeTokenChange() } + do { + if let museCodeTokenDeleteForTesting { try await museCodeTokenDeleteForTesting() } + else { + try await TokenStore.delete(server: MuseCodeSessionIngest.endpoint.absoluteString, + service: TokenStore.museCodeIngestService) + } + museCodeHasSavedIngestToken = false + defaults.removeObject(forKey: "museCodeHasSavedIngestToken") + museCodeUsageBridgeEnabled = false + museCodeIngestTokenStatus = "Muse ingest token forgotten." + } catch { museCodeIngestTokenStatus = "Keychain could not forget the Muse ingest token." } + } + + private func finishMuseCodeTokenChange() { + museCodeIngestTokenBusy = false + if museCodeUsageBridgeEnabled, let museCodeReport { enqueueMuseCodeBridge(report: museCodeReport) } + } + private func appendRunawayAlert(_ record: RunawayAlertRecord) { var list = runawayAlertHistory list.insert(record, at: 0) @@ -3054,39 +3471,34 @@ final class MonitorModel: ObservableObject { "\(providerKey)\u{1f}\(windowId)" } - private nonisolated static func readLocalSources() async -> LocalQuotaResult { - async let primary = LocalQuotaReader().read() - async let cursor = CursorQuotaReader().read() - async let copilot = CopilotQuotaReader().read() - async let grokBot = GrokBotQuotaReader().read() - // EXTRA Grok Bot source beside Cursor DashboardService; `source: "gbu"` - // so Settings can rank/disable it without replacing the Cursor reader. - async let gbu = GbuQuotaReader().read() - async let kimi = KimiQuotaReader().read() - async let zcode = ZCodeQuotaReader().read() + private nonisolated static func readLocalSources( + preferences: QuotaReaderPreferences = .init() + ) async -> LocalQuotaResult { + async let registered = LocalQuotaReaderRegistry.builtIn.read(preferences: preferences) async let antigravity = AntigravitySummaryReader().read() - let results = await [primary, cursor, copilot, grokBot, gbu, kimi, zcode] + var result = await registered let summary = await antigravity - var windows = results.flatMap(\.windows) - var issues = results.reduce(into: [String: String]()) { $0.merge($1.issues) { _, next in next } } + var windows = result.windows + var issues = result.issues if summary.windows.contains(where: { $0.boundedRemainingPercent != nil }) { windows.removeAll { $0.canonicalProviderKey == "google-antigravity" } windows += summary.windows issues["google-antigravity"] = nil } - let consentNeeded = results.reduce(into: Set()) { $0.formUnion($1.consentNeeded) } + result = LocalQuotaResult(windows: windows, issues: issues, + consentNeeded: result.consentNeeded) // One reader's "could not read" placeholder says nothing when another // reader of the same provider has a reading (Grok Bot's gbu and // DashboardService), and used to be drawn as an empty second bar. - return LocalQuotaResult(windows: windows, issues: issues, consentNeeded: consentNeeded) - .droppingSupersededPlaceholders() + return result.droppingSupersededPlaceholders() } private nonisolated static func readLocalResult(useLocal: Bool, - testingResult: LocalQuotaResult?) async -> LocalQuotaResult? { + testingResult: LocalQuotaResult?, + preferences: QuotaReaderPreferences) async -> LocalQuotaResult? { guard useLocal else { return nil } if let testingResult { return testingResult } - return await readLocalSources() + return await readLocalSources(preferences: preferences) } } diff --git a/Sources/CodeCaps/MuseCodeBridgeCheckpoint.swift b/Sources/CodeCaps/MuseCodeBridgeCheckpoint.swift new file mode 100644 index 00000000..37fb7bab --- /dev/null +++ b/Sources/CodeCaps/MuseCodeBridgeCheckpoint.swift @@ -0,0 +1,28 @@ +import Foundation +import QuotaCore + +/// One atomic personal checkpoint keeps acknowledged baselines and uncertain deltas together. +struct MuseCodeBridgeCheckpoint: Codable { + struct Pending: Codable { + let events: [MuseCodePlannedEvent] + let updated: [String: MuseCodeSessionObservation] + } + var version = 1 + var receiver = MuseCodeSessionIngest.endpoint.absoluteString + var producer = MuseCodeSessionIngest.producerId + var observations: [String: MuseCodeSessionObservation] = [:] + var pending: Pending? + + var hasExpectedScope: Bool { + version == 1 && receiver == MuseCodeSessionIngest.endpoint.absoluteString + && producer == MuseCodeSessionIngest.producerId + && observations.count <= MuseCodeDeltaPlanner.maxTrackedSessions + && (pending?.updated.count ?? 0) <= MuseCodeDeltaPlanner.maxTrackedSessions + && (pending?.events.count ?? 0) <= MuseCodeDeltaPlanner.maxTrackedSessions + && observations.values.allSatisfy { $0.totalTokens >= 0 } + && (pending?.updated.values.allSatisfy { $0.totalTokens >= 0 } ?? true) + && (pending?.events.allSatisfy { $0.delta > 0 && $0.observation.totalTokens >= 0 } ?? true) + } + + enum Failure: Error { case invalid, persistence } +} diff --git a/Sources/CodeCaps/MuseCodePlugin.swift b/Sources/CodeCaps/MuseCodePlugin.swift new file mode 100644 index 00000000..f856beb7 --- /dev/null +++ b/Sources/CodeCaps/MuseCodePlugin.swift @@ -0,0 +1,28 @@ +import Foundation + +/// A plugin shown in the Console's Plugins section. +/// +/// The raw value is the plugin's stable identifier: it is persisted in the +/// Console page's storage key (`plugin:`), so it must never be renamed +/// once shipped. +public enum CodeCapsPlugin: String, CaseIterable, Identifiable, Sendable { + case museCode = "muse-code" + + public var id: String { rawValue } + + public var title: String { + switch self { + case .museCode: return "Muse" + } + } + + public var symbol: String { + switch self { + case .museCode: return "puzzlepiece.extension" + } + } + + public static func named(_ id: String) -> CodeCapsPlugin? { + CodeCapsPlugin(rawValue: id) + } +} diff --git a/Sources/CodeCaps/MuseCodePluginView.swift b/Sources/CodeCaps/MuseCodePluginView.swift new file mode 100644 index 00000000..677836ef --- /dev/null +++ b/Sources/CodeCaps/MuseCodePluginView.swift @@ -0,0 +1,290 @@ +import QuotaCore +import SwiftUI + +/// Routes a Plugins-section page to the plugin that owns it. +struct MuseCodePluginPage: View { + @ObservedObject var model: MonitorModel + let pluginId: String + + var body: some View { + if let plugin = CodeCapsPlugin.named(pluginId), plugin == .museCode { + MuseCodeMonitorPage(model: model) + } else { + Text("Plugin unavailable") + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.secondary) + } + } +} + +/// The Muse monitor plugin: current burn, contributor share, the +/// per-model split, and the deterministic monitor's state and controls. +struct MuseCodeMonitorPage: View { + @ObservedObject var model: MonitorModel + @State private var ingestToken = "" + + /// The standard-session kind's popup option, offered here beside the + /// feature it belongs to. It is the same preference the Alerts & + /// Alarms page edits — one stored option behind both surfaces — and + /// it ships off: the popup is opt-in. + private var standardSessionPopupBinding: Binding { + Binding(get: { model.alarmManager.preferences[.museCodeStandardSession].popup }, + set: { value in + var option = model.alarmManager.preferences[.museCodeStandardSession] + option.popup = value + model.alarmManager.preferences[.museCodeStandardSession] = option + }) + } + + private var window90: MuseCodeWindowUsage? { model.museCodeReport?.window(minutes: 90) } + private var window60: MuseCodeWindowUsage? { model.museCodeReport?.window(minutes: 60) } + + private var status: MuseCodeBurnMonitor.Status { + MuseCodeBurnMonitor.status(report: model.museCodeReport, issue: model.museCodeIssue, + thresholdTokens: model.museCodeBurnThresholdTokens) + } + + private var isWarning: Bool { + if case .warning = status { return true } + return false + } + + var body: some View { + VStack(alignment: .leading, spacing: 18) { + headerSection + if let issue = model.museCodeIssue { + Text(issue) + .font(.system(size: 12)) + .foregroundStyle(Theme.warning) + .fixedSize(horizontal: false, vertical: true) + } + monitorSection + burnSection + contributorSection + modelsSection + alertsSection + bridgeSection + Text("Session stores rotate snapshots aggressively, so every total on this page is a floor rather than an exact count.") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + // MARK: - Header + + private var headerSection: some View { + HStack(alignment: .top, spacing: 12) { + Image(systemName: "puzzlepiece.extension") + .font(.system(size: 26)) + .foregroundStyle(isWarning ? Theme.warning : Theme.ink.opacity(0.8)) + .frame(width: 32, height: 32) + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 8) { + Text("Muse Monitor") + .font(.system(size: 18, weight: .bold, design: .rounded)) + if isWarning { + Text("WARNING") + .font(.system(size: 10, weight: .bold)) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Theme.warning, in: Capsule()) + } + } + Text("Deterministic monitoring of Muse token burn and standard-model sessions on this Mac.") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + Spacer() + } + } + + // MARK: - Sections + + private var monitorSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("MONITOR") + VStack(alignment: .leading, spacing: 8) { + row("Status", status.text) + if let report = model.museCodeReport { + row("Last Read", report.generatedAt.formatted(date: .omitted, time: .standard)) + } + if let alert = model.museCodeBurnAlert { + row("Burn Alert", alert.body) + } else if let alert = model.museCodeStandardSessionAlert { + row("Standard Session Alert", alert.body) + } + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var burnSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("BURN") + VStack(alignment: .leading, spacing: 8) { + if let window = window90 { + row("Last 90 Minutes", "\(MuseCodeFormatting.grouped(window.totalTokens)) tokens") + row("Burn Rate", "\(MuseCodeFormatting.grouped(Int(window.tokensPerHour.rounded()))) tokens per hour") + row("Active Sessions", "\(window.activeSessions)") + } + if let window = window60 { + row("Last 60 Minutes", "\(MuseCodeFormatting.grouped(window.totalTokens)) tokens") + } + if window90 == nil { + row("Burn", "No reading yet") + } + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var contributorSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("CONTRIBUTOR SHARE") + VStack(alignment: .leading, spacing: 8) { + if let window = window90, let share = window.contributorShare { + row("Contributor Share (90 minutes)", MuseCodeFormatting.percent(share)) + row("Contributor Tokens", MuseCodeFormatting.grouped(window.contributorTokens)) + if share < 1 { + row("Standard Tokens", MuseCodeFormatting.grouped(window.totalTokens - window.contributorTokens)) + } + } else { + row("Contributor Share (90 minutes)", "No tokens in window") + } + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var modelsSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("MODELS") + VStack(alignment: .leading, spacing: 8) { + if let window = window90, !window.models.isEmpty { + ForEach(window.models) { usage in + HStack(spacing: 10) { + Text(usage.modelId) + .font(.system(size: 12).monospaced()) + .lineLimit(1) + .truncationMode(.middle) + Spacer(minLength: 8) + Text(usage.isContributor ? "Contributor" : "Standard") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(usage.isContributor ? Theme.accent : Theme.warning) + Text("\(MuseCodeFormatting.grouped(usage.tokens)) tokens") + .font(.system(size: 12).monospacedDigit()) + Text(MuseCodeFormatting.percent(usage.share(of: window.totalTokens))) + .font(.system(size: 12).monospacedDigit()) + .foregroundStyle(.secondary) + .frame(width: 52, alignment: .trailing) + } + } + } else { + row("Models", "No model activity in window") + } + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var alertsSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("ALERTS") + VStack(alignment: .leading, spacing: 12) { + Toggle("Muse Alerts", isOn: $model.museCodeBurnAlertsEnabled) + Toggle("Popup Warning For Standard Sessions", isOn: standardSessionPopupBinding) + Text("When the popup warning is on, a standard-session alert also opens a popup window naming the session and its model." + + sentenceGap + + "It is off by default and is the same switch as the Popup toggle for Muse Standard Sessions in Alerts & Alarms.") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + HStack(spacing: 12) { + Text("Burn Threshold") + .font(.system(size: 13, weight: .medium)) + .frame(width: 150, alignment: .leading) + Text("\(MuseCodeFormatting.grouped(model.museCodeBurnThresholdTokens)) tokens in 90 minutes") + .font(.system(size: 13).monospacedDigit()) + Stepper("", value: $model.museCodeBurnThresholdTokens, + in: 100_000...50_000_000, step: 100_000) + .labelsHidden() + } + Text("Two alert kinds: museCodeBurn fires when burn passes the threshold while a session is on a standard model." + + sentenceGap + + "museCodeStandardSession fires on its own the moment a session starts on, or switches to, a standard model, whatever the burn rate.") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var bridgeSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("USAGE MONITOR BRIDGE") + VStack(alignment: .leading, spacing: 12) { + Toggle("Post Token Events To Usage Monitor", isOn: $model.museCodeUsageBridgeEnabled) + SecureField("Muse Ingest Token", text: $ingestToken) + .textFieldStyle(.roundedBorder) + .disabled(model.museCodeIngestTokenBusy) + HStack { + Button("Save Token") { + Task { if await model.saveMuseCodeIngestToken(ingestToken) { ingestToken = "" } } + } + .disabled(ingestToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + Button("Re-Authorize Saved Token") { + Task { await model.reauthorizeMuseCodeIngestToken() } + } + Button("Forget Token") { + Task { + await model.forgetMuseCodeIngestToken() + if !model.museCodeHasSavedIngestToken { ingestToken = "" } + } + } + .disabled(!model.museCodeHasSavedIngestToken) + if model.museCodeIngestTokenBusy { ProgressView().controlSize(.small) } + } + .disabled(model.museCodeIngestTokenBusy) + if let tokenStatus = model.museCodeIngestTokenStatus { + Text(tokenStatus).font(.system(size: 11)).foregroundStyle(.secondary) + } + row("Bridge Status", model.museCodeBridgeStatus ?? "Not posted yet") + Text("Posts each session's new tokens since the last reading to Usage Monitor, as muse-code token events." + + sentenceGap + + "Replays dedupe server-side, so a failed post is safe to retry.") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private func row(_ label: String, _ value: String) -> some View { + HStack(alignment: .top, spacing: 12) { + Text(label) + .font(.system(size: 13, weight: .medium)) + .frame(width: 170, alignment: .leading) + Text(value) + .font(.system(size: 13)) + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + } + } +} diff --git a/Sources/CodeCaps/QuitConfirmation.swift b/Sources/CodeCaps/QuitConfirmation.swift new file mode 100644 index 00000000..69b57d64 --- /dev/null +++ b/Sources/CodeCaps/QuitConfirmation.swift @@ -0,0 +1,33 @@ +import AppKit +import Carbon + +enum QuitConfirmationChoice: Equatable { + case closeAndKeepRunning + case quit + case cancel + + init(response: NSApplication.ModalResponse) { + switch response { + case .alertFirstButtonReturn: + self = .closeAndKeepRunning + case .alertSecondButtonReturn: + self = .quit + default: + self = .cancel + } + } +} + +enum QuitConfirmationPolicy { + static func shouldConfirm(systemTerminationReason: OSType?, automaticInstallInProgress: Bool) -> Bool { + guard !automaticInstallInProgress else { return false } + guard let systemTerminationReason else { return true } + return ![kAEQuitAll, kAEShutDown, kAERestart, kAEReallyLogOut].contains(systemTerminationReason) + } +} + +extension QuitConfirmationPolicy { + static func shouldShowStatusItem(displayMode: DisplayMode, keepRunningOverride: Bool) -> Bool { + displayMode != .dock || keepRunningOverride + } +} diff --git a/Sources/CodeCaps/ResetAlarmManager.swift b/Sources/CodeCaps/ResetAlarmManager.swift index 425474d0..cb882f3d 100644 --- a/Sources/CodeCaps/ResetAlarmManager.swift +++ b/Sources/CodeCaps/ResetAlarmManager.swift @@ -242,6 +242,7 @@ public final class ResetAlarmManager: ObservableObject { private var updatingLegacySound = false private(set) var detectedResetHistory: [ResetAlertRecord] = [] var onUsageDelivery: ((UsageAlertKind, String, String, UsageAlertOption) -> Void)? + var additionalDelivery: ((UsageAlertKind, String, String, String) -> Void)? private var popupWindows: [NSWindow] = [] private let defaults: UserDefaults @@ -581,6 +582,7 @@ public final class ResetAlarmManager: ObservableObject { identifier: String, navigation: AlertNavigation? = nil) { let option = preferences[kind] guard option.enabled else { return } + additionalDelivery?(kind, title, body, identifier) if let onUsageDelivery { onUsageDelivery(kind, title, body, option) return diff --git a/Sources/CodeCaps/SMSAlertController.swift b/Sources/CodeCaps/SMSAlertController.swift new file mode 100644 index 00000000..e543f43e --- /dev/null +++ b/Sources/CodeCaps/SMSAlertController.swift @@ -0,0 +1,137 @@ +import Combine +import Foundation +import QuotaCore + +/// The injected boundary keeps controller tests off the real Keychain. +@MainActor +struct SMSCredentialAccess { + var load: () async -> TwilioSMSCredentials? + var save: (TwilioSMSCredentials) async throws -> Void + var clear: () async throws -> Void + var reauthorize: () async -> TwilioSMSCredentials? + + static let live = Self(load: { await TwilioCredentialStore.shared.load() }, + save: { try await TwilioCredentialStore.shared.save($0) }, + clear: { try await TwilioCredentialStore.shared.clear() }, + reauthorize: { await TwilioCredentialStore.shared.readAllowingInteraction() }) +} + +@MainActor +final class SMSAlertController: ObservableObject { + enum Keys { + static let preferences = "smsAlertPreferences" + static let configuration = "twilioSMSConfiguration" + static let hasSetup = "twilioSMSHasSetup" + static let history = "smsAlertSendHistory" + } + + @Published var preferences: SMSAlertPreferences { + didSet { preferences.save(to: defaults, key: Keys.preferences) } + } + @Published private(set) var configuration: TwilioSMSConfiguration? + @Published private(set) var hasSavedSetup: Bool + @Published private(set) var status: String? + @Published private(set) var isWorking = false + private let defaults: UserDefaults + private let credentialAccess: SMSCredentialAccess + private let coordinator: SMSAlertCoordinator + private var setupRevision: UInt64 = 0 + + init(defaults: UserDefaults, credentialAccess: SMSCredentialAccess? = nil, + coordinator: SMSAlertCoordinator? = nil) { + self.defaults = defaults + self.credentialAccess = credentialAccess ?? .live + self.coordinator = coordinator ?? SMSAlertCoordinator(persistence: .userDefaults(defaults, key: Keys.history)) + self.preferences = .load(from: defaults, key: Keys.preferences) + self.hasSavedSetup = defaults.bool(forKey: Keys.hasSetup) + if let data = defaults.data(forKey: Keys.configuration) { + self.configuration = try? JSONDecoder().decode(TwilioSMSConfiguration.self, from: data) + } + } + + /// Called only for a newly detected event, never while reading exported history. + @discardableResult + func deliver(kind: String, title: String, body: String, eventID: String) -> Task? { + guard preferences[kind], hasSavedSetup else { return nil } + let revision = setupRevision + return Task { [weak self] in + guard let self else { return } + let credentials = await credentialAccess.load() + guard revision == setupRevision, preferences[kind], hasSavedSetup else { return } + let result = await coordinator.send(eventID: eventID, kind: kind, title: title, body: body, + preferences: preferences, credentials: credentials) + guard revision == setupRevision else { return } + switch result { + case .accepted: status = "Text accepted by Twilio." + case .failed(let failure): status = failure.localizedDescription + case .disabled, .duplicate: break + } + } + } + + @discardableResult + func saveSetup(configuration: TwilioSMSConfiguration, apiKeySecret: String) async -> Bool { + guard !isWorking else { return false } + isWorking = true + setupRevision &+= 1 + defer { isWorking = false } + do { + var secret = apiKeySecret.trimmingCharacters(in: .whitespacesAndNewlines) + if secret.isEmpty { + guard let existing = await credentialAccess.load(), + existing.configuration.accountSID == configuration.accountSID, + existing.configuration.apiKeySID == configuration.apiKeySID else { + status = "Enter the secret for this Twilio API key." + return false + } + secret = existing.apiKeySecret + } + let credentials = TwilioSMSCredentials(configuration: configuration, apiKeySecret: secret) + try credentials.validate() + try await credentialAccess.save(credentials) + remember(configuration) + status = "Twilio setup saved." + return true + } catch let failure as TwilioSMSFailure { status = failure.localizedDescription } + catch { status = "Keychain could not save the Twilio setup." } + return false + } + + func forgetSetup() async { + guard !isWorking else { return } + isWorking = true + setupRevision &+= 1 + defer { isWorking = false } + do { + try await credentialAccess.clear() + hasSavedSetup = false + configuration = nil + defaults.removeObject(forKey: Keys.configuration) + defaults.removeObject(forKey: Keys.hasSetup) + // Reservations remain after Forget, preventing an old event from being sent again. + status = "Twilio setup forgotten." + } catch { status = "Keychain could not forget the Twilio setup." } + } + + /// Invoked only from the explicit settings button. + func reauthorizeSavedSetup() async { + guard !isWorking else { return } + isWorking = true + setupRevision &+= 1 + defer { isWorking = false } + guard let credentials = await credentialAccess.reauthorize(), + (try? credentials.validate()) != nil else { + status = "The saved Twilio setup is unavailable in Keychain." + return + } + remember(credentials.configuration) + status = "Saved Twilio setup authorized." + } + + private func remember(_ config: TwilioSMSConfiguration) { + configuration = config + hasSavedSetup = true + defaults.set(true, forKey: Keys.hasSetup) + defaults.set(try? JSONEncoder().encode(config), forKey: Keys.configuration) + } +} diff --git a/Sources/CodeCaps/SMSSettingsView.swift b/Sources/CodeCaps/SMSSettingsView.swift new file mode 100644 index 00000000..34f0ffba --- /dev/null +++ b/Sources/CodeCaps/SMSSettingsView.swift @@ -0,0 +1,80 @@ +import QuotaCore +import SwiftUI + +@MainActor +struct SMSAlertKindToggle: View { + @ObservedObject var controller: SMSAlertController + let kindID: String + + var body: some View { + if SMSAlertPreferences.eligibleKinds.contains(kindID) { + Toggle("SMS", isOn: Binding(get: { controller.preferences[kindID] }, + set: { controller.preferences[kindID] = $0 })) + .help("Send a text through your saved Twilio setup when this alert is enabled.") + } + } +} + +@MainActor +struct SMSSettingsView: View { + @ObservedObject var controller: SMSAlertController + @State private var accountSID = "" + @State private var apiKeySID = "" + @State private var apiKeySecret = "" + @State private var messagingServiceSID = "" + @State private var recipient = "" + + var body: some View { + Section { + TextField("Account SID", text: $accountSID) + TextField("API Key SID", text: $apiKeySID) + SecureField(controller.hasSavedSetup ? "API Key Secret (Blank Keeps Saved Secret)" : "API Key Secret", + text: $apiKeySecret) + TextField("Messaging Service SID", text: $messagingServiceSID) + TextField("Recipient (E.164)", text: $recipient) + HStack { + Button("Save Setup") { + Task { + let saved = await controller.saveSetup(configuration: .init(accountSID: accountSID, + apiKeySID: apiKeySID, messagingServiceSID: messagingServiceSID, recipient: recipient), + apiKeySecret: apiKeySecret) + if saved { apiKeySecret = "" } + } + } + Button("Forget Setup") { + Task { + await controller.forgetSetup() + if !controller.hasSavedSetup { apiKeySecret = ""; adoptConfiguration() } + } + } + .disabled(!controller.hasSavedSetup) + Button("Re-Authorize Saved Setup") { + Task { + await controller.reauthorizeSavedSetup() + adoptConfiguration() + } + } + .disabled(!controller.hasSavedSetup) + if controller.isWorking { ProgressView().controlSize(.small) } + } + .disabled(controller.isWorking) + if let status = controller.status { + Text(status).font(.caption).foregroundStyle(.secondary) + } + } header: { + Text("Twilio Text Alerts") + } footer: { + Text("SMS starts off for every alert kind." + sentenceGap + + "Enable SMS beside an eligible alert above and save your own Twilio API key, Messaging Service, and recipient." + sentenceGap + + "Your Twilio account pays for texts; accepted submissions do not confirm delivery.") + } + .onAppear { adoptConfiguration() } + } + + private func adoptConfiguration() { + accountSID = controller.configuration?.accountSID ?? "" + apiKeySID = controller.configuration?.apiKeySID ?? "" + messagingServiceSID = controller.configuration?.messagingServiceSID ?? "" + recipient = controller.configuration?.recipient ?? "" + } +} diff --git a/Sources/CodeCaps/SettingsViews.swift b/Sources/CodeCaps/SettingsViews.swift index 741df9b0..585b6870 100644 --- a/Sources/CodeCaps/SettingsViews.swift +++ b/Sources/CodeCaps/SettingsViews.swift @@ -483,7 +483,8 @@ struct SettingsSourcesFleetPage: View { private func readerRow(_ reader: ReaderStatus) -> some View { let section = model.sections.first { $0.providerKey == reader.providerKey } let issue = model.issues[reader.providerKey] - let healthy = issue == nil && !(section?.windows.isEmpty ?? true) + let optionalEnabled = reader.optionalReaderID.map(model.isOptionalQuotaReaderEnabled) ?? true + let healthy = optionalEnabled && issue == nil && !(section?.windows.isEmpty ?? true) // A reader whose credential is on this Mac but unreadable by this // build gets a button rather than a sentence it cannot act on. let needsConsent = model.consentNeeded.contains(reader.providerKey) @@ -498,12 +499,28 @@ struct SettingsSourcesFleetPage: View { .font(.system(size: 11)) .foregroundStyle(.secondary) Spacer(minLength: 8) - Image(systemName: healthy ? "checkmark.circle" : "exclamationmark.triangle") - .font(.system(size: 12)) - .foregroundStyle(healthy ? Theme.accent : Theme.warning) - .accessibilityHidden(true) + if let readerID = reader.optionalReaderID { + Toggle("", isOn: Binding( + get: { model.isOptionalQuotaReaderEnabled(readerID) }, + set: { model.setOptionalQuotaReaderEnabled($0, readerID: readerID) })) + .labelsHidden() + .toggleStyle(.switch) + .controlSize(.mini) + .help(optionalEnabled ? "Turn Off \(reader.label) Quota Reads" : "Turn On \(reader.label) Quota Reads") + .accessibilityLabel("Read \(reader.label) Quota") + } else { + Image(systemName: healthy ? "checkmark.circle" : "exclamationmark.triangle") + .font(.system(size: 12)) + .foregroundStyle(healthy ? Theme.accent : Theme.warning) + .accessibilityHidden(true) + } } - if let issue { + if !optionalEnabled { + Text("Quota reads are off for this provider.") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } else if let issue { Text(issue) .font(.system(size: 11)) .foregroundStyle(.secondary) @@ -938,11 +955,12 @@ private struct ReauthorizeCaption: View { } } -/// The seven local readers, named by the credential they actually read. +/// Local quota readers, named by the credential they actually read. struct ReaderStatus { let providerKey: String let label: String let source: String + var optionalReaderID: String? = nil static let all: [ReaderStatus] = [ ReaderStatus(providerKey: "anthropic", label: "Claude", source: "Claude Code credentials"), @@ -953,6 +971,8 @@ struct ReaderStatus { ReaderStatus(providerKey: "grok", label: "Grok", source: "Grok CLI credentials"), ReaderStatus(providerKey: "grok-bot", label: "Grok Bot", source: "Cursor app session"), 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"), ] } @@ -1389,6 +1409,7 @@ struct SettingsNotificationsPage: View { .frame(width: 200, alignment: .leading) Toggle("Notification", isOn: alertBinding(kind, \.notification)) Toggle("Popup", isOn: alertBinding(kind, \.popup)) + SMSAlertKindToggle(controller: model.smsAlerts, kindID: kind.rawValue) Picker("Sound", selection: Binding( get: { model.alarmManager.preferences[kind].sound }, set: { model.alarmManager.setSound($0, for: kind) })) { @@ -1408,6 +1429,7 @@ struct SettingsNotificationsPage: View { + "Quota Exhausted alerts when \(QuotaCapRule.spentThreshold.formatted(.number.precision(.fractionLength(0...1))))% or less remains." + sentenceGap + "Provider bells choose which scheduled and vendor resets alert on this Mac.") } + SMSSettingsView(controller: model.smsAlerts) if let row = model.displaySections.first(where: { $0.providerKey == model.runawayAlertHistory.first?.providerKey }) ?? model.displaySections.first { diff --git a/Sources/CodeCaps/TokenStore.swift b/Sources/CodeCaps/TokenStore.swift index ff3a3fd3..a354c63c 100644 --- a/Sources/CodeCaps/TokenStore.swift +++ b/Sources/CodeCaps/TokenStore.swift @@ -26,11 +26,15 @@ enum TokenStore { static let readService = serviceName(suffix: "read-token") static let syncService = serviceName(suffix: "sync-token") - - /// The two service names this build owns: its Read Token and its Push - /// Token. A `.dev` build's names differ from the release app's, so neither - /// can reach the other's items. - static var ownServices: Set { [readService, syncService] } + /// The Muse plugin's bridge token: a producer-scoped Usage Monitor + /// ingest token for `muse-code`, kept apart from this app's own Push + /// Token because a scoped token authorizes exactly one producer. + static let museCodeIngestService = serviceName(suffix: "muse-code-ingest-token") + + /// The service names this build owns: its Read Token, its Push Token, + /// and the Muse bridge token. A `.dev` build's names differ from the + /// release app's, so neither can reach the other's items. + static var ownServices: Set { [readService, syncService, museCodeIngestService] } /// Whether `service` is exactly one of CodeCaps's own two items. The store /// refuses every other name before any Keychain call is made, so nothing diff --git a/Sources/CodeCaps/TwilioCredentialStore.swift b/Sources/CodeCaps/TwilioCredentialStore.swift new file mode 100644 index 00000000..e33db186 --- /dev/null +++ b/Sources/CodeCaps/TwilioCredentialStore.swift @@ -0,0 +1,60 @@ +import Foundation +import QuotaCore + +/// One narrowly scoped cache reuses the existing bounded, prompt-free Keychain path. +actor TwilioCredentialStore { + static let shared = TwilioCredentialStore() + private let service: String + private let cache: TokenCache + private let account = "sms-setup-v1" + + init(calls: KeychainCalls = .live, bundleIdentifier: String? = Bundle.main.bundleIdentifier, + bounds: TokenCache.Bounds = .init()) { + let service = Self.serviceName(bundleIdentifier: bundleIdentifier) + self.service = service + self.cache = TokenCache(calls: calls, bounds: bounds, ownServices: [service], log: { _ in }) + } + + nonisolated static func serviceName(bundleIdentifier: String? = Bundle.main.bundleIdentifier) -> String { + TokenStore.serviceName(suffix: "twilio-sms", bundleIdentifier: bundleIdentifier) + } + + func load() async -> TwilioSMSCredentials? { + decode(await cache.token(server: account, service: service)) + } + + /// Only an explicit settings action may allow a Keychain authorization panel. + func readAllowingInteraction() async -> TwilioSMSCredentials? { + decode(await cache.readAllowingInteraction(server: account, service: service)) + } + + func save(_ credentials: TwilioSMSCredentials) async throws { + try credentials.validate() + guard let encoded = try? JSONEncoder().encode(credentials), + let raw = String(data: encoded, encoding: .utf8) else { throw StoreFailure.invalidRecord } + do { try await cache.save(raw, server: account, service: service) } + catch { throw StoreFailure.keychain } + } + + func clear() async throws { + do { try await cache.delete(server: account, service: service) } + catch { throw StoreFailure.keychain } + } + + private func decode(_ raw: String?) -> TwilioSMSCredentials? { + guard let raw, let data = raw.data(using: .utf8), + let credentials = try? JSONDecoder().decode(TwilioSMSCredentials.self, from: data), + (try? credentials.validate()) != nil else { return nil } + return credentials + } + + enum StoreFailure: Error, LocalizedError { + case invalidRecord, keychain + var errorDescription: String? { + switch self { + case .invalidRecord: return "The Twilio setup could not be encoded." + case .keychain: return "Keychain could not update the saved Twilio setup." + } + } + } +} diff --git a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift new file mode 100644 index 00000000..9859601d --- /dev/null +++ b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift @@ -0,0 +1,104 @@ +import Foundation + +/// A typed extension point for adding another asynchronous local quota reader. +public protocol LocalQuotaReading: Sendable { + func read() async -> LocalQuotaResult +} + +extension LocalQuotaReader: LocalQuotaReading {} +extension CursorQuotaReader: LocalQuotaReading {} +extension CopilotQuotaReader: LocalQuotaReading {} +extension GrokBotQuotaReader: LocalQuotaReading {} +extension GbuQuotaReader: LocalQuotaReading {} +extension KimiQuotaReader: LocalQuotaReading {} +extension ZCodeQuotaReader: LocalQuotaReading {} + +/// A registered reader and the non-secret configuration metadata used to +/// describe it in the app. The factory keeps credential reads inside the +/// selected reader and is never invoked for a disabled optional reader. +public struct LocalQuotaReaderRegistration: Sendable { + public let id: String + public let label: String + public let configurationMetadata: [String: String] + public let isOptional: Bool + private let makeReader: @Sendable () -> any LocalQuotaReading + + public init(id: String, label: String, configurationMetadata: [String: String] = [:], + isOptional: Bool = false, + makeReader: @escaping @Sendable () -> any LocalQuotaReading) { + self.id = id + self.label = label + self.configurationMetadata = configurationMetadata + self.isOptional = isOptional + self.makeReader = makeReader + } + + fileprivate func read() async -> LocalQuotaResult { + await makeReader().read() + } +} + +/// Concurrent, deterministic aggregator for local quota readers. Results are +/// merged in registration order to preserve the existing issue precedence. +public struct LocalQuotaReaderRegistry: Sendable { + public let registrations: [LocalQuotaReaderRegistration] + + public init(registrations: [LocalQuotaReaderRegistration]) { + self.registrations = registrations + } + + public var optionalRegistrations: [LocalQuotaReaderRegistration] { + registrations.filter(\.isOptional) + } + + public func read(preferences: QuotaReaderPreferences = .init()) async -> LocalQuotaResult { + let selected = registrations.enumerated().filter { _, registration in + !registration.isOptional || preferences.isEnabled(registration.id) + } + let results = await withTaskGroup(of: (Int, LocalQuotaResult).self, + returning: [(Int, LocalQuotaResult)].self) { group in + for (index, registration) in selected { + group.addTask { (index, await registration.read()) } + } + var collected: [(Int, LocalQuotaResult)] = [] + for await result in group { collected.append(result) } + return collected.sorted { $0.0 < $1.0 } + } + var windows: [QuotaWindow] = [] + var issues: [String: String] = [:] + var consentNeeded: Set = [] + for (_, result) in results { + windows.append(contentsOf: result.windows) + issues.merge(result.issues) { _, next in next } + consentNeeded.formUnion(result.consentNeeded) + } + return LocalQuotaResult(windows: windows, issues: issues, consentNeeded: consentNeeded) + } + + /// The concrete built-ins stay explicit while the typed registration seam + /// allows future providers without a dynamic code loader. + public static let builtIn = LocalQuotaReaderRegistry(registrations: [ + LocalQuotaReaderRegistration(id: "local-primary", label: "Built-In Provider Sessions", + configurationMetadata: ["providers": "anthropic,openai,grok,minimax,google-antigravity"]) { + LocalQuotaReader() + }, + LocalQuotaReaderRegistration(id: "cursor", label: "Cursor", configurationMetadata: ["providerKey": "cursor"]) { + CursorQuotaReader() + }, + LocalQuotaReaderRegistration(id: "github-copilot", label: "GitHub Copilot", configurationMetadata: ["providerKey": "github-copilot"]) { + CopilotQuotaReader() + }, + LocalQuotaReaderRegistration(id: "grok-bot", label: "Grok Bot", configurationMetadata: ["providerKey": "grok-bot"]) { + GrokBotQuotaReader() + }, + LocalQuotaReaderRegistration(id: "gbu", label: "Grok Build Usage", configurationMetadata: ["providerKey": "grok-bot"]) { + GbuQuotaReader() + }, + LocalQuotaReaderRegistration(id: "kimi", label: "Kimi", configurationMetadata: ["providerKey": "kimi"], isOptional: true) { + KimiQuotaReader() + }, + LocalQuotaReaderRegistration(id: "zcode", label: "Z.ai / ZCode", configurationMetadata: ["providerKey": "zcode"], isOptional: true) { + ZCodeQuotaReader() + }, + ]) +} diff --git a/Sources/QuotaCore/MuseCodeBurnMonitor.swift b/Sources/QuotaCore/MuseCodeBurnMonitor.swift new file mode 100644 index 00000000..5e3a1f1b --- /dev/null +++ b/Sources/QuotaCore/MuseCodeBurnMonitor.swift @@ -0,0 +1,134 @@ +import Foundation + +/// Number formatting shared by the monitor's alert text and the plugin page, +/// so the words in a notification and the figures on screen cannot drift. +public enum MuseCodeFormatting { + public static func grouped(_ value: Int) -> String { + let formatter = NumberFormatter() + formatter.numberStyle = .decimal + return formatter.string(from: NSNumber(value: value)) ?? "\(value)" + } + + public static func percent(_ share: Double) -> String { + String(format: "%.1f%%", share * 100) + } +} + +/// The Muse plugin's deterministic rule set. Pure code: a report in, +/// an alert (or not) out — no I/O, no clock of its own, no model anywhere. +/// +/// Two distinct findings live here and in +/// `MuseCodeStandardSessionDetector`, because they are two distinct alert +/// kinds at the app level: +/// +/// - `BurnAlert` (kind `museCodeBurn`): the combined rule the owner asked +/// for — trailing-90-minute burn above the threshold AND at least one +/// session currently on a standard model. +/// - Standard-session events (kind `museCodeStandardSession`): the +/// contributor finding on its own, fired by the detector the moment a +/// session starts on, or switches to, a standard model, independent of +/// the burn threshold, so a future channel can subscribe to the finding +/// itself rather than to the burn alert's side effect. +/// +/// Neither rule uses the contributor token share. A share computed from +/// rotating session snapshots moves for reasons unrelated to either +/// question — stale sessions inside the window, token weight, last-segment +/// attribution — and reads below 100% even when every live session is on a +/// contributor model. Presence is the signal: which sessions are on +/// standard models right now. +public enum MuseCodeBurnMonitor { + public static let defaultThresholdTokens = 4_000_000 + public static let alertCooldown: TimeInterval = 3_600 + public static let windowMinutes = 90 + + public struct BurnAlert: Equatable, Sendable { + public let totalTokens: Int + public let thresholdTokens: Int + public let standardSessions: [MuseCodeStandardSessionEvent] + public let observedAt: Date + + public init(totalTokens: Int, thresholdTokens: Int, + standardSessions: [MuseCodeStandardSessionEvent], observedAt: Date) { + self.totalTokens = totalTokens + self.thresholdTokens = thresholdTokens + self.standardSessions = standardSessions + self.observedAt = observedAt + } + + public var title: String { "Muse Burn Above Threshold" } + + public var body: String { + "Muse used \(MuseCodeFormatting.grouped(totalTokens)) tokens in the last 90 minutes, above the \(MuseCodeFormatting.grouped(thresholdTokens)) token threshold." + + sentenceGap + + "Standard-model sessions: \(Self.sessionList(standardSessions))." + } + + static func sessionList(_ sessions: [MuseCodeStandardSessionEvent]) -> String { + sessions.map { "\($0.sessionId) on \($0.modelId)" }.joined(separator: ", ") + } + } + + /// The monitor state the plugin page shows, derived from the same + /// evaluation that fires the alerts. + public enum Status: Equatable, Sendable { + case storeUnavailable + case noActivity + case belowThreshold(totalTokens: Int) + case allContributor(totalTokens: Int) + case currentModelsUnknown(totalTokens: Int) + case warning(BurnAlert) + + public var text: String { + switch self { + case .storeUnavailable: return "Session store unavailable" + case .noActivity: return "No Muse activity in the last 90 minutes" + case .belowThreshold: return "Below the burn threshold" + case .allContributor: return "All sessions on contributor models" + case .currentModelsUnknown: return "Current session models unavailable" + case .warning: return "Burn threshold exceeded on standard models" + } + } + } + + /// The standard-model sessions in one reading: the detector's presence + /// test over the reading's latest per-session observations. + public static func standardSessions(in report: MuseCodeSessionReport) -> [MuseCodeStandardSessionEvent] { + MuseCodeStandardSessionDetector.standardSessions( + in: report.currentModelObservations) + } + + /// The combined rule. "Exceeds" is strict: a window exactly at the + /// threshold has not exceeded it. The standard-model condition is + /// presence — at least one session in the reading is on a standard + /// model — never the contributor token share. + public static func evaluateBurn(report: MuseCodeSessionReport, + thresholdTokens: Int) -> BurnAlert? { + guard let window = report.window(minutes: windowMinutes), + window.totalTokens > thresholdTokens else { return nil } + let standard = standardSessions(in: report) + guard !standard.isEmpty else { return nil } + return BurnAlert(totalTokens: window.totalTokens, + thresholdTokens: thresholdTokens, + standardSessions: standard, + observedAt: report.generatedAt) + } + + public static func status(report: MuseCodeSessionReport?, issue: String?, + thresholdTokens: Int) -> Status { + guard let report else { return .storeUnavailable } + guard let window = report.window(minutes: windowMinutes), + window.totalTokens > 0 else { return .noActivity } + if let alert = evaluateBurn(report: report, thresholdTokens: thresholdTokens) { + return .warning(alert) + } + if standardSessions(in: report).isEmpty { + guard !report.currentModelObservations.isEmpty, + report.currentModelObservations.allSatisfy({ observation in + guard let model = observation.modelId, !model.isEmpty else { return false } + return MuseCodeStandardSessionDetector.isContributor(modelId: model) + }) else { return .currentModelsUnknown(totalTokens: window.totalTokens) } + return .allContributor(totalTokens: window.totalTokens) + } + return .belowThreshold(totalTokens: window.totalTokens) + } +} diff --git a/Sources/QuotaCore/MuseCodeSessionIngest.swift b/Sources/QuotaCore/MuseCodeSessionIngest.swift new file mode 100644 index 00000000..7b14b674 --- /dev/null +++ b/Sources/QuotaCore/MuseCodeSessionIngest.swift @@ -0,0 +1,208 @@ +import Foundation + +/// The Muse bridge to Usage Monitor, built against the verified +/// session-event contract (Usage Monitor PR #1862): POST the v2 envelope to +/// `/api/ingest/usage` with the `muse-code` scoped producer token, one token +/// event per session observation. +/// +/// Delta discipline is the contract's core: a session's latest snapshot +/// total is cumulative for its current segment, so the bridge posts only the +/// positive delta since its previous observation — never the cumulative +/// total, which the server would sum into a double count. When a session's +/// segment resets (or its model changes), the new segment's total is the +/// delta. Event ids are stable per (session, snapshot, model), so a replay +/// after a failed post dedupes server-side instead of double-counting. +public enum MuseCodeSessionIngest { + public static let producerId = "muse-code" + public static let provider = "muse-code" + public static let service = "muse-code" + public static let source = "muse-session-stores" + public static let maxEventsPerBatch = 100 + public static let endpoint = URL(string: "https://usage.jays.services/api/ingest/usage")! + + public static func eventId(sessionId: String, snapshotId: String, modelId: String) -> String { + "codecaps-muse-code:\(sessionId):\(snapshotId):\(modelId)" + } + + public static func event(observation: MuseCodeSessionObservation, delta: Int) -> [String: Any] { + let metadata: [String: Any] = [ + "sessionId": observation.sessionId, + "contributor": observation.isContributor, + "source": source + ] + let event: [String: Any] = [ + "eventId": eventId(sessionId: observation.sessionId, + snapshotId: observation.snapshotId, + modelId: observation.modelId), + "provider": provider, + "service": service, + "producerKeyRef": observation.modelId, + "metricType": "usage", + "unit": "token", + "quantity": delta, + "billingMode": "estimated", + "confidence": "estimated", + "occurredAt": ISO8601DateFormatter().string(from: observation.observedAt), + "metadata": metadata + ] + return event + } + + public static func eventBatches(events: [[String: Any]]) -> [[[String: Any]]] { + stride(from: 0, to: events.count, by: maxEventsPerBatch).map { offset in + Array(events[offset.. Data { + let root: [String: Any] = [ + "schemaVersion": 2, + "producerId": producerId, + "events": events + ] + return try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]) + } +} + +/// One positive delta the bridge owes the server, with the observation it +/// came from. +public struct MuseCodePlannedEvent: Codable, Equatable, Sendable { + public let observation: MuseCodeSessionObservation + public let delta: Int + + public init(observation: MuseCodeSessionObservation, delta: Int) { + self.observation = observation + self.delta = delta + } +} + +/// Pure delta planning, so the discipline is testable without a server: the +/// previous observation per session in, the events to post and the baselines +/// to keep out. The caller persists `updated` only after every batch is +/// acknowledged, so a failed post retries the same deltas next refresh. +public enum MuseCodeDeltaPlanner { + public static let maxTrackedSessions = 1_024 + + public static func plan(observations: [MuseCodeSessionObservation], + previous: [String: MuseCodeSessionObservation]) + -> (events: [MuseCodePlannedEvent], updated: [String: MuseCodeSessionObservation]) { + var updated = previous + var events: [MuseCodePlannedEvent] = [] + for observation in observations { + guard observation.totalTokens >= 0 else { continue } + let prior = updated[observation.sessionId] + // A rotated or delayed snapshot must never rewind an acknowledged baseline. + if let prior, observation.observedAt < prior.observedAt { continue } + let delta: Int + if let prior, prior.segmentKey == observation.segmentKey, + prior.modelId == observation.modelId { + guard observation.totalTokens >= prior.totalTokens else { continue } + delta = observation.totalTokens - prior.totalTokens + } else { + // First observation of the session, a segment reset, or a + // model switch: the current segment's total is the delta. + delta = observation.totalTokens + } + if delta > 0 { + events.append(MuseCodePlannedEvent(observation: observation, delta: delta)) + } + updated[observation.sessionId] = observation + } + if updated.count > maxTrackedSessions { + updated = Dictionary(uniqueKeysWithValues: updated.values + .sorted { $0.observedAt > $1.observedAt } + .prefix(maxTrackedSessions) + .map { ($0.sessionId, $0) }) + } + return (events, updated) + } +} + +/// Usage Monitor's ingest acknowledgment. A batch counts as delivered only +/// when the acknowledgment is complete: every counter present and +/// non-negative, `received` equal to the number sent, and the dispositions +/// adding up to `received`. +public struct MuseCodeIngestAcknowledgment: Decodable, Equatable, Sendable { + public let received: Int + public let persisted: Int + public let duplicates: Int + public let pruned: Int + public let rejected: Int + + public func isComplete(sent: Int) -> Bool { + let counts = [received, persisted, duplicates, pruned, rejected] + guard counts.allSatisfy({ $0 >= 0 }), received == sent else { return false } + // Subtract from the bounded sent count, so hostile counts cannot + // overflow while checking the complete disposition of the batch. + var unaccounted = received + for count in [persisted, duplicates, pruned, rejected] { + guard count <= unaccounted else { return false } + unaccounted -= count + } + return unaccounted == 0 + } +} + +public struct MuseCodeIngestSummary: Equatable, Sendable { + public var sent: Int + public var persisted: Int + public var duplicates: Int + public var pruned: Int + public var rejected: Int + + public init(sent: Int = 0, persisted: Int = 0, duplicates: Int = 0, + pruned: Int = 0, rejected: Int = 0) { + self.sent = sent + self.persisted = persisted + self.duplicates = duplicates + self.pruned = pruned + self.rejected = rejected + } +} + +/// Posts Muse token events to Usage Monitor's `/api/ingest/usage`, in +/// batches of at most 100 events, with the v2 telemetry headers. +public struct MuseCodeSessionPoster: Sendable { + private let transport: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + + public init(transport: (@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse))? = nil) { + self.transport = transport ?? { request in + let (data, response) = try await URLSession.shared.data(for: request) + guard let http = response as? HTTPURLResponse else { + throw QuotaPublisherError.transport("Invalid response.") + } + return (data, http) + } + } + + public func publish(events: [[String: Any]], to endpoint: URL, token: String?, + shouldContinue: @Sendable () async -> Bool = { true }) async throws -> MuseCodeIngestSummary { + var summary = MuseCodeIngestSummary() + for batch in MuseCodeSessionIngest.eventBatches(events: events) { + guard await shouldContinue() else { throw CancellationError() } + var request = URLRequest(url: endpoint) + request.httpMethod = "POST" + request.setValue("application/json", forHTTPHeaderField: "content-type") + request.setValue("2", forHTTPHeaderField: "x-usage-telemetry-version") + if let token = token.map(sanitizedToken(_:)), !token.isEmpty { + request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + } + request.httpBody = try MuseCodeSessionIngest.batchData(events: batch) + let (data, http) = try await transport(request) + guard (200..<300).contains(http.statusCode) else { + throw QuotaPublisherError.httpStatus(http.statusCode, nil) + } + guard let acknowledgment = try? JSONDecoder().decode(MuseCodeIngestAcknowledgment.self, from: data), + acknowledgment.isComplete(sent: batch.count) else { + throw QuotaPublisherError.serverError( + "Usage Monitor returned an incomplete ingest acknowledgment.") + } + summary.sent += batch.count + summary.persisted += acknowledgment.persisted + summary.duplicates += acknowledgment.duplicates + summary.pruned += acknowledgment.pruned + summary.rejected += acknowledgment.rejected + } + return summary + } +} diff --git a/Sources/QuotaCore/MuseCodeSessionReader.swift b/Sources/QuotaCore/MuseCodeSessionReader.swift new file mode 100644 index 00000000..9060b2af --- /dev/null +++ b/Sources/QuotaCore/MuseCodeSessionReader.swift @@ -0,0 +1,405 @@ +import Foundation + +/// One distinct conversation segment observed in a Muse session snapshot. +/// +/// A segment is the unit the fleet's survey scripts proved additive: distinct +/// source ranges inside one session sum to the session's burn, while the same +/// range re-read from a later snapshot is the same segment, never new burn. +public struct MuseCodeTokenSegment: Equatable, Sendable { + public let sessionId: String + public let modelId: String + public let totalTokens: Int + public let promptTokens: Int? + public let observedAt: Date + public let sourceFirstId: String? + public let sourceLastId: String? + + public init(sessionId: String, modelId: String, totalTokens: Int, promptTokens: Int? = nil, + observedAt: Date, sourceFirstId: String? = nil, sourceLastId: String? = nil) { + self.sessionId = sessionId + self.modelId = modelId + self.totalTokens = totalTokens + self.promptTokens = promptTokens + self.observedAt = observedAt + self.sourceFirstId = sourceFirstId + self.sourceLastId = sourceLastId + } + + /// The segment's identity inside its session, matching the dedupe key the + /// survey scripts use: (sourceRange first id, last id, model, total). + public var dedupeKey: String { + [sourceFirstId ?? "", sourceLastId ?? "", modelId, String(totalTokens)] + .joined(separator: "\u{1}") + } + + public var isContributor: Bool { modelId.hasSuffix("-contributor") } +} + +/// Token totals for one model inside one trailing window. +public struct MuseCodeModelUsage: Equatable, Sendable, Identifiable { + public let modelId: String + public let tokens: Int + public let segmentCount: Int + public let sessionCount: Int + + public var id: String { modelId } + public var isContributor: Bool { modelId.hasSuffix("-contributor") } + + public init(modelId: String, tokens: Int, segmentCount: Int, sessionCount: Int) { + self.modelId = modelId + self.tokens = tokens + self.segmentCount = segmentCount + self.sessionCount = sessionCount + } + + public func share(of total: Int) -> Double { + total > 0 ? Double(tokens) / Double(total) : 0 + } +} + +/// Aggregated Muse burn for one trailing window. +public struct MuseCodeWindowUsage: Equatable, Sendable { + public let windowMinutes: Int + public let totalTokens: Int + public let contributorTokens: Int + /// Nil when the window has no tokens at all: no burn is neither 0% nor + /// 100% contributor, and the monitor must not treat it as either. + public let contributorShare: Double? + public let activeSessions: Int + public let models: [MuseCodeModelUsage] + + public init(windowMinutes: Int, totalTokens: Int, contributorTokens: Int, + contributorShare: Double?, activeSessions: Int, models: [MuseCodeModelUsage]) { + self.windowMinutes = windowMinutes + self.totalTokens = totalTokens + self.contributorTokens = contributorTokens + self.contributorShare = contributorShare + self.activeSessions = activeSessions + self.models = models + } + + public var standardModels: [MuseCodeModelUsage] { + models.filter { !$0.isContributor && $0.tokens > 0 } + } + + public var tokensPerHour: Double { + Double(totalTokens) * 60 / Double(windowMinutes) + } +} + +/// A session's latest snapshot observation: the bridge's unit of work. +/// +/// The Usage Monitor bridge contract is defined over latest snapshots, not +/// over the segment sum the local monitor uses: per session, the latest +/// snapshot's `tokenUsage.totalTokens` is cumulative for its current +/// segment, and only the positive delta since the previous observation may +/// be posted. +public struct MuseCodeSessionObservation: Equatable, Sendable, Codable { + public let sessionId: String + public let snapshotId: String + public let modelId: String + public let totalTokens: Int + /// Identifies the segment the cumulative total belongs to (the token + /// usage's source-range start). A changed key means the segment reset, + /// and the new segment's total is the delta. + public let segmentKey: String + public let observedAt: Date + + public init(sessionId: String, snapshotId: String, modelId: String, + totalTokens: Int, segmentKey: String, observedAt: Date) { + self.sessionId = sessionId + self.snapshotId = snapshotId + self.modelId = modelId + self.totalTokens = totalTokens + self.segmentKey = segmentKey + self.observedAt = observedAt + } + + public var isContributor: Bool { modelId.hasSuffix("-contributor") } +} + +/// One reading of the Muse session store: per-window aggregates for the +/// local monitor, plus each active session's latest observation for the +/// Usage Monitor bridge. +public struct MuseCodeSessionReport: Equatable, Sendable { + public let generatedAt: Date + public let windows: [MuseCodeWindowUsage] + public let segments: [MuseCodeTokenSegment] + public let latestObservations: [MuseCodeSessionObservation] + /// The model each active session is on now, including a nil model when + /// its latest snapshot has no model-bearing tokenUsage.  Kept separate + /// from token observations, which require valid cumulative usage data. + public let currentModelObservations: [MuseCodeSessionModelObservation] + + public init(generatedAt: Date, windows: [MuseCodeWindowUsage], + segments: [MuseCodeTokenSegment] = [], + latestObservations: [MuseCodeSessionObservation] = [], + currentModelObservations: [MuseCodeSessionModelObservation] = []) { + self.generatedAt = generatedAt + self.windows = windows + self.segments = segments + self.latestObservations = latestObservations + self.currentModelObservations = currentModelObservations + } + + public func window(minutes: Int) -> MuseCodeWindowUsage? { + windows.first { $0.windowMinutes == minutes } + } +} + +/// The reader's result, in the shape every QuotaCore reader uses: data or a +/// user-safe issue, never a throw to the caller. +public struct MuseCodeSessionResult: Equatable, Sendable { + public let report: MuseCodeSessionReport? + public let issue: String? + + public init(report: MuseCodeSessionReport?, issue: String?) { + self.report = report + self.issue = issue + } +} + +/// Reads the Muse session stores on this Mac. +/// +/// Muse writes one directory per session under +/// `~/.local/share/muse/sessions/.msp-view-g6//`, with a HEAD.json +/// naming the latest snapshot and `snapshot-.json` files whose +/// `continuation.view_materialization.current_state.tokenUsage` carries the +/// model and token total for one conversation segment. This reader scans the +/// snapshot files directly (the newest snapshot in a directory is the one +/// HEAD.json names), which covers both the latest-segment and the +/// segment-summed views the fleet's surveys validated. +public struct MuseCodeSessionReader: Sendable { + public static let storeRelativePath = ".local/share/muse/sessions/.msp-view-g6" + public static let windowMinutes = [60, 90] + + private static let maxSessionDirectories = 512 + private static let maxSnapshotsPerSession = 512 + private static let maxSnapshotBytes = 33_554_432 + private static let futureTolerance: TimeInterval = 120 + + private let homeDirectory: URL + private let now: @Sendable () -> Date + + public init(homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser, + now: @escaping @Sendable () -> Date = { Date() }) { + self.homeDirectory = homeDirectory.standardizedFileURL + self.now = now + } + + public func read() -> MuseCodeSessionResult { + let instant = now() + let root = homeDirectory.appendingPathComponent(Self.storeRelativePath, isDirectory: true) + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: root.path, isDirectory: &isDirectory), + isDirectory.boolValue else { + return MuseCodeSessionResult( + report: nil, + issue: "Muse session store was not found on this Mac.") + } + let cutoff = instant.addingTimeInterval(-90 * 60) + var segments: [MuseCodeTokenSegment] = [] + var activity: [String: Date] = [:] + var observations: [MuseCodeSessionObservation] = [] + var modelObservations: [MuseCodeSessionModelObservation] = [] + let entries = (try? FileManager.default.contentsOfDirectory( + at: root, includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey])) ?? [] + let sessionDirs = entries + .filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true } + .sorted { Self.modification(of: $0) > Self.modification(of: $1) } + .prefix(Self.maxSessionDirectories) + for directory in sessionDirs { + let sessionId = directory.lastPathComponent + guard let files = try? FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey]) else { continue } + let dated: [(url: URL, modified: Date, size: Int)] = files.map { url in + let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey]) + return (url, values?.contentModificationDate ?? .distantPast, values?.fileSize ?? 0) + } + // A session counts as active in a window when any of its files — + // HEAD.json included — was written inside it, the same activity + // test the survey scripts use. + guard let newest = dated.map(\.modified).max(), newest >= cutoff else { continue } + activity[sessionId] = newest + let allSnapshots = dated + .filter { $0.url.lastPathComponent.hasPrefix("snapshot-") + && $0.url.pathExtension == "json" } + let headId = Self.headSnapshotId(in: dated) + let headSnapshot = headId.flatMap { id in + allSnapshots.first { Self.snapshotId(from: $0.url) == id } + } + // Retain the newest snapshots that can contribute to the 90-minute + // window.  Always add HEAD even when the store contains more than the + // parsing cap, so it cannot be lost behind older snapshots. + var selected = Array(allSnapshots + .filter { $0.modified >= cutoff } + .sorted { $0.modified > $1.modified } + .prefix(Self.maxSnapshotsPerSession)) + if let headSnapshot, !selected.contains(where: { $0.url == headSnapshot.url }) { + if selected.count == Self.maxSnapshotsPerSession { selected.removeLast() } + selected.append(headSnapshot) + } + let snapshots = selected.sorted { $0.modified < $1.modified } + let currentSnapshot: (url: URL, modified: Date, size: Int)? + if let headId { + // A valid HEAD id is authoritative. If its file is absent, the + // current model is unknown; never substitute an older model. + currentSnapshot = headSnapshot + } else { + currentSnapshot = allSnapshots.max { $0.modified < $1.modified } + } + if let currentSnapshot { + modelObservations.append(MuseCodeSessionModelObservation( + sessionId: sessionId, + modelId: Self.currentModel(in: currentSnapshot.url, size: currentSnapshot.size), + observedAt: currentSnapshot.modified)) + } else { + modelObservations.append(MuseCodeSessionModelObservation( + sessionId: sessionId, modelId: nil, observedAt: newest)) + } + var parsed: [(snapshotId: String?, segment: MuseCodeTokenSegment)] = [] + for snapshot in snapshots { + if let segment = Self.segment(sessionId: sessionId, url: snapshot.url, + modified: snapshot.modified, size: snapshot.size) { + segments.append(segment) + parsed.append((Self.snapshotId(from: snapshot.url), segment)) + } + } + // The session's latest observation, for the bridge: the snapshot + // HEAD.json names when it was parsed, otherwise the newest one. + let chosen = parsed.first { $0.snapshotId != nil && $0.snapshotId == headId } + ?? parsed.max { $0.segment.observedAt < $1.segment.observedAt } + if let chosen { + observations.append(MuseCodeSessionObservation( + sessionId: sessionId, + snapshotId: chosen.snapshotId ?? "", + modelId: chosen.segment.modelId, + totalTokens: chosen.segment.totalTokens, + segmentKey: chosen.segment.sourceFirstId ?? "", + observedAt: chosen.segment.observedAt)) + } + } + return MuseCodeSessionResult( + report: Self.aggregate(segments: segments, sessionActivity: activity, + latestObservations: observations.sorted { $0.sessionId < $1.sessionId }, + currentModelObservations: modelObservations.sorted { $0.sessionId < $1.sessionId }, + now: instant), + issue: nil) + } + + private static func snapshotId(from url: URL) -> String? { + let name = url.lastPathComponent + guard name.hasPrefix("snapshot-"), name.hasSuffix(".json") else { return nil } + return String(name.dropFirst("snapshot-".count).dropLast(".json".count)) + } + + private static func headSnapshotId(in files: [(url: URL, modified: Date, size: Int)]) -> String? { + guard let head = files.first(where: { $0.url.lastPathComponent == "HEAD.json" }), + head.size > 0, head.size <= 1_048_576, + let data = try? Data(contentsOf: head.url), + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let id = root["latest_snapshot_id"] as? String, !id.isEmpty else { return nil } + return id + } + + private static func currentModel(in url: URL, size: Int) -> String? { + guard size > 0, size <= maxSnapshotBytes, + let data = try? Data(contentsOf: url), + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let continuation = root["continuation"] as? [String: Any], + let materialization = continuation["view_materialization"] as? [String: Any], + let state = materialization["current_state"] as? [String: Any], + let usage = state["tokenUsage"] as? [String: Any], + let modelId = usage["modelId"] as? String, + !modelId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil } + return modelId + } + + private static func modification(of url: URL) -> Date { + (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) + ?? .distantPast + } + + private static func segment(sessionId: String, url: URL, modified: Date, size: Int) -> MuseCodeTokenSegment? { + guard size > 0, size <= maxSnapshotBytes, + let data = try? Data(contentsOf: url), + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let continuation = root["continuation"] as? [String: Any], + let materialization = continuation["view_materialization"] as? [String: Any], + let state = materialization["current_state"] as? [String: Any], + let usage = state["tokenUsage"] as? [String: Any], + let modelId = usage["modelId"] as? String, !modelId.isEmpty, + let total = number(usage["totalTokens"]), total >= 0 else { return nil } + let range = usage["sourceRange"] as? [String: Any] + return MuseCodeTokenSegment( + sessionId: sessionId, + modelId: modelId, + totalTokens: Int(total.rounded()), + promptTokens: number(usage["promptTokens"]).map { Int($0.rounded()) }, + observedAt: modified, + sourceFirstId: (range?["first"] as? [String: Any])?["id"] as? String, + sourceLastId: (range?["last"] as? [String: Any])?["id"] as? String) + } + + private static func number(_ raw: Any?) -> Double? { + guard let value = raw as? NSNumber, CFGetTypeID(value) != CFBooleanGetTypeID(), + value.doubleValue.isFinite else { return nil } + return value.doubleValue + } + + /// The aggregation the surveys validated, as a pure function so it can be + /// tested without a session store: dedupe segments per session by source + /// range, then sum per model inside each trailing window. + public static func aggregate(segments raw: [MuseCodeTokenSegment], + sessionActivity: [String: Date], + latestObservations: [MuseCodeSessionObservation] = [], + currentModelObservations: [MuseCodeSessionModelObservation] = [], + now: Date) -> MuseCodeSessionReport { + // The stores rotate snapshots aggressively: a segment whose snapshot + // file has already been rotated away is invisible here, and a session + // that ends mid-window leaves only the segments still on disk. Every + // total this aggregation produces is therefore a floor, not an exact + // count — the plugin page says so wherever it shows these numbers. + var seen = Set() + var segments: [MuseCodeTokenSegment] = [] + for segment in raw.sorted(by: { $0.observedAt < $1.observedAt }) { + guard seen.insert(segment.sessionId + "\u{1}" + segment.dedupeKey).inserted else { continue } + segments.append(segment) + } + let horizon = now.addingTimeInterval(futureTolerance) + let windows = windowMinutes.map { minutes -> MuseCodeWindowUsage in + let cutoff = now.addingTimeInterval(-Double(minutes) * 60) + var byModel: [String: (tokens: Int, segments: Int, sessions: Set)] = [:] + for segment in segments where segment.observedAt >= cutoff && segment.observedAt <= horizon { + var entry = byModel[segment.modelId] ?? (tokens: 0, segments: 0, sessions: []) + entry.tokens += segment.totalTokens + entry.segments += 1 + entry.sessions.insert(segment.sessionId) + byModel[segment.modelId] = entry + } + let models = byModel + .map { MuseCodeModelUsage(modelId: $0.key, tokens: $0.value.tokens, + segmentCount: $0.value.segments, + sessionCount: $0.value.sessions.count) } + .sorted { $0.tokens != $1.tokens ? $0.tokens > $1.tokens : $0.modelId < $1.modelId } + let total = models.reduce(0) { $0 + $1.tokens } + let contributor = models.filter(\.isContributor).reduce(0) { $0 + $1.tokens } + let active = sessionActivity.filter { $0.value >= cutoff && $0.value <= horizon }.count + return MuseCodeWindowUsage( + windowMinutes: minutes, + totalTokens: total, + contributorTokens: contributor, + contributorShare: total > 0 ? Double(contributor) / Double(total) : nil, + activeSessions: active, + models: models) + } + let cutoff90 = now.addingTimeInterval(-90 * 60) + return MuseCodeSessionReport( + generatedAt: now, + windows: windows, + segments: segments.filter { $0.observedAt >= cutoff90 && $0.observedAt <= horizon }, + latestObservations: latestObservations, + currentModelObservations: currentModelObservations) + } +} diff --git a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift new file mode 100644 index 00000000..f7752a31 --- /dev/null +++ b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift @@ -0,0 +1,154 @@ +import Foundation + +/// One muse-code session's current model, as one poll of the session store +/// observed it. This is the detector's input, kept separate from the +/// reader's `MuseCodeSessionObservation` because a session whose current +/// segment carries no model id must be representable: `modelId` is nil for +/// such a session, and a nil model is never an event. +public struct MuseCodeSessionModelObservation: Equatable, Sendable { + public let sessionId: String + public let modelId: String? + public let observedAt: Date + + public init(sessionId: String, modelId: String?, observedAt: Date) { + self.sessionId = sessionId + self.modelId = modelId + self.observedAt = observedAt + } + + /// Adapts the reader's latest observation for one session. The reader + /// only emits observations for snapshots that carry a model, so the + /// adapted `modelId` is never nil today; the detector still tolerates + /// nil for any future source that can produce one. + public init(_ observation: MuseCodeSessionObservation) { + self.init(sessionId: observation.sessionId, + modelId: observation.modelId, + observedAt: observation.observedAt) + } +} + +/// A standard-model session event: one firing of the +/// `museCodeStandardSession` alert kind. The payload names the session, +/// the model it is on, and when it was observed — the three facts that say +/// which run of work left the contributor models. +public struct MuseCodeStandardSessionEvent: Equatable, Sendable { + public let sessionId: String + public let modelId: String + public let observedAt: Date + + public init(sessionId: String, modelId: String, observedAt: Date) { + self.sessionId = sessionId + self.modelId = modelId + self.observedAt = observedAt + } + + public var title: String { "Muse Standard Model Session" } + + public var body: String { + "Session \(sessionId) is running on the standard model \(modelId)." + + sentenceGap + + "Observed at \(Self.centralTimestamp(observedAt))." + } + + private static func centralTimestamp(_ date: Date) -> String { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(identifier: "America/Chicago") + formatter.dateFormat = "MMM d, yyyy h:mm a" + return formatter.string(from: date) + } +} + +/// Event-based detection of standard-model Muse sessions. +/// +/// This replaces the contributor token share as the monitor's contributor +/// finding. A share computed from rotating session snapshots moves for +/// reasons unrelated to the question — stale sessions inside the window, +/// token weight, last-segment attribution — and reads below 100% even when +/// every live session is on a contributor model. Presence has no such +/// noise: a session either is on a standard model or it is not. +/// +/// The detector is a small state machine over polls. It remembers the last +/// model each session was observed on and fires exactly when a session +/// enters a standard model: +/// +/// - a session observed for the first time, already on a standard model; +/// - a session whose model changed from a contributor model to a standard +/// model. +/// +/// A session that stays on the same standard model across polls does not +/// refire. A session that returns to a contributor model re-arms, so going +/// standard again is a new event. Observations with no model id are +/// ignored entirely — they neither fire nor touch the tracked state — so a +/// model-less segment can neither manufacture an event nor mask a later +/// contributor-to-standard switch. +/// +/// The state is `Codable` so the owner of the detector can persist it with +/// the same JSON-in-UserDefaults pattern the plugin already uses for the +/// Usage Monitor bridge baselines, and detection survives app relaunches. +public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { + /// The last model each tracked session was observed on, by session id. + /// Only model-bearing observations are recorded, so a session absent + /// here has never been observed with a model. + public private(set) var lastKnownModels: [String: String] + + public init(lastKnownModels: [String: String] = [:]) { + self.lastKnownModels = lastKnownModels + } + + /// A contributor model is a model id ending in `-contributor`. + public static func isContributor(modelId: String) -> Bool { + modelId.hasSuffix("-contributor") + } + + /// A standard model is any non-empty model id that is not a contributor + /// model. A missing model id is not standard — it is no information. + public static func isStandard(modelId: String?) -> Bool { + guard let modelId, !modelId.isEmpty else { return false } + return !isContributor(modelId: modelId) + } + + /// Feeds one poll's session observations and returns the events that + /// fire, in observation order. + /// + /// On the first poll after install the tracked state is empty, so every + /// session in that first scan counts as first-observed and fires if it + /// is on a standard model. That is deliberate: a standard session that + /// was already running when the monitor was installed is still a + /// standard session, and suppressing it would hide exactly the finding + /// the alert exists for. + @discardableResult + public mutating func observe( + _ observations: [MuseCodeSessionModelObservation] + ) -> [MuseCodeStandardSessionEvent] { + var events: [MuseCodeStandardSessionEvent] = [] + for observation in observations { + guard let modelId = observation.modelId, !modelId.isEmpty else { continue } + let previous = lastKnownModels[observation.sessionId] + let wasContributor = previous.map { Self.isContributor(modelId: $0) } ?? false + if Self.isStandard(modelId: modelId), previous == nil || wasContributor { + events.append(MuseCodeStandardSessionEvent( + sessionId: observation.sessionId, modelId: modelId, + observedAt: observation.observedAt)) + } + lastKnownModels[observation.sessionId] = modelId + } + return events + } + + /// The sessions in one poll whose current model is standard, as events + /// with no firing semantics: the presence test the burn rule uses. A + /// standard session that has been running for an hour still counts here + /// even though its start event fired long ago. + public static func standardSessions( + in observations: [MuseCodeSessionModelObservation] + ) -> [MuseCodeStandardSessionEvent] { + observations.compactMap { observation in + guard let modelId = observation.modelId, + isStandard(modelId: modelId) else { return nil } + return MuseCodeStandardSessionEvent(sessionId: observation.sessionId, + modelId: modelId, + observedAt: observation.observedAt) + } + } +} From 0aeb73d1c51baabd9a26fa13d807b10bb22cc693 Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:22:51 +0000 Subject: [PATCH 02/12] Add regression coverage for Muse monitoring, reset inference, provider controls, and SMS --- .../QuotaCore/QuotaReaderPreferences.swift | 32 +++ Sources/QuotaCore/ResetAlarmTracker.swift | 17 +- Sources/QuotaCore/SMSAlertCoordinator.swift | 81 ++++++ Sources/QuotaCore/TwilioSMSClient.swift | 180 ++++++++++++ Sources/QuotaCore/UsageAlertPreferences.swift | 29 +- .../MuseCodeBridgeSafetyTests.swift | 234 ++++++++++++++++ Tests/CodeCapsTests/MuseCodePluginTests.swift | 261 ++++++++++++++++++ .../CodeCapsTests/QuitConfirmationTests.swift | 38 +++ .../SMSAlertControllerTests.swift | 163 +++++++++++ Tests/CodeCapsTests/TokenStoreTests.swift | 10 +- .../TwilioCredentialStoreTests.swift | 82 ++++++ .../LocalQuotaReaderRegistryTests.swift | 89 ++++++ .../MuseCodeBurnMonitorTests.swift | 109 ++++++++ .../MuseCodeSessionIngestTests.swift | 168 +++++++++++ .../MuseCodeSessionReaderTests.swift | 229 +++++++++++++++ ...MuseCodeStandardSessionDetectorTests.swift | 127 +++++++++ .../ResetAlarmPlanChangeTests.swift | 13 +- .../ResetAlarmTrackerTests.swift | 54 ++++ .../SMSAlertCoordinatorTests.swift | 118 ++++++++ .../QuotaCoreTests/TwilioSMSClientTests.swift | 115 ++++++++ 20 files changed, 2138 insertions(+), 11 deletions(-) create mode 100644 Sources/QuotaCore/QuotaReaderPreferences.swift create mode 100644 Sources/QuotaCore/SMSAlertCoordinator.swift create mode 100644 Sources/QuotaCore/TwilioSMSClient.swift create mode 100644 Tests/CodeCapsTests/MuseCodeBridgeSafetyTests.swift create mode 100644 Tests/CodeCapsTests/MuseCodePluginTests.swift create mode 100644 Tests/CodeCapsTests/QuitConfirmationTests.swift create mode 100644 Tests/CodeCapsTests/SMSAlertControllerTests.swift create mode 100644 Tests/CodeCapsTests/TwilioCredentialStoreTests.swift create mode 100644 Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift create mode 100644 Tests/QuotaCoreTests/MuseCodeBurnMonitorTests.swift create mode 100644 Tests/QuotaCoreTests/MuseCodeSessionIngestTests.swift create mode 100644 Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift create mode 100644 Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift create mode 100644 Tests/QuotaCoreTests/SMSAlertCoordinatorTests.swift create mode 100644 Tests/QuotaCoreTests/TwilioSMSClientTests.swift diff --git a/Sources/QuotaCore/QuotaReaderPreferences.swift b/Sources/QuotaCore/QuotaReaderPreferences.swift new file mode 100644 index 00000000..04ce1ec8 --- /dev/null +++ b/Sources/QuotaCore/QuotaReaderPreferences.swift @@ -0,0 +1,32 @@ +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. +public struct QuotaReaderPreferences: Codable, Equatable, Sendable { + public static let defaultsKey = "optionalQuotaReaders" + public var enabledByReaderID: [String: Bool] + + public init(enabledByReaderID: [String: Bool] = [:]) { + self.enabledByReaderID = enabledByReaderID + } + + public func isEnabled(_ readerID: String) -> Bool { + enabledByReaderID[readerID] ?? true + } + + public mutating func setEnabled(_ enabled: Bool, for readerID: String) { + enabledByReaderID[readerID] = enabled + } + + public static func load(from defaults: UserDefaults, key: String = defaultsKey) -> Self { + guard let data = defaults.data(forKey: key), + let saved = try? JSONDecoder().decode(Self.self, from: data) else { return Self() } + return saved + } + + public func save(to defaults: UserDefaults, key: String = defaultsKey) { + guard let data = try? JSONEncoder().encode(self) else { return } + defaults.set(data, forKey: key) + } +} diff --git a/Sources/QuotaCore/ResetAlarmTracker.swift b/Sources/QuotaCore/ResetAlarmTracker.swift index 8129f9a1..bbc36136 100644 --- a/Sources/QuotaCore/ResetAlarmTracker.swift +++ b/Sources/QuotaCore/ResetAlarmTracker.swift @@ -462,7 +462,6 @@ public struct ResetAlarmTracker: Sendable { } if window.identity == nil { window.identity = observation.identity } window.lastSeenAt = now - if let period = observation.periodSeconds { window.periodSeconds = period } // A reading older than one already processed cannot say anything new. if let observed = observedAt, let last = window.lastObservedAt, observed < last { @@ -470,6 +469,16 @@ public struct ResetAlarmTracker: Sendable { return nil } + // A producer may reuse a window ID while switching its cadence.  Its reset time and remaining percentage no longer share the old baseline.  Keep the new reading as a baseline instead of comparing across periods. + if let observedPeriod = observation.periodSeconds, + let previousPeriod = window.periodSeconds, + abs(observedPeriod - previousPeriod) > ResetAlarmPolicy.resetDriftTolerance { + state.windows[key] = firstReading() + return nil + } + + if let period = observation.periodSeconds { window.periodSeconds = period } + let readAt = observedAt ?? now var isReset = false var isMidWindow = false @@ -493,7 +502,11 @@ public struct ResetAlarmTracker: Sendable { if let reading, let last = window.lastRemaining { climbed = reading >= last + ResetAlarmPolicy.earlyResetRiseMargin } - if jump > required || (jump > ResetAlarmPolicy.resetDriftTolerance && climbed) { + let rose = reading.flatMap { current in + window.lastRemaining.map { current > $0 + ResetAlarmPolicy.riseEpsilon } + } ?? false + if (jump > required && (hasPassed || rose)) + || (jump > ResetAlarmPolicy.resetDriftTolerance && climbed) { isReset = true // When the window had *not* reached its own scheduled end, // any reset is an early / mid-cycle vendor restore rather than diff --git a/Sources/QuotaCore/SMSAlertCoordinator.swift b/Sources/QuotaCore/SMSAlertCoordinator.swift new file mode 100644 index 00000000..5d1ef4d6 --- /dev/null +++ b/Sources/QuotaCore/SMSAlertCoordinator.swift @@ -0,0 +1,81 @@ +import Foundation +import CryptoKit + +public enum SMSAlertSendResult: Equatable, Sendable { + case disabled, duplicate, accepted + case failed(TwilioSMSFailure) +} + +/// Callers supply persistence explicitly; tests never touch standard preferences. +public struct SMSAlertPersistence: Sendable { + public var load: @Sendable () throws -> Data? + public var save: @Sendable (Data) throws -> Void + + public init(load: @escaping @Sendable () throws -> Data?, save: @escaping @Sendable (Data) throws -> Void) { + self.load = load + self.save = save + } + + public static func userDefaults(_ defaults: UserDefaults, key: String) -> Self { + Self(load: { defaults.data(forKey: key) }, save: { data in + defaults.set(data, forKey: key) + guard defaults.synchronize() else { throw TwilioSMSFailure.persistence } + }) + } +} + +/// Single-flight reservations survive relaunch and remain after uncertain outcomes. +public actor SMSAlertCoordinator { + private struct History: Codable { + let version: Int + var eventHashes: Set + } + private let persistence: SMSAlertPersistence + private let client: TwilioSMSClient + private let maximumReservations: Int + private var history: History? + + /// A full ledger fails closed instead of evicting IDs and risking repeat charges. + public init(persistence: SMSAlertPersistence, client: TwilioSMSClient = TwilioSMSClient(), + maximumReservations: Int = 16_384) { + self.persistence = persistence + self.client = client + self.maximumReservations = min(16_384, max(1, maximumReservations)) + } + + public func send(eventID: String, kind: String, title: String, body: String, + preferences: SMSAlertPreferences, credentials: TwilioSMSCredentials?) async -> SMSAlertSendResult { + guard preferences[kind] else { return .disabled } + guard let credentials else { return .failed(.invalidConfiguration) } + do { try credentials.validate() } + catch { return .failed(.invalidConfiguration) } + guard !eventID.isEmpty, eventID.utf8.count <= 4_096 else { return .failed(.persistence) } + let eventHash = SHA256.hash(data: Data((kind + "\u{0}" + eventID).utf8)) + .map { String(format: "%02x", $0) }.joined() + do { + if history == nil { + if let data = try persistence.load() { + guard data.count <= maximumReservations * 80 + 128 else { return .failed(.persistence) } + let loaded = try JSONDecoder().decode(History.self, from: data) + guard loaded.version == 1, loaded.eventHashes.count <= maximumReservations, + loaded.eventHashes.allSatisfy({ $0.count == 64 && $0.allSatisfy { "0123456789abcdef".contains($0) } }) else { + return .failed(.persistence) + } + history = loaded + } else { history = History(version: 1, eventHashes: []) } + } + guard var updated = history else { return .failed(.persistence) } + guard !updated.eventHashes.contains(eventHash) else { return .duplicate } + guard updated.eventHashes.count < maximumReservations else { return .failed(.capacity) } + updated.eventHashes.insert(eventHash) + // No actor suspension occurs until the reservation is durably saved. + try persistence.save(JSONEncoder().encode(updated)) + history = updated + } catch { return .failed(.persistence) } + do { + try await client.send(title: title, body: body, credentials: credentials) + return .accepted + } catch let failure as TwilioSMSFailure { return .failed(failure) } + catch { return .failed(.uncertain) } + } +} diff --git a/Sources/QuotaCore/TwilioSMSClient.swift b/Sources/QuotaCore/TwilioSMSClient.swift new file mode 100644 index 00000000..ca86f943 --- /dev/null +++ b/Sources/QuotaCore/TwilioSMSClient.swift @@ -0,0 +1,180 @@ +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +/// Personal opt-ins are independent of local notification delivery. +public struct SMSAlertPreferences: Codable, Equatable, Sendable { + public static let eligibleKinds: Set = [ + "museCodeStandardSession", "museCodeBurn", "quotaExhaustion" + ] + public var enabledKinds: Set + + public init(enabledKinds: Set = []) { + self.enabledKinds = enabledKinds.intersection(Self.eligibleKinds) + } + + public subscript(kindID: String) -> Bool { + get { Self.eligibleKinds.contains(kindID) && enabledKinds.contains(kindID) } + set { + if newValue && Self.eligibleKinds.contains(kindID) { enabledKinds.insert(kindID) } + else { enabledKinds.remove(kindID) } + } + } + + public static func load(from defaults: UserDefaults, key: String) -> Self { + guard let data = defaults.data(forKey: key), + let saved = try? JSONDecoder().decode(Self.self, from: data) else { return Self() } + return Self(enabledKinds: saved.enabledKinds) + } + + public func save(to defaults: UserDefaults, key: String) { + guard let data = try? JSONEncoder().encode(self) else { return } + defaults.set(data, forKey: key) + } +} + +public struct TwilioSMSConfiguration: Codable, Equatable, Sendable { + public var accountSID: String + public var apiKeySID: String + public var messagingServiceSID: String + public var recipient: String + + public init(accountSID: String, apiKeySID: String, messagingServiceSID: String, recipient: String) { + self.accountSID = accountSID.trimmingCharacters(in: .whitespacesAndNewlines) + self.apiKeySID = apiKeySID.trimmingCharacters(in: .whitespacesAndNewlines) + self.messagingServiceSID = messagingServiceSID.trimmingCharacters(in: .whitespacesAndNewlines) + self.recipient = recipient.trimmingCharacters(in: .whitespacesAndNewlines) + } + + public func validate() throws { + guard Self.isSID(accountSID, prefix: "AC"), Self.isSID(apiKeySID, prefix: "SK"), + Self.isSID(messagingServiceSID, prefix: "MG"), + recipient.range(of: #"\A\+[1-9][0-9]{1,14}\z"#, options: .regularExpression) != nil else { + throw TwilioSMSFailure.invalidConfiguration + } + } + + private static func isSID(_ value: String, prefix: String) -> Bool { + value.count == 34 && value.hasPrefix(prefix) + && value.dropFirst(2).allSatisfy { "0123456789abcdefABCDEF".contains($0) } + } +} + +/// The whole per-user setup belongs in one build-scoped Keychain item. +public struct TwilioSMSCredentials: Codable, Equatable, Sendable { + public var configuration: TwilioSMSConfiguration + public var apiKeySecret: String + + public init(configuration: TwilioSMSConfiguration, apiKeySecret: String) { + self.configuration = configuration + self.apiKeySecret = apiKeySecret.trimmingCharacters(in: .whitespacesAndNewlines) + } + + public func validate() throws { + try configuration.validate() + guard !apiKeySecret.isEmpty, apiKeySecret.utf8.count <= 256, + !apiKeySecret.contains(where: { $0.isWhitespace || $0.isNewline || $0 == ":" }) else { + throw TwilioSMSFailure.invalidConfiguration + } + } +} + +/// Errors never include Twilio response text, credentials, or the recipient. +public enum TwilioSMSFailure: Error, LocalizedError, Equatable, Sendable { + case invalidConfiguration, authentication, rejected, rateLimited, serviceUnavailable + case uncertain, invalidResponse, persistence, capacity + + public var errorDescription: String? { + switch self { + case .invalidConfiguration: return "Enter a valid Twilio SMS setup." + case .authentication: return "Twilio rejected the saved API credentials." + case .rejected: return "Twilio rejected this text message." + case .rateLimited: return "Twilio is limiting text messages." + case .serviceUnavailable: return "Twilio is temporarily unavailable." + case .uncertain: return "Text submission could not be confirmed.\u{00A0} This alert will not be retried." + case .invalidResponse: return "Twilio returned an unexpected response.\u{00A0} This alert will not be retried." + case .persistence: return "Text alerts could not save their send history." + case .capacity: return "Text alert send history is full." + } + } +} + +public struct TwilioSMSClient: Sendable { + public typealias Transport = @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + private let transport: Transport + + public init(transport: @escaping Transport = TwilioSMSClient.liveTransport) { + self.transport = transport + } + + /// Acceptance means Twilio created the message, never confirmed delivery. + public func send(title: String, body: String, credentials: TwilioSMSCredentials) async throws { + let request = try Self.request(title: title, body: body, credentials: credentials) + let data: Data + let response: HTTPURLResponse + do { (data, response) = try await transport(request) } + catch { throw TwilioSMSFailure.uncertain } + switch response.statusCode { + case 200..<300: break + case 401, 403: throw TwilioSMSFailure.authentication + case 429: throw TwilioSMSFailure.rateLimited + case 500...599: throw TwilioSMSFailure.serviceUnavailable + default: throw TwilioSMSFailure.rejected + } + struct Receipt: Decodable { let sid: String; let status: String } + guard data.count <= 65_536, + let receipt = try? JSONDecoder().decode(Receipt.self, from: data), + receipt.sid.count == 34, receipt.sid.hasPrefix("SM"), + receipt.sid.dropFirst(2).allSatisfy({ "0123456789abcdefABCDEF".contains($0) }) else { + throw TwilioSMSFailure.invalidResponse + } + guard ["accepted", "queued", "scheduled", "sending", "sent", "delivered"].contains(receipt.status) else { + throw TwilioSMSFailure.rejected + } + } + + static func request(title: String, body: String, credentials: TwilioSMSCredentials) throws -> URLRequest { + try credentials.validate() + let config = credentials.configuration + // The fixed host and SID validation prevent credential-bearing arbitrary endpoints. + let url = URL(string: "https://api.twilio.com/2010-04-01/Accounts/\(config.accountSID)/Messages.json")! + var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20) + request.httpMethod = "POST" + request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + request.setValue("application/json", forHTTPHeaderField: "Accept") + let authorization = Data("\(config.apiKeySID):\(credentials.apiKeySecret)".utf8).base64EncodedString() + request.setValue("Basic " + authorization, forHTTPHeaderField: "Authorization") + let message = String(("CodeCaps: " + title + "\n" + body).prefix(240)) + request.httpBody = Data([("To", config.recipient), ("MessagingServiceSid", config.messagingServiceSID), ("Body", message)] + .map { Self.formEncode($0.0) + "=" + Self.formEncode($0.1) }.joined(separator: "&").utf8) + return request + } + + private static func formEncode(_ value: String) -> String { + value.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"))! + } + + public static let liveTransport: Transport = { request in + let configuration = URLSessionConfiguration.ephemeral + configuration.httpCookieStorage = nil + configuration.urlCredentialStorage = nil + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + configuration.timeoutIntervalForRequest = 20 + configuration.timeoutIntervalForResource = 30 + let session = URLSession(configuration: configuration, delegate: NoSMSRedirects(), delegateQueue: nil) + defer { session.invalidateAndCancel() } + let (data, response) = try await session.data(for: request) + guard let response = response as? HTTPURLResponse else { throw TwilioSMSFailure.invalidResponse } + return (data, response) + } +} + +/// A redirect must never forward the Basic authorization header to another host. +final class NoSMSRedirects: NSObject, URLSessionTaskDelegate, @unchecked Sendable { + func urlSession(_ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { + completionHandler(nil) + } +} diff --git a/Sources/QuotaCore/UsageAlertPreferences.swift b/Sources/QuotaCore/UsageAlertPreferences.swift index 39190ce1..df0b2d2e 100644 --- a/Sources/QuotaCore/UsageAlertPreferences.swift +++ b/Sources/QuotaCore/UsageAlertPreferences.swift @@ -31,8 +31,20 @@ public struct CompanionPushRemovalAcknowledgment: Decodable { } /// Stable categories shared by Mac, companion, and remote notification payloads. +/// +/// Raw values are the stable alert-kind identifiers every delivery channel +/// selects on — including a future per-kind channel opt-in — so a case's +/// raw value must never be renamed once shipped. public enum UsageAlertKind: String, CaseIterable, Codable, Sendable, Identifiable { case anomaly, runaway, vendorReset, quotaReset, quotaExhaustion + // Renamed before the plugin's first release: this kind was + // `museCodeContributorBelow100` while the finding was a contributor + // token share. The finding is now event-based (a session on a standard + // model), so the identifier names that instead. Preferences are stored + // keyed by raw-value strings, so an install that saved options under + // the old key simply never reads that entry again, and `load` backfills + // this kind from its shipped default — no migration is needed. + case museCodeBurn, museCodeStandardSession public var id: String { rawValue } public var title: String { @@ -42,6 +54,8 @@ public enum UsageAlertKind: String, CaseIterable, Codable, Sendable, Identifiabl case .vendorReset: return "Vendor Quota Resets" case .quotaReset: return "Scheduled Quota Resets" case .quotaExhaustion: return "Quota Exhaustion" + case .museCodeBurn: return "Muse Burn" + case .museCodeStandardSession: return "Muse Standard Sessions" } } public var detail: String { @@ -51,6 +65,8 @@ public enum UsageAlertKind: String, CaseIterable, Codable, Sendable, Identifiabl case .vendorReset: return "A provider restores quota before its scheduled reset." case .quotaReset: return "A quota window resets on schedule." case .quotaExhaustion: return "A quota window reaches its limit." + case .museCodeBurn: return "Muse token burn passes the plugin threshold on standard models." + case .museCodeStandardSession: return "A Muse session starts on, or switches to, a standard model." } } } @@ -96,7 +112,14 @@ public struct UsageAlertPreferences: Codable, Equatable, Sendable { resetEnabled: Bool, resetSound: ResetAlarmSound, runawayEnabled: Bool = false) -> Self { if let data = defaults.data(forKey: key), - let saved = try? JSONDecoder().decode(Self.self, from: data) { + var saved = try? JSONDecoder().decode(Self.self, from: data) { + // Kinds added after the owner's preferences were first saved + // start from their shipped default rather than the subscript's + // disabled fallback, until the owner changes them. + for kind in [UsageAlertKind.museCodeBurn, .museCodeStandardSession] + where saved.options[kind.rawValue] == nil { + saved[kind] = UsageAlertOption(enabled: true) + } return saved } var result = Self() @@ -106,6 +129,10 @@ public struct UsageAlertPreferences: Codable, Equatable, Sendable { case .quotaReset, .vendorReset: enabled = resetEnabled case .anomaly, .runaway: enabled = runawayEnabled case .quotaExhaustion: enabled = false + // The Muse monitor is the feature these kinds exist for, so + // they ship enabled; the owner can turn either off in + // Alerts & Alarms without touching the other. + case .museCodeBurn, .museCodeStandardSession: enabled = true } result[kind] = UsageAlertOption(enabled: enabled, sound: resetSound) } diff --git a/Tests/CodeCapsTests/MuseCodeBridgeSafetyTests.swift b/Tests/CodeCapsTests/MuseCodeBridgeSafetyTests.swift new file mode 100644 index 00000000..fd864a9d --- /dev/null +++ b/Tests/CodeCapsTests/MuseCodeBridgeSafetyTests.swift @@ -0,0 +1,234 @@ +import XCTest +import QuotaCore +@testable import CodeCaps + +@MainActor +final class MuseCodeBridgeSafetyTests: XCTestCase { + private var suite = "" + private var defaults: UserDefaults! + private var scratch: URL! + private let instant = Date(timeIntervalSince1970: 1_800_000_000) + + override func setUp() { + super.setUp() + suite = "CodeCaps.MuseBridgeSafetyTests." + UUID().uuidString + defaults = UserDefaults(suiteName: suite)! + scratch = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + } + + override func tearDown() { + defaults.removePersistentDomain(forName: suite) + try? FileManager.default.removeItem(at: scratch) + defaults = nil + super.tearDown() + } + + private func model() -> MonitorModel { + let model = MonitorModel(defaults: defaults, burnRateHistoryURL: scratch.appendingPathComponent("burn.json"), + presentsPipWindows: false) + model.skipsSnapshotIOForTesting = true + model.museCodeBurnAlertsEnabled = false + model.alarmManager.onUsageDelivery = { _, _, _, _ in } + model.museCodeTokenReadForTesting = { "fixture-ingest-token" } + return model + } + + private func reading(total: Int, snapshot: String) -> MuseCodeSessionResult { + let observation = MuseCodeSessionObservation(sessionId: "s1", snapshotId: snapshot, + modelId: "muse-spark-contributor", totalTokens: total, segmentKey: "same-segment", observedAt: instant) + return .init(report: .init(generatedAt: instant.addingTimeInterval(Double(total)), windows: [], + latestObservations: [observation]), issue: nil) + } + + private func checkpoint() throws -> MuseCodeBridgeCheckpoint { + try JSONDecoder().decode(MuseCodeBridgeCheckpoint.self, + from: XCTUnwrap(defaults.data(forKey: "museCodeIngestCheckpoint"))) + } + + func testConcurrentReadingsPlanFromTheAcknowledgedBaselineAndKeepOnlyNewestPendingReport() async throws { + let model = model() + let firstStarted = expectation(description: "First post began") + let secondStarted = expectation(description: "Newest pending post began") + let gate = MuseBridgePostGate(onStart: { count in + if count == 1 { firstStarted.fulfill() } + if count == 2 { secondStarted.fulfill() } + }) + model.museCodePublishForTesting = { events, _, _ in await gate.publish(events) } + model.museCodeUsageBridgeEnabled = true + model.applyMuseCodeResult(reading(total: 100, snapshot: "A")) + await fulfillment(of: [firstStarted], timeout: 2) + model.applyMuseCodeResult(reading(total: 200, snapshot: "B")) + model.applyMuseCodeResult(reading(total: 300, snapshot: "C")) + XCTAssertEqual(gate.posts.count, 1) + gate.completeCurrent() + await fulfillment(of: [secondStarted], timeout: 2) + XCTAssertEqual(gate.posts.map { $0.first?["quantity"] as? Int }, [100, 200]) + gate.completeCurrent() + await model.museCodeBridgeTaskForTesting?.value + XCTAssertEqual(gate.posts.count, 2) + XCTAssertEqual(try checkpoint().observations["s1"]?.totalTokens, 300) + XCTAssertNil(try checkpoint().pending) + } + + func testDisabledBridgeDoesNotAdoptOldStatusOrStartANewerPostButKeepsAcknowledgedAccounting() async throws { + let model = model() + let started = expectation(description: "Post began") + let gate = MuseBridgePostGate(onStart: { _ in started.fulfill() }) + model.museCodePublishForTesting = { events, _, _ in await gate.publish(events) } + model.museCodeUsageBridgeEnabled = true + model.applyMuseCodeResult(reading(total: 100, snapshot: "A")) + await fulfillment(of: [started], timeout: 2) + model.applyMuseCodeResult(reading(total: 200, snapshot: "B")) + model.museCodeUsageBridgeEnabled = false + gate.completeCurrent() + await model.museCodeBridgeTaskForTesting?.value + XCTAssertEqual(model.museCodeBridgeStatus, "Bridge off.") + XCTAssertEqual(gate.posts.count, 1) + XCTAssertEqual(try checkpoint().observations["s1"]?.totalTokens, 100) + XCTAssertNil(try checkpoint().pending) + } + + func testTokenRotationWaitsForOldAcknowledgmentBeforePlanningWithTheNewToken() async throws { + let model = model() + let firstStarted = expectation(description: "Old token post began") + let secondStarted = expectation(description: "New token post began") + let gate = MuseBridgePostGate(onStart: { count in + if count == 1 { firstStarted.fulfill() } + if count == 2 { secondStarted.fulfill() } + }) + var currentToken = "old-fixture-token" + var tokens: [String?] = [] + model.museCodeTokenReadForTesting = { currentToken } + model.museCodeTokenSaveForTesting = { currentToken = $0 } + model.museCodePublishForTesting = { events, _, token in + tokens.append(token) + return await gate.publish(events) + } + model.museCodeUsageBridgeEnabled = true + model.applyMuseCodeResult(reading(total: 100, snapshot: "A")) + await fulfillment(of: [firstStarted], timeout: 2) + let saved = await model.saveMuseCodeIngestToken("new-fixture-token") + XCTAssertTrue(saved) + model.applyMuseCodeResult(reading(total: 200, snapshot: "B")) + XCTAssertEqual(gate.posts.count, 1) + gate.completeCurrent() + await fulfillment(of: [secondStarted], timeout: 2) + XCTAssertEqual(tokens, ["old-fixture-token", "new-fixture-token"]) + XCTAssertEqual(gate.posts.map { $0.first?["quantity"] as? Int }, [100, 100]) + gate.completeCurrent() + await model.museCodeBridgeTaskForTesting?.value + XCTAssertEqual(try checkpoint().observations["s1"]?.totalTokens, 200) + XCTAssertEqual(model.museCodeIngestTokenStatus, "Muse ingest token saved.") + } + + func testDisablingWhileTokenReadWaitsPreventsTheRequestAndRetainsTheExactPlan() async throws { + let model = model() + let started = expectation(description: "Credential read began") + var continuation: CheckedContinuation? + model.museCodeTokenReadForTesting = { + await withCheckedContinuation { + continuation = $0 + started.fulfill() + } + } + model.museCodePublishForTesting = { _, _, _ in + XCTFail("A disabled bridge must not begin a request after the credential await") + return .init() + } + model.museCodeUsageBridgeEnabled = true + model.applyMuseCodeResult(reading(total: 100, snapshot: "A")) + await fulfillment(of: [started], timeout: 2) + model.museCodeUsageBridgeEnabled = false + continuation?.resume(returning: "fixture-token") + await model.museCodeBridgeTaskForTesting?.value + XCTAssertEqual(try checkpoint().pending?.events.first?.delta, 100) + XCTAssertEqual(model.museCodeBridgeStatus, "Bridge off.") + } + + func testUncertainPostSurvivesRelaunchAndReplaysOriginalQuantityBeforeTheNewerDelta() async throws { + let first = model() + var originalEventID: String? + first.museCodePublishForTesting = { events, _, _ in + originalEventID = events.first?["eventId"] as? String + throw URLError(.timedOut) + } + first.museCodeUsageBridgeEnabled = true + first.applyMuseCodeResult(reading(total: 100, snapshot: "A")) + await first.museCodeBridgeTaskForTesting?.value + XCTAssertEqual(try checkpoint().pending?.events.first?.delta, 100) + let relaunched = model() + var posts: [[[String: Any]]] = [] + relaunched.museCodePublishForTesting = { events, _, _ in + posts.append(events) + return .init(sent: events.count, persisted: events.count) + } + relaunched.applyMuseCodeResult(reading(total: 200, snapshot: "B")) + await relaunched.museCodeBridgeTaskForTesting?.value + XCTAssertEqual(posts.map { $0.first?["quantity"] as? Int }, [100, 100]) + XCTAssertEqual(posts.first?.first?["eventId"] as? String, originalEventID) + XCTAssertNotEqual(posts.last?.first?["eventId"] as? String, originalEventID) + XCTAssertEqual(try checkpoint().observations["s1"]?.totalTokens, 200) + XCTAssertNil(try checkpoint().pending) + } + + func testRejectedAcknowledgmentRetainsPendingEventsInsteadOfAdvancingBaseline() async throws { + let model = model() + model.museCodePublishForTesting = { events, _, _ in + .init(sent: events.count, persisted: 0, rejected: events.count) + } + model.museCodeUsageBridgeEnabled = true + model.applyMuseCodeResult(reading(total: 100, snapshot: "A")) + await model.museCodeBridgeTaskForTesting?.value + XCTAssertEqual(try checkpoint().pending?.events.first?.delta, 100) + XCTAssertNil(try checkpoint().observations["s1"]) + XCTAssertTrue(model.museCodeBridgeStatus?.contains("Pending events were retained") == true) + } + + func testTokenSetupActionsAreExplicitAndUseOnlyInjectedCredentialCalls() async { + let model = model() + var saved: String? + var authorized = 0 + var deleted = 0 + model.museCodeTokenSaveForTesting = { saved = $0 } + model.museCodeTokenReauthorizeForTesting = { authorized += 1; return "fixture-token" } + model.museCodeTokenDeleteForTesting = { deleted += 1 } + XCTAssertNil(saved) + XCTAssertEqual(authorized, 0) + let success = await model.saveMuseCodeIngestToken(" fixture-token ") + XCTAssertTrue(success) + XCTAssertEqual(saved, "fixture-token") + XCTAssertTrue(model.museCodeHasSavedIngestToken) + XCTAssertFalse(model.museCodeUsageBridgeEnabled) + await model.reauthorizeMuseCodeIngestToken() + XCTAssertEqual(authorized, 1) + await model.forgetMuseCodeIngestToken() + XCTAssertEqual(deleted, 1) + XCTAssertFalse(model.museCodeHasSavedIngestToken) + XCTAssertFalse(model.museCodeUsageBridgeEnabled) + XCTAssertFalse(model.museCodeIngestTokenStatus?.contains("fixture-token") ?? true) + } +} + +@MainActor +private final class MuseBridgePostGate { + var posts: [[[String: Any]]] = [] + let onStart: (Int) -> Void + private var completion: CheckedContinuation? + + init(onStart: @escaping (Int) -> Void) { self.onStart = onStart } + + func publish(_ events: [[String: Any]]) async -> MuseCodeIngestSummary { + posts.append(events) + return await withCheckedContinuation { continuation in + completion = continuation + onStart(posts.count) + } + } + + func completeCurrent() { + let continuation = completion + completion = nil + let count = posts.last?.count ?? 0 + continuation?.resume(returning: .init(sent: count, persisted: count)) + } +} diff --git a/Tests/CodeCapsTests/MuseCodePluginTests.swift b/Tests/CodeCapsTests/MuseCodePluginTests.swift new file mode 100644 index 00000000..18a20fa6 --- /dev/null +++ b/Tests/CodeCapsTests/MuseCodePluginTests.swift @@ -0,0 +1,261 @@ +import XCTest +@testable import CodeCaps +import QuotaCore + +@MainActor +private final class SpyAlertChannel: CodeCapsAlertChannel { + var events: [CodeCapsAlertEvent] = [] + func deliver(_ event: CodeCapsAlertEvent) { events.append(event) } +} + +@MainActor +final class MuseCodePluginTests: XCTestCase { + private var suiteName = "" + private var defaults: UserDefaults! + + override func setUp() { + super.setUp() + suiteName = "MuseCodePluginTests." + UUID().uuidString + defaults = UserDefaults(suiteName: suiteName)! + } + + override func tearDown() { + defaults.removePersistentDomain(forName: suiteName) + defaults = nil + super.tearDown() + } + + // MARK: - Navigation and registry + + func testPluginPageRoundTripsThroughStorageKey() { + let page = ConsolePage.plugin("muse-code") + XCTAssertEqual(page.storageKey, "plugin:muse-code") + XCTAssertEqual(ConsolePage.fromStorageKey(page.storageKey), page) + XCTAssertFalse(page.isSettings) + XCTAssertEqual(page.settingsTitle, "Muse") + XCTAssertTrue(ConsolePage.pluginPages.contains(page)) + } + + func testPluginPageSurvivesReconcileWithoutQuotaRows() { + defaults.set("plugin:muse-code", forKey: "consoleLastPage") + let state = ConsoleState(defaults: defaults) + XCTAssertEqual(state.page, .plugin("muse-code")) + state.reconcile(available: [], readCompleted: true) + XCTAssertEqual(state.page, .plugin("muse-code"), + "a plugin page is local and never falls back to a platform") + } + + func testAlertKindsHaveStableIdentifiersAndShipEnabled() { + XCTAssertEqual(UsageAlertKind.museCodeBurn.rawValue, "museCodeBurn") + XCTAssertEqual(UsageAlertKind.museCodeStandardSession.rawValue, + "museCodeStandardSession") + let manager = ResetAlarmManager(defaults: defaults) + XCTAssertTrue(manager.preferences[.museCodeBurn].enabled) + XCTAssertTrue(manager.preferences[.museCodeStandardSession].enabled) + } + + func testStandardSessionPopupShipsOffAndPersistsWhenEnabled() { + let manager = ResetAlarmManager(defaults: defaults) + XCTAssertFalse(manager.preferences[.museCodeStandardSession].popup, + "the popup warning is opt-in and ships off") + var option = manager.preferences[.museCodeStandardSession] + option.popup = true + manager.preferences[.museCodeStandardSession] = option + let reloaded = ResetAlarmManager(defaults: defaults) + XCTAssertTrue(reloaded.preferences[.museCodeStandardSession].popup, + "the plugin page and Alerts & Alarms edit one stored preference") + } + + func testStandardSessionDeliveryCarriesThePopupOption() { + let (model, spy) = makeModel() + var delivered: [(kind: UsageAlertKind, option: UsageAlertOption)] = [] + model.alarmManager.onUsageDelivery = { kind, _, _, option in + delivered.append((kind, option)) + } + var option = model.alarmManager.preferences[.museCodeStandardSession] + option.popup = true + model.alarmManager.preferences[.museCodeStandardSession] = option + model.applyMuseCodeResult(result(total: 3_000_000, contributor: 2_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeStandardSession]) + XCTAssertEqual(delivered.map(\.kind), [.museCodeStandardSession]) + XCTAssertTrue(delivered.first?.option.popup == true, + "delivery reads the same popup option the plugin toggle sets") + } + + // MARK: - Monitor glue + + private func makeModel() -> (MonitorModel, SpyAlertChannel) { + let model = MonitorModel(defaults: defaults) + model.skipsSnapshotIOForTesting = true + let spy = SpyAlertChannel() + model.alertDispatcher.register(spy) + // Swallow the local channel so no test reaches the notification centre. + model.alarmManager.onUsageDelivery = { _, _, _, _ in } + return (model, spy) + } + + /// A reading whose window totals `total` tokens, `contributor` of them + /// on a contributor session; the rest, when any, sit on a standard + /// session. Callers may pass explicit observations instead — the bridge + /// tests do — in which case they are used as given. + private func result(total: Int, contributor: Int, + observations: [MuseCodeSessionObservation]? = nil) -> MuseCodeSessionResult { + var models: [MuseCodeModelUsage] = [] + var derived: [MuseCodeSessionObservation] = [] + if contributor > 0 { + models.append(MuseCodeModelUsage(modelId: "muse-spark-1.3-contributor", + tokens: contributor, segmentCount: 1, sessionCount: 1)) + derived.append(MuseCodeSessionObservation( + sessionId: "s-contributor", snapshotId: "snap-c", + modelId: "muse-spark-1.3-contributor", totalTokens: contributor, + segmentKey: "seg-c", observedAt: Date())) + } + if total > contributor { + models.append(MuseCodeModelUsage(modelId: "muse-wonder-1.0", tokens: total - contributor, + segmentCount: 1, sessionCount: 1)) + derived.append(MuseCodeSessionObservation( + sessionId: "s-standard", snapshotId: "snap-s", + modelId: "muse-wonder-1.0", totalTokens: total - contributor, + segmentKey: "seg-s", observedAt: Date())) + } + let window = MuseCodeWindowUsage( + windowMinutes: 90, totalTokens: total, contributorTokens: contributor, + contributorShare: total > 0 ? Double(contributor) / Double(total) : nil, + activeSessions: models.count, models: models) + return MuseCodeSessionResult( + report: MuseCodeSessionReport(generatedAt: Date(), windows: [window], + latestObservations: observations ?? derived, + currentModelObservations: (observations ?? derived).map(MuseCodeSessionModelObservation.init)), + issue: nil) + } + + func testOverThresholdMixedReadingEmitsBothAlertKinds() { + let (model, spy) = makeModel() + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeBurn, .museCodeStandardSession], + "the repeat reading re-fires neither kind: burn is in cooldown, the session is already reported") + XCTAssertNotNil(model.museCodeBurnAlert) + XCTAssertEqual(model.museCodeStandardSessionAlert?.sessionId, "s-standard") + XCTAssertTrue(spy.events.first?.body.contains("muse-wonder-1.0") == true) + XCTAssertTrue(spy.events.last?.body.contains("s-standard") == true, + "the standard-session event names the session") + } + + func testAllContributorReadingEmitsNothing() { + let (model, spy) = makeModel() + model.applyMuseCodeResult(result(total: 9_000_000, contributor: 9_000_000)) + XCTAssertTrue(spy.events.isEmpty) + XCTAssertNil(model.museCodeBurnAlert) + XCTAssertNil(model.museCodeStandardSessionAlert) + } + + func testBelowThresholdReadingEmitsOnlyTheStandardSessionKind() { + let (model, spy) = makeModel() + model.applyMuseCodeResult(result(total: 3_000_000, contributor: 2_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeStandardSession], + "the standard-session finding is its own event, not a burn side effect") + XCTAssertNil(model.museCodeBurnAlert) + XCTAssertNotNil(model.museCodeStandardSessionAlert) + } + + func testStandardSessionEventFiresOnSwitchAndRefiresAfterRecovery() { + let (model, spy) = makeModel() + func reading(modelId: String) -> MuseCodeSessionResult { + let observation = MuseCodeSessionObservation( + sessionId: "s1", snapshotId: "snap", modelId: modelId, + totalTokens: 100, segmentKey: "seg", observedAt: Date()) + return result(total: 100, + contributor: modelId.hasSuffix("-contributor") ? 100 : 0, + observations: [observation]) + } + model.applyMuseCodeResult(reading(modelId: "muse-spark-1.3-contributor")) + XCTAssertTrue(spy.events.isEmpty) + model.applyMuseCodeResult(reading(modelId: "muse-wonder-1.0")) + model.applyMuseCodeResult(reading(modelId: "muse-wonder-1.0")) + XCTAssertEqual(spy.events.filter { $0.kind == .museCodeStandardSession }.count, 1, + "the switch fires once; staying on the standard model does not refire") + model.applyMuseCodeResult(reading(modelId: "muse-spark-1.3-contributor")) + model.applyMuseCodeResult(reading(modelId: "muse-wonder-1.0")) + XCTAssertEqual(spy.events.filter { $0.kind == .museCodeStandardSession }.count, 2, + "returning to a contributor model re-arms the session") + XCTAssertEqual(model.museCodeStandardSessionAlert?.sessionId, "s1") + let eventIDs = spy.events.filter { $0.kind == .museCodeStandardSession }.map(\.identifier) + XCTAssertEqual(Set(eventIDs).count, 2) + } + + func testStandardSessionStateSurvivesModelRecreation() { + let (model, spy) = makeModel() + model.applyMuseCodeResult(result(total: 3_000_000, contributor: 2_000_000)) + XCTAssertEqual(spy.events.filter { $0.kind == .museCodeStandardSession }.count, 1) + // A fresh model over the same defaults stands in for an app + // relaunch: the persisted detector state must keep the already + // reported standard session from firing again. + let (relaunched, relaunchedSpy) = makeModel() + relaunched.applyMuseCodeResult(result(total: 3_000_000, contributor: 2_000_000)) + XCTAssertTrue(relaunchedSpy.events.isEmpty, + "the standard session was already reported before the relaunch") + XCTAssertNil(relaunched.museCodeStandardSessionAlert) + } + + func testDisabledAlertsEmitNothing() { + let (model, spy) = makeModel() + model.museCodeBurnAlertsEnabled = false + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + XCTAssertTrue(spy.events.isEmpty) + XCTAssertNil(model.museCodeBurnAlert) + XCTAssertNil(model.museCodeStandardSessionAlert) + } + + func testTwoBurnCooldownOccurrencesHaveDifferentIDsAndRepeatedPollIsSilent() { + let (model, spy) = makeModel() + let first = Date() + model.injectForTests(sections: [], now: first) + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + XCTAssertEqual(spy.events.filter { $0.kind == .museCodeBurn }.count, 1) + model.injectForTests(sections: [], now: first.addingTimeInterval(MuseCodeBurnMonitor.alertCooldown + 1)) + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + let ids = spy.events.filter { $0.kind == .museCodeBurn }.map(\.identifier) + XCTAssertEqual(ids.count, 2) + XCTAssertEqual(Set(ids).count, 2) + } + + // MARK: - Bridge + + func testBridgePostsDeltasOnceAndAdvancesBaseline() async { + let model = MonitorModel(defaults: defaults) + model.skipsSnapshotIOForTesting = true + model.alarmManager.onUsageDelivery = { _, _, _, _ in } + var posted: [[String: Any]] = [] + model.museCodeTokenReadForTesting = { "scoped-token" } + model.museCodePublishForTesting = { events, _, token in + XCTAssertEqual(token, "scoped-token") + posted = events + return MuseCodeIngestSummary(sent: events.count, persisted: events.count) + } + model.museCodeUsageBridgeEnabled = true + let observation = MuseCodeSessionObservation( + sessionId: "s1", snapshotId: "snap1", modelId: "muse-spark-1.3-contributor", + totalTokens: 700, segmentKey: "seg-a", observedAt: Date()) + model.applyMuseCodeResult(result(total: 700, contributor: 700, observations: [observation])) + await waitForBridgeStatus(model) { $0?.contains("Posted 1 token events") == true } + XCTAssertEqual(posted.count, 1) + XCTAssertEqual(posted.first?["quantity"] as? Int, 700) + XCTAssertEqual(posted.first?["eventId"] as? String, + "codecaps-muse-code:s1:snap1:muse-spark-1.3-contributor") + + model.applyMuseCodeResult(result(total: 700, contributor: 700, observations: [observation])) + await waitForBridgeStatus(model) { $0 == "No new Muse tokens to post." } + XCTAssertEqual(posted.count, 1, "the same cumulative total is never posted twice") + } + + private func waitForBridgeStatus(_ model: MonitorModel, + _ predicate: @escaping (String?) -> Bool) async { + for _ in 0..<2_000 { + if predicate(model.museCodeBridgeStatus) { return } + try? await Task.sleep(nanoseconds: 1_000_000) + } + XCTFail("bridge status never matched; last status: \(model.museCodeBridgeStatus ?? "nil")") + } +} diff --git a/Tests/CodeCapsTests/QuitConfirmationTests.swift b/Tests/CodeCapsTests/QuitConfirmationTests.swift new file mode 100644 index 00000000..67091d92 --- /dev/null +++ b/Tests/CodeCapsTests/QuitConfirmationTests.swift @@ -0,0 +1,38 @@ +import AppKit +import Carbon +import XCTest +@testable import CodeCaps + +final class QuitConfirmationTests: XCTestCase { + func testAlertResponsesChooseTheExpectedQuitAction() { + XCTAssertEqual(QuitConfirmationChoice(response: .alertFirstButtonReturn), .closeAndKeepRunning) + XCTAssertEqual(QuitConfirmationChoice(response: .alertSecondButtonReturn), .quit) + XCTAssertEqual(QuitConfirmationChoice(response: .alertThirdButtonReturn), .cancel) + XCTAssertEqual(QuitConfirmationChoice(response: NSApplication.ModalResponse(rawValue: 0)), .cancel) + } + + func testKeepRunningChoiceKeepsMenuBarAccessInDockOnlyMode() { + XCTAssertFalse(QuitConfirmationPolicy.shouldShowStatusItem(displayMode: .dock, keepRunningOverride: false)) + XCTAssertTrue(QuitConfirmationPolicy.shouldShowStatusItem(displayMode: .dock, keepRunningOverride: true)) + XCTAssertTrue(QuitConfirmationPolicy.shouldShowStatusItem(displayMode: .both, keepRunningOverride: false)) + } + + func testOrdinaryQuitPromptsEvenWithoutAUserEvent() { + XCTAssertTrue(QuitConfirmationPolicy.shouldConfirm(systemTerminationReason: nil, + automaticInstallInProgress: false)) + } + + func testSystemShutdownLogoutAndRestartSkipThePrompt() { + for reason in [kAEQuitAll, kAEShutDown, kAERestart, kAEReallyLogOut] { + XCTAssertFalse(QuitConfirmationPolicy.shouldConfirm(systemTerminationReason: reason, + automaticInstallInProgress: false)) + } + } + + func testOnlyAnActiveAutomaticInstallSkipsThePrompt() { + XCTAssertFalse(QuitConfirmationPolicy.shouldConfirm(systemTerminationReason: nil, + automaticInstallInProgress: true)) + XCTAssertTrue(QuitConfirmationPolicy.shouldConfirm(systemTerminationReason: nil, + automaticInstallInProgress: false)) + } +} diff --git a/Tests/CodeCapsTests/SMSAlertControllerTests.swift b/Tests/CodeCapsTests/SMSAlertControllerTests.swift new file mode 100644 index 00000000..b18d41ff --- /dev/null +++ b/Tests/CodeCapsTests/SMSAlertControllerTests.swift @@ -0,0 +1,163 @@ +import XCTest +import QuotaCore +@testable import CodeCaps + +@MainActor +final class SMSAlertControllerTests: XCTestCase { + private var credentials: TwilioSMSCredentials { + .init(configuration: .init(accountSID: "AC" + String(repeating: "a", count: 32), + apiKeySID: "SK" + String(repeating: "b", count: 32), + messagingServiceSID: "MG" + String(repeating: "c", count: 32), recipient: "+15551234567"), + apiKeySecret: "fixture-secret") + } + + private func makeDefaults() -> (UserDefaults, String) { + let suite = "CodeCaps.SMSControllerTests." + UUID().uuidString + return (UserDefaults(suiteName: suite)!, suite) + } + + func testConstructionAndDisabledKindsNeverReadKeychain() { + let (defaults, suite) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + let vault = SMSCredentialFixture() + let controller = SMSAlertController(defaults: defaults, credentialAccess: vault.access) + XCTAssertEqual(vault.loads, 0) + XCTAssertNil(controller.deliver(kind: "museCodeBurn", title: "Title", body: "Body", eventID: "event")) + controller.preferences["anomaly"] = true + XCTAssertNil(controller.deliver(kind: "anomaly", title: "Title", body: "Body", eventID: "event")) + XCTAssertEqual(vault.loads, 0) + XCTAssertFalse(controller.hasSavedSetup) + } + + func testBlankSecretPreservesMatchingSavedAPIKeyAndChangedKeyRequiresSecret() async { + let (defaults, suite) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + let vault = SMSCredentialFixture() + let controller = SMSAlertController(defaults: defaults, credentialAccess: vault.access) + let saved = await controller.saveSetup(configuration: credentials.configuration, apiKeySecret: credentials.apiKeySecret) + XCTAssertTrue(saved) + var config = credentials.configuration + config.recipient = "+15557654321" + let updated = await controller.saveSetup(configuration: config, apiKeySecret: "") + XCTAssertTrue(updated) + XCTAssertEqual(vault.credentials?.apiKeySecret, "fixture-secret") + XCTAssertEqual(vault.credentials?.configuration.recipient, "+15557654321") + config.apiKeySID = "SK" + String(repeating: "d", count: 32) + let refused = await controller.saveSetup(configuration: config, apiKeySecret: "") + XCTAssertFalse(refused) + XCTAssertEqual(vault.credentials?.configuration.apiKeySID, credentials.configuration.apiKeySID) + XCTAssertFalse(controller.status?.contains("fixture-secret") ?? true) + let relaunched = SMSAlertController(defaults: defaults, credentialAccess: vault.access) + XCTAssertTrue(relaunched.hasSavedSetup) + XCTAssertEqual(relaunched.configuration?.recipient, "+15557654321") + XCTAssertFalse(relaunched.preferences["museCodeBurn"]) + } + + func testSMSSendsWhenLocalMethodsAreOffAndDuplicateEventDoesNotReplay() async { + let (defaults, suite) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + let vault = SMSCredentialFixture() + let transport = SMSControllerTransportFixture() + let coordinator = SMSAlertCoordinator(persistence: .userDefaults(defaults, key: "fixture-history"), client: transport.client) + let controller = SMSAlertController(defaults: defaults, credentialAccess: vault.access, coordinator: coordinator) + _ = await controller.saveSetup(configuration: credentials.configuration, apiKeySecret: credentials.apiKeySecret) + controller.preferences["quotaExhaustion"] = true + let manager = ResetAlarmManager(defaults: defaults) + manager.preferences[.quotaExhaustion] = .init(enabled: true, notification: false, popup: false, sound: .silent) + var delivery: Task? + manager.additionalDelivery = { kind, title, body, eventID in + delivery = controller.deliver(kind: kind.rawValue, title: title, body: body, eventID: eventID) + } + manager.deliverUsageAlert(kind: .quotaExhaustion, title: "Quota Exhausted", body: "Fixture", identifier: "stable-event") + await delivery?.value + XCTAssertEqual(transport.count, 1) + XCTAssertEqual(controller.status, "Text accepted by Twilio.") + let relaunched = SMSAlertController(defaults: defaults, credentialAccess: vault.access, + coordinator: SMSAlertCoordinator(persistence: .userDefaults(defaults, key: "fixture-history"), client: transport.client)) + XCTAssertEqual(transport.count, 1) + await relaunched.deliver(kind: "quotaExhaustion", title: "Quota Exhausted", body: "Fixture", eventID: "stable-event")?.value + XCTAssertEqual(transport.count, 1) + } + + func testMasterKindOffPreventsAdditionalDelivery() { + let (defaults, suite) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + let manager = ResetAlarmManager(defaults: defaults) + manager.preferences[.quotaExhaustion] = .init(enabled: false, notification: false, popup: false, sound: .silent) + manager.additionalDelivery = { _, _, _, _ in XCTFail("Disabled kind cannot deliver SMS") } + manager.deliverUsageAlert(kind: .quotaExhaustion, title: "Fixture", body: "Fixture", identifier: "event") + } + + func testDisablingSMSWhileCredentialReadIsPendingCancelsSubmission() async { + let (defaults, suite) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + defaults.set(true, forKey: SMSAlertController.Keys.hasSetup) + let started = expectation(description: "Credential read began") + var pending: CheckedContinuation? + let access = SMSCredentialAccess(load: { + await withCheckedContinuation { continuation in + pending = continuation + started.fulfill() + } + }, save: { _ in }, clear: {}, reauthorize: { nil }) + let transport = SMSControllerTransportFixture() + let coordinator = SMSAlertCoordinator(persistence: .init(load: { nil }, save: { _ in }), client: transport.client) + let controller = SMSAlertController(defaults: defaults, credentialAccess: access, coordinator: coordinator) + controller.preferences["museCodeBurn"] = true + let delivery = controller.deliver(kind: "museCodeBurn", title: "Fixture", body: "Fixture", eventID: "event") + await fulfillment(of: [started], timeout: 1) + controller.preferences["museCodeBurn"] = false + pending?.resume(returning: credentials) + await delivery?.value + XCTAssertEqual(transport.count, 0) + } + + func testForgetClearsSetupButKeepsDedupeHistoryAndReauthorizationIsExplicit() async { + let (defaults, suite) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + let vault = SMSCredentialFixture() + let controller = SMSAlertController(defaults: defaults, credentialAccess: vault.access) + _ = await controller.saveSetup(configuration: credentials.configuration, apiKeySecret: credentials.apiKeySecret) + defaults.set(Data("fixture-history".utf8), forKey: SMSAlertController.Keys.history) + XCTAssertEqual(vault.reauthorizations, 0) + await controller.reauthorizeSavedSetup() + XCTAssertEqual(vault.reauthorizations, 1) + await controller.forgetSetup() + XCTAssertFalse(controller.hasSavedSetup) + XCTAssertNil(controller.configuration) + XCTAssertNil(vault.credentials) + XCTAssertNotNil(defaults.data(forKey: SMSAlertController.Keys.history)) + } +} + +@MainActor +private final class SMSCredentialFixture { + var credentials: TwilioSMSCredentials? + var loads = 0 + var reauthorizations = 0 + var access: SMSCredentialAccess { + .init(load: { self.loads += 1; return self.credentials }, + save: { self.credentials = $0 }, clear: { self.credentials = nil }, + reauthorize: { self.reauthorizations += 1; return self.credentials }) + } +} + +private final class SMSControllerTransportFixture: @unchecked Sendable { + private let lock = NSLock() + private var requests = 0 + var count: Int { + lock.lock(); defer { lock.unlock() } + return requests + } + private func increment() { + lock.lock(); defer { lock.unlock() } + requests += 1 + } + var client: TwilioSMSClient { + TwilioSMSClient(transport: { request in + self.increment() + return (Data(#"{"sid":"SMdddddddddddddddddddddddddddddddd","status":"queued"}"#.utf8), + HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)!) + }) + } +} diff --git a/Tests/CodeCapsTests/TokenStoreTests.swift b/Tests/CodeCapsTests/TokenStoreTests.swift index f8c1499a..319efe48 100644 --- a/Tests/CodeCapsTests/TokenStoreTests.swift +++ b/Tests/CodeCapsTests/TokenStoreTests.swift @@ -86,25 +86,27 @@ final class TokenStoreTests: XCTestCase { // MARK: Whose items - /// Only CodeCaps's own two items are ever named. Claude Code's saved login + /// Only CodeCaps's own three items are ever named.  Claude Code's saved login /// is read by `ClaudeCredentialSource` through `/usr/bin/security` and must /// never reach this store. func testOnlyCodeCapsItemsAreOwn() { XCTAssertTrue(TokenStore.isOwnService(TokenStore.readService)) XCTAssertTrue(TokenStore.isOwnService(TokenStore.syncService)) + XCTAssertTrue(TokenStore.isOwnService(TokenStore.museCodeIngestService)) XCTAssertFalse(TokenStore.isOwnService("Claude Code-credentials")) XCTAssertFalse(TokenStore.isOwnService("")) } /// Matching on the suffix would accept any app's `.sync-token`, and a - /// `.dev` build would accept the release app's names. Only this build's - /// own two names count. + /// `.dev` build would accept the release app's names.  Only this build's + /// own explicit names count. func testServicesThatMerelyEndTheSameWayAreNotOwn() { XCTAssertFalse(TokenStore.isOwnService("com.other.app.sync-token")) XCTAssertFalse(TokenStore.isOwnService("com.other.app.read-token")) XCTAssertFalse(TokenStore.isOwnService(TokenStore.readService + ".extra")) XCTAssertFalse(TokenStore.isOwnService(TokenStore.serviceName(suffix: "read-token", bundleIdentifier: "com.other.app"))) - XCTAssertEqual(TokenStore.ownServices, [TokenStore.readService, TokenStore.syncService]) + XCTAssertEqual(TokenStore.ownServices, + [TokenStore.readService, TokenStore.syncService, TokenStore.museCodeIngestService]) } // MARK: Failure wording diff --git a/Tests/CodeCapsTests/TwilioCredentialStoreTests.swift b/Tests/CodeCapsTests/TwilioCredentialStoreTests.swift new file mode 100644 index 00000000..e22f7c54 --- /dev/null +++ b/Tests/CodeCapsTests/TwilioCredentialStoreTests.swift @@ -0,0 +1,82 @@ +import XCTest +import Security +import QuotaCore +@testable import CodeCaps + +final class TwilioCredentialStoreTests: XCTestCase { + private var credentials: TwilioSMSCredentials { + .init(configuration: .init(accountSID: "AC" + String(repeating: "a", count: 32), + apiKeySID: "SK" + String(repeating: "b", count: 32), + messagingServiceSID: "MG" + String(repeating: "c", count: 32), recipient: "+15551234567"), + apiKeySecret: "fixture-secret") + } + + func testBuildScopedSingleRecordAndClearUseOnlyFakeKeychain() async throws { + let fixture = TwilioKeychainFixture() + let store = TwilioCredentialStore(calls: fixture.calls, bundleIdentifier: "com.example.CodeCaps.test") + let missing = await store.load() + XCTAssertNil(missing) + try await store.save(credentials) + let loaded = await store.load() + XCTAssertEqual(loaded, credentials) + XCTAssertEqual(fixture.itemCount, 1) + XCTAssertEqual(fixture.services, ["com.example.CodeCaps.test.twilio-sms"]) + try await store.clear() + let cleared = await store.load() + XCTAssertNil(cleared) + XCTAssertEqual(fixture.itemCount, 0) + } + + func testProductionAndDevelopmentServicesDifferFromExistingTokens() { + let release = TwilioCredentialStore.serviceName(bundleIdentifier: "com.example.CodeCaps") + let development = TwilioCredentialStore.serviceName(bundleIdentifier: "com.example.CodeCaps.dev") + XCTAssertNotEqual(release, development) + XCTAssertFalse(TokenStore.ownServices.contains(release)) + XCTAssertFalse(TokenStore.ownServices.contains(development)) + } + + func testInvalidSetupNeverTouchesKeychain() async { + let fixture = TwilioKeychainFixture() + let store = TwilioCredentialStore(calls: fixture.calls, bundleIdentifier: "com.example.CodeCaps.test") + var invalid = credentials + invalid.configuration.apiKeySID = "AC" + String(repeating: "b", count: 32) + do { + try await store.save(invalid) + XCTFail("Expected invalid setup rejection") + } catch { XCTAssertEqual(error as? TwilioSMSFailure, .invalidConfiguration) } + XCTAssertEqual(fixture.itemCount, 0) + XCTAssertTrue(fixture.services.isEmpty) + } +} + +private final class TwilioKeychainFixture: @unchecked Sendable { + private let lock = NSLock() + private var values: [String: Data] = [:] + private var touched: Set = [] + var calls: KeychainCalls { + .init(copyData: { service, account, _ in + self.lock.lock(); defer { self.lock.unlock() } + self.touched.insert(service) + let data = self.values[service + "/" + account] + return (data == nil ? errSecItemNotFound : errSecSuccess, data) + }, delete: { service, account in + self.lock.lock(); defer { self.lock.unlock() } + self.touched.insert(service) + self.values[service + "/" + account] = nil + return errSecSuccess + }, add: { service, account, data in + self.lock.lock(); defer { self.lock.unlock() } + self.touched.insert(service) + self.values[service + "/" + account] = data + return errSecSuccess + }) + } + var itemCount: Int { + lock.lock(); defer { lock.unlock() } + return values.count + } + var services: Set { + lock.lock(); defer { lock.unlock() } + return touched + } +} diff --git a/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift b/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift new file mode 100644 index 00000000..f8d8c747 --- /dev/null +++ b/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift @@ -0,0 +1,89 @@ +import XCTest +@testable import QuotaCore + +private final class InvocationCounter: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + + func increment() { + lock.lock() + count += 1 + lock.unlock() + } + + func value() -> Int { + lock.lock() + defer { lock.unlock() } + return count + } +} + +private struct RegistryFakeReader: LocalQuotaReading { + let result: LocalQuotaResult + var delayNanoseconds: UInt64 = 0 + + func read() async -> LocalQuotaResult { + if delayNanoseconds > 0 { try? await Task.sleep(nanoseconds: delayNanoseconds) } + return result + } +} + +final class LocalQuotaReaderRegistryTests: XCTestCase { + func testDisabledOptionalReaderIsNotConstructedOrInvoked() async { + let calls = InvocationCounter() + let registry = LocalQuotaReaderRegistry(registrations: [ + LocalQuotaReaderRegistration(id: "kimi", label: "Kimi", isOptional: true) { + calls.increment() + return RegistryFakeReader(result: LocalQuotaResult(issues: ["kimi": "read"])) + }, + ]) + var preferences = QuotaReaderPreferences() + preferences.setEnabled(false, for: "kimi") + + let result = await registry.read(preferences: preferences) + + XCTAssertEqual(calls.value(), 0) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertTrue(result.issues.isEmpty) + } + + func testMissingAndUnknownReaderChoicesDefaultToEnabled() { + let preferences = QuotaReaderPreferences() + XCTAssertTrue(preferences.isEnabled("kimi")) + XCTAssertTrue(preferences.isEnabled("future-provider")) + } + + func testPreferencesPersistExplicitChoiceAndPreserveUnknownIDs() { + let suite = "LocalQuotaReaderRegistryTests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + var preferences = QuotaReaderPreferences() + preferences.setEnabled(false, for: "kimi") + preferences.setEnabled(false, for: "future-provider") + preferences.save(to: defaults) + + let loaded = QuotaReaderPreferences.load(from: defaults) + XCTAssertFalse(loaded.isEnabled("kimi")) + XCTAssertFalse(loaded.isEnabled("future-provider")) + XCTAssertTrue(loaded.isEnabled("zcode")) + } + + func testNonOptionalReadersRunAndResultsMergeInRegistrationOrder() async { + let registry = LocalQuotaReaderRegistry(registrations: [ + LocalQuotaReaderRegistration(id: "primary", label: "Primary") { + RegistryFakeReader(result: LocalQuotaResult(issues: ["same": "first"], + consentNeeded: ["first"]), + delayNanoseconds: 50_000_000) + }, + LocalQuotaReaderRegistration(id: "kimi", label: "Kimi", isOptional: true) { + RegistryFakeReader(result: LocalQuotaResult(issues: ["same": "last"], + consentNeeded: ["second"])) + }, + ]) + + let result = await registry.read() + + XCTAssertEqual(result.issues["same"], "last") + XCTAssertEqual(result.consentNeeded, ["first", "second"]) + } +} diff --git a/Tests/QuotaCoreTests/MuseCodeBurnMonitorTests.swift b/Tests/QuotaCoreTests/MuseCodeBurnMonitorTests.swift new file mode 100644 index 00000000..d1d3a661 --- /dev/null +++ b/Tests/QuotaCoreTests/MuseCodeBurnMonitorTests.swift @@ -0,0 +1,109 @@ +import XCTest +@testable import QuotaCore + +final class MuseCodeBurnMonitorTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + /// A reading whose window totals `total` tokens, `contributor` of them + /// on a contributor session; the rest, when any, sit on one standard + /// session, which is what the burn rule's presence test reads. + private func report(total: Int, contributor: Int, + standardModel: String = "muse-wonder-1.0") -> MuseCodeSessionReport { + var models: [MuseCodeModelUsage] = [] + var observations: [MuseCodeSessionObservation] = [] + if contributor > 0 { + models.append(MuseCodeModelUsage(modelId: "muse-spark-1.3-contributor", + tokens: contributor, segmentCount: 1, sessionCount: 1)) + observations.append(MuseCodeSessionObservation( + sessionId: "s-contributor", snapshotId: "snap-c", + modelId: "muse-spark-1.3-contributor", totalTokens: contributor, + segmentKey: "seg-c", observedAt: now)) + } + if total > contributor { + models.append(MuseCodeModelUsage(modelId: standardModel, tokens: total - contributor, + segmentCount: 1, sessionCount: 1)) + observations.append(MuseCodeSessionObservation( + sessionId: "s-standard", snapshotId: "snap-s", + modelId: standardModel, totalTokens: total - contributor, + segmentKey: "seg-s", observedAt: now)) + } + let window = MuseCodeWindowUsage(windowMinutes: 90, totalTokens: total, + contributorTokens: contributor, + contributorShare: total > 0 ? Double(contributor) / Double(total) : nil, + activeSessions: observations.count, models: models) + return MuseCodeSessionReport(generatedAt: now, windows: [window], + latestObservations: observations, + currentModelObservations: observations.map(MuseCodeSessionModelObservation.init)) + } + + func testBurnFiresOverThresholdWithStandardSessionPresent() { + let alert = MuseCodeBurnMonitor.evaluateBurn( + report: report(total: 5_000_000, contributor: 4_000_000), + thresholdTokens: MuseCodeBurnMonitor.defaultThresholdTokens) + let burn = try? XCTUnwrap(alert) + XCTAssertNotNil(burn) + XCTAssertEqual(burn?.totalTokens, 5_000_000) + XCTAssertEqual(burn?.standardSessions.map(\.sessionId), ["s-standard"]) + XCTAssertEqual(burn?.standardSessions.map(\.modelId), ["muse-wonder-1.0"]) + XCTAssertTrue(burn?.body.contains("s-standard") == true, + "the warning names the standard session present") + XCTAssertTrue(burn?.body.contains("muse-wonder-1.0") == true, + "the warning names the standard model present") + } + + func testBurnSuppressedOverThresholdWithNoStandardSessions() { + let report = report(total: 9_000_000, contributor: 9_000_000) + XCTAssertNil(MuseCodeBurnMonitor.evaluateBurn( + report: report, thresholdTokens: MuseCodeBurnMonitor.defaultThresholdTokens), + "a heavy window with zero standard-model sessions does not fire, however it is shared") + XCTAssertEqual(MuseCodeBurnMonitor.status(report: report, issue: nil, + thresholdTokens: 4_000_000), + .allContributor(totalTokens: 9_000_000)) + } + + func testBurnSuppressedBelowThresholdWithStandardSessionPresent() { + let report = report(total: 3_000_000, contributor: 2_000_000) + XCTAssertNil(MuseCodeBurnMonitor.evaluateBurn( + report: report, thresholdTokens: MuseCodeBurnMonitor.defaultThresholdTokens), + "below the threshold the combined burn rule stays silent; the standard session is the detector kind's event, not this one's") + XCTAssertEqual(MuseCodeBurnMonitor.status(report: report, issue: nil, + thresholdTokens: 4_000_000), + .belowThreshold(totalTokens: 3_000_000)) + } + + func testBurnSuppressedExactlyAtThreshold() { + let report = report(total: 4_000_000, contributor: 3_000_000) + XCTAssertNil(MuseCodeBurnMonitor.evaluateBurn( + report: report, thresholdTokens: 4_000_000), + "exceeds is strict: exactly at the threshold has not exceeded it") + } + + func testStatusForMissingAndEmptyReports() { + XCTAssertEqual(MuseCodeBurnMonitor.status(report: nil, issue: "missing", + thresholdTokens: 4_000_000), + .storeUnavailable) + XCTAssertEqual(MuseCodeBurnMonitor.status(report: report(total: 0, contributor: 0), + issue: nil, thresholdTokens: 4_000_000), + .noActivity) + } + + func testWarningStatusCarriesTheBurnAlert() { + let report = report(total: 5_000_000, contributor: 4_000_000) + guard case .warning(let alert) = MuseCodeBurnMonitor.status( + report: report, issue: nil, thresholdTokens: 4_000_000) else { + return XCTFail("an over-threshold window with a standard session is a warning state") + } + XCTAssertEqual(alert.totalTokens, 5_000_000) + } + func testHistoricalStandardTokensDoNotSatisfyCurrentPresenceWhenHeadModelIsNil() { + let historical = report(total: 5_000_000, contributor: 4_000_000) + let current = MuseCodeSessionReport(generatedAt: now, windows: historical.windows, + latestObservations: historical.latestObservations, + currentModelObservations: [.init(sessionId: "s-standard", modelId: nil, observedAt: now)]) + XCTAssertNil(MuseCodeBurnMonitor.evaluateBurn(report: current, thresholdTokens: 4_000_000)) + XCTAssertTrue(MuseCodeBurnMonitor.standardSessions(in: current).isEmpty) + XCTAssertEqual(MuseCodeBurnMonitor.status(report: current, issue: nil, thresholdTokens: 4_000_000), + .currentModelsUnknown(totalTokens: 5_000_000)) + } + +} diff --git a/Tests/QuotaCoreTests/MuseCodeSessionIngestTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionIngestTests.swift new file mode 100644 index 00000000..4e56036e --- /dev/null +++ b/Tests/QuotaCoreTests/MuseCodeSessionIngestTests.swift @@ -0,0 +1,168 @@ +import XCTest +@testable import QuotaCore + +final class MuseCodeSessionIngestTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + private func observation(session: String = "s1", snapshot: String = "snap1", + model: String = "muse-wonder-1.0", total: Int, + segment: String = "seg-a", minutesAgo: Double = 5) -> MuseCodeSessionObservation { + MuseCodeSessionObservation(sessionId: session, snapshotId: snapshot, modelId: model, + totalTokens: total, segmentKey: segment, + observedAt: now.addingTimeInterval(-minutesAgo * 60)) + } + + // MARK: - Event shape (the verified contract) + + func testEventMatchesVerifiedContractShape() { + let event = MuseCodeSessionIngest.event( + observation: observation(model: "muse-spark-1.3-contributor", total: 5_000), delta: 1_250) + XCTAssertEqual(Set(event.keys), ["eventId", "provider", "service", "producerKeyRef", + "metricType", "unit", "quantity", "billingMode", + "confidence", "occurredAt", "metadata"]) + XCTAssertEqual(event["eventId"] as? String, + "codecaps-muse-code:s1:snap1:muse-spark-1.3-contributor") + XCTAssertEqual(event["provider"] as? String, "muse-code") + XCTAssertEqual(event["service"] as? String, "muse-code") + XCTAssertEqual(event["producerKeyRef"] as? String, "muse-spark-1.3-contributor") + XCTAssertEqual(event["metricType"] as? String, "usage") + XCTAssertEqual(event["unit"] as? String, "token") + XCTAssertEqual(event["quantity"] as? Int, 1_250, "quantity is the delta, never the cumulative total") + XCTAssertEqual(event["billingMode"] as? String, "estimated") + XCTAssertEqual(event["confidence"] as? String, "estimated") + let metadata = event["metadata"] as? [String: Any] + XCTAssertEqual(metadata?["sessionId"] as? String, "s1") + XCTAssertEqual(metadata?["contributor"] as? Bool, true) + XCTAssertEqual(metadata?["source"] as? String, "muse-session-stores") + } + + func testBatchEnvelopeMatchesVerifiedContractShape() throws { + let events = [MuseCodeSessionIngest.event(observation: observation(total: 10), delta: 10)] + let data = try MuseCodeSessionIngest.batchData(events: events) + let root = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + XCTAssertEqual(Set(root.keys), ["schemaVersion", "producerId", "events"]) + XCTAssertEqual(root["schemaVersion"] as? Int, 2) + XCTAssertEqual(root["producerId"] as? String, "muse-code") + XCTAssertEqual((root["events"] as? [Any])?.count, 1) + } + + func testBatchesChunkAtOneHundredEvents() { + let events = (0..<205).map { index in + MuseCodeSessionIngest.event(observation: observation(session: "s\(index)", total: 1), delta: 1) + } + XCTAssertEqual(MuseCodeSessionIngest.eventBatches(events: events).map(\.count), [100, 100, 5]) + } + + // MARK: - Delta discipline + + func testFirstObservationEmitsTheSegmentTotal() { + let plan = MuseCodeDeltaPlanner.plan(observations: [observation(total: 700)], previous: [:]) + XCTAssertEqual(plan.events.map(\.delta), [700]) + XCTAssertEqual(plan.updated["s1"]?.totalTokens, 700) + } + + func testSameSegmentEmitsOnlyThePositiveDelta() { + let previous = ["s1": observation(total: 700)] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", total: 950)], previous: previous) + XCTAssertEqual(plan.events.map(\.delta), [250], + "950 cumulative minus the 700 already posted is a 250 delta, not 950") + XCTAssertEqual(plan.events.first?.observation.snapshotId, "snap2") + } + + func testUnchangedTotalEmitsNothingButAdvancesBaseline() { + let previous = ["s1": observation(total: 700)] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", total: 700)], previous: previous) + XCTAssertTrue(plan.events.isEmpty) + XCTAssertEqual(plan.updated["s1"]?.snapshotId, "snap2") + } + + func testSegmentResetEmitsTheNewSegmentsTotal() { + let previous = ["s1": observation(total: 700, segment: "seg-a")] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", total: 300, segment: "seg-b")], + previous: previous) + XCTAssertEqual(plan.events.map(\.delta), [300], + "a reset segment's total is the delta, even though it is below the old total") + } + + func testModelSwitchEmitsTheNewTotal() { + let previous = ["s1": observation(model: "muse-wonder-1.0", total: 700)] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", model: "muse-spark-1.3-contributor", total: 200)], + previous: previous) + XCTAssertEqual(plan.events.map(\.delta), [200]) + XCTAssertEqual(plan.events.first?.observation.modelId, "muse-spark-1.3-contributor") + } + + func testDecreasedTotalInSameSegmentPreservesHighWaterMark() { + let previous = ["s1": observation(total: 700)] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", total: 400)], previous: previous) + XCTAssertTrue(plan.events.isEmpty, "a negative delta is never posted") + XCTAssertEqual(plan.updated["s1"]?.totalTokens, 700) + } + + func testLowerCounterThenRecoveryNeverBillsTheSameTokensAgain() { + let previous = ["s1": observation(total: 1_000)] + let lower = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", total: 900)], previous: previous) + let recovered = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap3", total: 1_000)], previous: lower.updated) + XCTAssertTrue(lower.events.isEmpty) + XCTAssertTrue(recovered.events.isEmpty) + XCTAssertEqual(recovered.updated["s1"]?.totalTokens, 1_000) + } + + func testOlderModelOrSegmentCannotRewindAnAcknowledgedObservation() { + let previous = ["s1": observation(snapshot: "new", total: 1_000, segment: "new-segment", minutesAgo: 1)] + let delayed = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "old", total: 900, segment: "old-segment", minutesAgo: 5)], + previous: previous) + XCTAssertTrue(delayed.events.isEmpty) + XCTAssertEqual(delayed.updated, previous) + } + + // MARK: - Poster + + private func response(status: Int = 200) -> HTTPURLResponse { + HTTPURLResponse(url: MuseCodeSessionIngest.endpoint, statusCode: status, + httpVersion: nil, headerFields: nil)! + } + + func testPosterPostsBatchesAndValidatesCompleteAcknowledgment() async throws { + let events = [MuseCodeSessionIngest.event(observation: observation(total: 10), delta: 10), + MuseCodeSessionIngest.event(observation: observation(session: "s2", total: 5), delta: 5)] + var requests: [URLRequest] = [] + let poster = MuseCodeSessionPoster { request in + requests.append(request) + let ack: [String: Any] = ["received": 2, "persisted": 2, "duplicates": 0, + "pruned": 0, "rejected": 0] + return (try JSONSerialization.data(withJSONObject: ack), self.response()) + } + let summary = try await poster.publish(events: events, to: MuseCodeSessionIngest.endpoint, token: "scoped-token") + XCTAssertEqual(summary, MuseCodeIngestSummary(sent: 2, persisted: 2, duplicates: 0, pruned: 0, rejected: 0)) + XCTAssertEqual(requests.count, 1) + XCTAssertEqual(requests.first?.value(forHTTPHeaderField: "x-usage-telemetry-version"), "2") + XCTAssertEqual(requests.first?.value(forHTTPHeaderField: "Authorization"), "Bearer scoped-token") + let body = try XCTUnwrap(JSONSerialization.jsonObject( + with: try XCTUnwrap(requests.first?.httpBody)) as? [String: Any]) + XCTAssertEqual(body["producerId"] as? String, "muse-code") + } + + func testPosterRejectsIncompleteAcknowledgment() async { + let events = [MuseCodeSessionIngest.event(observation: observation(total: 10), delta: 10)] + let poster = MuseCodeSessionPoster { _ in + let ack: [String: Any] = ["received": 0, "persisted": 0, "duplicates": 0, + "pruned": 0, "rejected": 0] + return (try JSONSerialization.data(withJSONObject: ack), self.response()) + } + do { + _ = try await poster.publish(events: events, to: MuseCodeSessionIngest.endpoint, token: "scoped-token") + XCTFail("an acknowledgment that does not account for the sent events must throw") + } catch { + XCTAssertTrue(error is QuotaPublisherError) + } + } +} diff --git a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift new file mode 100644 index 00000000..a2979fca --- /dev/null +++ b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift @@ -0,0 +1,229 @@ +import XCTest +@testable import QuotaCore + +final class MuseCodeSessionReaderTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + private func segment(session: String = "s1", model: String, tokens: Int, + minutesAgo: Double, first: String, last: String) -> MuseCodeTokenSegment { + MuseCodeTokenSegment(sessionId: session, modelId: model, totalTokens: tokens, + observedAt: now.addingTimeInterval(-minutesAgo * 60), + sourceFirstId: first, sourceLastId: last) + } + + func testAggregateDedupesRepeatedSegmentsPerSession() { + let original = segment(model: "muse-spark-1.3-contributor", tokens: 1_000, + minutesAgo: 10, first: "a", last: "b") + let reread = segment(model: "muse-spark-1.3-contributor", tokens: 1_000, + minutesAgo: 9, first: "a", last: "b") + let otherSession = segment(session: "s2", model: "muse-spark-1.3-contributor", + tokens: 1_000, minutesAgo: 8, first: "a", last: "b") + let report = MuseCodeSessionReader.aggregate( + segments: [original, reread, otherSession], + sessionActivity: ["s1": now, "s2": now], now: now) + let window = report.window(minutes: 90) + XCTAssertEqual(window?.totalTokens, 2_000, + "the same source range in one session is one segment; in another session it is its own") + XCTAssertEqual(window?.models.first?.segmentCount, 2) + XCTAssertEqual(window?.models.first?.sessionCount, 2) + XCTAssertEqual(report.segments.count, 2) + } + + func testAggregateWindowsAndContributorShare() { + let segments = [ + segment(model: "muse-spark-1.3-contributor", tokens: 3_000_000, + minutesAgo: 30, first: "a", last: "b"), + segment(model: "muse-wonder-1.0", tokens: 1_000_000, + minutesAgo: 20, first: "c", last: "d"), + segment(model: "muse-spark-1.3-contributor", tokens: 2_000_000, + minutesAgo: 75, first: "e", last: "f"), + segment(model: "muse-wonder-full-1.0", tokens: 9_000_000, + minutesAgo: 120, first: "g", last: "h") + ] + let report = MuseCodeSessionReader.aggregate( + segments: segments, sessionActivity: ["s1": now], now: now) + let window60 = report.window(minutes: 60) + XCTAssertEqual(window60?.totalTokens, 4_000_000) + XCTAssertEqual(window60?.contributorTokens, 3_000_000) + XCTAssertEqual(window60?.contributorShare, 0.75) + let window90 = report.window(minutes: 90) + XCTAssertEqual(window90?.totalTokens, 6_000_000) + XCTAssertEqual(window90?.contributorShare, 5.0 / 6.0) + XCTAssertEqual(window90?.standardModels.map(\.modelId), ["muse-wonder-1.0"], + "the 120-minute-old standard segment is outside both windows") + XCTAssertEqual(window90?.activeSessions, 1) + XCTAssertEqual(window90?.tokensPerHour, 4_000_000) + } + + func testAggregateEmptyWindowHasNoShare() { + let report = MuseCodeSessionReader.aggregate(segments: [], sessionActivity: [:], now: now) + XCTAssertEqual(report.window(minutes: 90)?.totalTokens, 0) + XCTAssertNil(report.window(minutes: 90)?.contributorShare, + "no burn is neither 0% nor 100% contributor") + } + + // MARK: - Filesystem + + private func makeHome() throws -> URL { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("MuseCodeSessionReaderTests." + UUID().uuidString) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + return home + } + + private func writeSnapshot(home: URL, session: String, name: String, + usage: [String: Any]?, modified: Date, headId: String = "x", + nullTokenUsage: Bool = false) throws { + let directory = home + .appendingPathComponent(".local/share/muse/sessions/.msp-view-g6/\(session)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = directory.appendingPathComponent(name) + if let usage { + let root: [String: Any] = ["continuation": ["view_materialization": + ["current_state": ["tokenUsage": usage]]]] + try JSONSerialization.data(withJSONObject: root).write(to: url) + } else if nullTokenUsage { + let root: [String: Any] = ["continuation": ["view_materialization": + ["current_state": ["tokenUsage": NSNull()]]]] + try JSONSerialization.data(withJSONObject: root).write(to: url) + } else { + try Data("not json".utf8).write(to: url) + } + try FileManager.default.setAttributes([.modificationDate: modified], ofItemAtPath: url.path) + let head = directory.appendingPathComponent("HEAD.json") + try JSONSerialization.data(withJSONObject: ["latest_snapshot_id": headId]).write(to: head) + try FileManager.default.setAttributes([.modificationDate: modified], ofItemAtPath: head.path) + } + + private func usage(model: String, tokens: Int, first: String, last: String) -> [String: Any] { + ["modelId": model, "totalTokens": tokens, "promptTokens": tokens / 2, + "sourceRange": ["first": ["id": first], "last": ["id": last]]] + } + + func testReaderScansStoreAndSkipsStaleAndMalformedSnapshots() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + try writeSnapshot(home: home, session: "session-a", name: "snapshot-1.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 2_000, first: "a1", last: "b1"), + modified: now.addingTimeInterval(-75 * 60)) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-2.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 1_000, first: "a2", last: "b2"), + modified: now.addingTimeInterval(-10 * 60)) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-3.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 1_000, first: "a2", last: "b2"), + modified: now.addingTimeInterval(-9 * 60)) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-4.json", + usage: usage(model: "muse-wonder-1.0", tokens: 500, first: "a3", last: "b3"), + modified: now.addingTimeInterval(-8 * 60)) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-bad.json", + usage: nil, modified: now.addingTimeInterval(-5 * 60)) + try writeSnapshot(home: home, session: "session-b", name: "snapshot-1.json", + usage: usage(model: "muse-wonder-1.0", tokens: 7_777, first: "z1", last: "z2"), + modified: now.addingTimeInterval(-180 * 60)) + + let result = MuseCodeSessionReader(homeDirectory: home, now: { self.now }).read() + XCTAssertNil(result.issue) + let report = try XCTUnwrap(result.report) + XCTAssertEqual(report.window(minutes: 60)?.totalTokens, 1_500) + XCTAssertEqual(report.window(minutes: 90)?.totalTokens, 3_500) + XCTAssertEqual(report.window(minutes: 90)?.contributorTokens, 3_000) + XCTAssertEqual(report.window(minutes: 90)?.activeSessions, 1, + "session-b's newest file is three hours old, so it is not active") + XCTAssertEqual(report.segments.count, 3, "the duplicate snapshot adds no segment") + XCTAssertEqual(report.latestObservations.map(\.sessionId), ["session-a"]) + XCTAssertEqual(report.currentModelObservations.map(\.sessionId), ["session-a"], + "stale session-b is not exposed as a currently active model") + let observation = report.latestObservations.first + XCTAssertEqual(observation?.snapshotId, "4", + "HEAD names an unknown id here, so the newest parsed snapshot is the latest") + XCTAssertEqual(observation?.modelId, "muse-wonder-1.0") + XCTAssertEqual(observation?.totalTokens, 500) + XCTAssertEqual(observation?.segmentKey, "a3") + } + + func testCurrentModelUsesNullHeadWithoutBackfillingAndPreservesHistoricalUsage() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + try writeSnapshot(home: home, session: "session-current", name: "snapshot-1.json", + usage: usage(model: "muse-wonder-1.0", tokens: 4_250, + first: "old-first", last: "old-last"), + modified: now.addingTimeInterval(-3 * 60), headId: "1") + try writeSnapshot(home: home, session: "session-current", name: "snapshot-2.json", + usage: nil, modified: now.addingTimeInterval(-2 * 60), headId: "2", + nullTokenUsage: true) + + let nullHead = try XCTUnwrap(MuseCodeSessionReader(homeDirectory: home, now: { self.now }) + .read().report) + XCTAssertEqual(nullHead.currentModelObservations.count, 1) + XCTAssertNil(nullHead.currentModelObservations.first?.modelId, + "HEAD's null tokenUsage means the current model is unknown, not the older standard model") + XCTAssertEqual(nullHead.window(minutes: 90)?.totalTokens, 4_250, + "a missing current model does not erase older valid token usage") + + try writeSnapshot(home: home, session: "session-current", name: "snapshot-3.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 800, + first: "contrib-first", last: "contrib-last"), + modified: now.addingTimeInterval(-60), headId: "3") + let contributor = try XCTUnwrap(MuseCodeSessionReader(homeDirectory: home, now: { self.now }) + .read().report) + XCTAssertEqual(contributor.currentModelObservations.first?.modelId, + "muse-spark-1.3-contributor") + XCTAssertEqual(contributor.window(minutes: 90)?.totalTokens, 5_050) + + try writeSnapshot(home: home, session: "session-current", name: "snapshot-4.json", + usage: usage(model: "muse-wonder-2.0", tokens: 200, + first: "standard-first", last: "standard-last"), + modified: now, headId: "4") + let standard = try XCTUnwrap(MuseCodeSessionReader(homeDirectory: home, now: { self.now }) + .read().report) + XCTAssertEqual(standard.currentModelObservations.first?.modelId, "muse-wonder-2.0") + XCTAssertEqual(standard.window(minutes: 90)?.totalTokens, 5_250) + } + + func testReaderKeepsNewestSnapshotsAndHeadBeyondParsingCap() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + for index in 0...512 { + try writeSnapshot(home: home, session: "session-many", name: "snapshot-\(index).json", + usage: usage(model: "muse-model-\(index)", tokens: 1, + first: "first-\(index)", last: "last-\(index)"), + modified: now.addingTimeInterval(Double(index - 512)), + headId: "512") + } + + let report = try XCTUnwrap(MuseCodeSessionReader(homeDirectory: home, now: { self.now }) + .read().report) + XCTAssertEqual(report.currentModelObservations.first?.modelId, "muse-model-512") + XCTAssertEqual(report.window(minutes: 90)?.totalTokens, 512, + "the newest 512 snapshots are retained for bounded usage parsing") + XCTAssertTrue(report.segments.contains { $0.modelId == "muse-model-512" }, + "the HEAD snapshot is always included in the bounded scan") + } + + func testReaderLatestObservationFollowsHeadSnapshotId() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + try writeSnapshot(home: home, session: "session-c", name: "snapshot-7.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 300, first: "c1", last: "c2"), + modified: now.addingTimeInterval(-20 * 60), headId: "7") + try writeSnapshot(home: home, session: "session-c", name: "snapshot-9.json", + usage: usage(model: "muse-wonder-1.0", tokens: 900, first: "c3", last: "c4"), + modified: now.addingTimeInterval(-5 * 60), headId: "7") + + let result = MuseCodeSessionReader(homeDirectory: home, now: { self.now }).read() + let observation = result.report?.latestObservations.first + XCTAssertEqual(observation?.snapshotId, "7", + "HEAD.json's latest_snapshot_id wins over the newest file by mtime") + XCTAssertEqual(observation?.modelId, "muse-spark-1.3-contributor") + XCTAssertEqual(observation?.totalTokens, 300) + XCTAssertEqual(observation?.isContributor, true) + } + + func testReaderReportsMissingStore() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + let result = MuseCodeSessionReader(homeDirectory: home, now: { self.now }).read() + XCTAssertNil(result.report) + XCTAssertNotNil(result.issue) + } +} diff --git a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift new file mode 100644 index 00000000..334ceeb7 --- /dev/null +++ b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift @@ -0,0 +1,127 @@ +import XCTest +@testable import QuotaCore + +final class MuseCodeStandardSessionDetectorTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + private let contributorModel = "muse-spark-1.3-contributor" + private let standardModel = "muse-wonder-1.0" + + private func observation(_ sessionId: String, _ modelId: String?, + at offset: TimeInterval = 0) -> MuseCodeSessionModelObservation { + MuseCodeSessionModelObservation(sessionId: sessionId, modelId: modelId, + observedAt: now.addingTimeInterval(offset)) + } + + func testNewStandardSessionFiresOnceNamingSessionModelAndTime() { + var detector = MuseCodeStandardSessionDetector() + let events = detector.observe([observation("s1", standardModel, at: 60)]) + XCTAssertEqual(events.count, 1) + XCTAssertEqual(events.first?.sessionId, "s1") + XCTAssertEqual(events.first?.modelId, standardModel) + XCTAssertEqual(events.first?.observedAt, now.addingTimeInterval(60)) + XCTAssertTrue(events.first?.body.contains("s1") == true, + "the alert payload names the session") + XCTAssertTrue(events.first?.body.contains(standardModel) == true, + "the alert payload names the model") + } + + func testEventBodyUsesCentralTwelveHourTime() { + let observedAt = ISO8601DateFormatter().date(from: "2026-11-03T12:00:00Z")! + let event = MuseCodeStandardSessionEvent(sessionId: "s1", modelId: standardModel, + observedAt: observedAt) + XCTAssertTrue(event.body.contains("Observed at Nov 3, 2026 6:00 AM.")) + } + + func testSameStandardSessionRepolledDoesNotRefire() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1) + XCTAssertTrue(detector.observe([observation("s1", standardModel, at: 120)]).isEmpty) + XCTAssertTrue(detector.observe([observation("s1", standardModel, at: 240)]).isEmpty, + "staying on the same standard model across polls is not a new event") + } + + func testStandardToDifferentStandardModelDoesNotRefire() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1) + XCTAssertTrue(detector.observe([observation("s1", "muse-wonder-full-1.0", at: 60)]).isEmpty, + "moving between standard models never left the standard side") + } + + func testContributorToStandardSwitchFires() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertTrue(detector.observe([observation("s1", contributorModel)]).isEmpty) + let events = detector.observe([observation("s1", standardModel, at: 60)]) + XCTAssertEqual(events.map(\.sessionId), ["s1"]) + XCTAssertEqual(events.first?.modelId, standardModel) + } + + func testStandardContributorStandardRefires() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1) + XCTAssertTrue(detector.observe([observation("s1", contributorModel, at: 60)]).isEmpty, + "returning to a contributor model is not an event, it re-arms") + let events = detector.observe([observation("s1", standardModel, at: 120)]) + XCTAssertEqual(events.count, 1, "going standard again after recovery is a new event") + } + + func testContributorOnlySessionsNeverFire() { + var detector = MuseCodeStandardSessionDetector() + for offset in stride(from: 0, through: 600, by: 60) { + let events = detector.observe([ + observation("s1", contributorModel, at: TimeInterval(offset)), + observation("s2", "muse-wonder-full-1.0-contributor", at: TimeInterval(offset)), + ]) + XCTAssertTrue(events.isEmpty) + } + } + + func testNullModelSessionNeverFiresAndLeavesNoTrace() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertTrue(detector.observe([observation("s1", nil)]).isEmpty) + XCTAssertTrue(detector.observe([observation("s1", nil, at: 60)]).isEmpty, + "a session with no model on its current segment is not an event") + XCTAssertEqual(detector.lastKnownModels.count, 0, + "a model-less observation records nothing") + // The later standard sighting is the first model-bearing one, so it + // fires as first-observed rather than being masked by the null. + XCTAssertEqual(detector.observe([observation("s1", standardModel, at: 120)]).count, 1) + } + + func testSessionsAreTrackedIndependently() { + var detector = MuseCodeStandardSessionDetector() + let first = detector.observe([ + observation("s1", contributorModel), + observation("s2", standardModel), + ]) + XCTAssertEqual(first.map(\.sessionId), ["s2"]) + let second = detector.observe([ + observation("s1", standardModel, at: 60), + observation("s2", standardModel, at: 60), + ]) + XCTAssertEqual(second.map(\.sessionId), ["s1"], + "s2 was already standard; only s1's switch is new") + } + + func testStateSurvivesCodableRoundTripWithoutRefiring() throws { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1) + // The persistence pattern the app uses: JSON in UserDefaults, loaded + // back at launch. A relaunched detector must not re-report s1. + let data = try JSONEncoder().encode(detector) + var relaunched = try JSONDecoder().decode(MuseCodeStandardSessionDetector.self, from: data) + XCTAssertEqual(relaunched, detector) + XCTAssertTrue(relaunched.observe([observation("s1", standardModel, at: 60)]).isEmpty) + XCTAssertEqual(relaunched.observe([observation("s2", standardModel, at: 60)]).count, 1, + "a genuinely new standard session still fires after a relaunch") + } + + func testStandardSessionsPresenceListsCurrentStandardSessions() { + let present = MuseCodeStandardSessionDetector.standardSessions(in: [ + observation("s1", contributorModel), + observation("s2", standardModel), + observation("s3", nil), + ]) + XCTAssertEqual(present.map(\.sessionId), ["s2"]) + XCTAssertEqual(present.first?.modelId, standardModel) + } +} diff --git a/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift b/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift index 94aa478b..5763b4b0 100644 --- a/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift +++ b/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift @@ -201,10 +201,15 @@ final class ResetAlarmPlanChangeTests: XCTestCase { let later = t0 + 2 * self.hour let events = tracker.process(weekly(at: later, resetAt: t0 + 11 * self.day, remaining: 40), now: later) - XCTAssertEqual(events.count, 1, "the early period end still has to be reported") - XCTAssertFalse(events[0].isVendorReset, "a quota that fell is not a refill") - XCTAssertFalse(events[0].isPlanChange, "a quota that fell is not a plan change") - XCTAssertNotEqual(events[0].reason, .planChange, "no event may claim the quota rose") + XCTAssertTrue(events.isEmpty, "a future-end correction with falling quota is not a reset") + + // Adopt the corrected end, then still report its actual scheduled rollover. + let scheduled = t0 + 11 * self.day + 60 + let rollover = tracker.process(weekly(at: scheduled, resetAt: scheduled + 7 * self.day, + remaining: 35), now: scheduled) + XCTAssertEqual(rollover.map(\.windowId), ["7d"]) + XCTAssertFalse(rollover.first?.isVendorReset ?? true) + XCTAssertFalse(rollover.first?.isPlanChange ?? true) } // MARK: The words diff --git a/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift b/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift index 2bf0ad8a..1bf60635 100644 --- a/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift +++ b/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift @@ -452,6 +452,60 @@ final class ResetAlarmTrackerTests: XCTestCase { XCTAssertEqual(events.first?.isVendorReset, false) } + func testReusedWindowIdWithChangedCadenceStartsANewBaseline() { + var tracker = ResetAlarmTracker() + let intervalEnd = t0 + 3 * hour + _ = tracker.process( + [reading("general", period: 5 * hour, resetAt: intervalEnd, remaining: 80, + observedAt: t0, provider: "minimax", label: "5h")], + now: t0) + + let switchedAt = t0 + hour + let weeklyEnd = t0 + 6 * day + let switched = tracker.process( + [reading("general", period: 7 * day, resetAt: weeklyEnd, remaining: 75, + observedAt: switchedAt, provider: "minimax", label: "7d")], + now: switchedAt) + + XCTAssertTrue(switched.isEmpty, "A reused ID with a new cadence is a new baseline, not a reset.") + let key = ResetAlarmTracker.windowKey(scope: "local", providerId: "minimax", windowId: "general") + XCTAssertEqual(tracker.state.windows[key]?.periodSeconds, 7 * day) + XCTAssertEqual(tracker.state.windows[key]?.periodResetAt, weeklyEnd) + XCTAssertEqual(tracker.state.windows[key]?.minimumRemaining, 75) + XCTAssertEqual(tracker.state.windows[key]?.lastRemaining, 75) + + let scheduledAt = weeklyEnd + hour + let scheduled = tracker.process( + [reading("general", period: 7 * day, resetAt: weeklyEnd + 7 * day, remaining: 70, + observedAt: scheduledAt, provider: "minimax", label: "7d")], + now: scheduledAt) + XCTAssertEqual(scheduled.map(\.reason), [.newPeriod], "A later weekly rollover remains a scheduled reset even if usage fell.") + } + + func testPreEndResetTimeCorrectionWithoutQuotaRiseIsNotAnAlarm() { + for remaining in [75.0, 65.0] { + var tracker = ResetAlarmTracker() + let initialEnd = t0 + 7 * day + _ = tracker.process( + [reading("weekly", period: 7 * day, resetAt: initialEnd, remaining: 75, + observedAt: t0, provider: "minimax", label: "7d")], + now: t0) + + let correctedAt = t0 + day + let correctedEnd = initialEnd + 4 * day + let events = tracker.process( + [reading("weekly", period: 7 * day, resetAt: correctedEnd, remaining: remaining, + observedAt: correctedAt, provider: "minimax", label: "7d")], + now: correctedAt) + + XCTAssertTrue(events.isEmpty, "A forward time correction without quota restoration must not announce a reset.") + let key = ResetAlarmTracker.windowKey(scope: "local", providerId: "minimax", windowId: "weekly") + XCTAssertEqual(tracker.state.windows[key]?.periodResetAt, correctedEnd) + XCTAssertEqual(tracker.state.windows[key]?.minimumRemaining, min(75, remaining)) + XCTAssertEqual(tracker.state.windows[key]?.lastRemaining, remaining) + } + } + /// A rise is only new evidence when the period end holds still. When the /// end moves too, the earlier rule already calls it an early reset — a /// provider resetting a limit early moves its reset time and the quota diff --git a/Tests/QuotaCoreTests/SMSAlertCoordinatorTests.swift b/Tests/QuotaCoreTests/SMSAlertCoordinatorTests.swift new file mode 100644 index 00000000..78535cda --- /dev/null +++ b/Tests/QuotaCoreTests/SMSAlertCoordinatorTests.swift @@ -0,0 +1,118 @@ +import XCTest +@testable import QuotaCore + +final class SMSAlertCoordinatorTests: XCTestCase { + private var credentials: TwilioSMSCredentials { + .init(configuration: .init(accountSID: "AC" + String(repeating: "a", count: 32), + apiKeySID: "SK" + String(repeating: "b", count: 32), + messagingServiceSID: "MG" + String(repeating: "c", count: 32), recipient: "+15551234567"), + apiKeySecret: "fixture-secret") + } + private let preferences = SMSAlertPreferences(enabledKinds: ["museCodeBurn"]) + + func testReservationIsSavedBeforeSendAndSurvivesRelaunch() async { + let disk = SMSHistoryFixture() + let client = TwilioSMSClient(transport: { request in + XCTAssertNotNil(disk.read()) + disk.recordRequest() + return (Data(#"{"sid":"SMdddddddddddddddddddddddddddddddd","status":"queued"}"#.utf8), + HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)!) + }) + let coordinator = SMSAlertCoordinator(persistence: disk.persistence, client: client) + let first = await coordinator.send(eventID: "stable-event", kind: "museCodeBurn", title: "Burn", body: "Fixture", + preferences: preferences, credentials: credentials) + XCTAssertEqual(first, .accepted) + let relaunched = SMSAlertCoordinator(persistence: disk.persistence, client: client) + let repeatSend = await relaunched.send(eventID: "stable-event", kind: "museCodeBurn", title: "Burn", body: "Fixture", + preferences: preferences, credentials: credentials) + XCTAssertEqual(repeatSend, .duplicate) + XCTAssertEqual(disk.requestCount, 1) + XCTAssertFalse(String(data: disk.read()!, encoding: .utf8)!.contains("stable-event")) + } + + func testUncertainOutcomeRemainsReservedAndConcurrentDuplicatesSendOnlyOnce() async { + let disk = SMSHistoryFixture() + let client = TwilioSMSClient(transport: { _ in + disk.recordRequest() + await Task.yield() + throw URLError(.timedOut) + }) + let coordinator = SMSAlertCoordinator(persistence: disk.persistence, client: client) + async let first = coordinator.send(eventID: "same", kind: "museCodeBurn", title: "Burn", body: "Fixture", + preferences: preferences, credentials: credentials) + async let second = coordinator.send(eventID: "same", kind: "museCodeBurn", title: "Burn", body: "Fixture", + preferences: preferences, credentials: credentials) + let results = await [first, second] + XCTAssertTrue(results.contains(.duplicate)) + XCTAssertTrue(results.contains(.failed(.uncertain))) + XCTAssertEqual(disk.requestCount, 1) + let relaunched = SMSAlertCoordinator(persistence: disk.persistence, client: client) + let repeatSend = await relaunched.send(eventID: "same", kind: "museCodeBurn", title: "Burn", body: "Fixture", + preferences: preferences, credentials: credentials) + XCTAssertEqual(repeatSend, .duplicate) + } + + func testDisabledUnconfiguredAndCorruptPersistenceNeverSend() async { + let disk = SMSHistoryFixture() + let client = TwilioSMSClient(transport: { _ in + XCTFail("No network call should be attempted") + throw URLError(.badURL) + }) + let coordinator = SMSAlertCoordinator(persistence: disk.persistence, client: client) + let disabled = await coordinator.send(eventID: "event", kind: "anomaly", title: "Fixture", body: "Fixture", + preferences: .init(enabledKinds: ["anomaly"]), credentials: credentials) + XCTAssertEqual(disabled, .disabled) + let unconfigured = await coordinator.send(eventID: "event", kind: "museCodeBurn", title: "Fixture", body: "Fixture", + preferences: preferences, credentials: nil) + XCTAssertEqual(unconfigured, .failed(.invalidConfiguration)) + let corrupt = SMSAlertCoordinator(persistence: .init(load: { Data("broken".utf8) }, save: { _ in }), client: client) + let failed = await corrupt.send(eventID: "event", kind: "museCodeBurn", title: "Fixture", body: "Fixture", + preferences: preferences, credentials: credentials) + XCTAssertEqual(failed, .failed(.persistence)) + let writeFailure = SMSAlertCoordinator(persistence: .init(load: { nil }, save: { _ in throw URLError(.cannotWriteToFile) }), client: client) + let failedWrite = await writeFailure.send(eventID: "event", kind: "museCodeBurn", title: "Fixture", body: "Fixture", + preferences: preferences, credentials: credentials) + XCTAssertEqual(failedWrite, .failed(.persistence)) + } + + func testFullHistoryFailsClosedRatherThanEvictingDedupeIDs() async { + let disk = SMSHistoryFixture() + let client = TwilioSMSClient(transport: { request in + disk.recordRequest() + return (Data(#"{"sid":"SMdddddddddddddddddddddddddddddddd","status":"queued"}"#.utf8), + HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)!) + }) + let coordinator = SMSAlertCoordinator(persistence: disk.persistence, client: client, maximumReservations: 1) + _ = await coordinator.send(eventID: "first", kind: "museCodeBurn", title: "Burn", body: "Fixture", + preferences: preferences, credentials: credentials) + let full = await coordinator.send(eventID: "second", kind: "museCodeBurn", title: "Burn", body: "Fixture", + preferences: preferences, credentials: credentials) + XCTAssertEqual(full, .failed(.capacity)) + XCTAssertEqual(disk.requestCount, 1) + } +} + +private final class SMSHistoryFixture: @unchecked Sendable { + private let lock = NSLock() + private var data: Data? + private var requests = 0 + var persistence: SMSAlertPersistence { + .init(load: { self.read() }, save: { self.write($0) }) + } + func read() -> Data? { + lock.lock(); defer { lock.unlock() } + return data + } + func write(_ value: Data) { + lock.lock(); defer { lock.unlock() } + data = value + } + func recordRequest() { + lock.lock(); defer { lock.unlock() } + requests += 1 + } + var requestCount: Int { + lock.lock(); defer { lock.unlock() } + return requests + } +} diff --git a/Tests/QuotaCoreTests/TwilioSMSClientTests.swift b/Tests/QuotaCoreTests/TwilioSMSClientTests.swift new file mode 100644 index 00000000..0b5a484a --- /dev/null +++ b/Tests/QuotaCoreTests/TwilioSMSClientTests.swift @@ -0,0 +1,115 @@ +import XCTest +@testable import QuotaCore + +final class TwilioSMSClientTests: XCTestCase { + private var credentials: TwilioSMSCredentials { + .init(configuration: .init(accountSID: "AC" + String(repeating: "a", count: 32), + apiKeySID: "SK" + String(repeating: "b", count: 32), + messagingServiceSID: "MG" + String(repeating: "c", count: 32), recipient: "+15551234567"), + apiKeySecret: "fixture-secret") + } + + func testSMSIsOffByDefaultAndUnknownKindsCannotBeEnabled() throws { + var preferences = SMSAlertPreferences() + for kind in SMSAlertPreferences.eligibleKinds { XCTAssertFalse(preferences[kind]) } + preferences["anomaly"] = true + XCTAssertFalse(preferences["anomaly"]) + preferences["museCodeBurn"] = true + let restored = try JSONDecoder().decode(SMSAlertPreferences.self, from: JSONEncoder().encode(preferences)) + XCTAssertTrue(restored["museCodeBurn"]) + XCTAssertFalse(restored["quotaExhaustion"]) + } + + func testFixedEndpointAPIKeyAuthenticationAndFormEncoding() throws { + let request = try TwilioSMSClient.request(title: "Session & burn", body: "+ quota = 1", credentials: credentials) + XCTAssertEqual(request.url?.host, "api.twilio.com") + XCTAssertEqual(request.url?.scheme, "https") + XCTAssertEqual(request.url?.path, "/2010-04-01/Accounts/\(credentials.configuration.accountSID)/Messages.json") + XCTAssertEqual(request.httpMethod, "POST") + XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), + "Basic " + Data((credentials.configuration.apiKeySID + ":fixture-secret").utf8).base64EncodedString()) + let form = String(data: request.httpBody!, encoding: .utf8)! + XCTAssertTrue(form.contains("To=%2B15551234567")) + XCTAssertTrue(form.contains("MessagingServiceSid=MG")) + XCTAssertTrue(form.contains("Session%20%26%20burn%0A%2B%20quota%20%3D%201")) + XCTAssertFalse(form.contains("fixture-secret")) + } + + func testMessageIsBoundedAndInvalidConfigurationNeverCreatesARequest() throws { + let request = try TwilioSMSClient.request(title: String(repeating: "x", count: 500), body: "body", credentials: credentials) + let form = String(data: request.httpBody!, encoding: .utf8)! + let body = form.components(separatedBy: "&Body=")[1].removingPercentEncoding! + XCTAssertEqual(body.count, 240) + var invalid = credentials + invalid.configuration.accountSID = "../another-account" + XCTAssertThrowsError(try TwilioSMSClient.request(title: "title", body: "body", credentials: invalid)) + invalid = credentials + invalid.configuration.recipient = "5551234567" + XCTAssertThrowsError(try invalid.validate()) + invalid = credentials + invalid.apiKeySecret = "secret\nheader" + XCTAssertThrowsError(try invalid.validate()) + } + + func testQueuedReceiptIsAcceptedWithoutClaimingDelivery() async throws { + let client = TwilioSMSClient(transport: { request in + let data = Data(#"{"sid":"SMdddddddddddddddddddddddddddddddd","status":"queued"}"#.utf8) + return (data, HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)!) + }) + try await client.send(title: "title", body: "body", credentials: credentials) + } + + func testRedirectDelegateRefusesCredentialForwardingWithoutStartingATask() { + let session = URLSession(configuration: .ephemeral) + defer { session.invalidateAndCancel() } + let url = URL(string: "https://api.twilio.com/example")! + let task = session.dataTask(with: url) + let response = HTTPURLResponse(url: url, statusCode: 302, httpVersion: nil, + headerFields: ["Location": "https://example.invalid/"])! + var completionCalled = false + NoSMSRedirects().urlSession(session, task: task, willPerformHTTPRedirection: response, + newRequest: URLRequest(url: URL(string: "https://example.invalid/")!)) { request in + XCTAssertNil(request) + completionCalled = true + } + XCTAssertTrue(completionCalled) + } + + func testMalformedAndFailedReceiptsCannotClaimAcceptance() async { + for responseBody in ["not-json", #"{"sid":"SMdddddddddddddddddddddddddddddddd","status":"failed"}"#] { + let client = TwilioSMSClient(transport: { request in + (Data(responseBody.utf8), HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)!) + }) + do { + try await client.send(title: "title", body: "body", credentials: credentials) + XCTFail("Malformed or failed receipt must not be accepted") + } catch { + XCTAssertNotNil(error as? TwilioSMSFailure) + XCTAssertFalse(error.localizedDescription.contains(responseBody)) + } + } + } + + func testErrorsAreSanitizedAndNeverRetried() async { + for (status, expected) in [(401, TwilioSMSFailure.authentication), (429, .rateLimited), + (503, .serviceUnavailable), (302, .rejected), (400, .rejected)] { + let counter = SMSRequestCounter() + let client = TwilioSMSClient(transport: { request in + await counter.increment() + return (Data("private phone and token".utf8), + HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!) + }) + do { + try await client.send(title: "title", body: "body", credentials: credentials) + XCTFail("Expected sanitized failure") + } catch { XCTAssertEqual(error as? TwilioSMSFailure, expected) } + let count = await counter.count + XCTAssertEqual(count, 1) + } + } +} + +private actor SMSRequestCounter { + var count = 0 + func increment() { count += 1 } +} From f14d9fa7787a835a81ec8994dc29d68df2a7c9e1 Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:40:25 +0000 Subject: [PATCH 03/12] Add supplied Kimi and Z.ai marks and complete CodeCaps release planning --- Sources/CodeCaps/PlatformLogo.swift | 8 ++++- .../Resources/ProviderMarks/README.md | 3 ++ .../Resources/ProviderMarks/kimi-color.png | Bin 0 -> 6090 bytes .../Resources/ProviderMarks/kimi-color.svg | 1 + .../Resources/ProviderMarks/kimi-dark.png | Bin 0 -> 6968 bytes .../Resources/ProviderMarks/kimi-light.png | Bin 0 -> 7672 bytes .../CodeCaps/Resources/ProviderMarks/kimi.svg | 1 + .../Resources/ProviderMarks/zai-color.png | Bin 0 -> 7921 bytes .../Resources/ProviderMarks/zai-dark.png | Bin 0 -> 7466 bytes .../Resources/ProviderMarks/zai-light.png | Bin 0 -> 7921 bytes .../CodeCaps/Resources/ProviderMarks/zai.svg | 1 + Tests/CodeCapsTests/CompanionModelTests.swift | 12 ++++++++ .../PlatformLogoResourceTests.swift | 27 ++++++++++++++-- .../ProviderMarkResolutionTests.swift | 2 +- .../ProviderMarkTripletTests.swift | 23 +++++++++++++- .../UsageAlertPreferencesTests.swift | 5 ++- docs/AUTO-UPDATE.md | 4 +-- ...6-11-03-cc205-monitoring-alert-controls.md | 29 ++++++++++++++++++ .../App/Models/CompanionQuotaModel.swift | 2 ++ .../App/Views/CompanionContentView.swift | 2 +- 20 files changed, 110 insertions(+), 10 deletions(-) create mode 100644 Sources/CodeCaps/Resources/ProviderMarks/kimi-color.png create mode 100644 Sources/CodeCaps/Resources/ProviderMarks/kimi-color.svg create mode 100644 Sources/CodeCaps/Resources/ProviderMarks/kimi-dark.png create mode 100644 Sources/CodeCaps/Resources/ProviderMarks/kimi-light.png create mode 100644 Sources/CodeCaps/Resources/ProviderMarks/kimi.svg create mode 100644 Sources/CodeCaps/Resources/ProviderMarks/zai-color.png create mode 100644 Sources/CodeCaps/Resources/ProviderMarks/zai-dark.png create mode 100644 Sources/CodeCaps/Resources/ProviderMarks/zai-light.png create mode 100644 Sources/CodeCaps/Resources/ProviderMarks/zai.svg create mode 100644 docs/rollouts/2026-11-03-cc205-monitoring-alert-controls.md diff --git a/Sources/CodeCaps/PlatformLogo.swift b/Sources/CodeCaps/PlatformLogo.swift index 2cab4813..d8dabeb9 100644 --- a/Sources/CodeCaps/PlatformLogo.swift +++ b/Sources/CodeCaps/PlatformLogo.swift @@ -286,6 +286,12 @@ private static let resourceNames: [String: String] = [ "grok-cli": "grok", "grok-bot": "grok-bot", "minimax": "minimax", + "kimi": "kimi", + // Z.ai is the brand; zcode remains the quota provider's stable key. + "zcode": "zai", + "z.ai": "zai", + "z-ai": "zai", + "zai": "zai", "muse": "muse", // Muse Assist ships byte-identical artwork to Muse; one base serves both. "muse-assist": "muse", @@ -529,7 +535,7 @@ private static func variantFile(base: String, style: MarkStyle, isDark: Bool) -> private static let monochromeKeys: Set = [ "grok-bot", "openai", "codex", "cursor", "xai", "x-ai", "grok", "grok-cli", - "github-copilot", "copilot", + "github-copilot", "copilot", "zcode", "z.ai", "z-ai", "zai", ] /// Presentation mode for a user-supplied custom mark. Defaults to `.color` diff --git a/Sources/CodeCaps/Resources/ProviderMarks/README.md b/Sources/CodeCaps/Resources/ProviderMarks/README.md index 26a6d211..cd270fc3 100644 --- a/Sources/CodeCaps/Resources/ProviderMarks/README.md +++ b/Sources/CodeCaps/Resources/ProviderMarks/README.md @@ -40,3 +40,6 @@ Several families were deliberately left alone, because there is no same-art high `scripts/regenerate-provider-marks.py` rebuilds the marks. It reports by default and writes only with `--write`. Before it writes anything it checks that the rebuilt mark is the same artwork (the silhouette has to match at draw size, and a colour mark's palette has to match too), that the source artwork can fill the exact box the artwork it replaces occupied, that the rebuild does not soften the silhouette, that it lands inside the absolute edge limit, and that it actually sharpens something. A source that fails any of those is reported and left alone, and one unreadable file is reported without stopping the rest of the run. `ProviderMarkDetailTests` holds the same rule as a test, so a blurry upscale cannot come back unnoticed. It measures the same thing, against the committed assets rather than a copy the build happened to make. A mark here may not have a silhouette edge wider than one device pixel at 28pt on a 2x display, except the two families named above, whose soft edge is the artwork's own. The companion's marks are measured in the pixels of the screen that serves them, because a 1x file is drawn on a 1x screen and a 3x file on a 3x one, so the file's own pixels are already the device pixels; their limit is 1.65 device pixels, which is about what a 24px raster can do at all. The two limits live in `scripts/regenerate-provider-marks.py`, which refuses to write a mark that would break them, and the test reads them from there so the two cannot drift apart. + + +Kimi ships the supplied `kimi-color.svg` as its Standard colour source and `kimi.svg` as its Light/Dark source.  Z.ai ships the supplied `zai.svg`; the stable `zcode` quota key and common Z.ai aliases resolve to this monochrome mark in every style.  Their PNG variants are transparent 256px AppKit rasterizations of those exact vectors.  Companion widgets use a separate Xcode asset catalog, not this SwiftPM directory.  Their `provider-kimi` and `provider-zai` vectors are byte-identical copies of the supplied Kimi colour and Z.ai mono marks. diff --git a/Sources/CodeCaps/Resources/ProviderMarks/kimi-color.png b/Sources/CodeCaps/Resources/ProviderMarks/kimi-color.png new file mode 100644 index 0000000000000000000000000000000000000000..daa7c7f47779a2a2d036798c4c7de27bbbd55be9 GIT binary patch literal 6090 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 US%Po={im+0WuRHAVf*NR0IdEU5dZ)H literal 0 HcmV?d00001 diff --git a/Sources/CodeCaps/Resources/ProviderMarks/kimi-color.svg b/Sources/CodeCaps/Resources/ProviderMarks/kimi-color.svg new file mode 100644 index 00000000..01cd62f2 --- /dev/null +++ b/Sources/CodeCaps/Resources/ProviderMarks/kimi-color.svg @@ -0,0 +1 @@ +Kimi \ No newline at end of file diff --git a/Sources/CodeCaps/Resources/ProviderMarks/kimi-dark.png b/Sources/CodeCaps/Resources/ProviderMarks/kimi-dark.png new file mode 100644 index 0000000000000000000000000000000000000000..5c87fffb40f8f740d54ce821b4b1ff8e19763319 GIT binary patch literal 6968 zcmd^Ei9b}~*S|BSm=H6TtXalVB5RhAvCfcP$`(_}l4L7u%vi$MB72BbvJ_gCZER)V zk}YCPp(2bWWSaY4zxVUL?;r7gKKFj^bD#5k&wb80&pFRI&m~)1;y4cp9RdJ=(-d!H z3ji>v2?N*;LJya~a*zGDAX}UPP(2{>6ME6S>R{?&VFAcNZ8iXw;0+-5hd{RwbOQjq z1pYrgFrb9x|JwURBT3C5XkfLek^Z?**zY1_mZ*JxXXee2dzP>6cHKuRAzJfc`jbXD zgnmYxeMa0VxTMhmchn?8s)M7dRDbLeAKO7B+`t_P(=u#nSC@w&+L{gHHgi@67$-lo zD;90LQo?Ultu)z#A(lnqHI*ydk=r3l;AqpErqXg%c`;2>d&>FQhC||Gb=7pf34HkxL*LJ*KtnkT-7)fzB8F@1}xLVu2E8S38 z?SXf8-oe>Rdp>x6y97?*KR5eciuqL|hS*MJqoU&wU#6yTfr#RieBJ!}==)2LWR;rg z>b585+7tA|I&;ui5vMQb5ok2kOE+|`?M}j_1+}ubaSMNstV*E@%`WG+HP(PVW|V9| z&SqEzg^vbkZVww8_RKo8WDac1%dC2NdkZFrsT!5<+Q7@nxD&=LhhZHQAsln6_U%K_ zWEQ9V-gIig^XJbuuK89VtdrBm$fN`CL{K#mJY$}(y5|_>+Oc}x*VnhkKBy95otl!9 zyiX?zNEW6Z4*|dxAE)YzJSImHaKpK5NnIsJt@vdvj@}p_I5$Bteho#jnIVfdTlAD{GKPbz=9w#|{WXBW2W|#WHNPK2c zPZr+mB%Gg3y!xtqp6Mt;mo)aj=)1O;UfR;Qh!iB6IqVIzSq96mwt-4EdqDxKhgU1LTM?&nw*qF#(qQG7KZES zkAn%Lm5=^=abd3@ZvTQc_FW{-mM(!dZz_+$&S4(SOAZOZ+`<8n`eODuE=7QD_WYXK zxKqU~$l3JKc@}kGgUIfz(6R6>;GpE=ElKXf(Kn2UDzw?Mqx6DnTB|Vsu*=3w{M^k2 zjOs!o8@`T9^z>$(;GRNCLv?la#dljb_3BI8BWu+5+V+-XDc`T}(q!j_Qr_3J2AU@2 zNA8x*%*S1L=AC1znZP+XO0B((Rf@#=(4pJ311iHxZe{;0Jm z!eF8Na9M&u>*lk&33KyDnb-(bS<_8@-d?@M{`1zHZ$Y0<0iIsWY z3W0)8q*T?(C=Euy40c(*TCu>z5H2vQq|fIP1N`2_@E6u~wE0JEszkX8+B6lbxyN05 zJ$mo6<+&&c)i-y2ilKV#%$m2WX=)znE-p3F|5%HXK;l&I>gYY4#c7ysu=@QF2 z4F(Lohf%Fb#S>3I@#vf!^gUN`!wkqS_i~hnu>OY_r_W1J)YWB&Wy(hT|5R0;HF<=n zmE!uBWJ=<3)qB#VrJTI`de@JeB3RG64%xcPqt4E|gUI`B;nlK3(B*lT4q_h9-~&y2 z_}XI$19ld=*cHqBclbjb8$B^hOi$F2^(r)0qCnU22?~6XNHkM9v0}!vm!AmYLr^>4 z9FZ->Z`mZ#9YhiMeG#Ktz8JM8{uPE!eOsl$Nn7|a_g5O{y*t1lgj&UmPb+6pd%PXQ zls!CyjNJ#WorZvD`01}p;ywu6awhbJQ|iaR%Sn?A)FT?rHd;P+v;D{leZrW$KOrl@ zZ2S7%&WioVd20AEzEI%~qMSxop@3Wro*^42MEnv^#hR`@NBWInnnovsylD(HF*VX! zmn7t$)Od()Wx{Ap%P0Rk;_^%TO_#5O)z@s`*TZwQzT6-$f_Hf`@UmWXXLxLrQ^x#C z86sW!H*i}bY6HJ)1B-J~HoB~Ll+GIQru6a?TbFV~y5#hb`Np~8_cgOR(>&i<>7WQ5 zlYq%G;i`NH;Y&6Xp#~;C4 zg90BWg4@v_SFcW(0j}!FUrV?_Zp)o~kWfe%5A+yI*&!zGDE9ST(HA)m``-8vLw7Sf zwaxyz(uBc^i5iI*?o@$E1HITtl_O-3nCR_ROiMx~qd@&c@Secc*WMg(GeDVe=k;-# zU+EN4Pk_uZ5GVa`zT#w71@0eS3400h67z7_|xin7Xq)FB(;L_^-PW7AcMy@~$U$5EVAQj%;R@`eK+( zDDchkzv({@K{JxWBE3;<-g8|<(T$6SNe%L25AclfY=x2W6t-h9cf@Hj3xFb61mbC8ef@C`{ih@`I)+8?k8f6dtO)Lc`@-?P2&f{=`N!TOB41N0rs z`ue!s4Jv4WVHQC==7{A<*2tDekpNw>Jp(*%@V63o=>zhKDE+Q6Bjm&J$G%@t)^PvM zDC8hCpSHFd`4^IfVkV3$+~C)_xM%omKxcxL8+<9U+u!|CF@oC?BO#AvXiG99gpNN` zS%EC~?h5$AvxDLy#Z(YY_*5Q&Vfta1lc_@1S|N~SreBD~?d0MZbv$hghuiVAzmM>Y zZ5id#m-|r7%VK1r%!)=3uYqlym?TqFa~)KukjM_%7Y7#6L4o64cXe~05<%xg zFiQBNd%Gx1nv^n$Ve+9U@AVgw1smSZuM`XXm7#%d&Ihk{io(7gDwKf0XqtvbSDYMk zx1(9tYRi-%xT4`*Z_6caQGfMqZwDn{l9t|_)1fE(xP;Hg7g}U*b{!m(cfdOsut;F4 zE2(uk^){*Zx8}NDR+CSdc_t|y@c#4xawHC#M%~AFIp#L`pD>!(qn(7=FawUq;20-x zv{@x%4e$F=T;EI>M5__<^#)9d1lDXB1$sWZ0TLg7m-KxlP1h@Yi<#V)QT)K4L}K=j zE^wE(&-2py#lq{o8Q`#dVRwQyTnO&qAx56nK^>{wnSFS83eU(1;jrpI4s*CJ5cf(B z$8^k_ZYiCVw`lV17_4d#>-|)5`#q)vK_Kh4IVzyRzd7a}z6;OsjJuw{9hlRoAuWJ? z`G~wj?P;3ESLT*{UeG04Kb~P#?|-s*-xgBtvokZz2Wy(tX<|h~SyeO>hTGFAFslmq zKEAJU1SG`$jGb`{!beA&IPl;=>P~Smf1HT6bV(4vNy9NPPz*nCzMMuZLe#$Ln57<0 z&%A5~aH_fEaGewrn%mQ8+CcJ}Jm_P>XiwlOUeXabK+S^u)0~k=JZEQ@skL4s`l|d$ z0fu=YA|e9fPL~uvFt1I)0<5=)5o8_#(3OP)66 zp@^dq2kKgQ?`p&A4_UMB4Gaw2+DTq=yngy+T7Ts9_a{)ATQl;TIMYex&D4hff^oDQ zrPm0H?i%uejX$~+>0Co nh){jO}pjU@pvg(4**hJr=y`m7k?(N%VYEXJo|GqNh zAZ3I@$|!$HUQKpO>;Owwqvg(oAZ{Ke43#{&Cr$%JJo{D`x+wP>%Dksl11JM|vm(20 z*QS%q`1fNHC1R(czP@kdc1R|0p7R!~_@CowV)^r2-|4fW|6bl&y;EmV-_XD{SFV+} zo69};Ed7IDqHXSxCh;oqM%fa?nkkRPe1Pl5%pPn0d3y8c!NdMl(Hg`2l1g4fgmG@o zUnc`a4G;ed8DZBXu|`(+T>5%WIvMeqrIu|3V`nJ%(Zw{dDa)uf1s8CfcaW`|mFgJ# zm^^6AE29b4UcL@hA&hBaA1WqP(iLqumsZME))hErDVP+*dRC zQr)E`+j}jyIFLDYUKh&X;*ehfsacm2H#BWDo1Z+HXL3aLWE(;@)r?zxxMZ^l_Xv7I zMJ#;L(77%?B~igjDDa9}?q3L;bH$jXgi7n#+gkkPvCdhwGNPPCFq8H4!m_q8%T7)u zVNA#yzSmgzj(JHBAg5c9Z5x8<*I(4+oujyixLfW9vq>b$n!+R26Y1Y15LE(8n3AK| z$imm7CHlorHIx!&T8vt|xL{kr`bbXxXq?fS=Kz;EfqBEja{d?}G{46&r)EtA52ef> zYQ5rea$08gR6p@|7O+11vEp;ORPE^zxA$gB4%%pMNPbEPyx1#p&Qg~oqE?z8B5c?}YH_Bxc<0V4Gk6ksy>OwW- z_NBiq(H(x%ulnyKws9aIC{co#yYNLUBn($qm~L$O12pz@zk3G}Xls7$x*>upCg2J8 zT0U&$AVV8aWe*C)3r%Rw64Y>nSbaS3r(h_N2&Yj>ZAPYT>R55z$;T)zkJRCE8h7hg zjMw*^vC4}w=eB@lbts`{ns)fLJ=9Q2&GcA6%*8H*4Cp=jabViek1Dlbp;c2AGHS=w z;+nbnl4Ug^wC3$qbc6!iw+j>6G2LO#la&`ZwYN_b~Ehbz^!RYu9OacK@xPk>`q==iGf>s&{IHTRhBJfWBIkvttoDjommB z4tJw2eeG`FnrTZa90_2LD6q*k=-U<*e2X`VHJ*wFG(gT*8B%5w^=g&CKTDt-x2oV)1%b{`T&j)1Qw$N`lS-STCZ9 z=`}BCUK8EvRPF)JWlKK2a@YRpXM){I{f)PNeEIX|kL0x2r6+T0i1L&dJh0zwHk*HX zs@k2t3=b<;R#bHBJS9}~^UjUv)3h@Yns-ZxDc+8Ad3*_uNk$QZAM zAE83GwBwyL{kBu^%@&b^?ra*_yEwsJj-J#F(deR2PoKiHCv1WZ7$Jz!B;}Z^&l*L$ zsb)#f(2pE`6f~bL8e9}<-Q7PmyW=WYKtBPyZ8nlfl&4WPMvQkE@dD>1Pefj$)7Vd1ImV%xtajjgCy z_2Q3eu@Y_97j%ui_twMZVAxnp+r-ext!$0U_f|I%Z;d!0FDjP`hAZyDkW@>}zRUFq znF&^FQ;jnU+hWoHvpwzLtlYN3#YZvAnVznTE%WsdhO zogwMRx_0|~8*^4n3l{TVX`fb9%BXlX6R0&)omwB6-@W!OSNlXz1nvnMo3>4RXa5ba zk*(sa)Sv3C-Z{nfp?+Db*^esbPMvFB>skam;)DKYmt?TCs>}hv| z2UVn$2DuA8N2;&y>O+a`-Qcy;hvE?zIgn8Xegsc=!(-8HS_ zxD(!W>v;IG8DKoig8p3mpygtr@I<1NzcXA_?pHbqO)}gG^S4l>`rd1)%P%;Rn%C*O zg-nEYX>97ePkAB{)fBCoxO&1|aYyJW&FMY~-SWx&^<#bbCSoC-O}#8s2F#fz5s|HJJ=7EpY$kA+|(XZ5> z<-6@1s4TUEKJ`v>+UdJ?pfu@rUCqW9WvL$}8vfi((E*4Jt3}vxk~Fjh%SRjPeUilb zQJo%0E6K8nnfE3ve}s}B?&5qiH9W}^`M?uTn4yHKXIg=*!-Ui}#WDnUl<+}&mUsla zAX=omAg_~qM_d0uaXTR!2%IRFI7c3@o$Wc%tsyz)DA7?cE|3kZe|ZV}+{>^yVi@E5 zlaCSO&kic;p1g04Y&mdi*To#5Z)YGZuQs1zFLrD+a8r?hibbS{mS7@aNjBSyBegR&Ku=TjdQ*vbJ!+aYL9uCD=E~&a>>?}}yC6Jgt=4mNjA3MZQ9b`(~ zX#<1o?sG!SWG+tL$RlZKw9L2lzIUoUI&0N31f9IwwN^rTPi5)wAu%>_=HUTO^UF@T zp;7&xR}5Xk$ofceMTPv0@N~ABQk=ggnV>L$Dzv<{xY*c}f6fXi&eIooIT;{ReFsn? zR+0iAw!hWx-BXw{ehnRFb(|m6FG7L0@3pv>y?OsURK6+3xje_!?&vGuY~V6{WFZPA zj@k?;UGoS(a3wq%h$IEcbCdLz{k+mjRD>NO4|%> z=>>+MtUjN$Hzv*XguXlYLKbjp~Bd~m$xw5j- zPM#CN1@t`)sH5WPuQ6cY5)AeyIvaneK*_Dx-$YfcKiXSu7N^oraCmWq5~0I38qPMr zL#jZT64*`6GA6I)Sk9kC7-9dvUg9UQaVJsb0|StB&DUhl@6sDT1uoFB$SeFBqUV28wLjE z8^8D7_x=(0dFDK`&&=Lyud~;0{Z^bPxP~G=E;TLy0QkyEa@qg@!VEzG6dUtp{I=Bk z-<_Mbq6|kg^T-2Bg0Kj?R|N9FF$h-Id#{d45 zgNe8S0Iidp33+6mEOD|GGlFYr~7W9+w zV%~%RM24u%hH$Q?MB6jBQS|Y1w>wcc({3sPA^?O1xw~0EMf^$vxt+2)zw;eW5A!00+JowC3^d+gLe5WMs!F$o2Vc zF>6#3VLhN=9ZvR7gYa$(Qkk}4zfx=Nk1!WoM$NO#{3$O7CntKb0V91PKmiuM%fJxQ z)nofNWLg7F8Dtl@9peqz(!94KEkzQdbh$;&tdcV5 z>?c^^XWT1#Z|T45LEkz#Wn$l{O?1W;s?wN1ov>ASqhEC+49q?5 zGXX-^^N~QFuiZC^3Mh26pTqg-Ch4^UX7~TB4Cc3wh498lSBFzBl>nf;1c-#R6fQ^> zxqXhkd8l?@0Z7!|A_9Y*iHTx8kvg}l1$AR`kYEXtD+mY&VoM+;?RTsU*Qcs6g`fAXfOm!T@RQZbb5$@gTrOsLy5MS@_g}vb2Mkq z=HCRtfU}a2Lk9R`(7F-u>-uF71u<|v)#XLR_Az*Y3%ENp-c9bmX^RBLbFn+Zq%t7W zPM}C<-izS*6?sVToxl+-#=dzjc&kML9BodIw&=iJQm`w0a3C|oTrZFF+_>PlAS5_M z?&uL@kRk666QHhsZ6}oN?eesV2*553bz^|TKv?u3!&vy%lx#~F@RW=SaX*9v$~Fu3 zj*5___pK=M*@Rc>KJWl-N&}E+);txw;1|rd{LaxV*<~9Q-98}?yIkB|@F8c+L{-qN z(;H1B?I3>re~_6+A42!I$7B91WQ9g#Su&X;=YH_a>yGGz~)u6d5 zJIU{=i&Fz5y>t6M0CatR-x8(VOUcE=wQZ@ZF$D97Tdd`Z${k9?q4I<3%0C)o?OQ4N zEOl$)H_CB4LUv*Q)nEo`!Y5bGMax*yYMXpJ4i zmGp$5c5B99;@ucL8!b^YUbJ(_Ere@un4wFNWvW3n>3#D$8Le{dS4bmz?_>d89D$vvaDG-=?Fnjng zTPyB?bwbiuvb~B>O7lBQ|Bo{>5kn~r&w^A{c>)%srLOa3fW!kbh_7s3YvZwuFXe5# z@WRl~!4`uVWRqp3zj7N3barx*Njdek1(`R*Wmp*MnIz@m*u7a_iHfZnt$)npMVvwM znFvT`!)}j@#E@RWXqEHs4%YtPn|3w!K+yc562FlZHxyt`i^p!1e?#3NWxf0*q%16p z?aJ$IMHJrs&MkBu6u9Gg-7g+HEo36o4Hp(G?(+H8WI1&__N+?51Ro0Qq{dCAPKcn3 z1a=)#CKU*5Xl#VFoNs%(S#Z8%(8!QnYe`@JCX>66cl!}@jE5$|d}XllamQAUjE5j2 zP--NkVyGY+kT&Hqf38BUpRQGITRWPDtGa{M{okGK=q8zStH$9g4U>>o&d3es6{(Rs zRg)Lx^x&(zOMZOAYEmTNyXLpI$`cXU+ua z&4-GUn2%+b+rhV3pW=W?I`BJ)(=`(H^Ok z+0TD5lxAoD1^qJx6&c$jOatNy4Zu*Km*n)NFZIq1 z!C#q`^CKDmq~govwK@ye5n2fF6V6c*Id#y!QluAfp&`;rM`1HHVB{`niq%F8=(1s5 zI<5*#Uk3O(Nvs6SycL*??itf@?reONIG7LbAcF*-Q0+VpnG!N>(q5O;6z;y+D-y;x zNmph$Rw$8Ru=0li$so<{F9_e8ASKV-^8EeA0Rc&6|J2Oea=`{O(K=!vnS-SNLBZh4 z5z~jeC;b8<9O>_n^EPiQ2Ixh~9~(>(1EE^W*ds@6*~TViWo>5(X8vMnD$B)Xw}Y8+ zK%T>d68~_XHJX-rpLCMBmE%WX%&E`xUXu}z2s5b^koZ8C*HuBUemiJ;0?FCC$39K7 zQ@*x2IlCmuEpTs=ToDrwL`pQqv_bm6eHs!O>6C_HWi8xLMS689Dc%OzFBgF+& z%farcAGnKF`uSG>Y(U>ayL_EO5JwS`DR&FOv6(*!R@>H&ViZq zF4B?SrCA98b;-}gmwv7yRBSZ5Oxh!*O*;HKE{=a*k%vY#5{ei<4hB~FT*`JzPxL+X zmNoyPSd~(CbE+{jvZZAM2%AetGOsa*wxuasa_Hev_<6b1KUnCSxG8Jh&3tAFRbYvg z&cOYf>~8%uoYh_i?t5tk@$5kjrFSiTDV=G3NX??Avw{=V7Dg3{(1%jndtV1cUvEng z+i!*mbRRM;Q^Ff(O&21zlGViS%4=DqrRFhDG^nsu0JNRFU%6tjGu|n9k@4BLbmpx} zvEXr{T7IIQ7zh$PIp30bx*GQSro*&msuD&2RbXp0!UR9sc`YjZ(_0({AX#-h z0@cQWww=1GYU#o9&?w!?cfI@gc6*IU1Nwe=5+{$e+TF8qO?)fQr_hW(8!h-`s`g~+ z^p4wC{xYgX7o4(^@~l{d#TG=?KQuG#xqe7(^h!8`qV2Q6huWo-6(ZI(Lz2#q%p?~7 z2Ue-gPtMO%Oq?;q5o0;v{&F;{K5P?bK6ULi_ijWh47y632Q_eF$rkq-2wXBrNq9Qy zUV&PQrRtv&k!0^Q5>}7$9S5@!BXs8X26GSh1H&`N6rUA!ziL^k&p}_Qz1b%v*bVW< zfsBI_0j<KxSHGP`O-npbBvBH)8;r#0>oQouf#f63s z>oSOL$Psk)>1tAsqV?AxgcYTyO-4sb?lGa)C(=?B6M19kPhvovGx_s&f2_@Kt%Q#_ zr{V&IG&9ezgi}2~{W*Rc&QRs`PXw`F+sSEw=X?s9EkTVMrLoa+)I1 zxR<$#-#XxFmgyxcd0d!!FGdQ+ZLNyv^o4mW)>@t`RNAi}t{HO<6vL52t;A%5u@8e) zBVOs>RqGu?)K5fzv82?_xW5hK8mMQ^{lG!I*N6;T*xU*{sXfyipu- z+ILp8i#dju6s+O0#aa&wiJfsC->}TGIM)ZF4^OLP-Q&=3#t$9#WdM{-qq)nD9$rhx(Eu+tkxA^`NttwrowIiA*NJ>mNdX8kmBOW=DT~G5i zE9JxmNojAZ#R}0WsrqKwMLWbXCmlo+@9D)vJe=TYMQ>DE*q(j>z`>B~`kbKXUIYH9 zOfG4}eOQm@Lkm2&vJG`Qw)ZN8|GW&R(|7i(*M#q#H3@&YniicE#iGv-gLFsbdS6Rm z+80AXc@M6VT57_+z~%X)(qF!#TEeepxvtux33HP z@Sl4rU62->mbk_&-mKUeB9Wc4vHiBbJnTV9R)_s-P(VI;Cp>fR8#W#Wh^w&LvX8pe z6^z}H?Wxgd6WT)as5A^#;S9IOby)$`N1<~KlK0&#-~|0}h3xa4V!=g|$@_xQq*8cN$KVeR%OCtZY+mc_hZgMm8LRxMLMz4ROM?t*u%tL(&Rn7zK{xc^~dWY(fL_7ot%EITyz6PL@abAPBHR zW_277-yHfafV7kS)cDHkxFxBZ5F-o)k6uSs)3=Xo#VghS?)XP~Jep*0cNGATR1=BY zuxTLfip@{Aq|9Pud|9yhItD0g`ph}h0&%XyRq;Y5(l1t*kLuZeX~p{h2QIT(s)z_# z8*5=9=a~ubIb%wY9P+ye7Ox)Zu3#>v3_?)KZHE2f2TQ?KS_LGTLXXXK6(2c2{}-!N zNkfd;F+myL;!ai*_YO~TNwDz`kDj3Vdv*(w;Y2x%J|sVY$g-mBcR2+F-|@h!_U6WN ztmfv?hB<|Z)0H!W-zm=~?fFhV$$X%|!00HnbwezIs6WDItZ%2aSU$6j#QT&O00-eE zKQNE3?l~-fLtSN6L%GbO#i!uR4+Ff1%)IuoH}_6{c=FqIN@{u8gxX4irHE8bI>rtO zBd+)bR9xQqPb6+JW6qOx8(Z~4gqr2*$^MZ$s}O9aWR(~=d%|JDc`LWfms?|2TM+Y2 zx{(yb@T2H3@lc>qJnVwXfWFMJHC)$QVtOwztAi*8ST*Hc$jUXfGkAgTfe1+HxNI$1 zAXR_$xQBhgW|h~MdHh<>K4;ubxomSnl%Wlb_YH|`nY|*s8Ej}h*kX#PJ}9baDZb1; z-DO>}ta=%no2}X#w5w0=agN6YY^rL&StP51)|>RK4QC}re0>Q@sxC#HLz}2exA~)l z82!^jZ$}*ZCIh}UU@zQY;Fc$ek6hVa-rTg-Ii@FM%`{y&Hj6zqVp9iR{5rO2u|wp{ z|3c8k<5afD0vP!sI_3HZe(m+98B8L*NZAzssfuefqcGaiH65Dq2sTlyS!SV?xQ|Kp ziqE)wMK?=oD+Zq7lIJ>_{M2q?a=st3h&NK`+N#pmvrh&&$aOJr2<;2Bbrz!otx@F5 zkF{~|m#r-oMHm0B(QT*fCb*d%YTH*9QVk*y$f)2CYxtUW9;L5^{koGflw z8vVV@Di%SA5$2}a=X{tfb`7g2($6p(m^(@Q@bG$$4FdQ?*iXV&Ug{zblNf8=+)j{t zfhKsi)FbN5V>z;`n@nx`Hc5P=*pYHA5!!v9TDEU-ZvKszvAU z6j7hah0DUSzCV(qA4`(;V?6qM+VYbPGDBdUB2t;$EkY+{MTqBT>w%Wj%lA0kcLp6T zgQ}%4N%~KLiS!ms+M7eTT)`)ln|7!>wVRA~abB!Vp{0@n``R*6f$k5@IfUi z09?V7@QpHXjzY@ux5?VHTzliCuSy2thxM169A=r}V!ZC6|6f}V zSM?z9^F^b_GrsK}+?{k3vt3Yk0G{zrZ`~gcp6lo>x)<+e27DsQ4rZb#HbH6@yWYK5 z)cC9rz4Nk$+R)YJkpHPZehi`^^!ok*&dXUWPa^jhAJLx*v7V}BXuJQCckX|#RWj(@ z_PVNp{wJ-k7rhwC7V;y9QRTyKKpa>}+H`~C4+AMVci@t@g&MKCn^nF z?qvv64uE-W7?y~S&fT-l`%2&Q5)#~$=k6LtpJo?@enq4Z_`J8=o|=agVWLieeSE&W zxTSR%NM}K4^_a?a_7~#PUYc-|0t`&lP)u(LO$!_6KXl{Lb~_VaNSZrfK)g_s$SvB> zW0|#Y?#;C0*lcKV{~Cd+^WXTJcfbHVZOqx2;-O5|kkVLqc8aP01ayCB;zkZJwb&)l zh$}j~`}94%TFOZ6(P6S0KNnK~r9)BPuKjf*wDYOGl zu<99=3*LAZI@{>N0Hv???i4AiEc!<8t^njjaT^cGKE3=cgjF@UBpJgEMbX`Uuf+^M zj7>l?eQVda4=c2Kz%e(T4_Uy$u*-B6>$$qkQnNJ&YQ`&(`34=9Me`VAOwZx1&$WtS zrQk8?LNyw?^CYlOKmJ>W7bZ-84Fj8DGaVVS-(9L5ru)>Bj(Od0i+A(I#JKS`)UTR5 z`hA(teUK`0{%tSuB!?h4*mS)pvVkyNz;(;MKJdG#+F3MA;ae;TMu}tq|K&2w zoF`{z+v>207CZ3%V_y=C0(HNVYkW5)Nvb9`p3oPYC~&hB+O}{JWMh_W=^E}Vu)i(q zVRx#=<~zpn7zww!hslW_Fo&+NkXGxDM48;sXwZf`wR5#t8YLZbVU%tr{Y3KPIa-d@ zgD6KOixZ(3x<4Z7%BF@1+P}X~%-1`J`DB^r7yfwvBK!8JZ668*^1LFv9V*Hc);svo znV{CZB+H-YONo)x-Sw^L1jhl>tQW4}6i-vY(O|W!O5-6WvBapIs7zY>j#;V@a+!(Y z`HctS&n;obF4>rje)mUMdG&t@{oZI+Bv=sF#akWID%d4~X5QgH@~x|g;+a&{PfOa} zmv%D~48nAMIFf?rK4M~~y}_(s8PzxqQCf;SDM)I-0_UC9g?($OvpMhc2maaO1Slil zuWTL=fTvW}CJ6knf~DDz5~jc^eAyX%IEpc-OAfC9nH0m%4{Fwa{li5aA@)y1ACi-I zsVR^^04g#@SptyXZjCMqH&fahf`h7~$xq~?!Ib>Jw^lP*A$wHe0zS496ex!sdMGL@ z3&9Ebmtn|wibB4qi3RGfkD@q7d&rq>6-B=%dbwauDa`HLOL^#=P823aHvFy@4cj0H z$Qs_!?h!Cc4*^zVEY3Pf7lkW>Qc|hRHNXu0)VIW@gwtZ0`xDS9KOMmD}tiFPg9Rf5xvB z0UYs>_aztL%Du6;b1wVCpe72wcoaXtcH=A<)5{K9>`AJ>u%-KpQo@BQV%l|=4{QX~ zH3L1Hcg4(f7=bUaU|~N<&Bv_#Me#}e22&zir_rh1xLoF$iPqn-wBPMQxfE#phKa=F2o&9?W75#`=VAG(<~&cEyB<$+2mlTK f|Mk->w~7V{pJ)v)3Y+`?djqR1uOU|{V;=fHDzy%r literal 0 HcmV?d00001 diff --git a/Sources/CodeCaps/Resources/ProviderMarks/kimi.svg b/Sources/CodeCaps/Resources/ProviderMarks/kimi.svg new file mode 100644 index 00000000..1915850e --- /dev/null +++ b/Sources/CodeCaps/Resources/ProviderMarks/kimi.svg @@ -0,0 +1 @@ +Kimi \ No newline at end of file diff --git a/Sources/CodeCaps/Resources/ProviderMarks/zai-color.png b/Sources/CodeCaps/Resources/ProviderMarks/zai-color.png new file mode 100644 index 0000000000000000000000000000000000000000..9f7d77da4c6ec545602d99b92995d1bfd965f52a GIT binary patch literal 7921 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 F{SQ%I-G2Z8 literal 0 HcmV?d00001 diff --git a/Sources/CodeCaps/Resources/ProviderMarks/zai-dark.png b/Sources/CodeCaps/Resources/ProviderMarks/zai-dark.png new file mode 100644 index 0000000000000000000000000000000000000000..eda49949baa90e6c5d18048244dea0d648afa2c8 GIT binary patch literal 7466 zcmc(E`#+O^`2W4lp=l^`4n@fMe8{<+$sy+)=9DDIa!M;3Dy0KCR*n@p8(OH0MI{kg zVTcjlE6g0{xb1uE`}jOQf5PX7J$B#Q?$_aZJrCD)?Vgi^6*reC7XSdf$VNSJ(*c;S`LjAxMR)TET64z z4G$7KBitFTrW1hs_Q33zO_!51A2jrU3%~UtrvvimEDpkP=Y$p28XqPf%EVy2_@rLl z>Cw?iT59_8lsBgRcv+~@G^VGpLGmeH&k~$>+RLzD@-_xwR80?eX z-p!I?JQm7A7yPee0R*b$grJ8!{R;$<7nmW>RnMn)hH`UN$o{d34vB9ujEVD%dFGL&JnVU2~KX#4icRaU(1L2Gejs;KHPq|Ytvh?PAO?Oq&P6=Z8 zf#mDry<3r-tW3LFw4ySfhrrWnHF$CjfG4ofv~ z1Wm!E3m}WjG*S}&z3S-%AY8k9X0PRk@+ow4L|{>3!lg@Jn$hP9CC7O&8~hw{l#JkM z#L>m&RZ?S6NSwa77Ld7nQ|xGku!vb^GCgwA}H|ZBA2( zZe(0!!^myDvq2aJ%xW|MkAfJrH5uz1wdhN@0bl z&Fy`#9~YQXo?KBI7rL4h_RS91no8yEXOAtZpKwW@Lind)ms>0FS48H_raFL9qZb(X ziF}CQ@0rBznety}BIHmGkh{zuKvHIW`7+TmauG|KmMCPsW=kGYZ)jvh`cLu>KM}sx z`6YPDHXMCD@*a;IiVF}Xm*E$aSb5@O!_V&`{O@}_0kW?!M*;~cAw=ZG-EaHY$xp8M zvYXIJ?~SpG(;Ic+A`G+AaPkzIY51&}SzAoN=8czn9S^z3S$F-eGQZqe0>DSy0BTvX;dB&7vxQRff)%IhYM|AUh=r8Lr-S=Tth0t;s@OXa* z;0bb{M$j6AoOQ7qGi3&xRZ9rJHOOG5hxM*TIsU35rLYgraV!*j z^uOOF*Pp=~r1=BRBmU&!MrQmYj=&s+-y&jj>0j%LVl+0{CCcz;T?wuhi&iDEh}ysf z^aUjfXBe!R*`n@q3awv&wMfb(kln_@BBq-ePnH_YGBhV5|5ClZ#(LlMasl;yL$wl#tPv4n zv9_4IA5WV94JZ+*`uR_rGe%g+<7jFwT0eUU@=iV!yWadRowDcnaEO~7<9XKO2xoUb z&Lb{-Eo?O@o1VT}o5t-eZyNWYq)blve9O0N%)wYaSXep!#i@>DMF63Dx{G;n0j*xvE2FxWI)EUX1kQ{<*T}pQZy4Cb_f?B@9FrUr&=`> z`%y=jg9S}wxvnychi=|^bAHRQ9JpOo?RdJGIiewIgDTgp3e|s7mcU18nN|eKO4!b! zK+>@R8IQOW8bCE$m7(Ucf2X!OV%K7<5OxeX2F;Esq_9ko(rS zx_g-A{|$5Il`T;24IrNd$i;_V3RN9p{uRY2#t77R-^vD$Xp!Gy ztT(Q84AQFMF?e0C!v-~RcJl-^chYjO4DXXx4NQIYu~=A1VvYP6LkdulFW*_H8LQ{v z@)a9xAwExQ{Egg`Y*239DjsWvthV{siWtWufc_dW!Rma3jx1n!y1RTSd-D2VIXGDD z5ilI-L*TT*h%9q(+Vy>mxm8MFw~BjsrU+bdRXx6^WNw3lPyZX-+NcoC<(rrz2_9if zPe#vf##!>i-$qWr$$qyv+ot&f+=!HZbKIQ%NE^>n+z8!}!iqQH_LVm^IbTzU)njQN z&01?&$(pLML5UAW^+y@X11Fv+8y_3p8DGG6Z(XvBSnnf@hBJidzid-Da-b)U;XS_0 z_2x%)^~yAFl#s%_tI1-pvVeq`L0Sy{O;&v~)Kq_|DD!Fb%;*j{`GpD&*B&ug__m@n zbx!|eIk+2{>a;aKIIhs-FssX7QHH8r>sQWn1x{LcjCCr9V)=j2&;0oe)Ue2IHeAG{6;pO61vJ1AKg){S(pL|(AT6KstV5cUP)S5 z5*b3#O&0)&j<`6ZDFL$Plh`b}SGP6MDO=WkQ|qys19pR7*NZ@) zXzoKOv9=r30o9BfbkfhLp52P34Vof|bah4c=-~b!Bb6O6*3u3GF z>t5f-ecDJZjR#!0o=tz&NgEj-7-GD4#+VDr(pW0rv*@-TS!$%?%;G_FiZ0I);Lf*O zo@gm*+#yf7Po4Y@Ij1{Y@;piIv09Znp;XoO;4K3m-Td>?B1dGWxNC*Dcq(g|NPT%C@cx<3*5dj15} z?ecmT7bvLG(z7MCI;huUh5USG5kf(jB2uu=M#p>4zt{7L+L#0M;7-shp#$v41+zA3 zwrcf7?;Jm@WSo2@PB@^yhyJi_Kelku3uHO^dT;Y3F#V{+7Iu6pgqn`ZyEYlpHqp5X zuNG?@133jWB(@3r*kcZZ3{dP4=ERU_XeW0z6!8rIN#bHiqU@JkjH zQsO`5cmT>1e(E)*WJSaxR!;)flD#Q;n75vlc?2*Vd*Fta5@HGt&gw`MxVc0kv~0(E zA4(ZJJJ7WCYZFvzC(IBrmmny-g5LSimm91pl@-$ekk=?+`i zgkPmC#E^6_6kC`0_G2?s?D{1K`*i{kN*ah}4m9rQf@9}uumc|dd2Kw2mZff-^s87W zvo7Vsi&=o5LQ$#HGznpv4tFcnvKhsz7kLkidr#SvRlA2Y*ft{M30o$=0`;Gw6RyO z>Sy>CRAURt$^PsBC$V)d0X}qsI!7p?DacZ__4Kw3$W)zjBX&$y-hVI1$XcB>J9n2A z0MWn?qBo;$Uepv0eHxubSNPyD^#XjN$iGcW&7rPfgr~GL@d~Ku0<#Kd)U)YLRyXJN zjI!zgr%Y27ts=*B``;*DP)}L00jn0(TOTjkj@v@GJfF3pMYESqr$175^0DaDSavj= zuL)5#yiyB%zioXKEe$2`rALgGS30DHOzF-t3>r541SP6P4%kB8k>1KsWhk^xms>xw z=v<~vP*a|&Uo?}4;)D;UEMgTTU~8H5ojAkRi^t^Izcjoq!)x5NiP@5yWu#Rk*Xve8 zO*wa)=0V)SRPXVCpgy)@3(?Q)wdklhr4)+g`DJc=A{0xwr3l~-_YI>3(;h__)M7)0 zx3bFcoqX6M{=ywubWuyo-zGL)C#V7+IJf}ito_KOt4*hyMwfu`wz#|MWGQcY-+Yy+ zxaC4bO31op*gwJLgC`k^mAI$m>c7C#NTuD;UwgrxYtGFubgOS&;CXbGmMX@ZokS5f7DhI8VgM2k;z?u zVrjM2ABYH0?zDoD3R*fq^dRUI$XA*9mMRp<>%Zp8Wwf2slP!@j|Ah{C4U0cqS6A^< z9#@*b|KUVdJ?YH6@o^HBcyT5ktOHIKvM!!N=RZA6SvRmoiK|dD%;M#8KC=Vhv3B1Y zuizKa7tDvGG?w9iJGV=Cy>tdvK^WBOvS*2J84qli5&k_ETv5iGmqwJ+!FXNh+Kf<;H-A^=KKGTchY0YsfPA^=}`lZz0;9B&-* zA$W3Do1ubGQlZ%Nr|rWKj2l>Y2zG8a3(Vl}O(Z^ULo0mPs*~kuuMVn@|ta>~ZqNguvI`tj_KM;&9bLnSeItK_KJ3AuEx0>SerPxq9P$54 zEH8LHfn)vNUBTsWiF1IaDfgpP&;VFvs_U^LqE#r4CM##hdR=dVDd(i1FUsjY0Os`f zMXJj1@17alNCu0A-s#7;rc#sJ9U))>DrbOUVIFv~X-Zn!lRgXlS~V~@-d<{_@qGjW z?C01vshmnGp;*l9oy+f{JnRd>C`L++{It6MjpLK{|T&~e@s&1Ti}SdR*<9L?l8((H2or5zQZVGJyW zW}aMfj_Gq9eQey-Wo!V-$UDbi`y6s(yB&nI<2R5gJI8AmBCQ7cP#RcosfizYfrSFz zthZ<1sj|(Q*$ahC#e&iyS5qys`wuH|uMX8PI~q1jYW0nr9eqUpfN|LOaF2t#Sh-MD zR-tTIqpCBYvf~Rg13gv8ei&jm7A7vRvGsDbWstNpfVrH#Nt9EEg);_%7WRvP_+_}? z-y^0(q_O>kw|7~->AjMGjr@0x<$b@gnz>_;e-W!gfMjKcFOFq_*{2L8p&V;6@1_7O zSJEuLH+!RwXaQ{2-xc`0zt};Wz8RbhZ;stCAHmgH|6c7k%Yk85RGCWWITK<1^QHm#c0iR1d zeEbeXq`;FiY%|$1R5ys3`QjPk5zPH01I^*I?W#Qk_~D2wu6d4C=8Q}7L0xWG4-}|* zScWH(+W4!>@cNBJOi+(A(9AT!kZri9TIbDt9MqcI{N5$GwYXxKGW%^cirQZuxSE9a z`C>>m{d)Bc?V(B-Y|sUmq_K|FJjA;gJ8?pH6A`3op2%(Sv4J2bGAiiUWx#((ayGfd zBKG{eF@E%$6?MPe!z+x z&@f*zFyB!+t#xTj?T`%n6oct_OrcS@EhBvchseAG+CUv#;kJYi-vc;UI&P}X+vJKS z!VFTyK|Y$kr*NOz(gqnB^&^?OrvE(VoUj_0T8%R8#uT|G7!W=!09S^0pzLgv z&4$R@ZUdIDJ5w`|pgyhBMbBG};QQBW@JX9+>`@-n|EmqC!I?QjEVz5Ji6XRKBzUm=}KUrHN!E4iX|@-@G4YnydIlsu5_zpt|$2i5|5&2#C$MY|FaR{fI0 zuPnU$(j~`gCTj&zfs01dagym3XukuAip^ofw1+tgFw zf{lltv1NZvscB2#D3)REhQ$Y-`+2irwUrM^}V@Ds}-OIs((L zQfl~$3L$_bxIeeIxZ{w!hH80kmr7@eDbZA^dmO_qfInYh--%3I{{7LtkyDy^IHCBG zGn=YwCTws15cab_`m4Gh-KRh^%jYMbRyfRfX@fevtb1W0s@lPuQ{;iDGT3xu={7Tc zOX$5}-{rw|o*fH2&W+ZHGJ`&3ucb9#-lS9UkEBs?NvZM-jYHn7mzBEX3JckJ z5Lr{LP*o&#^3LG1S1*n4i4c~A8WvC_D_z@iV83{ITcTs#wKVs8fUF_nz8k9kUZCOg z>jh2j4?Uyhv9f%yj*r`$pO?&xm$@o{vnf|je*MK$8Oyk#Mm7^8{pQtU^$GV!O?=!| zrGQ7yS&&%0qtFlT7gFlYn&nP6bX`#=}q2AlSSmr7#NT}wU9H44-;}b zrUwHnZx)<~4N&ax4Q5_NCfIqGMt z(K%siq#G{bQAA`x-k*~6I{{N(i^g(if3V1xy8!}-A`k1~-Zu=rZL&)37y7Wrciwo( z+iT;uU*S`sRVz{m!+R46pOKb(1EqSfSv}6O`54|rh5gfARMf^&c z$oTs_sj7Mb3S@&sk*J{iycQxR{rlZSgY^@e_XTF?+KF=*AV{ke8Q~ z_?G3GHvG)x7LCw1`7|&Sw2w=iul}UKQ;weDT(X6z^zn)ij(aSVHrjYIZZYl;p-m5>?lc`wiNee3-b-nH&sbM85JPVD&Y-`+P|Uss)+gq{Qd0CG(Y)kgpT0hp@j^DGvZ(w%1g>|M(4LI}@3}Xq4HtTbk8lmbyc%IrAO5d4C0;t#^mFr(bBFC{j?h zgP3^bQv)#`*sbpK@blw4$jyeU6HpB z>*_al(4pa}oEEc2W5;tP8)xIv(y7ID$H(WhL+G7MvmYf*9dr_u0ObGbD#fcYezi21 zwsIuK^rvy{s2AE3=B{N&qbK(Q zVegSZhJ0dr;+l=09~TpkT{WUHv+&MlH?6?ACxBj7DPvg<9bx$%Ntf8$BPW5}X~8<9{jq8HsOGMIG(TT#R;qqIybzdV!oMSa$o(_W49n z3hFtF+uqVYvj^>A#!8K}N!#-@n8hBN5N0GRx^B;%q~Ao~=4*CrrgPW%v*=x!&Y?46 z{fg{98vBf%YB?|cu;Ud&pQmbVGfGW`>wAPOgLqP_xKySMMLUS`Hrc{5>0LADtvZ&> zd1=YI=q+)&-LbJ#J(*&A62ujY;nMIa!gjJJ#(FxUp{8NRrU0hoj+sM`k zxD--Muq^F!D#_byKg=2G`tNZL2~R{%KUFz=rqUV*;+QhI-69qBbmMiS%dKuf1VR}Y z3NN>#Kj>|ZES48nt#SsZd+o%GEK(?B5D%Bm%`b-$3>HvD>-qF%Lkj>|~DtF>A5U02>-LfSti zL+kr`A%w>;sm0hJ#rMf?4iYcs`Cp=8{R*nM;Zy3pqnGY}{!>k|Gvgn}p1kehpX5gQ zv0IZSDSh-P=fPp(>%~KCQVLHwHqO3_odz@5L+jxmO@B%_^T^Oj@4rugu>PL9)D)@T z(-=8{6G1(vSHJ)M1Udhp4L2((-SpbHuy=Y*z@11;w^d=$?q|kFE3^M{z_9x9<`a7n z*Q5B~p&U9(lG}KA=hPO*&FL2ysT}{j>BdaY`X4cJzhv)DLb+H^r2{=AV%p?FseXnQ6dEVoGJ`9#(nJKTLymH9T3-XRJ4(TKH49Rd^L;McXtEq{+zW z>6!Y<4~TQ0BcgmTM2D*)9)osU+?;iJ{!Wg&{^@K#ce`(m`i(Aq+X|ff*G*nv@>t;U zY0>H(6nxv()R$Z)z_u(c+V08oAm-!Ik<)d59NET2EEbb6qvcwJa}j>Hd8TDM!+0PE z+>XdQj$fpa>@;`)hhPq^vZg10=#(b6kHbeU1TL}T?Z`btB|H*hHX5A->^?)-X9$Y< z=#t02&C;QhMlSHxN*JO4H@>LHPOH@5{A%?TEUiC3$c7O*7ZjvPPB;OgX0m$aQa>`4 zXFuC*RnadDEk|uZC8SJ?#^Tb?mN1q>`oGs*d-I}Xpt=}KfBCv}$Rx&crVM>Ke0mv| zWb!H|l?RR)JMAiH+?vTd=b=|ADM1P2>kMocDP7yBL^J_Cns~Rpc66v2Ha6j)%wGZI7v5 z2u=E6`L9ZG5&IfGxRB2d`W4QZ%K;sc$jA7#h5&FtlPn*y&}T?II;(e?9%mX}^f8~> zl-?i9Z)fq9y5+{P{nxyH|6_zG;4?l=L;c3~!pc@#sw57jxod8o`{m%f=-^8+Y)s=) z;2>J$i>os!)-lK^8SDPM#5^@Z6y;7`hQ1;m=4+bIF`hHU!O8tdLl(x7`zm_!g}fMW zRwG>-$p*a6{6@NZwuYOX+#+XD(~2vi8#2v0m@x~~32ThEHrqCJ$%SHOb`#EP?4}K% zuOlUcUH|3oA)eo;{IP7dutQ!GdHR7KhO%-;7z>WgAsEEhGi02M#nRh5{?v-2pR90=#gZsUo~O1VtK>I@=Pb#9R&IqdqDQ5(**Q)vq%cw- znwxTAVwGS-<(AjW)0WKM9p(*PxT4XeTAHG(YE@48`Z-UEnUi`Yc>n6y%&NJ$-vSs zRHn3Vy)$tHbEcT*kx)1L)an(Pq^!#ipElCb;J{A7TCk6MwX zhto0Py_r7t+wQZWz4+%B-yQ}8n9{!&N0q%$Hel3oInWa`{qt6Y0>PpdHJet@F`JO$1;iga))X{J|9fCs@&|>CgCuaI4U{S zyS*>VLE|MK>ZFZ?7o1-ThLyfffxLrr#QpiSdO<4!u~5{MauQKNpZFUUe6xbL+5kl% zmKvK)0^3~7g?nY4w|t|s2K8nG%=T;&VgQ)ZTLFVPa4vZ=2ef{^emW?*@n_eP%RgG< zYs&sSJV@^F<{wGq0iP#mKKPOMa;@Ciz7jg1_c%io{vxatL@6iD{9QGz2^NwbclR-Q zKednZyky;`j*$CUIr09jHji>K6&?YK7nSQi$@5wR8N%@-Py>1DB9jFJS5ZA$Gql9o zHz-i%#y(>pvH!ENwSe++5NvKKCs;@}*Vqt8^k*lRQ8fqG>G4qQzZ8gX;=KK_h76hv z2;2`TpG>JtPBaZ3WbyS{6I_q{YFZ<5qS2s+g0wK8^%Di2tX$q6zW0fQH>>q_jV-*_ zHZaUU1)u{QQM9UKqxpWv z!yZ?k2^Sd@Vpu789nc)?2YaLh07Y4lfXv-(uAkKRyCAs3G%kB9qIgi?8P?=2g3<#= ztlI^5-r#$CPK$eDEUDW{-w=tSBHk#wyFHxZvr$~7a6m5@QfYz0F%<$%xIUL#Zj50} zdS+AUE!vFULW2~RYx$!vmVetzn`mK5hzEg58daGH=35tqO2McDVd&vKH2Rl`Z@?2h zDIwsURQi7+`}6!A7&z~D&dJ^HBiP^1_z+b#0MRQMFoJ(AY|;w`s!_yS!tnCIdg!S5^Habn8A$#+$1;cya9<-c( z+Ppgdo_gg3yP=Yb><1D)9obL*H^lC%tR9Ey+m*H!b9AKJ(vzjb$pE&#?wZO8Vm4B~ z=tV~BnT^?Mm)SrcSGlX+cRcl=j>vD{0MRV=mQTlVn)6C=E9JXfF}$x3o{r5qsr<&7 z?-+d%cQBBoE>M924F?6vbf&uEzlGt2!Q5g&N1yO zZ~v%o?ckrn?csK7)brifgOcOGMO?f-1;&z!wO7k%Qdy72kbs* zId_(iL_nf@GN>8BEqdlMmip+wq2j=RgPxaXRtx+}u2#p--jvl$pepzdbi{!oC z%4UIAQzIey7zgV1^|Nai3iHun%KXgD-;~8Hmb#^nSATTV6huM+%&LG-mJlp9<@;|B zT3t#0CW1^W_Q%bImdV(H@LEcw>PFa=$VEztnco>@h(QveHUsk`<~KUNi-feuD`_BW?F;IbnMDnr{v;qIEnym~ z_ag%YL?0UBhLooIxcECdUeb8|-O*|GGbm3tP3d|(u9jw4YMTd&s{S#{as!KW+C8lH^KwCdIV~tl|;==gBBuSydvtC?pYfd$?_E<^@1K_ zdBYm|8}6UcM|Mc?r*1Iw8G-)Y)>terjH}23^pK9eV0Wuse_&xi&lQU;A=4Z;AOlqQ5e|Z{Kkyfo8Nwi~ zJCo9K!zRJ_kB^jCu`nRNQ7!|%5s6(5U7dW!Hz{`W{V`yzjU>JzD%W-VLoPXpS24p6 z2MLfUE4BKw%OLH88=HNHj_XirYnu@U2;0wnP*)B2U zGMnb+jUujiC4K_Hr^A~ozwt$ug!u0|W{joyzxb!MI}-p%TRm!9$8S~Ld(_jKLII7% z?n87O66>&%e!yBNTj(ftLA8Y zFH<{B&YIbN44enE>HmNM@*DLD#MN?iU-x`&2kO}oj_9#eQ8b65lq|kM80W_?jpM`Z z!*`=7g`(dQU6h*_;^grH=jz*NB%nu2$w`EwOu(M~bYDnr8NTta)8HYs-$Wa( zfQCf$jE?>EbZ<3{EP|?xtgps%H|fwxCbKPB5{eK9KoUXg-iba61qu==DgQ*uN}?}6 zP)!T*eo&hI3dz^q_7@fHI8eRI_2CBDDc5jzU%xcNhJydU^)DveqNvDQ{Zv@)hF_;g znXwR@iOO$^=hyaA)KZae&@+AQ;9K_Y*Ig*9ncq@O)hLi_-r+-l&9K2-HxI< z5f-niO4m+Qpn_(cJ;RSfGT}ZLt2!eu4FSj_?s1pDN{a-zI zC(-Wh>)wW{U;<_E)RCO4K@=4otqHogcq3+``4NvWk|uOeklaCvEW``Yh`0@I=XEq_ zrP?5Kj(*V{&7J^j>5twy_Gn%6u$+W)x11(}BX4LD@G0xW0S)B6zAB1#_RPM9bqoFD ze}Mw*M#>T}RtG^tIprelyxc)=d{J;nY;{S(>p}qsrkUO zMjIt)hpbTL)aIQ#+l1rTQ`piIRizu7p5yK|{z1m?P8HGJfqq(Z24OJiO)fy8>Jjruv8xNQ~G31o}`tS$i+U|{2D!z)zcWV00m=dC80$cuHWk#Kt_1b4{ zY9g6x6i$RF16`qk!ZUPy{~6K>&2}LfZ-&Nc^;2mBC0cQnQ4B^`6-n&`5^aA~K}<^1 z;J_+=$%e#Mn)HZFP&#;CE$B&tvu6kEtL69t8fnGo5wWH1PmTz=;PRSQ!H`N5x%k~t z#{yUjSZA`Ike2T9FU8yGzk$U){h}^KDi5)B0*Y(p0|p{iaFmdubG!h0vSkqupUR?h zFs0=5PEjnlwFz&Pl*QisipH*csp&!EDotM3UlP9p*B)wRbb4r>TX0}#mhPS69aq>A z@}F0?B;c0f6j}n1I2YL+RXw(BlWqj;Ej~mEG&iLW@elV8Jdl+2&Tmxve)vn~Gq_~qc}0J(xA-bdl2K!3Z9Jhr z8uYWWu-zvsi%FLkWZ-b6qXQw1Ls)H)kT3(nX`)wan zxH9Es$UuV*z92M_TxNAN!_G@yh|)mY3A`H9)Y*i=8Ua20f*AtFWUN+v;{(A#17m#1 zm9@YK?lpB%O!eCths++;a7DdyJ*hJ~{|RlB<&Mw0xn0vgV@?CfK+lg17qk3S-knJr*N882#teLx2S5uqlP`)tbGb`;LxW3* zmw$<)F26Bty8c_<`VwJ&HPCrM$-_yvIa_;Ld{Z&ei5`gCwlMjnhL_)X5u0qT?&kH} zzs4%E(!{Xq;_ad1u|-@u;GsY?Jc>)oOs%{uEJY6-Ujv-)KVw79yh_^H-R%26E+q6- zbPY!6OcC1P_X?K$RnsGfW-YAm0035%YRatsfo8^4=M(KxRmdqYu@oWfQ+4jYA2Nt0 zt%+x8txgTckbG`;JwB%g9vth`Co@*oB7)p|i4s7twHP|yezal}w74?9V=HERvG&g5 zM3@d*sPSGKOZKgAY-8>KP%^}Ic+OfKbQ?M?6b-G3WH`iQ(|%XvsJXpnsUg%uiTWe` z-K>=!aAsX|1TI)DCqssO7K4_R()de8{f126*5$|Tb4Ox(+21B_^_y_8PNFq?FXedc zjQBQIYR<0-#LV8Pksb1RaBV_H@$SVk=XGgNruo~b@gB$I7Xtg_N5uCs=dsIY1`7#^ z7xal?mB~8r$$=#7(~9RyudK#y63DLxe6+rJ%G9)w#|}Z3S!w;auq-z1UAk`~ihAL+ zdcIb?XvFN2S3?E;!v`wty7I5Tiff9qYboM}dY1ar>RhrMKkiXmEP;WA*bZr2AgLKo zZWfq&HLiOdxpu=ek*_1COLR5iR}1-2$W{H;)=zuB+k1XRz1I{jk(q6Cph-R_mmeyf zv=Di1saE368i7N})N)%Vcgy;yI=Q~0(aY1yAraJssK?XT>6aVxMxPXJIIs)d-L5Le z;XG@!uQPtyEkhaKR&{DcRN zhc)-i1wM{(RrVAgC`JvU70?25&YTYDbn}ES#TvCYZaARRVzo*eCafEh$#2l)KSc;V z(0l72C)0cxOI&SDytQQ4c3t{#i@5`6Ol{ivtbtV6KV0i8m}i+ZCavT0RO6!yAAxy+ z<}S5wPdRYoC5O_cAm4YvL-I|xH$Ul>Jk%%VNh5y`(MfK&-C&_6a>J_ljC!kuP+@L} z4{SP!+(-inMmQ#_EmjaZ%4RZxXs)LHb|rF6BPu5IZi~w_qenHrf?@IlxuJl2Z%+zlQ|S^^9^-d38siRN3TB!rbWDWhf+<}>Ds z+HDNgSJy#KKKoxSWz1GM72#@m3-Vc3daAPwrA4#v_8AtKh24LJCw1;!w= F{SQ%I-G2Z8 literal 0 HcmV?d00001 diff --git a/Sources/CodeCaps/Resources/ProviderMarks/zai.svg b/Sources/CodeCaps/Resources/ProviderMarks/zai.svg new file mode 100644 index 00000000..04ba2d98 --- /dev/null +++ b/Sources/CodeCaps/Resources/ProviderMarks/zai.svg @@ -0,0 +1 @@ +Z.ai \ No newline at end of file diff --git a/Tests/CodeCapsTests/CompanionModelTests.swift b/Tests/CodeCapsTests/CompanionModelTests.swift index b2557489..6ca401fd 100644 --- a/Tests/CodeCapsTests/CompanionModelTests.swift +++ b/Tests/CodeCapsTests/CompanionModelTests.swift @@ -96,6 +96,18 @@ final class CompanionModelTests: XCTestCase { // MARK: - App Group & Hygiene + func testCompanionMapsKimiAndZAIProviderAliasesToLogos() throws { + let source = try readCompanionModelSource() + XCTAssertTrue(source.contains(#"if key.contains("kimi") { return "provider-kimi" }"#)) + XCTAssertTrue(source.contains(#"["zcode", "z.ai", "z-ai", "zai"].contains(where: { key.contains($0) }) { return "provider-zai" }"#)) + let widgets = try String(contentsOf: URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("ios/CodeCapsCompanion/Widgets/WidgetViews.swift"), encoding: .utf8) + XCTAssertTrue(widgets.contains(#"if low.contains("kimi") { return "provider-kimi" }"#)) + XCTAssertTrue(widgets.contains(#"["zcode", "z.ai", "z-ai", "zai"].contains(where: { low.contains($0) }) { return "provider-zai" }"#)) + XCTAssertTrue(widgets.contains(#"asset == "provider-zai" ? .template : .original"#)) + } + func testCompanionResolvesCanonicalPlatformDisplayTitles() throws { let source = try readCompanionModelSource() XCTAssertTrue( diff --git a/Tests/CodeCapsTests/PlatformLogoResourceTests.swift b/Tests/CodeCapsTests/PlatformLogoResourceTests.swift index d3fd3c7d..f7df49d2 100644 --- a/Tests/CodeCapsTests/PlatformLogoResourceTests.swift +++ b/Tests/CodeCapsTests/PlatformLogoResourceTests.swift @@ -26,7 +26,7 @@ final class PlatformLogoResourceTests: XCTestCase { "google-antigravity", "antigravity", "google-antigravity:gemini", "google-antigravity:third-party", "gemini", "xai", "grok", "grok-cli", "grok-bot", "minimax", - "muse", "muse-assist", "muse-code", "cursor", + "muse", "muse-assist", "muse-code", "cursor", "kimi", "zcode", "z.ai", "zai", ] func testMissingAppearanceVariantFallsBackToTheColourMarkBeforePlaceholder() { @@ -54,6 +54,26 @@ final class PlatformLogoResourceTests: XCTestCase { /// installed app that was built before a mark was added keeps the old /// bundle, so this also asserts the bundle actually carries artwork rather /// than existing and being empty. + func testKimiKeepsBrandColorAndZAIAdaptsInEveryStyle() throws { + let kimiStandard = try XCTUnwrap(PlatformLogoImage.load(providerKey: "kimi", style: .standard)) + XCTAssertFalse(kimiStandard.isTemplate, "Kimi Standard must preserve its supplied blue artwork") + let colorPixels = try XCTUnwrap(kimiStandard.representations.first as? NSBitmapImageRep) + let bluePixel = (0.. 0.95 && $0.blueComponent > $0.redComponent * 1.5 } + XCTAssertNotNil(bluePixel, "Kimi Standard must contain the supplied blue mark") + XCTAssertTrue(try XCTUnwrap(PlatformLogoImage.load(providerKey: "kimi", style: .template)).isTemplate) + + for key in ["zcode", "z.ai", "z-ai", "zai"] { + XCTAssertTrue(try XCTUnwrap(PlatformLogoImage.load(providerKey: key, style: .standard)).isTemplate, + "\(key) Standard must remain an adaptive monochrome mark") + XCTAssertTrue(try XCTUnwrap(PlatformLogoImage.load(providerKey: key, style: .template)).isTemplate, + "\(key) Light/Dark must remain an adaptive monochrome mark") + } + } + func testTheResourceBundleCarriesArtwork() throws { let bundle = try XCTUnwrap(ResourceBundle.resolved, "the SwiftPM resource bundle could not be resolved at all") @@ -63,7 +83,8 @@ final class PlatformLogoResourceTests: XCTestCase { // The key itself still has to resolve, which is what // `testEveryProviderKeyResolvesABundledMark` above checks. let marks = ["claude", "openai", "gemini", "gemini-color", "gemini-mono", - "cursor", "xai", "grok", "grok-bot", "minimax", "muse", "muse-code", "muse-code-dark"] + "cursor", "xai", "grok", "grok-bot", "minimax", "muse", "muse-code", + "muse-code-dark", "kimi", "kimi-color", "zai", "zai-color"] // Every named mark must be present in some form. Deliberately not an // exact count: the owner replacing the fabricated MiniMax `{M}` with // the real PNG mark added a file, and an equality assertion is a test @@ -80,7 +101,7 @@ final class PlatformLogoResourceTests: XCTestCase { /// a different hat: `NSImage` returns an object, and the row draws nothing. func testEveryBundledMarkRasterises() throws { let bundle = try XCTUnwrap(ResourceBundle.resolved) - for name in ["claude", "openai", "gemini", "gemini-mono", "cursor", "xai", "grok", "grok-bot", "minimax", "muse", "muse-code", "muse-code-dark"] { + for name in ["claude", "openai", "gemini", "gemini-mono", "cursor", "xai", "grok", "grok-bot", "minimax", "muse", "muse-code", "muse-code-dark", "kimi", "zai"] { for ext in ["svg", "png"] { guard let url = bundle.url(forResource: name, withExtension: ext) else { continue } let image = try XCTUnwrap(NSImage(contentsOf: url), "\(name).\(ext) did not load") diff --git a/Tests/CodeCapsTests/ProviderMarkResolutionTests.swift b/Tests/CodeCapsTests/ProviderMarkResolutionTests.swift index 20c0979d..a93544cc 100644 --- a/Tests/CodeCapsTests/ProviderMarkResolutionTests.swift +++ b/Tests/CodeCapsTests/ProviderMarkResolutionTests.swift @@ -59,7 +59,7 @@ final class ProviderMarkResolutionTests: XCTestCase { let keys = ["anthropic", "claude", "openai", "codex", "xai", "grok", "grok-cli", "grok-bot", "cursor", "gemini", "antigravity", "google-antigravity", "minimax", "muse", "muse-assist", - "muse-code", "github-copilot", "copilot"] + "muse-code", "github-copilot", "copilot", "kimi", "zcode"] for key in keys { for style in [MarkStyle.standard, .template] { XCTAssertNotNil(PlatformLogoImage.load(providerKey: key, style: style), diff --git a/Tests/CodeCapsTests/ProviderMarkTripletTests.swift b/Tests/CodeCapsTests/ProviderMarkTripletTests.swift index 488e759c..7a370e34 100644 --- a/Tests/CodeCapsTests/ProviderMarkTripletTests.swift +++ b/Tests/CodeCapsTests/ProviderMarkTripletTests.swift @@ -22,7 +22,7 @@ final class ProviderMarkTripletTests: XCTestCase { "google-antigravity", "antigravity", "google-antigravity:gemini", "google-antigravity:third-party", "gemini", "xai", "grok", "grok-cli", "grok-bot", - "minimax", "muse", "muse-assist", "muse-code", "cursor", + "minimax", "muse", "muse-assist", "muse-code", "cursor", "kimi", "zcode", "github-copilot", "copilot", ] @@ -31,6 +31,27 @@ final class ProviderMarkTripletTests: XCTestCase { PlatformLogoImage.invalidateCaches() } + func testCompanionCatalogCarriesKimiAndZAIAssets() throws { + let catalog = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("ios/CodeCapsCompanion/Assets.xcassets") + let sourceRoot = catalog.deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().appendingPathComponent("Sources/CodeCaps/Resources/ProviderMarks") + for (asset, file, source) in [("provider-kimi", "provider-kimi.svg", "kimi-color.svg"), + ("provider-zai", "provider-zai.svg", "zai.svg")] { + let imageset = catalog.appendingPathComponent("\(asset).imageset") + let image = imageset.appendingPathComponent(file) + XCTAssertTrue(FileManager.default.fileExists(atPath: image.path), + "\(asset).imageset is missing its vector logo") + XCTAssertTrue(FileManager.default.fileExists(atPath: imageset.appendingPathComponent("Contents.json").path), + "\(asset).imageset is missing Contents.json") + let copiedVector = try Data(contentsOf: image) + let suppliedVector = try Data(contentsOf: sourceRoot.appendingPathComponent(source)) + XCTAssertEqual(copiedVector, suppliedVector, + "\(asset) must use the byte-exact supplied vector") + } + } + /// The companion's asset catalog must carry every provider the model can /// name, Copilot included: a missing imageset draws the dashed fallback. func testCompanionCatalogCarriesCopilotMark() { diff --git a/Tests/QuotaCoreTests/UsageAlertPreferencesTests.swift b/Tests/QuotaCoreTests/UsageAlertPreferencesTests.swift index bd8719fc..f3e694c0 100644 --- a/Tests/QuotaCoreTests/UsageAlertPreferencesTests.swift +++ b/Tests/QuotaCoreTests/UsageAlertPreferencesTests.swift @@ -26,11 +26,14 @@ final class UsageAlertPreferencesTests: XCTestCase { preferences.save(to: defaults, key: "alerts") let restored = UsageAlertPreferences.load(from: defaults, key: "alerts", resetEnabled: true, resetSound: .frog, runawayEnabled: false) - XCTAssertEqual(restored, preferences) + XCTAssertEqual(restored[.anomaly], preferences[.anomaly]) + XCTAssertEqual(restored[.runaway], preferences[.runaway]) XCTAssertFalse(restored[.anomaly].notification) XCTAssertTrue(restored[.anomaly].popup) XCTAssertEqual(restored[.runaway].sound, .silent) XCTAssertFalse(restored[.quotaReset].enabled) + XCTAssertTrue(restored[.museCodeBurn].enabled) + XCTAssertTrue(restored[.museCodeStandardSession].enabled) } func testCorruptPreferencesFallBackToLegacyChoices() { diff --git a/docs/AUTO-UPDATE.md b/docs/AUTO-UPDATE.md index 1e559792..7bd67d16 100644 --- a/docs/AUTO-UPDATE.md +++ b/docs/AUTO-UPDATE.md @@ -43,7 +43,7 @@ A `--dev` build (identifier `com.jays.agent-bar.mac.dev`) gets none of them, so ## Versions -`CFBundleVersion` is `git rev-list --count HEAD`, so every squash merge to `main` raises it by one, and Sparkle compares that number. CI checks out with `fetch-depth: 0`; a shallow clone would make every build number 1. `CFBundleShortVersionString` is `.` (prefix from `VERSION`, default `1.0`), matching the fleet's unified 1.#.### standard across macOS and iOS. A local build from a feature branch can carry a higher count than `main`; that copy simply waits until `main` passes it. +`CFBundleShortVersionString` uses the fixed marketing version `0.1.0`, preserving a higher released App Store version reported by the read-only ASC version planner.  `CFBundleVersion` uses the shared iOS/Mac planner: the 12-digit `YYYYMMDDHHMM` commit timestamp in America/Chicago, raised above the highest existing iOS, Mac, or Sparkle build when needed.  A rebuild therefore advances above the existing build, and the Mac bundle records its planner result.  The Mac release fails closed if ASC or the paired Sparkle build inventory is unavailable.  Local non-release builds use the commit timestamp and the registry marketing version without contacting ASC. ## Keys @@ -145,7 +145,7 @@ To pause releases entirely, disable the workflow (`gh workflow disable mac-relea 1. **Package.** Add `.package(url: "https://github.com/sparkle-project/Sparkle", from: "2.10.0")` and `.product(name: "Sparkle", package: "Sparkle")` on the executable target. Commit `Package.resolved`. 2. **App code.** Copy `Sources/CodeCaps/AutoUpdate.swift` and `Tests/CodeCapsTests/AutoUpdateTests.swift`, renaming the `CodeCaps` prefixes. Call `AppUpdater.shared.start()` first in `applicationDidFinishLaunching`, consume `UpdateRelaunchMarker` before opening any window, add a **Check For Updates…** menu item that calls `AppUpdater.shared.checkForUpdates()`, and validate it with `canCheckForUpdates`. For an Xcode-project app, the same file works; `SPUStandardUpdaterController` can also be instantiated in a nib. -3. **Bundle script.** Port from `script/build_and_run.sh`: `embed_frameworks`, `framework_helper_paths` and the signing loop in `sign_with_identity`, `verify_app_signature`, `sparkle_feed_url`, `sparkle_plist_entries` (and the `$(sparkle_plist_entries)` line in the Info.plist heredoc), and the `NOTARY_AUTH` block. Make `CFBundleVersion` monotonic (`git rev-list --count HEAD`). An Xcode-built app gets the embedding and rpath from Xcode's "Embed Frameworks" phase instead, but still needs the inside-out re-sign if it re-signs after the build. +3. **Bundle script.** Port from `script/build_and_run.sh`: `embed_frameworks`, `framework_helper_paths` and the signing loop in `sign_with_identity`, `verify_app_signature`, `sparkle_feed_url`, `sparkle_plist_entries` (and the `$(sparkle_plist_entries)` line in the Info.plist heredoc), and the `NOTARY_AUTH` block. Use the current 12-digit merge-time shared-build planner for `CFBundleVersion`; never use a commit count.  An Xcode-built app gets the embedding and rpath from Xcode's "Embed Frameworks" phase instead, but still needs the inside-out re-sign if it re-signs after the build. 4. **Keys.** `swift package resolve`, then `.build/artifacts/sparkle/Sparkle/bin/generate_keys --account `; export with `-x <0600 temp file>`; put the public key (`generate_keys --account -p`) in the build script; `gh secret set SPARKLE_ED_PRIVATE_KEY -R < `; then store the key in Infisical (`/-sparkle-ed25519-key`, name `_SPARKLE_ED25519`) and delete the temp file. Never print the private key. 5. **Hosting.** Public repository: GitHub Releases, feed `https://github.com///releases/latest/download/appcast.xml`. Private repository: Cloudflare R2 or Pages. 6. **CI.** Copy `.github/workflows/mac-release.yml`, `.github/actions/infisical-secrets/`, `scripts/infisical-fetch.mjs`, and `script/make_appcast.sh`. Change the app name, the `paths:` filter, the artifact names, and `SPARKLE_APP_LINK`. Make sure the signing certificate, the notarization key and the Sparkle key are reachable (see Secrets). diff --git a/docs/rollouts/2026-11-03-cc205-monitoring-alert-controls.md b/docs/rollouts/2026-11-03-cc205-monitoring-alert-controls.md new file mode 100644 index 00000000..ba49a0bb --- /dev/null +++ b/docs/rollouts/2026-11-03-cc205-monitoring-alert-controls.md @@ -0,0 +1,29 @@ +# CC-205: Monitoring And Alert Controls + +CodeCaps previously announced a new MiniMax quota week when an early reset timestamp changed, even if the remaining quota fell or a producer reused its window ID for another cadence.  The tracker now rebaselines a known cadence change and requires a quota rise before interpreting a pre-end timestamp jump as a reset.  Scheduled rollovers and demonstrated quota restores retain their existing alert rules. + +## Quit Behavior + +A user quit offers Close Window And Keep Running, Quit CodeCaps, and Cancel.  The first choice hides the app windows, preserves quota checks, and provides menu-bar access even in Dock-only mode.  Confirmed Quit retains the snapshot-write drain.  Explicit system shutdown/restart/logout and an active Sparkle installation bypass the prompt. + +## Providers And Plugins + +Kimi and Z.ai / ZCode use their existing readers and local sign-ins.  Sources & Fleet now offers separate quota-check switches.  Disabling one skips reader construction and credential/network access, removes its cached local rows, and invalidates an in-flight refresh. + +New providers can implement LocalQuotaReading and register a stable ID, label, configuration metadata, and factory in LocalQuotaReaderRegistry.  Personal enable choices remain on the device.  This typed extension point does not execute downloaded code. + +The Muse monitor preserves Rob/MA's original 95fc887 -> 5c2d697 -> f83d825 stack, supplied as a Git bundle after its VM worktree was identified.  It provides a Plugins section with deterministic Mac-local session monitoring.  A first-seen standard-model session alerts once; a sustained standard session stays silent; a return to contributor mode rearms the next standard transition.  Missing model IDs are ignored.  Codable state in UserDefaults survives relaunch.  The 90-minute, 4-million-token burn rule requires a currently observed standard session; contributor share is display-only.  The standard-session popup starts off and uses the same per-kind preference as Alerts & Alarms. + +Mac-local Muse stores do not reveal sessions running exclusively in another seat's cloud VM. + +## SMS Delivery + +Alerts & Alarms offers an independent SMS method for Muse Standard Sessions, Muse Token Burn, and Quota Exhaustion.  SMS starts off for every kind.  The category itself must also be enabled.  SMS remains available when local notification and popup methods are off. + +Save a Twilio account SID, API key SID/secret, Messaging Service SID, and E.164 recipient.  The credential record is kept in a separate build-scoped Keychain item; personal display configuration and alert choices remain in UserDefaults.  Saving setup sends no message.  Blank API secrets preserve a matching saved key; changing account/key requires the new secret.  Re-Authorize Saved Setup is the explicit interactive Keychain action. + +Only newly detected events enter SMS delivery.  A persistent hashed reservation is saved before submission, including uncertain outcomes, to avoid duplicate paid messages after relaunch.  The client uses a fixed Twilio HTTPS endpoint, rejects redirects, and does not retry automatically.  An accepted submission is reported as accepted, without claiming handset delivery.  No live SMS was sent during development or automated testing. + +## Verification + +Run swift build and swift test on macOS.  Tests cover reset corrections and scheduled rollovers, quit choices, disabled-reader non-invocation, Muse transition persistence and burn gating, SMS routing with local methods off, Keychain isolation, and durable deduplication.  Tests use private defaults, fake credentials, and injected transports.  No iOS simulator is used. diff --git a/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift b/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift index 5368cb6c..6d1a117d 100644 --- a/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift +++ b/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift @@ -782,6 +782,8 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { if key.contains("grok-bot") { return "provider-grok-bot" } if key.contains("grok") || key.contains("xai") { return "provider-grok" } if key.contains("minimax") { return "provider-minimax" } + if key.contains("kimi") { return "provider-kimi" } + if ["zcode", "z.ai", "z-ai", "zai"].contains(where: { key.contains($0) }) { return "provider-zai" } if key.contains("copilot") || lowId.contains("copilot") { return "provider-copilot" } if key.contains("muse-assist") || key.contains("muse_assist") { return "provider-muse-assist" } if key.contains("muse-code") || key.contains("muse_code") { return "provider-muse-code" } diff --git a/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift b/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift index 818bbdc9..744f2d57 100644 --- a/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift +++ b/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift @@ -1147,7 +1147,7 @@ public struct CompanionProviderLogo: View { /// Antigravity's supplied arch and Gemini's star keep their color here. private var isMonochrome: Bool { guard let name = resolvedLogoName else { return false } - return ["provider-openai", "provider-cursor", "provider-grok", "provider-grok-bot", "provider-copilot"] + return ["provider-openai", "provider-cursor", "provider-grok", "provider-grok-bot", "provider-copilot", "provider-zai"] .contains(name) } From 4fe58d075a69e80baaa3c9577afb13672af67f6f Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:40:41 +0000 Subject: [PATCH 04/12] Finish companion marks and validated shared Mac release metadata --- .../provider-kimi.imageset/Contents.json | 15 ++ .../provider-kimi.imageset/provider-kimi.svg | 1 + .../provider-zai.imageset/Contents.json | 15 ++ .../provider-zai.imageset/provider-zai.svg | 1 + .../Widgets/WidgetViews.swift | 4 + script/build_and_run.sh | 52 ++++--- scripts/mac-release-version.mjs | 147 ++++++++++++++++++ scripts/mac-release-workflow.test.mjs | 92 ++++++++++- 8 files changed, 308 insertions(+), 19 deletions(-) create mode 100644 ios/CodeCapsCompanion/Assets.xcassets/provider-kimi.imageset/Contents.json create mode 100644 ios/CodeCapsCompanion/Assets.xcassets/provider-kimi.imageset/provider-kimi.svg create mode 100644 ios/CodeCapsCompanion/Assets.xcassets/provider-zai.imageset/Contents.json create mode 100644 ios/CodeCapsCompanion/Assets.xcassets/provider-zai.imageset/provider-zai.svg create mode 100644 scripts/mac-release-version.mjs diff --git a/ios/CodeCapsCompanion/Assets.xcassets/provider-kimi.imageset/Contents.json b/ios/CodeCapsCompanion/Assets.xcassets/provider-kimi.imageset/Contents.json new file mode 100644 index 00000000..3d8833d2 --- /dev/null +++ b/ios/CodeCapsCompanion/Assets.xcassets/provider-kimi.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images" : [ + { + "filename" : "provider-kimi.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true + } +} diff --git a/ios/CodeCapsCompanion/Assets.xcassets/provider-kimi.imageset/provider-kimi.svg b/ios/CodeCapsCompanion/Assets.xcassets/provider-kimi.imageset/provider-kimi.svg new file mode 100644 index 00000000..01cd62f2 --- /dev/null +++ b/ios/CodeCapsCompanion/Assets.xcassets/provider-kimi.imageset/provider-kimi.svg @@ -0,0 +1 @@ +Kimi \ No newline at end of file diff --git a/ios/CodeCapsCompanion/Assets.xcassets/provider-zai.imageset/Contents.json b/ios/CodeCapsCompanion/Assets.xcassets/provider-zai.imageset/Contents.json new file mode 100644 index 00000000..35670416 --- /dev/null +++ b/ios/CodeCapsCompanion/Assets.xcassets/provider-zai.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images" : [ + { + "filename" : "provider-zai.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true + } +} diff --git a/ios/CodeCapsCompanion/Assets.xcassets/provider-zai.imageset/provider-zai.svg b/ios/CodeCapsCompanion/Assets.xcassets/provider-zai.imageset/provider-zai.svg new file mode 100644 index 00000000..04ba2d98 --- /dev/null +++ b/ios/CodeCapsCompanion/Assets.xcassets/provider-zai.imageset/provider-zai.svg @@ -0,0 +1 @@ +Z.ai \ No newline at end of file diff --git a/ios/CodeCapsCompanion/Widgets/WidgetViews.swift b/ios/CodeCapsCompanion/Widgets/WidgetViews.swift index 78c6f6ad..8f6f1fdf 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetViews.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetViews.swift @@ -69,8 +69,10 @@ struct ProviderMarkView: View { .clipShape(RoundedRectangle(cornerRadius: size * 0.22, style: .continuous)) } else if let asset = assetName(for: providerKey), let image = bundledImage(named: asset) { image + .renderingMode(asset == "provider-zai" ? .template : .original) .resizable() .scaledToFit() + .foregroundStyle(.primary) .frame(width: size, height: size) .clipShape(RoundedRectangle(cornerRadius: size * 0.22, style: .continuous)) } else { @@ -140,6 +142,8 @@ struct ProviderMarkView: View { if low.contains("openai") || low.contains("codex") { return "provider-openai" } if low.contains("cursor") { return "provider-cursor" } if low.contains("minimax") { return "provider-minimax" } + if low.contains("kimi") { return "provider-kimi" } + if ["zcode", "z.ai", "z-ai", "zai"].contains(where: { low.contains($0) }) { return "provider-zai" } if low.contains("copilot") { return "provider-copilot" } if low.contains("muse-assist") || low.contains("muse_assist") { return "provider-muse-assist" } if low.contains("muse-code") || low.contains("muse_code") { return "provider-muse-code" } diff --git a/script/build_and_run.sh b/script/build_and_run.sh index 70380c88..fec51da6 100755 --- a/script/build_and_run.sh +++ b/script/build_and_run.sh @@ -28,7 +28,6 @@ ICON_MAKER="$ROOT_DIR/script/make_icon.swift" ICON_FILE="AppIcon.icns" INSTALL_DIR="$HOME/Applications" INSTALLED_APP="$INSTALL_DIR/$APP_NAME.app" -VERSION_FILE="$ROOT_DIR/VERSION" ZIP_FILE="$DIST_DIR/$APP_NAME.zip" DMG_FILE="$DIST_DIR/$APP_NAME.dmg" NOTARY_PROFILE="${CODECAPS_NOTARY_PROFILE:-${AGENTBAR_NOTARY_PROFILE:-agentbar-notary}}" @@ -112,10 +111,10 @@ usage: script/build_and_run.sh [mode] --package also signs with the hardened runtime and a secure timestamp and prints the notarytool command; --release is the mode that actually notarizes. - Versions: CFBundleShortVersionString is unified as . - per fleet standard (prefix from VERSION file, default 1.0; commit count from - `git rev-list --count HEAD`). CFBundleVersion is `git rev-list --count HEAD`, - giving macOS and iOS the identical monotonic build number. + Versions: release builds use the fixed marketing version from the iOS app + registry, preserving a higher released App Store version when ASC reports one.  CFBundleVersion comes from the shared iOS/Mac planner as a 12-digit Chicago + merge timestamp, raised above every existing app and Sparkle build.  A release + fails closed when ASC or the paired Sparkle build inventory cannot be read.  Local non-release builds use the commit's Chicago timestamp and registry version. Auto-update: Sparkle.framework is embedded in Contents/Frameworks and signed inside-out. A build with the release identifier carries the update feed and @@ -441,23 +440,39 @@ sign_app_bundle() { fi } -# The marketing version is unified as . per fleet standard, -# where prefix is drawn from the VERSION file (defaulting to 1.0) and commit count -# is monotonic across all git commits. +VERSION_PLAN_READY=0 +BUILD_MARKETING_VERSION="" +BUILD_BUNDLE_VERSION="" + +prepare_build_versions() { + [[ "$VERSION_PLAN_READY" -eq 1 ]] && return 0 + local mode="offline" plan_output + [[ "$MODE" != "--release" ]] || mode="release" + if ! command -v node >/dev/null 2>&1; then + echo "error: Node.js is required to plan CodeCaps build versions." >&2 + return 1 + fi + if ! plan_output="$(node "$ROOT_DIR/scripts/mac-release-version.mjs" "$mode" "$ROOT_DIR")"; then + echo "error: CodeCaps build version plan is unavailable; no bundle was built." >&2 + return 1 + fi + IFS=$'\t' read -r BUILD_MARKETING_VERSION BUILD_BUNDLE_VERSION <<< "$plan_output" + if [[ ! "$BUILD_MARKETING_VERSION" =~ ^[0-9]+(\.[0-9]+){0,2}$ \ + || ! "$BUILD_BUNDLE_VERSION" =~ ^[1-9][0-9]{11}$ ]]; then + echo "error: CodeCaps build version planner returned invalid metadata." >&2 + return 1 + fi + VERSION_PLAN_READY=1 +} + short_version() { - local version="" - [[ ! -f "$VERSION_FILE" ]] || version="$(/usr/bin/sed -e 's/[[:space:]]//g' -e '/^$/d' "$VERSION_FILE" | /usr/bin/head -n 1)" - local prefix="${version:-1.0}" - prefix="$(printf '%s' "$prefix" | /usr/bin/awk -F. '{ if (NF >= 2) print $1"."$2; else print $1".0" }')" - local count="" - count="$(bundle_version)" - printf '%s.%s\n' "$prefix" "$count" + prepare_build_versions || exit 1 + printf '%s\n' "$BUILD_MARKETING_VERSION" } bundle_version() { - local count="" - count="$(/usr/bin/git -C "$ROOT_DIR" rev-list --count HEAD 2>/dev/null || true)" - printf '%s\n' "${count:-1}" + prepare_build_versions || exit 1 + printf '%s\n' "$BUILD_BUNDLE_VERSION" } bundle_identifier() { @@ -526,6 +541,7 @@ assert_resource_bundle_reachable() { } build_and_stage() { + prepare_build_versions || exit 1 local arch_flags=() if [[ "$UNIVERSAL" == "1" ]]; then local arch diff --git a/scripts/mac-release-version.mjs b/scripts/mac-release-version.mjs new file mode 100644 index 00000000..fd770497 --- /dev/null +++ b/scripts/mac-release-version.mjs @@ -0,0 +1,147 @@ +import {readFileSync, statSync} from 'node:fs'; +import {spawnSync} from 'node:child_process'; +import {join} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {nextSharedBuild} from './ios-fleet/shared-build.mjs'; + +const DEFAULT_MARKETING_VERSION = '0.1.0'; +const root = fileURLToPath(new URL('../', import.meta.url)); + +function parseVersion(value, {allowShort = false} = {}) { + const pattern = allowShort ? /^\d+(?:\.\d+){0,2}$/ : /^\d+(?:\.\d+){2}$/; + if (typeof value !== 'string' || !pattern.test(value)) { + throw new Error('invalid marketing version'); + } + return value.split('.').map(part => BigInt(part)).concat([0n, 0n]).slice(0, 3); +} + +function compareVersions(left, right, {allowShort = false} = {}) { + const a = parseVersion(left, {allowShort}); + const b = parseVersion(right, {allowShort}); + for (let i = 0; i < 3; i += 1) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; +} + +export function chicagoMergeStamp(date) { + if (!(date instanceof Date) || !Number.isFinite(date.getTime())) throw new Error('invalid merge date'); + const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { + timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', + hour: '2-digit', minute: '2-digit', hourCycle: 'h23', + }).formatToParts(date).map(part => [part.type, part.value])); + const stamp = `${parts.year}${parts.month}${parts.day}${parts.hour}${parts.minute}`; + if (!/^[1-9]\d{11}$/.test(stamp)) throw new Error('invalid Chicago merge stamp'); + return stamp; +} + +export function latestFixedMarketingVersion(fixedVersion, releasedVersion = '') { + parseVersion(fixedVersion); + if (!releasedVersion) return fixedVersion; + parseVersion(releasedVersion, {allowShort: true}); + return compareVersions(releasedVersion, fixedVersion, {allowShort: true}) > 0 ? releasedVersion : fixedVersion; +} + +export function releaseBuildPlannerArgs(app, floor, mergeStamp) { + const pairedBundleId = app.pairedBundleId || app.macBundleId || ''; + return [app.bundleId, ...(pairedBundleId ? [pairedBundleId] : []), String(floor), '--merge-stamp', mergeStamp]; +} + +export function planSharedBuild({mergeStamp, iosBuilds = [], macBuilds = [], extraFloors = []}) { + return nextSharedBuild({iosBuilds, macBuilds, extraFloors, complete: true, mergeStamp}).build; +} + +export function offlineBuildMetadata({mergeDate, fixedVersion = DEFAULT_MARKETING_VERSION}) { + const mergeStamp = chicagoMergeStamp(mergeDate); + return {marketingVersion: latestFixedMarketingVersion(fixedVersion), buildVersion: planSharedBuild({mergeStamp})}; +} + +function registry(rootDir) { + const data = JSON.parse(readFileSync(join(rootDir, 'scripts/ios-fleet/apps.json'), 'utf8')); + const app = data?.apps?.codecaps; + if (typeof app?.fixedMarketingVersion !== 'string' + || typeof app?.bundleId !== 'string' || typeof app?.pairedBuildFeed !== 'string') { + throw new Error('CodeCaps release registry is incomplete'); + } + parseVersion(app.fixedMarketingVersion); + return app; +} + +function mergeDate(rootDir) { + const result = spawnSync('git', ['-C', rootDir, 'show', '-s', '--format=%cI', 'HEAD'], {encoding: 'utf8'}); + if (result.error || result.status !== 0) throw new Error('could not read the merge commit date'); + const date = new Date(result.stdout.trim()); + if (!Number.isFinite(date.getTime())) throw new Error('could not parse the merge commit date'); + return date; +} + +function privateAuth() { + const keyId = process.env.ASC_KEY_ID || ''; + const issuerId = process.env.ASC_ISSUER_ID || ''; + const keyPath = process.env.ASC_KEY_PATH || ''; + if (!keyId || !issuerId || !keyPath) throw new Error('release requires the staged ASC key and identifiers'); + let info; + try { info = statSync(keyPath); } catch { throw new Error('release ASC key is unavailable'); } + if (!info.isFile() || info.size === 0) throw new Error('release ASC key is unavailable'); + let key; + try { key = readFileSync(keyPath, 'utf8'); } catch { throw new Error('release ASC key is unavailable'); } + if (!key.trim()) throw new Error('release ASC key is unavailable'); + return {keyId, issuerId, key}; +} + +function runASC(rootDir, command, args, auth) { + const child = spawnSync(process.execPath, [join(rootDir, 'scripts/ios-fleet/asc-api.mjs'), command, ...args], { + encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, + env: {...process.env, ASC_KEY_ID: auth.keyId, ASC_ISSUER_ID: auth.issuerId, ASC_KEY_P8: auth.key}, + }); + if (child.error || child.status !== 0) throw new Error(`ASC ${command} query failed`); + return child.stdout.trim(); +} + +export function parseAppcastFloor(xml) { + const versions = [...xml.matchAll(/\s*([0-9]+)\s*<\/sparkle:version>/g)] + .map(match => match[1]); + if (versions.length === 0 || versions.some(value => value.length > 12 || BigInt(value) < 1n)) { + throw new Error('paired Sparkle feed has no valid build floor'); + } + return versions.reduce((highest, value) => BigInt(value) > BigInt(highest) ? value : highest); +} + +function appcastFloor(url) { + if (!url.startsWith('https://')) throw new Error('paired Sparkle feed must use HTTPS'); + const child = spawnSync('curl', [ + '-fsSL', '--proto', '=https', '--proto-redir', '=https', '--connect-timeout', '10', + '--max-time', '30', '--max-filesize', '5000000', url, + ], {encoding: 'utf8', maxBuffer: 5 * 1024 * 1024}); + if (child.error || child.status !== 0) throw new Error('paired Sparkle feed is unavailable'); + return parseAppcastFloor(child.stdout); +} + +export function releaseMetadata({rootDir = root, date = mergeDate(rootDir), auth = privateAuth(), feedFloor} = {}) { + const app = registry(rootDir); + const mergeStamp = chicagoMergeStamp(date); + const floor = feedFloor ?? appcastFloor(app.pairedBuildFeed); + if (!/^[1-9]\d{0,11}$/.test(String(floor))) throw new Error('invalid paired build floor'); + const releasedVersion = runASC(rootDir, 'released-store-version', [app.bundleId, 'IOS'], auth); + const marketingVersion = latestFixedMarketingVersion(app.fixedMarketingVersion, releasedVersion); + const buildVersion = runASC(rootDir, 'plan-release-build', releaseBuildPlannerArgs(app, floor, mergeStamp), auth); + if (!/^[1-9]\d{11}$/.test(buildVersion)) throw new Error('ASC planner returned an invalid shared build'); + return {marketingVersion, buildVersion}; +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { + try { + const mode = process.argv[2] || 'release'; + const rootDir = process.argv[3] || root; + const result = mode === 'offline' + ? offlineBuildMetadata({mergeDate: mergeDate(rootDir), fixedVersion: registry(rootDir).fixedMarketingVersion}) + : mode === 'release' + ? releaseMetadata({rootDir}) + : (() => { throw new Error('mode must be offline or release'); })(); + process.stdout.write(`${result.marketingVersion}\t${result.buildVersion}\n`); + } catch (error) { + const message = error instanceof Error ? error.message : 'version planning failed'; + process.stderr.write(`Mac release version planning failed: ${message}\n`); + process.exitCode = 1; + } +} diff --git a/scripts/mac-release-workflow.test.mjs b/scripts/mac-release-workflow.test.mjs index c9715f1b..09ee75de 100644 --- a/scripts/mac-release-workflow.test.mjs +++ b/scripts/mac-release-workflow.test.mjs @@ -1,11 +1,12 @@ // Credential-free contract and mocked notarization preflight tests. import assert from 'node:assert/strict'; -import {readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync, readdirSync} from 'node:fs'; +import {readFileSync, mkdtempSync, mkdirSync, writeFileSync, chmodSync, rmSync, readdirSync} from 'node:fs'; import {tmpdir} from 'node:os'; import {join} from 'node:path'; import {fileURLToPath} from 'node:url'; import {spawnSync} from 'node:child_process'; import test from 'node:test'; +import {chicagoMergeStamp, latestFixedMarketingVersion, offlineBuildMetadata, parseAppcastFloor, planSharedBuild, releaseBuildPlannerArgs} from './mac-release-version.mjs'; const root = fileURLToPath(new URL('../', import.meta.url)); const read = p => readFileSync(join(root, p), 'utf8'); const workflow = read('.github/workflows/mac-release.yml'); @@ -295,3 +296,92 @@ test('the Sentry upload keeps the full-scope token away from the installer and r assert.match(sentry, /SENTRY_AUTH_TOKEN="\$TOKEN" SENTRY_PROJECT="\$project" \\\n\s+sentry-cli debug-files upload /); assert.match(sentry, /\*:\/\/\*\|\*@\*\)\n[^\n]*looks like a DSN[^\n]*\n\s+exit 1/); }); + + +test('Mac release versions use Chicago merge timestamps and the shared rebuild floor', () => { + const mergeDate = new Date('2026-10-29T14:30:00Z'); + const stamp = chicagoMergeStamp(mergeDate); + assert.equal(stamp, '202610290930'); + assert.match(stamp, /^[1-9][0-9]{11}$/); + assert.equal(chicagoMergeStamp(new Date(mergeDate)), stamp, 'the same commit date plans deterministically'); + assert.equal(planSharedBuild({mergeStamp: stamp}), stamp); + assert.equal(planSharedBuild({mergeStamp: stamp}), stamp, 'a repeat plan with unchanged inventory reuses the same shared build'); + assert.equal(planSharedBuild({mergeStamp: stamp, iosBuilds: [stamp]}), '202610290931'); + assert.equal(planSharedBuild({mergeStamp: stamp, macBuilds: [stamp]}), '202610290931'); + assert.equal(chicagoMergeStamp(new Date('2026-11-03T12:00:00Z')), '202611030600', + 'the conversion observes Chicago standard time after daylight saving ends'); +}); + +test('Mac marketing version keeps the registry default unless ASC proves a higher approved version', () => { + assert.equal(latestFixedMarketingVersion('0.1.0'), '0.1.0'); + assert.equal(latestFixedMarketingVersion('0.1.0', ''), '0.1.0'); + assert.equal(latestFixedMarketingVersion('0.1.0', '0.0.9'), '0.1.0'); + assert.equal(latestFixedMarketingVersion('0.1.0', '0.1.0'), '0.1.0'); + assert.equal(latestFixedMarketingVersion('0.1.0', '1.0'), '1.0', + 'ASC can return an approved two-component marketing version, which must be preserved'); + const approved = latestFixedMarketingVersion('0.1.0', '1.0.302'); + assert.equal(approved, '1.0.302'); + assert.equal(latestFixedMarketingVersion('0.1.0', '1.0.302'), approved, + 're-reading the same approved version does not bump or rewrite the train'); + assert.deepEqual(offlineBuildMetadata({mergeDate: new Date('2026-10-29T14:30:00Z')}), { + marketingVersion: '0.1.0', buildVersion: '202610290930', + }); + assert.throws(() => latestFixedMarketingVersion('0.1', '1.0.0'), /invalid marketing version/); + assert.throws(() => latestFixedMarketingVersion('0.1', '1.0'), /invalid marketing version/); + assert.throws(() => latestFixedMarketingVersion('0.1.0', 'not-a-version'), /invalid marketing version/); + assert.throws(() => latestFixedMarketingVersion('0.1.0', '1.0.302.1'), /invalid marketing version/); + assert.equal(parseAppcastFloor('210202610290930'), + '202610290930'); + assert.throws(() => parseAppcastFloor('1234567890123'), /no valid build floor/); +}); + +test('Mac shared build planning includes the registered paired app before its feed floor', () => { + assert.deepEqual(releaseBuildPlannerArgs({bundleId: 'com.example.ios', pairedBundleId: 'com.example.mac'}, '73', '202611030600'), + ['com.example.ios', 'com.example.mac', '73', '--merge-stamp', '202611030600']); + assert.deepEqual(releaseBuildPlannerArgs({bundleId: 'com.example.ios', macBundleId: 'com.example.mac'}, '73', '202611030600'), + ['com.example.ios', 'com.example.mac', '73', '--merge-stamp', '202611030600']); + assert.deepEqual(releaseBuildPlannerArgs({bundleId: 'com.example.ios'}, '73', '202611030600'), + ['com.example.ios', '73', '--merge-stamp', '202611030600']); +}); + +test('the build script accepts approved short marketing versions and caches the one planner result', () => { + const builder = read('script/build_and_run.sh'); + const start = builder.indexOf('VERSION_PLAN_READY=0\n'); + const end = builder.indexOf('\nshort_version() {', start); + assert.ok(start >= 0 && end > start, 'extract only the version helper, never source the build script'); + const versionHelper = builder.slice(start, end); + for (const marketingVersion of ['1.0', '1.0.302']) { + const temp = mkdtempSync(join(tmpdir(), 'codecaps-version-shell-')); + try { + const bin = join(temp, 'bin'); + mkdirSync(bin); + const nodeStub = join(bin, 'node'); + writeFileSync(nodeStub, '#!/bin/sh\nprintf called >> "$PLAN_CALLS"\nprintf "%s\\n" "$PLAN_OUTPUT"\n'); + chmodSync(nodeStub, 0o700); + const calls = join(temp, 'calls'); + const script = `${versionHelper}\nMODE=--dev\nROOT_DIR=/fixture\nprepare_build_versions\nprepare_build_versions\nprintf '%s\\t%s\\n' "$BUILD_MARKETING_VERSION" "$BUILD_BUNDLE_VERSION"\n`; + const result = spawnSync('bash', ['-c', script], { + encoding: 'utf8', env: {...process.env, PATH: `${bin}:${process.env.PATH}`, PLAN_CALLS: calls, + PLAN_OUTPUT: `${marketingVersion}\t202611030600`}, + }); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.trim(), `${marketingVersion}\t202611030600`); + assert.equal(readFileSync(calls, 'utf8'), 'called', 'the planner runs once and the cached plan serves subsequent calls'); + } finally { + rmSync(temp, {recursive: true, force: true}); + } + } +}); + +test('the Mac release builder fails closed on missing shared planning and no longer uses commit counts', () => { + const builder = read('script/build_and_run.sh'); + const planner = read('scripts/mac-release-version.mjs'); + assert.match(builder, /mac-release-version\.mjs/); + assert.match(builder, /no bundle was built/); + assert.match(builder, /prepare_build_versions \|\| exit 1\n local arch_flags=\(\)/, + 'build_and_stage must validate and cache the shared plan before starting Swift build actions'); + assert.doesNotMatch(builder, /git -C "\$ROOT_DIR" rev-list --count HEAD/); + assert.match(planner, /plan-release-build/); + assert.match(planner, /released-store-version/); + assert.match(planner, /pairedBuildFeed/); +}); From 35761ace9d48a60af981d0d5fe67947452b7af01 Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:28:43 +0000 Subject: [PATCH 05/12] Fix Provider Credential Boundaries And Alert Review Findings --- .gitleaksignore | 3 + Sources/CodeCaps/MonitorModel.swift | 38 ++-- Sources/QuotaCore/KimiQuotaReader.swift | 145 ++++++++++---- Sources/QuotaCore/MuseCodeSessionReader.swift | 32 ++- Sources/QuotaCore/TwilioSMSClient.swift | 15 +- Sources/QuotaCore/ZCodeQuotaReader.swift | 4 + Tests/CodeCapsTests/MuseCodePluginTests.swift | 46 +++++ .../PlatformLogoResourceTests.swift | 15 +- .../QuotaCoreTests/KimiQuotaReaderTests.swift | 187 ++++++++++++++++++ .../MuseCodeSessionReaderTests.swift | 40 ++++ .../QuotaCoreTests/TwilioSMSClientTests.swift | 6 + .../ZCodeQuotaReaderTests.swift | 19 ++ 12 files changed, 487 insertions(+), 63 deletions(-) diff --git a/.gitleaksignore b/.gitleaksignore index cb75a39b..1644f692 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -13,3 +13,6 @@ # other rule stays active, and a real credential in this repository is still # caught. 053e42631eaf6389365bbb37dedb2d67143ca2f6:scripts/install-release-secrets-tooling.sh:generic-api-key:38 + +# The flagged line validates a runtime-supplied secret and contains no secret value.  This exception pins only its commit, path, rule, and line. +0aeb73d1c51baabd9a26fa13d807b10bb22cc693:Sources/QuotaCore/TwilioSMSClient.swift:generic-api-key:76 diff --git a/Sources/CodeCaps/MonitorModel.swift b/Sources/CodeCaps/MonitorModel.swift index 8dbded8b..0e15271d 100644 --- a/Sources/CodeCaps/MonitorModel.swift +++ b/Sources/CodeCaps/MonitorModel.swift @@ -652,6 +652,7 @@ final class MonitorModel: ObservableObject { var museCodeTokenSaveForTesting: (@MainActor (String) async throws -> Void)? var museCodeTokenDeleteForTesting: (@MainActor () async throws -> Void)? var museCodeTokenReauthorizeForTesting: (@MainActor () async -> String?)? + var museCodeAlertSynchronizeForTesting: (@MainActor (String) -> Bool)? private var museCodeBridgeGeneration: UInt64 = 0 private var museCodeBridgeTask: Task? private var museCodePendingBridgeReport: MuseCodeSessionReport? @@ -3235,12 +3236,13 @@ final class MonitorModel: ObservableObject { museCodeBurnAlert = burn if let burn, now.timeIntervalSince1970 - lastMuseCodeBurnAlertAt >= MuseCodeBurnMonitor.alertCooldown { - lastMuseCodeBurnAlertAt = now.timeIntervalSince1970 - defaults.set(lastMuseCodeBurnAlertAt, forKey: "museCodeBurnLastSent") - guard defaults.synchronize() else { return } - alertDispatcher.emit(CodeCapsAlertEvent( - kind: .museCodeBurn, title: burn.title, body: burn.body, - identifier: "codecaps.musecode.burn." + UUID().uuidString, occurredAt: report.generatedAt)) + let candidateSentAt = now.timeIntervalSince1970 + if saveMuseCodeAlertState(candidateSentAt, key: "museCodeBurnLastSent") { + lastMuseCodeBurnAlertAt = candidateSentAt + alertDispatcher.emit(CodeCapsAlertEvent( + kind: .museCodeBurn, title: burn.title, body: burn.body, + identifier: "codecaps.musecode.burn." + UUID().uuidString, occurredAt: report.generatedAt)) + } } // The contributor finding is its own alert kind, independent of the // burn threshold, and it is an event, not a share: the detector @@ -3250,9 +3252,11 @@ final class MonitorModel: ObservableObject { // planned SMS channel is the expected one) never has to piggyback // on the burn alert. Each event carries its own notification // identifier, so two sessions' events never replace each other. - let events = museCodeStandardSessionDetector.observe( - report.currentModelObservations) - guard saveMuseCodeDetectorState() else { return } + var candidateDetector = museCodeStandardSessionDetector + let events = candidateDetector.observe(report.currentModelObservations) + guard let data = try? JSONEncoder().encode(candidateDetector), + saveMuseCodeAlertState(data, key: Self.museCodeDetectorKey) else { return } + museCodeStandardSessionDetector = candidateDetector if let latest = events.last { museCodeStandardSessionAlert = latest } @@ -3264,10 +3268,18 @@ final class MonitorModel: ObservableObject { } } - private func saveMuseCodeDetectorState() -> Bool { - guard let data = try? JSONEncoder().encode(museCodeStandardSessionDetector) else { return false } - defaults.set(data, forKey: Self.museCodeDetectorKey) - return defaults.synchronize() + /// Failed persistence leaves both the live detector/throttle and the cached + /// defaults at their previous state, so a later poll can attempt the event. + private func saveMuseCodeAlertState(_ value: Any, key: String) -> Bool { + let previous = defaults.object(forKey: key) + defaults.set(value, forKey: key) + let saved = museCodeAlertSynchronizeForTesting?(key) ?? defaults.synchronize() + guard saved else { + if let previous { defaults.set(previous, forKey: key) } + else { defaults.removeObject(forKey: key) } + return false + } + return true } /// One worker plans, posts, and commits baselines in order. diff --git a/Sources/QuotaCore/KimiQuotaReader.swift b/Sources/QuotaCore/KimiQuotaReader.swift index a996b29d..2ccf55ed 100644 --- a/Sources/QuotaCore/KimiQuotaReader.swift +++ b/Sources/QuotaCore/KimiQuotaReader.swift @@ -37,6 +37,7 @@ public struct KimiQuotaReader: Sendable { public func read() async -> LocalQuotaResult { do { + try Task.checkCancellation() guard let token = accessToken(), !token.isEmpty else { // No local sign-in at all: the product is simply absent, the // same way a missing `gh` binary is not a Copilot error. @@ -45,6 +46,7 @@ public struct KimiQuotaReader: Sendable { var lastStatus = 0 var sawTransportError = false for url in Self.usageURLs { + try Task.checkCancellation() let result: KimiHTTPPayload do { result = try await Self.fetchUsage(url: url, token: token, fetch: fetch) @@ -53,6 +55,7 @@ public struct KimiQuotaReader: Sendable { // rethrow so the outer catch reports the cancellation. throw CancellationError() } catch { + if Task.isCancelled || (error as? URLError)?.code == .cancelled { throw CancellationError() } // One unreachable host must not mask a healthy second one. sawTransportError = true continue @@ -162,7 +165,7 @@ private extension KimiQuotaReader { sourceApp: "local-mac", label: label, remainingPercent: percent, absoluteRemaining: remaining, absoluteLimit: limit, - quotaUnit: "requests", + quotaUnit: nil, remainingUnknown: percent == nil, isExhausted: exhausted, resetAt: resetTimestamp(data), @@ -212,13 +215,15 @@ private extension KimiQuotaReader { return nil } - /// Newest credential JSON under the two documented roots, then the - /// `api_key` lines of `config.toml` / `config.json` as a last resort. - static func readLocalAccessToken(home: URL) -> String? { + /// Only the CLI's designated Kimi Code credential is eligible, followed by + /// an explicitly identified Kimi Code provider with an approved coding URL. + internal static func readLocalAccessToken( + home: URL, environment: [String: String] = ProcessInfo.processInfo.environment + ) -> String? { let roots = [ - ProcessInfo.processInfo.environment["KIMI_CODE_HOME"].map { URL(fileURLWithPath: $0) } + environment["KIMI_CODE_HOME"].map { URL(fileURLWithPath: $0) } ?? home.appendingPathComponent(".kimi-code"), - ProcessInfo.processInfo.environment["KIMI_SHARE_DIR"].map { URL(fileURLWithPath: $0) } + environment["KIMI_SHARE_DIR"].map { URL(fileURLWithPath: $0) } ?? home.appendingPathComponent(".kimi"), ] let manager = FileManager.default @@ -226,11 +231,8 @@ private extension KimiQuotaReader { // root must beat a stale file in the first. var candidates: [URL] = [] for root in roots { - let directory = root.appendingPathComponent("credentials") - if let names = try? manager.contentsOfDirectory(atPath: directory.path) { - candidates += names.filter { $0.hasSuffix(".json") } - .map { directory.appendingPathComponent($0) } - } + let candidate = root.appendingPathComponent("credentials/kimi-code.json") + if manager.fileExists(atPath: candidate.path) { candidates.append(candidate) } } candidates.sort { lhs, rhs in let l = (try? manager.attributesOfItem(atPath: lhs.path)[.modificationDate] as? Date) ?? nil @@ -249,7 +251,11 @@ private extension KimiQuotaReader { static func credentialToken(at url: URL) -> String? { guard let data = try? Data(contentsOf: url, options: .mappedIfSafe), data.count <= Self.maxCredentialBytes, let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil } - guard let token = string(root["access_token"]), validToken(token) else { return nil } + // Extract the raw string, NOT via the label-capped string() helper: + // that helper caps at 160 bytes for display names, and a real OAuth + // access token is routinely far longer - routing it through the cap + // silently read a signed-in account as "no local sign-in". + guard let token = root["access_token"] as? String, validToken(token) else { return nil } // A token whose recorded expiry has passed is only going to earn a // 401; the CLI refreshes it on next use, so report the stored one // anyway and let the server answer. @@ -258,33 +264,95 @@ private extension KimiQuotaReader { internal static func configToken(root: URL) -> String? { if let data = try? Data(contentsOf: root.appendingPathComponent("config.toml"), options: .mappedIfSafe), - data.count <= Self.maxCredentialBytes, - let text = String(data: data, encoding: .utf8) { - for line in text.split(separator: "\n") { + data.count <= Self.maxCredentialBytes, let text = String(data: data, encoding: .utf8) { + var providers: [(name: String, fields: [String: String])] = [] + var currentName: String? + var fields: [String: String] = [:] + for line in text.split(separator: "\n", omittingEmptySubsequences: false) { let trimmed = line.trimmingCharacters(in: .whitespaces) - guard let equals = trimmed.firstIndex(of: "=") else { continue } - let key = trimmed[trimmed.startIndex.. String? { + var fields: [String: String] = [:] + fields["type"] = object["type"] as? String + fields["base_url"] = (object["base_url"] ?? object["baseUrl"]) as? String + fields["api_key"] = (object["api_key"] ?? object["apiKey"]) as? String + return providerToken(name: name, fields: fields) + } + + private static func providerToken(name: String, fields: [String: String]) -> String? { + let explicitlyKimi = ["managed:kimi-code", "kimi-code", "kimi"].contains(name) || fields["type"] == "kimi" + guard explicitlyKimi, let base = fields["base_url"], approvedCodingBase(base), + let token = fields["api_key"], validToken(token) else { return nil } + return token + } + + private static func approvedCodingBase(_ raw: String) -> Bool { + guard let url = URLComponents(string: raw), url.scheme == "https", + let host = url.host?.lowercased(), ["api.kimi.com", "api.kimi.ai"].contains(host), + url.port == nil || url.port == 443, url.user == nil, url.password == nil, + url.query == nil, url.fragment == nil else { return false } + return ["/coding/v1", "/coding/v1/"].contains(url.percentEncodedPath) + } + + /// A narrow TOML reader accepts only provider tables and quoted scalars. + /// Unknown tables, multiline strings, and ambiguous syntax fail closed. + private static func providerTableName(_ line: String) -> String? { + let pattern = #"^\[\s*providers\s*\.\s*(?:"([^"\\]+)"|'([^']+)'|([A-Za-z0-9_-]+))\s*\]\s*(?:#.*)?$"# + guard let regex = try? NSRegularExpression(pattern: pattern), + let match = regex.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)) else { return nil } + for index in 1...3 { + if let range = Range(match.range(at: index), in: line) { return String(line[range]) } + } + return nil + } + + private static func tomlString(_ raw: String) -> String? { + let value = raw.trimmingCharacters(in: .whitespaces) + guard let quote = value.first, quote == "\"" || quote == "'" else { return nil } + var escaped = false + for index in value.indices.dropFirst() { + let character = value[index] + if quote == "\"", character == "\\", !escaped { escaped = true; continue } + if character == quote, !escaped { + let tail = value[value.index(after: index)...].trimmingCharacters(in: .whitespaces) + guard tail.isEmpty || tail.hasPrefix("#") else { return nil } + if quote == "'" { return String(value[value.index(after: value.startIndex).. Double? { - guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), - number.doubleValue.isFinite, number.doubleValue >= 0 else { return nil } - return number.doubleValue + let parsed: Double? + if let text = value as? String { + parsed = Double(text.trimmingCharacters(in: .whitespacesAndNewlines)) + } else if let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() { + parsed = number.doubleValue + } else { parsed = nil } + guard let parsed, parsed.isFinite, parsed >= 0 else { return nil } + return parsed } internal static func int(_ value: Any?) -> Int? { diff --git a/Sources/QuotaCore/MuseCodeSessionReader.swift b/Sources/QuotaCore/MuseCodeSessionReader.swift index 9060b2af..078d9fcc 100644 --- a/Sources/QuotaCore/MuseCodeSessionReader.swift +++ b/Sources/QuotaCore/MuseCodeSessionReader.swift @@ -25,11 +25,13 @@ public struct MuseCodeTokenSegment: Equatable, Sendable { self.sourceLastId = sourceLastId } - /// The segment's identity inside its session, matching the dedupe key the - /// survey scripts use: (sourceRange first id, last id, model, total). + /// The segment's identity inside its session is its exact source range and model.  Its total is a high-water + /// value, not part of identity, when both boundaries exist.  If either boundary is absent, the total remains + /// in the key because the reader cannot safely prove those observations belong to the same segment. public var dedupeKey: String { - [sourceFirstId ?? "", sourceLastId ?? "", modelId, String(totalTokens)] - .joined(separator: "\u{1}") + var parts = [sourceFirstId ?? "", sourceLastId ?? "", modelId] + if sourceFirstId == nil || sourceLastId == nil { parts.append(String(totalTokens)) } + return parts.joined(separator: "\u{1}") } public var isContributor: Bool { modelId.hasSuffix("-contributor") } @@ -361,11 +363,23 @@ public struct MuseCodeSessionReader: Sendable { // that ends mid-window leaves only the segments still on disk. Every // total this aggregation produces is therefore a floor, not an exact // count — the plugin page says so wherever it shows these numbers. - var seen = Set() - var segments: [MuseCodeTokenSegment] = [] - for segment in raw.sorted(by: { $0.observedAt < $1.observedAt }) { - guard seen.insert(segment.sessionId + "\u{1}" + segment.dedupeKey).inserted else { continue } - segments.append(segment) + var highWaterBySegment: [String: MuseCodeTokenSegment] = [:] + for candidate in raw { + let key = candidate.sessionId + "\u{1}" + candidate.dedupeKey + guard let current = highWaterBySegment[key] else { + highWaterBySegment[key] = candidate + continue + } + if candidate.totalTokens > current.totalTokens + || (candidate.totalTokens == current.totalTokens && candidate.observedAt > current.observedAt) { + highWaterBySegment[key] = candidate + } + } + let segments = highWaterBySegment.values.sorted { left, right in + if left.observedAt != right.observedAt { return left.observedAt < right.observedAt } + if left.sessionId != right.sessionId { return left.sessionId < right.sessionId } + if left.modelId != right.modelId { return left.modelId < right.modelId } + return left.dedupeKey < right.dedupeKey } let horizon = now.addingTimeInterval(futureTolerance) let windows = windowMinutes.map { minutes -> MuseCodeWindowUsage in diff --git a/Sources/QuotaCore/TwilioSMSClient.swift b/Sources/QuotaCore/TwilioSMSClient.swift index ca86f943..f02dfc67 100644 --- a/Sources/QuotaCore/TwilioSMSClient.swift +++ b/Sources/QuotaCore/TwilioSMSClient.swift @@ -152,7 +152,20 @@ public struct TwilioSMSClient: Sendable { } private static func formEncode(_ value: String) -> String { - value.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"))! + let hex = Array("0123456789ABCDEF".utf8) + var encoded: [UInt8] = [] + encoded.reserveCapacity(value.utf8.count) + for byte in value.utf8 { + switch byte { + case 48...57, 65...90, 97...122, 45, 46, 95, 126: + encoded.append(byte) + default: + encoded.append(37) + encoded.append(hex[Int(byte >> 4)]) + encoded.append(hex[Int(byte & 0x0F)]) + } + } + return String(decoding: encoded, as: UTF8.self) } public static let liveTransport: Transport = { request in diff --git a/Sources/QuotaCore/ZCodeQuotaReader.swift b/Sources/QuotaCore/ZCodeQuotaReader.swift index 287a0f7c..00515428 100644 --- a/Sources/QuotaCore/ZCodeQuotaReader.swift +++ b/Sources/QuotaCore/ZCodeQuotaReader.swift @@ -35,6 +35,7 @@ public struct ZCodeQuotaReader: Sendable { public func read() async -> LocalQuotaResult { do { + try Task.checkCancellation() let store = credentials() // z.ai first: the desktop sign-in is a Z.ai account; the BigModel // token is the China-side equivalent of the same plan. @@ -45,6 +46,7 @@ public struct ZCodeQuotaReader: Sendable { var sawCredential = false var rejected = false for candidate in candidates { + try Task.checkCancellation() guard let token = store[candidate.key], Self.validToken(token) else { continue } sawCredential = true let result: ZCodeHTTPPayload @@ -55,6 +57,7 @@ public struct ZCodeQuotaReader: Sendable { // rethrow so the outer catch reports the cancellation. throw CancellationError() } catch { + if Task.isCancelled || (error as? URLError)?.code == .cancelled { throw CancellationError() } // One unreachable endpoint must not mask a healthy second // account. continue @@ -117,6 +120,7 @@ private extension ZCodeQuotaReader { // readers disagree and prepend `Bearer`, so a bare-credential 401 is // retried once with the prefix before the session is called rejected. for attempt in 0..<2 { + try Task.checkCancellation() var request = URLRequest(url: url) request.httpMethod = "GET" request.cachePolicy = .reloadIgnoringLocalCacheData diff --git a/Tests/CodeCapsTests/MuseCodePluginTests.swift b/Tests/CodeCapsTests/MuseCodePluginTests.swift index 18a20fa6..648fb99a 100644 --- a/Tests/CodeCapsTests/MuseCodePluginTests.swift +++ b/Tests/CodeCapsTests/MuseCodePluginTests.swift @@ -221,6 +221,52 @@ final class MuseCodePluginTests: XCTestCase { XCTAssertEqual(Set(ids).count, 2) } + func testFailedBurnPersistenceDoesNotBlockStandardAlertOrConsumeTheBurnCooldown() { + let (model, spy) = makeModel() + var burnSaveFails = true + model.museCodeAlertSynchronizeForTesting = { key in + !(key == "museCodeBurnLastSent" && burnSaveFails) + } + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeStandardSession]) + XCTAssertNil(defaults.object(forKey: "museCodeBurnLastSent")) + burnSaveFails = false + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeStandardSession, .museCodeBurn]) + } + + func testFailedDetectorPersistenceLeavesTheStandardEventEligibleWithoutRepeatingBurn() { + let (model, spy) = makeModel() + var detectorSaveFails = true + model.museCodeAlertSynchronizeForTesting = { key in + !(key == "museCodeStandardSessionDetector" && detectorSaveFails) + } + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeBurn]) + XCTAssertNil(defaults.object(forKey: "museCodeStandardSessionDetector")) + detectorSaveFails = false + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeBurn, .museCodeStandardSession]) + } + + func testPersistenceFailureDoesNotConsumeAContributorToStandardRearmAcrossRecreation() { + let (model, spy) = makeModel() + let contributor = MuseCodeSessionObservation(sessionId: "s1", snapshotId: "contributor", + modelId: "muse-spark-contributor", totalTokens: 100, segmentKey: "segment", observedAt: Date()) + let standard = MuseCodeSessionObservation(sessionId: "s1", snapshotId: "standard", + modelId: "muse-wonder", totalTokens: 100, segmentKey: "segment", observedAt: Date()) + model.applyMuseCodeResult(result(total: 100, contributor: 100, observations: [contributor])) + model.museCodeAlertSynchronizeForTesting = { _ in false } + model.applyMuseCodeResult(result(total: 100, contributor: 0, observations: [standard])) + XCTAssertTrue(spy.events.isEmpty) + let (relaunched, relaunchedSpy) = makeModel() + relaunched.applyMuseCodeResult(result(total: 100, contributor: 0, observations: [standard])) + relaunched.applyMuseCodeResult(result(total: 100, contributor: 0, observations: [standard])) + XCTAssertEqual(relaunchedSpy.events.map(\.kind), [.museCodeStandardSession]) + } + // MARK: - Bridge func testBridgePostsDeltasOnceAndAdvancesBaseline() async { diff --git a/Tests/CodeCapsTests/PlatformLogoResourceTests.swift b/Tests/CodeCapsTests/PlatformLogoResourceTests.swift index f7df49d2..6ee37108 100644 --- a/Tests/CodeCapsTests/PlatformLogoResourceTests.swift +++ b/Tests/CodeCapsTests/PlatformLogoResourceTests.swift @@ -58,11 +58,18 @@ final class PlatformLogoResourceTests: XCTestCase { let kimiStandard = try XCTUnwrap(PlatformLogoImage.load(providerKey: "kimi", style: .standard)) XCTAssertFalse(kimiStandard.isTemplate, "Kimi Standard must preserve its supplied blue artwork") let colorPixels = try XCTUnwrap(kimiStandard.representations.first as? NSBitmapImageRep) - let bluePixel = (0.. 0.95 && color.blueComponent > color.redComponent * 1.5 { + bluePixel = color + break pixelRows + } } - }.first { $0.alphaComponent > 0.95 && $0.blueComponent > $0.redComponent * 1.5 } + } XCTAssertNotNil(bluePixel, "Kimi Standard must contain the supplied blue mark") XCTAssertTrue(try XCTUnwrap(PlatformLogoImage.load(providerKey: "kimi", style: .template)).isTemplate) diff --git a/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift b/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift index c180646b..d4c5cfc6 100644 --- a/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift +++ b/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift @@ -32,6 +32,7 @@ final class KimiQuotaReaderTests: XCTestCase { XCTAssertEqual(window.remainingPercent, 75) XCTAssertEqual(window.absoluteRemaining, 75) XCTAssertEqual(window.absoluteLimit, 100) + XCTAssertNil(window.quotaUnit, "The provider does not establish a physical unit for these quota counters") XCTAssertEqual(window.resetAt, "2026-11-08T00:00:00Z") XCTAssertEqual(window.status, .available) XCTAssertFalse(window.isExhausted) @@ -111,14 +112,200 @@ final class KimiQuotaReaderTests: XCTestCase { XCTAssertEqual(result.windows[0].remainingPercent, 75) } + func testCredentialFileAcceptsRealLengthOauthToken() throws { + // Regression: the shared label helper caps at 160 bytes, which read a + // real signed-in account (OAuth tokens are routinely far longer) as + // "no local sign-in" - empty windows with no issue. The credential + // path must use only the token predicate (8 KB, no CR/LF). + let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let credentials = home.appendingPathComponent(".kimi-code/credentials") + try FileManager.default.createDirectory(at: credentials, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + let token = "eyJ" + String(repeating: "a", count: 500) + try """ + {"access_token": "\(token)", "refresh_token": "r", "expires_at": 1, "scope": "s", "token_type": "Bearer", "expires_in": 1} + """.write(to: credentials.appendingPathComponent("kimi-code.json"), atomically: true, encoding: .utf8) + XCTAssertEqual(KimiQuotaReader.readLocalAccessToken(home: home, environment: [:]), token) + } + + func testCredentialFileRejectsOversizedAndMultilineTokens() throws { + let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let credentials = home.appendingPathComponent(".kimi-code/credentials") + try FileManager.default.createDirectory(at: credentials, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + let oversized = String(repeating: "a", count: 8_193) + try """ + {"access_token": "\(oversized)"} + """.write(to: credentials.appendingPathComponent("kimi-code.json"), atomically: true, encoding: .utf8) + XCTAssertNil(KimiQuotaReader.readLocalAccessToken(home: home, environment: [:]), "beyond the 8 KB token bound is not a credential") + try """ + {"access_token": "line1\\nline2"} + """.write(to: credentials.appendingPathComponent("kimi-code.json"), atomically: true, encoding: .utf8) + XCTAssertNil(KimiQuotaReader.readLocalAccessToken(home: home, environment: [:]), "a CR/LF in the value is not a credential") + } + func testConfigTomlRequiresExactKeyAndStripsInlineComment() throws { let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: home) } try """ + [providers."managed:kimi-code"] + type = "kimi" + base_url = "https://api.kimi.com/coding/v1" api_key_backup = "wrong-token" api_key = "sk-test-token" # rotated """.write(to: home.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8) XCTAssertEqual(KimiQuotaReader.configToken(root: home), "sk-test-token") } + func testOfficialNumericStringCountersAndDurationProduceQuotaWindows() async { + let result = await read(#"{"usage":{"limit":"100","used":"29","remaining":"71"},"limits":[{"window":{"duration":"300","timeUnit":"TIME_UNIT_MINUTE"},"detail":{"limit":"100","remaining":"12"}}]}"#) + XCTAssertTrue(result.issues.isEmpty) + XCTAssertEqual(result.windows.count, 2) + XCTAssertEqual(result.windows.first?.remainingPercent, 71) + XCTAssertEqual(result.windows.last?.remainingPercent, 12) + XCTAssertEqual(result.windows.last?.window, "5h") + } + + func testNumericStringsPreserveFiniteNonnegativeAndExactIntegerGuards() async { + XCTAssertEqual(KimiQuotaReader.int("300"), 300) + XCTAssertEqual(KimiQuotaReader.int(" 5 "), 5) + let invalid: [Any?] = [nil, true, false, "NaN", "inf", "-1", "5.5", "1e309", "9223372036854775808"] + for value in invalid { XCTAssertNil(KimiQuotaReader.int(value)) } + let result = await read(#"{"usage":{"limit":"NaN","used":true},"limits":[{"detail":{"limit":"-1","used":"Infinity"}}]}"#) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["kimi"], "Kimi returned no readable quota.") + } + + func testOtherProviderKeyCannotReachTheKimiTransport() async throws { + let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let root = home.appendingPathComponent(".kimi-code") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + try """ + [providers.openai] + type = "openai" + base_url = "https://api.openai.com/v1" + api_key = "other-provider-fixture" + [services.moonshot_search] + api_key = "service-fixture" + """.write(to: root.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8) + let result = await KimiQuotaReader(accessToken: { + KimiQuotaReader.readLocalAccessToken(home: home, environment: [:]) + }, fetch: { _ in + XCTFail("An unrelated provider or service credential must never reach a Kimi request") + throw URLError(.badURL) + }).read() + XCTAssertTrue(result.windows.isEmpty) + XCTAssertTrue(result.issues.isEmpty) + } + + func testMultipleProvidersSelectTheExplicitKimiCodingProvider() async throws { + let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let root = home.appendingPathComponent(".kimi-code") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + try """ + [providers.anthropic] + type = "anthropic" + base_url = "https://api.anthropic.com/v1" + api_key = "other-provider-fixture" + [providers."managed:kimi-code"] + type = "kimi" + api_key = "kimi-fixture" + base_url = "https://api.kimi.ai/coding/v1/" + [services.moonshot_fetch] + api_key = "service-fixture" + """.write(to: root.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8) + let counter = KimiRequestCounter() + let result = await KimiQuotaReader(accessToken: { + KimiQuotaReader.readLocalAccessToken(home: home, environment: [:]) + }, fetch: { request in + await counter.increment() + XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer kimi-fixture") + return (Data(#"{"usage":{"limit":"100","remaining":"75"}}"#.utf8), + HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }).read() + XCTAssertEqual(result.windows.first?.remainingPercent, 75) + let count = await counter.count + XCTAssertEqual(count, 1) + } + + func testConfigFallbackRejectsUnscopedKeysAndUnapprovedCodingBases() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + for base in ["http://api.kimi.com/coding/v1", "https://api.kimi.com.evil.invalid/coding/v1", + "https://api.kimi.com/v1", "https://api.kimi.com/coding/v1?redirect=1", + "https://user@api.kimi.com/coding/v1", "https://api.kimi.com:8443/coding/v1"] { + try """ + [providers."managed:kimi-code"] + type = "kimi" + base_url = "\(base)" + api_key = "kimi-fixture" + """.write(to: root.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8) + XCTAssertNil(KimiQuotaReader.configToken(root: root)) + } + try #"api_key = "unscoped-fixture""#.write(to: root.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8) + XCTAssertNil(KimiQuotaReader.configToken(root: root)) + } + + func testConfigJSONAcceptsLongRawKimiTokenButRejectsOtherProvidersAndMalformedTokens() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let file = root.appendingPathComponent("config.json") + let longToken = String(repeating: "a", count: 512) + let kimi: [String: Any] = ["type": "kimi", "base_url": "https://api.kimi.com/coding/v1", "api_key": longToken] + try JSONSerialization.data(withJSONObject: ["providers": ["other": ["type": "openai", "api_key": "foreign-fixture"], + "managed:kimi-code": kimi]]).write(to: file) + XCTAssertEqual(KimiQuotaReader.configToken(root: root), longToken) + for token in [String(repeating: "a", count: 8_193), "first\nsecond", "first\rsecond"] { + var invalid = kimi + invalid["api_key"] = token + try JSONSerialization.data(withJSONObject: ["providers": ["managed:kimi-code": invalid]]).write(to: file) + XCTAssertNil(KimiQuotaReader.configToken(root: root)) + } + try JSONSerialization.data(withJSONObject: ["provider": "openai", "base_url": "https://api.openai.com/v1", "api_key": "foreign-fixture"]).write(to: file) + XCTAssertNil(KimiQuotaReader.configToken(root: root)) + try JSONSerialization.data(withJSONObject: ["provider": "kimi-code", "baseUrl": "https://api.kimi.ai/coding/v1", "apiKey": longToken]).write(to: file) + XCTAssertEqual(KimiQuotaReader.configToken(root: root), longToken) + } + + func testOnlyTheDesignatedOAuthCredentialIsReadAndItPrecedesConfigKeys() throws { + let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let root = home.appendingPathComponent(".kimi-code") + let credentials = root.appendingPathComponent("credentials") + try FileManager.default.createDirectory(at: credentials, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + try JSONSerialization.data(withJSONObject: ["access_token": "foreign-oauth-fixture"]) + .write(to: credentials.appendingPathComponent("another-provider.json")) + XCTAssertNil(KimiQuotaReader.readLocalAccessToken(home: home, environment: [:])) + try JSONSerialization.data(withJSONObject: ["access_token": "kimi-oauth-fixture"]) + .write(to: credentials.appendingPathComponent("kimi-code.json")) + try """ + [providers."managed:kimi-code"] + type = "kimi" + base_url = "https://api.kimi.com/coding/v1" + api_key = "kimi-api-key-fixture" + """.write(to: root.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8) + XCTAssertEqual(KimiQuotaReader.readLocalAccessToken(home: home, environment: [:]), "kimi-oauth-fixture") + } + + func testURLCancellationDoesNotTryTheFallbackHost() async { + let counter = KimiRequestCounter() + let result = await KimiQuotaReader(accessToken: { "fixture-token" }, fetch: { _ in + await counter.increment() + throw URLError(.cancelled) + }).read() + XCTAssertEqual(result.issues["kimi"], "Kimi quota refresh was cancelled.") + let count = await counter.count + XCTAssertEqual(count, 1) + } + +} + + +private actor KimiRequestCounter { + var count = 0 + func increment() { count += 1 } } diff --git a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift index a2979fca..78caa4d7 100644 --- a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift @@ -29,6 +29,46 @@ final class MuseCodeSessionReaderTests: XCTestCase { XCTAssertEqual(report.segments.count, 2) } + func testAggregateUsesHighWaterForRepeatedCumulativeRange() { + let first = segment(model: "muse-wonder-1.0", tokens: 100, + minutesAgo: 10, first: "first", last: "last") + let updated = segment(model: "muse-wonder-1.0", tokens: 200, + minutesAgo: 8, first: "first", last: "last") + let stale = segment(model: "muse-wonder-1.0", tokens: 150, + minutesAgo: 5, first: "first", last: "last") + + let report = MuseCodeSessionReader.aggregate( + segments: [first, updated, stale], sessionActivity: ["s1": now], now: now) + + XCTAssertEqual(report.window(minutes: 90)?.totalTokens, 200, + "cumulative snapshots of one exact source range contribute only their high-water total") + XCTAssertEqual(report.window(minutes: 90)?.models.first?.segmentCount, 1) + XCTAssertEqual(report.segments.first?.totalTokens, 200, + "a later stale snapshot cannot replace the segment high-water") + } + + func testAggregateSumsDistinctRangesSessionsAndModelSwitches() { + let segments = [ + segment(session: "s1", model: "muse-wonder-1.0", tokens: 100, + minutesAgo: 10, first: "shared-start", last: "range-one"), + segment(session: "s1", model: "muse-wonder-1.0", tokens: 50, + minutesAgo: 9, first: "shared-start", last: "range-two"), + segment(session: "s1", model: "muse-spark-1.3-contributor", tokens: 25, + minutesAgo: 8, first: "shared-start", last: "range-one"), + segment(session: "s2", model: "muse-wonder-1.0", tokens: 70, + minutesAgo: 7, first: "shared-start", last: "range-one"), + ] + + let report = MuseCodeSessionReader.aggregate( + segments: segments, sessionActivity: ["s1": now, "s2": now], now: now) + + XCTAssertEqual(report.window(minutes: 90)?.totalTokens, 245) + XCTAssertEqual(report.window(minutes: 90)?.models.first(where: { $0.modelId == "muse-wonder-1.0" })?.tokens, 220) + XCTAssertEqual(report.window(minutes: 90)?.models.first(where: { $0.modelId == "muse-spark-1.3-contributor" })?.tokens, 25) + XCTAssertEqual(report.window(minutes: 90)?.models.first(where: { $0.modelId == "muse-wonder-1.0" })?.sessionCount, 2) + XCTAssertEqual(report.segments.count, 4) + } + func testAggregateWindowsAndContributorShare() { let segments = [ segment(model: "muse-spark-1.3-contributor", tokens: 3_000_000, diff --git a/Tests/QuotaCoreTests/TwilioSMSClientTests.swift b/Tests/QuotaCoreTests/TwilioSMSClientTests.swift index 0b5a484a..e64e11d9 100644 --- a/Tests/QuotaCoreTests/TwilioSMSClientTests.swift +++ b/Tests/QuotaCoreTests/TwilioSMSClientTests.swift @@ -35,6 +35,12 @@ final class TwilioSMSClientTests: XCTestCase { XCTAssertFalse(form.contains("fixture-secret")) } + func testFormEncodingEscapesUnicodeAsUTF8Bytes() throws { + let request = try TwilioSMSClient.request(title: "café ☃️", body: "naïve", credentials: credentials) + let form = try XCTUnwrap(String(data: try XCTUnwrap(request.httpBody), encoding: .utf8)) + XCTAssertTrue(form.contains("CodeCaps%3A%20caf%C3%A9%20%E2%98%83%EF%B8%8F%0Ana%C3%AFve")) + } + func testMessageIsBoundedAndInvalidConfigurationNeverCreatesARequest() throws { let request = try TwilioSMSClient.request(title: String(repeating: "x", count: 500), body: "body", credentials: credentials) let form = String(data: request.httpBody!, encoding: .utf8)! diff --git a/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift b/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift index bcd090c0..b5038fbe 100644 --- a/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift +++ b/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift @@ -142,4 +142,23 @@ final class ZCodeQuotaReaderTests: XCTestCase { XCTAssertEqual(result.windows[0].quotaUnit, "tokens") XCTAssertEqual(result.windows[0].planName, "GLM Coding Max") } + func testURLCancellationDoesNotTryAnotherAuthenticationFormOrAccount() async { + let counter = ZCodeRequestCounter() + let result = await ZCodeQuotaReader(credentials: { + ["oauth:zai:access_token": "fixture-token", "oauth:bigmodel:access_token": "other-fixture-token"] + }, fetch: { _ in + await counter.increment() + throw URLError(.cancelled) + }).read() + XCTAssertEqual(result.issues["zcode"], "ZCode quota refresh was cancelled.") + let count = await counter.count + XCTAssertEqual(count, 1) + } + +} + + +private actor ZCodeRequestCounter { + var count = 0 + func increment() { count += 1 } } From 5a2bdef5331c36ef4eb7822a6127756155744ed4 Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:35:55 +0000 Subject: [PATCH 06/12] Use Scoped Service Tokens In CodeCaps Release Workflows --- .github/workflows/ios-ship.yml | 19 ++++++++-------- .github/workflows/mac-release.yml | 38 +++++++++++++++---------------- 2 files changed, 27 insertions(+), 30 deletions(-) diff --git a/.github/workflows/ios-ship.yml b/.github/workflows/ios-ship.yml index 35e58baa..2a3af355 100644 --- a/.github/workflows/ios-ship.yml +++ b/.github/workflows/ios-ship.yml @@ -229,8 +229,8 @@ jobs: with: names: SENTRY_DSN SENTRY_DSN_CODECAPS SENTRY_AUTH_TOKEN SENTRY_AUTH_TOKEN_FULLSCOPE project-id: ${{ secrets.INFISICAL_FLEET_OPS_PROJECT_ID }} - client-id: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID || secrets.INFISICAL_CLIENT_ID }} - client-secret: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET || secrets.INFISICAL_CLIENT_SECRET }} + secret-path: / + service-token: ${{ secrets.INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN }} env: GH_FALLBACK_SENTRY_DSN: ${{ secrets.SENTRY_DSN }} GH_FALLBACK_SENTRY_DSN_CODECAPS: ${{ secrets.SENTRY_DSN_CODECAPS }} @@ -276,10 +276,10 @@ jobs: # single-line and go to GITHUB_ENV; the multiline private key is staged # to a mode-600 file and only ASC_KEY_PATH is exported. # - # The tooling and the staging script run in ONE step on purpose. The - # tooling installs the Infisical CLI and the fleet's reader onto the - # runner, mints the access token they use, and runs the staging script - # in the same process tree, so the token never touches a file. The + # The tooling and the staging script run in ONE step on purpose.  The + # tooling installs the fleet's reader and passes it the scoped service + # token directly through its environment. The staging script runs in the + # same process tree, so the token never touches a file.  The # staging script is what resolves the three ASC values, and it writes # the private key to a mode-600 file: the key is never an environment # variable of a step, and only that file's path and the two identifiers @@ -291,8 +291,7 @@ jobs: - name: Load and stage the ASC credentials (Fleet-OPS prod /asc) env: INFISICAL_PROJECT_ID: ${{ secrets.INFISICAL_FLEET_OPS_PROJECT_ID }} - INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID || secrets.INFISICAL_CLIENT_ID }} - INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET || secrets.INFISICAL_CLIENT_SECRET }} + INFISICAL_SERVICE_TOKEN: ${{ secrets.INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN }} run: | set +o xtrace set -euo pipefail @@ -304,12 +303,12 @@ jobs: set -euo pipefail for name in ASC_KEY_ID ASC_ISSUER_ID; do if [ -z "${!name:-}" ]; then - echo "::error::Missing $name in Fleet-OPS prod /asc; verify the CI identity has read access to Fleet-OPS prod /asc." >&2 + echo "::error::Missing $name in Fleet-OPS prod /asc; verify the scoped /asc read service token has access to Fleet-OPS prod /asc." >&2 exit 1 fi done if [ -z "${ASC_KEY_PATH:-}" ] || [ ! -s "${ASC_KEY_PATH:-}" ]; then - echo '::error::Missing ASC key material in Fleet-OPS prod /asc; verify the CI identity has read access to Fleet-OPS prod /asc.' >&2 + echo '::error::Missing ASC key material in Fleet-OPS prod /asc; verify the scoped /asc read service token has access to Fleet-OPS prod /asc.' >&2 exit 1 fi - name: Import signing identity diff --git a/.github/workflows/mac-release.yml b/.github/workflows/mac-release.yml index 37b9040f..0716ec7f 100644 --- a/.github/workflows/mac-release.yml +++ b/.github/workflows/mac-release.yml @@ -7,13 +7,13 @@ name: Mac Release (Sparkle) # # Secrets (names only; no value is ever printed): # MAC_CERT_P12_BASE64, MAC_CERT_PASSWORD The Developer ID Application -# certificate for team CC8UTF7ATG. Read from Infisical the way -# BotFleet's release.yml does (INFISICAL_FLEET_OPS_PROJECT_ID plus -# INFISICAL_UNIVERSAL_AUTH_CLIENT_ID/_SECRET, or INFISICAL_CLIENT_ID/ -# _SECRET), with same-named repository secrets as the fallback. +# certificate for team CC8UTF7ATG. Read from Fleet-OPS Infisical prod / +# using INFISICAL_FLEET_OPS_PROJECT_ID and the read-only +# INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN. Same-named repository secrets +# remain a fallback. # ASC_KEY_ID, ASC_ISSUER_ID and the App Store Connect private key come from -# Fleet-OPS Infisical prod /asc, matching ios-ship.yml. Never fall back -# to the stale repository ASC_* secrets. The private key never enters +# Fleet-OPS Infisical prod /asc using that same read-only CI token. +# Never fall back to the stale repository ASC_* secrets. The private key never enters # the job environment: the tooling install and # scripts/stage-asc-key.mjs run in one step, so the key goes from the # fleet's reader straight into a mode-600 file, and only that file's @@ -135,8 +135,8 @@ jobs: with: names: MAC_CERT_P12_BASE64 MAC_CERT_PASSWORD SENTRY_DSN SENTRY_DSN_CODECAPS SENTRY_AUTH_TOKEN SENTRY_AUTH_TOKEN_FULLSCOPE project-id: ${{ secrets.INFISICAL_FLEET_OPS_PROJECT_ID }} - client-id: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID || secrets.INFISICAL_CLIENT_ID }} - client-secret: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET || secrets.INFISICAL_CLIENT_SECRET }} + secret-path: / + service-token: ${{ secrets.INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN }} env: GH_FALLBACK_MAC_CERT_P12_BASE64: ${{ secrets.MAC_CERT_P12_BASE64 }} GH_FALLBACK_MAC_CERT_PASSWORD: ${{ secrets.MAC_CERT_PASSWORD }} @@ -176,10 +176,10 @@ jobs: printf '%s\n' "$msg" >>"$RUNNER_TEMP/mac-release-sentry-dsn-missing" fi - # The tooling and the staging script run in ONE step on purpose. The - # tooling installs the Infisical CLI and the fleet's reader onto the - # runner, mints the access token they use, and runs the staging script - # in the same process tree, so the token never touches a file. The + # The tooling and the staging script run in ONE step on purpose.  The + # tooling installs the fleet's reader and passes it the scoped service + # token directly through its environment. The staging script runs in the + # same process tree, so the token never touches a file.  The # staging script is what resolves the three ASC values, and it writes # the private key to a mode-600 file: the key is never an environment # variable of a step, and only that file's path and the two identifiers @@ -192,8 +192,7 @@ jobs: if: github.event_name != 'pull_request' env: INFISICAL_PROJECT_ID: ${{ secrets.INFISICAL_FLEET_OPS_PROJECT_ID }} - INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID || secrets.INFISICAL_CLIENT_ID }} - INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET || secrets.INFISICAL_CLIENT_SECRET }} + INFISICAL_SERVICE_TOKEN: ${{ secrets.INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN }} run: | set +o xtrace set -euo pipefail @@ -206,12 +205,12 @@ jobs: set -euo pipefail for name in ASC_KEY_ID ASC_ISSUER_ID; do if [ -z "${!name:-}" ]; then - echo "::error::Missing $name in Fleet-OPS prod /asc; verify the CI identity has read access to Fleet-OPS prod /asc." >&2 + echo "::error::Missing $name in Fleet-OPS prod /asc; verify the scoped /asc read service token has access to Fleet-OPS prod /asc." >&2 exit 1 fi done if [ -z "${ASC_KEY_PATH:-}" ] || [ ! -s "${ASC_KEY_PATH:-}" ]; then - echo '::error::Missing ASC key material in Fleet-OPS prod /asc; verify the CI identity has read access to Fleet-OPS prod /asc.' >&2 + echo '::error::Missing ASC key material in Fleet-OPS prod /asc; verify the scoped /asc read service token has access to Fleet-OPS prod /asc.' >&2 exit 1 fi - name: Decide whether this run can publish @@ -513,8 +512,7 @@ jobs: - name: Load and stage the ASC credentials (Fleet-OPS prod /asc) env: INFISICAL_PROJECT_ID: ${{ secrets.INFISICAL_FLEET_OPS_PROJECT_ID }} - INFISICAL_CLIENT_ID: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID || secrets.INFISICAL_CLIENT_ID }} - INFISICAL_CLIENT_SECRET: ${{ secrets.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET || secrets.INFISICAL_CLIENT_SECRET }} + INFISICAL_SERVICE_TOKEN: ${{ secrets.INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN }} run: | set +o xtrace set -euo pipefail @@ -526,12 +524,12 @@ jobs: set -euo pipefail for name in ASC_KEY_ID ASC_ISSUER_ID; do if [ -z "${!name:-}" ]; then - echo "::error::Missing $name in Fleet-OPS prod /asc; verify the CI identity has read access to Fleet-OPS prod /asc." >&2 + echo "::error::Missing $name in Fleet-OPS prod /asc; verify the scoped /asc read service token has access to Fleet-OPS prod /asc." >&2 exit 1 fi done if [ -z "${ASC_KEY_PATH:-}" ] || [ ! -s "${ASC_KEY_PATH:-}" ]; then - echo '::error::Missing ASC key material in Fleet-OPS prod /asc; verify the CI identity has read access to Fleet-OPS prod /asc.' >&2 + echo '::error::Missing ASC key material in Fleet-OPS prod /asc; verify the scoped /asc read service token has access to Fleet-OPS prod /asc.' >&2 exit 1 fi - name: Verify notarization access before building From d0f1d6fae6cb5e550abf230ff50f7e9b57e4b871 Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:37:29 +0000 Subject: [PATCH 07/12] Add Scoped Infisical And Provider Credential Settings --- .github/actions/infisical-secrets/action.yml | 19 +- AGENTS.md | 2 +- INFISICAL.md | 66 +-- README.md | 6 +- Sources/CodeCaps/AppDelegate.swift | 4 +- Sources/CodeCaps/InfisicalIdentityStore.swift | 75 ++-- Sources/CodeCaps/MonitorModel.swift | 22 +- Sources/CodeCaps/SettingsViews.swift | 413 +++++++++--------- .../CodeCaps/ZAIQuotaCredentialStore.swift | 50 +++ Sources/CodeCaps/ZAIQuotaSettingsView.swift | 122 ++++++ Sources/QuotaCore/InfisicalBinding.swift | 102 +++++ Sources/QuotaCore/InfisicalSettings.swift | 150 ++++--- Sources/QuotaCore/KimiQuotaReader.swift | 8 +- .../QuotaCore/LocalQuotaReaderRegistry.swift | 55 ++- Sources/QuotaCore/WidgetPlatformDisplay.swift | 174 +++++++- Sources/QuotaCore/ZCodeQuotaReader.swift | 202 +++------ Tests/CodeCapsTests/CompanionModelTests.swift | 63 ++- .../InfisicalIdentityStoreTests.swift | 40 ++ Tests/CodeCapsTests/ZAIQuotaSetupTests.swift | 113 +++++ Tests/Fixtures/WidgetUIProbe.swift | 56 +++ 20 files changed, 1209 insertions(+), 533 deletions(-) create mode 100644 Sources/CodeCaps/ZAIQuotaCredentialStore.swift create mode 100644 Sources/CodeCaps/ZAIQuotaSettingsView.swift create mode 100644 Sources/QuotaCore/InfisicalBinding.swift create mode 100644 Tests/CodeCapsTests/ZAIQuotaSetupTests.swift diff --git a/.github/actions/infisical-secrets/action.yml b/.github/actions/infisical-secrets/action.yml index 01c54858..37d9f70d 100644 --- a/.github/actions/infisical-secrets/action.yml +++ b/.github/actions/infisical-secrets/action.yml @@ -1,6 +1,6 @@ name: Infisical secrets description: >- - Fetch named secrets from Infisical (universal-auth), mask them, and export + Fetch named secrets from Infisical with a scoped service token, mask them, and export them into $GITHUB_ENV -- falling back to a same-named GH_FALLBACK_ step env var and warning (or failing, for a name listed in `required`) when a name stays empty everywhere. Wraps scripts/infisical-fetch.mjs, a @@ -11,8 +11,8 @@ description: >- workflow command for that exact value, which is what scrubs it from the rendered log from that point on. - Copied from Simple-With-Us/BotFleet on 2026-09-29 for CodeCaps' - mac-release.yml; keep the two copies in step. + Originated as a copy of the fleet action; CodeCaps uses scoped service-token + auth under the current owner policy. NOTE: Usage-Monitor carries a parallel, not-yet-deduplicated copy of this fetch inlined in its own .github/workflows/ios-ship.yml (lines 151-185 at @@ -42,12 +42,10 @@ inputs: description: Infisical secret path. required: false default: / - client-id: - description: Universal-auth machine identity client id. - required: true - client-secret: - description: Universal-auth machine identity client secret. - required: true + service-token: + description: Full Infisical service token scoped to this project, environment, and path. + required: false + default: "" site-url: description: Infisical site URL. required: false @@ -69,7 +67,6 @@ runs: INFISICAL_PROJECT_ID: ${{ inputs.project-id }} INFISICAL_ENVIRONMENT: ${{ inputs.environment }} INFISICAL_SECRET_PATH: ${{ inputs.secret-path }} - INFISICAL_CLIENT_ID: ${{ inputs.client-id }} - INFISICAL_CLIENT_SECRET: ${{ inputs.client-secret }} + INFISICAL_SERVICE_TOKEN: ${{ inputs.service-token }} INFISICAL_SITE_URL: ${{ inputs.site-url }} run: node "$GITHUB_ACTION_PATH/../../../scripts/infisical-fetch.mjs" diff --git a/AGENTS.md b/AGENTS.md index 209ebb15..fc487f8e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,7 +40,7 @@ Hosting and routing (apexes, hostnames, hosts, deploy paths): see [`Fleet-OPS/do CodeCaps is a macOS menu-bar Swift app for **centralized monitoring and alerting of every AI subscription plan on your Mac** — usage, quotas, and caps across Claude, Codex, Cursor, Antigravity, Grok, MiniMax, and the -other AI CLIs already signed in. No provider API key is entered; CodeCaps +other AI CLIs already signed in.  Optional Z.ai coding-plan keys stay in Keychain; CodeCaps uses existing local sign-ins to query supported provider quotas and local helpers. Reading a credential file is not a passive quota-file refresh. The same readings can be pushed to an endpoint you run and pulled back into the diff --git a/INFISICAL.md b/INFISICAL.md index 3e038a13..9f845cc4 100644 --- a/INFISICAL.md +++ b/INFISICAL.md @@ -1,71 +1,77 @@ # INFISICAL.md — CodeCaps -Infisical is the sole source of truth for CodeCaps' app-level settings: secrets, environment config, and tunable settings knobs. Per-user settings stay in the app's own store and never go in Infisical. This file is the contract; `AGENTS.md` points here and every future change to settings follows it. +Infisical is the sole source of truth for CodeCaps' app-level settings: secrets, environment config, and tunable settings knobs.  Per-user settings stay in the app's own store and never go in Infisical.  This file is the contract; `AGENTS.md` points here and every future change to settings follows it. ## Project -- Project ID must be entered explicitly under Dashboard → Infisical Sync. There is no built-in project or migration fallback. Legacy two-field identities are not activated; the owner enters the three-field setup. -- Every build reads `prod`, and only `prod` (`InfisicalSettings.defaultEnvironment`). The dev and staging environments are retired (owner, 2026-10-10), so a `.dev` build reads `prod` too; `TokenStore` and `InfisicalIdentityStore` still scope Keychain items per build. The client refuses to log in, read or write for any other environment, and a test pins that. -- REST surface used: universal-auth login → project/environment metadata verification on explicit setup Save → three named `GET /api/v3/secrets/raw/{name}` requests → `PATCH` / `POST /api/v3/secrets/raw/{name}` for write-through. The app never lists root secrets or fetches an unrelated secret value. A missing managed key (404) remains unset, so its existing local/default behavior applies; any other read failure keeps the entire last-known-good cache. Implemented with zero new dependencies in `Sources/QuotaCore/InfisicalSettings.swift` (`URLSession` only). +- Infisical is optional.  With no selected read source, CodeCaps keeps its local settings and does not contact Infisical. +- Setup contains multiple labeled bindings, each with an explicit project ID, environment, folder path, Infisical site, authentication method, and either read or write purpose.  Each binding has its own credential. +- Service tokens are the recommended new setup.  The complete `st..` token is sent as `Authorization: Bearer st..`; it is never reduced to its final segment and never sent through universal-auth login.  Infisical enforces the token's actual environment/path scopes and permissions. +- Machine identities remain supported through universal-auth client ID and secret.  Existing version-1 identities migrate in memory to the same machine-auth read binding at `prod` and `/`, without a startup Keychain rewrite or automatic write selection. +- The owner selects one read settings source and an independent write binding.  A write binding must explicitly have write purpose and match the selected read source's site, project, environment, and folder.  Read access never implies write access, even when the underlying credential has broader server permissions. +- The default environment for a new form or migrated identity remains `prod`; newly configured bindings can explicitly choose another environment and folder. +- Runtime REST operations remain the three named `GET /api/v3/secrets/raw/{name}` reads and `PATCH` / `POST` writes.  Machine-auth setup also verifies project/environment metadata.  Service-token setup validates through the named reads because a scoped service token may not have project-metadata permission.  Saving a write binding does not perform a probe write or claim that server write permission was verified. ## Key Inventory | Key | Env | Sensitivity | Default | Notes | |---|---|---|---|---| -| `PULL_ENDPOINT` | prod | Non-sensitive (service URL) | `https://usage.jays.services/api/quota-windows` (not yet set in prod) | Service URL the Mac app pulls other machines' quota windows from. Migrated from the `endpoint` UserDefaults key. | -| `PUSH_ENDPOINT` | prod | Non-sensitive (service URL) | Empty — to be filled by the admin | Service URL the Mac app pushes this Mac's quota windows to. Migrated from the `syncEndpoint` UserDefaults key. | -| `SETTINGS_REFRESH_SECONDS` | prod | Non-sensitive (knob) | `300` (not yet set in prod) | Background refresh cadence for this cache, tunable via Infisical itself. Clamped to a 60-second floor so a typo cannot hot-loop the timer. | +| `PULL_ENDPOINT` | prod | Non-sensitive (service URL) | `https://usage.jays.services/api/quota-windows` (not yet set in prod) | Service URL the Mac app pulls other machines' quota windows from.  Migrated from the `endpoint` UserDefaults key. | +| `PUSH_ENDPOINT` | prod | Non-sensitive (service URL) | Empty — to be filled by the admin | Service URL the Mac app pushes this Mac's quota windows to.  Migrated from the `syncEndpoint` UserDefaults key. | +| `SETTINGS_REFRESH_SECONDS` | prod | Non-sensitive (knob) | `300` (not yet set in prod) | Background refresh cadence for this cache, tunable via Infisical itself.  Clamped to a 60-second floor so a typo cannot hot-loop the timer. | -The `prod` environment holds no CodeCaps keys yet: the two non-sensitive defaults above were only ever seeded in the now-retired `dev` environment and were not copied over. Until the admin sets them in `prod`, a missing managed key stays unset and the app's local defaults apply. `prod` values are set by the admin and never invented. Secret keys are documented as "to be filled by admin" and left empty — no secret value is ever invented, guessed, or copied into the project. +Missing managed keys remain unset, so the app's existing defaults apply.  Credentials and values are supplied by the owner, never invented or copied from unrelated projects.  Bindings do not create service tokens, machine identities, or new server-side grants. ## What Lives Here Versus What Does Not -**In Infisical (app-level):** the two fleet endpoint URLs and the refresh cadence above. Future app-level knobs (thresholds, intervals, feature flags) go here too. +**In Infisical (app-level):** the two fleet endpoint URLs and the refresh cadence above.  Future app-level knobs (thresholds, intervals, feature flags) go here too. **Explicitly out — per-user settings stay in the app's own store:** - Every display preference (`displayMode`, `menuBarStyle`, mark styles, `appearance`, `glanceView`, platform order, source ranking, disabled sources, high contrast) → `UserDefaults`. - Reset alarms (sound, cadence, message), anomaly multipliers, burn-rate alert toggles → `UserDefaults`. -- The Read Token and Push Token → the Keychain (`TokenStore`), never Infisical. They are the owner's per-server credentials; the Keychain is their correct home and Infisical only ever sees service URLs. -- The Infisical client identity itself (universal-auth client ID + secret + selected Project ID) → the Keychain (`InfisicalIdentityStore`), provisioned once by the owner under Dashboard → Infisical Sync. A shipped app cannot embed a client secret, so there is no fallback identity. +- The Read Token and Push Token → the Keychain (`TokenStore`), never Infisical.  They are the owner's per-server credentials; the Keychain is their correct home and Infisical only ever sees service URLs. +- Infisical setup bindings, including full service tokens or machine client secrets and their scope metadata → one versioned, build-scoped Keychain record (`InfisicalIdentityStore`).  No credential is persisted in UserDefaults, bundled into the app, logged, or included in an error message. **Explicitly out — build-time constants:** `SUFeedURL` / `SUPublicEDKey` (Sparkle, baked into the signed bundle — do not move these), provider API endpoints (`api.anthropic.com`, etc.), bundle identifiers, local credential file paths. -**Build-time CI secrets (Infisical prod, not runtime app keys):** `SENTRY_DSN` and `SENTRY_AUTH_TOKEN` live in the Fleet-OPS Infisical project (prod `/`) for the TestFlight / Sparkle ship jobs; both `ios-ship.yml` and `mac-release.yml` read that project, and no ship job reads a CodeCaps Infisical project. The iOS TestFlight workflow (`ios-ship.yml`) also reads `SENTRY_DSN_CODECAPS` from Fleet-OPS prod `/`: the DSN of Sentry project `codecaps`, to be filled by admin, which replaces the shared fleet `SENTRY_DSN` for the iOS archive. A missing `SENTRY_DSN_CODECAPS` falls back to the shared key and turns the run red. The Mac and iOS apps never fetch them at runtime; `InfisicalSettings` does not grow a fourth named read. Ship workflows load them through `.github/actions/infisical-secrets` (GitHub repository secrets of the same name as fallback) and inject `SENTRY_DSN` into the archive as an xcodebuild / Info.plist build setting. `SentryTelemetry` skips init when the value is empty. `SENTRY_AUTH_TOKEN` is used only by `sentry-cli` on the runner for dSYM / Size Analysis upload (org `simple-with-us`, project `codecaps`). `SENTRY_FLEET_DSN` is a GitHub repository secret for `.github/workflows/sentry-ci-report.yml` (fleet-infra), not an Infisical app key. +**Build-time CI secrets (Infisical prod, not runtime app keys):** `SENTRY_DSN` and `SENTRY_AUTH_TOKEN` live in the Fleet-OPS Infisical project (prod `/`) for the TestFlight / Sparkle ship jobs; both `ios-ship.yml` and `mac-release.yml` read that project, and no ship job reads a CodeCaps Infisical project.  The iOS TestFlight workflow (`ios-ship.yml`) also reads `SENTRY_DSN_CODECAPS` from Fleet-OPS prod `/`: the DSN of Sentry project `codecaps`, to be filled by admin, which replaces the shared fleet `SENTRY_DSN` for the iOS archive.  A missing `SENTRY_DSN_CODECAPS` falls back to the shared key and turns the run red.  The Mac and iOS apps never fetch them at runtime; `InfisicalSettings` does not grow a fourth named read.  Ship workflows load them through `.github/actions/infisical-secrets` (GitHub repository secrets of the same name as fallback) and inject `SENTRY_DSN` into the archive as an xcodebuild / Info.plist build setting.  `SentryTelemetry` skips init when the value is empty.  `SENTRY_AUTH_TOKEN` is used only by `sentry-cli` on the runner for dSYM / Size Analysis upload (org `simple-with-us`, project `codecaps`).  `SENTRY_FLEET_DSN` is a GitHub repository secret for `.github/workflows/sentry-ci-report.yml` (fleet-infra), not an Infisical app key. -**iOS companion:** the companion cannot safely hold a client secret, so it never talks to Infisical. The Mac app owns the Infisical read; the companion keeps reading quota data through its existing API (`https://usage.jays.services/api/quota-windows` with its read token). No companion code changed for this rollout. +**iOS companion:** the companion cannot safely hold a client secret, so it never talks to Infisical.  The Mac app owns the Infisical read; the companion keeps reading quota data through its existing API (`https://usage.jays.services/api/quota-windows` with its read token).  No companion code changed for this rollout. ## The Runtime Contract -1. **Load at startup.** `AppDelegate.startInfisicalSync` installs persisted configuration synchronously at launch, then asynchronously runs `refresh()` → adopt endpoints. Revision fences discard completions from a retired setup. A failure never blocks launch or the main thread; the app keeps its local values. -2. **Never fetch per-request.** All runtime reads go through `InfisicalSettings.value(for:)`, a synchronous memory-only read. The only network calls are the startup load, the refresh timer, `applicationDidBecomeActive`, and explicit admin Save actions. -3. **Background refresh.** A one-shot timer rescheduled after every fire (so a cadence change in Infisical takes effect next cycle), plus a refresh on `applicationDidBecomeActive`. A failed refresh is recorded on `lastError` (visible under Dashboard → Infisical Sync) and the last-known-good cache keeps serving — staleness is safer than an outage. - The three named reads complete before the cache changes; partial success never replaces it. Infisical sync remains optional and separately provisioned. Reading settings does not turn on quota push or pull. -4. **Write-through on admin save.** Saving the pull/push endpoint in Settings, or any managed key under Dashboard → Infisical Sync, writes to Infisical FIRST via `InfisicalSettings.set` and only then updates the local cache. A failed Infisical write throws and the save is rejected with the error shown inline — the cache and Infisical never diverge silently. -5. **Adoption, not clobbering.** After a load/refresh, `MonitorModel.adoptInfisicalEndpointsIfUnset` fills in an endpoint only when the owner never set one locally (key absent). A deliberately cleared field (stored as `""`) is never overridden. +1. **Load at startup.** `AppDelegate.startInfisicalSync` installs persisted configuration synchronously at launch, then asynchronously runs `refresh()` → adopt endpoints.  Revision fences discard completions from a retired setup.  A failure never blocks launch or the main thread; the app keeps its local values. +2. **Never fetch per-request.** All runtime reads go through `InfisicalSettings.value(for:)`, a synchronous memory-only read.  The only network calls are the startup load, the refresh timer, `applicationDidBecomeActive`, and explicit admin Save actions. +3. **Background refresh.** A one-shot timer rescheduled after every fire (so a cadence change in Infisical takes effect next cycle), plus a refresh on `applicationDidBecomeActive`.  A failed refresh is recorded on `lastError` (visible under Dashboard → Infisical Sync) and the last-known-good cache keeps serving — staleness is safer than an outage. + The three named reads complete before the cache changes; partial success never replaces it.  Infisical sync remains optional and separately provisioned.  Reading settings does not turn on quota push or pull. +4. **Write-through on admin save.** When Infisical is selected, saving managed settings requires an explicit matching write binding.  `InfisicalSettings.set` authenticates with that write binding, writes to Infisical first, and only then updates the cache.  The read credential is never used as a write fallback.  A failed write leaves the cache untouched; a retired setup cannot install values or begin a follow-up create. +5. **Adoption, not clobbering.** After a load/refresh, `MonitorModel.adoptInfisicalEndpointsIfUnset` fills in an endpoint only when the owner never set one locally (key absent).  A deliberately cleared field (stored as `""`) is never overridden. ## Admin Gating -CodeCaps is a single-user local app: the owner is the only user and therefore the admin. The gate is a deliberate no-op, documented here rather than implemented as a parallel auth system. The settings surfaces (Dashboard → Sources & Fleet, Dashboard → Infisical Sync) are reachable only on his own Mac. +CodeCaps is a single-user local app: the owner is the only user and therefore the admin.  The gate is a deliberate no-op, documented here rather than implemented as a parallel auth system.  The settings surfaces (Dashboard → Sources & Fleet, Dashboard → Infisical Sync) are reachable only on his own Mac. -## Provisioning +## Setup -1. In Infisical, create a machine identity scoped to the CodeCaps project, the `prod` environment, and the root secret path. Grant read access at that scope; grant write access only if this identity will save settings from the app. Use the narrowest permissions supported by the Infisical policy. The client requests only the three managed keys by name, but that request pattern alone does not restrict what an overprivileged identity could access. Copy its client ID and secret. -2. Open Dashboard → Infisical Sync, enter Client ID, Client Secret, and Project ID, then press Save Setup. With an unchanged Client ID, leaving Client Secret blank retains the saved secret. Save verifies login, project/environment metadata, and the three managed-key reads before atomically persisting all three fields in one Keychain record and switching the active cache. A failed validation or Keychain write leaves the previous setup and cached values active. An existing project with no managed keys is valid; a missing or inaccessible project is not. Project metadata access is needed for setup validation; routine refresh remains the existing three named reads. -3. Set `PULL_ENDPOINT` / `PUSH_ENDPOINT` / `SETTINGS_REFRESH_SECONDS` under Managed Keys (or directly in Infisical); the app picks them up on the next refresh. +1. Open Dashboard → Infisical Sync and add a labeled binding.  Choose Service Token (recommended) or Machine Identity, the explicit read or write purpose, project ID, environment, folder, and HTTPS Infisical site. +2. Paste an existing complete service token, or the existing machine client ID and client secret.  Save Binding stores the credential in this build's Keychain.  Blank credential fields retain the existing credential only for the same binding and authentication method; a changed machine client ID requires its secret again. +3. Add separate read and write bindings as needed for different project/environment/folder scopes.  Select Read Settings From to activate one source.  Select Write Settings With separately if managed settings should be editable; only matching write bindings appear.  Save Selection validates the selected read source and commits runtime configuration and Keychain persistence together. +4. Saving a candidate fails without replacing the active setup if validation or Keychain persistence fails.  Read-source validation requests only managed keys; missing keys are allowed, while authentication and other read failures preserve the prior setup. +5. Choose Local Settings Only to disconnect while retaining bindings.  Remove deletes one local binding; Forget All Bindings removes the app's stored setup.  Neither action deletes Infisical secrets or revokes server credentials. -## Switching and forgetting a setup +## Switching, Migration, And Rotation -Changing Project ID never carries cached values or status from the previous destination into the new cache. Existing local endpoint overrides, quota modes, read/push tokens, and provider sign-ins remain untouched. In-flight old reads, writes, and validation cannot install stale cache/status or initiate a follow-up create after a switch or Forget. An already submitted HTTP write cannot be recalled, but its response cannot affect the new setup. +Switching any selected scope retires old requests and clears the settings cache before the new source is installed.  Old completions cannot replace the new cache or status, and a delayed write cannot start a create request after a switch or Forget.  An already submitted HTTP request cannot be recalled. -Forget Setup atomically deletes the single stored identity/destination record. Legacy two-field records are never loaded. Keychain failures retain a complete prior three-field setup. Failed saves and clears restart the prior setup’s refresh cycle. No credential-file fallback is added. +Existing version-1 machine setup is read without rewriting it at launch.  The next explicit save writes the version-2 binding list into the same build-scoped Keychain item.  The migrated machine binding retains its client credentials, project, `prod`, and `/`; write selection remains empty until the owner explicitly provides one. -## Rotating A Value - -Edit the key in Infisical (dashboard or API) — the app picks it up within one refresh interval, or press Reload Now under Dashboard → Infisical Sync. To rotate the client identity itself: save the new identity under Dashboard → Infisical Sync (old Keychain items are overwritten), then revoke the old identity in Infisical. Tokens in the Keychain rotate through the existing Re-Authorize / Forget flows and are unaffected by this file. +To rotate credentials, edit the corresponding binding and paste its replacement, save successfully, then revoke the old credential through the normal owner-approved process.  Working credentials are never automatically minted, refreshed, or revoked by this setup flow. ## Hard Rules - No secret values in code, logs, PR bodies, or chat — names and metadata only. - No per-request Infisical fetches anywhere in the refresh, render, or event paths. +- No write without an explicit matching write binding; never reuse the read credential implicitly. +- Preserve complete service-token values and keep every credential in the app's own Keychain record. - No per-user settings migrated into Infisical, ever. - The local user is the admin; there is no separate admin role to invent. diff --git a/README.md b/README.md index ae6d9f21..cf9bd79d 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ A macOS menu bar app for supported AI plan usage and quota windows. It can shar ## Why This Exists -CodeCaps reads available usage and quota windows from supported AI apps and CLIs already signed in on this Mac — no provider API key is entered into CodeCaps. Optional push and pull connections can show readings from other configured Macs in one Glance popover. +CodeCaps reads available usage and quota windows from supported AI apps and CLIs already signed in on this Mac.  Optional Z.ai coding-plan quota checks use a key saved in this build's Keychain.  Optional push and pull connections can show readings from other configured Macs in one Glance popover. CodeCaps keeps local readings visible in the menu bar. If you run a collector, it can also bring multiple Macs into one view. @@ -18,7 +18,7 @@ Engineered with the proactive safeguards you'll come to rely on: - **Visual Usage History & Trend Graphs**: Dive into rich local usage history graphs. Inspect how your quota drains over time, evaluate burn pacing, and see anomaly alert markers directly on your timeline. - **Low-Quota Picture-in-Picture (PiP)**: Keep high-priority quotas visible in an on-top floating micro-HUD. Set PiP to open automatically whenever any provider's quota runs low, so you're never caught off-guard mid-prompt. - **Dual-Window Cadence & Smart Reset Alarms**: Monitor 5-hour rapid windows alongside weekly/monthly plan allowances. Reset alarms alert you on major period rollovers, and notify on short windows only when you're actually near the cap. -- **Zero API Keys**: Reads local CLI and application sessions directly on your Mac. No provider API key is ever entered into CodeCaps (provider CLIs keep their own credentials), and CodeCaps never exports provider sign-in tokens. +- **Local Sign-Ins And Optional Keys**: Reads supported CLI and application sessions directly on your Mac.  Z.ai coding-plan checks offer an explicit API key stored in Keychain; CodeCaps never exports provider sign-in tokens. ## What It Shows @@ -210,7 +210,7 @@ Console's sidebar has eight Settings pages. ## Privacy -- Never asks for a provider API key; each CLI's own credential file, Keychain item, or session database is reused as-is. +- Reuses supported local CLI credentials and session stores.  Optional Z.ai coding-plan keys stay in a separate build-scoped Keychain item. - Nothing leaves this Mac until you turn on push or pull and enter an endpoint yourself; fields are empty by default. - The Push Token and Read Token are the only two secrets stored, both in the Keychain. - Endpoints are validated as above (HTTPS, loopback-only HTTP, no embedded credentials/query/fragment). diff --git a/Sources/CodeCaps/AppDelegate.swift b/Sources/CodeCaps/AppDelegate.swift index 239bf189..e491ab16 100644 --- a/Sources/CodeCaps/AppDelegate.swift +++ b/Sources/CodeCaps/AppDelegate.swift @@ -240,11 +240,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe // Install persisted configuration synchronously on the main actor. // A delayed startup task must never restore A after Dashboard saved B. let settings = InfisicalSettings.shared - guard let identity = InfisicalIdentityStore.load() else { + guard let configuration = InfisicalIdentityStore.loadSetup()?.configuration else { settings.clearConfiguration() return } - settings.configure(identity.configuration) + settings.configure(configuration) refreshInfisicalSettings() } diff --git a/Sources/CodeCaps/InfisicalIdentityStore.swift b/Sources/CodeCaps/InfisicalIdentityStore.swift index 8fb70f6c..c98047ff 100644 --- a/Sources/CodeCaps/InfisicalIdentityStore.swift +++ b/Sources/CodeCaps/InfisicalIdentityStore.swift @@ -2,18 +2,9 @@ import Foundation import Security import QuotaCore -/// The owner-provisioned Infisical universal-auth identity that lets this Mac -/// act as an Infisical client (see INFISICAL.md). -/// -/// A shipped Mac app cannot safely embed a client secret — anyone can extract -/// it from the binary — so there is no fallback identity and no default. -/// The owner pastes his own machine identity's client ID and secret once, -/// under Settings → Infisical Sync, and they live in his Keychain from then -/// on, exactly like the read and push tokens `TokenStore` already keeps. -/// `InfisicalSettings` itself only ever holds them in memory. -/// -/// Every Keychain call goes through `calls`, so tests inject a fake and never -/// touch the real Keychain. Values are never logged anywhere on this path. +/// The app's own versioned Infisical binding record, scoped per build. +/// Machine identities and full service tokens never use preferences or logs. +/// Injected calls keep tests away from the real Keychain. enum InfisicalIdentityStore { struct Identity: Codable, Equatable, Sendable { var clientId: String @@ -31,6 +22,7 @@ enum InfisicalIdentityStore { private struct Record: Codable { var version = 1 var identity: Identity? + var setup: InfisicalSetup? } /// Test seam: the live implementation shells out to the Security @@ -78,38 +70,39 @@ enum InfisicalIdentityStore { private static let setupAccount = "setup-v1" - /// The provisioned identity, or nil when the owner has not set one up. - /// A half-written identity (one half missing) reads as absent. - static func load( - bundleIdentifier: String? = Bundle.main.bundleIdentifier - ) -> Identity? { - let service = serviceName(bundleIdentifier: bundleIdentifier) + /// V1 identities become read-only bindings in memory; no startup write migrates credentials. + static func loadSetup(bundleIdentifier: String? = Bundle.main.bundleIdentifier) -> InfisicalSetup? { let raw: String? - do { raw = try calls.read(service, setupAccount) } - catch { return nil } // Read failure must never activate another destination. - if let raw { - // A malformed/unsupported record fails closed. - guard let data = raw.data(using: .utf8), - let record = try? JSONDecoder().decode(Record.self, from: data), - record.version == 1, - let identity = record.identity, - !identity.clientId.isEmpty, !identity.clientSecret.isEmpty, - !identity.projectId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil } - return identity - } - // Two-field records have no explicit destination and are not loaded. - return nil + do { raw = try calls.read(serviceName(bundleIdentifier: bundleIdentifier), setupAccount) } + catch { return nil } + guard let raw, raw.utf8.count <= 1_048_576, let data = raw.data(using: .utf8), + let record = try? JSONDecoder().decode(Record.self, from: data) else { return nil } + let setup: InfisicalSetup + if record.version == 1, let identity = record.identity { + let read = identity.configuration.readBinding + setup = InfisicalSetup(bindings: [read], readBindingID: read.id) + } else if record.version == 2, let saved = record.setup { setup = saved } + else { return nil } + guard (try? setup.validate()) != nil else { return nil } + return setup } - static func save( - _ identity: Identity, - bundleIdentifier: String? = Bundle.main.bundleIdentifier - ) throws { - let service = serviceName(bundleIdentifier: bundleIdentifier) - guard !identity.projectId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { - throw StoreError.invalidRecord - } - try write(Record(identity: identity), service: service) + static func saveSetup(_ setup: InfisicalSetup, + bundleIdentifier: String? = Bundle.main.bundleIdentifier) throws { + try setup.validate() + try write(Record(version: 2, identity: nil, setup: setup), service: serviceName(bundleIdentifier: bundleIdentifier)) + } + + /// Compatibility for callers inspecting the selected machine-auth read identity. + static func load(bundleIdentifier: String? = Bundle.main.bundleIdentifier) -> Identity? { + guard let binding = loadSetup(bundleIdentifier: bundleIdentifier)?.configuration?.readBinding, + binding.authentication == .machineIdentity else { return nil } + return Identity(clientId: binding.clientId, clientSecret: binding.clientSecret, projectId: binding.projectId) + } + + static func save(_ identity: Identity, bundleIdentifier: String? = Bundle.main.bundleIdentifier) throws { + let read = identity.configuration.readBinding + try saveSetup(InfisicalSetup(bindings: [read], readBindingID: read.id), bundleIdentifier: bundleIdentifier) } static func delete( diff --git a/Sources/CodeCaps/MonitorModel.swift b/Sources/CodeCaps/MonitorModel.swift index 0e15271d..2afbd20c 100644 --- a/Sources/CodeCaps/MonitorModel.swift +++ b/Sources/CodeCaps/MonitorModel.swift @@ -613,6 +613,7 @@ final class MonitorModel: ObservableObject { public let alarmManager: ResetAlarmManager let smsAlerts: SMSAlertController + let zAIQuotaSetup: ZAIQuotaSetupController /// App-level alert fan-out. Producers emit `CodeCapsAlertEvent`s here /// and registered channels deliver them; today the only channel is the @@ -704,6 +705,7 @@ final class MonitorModel: ObservableObject { /// model redraws when All or a provider's bell flips. private var alarmChanges: AnyCancellable? private var smsChanges: AnyCancellable? + private var zAIQuotaChanges: AnyCancellable? /// Re-checks the saved-token states when `TokenStore` gains a token nobody /// was waiting for, so the Re-Authorize button clears without a refresh. private var tokenChanges: AnyCancellable? @@ -826,6 +828,7 @@ final class MonitorModel: ObservableObject { alarmManager = ResetAlarmManager(defaults: defaults) smsAlerts = SMSAlertController(defaults: defaults) + zAIQuotaSetup = ZAIQuotaSetupController(defaults: defaults) appearance = AppAppearance(rawValue: defaults.string(forKey: "appearance") ?? "") ?? .system glanceView = GlanceViewMode(rawValue: defaults.string(forKey: "glanceView") ?? "") ?? .fromMac @@ -845,6 +848,8 @@ final class MonitorModel: ObservableObject { smsChanges = smsAlerts.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() } + zAIQuotaChanges = zAIQuotaSetup.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() } + zAIQuotaSetup.changed = { [weak self] in self?.zAIQuotaSetupChanged() } alarmManager.additionalDelivery = { [weak self] kind, title, body, identifier in self?.smsAlerts.deliver(kind: kind.rawValue, title: title, body: body, eventID: identifier) } @@ -1239,6 +1244,18 @@ final class MonitorModel: ObservableObject { if providerChecksEnabled || serverEnabled { refreshProviderChecks() } } + private func zAIQuotaSetupChanged() { + invalidateRefresh() + if let providerResult { + self.providerResult = LocalQuotaResult( + windows: providerResult.windows.filter { $0.canonicalProviderKey != "zcode" }, + issues: providerResult.issues.filter { $0.key != "zcode" }, + consentNeeded: providerResult.consentNeeded.subtracting(["zcode"])) + rebuildLocalState(recordSamples: false) + } + if localEnabled && providerChecksEnabled && isOptionalQuotaReaderEnabled("zcode") { refreshProviderChecks() } + } + func setSourceEnabled(_ enabled: Bool, _ source: String, for providerKey: String) { var disabled = disabledSources if enabled { disabled.remove(source) } else { disabled.insert(source) } @@ -3486,7 +3503,10 @@ final class MonitorModel: ObservableObject { private nonisolated static func readLocalSources( preferences: QuotaReaderPreferences = .init() ) async -> LocalQuotaResult { - async let registered = LocalQuotaReaderRegistry.builtIn.read(preferences: preferences) + let registry = LocalQuotaReaderRegistry.configured(zCodeCredentialProvider: { + await ZAIQuotaCredentialStore.shared.load() + }) + async let registered = registry.read(preferences: preferences) async let antigravity = AntigravitySummaryReader().read() var result = await registered let summary = await antigravity diff --git a/Sources/CodeCaps/SettingsViews.swift b/Sources/CodeCaps/SettingsViews.swift index 585b6870..aad5f007 100644 --- a/Sources/CodeCaps/SettingsViews.swift +++ b/Sources/CodeCaps/SettingsViews.swift @@ -455,13 +455,14 @@ struct SettingsSourcesFleetPage: View { .disabled(!model.localEnabled || !model.sessionFileChecksEnabled) ForEach(ReaderStatus.all, id: \.providerKey) { reader in readerRow(reader) + if reader.optionalReaderID == "zcode" { ZAIQuotaSettingsView(controller: model.zAIQuotaSetup) } } } header: { Eyebrow("THIS MAC") } footer: { VStack(alignment: .leading, spacing: 4) { - Text("CodeCaps reads each CLI's own saved credentials in place." + sentenceGap - + "It never asks you for a provider API key.") + Text("Most provider quotas use each CLI's existing local sign-in." + sentenceGap + + "Z.ai Coding Plan quota reads use the API key you save here.") Text("Provider Checks use existing local sign-ins and provider quota endpoints." + sentenceGap + "Copilot uses your existing GitHub CLI sign-in.") Text("Codex Session File Checks: 1 local quota source." + sentenceGap @@ -1757,286 +1758,290 @@ struct CommitButton: View { /// The admin surface for Infisical as the source of truth (see INFISICAL.md). /// -/// CodeCaps is a single-user local app, so the owner IS the admin and the gate -/// is a no-op by design — this page is only reachable on his own Mac. The -/// client identity is his own universal-auth machine identity, stored in his -/// Keychain like the read and push tokens already are; it is never embedded -/// in the app and never leaves the machine. The iOS companion cannot hold a -/// client secret, so it stays out of Infisical entirely and keeps reading -/// through its existing quota API — the Mac app owns the Infisical read. +/// Optional, owner-configured Infisical access is kept in the app's own +/// build-scoped Keychain record, with independent read and write selections. @MainActor struct SettingsInfisicalPage: View { @ObservedObject var model: MonitorModel - - @State private var clientId = "" - @State private var clientSecret = "" + @State private var setup = InfisicalSetup() + @State private var editingID: String? + @State private var label = "" @State private var projectId = "" - @State private var savedIdentity: InfisicalIdentityStore.Identity? - @State private var operationId = UUID() - @State private var hasIdentity = false + @State private var environment = "prod" + @State private var folder = "/" + @State private var site = "https://app.infisical.com" + @State private var authentication: InfisicalBinding.Authentication = .serviceToken + @State private var access: InfisicalBinding.Access = .read + @State private var credential = "" + @State private var clientId = "" + @State private var readSelection = "" + @State private var writeSelection = "" @State private var pullEndpoint = "" @State private var pushEndpoint = "" @State private var refreshSeconds = "" + @State private var formRevision: InfisicalSettings.Revision? @State private var working = false + @State private var operationID = UUID() @State private var message: String? - @State private var succeeded = false - @State private var keyMessage: String? - @State private var keySucceeded = false + private var settings: InfisicalSettings { .shared } - private var settings: InfisicalSettings { InfisicalSettings.shared } + private var draftRead: InfisicalBinding? { setup.bindings.first { $0.id == readSelection && $0.access == .read } } + private var matchingWrites: [InfisicalBinding] { + guard let draftRead else { return [] } + return setup.bindings.filter { $0.access == .write && $0.matchesScope(of: draftRead) } + } + private var hasSavedCredential: Bool { + setup.bindings.contains { + $0.id == editingID && $0.authentication == authentication + && (authentication == .serviceToken || $0.clientId == clientId.trimmingCharacters(in: .whitespacesAndNewlines)) + } + } var body: some View { SettingsPage { - // Owner 2026-10-08: this page looked like a required setup step, - // and it is not one — CodeCaps works entirely from the local AI - // tools when nothing is connected here. Section { - VStack(alignment: .leading, spacing: 5) { - Eyebrow("OPTIONAL") - .foregroundStyle(Theme.warning) - Text("Share settings across your Macs, and let the fleet push quotas here.") - .font(.system(size: 11, weight: .medium)) - .foregroundStyle(Theme.ink) - .fixedSize(horizontal: false, vertical: true) - Text("CodeCaps reads every quota from the AI tools already signed in on this Mac. " + sentenceGap - + "Connecting Infisical is only for setting a machine up to share its own configuration, and to receive quota data from your other Macs.") - .font(.system(size: 11)) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - .padding(.vertical, 2) + Text("Infisical is optional.") + .font(.headline) + Text("Keep settings in your Infisical projects and folders." + sentenceGap + + "Quota monitoring continues locally when no read source is selected.") + .font(.caption).foregroundStyle(.secondary) } - Section { - TextField("Client ID", text: $clientId, - prompt: Text("Client ID")) - .disabled(working) - SecureField("Client Secret", text: $clientSecret, - prompt: Text(savedIdentity?.clientId == clientId && hasIdentity - ? "Saved in Keychain (leave blank to keep)" : "Client Secret")) - .disabled(working) - TextField("Project ID", text: $projectId) - .disabled(working) - HStack { - if hasIdentity { - Button("Forget Setup", role: .destructive, action: forgetIdentity) + ForEach(setup.bindings) { binding in + HStack { + VStack(alignment: .leading) { + Text(binding.label).font(.headline) + Text(binding.access.title + " · " + binding.projectId + " · " + binding.environment + " · " + binding.secretPath) + .font(.caption).foregroundStyle(.secondary) + } + Spacer() + Button("Edit") { edit(binding) } + Button("Remove", role: .destructive) { remove(binding.id) } } - Spacer() - if working { ProgressView().controlSize(.small) } - CommitButton(title: "Save Setup", prominent: !clientId.isEmpty, action: saveIdentity) - .disabled(working || candidateIdentity == nil) } - if let message { - Text(message) - .font(.system(size: 11)) - .foregroundStyle(succeeded ? Theme.accent : Theme.danger) - .fixedSize(horizontal: false, vertical: true) + Button("New Binding") { clearEditor() } + Picker("Read Settings From", selection: $readSelection) { + Text("Local Settings Only").tag("") + ForEach(setup.bindings.filter { $0.access == .read }) { Text($0.label).tag($0.id) } } - } header: { - Eyebrow("CLIENT IDENTITY & PROJECT") - } footer: { - Text("Your own Infisical machine identity, kept in your Keychain." + sentenceGap - + "Nothing here is embedded in the app or sent anywhere but Infisical.") - .font(.system(size: 11)) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) + .onChange(of: readSelection) { _, _ in + if !matchingWrites.contains(where: { $0.id == writeSelection }) { writeSelection = "" } + } + Picker("Write Settings With", selection: $writeSelection) { + Text("No Write Access").tag("") + ForEach(matchingWrites) { Text($0.label).tag($0.id) } + } + Button("Save Selection") { saveSelection() } + } header: { Eyebrow("SAVED BINDINGS") } + footer: { + Text("Read and write access are selected separately." + sentenceGap + + "A write binding must match the selected read source’s project, environment, folder, and Infisical site.") } - + .disabled(working) Section { - LabeledContent("Status") { Text(statusLine).font(.system(size: 11)).foregroundStyle(.secondary) } - LabeledContent("Environment") { Text(settingsEnvironment).font(.system(size: 11)) } - if let savedIdentity { - LabeledContent("Saved Project ID") { Text(savedIdentity.projectId).font(.system(size: 11)) } + TextField("Label", text: $label) + Picker("Authentication", selection: $authentication) { + ForEach(InfisicalBinding.Authentication.allCases, id: \.self) { Text($0.title).tag($0) } } - if let loaded = settings.lastLoadedAt { - LabeledContent("Last Synced") { - Text(loaded.formatted(date: .omitted, time: .shortened)).font(.system(size: 11)) - } - } - if let error = settings.lastError { - Text(error) - .font(.system(size: 11)) - .foregroundStyle(Theme.danger) - .fixedSize(horizontal: false, vertical: true) + .onChange(of: authentication) { _, _ in credential = "" } + Picker("Access", selection: $access) { + ForEach(InfisicalBinding.Access.allCases, id: \.self) { Text($0.title).tag($0) } } + TextField("Project ID", text: $projectId) + TextField("Environment", text: $environment) + TextField("Folder", text: $folder) + TextField("Infisical Site", text: $site) + if authentication == .machineIdentity { TextField("Client ID", text: $clientId) } + SecureField(authentication == .serviceToken ? "Service Token" : "Client Secret", text: $credential, + prompt: Text(hasSavedCredential ? "Leave Blank To Keep Saved Credential" : "Credential")) HStack { - Spacer() - Button("Reload Now", action: reloadNow).disabled(working || !hasIdentity) + if working { ProgressView().controlSize(.small) } + Button(editingID == nil ? "Add Binding" : "Save Binding") { saveBinding() } + .disabled(label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } - } header: { - Eyebrow("SYNC STATUS") + } header: { Eyebrow(editingID == nil ? "NEW BINDING" : "EDIT BINDING") } + footer: { + Text("Use the complete service token, including its st. prefix." + sentenceGap + + "Credentials stay in this build’s Keychain; Infisical enforces their actual permissions.") } - + .disabled(working) + Section { + if let read = settings.activeReadBinding { + LabeledContent("Read Source", value: read.label) + LabeledContent("Environment", value: read.environment) + LabeledContent("Folder", value: read.secretPath) + } else { Text("Local settings only") } + if let loaded = settings.lastLoadedAt { + LabeledContent("Last Synced") { Text(loaded.formatted(date: .omitted, time: .shortened)) } + } + if let error = settings.lastError { Text(error).foregroundStyle(.orange) } + if let message { Text(message).font(.caption).foregroundStyle(.secondary) } + Button("Reload Now") { reloadNow() }.disabled(working || !settings.isProvisioned) + Button("Forget All Bindings", role: .destructive) { forgetAll() }.disabled(working || setup.bindings.isEmpty) + } header: { Eyebrow("SYNC STATUS") } Section { TextField("Pull Endpoint", text: $pullEndpoint) TextField("Push Endpoint", text: $pushEndpoint) TextField("Refresh Seconds", text: $refreshSeconds) - HStack { - Spacer() - if working { ProgressView().controlSize(.small) } - CommitButton(title: "Save Keys", prominent: keysDirty, action: saveKeys) - .disabled(working || !hasIdentity) - } - if let keyMessage = keyMessage { - Text(keyMessage) - .font(.system(size: 11)) - .foregroundStyle(keySucceeded ? Theme.accent : Theme.danger) - .fixedSize(horizontal: false, vertical: true) - } - } header: { - Eyebrow("MANAGED KEYS") - } footer: { - Text("Saving writes to Infisical first; a failed write fails the save." + sentenceGap - + "The pull and push pages write their endpoints through the same path.") - .font(.system(size: 11)) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) + Button("Save Keys") { saveKeys() } + .disabled(working || !settings.canWrite) + } header: { Eyebrow("MANAGED KEYS") } + footer: { + Text(settings.canWrite ? "Changes are saved to Infisical before the local cache updates." + : "Choose a matching write binding to save changes to Infisical.") } } - .onAppear { refreshFromStore(reloadSetup: true) } + .onAppear { reloadSetup() } + .onReceive(NotificationCenter.default.publisher(for: .infisicalIdentityChanged)) { _ in + if !working { reloadSetup() } + } } - private var statusLine: String { - if hasIdentity { - if let last = settings.lastLoadedAt { - return "Active (Synced \(last.formatted(date: .omitted, time: .shortened)))" - } - return "Active" - } - return "Not configured" + private func reloadSetup() { + setup = InfisicalIdentityStore.loadSetup() ?? InfisicalSetup() + readSelection = setup.readBindingID ?? "" + writeSelection = setup.writeBindingID ?? "" + refreshKeys() + } + + private func refreshKeys() { + pullEndpoint = settings.value(for: InfisicalSettings.Keys.pullEndpoint) ?? "" + pushEndpoint = settings.value(for: InfisicalSettings.Keys.pushEndpoint) ?? "" + refreshSeconds = settings.value(for: InfisicalSettings.Keys.refreshSeconds) ?? "" + formRevision = settings.revision } - private var settingsEnvironment: String { - InfisicalSettings.defaultEnvironment() + private func clearEditor() { + editingID = nil; label = ""; projectId = ""; environment = "prod"; folder = "/" + site = "https://app.infisical.com"; authentication = .serviceToken; access = .read + credential = ""; clientId = "" } - private var keysDirty: Bool { - pullEndpoint != (settings.value(for: InfisicalSettings.Keys.pullEndpoint) ?? "") - || pushEndpoint != (settings.value(for: InfisicalSettings.Keys.pushEndpoint) ?? "") - || refreshSeconds != (settings.value(for: InfisicalSettings.Keys.refreshSeconds) ?? "") + private func edit(_ binding: InfisicalBinding) { + editingID = binding.id; label = binding.label; projectId = binding.projectId + environment = binding.environment; folder = binding.secretPath; site = binding.siteURL.absoluteString + authentication = binding.authentication; access = binding.access; clientId = binding.clientId; credential = "" } - private var candidateIdentity: InfisicalIdentityStore.Identity? { - let id = clientId.trimmingCharacters(in: .whitespacesAndNewlines) - let project = projectId.trimmingCharacters(in: .whitespacesAndNewlines) - let secret = clientSecret.isEmpty && savedIdentity?.clientId == id - ? (savedIdentity?.clientSecret ?? "") : clientSecret - guard !id.isEmpty, !secret.isEmpty, !project.isEmpty else { return nil } - return InfisicalIdentityStore.Identity(clientId: id, clientSecret: secret, projectId: project) + private func saveBinding() { + guard let url = URL(string: site.trimmingCharacters(in: .whitespacesAndNewlines)) else { message = "Enter an HTTPS Infisical site."; return } + let latest = InfisicalIdentityStore.loadSetup() ?? setup + let existing = latest.bindings.first { $0.id == editingID && $0.authentication == authentication } + 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) + 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 } + var candidate = latest + candidate.bindings.removeAll { $0.id == binding.id } + candidate.bindings.append(binding) + reconcileSelections(&candidate) + apply(candidate) } - private func refreshFromStore(reloadSetup: Bool = false) { - savedIdentity = InfisicalIdentityStore.load() - hasIdentity = savedIdentity != nil - if reloadSetup { - clientId = savedIdentity?.clientId ?? "" - clientSecret = "" - projectId = savedIdentity?.projectId ?? "" + private func reconcileSelections(_ candidate: inout InfisicalSetup) { + if !candidate.bindings.contains(where: { $0.id == candidate.readBindingID && $0.access == .read }) { + candidate.readBindingID = nil; candidate.writeBindingID = nil } - pullEndpoint = settings.value(for: InfisicalSettings.Keys.pullEndpoint) ?? "" - pushEndpoint = settings.value(for: InfisicalSettings.Keys.pushEndpoint) ?? "" - refreshSeconds = settings.value(for: InfisicalSettings.Keys.refreshSeconds) ?? "" + if let writeID = candidate.writeBindingID, + let write = candidate.bindings.first(where: { $0.id == writeID }), + let read = candidate.configuration?.readBinding, write.access == .write, write.matchesScope(of: read) { return } + candidate.writeBindingID = nil } - private func beginOperation() -> UUID { - let id = UUID() - operationId = id - working = true - return id + private func saveSelection() { + var candidate = InfisicalIdentityStore.loadSetup() ?? setup + candidate.readBindingID = readSelection.isEmpty ? nil : readSelection + candidate.writeBindingID = writeSelection.isEmpty ? nil : writeSelection + apply(candidate) + } + + private func remove(_ id: String) { + var candidate = InfisicalIdentityStore.loadSetup() ?? setup + candidate.bindings.removeAll { $0.id == id } + reconcileSelections(&candidate) + apply(candidate) } - private func saveIdentity() { - guard let identity = candidateIdentity else { return } - let operation = beginOperation() + private func apply(_ candidate: InfisicalSetup) { + do { try candidate.validate() } + catch { message = "Check the binding fields and matching read/write selections."; return } + let operation = UUID(); operationID = operation; working = true; message = nil let revision = settings.beginSetupChange() - message = nil - keyMessage = nil Task { - defer { if operationId == operation { working = false } } + defer { if operationID == operation { working = false } } + guard operationID == operation, settings.isCurrent(revision) else { return } do { - let committed = try await settings.validateAndConfigure(identity.configuration, revision: revision) { - try InfisicalIdentityStore.save(identity) + let committed: InfisicalSettings.Revision + if let configuration = candidate.configuration { + committed = try await settings.validateAndConfigure(configuration, revision: revision) { + try InfisicalIdentityStore.saveSetup(candidate) + } + } else { + try settings.clearConfiguration(expectedRevision: revision) { try InfisicalIdentityStore.saveSetup(candidate) } + committed = settings.revision } - guard operationId == operation, settings.isCurrent(committed) else { return } - model.adoptInfisicalEndpointsIfUnset() - refreshFromStore(reloadSetup: true) - succeeded = true - message = "Setup saved and project verified against Infisical." + guard operationID == operation, settings.isCurrent(committed) else { return } + setup = candidate; readSelection = candidate.readBindingID ?? ""; writeSelection = candidate.writeBindingID ?? "" + credential = ""; clearEditor(); refreshKeys(); model.adoptInfisicalEndpointsIfUnset() + message = candidate.configuration == nil ? "Bindings saved; settings stay local." : "Bindings saved and selected read source checked." NotificationCenter.default.post(name: .infisicalIdentityChanged, object: nil) } catch { - guard operationId == operation, settings.isCurrent(revision) else { return } - succeeded = false - message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription - // Validation retires the old timer revision even on failure. - // Resume refreshes for the still-persisted setup. + if let failure = error as? InfisicalSettings.SettingsError, case .superseded = failure { return } + guard operationID == operation, + candidate.configuration == nil || settings.isCurrent(revision) else { return } + message = (error as? InfisicalSettings.SettingsError)?.errorDescription ?? "Could not save the Infisical setup." NotificationCenter.default.post(name: .infisicalIdentityChanged, object: nil) } } } - private func forgetIdentity() { - // Clear can interrupt validation or a read/write. The core's revision - // fence prevents their eventual completions from reinstalling old data. - operationId = UUID() - working = false + private func forgetAll() { do { try settings.clearConfiguration { try InfisicalIdentityStore.delete() } - refreshFromStore(reloadSetup: true) - succeeded = true - message = "Setup removed." + sentenceGap + "The Dashboard stays local until you add one again." - keyMessage = nil + clearEditor(); reloadSetup(); message = "Infisical bindings forgotten." NotificationCenter.default.post(name: .infisicalIdentityChanged, object: nil) } catch { - succeeded = false - message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription + message = "Keychain could not forget the Infisical setup." NotificationCenter.default.post(name: .infisicalIdentityChanged, object: nil) } } private func reloadNow() { - let operation = beginOperation() + working = true let revision = settings.revision Task { - defer { if operationId == operation { working = false } } + defer { working = false } await settings.refresh() - guard operationId == operation, settings.isCurrent(revision) else { return } - model.adoptInfisicalEndpointsIfUnset() - refreshFromStore() + guard settings.isCurrent(revision) else { reloadSetup(); return } + refreshKeys(); model.adoptInfisicalEndpointsIfUnset() } } private func saveKeys() { - let operation = beginOperation() - let revision = settings.revision - keyMessage = nil - // Snapshot the form before any suspension; every key belongs to this - // setup, even if a different settings window switches projects mid-save. - let updates = [ - (InfisicalSettings.Keys.pullEndpoint, pullEndpoint), - (InfisicalSettings.Keys.pushEndpoint, pushEndpoint), - (InfisicalSettings.Keys.refreshSeconds, refreshSeconds), - ] + guard let revision = formRevision, settings.isCurrent(revision) else { + message = "The selected source changed; reload its settings before saving."; refreshKeys(); return + } + let values = [(InfisicalSettings.Keys.pullEndpoint, pullEndpoint), (InfisicalSettings.Keys.pushEndpoint, pushEndpoint), + (InfisicalSettings.Keys.refreshSeconds, refreshSeconds)] + working = true Task { - defer { if operationId == operation { working = false } } + defer { working = false } do { - var wroteAny = false - for (key, field) in updates { - guard operationId == operation, settings.isCurrent(revision) else { return } - let value = field.trimmingCharacters(in: .whitespacesAndNewlines) - guard value != (settings.value(for: key) ?? "") else { continue } - try await settings.set(value, for: key, expectedRevision: revision) - wroteAny = true + for (key, value) in values where value != (settings.value(for: key) ?? "") { + try await settings.set(value.trimmingCharacters(in: .whitespacesAndNewlines), for: key, expectedRevision: revision) } - guard operationId == operation, settings.isCurrent(revision) else { return } - model.adoptInfisicalEndpointsIfUnset() - refreshFromStore() - keySucceeded = true - keyMessage = wroteAny ? "Keys saved to Infisical." : "No changes to save." + guard settings.isCurrent(revision) else { return } + refreshKeys(); model.adoptInfisicalEndpointsIfUnset(); message = "Keys saved to Infisical." } catch { - guard operationId == operation, settings.isCurrent(revision) else { return } - refreshFromStore() - keySucceeded = false - keyMessage = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription + guard settings.isCurrent(revision) else { return } + refreshKeys(); message = (error as? InfisicalSettings.SettingsError)?.errorDescription ?? "Could not save the settings." } } } diff --git a/Sources/CodeCaps/ZAIQuotaCredentialStore.swift b/Sources/CodeCaps/ZAIQuotaCredentialStore.swift new file mode 100644 index 00000000..24eaf503 --- /dev/null +++ b/Sources/CodeCaps/ZAIQuotaCredentialStore.swift @@ -0,0 +1,50 @@ +import Foundation +import QuotaCore + +/// Region and key share one build-scoped record, separate from all provider logins. +actor ZAIQuotaCredentialStore { + static let shared = ZAIQuotaCredentialStore() + private let service: String + private let account = "quota-api-key-v1" + private let cache: TokenCache + + init(calls: KeychainCalls = .live, bundleIdentifier: String? = Bundle.main.bundleIdentifier, + bounds: TokenCache.Bounds = .init()) { + let service = Self.serviceName(bundleIdentifier: bundleIdentifier) + self.service = service + cache = TokenCache(calls: calls, bounds: bounds, ownServices: [service], log: { _ in }) + } + + nonisolated static func serviceName(bundleIdentifier: String? = Bundle.main.bundleIdentifier) -> String { + TokenStore.serviceName(suffix: "zai-quota-api-key", bundleIdentifier: bundleIdentifier) + } + + func load() async -> ZCodeQuotaCredential? { + decode(await cache.token(server: account, service: service)) + } + + func readAllowingInteraction() async -> ZCodeQuotaCredential? { + decode(await cache.readAllowingInteraction(server: account, service: service)) + } + + func save(_ credential: ZCodeQuotaCredential) async throws { + guard credential.isValid, let data = try? JSONEncoder().encode(credential), + let raw = String(data: data, encoding: .utf8) else { throw Failure.invalid } + do { try await cache.save(raw, server: account, service: service) } + catch { throw Failure.keychain } + } + + func clear() async throws { + do { try await cache.delete(server: account, service: service) } + catch { throw Failure.keychain } + } + + private func decode(_ raw: String?) -> ZCodeQuotaCredential? { + guard let raw, let data = raw.data(using: .utf8), + let credential = try? JSONDecoder().decode(ZCodeQuotaCredential.self, from: data), + credential.isValid else { return nil } + return credential + } + + enum Failure: Error { case invalid, keychain } +} diff --git a/Sources/CodeCaps/ZAIQuotaSettingsView.swift b/Sources/CodeCaps/ZAIQuotaSettingsView.swift new file mode 100644 index 00000000..b3248641 --- /dev/null +++ b/Sources/CodeCaps/ZAIQuotaSettingsView.swift @@ -0,0 +1,122 @@ +import Combine +import Foundation +import QuotaCore +import SwiftUI + +@MainActor +struct ZAIQuotaCredentialAccess { + var save: (ZCodeQuotaCredential) async throws -> Void + var clear: () async throws -> Void + var reauthorize: () async -> ZCodeQuotaCredential? + + static let live = Self(save: { try await ZAIQuotaCredentialStore.shared.save($0) }, + clear: { try await ZAIQuotaCredentialStore.shared.clear() }, + reauthorize: { await ZAIQuotaCredentialStore.shared.readAllowingInteraction() }) +} + +@MainActor +final class ZAIQuotaSetupController: ObservableObject { + @Published private(set) var hasSavedKey: Bool + @Published private(set) var savedRegion: ZCodeQuotaRegion? + @Published private(set) var isWorking = false + @Published private(set) var status: String? + var changed: (() -> Void)? + private let defaults: UserDefaults + private let access: ZAIQuotaCredentialAccess + + init(defaults: UserDefaults, access: ZAIQuotaCredentialAccess? = nil) { + self.defaults = defaults + self.access = access ?? .live + hasSavedKey = defaults.bool(forKey: "zaiQuotaHasSavedKey") + savedRegion = defaults.string(forKey: "zaiQuotaRegion").flatMap(ZCodeQuotaRegion.init(rawValue:)) + } + + @discardableResult + func save(apiKey: String, region: ZCodeQuotaRegion) async -> Bool { + guard !isWorking else { return false } + let credential = ZCodeQuotaCredential(region: region, apiKey: apiKey) + guard credential.isValid else { status = "Enter a valid Coding Plan API key."; return false } + isWorking = true + defer { isWorking = false } + do { + try await access.save(credential) + remember(region) + status = "Coding Plan API key saved." + changed?() + return true + } catch { status = "Keychain could not save the Coding Plan API key."; return false } + } + + func reauthorize() async { + guard !isWorking else { return } + isWorking = true + defer { isWorking = false } + guard let credential = await access.reauthorize(), credential.isValid else { + status = "The saved Coding Plan API key is unavailable in Keychain." + return + } + remember(credential.region) + status = "Saved Coding Plan API key authorized." + changed?() + } + + func forget() async { + guard !isWorking else { return } + isWorking = true + defer { isWorking = false } + do { + try await access.clear() + hasSavedKey = false + savedRegion = nil + defaults.removeObject(forKey: "zaiQuotaHasSavedKey") + defaults.removeObject(forKey: "zaiQuotaRegion") + status = "Coding Plan API key forgotten." + changed?() + } catch { status = "Keychain could not forget the Coding Plan API key." } + } + + private func remember(_ region: ZCodeQuotaRegion) { + hasSavedKey = true + savedRegion = region + defaults.set(true, forKey: "zaiQuotaHasSavedKey") + defaults.set(region.rawValue, forKey: "zaiQuotaRegion") + } +} + +@MainActor +struct ZAIQuotaSettingsView: View { + @ObservedObject var controller: ZAIQuotaSetupController + @State private var apiKey = "" + @State private var region: ZCodeQuotaRegion = .zAI + + var body: some View { + DisclosureGroup("Z.ai Coding Plan Key") { + Picker("Region", selection: $region) { + ForEach(ZCodeQuotaRegion.allCases) { region in Text(region.title).tag(region) } + } + SecureField("Coding Plan API Key", text: $apiKey) + HStack { + Button("Save Key") { + Task { if await controller.save(apiKey: apiKey, region: region) { apiKey = "" } } + } + .disabled(apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + Button("Re-Authorize Saved Key") { Task { await controller.reauthorize() } } + Button("Forget Key") { + Task { + await controller.forget() + if !controller.hasSavedKey { apiKey = "" } + } + } + .disabled(!controller.hasSavedKey) + if controller.isWorking { ProgressView().controlSize(.small) } + } + if let status = controller.status { Text(status).font(.caption).foregroundStyle(.secondary) } + Text("Enter an existing Coding Plan API key for the selected region." + sentenceGap + + "The key and region are saved together in this build’s Keychain.") + .font(.caption).foregroundStyle(.secondary) + } + .disabled(controller.isWorking) + .onAppear { region = controller.savedRegion ?? .zAI } + .onChange(of: controller.savedRegion) { _, value in region = value ?? .zAI } + } +} diff --git a/Sources/QuotaCore/InfisicalBinding.swift b/Sources/QuotaCore/InfisicalBinding.swift new file mode 100644 index 00000000..0c82b767 --- /dev/null +++ b/Sources/QuotaCore/InfisicalBinding.swift @@ -0,0 +1,102 @@ +import Foundation + +/// Personal credentials and their explicit purpose are persisted only by the app's Keychain store. +public struct InfisicalBinding: Codable, Equatable, Sendable, Identifiable { + public enum Authentication: String, Codable, CaseIterable, Hashable, Sendable { + case serviceToken, machineIdentity + public var title: String { self == .serviceToken ? "Service Token (Recommended)" : "Machine Identity" } + } + public enum Access: String, Codable, CaseIterable, Hashable, Sendable { + case read, write + public var title: String { self == .read ? "Read" : "Write" } + } + public var id: String + public var label: String + public var siteURL: URL + public var projectId: String + public var environment: String + public var secretPath: String + public var authentication: Authentication + public var access: Access + public var serviceToken: String + public var clientId: String + public var clientSecret: String + + public init(id: String = UUID().uuidString, label: String, + siteURL: URL = URL(string: "https://app.infisical.com")!, + projectId: String, environment: String = "prod", secretPath: String = "/", + authentication: Authentication = .serviceToken, access: Access, + serviceToken: String = "", clientId: String = "", clientSecret: String = "") { + self.id = id; self.label = label; self.siteURL = siteURL + self.projectId = projectId; self.environment = environment; self.secretPath = secretPath + self.authentication = authentication; self.access = access + self.serviceToken = serviceToken; self.clientId = clientId; self.clientSecret = clientSecret + } + + public func validate() throws { + guard !id.isEmpty, id.utf8.count <= 128, !label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + label.utf8.count <= 160, !projectId.isEmpty, projectId.utf8.count <= 256, + projectId.unicodeScalars.allSatisfy({ CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "_-" )).contains($0) }), + !environment.isEmpty, environment.utf8.count <= 128, + environment.unicodeScalars.allSatisfy({ CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "_-" )).contains($0) }), + secretPath.hasPrefix("/"), secretPath.utf8.count <= 1_024, + !secretPath.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }), + !secretPath.split(separator: "/", omittingEmptySubsequences: false).contains(where: { $0 == "." || $0 == ".." }), + let site = URLComponents(url: siteURL, resolvingAgainstBaseURL: false), + site.scheme == "https", site.host?.isEmpty == false, + site.user == nil, site.password == nil, site.query == nil, site.fragment == nil else { + throw InfisicalSettings.SettingsError.invalidDestination + } + switch authentication { + case .serviceToken: + let parts = serviceToken.split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false) + guard parts.count == 3, parts[0] == "st", !parts[1].isEmpty, !parts[2].isEmpty, + serviceToken.utf8.count <= 16_384, + serviceToken.unicodeScalars.allSatisfy({ $0.value >= 33 && $0.value <= 126 }) else { + throw InfisicalSettings.SettingsError.invalidDestination + } + case .machineIdentity: + guard !clientId.isEmpty, clientId.utf8.count <= 512, + !clientSecret.isEmpty, clientSecret.utf8.count <= 16_384 else { + throw InfisicalSettings.SettingsError.invalidDestination + } + } + } + + public func matchesScope(of other: Self) -> Bool { + siteURL == other.siteURL && projectId == other.projectId + && environment == other.environment && secretPath == other.secretPath + } +} + +public struct InfisicalSetup: Codable, Equatable, Sendable { + public var bindings: [InfisicalBinding] + public var readBindingID: String? + public var writeBindingID: String? + + public init(bindings: [InfisicalBinding] = [], readBindingID: String? = nil, writeBindingID: String? = nil) { + self.bindings = bindings; self.readBindingID = readBindingID; self.writeBindingID = writeBindingID + } + + public var configuration: InfisicalSettings.Configuration? { + guard let readBindingID, let read = bindings.first(where: { $0.id == readBindingID }), read.access == .read else { return nil } + let write = writeBindingID.flatMap { id in bindings.first { $0.id == id } } + return .init(readBinding: read, writeBinding: write) + } + + public func validate() throws { + guard bindings.count <= 32, Set(bindings.map(\.id)).count == bindings.count else { + throw InfisicalSettings.SettingsError.invalidDestination + } + for binding in bindings { try binding.validate() } + if let writeBindingID { + guard bindings.contains(where: { $0.id == writeBindingID && $0.access == .write }) else { + throw InfisicalSettings.SettingsError.writeNotConfigured + } + } + if readBindingID != nil { + guard let configuration else { throw InfisicalSettings.SettingsError.invalidDestination } + try configuration.validate() + } else if writeBindingID != nil { throw InfisicalSettings.SettingsError.writeNotConfigured } + } +} diff --git a/Sources/QuotaCore/InfisicalSettings.swift b/Sources/QuotaCore/InfisicalSettings.swift index 8d950ade..fd4c6a00 100644 --- a/Sources/QuotaCore/InfisicalSettings.swift +++ b/Sources/QuotaCore/InfisicalSettings.swift @@ -17,11 +17,10 @@ import Foundation /// write throws and leaves the cache untouched — the cache and Infisical /// never diverge silently. /// -/// The universal-auth client secret is provisioned by the owner into his own -/// Keychain (Settings → Infisical Sync) and held here only in memory. It is -/// never logged, never persisted by this type, and never leaves an error -/// message. The iOS companion never holds it at all — the Mac app owns the -/// Infisical read and the companion keeps reading through its existing API. +/// Full service tokens and machine client secrets come from the owner's +/// build-scoped Keychain bindings and remain in memory on this path. +/// Authentication values are never logged or included in error messages. +/// The iOS companion does not hold these Infisical credentials. /// /// The class is `@unchecked Sendable`: every stored property is either a /// value type or guarded by `lock`, so synchronous memory-only reads are safe @@ -50,34 +49,44 @@ public final class InfisicalSettings: @unchecked Sendable { /// timer into a hot loop. public static let minimumRefreshInterval: TimeInterval = 60 - /// Every build reads the `prod` environment, and only `prod`. The dev and - /// staging environments are retired (owner, 2026-10-10), so a `.dev` build - /// reads prod too. `TokenStore` and `InfisicalIdentityStore` still scope - /// Keychain items per build. `accessToken(for:revision:)` refuses any - /// configuration whose environment differs, before any request is sent. + /// Legacy setups keep prod; new bindings explicitly choose their environment. public static func defaultEnvironment() -> String { "prod" } // MARK: - Configuration public struct Configuration: Equatable, Sendable { - public var siteURL: URL - public var projectId: String - public var environment: String - public var clientId: String - public var clientSecret: String - - public init( - siteURL: URL = URL(string: "https://app.infisical.com")!, - projectId: String, - environment: String, - clientId: String, - clientSecret: String - ) { - self.siteURL = siteURL - self.projectId = projectId - self.environment = environment - self.clientId = clientId - self.clientSecret = clientSecret + public var readBinding: InfisicalBinding + public var writeBinding: InfisicalBinding? + + public var siteURL: URL { get { readBinding.siteURL } set { readBinding.siteURL = newValue } } + public var projectId: String { get { readBinding.projectId } set { readBinding.projectId = newValue } } + public var environment: String { get { readBinding.environment } set { readBinding.environment = newValue } } + public var clientId: String { get { readBinding.clientId } set { readBinding.clientId = newValue } } + public var clientSecret: String { get { readBinding.clientSecret } set { readBinding.clientSecret = newValue } } + public var secretPath: String { readBinding.secretPath } + + /// Existing call sites retain machine authentication and receive no implicit write permission. + public init(siteURL: URL = URL(string: "https://app.infisical.com")!, projectId: String, + environment: String, clientId: String, clientSecret: String) { + readBinding = InfisicalBinding(id: "legacy-machine-read", label: "Existing Machine Identity", + siteURL: siteURL, projectId: projectId, environment: environment, + authentication: .machineIdentity, access: .read, clientId: clientId, clientSecret: clientSecret) + writeBinding = nil + } + + public init(readBinding: InfisicalBinding, writeBinding: InfisicalBinding? = nil) { + self.readBinding = readBinding; self.writeBinding = writeBinding + } + + public func validate() throws { + try readBinding.validate() + guard readBinding.access == .read else { throw SettingsError.invalidDestination } + if let writeBinding { + try writeBinding.validate() + guard writeBinding.access == .write, writeBinding.matchesScope(of: readBinding) else { + throw SettingsError.writeNotConfigured + } + } } } @@ -85,6 +94,7 @@ public final class InfisicalSettings: @unchecked Sendable { public enum SettingsError: Error, LocalizedError { case notConfigured + case writeNotConfigured case superseded case invalidDestination case projectUnavailable(status: Int) @@ -96,24 +106,26 @@ public final class InfisicalSettings: @unchecked Sendable { public var errorDescription: String? { switch self { + case .writeNotConfigured: + return "Choose an explicit write binding for the same project, environment, and folder." case .superseded: return "Infisical setup changed while this request was running. Try again with the current setup." case .invalidDestination: - return "Infisical did not confirm the selected Project ID and environment. The previous setup is unchanged." + return "Check the Infisical binding, authentication, and scope fields.\u{00A0} The previous setup is unchanged." case .projectUnavailable(let status): return "Infisical project verification failed (HTTP \(status)). Check the Project ID and identity access." case .notConfigured: - return "Infisical sync is not set up. Add your client identity under Settings → Infisical Sync (see INFISICAL.md)." + return "Infisical sync is not set up.\u{00A0} Select a read binding in Infisical Sync." case .loginFailed(let status): return "Infisical login failed (HTTP \(status)). Check the client identity under Settings → Infisical Sync." case .fetchFailed(let status): return "Infisical settings fetch failed (HTTP \(status)). The last-known-good values are still in effect." case .writeFailed(let status): - return "Infisical write failed (HTTP \(status)) — the setting was NOT saved, so the cache and Infisical cannot diverge." + return "Infisical did not confirm the write (HTTP \(status)).\u{00A0} The cached setting was kept." case .decoding(let what): return "Infisical returned an unexpected response (\(what))." - case .transport(let error): - return "Infisical request failed: \(error.localizedDescription)" + case .transport: + return "Infisical request failed." } } } @@ -154,7 +166,10 @@ public final class InfisicalSettings: @unchecked Sendable { request.httpBody = body // Ephemeral: nothing about these requests is cached, cookied, or // written to disk — same posture as the quota fetchers. - let session = URLSession(configuration: .ephemeral) + let configuration = URLSessionConfiguration.ephemeral + configuration.urlCredentialStorage = nil + let session = URLSession(configuration: configuration, delegate: InfisicalNoRedirects(), delegateQueue: nil) + defer { session.invalidateAndCancel() } let (data, response) = try await session.data(for: request) return (data, (response as? HTTPURLResponse)?.statusCode ?? -1) } @@ -219,9 +234,10 @@ public final class InfisicalSettings: @unchecked Sendable { /// Persistence and the runtime switch share a synchronous commit boundary. /// A Keychain failure leaves the active configuration and cache intact. - public func clearConfiguration(persist: () throws -> Void) throws { + public func clearConfiguration(expectedRevision: Revision? = nil, persist: () throws -> Void) throws { lock.lock() defer { lock.unlock() } + if let expectedRevision, expectedRevision.generation != _generation { throw SettingsError.superseded } _generation &+= 1 try persist() _configuration = nil @@ -248,8 +264,7 @@ public final class InfisicalSettings: @unchecked Sendable { persist: () throws -> Void ) async throws -> Revision { let revision = revision ?? beginSetupChange() - guard !configuration.projectId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, - !configuration.environment.isEmpty else { throw SettingsError.invalidDestination } + try configuration.validate() let values = try await fetchManaged(configuration: configuration, revision: revision, verifyDestination: true) return try commitSetup(configuration, values: values, revision: revision, persist: persist) @@ -273,6 +288,19 @@ public final class InfisicalSettings: @unchecked Sendable { /// Whether the owner has provisioned an Infisical identity. With no /// identity every read falls back to local values and every save stays /// local — today's behaviour, unchanged. + public var canWrite: Bool { + lock.lock() + defer { lock.unlock() } + guard let configuration = _configuration, let write = configuration.writeBinding else { return false } + return write.access == .write && write.matchesScope(of: configuration.readBinding) + && (try? configuration.validate()) != nil + } + + public var activeReadBinding: InfisicalBinding? { + lock.lock(); defer { lock.unlock() } + return _configuration?.readBinding + } + public var isProvisioned: Bool { lock.lock() defer { lock.unlock() } @@ -377,7 +405,11 @@ public final class InfisicalSettings: @unchecked Sendable { public func set(_ value: String, for key: String, expectedRevision: Revision? = nil) async throws { let (configuration, revision) = try configurationOrThrow() if let expectedRevision, expectedRevision != revision { throw SettingsError.superseded } - try await writeSecret(configuration: configuration, revision: revision, key: key, value: value) + try configuration.validate() + guard let write = configuration.writeBinding, write.access == .write, + write.matchesScope(of: configuration.readBinding) else { throw SettingsError.writeNotConfigured } + guard Self.managedKeys.contains(key) else { throw SettingsError.invalidDestination } + try await writeSecret(binding: write, revision: revision, key: key, value: value) try install(value, for: key, revision: revision) } @@ -400,16 +432,14 @@ public final class InfisicalSettings: @unchecked Sendable { // MARK: - Infisical REST - private func accessToken(for configuration: Configuration, revision: Revision) async throws -> String { + private func accessToken(for binding: InfisicalBinding, revision: Revision) async throws -> String { try checkCurrent(revision) - // Prod-only guard: no login, read or write goes out for another environment. - guard configuration.environment == Self.defaultEnvironment() else { - throw SettingsError.invalidDestination - } - let url = configuration.siteURL.appendingPathComponent("api/v1/auth/universal-auth/login") + try binding.validate() + if binding.authentication == .serviceToken { return binding.serviceToken } + let url = binding.siteURL.appendingPathComponent("api/v1/auth/universal-auth/login") let body = try JSONSerialization.data(withJSONObject: [ - "clientId": configuration.clientId, - "clientSecret": configuration.clientSecret, + "clientId": binding.clientId, + "clientSecret": binding.clientSecret, ]) let (data, status) = try await sending { try await self.transport.send( @@ -449,8 +479,9 @@ public final class InfisicalSettings: @unchecked Sendable { private func fetchManaged(configuration: Configuration, revision: Revision, verifyDestination: Bool = false) async throws -> [String: String] { - let token = try await accessToken(for: configuration, revision: revision) - if verifyDestination { + try configuration.validate() + let token = try await accessToken(for: configuration.readBinding, revision: revision) + if verifyDestination && configuration.readBinding.authentication == .machineIdentity { try await verifyProject(configuration: configuration, token: token, revision: revision) } var values: [String: String] = [:] @@ -465,7 +496,7 @@ public final class InfisicalSettings: @unchecked Sendable { components.queryItems = [ URLQueryItem(name: "workspaceId", value: configuration.projectId), URLQueryItem(name: "environment", value: configuration.environment), - URLQueryItem(name: "secretPath", value: "/"), + URLQueryItem(name: "secretPath", value: configuration.secretPath), URLQueryItem(name: "type", value: "shared"), URLQueryItem(name: "expandSecretReferences", value: "false"), URLQueryItem(name: "include_imports", value: "false"), @@ -495,16 +526,16 @@ public final class InfisicalSettings: @unchecked Sendable { return values } - private func writeSecret(configuration: Configuration, revision: Revision, key: String, value: String) async throws { - let token = try await accessToken(for: configuration, revision: revision) + private func writeSecret(binding: InfisicalBinding, revision: Revision, key: String, value: String) async throws { + let token = try await accessToken(for: binding, revision: revision) let encoded = key.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? key // The /raw/ write path accepts a plaintext secretValue (the pilot // validated this: the non-raw path demands client-side E2EE fields). - let url = configuration.siteURL.appendingPathComponent("api/v3/secrets/raw/\(encoded)") + let url = binding.siteURL.appendingPathComponent("api/v3/secrets/raw/\(encoded)") let body = try JSONSerialization.data(withJSONObject: [ - "workspaceId": configuration.projectId, - "environment": configuration.environment, - "secretPath": "/", + "workspaceId": binding.projectId, + "environment": binding.environment, + "secretPath": binding.secretPath, "secretValue": value, "type": "shared", ]) @@ -543,3 +574,12 @@ public final class InfisicalSettings: @unchecked Sendable { } } } + + +private final class InfisicalNoRedirects: NSObject, URLSessionTaskDelegate, @unchecked Sendable { + func urlSession(_ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { + completionHandler(nil) + } +} diff --git a/Sources/QuotaCore/KimiQuotaReader.swift b/Sources/QuotaCore/KimiQuotaReader.swift index 2ccf55ed..63db8475 100644 --- a/Sources/QuotaCore/KimiQuotaReader.swift +++ b/Sources/QuotaCore/KimiQuotaReader.swift @@ -268,8 +268,8 @@ private extension KimiQuotaReader { var providers: [(name: String, fields: [String: String])] = [] var currentName: String? var fields: [String: String] = [:] - for line in text.split(separator: "\n", omittingEmptySubsequences: false) { - let trimmed = line.trimmingCharacters(in: .whitespaces) + for line in text.split(whereSeparator: \.isNewline) { + let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) if trimmed.hasPrefix("[") { if let currentName { providers.append((currentName, fields)) } currentName = providerTableName(trimmed) @@ -339,14 +339,14 @@ private extension KimiQuotaReader { } private static func tomlString(_ raw: String) -> String? { - let value = raw.trimmingCharacters(in: .whitespaces) + let value = raw.trimmingCharacters(in: .whitespacesAndNewlines) guard let quote = value.first, quote == "\"" || quote == "'" else { return nil } var escaped = false for index in value.indices.dropFirst() { let character = value[index] if quote == "\"", character == "\\", !escaped { escaped = true; continue } if character == quote, !escaped { - let tail = value[value.index(after: index)...].trimmingCharacters(in: .whitespaces) + let tail = value[value.index(after: index)...].trimmingCharacters(in: .whitespacesAndNewlines) guard tail.isEmpty || tail.hasPrefix("#") else { return nil } if quote == "'" { return String(value[value.index(after: value.startIndex).. ZCodeQuotaCredential? + ) -> LocalQuotaReaderRegistry { + LocalQuotaReaderRegistry(registrations: [ + LocalQuotaReaderRegistration(id: "local-primary", label: "Built-In Provider Sessions", + configurationMetadata: ["providers": "anthropic,openai,grok,minimax,google-antigravity"]) { + LocalQuotaReader() + }, + LocalQuotaReaderRegistration(id: "cursor", label: "Cursor", configurationMetadata: ["providerKey": "cursor"]) { + CursorQuotaReader() + }, + LocalQuotaReaderRegistration(id: "github-copilot", label: "GitHub Copilot", configurationMetadata: ["providerKey": "github-copilot"]) { + CopilotQuotaReader() + }, + LocalQuotaReaderRegistration(id: "grok-bot", label: "Grok Bot", configurationMetadata: ["providerKey": "grok-bot"]) { + GrokBotQuotaReader() + }, + LocalQuotaReaderRegistration(id: "gbu", label: "Grok Build Usage", configurationMetadata: ["providerKey": "grok-bot"]) { + GbuQuotaReader() + }, + LocalQuotaReaderRegistration(id: "kimi", label: "Kimi", configurationMetadata: ["providerKey": "kimi"], isOptional: true) { + KimiQuotaReader() + }, + LocalQuotaReaderRegistration(id: "zcode", label: "Z.ai / ZCode", configurationMetadata: ["providerKey": "zcode"], isOptional: true) { + ZCodeQuotaReader(credential: zCodeCredentialProvider) + }, + ]) + } } diff --git a/Sources/QuotaCore/WidgetPlatformDisplay.swift b/Sources/QuotaCore/WidgetPlatformDisplay.swift index a08202a1..d02005a1 100644 --- a/Sources/QuotaCore/WidgetPlatformDisplay.swift +++ b/Sources/QuotaCore/WidgetPlatformDisplay.swift @@ -114,9 +114,8 @@ public enum WidgetPlatformDisplay { /// The one percentage a plan card leads with. /// /// It is the lowest honest reading on the card, except that a Muse Assist -/// extra balance that can still be spent speaks for the card: the weekly -/// allowance being spent does not stop the plan while the extra balance is -/// being used, and the weekly row below still shows its own 0%. +/// extra balance takes over only when the weekly allowance is spent. +/// The weekly row below still shows its own 0%. public enum CardHeadline { public struct Reading: Equatable { public var isMuseAssistExtra: Bool @@ -132,11 +131,13 @@ public enum CardHeadline { public static func percent(_ readings: [Reading]) -> Double? { let honest = readings.filter { !$0.isMasked } + let primary = honest.filter { !$0.isMuseAssistExtra }.compactMap(\.remainingPercent).filter { $0.isFinite }.min() if let extra = honest.first(where: { $0.isMuseAssistExtra }), - let percent = extra.remainingPercent, percent.isFinite, percent > 0 { + let percent = extra.remainingPercent, percent.isFinite, percent > 0, + primary == nil || QuotaCapRule.isAtCap(remainingPercent: primary) { return percent } - return honest.compactMap(\.remainingPercent).filter { $0.isFinite }.min() + return primary ?? honest.compactMap(\.remainingPercent).filter { $0.isFinite }.min() } } @@ -151,3 +152,166 @@ public enum UpdatedStamp { return date.formatted(date: .abbreviated, time: .shortened) } } + + +/// Allowance identity and source selection shared by the companion and widgets. +public enum QuotaCardProjection { + public struct Reading: Equatable, Sendable { + public var id: String + public var providerKey: String + public var label: String + public var window: String? + public var modelId: String? + public var modelType: String? + public var remainingPercent: Double? + public var absoluteRemaining: Double? + public var resetAt: Date? + public var reportedAt: Date? + public var source: String? + public var via: String? + + public init(id: String, providerKey: String, label: String, window: String? = nil, + modelId: String? = nil, modelType: String? = nil, + remainingPercent: Double? = nil, absoluteRemaining: Double? = nil, + resetAt: Date? = nil, reportedAt: Date? = nil, + source: String? = nil, via: String? = nil) { + self.id = id + self.providerKey = providerKey + self.label = label + self.window = window + self.modelId = modelId + self.modelType = modelType + self.remainingPercent = remainingPercent + self.absoluteRemaining = absoluteRemaining + self.resetAt = resetAt + self.reportedAt = reportedAt + self.source = source + self.via = via + } + + public var hasReading: Bool { + remainingPercent?.isFinite == true + || (absoluteRemaining?.isFinite == true && (absoluteRemaining ?? -1) >= 0) + } + + /// Only these model limits have a separate detail in the companion. + public var detailName: String? { + let identity = [id, label, modelId ?? "", modelType ?? ""].joined(separator: " ").lowercased() + if providerKey == "anthropic", identity.contains("fable") { return "Fable" } + if providerKey == "google-antigravity", identity.contains("argon") { return "Argon" } + return nil + } + + public var isQuota: Bool { + let lower = label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !id.lowercased().hasSuffix(":plan-metadata"), lower != "plan details" else { return false } + guard !QuotaCapRule.isSupplementaryVideoQuota(providerKey: providerKey, modelId: modelId, + modelType: modelType, label: label), + !QuotaCapRule.isScopedPoolAllowance(providerKey: providerKey, id: id, modelId: modelId, + modelType: modelType, label: label) else { return false } + let subModel = QuotaCapRule.isSubModelLimit(providerKey: providerKey, id: id, modelId: modelId, + modelType: modelType, label: label) + return !subModel || detailName != nil + } + + public var allowanceKey: String { + let cadence = QuotaWindowVocabulary.standardCadence(windowToken: window, label: label, + resetAt: resetAt).lowercased() + if let detailName { return detailName.lowercased() + ":" + cadence } + if QuotaWindowVocabulary.isExtraAllowance(providerKey: providerKey, label: label, windowToken: window) { + return "extra:" + cadence + } + // Primary model names describe observations of the same plan allowance. + return cadence + } + + public var displayLabel: String { + if let detailName { return detailName + " limit" } + if QuotaWindowVocabulary.isExtraAllowanceLabel(label) { return label } + return QuotaWindowVocabulary.windowLabel(windowToken: window, existingLabel: label, resetAt: resetAt) + } + } + + public static func antigravityPeriod(_ reading: Reading) -> String? { + let token = (reading.window ?? "").lowercased().replacingOccurrences(of: " ", with: "") + let label = reading.label.lowercased() + if ["weekly", "week", "1w", "7d", "168h", "10080m"].contains(token) + || label.contains("weekly") || label.contains("week") { return "weekly" } + if ["5h", "5hr", "5-hour", "5hours", "300m"].contains(token) + || label.contains("5h") || label.contains("5-hour") || label.contains("five_hour") { return "5h" } + return nil + } + + /// Exported pool rows are authoritative; raw model observations fill only absent periods. + public static func selectedPoolIndices(in readings: [Reading], poolKey: String, now: Date = Date()) -> [Int] { + ["5h", "weekly"].compactMap { period in + let indices = readings.indices.filter { + readings[$0].detailName == nil && readings[$0].isQuota && antigravityPeriod(readings[$0]) == period + } + guard let pick = preferredIndex(in: indices.map { readings[$0] }, now: now, + canonicalID: "antigravity:" + poolKey + ":" + period) else { return nil } + return indices[pick] + } + } + + /// Prefer measurable, current Mac readings; otherwise use the newest current feed. + /// An unknown placeholder never displaces a measured allowance. + public static func preferredIndex(in readings: [Reading], now: Date = Date(), + canonicalID: String? = nil) -> Int? { + guard !readings.isEmpty else { return nil } + let measured = readings.indices.filter { readings[$0].hasReading } + let available = measured.isEmpty ? Array(readings.indices) : measured + let fresh = available.filter { + QuotaFreshnessRule.isFresh(observedAt: readings[$0].reportedAt, resetAt: readings[$0].resetAt, now: now) + } + let pool = fresh.isEmpty ? available : fresh + if let canonicalID, let canonical = pool.first(where: { readings[$0].id == canonicalID }) { + return canonical + } + let observations = pool.map { + FleetQuotaObservation(remainingPercent: readings[$0].remainingPercent, + reportedAt: readings[$0].reportedAt, + isMacCodeCapsReading: FleetMacReading.isMacCodeCapsReading( + id: readings[$0].id, source: readings[$0].source, via: readings[$0].via)) + } + guard let pick = FleetMacReading.pickCardDisplay(from: observations, now: now) else { return pool.first } + let chosen = pool[pick.chosenIndex] + let chosenIsMac = observations[pick.chosenIndex].isMacCodeCapsReading + let tied = pool.indices.filter { + readings[pool[$0]].reportedAt == readings[chosen].reportedAt + && observations[$0].isMacCodeCapsReading == chosenIsMac + }.map { pool[$0] } + return tied.min { (readings[$0].remainingPercent ?? .infinity) < (readings[$1].remainingPercent ?? .infinity) } ?? chosen + } + + /// One honest row per allowance, primary periods first and model details last. + /// Missing readings remain a provider status rather than an empty quota meter. + public static func selectedIndices(in readings: [Reading], now: Date = Date()) -> [Int] { + var groups: [String: [Int]] = [:] + var order: [String] = [] + for index in readings.indices where readings[index].isQuota { + let key = readings[index].allowanceKey + if groups[key] == nil { order.append(key) } + groups[key, default: []].append(index) + } + let selected = order.compactMap { key -> Int? in + guard let indices = groups[key], + let pick = preferredIndex(in: indices.map { readings[$0] }, now: now) else { return nil } + let index = indices[pick] + return readings[index].hasReading ? index : nil + } + return selected.sorted { left, right in + let l = readings[left], r = readings[right] + if (l.detailName != nil) != (r.detailName != nil) { return l.detailName == nil } + if l.providerKey == "muse-assist" { + let lExtra = QuotaWindowVocabulary.isExtraAllowance(providerKey: l.providerKey, label: l.label, windowToken: l.window) + let rExtra = QuotaWindowVocabulary.isExtraAllowance(providerKey: r.providerKey, label: r.label, windowToken: r.window) + if lExtra != rExtra { return !lExtra } + } + let lp = ResetAlarmCadence.periodSeconds(token: l.window, label: l.label) ?? .infinity + let rp = ResetAlarmCadence.periodSeconds(token: r.window, label: r.label) ?? .infinity + if lp != rp { return lp < rp } + return left < right + } + } +} diff --git a/Sources/QuotaCore/ZCodeQuotaReader.swift b/Sources/QuotaCore/ZCodeQuotaReader.swift index 00515428..c0fa5812 100644 --- a/Sources/QuotaCore/ZCodeQuotaReader.swift +++ b/Sources/QuotaCore/ZCodeQuotaReader.swift @@ -1,106 +1,89 @@ -import CryptoKit import Foundation -/// Reads the GLM Coding Plan quota behind the local ZCode sign-in. -/// -/// ZCode keeps its OAuth business tokens in `~/.zcode/v2/credentials.json`, -/// each value sealed as `enc:v1:..` with AES-256-GCM -/// under a key derived from a per-machine, non-secret fallback string -/// (ZCode's own `credentialCipherProvider.ts`: SHA-256 of -/// `zcode-credential-fallback:darwin::`, overridable through -/// `ZCODE_CREDENTIAL_SECRET`). The monitor endpoint takes the credential -/// verbatim in the `authorization` header — ZCode's own client deliberately -/// adds no `Bearer` prefix. Decrypted values never leave this type; when the -/// store cannot be read or opened the reader says so and publishes nothing. +/// One explicitly supplied Coding Plan key and its inseparable regional endpoint. +public enum ZCodeQuotaRegion: String, Codable, CaseIterable, Equatable, Sendable, Identifiable { + case zAI = "zai" + case bigModel = "bigmodel" + public var id: String { rawValue } + public var title: String { self == .zAI ? "Z.ai" : "BigModel" } + public var quotaURL: URL { + switch self { + case .zAI: return URL(string: "https://api.z.ai/api/monitor/usage/quota/limit")! + case .bigModel: return URL(string: "https://bigmodel.cn/api/monitor/usage/quota/limit")! + } + } +} + +public struct ZCodeQuotaCredential: Codable, Equatable, Sendable { + public var region: ZCodeQuotaRegion + public var apiKey: String + + public init(region: ZCodeQuotaRegion, apiKey: String) { + self.region = region + self.apiKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines) + } + + public var isValid: Bool { + !apiKey.isEmpty && apiKey.utf8.count <= 8_192 + && apiKey.unicodeScalars.allSatisfy { $0.value >= 33 && $0.value <= 126 } + } +} + +/// Reads quota only with an explicitly supplied Coding Plan API key. +/// ZCode's OAuth business tokens are not quota credentials and are never read here. public struct ZCodeQuotaReader: Sendable { private let now: @Sendable () -> Date - private let credentials: @Sendable () -> [String: String] + private let credential: @Sendable () async -> ZCodeQuotaCredential? private let fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) private static let maxResponseBytes = 262_144 - private static let maxCredentialBytes = 1_048_576 private static let timeout: TimeInterval = 15 public init( - homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser, now: @escaping @Sendable () -> Date = { Date() }, - credentials: (@Sendable () -> [String: String])? = nil, + credential: (@Sendable () async -> ZCodeQuotaCredential?)? = nil, fetch: (@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse))? = nil ) { self.now = now - let home = homeDirectory.standardizedFileURL - self.credentials = credentials ?? { Self.readLocalCredentials(home: home) } + self.credential = credential ?? { nil } self.fetch = fetch ?? Self.makeFetcher() } public func read() async -> LocalQuotaResult { do { try Task.checkCancellation() - let store = credentials() - // z.ai first: the desktop sign-in is a Z.ai account; the BigModel - // token is the China-side equivalent of the same plan. - let candidates: [(key: String, url: URL)] = [ - ("oauth:zai:access_token", URL(string: "https://api.z.ai/api/monitor/usage/quota/limit")!), - ("oauth:bigmodel:access_token", URL(string: "https://bigmodel.cn/api/monitor/usage/quota/limit")!), - ] - var sawCredential = false - var rejected = false - for candidate in candidates { - try Task.checkCancellation() - guard let token = store[candidate.key], Self.validToken(token) else { continue } - sawCredential = true - let result: ZCodeHTTPPayload - do { - result = try await Self.fetchQuota(url: candidate.url, token: token, fetch: fetch) - } catch is CancellationError { - // Cooperative cancellation is not a transport failure; - // rethrow so the outer catch reports the cancellation. - throw CancellationError() - } catch { - if Task.isCancelled || (error as? URLError)?.code == .cancelled { throw CancellationError() } - // One unreachable endpoint must not mask a healthy second - // account. - continue - } - if result.statusCode == 401 || result.statusCode == 403 { - rejected = true - continue - } - guard (200..<300).contains(result.statusCode), let root = result.root else { continue } - if let noPlan = Self.noPlanMessage(root) { - return LocalQuotaResult(issues: ["zcode": noPlan]) - } - guard Self.envelopeSucceeded(root), let data = root["data"] as? [String: Any] else { continue } - let windows = Self.parse(data, observedAt: now()) - if windows.isEmpty { - // A 200 envelope with an empty limits array is a truthful - // account state (no quota windows on this plan), not a - // parse failure; say so instead of claiming unreadability. - let rawLimits = data["limits"] as? [[String: Any]] - // Only an observed empty array is the truthful empty - // state; a missing or mistyped limits value is unreadable. - let message = (rawLimits?.isEmpty == true) - ? "ZCode returned no quota windows for this account." - : "ZCode returned no readable quota." - return LocalQuotaResult(issues: ["zcode": message]) - } - let issues = windows.allSatisfy { $0.remainingPercent == nil } - ? ["zcode": "ZCode returned no readable quota."] - : [:] - return LocalQuotaResult(windows: windows, issues: issues) + guard let credential = await credential(), credential.isValid else { + return LocalQuotaResult(issues: ["zcode": "Z.ai quota setup is needed.\u{00A0} Save a Coding Plan API key in Sources & Fleet."]) } - if !sawCredential { - // No ZCode sign-in on this Mac: the product is absent, not broken. - return LocalQuotaResult() + try Task.checkCancellation() + let result = try await Self.fetchQuota(url: credential.region.quotaURL, token: credential.apiKey, fetch: fetch) + if result.statusCode == 401 || result.statusCode == 403 { + return LocalQuotaResult(issues: ["zcode": "The saved Coding Plan API key was rejected."]) } - if rejected { - return LocalQuotaResult(issues: ["zcode": "ZCode session was rejected; sign in again in ZCode."]) + guard (200..<300).contains(result.statusCode), let root = result.root else { + return LocalQuotaResult(issues: ["zcode": "Z.ai quota service is unavailable."]) } - return LocalQuotaResult(issues: ["zcode": "ZCode quota service is unavailable."]) + if let noPlan = Self.noPlanMessage(root) { return LocalQuotaResult(issues: ["zcode": noPlan]) } + guard Self.envelopeSucceeded(root), let data = root["data"] as? [String: Any] else { + return LocalQuotaResult(issues: ["zcode": "Z.ai quota service is unavailable."]) + } + let windows = Self.parse(data, observedAt: now(), region: credential.region) + if windows.isEmpty { + let rawLimits = data["limits"] as? [[String: Any]] + let message = rawLimits?.isEmpty == true + ? "Z.ai returned no quota windows for this account." : "Z.ai returned no readable quota." + return LocalQuotaResult(issues: ["zcode": message]) + } + let issues = windows.allSatisfy { $0.remainingPercent == nil } + ? ["zcode": "Z.ai returned no readable quota."] : [:] + return LocalQuotaResult(windows: windows, issues: issues) } catch is CancellationError { - return LocalQuotaResult(issues: ["zcode": "ZCode quota refresh was cancelled."]) + return LocalQuotaResult(issues: ["zcode": "Z.ai quota refresh was cancelled."]) } catch { - return LocalQuotaResult(issues: ["zcode": "ZCode quota service is unavailable."]) + if Task.isCancelled || (error as? URLError)?.code == .cancelled { + return LocalQuotaResult(issues: ["zcode": "Z.ai quota refresh was cancelled."]) + } + return LocalQuotaResult(issues: ["zcode": "Z.ai quota service is unavailable."]) } } } @@ -149,7 +132,7 @@ private extension ZCodeQuotaReader { static func noPlanMessage(_ root: [String: Any]) -> String? { let message = (root["msg"] as? String) ?? (root["message"] as? String) ?? "" if message.contains("不存在coding plan") || message.contains("没有资格") { - return "No GLM Coding Plan is active on this ZCode account." + return "No GLM Coding Plan is active on this account." } return nil } @@ -160,7 +143,7 @@ private extension ZCodeQuotaReader { /// `unit: 3` is the rolling five-hour window, `unit: 6` the weekly one — /// and TIME_LIMIT is the monthly tool-call quota. `percentage` is the /// USED share; CodeCaps rows show what remains. - static func parse(_ data: [String: Any], observedAt: Date) -> [QuotaWindow] { + static func parse(_ data: [String: Any], observedAt: Date, region: ZCodeQuotaRegion) -> [QuotaWindow] { let observed = ISO8601DateFormatter().string(from: observedAt) let plan = (data["level"] as? String).flatMap { level -> String? in guard !level.isEmpty, level.utf8.count <= 40, @@ -192,7 +175,7 @@ private extension ZCodeQuotaReader { let exhausted = percent == 0 windows.append(QuotaWindow( id: "local-mac:zcode:\(type.lowercased())-\(unit.map(String.init) ?? "x")", - provider: "ZCode", providerKey: "zcode", providerLabel: "ZCode", + provider: region.title, providerKey: "zcode", providerLabel: region.title, sourceApp: "local-mac", label: descriptor.label, remainingPercent: percent, absoluteRemaining: remaining, absoluteLimit: cap, @@ -227,63 +210,6 @@ private extension ZCodeQuotaReader { return ISO8601DateFormatter().string(from: Date(timeIntervalSince1970: milliseconds / 1000)) } - // MARK: - Local credential store - - /// Decrypts the values of `~/.zcode/v2/credentials.json`. Any entry that - /// fails to open is dropped rather than failing the whole store, and a - /// store that yields no usable values reads as "not signed in". - static func readLocalCredentials(home: URL) -> [String: String] { - let environment = ProcessInfo.processInfo.environment - let base = environment["ZCODE_DATA_BASE_DIR"].map { URL(fileURLWithPath: $0) } ?? home - let file = base.appendingPathComponent(".zcode/v2/credentials.json") - guard let data = try? Data(contentsOf: file, options: .mappedIfSafe), - data.count <= Self.maxCredentialBytes, - let raw = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { - return [:] - } - let secret = environment["ZCODE_CREDENTIAL_SECRET"] - ?? "zcode-credential-fallback:darwin:\(home.path):\(NSUserName())" - let key = SymmetricKey(data: Data(SHA256.hash(data: Data(secret.utf8)))) - var store: [String: String] = [:] - for (name, value) in raw { - guard let text = value as? String else { continue } - if let opened = decrypt(text, key: key) { - store[name] = opened - } else if !text.hasPrefix("enc:v1:"), validToken(text) { - store[name] = text - } - } - return store - } - - /// Opens one `enc:v1:..` value (AES-256-GCM, 12-byte - /// nonce, 16-byte tag; base64url segments, in ZCode's own order). - static func decrypt(_ value: String, key: SymmetricKey) -> String? { - let prefix = "enc:v1:" - guard value.hasPrefix(prefix) else { return nil } - let parts = value.dropFirst(prefix.count).split(separator: ".", omittingEmptySubsequences: false) - guard parts.count == 3, - let nonceData = base64url(parts[0]), nonceData.count == 12, - let tagData = base64url(parts[1]), tagData.count == 16, - let ciphertext = base64url(parts[2]), !ciphertext.isEmpty, - let nonce = try? AES.GCM.Nonce(data: nonceData), - let box = try? AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tagData), - let opened = try? AES.GCM.open(box, using: key) else { - return nil - } - return String(data: opened, encoding: .utf8) - } - - static func base64url(_ text: Substring) -> Data? { - var base64 = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") - base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4) - return Data(base64Encoded: base64) - } - - static func validToken(_ token: String) -> Bool { - !token.isEmpty && token.utf8.count <= 8_192 && !token.contains("\r") && !token.contains("\n") - } - static func makeFetcher() -> @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) { return { request in let config = URLSessionConfiguration.ephemeral diff --git a/Tests/CodeCapsTests/CompanionModelTests.swift b/Tests/CodeCapsTests/CompanionModelTests.swift index 6ca401fd..209d7b62 100644 --- a/Tests/CodeCapsTests/CompanionModelTests.swift +++ b/Tests/CodeCapsTests/CompanionModelTests.swift @@ -8,6 +8,45 @@ import QuotaCore /// Mirrors the companion contract used on iOS so behavioral regressions /// are caught directly in the standard `swift test` suite. final class CompanionModelTests: XCTestCase { + @MainActor + func testSharedProjectionMatchesActualMacMetersForSanitizedScreenshotRows() { + let now = Date(timeIntervalSince1970: 1_800_000_000) + let stamp = ISO8601DateFormatter().string(from: now) + let reset = ISO8601DateFormatter().string(from: now.addingTimeInterval(3600)) + func window(_ id: String, _ provider: String, _ token: String?, _ percent: Double?, + model: String? = nil, label: String = "Quota") -> QuotaWindow { + QuotaWindow(id: id, provider: provider, providerKey: provider, modelId: model, label: label, + remainingPercent: percent, remainingUnknown: percent == nil, resetAt: reset, + window: token, occurredAt: stamp, source: "CodeCaps") + } + let fixtures = [ + [window("minimax:plan", "minimax", nil, nil, label: "Plan"), + window("minimax:5h", "minimax", "5h", 92, model: "general"), + window("minimax:7d", "minimax", "7d", 74, model: "general")], + [window("claude:plan", "anthropic", nil, nil, label: "Plan"), + window("claude:5h", "anthropic", "5h", 80), + window("claude:missing", "anthropic", "7d", nil), + window("claude:7d", "anthropic", "7d", 0), + window("claude:fable", "anthropic", "7d", 0, model: "fable")] + ] + for windows in fixtures { + let section = QuotaResponse(generatedAt: stamp, windows: windows).platformSections(now: now) + .first { !$0.windows.isEmpty }! + let mac = DisplaySection.rows(for: section, now: now)[0] + let pair = glanceMeterPair(for: mac, now: now) + let macIDs = [pair.short?.window.id, pair.long?.window.id].compactMap { $0 } + let readings = windows.map { + QuotaCardProjection.Reading(id: $0.id, providerKey: $0.canonicalProviderKey, label: $0.label, + window: $0.window, modelId: $0.modelId, remainingPercent: $0.boundedRemainingPercent, + resetAt: $0.resetDate, reportedAt: $0.occurredDate, source: $0.source) + } + let companionIDs = QuotaCardProjection.selectedIndices(in: readings, now: now) + .filter { readings[$0].detailName == nil }.map { readings[$0].id } + XCTAssertEqual(companionIDs, macIDs) + XCTAssertEqual(companionIDs.count, 2) + } + } + func testPhoneNonfiniteReadingGuardsRemainAtTextAndBarBoundaries() throws { let source = try readCompanionModelSource() XCTAssertTrue(source.contains("guard let remainingPercent, remainingPercent.isFinite else { return \"—\" }")) @@ -316,8 +355,8 @@ final class CompanionModelTests: XCTestCase { func testAntigravityRowSelectsDrivingObservationWithoutAveraging() throws { let source = try readCompanionModelSource() XCTAssertTrue( - source.contains("(left.remainingPercent ?? 101) < (right.remainingPercent ?? 101)"), - "a tie between two models of one shared pool must take the lower value" + source.contains("QuotaCardProjection.selectedPoolIndices(in: facts, poolKey: poolKey, now: now)"), + "the companion must use the shared pool resolver tested for lower-value ties" ) XCTAssertFalse( source.contains("remainingPercent) / Double("), @@ -340,8 +379,8 @@ final class CompanionModelTests: XCTestCase { func testNonAntigravityPlatformsKeepTheirOwnWindows() throws { let source = try readCompanionModelSource() XCTAssertTrue( - source.contains("let modelQualifier = (w.modelId ?? \"\").lowercased()"), - "buildPlatformSection must still fold ordinary platforms by model-qualified cadence" + source.contains("let cadenceKey = reading(w).allowanceKey"), + "ordinary provider windows must use shared allowance identity, preserving named model details" ) } @@ -710,14 +749,10 @@ final class CompanionModelTests: XCTestCase { func testMiniMaxConsolidationToTwoWindows() throws { let source = try readCompanionModelSource() - XCTAssertTrue( - source.contains(#"let isMiniMax = providerKey.lowercased().contains("minimax")"#), - "MiniMax must be identified during platform section building" - ) - XCTAssertTrue( - source.contains("let effectiveQualifier = isMiniMax ? \"\" : modelQualifier"), - "MiniMax must not split cadences by modelQualifier, collapsing into two primary windows" - ) + XCTAssertTrue(source.contains("let cadenceKey = reading(w).allowanceKey"), + "MiniMax model names must not create duplicate allowance rows") + XCTAssertTrue(source.contains("QuotaCardProjection.preferredIndex(in: [reading(current), reading(candidate)], now: now)"), + "MiniMax and other providers must share measured Mac/source precedence") } func testCompanionMeterUsesHyphenatedCaptionsNotPopoverTags() throws { @@ -926,11 +961,11 @@ final class CompanionModelTests: XCTestCase { "the phone must pick the freshest five-hour window, not the first one in payload order" ) XCTAssertTrue( - source.contains("if isFresher(w, than: weeklyWin) { weeklyWin = w }"), + source.contains("let weeklyWin = selected.first { Self.antigravityPeriod(of: $0) == \"weekly\" }"), "the phone's weekly window must be the freshest one that matches" ) XCTAssertTrue( - source.contains("if isFresher(w, than: fiveHourWin) { fiveHourWin = w }"), + source.contains("let fiveHourWin = selected.first { Self.antigravityPeriod(of: $0) == \"5h\" }"), "the phone's five-hour window must be the freshest one that matches" ) XCTAssertTrue( diff --git a/Tests/CodeCapsTests/InfisicalIdentityStoreTests.swift b/Tests/CodeCapsTests/InfisicalIdentityStoreTests.swift index 561acc22..82556e7b 100644 --- a/Tests/CodeCapsTests/InfisicalIdentityStoreTests.swift +++ b/Tests/CodeCapsTests/InfisicalIdentityStoreTests.swift @@ -126,4 +126,44 @@ final class InfisicalIdentityStoreTests: XCTestCase { XCTAssertNil(InfisicalIdentityStore.load(bundleIdentifier: "com.jays.agent-bar.mac.test")) } + func testV1MigrationPreservesMachineReadsButNeverInfersWriteAccess() throws { + let service = "com.jays.agent-bar.mac.test.infisical-identity" + let legacy = #"{"version":1,"identity":{"clientId":"legacy-id","clientSecret":"legacy-secret","projectId":"project-A"}}"# + vault["\(service)/setup-v1"] = legacy + let setup = try XCTUnwrap(InfisicalIdentityStore.loadSetup(bundleIdentifier: "com.jays.agent-bar.mac.test")) + XCTAssertEqual(setup.bindings.count, 1) + XCTAssertEqual(setup.configuration?.readBinding.authentication, .machineIdentity) + XCTAssertEqual(setup.configuration?.readBinding.environment, "prod") + XCTAssertEqual(setup.configuration?.readBinding.secretPath, "/") + XCTAssertEqual(setup.configuration?.readBinding.clientSecret, "legacy-secret") + XCTAssertNil(setup.writeBindingID) + XCTAssertNil(setup.configuration?.writeBinding) + XCTAssertEqual(vault["\(service)/setup-v1"], legacy, "Startup migration must not rewrite working credentials") + } + + func testV2RetainsMultipleScopesAndIndependentSelectionsInOneKeychainRecord() throws { + let read = InfisicalBinding(id: "read", label: "Project A Read", projectId: "project-A", environment: "qa", + secretPath: "/codecaps", access: .read, serviceToken: "st.fixture.read-secret") + var write = read + write.id = "write"; write.label = "Project A Write"; write.access = .write; write.serviceToken = "st.fixture.write-secret" + let other = InfisicalBinding(id: "other", label: "Other Project", projectId: "project-B", environment: "prod", + secretPath: "/shared", access: .read, serviceToken: "st.fixture.other-secret") + let setup = InfisicalSetup(bindings: [read, write, other], readBindingID: read.id, writeBindingID: write.id) + try InfisicalIdentityStore.saveSetup(setup, bundleIdentifier: "com.jays.agent-bar.mac.test") + XCTAssertEqual(InfisicalIdentityStore.loadSetup(bundleIdentifier: "com.jays.agent-bar.mac.test"), setup) + XCTAssertEqual(vault.count, 1) + XCTAssertNil(InfisicalIdentityStore.load(bundleIdentifier: "com.jays.agent-bar.mac.test")) + } + + func testMismatchedWriteBindingNeverReplacesTheSavedSetup() throws { + let identity = InfisicalIdentityStore.Identity(clientId: "id", clientSecret: "secret", projectId: "project-A") + try InfisicalIdentityStore.save(identity, bundleIdentifier: "com.jays.agent-bar.mac.test") + var setup = try XCTUnwrap(InfisicalIdentityStore.loadSetup(bundleIdentifier: "com.jays.agent-bar.mac.test")) + var write = setup.bindings[0] + write.id = "write"; write.access = .write; write.secretPath = "/another-folder" + setup.bindings.append(write); setup.writeBindingID = write.id + XCTAssertThrowsError(try InfisicalIdentityStore.saveSetup(setup, bundleIdentifier: "com.jays.agent-bar.mac.test")) + XCTAssertEqual(InfisicalIdentityStore.load(bundleIdentifier: "com.jays.agent-bar.mac.test"), identity) + } + } diff --git a/Tests/CodeCapsTests/ZAIQuotaSetupTests.swift b/Tests/CodeCapsTests/ZAIQuotaSetupTests.swift new file mode 100644 index 00000000..ca87107a --- /dev/null +++ b/Tests/CodeCapsTests/ZAIQuotaSetupTests.swift @@ -0,0 +1,113 @@ +import XCTest +import Security +import QuotaCore +@testable import CodeCaps + +@MainActor +final class ZAIQuotaSetupTests: XCTestCase { + func testSavedRegionAndKeyRoundTripAsOneNarrowBuildScopedRecord() async throws { + let vault = ZAIQuotaKeychainFixture() + let store = ZAIQuotaCredentialStore(calls: vault.calls, bundleIdentifier: "com.example.CodeCaps.test") + let missing = await store.load() + XCTAssertNil(missing) + let credential = ZCodeQuotaCredential(region: .bigModel, apiKey: "fixture-key") + try await store.save(credential) + let loaded = await store.load() + XCTAssertEqual(loaded, credential) + XCTAssertEqual(loaded?.region.quotaURL.host, "bigmodel.cn") + XCTAssertEqual(vault.count, 1) + XCTAssertEqual(vault.services, ["com.example.CodeCaps.test.zai-quota-api-key"]) + XCTAssertFalse(TokenStore.ownServices.contains("com.example.CodeCaps.test.zai-quota-api-key")) + try await store.clear() + let forgotten = await store.load() + XCTAssertNil(forgotten) + XCTAssertEqual(vault.count, 0) + } + + func testInvalidKeyIsRejectedBeforeAnyKeychainWriteAndDevelopmentServicesDiffer() async { + let vault = ZAIQuotaKeychainFixture() + let store = ZAIQuotaCredentialStore(calls: vault.calls, bundleIdentifier: "com.example.CodeCaps.test") + do { + try await store.save(.init(region: .zAI, apiKey: String(repeating: "a", count: 8_193))) + XCTFail("Oversized key must be refused") + } catch { XCTAssertTrue(error is ZAIQuotaCredentialStore.Failure) } + XCTAssertEqual(vault.count, 0) + XCTAssertTrue(vault.services.isEmpty) + XCTAssertNotEqual(ZAIQuotaCredentialStore.serviceName(bundleIdentifier: "com.example.CodeCaps"), + ZAIQuotaCredentialStore.serviceName(bundleIdentifier: "com.example.CodeCaps.dev")) + } + + func testSetupIsExplicitAndPreferencesNeverContainTheKey() async { + let suite = "ZAIQuotaSetupTests." + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + var saved: ZCodeQuotaCredential? + var authorizations = 0 + var clears = 0 + var changes = 0 + let controller = ZAIQuotaSetupController(defaults: defaults, access: .init( + save: { saved = $0 }, clear: { saved = nil; clears += 1 }, + reauthorize: { authorizations += 1; return saved })) + controller.changed = { changes += 1 } + XCTAssertNil(saved) + XCTAssertEqual(authorizations, 0) + let success = await controller.save(apiKey: "fixture-key", region: .bigModel) + XCTAssertTrue(success) + XCTAssertEqual(saved?.region, .bigModel) + XCTAssertTrue(controller.hasSavedKey) + XCTAssertEqual(controller.savedRegion, .bigModel) + XCTAssertEqual(changes, 1) + XCTAssertFalse(defaults.dictionaryRepresentation().values.contains { ($0 as? String)?.contains("fixture-key") == true }) + await controller.reauthorize() + XCTAssertEqual(authorizations, 1) + await controller.forget() + XCTAssertEqual(clears, 1) + XCTAssertFalse(controller.hasSavedKey) + XCTAssertNil(controller.savedRegion) + XCTAssertEqual(changes, 3) + } + + func testFailedStoreWritesKeepSetupMetadataAndDoNotSignalAChangedReader() async { + let suite = "ZAIQuotaSetupTests." + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + enum Failure: Error { case refused } + let controller = ZAIQuotaSetupController(defaults: defaults, access: .init( + save: { _ in throw Failure.refused }, clear: { throw Failure.refused }, reauthorize: { nil })) + var changes = 0 + controller.changed = { changes += 1 } + let success = await controller.save(apiKey: "fixture-key", region: .zAI) + XCTAssertFalse(success) + XCTAssertFalse(controller.hasSavedKey) + XCTAssertEqual(changes, 0) + XCTAssertFalse(controller.status?.contains("fixture-key") ?? true) + await controller.forget() + XCTAssertEqual(changes, 0) + } +} + +private final class ZAIQuotaKeychainFixture: @unchecked Sendable { + private let lock = NSLock() + private var values: [String: Data] = [:] + private var touched: Set = [] + var calls: KeychainCalls { + .init(copyData: { service, account, _ in + self.lock.lock(); defer { self.lock.unlock() } + self.touched.insert(service) + let data = self.values[service + "/" + account] + return (data == nil ? errSecItemNotFound : errSecSuccess, data) + }, delete: { service, account in + self.lock.lock(); defer { self.lock.unlock() } + self.touched.insert(service) + self.values[service + "/" + account] = nil + return errSecSuccess + }, add: { service, account, data in + self.lock.lock(); defer { self.lock.unlock() } + self.touched.insert(service) + self.values[service + "/" + account] = data + return errSecSuccess + }) + } + var count: Int { lock.lock(); defer { lock.unlock() }; return values.count } + var services: Set { lock.lock(); defer { lock.unlock() }; return touched } +} diff --git a/Tests/Fixtures/WidgetUIProbe.swift b/Tests/Fixtures/WidgetUIProbe.swift index 628bbe61..e3f16ff9 100644 --- a/Tests/Fixtures/WidgetUIProbe.swift +++ b/Tests/Fixtures/WidgetUIProbe.swift @@ -4,6 +4,62 @@ import WidgetKit import AppIntents @main struct Gallery { @MainActor static func checkSemantics() async throws { + let stamp = ISO8601DateFormatter().string(from: Date()) + let reset = ISO8601DateFormatter().string(from: Date().addingTimeInterval(3600)) + func wire(_ id: String, _ provider: String, _ token: String?, _ percent: Double?, + _ label: String = "Quota", model: String? = nil, source: String? = nil) -> [String: Any] { + var value: [String: Any] = ["id":id, "provider":provider, "providerKey":provider, + "label":label, "occurredAt":stamp, "reportedAt":stamp, "resetAt":reset] + value["window"] = token; value["remainingPercent"] = percent + value["modelId"] = model; value["source"] = source + return value + } + let payload = [ + wire("claude:plan-metadata", "anthropic", nil, nil, "Plan Details"), + wire("claude:5h", "anthropic", "5h", 80), wire("claude:7d", "anthropic", "7d", 0), + wire("claude:7d:missing", "anthropic", "7d", nil), + wire("claude:fable", "anthropic", "7d", 0, model:"Fable"), + wire("plan", "minimax", nil, nil, "Plan"), wire("minimax:5h", "minimax", "5h", 92), + wire("minimax:7d", "minimax", "7d", 74), + wire("raw:gemini:5h", "google-antigravity", "5h", 7, "Gemini 5-hour"), + wire("antigravity:gemini:5h", "google-antigravity", "5h", 63, "Gemini Models · 5-hour"), + wire("antigravity:gemini:weekly", "google-antigravity", "7d", 1, "Gemini Models · Weekly"), + wire("gemini:argon", "google-antigravity", "5h", 0, "Gemini Argon", model:"Argon"), + wire("mirror:github-copilot", "github-copilot", "1m", 0), + wire("local-mac:github-copilot", "github-copilot", "1m", 100, source:"CodeCaps") + ] + let parsed = WidgetPresentation.parseSnapshot(data: try JSONSerialization.data(withJSONObject:["windows":payload])) + let claude = parsed.first { $0.providerKey == "anthropic" }! + precondition(claude.primaryWindows.count == 2 && claude.detailWindows.map(\.label) == ["Fable limit"]) + precondition(claude.dualWindows()?.window2.id == "claude:7d") + precondition(claude.atCapWindow()?.id == "claude:7d") + let minimax = parsed.first { $0.providerKey == "minimax" }! + precondition(minimax.windows.count == 2 && !minimax.hasModelDetails && minimax.remainingPercent == 74) + let gemini = parsed.first { $0.id == "antigravity-gemini" }! + precondition(gemini.primaryWindows.map(\.remainingPercent) == [63, 1]) + precondition(gemini.remainingPercent == 1 && gemini.detailWindows.map(\.label) == ["Argon limit"]) + precondition(gemini.atCapWindow() == nil) + let copilot = parsed.first { $0.providerKey == "github-copilot" }! + precondition(copilot.title == "GitHub Copilot" && copilot.remainingPercent == 100) + precondition(copilot.primaryWindows.count == 1 && !copilot.hasModelDetails) + let week = CompanionWindowItem(id:"weekly", label:"7-day", cadence:"7d", remainingPercent:57, + resetAt:Date().addingTimeInterval(3600), reportedAt:Date()) + let plan = CompanionWindowItem(id:"plan", label:"Plan", cadence:"Plan", remainingPercent:nil, resetAt:nil) + let fable = CompanionWindowItem(id:"fable", label:"Fable limit", cadence:"7d", remainingPercent:0, + resetAt:Date().addingTimeInterval(3600), isSubModelLimit:true, reportedAt:Date()) + let phone = CompanionQuotaItem(id:"anthropic", providerKey:"anthropic", title:"Claude Code", subtitle:nil, + remainingPercent:0, resetAt:nil, isExhausted:false, isAlarmEnabled:false, windows:[plan,week,fable]) + precondition(phone.cardShortWindow(scope:.allSources)?.window.id == "weekly") + precondition(phone.cardLongWindow(scope:.allSources) == nil && phone.cardRemainingPercent(scope:.allSources) == 57) + precondition(phone.isExpandable && phone.cardDetailWindows(scope:.allSources).map(\.label) == ["Fable limit"]) + let weeklyHealthy = WidgetWindowItem(id:"weekly", label:"Weekly", cadence:"7d", remainingPercent:47, resetAt:nil) + let positiveExtra = WidgetWindowItem(id:"extra", label:"Additional tokens", cadence:"Other limit", remainingPercent:81, + resetAt:nil, isExtraAllowance:true) + let healthyMuse = WidgetPlatformItem(id:"muse-assist", providerKey:"muse-assist", title:"Muse Assist", subtitle:"", + remainingPercent:47, resetAt:nil, windows:[weeklyHealthy,positiveExtra]) + precondition(healthyMuse.controllingWindow()?.id == "weekly") + precondition(WidgetPresentation.displayPercent(percent:.nan,isMasked:false) == "—") + print("PASS: sanitized parser and companion selection preserve primary quotas, Fable, Argon and Mac precedence") let missing=WidgetWindowItem(id:"missing",label:"Other limit",cadence:"Other limit",remainingPercent:nil,resetAt:nil) let zero=WidgetWindowItem(id:"zero",label:"7-day",cadence:"7d",remainingPercent:0,resetAt:nil) let extra=WidgetWindowItem(id:"extra",label:"Other limit",cadence:"Other limit",remainingPercent:83,resetAt:nil,isExtraAllowance:true) From 7116a684ba83f3cd05ff5c04cb93a5c28baf9614 Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:38:12 +0000 Subject: [PATCH 08/12] Align Companion And Widget Quotas With Mac Selection --- .../InfisicalBindingTests.swift | 106 ++++++++ .../InfisicalProjectSelectionTests.swift | 6 +- .../InfisicalSettingsTests.swift | 58 +++-- .../QuotaCoreTests/KimiQuotaReaderTests.swift | 23 ++ .../LocalQuotaReaderRegistryTests.swift | 21 ++ .../QuotaCardProjectionTests.swift | 90 +++++++ .../ZCodeQuotaReaderTests.swift | 108 +++++--- docs/AUTO-UPDATE.md | 9 +- docs/CI-INFISICAL-SERVICE-TOKENS.md | 14 + ...6-11-03-cc205-monitoring-alert-controls.md | 12 + .../App/Models/CompanionQuotaModel.swift | 134 +++++----- .../App/Views/CompanionContentView.swift | 30 +-- .../Widgets/WidgetDataProvider.swift | 2 +- .../Widgets/WidgetPresentation.swift | 242 ++++++------------ .../Widgets/WidgetViews.swift | 12 +- .../Widgets/WidgetWindowRows.swift | 2 +- scripts/cursor-cloud-start.sh | 43 ++-- scripts/infisical-fetch-expand.node-test.mjs | 17 +- scripts/infisical-fetch.mjs | 52 ++-- scripts/infisical-fetch.node-test.mjs | 32 +-- 20 files changed, 589 insertions(+), 424 deletions(-) create mode 100644 Tests/QuotaCoreTests/InfisicalBindingTests.swift create mode 100644 Tests/QuotaCoreTests/QuotaCardProjectionTests.swift create mode 100644 docs/CI-INFISICAL-SERVICE-TOKENS.md diff --git a/Tests/QuotaCoreTests/InfisicalBindingTests.swift b/Tests/QuotaCoreTests/InfisicalBindingTests.swift new file mode 100644 index 00000000..94515d98 --- /dev/null +++ b/Tests/QuotaCoreTests/InfisicalBindingTests.swift @@ -0,0 +1,106 @@ +import XCTest +@testable import QuotaCore + +final class InfisicalBindingTests: XCTestCase { + private func binding(_ access: InfisicalBinding.Access, token: String) -> InfisicalBinding { + .init(id: access.rawValue, label: access.title, projectId: "project-A", environment: "qa", + secretPath: "/apps/codecaps", access: access, serviceToken: token) + } + + func testServiceTokenIsSentIntactWithoutLoginOrProjectMetadataRequests() async throws { + let transport = MockInfisicalTransport() + let token = "st.fixture-id.complete-secret-part" + transport.handler = { method, url, headers, _ in + XCTAssertEqual(method, "GET") + XCTAssertTrue(url.path.contains("/api/v3/secrets/raw/")) + XCTAssertEqual(headers["Authorization"], "Bearer " + token) + return (Data(), 404) + } + let settings = InfisicalSettings(transport: transport) + try await settings.validateAndConfigure(.init(readBinding: binding(.read, token: token)), persist: {}) + XCTAssertEqual(transport.calls.count, 3) + XCTAssertFalse(settings.canWrite) + } + + func testWriteUsesSeparateMatchingCredentialAndPreservesItsScopeForCreateFallback() async throws { + let transport = MockInfisicalTransport() + transport.handler = { method, url, headers, body in + if method == "GET" { + XCTAssertEqual(headers["Authorization"], "Bearer st.fixture.read-secret") + return (Data(), 404) + } + XCTAssertEqual(headers["Authorization"], "Bearer st.fixture.write-secret") + let fields = try XCTUnwrap(body.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }) + XCTAssertEqual(fields["workspaceId"] as? String, "project-A") + XCTAssertEqual(fields["environment"] as? String, "qa") + XCTAssertEqual(fields["secretPath"] as? String, "/apps/codecaps") + XCTAssertTrue(url.path.hasSuffix("PULL_ENDPOINT")) + return (Data(), method == "PATCH" ? 404 : 200) + } + let settings = InfisicalSettings(transport: transport) + let read = binding(.read, token: "st.fixture.read-secret") + let write = binding(.write, token: "st.fixture.write-secret") + try await settings.validateAndConfigure(.init(readBinding: read, writeBinding: write), persist: {}) + XCTAssertTrue(settings.canWrite) + try await settings.set("https://quota.example/pull", for: InfisicalSettings.Keys.pullEndpoint) + XCTAssertEqual(transport.methods, ["GET", "GET", "GET", "PATCH", "POST"]) + XCTAssertEqual(settings.value(for: InfisicalSettings.Keys.pullEndpoint), "https://quota.example/pull") + } + + func testReadCredentialIsNeverInferredToAuthorizeWrites() async { + let transport = MockInfisicalTransport() + let settings = InfisicalSettings(transport: transport) + settings.configure(.init(readBinding: binding(.read, token: "st.fixture.read-secret"))) + do { + try await settings.set("value", for: InfisicalSettings.Keys.pullEndpoint) + XCTFail("No selected write binding must fail") + } catch InfisicalSettings.SettingsError.writeNotConfigured {} catch { XCTFail("Unexpected error") } + XCTAssertTrue(transport.calls.isEmpty) + } + + func testWriteCannotCrossProjectEnvironmentFolderOrSite() async { + let read = binding(.read, token: "st.fixture.read-secret") + for mismatch in 0..<4 { + var write = binding(.write, token: "st.fixture.write-secret") + if mismatch == 0 { write.projectId = "project-B" } + if mismatch == 1 { write.environment = "prod" } + if mismatch == 2 { write.secretPath = "/another-folder" } + if mismatch == 3 { write.siteURL = URL(string: "https://another.example")! } + let transport = MockInfisicalTransport() + let settings = InfisicalSettings(transport: transport) + settings.configure(.init(readBinding: read, writeBinding: write)) + do { try await settings.set("value", for: InfisicalSettings.Keys.pullEndpoint); XCTFail("Mismatched scope must fail") } + catch InfisicalSettings.SettingsError.writeNotConfigured {} catch { XCTFail("Unexpected error") } + XCTAssertTrue(transport.calls.isEmpty) + } + } + + func testInvalidServiceTokensAndMissingSelectionsFailClosed() { + for token in ["secret-only", "Bearer st.id.secret", "st..secret", "st.id.", "st.id.first\nsecond"] { + XCTAssertThrowsError(try binding(.read, token: token).validate()) + } + let read = binding(.read, token: "st.fixture.read-secret") + XCTAssertThrowsError(try InfisicalSetup(bindings: [read], readBindingID: read.id, writeBindingID: "missing").validate()) + let write = binding(.write, token: "st.fixture.write-secret") + XCTAssertThrowsError(try InfisicalSetup(bindings: [write], writeBindingID: write.id).validate()) + XCTAssertNoThrow(try InfisicalSetup(bindings: [read, write]).validate()) + } + func testRetiredDisconnectCannotDeleteANewerSelectedSource() throws { + let transport = MockInfisicalTransport() + let settings = InfisicalSettings(transport: transport) + settings.configure(.init(readBinding: binding(.read, token: "st.fixture.read-secret"))) + let retired = settings.beginSetupChange() + var newer = binding(.read, token: "st.fixture.other-secret") + newer.projectId = "project-B" + settings.configure(.init(readBinding: newer)) + XCTAssertThrowsError(try settings.clearConfiguration(expectedRevision: retired) { + XCTFail("A retired disconnect must not delete the current Keychain setup") + }) { error in + guard case InfisicalSettings.SettingsError.superseded = error else { return XCTFail("Expected superseded disconnect") } + } + XCTAssertEqual(settings.activeReadBinding?.projectId, "project-B") + XCTAssertTrue(settings.isProvisioned) + XCTAssertTrue(transport.calls.isEmpty) + } + +} diff --git a/Tests/QuotaCoreTests/InfisicalProjectSelectionTests.swift b/Tests/QuotaCoreTests/InfisicalProjectSelectionTests.swift index 8e85a6ef..42d55292 100644 --- a/Tests/QuotaCoreTests/InfisicalProjectSelectionTests.swift +++ b/Tests/QuotaCoreTests/InfisicalProjectSelectionTests.swift @@ -68,7 +68,11 @@ private actor ProjectSelectionTransport: InfisicalSettings.Transport { } private func projectConfiguration(_ project: String) -> InfisicalSettings.Configuration { - .init(projectId: project, environment: "prod", clientId: "synthetic-id", clientSecret: "synthetic-secret") + var configuration = InfisicalSettings.Configuration(projectId: project, environment: "prod", clientId: "synthetic-id", clientSecret: "synthetic-secret") + var write = configuration.readBinding + write.id = "explicit-test-write"; write.access = .write + configuration.writeBinding = write + return configuration } final class InfisicalProjectSelectionTests: XCTestCase { diff --git a/Tests/QuotaCoreTests/InfisicalSettingsTests.swift b/Tests/QuotaCoreTests/InfisicalSettingsTests.swift index 73c06fae..4c31e1f1 100644 --- a/Tests/QuotaCoreTests/InfisicalSettingsTests.swift +++ b/Tests/QuotaCoreTests/InfisicalSettingsTests.swift @@ -49,12 +49,16 @@ private func configuredSettings( values: [String: String] = [:] ) -> InfisicalSettings { let settings = InfisicalSettings(transport: transport) - settings.configure(InfisicalSettings.Configuration( + var configuration = InfisicalSettings.Configuration( projectId: "synthetic-project", environment: "prod", clientId: "test-client", clientSecret: "test-secret" - )) + ) + var write = configuration.readBinding + write.id = "explicit-test-write"; write.access = .write + configuration.writeBinding = write + settings.configure(configuration) transport.handler = { method, url, _, _ in if url.path.hasSuffix("/api/v1/auth/universal-auth/login"), method == "POST" { return (loginPayload(), 200) @@ -331,41 +335,39 @@ final class InfisicalSettingsTests: XCTestCase { XCTAssertEqual(settings.refreshInterval, InfisicalSettings.minimumRefreshInterval) } - /// The dev and staging environments are retired (owner, 2026-10-10), so - /// every build variant, `.dev` included, reads prod. + /// Legacy machine setups retain prod as their migration default. func testDefaultEnvironmentIsProdForEveryBuild() { XCTAssertEqual(InfisicalSettings.defaultEnvironment(), "prod") } - func testNonProdEnvironmentIsRefusedBeforeAnyRequest() async throws { - for environment in ["dev", "staging", "production", ""] { + func testExplicitEnvironmentAndFolderAreUsedForNamedReads() async throws { + for environment in ["dev", "staging", "production"] { let transport = MockInfisicalTransport() - let settings = InfisicalSettings(transport: transport) - settings.configure(InfisicalSettings.Configuration( - projectId: "synthetic-project", - environment: environment, - clientId: "test-client", - clientSecret: "test-secret" - )) - do { - try await settings.load() - XCTFail("Expected a refusal for environment \"\(environment)\"") - } catch InfisicalSettings.SettingsError.invalidDestination { - } - do { - try await settings.validateAndConfigure(InfisicalSettings.Configuration( - projectId: "synthetic-project", - environment: environment, - clientId: "test-client", - clientSecret: "test-secret" - ), persist: {}) - XCTFail("Expected a refusal for environment \"\(environment)\"") - } catch InfisicalSettings.SettingsError.invalidDestination { + transport.handler = { method, url, headers, _ in + XCTAssertEqual(method, "GET") + XCTAssertEqual(headers["Authorization"], "Bearer st.fixture.read-secret") + let query = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems + XCTAssertEqual(query?.first(where: { $0.name == "environment" })?.value, environment) + XCTAssertEqual(query?.first(where: { $0.name == "secretPath" })?.value, "/codecaps") + return (Data(), 404) } - XCTAssertTrue(transport.calls.isEmpty, "no request may go out for \"\(environment)\"") + let settings = InfisicalSettings(transport: transport) + let read = InfisicalBinding(label: "Scoped Read", projectId: "synthetic-project", environment: environment, + secretPath: "/codecaps", access: .read, serviceToken: "st.fixture.read-secret") + try await settings.validateAndConfigure(.init(readBinding: read), persist: {}) + XCTAssertEqual(transport.calls.count, 3) } } + func testBlankEnvironmentIsRejectedBeforeNetwork() async { + let transport = MockInfisicalTransport() + let settings = InfisicalSettings(transport: transport) + settings.configure(.init(projectId: "synthetic-project", environment: "", clientId: "id", clientSecret: "secret")) + do { try await settings.load(); XCTFail("Blank environment must fail") } + catch InfisicalSettings.SettingsError.invalidDestination {} catch { XCTFail("Unexpected error") } + XCTAssertTrue(transport.calls.isEmpty) + } + func testClearConfigurationEmptiesCache() async throws { let transport = MockInfisicalTransport() let settings = configuredSettings(transport: transport, values: [ diff --git a/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift b/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift index d4c5cfc6..7f23884b 100644 --- a/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift +++ b/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift @@ -144,6 +144,29 @@ final class KimiQuotaReaderTests: XCTestCase { XCTAssertNil(KimiQuotaReader.readLocalAccessToken(home: home, environment: [:]), "a CR/LF in the value is not a credential") } + func testConfigTomlCRLFSelectsApprovedKimiKeyAcrossProvidersAndComments() throws { + let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + let lines = [ + "# provider credentials", + "[providers.anthropic]", + "type = \"anthropic\"", + "base_url = \"https://api.anthropic.com/v1\"", + "api_key = \"other-provider-fixture\"", + "[providers.\"managed:kimi-code\"]", + "type = \"kimi\"", + "base_url = \"https://api.kimi.com/coding/v1\"", + "# api_key = \"commented-out-fixture\"", + "api_key = \"kimi-crlf-fixture\"" + ] + try (lines.joined(separator: "\r\n") + "\r\n").write( + to: home.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8 + ) + + XCTAssertEqual(KimiQuotaReader.configToken(root: home), "kimi-crlf-fixture") + } + func testConfigTomlRequiresExactKeyAndStripsInlineComment() throws { let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) diff --git a/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift b/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift index f8d8c747..d0245aba 100644 --- a/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift +++ b/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift @@ -86,4 +86,25 @@ final class LocalQuotaReaderRegistryTests: XCTestCase { XCTAssertEqual(result.issues["same"], "last") XCTAssertEqual(result.consentNeeded, ["first", "second"]) } + func testDisabledZAIReaderDoesNotResolveItsSavedKey() async { + let calls = InvocationCounter() + let registry = LocalQuotaReaderRegistry(registrations: [ + LocalQuotaReaderRegistration(id: "zcode", label: "Z.ai", isOptional: true) { + ZCodeQuotaReader(credential: { + calls.increment() + return .init(region: .zAI, apiKey: "fixture-api-key") + }, fetch: { _ in + XCTFail("Disabled optional reader must not make quota requests") + throw URLError(.badURL) + }) + } + ]) + var preferences = QuotaReaderPreferences() + preferences.setEnabled(false, for: "zcode") + let result = await registry.read(preferences: preferences) + XCTAssertEqual(calls.value(), 0) + XCTAssertTrue(result.issues.isEmpty) + XCTAssertTrue(result.windows.isEmpty) + } + } diff --git a/Tests/QuotaCoreTests/QuotaCardProjectionTests.swift b/Tests/QuotaCoreTests/QuotaCardProjectionTests.swift new file mode 100644 index 00000000..b07e4228 --- /dev/null +++ b/Tests/QuotaCoreTests/QuotaCardProjectionTests.swift @@ -0,0 +1,90 @@ +import XCTest +@testable import QuotaCore + +final class QuotaCardProjectionTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + private func row(_ id: String, _ provider: String, _ token: String?, _ percent: Double?, + label: String = "Quota", model: String? = nil, age: Double = 0, + reset: Double = 3600, source: String? = nil) -> QuotaCardProjection.Reading { + .init(id: id, providerKey: provider, label: label, window: token, modelId: model, + remainingPercent: percent, resetAt: now.addingTimeInterval(reset), + reportedAt: now.addingTimeInterval(-age), source: source) + } + + func testPlanAndUnknownCopiesDoNotDisplaceMiniMaxOrCodexMeters() { + for provider in ["minimax", "openai"] { + let rows = [row("plan", provider, nil, nil, label: "Plan"), + row("unknown", provider, "7d", nil), + row("short", provider, "5h", 92), + row("weekly", provider, "7d", 74), + row("p:plan-metadata", provider, nil, 100, label: "Plan Details")] + XCTAssertEqual(QuotaCardProjection.selectedIndices(in: rows, now: now).map { rows[$0].id }, ["short", "weekly"]) + } + } + + func testPrimaryModelIdsDoNotCreateDuplicateAllowancesButFableIsDistinct() { + let rows = [row("unknown", "anthropic", "7d", nil), + row("short", "anthropic", "5h", 80), row("weekly", "anthropic", "7d", 0), + row("fable", "anthropic", "7d", 0, model: "Fable"), + row("sonnet", "anthropic", "7d", 15, model: "sonnet")] + let selected = QuotaCardProjection.selectedIndices(in: rows, now: now).map { rows[$0] } + XCTAssertEqual(selected.map(\.id), ["short", "weekly", "fable"]) + XCTAssertEqual(selected.last?.displayLabel, "Fable limit") + XCTAssertNotEqual(rows[2].allowanceKey, rows[3].allowanceKey) + let minimax = [row("older", "minimax", "5h", 2, model: "MiniMax-M2", age: 30), + row("newer", "minimax", "5h", 92, model: "MiniMax-M2.5")] + XCTAssertEqual(QuotaCardProjection.selectedIndices(in: minimax, now: now), [1]) + } + + func testMeasurableMacReadingWinsMirrorAndUnknownMacNeverWinsReading() { + let rows = [row("mirror", "github-copilot", "1m", 0), + row("local-mac:copilot:premium", "github-copilot", "1m", 100, age: 30), + row("local-mac:copilot:unknown", "github-copilot", "1m", nil)] + XCTAssertEqual(QuotaCardProjection.selectedIndices(in: rows, now: now), [1]) + XCTAssertEqual(QuotaCardProjection.preferredIndex(in: [rows[0], rows[2]], now: now), 0) + let expiredMac = row("local-mac:old", "github-copilot", "1m", 0, age: 60, reset: -1) + XCTAssertEqual(QuotaCardProjection.preferredIndex(in: [rows[0], expiredMac], now: now), 0) + } + + func testUnknownOnlyProviderHasNoInventedQuotaAndCountOnlyExtraSurvives() { + XCTAssertEqual(QuotaCardProjection.selectedIndices(in: [row("unknown", "grok", "7d", nil)], now: now), []) + var extra = row("extra", "muse-assist", nil, nil, label: "Additional tokens") + extra.absoluteRemaining = 42 + let weekly = row("weekly", "muse-assist", "7d", 47) + XCTAssertEqual(QuotaCardProjection.selectedIndices(in: [extra, weekly], now: now), [1, 0]) + XCTAssertNotEqual(extra.allowanceKey, weekly.allowanceKey) + extra.absoluteRemaining = .nan + XCTAssertFalse(extra.hasReading) + } + + func testCanonicalAntigravityPoolRowsDriveBothPeriodsAndArgonStaysSeparate() { + let rows = [row("raw:gemini:5h", "google-antigravity", "5h", 7), + row("antigravity:gemini:5h", "google-antigravity", "5h", 63, age: 10), + row("antigravity:gemini:weekly", "google-antigravity", "7d", 1), + row("argon", "google-antigravity", "5h", 0, model: "Argon")] + XCTAssertEqual(QuotaCardProjection.selectedPoolIndices(in: rows, poolKey: "gemini", now: now), [1, 2]) + XCTAssertEqual(rows[3].displayLabel, "Argon limit") + XCTAssertEqual(rows[3].detailName, "Argon") + XCTAssertEqual(rows[0].detailName, nil) + XCTAssertEqual([rows[1], rows[2]].compactMap(\.remainingPercent).min(), 1) + } + + func testEqualTimePoolObservationsUseLowerReadingWithoutAveraging() { + let rows = [row("a", "google-antigravity", "7d", 63), row("b", "google-antigravity", "7d", 7)] + XCTAssertEqual(QuotaCardProjection.selectedPoolIndices(in: rows, poolKey: "gemini", now: now), [1]) + } + + func testHealthyMuseWeeklyLeadsUntilItsAllowanceIsSpent() { + let weekly = CardHeadline.Reading(isMuseAssistExtra: false, isMasked: false, remainingPercent: 47) + let extra = CardHeadline.Reading(isMuseAssistExtra: true, isMasked: false, remainingPercent: 81) + XCTAssertEqual(CardHeadline.percent([weekly, extra]), 47) + XCTAssertEqual(CardHeadline.percent([.init(isMuseAssistExtra: false, isMasked: false, remainingPercent: 0), extra]), 81) + } + + func testExpiredCanonicalPoolCannotReplaceCurrentObservation() { + let rows = [row("antigravity:gemini:weekly", "google-antigravity", "7d", 0, age: 100, reset: -1), + row("raw", "google-antigravity", "7d", 51)] + XCTAssertEqual(QuotaCardProjection.selectedPoolIndices(in: rows, poolKey: "gemini", now: now), [1]) + } +} diff --git a/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift b/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift index b5038fbe..a863a2a9 100644 --- a/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift +++ b/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift @@ -6,14 +6,19 @@ final class ZCodeQuotaReaderTests: XCTestCase { private func read( _ json: String, status: Int = 200, - store: [String: String]? = ["oauth:zai:access_token": "tok"] + credential: ZCodeQuotaCredential? = .init(region: .zAI, apiKey: "fixture-api-key") ) async -> LocalQuotaResult { await ZCodeQuotaReader( now: { Date(timeIntervalSince1970: 0) }, - credentials: { store ?? [:] }, - fetch: { _ in + credential: { credential }, + fetch: { request in + XCTAssertEqual(request.url, credential?.region.quotaURL) + let authorization = request.value(forHTTPHeaderField: "authorization") + if status == 401, let key = credential?.apiKey { + XCTAssertTrue(authorization == key || authorization == "Bearer " + key) + } else { XCTAssertEqual(authorization, credential?.apiKey) } let response = HTTPURLResponse( - url: URL(string: "https://api.z.ai/api/monitor/usage/quota/limit")!, + url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil )! return (Data(json.utf8), response) @@ -27,7 +32,7 @@ final class ZCodeQuotaReaderTests: XCTestCase { XCTAssertEqual(result.windows.count, 2) let fiveHour = result.windows[0] XCTAssertEqual(fiveHour.providerKey, "zcode") - XCTAssertEqual(fiveHour.providerLabel, "ZCode") + XCTAssertEqual(fiveHour.providerLabel, "Z.ai") XCTAssertEqual(fiveHour.label, "5-hour limit") XCTAssertEqual(fiveHour.window, "5h") // percentage is the USED share; the row shows what remains. @@ -56,16 +61,16 @@ final class ZCodeQuotaReaderTests: XCTestCase { XCTAssertTrue(window.skip) } - func testMissingCredentialIsSilent() async { - let result = await read("{}", store: nil) + func testMissingCredentialReportsSetupNeededWithoutFetching() async { + let result = await read("{}", credential: nil) XCTAssertTrue(result.windows.isEmpty) - XCTAssertTrue(result.issues.isEmpty) + XCTAssertTrue(result.issues["zcode"]?.contains("setup is needed") == true) } func testNoPlanMessageIsAnIssue() async { let result = await read(#"{"code":500,"msg":"当前用户不存在coding plan"}"#) XCTAssertTrue(result.windows.isEmpty) - XCTAssertEqual(result.issues["zcode"], "No GLM Coding Plan is active on this ZCode account.") + XCTAssertEqual(result.issues["zcode"], "No GLM Coding Plan is active on this account.") } func testEmptyLimitsReportNoWindowsForAccount() async { @@ -74,13 +79,13 @@ final class ZCodeQuotaReaderTests: XCTestCase { // read as an empty account, never as "unavailable" or a full quota. let result = await read(#"{"code":200,"data":{"limits":[]}}"#) XCTAssertTrue(result.windows.isEmpty) - XCTAssertEqual(result.issues["zcode"], "ZCode returned no quota windows for this account.") + XCTAssertEqual(result.issues["zcode"], "Z.ai returned no quota windows for this account.") } func testUnparseableLimitsReportNoReadableQuota() async { let result = await read(#"{"code":200,"data":{"limits":[{"unit":6}]}}"#) XCTAssertTrue(result.windows.isEmpty) - XCTAssertEqual(result.issues["zcode"], "ZCode returned no readable quota.") + XCTAssertEqual(result.issues["zcode"], "Z.ai returned no readable quota.") } func testMissingLimitsKeyReportsNoReadableQuota() async { @@ -88,55 +93,51 @@ final class ZCodeQuotaReaderTests: XCTestCase { // malformed payload, not a truthful empty account. let missing = await read(#"{"code":200,"data":{}}"#) XCTAssertTrue(missing.windows.isEmpty) - XCTAssertEqual(missing.issues["zcode"], "ZCode returned no readable quota.") + XCTAssertEqual(missing.issues["zcode"], "Z.ai returned no readable quota.") let mistyped = await read(#"{"code":200,"data":{"limits":"none"}}"#) XCTAssertTrue(mistyped.windows.isEmpty) - XCTAssertEqual(mistyped.issues["zcode"], "ZCode returned no readable quota.") + XCTAssertEqual(mistyped.issues["zcode"], "Z.ai returned no readable quota.") } func testCancellationIsNotReportedAsTransportFailure() async { let result = await ZCodeQuotaReader( now: { Date(timeIntervalSince1970: 0) }, - credentials: { ["oauth:zai:access_token": "tok"] }, + credential: { .init(region: .zAI, apiKey: "fixture-api-key") }, fetch: { _ in throw CancellationError() } ).read() - XCTAssertEqual(result.issues["zcode"], "ZCode quota refresh was cancelled.") + XCTAssertEqual(result.issues["zcode"], "Z.ai quota refresh was cancelled.") } func testRejectedSessionIsAnIssue() async { let result = await read("{}", status: 401) XCTAssertTrue(result.windows.isEmpty) - XCTAssertEqual(result.issues["zcode"], "ZCode session was rejected; sign in again in ZCode.") + XCTAssertEqual(result.issues["zcode"], "The saved Coding Plan API key was rejected.") } func testEnvelopeFailureWithoutDataIsUnavailable() async { let result = await read(#"{"code":500,"msg":"boom"}"#) XCTAssertTrue(result.windows.isEmpty) - XCTAssertEqual(result.issues["zcode"], "ZCode quota service is unavailable.") + XCTAssertEqual(result.issues["zcode"], "Z.ai quota service is unavailable.") } - func testTransportErrorFallsThroughToSecondCredential() async { - let result = await ZCodeQuotaReader( - now: { Date(timeIntervalSince1970: 0) }, - credentials: { ["oauth:zai:access_token": "tok", "oauth:bigmodel:access_token": "bm-tok"] }, + func testTransportFailureNeverSendsTheKeyToAnotherRegion() async { + let counter = ZCodeRequestCounter() + let result = await ZCodeQuotaReader(credential: { .init(region: .zAI, apiKey: "fixture-api-key") }, fetch: { request in - if request.url?.host == "api.z.ai" { throw URLError(.notConnectedToInternet) } - let response = HTTPURLResponse( - url: URL(string: "https://bigmodel.cn/api/monitor/usage/quota/limit")!, - statusCode: 200, httpVersion: nil, headerFields: nil - )! - return (Data(#"{"code":200,"data":{"level":"max","limits":[{"type":"TOKENS_LIMIT","unit":6,"percentage":5}]}}"#.utf8), response) - } - ).read() - XCTAssertTrue(result.issues.isEmpty) - XCTAssertEqual(result.windows.count, 1) - XCTAssertEqual(result.windows[0].quotaUnit, "tokens") + await counter.increment() + XCTAssertEqual(request.url?.host, "api.z.ai") + throw URLError(.notConnectedToInternet) + }).read() + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["zcode"], "Z.ai quota service is unavailable.") + let count = await counter.count + XCTAssertEqual(count, 1) } - func testFallsBackToBigModelCredential() async { + func testBigModelKeyUsesOnlyItsPairedRegionalEndpoint() async { let result = await read( #"{"code":200,"data":{"level":"max","limits":[{"type":"TOKENS_LIMIT","unit":6,"percentage":5}]}}"#, - store: ["oauth:bigmodel:access_token": "bm-tok"] + credential: .init(region: .bigModel, apiKey: "bigmodel-fixture-key") ) XCTAssertEqual(result.windows.count, 1) XCTAssertEqual(result.windows[0].quotaUnit, "tokens") @@ -144,17 +145,50 @@ final class ZCodeQuotaReaderTests: XCTestCase { } func testURLCancellationDoesNotTryAnotherAuthenticationFormOrAccount() async { let counter = ZCodeRequestCounter() - let result = await ZCodeQuotaReader(credentials: { - ["oauth:zai:access_token": "fixture-token", "oauth:bigmodel:access_token": "other-fixture-token"] + let result = await ZCodeQuotaReader(credential: { + .init(region: .zAI, apiKey: "fixture-api-key") }, fetch: { _ in await counter.increment() throw URLError(.cancelled) }).read() - XCTAssertEqual(result.issues["zcode"], "ZCode quota refresh was cancelled.") + XCTAssertEqual(result.issues["zcode"], "Z.ai quota refresh was cancelled.") let count = await counter.count XCTAssertEqual(count, 1) } + func testDefaultReaderNeedsExplicitSetupAndNeverAttemptsOAuthOrQuotaCalls() async { + let result = await ZCodeQuotaReader(fetch: { _ in + XCTFail("No explicit Coding Plan key means no request") + throw URLError(.badURL) + }).read() + XCTAssertTrue(result.windows.isEmpty) + XCTAssertTrue(result.issues["zcode"]?.contains("setup is needed") == true) + } + + func testInvalidSavedKeyCannotReachTransport() async { + var invalid = ZCodeQuotaCredential(region: .zAI, apiKey: "fixture-key") + invalid.apiKey = "first\nsecond" + let saved = invalid + let result = await ZCodeQuotaReader(credential: { saved }, fetch: { _ in + XCTFail("An invalid saved key must not reach quota transport") + throw URLError(.badURL) + }).read() + XCTAssertTrue(result.windows.isEmpty) + XCTAssertTrue(result.issues["zcode"]?.contains("setup is needed") == true) + } + + func testRejectedKeyCannotFallBackToAnotherRegion() async { + let counter = ZCodeRequestCounter() + let result = await ZCodeQuotaReader(credential: { .init(region: .zAI, apiKey: "fixture-api-key") }, fetch: { request in + await counter.increment() + XCTAssertEqual(request.url?.host, "api.z.ai") + return (Data("{}".utf8), HTTPURLResponse(url: request.url!, statusCode: 401, httpVersion: nil, headerFields: nil)!) + }).read() + let count = await counter.count + XCTAssertEqual(count, 2) + XCTAssertEqual(result.issues["zcode"], "The saved Coding Plan API key was rejected.") + } + } diff --git a/docs/AUTO-UPDATE.md b/docs/AUTO-UPDATE.md index 7bd67d16..652cff6a 100644 --- a/docs/AUTO-UPDATE.md +++ b/docs/AUTO-UPDATE.md @@ -54,7 +54,7 @@ The EdDSA key pair is per app, so one app's key cannot sign another app's update - Stored as the repository secret `SPARKLE_ED_PRIVATE_KEY` by piping the file into `gh secret set`. It reaches `generate_appcast` on standard input, never as an argument. - The public key is `Ou2J0syHZawPSY3JLTLVyhbOylmtyr0QnZPbq7acETQ=`, in `script/build_and_run.sh`. -The App Store Connect signing key is a separate key, and CI reads it from Fleet-OPS prod `/asc` rather than from a repository secret. The repository copy of that key was revoked (HTTP 401, CC-163), which is what kept the Mac release from publishing for nine days. In CI the values come from the fleet's own reader, `fleet-secrets`, which `scripts/install-release-secrets-tooling.sh` installs onto the runner together with the pinned Infisical CLI. That script mints an Infisical access token with universal auth, proves the reader can list Fleet-OPS prod `/asc` with that token and that the list holds all three names, and only then runs `scripts/stage-asc-key.mjs`, the one thing in the release that resolves a value. The reader is proved first on purpose: the consumer reads a failed lookup as an empty value, so a broken reader, a rejected token and a name that is absent from the vault would otherwise all look like the same missing credential. The one failure the consumer tells apart is an unresolved Infisical reference, which the reader reports with its own exit code and the consumer names as a reference. The token is minted into a shell variable and never reaches a file, `$GITHUB_ENV` or the log; the project id comes from the `INFISICAL_FLEET_OPS_PROJECT_ID` secret rather than from a literal in a public workflow. The multiline private key is streamed over stdin into a mode-600 file by `scripts/stage-asc-key.mjs`, and the `ASC_KEY_P8` entry is removed from the job's environment file in the same step, so only that file's path and the two identifiers cross into the later steps. The same loader is used by `mac-release.yml` and `ios-ship.yml`, and `scripts/mac-release-workflow.test.mjs` pins the two to the same text. The reader can also be proved on its own, with a token the caller already holds in `INFISICAL_TOKEN`, by running `bash scripts/install-release-secrets-tooling.sh check-reader`; without that token the check says so instead of reporting a rejected one. +The App Store Connect signing key is a separate key, and CI reads it from Fleet-OPS prod `/asc` rather than from a repository secret.  The repository copy of that key was revoked (HTTP 401, CC-163), which is what kept the Mac release from publishing for nine days.  In CI, `scripts/install-release-secrets-tooling.sh` installs the pinned Infisical CLI and fleet-owned `fleet-secrets` reader, then passes the reader the pre-provisioned, read-only CI service token scoped to prod `/` and `/asc` directly through `INFISICAL_TOKEN`; it does not create an access token or use machine-identity auth.  It proves the reader can list Fleet-OPS prod `/asc` and that the list holds all three names, then runs `scripts/stage-asc-key.mjs`, the one release component that resolves a value.  The reader is proved first because the consumer reads a failed lookup as an empty value, so a broken reader, a rejected token and a missing vault name would otherwise look alike.  An unresolved Infisical reference remains distinct and is reported by the reader and consumer.  The service token stays in process memory and never reaches a file, `$GITHUB_ENV` or the log; the project id comes from the `INFISICAL_FLEET_OPS_PROJECT_ID` secret rather than a literal in a public workflow.  The multiline private key is streamed over stdin into a mode-600 file, and the `ASC_KEY_P8` environment entry is removed from the job environment, so only the file path and the two identifiers cross into later steps.  Both `mac-release.yml` and `ios-ship.yml` use the same loader, which `scripts/mac-release-workflow.test.mjs` pins to identical text.  The reader can be checked independently with an already-held service token in `INFISICAL_TOKEN` by running `bash scripts/install-release-secrets-tooling.sh check-reader`; without that token the check reports the missing configuration. To check that the release credentials still work without publishing anything, run the "Mac Release (Sparkle)" workflow by hand with the `verify-only` input set. It fetches the key, asks Apple's notarization service whether it still accepts it, and stops. @@ -70,11 +70,12 @@ A private repository cannot do this, because anonymous clients cannot download i | Name | Where | Status on Tue, Sep 29, 2026 | |---|---|---| -| `MAC_CERT_P12_BASE64`, `MAC_CERT_PASSWORD` | Infisical (the way BotFleet's `release.yml` reads them), needing `INFISICAL_PROJECT_ID` and `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID`/`_SECRET` (or `INFISICAL_CLIENT_ID`/`_SECRET`) repository secrets; or same-named repository secrets as the fallback | Missing. Publishing is gated until they exist. | -| `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_KEY_P8` | Fleet-OPS Infisical prod `/asc`, read by the fleet's `fleet-secrets` reader that `scripts/install-release-secrets-tooling.sh` installs onto the runner. The same loader serves `ios-ship.yml`. The stale repository copies are never read. The reader is proved against the minted token before anything is staged, so a broken reader is reported as a reader fault rather than as a missing credential. The PEM is streamed over stdin by `scripts/stage-asc-key.mjs` into a mode-600 temporary file, and the `ASC_KEY_P8` environment entry is removed from the job's environment file in the same step, so only the file's path and the two identifiers cross into the later steps. | Notarization access is verified with read-only `notarytool history` before building. Artifact acceptance is still required separately. | +| `INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN` | One read-only Fleet-OPS prod service token scoped to `/` and `/asc`, passed directly by the certificate/Sentry fetcher and `fleet-secrets` ASC reader; project id is `INFISICAL_FLEET_OPS_PROJECT_ID`. Same-named repository secrets remain fallbacks for certificate/Sentry values; stale ASC repository copies are never read. Missing token or unreadable ASC scope fails closed. | Used for Mac and iOS release reads. Notarization access is verified with read-only `notarytool history` before building. Artifact acceptance is still required separately. | +| `MAC_CERT_P12_BASE64`, `MAC_CERT_PASSWORD` | Fleet-OPS prod `/`; fetched through the shared CI token above. | Missing. Publishing is gated until they exist. | +| `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_KEY_P8` | Fleet-OPS prod `/asc`; fetched by `fleet-secrets` using the shared CI token above. The PEM is streamed over stdin by `scripts/stage-asc-key.mjs` into a mode-600 temporary file, and the `ASC_KEY_P8` environment entry is removed from the job's environment file in the same step. | The same path serves `ios-ship.yml`; only the key-file path and two identifiers cross into later steps. | | `SPARKLE_ED_PRIVATE_KEY` | Repository secret | Present. | -Pull requests skip credential loading, perform ad-hoc structural validation and never publish. On main, a missing Infisical identity, missing fleet ASC material, or failed notarization preflight fails the job before publication. If fleet ASC loading succeeds but certificate or Sparkle signing material is missing, the publication gate reports the missing names and runs the existing ad-hoc build-only validation. None of these non-publishing paths updates the feed. +Pull requests skip credential loading, perform ad-hoc structural validation and never publish. On main, a missing required Infisical service token, missing fleet ASC material, or failed notarization preflight fails the job before publication. If fleet ASC loading succeeds but certificate or Sparkle signing material is missing, the publication gate reports the missing names and runs the existing ad-hoc build-only validation. None of these non-publishing paths updates the feed. ### Diagnosing a stale Sparkle feed diff --git a/docs/CI-INFISICAL-SERVICE-TOKENS.md b/docs/CI-INFISICAL-SERVICE-TOKENS.md new file mode 100644 index 00000000..35b098e9 --- /dev/null +++ b/docs/CI-INFISICAL-SERVICE-TOKENS.md @@ -0,0 +1,14 @@ +# CodeCaps CI Infisical Service Tokens + +This file records automation secret names and their intended scopes.  It contains no token values.  The Mac app’s optional user-configured Infisical setup is documented separately in `INFISICAL.md`. + +## Expected Secret Names + +| Secret name | Project | Environment | Path | Permission | Consumer | +|---|---|---|---|---|---| +| `INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN` | `INFISICAL_FLEET_OPS_PROJECT_ID` | `prod` | `/` and `/asc` | Read | GitHub release certificate/Sentry fetches and Mac/iOS release ASC credential staging | +| `INFISICAL_CODECAPS_PROD_ROOT_READ_SERVICE_TOKEN` | `INFISICAL_PROJECT_ID` from `.cursor/infisical.env` | `prod` | `/` | Read | Cursor Cloud startup export | + +The Actions composite fetcher and ASC reader share one read-only Fleet-OPS token scoped to the required prod `/` and `/asc` folders.  Both consumers pass the full service token directly as a Bearer token.  It does not log in or accept machine-identity client IDs or secrets.  Root-path certificate and Sentry values keep their same-named GitHub secret fallbacks.  ASC staging has no GitHub fallback and fails closed if its `/asc` service token or required ASC values are unavailable. + +Infisical service tokens should be provisioned with the listed project, environment, path, read-only permission, and an owner-selected expiry.  The repository records environment variable names only; token values must be supplied through the existing authorized secret channel.  No service token is embedded, generated, or provisioned by this change. diff --git a/docs/rollouts/2026-11-03-cc205-monitoring-alert-controls.md b/docs/rollouts/2026-11-03-cc205-monitoring-alert-controls.md index ba49a0bb..280ba2e4 100644 --- a/docs/rollouts/2026-11-03-cc205-monitoring-alert-controls.md +++ b/docs/rollouts/2026-11-03-cc205-monitoring-alert-controls.md @@ -27,3 +27,15 @@ Only newly detected events enter SMS delivery.  A persistent hashed reservation ## Verification Run swift build and swift test on macOS.  Tests cover reset corrections and scheduled rollovers, quit choices, disabled-reader non-invocation, Muse transition persistence and burn gating, SMS routing with local methods off, Keychain isolation, and durable deduplication.  Tests use private defaults, fake credentials, and injected transports.  No iOS simulator is used. + +## Provider Authentication And Optional Infisical + +Kimi config fallback selects only an explicit Kimi coding provider with an approved coding URL.  The reader preserves long OAuth and JSON API keys, accepts finite numeric-string counters, and stops fallback after cancellation. + +Z.ai / BigModel quota checks use an explicitly saved coding-plan API key, with a region-paired endpoint and separate build-scoped Keychain record.  CodeCaps does not send ZCode OAuth tokens to the coding-plan quota API or create account API credentials. + +Infisical remains optional.  Its setup stores multiple labeled Keychain bindings by project, environment, folder, authentication method, and intended read or write use.  Service tokens are sent intact as Bearer credentials; app-local machine identities remain an explicit option.  A write binding must be selected independently and match the active read scope.  Existing single-identity records migrate in memory to read-only bindings. + +Release automation uses one scoped read service token for Fleet-OPS prod / and /asc, with no Universal Auth fallback.  Replacement token binding and workflow publication must be verified before release. + +Native validation before the companion follow-up: swift build passed; swift test executed 1,563 tests with 10 skipped and zero failures.  The automation contract suite passed 79 tests. diff --git a/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift b/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift index 6d1a117d..82cb58aa 100644 --- a/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift +++ b/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift @@ -77,7 +77,7 @@ public enum CompanionDateFormatter { } /// An individual quota window or time period within a platform. -public struct CompanionWindowItem: Identifiable, Codable, Equatable { +public struct CompanionWindowItem: Identifiable, Codable, Equatable, Sendable { public let id: String public let label: String public let cadence: String @@ -449,7 +449,12 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { /// A platform card is expandable if it reports more than two allowance /// windows or holds provider plan details. public var isExpandable: Bool { - windows.count > 2 || !providerDetailRows.isEmpty + windows.contains { $0.isSubModelLimit && ($0.label == "Fable limit" || $0.label == "Argon limit") + && ($0.remainingPercent?.isFinite == true || $0.absoluteRemaining?.isFinite == true) } + } + + public func cardDetailWindows(scope: CompanionSourceScope, now: Date = Date()) -> [CompanionWindowItem] { + cardWindows(scope: scope, now: now).filter { $0.isSubModelLimit } } /// Both feeds must report within this window for a source-disagreement banner. @@ -539,7 +544,7 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { /// Main-card windows: fresh Mac CodeCaps readings win; otherwise the newest feed with an Updated label. public func cardWindowRows(scope: CompanionSourceScope, now: Date = Date()) -> [CardWindow] { - windows.map { primary in + let resolved = windows.map { primary in let key = Self.allowanceKey(for: primary) // This iPhone: only this device's primary windows. All Sources: fold // in mirror feeds so Mac/fleet readings can win when fresher. @@ -552,6 +557,13 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { let pool = mirrors.isEmpty ? [primary] : [primary] + mirrors return Self.resolveCardWindow(pool: pool, now: now) } + return resolved.filter { + let window = $0.window + let measured = window.remainingPercent?.isFinite == true + || (window.absoluteRemaining?.isFinite == true && (window.absoluteRemaining ?? -1) >= 0) + return measured && !window.isSupplementaryVideoQuota && !window.isScopedPoolAllowance + && (!window.isSubModelLimit || window.label == "Fable limit" || window.label == "Argon limit") + } } public func cardWindows(scope: CompanionSourceScope, now: Date = Date()) -> [CompanionWindowItem] { @@ -559,7 +571,7 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { } public func cardShortWindow(scope: CompanionSourceScope, now: Date = Date()) -> CardWindow? { - let resolved = cardWindowRows(scope: scope, now: now) + let resolved = cardWindowRows(scope: scope, now: now).filter { !$0.window.isSubModelLimit } if providerKey == "muse-assist" { if let weekly = resolved.first(where: { QuotaWindowVocabulary.isMuseAssistWeekly( @@ -577,7 +589,7 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { } public func cardLongWindow(scope: CompanionSourceScope, now: Date = Date()) -> CardWindow? { - let resolved = cardWindowRows(scope: scope, now: now) + let resolved = cardWindowRows(scope: scope, now: now).filter { !$0.window.isSubModelLimit } if providerKey == "muse-assist" { if let extra = resolved.first(where: { QuotaWindowVocabulary.isMuseAssistExtra( @@ -605,7 +617,9 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { /// spent reports whatever it last saw, and the card put that on its /// headline while the label beside it said "n/a". public func cardRemainingPercent(scope: CompanionSourceScope, now: Date = Date()) -> Double? { - let readings = cardWindows(scope: scope, now: now).map { window in + let primary = cardWindows(scope: scope, now: now).filter { !$0.isSubModelLimit } + let fresh = primary.filter { $0.isFresh(now: now) } + let readings = (fresh.isEmpty ? primary : fresh).map { window in CardHeadline.Reading( isMuseAssistExtra: providerKey == "muse-assist" && QuotaWindowVocabulary.isMuseAssistExtra( @@ -649,7 +663,11 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { } private static func resolveCardWindow(pool: [CompanionWindowItem], now: Date) -> CardWindow { - let observations = pool.map { + let measured = pool.filter { $0.remainingPercent?.isFinite == true || $0.absoluteRemaining?.isFinite == true } + let available = measured.isEmpty ? pool : measured + let fresh = available.filter { $0.isFresh(now: now) } + let candidates = fresh.isEmpty ? available : fresh + let observations = candidates.map { FleetQuotaObservation( remainingPercent: $0.remainingPercent, reportedAt: $0.reportedAt, @@ -657,9 +675,9 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { ) } if let pick = FleetMacReading.pickCardDisplay(from: observations, now: now) { - return CardWindow(window: pool[pick.chosenIndex], updatedLabel: pick.updatedLabel) + return CardWindow(window: candidates[pick.chosenIndex], updatedLabel: pick.updatedLabel) } - return CardWindow(window: pool[0], updatedLabel: nil) + return CardWindow(window: candidates[0], updatedLabel: nil) } public var sourceCount: Int { @@ -1900,11 +1918,11 @@ public final class CompanionQuotaModel: ObservableObject { if !antigravityWindows.isEmpty { let geminiWindows = antigravityWindows.filter { let s = ($0.id + " " + $0.label + " " + ($0.modelType ?? "") + " " + ($0.modelId ?? "")).lowercased() - return s.contains("gemini") + return s.contains("gemini") || s.contains("argon") } let thirdPartyWindows = antigravityWindows.filter { let s = ($0.id + " " + $0.label + " " + ($0.modelType ?? "") + " " + ($0.modelId ?? "")).lowercased() - return !s.contains("gemini") + return !s.contains("gemini") && !s.contains("argon") } if let geminiItem = consolidateAntigravityPool( @@ -1983,6 +2001,15 @@ public final class CompanionQuotaModel: ObservableObject { } } + func reading(_ wire: WireRawWindow) -> QuotaCardProjection.Reading { + QuotaCardProjection.Reading(id: wire.id, providerKey: providerKey, label: wire.label, + window: wire.window, modelId: wire.modelId, modelType: wire.modelType, + remainingPercent: wire.remainingUnknown == true ? nil : wire.remainingPercent, + absoluteRemaining: wire.absoluteRemaining, + resetAt: CompanionDateFormatter.date(from: wire.resetAt), reportedAt: Self.reportedAt(from: wire), + source: wire.source, via: wire.via) + } + var primaryWindows: [CompanionWindowItem] = [] var duplicateWindows: [CompanionWindowItem] = [] var primaryIndexByCadenceKey: [String: Int] = [:] @@ -1996,6 +2023,7 @@ public final class CompanionQuotaModel: ObservableObject { // observation time. It only judges copies: this Mac's own reading // keeps its row, so an expired one greys out instead of vanishing. let liveWindows = rawWindows.filter { w in + guard reading(w).isQuota else { return false } let lowId = w.id.lowercased() let lowLabel = w.label.lowercased() if lowId.hasSuffix(":plan-metadata") || lowLabel == "plan details" { @@ -2035,25 +2063,15 @@ public final class CompanionQuotaModel: ObservableObject { /// already replaced (owner, Oct-22-2026). The widget asks the same /// question the same way, so the two cannot drift. func isFresher(_ candidate: WireRawWindow, than current: WireRawWindow) -> Bool { - let candidateFresh = isFresh(candidate) - let currentFresh = isFresh(current) - if candidateFresh != currentFresh { return candidateFresh } - return (CompanionDateFormatter.date(from: candidate.occurredAt) ?? .distantPast) - > (CompanionDateFormatter.date(from: current.occurredAt) ?? .distantPast) + QuotaCardProjection.preferredIndex(in: [reading(current), reading(candidate)], now: now) == 1 } for w in liveWindows { let parsedReset = CompanionDateFormatter.date(from: w.resetAt) let parsedReportedAt = Self.reportedAt(from: w) let cadence = Self.formatCadence(w.label, window: w.window, resetAt: parsedReset) - let displayLabel = QuotaWindowVocabulary.isExtraAllowanceLabel(w.label) - ? w.label - : QuotaWindowVocabulary.windowLabel( - windowToken: w.window, - existingLabel: w.label, - resetAt: parsedReset - ) - let pct = w.remainingPercent + let displayLabel = reading(w).displayLabel + let pct = reading(w).remainingPercent // A reading decides, as it does on every surface: the export never // clears `isExhausted`, so a stale word must not outvote a reading // that says there is room left. The provider's word is the @@ -2061,17 +2079,7 @@ public final class CompanionQuotaModel: ObservableObject { let exhausted = QuotaCapRule.isExhausted(remainingPercent: pct, providerSaysExhausted: w.isExhausted ?? false) - let modelQualifier = (w.modelId ?? "").lowercased() - let isMiniMax = providerKey.lowercased().contains("minimax") || id.lowercased().contains("minimax") - let effectiveQualifier = isMiniMax ? "" : modelQualifier - let baseAllowanceKey = CompanionWindowItem.fallbackNormalizedWindowKey( - cadence: cadence, - label: displayLabel, - resetAt: parsedReset - ) - let cadenceKey = effectiveQualifier.isEmpty - ? baseAllowanceKey - : "\(effectiveQualifier):\(baseAllowanceKey)" + let cadenceKey = reading(w).allowanceKey // The shared cap rule needs the window's own label, not the // display label: the Mac reads the reader's own label, and that is @@ -2136,6 +2144,7 @@ public final class CompanionQuotaModel: ObservableObject { // Standardize cadence order: shorter periods (e.g. 5-hour) precede longer periods (e.g. weekly). primaryWindows.sort { left, right in + if left.isSubModelLimit != right.isSubModelLimit { return !left.isSubModelLimit } if providerKey == "muse-assist" { let leftWeekly = QuotaWindowVocabulary.isMuseAssistWeekly( providerKey: providerKey, windowToken: left.rawWindowToken, label: left.label, resetAt: left.resetAt) @@ -2158,8 +2167,9 @@ public final class CompanionQuotaModel: ObservableObject { } // Controlling percentage is the minimum among primary non-masked windows - let validPercents = primaryWindows.compactMap(\.remainingPercent) - let controllingPct = validPercents.min() + let primaryReadings = primaryWindows.filter { !$0.isSubModelLimit && !$0.isScopedPoolAllowance } + let freshReadings = primaryReadings.filter { $0.isFresh(now: now) } + let controllingPct = (freshReadings.isEmpty ? primaryReadings : freshReadings).compactMap(\.remainingPercent).min() // Each window above already decided through the shared rule, so the // pool is exhausted when any of them is. Evaluating the provider's // word against `controllingPct` instead would compare a reading that @@ -2275,17 +2285,16 @@ public final class CompanionQuotaModel: ObservableObject { > (CompanionDateFormatter.date(from: current.occurredAt) ?? .distantPast) } - var weeklyWin: WireRawWindow? - var fiveHourWin: WireRawWindow? - for w in windows { - let s = (w.id + " " + w.label).lowercased() - if s.contains("weekly") || s.contains("1w") || s.contains("7d") { - if isFresher(w, than: weeklyWin) { weeklyWin = w } - } - if s.contains("5h") || s.contains("5-hour") || s.contains("interval") { - if isFresher(w, than: fiveHourWin) { fiveHourWin = w } - } + let facts = windows.map { + QuotaCardProjection.Reading(id: $0.id, providerKey: "google-antigravity", label: $0.label, + window: $0.window, modelId: $0.modelId, modelType: $0.modelType, + remainingPercent: $0.remainingPercent, absoluteRemaining: $0.absoluteRemaining, + resetAt: CompanionDateFormatter.date(from: $0.resetAt), reportedAt: Self.reportedAt(from: $0), + source: $0.source, via: $0.via) } + let selected = QuotaCardProjection.selectedPoolIndices(in: facts, poolKey: poolKey, now: now).map { windows[$0] } + let weeklyWin = selected.first { Self.antigravityPeriod(of: $0) == "weekly" } + let fiveHourWin = selected.first { Self.antigravityPeriod(of: $0) == "5h" } let weeklyPct = weeklyWin?.remainingPercent // Only a fresh window may spend the pool. A pool copy that is days old @@ -2303,7 +2312,6 @@ public final class CompanionQuotaModel: ObservableObject { && QuotaCapRule.isExhausted(remainingPercent: weeklyPct, providerSaysExhausted: weeklyWin?.isExhausted ?? false) - let controllingPct: Double? let isExhausted: Bool let subtitle: String @@ -2315,16 +2323,11 @@ public final class CompanionQuotaModel: ObservableObject { fiveHourWin.flatMap { isFresh($0) ? $0.remainingPercent : nil }, weeklyWin.flatMap { isFresh($0) ? $0.remainingPercent : nil } ].compactMap { $0 } - let validPercents = [fiveHourWin?.remainingPercent, weeklyWin?.remainingPercent].compactMap { $0 } if weeklyExhausted && weeklyWin != nil { - controllingPct = weeklyPct ?? 0 isExhausted = true subtitle = "\(QuotaWindowVocabulary.sevenDay) limit exhausted" } else { - controllingPct = freshPercents.min() - ?? validPercents.min() - ?? windows.compactMap(\.remainingPercent).min() isExhausted = QuotaCapRule.isAtCap(remainingPercent: freshPercents.min()) subtitle = defaultSubtitle } @@ -2340,9 +2343,16 @@ public final class CompanionQuotaModel: ObservableObject { // value, and never average or add. let childWindows = Self.periodRows( poolKey: poolKey, - windows: windows, + windows: selected, weeklyExhausted: weeklyExhausted ) + let detailReports = windows.filter { + [$0.id, $0.label, $0.modelId ?? "", $0.modelType ?? ""].joined(separator: " ") + .localizedCaseInsensitiveContains("argon") + } + let details = buildPlatformSection(id: itemId, providerKey: "google-antigravity", title: title, + rawWindows: detailReports).windows + let projectedWindows = childWindows + details let nearestReset = childWindows.compactMap(\.resetAt).filter { $0 > now }.min() ?? childWindows.compactMap(\.resetAt).min() @@ -2352,11 +2362,11 @@ public final class CompanionQuotaModel: ObservableObject { providerKey: "google-antigravity", title: title, subtitle: subtitle, - remainingPercent: controllingPct, + remainingPercent: childWindows.filter { !$0.isMasked }.compactMap(\.remainingPercent).min(), resetAt: nearestReset, isExhausted: isExhausted, isAlarmEnabled: alarmProviderIds.contains(itemId), - windows: childWindows, + windows: projectedWindows, duplicateWindows: [], iconHint: poolKey == "third-party" ? "antigravity" : "gemini" ) @@ -2414,13 +2424,7 @@ public final class CompanionQuotaModel: ObservableObject { // take the latest observation, breaking a tie between two models of // the same pool with the lower value. Never averaged, never added. let canonicalID = "antigravity:\(poolKey):\(period)" - let driving = candidates.first { $0.id == canonicalID } - ?? candidates.min { left, right in - let l = CompanionDateFormatter.date(from: left.resetAt) ?? .distantPast - let r = CompanionDateFormatter.date(from: right.resetAt) ?? .distantPast - if l != r { return l > r } - return (left.remainingPercent ?? 101) < (right.remainingPercent ?? 101) - } + let driving = candidates.first { $0.id == canonicalID } ?? candidates.first guard let driving else { return nil } // A weekly the provider reports as gone without a figure still has to @@ -2548,7 +2552,7 @@ public final class CompanionQuotaModel: ObservableObject { if pKey.contains("muse-assist") || prov.contains("muse-assist") || prov.contains("muse assist") || id.contains("assist") { return ("muse-assist", "Muse Assist", "muse-assist") } - if pKey.contains("muse-code") || prov.contains("muse-code") || prov.contains("muse code") || id.contains("code") { + if pKey.contains("muse-code") || prov.contains("muse-code") || prov.contains("muse code") || id.hasPrefix("local-mac:muse-code:") { return ("muse-code", "Muse Code", "muse-code") } if pKey.contains("muse") || prov.contains("muse") { @@ -2563,7 +2567,7 @@ public final class CompanionQuotaModel: ObservableObject { if pKey.contains("grok") || prov.contains("grok") || pKey.contains("xai") || prov.contains("xai") { return ("xai", "Grok", "xai") } - let fallbackKey = (raw.providerKey ?? raw.provider).trimmingCharacters(in: .whitespacesAndNewlines) + let fallbackKey = canonicalManifestKey(provider: raw.provider, providerKey: raw.providerKey, via: raw.via) let key = fallbackKey.isEmpty ? "other" : fallbackKey let title = WidgetPlatformDisplay.title(canonicalKey: key, wireProvider: raw.provider) return (key, title, fallbackKey.isEmpty ? key : fallbackKey) diff --git a/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift b/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift index 744f2d57..5909cf29 100644 --- a/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift +++ b/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift @@ -298,12 +298,10 @@ public struct CompanionContentView: View { let short = item.cardShortWindow(scope: scope) let long = item.cardLongWindow(scope: scope) let cardWindows = item.cardWindows(scope: scope) - let extraWindows = cardWindows.filter { - $0.id != short?.window.id && $0.id != long?.window.id - } + let extraWindows = item.cardDetailWindows(scope: scope) let atCapWindow = item.atCapWindow(scope: scope) let isAtCap = atCapWindow != nil - let usableMuseExtra = item.providerKey == "muse-assist" ? cardWindows.first(where: { + let usableMuseExtra = item.providerKey == "muse-assist" && isAtCap ? cardWindows.first(where: { QuotaWindowVocabulary.isMuseAssistExtra(providerKey: item.providerKey, windowToken: $0.rawWindowToken, label: $0.label, resetAt: $0.resetAt) && (($0.remainingPercent ?? 0) > 0 || ($0.absoluteRemaining ?? 0) > 0) }) : nil @@ -443,26 +441,10 @@ public struct CompanionContentView: View { } } - // Multiple time periods / windows and provider details when expanded - if isExpanded { - let hasExtraWindows = !extraWindows.isEmpty - let hasDetails = !item.providerDetailRows.isEmpty - if hasExtraWindows || hasDetails { - Divider() - .padding(.vertical, 2) - - if hasExtraWindows { - VStack(alignment: .leading, spacing: 10) { - ForEach(extraWindows) { win in - windowRow(win) - } - } - } - - if hasDetails { - CompanionProviderDetailsView(rows: item.providerDetailRows) - .padding(.top, hasExtraWindows ? 6 : 0) - } + if isExpanded && !extraWindows.isEmpty { + Divider().padding(.vertical, 2) + VStack(alignment: .leading, spacing: 10) { + ForEach(extraWindows) { win in windowRow(win) } } } } diff --git a/ios/CodeCapsCompanion/Widgets/WidgetDataProvider.swift b/ios/CodeCapsCompanion/Widgets/WidgetDataProvider.swift index 7a03c979..613a8033 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetDataProvider.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetDataProvider.swift @@ -52,7 +52,7 @@ public struct CodeCapsWidgetEntry: TimelineEntry { } public var selectedDetail: WidgetPlatformItem? { guard let id = UserDefaults(suiteName: WidgetSnapshotStore.appGroupId)?.string(forKey: "widgetDetail:" + detailScope) else { return nil } - return platforms.first { $0.id == id } + return platforms.first { $0.id == id && $0.hasModelDetails } } /// Primary platform to display in single-provider focus widgets. diff --git a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift index 328c761a..87c2854e 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift @@ -91,6 +91,8 @@ public struct WidgetWindowItem: Identifiable, Equatable, Sendable { return (observedAt ?? .distantPast) > (other.observedAt ?? .distantPast) } + public var isModelDetail: Bool { label == "Fable limit" || label == "Argon limit" } + public var displayPercent: String { if !isMasked, remainingPercent == nil, let count = absoluteRemaining, count.isFinite, count >= 0 { return "\(count.formatted(.number.precision(.fractionLength(0...2)))) left" @@ -272,8 +274,12 @@ public struct WidgetPlatformItem: Identifiable, Equatable, Sendable { return max(0.0, min(1.0, pct / 100.0)) } + public var primaryWindows: [WidgetWindowItem] { windows.filter { !$0.isModelDetail } } + public var detailWindows: [WidgetWindowItem] { windows.filter(\.isModelDetail) } + public var hasModelDetails: Bool { !detailWindows.isEmpty } + public var elapsedFraction: Double? { - windows.compactMap { $0.elapsedFraction() }.first + primaryWindows.compactMap { $0.elapsedFraction() }.first } /// The window whose exhausted allowance caps this plan, honouring masked @@ -286,7 +292,7 @@ public struct WidgetPlatformItem: Identifiable, Equatable, Sendable { /// provider read "At Cap" beside bars the app had already recovered (owner, /// Oct-22-2026). public func atCapWindow(now: Date = Date()) -> WidgetWindowItem? { - windows + primaryWindows .filter { $0.isFresh(now: now) || (WidgetPresentation.isAtCap(percent: $0.remainingPercent, isExhausted: $0.isExhausted) && $0.resetAt != nil && $0.resetAt! > now) } .filter { !$0.isMasked && $0.remainingPercent != nil } .filter { WidgetPresentation.isAtCap(percent: $0.remainingPercent, isExhausted: $0.isExhausted) } @@ -321,9 +327,9 @@ public struct WidgetPlatformItem: Identifiable, Equatable, Sendable { /// A masked window can never win `.mostUrgent`, since "we cannot see this /// one" is not urgency. public func controllingWindow(_ pick: WidgetWindowPick = .mostUrgent) -> WidgetWindowItem? { - guard !windows.isEmpty else { return nil } - let visible = windows.filter { !$0.isMasked } - let pool = visible.isEmpty ? windows : visible + guard !primaryWindows.isEmpty else { return nil } + let visible = primaryWindows.filter { !$0.isMasked } + let pool = visible.isEmpty ? primaryWindows : visible switch pick { case .mostHeadroom: // Counts have no denominator and cannot be ranked as 100% headroom. @@ -337,6 +343,10 @@ public struct WidgetPlatformItem: Identifiable, Equatable, Sendable { ($0.resetAt ?? .distantFuture) < ($1.resetAt ?? .distantFuture) } case .mostUrgent: + if providerKey == "muse-assist", let weekly = pool.first(where: { !$0.isExtraAllowance }) { + if QuotaCapRule.isAtCap(remainingPercent: weekly.remainingPercent), let extra = usableMuseExtra { return extra } + return weekly + } return pool.min { // Least remaining first; soonest reset breaks the tie. let lhs = $0.remainingPercent ?? 100 @@ -353,8 +363,8 @@ public struct WidgetPlatformItem: Identifiable, Equatable, Sendable { /// this returns the pair (shortest period first). Returns nil if the plan does not have two distinct windows /// or if one of the windows carries no reading or reset date. public func dualWindows() -> (window1: WidgetWindowItem, window2: WidgetWindowItem)? { - guard windows.count >= 2 else { return nil } - let visible = windows.filter { !$0.isMasked && ($0.remainingPercent != nil || $0.absoluteRemaining != nil || $0.resetAt != nil) } + guard primaryWindows.count >= 2 else { return nil } + let visible = primaryWindows.filter { !$0.isMasked && ($0.remainingPercent != nil || $0.absoluteRemaining != nil || $0.resetAt != nil) } guard visible.count >= 2 else { return nil } return (visible[0], visible[1]) } @@ -383,8 +393,8 @@ public enum WidgetPresentation { public static func displayPercent(percent: Double?, isMasked: Bool) -> String { if isMasked { return "n/a" } - guard let percent else { return "—" } - return "\(Int(percent.rounded()))%" + guard let percent, percent.isFinite else { return "—" } + return "\(Int(min(100, max(0, percent)).rounded()))%" } public static func statusColor(percent: Double?, isMasked: Bool) -> Color { @@ -522,6 +532,8 @@ public enum WidgetPresentation { let window: String? let resetAt: String? let occurredAt: String? + let reportedAt: String? + let via: String? let source: String? let machine: String? let producerInstanceId: String? @@ -541,7 +553,7 @@ public enum WidgetPresentation { private enum CodingKeys: String, CodingKey { case id, provider, providerKey, label, remainingPercent, isExhausted - case modelType, modelId, window, resetAt, occurredAt, source, machine + case modelType, modelId, window, resetAt, occurredAt, reportedAt, via, source, machine case producerInstanceId, remainingUnknown, absoluteRemaining, plan, planName, planMetadata case planDetectedName, planUserName, planUserCostUsd, planUserRenewalDateText case planUserSubtitle, planShowCostAndRenewal, planHasMismatch, planUserUpdatedAt @@ -560,6 +572,8 @@ public enum WidgetPresentation { window = try container.decodeIfPresent(String.self, forKey: .window) resetAt = try container.decodeIfPresent(String.self, forKey: .resetAt) occurredAt = try container.decodeIfPresent(String.self, forKey: .occurredAt) + reportedAt = try container.decodeIfPresent(String.self, forKey: .reportedAt) + via = try container.decodeIfPresent(String.self, forKey: .via) source = try container.decodeIfPresent(String.self, forKey: .source) machine = try container.decodeIfPresent(String.self, forKey: .machine) producerInstanceId = try container.decodeIfPresent(String.self, forKey: .producerInstanceId) @@ -727,11 +741,11 @@ public enum WidgetPresentation { if !antigravityWindows.isEmpty { let geminiWindows = antigravityWindows.filter { let s = ($0.id + " " + $0.label + " " + ($0.modelType ?? "") + " " + ($0.modelId ?? "")).lowercased() - return s.contains("gemini") + return s.contains("gemini") || s.contains("argon") } let thirdPartyWindows = antigravityWindows.filter { let s = ($0.id + " " + $0.label + " " + ($0.modelType ?? "") + " " + ($0.modelId ?? "")).lowercased() - return !s.contains("gemini") + return !s.contains("gemini") && !s.contains("argon") } if let item = consolidateAntigravityPool( @@ -776,6 +790,16 @@ public enum WidgetPresentation { return platforms } + private static func quotaReading(_ wire: WireRawWindow, providerKey: String) -> QuotaCardProjection.Reading { + QuotaCardProjection.Reading(id: wire.id, providerKey: providerKey, label: wire.label, + window: wire.window, modelId: wire.modelId, modelType: wire.modelType, + remainingPercent: wire.remainingUnknown == true ? nil : wire.remainingPercent, + absoluteRemaining: wire.absoluteRemaining, + resetAt: parseDate(from: wire.resetAt), + reportedAt: parseDate(from: wire.reportedAt) ?? parseDate(from: wire.occurredAt), + source: wire.source, via: wire.via) + } + /// Build a single WidgetPlatformItem from a window group + manifest hints. private static func buildPlatformItem( id: String, @@ -803,123 +827,36 @@ public enum WidgetPresentation { } } - var windowByCadence: [String: WidgetWindowItem] = [:] - var cadenceOrder: [String] = [] - var childWindows: [WidgetWindowItem] = [] - - // A copy of a period that ended before the last refresh is not a - // reading, so it never becomes a row here either. The rule is the - // shared one, the same the Mac and the phone ask, so the three - // surfaces cannot drift apart, and it is asked with the reading's own - // observation time. It only judges copies: this Mac's own reading - // keeps its row, so an expired one greys out instead of vanishing. let liveWindows = rawWindows.filter { w in - let lowId = w.id.lowercased() - let lowLabel = w.label.lowercased() - if lowId.hasSuffix(":plan-metadata") || lowLabel == "plan details" { - return false - } - if (w.remainingUnknown == true || lowLabel.contains("plan details")) - && w.remainingPercent == nil - && w.absoluteRemaining == nil - && parseDate(from: w.resetAt) == nil - && !QuotaWindowVocabulary.isExtraAllowanceLabel(w.label) { - return false - } - if QuotaWindowVocabulary.isOwnDeviceWindow(id: w.id, - source: w.source, - machine: w.machine, - producerInstanceId: w.producerInstanceId, - ownInstanceId: ownInstanceId) { - return true - } - return !QuotaFreshnessRule.isDeadCopy(observedAt: parseDate(from: w.occurredAt), - resetAt: parseDate(from: w.resetAt), - now: now) + let reading = quotaReading(w, providerKey: providerKey) + guard reading.isQuota else { return false } + if QuotaWindowVocabulary.isOwnDeviceWindow(id: w.id, source: w.source, machine: w.machine, + producerInstanceId: w.producerInstanceId, ownInstanceId: ownInstanceId) { return true } + return !QuotaFreshnessRule.isDeadCopy(observedAt: reading.reportedAt, resetAt: reading.resetAt, now: now) } - - for w in liveWindows { - let parsedReset = parseDate(from: w.resetAt) - let observed = parseDate(from: w.occurredAt) - let cadence = formatCadence(w.label, window: w.window, resetAt: parsedReset) - let pct = w.remainingPercent - // The one shared rule decides, as it does on the phone and on the - // Mac: a reading outranks the export's stale exhausted word, and - // the word is the fallback for a window that reports no figure. - let exhausted = QuotaCapRule.isExhausted(remainingPercent: pct, - providerSaysExhausted: w.isExhausted ?? false) - let displayLabel = QuotaWindowVocabulary.windowLabel( - windowToken: w.window, - existingLabel: w.label.isEmpty ? cadence : w.label, - resetAt: parsedReset - ) - // The extra-allowance identity is read off the wire label, not - // off the display label: the display copy rewrites an extra - // allowance into the same "Other limit" text every unknown - // window gets, so by the time the qualifier is resolved the - // difference is gone. - let isExtraAllowance = QuotaWindowVocabulary.isExtraAllowance( - providerKey: providerKey, - label: w.label, - windowToken: w.window - ) - - let item = WidgetWindowItem( - id: w.id, - label: displayLabel, - cadence: cadence, - remainingPercent: pct, - resetAt: parsedReset, - isExhausted: exhausted, - isMasked: false, - observedAt: observed, - isExtraAllowance: isExtraAllowance, - absoluteRemaining: w.absoluteRemaining - ) - - // One window per cadence, and the freshest one. The payload - // carries a fleet copy beside the local window, and the fleet copy - // is often days old, so taking the first one in payload order let a - // stale copy win and the widget show figures the app had already - // replaced (owner, Oct-22-2026). - let cadenceKey = cadence.lowercased() - if let current = windowByCadence[cadenceKey] { - if item.isFresher(than: current, now: now) { - windowByCadence[cadenceKey] = item - } - } else { - cadenceOrder.append(cadenceKey) - windowByCadence[cadenceKey] = item - } + let readings = liveWindows.map { quotaReading($0, providerKey: providerKey) } + let childWindows = QuotaCardProjection.selectedIndices(in: readings, now: now).map { index in + let w = liveWindows[index] + let reading = readings[index] + return WidgetWindowItem(id: w.id, label: reading.displayLabel, + cadence: formatCadence(w.label, window: w.window, resetAt: reading.resetAt), + remainingPercent: reading.remainingPercent, resetAt: reading.resetAt, + isExhausted: QuotaCapRule.isExhausted(remainingPercent: reading.remainingPercent, + providerSaysExhausted: w.isExhausted ?? false), + observedAt: reading.reportedAt, + isExtraAllowance: QuotaWindowVocabulary.isExtraAllowance(providerKey: providerKey, + label: w.label, windowToken: w.window), absoluteRemaining: w.absoluteRemaining) } - childWindows = cadenceOrder.compactMap { windowByCadence[$0] } - - // Standardize cadence order: shorter periods (e.g. 5-hour) precede longer periods (e.g. weekly). - childWindows.sort { left, right in - let lPeriod = ResetAlarmCadence.periodSeconds(token: left.cadence, label: left.label) ?? 86400 - let rPeriod = ResetAlarmCadence.periodSeconds(token: right.cadence, label: right.label) ?? 86400 - if lPeriod != rPeriod { - return lPeriod < rPeriod - } - return left.id < right.id - } - - // The headline reads the fresh windows, the way the Mac's dashboard row - // does: a stale reading says how the plan looked when it was taken. - // The last known reading stands in when nothing is fresh, so a row with - // no live reading still shows what it last knew, beside the time it - // was taken. - let freshWindows = childWindows.filter { $0.isFresh(now: now) } - let freshPercent = freshWindows.compactMap(\.remainingPercent).min() - let lastKnownPercent = childWindows.compactMap(\.remainingPercent).min() - // Only a fresh window may cap the plan. - let atCap = freshWindows.first { - WidgetPresentation.isAtCap(percent: $0.remainingPercent, isExhausted: $0.isExhausted) - } - let controllingPct = atCap?.remainingPercent ?? freshPercent ?? lastKnownPercent - let isExhausted = atCap != nil - let nearestReset = childWindows.compactMap(\.resetAt).filter { $0 > now }.min() - ?? childWindows.compactMap(\.resetAt).min() + let primary = childWindows.filter { !$0.isModelDetail } + let fresh = primary.filter { $0.isFresh(now: now) } + let headline = fresh.isEmpty ? primary : fresh + let controllingPct = CardHeadline.percent(headline.map { + CardHeadline.Reading(isMuseAssistExtra: providerKey == "muse-assist" && $0.isExtraAllowance, + isMasked: $0.isMasked, remainingPercent: $0.remainingPercent) + }) + let isExhausted = fresh.contains { QuotaCapRule.isAtCap(remainingPercent: $0.remainingPercent) } + let nearestReset = primary.compactMap(\.resetAt).filter { $0 > now }.min() + ?? primary.compactMap(\.resetAt).min() let automaticPlan = rawWindows.compactMap(\.planName).first(where: { !$0.isEmpty }) ?? rawWindows.compactMap(\.plan).first(where: { !$0.isEmpty }) @@ -980,7 +917,7 @@ public enum WidgetPresentation { ownInstanceId: ownInstanceId) { return true } - return !QuotaFreshnessRule.isDeadCopy(observedAt: parseDate(from: w.occurredAt), + return !QuotaFreshnessRule.isDeadCopy(observedAt: parseDate(from: w.reportedAt) ?? parseDate(from: w.occurredAt), resetAt: parseDate(from: w.resetAt), now: now) } @@ -997,7 +934,7 @@ public enum WidgetPresentation { /// shared rule. func isFresh(_ window: WireRawWindow?) -> Bool { guard let window else { return false } - return QuotaFreshnessRule.isFresh(observedAt: parseDate(from: window.occurredAt), + return QuotaFreshnessRule.isFresh(observedAt: parseDate(from: window.reportedAt) ?? parseDate(from: window.occurredAt), resetAt: parseDate(from: window.resetAt), now: now) } @@ -1015,18 +952,10 @@ public enum WidgetPresentation { > (parseDate(from: current.occurredAt) ?? .distantPast) } - for w in windows { - let label = (w.label + " " + (w.window ?? "")).lowercased() - if label.contains("5h") || label.contains("5-hour") { - if isFresher(w, than: fiveHourWin) { - fiveHourWin = w - } - } else if label.contains("7d") || label.contains("weekly") || label.contains("1w") { - if isFresher(w, than: weeklyWin) { - weeklyWin = w - } - } - } + let readings = windows.map { quotaReading($0, providerKey: "google-antigravity") } + let selected = QuotaCardProjection.selectedPoolIndices(in: readings, poolKey: poolKey, now: now).map { windows[$0] } + fiveHourWin = selected.first { QuotaCardProjection.antigravityPeriod(quotaReading($0, providerKey: "google-antigravity")) == "5h" } + weeklyWin = selected.first { QuotaCardProjection.antigravityPeriod(quotaReading($0, providerKey: "google-antigravity")) == "weekly" } let weeklyPct = weeklyWin?.remainingPercent // Only a fresh window may spend the pool. A pool copy that is days old @@ -1052,7 +981,7 @@ public enum WidgetPresentation { resetAt: reset, isExhausted: fiveHourSpent, isMasked: weeklyExhausted, - observedAt: parseDate(from: f.occurredAt) + observedAt: parseDate(from: f.reportedAt) ?? parseDate(from: f.occurredAt) )) } @@ -1070,23 +999,22 @@ public enum WidgetPresentation { resetAt: reset, isExhausted: weeklyExhausted, isMasked: false, - observedAt: parseDate(from: w.occurredAt) + observedAt: parseDate(from: w.reportedAt) ?? parseDate(from: w.occurredAt) )) } - let validPercents = [fiveHourWin?.remainingPercent, weeklyWin?.remainingPercent].compactMap { $0 } - // The headline reads the fresh windows, the way the Mac's dashboard row - // does, and falls back to the last known reading when nothing is fresh. - let freshPercents = [ - fiveHourWin.flatMap { isFresh($0) ? $0.remainingPercent : nil }, - weeklyWin.flatMap { isFresh($0) ? $0.remainingPercent : nil } - ].compactMap { $0 } - let controllingPct = freshPercents.min() ?? validPercents.min() ?? windows.compactMap(\.remainingPercent).min() - // The pool rule the phone applies: a weekly the provider reports as - // spent spends the pool even when the five-hour window beside it still - // reports a healthy reading, and the controlling reading decides every - // other case. - let isExhausted = weeklyExhausted || QuotaCapRule.isAtCap(remainingPercent: freshPercents.min()) + let primary = childWindows + let fresh = primary.filter { $0.isFresh(now: now) && !$0.isMasked } + let fallback = primary.filter { !$0.isMasked } + let controllingPct = (fresh.isEmpty ? fallback : fresh).compactMap(\.remainingPercent).min() + let isExhausted = weeklyExhausted || QuotaCapRule.isAtCap(remainingPercent: fresh.compactMap(\.remainingPercent).min()) + let detailReports = windows.filter { quotaReading($0, providerKey: "google-antigravity").detailName == "Argon" } + if !detailReports.isEmpty { + let details = buildPlatformItem(id: "argon", providerKey: "google-antigravity", title: title, + iconHint: iconHint, defaultWindowLabel: nil, rawWindows: detailReports, now: now, + ownInstanceId: ownInstanceId) + childWindows += details.detailWindows + } let nearestReset = childWindows.compactMap(\.resetAt).filter { $0 > now }.min() ?? childWindows.compactMap(\.resetAt).min() @@ -1169,7 +1097,7 @@ public enum WidgetPresentation { if pKey.contains("muse-assist") || prov.contains("muse-assist") || prov.contains("muse assist") || id.contains("assist") { return ("muse-assist", "Muse Assist", "muse-assist") } - if pKey.contains("muse-code") || prov.contains("muse-code") || prov.contains("muse code") || id.contains("code") { + if pKey.contains("muse-code") || prov.contains("muse-code") || prov.contains("muse code") || id.hasPrefix("local-mac:muse-code:") { return ("muse-code", "Muse Code", "muse-code") } if pKey.contains("muse") || prov.contains("muse") { @@ -1184,7 +1112,7 @@ public enum WidgetPresentation { if pKey.contains("grok") || prov.contains("grok") || pKey.contains("xai") || prov.contains("xai") { return ("xai", "Grok", "xai") } - let fallbackKey = (raw.providerKey ?? raw.provider).trimmingCharacters(in: .whitespacesAndNewlines) + let fallbackKey = canonicalManifestKey(provider: raw.providerKey ?? raw.provider, via: raw.via) let key = fallbackKey.isEmpty ? "other" : fallbackKey let title = WidgetPlatformDisplay.title(canonicalKey: key, wireProvider: raw.provider) return (key, title, fallbackKey.isEmpty ? key : fallbackKey) diff --git a/ios/CodeCapsCompanion/Widgets/WidgetViews.swift b/ios/CodeCapsCompanion/Widgets/WidgetViews.swift index 8f6f1fdf..6b83aab0 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetViews.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetViews.swift @@ -638,7 +638,7 @@ struct ProviderFocusView: View { if entry.quotasPerProvider == .oneQuota, let controlling = platform.controllingWindow(pick) { return [controlling] } - return platform.windows + return platform.primaryWindows }() if let atCap, platform.usableMuseExtra == nil { @@ -877,10 +877,10 @@ struct WidgetPlanDetailView: View { Spacer() } Text(platform.title).font(.headline) - ForEach(Array(platform.windows.prefix(4))) { window in + ForEach(platform.detailWindows) { window in VStack(alignment: .leading, spacing: 4) { HStack(spacing: 8) { - Text(window.cadenceToken).font(.caption.bold()) + Text(window.label).font(.caption.bold()) Text(window.displayPercent).font(.subheadline.bold()).foregroundStyle(window.statusColor) Text(window.countdown().isEmpty ? "—" : window.countdown()) .font(.caption).foregroundStyle(.secondary) @@ -891,12 +891,6 @@ struct WidgetPlanDetailView: View { if window.isStale() { Text("Reading is stale").font(.caption2).foregroundStyle(.secondary) } } } - if platform.windows.count > 4 { - Text("+\(platform.windows.count - 4) more windows in CodeCaps").font(.caption2).foregroundStyle(.secondary) - } - if let plan = platform.planMetadata?.detectedPlanName, !plan.isEmpty { - Text(plan).font(.caption).foregroundStyle(.secondary).lineLimit(1) - } Spacer(minLength: 0) } } diff --git a/ios/CodeCapsCompanion/Widgets/WidgetWindowRows.swift b/ios/CodeCapsCompanion/Widgets/WidgetWindowRows.swift index 8d33a074..ce126573 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetWindowRows.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetWindowRows.swift @@ -399,7 +399,7 @@ struct PlanGrid: View { ) } } - if let detailScope { + if let detailScope, platform.hasModelDetails { Button(intent: ShowWidgetPlanDetailIntent(planID: platform.id, overviewKey: detailScope)) { Image(systemName: "info.circle").font(.system(size: 11)) } diff --git a/scripts/cursor-cloud-start.sh b/scripts/cursor-cloud-start.sh index df7c1568..b5575ca6 100755 --- a/scripts/cursor-cloud-start.sh +++ b/scripts/cursor-cloud-start.sh @@ -1,19 +1,19 @@ #!/usr/bin/env bash # Cursor cloud agent start for CodeCaps. # -# Runs on every agent boot. When the dashboard has injected -# INFISICAL_CLIENT_ID and INFISICAL_CLIENT_SECRET, logs into Infisical -# universal auth and exports the dev-env secret map for this repo to a -# 0600 file at $HOME/.cursor-cloud-env/codecaps.env, plus a tiny +# Runs on every agent boot. When the dashboard has injected the scoped +# CodeCaps prod-root read service token, it reads the configured project and +# exports the secret map for this repo to a 0600 file at +# $HOME/.cursor-cloud-env/codecaps.env, plus a tiny # codecaps.source.sh that future shells can `source` without printing. # # If the dashboard secrets are missing, prints the missing NAMES (never # values) and exits 0 so the agent boots cleanly. Never prints a secret # value at any point. # -# Uses the same universal-auth + raw-secrets API as scripts/infisical-fetch.mjs -# (which the mac-release workflow uses for GITHUB_ENV), but the dotenv -# output here is the form a Linux non-Apple script actually needs. +# Uses the same direct service-token + raw-secrets API as +# scripts/infisical-fetch.mjs, but the dotenv output here is the form a Linux +# non-Apple script actually needs. set -euo pipefail REPO_NAME="codecaps" @@ -39,19 +39,19 @@ if [[ "${INFISICAL_ENV:-prod}" != "prod" ]]; then exit 0 fi -# 2. Require the dashboard-injected credentials by NAME only. +# 2. Require the dashboard-injected project and service token by NAME only. MISSING=() -[[ -z "${INFISICAL_CLIENT_ID:-}" ]] && MISSING+=("INFISICAL_CLIENT_ID") -[[ -z "${INFISICAL_CLIENT_SECRET:-}" ]] && MISSING+=("INFISICAL_CLIENT_SECRET") +[[ -z "${INFISICAL_PROJECT_ID:-}" ]] && MISSING+=("INFISICAL_PROJECT_ID") +[[ -z "${INFISICAL_CODECAPS_PROD_ROOT_READ_SERVICE_TOKEN:-}" ]] \ + && MISSING+=("INFISICAL_CODECAPS_PROD_ROOT_READ_SERVICE_TOKEN") if (( ${#MISSING[@]} > 0 )); then echo "CodeCaps: skipping Infisical export. Add the following names to the Cursor dashboard secrets: ${MISSING[*]}" exit 0 fi -# 3. Fetch the prod-env secrets via the same API path as -# scripts/infisical-fetch.mjs (loginUniversalAuth + listSecretsRaw), -# then emit a dotenv file on stdout. The script does not echo values -# and does not log the response body. Stderr only carries status. +# 3. Fetch prod secrets with the scoped service token, then emit a dotenv +# file on stdout. The script does not echo credentials or log response +# bodies. Stderr only carries status. mkdir -p "${ENV_DIR}" chmod 0700 "${ENV_DIR}" @@ -62,26 +62,17 @@ if INFISICAL_SITE_URL="${INFISICAL_DOMAIN:-https://app.infisical.com}" \ INFISICAL_PROJECT_ID="${INFISICAL_PROJECT_ID:-}" \ INFISICAL_ENVIRONMENT="${INFISICAL_ENV:-prod}" \ INFISICAL_SECRET_PATH="${INFISICAL_SECRET_PATH:-/}" \ + INFISICAL_SERVICE_TOKEN="${INFISICAL_CODECAPS_PROD_ROOT_READ_SERVICE_TOKEN}" \ node -e ' const site = String(process.env.INFISICAL_SITE_URL || "").replace(/\/+$/, ""); const projectId = process.env.INFISICAL_PROJECT_ID || ""; const env = process.env.INFISICAL_ENVIRONMENT || "prod"; const path = process.env.INFISICAL_SECRET_PATH || "/"; - const cid = process.env.INFISICAL_CLIENT_ID || ""; - const cs = process.env.INFISICAL_CLIENT_SECRET || ""; + const token = process.env.INFISICAL_SERVICE_TOKEN || ""; const log = (m) => process.stderr.write(m + "\n"); - if (!site || !projectId || !cid || !cs) { log("CodeCaps: Infisical config incomplete; skipping."); process.exit(0); } + if (!site || !projectId || !token.startsWith("st.")) { log("CodeCaps: Infisical service-token config invalid; skipping."); process.exit(0); } (async () => { try { - const lr = await fetch(site + "/api/v1/auth/universal-auth/login", { - method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ clientId: cid, clientSecret: cs }), - signal: AbortSignal.timeout(30000), - }); - if (!lr.ok) { log("CodeCaps: Infisical login failed (HTTP " + lr.status + ")."); process.exit(0); } - const lb = await lr.json(); - const token = lb && lb.accessToken; - if (!token) { log("CodeCaps: Infisical login returned no accessToken."); process.exit(0); } const qs = new URLSearchParams({ workspaceId: projectId, environment: env, secretPath: path, viewSecretValue: "true", expandSecretReferences: "false", include_imports: "false", diff --git a/scripts/infisical-fetch-expand.node-test.mjs b/scripts/infisical-fetch-expand.node-test.mjs index db2eaba7..d938c28d 100644 --- a/scripts/infisical-fetch-expand.node-test.mjs +++ b/scripts/infisical-fetch-expand.node-test.mjs @@ -12,14 +12,11 @@ import { isUnresolvedReference, run } from "./infisical-fetch.mjs"; const REFERENCE = "${prod.global-api-keys.SENTINEL_KEY_ref_3c9e}"; const RESOLVED = "sentinel-resolved-value-5d1a"; -/** Stub Infisical: login succeeds, the list call returns the fixture secrets - * and records every list URL so a test can assert on the query string. */ +/** Stub Infisical: the list call returns the fixture secrets and records + * every list URL so a test can assert on the query string. */ function stubFetch(vaultSecrets, listUrls = []) { return async (url) => { const u = String(url); - if (u.includes("/api/v1/auth/universal-auth/login")) { - return { ok: true, json: async () => ({ accessToken: "test-token", expiresIn: 3600 }) }; - } if (u.includes("/api/v3/secrets/raw")) { listUrls.push(u); return { @@ -37,21 +34,17 @@ function baseEnv(githubEnv, names) { return { INFISICAL_NAMES: names, INFISICAL_PROJECT_ID: "proj", - INFISICAL_CLIENT_ID: "id", - INFISICAL_CLIENT_SECRET: "secret", + INFISICAL_SERVICE_TOKEN: "st.test-id.test-secret", GITHUB_ENV: githubEnv, }; } -test("the secrets request carries the bearer token from the login", async () => { +test("the secrets request carries the full scoped service token as its bearer without login", async () => { const dir = mkdtempSync(join(tmpdir(), "ops818-fetch-")); try { const authHeaders = []; const stub = async (url, options) => { const u = String(url); - if (u.includes("/api/v1/auth/universal-auth/login")) { - return { ok: true, json: async () => ({ accessToken: "test-token", expiresIn: 3600 }) }; - } if (u.includes("/api/v3/secrets/raw")) { authHeaders.push(options && options.headers && options.headers.authorization); return { ok: true, json: async () => ({ secrets: [{ secretKey: "FOO", secretValue: RESOLVED }] }) }; @@ -61,7 +54,7 @@ test("the secrets request carries the bearer token from the login", async () => await run({ env: baseEnv(join(dir, "env"), "FOO"), fetchImpl: stub, log: () => {} }); // A broken token has to fail the request, and a test that ignored the // header would not have noticed. - assert.deepEqual(authHeaders, ["Bearer test-token"]); + assert.deepEqual(authHeaders, ["Bearer st.test-id.test-secret"]); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/scripts/infisical-fetch.mjs b/scripts/infisical-fetch.mjs index 0f6a352c..eb020824 100644 --- a/scripts/infisical-fetch.mjs +++ b/scripts/infisical-fetch.mjs @@ -1,10 +1,8 @@ -// Copied from Simple-With-Us/BotFleet scripts/infisical-fetch.mjs, in step with -// BotFleet's main at b91fa490e7e7 on 2026-10-21, together with -// .github/actions/infisical-secrets, so the Mac release workflow reads its -// signing certificate the way BotFleet's release.yml does. Keep the two copies -// in step until the fleet has a shared action. +// Originated from Simple-With-Us/BotFleet scripts/infisical-fetch.mjs and its +// composite action. CodeCaps uses direct scoped service-token auth per owner +// policy; keep the masking and fallback behavior covered by local contract tests. // -// CI-side Infisical fetch: universal-auth login, one bulk secrets list, then +// CI-side Infisical fetch: direct scoped service-token auth, one bulk list, then // per requested name mask + export into $GITHUB_ENV -- falling back to a // same-named GH_FALLBACK_ step env var, warning when a name stays // empty everywhere, and failing only for a name listed in `required`. @@ -36,28 +34,6 @@ function stripTrailingSlash(url) { return String(url ?? "").replace(/\/+$/, ""); } -/** POST .../api/v1/auth/universal-auth/login -- returns the bearer token - * string only. Body is built with JSON.stringify, never string - * interpolation, so a client secret containing a quote cannot break the - * request shape. */ -export async function loginUniversalAuth({ siteUrl, clientId, clientSecret, fetchImpl = fetch, timeoutMs = 30_000 }) { - const res = await fetchImpl(`${siteUrl}/api/v1/auth/universal-auth/login`, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ clientId, clientSecret }), - signal: AbortSignal.timeout(timeoutMs), - }); - if (!res.ok) { - throw new Error(`Infisical login failed: HTTP ${res.status}`); - } - const body = await res.json(); - const token = body && body.accessToken; - if (!token) { - throw new Error("Infisical login response carried no accessToken"); - } - return token; -} - /** GET .../api/v3/secrets/raw for the whole path in one call -- returns a * Map. viewSecretValue is always "true" here; this * script only ever runs where values are needed (it exists to populate @@ -67,7 +43,7 @@ export async function loginUniversalAuth({ siteUrl, clientId, clientSecret, fetc * reference such as ${prod.some-folder.NAME} (the Fleet-OPS root, OPS-818) comes * back as the referenced value. With "false" the literal reference string * would land in GITHUB_ENV as if it were the credential. Expanding needs the - * reading identity to be able to read the referenced folder too. */ + * scoped service token to read the referenced folder too. */ export async function listSecretsRaw({ siteUrl, token, projectId, environment, secretPath, fetchImpl = fetch, timeoutMs = 30_000 }) { const qs = new URLSearchParams({ workspaceId: projectId, @@ -137,7 +113,7 @@ export function writeGithubEnvValue(path, name, value, appendFileImpl = appendFi /** A value that is still a bare Infisical reference such as * ${prod.some-folder.NAME}: the server did not expand it (target missing, or - * the reading identity cannot read the referenced folder). Exporting it would + * the scoped service token cannot read the referenced folder). Exporting it would * hand a workflow the literal reference string as if it were the credential. */ export const UNRESOLVED_REFERENCE = /^\$\{[^}]+\}$/; @@ -148,12 +124,15 @@ export function isUnresolvedReference(value) { /** Resolves the vault snapshot (empty map when unconfigured or the fetch * failed) -- never throws; a failure is reported through `log` and the * caller proceeds on GH_FALLBACK_ alone. */ -async function resolveVaultValues({ siteUrl, projectId, clientId, clientSecret, environment, secretPath, fetchImpl, log }) { - if (!projectId || !clientId || !clientSecret) { +async function resolveVaultValues({ siteUrl, projectId, token, environment, secretPath, fetchImpl, log }) { + if (!projectId || !token) { + return new Map(); + } + if (!token.startsWith("st.")) { + log("::warning::Infisical service token is not configured; using GitHub secret fallbacks only."); return new Map(); } try { - const token = await loginUniversalAuth({ siteUrl, clientId, clientSecret, fetchImpl }); return await listSecretsRaw({ siteUrl, token, projectId, environment, secretPath, fetchImpl }); } catch (err) { // Never interpolate the raw error body -- Infisical error payloads have @@ -172,11 +151,10 @@ export async function run({ env = process.env, fetchImpl = fetch, log = (line) = const projectId = env.INFISICAL_PROJECT_ID || ""; const environment = env.INFISICAL_ENVIRONMENT || "prod"; const secretPath = env.INFISICAL_SECRET_PATH || "/"; - const clientId = env.INFISICAL_CLIENT_ID || ""; - const clientSecret = env.INFISICAL_CLIENT_SECRET || ""; + const token = env.INFISICAL_SERVICE_TOKEN || ""; const githubEnvPath = env.GITHUB_ENV || ""; - const vaultValues = await resolveVaultValues({ siteUrl, projectId, clientId, clientSecret, environment, secretPath, fetchImpl, log }); + const vaultValues = await resolveVaultValues({ siteUrl, projectId, token, environment, secretPath, fetchImpl, log }); const missingRequired = []; const unresolved = []; @@ -198,7 +176,7 @@ export async function run({ env = process.env, fetchImpl = fetch, log = (line) = if (isUnresolvedReference(value)) { // Name the KEY only -- never the value, even though it is a reference. unresolved.push(name); - log(`::error::${name} is still an unresolved Infisical secret reference after the ${environment} export; check the target exists and the CI identity can read the referenced folder.`); + log(`::error::${name} is still an unresolved Infisical secret reference after the ${environment} export; check the target exists and the scoped service token can read the referenced folder.`); continue; } maskValue(value, log); diff --git a/scripts/infisical-fetch.node-test.mjs b/scripts/infisical-fetch.node-test.mjs index 4d02f2ef..57db8918 100644 --- a/scripts/infisical-fetch.node-test.mjs +++ b/scripts/infisical-fetch.node-test.mjs @@ -25,18 +25,12 @@ function tempGithubEnv() { return { dir, path: join(dir, "github_env") }; } -/** A stub fetch standing in for Infisical: login always succeeds, the list - * call returns exactly the fixture secrets given. Neither ever touches the - * network. */ +/** A stub fetch standing in for Infisical: the list call returns exactly + * the fixture secrets given. It rejects any unexpected auth endpoint and never + * touches the network. */ function stubFetch(vaultSecrets) { return async (url) => { const u = String(url); - if (u.includes("/api/v1/auth/universal-auth/login")) { - return { - ok: true, - json: async () => ({ accessToken: "test-token", expiresIn: 3600 }), - }; - } if (u.includes("/api/v3/secrets/raw")) { return { ok: true, @@ -62,8 +56,7 @@ test("a name present in the vault is masked and written to GITHUB_ENV", async () env: { INFISICAL_NAMES: "FOO", INFISICAL_PROJECT_ID: "proj", - INFISICAL_CLIENT_ID: "id", - INFISICAL_CLIENT_SECRET: "secret", + INFISICAL_SERVICE_TOKEN: "st.test-id.test-secret", GITHUB_ENV: path, }, fetchImpl: stubFetch({ FOO: SENTINEL_PRESENT }), @@ -94,8 +87,7 @@ test("a name missing from the vault falls back to GH_FALLBACK_", async () env: { INFISICAL_NAMES: "BAR", INFISICAL_PROJECT_ID: "proj", - INFISICAL_CLIENT_ID: "id", - INFISICAL_CLIENT_SECRET: "secret", + INFISICAL_SERVICE_TOKEN: "st.test-id.test-secret", GH_FALLBACK_BAR: SENTINEL_FALLBACK, GITHUB_ENV: path, }, @@ -120,8 +112,7 @@ test("a name missing from both the vault and the fallback warns and is absent", env: { INFISICAL_NAMES: "BAZ", INFISICAL_PROJECT_ID: "proj", - INFISICAL_CLIENT_ID: "id", - INFISICAL_CLIENT_SECRET: "secret", + INFISICAL_SERVICE_TOKEN: "st.test-id.test-secret", GITHUB_ENV: path, }, fetchImpl: stubFetch({}), @@ -156,8 +147,7 @@ test("a missing required name rejects instead of silently continuing", async () INFISICAL_NAMES: "QUX", INFISICAL_REQUIRED: "QUX", INFISICAL_PROJECT_ID: "proj", - INFISICAL_CLIENT_ID: "id", - INFISICAL_CLIENT_SECRET: "secret", + INFISICAL_SERVICE_TOKEN: "st.test-id.test-secret", GITHUB_ENV: path, }, fetchImpl: stubFetch({}), @@ -181,8 +171,7 @@ test("every line in a mixed run is either an add-mask carrier or a warning, neve env: { INFISICAL_NAMES: "FOO BAZ", INFISICAL_PROJECT_ID: "proj", - INFISICAL_CLIENT_ID: "id", - INFISICAL_CLIENT_SECRET: "secret", + INFISICAL_SERVICE_TOKEN: "st.test-id.test-secret", GITHUB_ENV: path, }, fetchImpl: stubFetch({ FOO: SENTINEL_PRESENT }), @@ -200,7 +189,7 @@ test("every line in a mixed run is either an add-mask carrier or a warning, neve } }); -test("no configured identity resolves purely from GH_FALLBACK_, with no fetch call", async () => { +test("no configured service token resolves purely from GH_FALLBACK_, with no fetch call", async () => { const { dir, path } = tempGithubEnv(); try { const { lines, log } = collectLines(); @@ -232,8 +221,7 @@ test("every line of a multi-line value gets its own ::add-mask:: and is never pr env: { INFISICAL_NAMES: "MAC_CERT_P12_BASE64", INFISICAL_PROJECT_ID: "proj", - INFISICAL_CLIENT_ID: "id", - INFISICAL_CLIENT_SECRET: "secret", + INFISICAL_SERVICE_TOKEN: "st.test-id.test-secret", GITHUB_ENV: path, }, fetchImpl: stubFetch({ MAC_CERT_P12_BASE64: SENTINEL_MULTILINE }), From da4e47e8fcf84c47e9bf525301170f87e4b2e70c Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:39:47 +0000 Subject: [PATCH 09/12] Use Scoped Service Tokens In Release Tooling --- scripts/install-release-secrets-tooling.sh | 186 +++++---------------- 1 file changed, 43 insertions(+), 143 deletions(-) diff --git a/scripts/install-release-secrets-tooling.sh b/scripts/install-release-secrets-tooling.sh index 7f866c68..e6767df4 100755 --- a/scripts/install-release-secrets-tooling.sh +++ b/scripts/install-release-secrets-tooling.sh @@ -1,26 +1,11 @@ #!/usr/bin/env bash -# Install the credential tooling the release workflows read Fleet-OPS with, -# mint the Infisical access token that tooling uses, and run the consumer that -# resolves the credentials. +# Install the pinned Infisical CLI and fleet-owned `fleet-secrets` reader, pass +# the reader a read-only service token scoped to Fleet-OPS prod /asc, prove it +# can list that folder's names, and run scripts/stage-asc-key.mjs. # -# It installs two things: -# -# * the Infisical CLI, pinned to version 0.44.4. The release tarball is -# checked against the pinned SHA-256 of the asset before it is unpacked, -# so a moved or rebuilt asset fails the step instead of installing -# something nobody reviewed. -# * the fleet's `fleet-secrets` reader, taken from the pinned commit of the -# public AI-Fleet-Coordinator repository and installed with the upstream -# installer, so the runner ends up with the layout every fleet Mac has. -# -# It then mints an Infisical access token with universal auth, proves that the -# fleet's reader can use that token, and runs scripts/stage-asc-key.mjs, the -# only thing in the release that reads a credential. -# -# The token never touches a file. It is minted into a shell variable, it is -# exported into the environment of the consumer, and the consumer runs in this -# same process tree. It is never echoed, never printed, never written to -# $GITHUB_ENV and never written to disk. +# The full service token is supplied by the workflow, stays in process memory, +# and is passed directly as INFISICAL_TOKEN to the reader. It is never echoed, +# written to a file, or written to $GITHUB_ENV. # # The reader is proven before the consumer runs, because the consumer cannot # tell a broken reader from a missing credential: it reads a failed lookup as @@ -29,26 +14,12 @@ # when the fault is the tooling. The proof is read-only: it lists the names # in Fleet-OPS prod /asc and never a value. # -# The names the workflow already uses are mapped here onto the names the -# reader and the CLI expect: -# -# INFISICAL_PROJECT_ID -> INFISICAL_FLEET_OPS_PROJECT_ID -# INFISICAL_CLIENT_ID -> INFISICAL_UNIVERSAL_AUTH_CLIENT_ID -# INFISICAL_CLIENT_SECRET -> INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET -# +# The workflow supplies INFISICAL_PROJECT_ID and INFISICAL_SERVICE_TOKEN. +# This script maps the project id to the reader's expected environment name. # Run: bash scripts/install-release-secrets-tooling.sh set +o xtrace set -euo pipefail -# The replacement in a bash substitution is a pattern, and in bash 5.2 and -# later an ampersand in it expands to the text that matched, which here would -# be the credential itself. The option is turned off where the shell has it, -# and the preview refuses a value that could put one in the replacement, so -# neither shell can expand one back into the secret. -if shopt -q patsub_replacement 2>/dev/null; then - shopt -u patsub_replacement -fi - INFISICAL_CLI_VERSION="0.44.4" INFISICAL_CLI_SHA256_arm64="02ccd2ce6e1d80eeafb06022697fe7f3c6434ba757b31590f2ff8f88d6ccaf51" INFISICAL_CLI_SHA256_x86_64="35a6af67d361bf4f14ec814c08143293dd00f35eb0ad6a171eec967ca5c9585e" @@ -79,7 +50,19 @@ fail() { return 1 } -# The SHA-256 of a file, with the two tools a runner may have. +# Reader diagnostics are captured, but the service token is still redacted if +# an upstream tool echoes it into stderr. +scrub() { + local text="$1" + if [ -n "${INFISICAL_SERVICE_TOKEN:-}" ]; then + text="${text//"$INFISICAL_SERVICE_TOKEN"/}" + fi + if [ -n "${INFISICAL_TOKEN:-}" ]; then + text="${text//"$INFISICAL_TOKEN"/}" + fi + printf '%s' "$text" +} + sha256_of() { if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}' @@ -88,64 +71,6 @@ sha256_of() { fi } -# A masked preview of a credential: the first eight characters and the last -# four, with an ellipsis between them. It is not reversible, because the -# ellipsis stands for the part that is not shown, and it names the value that -# was rejected so an operator can tell which one it was without being handed -# the value (rule 43). -# -# The preview is only a preview when the middle of the value is really hidden. -# The two slices cover twelve characters between them, so a value of twelve -# characters or fewer would be reconstructed in full by the two of them -# together; those are redacted outright instead. The message that carries the -# preview names the credential, so an operator still knows which value was -# refused without any part of the value being shown. -# -# The preview also has to be an ordinary string. The replacement in a bash -# substitution is a pattern, and in bash 5.2 and later an ampersand in it -# expands to the text that matched, which here would be the credential -# itself. A value that could put one in the preview is refused, so the -# preview can only ever be text. -mask() { - local value="$1" - case "$value" in - *[\&]*) printf '%s' ""; return ;; - esac - if [ "${#value}" -le 12 ]; then - printf '%s' "" - return - fi - printf '%s…%s' "${value:0:8}" "${value: -4}" -} - -# A tool's own error text, with the client id, the client secret and the -# access token taken out of it. A failed login or a failed read must be -# diagnosable from the log, and no part of the identity belongs in a log. -# The token is minted fresh for every job, so a slice of it would identify -# nothing an operator can act on; the diagnosis names the fault instead. -# -# The client id and the client secret are long lived and the runner masks -# them by value, so they are redacted whole: a preview of either would -# defeat that masking and put twelve characters of a standing credential in -# a public log. The access token is minted for one job, so it may carry a -# preview, and that preview is what tells the operator which value was -# refused. -scrub() { - local text="$1" masked redacted - redacted='' - if [ -n "${INFISICAL_CLIENT_ID:-}" ]; then - text="${text//"$INFISICAL_CLIENT_ID"/${redacted}}" - fi - if [ -n "${INFISICAL_CLIENT_SECRET:-}" ]; then - text="${text//"$INFISICAL_CLIENT_SECRET"/${redacted}}" - fi - if [ -n "${INFISICAL_TOKEN:-}" ]; then - masked="$(mask "$INFISICAL_TOKEN")" - text="${text//"$INFISICAL_TOKEN"/${masked}}" - fi - printf '%s' "$text" -} - install_infisical_cli() { local asset expected actual published base case "$(uname -m)" in @@ -168,8 +93,6 @@ install_infisical_cli() { actual="$(sha256_of "$work/$asset")" [ "$actual" = "$expected" ] \ || { fail "the Infisical CLI $asset does not match the pinned checksum"; return 1; } - # The release publishes the same checksum in its own list. A disagreement - # means the asset moved, and the step fails rather than installing it. if curl -fsSL "$base/checksums-darwin.txt" -o "$work/checksums.txt" 2>/dev/null; then published="$(awk -v a="$asset" '$2 == a { print $1 }' "$work/checksums.txt")" if [ -n "$published" ] && [ "$published" != "$expected" ]; then @@ -205,40 +128,24 @@ install_fleet_secrets() { say "installed: fleet-secrets ($FLEET_READER_COMMIT) -> $TOOLS_DIR/fleet-secrets" } -mint_token() { - local status token project_id - project_id="${INFISICAL_PROJECT_ID:-}" +configure_service_token() { + local project_id token + project_id="${INFISICAL_PROJECT_ID:-${INFISICAL_FLEET_OPS_PROJECT_ID:-}}" [ -n "$project_id" ] || { fail "the Fleet-OPS Infisical project id is not set"; return 1; } - [ -n "${INFISICAL_CLIENT_ID:-}" ] \ - || { fail "the Infisical universal auth client id is not set"; return 1; } - [ -n "${INFISICAL_CLIENT_SECRET:-}" ] \ - || { fail "the Infisical universal auth client secret is not set"; return 1; } - - export INFISICAL_UNIVERSAL_AUTH_CLIENT_ID="$INFISICAL_CLIENT_ID" - export INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET="$INFISICAL_CLIENT_SECRET" - export INFISICAL_DISABLE_UPDATE_CHECK="true" - - # The token is minted into a shell variable and stays there. It is read - # from the command's output, which never reaches the log, and it is never - # written to a file. - status=0 - token="$("$TOOLS_DIR/infisical" login --method=universal-auth --plain --silent 2>"$work/login.err")" || status=$? - if [ "$status" -ne 0 ]; then - say "the Infisical CLI refused the universal auth login (exit $status); the client id or the client secret was refused: $(scrub "$(cat "$work/login.err")")" - fail "no Infisical access token was minted" - return 1 - fi + token="${INFISICAL_SERVICE_TOKEN:-}" + [ -n "$token" ] || { fail "the Fleet-OPS /asc read service token is not set"; return 1; } case "$token" in - "") fail "the Infisical CLI returned no access token"; return 1 ;; - *[[:space:]]*) fail "the Infisical CLI returned an access token that is not a single line"; return 1 ;; + st.*.*) ;; + *) fail "the Fleet-OPS /asc credential is not a full Infisical service token"; return 1 ;; + esac + case "$token" in + *[[:space:]]*) fail "the Fleet-OPS /asc service token is not a single line"; return 1 ;; esac - - # The token and the project id are the session the consumer inherits. The - # client secret stays out of it: the token is the identity from here on. export INFISICAL_TOKEN="$token" export INFISICAL_FLEET_OPS_PROJECT_ID="$project_id" export PATH="$TOOLS_DIR:$PATH" - say "minted: an Infisical access token for the consumer" + unset INFISICAL_SERVICE_TOKEN + say "configured: read-only Infisical service token for Fleet-OPS prod /asc" } # The reader is proven before the consumer runs. The consumer reads a failed @@ -248,8 +155,8 @@ mint_token() { # names the fault instead. # # The proof is read-only and lists names, never values: `fleet-secrets names -# --path /asc` is the fleet's own reader, and it carries the minted token -# through INFISICAL_TOKEN. +# --path /asc` is the fleet's own reader, and it carries the scoped service +# token through INFISICAL_TOKEN. # # The reader's exit codes are its own: 2 is a refused configuration, 4 is a # fetch or auth failure and 5 is an unresolved reference in the vault. A @@ -307,7 +214,7 @@ check_reader() { fail "the fleet-secrets reader refused to read Fleet-OPS prod /asc (exit 2); the reader or its configuration is at fault, not the vault permissions: ${detail}" ;; 4) - fail "the fleet-secrets reader could not read Fleet-OPS prod /asc (exit 4); the minted Infisical access token was rejected or the vault was unreachable: ${detail}" + fail "the fleet-secrets reader could not read Fleet-OPS prod /asc (exit 4); the service token was rejected or the vault was unreachable: ${detail}" ;; *) fail "the fleet-secrets reader failed to list Fleet-OPS prod /asc (exit ${status}); the reader is at fault: ${detail}" @@ -317,30 +224,23 @@ check_reader() { } install_tooling() { + configure_service_token || return 1 install_infisical_cli || return 1 install_fleet_secrets || return 1 - mint_token || return 1 check_reader || return 1 } -# The reader can be proved on its own, with a token the caller already holds. -# An operator runs it to test a reader or a token without running a release -# step, and the contract test drives it with a stubbed reader: +# The reader can be proved on its own with the caller-supplied scoped token. +# The contract test drives this path with a stubbed reader: # -# INFISICAL_TOKEN=... INFISICAL_FLEET_OPS_PROJECT_ID=... \ +# INFISICAL_SERVICE_TOKEN=st.. INFISICAL_PROJECT_ID=... \ # bash scripts/install-release-secrets-tooling.sh check-reader # -# Without an argument the script does the whole release job: install the -# tooling, mint the token, prove the reader and run the consumer. +# Without an argument the script configures that token, installs the reader, +# proves the read scope, and runs the consumer. if [ "${1:-}" = "check-reader" ]; then export PATH="$TOOLS_DIR:$PATH" - # Without a token the reader falls back to sources a runner does not have - # and fails the way a rejected token fails, so an absent token is named - # before the reader is asked. - if [ -z "${INFISICAL_TOKEN:-}" ]; then - fail "no Infisical access token in the environment; export INFISICAL_TOKEN and INFISICAL_FLEET_OPS_PROJECT_ID before proving the reader" - exit 1 - fi + configure_service_token || exit 1 check_reader || exit 1 exit 0 fi From 6ba06c1f094adc5a99845f7d987520f4ad9caddf Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:44:11 +0000 Subject: [PATCH 10/12] Compile Companion And Widgets In Native Fixtures --- scripts/test-widget-ui-native.sh | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/scripts/test-widget-ui-native.sh b/scripts/test-widget-ui-native.sh index e70fead7..0da1eb84 100755 --- a/scripts/test-widget-ui-native.sh +++ b/scripts/test-widget-ui-native.sh @@ -13,6 +13,14 @@ done for name in ResetAlarmCadence QuotaWindowVocabulary QuotaWindowCaption FleetSourceDisagreement WidgetPlatformDisplay PlanMetadata WidgetSnapshotFetcher CompanionReadTokenStore; do sources+=("Sources/QuotaCore/$name.swift") done +# Compile the actual companion model and views without constructing the stateful model. +sources+=("ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift" + "ios/CodeCapsCompanion/App/Models/CompanionTheme.swift" + "ios/CodeCapsCompanion/App/Models/AlarmSoundPlayer.swift" + "ios/CodeCapsCompanion/App/Models/SentenceGap.swift" + "ios/CodeCapsCompanion/App/Views/CompanionContentView.swift" + "Sources/QuotaCore/UsageAlertPreferences.swift" "Sources/QuotaCore/ResetAlarmSound.swift" + "Sources/QuotaCore/ResetAlarmTracker.swift" "Sources/QuotaCore/ResetAlarmMessage.swift") swiftc -parse-as-library "${sources[@]}" Tests/Fixtures/WidgetUIProbe.swift -o "$out/probe" CODECAPS_WIDGET_RENDER_DIR="$out" "$out/probe" printf 'Native render artifacts: %s\n' "$out" From a401fb7933fed74e897d37b5f77e145934d59348 Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:15:23 +0000 Subject: [PATCH 11/12] Verify Service-Token Release Workflow Inputs --- .../ios-fleet/test-publish-ios-versions.sh | 3 +- scripts/ios-ship-workflow.test.mjs | 7 +++- scripts/mac-release-workflow.test.mjs | 32 +++++++++++++------ 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/scripts/ios-fleet/test-publish-ios-versions.sh b/scripts/ios-fleet/test-publish-ios-versions.sh index 9a83d6c4..c97d11f1 100755 --- a/scripts/ios-fleet/test-publish-ios-versions.sh +++ b/scripts/ios-fleet/test-publish-ios-versions.sh @@ -117,7 +117,8 @@ grep -q "HTTP 403" "${TMP}/fail.err" grep -q "Resource not accessible" "${TMP}/fail.err" # No credential: the cause is printed, including why the ship token cannot work. -if PATH="/usr/bin:/bin" HOME="${TMP}" bash "${TMP}/fleet/publish-ios-versions.sh" \ +if env -u IOS_VERSIONS_PUBLISH_TOKEN -u GH_TOKEN -u GITHUB_TOKEN \ + PATH="/usr/bin:/bin" HOME="${TMP}" bash "${TMP}/fleet/publish-ios-versions.sh" \ --bundle-id com.simplewithus.codecaps.ios --version 1.0.264 >"${TMP}/notoken.out" 2>"${TMP}/notoken.err"; then echo "FAIL: no-credential publish must exit non-zero so the ship log warns" >&2; exit 1 fi diff --git a/scripts/ios-ship-workflow.test.mjs b/scripts/ios-ship-workflow.test.mjs index fe088e0b..fa4815a0 100644 --- a/scripts/ios-ship-workflow.test.mjs +++ b/scripts/ios-ship-workflow.test.mjs @@ -212,7 +212,12 @@ test("ASC credentials come from Fleet-OPS /asc, never the stale repository secre // the step fell through to the repository copies without saying so. assert.doesNotMatch(code, /project-id: \$\{\{ secrets\.INFISICAL_PROJECT_ID \}\}/); assert.match(code, /project-id: \$\{\{ secrets\.INFISICAL_FLEET_OPS_PROJECT_ID \}\}/); - assert.match(code, /secrets\.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID/); + assert.equal( + (code.match(/secrets\.INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN/g) || []).length, + 2, + 'the root Sentry loader and /asc key loader share one read service token', + ); + assert.doesNotMatch(code, /INFISICAL_CLIENT_ID|INFISICAL_CLIENT_SECRET|UNIVERSAL_AUTH/); assert.doesNotMatch(code, /infisical secrets get/); assert.doesNotMatch(code, /infisical\/get-cli/); // No new code may talk to the vault directly. diff --git a/scripts/mac-release-workflow.test.mjs b/scripts/mac-release-workflow.test.mjs index 09ee75de..8f415920 100644 --- a/scripts/mac-release-workflow.test.mjs +++ b/scripts/mac-release-workflow.test.mjs @@ -77,13 +77,13 @@ test('Sparkle reads the ASC credentials through the fleet reader, never reposito // direct loader must not be called from a workflow at all. assert.doesNotMatch(loader, /node scripts\/infisical-fetch\.mjs/); // The step is a single call to the tooling, and the tooling runs the - // consumer in the same process tree, so the minted token reaches it + // consumer in the same process tree, so the supplied service token reaches it // through its environment and never through a file. assert.match(loader, /run: \|[\s\S]*bash scripts\/install-release-secrets-tooling\.sh/); const tooling = read('scripts/install-release-secrets-tooling.sh'); assert.match(tooling, /node "\$repo_root\/scripts\/stage-asc-key\.mjs"/); assert.doesNotMatch(tooling, /release-secrets-env\.sh/); - // The minted token must never reach the log. The guard names every output + // The supplied service token must never reach the log. The guard names every output // helper the script has, because a regression that printed through `say` or // `fail` would leak the token while a guard that only matched `printf` // still passed. @@ -97,14 +97,18 @@ test('Sparkle reads the ASC credentials through the fleet reader, never reposito // is sent to fix vault permissions when the fault is the tooling. assert.match(tooling, /check_reader/); assert.match(tooling, /names --path \/asc/); - // The proof is a step of the install, after the token is minted, and the + // The proof is a step of the install, after the token is configured, and the // install is called before the consumer. The order is asserted at the // call site: the guard inside the function body only says the function // would prove the reader, not that the release calls it first. const installStart = tooling.indexOf('install_tooling() {'); assert.notEqual(installStart, -1, 'the install has to be one function'); const installBody = tooling.slice(installStart, tooling.indexOf('\n}\n', installStart)); - assert.match(installBody, /mint_token \|\| return 1[\s\S]*check_reader \|\| return 1/); + assert.match(installBody, /configure_service_token \|\| return 1[\s\S]*install_infisical_cli \|\| return 1[\s\S]*install_fleet_secrets \|\| return 1[\s\S]*check_reader \|\| return 1/); + assert.match(tooling, /INFISICAL_CLI_VERSION="0\.44\.4"/); + assert.match(tooling, /INFISICAL_CLI_SHA256_arm64=/); + assert.match(tooling, /INFISICAL_CLI_SHA256_x86_64=/); + assert.doesNotMatch(tooling, /mint_token|universal-auth|INFISICAL_CLIENT_ID|INFISICAL_CLIENT_SECRET/); const installCall = tooling.indexOf('install_tooling || install_rc=$?'); const consumerCall = tooling.indexOf('node "$repo_root/scripts/stage-asc-key.mjs"'); assert.notEqual(installCall, -1, 'the release has to call the install'); @@ -148,17 +152,25 @@ test('Sparkle reads the ASC credentials through the fleet reader, never reposito // reads, and the staging script owns the folder inside it. assert.match(loader, /Load and stage the ASC credentials \(Fleet-OPS prod \/asc\)/); assert.match(stage, /SECRET_FOLDER = '\/asc'/); - assert.match(loader, /INFISICAL_CLIENT_ID: \$\{\{ secrets\.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID \|\| secrets\.INFISICAL_CLIENT_ID \}\}/); - assert.match(loader, /INFISICAL_CLIENT_SECRET: \$\{\{ secrets\.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET \|\| secrets\.INFISICAL_CLIENT_SECRET \}\}/); - // The bare Infisical CLI is gone: it prints the value to stdout, and its - // only install path is macOS-only. + assert.match(loader, /INFISICAL_PROJECT_ID: \$\{\{ secrets\.INFISICAL_FLEET_OPS_PROJECT_ID \}\}/); + assert.match(loader, /INFISICAL_SERVICE_TOKEN: \$\{\{ secrets\.INFISICAL_CODECAPS_CI_READ_SERVICE_TOKEN \}\}/); + const action = read('.github/actions/infisical-secrets/action.yml'); + assert.match(action, /service-token:/); + assert.match(action, /INFISICAL_SERVICE_TOKEN: \$\{\{ inputs\.service-token \}\}/); + assert.doesNotMatch(action, /client-id:|client-secret:|universal-auth|INFISICAL_CLIENT_ID|INFISICAL_CLIENT_SECRET/); + assert.match(read('scripts/cursor-cloud-start.sh'), /INFISICAL_CODECAPS_PROD_ROOT_READ_SERVICE_TOKEN/); + assert.match(read('scripts/cursor-cloud-start.sh'), /authorization:\s*"Bearer "\s*\+\s*token/); + assert.doesNotMatch(read('scripts/cursor-cloud-start.sh'), /universal-auth|INFISICAL_CLIENT_ID|INFISICAL_CLIENT_SECRET/); + assert.doesNotMatch(loader, /INFISICAL_CLIENT_ID|INFISICAL_CLIENT_SECRET|UNIVERSAL_AUTH/); + // Workflows never call the CLI to print secret values. The pinned CLI is + // installed only as the backend required by the fleet-secrets reader. for (const file of [workflow, iosShip]) { assert.doesNotMatch(file, /infisical secrets get/); assert.doesNotMatch(file, /infisical\/get-cli/); } assert.match(tooling, /stage-asc-key\.mjs/); - assert.match(loader, /Missing \$name in Fleet-OPS prod \/asc; verify the CI identity has read access to Fleet-OPS prod \/asc\./); - assert.match(loader, /Missing ASC key material in Fleet-OPS prod \/asc; verify the CI identity has read access to Fleet-OPS prod \/asc\./); + assert.match(loader, /Missing \$name in Fleet-OPS prod \/asc; verify the scoped \/asc read service token has access to Fleet-OPS prod \/asc\./); + assert.match(loader, /Missing ASC key material in Fleet-OPS prod \/asc; verify the scoped \/asc read service token has access to Fleet-OPS prod \/asc\./); assert.match(code, /NOTARY_KEY_PATH: \$\{\{ env.ASC_KEY_PATH \}\}/); assert.match(code, /NOTARY_KEY_ID: \$\{\{ env.ASC_KEY_ID \}\}/); assert.match(code, /NOTARY_ISSUER_ID: \$\{\{ env.ASC_ISSUER_ID \}\}/); From 9e0ea5af5df3a5e58f0b8fa51fc2d4ebe296f43f Mon Sep 17 00:00:00 2001 From: "swu-codex[bot]" <344783151+swu-codex[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:53:40 +0000 Subject: [PATCH 12/12] Preserve Automatic ZCode Sign-In And Finish Reset And Widget Corrections --- Sources/CodeCaps/SettingsViews.swift | 2 +- .../QuotaCore/LocalQuotaReaderRegistry.swift | 2 +- Sources/QuotaCore/ResetAlarmTracker.swift | 6 +- Sources/QuotaCore/ZCodeQuotaReader.swift | 556 +++++++++++++++++- Tests/CodeCapsTests/WidgetTests.swift | 25 +- .../ResetAlarmPlanChangeTests.swift | 42 +- .../ResetAlarmTrackerTests.swift | 4 +- .../ZCodeQuotaReaderTests.swift | 422 ++++++++++++- .../Widgets/WidgetPresentation.swift | 2 +- scripts/stage-asc-key.node-test.mjs | 172 +++--- 10 files changed, 1121 insertions(+), 112 deletions(-) diff --git a/Sources/CodeCaps/SettingsViews.swift b/Sources/CodeCaps/SettingsViews.swift index aad5f007..b6cd61a0 100644 --- a/Sources/CodeCaps/SettingsViews.swift +++ b/Sources/CodeCaps/SettingsViews.swift @@ -462,7 +462,7 @@ struct SettingsSourcesFleetPage: View { } footer: { VStack(alignment: .leading, spacing: 4) { Text("Most provider quotas use each CLI's existing local sign-in." + sentenceGap - + "Z.ai Coding Plan quota reads use the API key you save here.") + + "Z.ai Coding Plan quota reads use your ZCode sign-in, or the regional API key you save here.") Text("Provider Checks use existing local sign-ins and provider quota endpoints." + sentenceGap + "Copilot uses your existing GitHub CLI sign-in.") Text("Codex Session File Checks: 1 local quota source." + sentenceGap diff --git a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift index 41231999..0c7ae183 100644 --- a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift +++ b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift @@ -79,7 +79,7 @@ public struct LocalQuotaReaderRegistry: Sendable { /// allows future providers without a dynamic code loader. public static let builtIn = configured(zCodeCredentialProvider: { nil }) - /// The optional Z.ai factory resolves its own saved key only when selected. + /// 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 { diff --git a/Sources/QuotaCore/ResetAlarmTracker.swift b/Sources/QuotaCore/ResetAlarmTracker.swift index bbc36136..c601e20f 100644 --- a/Sources/QuotaCore/ResetAlarmTracker.swift +++ b/Sources/QuotaCore/ResetAlarmTracker.swift @@ -496,8 +496,7 @@ public struct ResetAlarmTracker: Sendable { : max(ResetAlarmPolicy.resetDriftTolerance, window.periodSeconds.map { $0 * ResetAlarmPolicy.earlyResetShareOfPeriod } ?? ResetAlarmPolicy.earlyResetUnknownPeriod) - // A provider that resets early may move the reset time by less - // than `required`; the percentage jumping back up settles it. + // A correction is not proof of restored quota when a readable percentage stays flat or falls; allow an unmeasured scheduled rollover only after the old end passes. var climbed = false if let reading, let last = window.lastRemaining { climbed = reading >= last + ResetAlarmPolicy.earlyResetRiseMargin @@ -505,7 +504,8 @@ public struct ResetAlarmTracker: Sendable { let rose = reading.flatMap { current in window.lastRemaining.map { current > $0 + ResetAlarmPolicy.riseEpsilon } } ?? false - if (jump > required && (hasPassed || rose)) + let resetHasQuotaEvidence = rose || (hasPassed && reading == nil) + if (jump > required && resetHasQuotaEvidence) || (jump > ResetAlarmPolicy.resetDriftTolerance && climbed) { isReset = true // When the window had *not* reached its own scheduled end, diff --git a/Sources/QuotaCore/ZCodeQuotaReader.swift b/Sources/QuotaCore/ZCodeQuotaReader.swift index c0fa5812..c3b610be 100644 --- a/Sources/QuotaCore/ZCodeQuotaReader.swift +++ b/Sources/QuotaCore/ZCodeQuotaReader.swift @@ -1,3 +1,4 @@ +import CryptoKit import Foundation /// One explicitly supplied Coding Plan key and its inseparable regional endpoint. @@ -29,9 +30,540 @@ public struct ZCodeQuotaCredential: Codable, Equatable, Sendable { } } + +/// Reads the GLM Coding Plan quota behind the local ZCode sign-in. +/// +/// ZCode keeps its OAuth business tokens in `~/.zcode/v2/credentials.json`, +/// each value sealed as `enc:v1:..` with AES-256-GCM +/// under a key derived from a per-machine, non-secret fallback string +/// (ZCode's own `credentialCipherProvider.ts`: SHA-256 of +/// `zcode-credential-fallback:darwin::`, overridable through +/// `ZCODE_CREDENTIAL_SECRET`). Decrypted values never leave this type; when +/// the store cannot be read or opened the reader says so and publishes +/// nothing. +/// +/// The monitor endpoint does NOT take the raw business token: ZCode's own +/// usage pipeline (`project-access-token-client.ts` + +/// `accountProviderCredentialService.ts`, whose comment states the material +/// is a request-time token that never touches the long-term key cache) +/// exchanges it for a short-lived project token and calls +/// `/api/monitor/usage/quota/limit` with `Bearer `. This +/// reader mirrors that chain: +/// +/// 1. `GET /api/biz/customer/getCustomerInfo` to select the personal +/// organization/project (projects whose `projectType` is not `2`, +/// preferring 默认机构 / 默认项目); +/// 2. `GET /api/biz/v1/organization/{org}/projects/{proj}/api_keys` to +/// find the existing `zcode-api-key` entry — LIST ONLY, a missing key +/// is reported as an issue, never created; +/// 3. `POST {api_keys}/{apiKeyId}/access_tokens` to mint the request-time +/// token — the same sign-in material ZCode itself requests on every +/// refresh, not a persistent account change; +/// 4. `GET /api/monitor/usage/quota/limit` with `Bearer `. +/// +/// Version tolerance: no public 3.16.x source exists, so the contract is +/// grounded on the v3.15.1..v3.17.1 upstream bracket. Every step is +/// byte-stable across the bracket EXCEPT customerInfo's z.ai authorization +/// (Bearer in 3.15.1, raw in 3.17.1, whose comment says a Bearer rejection +/// there would be misread as login invalidation). That one call is tried +/// raw first and retried with `Bearer` only on an HTTP 401/403 — never on a +/// transport or payload failure. Only ZCode's own origins are contacted. +public struct ZCodeQuotaReader: Sendable { + private let credential: @Sendable () async -> ZCodeQuotaCredential? + private let now: @Sendable () -> Date + private let credentials: @Sendable () -> [String: String] + private let zcodeClientVersion: @Sendable () -> String? + private let fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + + private static let maxResponseBytes = 262_144 + private static let maxCredentialBytes = 1_048_576 + private static let timeout: TimeInterval = 15 + + public init( + homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser, + now: @escaping @Sendable () -> Date = { Date() }, + credential: (@Sendable () async -> ZCodeQuotaCredential?)? = nil, + credentials: (@Sendable () -> [String: String])? = nil, + zcodeClientVersion: (@Sendable () -> String?)? = nil, + fetch: (@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse))? = nil + ) { + self.credential = credential ?? { nil } + self.now = now + let home = homeDirectory.standardizedFileURL + self.credentials = credentials ?? { Self.readLocalCredentials(home: home) } + self.zcodeClientVersion = zcodeClientVersion ?? { Self.installedZCodeVersion() } + self.fetch = fetch ?? Self.makeFetcher() + } + + private enum Family { + case zai + case bigmodel + } + + private struct Account { + let family: Family + let loginKey: String + let origin: String + } + + private static let accounts: [Account] = [ + // z.ai first: the desktop sign-in is a Z.ai account; the BigModel + // token is the China-side equivalent of the same plan. + Account(family: .zai, loginKey: "oauth:zai:access_token", origin: "https://api.z.ai"), + Account(family: .bigmodel, loginKey: "oauth:bigmodel:access_token", origin: "https://bigmodel.cn"), + ] + + /// Chain failures that map to honest account issues instead of the + /// generic unavailable/rejected wording. + private enum Flow: Error { + /// 401/403 anywhere in the chain: the sign-in itself is rejected. + case rejected + /// Transport failure, non-success envelope, or malformed payload. + case unavailable + /// A truthful account state to publish (no project, no key, disabled). + case account(String) + } + + public func read() async -> LocalQuotaResult { + if let supplied = await credential() { + return await ExplicitZCodeQuotaReader(now: now, credential: { supplied }, fetch: fetch).read() + } + do { + try Task.checkCancellation() + let store = credentials() + var sawCredential = false + var rejected = false + var firstAccountIssue: String? + for account in Self.accounts { + guard let login = store[account.loginKey], Self.validToken(login) else { continue } + sawCredential = true + do { + return try await readAccount(account, login: login) + } catch is CancellationError { + // Cooperative cancellation is not a transport failure; + // rethrow so the outer catch reports the cancellation. + throw CancellationError() + } catch let flow as Flow { + switch flow { + case .rejected: + rejected = true + case .account(let message): + if firstAccountIssue == nil { firstAccountIssue = message } + case .unavailable: + break + } + } catch { + // One unreachable endpoint must not mask a healthy second + // account. + } + } + if !sawCredential { + // No ZCode sign-in on this Mac: the product is absent, not broken. + return LocalQuotaResult() + } + if let firstAccountIssue { + return LocalQuotaResult(issues: ["zcode": firstAccountIssue]) + } + if rejected { + return LocalQuotaResult(issues: ["zcode": "ZCode session was rejected; sign in again in ZCode."]) + } + return LocalQuotaResult(issues: ["zcode": "ZCode quota service is unavailable."]) + } catch is CancellationError { + return LocalQuotaResult(issues: ["zcode": "ZCode quota refresh was cancelled."]) + } catch { + return LocalQuotaResult(issues: ["zcode": "ZCode quota service is unavailable."]) + } + } + + private func readAccount(_ account: Account, login: String) async throws -> LocalQuotaResult { + let (organizationId, projectId) = try await selectProject(account, login: login) + let keyId = try await codingPlanKeyId(account, login: login, organizationId: organizationId, projectId: projectId) + let token = try await mintProjectToken(account, login: login, organizationId: organizationId, projectId: projectId, keyId: keyId) + return try await quota(account, token: token) + } + + /// Step 1: the personal organization/project, per ZCode's own selection: + /// non-team projects (`projectType` other than "2"), preferring the + /// default-named organization and project, else the first of each. + private func selectProject(_ account: Account, login: String) async throws -> (String, String) { + let url = URL(string: "\(account.origin)/api/biz/customer/getCustomerInfo")! + // The single bracket-unstable header: raw first, `Bearer` only after + // an HTTP auth rejection, and never for the bigmodel family. + // The retry trigger is deliberately HTTP-only: ZCode's own client + // treats a non-success envelope as an invalid response, not an auth + // signal, so a 200 with a failed envelope never swaps the header form. + let forms = account.family == .zai ? [login, "Bearer \(login)"] : [login] + for (index, header) in forms.enumerated() { + let payload = try await request("GET", url: url, authorization: header) + if payload.statusCode == 401 || payload.statusCode == 403 { + if index + 1 < forms.count { continue } + throw Flow.rejected + } + guard (200..<300).contains(payload.statusCode), + let data = Self.envelopeData(payload.root) as? [String: Any], + let organizations = data["organizations"] as? [[String: Any]] else { + throw Flow.unavailable + } + // ZCode's own selection, kept exact: non-team projects, the + // default-named organization/project when present, else first. + let personal: [(id: String, name: String?, projects: [[String: Any]])] = organizations.compactMap { org in + guard let organizationId = org["organizationId"] as? String, !organizationId.isEmpty else { return nil } + let projects = (org["projects"] as? [[String: Any]] ?? []).filter { project in + if let type = project["projectType"] as? String { return type != "2" } + if let type = project["projectType"] as? NSNumber { return type.intValue != 2 } + return true + } + guard !projects.isEmpty else { return nil } + return (organizationId, org["organizationName"] as? String, projects) + } + let org = personal.first(where: { $0.name?.contains("默认机构") == true }) ?? personal.first + let project = org.flatMap { candidate in + candidate.projects.first(where: { ($0["projectName"] as? String)?.contains("默认项目") == true }) ?? candidate.projects.first + } + guard let organizationId = org?.id, + let projectId = project?["projectId"] as? String, !projectId.isEmpty else { + throw Flow.account("ZCode sign-in has no selectable personal project.") + } + return (organizationId, projectId) + } + // Unreachable (every iteration returns or throws) but required: the + // compiler cannot prove the loop never completes normally. + throw Flow.rejected + } + + /// Step 2: the existing `zcode-api-key` entry's id. LIST ONLY: ZCode + /// creates the key here when absent, and this reader deliberately does + /// not — an absent key is an account issue, not a mutation to perform. + private func codingPlanKeyId(_ account: Account, login: String, organizationId: String, projectId: String) async throws -> String { + let base = "\(account.origin)/api/biz/v1/organization/\(Self.pathEscape(organizationId))/projects/\(Self.pathEscape(projectId))/api_keys" + let url = URL(string: base)! + // Personal key management keeps the family-dependent form across the + // whole bracket: z.ai Bearer, bigmodel raw. + let header = account.family == .zai ? "Bearer \(login)" : login + let payload = try await request("GET", url: url, authorization: header) + if payload.statusCode == 401 || payload.statusCode == 403 { throw Flow.rejected } + guard (200..<300).contains(payload.statusCode), + let list = Self.envelopeData(payload.root) as? [[String: Any]] else { + throw Flow.unavailable + } + for entry in list where entry["name"] as? String == "zcode-api-key" { + if let id = entry["apiKey"] as? String, !id.isEmpty { + return id + } + } + throw Flow.account("ZCode account has no coding-plan API key yet; open ZCode once to finish the coding-plan setup.") + } + + /// Step 3: mint the request-time project token. `Bearer` for both + /// families, stable across the bracket. An envelope 404 means the key + /// vanished; `enable: false` means the account disabled the token. The + /// minted token is short-lived sign-in material (the payload carries its + /// own expiry), the same call ZCode's monitor makes every refresh. + private func mintProjectToken(_ account: Account, login: String, organizationId: String, projectId: String, keyId: String) async throws -> String { + let base = "\(account.origin)/api/biz/v1/organization/\(Self.pathEscape(organizationId))/projects/\(Self.pathEscape(projectId))/api_keys" + let url = URL(string: "\(base)/\(Self.pathEscape(keyId))/access_tokens")! + var body: [String: Any] = ["clientType": "zcode"] + if let version = zcodeClientVersion() { body["clientVersion"] = version } + let payload = try await request("POST", url: url, authorization: "Bearer \(login)", body: body) + if payload.statusCode == 401 || payload.statusCode == 403 { throw Flow.rejected } + guard (200..<300).contains(payload.statusCode), let root = payload.root else { throw Flow.unavailable } + if (root["code"] as? NSNumber)?.intValue == 404 || (root["code"] as? String) == "404" { + throw Flow.account("ZCode's coding-plan key no longer exists; sign in again in ZCode.") + } + guard let data = Self.envelopeData(root) as? [String: Any] else { throw Flow.unavailable } + guard let enable = data["enable"] as? NSNumber else { throw Flow.unavailable } + guard enable.boolValue else { throw Flow.account("ZCode reports the coding-plan token disabled.") } + guard let token = data["accessToken"] as? String, Self.validToken(token) else { throw Flow.unavailable } + return token + } + + /// Step 4: the quota read, always `Bearer ` — the one + /// credential form the bracket agrees on for this endpoint. + private func quota(_ account: Account, token: String) async throws -> LocalQuotaResult { + let url = URL(string: "\(account.origin)/api/monitor/usage/quota/limit")! + let payload = try await request("GET", url: url, authorization: "Bearer \(token)") + if payload.statusCode == 401 || payload.statusCode == 403 { throw Flow.rejected } + guard (200..<300).contains(payload.statusCode), let root = payload.root else { throw Flow.unavailable } + // Account truths are thrown, not returned: read() records the issue + // and still tries the second account, which may be healthy. + if let noPlan = Self.noPlanMessage(root) { + throw Flow.account(noPlan) + } + guard Self.envelopeSucceeded(root), let data = root["data"] as? [String: Any] else { throw Flow.unavailable } + let windows = Self.parse(data, observedAt: now()) + if windows.isEmpty { + // A 200 envelope with an empty limits array is a truthful + // account state (no quota windows on this plan), not a + // parse failure; say so instead of claiming unreadability. + let rawLimits = data["limits"] as? [[String: Any]] + // Only an observed empty array is the truthful empty + // state; a missing or mistyped limits value is unreadable. + let message = (rawLimits?.isEmpty == true) + ? "ZCode returned no quota windows for this account." + : "ZCode returned no readable quota." + throw Flow.account(message) + } + let issues = windows.allSatisfy { $0.remainingPercent == nil } + ? ["zcode": "ZCode returned no readable quota."] + : [:] + return LocalQuotaResult(windows: windows, issues: issues) + } + + private func request( + _ method: String, + url: URL, + authorization: String, + body: [String: Any]? = nil + ) async throws -> ZCodeHTTPPayload { + var request = URLRequest(url: url) + request.httpMethod = method + request.cachePolicy = .reloadIgnoringLocalCacheData + request.timeoutInterval = Self.timeout + request.setValue(authorization, forHTTPHeaderField: "authorization") + request.setValue("application/json", forHTTPHeaderField: "Accept") + if let body, let encoded = try? JSONSerialization.data(withJSONObject: body) { + request.httpBody = encoded + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + let (data, response) = try await fetch(request) + let root = data.count <= Self.maxResponseBytes + ? (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + : nil + return ZCodeHTTPPayload(statusCode: response.statusCode, root: root) + } +} + +private struct ZCodeHTTPPayload { + let statusCode: Int + let root: [String: Any]? +} + +private extension ZCodeQuotaReader { + /// The success envelope ZCode's management and mint endpoints share: + /// `code` 0 or 200, as a number or a string (`project-access-token-response.ts`). + static func envelopeData(_ root: [String: Any]?) -> Any? { + guard let root else { return nil } + let code: Int? + if let number = root["code"] as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() { + code = number.intValue + } else if let text = root["code"] as? String { + code = Int(text) + } else { + code = nil + } + guard code == 0 || code == 200 else { return nil } + return root["data"] + } + + /// `encodeURIComponent` semantics for ids inside a path: everything + /// outside the unreserved set is escaped. + static func pathEscape(_ value: String) -> String { + value.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")) ?? value + } + + /// The installed ZCode app's own version, for the mint body's + /// `clientVersion`; omitted when the app cannot be read. + static func installedZCodeVersion() -> String? { + let plist = URL(fileURLWithPath: "/Applications/ZCode.app/Contents/Info.plist") + guard let data = try? Data(contentsOf: plist), + let root = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], + let version = root["CFBundleShortVersionString"] as? String, + !version.isEmpty, version.utf8.count <= 40, + version.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.union(CharacterSet(charactersIn: ".-")).contains) else { return nil } + return version + } + + /// Success per ZCode's own envelope check: `success` not explicitly false + /// and `code` absent, 0, or 200. + static func envelopeSucceeded(_ root: [String: Any]) -> Bool { + if let success = root["success"] as? Bool, !success { return false } + guard let code = (root["code"] as? NSNumber)?.intValue else { return true } + return code == 0 || code == 200 + } + + static func noPlanMessage(_ root: [String: Any]) -> String? { + let message = (root["msg"] as? String) ?? (root["message"] as? String) ?? "" + if message.contains("不存在coding plan") || message.contains("没有资格") { + return "No GLM Coding Plan is active on this ZCode account." + } + return nil + } + + /// Maps `data.limits[]` onto windows. Type semantics from ZCode's own + /// presentation layer (`codingPlanQuotaPresentation.ts`): TOKENS_LIMIT + /// (BigModel) and CREDIT_LIMIT (z.ai) are the same token buckets — + /// `unit: 3` is the rolling five-hour window, `unit: 6` the weekly one — + /// and TIME_LIMIT is the monthly tool-call quota. `percentage` is the + /// USED share; CodeCaps rows show what remains. + static func parse(_ data: [String: Any], observedAt: Date) -> [QuotaWindow] { + let observed = ISO8601DateFormatter().string(from: observedAt) + let plan = (data["level"] as? String).flatMap { level -> String? in + guard !level.isEmpty, level.utf8.count <= 40, + level.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.union(CharacterSet(charactersIn: " _+-")).contains) else { return nil } + let normalized = level.prefix(1).uppercased() + level.dropFirst().lowercased() + return "GLM Coding \(normalized)" + } + guard let limits = data["limits"] as? [[String: Any]] else { return [] } + var windows: [QuotaWindow] = [] + for limit in limits { + guard let type = limit["type"] as? String, !type.isEmpty else { continue } + let unit = (limit["unit"] as? NSNumber)?.intValue + let descriptor = descriptor(type: type, unit: unit) + let percentage = number(limit["percentage"]) + let remaining = number(limit["remaining"]) + // currentValue is the CONSUMED amount and number is the window + // length; the cap only exists when the payload names a remaining + // figure, as remaining + used. + let used = number(limit["currentValue"]) + let cap: Double? = remaining.flatMap { r in used.map { r + $0 } } + let percent: Double? + if let percentage { + percent = min(100, max(0, 100 - percentage)) + } else if let remaining, let cap, cap > 0 { + percent = min(100, max(0, remaining / cap * 100)) + } else { + percent = nil + } + let exhausted = percent == 0 + windows.append(QuotaWindow( + id: "local-mac:zcode:\(type.lowercased())-\(unit.map(String.init) ?? "x")", + provider: "ZCode", providerKey: "zcode", providerLabel: "ZCode", + sourceApp: "local-mac", label: descriptor.label, + remainingPercent: percent, + absoluteRemaining: remaining, absoluteLimit: cap, + quotaUnit: descriptor.unitLabel, + planName: plan, + remainingUnknown: percent == nil, + isExhausted: exhausted, + resetAt: resetTimestamp(limit["nextResetTime"]), + window: descriptor.window, + status: QuotaWindowStatus.derived(remainingPercent: percent), + skip: exhausted, skipReason: exhausted ? "quota exhausted" : nil, + occurredAt: observed, source: "zcode" + )) + } + return windows + } + + static func descriptor(type: String, unit: Int?) -> (label: String, window: String, unitLabel: String) { + if type == "TIME_LIMIT" { + return ("MCP tool calls", "monthly", "calls") + } + let unitLabel = type == "CREDIT_LIMIT" ? "credits" : "tokens" + switch unit { + case 3: return ("5-hour limit", "5h", unitLabel) + case 6: return ("Weekly limit", "weekly", unitLabel) + default: return ("Usage limit", "unspecified", unitLabel) + } + } + + static func resetTimestamp(_ value: Any?) -> String? { + guard let milliseconds = number(value), milliseconds > 0 else { return nil } + return ISO8601DateFormatter().string(from: Date(timeIntervalSince1970: milliseconds / 1000)) + } + + // MARK: - Local credential store + + /// Decrypts the values of `~/.zcode/v2/credentials.json`. Any entry that + /// fails to open is dropped rather than failing the whole store, and a + /// store that yields no usable values reads as "not signed in". + static func readLocalCredentials(home: URL) -> [String: String] { + let environment = ProcessInfo.processInfo.environment + let base = environment["ZCODE_DATA_BASE_DIR"].map { URL(fileURLWithPath: $0) } ?? home + let file = base.appendingPathComponent(".zcode/v2/credentials.json") + guard let data = try? Data(contentsOf: file, options: .mappedIfSafe), + data.count <= Self.maxCredentialBytes, + let raw = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { + return [:] + } + let secret = environment["ZCODE_CREDENTIAL_SECRET"] + ?? "zcode-credential-fallback:darwin:\(home.path):\(NSUserName())" + let key = SymmetricKey(data: Data(SHA256.hash(data: Data(secret.utf8)))) + var store: [String: String] = [:] + for (name, value) in raw { + guard let text = value as? String else { continue } + if let opened = decrypt(text, key: key) { + store[name] = opened + } else if !text.hasPrefix("enc:v1:"), validToken(text) { + store[name] = text + } + } + return store + } + + /// Opens one `enc:v1:..` value (AES-256-GCM, 12-byte + /// nonce, 16-byte tag; base64url segments, in ZCode's own order). + static func decrypt(_ value: String, key: SymmetricKey) -> String? { + let prefix = "enc:v1:" + guard value.hasPrefix(prefix) else { return nil } + let parts = value.dropFirst(prefix.count).split(separator: ".", omittingEmptySubsequences: false) + guard parts.count == 3, + let nonceData = base64url(parts[0]), nonceData.count == 12, + let tagData = base64url(parts[1]), tagData.count == 16, + let ciphertext = base64url(parts[2]), !ciphertext.isEmpty, + let nonce = try? AES.GCM.Nonce(data: nonceData), + let box = try? AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tagData), + let opened = try? AES.GCM.open(box, using: key) else { + return nil + } + return String(data: opened, encoding: .utf8) + } + + static func base64url(_ text: Substring) -> Data? { + var base64 = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4) + return Data(base64Encoded: base64) + } + + static func validToken(_ token: String) -> Bool { + !token.isEmpty && token.utf8.count <= 8_192 && !token.contains("\r") && !token.contains("\n") + } + + static func makeFetcher() -> @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) { + return { request in + let config = URLSessionConfiguration.ephemeral + config.httpCookieStorage = nil + config.urlCache = nil + config.requestCachePolicy = .reloadIgnoringLocalCacheData + config.timeoutIntervalForRequest = Self.timeout + config.timeoutIntervalForResource = Self.timeout + let session = URLSession(configuration: config, delegate: ZCodeNoRedirectDelegate(), delegateQueue: nil) + defer { session.invalidateAndCancel() } + let (bytes, response) = try await session.bytes(for: request) + guard let http = response as? HTTPURLResponse else { throw ZCodeQuotaError.unavailable } + if let length = http.value(forHTTPHeaderField: "Content-Length"), let count = Int(length), count > Self.maxResponseBytes { + throw ZCodeQuotaError.unavailable + } + var data = Data() + data.reserveCapacity(16_384) + for try await byte in bytes { + guard data.count < Self.maxResponseBytes else { throw ZCodeQuotaError.unavailable } + data.append(byte) + } + return (data, http) + } + } + + static func number(_ value: Any?) -> Double? { + guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), + number.doubleValue.isFinite, number.doubleValue >= 0 else { return nil } + return number.doubleValue + } +} + +private enum ZCodeQuotaError: Error { + case unavailable +} + +private final class ZCodeNoRedirectDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { + completionHandler(nil) + } +} + /// Reads quota only with an explicitly supplied Coding Plan API key. /// ZCode's OAuth business tokens are not quota credentials and are never read here. -public struct ZCodeQuotaReader: Sendable { +private struct ExplicitZCodeQuotaReader: Sendable { private let now: @Sendable () -> Date private let credential: @Sendable () async -> ZCodeQuotaCredential? private let fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) @@ -88,17 +620,17 @@ public struct ZCodeQuotaReader: Sendable { } } -private struct ZCodeHTTPPayload { +private struct ExplicitZCodeHTTPPayload { let statusCode: Int let root: [String: Any]? } -private extension ZCodeQuotaReader { +private extension ExplicitZCodeQuotaReader { static func fetchQuota( url: URL, token: String, fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) - ) async throws -> ZCodeHTTPPayload { + ) async throws -> ExplicitZCodeHTTPPayload { // The monitor contract takes the credential verbatim. Community // readers disagree and prepend `Bearer`, so a bare-credential 401 is // retried once with the prefix before the session is called rejected. @@ -116,9 +648,9 @@ private extension ZCodeQuotaReader { let root = data.count <= Self.maxResponseBytes ? (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] : nil - return ZCodeHTTPPayload(statusCode: response.statusCode, root: root) + return ExplicitZCodeHTTPPayload(statusCode: response.statusCode, root: root) } - return ZCodeHTTPPayload(statusCode: 401, root: nil) + return ExplicitZCodeHTTPPayload(statusCode: 401, root: nil) } /// Success per ZCode's own envelope check: `success` not explicitly false @@ -218,17 +750,17 @@ private extension ZCodeQuotaReader { config.requestCachePolicy = .reloadIgnoringLocalCacheData config.timeoutIntervalForRequest = Self.timeout config.timeoutIntervalForResource = Self.timeout - let session = URLSession(configuration: config, delegate: ZCodeNoRedirectDelegate(), delegateQueue: nil) + let session = URLSession(configuration: config, delegate: ExplicitZCodeNoRedirectDelegate(), delegateQueue: nil) defer { session.invalidateAndCancel() } let (bytes, response) = try await session.bytes(for: request) - guard let http = response as? HTTPURLResponse else { throw ZCodeQuotaError.unavailable } + guard let http = response as? HTTPURLResponse else { throw ExplicitZCodeQuotaError.unavailable } if let length = http.value(forHTTPHeaderField: "Content-Length"), let count = Int(length), count > Self.maxResponseBytes { - throw ZCodeQuotaError.unavailable + throw ExplicitZCodeQuotaError.unavailable } var data = Data() data.reserveCapacity(16_384) for try await byte in bytes { - guard data.count < Self.maxResponseBytes else { throw ZCodeQuotaError.unavailable } + guard data.count < Self.maxResponseBytes else { throw ExplicitZCodeQuotaError.unavailable } data.append(byte) } return (data, http) @@ -242,11 +774,11 @@ private extension ZCodeQuotaReader { } } -private enum ZCodeQuotaError: Error { +private enum ExplicitZCodeQuotaError: Error { case unavailable } -private final class ZCodeNoRedirectDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable { +private final class ExplicitZCodeNoRedirectDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable { func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } diff --git a/Tests/CodeCapsTests/WidgetTests.swift b/Tests/CodeCapsTests/WidgetTests.swift index 32b06f96..b949216c 100644 --- a/Tests/CodeCapsTests/WidgetTests.swift +++ b/Tests/CodeCapsTests/WidgetTests.swift @@ -179,7 +179,7 @@ final class WidgetTests: XCTestCase { func testWidgetDropsACopyOfAPeriodThatEnded() throws { let source = try readSource(at: Self.widgetPresentationURL) XCTAssertTrue( - source.contains("QuotaFreshnessRule.isDeadCopy(observedAt: parseDate(from: w.occurredAt),"), + source.contains("QuotaFreshnessRule.isDeadCopy(observedAt: parseDate(from: w.reportedAt) ?? parseDate(from: w.occurredAt),"), "the widget must ask the shared rule about a window whose period already ended" ) XCTAssertFalse( @@ -240,13 +240,24 @@ final class WidgetTests: XCTestCase { /// how the plan looked when the reading was taken. func testWidgetOnlyLetsAFreshWindowCapAPlan() throws { let source = try readSource(at: Self.widgetPresentationURL) + let atCapMethod = source + .components(separatedBy: "public func atCapWindow(now: Date = Date()) -> WidgetWindowItem? {") + .dropFirst() + .first? + .components(separatedBy: "\n }") + .first ?? "" + XCTAssertFalse(atCapMethod.isEmpty, "the widget must decide caps through its window selector") XCTAssertTrue( - source.contains(".filter { $0.isFresh(now: now) }"), + atCapMethod.contains(".filter { $0.isFresh(now: now) }"), "the widget's cap window must be chosen from the fresh windows" ) XCTAssertTrue( - source.contains("let atCap = freshWindows.first {"), - "the widget's cap line must be decided from the fresh windows" + atCapMethod.contains(".filter { !$0.isMasked && $0.remainingPercent != nil }"), + "masked and unknown windows must not cap a plan" + ) + XCTAssertTrue( + atCapMethod.contains(".filter { WidgetPresentation.isAtCap(percent: $0.remainingPercent, isExhausted: $0.isExhausted) }"), + "the widget must use the shared cap rule after freshness filtering" ) } @@ -297,7 +308,11 @@ final class WidgetTests: XCTestCase { "the widget's weekly must be decided through the shared rule, and only a fresh reading may spend it" ) XCTAssertTrue( - source.contains("let isExhausted = weeklyExhausted || QuotaCapRule.isAtCap(remainingPercent: freshPercents.min())"), + source.contains("let fresh = primary.filter { $0.isFresh(now: now) && !$0.isMasked }"), + "only fresh, unmasked readings may contribute to the pool cap" + ) + XCTAssertTrue( + source.contains("let isExhausted = weeklyExhausted || QuotaCapRule.isAtCap(remainingPercent: fresh.compactMap(\\.remainingPercent).min())"), "a spent weekly must spend the pool even when the five-hour window still reports headroom, " + "and only a fresh reading may spend it" ) diff --git a/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift b/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift index 5763b4b0..b4acae15 100644 --- a/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift +++ b/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift @@ -194,24 +194,56 @@ final class ResetAlarmPlanChangeTests: XCTestCase { func testAMidCycleEventThatFellIsNeitherARefillNorAPlanChange() { var tracker = ResetAlarmTracker() let weekEnd = t0 + 7 * self.day - _ = tracker.process(weekly(at: t0, resetAt: weekEnd, remaining: 90), now: t0) + _ = tracker.process(weekly(at: t0, resetAt: weekEnd, remaining: 74), now: t0) - // The reported end jumps forward by more than half the period, which is - // how the tracker sees a period that ended early, and the quota falls. + // The saved MiniMax alerts held at 74%, then fell to 73% while the reported end moved forward. let later = t0 + 2 * self.hour - let events = tracker.process(weekly(at: later, resetAt: t0 + 11 * self.day, remaining: 40), now: later) + let events = tracker.process(weekly(at: later, resetAt: t0 + 11 * self.day, remaining: 73), now: later) XCTAssertTrue(events.isEmpty, "a future-end correction with falling quota is not a reset") // Adopt the corrected end, then still report its actual scheduled rollover. let scheduled = t0 + 11 * self.day + 60 let rollover = tracker.process(weekly(at: scheduled, resetAt: scheduled + 7 * self.day, - remaining: 35), now: scheduled) + remaining: 100), now: scheduled) XCTAssertEqual(rollover.map(\.windowId), ["7d"]) + XCTAssertEqual(rollover.first?.reason, .newPeriod) + XCTAssertEqual(rollover.first?.endedPeriodResetAt, t0 + 11 * self.day) XCTAssertFalse(rollover.first?.isVendorReset ?? true) XCTAssertFalse(rollover.first?.isPlanChange ?? true) } + /// The live MiniMax history recorded a stale 9:00 AM deadline, then a correction to Nov 8 at 6:00 PM with the weekly balance unchanged at 73%. + func testPassedMiniMaxDeadlineCorrectionWithUnchangedQuotaDoesNotAlertAndValidRolloverDoes() { + var tracker = ResetAlarmTracker() + func minimax(at observedAt: Date, resetAt: Date, remaining: Double) -> ResetAlarmObservation { + ResetAlarmObservation(scope: "local", providerId: "minimax", providerTitle: "MiniMax", + windowId: "local-mac:minimax:general:weekly", windowLabel: "7d", periodSeconds: 7 * day, + resetAt: resetAt, remainingPercent: remaining, observedAt: observedAt) + } + + let firstRead = t0 + let staleDeadline = firstRead + 25 * 60 + _ = tracker.process([minimax(at: firstRead, resetAt: staleDeadline, remaining: 73)], now: firstRead) + + let correctedRead = firstRead + 32 * 60 + let correctedDeadline = staleDeadline + 5 * day + 9 * hour + let correction = tracker.process( + [minimax(at: correctedRead, resetAt: correctedDeadline, remaining: 73)], now: correctedRead) + + XCTAssertTrue(correction.isEmpty, "a passed stale deadline corrected forward without quota restoration is not a new week") + let key = ResetAlarmTracker.windowKey(scope: "local", providerId: "minimax", windowId: "local-mac:minimax:general:weekly") + XCTAssertEqual(tracker.state.windows[key]?.periodResetAt, correctedDeadline) + XCTAssertEqual(tracker.state.windows[key]?.lastRemaining, 73) + + let scheduled = correctedDeadline + 60 + let rollover = tracker.process( + [minimax(at: scheduled, resetAt: scheduled + 7 * day, remaining: 100)], now: scheduled) + XCTAssertEqual(rollover.map(\.windowId), ["local-mac:minimax:general:weekly"]) + XCTAssertEqual(rollover.first?.reason, .newPeriod) + XCTAssertEqual(rollover.first?.endedPeriodResetAt, correctedDeadline) + } + // MARK: The words func testAPlanChangeIsAnnouncedUnderItsOwnName() { diff --git a/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift b/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift index 1bf60635..0a8bf466 100644 --- a/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift +++ b/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift @@ -476,10 +476,10 @@ final class ResetAlarmTrackerTests: XCTestCase { let scheduledAt = weeklyEnd + hour let scheduled = tracker.process( - [reading("general", period: 7 * day, resetAt: weeklyEnd + 7 * day, remaining: 70, + [reading("general", period: 7 * day, resetAt: weeklyEnd + 7 * day, remaining: 100, observedAt: scheduledAt, provider: "minimax", label: "7d")], now: scheduledAt) - XCTAssertEqual(scheduled.map(\.reason), [.newPeriod], "A later weekly rollover remains a scheduled reset even if usage fell.") + XCTAssertEqual(scheduled.map(\.reason), [.newPeriod], "A later weekly rollover with quota restored remains a scheduled reset.") } func testPreEndResetTimeCorrectionWithoutQuotaRiseIsNotAnAlarm() { diff --git a/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift b/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift index a863a2a9..7f7b380a 100644 --- a/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift +++ b/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift @@ -2,7 +2,413 @@ import Foundation import XCTest @testable import QuotaCore +/// The reader walks ZCode's own project-token chain before the quota call, +/// so every stub routes by request path and can record what was sent. final class ZCodeQuotaReaderTests: XCTestCase { + private final class Recorder: @unchecked Sendable { + private let lock = NSLock() + private var seen: [URLRequest] = [] + func add(_ request: URLRequest) { lock.lock(); seen.append(request); lock.unlock() } + func snapshot() -> [URLRequest] { lock.lock(); defer { lock.unlock() }; return seen } + } + + private let customerJSON = #"{"code":200,"data":{"organizations":[{"organizationId":"o1","organizationName":"默认机构","projects":[{"projectId":"p1","projectName":"默认项目","projectType":1}]}]}}"# + private let keysJSON = #"{"code":200,"data":[{"name":"zcode-api-key","apiKey":"key-id-1"}]}"# + private let mintJSON = #"{"code":200,"data":{"enable":true,"accessToken":"proj-tok","expiresAt":9999999999,"expiresIn":3600}}"# + + private struct Stub { + var quotaJSON: String + var quotaStatus: Int = 200 + var customerJSON: String? + var customerStatus: Int = 200 + var keysJSON: String? + var keysStatus: Int = 200 + var mintJSON: String? + var mintStatus: Int = 200 + } + + private func read( + _ stub: Stub, + store: [String: String]? = ["oauth:zai:access_token": "tok"], + recorder: Recorder? = nil + ) async -> LocalQuotaResult { + let customer = customerJSON + let keys = keysJSON + let mint = mintJSON + return await ZCodeQuotaReader( + now: { Date(timeIntervalSince1970: 0) }, + credentials: { store ?? [:] }, + zcodeClientVersion: { "3.16.3" }, + fetch: { request in + recorder?.add(request) + let path = request.url?.path ?? "" + let body: String + let status: Int + if path.hasSuffix("/api/biz/customer/getCustomerInfo") { + body = stub.customerJSON ?? customer + status = stub.customerStatus + } else if path.hasSuffix("/access_tokens") { + body = stub.mintJSON ?? mint + status = stub.mintStatus + } else if path.contains("/api_keys") { + body = stub.keysJSON ?? keys + status = stub.keysStatus + } else { + body = stub.quotaJSON + status = stub.quotaStatus + } + let response = HTTPURLResponse( + url: request.url!, + statusCode: status, httpVersion: nil, headerFields: nil + )! + return (Data(body.utf8), response) + } + ).read() + } + + // MARK: - Chain contract + + func testChainSendsTheContractCredentials() async { + let recorder = Recorder() + let result = await read(Stub(quotaJSON: #"{"code":200,"data":{"level":"pro","limits":[{"type":"CREDIT_LIMIT","unit":3,"percentage":40,"currentValue":1000,"remaining":600}]}}"#), recorder: recorder) + XCTAssertEqual(result.windows.count, 1) + let requests = recorder.snapshot() + XCTAssertEqual(requests.count, 4, "customerInfo, key list, mint, quota - in that order") + XCTAssertTrue(requests[0].url!.path.hasSuffix("/api/biz/customer/getCustomerInfo")) + XCTAssertEqual(requests[0].value(forHTTPHeaderField: "authorization"), "tok", "customerInfo is tried with the raw login token first") + XCTAssertEqual(requests[1].url!.path, "/api/biz/v1/organization/o1/projects/p1/api_keys") + XCTAssertEqual(requests[1].httpMethod, "GET") + XCTAssertEqual(requests[1].value(forHTTPHeaderField: "authorization"), "Bearer tok", "personal key management keeps the z.ai Bearer form") + XCTAssertTrue(requests[2].url!.path.hasSuffix("/api_keys/key-id-1/access_tokens")) + XCTAssertEqual(requests[2].httpMethod, "POST") + XCTAssertEqual(requests[2].value(forHTTPHeaderField: "authorization"), "Bearer tok", "the mint is Bearer for both families") + let mintBody = (try? JSONSerialization.jsonObject(with: requests[2].httpBody ?? Data())) as? [String: Any] + XCTAssertEqual(mintBody?["clientType"] as? String, "zcode") + XCTAssertEqual(mintBody?["clientVersion"] as? String, "3.16.3") + XCTAssertEqual(requests[3].url!.path, "/api/monitor/usage/quota/limit") + XCTAssertEqual(requests[3].value(forHTTPHeaderField: "authorization"), "Bearer proj-tok", "the quota call presents the minted project token, never the raw login token") + } + + private final class AnswerBox: @unchecked Sendable { + private let lock = NSLock() + private var answers: [(Int, String)] + init(_ answers: [(Int, String)]) { self.answers = answers } + func next(fallback: (Int, String)) -> (Int, String) { + lock.lock(); defer { lock.unlock() } + return answers.isEmpty ? fallback : answers.removeFirst() + } + } + + func testCustomerInfoRetriesBearerOnlyAfterAnAuthRejection() async { + let recorder = Recorder() + let customer = customerJSON + let keys = keysJSON + let mint = mintJSON + let answers = AnswerBox([(401, "{}"), (200, customer)]) + let result = await ZCodeQuotaReader( + now: { Date(timeIntervalSince1970: 0) }, + credentials: { ["oauth:zai:access_token": "tok"] }, + zcodeClientVersion: { "3.16.3" }, + fetch: { request in + recorder.add(request) + let path = request.url?.path ?? "" + var body = "" + var status = 200 + if path.hasSuffix("/api/biz/customer/getCustomerInfo") { + let answer = answers.next(fallback: (200, customer)) + status = answer.0 + body = answer.1 + } else if path.hasSuffix("/access_tokens") { + body = mint + } else if path.contains("/api_keys") { + body = keys + } else { + body = #"{"code":200,"data":{"limits":[{"type":"CREDIT_LIMIT","unit":3,"percentage":10,"remaining":900,"currentValue":100}]}}"# + } + let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)! + return (Data(body.utf8), response) + } + ).read() + XCTAssertEqual(result.windows.count, 1) + let headers = recorder.snapshot() + .filter { $0.url!.path.hasSuffix("/api/biz/customer/getCustomerInfo") } + .map { $0.value(forHTTPHeaderField: "authorization") } + XCTAssertEqual(headers, ["tok", "Bearer tok"], "raw first, Bearer only after the HTTP 401") + } + + func testCustomerInfoRejectedOnBothFormsMeansSignInAgain() async { + let result = await read(Stub(quotaJSON: "{}", customerStatus: 401)) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["zcode"], "ZCode session was rejected; sign in again in ZCode.") + } + + func testBigmodelChainUsesRawKeyListAuthAndNoFallback() async { + let recorder = Recorder() + let result = await read( + Stub(quotaJSON: #"{"code":200,"data":{"level":"max","limits":[{"type":"TOKENS_LIMIT","unit":6,"percentage":5}]}}"#), + store: ["oauth:bigmodel:access_token": "bm-tok"], + recorder: recorder + ) + XCTAssertEqual(result.windows.count, 1) + let requests = recorder.snapshot() + XCTAssertEqual(requests.count, 4, "no Bearer retry for bigmodel: the bracket agrees on raw customerInfo there") + XCTAssertEqual(requests[0].url!.host, "bigmodel.cn") + XCTAssertEqual(requests[0].value(forHTTPHeaderField: "authorization"), "bm-tok") + XCTAssertEqual(requests[1].value(forHTTPHeaderField: "authorization"), "bm-tok", "bigmodel key management is the raw token") + XCTAssertEqual(requests[2].value(forHTTPHeaderField: "authorization"), "Bearer bm-tok") + XCTAssertEqual(requests[3].value(forHTTPHeaderField: "authorization"), "Bearer proj-tok") + } + + // MARK: - Honest account issues (never a mutation) + + func testMissingNamedKeyIsAnIssueAndNeverCreates() async { + let recorder = Recorder() + let result = await read(Stub(quotaJSON: "{}", keysJSON: #"{"code":200,"data":[{"name":"other-key","apiKey":"k2"}]}"#), recorder: recorder) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["zcode"], "ZCode account has no coding-plan API key yet; open ZCode once to finish the coding-plan setup.") + let creations = recorder.snapshot().filter { $0.url!.path.hasSuffix("/api_keys") && $0.httpMethod == "POST" } + XCTAssertTrue(creations.isEmpty, "the reader lists keys only; it never creates one") + } + + func testDisabledTokenIsAnIssue() async { + let result = await read(Stub(quotaJSON: "{}", mintJSON: #"{"code":200,"data":{"enable":false}}"#)) + XCTAssertEqual(result.issues["zcode"], "ZCode reports the coding-plan token disabled.") + } + + func testMintKeyGoneIsAnIssue() async { + let result = await read(Stub(quotaJSON: "{}", mintJSON: #"{"code":404,"msg":"gone"}"#)) + XCTAssertEqual(result.issues["zcode"], "ZCode's coding-plan key no longer exists; sign in again in ZCode.") + } + + func testNoPersonalProjectIsAnIssue() async { + let teams = #"{"code":200,"data":{"organizations":[{"organizationId":"o9","organizationName":"团队","projects":[{"projectId":"p9","projectName":"团队项目","projectType":2}]}]}}"# + let result = await read(Stub(quotaJSON: "{}", customerJSON: teams)) + XCTAssertEqual(result.issues["zcode"], "ZCode sign-in has no selectable personal project.") + } + + func testQuotaRejectedAfterMintMeansSignInAgain() async { + let result = await read(Stub(quotaJSON: "{}", quotaStatus: 401)) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["zcode"], "ZCode session was rejected; sign in again in ZCode.") + } + + func testChainAccountIssueFallsThroughToAHealthySecondAccount() async { + let customer = customerJSON + let keys = keysJSON + let mint = mintJSON + let result = await ZCodeQuotaReader( + now: { Date(timeIntervalSince1970: 0) }, + credentials: { ["oauth:zai:access_token": "tok", "oauth:bigmodel:access_token": "bm-tok"] }, + zcodeClientVersion: { "3.16.3" }, + fetch: { request in + let host = request.url?.host ?? "" + let path = request.url?.path ?? "" + let body: String + if path.hasSuffix("/api/biz/customer/getCustomerInfo") { + body = host == "api.z.ai" + ? #"{"code":200,"data":{"organizations":[]}}"# + : customer + } else if path.hasSuffix("/access_tokens") { + body = mint + } else if path.contains("/api_keys") { + body = keys + } else { + body = #"{"code":200,"data":{"level":"max","limits":[{"type":"TOKENS_LIMIT","unit":6,"percentage":5}]}}"# + } + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return (Data(body.utf8), response) + } + ).read() + XCTAssertEqual(result.windows.count, 1, "a broken z.ai chain must not mask a working bigmodel account") + XCTAssertEqual(result.windows[0].quotaUnit, "tokens") + } + + func testNoPlanFallsThroughToAHealthySecondAccount() async { + let customer = customerJSON + let keys = keysJSON + let mint = mintJSON + let result = await ZCodeQuotaReader( + now: { Date(timeIntervalSince1970: 0) }, + credentials: { ["oauth:zai:access_token": "tok", "oauth:bigmodel:access_token": "bm-tok"] }, + zcodeClientVersion: { "3.16.3" }, + fetch: { request in + let host = request.url?.host ?? "" + let path = request.url?.path ?? "" + let body: String + if path.hasSuffix("/api/biz/customer/getCustomerInfo") { + body = customer + } else if path.hasSuffix("/access_tokens") { + body = mint + } else if path.contains("/api_keys") { + body = keys + } else { + body = host == "api.z.ai" + ? #"{"code":500,"msg":"当前用户不存在coding plan"}"# + : #"{"code":200,"data":{"level":"max","limits":[{"type":"TOKENS_LIMIT","unit":6,"percentage":5}]}}"# + } + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return (Data(body.utf8), response) + } + ).read() + XCTAssertEqual(result.windows.count, 1, "z.ai's no-plan answer must not mask bigmodel's quota") + XCTAssertEqual(result.windows[0].quotaUnit, "tokens") + } + + func testEnvelopeAuthFailureOnRawAttemptNeverSwapsTheHeader() async { + // ZCode's client treats a non-success envelope as an invalid response, + // not an auth signal: only HTTP 401/403 triggers the Bearer retry. + let recorder = Recorder() + let result = await read( + Stub(quotaJSON: "{}", customerJSON: #"{"code":401,"msg":"unauthorized"}"#), + recorder: recorder + ) + XCTAssertEqual(result.issues["zcode"], "ZCode quota service is unavailable.") + let customerCalls = recorder.snapshot().filter { $0.url!.path.hasSuffix("/api/biz/customer/getCustomerInfo") } + XCTAssertEqual(customerCalls.count, 1, "an envelope-level failure is not an auth rejection: no Bearer retry") + } + + // MARK: - Quota payload mapping (unchanged contract) + + func testCreditLimitsBecomeFiveHourAndWeeklyWindows() async { + let result = await read(Stub(quotaJSON: #"{"code":200,"msg":"ok","data":{"level":"pro","limits":[{"type":"CREDIT_LIMIT","unit":3,"number":5,"percentage":40,"currentValue":1000,"remaining":600,"nextResetTime":1762531200000},{"type":"CREDIT_LIMIT","unit":6,"percentage":90,"currentValue":5000,"remaining":500}]}}"#)) + XCTAssertTrue(result.issues.isEmpty) + XCTAssertEqual(result.windows.count, 2) + let fiveHour = result.windows[0] + XCTAssertEqual(fiveHour.providerKey, "zcode") + XCTAssertEqual(fiveHour.providerLabel, "ZCode") + XCTAssertEqual(fiveHour.label, "5-hour limit") + XCTAssertEqual(fiveHour.window, "5h") + // percentage is the USED share; the row shows what remains. + XCTAssertEqual(fiveHour.remainingPercent, 60) + XCTAssertEqual(fiveHour.absoluteRemaining, 600) + // The cap is remaining + consumed; currentValue alone is usage. + XCTAssertEqual(fiveHour.absoluteLimit, 1600) + XCTAssertEqual(fiveHour.quotaUnit, "credits") + XCTAssertEqual(fiveHour.planName, "GLM Coding Pro") + XCTAssertNotNil(fiveHour.resetAt) + let weekly = result.windows[1] + XCTAssertEqual(weekly.label, "Weekly limit") + XCTAssertEqual(weekly.window, "weekly") + XCTAssertEqual(weekly.remainingPercent, 10) + XCTAssertEqual(weekly.status, .nearCap) + } + + func testTimeLimitIsTheMonthlyToolQuota() async { + let result = await read(Stub(quotaJSON: #"{"code":0,"data":{"level":"lite","limits":[{"type":"TIME_LIMIT","unit":5,"percentage":100}]}}"#)) + let window = result.windows[0] + XCTAssertEqual(window.label, "MCP tool calls") + XCTAssertEqual(window.window, "monthly") + XCTAssertEqual(window.quotaUnit, "calls") + XCTAssertEqual(window.remainingPercent, 0) + XCTAssertTrue(window.isExhausted) + XCTAssertTrue(window.skip) + } + + func testMissingCredentialIsSilent() async { + let result = await read(Stub(quotaJSON: "{}"), store: nil) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertTrue(result.issues.isEmpty) + } + + func testNoPlanMessageIsAnIssue() async { + let result = await read(Stub(quotaJSON: #"{"code":500,"msg":"当前用户不存在coding plan"}"#)) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["zcode"], "No GLM Coding Plan is active on this ZCode account.") + } + + func testEmptyLimitsReportNoWindowsForAccount() async { + // Live-verified account state: a signed-in account whose plan exposes + // no quota windows answers 200 with an empty limits array. That must + // read as an empty account, never as "unavailable" or a full quota. + let result = await read(Stub(quotaJSON: #"{"code":200,"data":{"limits":[]}}"#)) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["zcode"], "ZCode returned no quota windows for this account.") + } + + func testUnparseableLimitsReportNoReadableQuota() async { + let result = await read(Stub(quotaJSON: #"{"code":200,"data":{"limits":[{"unit":6}]}}"#)) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["zcode"], "ZCode returned no readable quota.") + } + + func testMissingLimitsKeyReportsNoReadableQuota() async { + // A 200 envelope whose data omits limits (or mistypes it) is a + // malformed payload, not a truthful empty account. + let missing = await read(Stub(quotaJSON: #"{"code":200,"data":{}}"#)) + XCTAssertTrue(missing.windows.isEmpty) + XCTAssertEqual(missing.issues["zcode"], "ZCode returned no readable quota.") + let mistyped = await read(Stub(quotaJSON: #"{"code":200,"data":{"limits":"none"}}"#)) + XCTAssertTrue(mistyped.windows.isEmpty) + XCTAssertEqual(mistyped.issues["zcode"], "ZCode returned no readable quota.") + } + + func testCancellationIsNotReportedAsTransportFailure() async { + let result = await ZCodeQuotaReader( + now: { Date(timeIntervalSince1970: 0) }, + credentials: { ["oauth:zai:access_token": "tok"] }, + fetch: { _ in throw CancellationError() } + ).read() + XCTAssertEqual(result.issues["zcode"], "ZCode quota refresh was cancelled.") + } + + func testRejectedSessionIsAnIssue() async { + let result = await read(Stub(quotaJSON: "{}", quotaStatus: 401)) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["zcode"], "ZCode session was rejected; sign in again in ZCode.") + } + + func testEnvelopeFailureWithoutDataIsUnavailable() async { + let result = await read(Stub(quotaJSON: #"{"code":500,"msg":"boom"}"#)) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["zcode"], "ZCode quota service is unavailable.") + } + + func testTransportErrorFallsThroughToSecondCredential() async { + let customer = customerJSON + let keys = keysJSON + let mint = mintJSON + let result = await ZCodeQuotaReader( + now: { Date(timeIntervalSince1970: 0) }, + credentials: { ["oauth:zai:access_token": "tok", "oauth:bigmodel:access_token": "bm-tok"] }, + zcodeClientVersion: { "3.16.3" }, + fetch: { request in + if request.url?.host == "api.z.ai" { throw URLError(.notConnectedToInternet) } + let path = request.url?.path ?? "" + let body: String + if path.hasSuffix("/api/biz/customer/getCustomerInfo") { + body = customer + } else if path.hasSuffix("/access_tokens") { + body = mint + } else if path.contains("/api_keys") { + body = keys + } else { + body = #"{"code":200,"data":{"level":"max","limits":[{"type":"TOKENS_LIMIT","unit":6,"percentage":5}]}}"# + } + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return (Data(body.utf8), response) + } + ).read() + XCTAssertTrue(result.issues.isEmpty) + XCTAssertEqual(result.windows.count, 1) + XCTAssertEqual(result.windows[0].quotaUnit, "tokens") + } + + func testFallsBackToBigModelCredential() async { + let result = await read( + Stub(quotaJSON: #"{"code":200,"data":{"level":"max","limits":[{"type":"TOKENS_LIMIT","unit":6,"percentage":5}]}}"#), + store: ["oauth:bigmodel:access_token": "bm-tok"] + ) + XCTAssertEqual(result.windows.count, 1) + XCTAssertEqual(result.windows[0].quotaUnit, "tokens") + XCTAssertEqual(result.windows[0].planName, "GLM Coding Max") + } +} + +import Foundation +import XCTest +@testable import QuotaCore + +final class ExplicitZCodeQuotaReaderTests: XCTestCase { private func read( _ json: String, status: Int = 200, @@ -11,6 +417,10 @@ final class ZCodeQuotaReaderTests: XCTestCase { await ZCodeQuotaReader( now: { Date(timeIntervalSince1970: 0) }, credential: { credential }, + credentials: { + if credential != nil { XCTFail("An explicit credential must not read the local OAuth store") } + return [:] + }, fetch: { request in XCTAssertEqual(request.url, credential?.region.quotaURL) let authorization = request.value(forHTTPHeaderField: "authorization") @@ -61,10 +471,10 @@ final class ZCodeQuotaReaderTests: XCTestCase { XCTAssertTrue(window.skip) } - func testMissingCredentialReportsSetupNeededWithoutFetching() async { + func testAbsentExplicitAndLocalCredentialsStaySilentWithoutFetching() async { let result = await read("{}", credential: nil) XCTAssertTrue(result.windows.isEmpty) - XCTAssertTrue(result.issues["zcode"]?.contains("setup is needed") == true) + XCTAssertTrue(result.issues.isEmpty) } func testNoPlanMessageIsAnIssue() async { @@ -156,13 +566,13 @@ final class ZCodeQuotaReaderTests: XCTestCase { XCTAssertEqual(count, 1) } - func testDefaultReaderNeedsExplicitSetupAndNeverAttemptsOAuthOrQuotaCalls() async { - let result = await ZCodeQuotaReader(fetch: { _ in - XCTFail("No explicit Coding Plan key means no request") + func testNoSavedKeyAndNoLocalSignInNeverAttemptQuotaCalls() async { + let result = await ZCodeQuotaReader(credentials: { [:] }, fetch: { _ in + XCTFail("No saved key or local sign-in means no request") throw URLError(.badURL) }).read() XCTAssertTrue(result.windows.isEmpty) - XCTAssertTrue(result.issues["zcode"]?.contains("setup is needed") == true) + XCTAssertTrue(result.issues.isEmpty) } func testInvalidSavedKeyCannotReachTransport() async { diff --git a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift index 87c2854e..ae75ccdc 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift @@ -293,7 +293,7 @@ public struct WidgetPlatformItem: Identifiable, Equatable, Sendable { /// Oct-22-2026). public func atCapWindow(now: Date = Date()) -> WidgetWindowItem? { primaryWindows - .filter { $0.isFresh(now: now) || (WidgetPresentation.isAtCap(percent: $0.remainingPercent, isExhausted: $0.isExhausted) && $0.resetAt != nil && $0.resetAt! > now) } + .filter { $0.isFresh(now: now) } .filter { !$0.isMasked && $0.remainingPercent != nil } .filter { WidgetPresentation.isAtCap(percent: $0.remainingPercent, isExhausted: $0.isExhausted) } .min { ($0.resetAt ?? .distantFuture) < ($1.resetAt ?? .distantFuture) } diff --git a/scripts/stage-asc-key.node-test.mjs b/scripts/stage-asc-key.node-test.mjs index a098c431..0186974b 100644 --- a/scripts/stage-asc-key.node-test.mjs +++ b/scripts/stage-asc-key.node-test.mjs @@ -7,11 +7,11 @@ // approved fallback, so the test stubs that fallback -- the injected getter // -- rather than a network endpoint. Nothing here reaches the vault. // -// Every fixture is synthetic. The private key in these tests is a marker -// string, not a credential. +// Every private key fixture is generated at runtime from an ephemeral P-256 keypair. // // Run: node --test scripts/stage-asc-key.node-test.mjs import assert from 'node:assert/strict'; +import { generateKeyPairSync } from 'node:crypto'; import { spawn, spawnSync } from 'node:child_process'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -21,10 +21,19 @@ import { fileURLToPath } from 'node:url'; import { run, UNRESOLVED_REFERENCE } from './stage-asc-key.mjs'; -// A synthetic fixture, not a credential. It stands in for the private key -// so the test can tell a leak from a clean run. -const KEY_MARKER = 'SYNTHETIC-MULTILINE-FIXTURE-DO-NOT-USE'; -const KEY = `-----BEGIN PRIVATE KEY-----\n${KEY_MARKER}\n-----END PRIVATE KEY-----`; // gitleaks:allow +// Keep the fixture structurally valid while never storing PEM material in the repository. +function generateTestKey() { + return generateKeyPairSync('ec', { + namedCurve: 'prime256v1', + privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, + publicKeyEncoding: { type: 'spki', format: 'pem' }, + }).privateKey; +} + +const KEY = generateTestKey(); +const KEY_MARKER = KEY.split(/\r?\n/)[1]; +const ENVIRONMENT_KEY = generateTestKey(); +const ENVIRONMENT_KEY_MARKER = ENVIRONMENT_KEY.split(/\r?\n/)[1]; const VAULT = { ASC_KEY_ID: 'STUBKEYID', ASC_ISSUER_ID: 'STUBISSUER', @@ -104,7 +113,10 @@ function importEnvironmentFile(path) { * key-bearing entry, and a later step is handed no key. */ function assertNoKeySurvives(envPath) { const written = readFileSync(envPath, 'utf8'); - assert.ok(!written.includes(KEY_MARKER), 'the key bytes must not survive in the environment file'); + assert.ok( + ![KEY, KEY_MARKER, ENVIRONMENT_KEY, ENVIRONMENT_KEY_MARKER].some((fixture) => written.includes(fixture)), + 'private key bytes must not survive in the environment file', + ); assert.doesNotMatch(written, /ASC_KEY_P8/, 'the ASC_KEY_P8 entry must be removed, not blanked'); const imported = importEnvironmentFile(envPath); assert.ok(!('ASC_KEY_P8' in imported), 'a later step must not be handed the key'); @@ -383,17 +395,18 @@ test('the environment is looked up first, before the approved fallback', async ( const env = baseEnv(dir, { ASC_KEY_ID: 'ENVKEYID', ASC_ISSUER_ID: 'ENVISSUER', - ASC_KEY_P8: `-----BEGIN PRIVATE KEY-----\nENVIRONMENT-COPY\n-----END PRIVATE KEY-----`, // gitleaks:allow + ASC_KEY_P8: ENVIRONMENT_KEY, }); const getter = stubGetter(); await run({ env, getSecret: getter, log: () => {} }); assert.deepEqual(getter.calls, [], 'the fallback must not be consulted when the environment has the name'); const written = readFileSync(env.GITHUB_ENV, 'utf8'); + assertNoKeySurvives(env.GITHUB_ENV); assert.match(written, /ENVKEYID/); assert.match(written, /ENVISSUER/); const keyPath = written.match(/^ASC_KEY_PATH=(.*)$/m)[1].trim(); - assert.ok(readFileSync(keyPath, 'utf8').includes('ENVIRONMENT-COPY'), 'the environment copy is the one that is staged'); + assert.ok(readFileSync(keyPath, 'utf8').includes(ENVIRONMENT_KEY_MARKER), 'the environment copy is the one that is staged'); } finally { rmSync(dir, { recursive: true, force: true }); } @@ -572,8 +585,7 @@ test('an installer failure still runs the consumer and clears the key', async () GITHUB_ENV: envFile, ASC_STAGING_ROOT: staging, INFISICAL_PROJECT_ID: 'test-project-id', - INFISICAL_CLIENT_ID: 'test-client-id', - INFISICAL_CLIENT_SECRET: 'test-client-secret', + INFISICAL_SERVICE_TOKEN: 'st.test-id.test-secret', }; // Nothing from the shell that runs the suite may stand in for the // credentials or the token the failed install never produced. @@ -617,23 +629,23 @@ test('a broken reader is reported as a reader fault, not as a missing credential ...process.env, HOME: home, PATH: '/usr/bin:/bin', - INFISICAL_TOKEN: 'test-token', - INFISICAL_FLEET_OPS_PROJECT_ID: '11111111-2222-3333-4444-555555555555', + INFISICAL_SERVICE_TOKEN: 'st.test-id.test-secret', + INFISICAL_PROJECT_ID: '11111111-2222-3333-4444-555555555555', }; // A reader that cannot authenticate: the token is at fault, and the // message has to say so instead of blaming the vault permissions. // The reader's own text is passed through for the diagnosis, so the // stub repeats the token in it: the token must not reach the log. - const rejected = writeStubReader(dir, 4, 'fleet-secrets: fetch-failed: exit-1 for test-token'); + const rejected = writeStubReader(dir, 4, 'fleet-secrets: fetch-failed: exit-1 for st.test-id.test-secret'); const rejectedResult = await runScript(script, { env: { ...base, FLEET_SECRETS: rejected }, args: ['check-reader'] }); assert.notEqual(rejectedResult.code, 0, 'a reader that cannot authenticate must fail the check'); - assert.match(rejectedResult.stderr, /access token was rejected/, 'the message must name the token'); + assert.match(rejectedResult.stderr, /service token was rejected/, 'the message must name the token'); assert.doesNotMatch(rejectedResult.stderr, /Missing ASC_KEY_ID/, 'a reader fault must not read as a missing credential'); - assert.ok(!rejectedResult.stderr.includes('test-token'), 'the access token must not reach the log'); - assert.ok(!rejectedResult.stdout.includes('test-token'), 'the access token must not reach the log'); - assert.ok(!rejectedResult.stderr.includes('test-tok'), 'no slice of a short access token may reach the log'); - assert.ok(!rejectedResult.stdout.includes('test-tok'), 'no slice of a short access token may reach the log'); + assert.ok(!rejectedResult.stderr.includes('st.test-id.test-secret'), 'the access token must not reach the log'); + assert.ok(!rejectedResult.stdout.includes('st.test-id.test-secret'), 'the access token must not reach the log'); + assert.ok(!rejectedResult.stderr.includes('st.test-id'), 'no slice of a short access token may reach the log'); + assert.ok(!rejectedResult.stdout.includes('st.test-id'), 'no slice of a short access token may reach the log'); assert.match(rejectedResult.stderr, /fetch-failed: exit-1 for /, 'a token too short to have a hidden middle is redacted outright'); // A reader that refuses the request: the tooling is at fault. @@ -677,10 +689,10 @@ test('a broken reader is reported as a reader fault, not as a missing credential // No token in the environment: the reader would fail the way a rejected // token fails, so the absent token is named before the reader is asked. const noToken = { ...base, FLEET_SECRETS: working }; - delete noToken.INFISICAL_TOKEN; + delete noToken.INFISICAL_SERVICE_TOKEN; const noTokenResult = await runScript(script, { env: noToken, args: ['check-reader'] }); assert.notEqual(noTokenResult.code, 0, 'a check without a token must fail'); - assert.match(noTokenResult.stderr, /no Infisical access token in the environment/, 'the message must name the absent token'); + assert.match(noTokenResult.stderr, /read service token is not set/, 'the message must name the absent token'); assert.doesNotMatch(noTokenResult.stderr, /was rejected/, 'an absent token is not a rejected one'); // No reader at all is a tooling fault, and it is named as one. @@ -692,52 +704,65 @@ test('a broken reader is reported as a reader fault, not as a missing credential } }); -/** A literal string for a regular expression. The preview carries an ellipsis - * and angle brackets, neither of which is a metacharacter, but the helper keeps - * a future preview from changing the meaning of the pattern. */ -function escapeRegExp(value) { - return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -} +test('the full scoped service token reaches the fleet reader unchanged', async () => { + const dir = mkdtempSync(join(tmpdir(), 'asc-token-passthrough-')); + try { + const script = fileURLToPath(new URL('install-release-secrets-tooling.sh', import.meta.url)); + const home = join(dir, 'home'); + mkdirSync(home, { recursive: true }); + const capture = join(dir, 'captured-token'); + const reader = join(dir, 'reader'); + const serviceToken = 'st.synthetic-id.secret-value'; + writeFileSync(reader, `#!/bin/bash +printf '%s' "$INFISICAL_TOKEN" > "$TOKEN_CAPTURE_PATH" +printf '%s\n' ASC_KEY_ID ASC_ISSUER_ID ASC_KEY_P8 +`, { mode: 0o755 }); + const result = await runScript(script, { + env: { + ...process.env, + HOME: home, + PATH: '/usr/bin:/bin', + INFISICAL_SERVICE_TOKEN: serviceToken, + INFISICAL_PROJECT_ID: '11111111-2222-3333-4444-555555555555', + TOKEN_CAPTURE_PATH: capture, + FLEET_SECRETS: reader + }, + args: ['check-reader'] + }); + + assert.equal(result.code, 0, 'a reader accepting the supplied token must pass'); + assert.equal(readFileSync(capture, 'utf8'), serviceToken, 'the full `st.` token is passed unchanged'); + assert.ok(!result.stdout.includes(serviceToken), 'the token must not reach stdout'); + assert.ok(!result.stderr.includes(serviceToken), 'the token must not reach stderr'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); -test('a credential is previewed only when the middle of it is really hidden', async () => { +test('scoped service tokens of different lengths are redacted whole', async () => { const script = fileURLToPath(new URL('install-release-secrets-tooling.sh', import.meta.url)); + const bodies = ['x', 'abcdefghijkl', 'abcdefghijklmnopqrstuvwxyz0123']; - // The two slices the preview is built from cover twelve characters between - // them, so a value of twelve characters or fewer is reconstructed in full - // by the two of them together. Thirteen is the first length with a middle - // left over, and it is the boundary the helper has to hold. The hidden - // middle of each case is a string that does not occur in the prose around - // it, so a leak of it is a leak and not a coincidence. - const cases = [ - { token: 'abcdefghij', preview: '', hidden: 'abcdefghij' }, - { token: 'abcdefghijkl', preview: '', hidden: 'abcdefghijkl' }, - { token: 'abcdefghZijkl', preview: 'abcdefgh…ijkl', hidden: 'Z' }, - { token: 'abcdefghijklmnopqrstuvwxyz0123', preview: 'abcdefgh…0123', hidden: 'ijklmnopqrstuvwxyz' } - ]; - - for (const { token, preview, hidden } of cases) { - const dir = mkdtempSync(join(tmpdir(), 'asc-preview-')); + for (const body of bodies) { + const dir = mkdtempSync(join(tmpdir(), 'asc-token-redaction-')); try { const home = join(dir, 'home'); mkdirSync(home, { recursive: true }); + const serviceToken = `st.test-id.${body}`; const base = { ...process.env, HOME: home, PATH: '/usr/bin:/bin', - INFISICAL_TOKEN: token, - INFISICAL_FLEET_OPS_PROJECT_ID: '11111111-2222-3333-4444-555555555555' + INFISICAL_SERVICE_TOKEN: serviceToken, + INFISICAL_PROJECT_ID: '11111111-2222-3333-4444-555555555555' }; - - // The reader repeats the token in its own error text, which is the text - // the failure carries, so the token is in the log unless it is masked. - const rejected = writeStubReader(dir, 4, `fleet-secrets: fetch-failed: exit-1 for ${token}`); + const rejected = writeStubReader(dir, 4, `fleet-secrets: fetch-failed: exit-1 for ${serviceToken}`); const result = await runScript(script, { env: { ...base, FLEET_SECRETS: rejected }, args: ['check-reader'] }); assert.notEqual(result.code, 0, 'a reader that cannot authenticate must fail the check'); - assert.ok(!result.stderr.includes(token), `the access token must not reach the log (${token.length} characters)`); - assert.ok(!result.stdout.includes(token), `the access token must not reach stdout (${token.length} characters)`); - assert.match(result.stderr, new RegExp(`fetch-failed: exit-1 for ${escapeRegExp(preview)}`), `the failure carries the preview of a ${token.length} character token`); - assert.ok(!result.stderr.includes(hidden), `the hidden middle must stay hidden (${token.length} characters)`); + assert.ok(!result.stderr.includes(serviceToken), 'the full service token must not reach stderr'); + assert.ok(!result.stdout.includes(serviceToken), 'the full service token must not reach stdout'); + assert.match(result.stderr, /fetch-failed: exit-1 for /, 'the entire service token is replaced'); } finally { rmSync(dir, { recursive: true, force: true }); } @@ -778,21 +803,21 @@ test('a credential that carries an ampersand is never expanded back into the log // and later an ampersand in it expands to the text that matched, which // here would be the whole credential. The ampersand sits in the first // eight characters, so it is in the part of the value a preview shows. - const token = 'abc&efghijklmnopqrst'; + const token = 'st.test-id.abc&efghijklmnopqrst'; const base = { ...process.env, HOME: home, PATH: '/usr/bin:/bin', - INFISICAL_TOKEN: token, - INFISICAL_FLEET_OPS_PROJECT_ID: '11111111-2222-3333-4444-555555555555' + INFISICAL_SERVICE_TOKEN: token, + INFISICAL_PROJECT_ID: '11111111-2222-3333-4444-555555555555' }; const rejected = writeStubReader(dir, 4, `fleet-secrets: fetch-failed: exit-1 for ${token}`); for (const shell of shells()) { const result = await runScript(script, { env: { ...base, FLEET_SECRETS: rejected }, args: ['check-reader'], shell }); assert.notEqual(result.code, 0, 'a reader that cannot authenticate must fail the check'); - assert.ok(!result.stderr.includes(token), `the access token must not reach the log (${shell})`); - assert.ok(!result.stdout.includes(token), `the access token must not reach stdout (${shell})`); + assert.ok(!result.stderr.includes(token), `the service token must not reach the log (${shell})`); + assert.ok(!result.stdout.includes(token), `the service token must not reach stdout (${shell})`); assert.ok(!result.stderr.includes('&'), `no ampersand may reach the log (${shell})`); } } finally { @@ -800,36 +825,31 @@ test('a credential that carries an ampersand is never expanded back into the log } }); -test('the long lived client credentials are redacted whole', async () => { +test('the scoped service token is redacted whole', async () => { const dir = mkdtempSync(join(tmpdir(), 'asc-client-')); try { const script = fileURLToPath(new URL('install-release-secrets-tooling.sh', import.meta.url)); const home = join(dir, 'home'); mkdirSync(home, { recursive: true }); - // The client id and the client secret stand for months and the runner - // masks them by value, so a preview of either would defeat that masking - // and put twelve characters of a standing credential in a public log. - const clientId = 'client-id-abcdefghijklmnop'; - const clientSecret = 'client-secret-abcdefghijklmnop'; + // The service token is a standing credential, so even a preview of it + // must not reach the Actions log. + const serviceToken = 'st.client-id.secret-abcdefghijklmnop'; const base = { ...process.env, HOME: home, PATH: '/usr/bin:/bin', - INFISICAL_CLIENT_ID: clientId, - INFISICAL_CLIENT_SECRET: clientSecret, - INFISICAL_TOKEN: 'abcdefghijklmnopqrstuvwxyz0123', - INFISICAL_FLEET_OPS_PROJECT_ID: '11111111-2222-3333-4444-555555555555' + INFISICAL_SERVICE_TOKEN: serviceToken, + INFISICAL_PROJECT_ID: 'test-project-id' }; - const rejected = writeStubReader(dir, 4, `fleet-secrets: fetch-failed: exit-1 for ${clientId} and ${clientSecret}`); + const rejected = writeStubReader(dir, 4, `fleet-secrets: fetch-failed: exit-1 for ${serviceToken}`); const result = await runScript(script, { env: { ...base, FLEET_SECRETS: rejected }, args: ['check-reader'] }); assert.notEqual(result.code, 0, 'a reader that cannot authenticate must fail the check'); - assert.ok(!result.stderr.includes(clientId), 'the client id must not reach the log'); - assert.ok(!result.stderr.includes(clientSecret), 'the client secret must not reach the log'); - assert.ok(!result.stderr.includes('client-id-abc'), 'no slice of the client id may reach the log'); - assert.ok(!result.stderr.includes('client-sec'), 'no slice of the client secret may reach the log'); - assert.match(result.stderr, /for /, 'the credentials are redacted whole'); + assert.ok(!result.stderr.includes(serviceToken), 'the service token must not reach the log'); + assert.ok(!result.stderr.includes('st.client-id'), 'no service-token prefix may reach the log'); + assert.ok(!result.stderr.includes('secret-abc'), 'no service-token secret slice may reach the log'); + assert.match(result.stderr, /for /, 'the service token is redacted whole'); } finally { rmSync(dir, { recursive: true, force: true }); } @@ -846,8 +866,8 @@ test('a name the environment carries as whitespace is still required in the vaul ...process.env, HOME: home, PATH: '/usr/bin:/bin', - INFISICAL_TOKEN: 'abcdefghijklmnopqrstuvwxyz0123', - INFISICAL_FLEET_OPS_PROJECT_ID: '11111111-2222-3333-4444-555555555555' + INFISICAL_SERVICE_TOKEN: 'st.test-id.test-secret', + INFISICAL_PROJECT_ID: '11111111-2222-3333-4444-555555555555' }; // The consumer trims a value and refuses one that holds nothing but