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
30 changes: 19 additions & 11 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co

PingClaude is a macOS menu bar app that automatically pings Claude to manage the rolling 5-hour token usage window. It features:
- Scheduled pings via Claude API or CLI fallback
- Live usage tracking from claude.ai Web API
- Free usage polling from claude.ai Web API (with silent backoff on errors)
- Usage velocity tracking (burn rate in %/hr)
- Menu bar status display with percentage
- SwiftUI-based settings, history, and dashboard views
Expand Down Expand Up @@ -58,7 +58,7 @@ AppDelegate (lifecycle coordinator)
├── LogStore (file-backed event log)
├── PingHistoryStore (JSON-backed ping records)
├── PingService (API + CLI ping execution)
├── UsageService (polls claude.ai for usage metrics)
├── UsageService (free usage polling + plan tier detection)
├── UsageVelocityTracker (burn rate tracking with persistent samples)
├── SchedulerService (timer + sleep/wake handling)
└── StatusBarController (menu bar UI + Combine observers)
Expand Down Expand Up @@ -101,13 +101,13 @@ Check `canPingViaAPI` to determine which path. API mode requires `orgId` + `sess

`AppDelegate` calls `ProcessInfo.beginActivity(.userInitiated)` to prevent macOS App Nap from suspending timers. Critical for reliable ping scheduling.

**5. Usage Polling is Free**
**5. Free Usage Polling**

`UsageService` polls claude.ai usage API without consuming tokens or starting sessions. Runs on configurable interval (default: 1 min).
`UsageService` polls the claude.ai usage API on a configurable interval (default: 5 min) without consuming tokens. On API errors (429, network), it silently backs off with exponential delay (max 30 min) — no user-facing error display. Usage data is also set by `StatusBarController.updateUsageFromPing()` from each ping's `message_limit` SSE event. Both sources merge into `latestUsage`; whichever updates most recently wins. Plan tier is fetched separately at startup.

**6. Reset-Triggered Ping**

When usage API reports a session reset time and utilization > 20%, `SchedulerService` automatically schedules a ping at the exact reset moment (with retry logic). Works independently of regular schedule.
When ping data reports a session reset time and utilization > 20%, `SchedulerService` automatically schedules a ping at the exact reset moment (with retry logic). Works independently of regular schedule.

### Data Flow

Expand All @@ -120,13 +120,21 @@ User/Timer → PingService.ping()
→ StatusBarController updates via Combine
```

**Usage tracking:**
**Usage tracking (two sources):**
```
Timer → UsageService.poll()
→ Parse API response
→ Update @Published properties
→ UsageVelocityTracker.recordSample()
→ StatusBarController updates menu bar icon with %
Source 1 (polling):
Timer → UsageService.fetchUsage()
→ Parse API response (free, no tokens)
→ Update latestUsage @Published
→ On 429: silent exponential backoff (max 30 min)

Source 2 (pings):
PingService.ping() → message_limit SSE event
→ StatusBarController.updateUsageFromPing()
→ Sets usageService.latestUsage

Both → UsageVelocityTracker.recordSample()
→ Menu bar icon updates with %
```

**Settings changes:**
Expand Down
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# PingClaude

A macOS menu bar app that automatically pings Claude to manage your rolling token usage window, with optional live usage tracking from the Claude Web API.
A macOS menu bar app that automatically pings Claude to manage your rolling token usage window, with free live usage tracking from the Claude Web API.

## Why?

Claude Code has a rolling 5-hour token usage window. If you start coding at 10 AM and hit the limit at noon, you have to wait until 3 PM for those tokens to free up. By sending small automated pings earlier (e.g., 7 AM), those tokens roll off at noon, effectively resetting your window right when you need it.

PingClaude automates this strategy — it runs in your menu bar, pings Claude on a schedule, and can show your real-time session utilization percentage and exact reset time.
PingClaude automates this strategy — it runs in your menu bar, pings Claude on a schedule, and shows your real-time session utilization percentage and exact reset time.

## Screenshots

Expand Down Expand Up @@ -105,17 +105,17 @@ Settings, Ping History, and Claude Info share a single tabbed window. Opening an
- **Interval** — Time between pings (15 minutes to 4 hours)
- **Ping on startup** — Immediately ping when the app first launches. If network is unavailable, retries automatically with exponential backoff (15s, 30s, 60s, 120s) for up to 5 minutes.
- **Ping on wake** — Immediately ping when your computer wakes from sleep. If network is unavailable (common with VPN), retries automatically with exponential backoff for up to 5 minutes.
- **Usage poll** — How often to refresh usage data (15 sec to 5 min, default: 1 min). This is free — no tokens consumed, no sessions started.
- **Usage poll** — How often to refresh usage data (1 min to 10 min, default: 5 min). This is free — no tokens consumed, no sessions started. Requires Web API credentials.

**Token Window:**
- **Reset window** — Hours until tokens roll off (default: 5 hours). Set to 0 (Disabled) if Claude removes this rolling window.

**Claude Web API:**

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.
Enables three features: API-based pinging (no CLI needed), plan tier detection, and free usage polling (session %, weekly %, per-model breakdowns). Usage polling reads your account metrics without consuming any tokens or starting a session. If the usage API is temporarily unavailable, the app silently falls back to usage data from pings. 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.
- **Session Key** — Your `sessionKey` cookie. Auto-refreshes on each API call, so once entered it stays valid.

**Storage:**
- **Log folder** — Where ping history is saved (default: `~/Library/Logs/PingClaude/`)
Expand All @@ -132,15 +132,15 @@ A visual dashboard showing:
- **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.)
- Reset countdowns and times
- Auto-refreshes on the configured usage poll interval, plus a manual Refresh button
- Auto-refreshes on the configured usage poll interval, plus on each ping

Usage pace is computed from periodic usage samples stored locally. It starts showing data after at least 2 samples are collected (typically within 1-2 minutes of launching with usage polling enabled).

Usage polling is free — no tokens consumed, no sessions started. Requires Claude Web API credentials to be configured in Settings.
Usage polling is free — no tokens consumed, no sessions started. If the API is temporarily unavailable, the app silently backs off and continues showing data from pings. Requires Claude Web API credentials to be configured in Settings.

### Reset-Triggered Ping

When the usage API reports a session reset time and your utilization is above 20%, PingClaude automatically schedules a ping at the exact reset moment. This ensures you start the new session window immediately. If the session hasn't actually reset yet, it retries up to 3 times with 30-second delays. This works independently of the regular schedule — even if the schedule is disabled, reset pings will fire as long as usage polling is active.
When the usage API or a ping reports a session reset time and your utilization is above 20%, PingClaude automatically schedules a ping at the exact reset moment. This ensures you start the new session window immediately. If the session hasn't actually reset yet, it retries up to 3 times with 30-second delays. This works independently of the regular schedule — even if the schedule is disabled, reset pings will fire as long as usage polling is active.

### Network Retry on Wake/Startup

Expand Down Expand Up @@ -216,7 +216,7 @@ Sources/PingClaude/
├── StatusBarController.swift # Menu bar icon, menu, Combine observers
├── PingService.swift # API ping + CLI fallback with timeout
├── SchedulerService.swift # Timer scheduling + sleep/wake handling
├── UsageService.swift # Polls claude.ai usage API for live metrics
├── UsageService.swift # Free usage polling + plan tier detection (silent backoff)
├── UsageVelocityTracker.swift # Burn rate tracking (%/hr) with persistent samples
├── SettingsStore.swift # UserDefaults-backed @Published config
├── SettingsView.swift # SwiftUI settings form
Expand Down Expand Up @@ -262,7 +262,7 @@ Your Claude Web API credentials (Org ID and Session Key) may be missing or expir
Check Console.app for diagnostic messages — filter by "PingClaude". The app retries plan detection up to 3 times. Auth errors (401/403) stop retries until you update the session key.

**Usage data not showing:**
Ensure both Org ID and Session Key are configured in Settings. Usage polling is free and doesn't consume tokens. The session key auto-refreshes on each poll, but may need to be re-entered if the app was offline for an extended period.
Ensure both Org ID and Session Key are configured in Settings. Usage polling is free and doesn't consume tokens. If the usage API is temporarily unavailable (e.g., during Anthropic outages), the app silently backs off and shows data from pings instead. The session key auto-refreshes on each API call, but may need to be re-entered if the app was offline for an extended period.

**Viewing logs:**
- App event log: `cat ~/Library/Logs/PingClaude/pingclaude.log`
Expand Down
2 changes: 1 addition & 1 deletion Sources/PingClaude/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
schedulerService.start()
}

// Start usage polling if configured
// Start usage polling + plan fetch if API configured
if settingsStore.hasUsageAPIConfig {
usageService.startPolling()
}
Expand Down
31 changes: 6 additions & 25 deletions Sources/PingClaude/ClaudeInfoView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ struct ClaudeInfoView: View {
VStack(spacing: 12) {
Spacer().frame(height: 60)
ProgressIndicator()
Text("Fetching usage data...")
Text("Waiting for first ping...")
.font(.system(size: 13))
.foregroundColor(.secondary)
Spacer()
Expand Down Expand Up @@ -149,26 +149,8 @@ struct ClaudeInfoView: View {
}

// Last updated
if let error = usageService.lastError {
HStack(spacing: 4) {
Text("\u{26A0}")
Text(error)
.font(.system(size: 11))
.foregroundColor(.orange)
}
}

HStack {
Text("Last updated: \(formattedFetchTime(usage.fetchedAt)) \u{00B7} Auto-refreshes every \(formattedPollInterval)")
.font(.system(size: 11))
.foregroundColor(.secondary)
Spacer()
Button("Refresh") {
usageService.refreshAll()
}
}
Text("Usage polling is free \u{2014} no tokens consumed, no sessions started.")
.font(.system(size: 10))
Text("Last updated: \(formattedFetchTime(usage.fetchedAt)) \u{00B7} Auto-refreshes every \(formattedPollInterval) + on each ping")
.font(.system(size: 11))
.foregroundColor(.secondary)

// Log & Troubleshooting
Expand All @@ -192,7 +174,6 @@ struct ClaudeInfoView: View {
VStack(alignment: .leading, spacing: 2) {
Text("\u{2022} Plan shows \"--\": Check Web API credentials in Settings")
Text("\u{2022} Auth errors: Re-enter session key from browser")
Text("\u{2022} Parse errors: API response format may have changed")
Text("\u{2022} System diagnostics: Open Console.app, filter by \"PingClaude\"")
}
.font(.system(size: 11))
Expand Down Expand Up @@ -247,9 +228,9 @@ struct ClaudeInfoView: View {
}

private var formattedPollInterval: String {
let secs = settings.usagePollingSeconds
if secs < 60 { return "\(secs) sec" }
return "\(secs / 60) min"
let seconds = settings.usagePollingSeconds
if seconds < 60 { return "\(seconds)s" }
return "\(seconds / 60) min"
}

private func formattedFetchTime(_ date: Date) -> String {
Expand Down
2 changes: 1 addition & 1 deletion Sources/PingClaude/Constants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ enum Constants {
// Retry configuration for wake/startup pings (network delays, VPN connection)
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
static let usageMaxBackoffSeconds: TimeInterval = 1800 // Max backoff for usage API errors (30 min)

// Available models
static let availableModels = ["haiku", "sonnet", "opus"]
Expand Down
5 changes: 0 additions & 5 deletions Sources/PingClaude/SchedulerService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -306,11 +306,6 @@ class SchedulerService: ObservableObject {

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

// 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 }
self.pingHistoryStore.addPingResult(result)
Expand Down
18 changes: 8 additions & 10 deletions Sources/PingClaude/SettingsStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ class SettingsStore: ObservableObject {
@Published var usagePollingSeconds: Int {
didSet { defaults.set(usagePollingSeconds, forKey: Constants.Keys.usagePollingSeconds) }
}

/// Whether we have enough config to poll the usage API
/// Whether we have enough config for API-based pinging
var hasUsageAPIConfig: Bool {
!claudeSessionKey.isEmpty && !claudeOrgId.isEmpty
}
Expand All @@ -92,7 +91,7 @@ class SettingsStore: ObservableObject {
Constants.Keys.pingOnStartup: Constants.Defaults.pingOnStartup,
Constants.Keys.claudeSessionKey: "",
Constants.Keys.claudeOrgId: "",
Constants.Keys.usagePollingSeconds: 60
Constants.Keys.usagePollingSeconds: 300
])

// Load values
Expand All @@ -115,19 +114,18 @@ class SettingsStore: ObservableObject {
claudeSessionKey = defaults.string(forKey: Constants.Keys.claudeSessionKey) ?? ""
claudeOrgId = defaults.string(forKey: Constants.Keys.claudeOrgId) ?? ""

// Migrate old usagePollingMinutes → usagePollingSeconds
if defaults.contains(key: Constants.Keys.usagePollingSeconds) {
usagePollingSeconds = defaults.integer(forKey: Constants.Keys.usagePollingSeconds)
} else if defaults.contains(key: Constants.Keys.usagePollingMinutes) {
usagePollingSeconds = defaults.integer(forKey: Constants.Keys.usagePollingMinutes) * 60
// Migrate legacy usagePollingMinutes → usagePollingSeconds
if let legacyMinutes = defaults.object(forKey: Constants.Keys.usagePollingMinutes) as? Int, legacyMinutes > 0 {
usagePollingSeconds = legacyMinutes * 60
defaults.removeObject(forKey: Constants.Keys.usagePollingMinutes)
} else {
usagePollingSeconds = 60
usagePollingSeconds = defaults.integer(forKey: Constants.Keys.usagePollingSeconds)
}

// Fix zero values from register(defaults:) for integers
if intervalMinutes == 0 { intervalMinutes = Constants.Defaults.intervalMinutes }
if maxLogSizeMB == 0 { maxLogSizeMB = Constants.Defaults.maxLogSizeMB }
if usagePollingSeconds == 0 { usagePollingSeconds = 60 }
if usagePollingSeconds == 0 { usagePollingSeconds = 300 }
// resetWindowHours == 0 is valid (means "no window tracking"), only fix if never set
if !defaults.contains(key: Constants.Keys.resetWindowHours) {
resetWindowHours = Constants.Defaults.resetWindowHours
Expand Down
Loading
Loading