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
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ Settings, Ping History, and Claude Info share a single tabbed window. Opening an

**Claude Web API:**

Enables two features: API-based pinging (no CLI needed) and live usage tracking (session %, weekly %, monthly spend). Usage polling is free — it reads your account metrics without consuming any tokens or starting a session. Click the `?` icon in Settings for step-by-step setup instructions.
Enables two features: API-based pinging (no CLI needed) and live usage tracking (session %, weekly %). Usage polling is free — it reads your account metrics without consuming any tokens or starting a session. Click the `?` icon in Settings for step-by-step setup instructions.

- **Org ID** — Your organization UUID. Stays constant for your account.
- **Session Key** — Your `sessionKey` cookie. Auto-refreshes on each API poll, so once entered it stays valid.
Expand All @@ -131,7 +131,6 @@ A visual dashboard showing:
- Session usage with colored progress bar (green → orange → red)
- **Usage Pace** — burn rate (%/hr) for the current session, past week, and all time, plus estimated time remaining until you hit the rate limit. Color-coded: green (>2h left), orange (<2h), red (<1h).
- Weekly usage with per-model breakdowns (Opus, Sonnet, Cowork, etc.)
- Monthly extra-usage spend with credits used vs. limit
- Reset countdowns and times
- Auto-refreshes on the configured usage poll interval, plus a manual Refresh button

Expand Down
29 changes: 2 additions & 27 deletions Sources/PingClaude/ClaudeInfoView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -148,31 +148,6 @@ struct ClaudeInfoView: View {
.padding(.top, 4)
}

// Monthly Spend
GroupBox(label: Text("Monthly Spend").font(.headline)) {
VStack(alignment: .leading, spacing: 8) {
if let limit = usage.monthlyLimitCents, let used = usage.monthlyUsedCents, limit > 0 {
let pct = min(Double(used) / Double(limit) * 100, 100)
UsageBar(
label: "Extra usage credits",
percentage: pct,
detail: String(format: "$%.2f / $%.2f", Double(used) / 100.0, Double(limit) / 100.0)
)

if usage.outOfCredits == true {
Text("Out of credits!")
.font(.system(size: 12, weight: .semibold))
.foregroundColor(.red)
}
} else {
Text("No spend data available")
.font(.system(size: 12))
.foregroundColor(.secondary)
}
}
.padding(.top, 4)
}

// Last updated
if let error = usageService.lastError {
HStack(spacing: 4) {
Expand All @@ -189,7 +164,7 @@ struct ClaudeInfoView: View {
.foregroundColor(.secondary)
Spacer()
Button("Refresh") {
usageService.fetchUsage()
usageService.refreshAll()
}
}
Text("Usage polling is free \u{2014} no tokens consumed, no sessions started.")
Expand All @@ -199,7 +174,7 @@ struct ClaudeInfoView: View {
// Log & Troubleshooting
GroupBox(label: Text("Log & Troubleshooting").font(.headline)) {
VStack(alignment: .leading, spacing: 6) {
Text("All API calls (usage, spend, plan) are logged with status codes and key values.")
Text("All API calls (usage, plan) are logged with status codes and key values.")
.font(.system(size: 11))
.foregroundColor(.secondary)

Expand Down
1 change: 1 addition & 0 deletions Sources/PingClaude/Constants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ enum Constants {
static let maxNetworkRetries = 4 // Max retry attempts after initial failure
static let retryDelays: [TimeInterval] = [15, 30, 60, 120] // Exponential backoff delays
static let usageMaxBackoffSeconds: TimeInterval = 600 // 10 min max backoff for usage polling
static let planFetchDelaySeconds: TimeInterval = 2 // Delay before plan tier fetch to avoid simultaneous API calls

// Available models
static let availableModels = ["haiku", "sonnet", "opus"]
Expand Down
3 changes: 1 addition & 2 deletions Sources/PingClaude/HelpWindow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ struct HelpView: View {
"""
The Claude Web API enables two features:
1. Pinging via API (no CLI needed)
2. Live usage tracking (session %, weekly %, monthly spend)
2. Live usage tracking (session %, weekly %)

Usage polling is free \u{2014} it reads your account metrics without \
consuming any tokens or starting a session. The poll interval is \
Expand All @@ -128,7 +128,6 @@ struct HelpView: View {
and all time, plus estimated time remaining until rate limit. \
Color-coded: green (>2h), orange (<2h), red (<1h).
\u{2022} Weekly usage and per-model breakdowns
\u{2022} Monthly extra-usage spend
\u{2022} Reset countdowns and times

Pace data starts showing after 2+ usage samples are collected \
Expand Down
6 changes: 4 additions & 2 deletions Sources/PingClaude/SchedulerService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,10 @@ class SchedulerService: ObservableObject {

logStore.log("Reset ping firing (attempt \(resetPingRetryCount + 1))")

// Refresh usage data first to get fresh numbers
usageService.fetchUsage()
// Refresh usage data unless rate-limited (don't bypass backoff)
if !usageService.isBackingOff {
usageService.fetchUsage()
}

pingService.ping { [weak self] result in
guard let self = self else { return }
Expand Down
9 changes: 4 additions & 5 deletions Sources/PingClaude/StatusBarController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -435,8 +435,10 @@ class StatusBarController {
} else {
self.logStore.log("Manual ping failed via \(methodTag): \(result.errorMessage ?? "unknown")")
}
// Also refresh full usage data (breakdowns, monthly spend)
self.usageService.fetchUsage()
// Refresh usage data unless rate-limited (don't bypass backoff)
if !self.usageService.isBackingOff {
self.usageService.fetchUsage()
}
}
}

Expand All @@ -451,9 +453,6 @@ class StatusBarController {
weeklyUtilization: pingUsage.weeklyUtilization.map { $0 * 100 } ?? prev?.weeklyUtilization,
weeklyResetsAt: pingUsage.weeklyResetsAt.map { Date(timeIntervalSince1970: $0) } ?? prev?.weeklyResetsAt,
breakdowns: prev?.breakdowns ?? [],
monthlyLimitCents: prev?.monthlyLimitCents,
monthlyUsedCents: prev?.monthlyUsedCents,
outOfCredits: prev?.outOfCredits,
fetchedAt: Date()
)
usageService.latestUsage = usage
Expand Down
111 changes: 37 additions & 74 deletions Sources/PingClaude/UsageService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,6 @@ struct UsageBreakdown {
let resetsAt: Date?
}

struct SpendResponse: Codable {
let monthly_credit_limit: Int?
let used_credits: Int?
let out_of_credits: Bool?
let is_enabled: Bool?
}

/// Claude subscription plan tier
enum PlanTier: String, CustomStringConvertible {
case free = "Free"
Expand Down Expand Up @@ -76,9 +69,6 @@ struct UsageData {
let weeklyUtilization: Double? // 0-100
let weeklyResetsAt: Date?
let breakdowns: [UsageBreakdown] // per-model, cowork, extra — only non-null entries
let monthlyLimitCents: Int? // e.g. 5000 = $50
let monthlyUsedCents: Int? // e.g. 2405 = $24.05
let outOfCredits: Bool?
let fetchedAt: Date

var sessionResetsInString: String? {
Expand Down Expand Up @@ -114,6 +104,9 @@ class UsageService: ObservableObject {
private var isUpdatingSessionKey = false
private var consecutiveErrors: Int = 0

/// True when usage API is in backoff due to 429 rate limiting
var isBackingOff: Bool { consecutiveErrors > 0 }

private let isoFormatter: ISO8601DateFormatter = {
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
Expand Down Expand Up @@ -160,6 +153,40 @@ class UsageService: ObservableObject {
// Fetch immediately, then schedule next poll after completion
fetchUsage()
scheduleNextPoll()

// Fetch plan tier separately with delay to avoid simultaneous API calls
fetchPlanIfNeeded()
}

/// Fetch plan tier once at startup (skips if already known or max attempts reached)
func fetchPlanIfNeeded() {
guard settingsStore.hasUsageAPIConfig else { return }
guard planTier == nil && planFetchAttempts < 3 else { return }

let orgId = settingsStore.claudeOrgId
let cookie = "sessionKey=\(settingsStore.claudeSessionKey)"

DispatchQueue.main.asyncAfter(deadline: .now() + Constants.planFetchDelaySeconds) { [weak self] in
guard let self = self else { return }
guard self.planTier == nil && self.planFetchAttempts < 3 else { return }
self.fetchPlanInfo(orgId: orgId, cookie: cookie)
}
}

/// Manual refresh: fetch usage immediately, then plan after stagger delay
func refreshAll() {
guard settingsStore.hasUsageAPIConfig else { return }

let orgId = settingsStore.claudeOrgId
let cookie = "sessionKey=\(settingsStore.claudeSessionKey)"

fetchUsageData(orgId: orgId, cookie: cookie)

planFetchAttempts = 0
DispatchQueue.main.asyncAfter(deadline: .now() + Constants.planFetchDelaySeconds) { [weak self] in
guard let self = self else { return }
self.fetchPlanInfo(orgId: orgId, cookie: cookie)
}
}

private func scheduleNextPoll() {
Expand Down Expand Up @@ -193,13 +220,7 @@ class UsageService: ObservableObject {
let orgId = settingsStore.claudeOrgId
let cookie = "sessionKey=\(settingsStore.claudeSessionKey)"

// Fetch both usage and spend data in parallel
fetchUsageData(orgId: orgId, cookie: cookie)
fetchSpendData(orgId: orgId, cookie: cookie)
// Fetch plan info with retry (up to 3 attempts per polling session)
if planTier == nil && planFetchAttempts < 3 {
fetchPlanInfo(orgId: orgId, cookie: cookie)
}
}

private func fetchUsageData(orgId: String, cookie: String) {
Expand Down Expand Up @@ -281,18 +302,12 @@ class UsageService: ObservableObject {
}
}

// Preserve spend data from previous fetch if available
let prevSpend = self.latestUsage

let usage = UsageData(
sessionUtilization: decoded.five_hour?.utilization ?? 0,
sessionResetsAt: self.parseDate(decoded.five_hour?.resets_at),
weeklyUtilization: decoded.seven_day?.utilization,
weeklyResetsAt: self.parseDate(decoded.seven_day?.resets_at),
breakdowns: breakdowns,
monthlyLimitCents: prevSpend?.monthlyLimitCents,
monthlyUsedCents: prevSpend?.monthlyUsedCents,
outOfCredits: prevSpend?.outOfCredits,
fetchedAt: Date()
)
self.latestUsage = usage
Expand All @@ -312,58 +327,6 @@ class UsageService: ObservableObject {
}.resume()
}

private func fetchSpendData(orgId: String, cookie: String) {
let urlString = "\(Constants.usageAPIBase)/\(orgId)/overage_spend_limit"
guard let url = URL(string: urlString) else { return }

var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(cookie, forHTTPHeaderField: "Cookie")

URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
DispatchQueue.main.async {
guard let self = self else { return }
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200,
let data = data else { return }

// Update session key if server sends a different one (without triggering polling restart)
if let setCookie = httpResponse.value(forHTTPHeaderField: "Set-Cookie"),
let newKey = self.extractSessionKey(from: setCookie),
newKey != self.settingsStore.claudeSessionKey {
self.isUpdatingSessionKey = true
self.settingsStore.claudeSessionKey = newKey
self.isUpdatingSessionKey = false
}

if let decoded = try? JSONDecoder().decode(SpendResponse.self, from: data),
let existing = self.latestUsage {
// Merge spend data into existing usage data
self.latestUsage = UsageData(
sessionUtilization: existing.sessionUtilization,
sessionResetsAt: existing.sessionResetsAt,
weeklyUtilization: existing.weeklyUtilization,
weeklyResetsAt: existing.weeklyResetsAt,
breakdowns: existing.breakdowns,
monthlyLimitCents: decoded.monthly_credit_limit,
monthlyUsedCents: decoded.used_credits,
outOfCredits: decoded.out_of_credits,
fetchedAt: existing.fetchedAt
)

// Log spend data
var spendParts = ["Spend API OK:"]
if let used = decoded.used_credits, let limit = decoded.monthly_credit_limit {
spendParts.append(String(format: "$%.2f/$%.2f", Double(used) / 100.0, Double(limit) / 100.0))
}
if decoded.out_of_credits == true { spendParts.append("OUT OF CREDITS") }
self.logStore?.log(spendParts.joined(separator: " "))
}
}
}.resume()
}

private func fetchPlanInfo(orgId: String, cookie: String) {
let urlString = "\(Constants.usageAPIBase)/\(orgId)"
guard let url = URL(string: urlString) else { return }
Expand Down
Loading