A native macOS menu-bar app (Swift 6 / AppKit, macOS 26+) that polls Claude.ai usage once per minute and renders the result in the menu bar. Single-binary SPM package, no Xcode project, no external runtime dependencies beyond system frameworks.
Primary path is a direct JSON API call over URLSession to
claude.ai/api/organizations/{uuid}/usage, reusing the logged-in
cookies. A hidden WebView is only spun up as a fallback (Cloudflare
clearance refresh, login, or DOM-scrape if the API shape changes). On a
healthy session no WebView is created, so idle footprint sits at ~14 MB.
(History: the app used to DOM-scrape the SPA via a per-minute ephemeral
WebView — that path is retained as the fallback.)
claude_counter/
├── Makefile # all developer commands (build/install/lint/test/ci)
├── .swiftlint.yml # SwiftLint config — strict, opt-in heavy
├── .swiftformat # SwiftFormat config — formatting source of truth
├── .periphery.yml # Periphery config — dead code detection
├── .pre-commit-config.yaml # pre-commit hook (gitleaks + Swift toolchain)
├── .github/workflows/ci.yml # GitHub Actions: build · test · lint · format · dead-code
├── CHANGELOG.md # user-facing changes; release.sh bump cuts Unreleased
├── BACKLOG.md # what is left, most pressing first
├── .claude/skills/release/ # the release procedure (order, mirror wait, rollback)
├── scripts/
│ ├── build-app.sh # bundle assembly + codesign (+ notarize) + install
│ ├── release.sh # release steps: check / bump / notes / build / cask
│ ├── periphery.sh # pinned open-source Periphery 3.8.0 (sha256-checked download)
│ └── setup-codesign-cert.sh # one-time stable cert in login keychain
└── App/
├── Package.swift # swift-tools 6.2, strict concurrency, warnings-as-errors
├── Sources/CounterShared/ # used by app + widget: UsageSnapshot (reads StatusExport v2), SharedContainer, UsageStyle
├── Sources/ClaudeCounterWidget/ # WidgetKit extension (small + medium), packaged as PlugIns/*.appex
├── Resources/*.entitlements # app: App Group; widget: sandbox + App Group
├── Sources/ClaudeCounter/
│ ├── ClaudeCounterApp.swift # @main, AppDelegate, accessory mode
│ ├── AppState.swift # @Observable, holds ClaudeUsage
│ ├── Logging/AppLog.swift # os.Logger facade (no NSLog allowed)
│ ├── Models/ClaudeUsage.swift
│ ├── Scraper/
│ │ ├── QuotaScraper.swift # 60s timer, state, entry point
│ │ ├── QuotaScraper+Orchestrator.swift # API-first scrape(), fallback routing, backoff
│ │ ├── UsageAPIClient.swift # URLSession: discovery + /usage fetch
│ │ ├── UsageResponseClassifier.swift # HTTP → UsageFetchResult (challenge/login/decode)
│ │ ├── UsageAPIModels.swift # Decodable: OrgSummary, UsageResponse, UsageLimit, FlatWindow
│ │ ├── UsageMapper.swift # pure: UsageResponse.limits[] → ClaudeUsage
│ │ ├── CookieBridge.swift # host-scoped read/write of WKWebsiteDataStore cookies
│ │ ├── OffHostRedirectGuard.swift # strips Cookie header on off-host redirect
│ │ ├── OrgIDStore.swift # UserDefaults cache of org uuid
│ │ ├── QuotaScraper+Lifecycle.swift # tearDown, watchdog, retry (fallback WebView)
│ │ ├── QuotaScraper+Navigation.swift # fallback WebView nav + /login detection
│ │ ├── QuotaScraper+Extract.swift # fallback: JS eval + debug dump
│ │ ├── QuotaScraper+JS.swift # fallback: the DOM extraction script
│ │ ├── QuotaPayload.swift # fallback: typed view over JS result
│ │ ├── QuotaParser.swift # fallback: pure QuotaPayload → ClaudeUsage
│ │ ├── ScrapeDebugLog.swift # fallback scrape dump to ~/Library/Logs
│ │ ├── ContentBlocker.swift # WKContentRuleList (fallback WebView)
│ │ └── WebViewFactory.swift # WKWebView factory + shared Safari UA
│ ├── StatusBar/
│ │ ├── StatusBarController.swift
│ │ ├── StatusBarController+Menu.swift
│ │ └── QuotaTitleFormatter.swift
│ ├── Widget/WidgetBridge.swift # writes the snapshot to the App Group, reloads the widget on change
│ ├── Codex/ # Codex provider: auth.json token, /wham/usage, poller
│ ├── Export/ # `--json` CLI + CFMessagePort server, StatusExport schema v2
│ ├── Settings/SettingsStore.swift # UserDefaults-backed settings
│ ├── UI/
│ │ ├── Glass.swift # glassSurface/GlassGroup/backdrop
│ │ ├── GlassWindow.swift # see-through window chrome + full-window clear glass
│ │ ├── GlassWindowSlot.swift # builds/reshows a glass window, restores its frame
│ │ ├── ScrollEdgeFade.swift # content dissolves at scroll edges
│ │ ├── SettingsView*.swift, SettingsComponents.swift, CustomFormatEditor.swift
│ │ ├── UsageOverviewView.swift # Usage window: Claude + Codex cards
│ │ ├── UsageWindow.swift # NSWindow with WebView (login)
│ │ └── WebViewCoordinator.swift # OAuth popup handling
│ └── LoginItem/LoginItemManager.swift # SMAppService wrapper
└── Tests/ClaudeCounterTests/ # Swift Testing; 146 tests / 21 suites
├── UsageAPIModelsTests, UsageMapperTests, OrgIDStoreTests, CookieBridgeTests
├── UsageAPIClientTests (+Classification, +TestSupport, StubURLProtocol)
├── QuotaScraperOrchestrationTests, QuotaScraperBackoffTests (+TestSupport)
└── ClaudeUsageTests, QuotaParserTests, JSQuotaParserTests, QuotaPayloadTests, …
NSStatusItem ──► click ──► NSMenu (Open / Login / Refresh / Quit)
▲
│ withObservationTracking re-renders title on every change
│
AppState.usage ◄──── QuotaScraper (60s Timer) ──► scrape() [+Orchestrator]
│ │
│ ├─ UsageAPIClient.fetch() (URLSession, no cookie jar)
│ │ ├─ CookieBridge: read claude.ai cookies from WKWebsiteDataStore
│ │ ├─ OrgIDStore: cached uuid? else GET /api/organizations
│ │ ├─ GET /api/organizations/{uuid}/usage (Safari UA + cookies)
│ │ └─ classify → UsageMapper.map(limits[]) → ClaudeUsage
│ │
│ └─ UsageFetchResult:
│ .success → AppState.usage = … (NO WebView)
│ .needsCookieRefresh / .decodeFailed → fallback WebView path
│ .notLoggedIn → arm backoff (suppress fallback until re-probe)
│ .transport → leave state untouched
│
QuotaTitleFormatter → " 9% 2h 28m 26%"
The fallback WebView path is the old pipeline (QuotaScraper
+Navigation/+Extract/+JS → QuotaPayload → QuotaParser): build hidden
WKWebView → load claude.ai/settings/usage → poll DOM → parse →
tearDown. It refreshes Cloudflare/session cookies and DOM-scrapes when
the API can't answer.
UsageWindow is the visible login window. It owns its own WKWebView
(blockHeavy: false, full content) on the same
WKWebsiteDataStore.default(), so a login there is picked up by both
the API path (via CookieBridge) and the fallback on the next tick.
- API-first; WebView is fallback only. The 60s tick must go through
UsageAPIClient(URLSession). Only.needsCookieRefresh/.decodeFailedmay spin a WebView. Instantiating a WebView on the happy path reintroduces the ~700 MB-class WebContent process the whole optimization story removed. - URLSession owns no cookie jar.
httpCookieStorage = nil,httpCookieAcceptPolicy = .never,httpShouldSetCookies = false. Cookies come only fromCookieBridgeper request. A jar would drift from the WebView store (the single source of truth). - Cookies are claude.ai-scoped and never logged.
CookieBridgefilters to exactclaude.aihost (rejects lookalikes);OffHostRedirectGuardstrips theCookieheader on any off-host redirect; no log line ever contains a cookie name or value (privacy: .private/ counts-only). Session token handling lives here — treat changes as security-sensitive. - Logged-out backoff persists across ticks.
.notLoggedInarms theloggedOutflag; the automatic timer must NOT clear it (else the WebView fallback would relaunch every minute). It clears only on an explicit re-probe (forceRefresh()from wake / Refresh Now / window open) or a.success. - Ephemeral fallback WebView. When the fallback does run: build → load → extract → tearDown. Never cache a persistent WebView.
- AppKit only. No
MenuBarExtra, no SwiftUI scenes. SwiftUI's status bar API can't render arbitraryNSAttributedStringtitles with our color logic. - Stable code-signing cert. TCC permissions and SMAppService
Login Item registration are tied to the signature's certificate
chain. Ad-hoc signing produces a fresh cdhash each build → macOS
resets permissions.
make setup-certcreates the cert once;build-app.shdetects and uses it automatically. WKWebsiteDataStore.default()is shared. Both the scraper and the visible window must use it. An ephemeral data store kills login.- Bundle ID stays
com.servitola.claudecounter. Changing it detaches existing TCC entries and Login Item registration.
make build # debug, no install — fast inner loop
make setup-cert # one-time per machine, creates self-signed cert
make install # build + replace /Applications + relaunch if running
make update # build + replace + always launch
make ship # update + git clean -dfx (frees ~212 MB build cache)
make reinstall # nuke /Applications/<app> then install
make uninstall # remove app (cookies stay)
make purge # uninstall + delete cookies and preferences
make verify-sign # show installed signature identitymake test # swift test (146 tests / 21 suites, Swift Testing, no live network)
make lint # SwiftLint --strict (treats warnings as errors)
make lint-fix # auto-fix what SwiftLint can
make format # SwiftFormat — rewrite sources in place
make format-check # CI-safe: error if anything would change
make dead-code # Periphery scan in --strict mode (scripts/periphery.sh)
make ci # everything above, in failure-fast order
make hooks-install # install pre-commit hook (lint + format + build + test + gitleaks)
make vm-smoke VERSION=x.y.z # published cask on a throwaway macOS 27 VM (tart, dotfiles `vm`)Periphery went commercial and archived its repository, so Homebrew deprecated
the formula (disabled 2027-08-12). scripts/periphery.sh downloads the last
open-source release (3.8.0, MIT) from GitHub, checks its sha256 and caches it in
~/Library/Caches/claude_counter/; no Homebrew install is needed, here or in CI.
It gets no fixes: Swift 6.4 already moved the index store, which the
dead-code target handles with --index-store-path.
CI in .github/workflows/ci.yml runs the same make ci on macos-26
(the Liquid Glass APIs need the macOS 26 SDK; macos-15 has only Swift 6.0).
Compiler is also strict:
swift-tools 6.2treatAllWarnings(as: .error)enableExperimentalFeature("StrictConcurrency")- Upcoming features:
ExistentialAny,InternalImportsByDefault,InferIsolatedConformances,NonisolatedNonsendingByDefault
scripts/build-app.sh writes Info.plist inline (LSUIElement=true,
macOS 26 minimum). It picks the stable cert if present, falls back to
ad-hoc with a warning.
Measure phys_footprint (what Activity Monitor's "Memory" column shows),
not RSS — RSS includes shared framework pages that don't count against
the app.
| State | phys_footprint |
|---|---|
| Idle, API path (~99% of the time) | ~14 MB |
| Fallback WebView active (brief) | spikes, then returns |
On the API path no WebContent/GPU helper spawns and WebKit/JSC ideally stay dormant. If idle footprint climbs back toward the old ~80 MB, or a WebContent process appears every tick, the API path has regressed (likely something forcing the WebView). Verify with:
PID=$(pgrep -x ClaudeCounter)
vmmap --summary $PID | grep "Physical footprint:"
# and confirm no per-tick helper:
ps -axo pid,comm | grep -i "WebKit.WebContent"Note: CookieBridge reading WKWebsiteDataStore and purgeResourceCache
on launch still initialize WebKit in-process today (a known residual ~few
MB + a Networking XPC); eliminating that needs a no-WebKit cookie read and
was deliberately left out (see work/completed/api-scraper for the analysis).
- Discovery —
GET /api/organizations→ first orguuid, cached inOrgIDStore(UserDefaults), re-discovered on auth/not-found failure. The uuid is UUID-validated before being interpolated into the path. - Fetch —
GET /api/organizations/{uuid}/usagewith the shared Safari UA (WebViewFactory.safariUserAgent) and CookieBridge cookies.URLSession(system TLS) passes Cloudflare where curl gets 403 — that fingerprint difference is why this can't be a shelled-out HTTP call. - Classify (
UsageResponseClassifier, shared by discovery + usage, runs before JSON decode): 403 + "Just a moment…" challenge →.needsCookieRefresh; 401 //loginredirect / 200-login-page body →.notLoggedIn; other non-200 →.decodeFailed. - Map (
UsageMapper):limits[]entrykind == "session"→ current,kind == "weekly_all"(neverweekly_scoped) → weekly;resets_atISO-8601 →Datestraight through; flatfive_hour/seven_dayare the fallback fields.percent(Double) truncates to Int.
ClaudeUsage stores currentResetAt: Date? (not minutes) so the
menu-bar title's 60-second refresh ticks down without a fresh fetch.
claude.ai/settings/usage is a React SPA (body.innerText is empty).
QuotaScraper+JS.swift walks the DOM, collects every aria-label +
text node, joins with |, then: \d+\.?\d*\s*%\s*used → percentages;
[role=progressbar][aria-valuenow] → numeric fallback; six "Resets in
Xh Ym" patterns + an absolute "Resets at 9:30 PM" fallback. This whole
path was the original mechanism — kept as insurance against the
unversioned /usage endpoint changing shape.
~/Library/Logs/ClaudeCounter/scrape-debug.txt is rewritten only when
the fallback runs, with percentages, bar values, matched pattern, and
the first 2000 chars of aggregated text. NSLog from a non-Apple-signed
bundle is filtered out of unified logging — this file is the fallback's
only runtime visibility.
ContentBlocker.shared.prewarm() runs from
applicationDidFinishLaunching. It compiles a WKContentRuleList
that drops image, font, media, popup, ping resources plus
~15 analytics/RUM domains. Compilation is async (~50-200 ms) — the
first scrape may run unfiltered, every subsequent one is blocked.
The visible Usage window passes blockHeavy: false so login flows,
brand assets, and CAPTCHAs render normally.
- The
/usageAPI is internal and unversioned. If its JSON shape changes,UsageMapperyields nil →.decodeFailed→ the DOM-scrape fallback takes over (degrades, doesn't break). The pinnedusage.jsonfixture in the tests flags shape drift early. - Cloudflare
cf_clearanceexpiry is the normal trigger for the fallback WebView: it re-passes the challenge, refreshes the cookie, and the API path resumes next tick. OnlyURLSession(system TLS) clears Cloudflare — curl/libcurl get 403. - claude.ai changing markup breaks only the fallback regex (DOM
scrape). If the fallback also fails, check
~/Library/Logs/ClaudeCounter/scrape-debug.txtand adjust patterns inQuotaScraper+JS.swift. security importPKCS12 password fails unlessopenssl pkcs12is invoked with-legacy. Modern OpenSSL defaults to AES-256-CBC whichsecurityrejects.- Watchdog (30 s) kills hung scrapes. Without it, a stuck WebContent process pins memory until next launch.
@MainActoreverywhere in the scraper. WKWebView andTimercallbacks must run on main; cross-actor hops are explicit viaTask { @MainActor in ... }.
- New menu item: edit
StatusBarController+Menu.swiftonly. Keep@objcmethods on the controller, not in extensions in separate files (Swift's selector dispatch wants them visible). - New persisted setting: add a key + getter/setter to
Settings/SettingsStore.swift(oneUserDefaultskey per field, dotted-namespaced, graceful fallback on missing/invalid), mirror it ontoAppState, hydrate once inClaudeCounterApp, and add a control toUI/SettingsView.swiftbound via the dual-write pattern (writes bothAppStatefor live re-render and the store for persistence). - Changing the scrape interval:
QuotaScraper.interval. Don't go below 30 s — claude.ai may rate-limit and the cost/benefit collapses.
StatusBar/QuotaTitleFormatter.swift + +Template.swift render the
status-bar string. Two orthogonal axes on AppState:
displayMode(ProviderDisplayMode): which providers show.titleFormat(Models/TitleFormat.swift): how each chip renders + colors. Presets: full/weekly/session/weeklyAlert/custom..fulluses the legacy per-provider renderer (omits empty windows — keep for regression). All other presets + custom go through the flat token engine ({claude.session},{codex.weekly},.resetvariants; literal text passes through; nil →–%/–m). Coloring is a separateColorRule(driver/target/warn/alert): weeklyAlert colors BOTH weekly numbers by Claude's session (70/92).
Settings and Usage windows are non-opaque (NSWindow.applyGlassChrome): a
full-window SwiftUI glassEffect(.clear) shows the desktop through, frosted
glassSurface cards fill it to an 8 pt rim, and the top card runs under the
titlebar. Learned the hard way:
NSVisualEffectView(.behindWindow)andNSGlassEffectViewas the window background render near-opaque; only SwiftUI glass samples the desktop.- An empty unified
NSToolbaris what drops the traffic lights inside the top card;safeAreaRegions = []stops an empty strip under the content. - A scrolling root must not size the window (
sizesToContent: false): its ideal size is the whole scroll height. Settings' autosave key is.v2because 1.1.0 saved screen-tall frames. - Restore the autosaved frame after
applyGlassChrome(GlassWindowSlotdoes): restored before it, the toolbar and the hosting controller nudged the window 33 pt up on every launch. - The system focus ring ignores rounded glass shapes: buttons use
.shapedFocusRing(shape), never a bare.focusEffectDisabled(). - Force the light theme for one app without touching the system:
defaults write com.servitola.claudecounter NSRequiresAquaSystemAppearance -bool yes, relaunch;defaults deletethe key afterwards. - Screenshots of these windows show whatever is behind them: put a neutral
backdrop (e.g. an
hs.canvas) behind before capturing.
ClaudeCounterWidget is an ordinary SwiftPM executable linked with
-e _NSExtensionMain; build-app.sh wraps it into
Contents/PlugIns/ClaudeCounterWidget.appex (CFBundlePackageType XPC!,
NSExtensionPointIdentifier com.apple.widgetkit-extension). No Xcode project.
- Data path:
WidgetBridgewritesStatusExportbytes toSharedContainer.snapshotURL(App GroupNZNV266K59.com.servitola.claudecounter) and callsreloadTimelinesonly whenDigest(percents + minute-rounded resets) changes — WidgetKit budgets reloads for a background app. The widget's timeline holds 60 one-minute entries so the countdown needs none. - Signing: appex and app are signed separately with their own entitlements
(never
--deep: the widget must keep its sandbox). The group is team-prefixed, so only a Developer ID signature of team NZNV266K59 reaches it; local builds use that identity when the keychain has it. - Debug:
pluginkit -m -p com.apple.widgetkit-extension -v | grep claudecounter;/usr/bin/log show --predicate 'process == "ClaudeCounterWidget"'(the user's shell has alogfunction, call the binary by path).
scripts/vm-smoke.sh runs the published cask through a fresh clone of the
gg27 tart base (macOS 27, Homebrew, Command Line Tools only) and deletes
it: about a minute. Learned while building it:
- The first launch of a quarantined app waits for macOS's "downloaded from
the Internet" prompt;
openandtart execthen hang. The script checks Gatekeeper first, then strips the quarantine; each step has its own alarm. - Building in that VM fails: in the macOS 27 SDK SwiftUI's
@Stateis a macro whose plugin ships only with full Xcode. Build tests there need a base baked with Xcode.
.claude/skills/release/SKILL.md is the procedure. In short: origin is the
private Gitea and the only push target; GitHub is fed by its push mirror. The
zip is built and notarized locally (make release-notarized, App Store
Connect API key from the environment — a keychain profile cannot be saved from
a non-GUI session). Create the GitHub release only after the mirror delivered
the tag, or gh makes the tag on the old commit and the mirror is rejected.
State (2026-10-01, main): 1.1.0 released and in Homebrew (notarized).
Since then, local only: AGPL licence, CI on macos-26, README/CHANGELOG/BACKLOG,
release tooling, the settings-window size fix and scroll fade. Next: 1.1.1
with the size fix. Open work is in BACKLOG.md.