diff --git a/.gitleaksignore b/.gitleaksignore index cb75a39b..6b82be56 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -13,3 +13,9 @@ # 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 + +# The copied release-branch history flags the same runtime validation, without a literal credential. +70cd5be758bfe4664ca8fa25e569db40bbf53006:Sources/QuotaCore/TwilioSMSClient.swift:generic-api-key:76 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 3f5c15db..537f2ed0 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 91019d80..8ac38f7b 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 @@ -237,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() } @@ -366,12 +369,56 @@ 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 QuitConfirmationPolicy.windowsToHide(managed: [consoleWindow, floatingGlance]) { + 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 +431,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 ee1850a2..b2d8eba7 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/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 59c323ba..31ac9da5 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 } @@ -559,8 +616,21 @@ 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 + let zAIQuotaSetup: ZAIQuotaSetupController + + /// 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 @@ -584,6 +654,29 @@ 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?)? + var museCodeAlertSynchronizeForTesting: (@MainActor (String) -> Bool)? + 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 @@ -618,6 +711,8 @@ 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? + 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? @@ -707,6 +802,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 @@ -726,8 +822,20 @@ 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) + zAIQuotaSetup = ZAIQuotaSetupController(defaults: defaults) appearance = AppAppearance(rawValue: defaults.string(forKey: "appearance") ?? "") ?? .system glanceView = GlanceViewMode(rawValue: defaults.string(forKey: "glanceView") ?? "") ?? .fromMac @@ -744,6 +852,14 @@ final class MonitorModel: ObservableObject { alarmChanges = alarmManager.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() } + 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) + } tokenChanges = NotificationCenter.default.publisher(for: TokenStore.tokenBecameAvailable) .receive(on: DispatchQueue.main) .sink { [weak self] _ in @@ -1137,6 +1253,40 @@ 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() } + } + + 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) } @@ -1819,6 +1969,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 @@ -2158,7 +2311,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.") @@ -2327,6 +2482,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 @@ -2334,7 +2490,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? @@ -2507,6 +2664,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() @@ -2719,6 +2877,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() @@ -3132,6 +3291,303 @@ 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 { + 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 + // 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. + 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 + } + 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)) + } + } + + /// 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. + private func enqueueMuseCodeBridge(report: MuseCodeSessionReport) { + guard museCodeUsageBridgeEnabled else { return } + if museCodePendingBridgeReport == nil || report.generatedAt >= museCodePendingBridgeReport!.generatedAt { + museCodePendingBridgeReport = report + } + guard museCodeBridgeTask == nil, !museCodeIngestTokenBusy else { return } + let workerGeneration = museCodeBridgeGeneration + museCodeBridgeTask = Task { @MainActor [weak self] in + guard let self else { return } + defer { + self.museCodeBridgeTask = nil + if self.museCodeUsageBridgeEnabled, !self.museCodeIngestTokenBusy, + let pending = self.museCodePendingBridgeReport { + self.enqueueMuseCodeBridge(report: pending) + } + } + while workerGeneration == self.museCodeBridgeGeneration, + self.museCodeUsageBridgeEnabled, !self.museCodeIngestTokenBusy, + let next = self.museCodePendingBridgeReport { + self.museCodePendingBridgeReport = nil + let completed = await self.postMuseCodeBridge(report: next, generation: workerGeneration) + // A credential or enablement change invalidates this worker.  Its defer + // starts a fresh main-actor worker for any newer pending report. + guard workerGeneration == self.museCodeBridgeGeneration else { break } + // Failure waits for a later refresh; it never retries immediately. + if !completed { break } + } + } + } + + 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) @@ -3155,39 +3611,37 @@ 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 { + let registry = LocalQuotaReaderRegistry.configured(zCodeCredentialProvider: { + await ZAIQuotaCredentialStore.shared.load() + }) + async let registered = registry.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) } } @@ -3249,4 +3703,4 @@ extension MonitorModel { windowLabel: alert.windowLabel, summary: alert.summary, occurredAt: alert.occurredAt) } } -} +} \ No newline at end of file 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..63f3001f --- /dev/null +++ b/Sources/CodeCaps/QuitConfirmation.swift @@ -0,0 +1,42 @@ +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 + } +} + +@MainActor +extension QuitConfirmationPolicy { + static func windowsToHide(managed: [NSWindow?]) -> [NSWindow] { + managed.compactMap { $0 }.filter { + $0.styleMask.contains(.titled) && $0.level != .statusBar && $0.level != .popUpMenu + } + } +} diff --git a/Sources/CodeCaps/ResetAlarmManager.swift b/Sources/CodeCaps/ResetAlarmManager.swift index 425474d0..59d66b05 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 @@ -822,6 +824,7 @@ func resetAlarmObservations(for row: DisplaySection, scope: String) -> [ResetAla windowLabel: glanceMeterCaption(snapshot), periodSeconds: quotaWindowPeriodSeconds(snapshot), resetAt: snapshot.resetAt, + periodStartAt: snapshot.window.periodStartDate, remainingPercent: row.isMasked(snapshot) ? nil : snapshot.remainingPercent, observedAt: snapshot.observedAt, identity: snapshot.window.accountKey) diff --git a/Sources/CodeCaps/SMSAlertController.swift b/Sources/CodeCaps/SMSAlertController.swift new file mode 100644 index 00000000..876cc297 --- /dev/null +++ b/Sources/CodeCaps/SMSAlertController.swift @@ -0,0 +1,151 @@ +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 + private var deliveryTasks: [UUID: Task] = [:] + + 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 + let deliveryID = UUID() + let task = Task { @MainActor [weak self] in + guard let self else { return } + defer { self.deliveryTasks.removeValue(forKey: deliveryID) } + guard !Task.isCancelled else { return } + let credentials = await self.credentialAccess.load() + guard !Task.isCancelled, revision == self.setupRevision, + self.preferences[kind], self.hasSavedSetup else { return } + let result = await self.coordinator.send(eventID: eventID, kind: kind, title: title, body: body, + preferences: self.preferences, credentials: credentials) + guard !Task.isCancelled, revision == self.setupRevision else { return } + switch result { + case .accepted: self.status = "Text accepted by Twilio." + case .failed(let failure): self.status = failure.localizedDescription + case .disabled, .duplicate: break + } + } + deliveryTasks[deliveryID] = task + return task + } + + @discardableResult + func saveSetup(configuration: TwilioSMSConfiguration, apiKeySecret: String) async -> Bool { + guard !isWorking else { return false } + isWorking = true + invalidateDeliveries() + 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 + invalidateDeliveries() + 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 + invalidateDeliveries() + 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 invalidateDeliveries() { + setupRevision &+= 1 + let active = Array(deliveryTasks.values) + deliveryTasks.removeAll() + active.forEach { $0.cancel() } + } + + 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 2dfeb0a3..a3549703 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 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 @@ -483,7 +484,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 +500,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.success : 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.success : 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 +956,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 +972,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 +1410,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 +1430,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 { @@ -1735,286 +1758,296 @@ 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) + 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 { + 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) } + } } - .padding(.vertical, 2) + 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) } + } + .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 { - 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("Label", text: $label) + Picker("Authentication", selection: $authentication) { + ForEach(InfisicalBinding.Authentication.allCases, id: \.self) { Text($0.title).tag($0) } + } + .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) - .disabled(working) + 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 { - if hasIdentity { - Button("Forget Setup", role: .destructive, action: forgetIdentity) - } - 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.success : Theme.danger) - .fixedSize(horizontal: false, vertical: true) + Button(editingID == nil ? "Add Binding" : "Save Binding") { saveBinding() } + .disabled(label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } - } 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.") + } 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.") .font(.system(size: 11)) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } - + .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)) } - } + 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)).font(.system(size: 11)) - } - } - if let error = settings.lastError { - Text(error) - .font(.system(size: 11)) - .foregroundStyle(Theme.danger) - .fixedSize(horizontal: false, vertical: true) + LabeledContent("Last Synced") { Text(loaded.formatted(date: .omitted, time: .shortened)) } } - HStack { - Spacer() - Button("Reload Now", action: reloadNow).disabled(working || !hasIdentity) - } - } header: { - Eyebrow("SYNC STATUS") - } - + 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.success : 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.") + 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.") .font(.system(size: 11)) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } } - .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 saveIdentity() { - guard let identity = candidateIdentity else { return } - let operation = beginOperation() + private func remove(_ id: String) { + var candidate = InfisicalIdentityStore.loadSetup() ?? setup + candidate.bindings.removeAll { $0.id == id } + reconcileSelections(&candidate) + apply(candidate) + } + + 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/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/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/AntigravityQuotaGroups.swift b/Sources/QuotaCore/AntigravityQuotaGroups.swift index 5a53991b..9f3414b7 100644 --- a/Sources/QuotaCore/AntigravityQuotaGroups.swift +++ b/Sources/QuotaCore/AntigravityQuotaGroups.swift @@ -233,8 +233,13 @@ public enum AntigravityQuotaGroups { private static func cadence(_ value: QuotaWindow) -> String? { let token = value.window?.lowercased().replacingOccurrences(of: " ", with: "") - if ["weekly", "week", "1w", "7d", "168h", "10080m"].contains(token ?? "") || value.label.lowercased().contains("weekly") { return "weekly" } - if ["5h", "5hr", "5-hour", "5hours", "300m"].contains(token ?? "") { return "5h" } + let label = value.label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let weeklyLabels: Set = ["weekly", "week", "7-day", "7 day", "7-day window", "7 day window"] + let fiveHourLabels: Set = ["5h", "5hr", "5-hour", "5 hours", "5-hour window", "5 hour window", "five_hour"] + if ["weekly", "week", "1w", "7d", "168h", "10080m"].contains(token ?? "") + || weeklyLabels.contains(label) { return "weekly" } + if ["5h", "5hr", "5-hour", "5hours", "300m"].contains(token ?? "") + || fiveHourLabels.contains(label) { return "5h" } // The helper's model quotaInfo is the short pool. A weekly reading // must be explicitly identified; a reset's distance is not a duration. if token == nil && value.sourceApp == "local-mac" && value.modelId != nil { return "5h" } diff --git a/Sources/QuotaCore/CursorQuotaReader.swift b/Sources/QuotaCore/CursorQuotaReader.swift index 89137e23..7f47cdd6 100644 --- a/Sources/QuotaCore/CursorQuotaReader.swift +++ b/Sources/QuotaCore/CursorQuotaReader.swift @@ -33,11 +33,15 @@ public struct CursorQuotaReader: Sendable { guard let cookie = try cursorCookie(for: token, now: now()) else { return LocalQuotaResult(issues: ["cursor": "Cursor local session is not usable; sign in again in Cursor."]) } - let observedAt = now() async let summaryPayload = Self.fetchUsageSummary(cookie: cookie, fetch: fetch) async let periodPayload = Self.fetchCurrentPeriodUsageSafely(token: token, cookie: cookie, fetch: fetch) let summaryResult = try await summaryPayload let periodResult = await periodPayload + // Stamp the quota when both API reads have completed. Capturing + // the clock before the network requests made a slow Cursor read + // look older than a faster xAI alias, allowing the shared pool to + // keep that alias's prior percentage on the Cursor row. + let observedAt = now() if summaryResult.statusCode == 401 || summaryResult.statusCode == 403 { return LocalQuotaResult(issues: ["cursor": "Cursor session was rejected; sign in again in Cursor."]) 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 416a717d..3e21a28b 100644 --- a/Sources/QuotaCore/KimiQuotaReader.swift +++ b/Sources/QuotaCore/KimiQuotaReader.swift @@ -61,6 +61,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) @@ -69,6 +70,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 @@ -192,7 +194,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), @@ -246,17 +248,21 @@ private extension KimiQuotaReader { /// Newest credential JSON under the two documented roots, then the /// `api_key` lines of `config.toml` / `config.json` as a last resort. - internal static func readLocalAccessToken(home: URL) -> String? { - readLocalCredential(home: home)?.token + internal static func readLocalAccessToken( + home: URL, environment: [String: String] = ProcessInfo.processInfo.environment + ) -> String? { + readLocalCredential(home: home, environment: environment)?.token } /// The token plus the expiry the credential records alongside it, so a /// server rejection can be told apart from a locally known expiry. - internal static func readLocalCredential(home: URL) -> (token: String, expiresAt: Date?)? { + internal static func readLocalCredential( + home: URL, environment: [String: String] = ProcessInfo.processInfo.environment + ) -> (token: String, expiresAt: Date?)? { 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 @@ -264,11 +270,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 @@ -314,33 +317,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") { - 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: .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: .whitespacesAndNewlines) + guard tail.isEmpty || tail.hasPrefix("#") else { return nil } + if quote == "'" { return String(value[value.index(after: value.startIndex).. 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 = configured(zCodeCredentialProvider: { nil }) + + /// 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 { + 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/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..078d9fcc --- /dev/null +++ b/Sources/QuotaCore/MuseCodeSessionReader.swift @@ -0,0 +1,419 @@ +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 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 { + 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") } +} + +/// 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 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 + 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) + } + } +} 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 4fbf52fc..be0a0812 100644 --- a/Sources/QuotaCore/ResetAlarmTracker.swift +++ b/Sources/QuotaCore/ResetAlarmTracker.swift @@ -29,6 +29,8 @@ public struct ResetAlarmObservation: Equatable, Sendable { public var periodSeconds: TimeInterval? /// When the current period ends. public var resetAt: Date? + /// When the current period began, when the provider reports it explicitly. + public var periodStartAt: Date? /// Percentage remaining, or `nil` when the reading is unknown or must not /// be believed (an Antigravity five-hour window under a spent weekly cap). public var remainingPercent: Double? @@ -50,6 +52,7 @@ public struct ResetAlarmObservation: Equatable, Sendable { windowLabel: String, periodSeconds: TimeInterval?, resetAt: Date?, + periodStartAt: Date? = nil, remainingPercent: Double?, observedAt: Date?, identity: String? = nil @@ -61,6 +64,7 @@ public struct ResetAlarmObservation: Equatable, Sendable { self.windowLabel = windowLabel self.periodSeconds = periodSeconds self.resetAt = resetAt + self.periodStartAt = periodStartAt self.remainingPercent = remainingPercent self.observedAt = observedAt self.identity = identity @@ -138,6 +142,8 @@ public struct ResetAlarmTrackerState: Codable, Equatable, Sendable { public struct Window: Codable, Equatable, Sendable { /// When the current period ends, as last reported. public var periodResetAt: Date? + /// When the current period began, when the provider reports it explicitly. + public var periodStartAt: Date? /// The lowest percentage remaining observed in the current period. public var minimumRemaining: Double? /// The latest known percentage remaining. @@ -152,6 +158,7 @@ public struct ResetAlarmTrackerState: Codable, Equatable, Sendable { public init( periodResetAt: Date?, + periodStartAt: Date? = nil, minimumRemaining: Double?, lastRemaining: Double?, lastObservedAt: Date?, @@ -160,6 +167,7 @@ public struct ResetAlarmTrackerState: Codable, Equatable, Sendable { identity: String? = nil ) { self.periodResetAt = periodResetAt + self.periodStartAt = periodStartAt self.minimumRemaining = minimumRemaining self.lastRemaining = lastRemaining self.lastObservedAt = lastObservedAt @@ -441,6 +449,7 @@ public struct ResetAlarmTracker: Sendable { func firstReading() -> ResetAlarmTrackerState.Window { .init(periodResetAt: observation.resetAt, + periodStartAt: observation.periodStartAt, minimumRemaining: reading, lastRemaining: reading, lastObservedAt: observedAt, @@ -463,7 +472,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 { @@ -471,6 +479,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 @@ -483,6 +501,33 @@ public struct ResetAlarmTracker: Sendable { let hasPassed = readAt >= previousReset.addingTimeInterval(-60) if let reported = observation.resetAt { let jump = reported.timeIntervalSince(previousReset) + // A deadline correction needs a substantial quota rise or an elapsed full cadence. + let advancedFullCadence = window.periodSeconds.map { period in + // Calendar months range from 28 to 31 days; fixed cadences use drift tolerance. + let tolerance = ResetAlarmPolicy.resetDriftTolerance + if (28 * 86_400...31 * 86_400).contains(period) { + return jump >= 28 * 86_400 - tolerance && jump <= 31 * 86_400 + tolerance + } + return abs(jump - period) <= tolerance + } ?? false + // Some providers publish both sides of the period.  When they + // do, an end-time correction by one cadence is not enough to + // prove a reset: their explicit start must advance too.  This + // prevents MiniMax's corrected weekly deadline from repeatedly + // announcing a new week while its weekly period is unchanged. + let explicitStartConfirmsPeriod = { + guard let current = observation.periodStartAt, + let previous = window.periodStartAt, + let period = window.periodSeconds else { return true } + let advance = current.timeIntervalSince(previous) + let tolerance = ResetAlarmPolicy.resetDriftTolerance + // Same band as advancedFullCadence: a calendar-month window accepts a + // 28-to-31-day start advance; fixed cadences use drift tolerance. + if (28 * 86_400...31 * 86_400).contains(period) { + return advance >= 28 * 86_400 - tolerance && advance <= 31 * 86_400 + tolerance + } + return abs(advance - period) <= tolerance + }() let required = hasPassed ? ResetAlarmPolicy.resetDriftTolerance : max(ResetAlarmPolicy.resetDriftTolerance, @@ -504,8 +549,31 @@ public struct ResetAlarmTracker: Sendable { // 3:48 pm, 5:03 pm and later false MiniMax and Antigravity // 5h alerts). Across a passed end the climb keeps settling // small early moves as before. - let forwardJump = jump > required - || (jump > ResetAlarmPolicy.resetDriftTolerance && climbed && hasPassed) + // The deadline branch needs the quota to climb with it: a + // rolling window slides its end while usage ages out (CC-215), + // and a stale or partially corrected deadline - the MiniMax + // weekly deadline advancing only five days nine hours - adopts + // silently. After the end has passed, a deadline that + // advanced a compatible full cadence, confirmed by an explicit + // start when one is reported, proves a scheduled rollover on + // its own; a genuine refill with the end still ahead is + // caught by the held-end courtesy and vendor-restore rules + // below. + // A courtesy reset that also rolls the window forward reissues + // a fresh full period: the new end sits one whole period from + // now (a rolling climb leaves less than that) and the quota + // came back by a restore-sized rise (owner 2026-10-08: quota + // restored before the window was due must alert). + let freshPeriod = window.periodSeconds.map { period in + abs(reported.timeIntervalSince(readAt) - period) + <= ResetAlarmPolicy.resetDriftTolerance + } ?? false + let strongQuotaRestore = reading.flatMap { current in + window.lastRemaining.map { current >= $0 + ResetAlarmPolicy.vendorRestoreRise } + } ?? false + let forwardJump = (jump > required && climbed) + || (hasPassed && advancedFullCadence && explicitStartConfirmsPeriod) + || (!hasPassed && freshPeriod && strongQuotaRestore) if forwardJump { isReset = true // When the window had *not* reached its own scheduled end, @@ -549,8 +617,10 @@ public struct ResetAlarmTracker: Sendable { } // The old period is over and the percentage went back up, even // though the reader has not published the next reset time yet. - if !isReset, hasPassed, let reading, let last = window.lastRemaining, - reading > last + ResetAlarmPolicy.riseEpsilon { + if !isReset, hasPassed, + observation.resetAt.map({ $0 <= previousReset + ResetAlarmPolicy.resetDriftTolerance }) ?? true, + let reading, let last = window.lastRemaining, + reading >= last + ResetAlarmPolicy.earlyResetRiseMargin { isReset = true nextResetAt = observation.resetAt.flatMap { $0 > readAt ? $0 : nil } } @@ -659,8 +729,12 @@ public struct ResetAlarmTracker: Sendable { // All three carries share one evidence bar: a rise against // an end that slid with the clock is the window rolling, not // a restore (CC-215). An unknown end cannot prove a restore. + // A reading at or above 99.5% counts as full only when the + // prior reading was below it by a real margin: a sub-point + // rounding wobble near full (99.4 to 99.6) is not a vendor + // handing the quota back. let jumpedToFull = periodEndHeld && !slidWithTheClock - && reading >= 99.5 && last < 99.5 + && reading >= 99.5 && last <= 99.5 - ResetAlarmPolicy.riseEpsilon let surgedMidWindow = periodEndHeld && !slidWithTheClock && last < 80.0 && reading >= 95.0 let quotaHandedBack = periodEndHeld && !slidWithTheClock @@ -677,7 +751,8 @@ public struct ResetAlarmTracker: Sendable { nextResetAt = reported } if let reading, let last = window.lastRemaining { - let jumpedToFull = reading >= 99.5 && last < 99.5 + let jumpedToFull = reading >= 99.5 + && last <= 99.5 - ResetAlarmPolicy.riseEpsilon let surgedMidWindow = last < 80.0 && reading >= 95.0 if jumpedToFull || surgedMidWindow { isReset = true @@ -749,6 +824,9 @@ public struct ResetAlarmTracker: Sendable { window.lastRemaining = reading } } + if let periodStartAt = observation.periodStartAt { + window.periodStartAt = periodStartAt + } // Assigned unconditionally, so it always means "the stamp carried by the // previous reading" and is nil when that reading was unstamped. Only // ever writing it on a stamped reading would leave a stale anchor diff --git a/Sources/QuotaCore/SMSAlertCoordinator.swift b/Sources/QuotaCore/SMSAlertCoordinator.swift new file mode 100644 index 00000000..43f4cc75 --- /dev/null +++ b/Sources/QuotaCore/SMSAlertCoordinator.swift @@ -0,0 +1,82 @@ +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) } + guard !Task.isCancelled else { return .failed(.uncertain) } + 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..f02dfc67 --- /dev/null +++ b/Sources/QuotaCore/TwilioSMSClient.swift @@ -0,0 +1,193 @@ +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 { + 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 + 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/Sources/QuotaCore/WidgetPlatformDisplay.swift b/Sources/QuotaCore/WidgetPlatformDisplay.swift index ab1f395c..e893da5e 100644 --- a/Sources/QuotaCore/WidgetPlatformDisplay.swift +++ b/Sources/QuotaCore/WidgetPlatformDisplay.swift @@ -118,9 +118,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 @@ -161,3 +160,169 @@ 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 ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased().replacingOccurrences(of: " ", with: "") + let label = reading.label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let weeklyLabels: Set = ["weekly", "week", "7-day", "7 day", "7-day window", "7 day window"] + let fiveHourLabels: Set = ["5h", "5hr", "5-hour", "5 hours", "5-hour window", "5 hour window", "five_hour"] + if ["weekly", "week", "1w", "7d", "168h", "10080m"].contains(token) + || weeklyLabels.contains(label) { return "weekly" } + if ["5h", "5hr", "5-hour", "5hours", "300m"].contains(token) + || fiveHourLabels.contains(label) { 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 c821a4d4..212a1b71 100644 --- a/Sources/QuotaCore/ZCodeQuotaReader.swift +++ b/Sources/QuotaCore/ZCodeQuotaReader.swift @@ -1,6 +1,36 @@ import CryptoKit import Foundation +/// 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 the GLM Coding Plan quota behind the local ZCode sign-in. /// /// ZCode keeps its OAuth business tokens in `~/.zcode/v2/credentials.json`, @@ -39,6 +69,7 @@ import Foundation /// 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? @@ -51,10 +82,12 @@ public struct ZCodeQuotaReader: Sendable { 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) } @@ -121,7 +154,11 @@ public struct ZCodeQuotaReader: Sendable { } 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 @@ -608,3 +645,226 @@ private final class ZCodeNoRedirectDelegate: NSObject, URLSessionTaskDelegate, @ 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. +private struct ExplicitZCodeQuotaReader: Sendable { + private let now: @Sendable () -> Date + private let credential: @Sendable () async -> ZCodeQuotaCredential? + private let fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + + private static let maxResponseBytes = 262_144 + private static let timeout: TimeInterval = 15 + + public init( + now: @escaping @Sendable () -> Date = { Date() }, + credential: (@Sendable () async -> ZCodeQuotaCredential?)? = nil, + fetch: (@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse))? = nil + ) { + self.now = now + self.credential = credential ?? { nil } + self.fetch = fetch ?? Self.makeFetcher() + } + + public func read() async -> LocalQuotaResult { + do { + try Task.checkCancellation() + 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."]) + } + 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."]) + } + guard (200..<300).contains(result.statusCode), let root = result.root else { + return LocalQuotaResult(issues: ["zcode": "Z.ai 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": "Z.ai quota refresh was cancelled."]) + } catch { + 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."]) + } + } +} + +private struct ExplicitZCodeHTTPPayload { + let statusCode: Int + let root: [String: Any]? +} + +private extension ExplicitZCodeQuotaReader { + static func fetchQuota( + url: URL, + token: String, + fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + ) 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. + for attempt in 0..<2 { + try Task.checkCancellation() + var request = URLRequest(url: url) + request.httpMethod = "GET" + request.cachePolicy = .reloadIgnoringLocalCacheData + request.timeoutInterval = Self.timeout + let header = attempt == 0 ? token : "Bearer \(token)" + request.setValue(header, forHTTPHeaderField: "authorization") + request.setValue("application/json", forHTTPHeaderField: "Accept") + let (data, response) = try await fetch(request) + if response.statusCode == 401, attempt == 0 { continue } + let root = data.count <= Self.maxResponseBytes + ? (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + : nil + return ExplicitZCodeHTTPPayload(statusCode: response.statusCode, root: root) + } + return ExplicitZCodeHTTPPayload(statusCode: 401, root: nil) + } + + /// 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 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, 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, + 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: region.title, providerKey: "zcode", providerLabel: region.title, + 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)) + } + + 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: ExplicitZCodeNoRedirectDelegate(), delegateQueue: nil) + defer { session.invalidateAndCancel() } + let (bytes, response) = try await session.bytes(for: request) + 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 ExplicitZCodeQuotaError.unavailable + } + var data = Data() + data.reserveCapacity(16_384) + for try await byte in bytes { + guard data.count < Self.maxResponseBytes else { throw ExplicitZCodeQuotaError.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 ExplicitZCodeQuotaError: Error { + case unavailable +} + +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/CompanionModelTests.swift b/Tests/CodeCapsTests/CompanionModelTests.swift index cba5fcfe..3435956a 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 \"—\" }")) @@ -299,6 +338,14 @@ final class CompanionModelTests: XCTestCase { ) } + func testCompanionAntigravityPeriodLabelsUseExactCanonicalValues() throws { + let source = try readCompanionModelSource() + XCTAssertTrue(source.contains("weeklyLabels.contains(label)")) + XCTAssertTrue(source.contains("fiveHourLabels.contains(label)")) + XCTAssertFalse(source.contains("label.contains(\"week\")")) + XCTAssertFalse(source.contains("label.contains(\"5h\")")) + } + /// The shared-pool rule from `AntigravityQuotaGroups`: a weekly reading has /// to be identified explicitly, and a reset's distance is not a duration. /// @@ -348,8 +395,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("), @@ -372,8 +419,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 effectiveQualifier = isMiniMax ? \"\" : modelQualifier"), + "ordinary provider windows must use shared allowance identity, preserving named model details" ) } @@ -799,14 +846,12 @@ 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 effectiveQualifier = isMiniMax ? \"\" : modelQualifier"), + "MiniMax model names must not create duplicate allowance rows") + XCTAssertTrue(source.contains("let cadenceKey = effectiveQualifier.isEmpty"), + "MiniMax rows consolidate on the wire allowance identity without model qualifiers") + 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 { @@ -1078,11 +1123,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/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..648fb99a --- /dev/null +++ b/Tests/CodeCapsTests/MuseCodePluginTests.swift @@ -0,0 +1,307 @@ +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) + } + + 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 { + 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..7ee103c5 --- /dev/null +++ b/Tests/CodeCapsTests/QuitConfirmationTests.swift @@ -0,0 +1,58 @@ +import AppKit +import Carbon +import XCTest +@testable import CodeCaps + +final class QuitConfirmationTests: XCTestCase { + @MainActor + func testOnlyManagedContentWindowsAreSelectedForHiding() { + func window(_ style: NSWindow.StyleMask = [.titled]) -> NSWindow { + NSWindow(contentRect: .zero, styleMask: style, backing: .buffered, defer: false) + } + let console = window() + let glance = window() + let status = window() + status.level = .statusBar + let popup = window() + popup.level = .popUpMenu + let system = window([]) + let unrelated = window() + let selected = QuitConfirmationPolicy.windowsToHide(managed: [console, nil, glance, status, popup, system]) + XCTAssertEqual(selected.map(ObjectIdentifier.init), [console, glance].map(ObjectIdentifier.init)) + XCTAssertFalse(selected.contains { $0 === unrelated }) + XCTAssertFalse(console.isVisible, "Selection alone must not show or hide windows") + XCTAssertTrue(QuitConfirmationPolicy.shouldShowStatusItem(displayMode: .dock, keepRunningOverride: true)) + } + + 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..5fd513f3 --- /dev/null +++ b/Tests/CodeCapsTests/SMSAlertControllerTests.swift @@ -0,0 +1,230 @@ +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 testForgetCancelsAnInFlightSMSRequest() async { + let (defaults, suite) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + let vault = SMSCredentialFixture() + let requestStarted = expectation(description: "SMS transport started") + let transport = SMSBlockingTransportFixture { requestStarted.fulfill() } + 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["museCodeBurn"] = true + let delivery = controller.deliver(kind: "museCodeBurn", title: "Fixture", body: "Fixture", eventID: "event") + await fulfillment(of: [requestStarted], timeout: 1) + + await controller.forgetSetup() + await delivery?.value + + XCTAssertTrue(transport.wasCancelled) + XCTAssertFalse(transport.completed) + XCTAssertFalse(controller.hasSavedSetup) + XCTAssertEqual(controller.status, "Twilio setup forgotten.") + } + + 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 SMSBlockingTransportFixture: @unchecked Sendable { + private let lock = NSLock() + private var cancellationObserved = false + private var requestCompleted = false + private let onStart: @Sendable () -> Void + + init(onStart: @escaping @Sendable () -> Void) { self.onStart = onStart } + + var wasCancelled: Bool { + lock.lock(); defer { lock.unlock() } + return cancellationObserved + } + + var completed: Bool { + lock.lock(); defer { lock.unlock() } + return requestCompleted + } + + private func markCancelled() { + lock.lock(); defer { lock.unlock() } + cancellationObserved = true + } + + private func markCompleted() { + lock.lock(); defer { lock.unlock() } + requestCompleted = true + } + + var client: TwilioSMSClient { + TwilioSMSClient(transport: { [self] request in + onStart() + do { + try await Task.sleep(nanoseconds: 30_000_000_000) + markCompleted() + } catch { + markCancelled() + throw error + } + return (Data(#"{"sid":"SMdddddddddddddddddddddddddddddddd","status":"queued"}"#.utf8), + HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)!) + }) + } +} + +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/CodeCapsTests/WidgetTests.swift b/Tests/CodeCapsTests/WidgetTests.swift index 435ea544..6ffd0069 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,31 @@ 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") + // A platform that reports only supplementary video windows keeps them, + // and a stale window that is at cap with a reset still ahead may name + // the cap; every other cap pick comes from the fresh windows. + XCTAssertTrue( + atCapMethod.contains("let planWindows = windows.filter { !$0.isSupplementaryVideoQuota }"), + "the widget's cap window never comes from a supplementary video pool" + ) XCTAssertTrue( - source.contains(".filter { $0.isFresh(now: now) }"), + atCapMethod.contains("$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 +315,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/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 7f6cb5c7..9423b79f 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) diff --git a/Tests/QuotaCoreTests/AntigravityQuotaGroupsTests.swift b/Tests/QuotaCoreTests/AntigravityQuotaGroupsTests.swift index 6cf030d7..2bb4088d 100644 --- a/Tests/QuotaCoreTests/AntigravityQuotaGroupsTests.swift +++ b/Tests/QuotaCoreTests/AntigravityQuotaGroupsTests.swift @@ -58,6 +58,21 @@ final class AntigravityQuotaGroupsTests: XCTestCase { XCTAssertEqual(AntigravityQuotaGroups.normalize(groups, includeMissing: true), groups) } + func testCadenceLabelsRequireExactCanonicalValues() { + var window = report("claude-sonnet", 80) + window.modelId = nil + window.label = "notweekly" + XCTAssertNil(AntigravityQuotaGroups.cadenceKey(for: window)) + window.label = "weekend" + XCTAssertNil(AntigravityQuotaGroups.cadenceKey(for: window)) + window.label = " 7-day window " + XCTAssertEqual(AntigravityQuotaGroups.cadenceKey(for: window), "weekly") + window.label = "not a 5-hour limit" + XCTAssertNil(AntigravityQuotaGroups.cadenceKey(for: window)) + window.label = " 5-hour window " + XCTAssertEqual(AntigravityQuotaGroups.cadenceKey(for: window), "5h") + } + func testASourceReportedExhaustionSurvivesGroupingAndExport() throws { // Antigravity called this pool dead at 15% — a rejected session, a // suspended plan — and the percentage is the last good reading rather diff --git a/Tests/QuotaCoreTests/CursorQuotaReaderTests.swift b/Tests/QuotaCoreTests/CursorQuotaReaderTests.swift index 4affe989..8d997cc4 100644 --- a/Tests/QuotaCoreTests/CursorQuotaReaderTests.swift +++ b/Tests/QuotaCoreTests/CursorQuotaReaderTests.swift @@ -5,6 +5,27 @@ import XCTest final class CursorQuotaReaderTests: XCTestCase { private let observedAt = Date(timeIntervalSince1970: 1_789_000_000) + func testObservationTimestampIsCapturedAfterQuotaRequestsComplete() async throws { + let responseAt = observedAt.addingTimeInterval(45) + let clock = MutableDateClock(observedAt) + let token = Self.jwt(subject: "auth0|cursor-user-response-time", expiration: responseAt.addingTimeInterval(3600)) + let reader = CursorQuotaReader( + now: { clock.read() }, + accessToken: { token }, + fetch: { request in + clock.set(responseAt) + guard request.url?.path.contains("usage-summary") == true else { + return Self.response("{}", status: 404) + } + return Self.response(#"{"billingCycleEnd":"2026-10-01T00:00:00Z","membershipType":"pro","individualUsage":{"plan":{"used":2500,"limit":10000,"remaining":7500}}}"#) + } + ) + + let result = await reader.read() + let window = try XCTUnwrap(result.windows.first) + XCTAssertEqual(window.occurredDate, responseAt) + } + func testReadsIncludedPlanAndTranslatesCursorAppTokenToSessionCookie() async { let token = Self.jwt(subject: "auth0|cursor-user-1", expiration: observedAt.addingTimeInterval(3600)) let reader = CursorQuotaReader( @@ -275,3 +296,22 @@ final class CursorQuotaReaderTests: XCTestCase { return formatter.string(from: Date(timeIntervalSince1970: Double(ms) / 1_000)) } } + +private final class MutableDateClock: @unchecked Sendable { + private let lock = NSLock() + private var instant: Date + + init(_ instant: Date) { self.instant = instant } + + func read() -> Date { + lock.lock() + defer { lock.unlock() } + return instant + } + + func set(_ instant: Date) { + lock.lock() + defer { lock.unlock() } + self.instant = instant + } +} 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 a2e9fd61..4d8a5b05 100644 --- a/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift +++ b/Tests/QuotaCoreTests/KimiQuotaReaderTests.swift @@ -49,6 +49,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) @@ -280,9 +281,163 @@ final class KimiQuotaReaderTests: XCTestCase { 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/LocalQuotaReaderRegistryTests.swift b/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift new file mode 100644 index 00000000..d0245aba --- /dev/null +++ b/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift @@ -0,0 +1,110 @@ +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"]) + } + 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/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..78caa4d7 --- /dev/null +++ b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift @@ -0,0 +1,269 @@ +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 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, + 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/QuotaCardProjectionTests.swift b/Tests/QuotaCoreTests/QuotaCardProjectionTests.swift new file mode 100644 index 00000000..f92eac9d --- /dev/null +++ b/Tests/QuotaCoreTests/QuotaCardProjectionTests.swift @@ -0,0 +1,94 @@ +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]) + } + + /// The merged headline rule (#374): a Muse Assist extra meter with room + /// headlines the card, and it also stands in when the plan itself reads + /// spent. The weekly leads only when no extra reading exists. + func testAMuseExtraWithRoomHeadlinesTheCard() { + 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]), 81) + XCTAssertEqual(CardHeadline.percent([.init(isMuseAssistExtra: false, isMasked: false, remainingPercent: 0), extra]), 81) + XCTAssertEqual(CardHeadline.percent([weekly]), 47) + } + + 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/ResetAlarmPlanChangeTests.swift b/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift index 94aa478b..b477a510 100644 --- a/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift +++ b/Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift @@ -88,6 +88,43 @@ final class ResetAlarmPlanChangeTests: XCTestCase { XCTAssertFalse(events[0].isPlanChange) } + func testMidWindowRestoreFromLowNinetiesToFullStillCountsAsAVendorReset() { + var tracker = ResetAlarmTracker() + let weekEnd = t0 + 7 * day + _ = tracker.process(weekly(at: t0, resetAt: weekEnd, remaining: 92), now: t0) + + let later = t0 + 2 * hour + let events = tracker.process(weekly(at: later, resetAt: weekEnd, remaining: 100), now: later) + + XCTAssertEqual(events.count, 1) + XCTAssertTrue(events[0].isVendorReset, "a full refill remains a vendor reset even after some intervening use") + } + + func testNearFullRoundingWobbleIsNotReportedAsVendorReset() { + var tracker = ResetAlarmTracker() + let weekEnd = t0 + 7 * day + _ = tracker.process(weekly(at: t0, resetAt: weekEnd, remaining: 99.4), now: t0) + + let later = t0 + 2 * hour + let events = tracker.process(weekly(at: later, resetAt: weekEnd, remaining: 99.6), now: later) + + XCTAssertTrue(events.isEmpty, "a sub-point rounding wobble near full is not evidence of a vendor reset") + } + + func testPreExpirySmallDeadlineNudgeAndTenPointRiseIsNotAReset() { + var tracker = ResetAlarmTracker() + let oldEnd = t0 + 5 * day + _ = tracker.process(weekly(at: t0, resetAt: oldEnd, remaining: 72), now: t0) + + let later = t0 + hour + let nudgedEnd = oldEnd + 16 * 60 + let events = tracker.process(weekly(at: later, resetAt: nudgedEnd, remaining: 84), now: later) + + XCTAssertTrue(events.isEmpty, "a 16-minute nudge is not a weekly reset even when quota rises by ten points") + XCTAssertEqual(tracker.state.windows[ResetAlarmTracker.windowKey(scope: "local", providerId: "musecode", windowId: "7d")]?.periodResetAt, + nudgedEnd) + } + /// The line itself. The floor is 95 rather than 99 because the first /// reading after a reset can already carry a little usage. func testTheLevelTheQuotaLandsAtDecidesWhichNameItGets() { @@ -194,17 +231,138 @@ 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: 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) + } + + func testMiniMaxWeeklyDeadlineCorrectionNeedsAnAdvancedExplicitPeriodStart() { + var tracker = ResetAlarmTracker() + let week = 7 * day + let periodStart = t0 - 6 * day + let staleEnd = t0 + hour + let correctedEnd = staleEnd + week + func minimax(at observedAt: Date, start: Date, end: Date, remaining: Double) -> ResetAlarmObservation { + ResetAlarmObservation(scope: "local", providerId: "minimax", providerTitle: "MiniMax", + windowId: "general:weekly", windowLabel: "7d", periodSeconds: week, + resetAt: end, periodStartAt: start, remainingPercent: remaining, observedAt: observedAt) + } + + _ = tracker.process([minimax(at: t0, start: periodStart, end: staleEnd, remaining: 26)], now: t0) + let correctionAt = staleEnd + 60 + let correction = tracker.process( + [minimax(at: correctionAt, start: periodStart, end: correctedEnd, remaining: 26)], now: correctionAt) + XCTAssertTrue(correction.isEmpty) + + let repeated = correctionAt + hour + XCTAssertTrue(tracker.process( + [minimax(at: repeated, start: periodStart, end: correctedEnd, remaining: 26)], now: repeated).isEmpty) + + let rolloverAt = correctedEnd + 60 + let rollover = tracker.process( + [minimax(at: rolloverAt, start: periodStart + week, end: correctedEnd + week, remaining: 24)], now: rolloverAt) + XCTAssertEqual(rollover.map(\.windowId), ["general:weekly"]) + XCTAssertEqual(rollover.first?.reason, .newPeriod) + } + + func testPassedStaleWeeklyDeadlineAdoptsFlatAndSmallFluctuationsSilently() { + for balance in [72.0, 73.0, 74.0] { + var tracker = ResetAlarmTracker() + let oldEnd = t0 + 25 * 60 + let nextEnd = oldEnd + 5 * day + 9 * hour + _ = tracker.process(weekly(at: t0, resetAt: oldEnd, remaining: 72, provider: "minimax"), now: t0) + let later = t0 + 32 * 60 + XCTAssertTrue(tracker.process(weekly(at: later, resetAt: nextEnd, remaining: balance, provider: "minimax"), now: later).isEmpty) + let key = ResetAlarmTracker.windowKey(scope: "local", providerId: "minimax", windowId: "7d") + XCTAssertEqual(tracker.state.windows[key]?.periodResetAt, nextEnd) + XCTAssertEqual(tracker.state.windows[key]?.lastRemaining, balance) + XCTAssertTrue(tracker.process(weekly(at: later + 60, resetAt: nextEnd, remaining: balance, provider: "minimax"), now: later + 60).isEmpty) + } + } + + func testFleetWeeklyFutureDeadlineCorrectionsNeverTreatSmallDriftAsMidwindowRestore() { + for balance in [72.0, 73.0, 74.0] { + var tracker = ResetAlarmTracker() + let oldEnd = t0 + day + func fleet(at time: Date, end: Date, value: Double) -> ResetAlarmObservation { + ResetAlarmObservation(scope: "Mac.Jays.Services", providerId: "minimax", providerTitle: "MiniMax", + windowId: "7d", windowLabel: "7d", periodSeconds: 7 * day, + resetAt: end, remainingPercent: value, observedAt: time) + } + _ = tracker.process([fleet(at: t0, end: oldEnd, value: 72)], now: t0) + let later = t0 + hour + XCTAssertTrue(tracker.process([fleet(at: later, end: oldEnd + 5 * day, value: balance)], now: later).isEmpty) + let key = ResetAlarmTracker.windowKey(scope: "Mac.Jays.Services", providerId: "minimax", windowId: "7d") + XCTAssertEqual(tracker.state.windows[key]?.periodResetAt, oldEnd + 5 * day) + XCTAssertEqual(tracker.state.windows[key]?.lastRemaining, balance) + } + } - 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") + func testFlatFullQuotaStillReportsElapsedWeeklyAndCalendarMonthRollovers() { + for (period, advance) in [(7 * day, 7 * day), (30 * day, 28 * day), (30 * day, 31 * day)] { + var tracker = ResetAlarmTracker() + let end = t0 + hour + _ = tracker.process([reading("cadence", period: period, resetAt: end, remaining: 100, observedAt: t0)], now: t0) + let later = end + 60 + let events = tracker.process([reading("cadence", period: period, resetAt: end + advance, remaining: 100, observedAt: later)], now: later) + XCTAssertEqual(events.count, 1) + XCTAssertEqual(events.first?.reason, .newPeriod) + } + } + + func testFiveHourFlatQuotaRolloverRetainsNearCapNotificationPolicy() { + var tracker = ResetAlarmTracker() + let end = t0 + hour + _ = tracker.process([reading("5h", period: 5 * hour, resetAt: end, remaining: 10, observedAt: t0)], now: t0) + let later = end + 60 + let events = tracker.process([reading("5h", period: 5 * hour, resetAt: end + 5 * hour, remaining: 10, observedAt: later)], now: later) + XCTAssertEqual(events.count, 1) + XCTAssertEqual(events.first?.reason, .newPeriod) } // MARK: The words diff --git a/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift b/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift index 29c3ea24..62e5d6dc 100644 --- a/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift +++ b/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift @@ -452,6 +452,63 @@ 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: 100, + observedAt: scheduledAt, provider: "minimax", label: "7d")], + now: scheduledAt) + XCTAssertEqual(scheduled.map(\.reason), [.newPeriod], "A later weekly rollover with quota restored remains a scheduled reset.") + } + + 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 + // Within the period-share bound: half the weekly period is the + // decisive-move bar (CC-215), so a one-day correction stays a + // quiet correction while a move past it is a vendor reset. + let correctedEnd = initialEnd + 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..e64e11d9 --- /dev/null +++ b/Tests/QuotaCoreTests/TwilioSMSClientTests.swift @@ -0,0 +1,121 @@ +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 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)! + 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 } +} 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/Tests/QuotaCoreTests/WidgetPlatformDisplayTests.swift b/Tests/QuotaCoreTests/WidgetPlatformDisplayTests.swift index 882ee80b..37eab52c 100644 --- a/Tests/QuotaCoreTests/WidgetPlatformDisplayTests.swift +++ b/Tests/QuotaCoreTests/WidgetPlatformDisplayTests.swift @@ -30,6 +30,20 @@ final class WidgetPlatformDisplayTests: XCTestCase { } } + func testAntigravityPeriodUsesCanonicalTokensAndExactLabels() { + func reading(window: String?, label: String) -> QuotaCardProjection.Reading { + .init(id: "fixture", providerKey: "google-antigravity", label: label, window: window) + } + + XCTAssertEqual(QuotaCardProjection.antigravityPeriod(reading(window: nil, label: " Weekly ")), "weekly") + XCTAssertEqual(QuotaCardProjection.antigravityPeriod(reading(window: "1w", label: "usage")), "weekly") + XCTAssertEqual(QuotaCardProjection.antigravityPeriod(reading(window: nil, label: "5-hour window")), "5h") + XCTAssertEqual(QuotaCardProjection.antigravityPeriod(reading(window: "300m", label: "usage")), "5h") + XCTAssertNil(QuotaCardProjection.antigravityPeriod(reading(window: nil, label: "notweekly"))) + XCTAssertNil(QuotaCardProjection.antigravityPeriod(reading(window: nil, label: "weekend"))) + XCTAssertNil(QuotaCardProjection.antigravityPeriod(reading(window: nil, label: "not a 5-hour limit"))) + } + func testMuseAssistUsableExtraSpeaksForTheCardHeadline() { let readings = [ CardHeadline.Reading(isMuseAssistExtra: false, isMasked: false, remainingPercent: 0), diff --git a/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift b/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift index 34171213..037fa986 100644 --- a/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift +++ b/Tests/QuotaCoreTests/ZCodeQuotaReaderTests.swift @@ -513,3 +513,206 @@ final class ZCodeQuotaReaderTests: XCTestCase { 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, + credential: ZCodeQuotaCredential? = .init(region: .zAI, apiKey: "fixture-api-key") + ) async -> LocalQuotaResult { + 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") + if status == 401, let key = credential?.apiKey { + XCTAssertTrue(authorization == key || authorization == "Bearer " + key) + } else { XCTAssertEqual(authorization, credential?.apiKey) } + let response = HTTPURLResponse( + url: request.url!, + statusCode: status, httpVersion: nil, headerFields: nil + )! + return (Data(json.utf8), response) + } + ).read() + } + + func testCreditLimitsBecomeFiveHourAndWeeklyWindows() async { + let result = await read(#"{"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, "Z.ai") + 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(#"{"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 testAbsentExplicitAndLocalCredentialsStaySilentWithoutFetching() async { + let result = await read("{}", credential: nil) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertTrue(result.issues.isEmpty) + } + + 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 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(#"{"code":200,"data":{"limits":[]}}"#) + XCTAssertTrue(result.windows.isEmpty) + 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"], "Z.ai 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(#"{"code":200,"data":{}}"#) + XCTAssertTrue(missing.windows.isEmpty) + 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"], "Z.ai returned no readable quota.") + } + + func testCancellationIsNotReportedAsTransportFailure() async { + let result = await ZCodeQuotaReader( + now: { Date(timeIntervalSince1970: 0) }, + credential: { .init(region: .zAI, apiKey: "fixture-api-key") }, + fetch: { _ in throw CancellationError() } + ).read() + 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"], "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"], "Z.ai quota service is unavailable.") + } + + func testTransportFailureNeverSendsTheKeyToAnotherRegion() 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") + 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 testBigModelKeyUsesOnlyItsPairedRegionalEndpoint() async { + let result = await read( + #"{"code":200,"data":{"level":"max","limits":[{"type":"TOKENS_LIMIT","unit":6,"percentage":5}]}}"#, + credential: .init(region: .bigModel, apiKey: "bigmodel-fixture-key") + ) + XCTAssertEqual(result.windows.count, 1) + XCTAssertEqual(result.windows[0].quotaUnit, "tokens") + XCTAssertEqual(result.windows[0].planName, "GLM Coding Max") + } + func testURLCancellationDoesNotTryAnotherAuthenticationFormOrAccount() async { + let counter = ZCodeRequestCounter() + 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"], "Z.ai quota refresh was cancelled.") + let count = await counter.count + XCTAssertEqual(count, 1) + } + + 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.isEmpty) + } + + 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.") + } + +} + + +private actor ZCodeRequestCounter { + var count = 0 + func increment() { count += 1 } +} diff --git a/docs/AUTO-UPDATE.md b/docs/AUTO-UPDATE.md index c68e19db..f9e8ea5a 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. @@ -74,7 +74,7 @@ A private repository cannot do this, because anonymous clients cannot download i | `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. | | `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 new file mode 100644 index 00000000..280ba2e4 --- /dev/null +++ b/docs/rollouts/2026-11-03-cc205-monitoring-alert-controls.md @@ -0,0 +1,41 @@ +# 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. + +## 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 a9b486b1..bd1948c0 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 @@ -503,7 +503,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. @@ -610,6 +615,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] { @@ -617,7 +629,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( @@ -634,7 +646,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( @@ -688,7 +700,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( @@ -733,7 +747,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, @@ -741,9 +759,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 { @@ -2023,11 +2041,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( @@ -2106,6 +2124,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] = [:] @@ -2123,6 +2150,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" { @@ -2169,25 +2197,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 @@ -2301,6 +2319,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) @@ -2323,8 +2342,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 @@ -2447,17 +2467,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 @@ -2475,7 +2494,6 @@ public final class CompanionQuotaModel: ObservableObject { && QuotaCapRule.isExhausted(remainingPercent: weeklyPct, providerSaysExhausted: weeklyWin?.isExhausted ?? false) - let controllingPct: Double? let isExhausted: Bool let subtitle: String @@ -2487,16 +2505,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 } @@ -2512,9 +2525,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() @@ -2524,11 +2544,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" ) @@ -2552,13 +2572,15 @@ public final class CompanionQuotaModel: ObservableObject { /// pool because of it. private static func antigravityPeriod(of w: WireRawWindow) -> String? { let token = (w.window ?? "").lowercased().replacingOccurrences(of: " ", with: "") - let label = w.label.lowercased() + let label = w.label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let weeklyLabels: Set = ["weekly", "week", "7-day", "7 day", "7-day window", "7 day window"] + let fiveHourLabels: Set = ["5h", "5hr", "5-hour", "5 hours", "5-hour window", "5 hour window", "five_hour"] if ["weekly", "week", "1w", "7d", "168h", "10080m"].contains(token) - || label.contains("weekly") || label.contains("week") { + || weeklyLabels.contains(label) { return "weekly" } if ["5h", "5hr", "5-hour", "5hours", "300m"].contains(token) - || label.contains("5h") || label.contains("5-hour") || label.contains("five_hour") { + || fiveHourLabels.contains(label) { return "5h" } return nil @@ -2586,13 +2608,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 @@ -2720,7 +2736,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") { @@ -2735,7 +2751,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 5c8260c4..f3d7a0cc 100644 --- a/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift +++ b/ios/CodeCapsCompanion/App/Views/CompanionContentView.swift @@ -298,9 +298,7 @@ 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 // Two pools of one provider share a title (Antigravity's Gemini and @@ -486,26 +484,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 f8c1df24..7123ac98 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift @@ -100,6 +100,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" @@ -289,8 +291,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 @@ -389,8 +395,8 @@ public struct WidgetPlatformItem: Identifiable, Equatable, Sendable { /// allowance is a one-day window, so the row showed "5h" and "1d" while /// the weekly reading the owner routes on was nowhere. public func dualWindows() -> (window1: WidgetWindowItem, window2: WidgetWindowItem)? { - guard windows.count >= 2 else { return nil } - let visible = windows.filter { + 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 } @@ -445,8 +451,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 { @@ -584,6 +590,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? @@ -607,7 +615,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 @@ -628,6 +636,8 @@ public enum WidgetPresentation { windowKey = try container.decodeIfPresent(String.self, forKey: .windowKey) 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) @@ -866,11 +876,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( @@ -915,6 +925,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, @@ -942,39 +962,12 @@ 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 { @@ -1151,7 +1144,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) } @@ -1168,7 +1161,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) } @@ -1186,18 +1179,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 @@ -1223,7 +1208,7 @@ public enum WidgetPresentation { resetAt: reset, isExhausted: fiveHourSpent, isMasked: weeklyExhausted, - observedAt: parseDate(from: f.occurredAt) + observedAt: parseDate(from: f.reportedAt) ?? parseDate(from: f.occurredAt) )) } @@ -1241,23 +1226,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() @@ -1340,7 +1324,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") { @@ -1355,7 +1339,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 469b6b9c..ac387c1b 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 { @@ -646,7 +648,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 { @@ -886,10 +888,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) @@ -900,12 +902,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 9afab964..f2aa3dc8 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetWindowRows.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetWindowRows.swift @@ -505,7 +505,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/ios-fleet/apps.json b/scripts/ios-fleet/apps.json index 7c08e0eb..fbf21329 100644 --- a/scripts/ios-fleet/apps.json +++ b/scripts/ios-fleet/apps.json @@ -12,8 +12,8 @@ "projectRel": "ios/CodeCapsCompanion/CodeCapsCompanion.xcodeproj", "xcodegenDir": "ios/CodeCapsCompanion", "worktreeHint": "~/Code/codecaps", - "marketingVersionDefault": "1.0.0", - "notes": "CodeCaps Companion \u2014 iOS companion for CodeCaps AI subscription monitor. Apple ID 6814623846 registered on ASC. ASC SKU codecaps-companion-ios. Marketing train 1.0.N: the next patch after the highest one App Store Connect holds on the train (the retired 0.1.N builds are on their own train and do not count); build is the repo commit count, raised above the App Store Connect floor. The two numbers are independent (AFC-517)." + "marketingVersionDefault": "0.1.0", + "notes": "CodeCaps Companion \u2014 iOS companion for CodeCaps AI subscription monitor. Apple ID 6814623846 registered on ASC. ASC SKU codecaps-companion-ios. CodeCaps stays on the fixed 0.1.0 marketing version; each release gets a shared merge-time build number above the App Store Connect floor." } } } diff --git a/scripts/ios-fleet/appstore-connect.env.example b/scripts/ios-fleet/appstore-connect.env.example index 0babe853..fc06daa2 100644 --- a/scripts/ios-fleet/appstore-connect.env.example +++ b/scripts/ios-fleet/appstore-connect.env.example @@ -1,7 +1,7 @@ # Environment for scripts/ios-fleet (App Store Connect API key). # Nothing is read from a local secrets folder. CI exports these three names in the job # environment. On a Mac, ship-testflight.sh and asc-api.mjs read them from Infisical -# Fleet-OPS with `fleet-secrets get` when they are not set: +# Fleet-OPS with `fleet-secrets get` and an explicit Infisical service token when they are not set: # /asc ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_P8 (the .p8 contents) # Never commit real values. # diff --git a/scripts/ios-fleet/asc-api.mjs b/scripts/ios-fleet/asc-api.mjs index 1c1dfb98..5031dd64 100644 --- a/scripts/ios-fleet/asc-api.mjs +++ b/scripts/ios-fleet/asc-api.mjs @@ -38,6 +38,7 @@ import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { normalizePrivateKey } from "./asc-key.mjs"; +import { fleetSecretsEnvironment, hasInfisicalServiceToken } from "./infisical-service-token.mjs"; // The version-numbering RULES live in ./version-plan.mjs (pure, no I/O, no // network); this client only reads the App Store Connect state they need. import { @@ -220,11 +221,15 @@ function materializeP8(pem) { // FLEET_SECRETS_BIN, then FLEET_SECRETS (what ship-testflight.sh reads and what // the test suites set), override the default binary. Values stay in memory. function fleetSecretsGet(name, folder) { + // `fleet-secrets` can use a host machine identity when no service token is + // present. Release automation must never enter that fallback. + if (!hasInfisicalServiceToken(process.env)) return ""; const bin = process.env.FLEET_SECRETS_BIN || process.env.FLEET_SECRETS || join(homedir(), ".local", "bin", "fleet-secrets"); try { return execFileSync(bin, ["get", name, "--path", folder], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], + env: fleetSecretsEnvironment(process.env), timeout: 30000 }).replace(/\n$/, ""); } catch { diff --git a/scripts/ios-fleet/asc-key.mjs b/scripts/ios-fleet/asc-key.mjs index b16e2517..50a43e89 100644 --- a/scripts/ios-fleet/asc-key.mjs +++ b/scripts/ios-fleet/asc-key.mjs @@ -36,6 +36,7 @@ */ import { writeFileSync } from "node:fs"; import { createPrivateKey } from "node:crypto"; +import { hasInfisicalServiceToken } from "./infisical-service-token.mjs"; // Normalizes a PEM private key and refuses anything that is not one. // @@ -96,6 +97,12 @@ export const CLIENT_ENV_ALLOWLIST = [ "APPLE_API_KEY_ID", "APPLE_API_ISSUER_ID", "APPLE_API_KEY_P8_BASE64", + "INFISICAL_FLEET_OPS_PROJECT_ID", + "INFISICAL_TOKEN", + "INFISICAL_PROJECT_ID", + "INFISICAL_ENVIRONMENT", + "INFISICAL_SITE_URL", + "INFISICAL_API_URL", "FLEET_SECRETS_BIN", "FLEET_SECRETS" ]; @@ -107,9 +114,11 @@ export const CLIENT_ENV_ALLOWLIST = [ export function clientEnvironment(env = process.env, extra = {}) { const child = {}; for (const name of CLIENT_ENV_ALLOWLIST) { + if (name === "INFISICAL_TOKEN" && !hasInfisicalServiceToken(env)) continue; const value = env[name]; if (typeof value === "string" && value.length > 0) child[name] = value; } + if (hasInfisicalServiceToken(env)) child.INFISICAL_TOKEN = env.INFISICAL_TOKEN; return { ...child, ...extra }; } diff --git a/scripts/ios-fleet/expire-obsolete-codecaps-versions.mjs b/scripts/ios-fleet/expire-obsolete-codecaps-versions.mjs new file mode 100644 index 00000000..8763421b --- /dev/null +++ b/scripts/ios-fleet/expire-obsolete-codecaps-versions.mjs @@ -0,0 +1,285 @@ +#!/usr/bin/env node +import { execFileSync } from "node:child_process"; +import { createSign } from "node:crypto"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { normalizePrivateKey } from "./asc-key.mjs"; +import { fleetSecretsEnvironment, hasInfisicalServiceToken } from "./infisical-service-token.mjs"; + +const APP_BUNDLE = "com.simplewithus.codecaps.ios"; +const KEEP_VERSION = "0.1.0"; +const API_ORIGIN = "https://api.appstoreconnect.apple.com"; +const MAX_PAGES = 50; + +function base64url(value) { + return Buffer.from(value).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} + +function privateKey(value) { + const cleaned = String(value || "").trim(); + if (!cleaned) return ""; + if (cleaned.includes("-----BEGIN ")) return normalizePrivateKey(cleaned) || ""; + const decoded = Buffer.from(cleaned, "base64").toString("utf8"); + return normalizePrivateKey(decoded) || ""; +} + +function fleetSecret(name) { + if (!hasInfisicalServiceToken(process.env)) return ""; + const bin = process.env.FLEET_SECRETS_BIN || process.env.FLEET_SECRETS + || join(homedir(), ".local", "bin", "fleet-secrets"); + try { + return execFileSync(bin, ["get", name, "--path", "/asc"], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + env: fleetSecretsEnvironment(process.env), + timeout: 30000 + }).replace(/\n$/, ""); + } catch { + return ""; + } +} + +function credentials() { + const appleKey = process.env.APPLE_API_KEY_P8_BASE64 || ""; + const appleId = String(process.env.APPLE_API_KEY_ID || "").trim(); + const appleIssuer = String(process.env.APPLE_API_ISSUER_ID || "").trim(); + const ascKey = process.env.ASC_KEY_P8 || ""; + const ascId = String(process.env.ASC_KEY_ID || "").trim(); + const ascIssuer = String(process.env.ASC_ISSUER_ID || "").trim(); + const keyId = appleId || ascId || fleetSecret("ASC_KEY_ID").trim(); + const issuerId = appleIssuer || ascIssuer || fleetSecret("ASC_ISSUER_ID").trim(); + const key = privateKey(appleKey || ascKey || fleetSecret("ASC_KEY_P8")); + if (!/^[A-Za-z0-9]{1,40}$/.test(keyId) || !issuerId || !key) { + throw new Error("an authorized App Store Connect API key is unavailable"); + } + if (!appleKey && !ascKey && !hasInfisicalServiceToken(process.env)) { + throw new Error("an explicit Infisical service token is required for the ASC secret fallback"); + } + return { keyId, issuerId, key }; +} + +function resolveApiBase() { + const configured = String(process.env.ASC_API_BASE || API_ORIGIN).replace(/\/+$/, ""); + if (configured === API_ORIGIN) return configured; + if (/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(configured)) return configured; + throw new Error("ASC_API_BASE must be the production host or a loopback test host"); +} + +function signedToken(credential) { + const now = Math.floor(Date.now() / 1000); + const header = base64url(JSON.stringify({ alg: "ES256", kid: credential.keyId, typ: "JWT" })); + const payload = base64url(JSON.stringify({ iss: credential.issuerId, iat: now, exp: now + 1190, aud: "appstoreconnect-v1" })); + const signingInput = `${header}.${payload}`; + const signer = createSign("SHA256"); + signer.update(signingInput); + signer.end(); + const signature = signer.sign({ key: credential.key, dsaEncoding: "ieee-p1363" }); + return `${signingInput}.${base64url(signature)}`; +} + +function createClient() { + const base = resolveApiBase(); + const token = signedToken(credentials()); + return async (method, path, body) => { + const target = path.startsWith("http") ? new URL(path) : new URL(path, `${base}/`); + if (target.origin !== base) throw new Error("ASC pagination link changed API host"); + let response; + try { + response = await fetch(target, { + method, + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body, + signal: AbortSignal.timeout(30000) + }); + } catch { + return { ok: false, status: 0, parsed: null }; + } + const text = await response.text(); + let parsed; + try { parsed = JSON.parse(text); } catch { parsed = null; } + return { ok: response.ok, status: response.status, parsed }; + }; +} + +async function allRows(api, firstPath, type, describe) { + const rows = []; + let next = firstPath; + for (let page = 0; page < MAX_PAGES && next; page++) { + const response = await api("GET", next); + if (!response.ok || !Array.isArray(response.parsed?.data)) { + throw new Error(`${describe} inventory failed (HTTP ${response.status})`); + } + for (const row of response.parsed.data) { + if (row?.type !== type || typeof row.id !== "string") throw new Error(`malformed ${describe} inventory row`); + rows.push(row); + } + next = response.parsed.links?.next || ""; + } + if (next) throw new Error(`${describe} inventory exceeds ${MAX_PAGES} pages`); + return rows; +} + +async function readInventory(api, appId) { + const versionRows = await allRows( + api, + `/v1/apps/${encodeURIComponent(appId)}/appStoreVersions?filter[platform]=IOS&limit=200`, + "appStoreVersions", + "App Store version" + ); + const versions = versionRows.map((row) => { + const version = row.attributes?.versionString; + const state = row.attributes?.appStoreState; + if (!/^\d+(?:\.\d+)*$/.test(version || "") || typeof state !== "string" || row.attributes?.platform !== "IOS") { + throw new Error(`malformed iOS App Store version ${row.id}`); + } + return { id: row.id, version, state }; + }); + + const builds = []; + const trainVersions = new Map(); + let next = `/v1/builds?filter[app]=${encodeURIComponent(appId)}` + + `&filter[preReleaseVersion.platform]=IOS&include=preReleaseVersion&limit=200`; + for (let page = 0; page < MAX_PAGES && next; page++) { + const response = await api("GET", next); + if (!response.ok || !Array.isArray(response.parsed?.data)) throw new Error(`TestFlight build inventory failed (HTTP ${response.status})`); + for (const train of response.parsed.included || []) { + if (train?.type !== "preReleaseVersions" || typeof train.id !== "string" + || !/^\d+(?:\.\d+)*$/.test(train.attributes?.version || "") || train.attributes?.platform !== "IOS") { + throw new Error("malformed included iOS TestFlight train"); + } + trainVersions.set(train.id, train.attributes.version); + } + for (const row of response.parsed.data) { + const version = trainVersions.get(row.relationships?.preReleaseVersion?.data?.id); + if (row.type !== "builds" || typeof row.id !== "string" || typeof row.attributes?.expired !== "boolean" + || !/^\d+(?:\.\d+)*$/.test(row.attributes?.version || "") || !version) { + throw new Error(`unattributed or malformed TestFlight build ${row?.id || "(missing id)"}`); + } + builds.push({ id: row.id, build: row.attributes.version, version, expired: row.attributes.expired }); + } + next = response.parsed.links?.next || ""; + } + if (next) throw new Error(`TestFlight build inventory exceeds ${MAX_PAGES} pages`); + return { versions, builds }; +} + +async function readReviewItems(api, appId, versions) { + const submissions = await allRows( + api, + `/v1/apps/${encodeURIComponent(appId)}/reviewSubmissions?filter[platform]=IOS&limit=200`, + "reviewSubmissions", + "App Store review submission" + ); + const versionsById = new Map(versions.map((version) => [version.id, version])); + const items = []; + for (const submission of submissions) { + const submissionState = submission.attributes?.state; + if (typeof submissionState !== "string") throw new Error(`malformed App Store review submission ${submission.id}`); + const submissionPath = `/v1/reviewSubmissions/${encodeURIComponent(submission.id)}/items` + + `?limit=200&fields[reviewSubmissionItems]=state,appStoreVersion`; + const rows = await allRows(api, submissionPath, "reviewSubmissionItems", "App Store review item"); + for (const item of rows) { + const versionRef = item.relationships?.appStoreVersion?.data; + if (!versionRef) continue; + if (versionRef.type !== "appStoreVersions" || typeof versionRef.id !== "string") { + throw new Error(`malformed App Store version relationship on review item ${item.id}`); + } + const version = versionsById.get(versionRef.id); + if (!version) throw new Error(`review item ${item.id} references an unlisted iOS App Store version`); + const activeSubmission = ["READY_FOR_REVIEW", "WAITING_FOR_REVIEW", "IN_REVIEW"].includes(submissionState); + const pendingRelease = submissionState === "COMPLETE" + && ["WAITING_FOR_EXPORT_COMPLIANCE", "PENDING_DEVELOPER_RELEASE", "PENDING_APPLE_RELEASE"].includes(version.state); + if (version.version !== KEEP_VERSION && (activeSubmission || pendingRelease)) { + items.push({ id: item.id, versionId: version.id, version: version.version, versionState: version.state, + submissionId: submission.id, submissionState, itemState: item.attributes?.state || "unknown" }); + } + } + } + return items; +} + +const deletableVersionStates = new Set([ + "PREPARE_FOR_SUBMISSION", "DEVELOPER_REJECTED", "REJECTED", "METADATA_REJECTED", "INVALID_BINARY" +]); + +export async function expireObsoleteVersions({ api = createClient(), apply = false } = {}) { + const appResponse = await api("GET", `/v1/apps?filter[bundleId]=${encodeURIComponent(APP_BUNDLE)}&limit=1`); + const app = appResponse.parsed?.data?.[0]; + if (!appResponse.ok || app?.type !== "apps" || typeof app.id !== "string") { + throw new Error(`CodeCaps App Store record lookup failed (HTTP ${appResponse.status})`); + } + const inventory = await readInventory(api, app.id); + const reviewItems = await readReviewItems(api, app.id, inventory.versions); + const reviewVersionIds = new Set(reviewItems.map((item) => item.versionId)); + const builds = inventory.builds.filter((row) => row.version !== KEEP_VERSION && !row.expired); + const versionsToDelete = inventory.versions.filter((row) => row.version !== KEEP_VERSION && deletableVersionStates.has(row.state)); + const protectedVersions = inventory.versions.filter((row) => row.version !== KEEP_VERSION + && !deletableVersionStates.has(row.state) && !reviewVersionIds.has(row.id)); + if (!apply) { + return { dryRun: true, keptVersion: KEEP_VERSION, + buildsToExpire: builds.map(({ build, version }) => ({ build, version })), + appStoreVersionsToDelete: versionsToDelete.map(({ version, state }) => ({ version, state })), + reviewItemsToRemove: reviewItems.map(({ version, versionState, submissionState, itemState }) => ({ + version, versionState, submissionState, itemState + })), + protectedVersions: protectedVersions.map(({ version, state }) => ({ version, state })) }; + } + + for (const row of builds) { + const response = await api("PATCH", `/v1/builds/${encodeURIComponent(row.id)}`, JSON.stringify({ + data: { type: "builds", id: row.id, attributes: { expired: true } } + })); + if (!response.ok) throw new Error(`TestFlight build ${row.build} (${row.version}) failed to expire (HTTP ${response.status})`); + } + for (const item of reviewItems) { + const response = await api("DELETE", `/v1/reviewSubmissionItems/${encodeURIComponent(item.id)}`); + if (!response.ok) { + throw new Error(`App Store version ${item.version} could not be removed from ${item.submissionState} review (HTTP ${response.status})`); + } + } + + const afterReviewRemoval = await readInventory(api, app.id); + const versionsToDeleteNow = afterReviewRemoval.versions.filter((row) => row.version !== KEEP_VERSION + && deletableVersionStates.has(row.state)); + for (const row of versionsToDeleteNow) { + const response = await api("DELETE", `/v1/appStoreVersions/${encodeURIComponent(row.id)}`); + if (!response.ok) throw new Error(`App Store version ${row.version} failed to delete (HTTP ${response.status})`); + } + + const verified = await readInventory(api, app.id); + const remainingReviewItems = await readReviewItems(api, app.id, verified.versions); + const activeBuilds = verified.builds.filter((row) => row.version !== KEEP_VERSION && !row.expired); + const remainingDeletableVersions = verified.versions.filter((row) => row.version !== KEEP_VERSION && deletableVersionStates.has(row.state)); + const remainingProtected = verified.versions.filter((row) => row.version !== KEEP_VERSION && !deletableVersionStates.has(row.state)); + const result = { dryRun: false, keptVersion: KEEP_VERSION, expiredBuilds: builds.length, + removedFromReview: reviewItems.map(({ version, submissionState }) => ({ version, submissionState })), + deletedAppStoreVersions: versionsToDeleteNow.map(({ version }) => version), + remainingOldActiveBuilds: activeBuilds.length, + remainingDeletableAppStoreVersions: remainingDeletableVersions.map(({ version, state }) => ({ version, state })), + remainingOldReviewItems: remainingReviewItems.map(({ version, submissionState }) => ({ version, submissionState })), + protectedVersions: remainingProtected.map(({ version, state }) => ({ version, state })) }; + if (activeBuilds.length || remainingDeletableVersions.length || remainingReviewItems.length || remainingProtected.length) process.exitCode = 3; + return result; +} + +async function main() { + const [bundle, keepVersion, action] = process.argv.slice(2); + if (bundle !== APP_BUNDLE || keepVersion !== KEEP_VERSION || ![undefined, "--apply", "--dry-run"].includes(action)) { + console.error("Usage: expire-obsolete-codecaps-versions.mjs com.simplewithus.codecaps.ios 0.1.0 [--apply|--dry-run]"); + process.exitCode = 2; + return; + } + try { + const result = await expireObsoleteVersions({ apply: action === "--apply" }); + if (result.protectedVersions.length) { + console.error(`${result.protectedVersions.length} older App Store version(s) are not editable drafts and remain protected`); + } + console.log(JSON.stringify(result)); + } catch (error) { + console.error(`expire-obsolete-codecaps-versions: ${error.message}`); + process.exitCode = 2; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main(); diff --git a/scripts/ios-fleet/infisical-service-token.mjs b/scripts/ios-fleet/infisical-service-token.mjs new file mode 100644 index 00000000..39b4afc3 --- /dev/null +++ b/scripts/ios-fleet/infisical-service-token.mjs @@ -0,0 +1,30 @@ +// Same shapes as the installer (st.*.*): current three-segment and legacy four-segment. +const SERVICE_TOKEN_PATTERN = /^st\.[^.\s]+(\.[^.\s]+)+$/; + +/** Only an explicit full service token may reach the automation secret reader. */ +export function hasInfisicalServiceToken(env = process.env) { + return typeof env.INFISICAL_TOKEN === "string" && SERVICE_TOKEN_PATTERN.test(env.INFISICAL_TOKEN); +} + +/** Minimal environment for `fleet-secrets`; machine identity settings never cross. */ +export function fleetSecretsEnvironment(env = process.env) { + if (!hasInfisicalServiceToken(env)) return {}; + const child = {}; + for (const name of [ + "PATH", + "HOME", + "TMPDIR", + "LANG", + "LC_ALL", + "INFISICAL_TOKEN", + "INFISICAL_FLEET_OPS_PROJECT_ID", + "INFISICAL_PROJECT_ID", + "INFISICAL_ENVIRONMENT", + "INFISICAL_SITE_URL", + "INFISICAL_API_URL" + ]) { + const value = env[name]; + if (typeof value === "string" && value.length > 0) child[name] = value; + } + return child; +} diff --git a/scripts/ios-fleet/ship-testflight.sh b/scripts/ios-fleet/ship-testflight.sh index 4512442e..63bfda7d 100755 --- a/scripts/ios-fleet/ship-testflight.sh +++ b/scripts/ios-fleet/ship-testflight.sh @@ -106,7 +106,7 @@ # # Secrets (never printed): # ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_P8 (env first, e.g. CI; else Infisical via -# `fleet-secrets get` from Fleet-OPS /asc: ASC_KEY_ID, ASC_ISSUER_ID and the .p8 in ASC_KEY_P8, +# `fleet-secrets get` with an explicit Infisical service token from Fleet-OPS /asc: ASC_KEY_ID, ASC_ISSUER_ID and the .p8 in ASC_KEY_P8, # written to a 0600 temp file and deleted on exit) # A named ASC_KEY_PATH is not a credential source at all: it is ignored, so # a stale or foreign path in an operator's shell can never decide which @@ -293,11 +293,21 @@ resolve_project() { } # fs_get NAME FOLDER -> value on stdout (never logged); non-zero when absent. +has_infisical_service_token() { + # Same shapes as scripts/install-release-secrets-tooling.sh (st.*.*): the + # current three-segment token and the legacy four-segment one. + [[ "${INFISICAL_TOKEN:-}" =~ ^st\.[^[:space:].]+(\.[^[:space:].]+)+$ ]] +} + fs_get() { local v bin="$FLEET_SECRETS_BIN" + has_infisical_service_token || return 1 [[ -x "$bin" ]] || bin="$(command -v fleet-secrets 2>/dev/null || true)" [[ -n "$bin" && -x "$bin" ]] || return 1 - v="$("$bin" get "$1" --path "$2" 2>/dev/null /dev/null /dev/null 2>&1 && return 0 return 1 @@ -605,11 +616,15 @@ load_sentry_auth() { # The reader's exit status is captured on its own: in a pipeline the # status would be the one of the last stage, so a failed read would look # like a successful read of an empty secret. - if ! raw="$(fleet-secrets get SENTRY_AUTH_TOKEN_FULLSCOPE 2>/dev/null)"; then + if ! raw="$(fs_get SENTRY_AUTH_TOKEN_FULLSCOPE / 2>/dev/null)"; then SENTRY_TOKEN_REASON="SENTRY_AUTH_TOKEN_FULLSCOPE could not be read from fleet-secrets" return 1 fi token="$(printf '%s' "$raw" | tr -d '\r')" + elif [[ -z "$token" ]] && { [[ -x "${FLEET_SECRETS_BIN:-}" ]] || command -v fleet-secrets &>/dev/null; }; then + # The reason is only for the case that ends without a token: a CodeCaps + # token in the slot wins and leaves the reason empty (PR #357 review). + SENTRY_TOKEN_REASON="an explicit Infisical service token is required; machine identity is disabled for CodeCaps automation" fi # Nothing better turned up, so the DSN in the CodeCaps slot is the answer, # and the case below refuses it by name. @@ -1088,8 +1103,8 @@ asc_latest_marketing_patch() { logerr "asc-patch: node not on PATH; cannot verify against App Store Connect" return 1 fi - if [[ -z "${ASC_KEY_ID:-}" && -z "${APPLE_API_KEY_ID:-}" && ! -x "$FLEET_SECRETS_BIN" ]] && ! command -v fleet-secrets >/dev/null 2>&1; then - logerr "asc-patch: no ASC_* in env and no fleet-secrets; cannot verify against App Store Connect" + if ! asc_credential_available; then + logerr "asc-patch: no ASC credential or explicit Infisical service token; cannot verify against App Store Connect" return 1 fi set +e @@ -1148,8 +1163,8 @@ asc_build_floor() { logerr "asc-floor: node not on PATH; cannot verify against App Store Connect" return 1 fi - if [[ -z "${ASC_KEY_ID:-}" && -z "${APPLE_API_KEY_ID:-}" && ! -x "$FLEET_SECRETS_BIN" ]] && ! command -v fleet-secrets >/dev/null 2>&1; then - logerr "asc-floor: no ASC_* in env and no fleet-secrets; cannot verify against App Store Connect" + if ! asc_credential_available; then + logerr "asc-floor: no ASC credential or explicit Infisical service token; cannot verify against App Store Connect" return 1 fi errfile="$(mktemp "${TMPDIR:-/tmp}/ios-fleet-floor.XXXXXX" 2>/dev/null || printf '')" diff --git a/scripts/ios-fleet/test-asc-credentials.mjs b/scripts/ios-fleet/test-asc-credentials.mjs index 25c66ac4..95ec3e54 100644 --- a/scripts/ios-fleet/test-asc-credentials.mjs +++ b/scripts/ios-fleet/test-asc-credentials.mjs @@ -29,6 +29,8 @@ const ascPem = pem(); const otherPem = pem(); const fake = join(root, "fleet-secrets"); writeFileSync(fake, `#!/usr/bin/env node +if (!/^st\\.[^.\\s]+\\.[^.\\s]+$/.test(process.env.INFISICAL_TOKEN || "")) process.exit(9); +if (process.env.INFISICAL_CLIENT_ID || process.env.INFISICAL_CLIENT_SECRET || process.env.INFISICAL_MACHINE_IDENTITY_ID) process.exit(10); const [, , verb, name, , folder] = process.argv; const table = { "/asc:ASC_KEY_ID": "ASCKEY0001", @@ -52,7 +54,7 @@ function run(env) { }); server.listen(0, "127.0.0.1", () => { const url = `http://127.0.0.1:${server.address().port}/v1/apps`; - const base = { PATH: process.env.PATH, HOME: home, FLEET_SECRETS: fake }; + const base = { PATH: process.env.PATH, HOME: home, FLEET_SECRETS: fake, INFISICAL_TOKEN: "st.synthetic-id.synthetic-secret" }; const child = spawn(process.execPath, [script, "GET", url], { env: { ...base, ...env }, stdio: ["ignore", "pipe", "pipe"] }); child.stdout.resume(); child.stderr.resume(); @@ -79,6 +81,12 @@ test("nothing in the environment: id, issuer and key all come from /asc", async assert.equal(r.iss, "issuer-from-asc"); }); +test("Infisical fallback fails closed without an explicit service token", async () => { + const r = await run({ INFISICAL_TOKEN: "" }); + assert.notEqual(r.code, 0); + assert.equal(r.kid, null); +}); + test("an env key id equal to the /asc one is served from /asc", async () => { const r = await run({ ASC_KEY_ID: "ASCKEY0001" }); assert.equal(r.code, 0); diff --git a/scripts/ios-fleet/test-asc-credentials.sh b/scripts/ios-fleet/test-asc-credentials.sh index 1be22b2c..e8ff2603 100755 --- a/scripts/ios-fleet/test-asc-credentials.sh +++ b/scripts/ios-fleet/test-asc-credentials.sh @@ -21,6 +21,7 @@ trap 'HOME="$real_home" rm -rf "$tmp"' EXIT export HOME="${tmp}/home" export TMPDIR="${tmp}/tmp" mkdir -p "$HOME" "$TMPDIR" +export INFISICAL_TOKEN="st.synthetic-id.synthetic-secret" fail() { echo "FAIL: $*" >&2; exit 1; } @@ -34,16 +35,18 @@ gen_pem > "${tmp}/other.p8" chmod 600 "${tmp}/asc.p8" "${tmp}/other.p8" # Fake fleet-secrets: prints synthetic values, records the folders it was asked for. -cat > "${tmp}/fleet-secrets" <<'FAKE' +cat > "${tmp}/fleet-secrets" <> "${FAKE_LOG}" -case "${folder}:${name}" in +[[ "\${INFISICAL_TOKEN:-}" =~ ^st\.[^[:space:].]+\.[^[:space:].]+$ ]] || exit 9 +[[ -z "\${INFISICAL_CLIENT_ID:-}\${INFISICAL_CLIENT_SECRET:-}\${INFISICAL_MACHINE_IDENTITY_ID:-}" ]] || exit 10 +[[ "\$1" == get ]] || exit 2 +name="\$2"; folder="\$4" +echo "\${name} \${folder}" >> "${tmp}/fake.log" +case "\${folder}:\${name}" in /asc:ASC_KEY_ID) printf 'ABCDE12345\n' ;; /asc:ASC_ISSUER_ID) printf 'issuer-synthetic\n' ;; - /asc:ASC_KEY_P8) cat "${FAKE_ASC_PEM}" ;; - /authkey-otherkey01-p8:AUTHKEY_OTHERKEY01) cat "${FAKE_OTHER_PEM}" ;; + /asc:ASC_KEY_P8) cat "${tmp}/asc.p8" ;; + /authkey-otherkey01-p8:AUTHKEY_OTHERKEY01) cat "${tmp}/other.p8" ;; *) exit 3 ;; esac FAKE @@ -55,7 +58,7 @@ export FAKE_OTHER_PEM="${tmp}/other.p8" extract() { awk ' - /^fs_get\(\) \{/ || /^load_secrets\(\) \{/ || /^cleanup_asc_tmp\(\) \{/ || /^expand_tilde\(\) \{/ || /^rejected_key_file\(\) \{/ || /^init_rejected_key_file\(\) \{/ || /^rejected_key_label\(\) \{/ || /^asc_rejected_key_label\(\) \{/ || /^asc_rejected_key_sources\(\) \{/ { grab = 1 } + /^has_infisical_service_token\(\) \{/ || /^fs_get\(\) \{/ || /^load_secrets\(\) \{/ || /^cleanup_asc_tmp\(\) \{/ || /^expand_tilde\(\) \{/ || /^rejected_key_file\(\) \{/ || /^init_rejected_key_file\(\) \{/ || /^rejected_key_label\(\) \{/ || /^asc_rejected_key_label\(\) \{/ || /^asc_rejected_key_sources\(\) \{/ { grab = 1 } grab { print } grab && /^\}/ { grab = 0 } ' "$script" diff --git a/scripts/ios-fleet/test-asc-key.test.mjs b/scripts/ios-fleet/test-asc-key.test.mjs index 38812e55..07047d87 100644 --- a/scripts/ios-fleet/test-asc-key.test.mjs +++ b/scripts/ios-fleet/test-asc-key.test.mjs @@ -148,6 +148,25 @@ test("the child's environment is an allowlist, not a copy of the parent's", () = } }); +test("only an explicit service token reaches Infisical automation children", () => { + const env = { + PATH: "/usr/bin", + HOME: "/tmp/home", + INFISICAL_TOKEN: "st.synthetic-id.synthetic-secret", + INFISICAL_CLIENT_ID: "machine-client-id", + INFISICAL_CLIENT_SECRET: "machine-client-secret", + INFISICAL_MACHINE_IDENTITY_ID: "machine-identity-id" + }; + const child = clientEnvironment(env); + assert.equal(child.INFISICAL_TOKEN, env.INFISICAL_TOKEN); + assert.equal(child.INFISICAL_CLIENT_ID, undefined); + assert.equal(child.INFISICAL_CLIENT_SECRET, undefined); + assert.equal(child.INFISICAL_MACHINE_IDENTITY_ID, undefined); + + const invalid = clientEnvironment({ ...env, INFISICAL_TOKEN: "not-a-service-token" }); + assert.equal(invalid.INFISICAL_TOKEN, undefined); +}); + test("the credential comes from the environment, and a path is not a source", async () => { const { credentialEnvironment } = await import(pathToFileURL(apnsScript).href); // The environment is an approved source. diff --git a/scripts/ios-fleet/test-expire-obsolete-codecaps-versions.mjs b/scripts/ios-fleet/test-expire-obsolete-codecaps-versions.mjs new file mode 100644 index 00000000..042c51ce --- /dev/null +++ b/scripts/ios-fleet/test-expire-obsolete-codecaps-versions.mjs @@ -0,0 +1,200 @@ +import assert from "node:assert/strict"; +import { generateKeyPairSync } from "node:crypto"; +import { spawn } from "node:child_process"; +import { createServer } from "node:http"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; + +const here = dirname(fileURLToPath(import.meta.url)); +const script = join(here, "expire-obsolete-codecaps-versions.mjs"); +const privateKey = generateKeyPairSync("ec", { namedCurve: "prime256v1" }).privateKey + .export({ type: "pkcs8", format: "pem" }); + +function run(base, bundle = "com.simplewithus.codecaps.ios", action = "--apply") { + return new Promise((resolve) => { + const child = spawn(process.execPath, [script, bundle, "0.1.0", action], { + env: { + ...process.env, + ASC_KEY_ID: "SYNTHETICKEYID1", + ASC_ISSUER_ID: "synthetic-issuer", + ASC_KEY_P8: privateKey, + APPLE_API_KEY_ID: "", + APPLE_API_ISSUER_ID: "", + APPLE_API_KEY_P8_BASE64: "", + ASC_API_BASE: base, + NO_PROXY: "127.0.0.1,localhost", + no_proxy: "127.0.0.1,localhost" + }, + stdio: ["ignore", "pipe", "pipe"] + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (data) => { stdout += data; }); + child.stderr.on("data", (data) => { stderr += data; }); + child.on("close", (code) => resolve({ code, stdout, stderr })); + }); +} + +async function withASC(state, action) { + const requests = []; + const server = createServer(async (request, response) => { + const url = new URL(request.url, "http://127.0.0.1"); + requests.push({ method: request.method, path: url.pathname }); + const send = (status, payload) => { + response.writeHead(status, { "Content-Type": "application/json" }); + response.end(payload === undefined ? "" : JSON.stringify(payload)); + }; + if (url.pathname === "/v1/apps") { + send(200, { data: [{ id: "codecaps-ios", type: "apps", attributes: { bundleId: "com.simplewithus.codecaps.ios" } }] }); + return; + } + if (url.pathname === "/v1/apps/codecaps-ios/appStoreVersions" && request.method === "GET") { + send(200, { data: state.versions.map((version) => ({ + id: version.id, + type: "appStoreVersions", + attributes: { versionString: version.version, appStoreState: version.state, platform: "IOS" } + })) }); + return; + } + if (url.pathname === "/v1/apps/codecaps-ios/reviewSubmissions" && request.method === "GET") { + send(200, { data: state.submissions.map((submission) => ({ + id: submission.id, + type: "reviewSubmissions", + attributes: { state: submission.state } + })) }); + return; + } + const reviewItems = /^\/v1\/reviewSubmissions\/([^/]+)\/items$/.exec(url.pathname); + if (reviewItems && request.method === "GET") { + const submission = state.submissions.find((item) => item.id === reviewItems[1]); + send(200, { data: (submission?.items || []).map((item) => ({ + id: item.id, + type: "reviewSubmissionItems", + attributes: { state: item.state }, + ...(item.versionId ? { relationships: { appStoreVersion: { data: { type: "appStoreVersions", id: item.versionId } } } } : {}) + })) }); + return; + } + if (url.pathname === "/v1/builds" && request.method === "GET") { + send(200, { + data: state.builds.map((build) => ({ + id: build.id, + type: "builds", + attributes: { version: build.build, expired: build.expired }, + relationships: { preReleaseVersion: { data: { type: "preReleaseVersions", id: build.trainId } } } + })), + included: state.trains.map((train) => ({ + id: train.id, + type: "preReleaseVersions", + attributes: { version: train.version, platform: "IOS" } + })) + }); + return; + } + const build = /^\/v1\/builds\/([^/]+)$/.exec(url.pathname); + if (build && request.method === "PATCH") { + let body = ""; + for await (const chunk of request) body += chunk; + const update = JSON.parse(body); + const row = state.builds.find((item) => item.id === build[1]); + row.expired = update.data.attributes.expired; + send(200, { data: { id: row.id, type: "builds", attributes: { expired: row.expired } } }); + return; + } + const version = /^\/v1\/appStoreVersions\/([^/]+)$/.exec(url.pathname); + if (version && request.method === "DELETE") { + state.versions = state.versions.filter((item) => item.id !== version[1]); + send(204); + return; + } + const reviewItem = /^\/v1\/reviewSubmissionItems\/([^/]+)$/.exec(url.pathname); + if (reviewItem && request.method === "DELETE") { + for (const submission of state.submissions) { + const item = submission.items.find((entry) => entry.id === reviewItem[1]); + if (item?.versionId) { + const appVersion = state.versions.find((entry) => entry.id === item.versionId); + if (appVersion) appVersion.state = "DEVELOPER_REJECTED"; + } + submission.items = submission.items.filter((entry) => entry.id !== reviewItem[1]); + } + send(204); + return; + } + send(404, { errors: [{ title: `unhandled ${request.method} ${url.pathname}` }] }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const result = await action(`http://127.0.0.1:${server.address().port}`, state, requests); + await new Promise((resolve) => server.close(resolve)); + return result; +} + +function fixture() { + return { + versions: [ + { id: "version-010", version: "0.1.0", state: "PREPARE_FOR_SUBMISSION" }, + { id: "version-old", version: "1.0.235", state: "PREPARE_FOR_SUBMISSION" }, + { id: "version-review", version: "1.0.236", state: "WAITING_FOR_REVIEW" } + ], + submissions: [{ + id: "submission-old", + state: "WAITING_FOR_REVIEW", + items: [ + { id: "review-item-old", versionId: "version-review", state: "READY_FOR_REVIEW" }, + { id: "review-item-other", state: "READY_FOR_REVIEW" } + ] + }], + trains: [ + { id: "train-010", version: "0.1.0" }, + { id: "train-old", version: "1.0.235" } + ], + builds: [ + { id: "build-010", build: "202611030900", trainId: "train-010", expired: false }, + { id: "build-old-active", build: "352", trainId: "train-old", expired: false }, + { id: "build-old-expired", build: "353", trainId: "train-old", expired: true } + ] + }; +} + +test("dry run reports only non-0.1.0 targets and changes nothing", async () => { + const state = fixture(); + const result = await withASC(state, async (base) => run(base, undefined, "--dry-run")); + assert.equal(result.code, 0, result.stderr); + assert.equal(JSON.parse(result.stdout).buildsToExpire.length, 1); + assert.deepEqual(JSON.parse(result.stdout).appStoreVersionsToDelete, [{ version: "1.0.235", state: "PREPARE_FOR_SUBMISSION" }]); + assert.deepEqual(JSON.parse(result.stdout).reviewItemsToRemove, [{ + version: "1.0.236", versionState: "WAITING_FOR_REVIEW", submissionState: "WAITING_FOR_REVIEW", itemState: "READY_FOR_REVIEW" + }]); + assert.equal(state.builds[1].expired, false); + assert.equal(state.versions.length, 3); + assert.equal(state.submissions[0].items.length, 2); +}); + +test("apply expires old builds, withdraws the old submission, and preserves every 0.1.0 build", async () => { + const state = fixture(); + const result = await withASC(state, async (base) => run(base)); + assert.equal(result.code, 0, result.stderr); + assert.equal(state.builds.find((item) => item.id === "build-010").expired, false); + assert.equal(state.builds.find((item) => item.id === "build-old-active").expired, true); + assert.equal(state.builds.find((item) => item.id === "build-old-expired").expired, true); + assert.deepEqual(state.versions.map((item) => item.version), ["0.1.0"]); + assert.deepEqual(JSON.parse(result.stdout).deletedAppStoreVersions.sort(), ["1.0.235", "1.0.236"]); + assert.deepEqual(JSON.parse(result.stdout).removedFromReview, [{ version: "1.0.236", submissionState: "WAITING_FOR_REVIEW" }]); + assert.deepEqual(state.submissions[0].items.map((item) => item.id), ["review-item-other"]); +}); + +test("a released old App Store version is reported and never deleted", async () => { + const state = fixture(); + state.versions.push({ id: "released-old", version: "0.0.9", state: "READY_FOR_DISTRIBUTION" }); + const result = await withASC(state, async (base) => run(base)); + assert.equal(result.code, 3); + assert.ok(state.versions.some((item) => item.id === "released-old")); + assert.ok(!state.versions.some((item) => item.id === "version-old")); +}); + +test("the command refuses another app bundle", async () => { + const state = fixture(); + const result = await withASC(state, async (base) => run(base, "com.example.other")); + assert.equal(result.code, 2); + assert.equal(state.versions.length, 3); +}); 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 f044b1fa..586d5aec 100644 --- a/scripts/ios-ship-workflow.test.mjs +++ b/scripts/ios-ship-workflow.test.mjs @@ -22,6 +22,19 @@ function read(rel) { return readFileSync(join(ROOT, rel), "utf8"); } +// Hand-written shape checks: this dependency-free script does not import zod, +// and a malformed apps.json must fail with a configuration error, not a TypeError. +function readFixedMarketingVersion(raw) { + assert.equal(raw !== null && typeof raw === "object" && !Array.isArray(raw), true, "apps config must be an object"); + const root = raw.apps; + assert.equal(root !== null && typeof root === "object" && !Array.isArray(root), true, "apps.apps must be an object"); + const codecaps = root.codecaps; + assert.equal(codecaps !== null && typeof codecaps === "object" && !Array.isArray(codecaps), true, "apps.apps.codecaps must be an object"); + const version = codecaps.fixedMarketingVersion; + assert.equal(typeof version, "string", "apps.apps.codecaps.fixedMarketingVersion must be a string"); + return version; +} + function withoutComments(text) { return text .split("\n") @@ -370,9 +383,10 @@ test("the ship job clears a stale archive lock restored from the ship-state cach assert.ok(beforeSave.includes(lockRm), "the archive lock is removed before the ship-state cache is saved"); }); -test("the marketing train is 1.0.N and release notes use the owner clock", () => { +test("the fixed marketing version is 0.1.0 and release notes use the owner clock", () => { const apps = JSON.parse(read("scripts/ios-fleet/apps.json")); - assert.match(apps.apps.codecaps.marketingVersionDefault, /^1\.0\.\d+$/); + assert.equal(readFixedMarketingVersion(apps), "0.1.0"); + assert.equal(apps.apps.codecaps.marketingVersionDefault, "0.1.0"); const src = read("scripts/ios-fleet/asc-api.mjs"); const fn = src.match(/function centralTimestamp[\s\S]*?\n}\n/)[0]; @@ -431,9 +445,17 @@ test("the iOS lane loads the Sentry API token, not the DSN", () => { function runSentryAuth(env, stub = null) { const dir = mkdtempSync(join(tmpdir(), "sentry-auth-")); try { + // The merged load_sentry_auth calls the reader helpers defined beside + // it, so the extracted block carries them too or the sourced function + // fails before the stub is ever asked (PR #357 review). + const helpers = ["has_infisical_service_token", "fs_get"].map((name) => { + const m = shipScript.match(new RegExp(`${name}\\(\\) \\{[\\s\\S]*?\\n\\}`)); + assert.ok(m, `ship-testflight.sh defines ${name}`); + return m[0]; + }); const fn = shipScript.match(/load_sentry_auth\(\) \{[\s\S]*?\n\}/); assert.ok(fn, "ship-testflight.sh defines load_sentry_auth"); - writeFileSync(join(dir, "fn.sh"), fn[0]); + writeFileSync(join(dir, "fn.sh"), [...helpers, fn[0]].join("\n")); if (stub) writeFileSync(join(dir, "fleet-secrets"), stub, { mode: 0o755 }); const out = execFileSync( "bash", @@ -442,7 +464,10 @@ function runSentryAuth(env, stub = null) { encoding: "utf8", // The stub directory is the only place a reader can come from, so the // test never reaches a real vault. - env: { PATH: `${dir}:/usr/bin:/bin`, DIR: dir, ...env }, + // FLEET_SECRETS_BIN pins the reader to the stub, so a host that has + // a real fleet-secrets on its PATH cannot answer instead (the tests + // must be hermetic on any machine). + env: { PATH: `${dir}:/usr/bin:/bin`, DIR: dir, FLEET_SECRETS_BIN: join(dir, "fleet-secrets"), ...env }, }, ); const field = (name) => (out.match(new RegExp(`^${name}=(.*)$`, "m")) || [])[1] ?? ""; @@ -460,7 +485,11 @@ const FLEET_SECRETS_STUB = [ ].join("\n"); test("a DSN in the CodeCaps token slot falls through to fleet-secrets", () => { - const r = runSentryAuth({ SENTRY_AUTH_TOKEN: "https://key@o1.ingest.us.sentry.io/2" }, FLEET_SECRETS_STUB); + // The service-token guard reads the run's environment before the stub + // reader is asked, so the probe carries a token (PR #357 review). + const r = runSentryAuth( + { SENTRY_AUTH_TOKEN: "https://key@o1.ingest.us.sentry.io/2", INFISICAL_TOKEN: "st.test.service" }, + FLEET_SECRETS_STUB); assert.equal(r.rc, "0"); assert.equal(r.token, "synthetic-fullscope-token"); assert.equal(r.reason, ""); @@ -474,7 +503,9 @@ test("a DSN in the CodeCaps token slot is refused when there is no reader", () = }); test("a CodeCaps token that is not a DSN still wins over fleet-secrets", () => { - const r = runSentryAuth({ SENTRY_AUTH_TOKEN: "synthetic-codecaps-token" }, FLEET_SECRETS_STUB); + const r = runSentryAuth( + { SENTRY_AUTH_TOKEN: "synthetic-codecaps-token", INFISICAL_TOKEN: "st.test.service" }, + FLEET_SECRETS_STUB); assert.equal(r.rc, "0"); assert.equal(r.token, "synthetic-codecaps-token"); assert.equal(r.reason, ""); 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/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"