From b9807ad875e5c674179cb5543e06cf99c0827d98 Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:40:30 +0000 Subject: [PATCH 1/4] Widget: restore #369 wire-parse contract, single Argon detail, honest pool headline + WidgetParseTests CI coverage * Drop the #357 detailReports double-append so the antigravity pool shows one "Argon limit" detail instead of two * Exclude sub-model limits from the pool headline aggregation, mirroring the phone cardRemainingPercent semantics, so the Gemini pool reads its own 1% instead of being dragged to 0% by a spent Argon row * Restore #369's explicit widget intake filter (admits flagged video rows, drops reading-less unknown rows and plan metadata) in place of #357's isQuota guard, which silently dropped the qa6 video contract; shared WidgetPlatformDisplay.isQuota stays untouched so phone/Mac/selectedIndices behavior is unchanged * Repair the stale WidgetUIProbe harness (cardDetailWindows API, canonical 63/1 Gemini expectation, #360 count-only pair rule) and extend it to render the antigravity gallery through the real wire parse * Add WidgetParseTests: the actual widget parse path compiled into CI for the first time (build-time source mirroring, no committed copies to drift), pinning the antigravity single-detail/headline, qa3 rows + video flags, qa6 cap-state, qa4 merge and companion card details --- Package.swift | 8 + Plugins/WidgetParseMirrorGen/Plugin.swift | 80 +++++++++ Sources/WidgetParseMirrorTool/main.swift | 27 +++ Tests/Fixtures/WidgetUIProbe.swift | 52 +++++- Tests/WidgetParseTests/ProbeShims.swift | 44 +++++ .../WidgetParseContractTests.swift | 156 ++++++++++++++++++ 6 files changed, 361 insertions(+), 6 deletions(-) create mode 100644 Plugins/WidgetParseMirrorGen/Plugin.swift create mode 100644 Sources/WidgetParseMirrorTool/main.swift create mode 100644 Tests/WidgetParseTests/ProbeShims.swift create mode 100644 Tests/WidgetParseTests/WidgetParseContractTests.swift diff --git a/Package.swift b/Package.swift index 077c06fb..7e04c9bf 100644 --- a/Package.swift +++ b/Package.swift @@ -28,6 +28,14 @@ let package = Package( resources: [.process("Resources")] ), .testTarget(name: "QuotaCoreTests", dependencies: ["QuotaCore"]), + // The iOS widget parse path, compiled straight from the iOS sources + // (mirrored into the test build at build time, so there is no + // committed copy to drift) because the companion builds via + // xcodebuild, not SPM: without this target the code feeding every + // widget pixel had no CI. + .executableTarget(name: "WidgetParseMirrorTool"), + .plugin(name: "WidgetParseMirrorGen", capability: .buildTool(), dependencies: ["WidgetParseMirrorTool"]), + .testTarget(name: "WidgetParseTests", plugins: ["WidgetParseMirrorGen"]), .testTarget(name: "CodeCapsTests", dependencies: ["CodeCaps"]), ] ) diff --git a/Plugins/WidgetParseMirrorGen/Plugin.swift b/Plugins/WidgetParseMirrorGen/Plugin.swift new file mode 100644 index 00000000..a9258873 --- /dev/null +++ b/Plugins/WidgetParseMirrorGen/Plugin.swift @@ -0,0 +1,80 @@ +import Foundation +import PackagePlugin + +/// Mirrors the iOS widget parse-path sources into the WidgetParseTests target +/// so the wire-parse contract compiles in CI. The iOS companion is built by +/// xcodebuild, not SPM, so these files sit outside the package's source +/// roots; mirroring them at build time keeps a single source of truth with no +/// committed copy to drift. (Git symlinks cannot be published through the +/// fleet's hosted write routes, and a 79 KB mirrored file exceeds the hosted +/// blob limit, so build-time mirroring is the publishable shape.) +@main +struct WidgetParseMirrorGenPlugin: BuildToolPlugin { + func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] { + let packageDir = context.package.directory + let outputDir = context.pluginWorkDirectory + let tool = try context.tool(named: "WidgetParseMirrorTool") + let rels = [ + "ios/CodeCapsCompanion/App/Models/AlarmSoundPlayer.swift", + "Sources/QuotaCore/AnomalyDetector.swift", + "Sources/QuotaCore/AntigravityQuotaGroups.swift", + "Sources/QuotaCore/BoundedHTTPFetch.swift", + "Sources/QuotaCore/BoundedQuotaProcess.swift", + "ios/CodeCapsCompanion/App/Models/CompanionQuotaModel.swift", + "Sources/QuotaCore/CompanionReadTokenStore.swift", + "ios/CodeCapsCompanion/App/Models/CompanionTheme.swift", + "Sources/QuotaCore/FleetOrigin.swift", + "Sources/QuotaCore/FleetSourceDisagreement.swift", + "Sources/QuotaCore/GrokGrpcCredits.swift", + "Sources/QuotaCore/InfisicalBinding.swift", + "Sources/QuotaCore/InfisicalSettings.swift", + "Sources/QuotaCore/LocalQuotaSnapshot.swift", + "Sources/QuotaCore/MuseCodeBurnMonitor.swift", + "Sources/QuotaCore/MuseCodeSessionIngest.swift", + "Sources/QuotaCore/MuseCodeSessionReader.swift", + "Sources/QuotaCore/MuseCodeStandardSessionDetector.swift", + "Sources/QuotaCore/PlaceholderWindows.swift", + "Sources/QuotaCore/PlanMetadata.swift", + "Sources/QuotaCore/ProviderUsageDetails.swift", + "Sources/QuotaCore/QuotaBarMetrics.swift", + "Sources/QuotaCore/QuotaClient.swift", + "Sources/QuotaCore/QuotaExhaustionForecast.swift", + "Sources/QuotaCore/QuotaModels.swift", + "Sources/QuotaCore/QuotaPublisher.swift", + "Sources/QuotaCore/QuotaReaderPreferences.swift", + "Sources/QuotaCore/QuotaWindowCaption.swift", + "Sources/QuotaCore/QuotaWindowPairing.swift", + "Sources/QuotaCore/QuotaWindowPresentation.swift", + "Sources/QuotaCore/QuotaWindowVocabulary.swift", + "ios/CodeCapsCompanion/App/Models/RemotePushRegistration.swift", + "Sources/QuotaCore/ResetAlarmCadence.swift", + "Sources/QuotaCore/ResetAlarmMessage.swift", + "Sources/QuotaCore/ResetAlarmSound.swift", + "Sources/QuotaCore/ResetAlarmTracker.swift", + "Sources/QuotaCore/SMSAlertCoordinator.swift", + "Sources/QuotaCore/TokenHygiene.swift", + "Sources/QuotaCore/TwilioSMSClient.swift", + "Sources/QuotaCore/UnifiedSubscriptionPool.swift", + "Sources/QuotaCore/UsageAlertPreferences.swift", + "Sources/QuotaCore/UsageAlertPublisher.swift", + "Sources/QuotaCore/UsageMonitorPushMetadata.swift", + "ios/CodeCapsCompanion/Widgets/WidgetConfigurationIntent.swift", + "ios/CodeCapsCompanion/Widgets/WidgetDataProvider.swift", + "ios/CodeCapsCompanion/Widgets/WidgetDetailIntent.swift", + "Sources/QuotaCore/WidgetPlatformDisplay.swift", + "ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift", + "Sources/QuotaCore/WidgetSnapshotFetcher.swift", + "ios/CodeCapsCompanion/Widgets/WidgetViews.swift", + "ios/CodeCapsCompanion/Widgets/WidgetWindowRows.swift" + ] + let inputs = rels.map { packageDir.appending(subpath: $0) } + let outputs = rels.map { outputDir.appending(URL(fileURLWithPath: $0).lastPathComponent) } + return [.buildCommand( + displayName: "Mirror the iOS widget parse-path sources into WidgetParseTests", + executable: tool.path, + arguments: [packageDir.string, outputDir.string] + rels, + inputFiles: inputs, + outputFiles: outputs + )] + } +} diff --git a/Sources/WidgetParseMirrorTool/main.swift b/Sources/WidgetParseMirrorTool/main.swift new file mode 100644 index 00000000..f34efd85 --- /dev/null +++ b/Sources/WidgetParseMirrorTool/main.swift @@ -0,0 +1,27 @@ +import Foundation + +// Mirror the iOS widget parse-path sources into the WidgetParseTests build. +// The iOS companion is built by xcodebuild, not SPM, so these files live +// outside the package's source roots; copying them at build time keeps one +// source of truth with zero committed duplication. +// Usage: WidgetParseMirrorTool ... +let args = Array(CommandLine.arguments.dropFirst()) +guard args.count >= 2 else { + FileHandle.standardError.write(Data("usage: WidgetParseMirrorTool ...\n".utf8)) + exit(2) +} +let packageDir = args[0] +let outputDir = args[1] +let fm = FileManager.default +try? fm.createDirectory(atPath: outputDir, withIntermediateDirectories: true) +for rel in args.dropFirst(2) { + let src = packageDir + "/" + rel + let dst = outputDir + "/" + URL(fileURLWithPath: rel).lastPathComponent + try? fm.removeItem(atPath: dst) + do { + try fm.copyItem(atPath: src, toPath: dst) + } catch { + FileHandle.standardError.write(Data("WidgetParseMirrorTool: cannot copy \(rel): \(error)\n".utf8)) + exit(1) + } +} diff --git a/Tests/Fixtures/WidgetUIProbe.swift b/Tests/Fixtures/WidgetUIProbe.swift index 90547e47..04773896 100644 --- a/Tests/Fixtures/WidgetUIProbe.swift +++ b/Tests/Fixtures/WidgetUIProbe.swift @@ -44,10 +44,11 @@ import AppIntents precondition(minimax.dualWindows()?.window1.id == "minimax:5h") precondition(minimax.dualWindows()?.window2.id == "minimax:7d") let gemini = parsed.first { $0.id == "antigravity-gemini" }! - // 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]) + // The exported pool rows are authoritative beside raw model observations + // (WidgetPlatformDisplay.selectedPoolIndices): the canonical + // antigravity:gemini:5h copy (63) wins the five-hour slot and the raw 7% + // copy never reaches a bar. + 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" }! @@ -69,7 +70,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(\.window.label) == ["Fable limit"]) + 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) @@ -93,7 +94,10 @@ import AppIntents precondition(counted.controllingWindow(.mostHeadroom)?.id == zero.id) precondition(counted.usableMuseExtra?.absoluteRemaining == 42) precondition(counted.windows.last?.absoluteRemaining == 42) - precondition(counted.dualWindows() != nil) + // A count-only extra (no percent, no reset) displays its "N left" caption + // but never fills a meter-pair slot: the shared rule seats only windows + // with a percentage or a reset (QuotaWindowPairing.meterPair, PR #360). + precondition(counted.dualWindows() == nil) precondition(!ShowWidgetPlanDetailIntent.openAppWhenRun) let defaults=UserDefaults(suiteName:WidgetSnapshotStore.appGroupId)! let scope="native-regression-"+UUID().uuidString @@ -262,6 +266,28 @@ import AppIntents precondition(platforms[1].usableMuseExtra?.absoluteRemaining == 42) precondition(platforms[1].atCapWindow()?.remainingPercent == 0) let entry=CodeCapsWidgetEntry(date:Date(),platforms:platforms,lastUpdated:Date()) + // Render the antigravity pool through the real wire parse, so the gallery + // shows the pool row and its single Argon detail exactly as the widget + // draws them: one "Argon limit" row beside the pool meters, and the pool + // headline read from the pool's own windows, never the spent detail. + let antiStamp = ISO8601DateFormatter().string(from: Date()) + let antiReset = ISO8601DateFormatter().string(from: Date().addingTimeInterval(3600)) + func antiWire(_ id: String, _ token: String?, _ percent: Double?, _ label: String, model: String? = nil) -> [String: Any] { + var value: [String: Any] = ["id":id, "provider":"google-antigravity", "providerKey":"google-antigravity", + "label":label, "occurredAt":antiStamp, "reportedAt":antiStamp, "resetAt":antiReset] + value["window"] = token; value["remainingPercent"] = percent + value["modelId"] = model + return value + } + let antiPayload = [ + antiWire("raw:gemini:5h", "5h", 7, "Gemini 5-hour"), + antiWire("antigravity:gemini:5h", "5h", 63, "Gemini Models 5-hour"), + antiWire("antigravity:gemini:weekly", "7d", 1, "Gemini Models Weekly"), + antiWire("gemini:argon", "5h", 0, "Gemini Argon", model:"Argon") + ] + let antiParsed = WidgetPresentation.parseSnapshot(data: try JSONSerialization.data(withJSONObject:["windows":antiPayload])) + let geminiPlatform = antiParsed.first { $0.id == "antigravity-gemini" }! + let antiEntry = CodeCapsWidgetEntry(date:Date(), platforms:[geminiPlatform], lastUpdated:Date()) for (name,scheme) in [("light",ColorScheme.light),("dark",ColorScheme.dark)] { let view=HStack(alignment:.top,spacing:20) { VStack { @@ -277,6 +303,20 @@ import AppIntents guard let img=renderer.cgImage else {fatalError("render unavailable")} let rep=NSBitmapImageRep(cgImage:img) try rep.representation(using:.png,properties:[:])!.write(to:URL(fileURLWithPath:"\(ProcessInfo.processInfo.environment["CODECAPS_WIDGET_RENDER_DIR"] ?? NSTemporaryDirectory())/widget-gallery-"+name+".png")) + let antiView=HStack(alignment:.top,spacing:20) { + VStack { + Text("Large overview (antigravity pool)").font(.caption) + OverviewLargeView(entry:antiEntry).frame(width:338,height:354) + } + VStack { + Text("In-widget plan details (antigravity pool)").font(.caption) + WidgetPlanDetailView(platform:geminiPlatform,entry:antiEntry).padding(14).frame(width:338,height:354) + } + }.padding(16).background(scheme == .dark ? Color.black : Color.white).environment(\.colorScheme,scheme) + let antiRenderer=ImageRenderer(content:antiView);antiRenderer.scale=2 + guard let antiImg=antiRenderer.cgImage else {fatalError("render unavailable")} + let antiRep=NSBitmapImageRep(cgImage:antiImg) + try antiRep.representation(using:.png,properties:[:])!.write(to:URL(fileURLWithPath:"\(ProcessInfo.processInfo.environment["CODECAPS_WIDGET_RENDER_DIR"] ?? NSTemporaryDirectory())/widget-gallery-antigravity-"+name+".png")) } } } diff --git a/Tests/WidgetParseTests/ProbeShims.swift b/Tests/WidgetParseTests/ProbeShims.swift new file mode 100644 index 00000000..18f6b56c --- /dev/null +++ b/Tests/WidgetParseTests/ProbeShims.swift @@ -0,0 +1,44 @@ +public enum TestNotificationOutcome: Equatable, Sendable { + case sent + /// Notifications are off for this app; nothing can be delivered until the + /// owner grants them in Settings. + case denied + /// Delivery failed for a reason worth showing. + case failed(String) + + public var isFailure: Bool { + if case .sent = self { return false } + return true + } + + public var message: String { + switch self { + case .sent: + return "Test notification accepted." + sentenceGap + "System settings control banners and sound." + case .denied: + return "Notifications are turned off for CodeCaps." + sentenceGap + + "Turn them on in Settings, then try again." + case .failed(let reason): + return "Could not send the test notification." + sentenceGap + reason + } + } +} +public struct LocalQuotaResult: Equatable, Sendable { + public let windows: [QuotaWindow] + public let issues: [String: String] + /// Provider keys whose credential exists on this Mac but is unreadable + /// until the owner allows this build once. Kept apart from `issues` + /// because it is the difference between "sign in" — which the owner + /// cannot act on when they already have — and a button they can press. + public let consentNeeded: Set + + public init(windows: [QuotaWindow] = [], + issues: [String: String] = [:], + consentNeeded: Set = []) { + self.windows = windows + self.issues = issues + self.consentNeeded = consentNeeded + } +} + +/// Reads the quota sources that the vendor CLIs already use on this Mac. diff --git a/Tests/WidgetParseTests/WidgetParseContractTests.swift b/Tests/WidgetParseTests/WidgetParseContractTests.swift new file mode 100644 index 00000000..9763013f --- /dev/null +++ b/Tests/WidgetParseTests/WidgetParseContractTests.swift @@ -0,0 +1,156 @@ +import XCTest + +/// Wire-parse contract for the iOS widget's snapshot path. The parse-path +/// sources are mirrored into this target at build time (from +/// ios/CodeCapsCompanion/Widgets and Sources/QuotaCore, see +/// Plugins/WidgetParseMirrorGen) because the iOS +/// companion is built by xcodebuild, not SPM: without this target the whole +/// parse path - the code that feeds every widget pixel - had no CI coverage, +/// which is how PR #357 broke the iOS build invisibly for days. +final class WidgetParseContractTests: XCTestCase { + + /// The package root, resolved from this file's build-time path, so the + /// committed wire fixtures load no matter where the test process starts. + private var packageRoot: URL { + URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // WidgetParseTests dir + .deletingLastPathComponent() // Tests dir + .deletingLastPathComponent() // package root + } + + private func wire(_ id: String, _ provider: String, _ token: String?, _ percent: Double?, + _ label: String = "Quota", model: String? = nil, source: String? = nil, + stamp: String, reset: String) -> [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 + } + + /// The antigravity pool through the real parse path: one Argon detail + /// (never a duplicate), the exported pool rows winning the meters, and a + /// spent detail never dragging the pool headline to zero. + func testAntigravityPoolKeepsSingleArgonDetailAndHonestHeadline() throws { + let stamp = ISO8601DateFormatter().string(from: Date()) + let reset = ISO8601DateFormatter().string(from: Date().addingTimeInterval(3600)) + let payload = [ + wire("claude:plan-metadata", "anthropic", nil, nil, "Plan Details", stamp: stamp, reset: reset), + wire("raw:gemini:5h", "google-antigravity", "5h", 7, "Gemini 5-hour", stamp: stamp, reset: reset), + wire("antigravity:gemini:5h", "google-antigravity", "5h", 63, "Gemini Models 5-hour", stamp: stamp, reset: reset), + wire("antigravity:gemini:weekly", "google-antigravity", "7d", 1, "Gemini Models Weekly", stamp: stamp, reset: reset), + wire("gemini:argon", "google-antigravity", "5h", 0, "Gemini Argon", model: "Argon", stamp: stamp, reset: reset), + ] + let parsed = WidgetPresentation.parseSnapshot(data: try JSONSerialization.data(withJSONObject: ["windows": payload])) + let gemini = try XCTUnwrap(parsed.first { $0.id == "antigravity-gemini" }) + // The canonical exported row wins the five-hour meter. + XCTAssertEqual(gemini.primaryWindows.map(\.remainingPercent), [63, 1]) + // Exactly one Argon detail row. + XCTAssertEqual(gemini.detailWindows.map(\.label), ["Argon limit"]) + XCTAssertEqual(gemini.windows.filter { $0.id == "gemini:argon" }.count, 1) + // The spent detail sits beside the pool: the headline reads the + // pool's own weekly (1), not the 0% detail, and nothing caps. + XCTAssertEqual(gemini.remainingPercent, 1) + XCTAssertNil(gemini.atCapWindow()) + } + + /// The qa3 wire capture (committed verbatim): the MiniMax plan keeps its + /// 5h and weekly rows, both video cadences stay as separate flagged rows, + /// the reading-less unknown row earns no row, and Copilot keeps buckets. + func testQA3WireFixtureMiniMaxRowsAndVideoFlags() throws { + let fxNow = ISO8601DateFormatter().date(from: "2026-11-06T07:50:00Z")! + let fxData = try Data(contentsOf: packageRoot.appendingPathComponent("Tests/Fixtures/qa3-wire-regression-fixture.json")) + let fx = WidgetPresentation.parseSnapshot(data: fxData, now: fxNow) + let minimax = try XCTUnwrap(fx.first { $0.providerKey.contains("minimax") || $0.id.contains("minimax") }) + let ids = minimax.windows.map { $0.id } + let phone5h = "[\"producer\",\"4f938669-72f9-4386-8808-6408a031ab4d\",\"general\"]" + let macWeekly = "[\"producer\",\"Mac.Jays.Services\",\"general\"]" + let phoneVideo = "[\"producer\",\"4f938669-72f9-4386-8808-6408a031ab4d\",\"video\"]" + let macVideo = "[\"producer\",\"Mac.Jays.Services\",\"video\"]" + XCTAssertEqual(minimax.windows.count, 4, "5h plan, 7d plan, 1d video, 7d video: \(ids)") + XCTAssertTrue(ids.contains(phone5h), "the fresher codecaps copy wins the merged 5h plan row: \(ids)") + XCTAssertEqual(minimax.windows.first { $0.id == macWeekly }?.remainingPercent, 5) + XCTAssertTrue(ids.contains(phoneVideo) && ids.contains(macVideo), "both video cadences keep rows: \(ids)") + XCTAssertEqual(minimax.windows.filter { $0.isSupplementaryVideoQuota }.count, 2, "both video rows flagged") + XCTAssertEqual(minimax.windows.filter { !$0.isSupplementaryVideoQuota }.count, 2, "exactly the two plan rows unflagged") + XCTAssertEqual(minimax.dualWindows()?.window1.id, phone5h, "the pair opens on the plan 5h") + XCTAssertEqual(minimax.dualWindows()?.window2.id, macWeekly, "the pair holds the plan weekly, never a video row") + XCTAssertNil(minimax.atCapWindow(now: fxNow), "video rows never cap the plan") + let copilot = try XCTUnwrap(fx.first { $0.providerKey.contains("copilot") || $0.id.contains("copilot") }) + XCTAssertEqual(copilot.windows.count, 3, "copilot buckets keep rows") + XCTAssertTrue(copilot.windows.contains { $0.remainingPercent == 0 }, "the exhausted Premium row stays visible") + } + + /// The qa6 wire captures: a spent video pool never caps or outranks a + /// live plan, a spent plan caps itself, and a video-only platform keeps + /// its cap through the all-window fallback. + func testQA6VideoCapStateExclusion() throws { + let q6Now = ISO8601DateFormatter().date(from: "2026-11-06T10:30:00Z")! + func load(_ name: String) throws -> [WidgetPlatformItem] { + try WidgetPresentation.parseSnapshot(data: Data(contentsOf: packageRoot.appendingPathComponent("qa6-harness/" + name)), now: q6Now) + } + let phone5h = "[\"producer\",\"4f938669-72f9-4386-8808-6408a031ab4d\",\"general\"]" + let macWeekly = "[\"producer\",\"Mac.Jays.Services\",\"general\"]" + let phoneVideo = "[\"producer\",\"4f938669-72f9-4386-8808-6408a031ab4d\",\"video\"]" + let q6a = try XCTUnwrap(load("qa6-a-spent-video-live-plan.json").first { $0.providerKey == "minimax" }) + XCTAssertEqual(q6a.windows.count, 4) + XCTAssertEqual(q6a.windows.filter { $0.isSupplementaryVideoQuota }.count, 2) + XCTAssertNil(q6a.atCapWindow(now: q6Now), "spent video must not cap a live plan") + XCTAssertEqual(q6a.remainingPercent, 5, "headline derives from plan windows, not the spent video") + XCTAssertFalse(q6a.isExhausted) + XCTAssertEqual(q6a.dualWindows()?.window1.id, phone5h) + XCTAssertEqual(q6a.controllingWindow(.mostUrgent)?.id, macWeekly) + XCTAssertEqual(q6a.controllingWindow(.mostHeadroom)?.id, phone5h) + let q6b = try XCTUnwrap(load("qa6-b-spent-plan-live-video.json").first { $0.providerKey == "minimax" }) + XCTAssertEqual(q6b.atCapWindow(now: q6Now)?.id, phone5h, "the spent plan 5h caps the platform") + XCTAssertTrue(q6b.isExhausted) + XCTAssertEqual(q6b.controllingWindow(.mostUrgent)?.id, phone5h) + let q6c = try XCTUnwrap(load("qa6-c-video-only-spent.json").first { $0.providerKey == "minimax" }) + XCTAssertEqual(q6c.windows.count, 1) + XCTAssertEqual(q6c.atCapWindow(now: q6Now)?.id, phoneVideo, "video-only fallback binds the video window") + XCTAssertTrue(q6c.isExhausted) + } + + /// The qa4 capture: one xAI subscription pool seen by two producers + /// merges to one 7d row, the fresher phone copy winning. + func testQA4XaiPoolMergesAcrossProducers() throws { + let xaiNow = ISO8601DateFormatter().date(from: "2026-11-06T09:25:00Z")! + let data = try Data(contentsOf: packageRoot.appendingPathComponent("Tests/Fixtures/qa4-xai-wire-counterexample.json")) + let parsed = WidgetPresentation.parseSnapshot(data: data, now: xaiNow) + let xai = try XCTUnwrap(parsed.first { $0.providerKey == "xai" }) + XCTAssertEqual(xai.windows.count, 1, "the two producer copies of one pool must merge") + XCTAssertEqual(xai.windows.first?.id, "[\"producer\",\"4f938669-72f9-4386-8808-6408a031ab4d\",\"grok:subscription\"]") + XCTAssertEqual(xai.windows.first?.remainingPercent, 79) + } + + /// The phone's companion card model: sub-model limits are expandable + /// details beside the card, never headline meters; a count-only extra + /// shows its "N left" caption but fills no meter-pair slot (#360). + func testCompanionCardDetailsAndCaptions() { + 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]) + XCTAssertEqual(phone.cardShortWindow(scope: .allSources)?.window.id, "weekly") + XCTAssertNil(phone.cardLongWindow(scope: .allSources)) + XCTAssertEqual(phone.cardRemainingPercent(scope: .allSources), 57) + XCTAssertTrue(phone.isExpandable) + XCTAssertEqual(phone.cardDetailWindows(scope: .allSources).map(\.label), ["Fable limit"]) + + let zero = WidgetWindowItem(id: "zero", label: "7-day", cadence: "7d", remainingPercent: 0, resetAt: nil) + let countedExtra = WidgetWindowItem(id: "count-extra", label: "Other limit", cadence: "Other limit", + remainingPercent: nil, resetAt: nil, isExtraAllowance: true, + absoluteRemaining: 42) + XCTAssertEqual(countedExtra.displayPercent, "42 left") + let counted = WidgetPlatformItem(id: "counted", providerKey: "muse-assist", title: "Muse Assist", + subtitle: "", remainingPercent: 0, resetAt: nil, + windows: [zero, countedExtra]) + XCTAssertNil(counted.dualWindows(), "a count-only extra fills no meter-pair slot (QuotaWindowPairing, #360)") + } +} From ebdca6aa4152e0d22c5674d4c27a9d49d3df62f2 Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:41:07 +0000 Subject: [PATCH 2/4] Widget: restore #369 intake filter, single Argon detail, honest pool headline --- .../Widgets/WidgetPresentation.swift | 38 ++++++++++++++----- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift index 156271b5..d6f5f560 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift @@ -988,7 +988,25 @@ public enum WidgetPresentation { let liveWindows = rawWindows.filter { w in let reading = quotaReading(w, providerKey: providerKey) - guard reading.isQuota else { return false } + let lowId = w.id.lowercased() + let lowLabel = w.label.lowercased() + if lowId.hasSuffix(":plan-metadata") || lowLabel == "plan details" { + return false + } + // A copy that says it does not know the reading, carries no + // figure and names no reset is a status note, not a window: it + // never earns a row (the phone's intake keeps the same rule). + 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 + } + // A supplementary video allowance is a real row beside the plan, + // not a non-quota: it survives intake flagged, and the + // plan-state, cap, pair and headline exclusions keep it off the + // plan's own bars (the qa6 wire contract, PR #369). 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) @@ -1298,19 +1316,19 @@ public enum WidgetPresentation { )) } - let primary = childWindows + // The headline reads the pool's own meters only: a spent per-model + // detail (a 0% Argon limit) sits beside the pool and must not drag + // its figure to zero - the same exclusion the phone's + // cardRemainingPercent applies with isSubModelLimit. + let primary = childWindows.filter { !$0.isModelDetail } 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 - } - + // Sub-model details arrive only through the detail loop above: + // appending buildPlatformItem's detailWindows here added a second + // copy of every Argon row beside the loop's own (native probe: + // gemini detailWindows == ["Argon limit"], not two). let nearestReset = childWindows.compactMap(\.resetAt).filter { $0 > now }.min() ?? childWindows.compactMap(\.resetAt).min() From ec89a09493337e030d450e6924b47ed99999dcfe Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:09:31 +0000 Subject: [PATCH 3/4] Keep the shared intake gate for scoped pools and detail-less model limits; admit video; match metadata ids inside JSON-shaped ids --- .../Widgets/WidgetPresentation.swift | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift index d6f5f560..0befe3f5 100644 --- a/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift +++ b/ios/CodeCapsCompanion/Widgets/WidgetPresentation.swift @@ -990,7 +990,22 @@ public enum WidgetPresentation { let reading = quotaReading(w, providerKey: providerKey) let lowId = w.id.lowercased() let lowLabel = w.label.lowercased() - if lowId.hasSuffix(":plan-metadata") || lowLabel == "plan details" { + // The shared intake gate stays: a scoped pool (a code-review or + // per-model bucket) or a per-model limit that names no detail is + // not the plan's own quota - it never earns a row, a meter, the + // headline or the cap, exactly as on the phone (PR #376 parity). + // The one case the gate misclassifies is the supplementary video + // allowance: that is a real row beside the plan, not a + // non-quota, so it survives intake flagged, and the plan-state, + // cap, pair and headline exclusions keep it off the plan's own + // bars (the qa6 wire contract, PR #369). + let isSupplementaryVideo = QuotaCapRule.isSupplementaryVideoQuota( + providerKey: providerKey, modelId: w.modelId, modelType: w.modelType, label: w.label) + guard reading.isQuota || isSupplementaryVideo else { return false } + // Producer-scoped window ids are serialized JSON, so they end in + // `"]`, not in the bare token: match the metadata marker + // anywhere in the id (Kody review, PR #387). + if lowId.contains("plan-metadata") || lowLabel == "plan details" { return false } // A copy that says it does not know the reading, carries no @@ -1003,10 +1018,6 @@ public enum WidgetPresentation { && !QuotaWindowVocabulary.isExtraAllowanceLabel(w.label) { return false } - // A supplementary video allowance is a real row beside the plan, - // not a non-quota: it survives intake flagged, and the - // plan-state, cap, pair and headline exclusions keep it off the - // plan's own bars (the qa6 wire contract, PR #369). 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) From a7fa230b4020102107f7e8d7fa838c2423591338 Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:09:44 +0000 Subject: [PATCH 4/4] Pin that spent scoped pools and JSON-shaped metadata ids stay out of widget intake --- .../WidgetParseContractTests.swift | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Tests/WidgetParseTests/WidgetParseContractTests.swift b/Tests/WidgetParseTests/WidgetParseContractTests.swift index 9763013f..2d690d9b 100644 --- a/Tests/WidgetParseTests/WidgetParseContractTests.swift +++ b/Tests/WidgetParseTests/WidgetParseContractTests.swift @@ -153,4 +153,29 @@ final class WidgetParseContractTests: XCTestCase { windows: [zero, countedExtra]) XCTAssertNil(counted.dualWindows(), "a count-only extra fills no meter-pair slot (QuotaWindowPairing, #360)") } + + /// A spent scoped pool (Codex's Code Review bucket) is not the plan's + /// quota: it earns no row, cannot cap the plan and cannot drag the + /// headline - the phone's intake and the shared gate agree (PR #376, + /// Kody review on this PR). And a producer-scoped plan-metadata id is + /// serialized JSON, so the metadata marker must match inside the id, not + /// only at its tail. + func testScopedPoolsAndJsonMetadataIdsStayOutOfIntake() throws { + let stamp = ISO8601DateFormatter().string(from: Date()) + let reset = ISO8601DateFormatter().string(from: Date().addingTimeInterval(3600)) + // The id shape the fleet actually ships (qa3 wire fixture). + let metadataJsonId = "[\"producer\",\"4f938669-72f9-4386-8808-6408a031ab4d\",\"minimax:plan-metadata\"]" + let payload = [ + wire("openai:subscription", "openai", "5h", 62, "5-hour window", stamp: stamp, reset: reset), + wire("openai:code-review", "openai", "7d", 0, "Code Review", stamp: stamp, reset: reset), + wire(metadataJsonId, "minimax", nil, nil, "MiniMax quota", stamp: stamp, reset: reset), + ] + let parsed = WidgetPresentation.parseSnapshot(data: try JSONSerialization.data(withJSONObject: ["windows": payload])) + let codex = try XCTUnwrap(parsed.first { $0.providerKey == "openai" }) + XCTAssertEqual(codex.windows.map(\.id), ["openai:subscription"]) + XCTAssertEqual(codex.remainingPercent, 62) + XCTAssertNil(codex.atCapWindow()) + let minimax = parsed.first { $0.providerKey == "minimax" } + XCTAssertTrue(minimax?.windows.isEmpty ?? true, "a JSON-shaped metadata id is a caption, not a window") + } }