diff --git a/Sources/CodeCaps/SMSAlertController.swift b/Sources/CodeCaps/SMSAlertController.swift index 876cc297..0d7465f0 100644 --- a/Sources/CodeCaps/SMSAlertController.swift +++ b/Sources/CodeCaps/SMSAlertController.swift @@ -10,10 +10,48 @@ struct SMSCredentialAccess { var clear: () async throws -> Void var reauthorize: () async -> TwilioSMSCredentials? - static let live = Self(load: { await TwilioCredentialStore.shared.load() }, + static let live = Self(load: { await SMSCredentialAccess.resolvedLiveCredentials() }, save: { try await TwilioCredentialStore.shared.save($0) }, clear: { try await TwilioCredentialStore.shared.clear() }, - reauthorize: { await TwilioCredentialStore.shared.readAllowingInteraction() }) + reauthorize: { + if let resolved = await SMSCredentialAccess.resolvedLiveCredentials() { + return resolved + } + return await TwilioCredentialStore.shared.readAllowingInteraction() + }) + + /// An operator-provided Twilio API key secret outranks the Keychain setup + /// record: the process environment first, then the app's Infisical + /// project, and the Keychain record only last. An ordinary service + /// credential must not make the Keychain its source of truth (Kody + /// review, PR #367). The Keychain record still supplies the rest of the + /// configuration the secret is used with, and `save`/`clear` keep + /// handling explicitly entered values. + nonisolated static func resolvedCredentials(stored: TwilioSMSCredentials?, + environment: [String: String], + infisicalSecret: String?) -> TwilioSMSCredentials? { + func splicing(_ secret: String) -> TwilioSMSCredentials { + let configuration = stored?.configuration ?? TwilioSMSConfiguration( + accountSID: environment["TWILIO_ACCOUNT_SID"] ?? "", + apiKeySID: environment["TWILIO_API_KEY_SID"] ?? "", + messagingServiceSID: environment["TWILIO_MESSAGING_SERVICE_SID"] ?? "", + recipient: environment["TWILIO_RECIPIENT"] ?? "") + return TwilioSMSCredentials(configuration: configuration, apiKeySecret: secret) + } + let envSecret = environment["TWILIO_API_KEY_SECRET"]? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !envSecret.isEmpty { return splicing(envSecret) } + if let secret = infisicalSecret?.trimmingCharacters(in: .whitespacesAndNewlines), + !secret.isEmpty { return splicing(secret) } + return stored + } + + private static func resolvedLiveCredentials() async -> TwilioSMSCredentials? { + let stored = await TwilioCredentialStore.shared.load() + return resolvedCredentials(stored: stored, + environment: ProcessInfo.processInfo.environment, + infisicalSecret: InfisicalSettings.shared.value(for: "TWILIO_API_KEY_SECRET")) + } } @MainActor diff --git a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift index 0c7ae183..a513a55a 100644 --- a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift +++ b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift @@ -68,7 +68,13 @@ public struct LocalQuotaReaderRegistry: Sendable { var issues: [String: String] = [:] var consentNeeded: Set = [] for (_, result) in results { - windows.append(contentsOf: result.windows) + // Two registrations can surface the same QuotaWindow (grok-bot and + // gbu both declare providerKey "grok-bot"); a duplicate row would + // reach every downstream surface twice, so only new windows are + // appended (Kody review, PR #367). + for window in result.windows where !windows.contains(window) { + windows.append(window) + } issues.merge(result.issues) { _, next in next } consentNeeded.formUnion(result.consentNeeded) } diff --git a/Sources/QuotaCore/QuotaWindowVocabulary.swift b/Sources/QuotaCore/QuotaWindowVocabulary.swift index 0224f277..2c3516f1 100644 --- a/Sources/QuotaCore/QuotaWindowVocabulary.swift +++ b/Sources/QuotaCore/QuotaWindowVocabulary.swift @@ -941,16 +941,24 @@ public enum QuotaCapRule { || id.hasPrefix("openai:additional:") || id.hasPrefix("openai:code-review:") || id.hasPrefix("additional:") || id.hasPrefix("code-review:") } + // Exact tokens, not substrings: "Argonaut" or "fable-era" is not a + // per-model limit (Kody review, PR #367). + func tokens(_ raw: String) -> Set { + // A hyphen or underscore stays inside a token: a model id like + // "fable-era" is one model, not the Fable limit; structural + // separators (":", "/", whitespace) are what split the fields. + Set(raw.lowercased() + .split(whereSeparator: { $0.isWhitespace || ":·/|,;".contains($0) }) + .map(String.init)) + } if providerKey == "google-antigravity" { - if let modelId = modelId?.lowercased(), modelId.contains("argon") { return true } - if let modelType = modelType?.lowercased(), modelType.contains("argon") { return true } - if label.localizedCaseInsensitiveContains("argon") { return true } - return false + if let modelId, !tokens(modelId).isDisjoint(with: ["argon"]) { return true } + if let modelType, !tokens(modelType).isDisjoint(with: ["argon"]) { return true } + return !tokens(label).isDisjoint(with: ["argon"]) } if providerKey == "anthropic" { if let model = modelId?.lowercased(), !model.isEmpty { return true } - let lower = label.lowercased() - return lower.contains("fable") || lower.contains("sonnet") || lower.contains("opus") || lower.contains("haiku") + return !tokens(label).isDisjoint(with: ["fable", "sonnet", "opus", "haiku"]) } return false } diff --git a/Sources/QuotaCore/ResetAlarmTracker.swift b/Sources/QuotaCore/ResetAlarmTracker.swift index be0a0812..329bf514 100644 --- a/Sources/QuotaCore/ResetAlarmTracker.swift +++ b/Sources/QuotaCore/ResetAlarmTracker.swift @@ -502,13 +502,21 @@ public struct ResetAlarmTracker: Sendable { if let reported = observation.resetAt { let jump = reported.timeIntervalSince(previousReset) // A deadline correction needs a substantial quota rise or an elapsed full cadence. + // A roll-immediately provider restarts each period when the last + // one ends, so a Mac asleep through several periods wakes to an + // end that moved by a whole multiple of the cadence. Accept any + // whole number of periods, not exactly one. A wait-for-usage + // provider's end does not move on a schedule, so it never matches + // this shape; cadence alone is never proof. let advancedFullCadence = window.periodSeconds.map { period in - // Calendar months range from 28 to 31 days; fixed cadences use drift tolerance. let tolerance = ResetAlarmPolicy.resetDriftTolerance + let periods = (jump / period).rounded() + guard periods >= 1 else { return false } + // Calendar months range from 28 to 31 days; fixed cadences use drift tolerance. if (28 * 86_400...31 * 86_400).contains(period) { - return jump >= 28 * 86_400 - tolerance && jump <= 31 * 86_400 + tolerance + return jump >= periods * 28 * 86_400 - tolerance && jump <= periods * 31 * 86_400 + tolerance } - return abs(jump - period) <= tolerance + return abs(jump - periods * 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 @@ -521,12 +529,15 @@ public struct ResetAlarmTracker: Sendable { 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. + // Same whole-multiple rule as advancedFullCadence: a calendar-month + // window accepts a 28-to-31-day start advance per period; + // fixed cadences use drift tolerance. + let periods = (advance / period).rounded() + guard periods >= 1 else { return true } if (28 * 86_400...31 * 86_400).contains(period) { - return advance >= 28 * 86_400 - tolerance && advance <= 31 * 86_400 + tolerance + return advance >= periods * 28 * 86_400 - tolerance && advance <= periods * 31 * 86_400 + tolerance } - return abs(advance - period) <= tolerance + return abs(advance - periods * period) <= tolerance }() let required = hasPassed ? ResetAlarmPolicy.resetDriftTolerance diff --git a/Sources/QuotaCore/WidgetPlatformDisplay.swift b/Sources/QuotaCore/WidgetPlatformDisplay.swift index e893da5e..a44bf6f9 100644 --- a/Sources/QuotaCore/WidgetPlatformDisplay.swift +++ b/Sources/QuotaCore/WidgetPlatformDisplay.swift @@ -203,10 +203,23 @@ public enum QuotaCardProjection { } /// Only these model limits have a separate detail in the companion. + /// The identity fields are tokenized on non-alphanumeric characters + /// and matched exactly, so a model id like "Fabled" or "fable-era" + /// cannot be classified as the Fable limit by a substring accident + /// (Kody review, PR #367). 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" } + let tokens = Set( + [id, label, modelId ?? "", modelType ?? ""] + .joined(separator: " ") + .lowercased() + // A hyphen or underscore stays inside a token: a + // model id like "fable-era" is one model, not the Fable + // limit; structural separators (":", "/", whitespace) + // are what split the fields. + .split(whereSeparator: { $0.isWhitespace || ":·/|,;".contains($0) }) + .map(String.init)) + if providerKey == "anthropic", tokens.contains("fable") { return "Fable" } + if providerKey == "google-antigravity", tokens.contains("argon") { return "Argon" } return nil } @@ -229,8 +242,11 @@ public enum QuotaCardProjection { if QuotaWindowVocabulary.isExtraAllowance(providerKey: providerKey, label: label, windowToken: window) { return "extra:" + cadence } - // Primary model names describe observations of the same plan allowance. - return cadence + // Primary model names describe observations of the same plan + // allowance. The provider prefixes the bare-cadence fallback so + // distinct providers cannot collapse into one grouping bucket + // (Kody review, PR #367). + return providerKey.lowercased() + ":" + cadence } public var displayLabel: String { diff --git a/Tests/CodeCapsTests/TwilioCredentialStoreTests.swift b/Tests/CodeCapsTests/TwilioCredentialStoreTests.swift index e22f7c54..9a0309bf 100644 --- a/Tests/CodeCapsTests/TwilioCredentialStoreTests.swift +++ b/Tests/CodeCapsTests/TwilioCredentialStoreTests.swift @@ -35,6 +35,36 @@ final class TwilioCredentialStoreTests: XCTestCase { XCTAssertFalse(TokenStore.ownServices.contains(development)) } + /// The Twilio API key secret resolves env-first, then Infisical, and the + /// Keychain record only last: an ordinary service credential must not + /// make the Keychain its source of truth (Kody review, PR #367). + func testSecretResolutionOrderIsEnvironmentThenInfisicalThenKeychain() { + let stored = TwilioSMSCredentials( + configuration: TwilioSMSConfiguration(accountSID: "AC123", apiKeySID: "SK123", + messagingServiceSID: "MG123", recipient: "+15551234567"), + apiKeySecret: "keychain-secret") + let envCredentials = SMSCredentialAccess.resolvedCredentials( + stored: stored, + environment: ["TWILIO_API_KEY_SECRET": "env-secret"], + infisicalSecret: "infisical-secret") + XCTAssertEqual(envCredentials?.apiKeySecret, "env-secret", "the environment wins") + let infisicalCredentials = SMSCredentialAccess.resolvedCredentials( + stored: stored, environment: [:], infisicalSecret: "infisical-secret") + XCTAssertEqual(infisicalCredentials?.apiKeySecret, "infisical-secret", "Infisical outranks the Keychain") + let keychainCredentials = SMSCredentialAccess.resolvedCredentials( + stored: stored, environment: [:], infisicalSecret: nil) + XCTAssertEqual(keychainCredentials?.apiKeySecret, "keychain-secret", + "with no operator secret the Keychain record still answers") + // A stored record supplies the configuration an operator secret is used with. + XCTAssertEqual(envCredentials?.configuration, stored.configuration) + XCTAssertNil(SMSCredentialAccess.resolvedCredentials(stored: nil, environment: [:], infisicalSecret: nil), + "no secret anywhere means no credentials") + // An empty or blank secret is not a secret. + XCTAssertEqual(SMSCredentialAccess.resolvedCredentials( + stored: stored, environment: ["TWILIO_API_KEY_SECRET": " "], + infisicalSecret: nil)?.apiKeySecret, "keychain-secret") + } + func testInvalidSetupNeverTouchesKeychain() async { let fixture = TwilioKeychainFixture() let store = TwilioCredentialStore(calls: fixture.calls, bundleIdentifier: "com.example.CodeCaps.test") diff --git a/Tests/Fixtures/WidgetUIProbe.swift b/Tests/Fixtures/WidgetUIProbe.swift index 9423b79f..90547e47 100644 --- a/Tests/Fixtures/WidgetUIProbe.swift +++ b/Tests/Fixtures/WidgetUIProbe.swift @@ -30,18 +30,36 @@ import AppIntents ] 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"]) + // The producer's "no reading yet" copy of the weekly allowance keeps its + // own row (a distinct wire series), the "Plan Details" caption row is + // dropped, and the Fable detail sits beside the plan windows. + precondition(claude.primaryWindows.count == 3 && 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) + // The supplementary video daily never takes a bar from the plan's own + // windows: the pair stays the 5-hour and weekly coding windows (owner + // 2026-11-06: "Widget says 1d instead of 7d"). + precondition(minimax.dualWindows()?.window1.id == "minimax:5h") + precondition(minimax.dualWindows()?.window2.id == "minimax:7d") let gemini = parsed.first { $0.id == "antigravity-gemini" }! - precondition(gemini.primaryWindows.map(\.remainingPercent) == [63, 1]) + // The widget's pool rule keeps the freshest copy of each period, unlike + // the phone's canonical-row preference: both copies here carry no + // observation stamp, so the payload's first row wins the five-hour slot. + precondition(gemini.primaryWindows.map(\.remainingPercent) == [7, 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) + precondition(copilot.title == "GitHub Copilot") + // The headline answers the shared cap rule over all windows, so the + // mirror copy reading zero spends it even while this Mac's own copy + // reports 100; the own copy is carried as a primary window beside it. + precondition(copilot.remainingPercent == 0) + // This Mac's own copy and the mirror copy are distinct wire series; the + // own copy is present and the platform carries no detail rows. + precondition(copilot.primaryWindows.contains { $0.id == "local-mac:github-copilot" } + && !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) @@ -51,7 +69,7 @@ import AppIntents 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"]) + precondition(phone.isExpandable && phone.cardDetailWindows(scope:.allSources).map(\.window.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) diff --git a/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift b/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift index d0245aba..c5cf2783 100644 --- a/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift +++ b/Tests/QuotaCoreTests/LocalQuotaReaderRegistryTests.swift @@ -107,4 +107,27 @@ final class LocalQuotaReaderRegistryTests: XCTestCase { XCTAssertTrue(result.windows.isEmpty) } + /// Two registrations can surface the same QuotaWindow (grok-bot and gbu + /// both declare providerKey "grok-bot"); the merged snapshot must carry + /// the row once, not once per reader (Kody review, PR #367). + func testIdenticalWindowsFromTwoReadersArePublishedOnce() async { + func makeWindow(percent: Double) -> QuotaWindow { + QuotaWindow(id: "grok:weekly", provider: "grok", providerKey: "grok-bot", + label: "weekly", remainingPercent: percent, + occurredAt: "2026-11-06T12:00:00Z") + } + let window = makeWindow(percent: 42) + let registry = LocalQuotaReaderRegistry(registrations: [ + LocalQuotaReaderRegistration(id: "grok-bot", label: "Grok Bot") { + RegistryFakeReader(result: LocalQuotaResult(windows: [window, makeWindow(percent: 7)])) + }, + LocalQuotaReaderRegistration(id: "gbu", label: "Grok Build Usage") { + RegistryFakeReader(result: LocalQuotaResult(windows: [window])) + }, + ]) + let result = await registry.read(preferences: .init()) + XCTAssertEqual(result.windows.count, 2, "an identical window from a second reader must be dropped") + XCTAssertEqual(result.windows.filter { $0.remainingPercent == 42 }.count, 1) + } + } diff --git a/Tests/QuotaCoreTests/QuotaCardProjectionTests.swift b/Tests/QuotaCoreTests/QuotaCardProjectionTests.swift index f92eac9d..746e1646 100644 --- a/Tests/QuotaCoreTests/QuotaCardProjectionTests.swift +++ b/Tests/QuotaCoreTests/QuotaCardProjectionTests.swift @@ -91,4 +91,30 @@ final class QuotaCardProjectionTests: XCTestCase { row("raw", "google-antigravity", "7d", 51)] XCTAssertEqual(QuotaCardProjection.selectedPoolIndices(in: rows, poolKey: "gemini", now: now), [1]) } + + /// The bare-cadence fallback in `allowanceKey` carries the provider, so + /// two providers' identical cadences never collapse into one grouping + /// bucket (Kody review, PR #367). + func testBareCadenceAllowanceKeyIsProviderPrefixed() { + let grok = row("grok-weekly", "grok-bot", "7d", 50) + let cursor = row("cursor-weekly", "cursor", "7d", 90) + XCTAssertNotEqual(grok.allowanceKey, cursor.allowanceKey, + "two providers' weekly windows must not share an allowance key") + XCTAssertTrue(grok.allowanceKey.hasPrefix("grok-bot:")) + // Within one provider the primary rows still group together. + XCTAssertEqual(grok.allowanceKey, + row("grok-weekly-copy", "grok-bot", "7d", 51).allowanceKey) + } + + /// Model classification is by exact token: a model id that merely + /// contains the word is not the Fable limit (Kody review, PR #367). + func testFableDetectionIsExactTokenNotSubstring() { + XCTAssertNotNil(row("claude:fable", "anthropic", "7d", 0, model: "Fable").detailName) + XCTAssertNil(row("claude:fable-era", "anthropic", "7d", 0, model: "Fable-era").detailName, + "fable-era is its own model, not the Fable limit") + XCTAssertNil(row("claude:fabled", "anthropic", "7d", 0, model: "Fabled").detailName) + XCTAssertNil(row("antigravity:argonaut", "google-antigravity", "5h", 0, model: "Argonaut").detailName, + "Argonaut is not the Argon limit") + XCTAssertNotNil(row("gemini:argon", "google-antigravity", "5h", 0, model: "Argon").detailName) + } } diff --git a/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift b/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift index 62e5d6dc..e87946b4 100644 --- a/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift +++ b/Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift @@ -1065,6 +1065,90 @@ extension ResetAlarmTrackerTests { } } +// MARK: - Missed periods while the Mac was asleep +// +// Owner, 2026-11-06: a roll-immediately provider restarts each period when +// the last one ends, so a Mac asleep through several periods wakes to an end +// that moved by a whole multiple of the cadence. Matching exactly one period +// missed every one of those rollovers. A wait-for-usage provider's end does +// not move on a schedule, so nothing here treats elapsed cadence alone as +// proof of a reset: the vendor's reported times must have moved. + +extension ResetAlarmTrackerTests { + /// Two whole 5-hour periods passed while the Mac was asleep; the vendor's + /// reported end moved by exactly two cadences. This must alert. + func testAWakeAfterTwoMissedPeriodsAlerts() { + var tracker = ResetAlarmTracker() + let end = t0 + 5 * self.hour + _ = tracker.process(courtesyWindow(resetAt: end, at: t0, remaining: 40), now: t0) + + let wake = t0.addingTimeInterval(11 * self.hour) + let rolled = end.addingTimeInterval(2 * 5 * self.hour) + let events = tracker.process(courtesyWindow(resetAt: rolled, at: wake, remaining: 100), now: wake) + + XCTAssertEqual(events.count, 1, "a rollover of two whole periods while asleep produced no alert") + } + + /// A weekly window that rolled three times while the Mac was away: the + /// reported end advanced by exactly three whole periods. + func testAWakeAfterThreeMissedWeeksAlerts() { + var tracker = ResetAlarmTracker() + let end = t0 + 7 * self.day + _ = tracker.process([reading("7d", period: 7 * day, resetAt: end, remaining: 30, observedAt: t0)], now: t0) + + let wake = t0.addingTimeInterval(23 * self.day) + let rolled = end.addingTimeInterval(3 * 7 * self.day) + let events = tracker.process([reading("7d", period: 7 * day, resetAt: rolled, remaining: 100, observedAt: wake)], now: wake) + + XCTAssertEqual(events.count, 1, "a rollover of three whole weeks while away produced no alert") + } + + /// The wait-for-usage provider shape, owner 2026-11-06: "some wait until + /// there is some usage". The Mac sleeps through what would have been two + /// periods, but the vendor's end has not moved and the quota has not + /// risen - no usage, no new period. Nothing may alert: elapsed cadence + /// alone is not a reset. + func testAWaitForUsageProviderSilentThroughTheGapDoesNotAlert() { + var tracker = ResetAlarmTracker() + let end = t0 + 7 * self.day + _ = tracker.process(courtesyWindow(resetAt: end, at: t0, remaining: 40), now: t0) + + let wake = t0.addingTimeInterval(16 * self.day) + let events = tracker.process(courtesyWindow(resetAt: end, at: wake, remaining: 40), now: wake) + + XCTAssertTrue(events.isEmpty, + "an unmoved end with no quota rise after a long sleep was reported as a reset") + } + + /// The same provider after usage resumes: the quota is back at full while + /// the end stays where it was, which the restore-shape rules already + /// alert. The missed-periods rule must not double-report it. + func testAWaitForUsageProviderRestoreAlertsOnceNotTwice() { + var tracker = ResetAlarmTracker() + let end = t0 + 7 * self.day + _ = tracker.process(courtesyWindow(resetAt: end, at: t0, remaining: 12), now: t0) + + let wake = t0.addingTimeInterval(16 * self.day) + let events = tracker.process(courtesyWindow(resetAt: end, at: wake, remaining: 100), now: wake) + + XCTAssertEqual(events.count, 1, "a post-usage restore after a long sleep alerted zero or multiple times") + } + + /// The false-positive side: an end that moved by one and a half periods is + /// not a whole-period rollover shape, so this rule must not claim it. + func testAFractionalAdvanceIsNotClaimedAsMissedPeriods() { + var tracker = ResetAlarmTracker() + let end = t0 + 5 * self.hour + _ = tracker.process(courtesyWindow(resetAt: end, at: t0, remaining: 40), now: t0) + + let wake = t0.addingTimeInterval(11 * self.hour) + let drifted = end.addingTimeInterval(5 * self.hour + 90 * 60) + XCTAssertTrue( + tracker.process(courtesyWindow(resetAt: drifted, at: wake, remaining: 40), now: wake).isEmpty, + "a 1.5-period end drift with no quota rise was reported as a reset") + } +} + // MARK: - Courtesy resets // // Owner request, 2026-10-08: "can't the app tell if usage suddenly jumps to diff --git a/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift b/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift index bd1948c0..6ea25cc9 100644 --- a/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift +++ b/ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift @@ -602,7 +602,13 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { // a plan meter: the cap rule skips it and the headline excludes it, // so drawing it as a bar put an empty meter beside a headline that // said otherwise (kody, PR #376). - windows.filter { !$0.isScopedPoolAllowance }.map { primary in + // A per-model detail (Fable) is a card detail row, not a card meter, + // and a wire plan caption ("Plan" with no reading) is not an + // allowance at all: neither takes a short/long slot or the headline + // (native probe, PR #367). + windows.filter { !$0.isScopedPoolAllowance && !$0.isSubModelLimit + && !(($0.label == "Plan" || $0.cadence == "Plan") && $0.remainingPercent == nil) } + .map { primary in let key = Self.allowanceKey(for: primary) // This iPhone: only this device's primary windows. All Sources: fold // in mirror feeds so Mac/fleet readings can win when fresher. @@ -628,6 +634,13 @@ public struct CompanionQuotaItem: Identifiable, Codable, Equatable { cardWindowRows(scope: scope, now: now).map(\.window) } + /// The per-model detail rows beside the plan (Anthropic's Fable limit, + /// Antigravity's Argon limit): the card's own sub-model identity marks + /// them, exactly as the widget's carried flag does. + public func cardDetailWindows(scope: CompanionSourceScope, now: Date = Date()) -> [CardWindow] { + windows.filter { $0.isSubModelLimit }.map { CardWindow(window: $0, updatedLabel: nil) } + } + public func cardShortWindow(scope: CompanionSourceScope, now: Date = Date()) -> CardWindow? { let resolved = cardWindowRows(scope: scope, now: now).filter { !$0.window.isSubModelLimit } if providerKey == "muse-assist" { diff --git a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift index 7123ac98..f0e3729e 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift @@ -27,6 +27,12 @@ public struct WidgetWindowItem: Identifiable, Equatable, Sendable { /// the video tokens - a "Hailuo" daily arrives here as "1d window" /// (Kody review, PR #367). public let isSupplementaryVideoQuota: Bool + /// True when the window is a per-model detail beside the plan (Anthropic's + /// Fable, Antigravity's Argon) rather than one of the plan's own meters. + /// The identity is captured at construction from the wire fields, for the + /// same reason the video identity is: the display label rewrite happens + /// here, after the question has to be answered. + public let isModelDetail: Bool /// Short distinguishing label for a bar when two bars share one cadence /// token (e.g. two "7d" bars). "Free weekly limit" reads "weekly", /// "Additional tokens" reads "additional". Empty when the row needs no @@ -56,6 +62,7 @@ public struct WidgetWindowItem: Identifiable, Equatable, Sendable { barQualifier: String = "", isExtraAllowance: Bool = false, isSupplementaryVideoQuota: Bool = false, + isModelDetail: Bool = false, absoluteRemaining: Double? = nil ) { self.id = id @@ -70,6 +77,7 @@ public struct WidgetWindowItem: Identifiable, Equatable, Sendable { self.barQualifier = barQualifier self.isExtraAllowance = isExtraAllowance self.isSupplementaryVideoQuota = isSupplementaryVideoQuota + self.isModelDetail = isModelDetail } /// Whether the reading is old enough that the widget says when it was @@ -164,6 +172,7 @@ public struct WidgetWindowItem: Identifiable, Equatable, Sendable { barQualifier: qualifier, isExtraAllowance: isExtraAllowance, isSupplementaryVideoQuota: isSupplementaryVideoQuota, + isModelDetail: isModelDetail, absoluteRemaining: absoluteRemaining ) } @@ -208,6 +217,22 @@ public struct WidgetPlatformItem: Identifiable, Equatable, Sendable { public let defaultWindowLabel: String? public let planMetadata: PlanMetadata? + /// The plan's own meters. Per-model details (Fable, Argon) and + /// supplementary video allowances sit beside the plan, not inside it, so + /// a detail view or a focus bar picks from these. + public var primaryWindows: [WidgetWindowItem] { + windows.filter { !$0.isModelDetail && !$0.isSupplementaryVideoQuota } + } + + /// The per-model detail windows beside the plan, in payload order. + public var detailWindows: [WidgetWindowItem] { + windows.filter { $0.isModelDetail } + } + + /// Whether a detail scope exists for this platform at all: a plan with + /// no per-model rows has nothing to expand into. + public var hasModelDetails: Bool { !detailWindows.isEmpty } + public init( id: String, providerKey: String, @@ -313,7 +338,9 @@ public struct WidgetPlatformItem: Identifiable, Equatable, Sendable { // pool never reports the subscription capped (Sentry review, PR // #369). A platform that reports ONLY video windows keeps them - // they are all it has. - let planWindows = windows.filter { !$0.isSupplementaryVideoQuota } + // A per-model detail (Argon, Fable) is beside the plan for the same + // reason: its own spent limit does not cap the subscription. + let planWindows = windows.filter { !$0.isSupplementaryVideoQuota && !$0.isModelDetail } let capPool = planWindows.isEmpty ? windows : planWindows return capPool .filter { $0.isFresh(now: now) || (WidgetPresentation.isAtCap(percent: $0.remainingPercent, isExhausted: $0.isExhausted) && $0.resetAt != nil && $0.resetAt! > now) } @@ -451,6 +478,8 @@ public enum WidgetPresentation { public static func displayPercent(percent: Double?, isMasked: Bool) -> String { if isMasked { return "n/a" } + // A non-finite figure is no figure: a NaN must not trap the + // integer conversion (native probe, PR #367). guard let percent, percent.isFinite else { return "—" } return "\(Int(min(100, max(0, percent)).rounded()))%" } @@ -971,6 +1000,14 @@ public enum WidgetPresentation { } for w in liveWindows { + // The wire's plan-metadata rows are captions, not allowances: a + // bare "Plan" or "Plan Details" row carries no reading, and if it + // were carried it would take a bar slot beside the plan's own + // meters (native probe, PR #367). + let trimmedLabel = w.label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !w.id.lowercased().hasSuffix(":plan-metadata"), + trimmedLabel != "plan details", + !(trimmedLabel == "plan" && w.remainingPercent == nil) else { continue } let parsedReset = parseDate(from: w.resetAt) let observed = parseDate(from: w.occurredAt) let cadence = formatCadence(w.label, window: w.window, resetAt: parsedReset) @@ -980,7 +1017,7 @@ public enum WidgetPresentation { // the word is the fallback for a window that reports no figure. let exhausted = QuotaCapRule.isExhausted(remainingPercent: pct, providerSaysExhausted: w.isExhausted ?? false) - let displayLabel = QuotaWindowVocabulary.windowLabel( + var displayLabel = QuotaWindowVocabulary.windowLabel( windowToken: w.window, existingLabel: w.label.isEmpty ? cadence : w.label, resetAt: parsedReset @@ -1007,6 +1044,16 @@ public enum WidgetPresentation { modelType: w.modelType, label: w.label ) + // The per-model detail identity is answered the same way, at + // construction, from the same wire fields; the detail row then + // carries its canonical " limit" display label. + let detailName = QuotaCardProjection.Reading( + id: w.id, providerKey: providerKey, label: w.label, window: w.window, + modelId: w.modelId, modelType: w.modelType).detailName + let isModelDetail = detailName != nil + if isModelDetail { + displayLabel = detailName! + " limit" + } let item = WidgetWindowItem( id: w.id, @@ -1019,6 +1066,7 @@ public enum WidgetPresentation { observedAt: observed, isExtraAllowance: isExtraAllowance, isSupplementaryVideoQuota: isSupplementaryVideo, + isModelDetail: isModelDetail, absoluteRemaining: w.absoluteRemaining ) @@ -1212,6 +1260,27 @@ public enum WidgetPresentation { )) } + // Sub-model limits (Argon) are details beside the pool, not pool + // meters: the pool rows stay the plan's own five-hour and weekly + // windows (native probe: gemini detailWindows == ["Argon limit"]). + for w in windows where !childWindows.contains(where: { $0.id == w.id }) { + let reading = QuotaCardProjection.Reading( + id: w.id, providerKey: "google-antigravity", label: w.label, window: w.window, + modelId: w.modelId, modelType: w.modelType) + guard let detail = reading.detailName else { continue } + childWindows.append(WidgetWindowItem( + id: w.id, + label: detail + " limit", + cadence: shortCadence(cadence: w.window ?? "", label: w.label), + remainingPercent: w.remainingPercent, + resetAt: parseDate(from: w.resetAt), + isExhausted: QuotaCapRule.isExhausted(remainingPercent: w.remainingPercent, + providerSaysExhausted: w.isExhausted ?? false), + observedAt: parseDate(from: w.occurredAt), + isModelDetail: true + )) + } + if let w = weeklyWin { let reset = parseDate(from: w.resetAt) childWindows.append(WidgetWindowItem( diff --git a/scripts/stage-asc-key.mjs b/scripts/stage-asc-key.mjs index 37486053..67644605 100644 --- a/scripts/stage-asc-key.mjs +++ b/scripts/stage-asc-key.mjs @@ -37,6 +37,7 @@ import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { isUnresolvedReference, maskValue, writeGithubEnvValue } from './infisical-fetch.mjs'; +import { fleetSecretsEnvironment, hasInfisicalServiceToken } from './ios-fleet/infisical-service-token.mjs'; const here = dirname(fileURLToPath(import.meta.url)); const STAGING_SCRIPT = join(here, 'ios-stage-asc-key.sh'); @@ -172,19 +173,25 @@ const READER_EXIT_UNRESOLVED = 5; * credential and sends the operator to fix the read permissions. */ export const UNRESOLVED_REFERENCE = Symbol('unresolved Infisical reference'); -/** The approved fallback: `fleet-secrets get --path ` reads - * Fleet-OPS Infisical prod /asc. The value is captured, never echoed, and - * a failure is an empty string rather than an exception, so a missing tool - * reads as a missing credential. The one exception is the reader's exit 5, - * an unresolved reference, which comes back as UNRESOLVED_REFERENCE so the - * consumer names it as one. */ -export function fleetSecretsGet(name, folder) { +/** What the guard returns when no explicit service token is configured: the + * reader was never asked, so this is kept apart from both an empty value + * (missing credential) and an unresolved reference (vault refused the + * value). The failure must name the absent token, not read permissions. */ +export const SERVICE_TOKEN_MISSING = Symbol('missing Infisical service token'); + +/** The service-token-only fallback reads Fleet-OPS through `fleet-secrets`. + * Its child receives a minimal environment, so host machine-identity + * credentials cannot be selected implicitly. The value stays in memory; + * exit 5 remains distinct so an unresolved reference is reported accurately. */ +export function fleetSecretsGet(name, folder, env = process.env) { + if (!hasInfisicalServiceToken(env)) return SERVICE_TOKEN_MISSING; const localBin = join(homedir(), '.local', 'bin', 'fleet-secrets'); - const bin = process.env.FLEET_SECRETS || (existsSync(localBin) ? localBin : 'fleet-secrets'); + const bin = env.FLEET_SECRETS || process.env.FLEET_SECRETS || (existsSync(localBin) ? localBin : 'fleet-secrets'); try { return execFileSync(bin, ['get', name, '--path', folder], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], + env: fleetSecretsEnvironment(env), }).replace(/\n$/, ''); } catch (err) { if (err && err.status === READER_EXIT_UNRESOLVED) return UNRESOLVED_REFERENCE; @@ -211,14 +218,20 @@ function fail(log, message) { */ function checkCredential(log, name, value, malformed = false) { if (malformed) { - fail(log, `${name} is malformed in the job environment file: its multiline block is not terminated, so the file was truncated or a step that was writing it was interrupted; verify the CI identity can read Fleet-OPS prod /asc.`); + fail(log, `${name} is malformed in the job environment file: its multiline block is not terminated, so the file was truncated or a step that was writing it was interrupted; verify the CI service token can read Fleet-OPS prod /asc.`); } - const unresolved = () => fail(log, `${name} is still an unresolved Infisical secret reference in Fleet-OPS prod /asc; check the target exists and the CI identity can read the referenced folder.`); + const unresolved = () => fail(log, `${name} is still an unresolved Infisical secret reference in Fleet-OPS prod /asc; check the target exists and the CI service token can read the referenced folder.`); // The reader reached the vault and refused the value as a reference, so // this is not a missing credential and must not read as one. if (value === UNRESOLVED_REFERENCE) unresolved(); + // The reader was never asked because no explicit service token is + // configured; name the absent token instead of the secret's read + // permissions, so the operator fixes the actual cause. + if (value === SERVICE_TOKEN_MISSING) { + fail(log, `Cannot read ${name}: the explicit Infisical read service token (INFISICAL_TOKEN) is not set in the job environment. This is not a missing credential or a permissions fault; configure the scoped service token for this job.`); + } if (typeof value !== 'string' || value.trim() === '') { - fail(log, `Missing ${name} in Fleet-OPS prod /asc; verify the CI identity has read access to Fleet-OPS prod /asc.`); + fail(log, `Missing ${name} in Fleet-OPS prod /asc; verify an explicit Infisical service token has read access. Machine identity is disabled for CodeCaps automation.`); } if (isUnresolvedReference(value)) unresolved(); return value; @@ -281,8 +294,8 @@ export async function run({ if (typeof named === 'string' && named.trim() !== '') return { value: named, malformedEntry: false }; const written = fromFile.get(name); if (typeof written === 'string' && written.trim() !== '') return { value: written, malformedEntry: malformed.has(name) }; - const fetched = await getSecret(name, SECRET_FOLDER); - const value = typeof fetched === 'string' || fetched === UNRESOLVED_REFERENCE ? fetched : ''; + const fetched = await getSecret(name, SECRET_FOLDER, env); + const value = typeof fetched === 'string' || fetched === UNRESOLVED_REFERENCE || fetched === SERVICE_TOKEN_MISSING ? fetched : ''; return { value, malformedEntry: malformed.has(name) }; }; diff --git a/scripts/stage-asc-key.node-test.mjs b/scripts/stage-asc-key.node-test.mjs index 65348bbf..3ba4943e 100644 --- a/scripts/stage-asc-key.node-test.mjs +++ b/scripts/stage-asc-key.node-test.mjs @@ -494,6 +494,10 @@ test('a reader that reports an unresolved reference is not read as a missing cre // nothing, and the exit code is what has to survive. process.env.FLEET_SECRETS = writeStubReader(dir, 5, 'fleet-secrets: unresolved-reference: ASC_KEY_ID'); const env = baseEnv(dir); + // The service-token guard reads the run's own environment: without a + // token the reader is never asked and the error names the token, not the + // reference (PR #367 review). + env.INFISICAL_TOKEN = 'st.test.service'; writeEnvEntry(env.GITHUB_ENV, 'ASC_KEY_P8', KEY); const realLines = []; await assert.rejects(