Skip to main content
CodexBar uses several data models to represent usage quotas, rate limits, credits, and account identity across different providers.

UsageSnapshot

The primary data structure returned by all fetch strategies:
primary
RateWindow?
Primary rate limit window (e.g., 5-hour for Codex, session for Claude)
secondary
RateWindow?
Secondary rate limit window (e.g., weekly for Codex, on-demand for Cursor)
tertiary
RateWindow?
Optional third window (rarely used)
providerCost
ProviderCostSnapshot?
Token-level cost tracking data
zaiUsage
ZaiUsageSnapshot?
Zai-specific usage data
minimaxUsage
MiniMaxUsageSnapshot?
MiniMax-specific usage data
openRouterUsage
OpenRouterUsageSnapshot?
OpenRouter-specific usage data
cursorRequests
CursorRequestUsage?
Cursor request tracking data
updatedAt
Date
required
Timestamp when this snapshot was created
identity
ProviderIdentitySnapshot?
Account identity information

Methods

switcherWeeklyWindow

public func switcherWeeklyWindow(
    for provider: UsageProvider,
    showUsed: Bool
) -> RateWindow?
Returns the appropriate window to display in the provider switcher. Handles provider-specific logic:
  • Factory: Prefers secondary window over primary
  • Cursor: Falls back to On-Demand when Plan is exhausted (in “show remaining” mode only)
  • Others: Returns primary or falls back to secondary

scoped

public func scoped(to provider: UsageProvider) -> UsageSnapshot
Returns a copy with identity scoped to the specified provider.

Example

let usage = UsageSnapshot(
    primary: RateWindow(
        usedPercent: 45.2,
        windowMinutes: 300,
        resetsAt: Date().addingTimeInterval(3600),
        resetDescription: "1 hour"
    ),
    secondary: RateWindow(
        usedPercent: 12.8,
        windowMinutes: 10080,
        resetsAt: Date().addingTimeInterval(86400 * 5),
        resetDescription: "5 days"
    ),
    tertiary: nil,
    updatedAt: Date(),
    identity: ProviderIdentitySnapshot(
        providerID: .codex,
        accountEmail: "[email protected]",
        accountOrganization: nil,
        loginMethod: "chatgpt-plus"
    )
)

RateWindow

Represents a single rate limit window:
usedPercent
Double
required
Percentage of quota used (0-100)
windowMinutes
Int?
Duration of window in minutes (e.g., 300 for 5 hours)
resetsAt
Date?
Exact timestamp when window resets
resetDescription
String?
Human-readable reset description (e.g., “2 hours”, “tomorrow”)

Properties

public var remainingPercent: Double {
    max(0, 100 - usedPercent)
}

Example

// Session window with exact reset time
let sessionWindow = RateWindow(
    usedPercent: 67.3,
    windowMinutes: 300,
    resetsAt: Date().addingTimeInterval(7200),
    resetDescription: "2 hours"
)

print(sessionWindow.remainingPercent) // 32.7

// Weekly window with only description
let weeklyWindow = RateWindow(
    usedPercent: 23.1,
    windowMinutes: 10080,
    resetsAt: nil,
    resetDescription: "3 days until reset"
)

ProviderIdentitySnapshot

Account identity information for a specific provider:
providerID
UsageProvider?
The provider this identity belongs to
accountEmail
String?
Account email address
accountOrganization
String?
Organization or workspace name
loginMethod
String?
Login method or plan type (e.g., “chatgpt-plus”, “oauth”)

Methods

scoped

public func scoped(to provider: UsageProvider) -> ProviderIdentitySnapshot
Returns a copy with providerID set to the specified provider.
Identity silo rule: Never display identity fields from one provider in another provider’s UI. Always use scoped(to:) or identity(for:) methods to enforce boundaries.

Example

let identity = ProviderIdentitySnapshot(
    providerID: .claude,
    accountEmail: "[email protected]",
    accountOrganization: "Acme Corp",
    loginMethod: "workspace"
)

// Accessing in UI
if let email = usage.identity(for: .claude)?.accountEmail {
    print("Logged in as: \(email)")
}

CreditsSnapshot

Credit balance and usage events:
remaining
Double
required
Remaining credit balance
events
[CreditEvent]
required
History of credit usage events
updatedAt
Date
required
Timestamp when snapshot was created

CreditEvent

id
UUID
required
Unique identifier for this event
date
Date
required
When the credits were used
service
String
required
Service or model that consumed credits (e.g., “gpt-4”, “claude-opus”)
creditsUsed
Double
required
Amount of credits consumed

Example

let credits = CreditsSnapshot(
    remaining: 42.50,
    events: [
        CreditEvent(
            date: Date(),
            service: "gpt-4",
            creditsUsed: 2.30
        ),
        CreditEvent(
            date: Date().addingTimeInterval(-3600),
            service: "claude-opus-3",
            creditsUsed: 1.75
        )
    ],
    updatedAt: Date()
)

print("Credits remaining: \(credits.remaining)")
print("Total events: \(credits.events.count)")

AccountInfo

Simple account information structure:
email
String?
Account email
plan
String?
Plan type or subscription tier

Example

let account = AccountInfo(
    email: "[email protected]",
    plan: "chatgpt-plus"
)

Usage Errors

public enum UsageError: LocalizedError, Sendable {
    case noSessions
    case noRateLimitsFound
    case decodeFailed
}
noSessions
UsageError
No provider sessions found. User needs to run at least one prompt.
noRateLimitsFound
UsageError
Sessions exist but no rate limit data is available yet.
decodeFailed
UsageError
Failed to parse provider session data.

Best Practices

Creating Usage Snapshots

// Always provide updatedAt
let usage = UsageSnapshot(
    primary: primaryWindow,
    secondary: secondaryWindow,
    updatedAt: Date(), // Current time
    identity: identity
)

Accessing Identity Fields

// ✅ Correct: scoped access
let email = usage.identity(for: .codex)?.accountEmail

// ❌ Wrong: direct access without scoping
let email = usage.identity?.accountEmail // May leak cross-provider data

Window Selection Logic

// Use switcherWeeklyWindow for UI display
if let window = usage.switcherWeeklyWindow(for: provider, showUsed: false) {
    print("Remaining: \(window.remainingPercent)%")
}

// Direct window access for specific logic
if let primary = usage.primary {
    print("Primary window: \(primary.usedPercent)%")
}

Rate Window Display

func formatWindow(_ window: RateWindow) -> String {
    let percent = String(format: "%.1f", window.remainingPercent)
    if let reset = window.resetDescription {
        return "\(percent)% remaining (resets in \(reset))"
    } else {
        return "\(percent)% remaining"
    }
}

Build docs developers (and LLMs) love