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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"]),
]
)
80 changes: 80 additions & 0 deletions Plugins/WidgetParseMirrorGen/Plugin.swift
Original file line number Diff line number Diff line change
@@ -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
)]
}
}
27 changes: 27 additions & 0 deletions Sources/WidgetParseMirrorTool/main.swift
Original file line number Diff line number Diff line change
@@ -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 <packageDir> <outputDir> <relative-path>...
let args = Array(CommandLine.arguments.dropFirst())
guard args.count >= 2 else {
FileHandle.standardError.write(Data("usage: WidgetParseMirrorTool <packageDir> <outputDir> <relative-path>...\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)
}
}
52 changes: 46 additions & 6 deletions Tests/Fixtures/WidgetUIProbe.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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" }!
Expand All @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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"))
}
}
}
44 changes: 44 additions & 0 deletions Tests/WidgetParseTests/ProbeShims.swift
Original file line number Diff line number Diff line change
@@ -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<String>

public init(windows: [QuotaWindow] = [],
issues: [String: String] = [:],
consentNeeded: Set<String> = []) {
self.windows = windows
self.issues = issues
self.consentNeeded = consentNeeded
}
}

/// Reads the quota sources that the vendor CLIs already use on this Mac.
Loading
Loading