agentleFS
NihondoNihondo/AgentLimits/CLAUDE.md

AgentLimits

CLAUDE.md65 starsChanged 3 months agoMITView on GitHub

AgentLimits is a macOS Sonoma+ menu bar app with WidgetKit widgets that display usage limits (Codex/Claude Code) and ccusage token usage (today/this week/this month). The app embeds WKWebView for service login and fetches usage data from internal backend APIs. Login WebViews are kept active in the background only for providers with a successful cached usage snapshot. ccusage token usage is fetched via CLI and stored as snapshots for widgets.

  • In this repositoryOne other file it gives its agents.

The file

We split this CLAUDE.md into the rules it gives an agent

12 rules. About 0 are common, 6 are distinctive, and 6 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈6

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 6

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    After renewing an Apple Development certificate, refresh development provisioning profiles for both the app and widget.

    line 26
  2. Distinctive:

    When the settings window is closed, the icon hides again (unless the user turned the toggle off while settings were open)

    line 145
  3. Very specific:

    When usage exceeds pacemaker in used mode only, the outer ring is segmented and color-coded (green → orange → red) to show warning/danger …

    line 158
  4. Distinctive:

    Test execution from settings UI

    line 205
  5. Very specific:

    Do not add UsageWindowKind.monthly.

    line 251
  6. Distinctive:

    Keep README.md in English

    line 334
  7. Very specific:

    Keep README_ja.md in Japanese

    line 335
  8. Distinctive:

    Keep AGENTS.md and CLAUDE.md in English

    line 336
  9. Very specific:

    Create GitHub Release with tag v{MARKETING_VERSION} and attach AgentLimits.zip

    line 358
  10. Distinctive:

    Import it into Keychain with:

    line 376
  11. Very specific:

    Verify with generate_appcast — it should sign without prompting for a key

    line 380
  12. Very specific:

    If the private key is lost, generate a new key pair with generate_keys, update SUPublicEDKey in Info.plist, and publish a new release.

    line 382

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

AgentLimits is a macOS Sonoma+ menu bar app with WidgetKit widgets that display usage limits (Codex/Claude Code) and ccusage token usage (today/this week/this month). The app embeds WKWebView for service login and fetches usage data from internal backend APIs. Login WebViews are kept active in the background only for providers with a successful cached usage snapshot. ccusage token usage is fetched via CLI and stored as snapshots for widgets.

Build Commands

# Open in Xcode (recommended)
xed AgentLimits.xcodeproj

# Build from CLI
xcodebuild -scheme AgentLimits -destination 'platform=macOS'

# Run tests
xcodebuild test -scheme AgentLimits -destination 'platform=macOS'

Development Signing Troubleshooting

  • Set the local team in Configurations/DevelopmentTeam.local.xcconfig. Check the effective DEVELOPMENT_TEAM with xcodebuild -scheme AgentLimits -showBuildSettings before changing project settings.
  • The app and widget must use the same team. The widget identifier com.dmng.agentlimit.AgentLimit.AgentLimitWidget must be a regular App ID, not an App Clip, with the existing group.com.dmng.agentlimit App Group assigned.
  • After renewing an Apple Development certificate, refresh development provisioning profiles for both the app and widget. A profile can remain within its own validity period while containing an expired certificate. Compare certificate fingerprints, not just display names.
  • Try a signed build with xcodebuild -scheme AgentLimits -destination 'platform=macOS' -allowProvisioningUpdates. A build with CODE_SIGNING_ALLOWED=NO does not validate signing or provisioning.
  • If automatic signing reports that the existing widget Bundle ID is unavailable, inspect its registration in Apple Developer. On Demand Install Capable identifies an App Clip; such a registration is unsuitable for this macOS widget and may be absent from the macOS development profile App ID list. Do not rename the production Bundle ID just to suppress the error. Correcting a mistaken registration may require Apple Developer support or deletion and re-registration; obtain explicit approval before deleting an identifier.

Architecture

Data Flow

  1. User logs into service (chatgpt.com or claude.ai or github.com) via WKWebView
  2. *UsageFetcher executes JavaScript to extract auth token/org ID, then fetches usage API:
    • Codex: https://chatgpt.com/backend-api/wham/usage
    • Claude Code: https://claude.ai/api/organizations/{orgId}/usage
    • GitHub Copilot: https://github.com/github-copilot/chat/entitlement
    • Codex weekly-only responses may arrive in API primary_window; when its limit_window_seconds is within one second of 604,800 and no usable secondary window exists, snapshot creation moves it to secondaryWindow with .secondary kind and leaves primaryWindow nil.
    • Codex monthly-only responses are detected from limit_window_seconds > UsageLimitDuration.sevenDays + 1, not from plan_type; monthly Codex snapshots keep primaryWindow and drop secondaryWindow.
  3. UsageViewModel manages auto-refresh (configurable 1-10 minutes) and per-provider state
  4. UsageSnapshotStore persists usage snapshots as JSON under App Group container
    • A cached usage snapshot is also the login-history signal used to decide whether a provider WebView may stay active in the background.
  5. CCUsageFetcher runs CLI to fetch token usage:
    • Codex: npx -y ccusage@latest codex daily
    • Claude Code: npx -y ccusage@latest claude daily
    • The executed command is a per-provider editable template (CCUsageSettings.commandTemplate); when empty, it falls back to the generated default above plus additional args. {{since}} in the template expands to the current month's start date (YYYYMMDD) at execution time; -j and the placeholder itself are part of the template, not auto-appended.
  6. CopilotBillingFetcher fetches billing usage via WebView JS (triggered after Copilot entitlement fetch):
    • API: https://github.com/settings/billing/usage_table?group=0&period=3&product=&query=
  7. TokenUsageViewModel manages auto-refresh (configurable 1-10 minutes) and snapshot persistence
  8. CustomUsageViewModel runs enabled custom service executables concurrently on the Usage refresh interval, validates stdout, and atomically persists the exact bytes to usage_snapshot_custom_<provider>.json. Each provider has an in-flight guard; failures preserve the previous successful snapshot.
  9. Widgets read their respective snapshot files (no network access). CustomUsageWidget resolves a configured AppEntity through the App Group service index and reads the selected custom snapshot.
  10. ThresholdNotificationManager converts built-in and custom data to UsagePresentationSnapshot, then checks service-key + semantic-window thresholds.
  11. MenuBarController (AppKit NSStatusItem) manages the menu bar icon and dropdown menu
  • Icon label: MenuBarLabelContentView rendered via ImageRenderer → NSStatusItem.button.image
  • Menu dropdown: dashboard rows use NSHostingView<DashboardMenuItemView> as NSMenuItem.view
  1. Bundled Claude Code status line script reads snapshots + App Group settings for CLI display

Key Components

FilePurpose
AgentLimits/App/AgentLimitsApp.swiftMain app entry (@main), settings Window scene, deep link handling
AgentLimits/App/AppSharedState.swiftShared app state; applies login-history-based WebView background policy and owns settings window close callbacks
AgentLimits/App/MenuBar/MenuBarController.swiftNSStatusItem + NSMenu management; renders icon via ImageRenderer, dashboard rows via NSHostingView
AgentLimits/App/MenuBar/MenuBarLabelContent.swiftSwiftUI views for menu bar icon (MenuBarLabelContentView, MenuBarProviderStatusView, MenuBarPercentLineView)
AgentLimits/App/MenuBar/DashboardMenuItemView.swiftPer-provider dashboard row (header + linear bars + percent labels) used as NSMenuItem.view
AgentLimits/App/MenuBar/UsageLinearBarView.swiftLinear progress bar (usage bar + pacemaker bar) — linear equivalent of UsageDonutView
AgentLimits/App/MenuBar/AppUsageColorResolver.swiftApp-side color resolver equivalent to WidgetUsageColorResolver in the widget target
AgentLimits/App/SettingsTabView.swiftTab-based settings UI (Usage, ccusage, Wake Up, Notification, Advanced)
AgentLimits/App/DesignTokens.swiftShared design tokens (spacing/corners/window min size)
AgentLimits/App/CLICommandSettingsView.swiftAdvanced Settings UI (CLI paths + scripts + widget tap action + menu bar icon hide toggle)
AgentLimits/App/LanguageManager.swiftLanguage settings management (System or any bundled localization)
AgentLimits/App/LoginItemManager.swiftLogin item (start at login) management
AgentLimits/App/AppLogger.swiftApplication-wide logging utility
AgentLimits/App/AutoRefreshCoordinator.swiftAuto-refresh cycle coordination
AgentLimits/App/ShellExecutor.swiftShell command execution utility
AgentLimits/CustomUsage/CustomUsageServiceStore.swiftDynamic custom service registry and App Group widget-safe descriptor synchronization
AgentLimits/CustomUsage/CustomUsageScriptRunner.swiftDirect executable runner with timeout and stdout/stderr limits
AgentLimits/CustomUsage/CustomUsageViewModel.swiftCustom refresh scheduling, in-flight deduplication, exact-byte snapshot persistence, notifications, and widget reloads
AgentLimits/CustomUsage/CustomUsageSettingsView.swiftList/detail custom service management UI
AgentLimits/Usage/CodexUsageFetcher.swiftCodex API + JS token extraction
AgentLimits/Usage/ClaudeUsageFetcher.swiftClaude API + JS org ID extraction
AgentLimits/Usage/CopilotUsageFetcher.swiftGitHub Copilot entitlement API + JS cookie-based auth
AgentLimits/Usage/CopilotBillingFetcher.swiftGitHub Copilot billing usage_table API + daily aggregation
AgentLimits/Usage/UsageViewModel.swiftUsage limits state, auto-refresh, per-provider tracking, threshold check
AgentLimits/Usage/ProviderStateManager.swiftPer-provider state management (Codex/Claude Code/Copilot independent tracking)
AgentLimits/Usage/UsageDisplayModeStore.swiftDisplay mode persistence and snapshot conversion
AgentLimits/Usage/AppUsageModels.swiftApp-only display mode + localized errors + ProviderOrderStore (provider display order persistence)
AgentLimits/Usage/ContentView.swiftUsage limits settings UI with WebView
AgentLimits/Usage/WebViewStore.swiftWKWebView lifecycle, page-ready detection, suspend/resume for inactive login pages
AgentLimits/Usage/WebViewScriptRunner.swiftJavaScript injection executor
AgentLimits/Usage/UsageWebViewPool.swiftPer-provider WebViewStore management and background active-provider policy
AgentLimits/CCUsage/TokenUsageViewModel.swiftccusage state, auto-refresh, snapshot persistence
AgentLimits/CCUsage/CCUsageFetcher.swiftCLI execution + parsing for ccusage
AgentLimits/CCUsage/CCUsageSettingsView.swiftccusage settings UI
AgentLimitsShared/UsageModels.swiftShared usage models/store and helpers
AgentLimitsShared/CustomUsageModels.swiftCommon service identity, semantic windows, custom JSON contract/validator, exact-byte store, and widget service index
AgentLimitsShared/UsageColorSettings.swiftUsage color persistence (menu bar + widgets)
AgentLimitsShared/TokenUsageModels.swiftShared token usage models/store and helpers
AgentLimitsShared/TokenUsageFormatting.swiftShared cost/token formatting for ccusage
AgentLimitsShared/WidgetTapActionSettings.swiftWidget tap action settings (open website / refresh data)
AgentLimitsTests/LanguageCodeResolverTests.swiftLanguage resolution and English fallback regression tests
AgentLimitsWidget/AgentLimitsWidget.swiftUsage limits widget TimelineProvider and donut gauge UI
AgentLimitsWidget/CustomUsageWidget.swiftAppIntent-configurable custom usage widget and service entity query
AgentLimitsWidget/TokenUsageWidget.swiftccusage token usage widget TimelineProvider and rows UI (small + medium with heatmap)
AgentLimitsWidget/HeatmapView.swiftHeatmap grid view for medium widget (7 rows × 4-6 columns)
AgentLimitsWidget/HeatmapColors.swift5-level color scheme (GitHub-style) + accented mode support
AgentLimitsWidget/HeatmapLevelResolver.swiftQuartile-based level calculation for heatmap colors
AgentLimitsWidget/AgentLimitsWidgetBundle.swiftWidget bundle registration
AgentLimitsWidget/WidgetUsageModels.swiftWidget error localization (bridges shared resolver to widget strings)
AgentLimitsWidget/WidgetLanguageHelper.swiftWidget language helper
AgentLimitsWidget/WidgetUpdateTimeFormatter.swiftUpdate time formatting (HH:mm or --:-- if >24h ago)
AgentLimits/WakeUp/WakeUpScheduler.swiftLaunchAgent-based CLI scheduler for starting 5h sessions
AgentLimits/WakeUp/WakeUpSettingsView.swiftWake Up schedule configuration UI
AgentLimits/Notification/ThresholdNotificationManager.swiftUsage threshold notification logic
AgentLimits/Notification/ThresholdNotificationSettings.swiftPer-provider, per-window threshold settings model
AgentLimits/Notification/ThresholdNotificationStore.swiftThreshold settings persistence
AgentLimits/Notification/ThresholdSettingsView.swiftThreshold notification settings UI (thresholds + usage colors)
AgentLimits/Pacemaker/PacemakerSettingsView.swiftPacemaker settings UI (menu bar toggle + ring warning toggle + thresholds + colors)
AgentLimits/Scripts/agentlimits_statusline_claude.shClaude Code status line script (reads App Group snapshots)
scripts/cursor_usage.pySample Custom Usage CLI for Cursor's current billing-cycle plan usage (reads Cursor's local state DB and calls its internal usage endpoint)
scripts/antigravity_usage.pySample Custom Usage CLI for Google Antigravity (agy CLI/IDE) Gemini 5h/weekly quota: reads the macOS Keychain OAuth token and calls Cloud Code's retrieveUserQuotaSummary (requires a paid Antigravity plan; 403s on free tier)

Features

Menu Bar Status Display

  • Menu bar is implemented with AppKit NSStatusItem + NSMenu via MenuBarController (no MenuBarExtra)
  • Icon label: MenuBarLabelContentView rendered to NSImage via ImageRenderer and set on NSStatusItem.button
    • Two-line layout per provider: line 1 = provider name, line 2 = X% / Y% (5h/weekly)
    • Monthly-only providers (Copilot and Codex responses with a primary window longer than weekly) render a single X% line instead of X% / --
    • Color-coded status; pacemaker indicator ↑ shown when over budget
    • Percentage and arrow colors are adjusted only at menu bar render time: darken by 22% in light color scheme, lighten by 28% in dark color scheme
    • Responds to changes via Combine (objectWillChange) for snapshot updates and KVO for specific UserDefaults keys (display mode, menu bar toggles, provider order, pacemaker settings, status colors); 300 ms debounce before re-render
    • MenuBarIconCacheKey (snapshot fetchedAt, enabled state, display mode, color scheme) skips ImageRenderer when inputs are identical; KVO-triggered setting changes always invalidate the cache
  • Dashboard section at the top of the menu (collapsible per provider via Usage settings):
    • Each row is NSMenuItem.view = NSHostingView<DashboardMenuItemView> for full SwiftUI rendering
    • Header: provider name + remaining time (clock) + reset time (calendar)
    • Per-window linear bars: usage bar (pacemaker segment coloring) + pacemaker bar (N divisions with gaps)
    • Clicking a dashboard row opens the provider's usage page in the browser
    • Dashboard visibility is configurable per provider (menu_bar_dashboard_*_enabled, default: true)
    • Provider display order is user-configurable via drag-and-drop in Usage settings; persisted as provider_display_order ([String] rawValue array); managed by ProviderOrderStore in AppUsageModels.swift
  • Per-provider menu bar icon toggle (Codex/Claude Code/Copilot separately)
  • Hide menu bar icon option (menu_bar_icon_hidden): hides the entire NSStatusItem via isVisible = false
    • While hidden, relaunching the app (Finder double-click / Spotlight / open -a) triggers applicationShouldHandleReopen, which temporarily reveals the icon and opens the settings window
    • When the settings window is closed, the icon hides again (unless the user turned the toggle off while settings were open)
    • A 2-second guard after applicationDidFinishLaunching prevents accidental reveal from LaunchServices reopen events at startup
  • Status colors customizable from Notification settings
  • Menu includes: Display Mode, Language, Wake Up → Run Now, Start app at login, Check for Updates

Pacemaker

  • Time-based usage benchmark that calculates what percentage of the window has elapsed
  • Compares actual usage against elapsed time to determine if user is on track
  • Status levels based on difference (usedPercent - pacemakerPercent):
    • Green: at or below pacemaker (on track)
    • Orange: exceeds pacemaker (slight excess, default threshold: 0%)
    • Danger: 10%+ ahead of pacemaker (significant excess, default threshold: 10%)
  • Widget shows dual rings when pacemaker data is available: outer = actual usage, inner = pacemaker percentage
    • When usage exceeds pacemaker in used mode only, the outer ring is segmented and color-coded (green → orange → red) to show warning/danger zones (toggleable via pacemaker_ring_warning_enabled, enabled by default)
    • Inner pacemaker ring is always divided into equal time segments with small gaps: 5 segments for 5h window (1 per hour), 7 segments for weekly window (1 per day)
  • Menu bar shows both values with configurable colors
  • Thresholds and pacemaker colors are configurable in Pacemaker settings (warning/danger delta)

Usage Monitoring

  • Sign in to each service in the in-app WKWebView (Codex/Claude Code)
  • Usage tab places the login WKWebView in a bottom collapsible panel (chevron up/down), collapsed by default
  • Expanded login panel opens upward and can be closed via the handle toggle or background tap
  • Auto refresh interval is configurable (1-10 minutes)
  • Display mode (used/remaining) shared across app + widgets
  • Color-coded percentage display in widgets based on usage level and display mode
  • Widget tap action configurable: open website or refresh data (Advanced Settings)
  • Usage screen includes Clear Data to remove embedded browser login data, website storage, and cached usage snapshots, which resets login-history-based background WebView eligibility

Custom Usage Services

  • Dynamic services are identified by immutable provider slugs matching ^[a-z0-9][a-z0-9_-]{0,62}$; there is no isCustom field.
  • Common identity uses builtIn:<rawValue> or custom:<slug>. Semantic window kinds are 5h, 1w, 1month, and custom (for a window that doesn't semantically fit the first three — e.g. an arbitrary or expiry-less interval; it always sorts last and its default label is •). durationSeconds, not the kind value, drives pacemaker division count, so custom can still get 5- or 7-way divisions.
  • A custom executable runs directly with no arguments, from its parent directory, with the standard AgentLimits PATH prefix. Limits are 60 seconds, 256 KiB stdout, and 64 KiB stderr.
  • scripts/cursor_usage.py is a standalone sample custom-service executable: it reads cursorAuth/accessToken from Cursor's local state.vscdb and calls DashboardService/GetCurrentPeriodUsage on api2.cursor.sh. It emits the current billing-cycle plan usage as a 1month window using Cursor's returned percentage and reset time. It must never log the access token; Cursor's internal endpoint is intentionally treated as an unstable integration.
  • stdout must be schema version 1 JSON with a matching provider, timezone-aware fetchedAt, and one or two unique windows. label, title, resetAt, durationSeconds, and isPacemakerEnabled are optional; supplied reset dates are timezone-aware and supplied durations are finite positive values. label is the short compact-display name (donut center, dashboard row) and also disables pacemaker ring divisions when set; title is an independent longer heading used for the widget's medium-size detail column, the notification settings section title, and notification bodies — it resolves as title ?? label ?? kind's default text (SemanticUsageWindow.heading(fallback:)) and never affects pacemaker ring divisions. Pacemaker rendering requires the enabled flag, reset date, and duration. Unknown fields are accepted.
  • Expiry-backed threshold notifications deduplicate by reset date. No-expiry windows persist an active-threshold flag, notify once while usage remains above a level, and become eligible again only after usage falls below that level.
  • Successful output is validated before the original bytes (including the trailing newline) are atomically saved. Validation and execution failures never overwrite the last success.
  • Service settings include display name, script path, optional HTTP/HTTPS URL, auto refresh, menu bar visibility, and dashboard visibility. Run status stores last attempt, last success, and the latest error.
  • Custom services share the Usage 1–10 minute interval. Startup/periodic refresh respects auto refresh; manual tests and widget refresh deep links do not.
  • Wake Up and ccusage remain built-in-provider-only.
  • CustomUsageWidget is one AppIntentConfiguration kind. Each widget instance selects a CustomUsageServiceEntity; the App Group index contains only provider ID and display name, never executable paths.

Token Usage (ccusage)

  • CLI-based fetch and parsing for Codex/Claude Code
  • Separate widgets for ccusage token usage (small and medium sizes)
  • Per-provider enable/disable
  • The full command is user-editable per provider (e.g. to swap in a custom ccusage-compatible script that merges data across machines); {{since}} expands to the current month's start date, and clearing the field restores the generated default
  • Small widget: Usage summary (today/week/month cost and tokens)
  • Medium widget: Usage summary + GitHub-style heatmap
    • Layout: 7 rows (Sun-Sat) × 4-6 columns (weeks of current month)
    • Color levels: 5 levels based on quartile distribution (GitHub contributions style)
    • Weekday labels: Mon, Wed, Fri displayed on left side
    • Desktop pinned mode: Uses opacity-based white colors for accented rendering
  • Auto refresh interval is configurable (1-10 minutes)
  • Widget tap action configurable: open website or refresh data (Advanced Settings)

Wake Up (LaunchAgent-based CLI Scheduler)

  • Schedules CLI commands (codex exec --skip-git-repo-check "hello" / claude -p "hello") at user-defined hours
  • Creates LaunchAgent plist files in ~/Library/LaunchAgents/
  • Logs CLI output to /tmp/agentlimit-wakeup-*.log
  • Per-provider schedule with additional CLI arguments support
  • Test execution from settings UI

Threshold Notification

  • Sends system notifications when usage exceeds configured threshold
  • Per-provider settings (Codex / Claude Code separately)
  • Per-window settings (5h / weekly separately)
  • Default threshold: 90%
  • Duplicate prevention: notifies only once per reset cycle
  • Usage color settings (donut + status colors) live in Notification settings

Advanced Settings (CLI Paths / Scripts / Widget Tap / Menu Bar)

  • Full path overrides for codex, claude, npx
  • PATH resolution results shown in UI
  • Bundled status line script path shown with copy action
  • Widget tap action: open website (default) or refresh data
  • Menu bar icon hide toggle (menu_bar_icon_hidden) — app-wide setting lives here, not in per-provider Usage settings

Claude Code Status Line Script

  • Bundled script for Claude Code status line integration
  • Reads Claude Code usage snapshot and App Group settings (display mode, language, thresholds, colors)
  • Outputs a single line with 5h/weekly usage, reset times, and update time
  • Supports overrides: -ja, -en, -r (remaining), -u (used), -p (pacemaker), -i (usage + pacemaker inline), -d (debug)
  • Requires jq

Shared Data Model

AgentLimitsShared/UsageModels.swift defines the shared usage model and snapshot store. App/widget add target-specific extensions in AgentLimits/Usage/AppUsageModels.swift and AgentLimitsWidget/WidgetUsageModels.swift.

AgentLimitsShared/CustomUsageModels.swift keeps the legacy built-in model unchanged and adds the common presentation layer:

  • UsageServiceKey: builtIn:<rawValue> or custom:<slug>
  • SemanticUsageWindowKind: .fiveHours, .oneWeek, .oneMonth
  • UsagePresentationSnapshot: normalizes legacy primary/secondary windows and custom snapshots for menu, dashboard, colors, pacemaker, and notifications
  • SemanticUsageWindow: owns the resolved label and the optional expiry/pacemaker capability used consistently by widgets, dashboard, menu bar, and notifications
  • CustomUsageSnapshotStore: validates then atomically writes the unmodified stdout bytes

UsageWindow stores per-window usage data:

  • kind: .primary or .secondary
  • usedPercent: 0-100
  • resetAt: Date?
  • limitWindowSeconds: TimeInterval
  • usedCount: Int? — used count (Copilot premium interactions)
  • limitCount: Int? — limit count (Copilot premium interactions quota)

Monthly-only usage windows:

  • UsageWindow.isLongerThanWeeklyWindow returns true when limitWindowSeconds > UsageLimitDuration.sevenDays + 1.
  • UsageSnapshot.isSingleMonthlyWindow is the shared UI/display helper for Copilot and monthly-only Codex snapshots.
  • Do not add UsageWindowKind.monthly; monthly snapshots reuse .primary for storage and threshold compatibility.

AgentLimitsShared/TokenUsageModels.swift defines token usage snapshots:

  • provider: .codex or .claude
  • today / thisWeek / thisMonth: TokenUsagePeriod with costUSD, totalTokens
  • dailyUsage: [DailyUsageEntry] - Daily usage entries for heatmap (ISO8601 date string + totalTokens)
  • fetchedAt: Date

Storage Paths (App Group: group.com.dmng.agentlimit)

~/Library/Group Containers/group.com.dmng.agentlimit/Library/Application Support/AgentLimit/
├── usage_snapshot.json           # Codex usage limits
├── usage_snapshot_claude.json    # Claude Code usage limits
├── usage_snapshot_copilot.json   # GitHub Copilot usage limits
├── usage_snapshot_custom_<provider>.json # Custom usage service (one per provider slug)
├── token_usage_codex.json        # ccusage Codex
├── token_usage_claude.json       # ccusage Claude
└── token_usage_copilot.json      # Copilot billing

UserDefaults Keys

KeyPurpose
usage_display_modeDisplay mode (used% / remaining%; legacy pacemaker values are treated as used%)
usage_display_mode_cachedCached display mode used to convert stored snapshots (also shared via App Group for widgets)
menu_bar_status_codex_enabledMenu bar Codex status display toggle
menu_bar_status_claude_enabledMenu bar Claude Code status display toggle
menu_bar_status_copilot_enabledMenu bar GitHub Copilot status display toggle
menu_bar_dashboard_codex_enabledDashboard row visibility for Codex (default: true)
menu_bar_dashboard_claude_enabledDashboard row visibility for Claude Code (default: true)
menu_bar_dashboard_copilot_enabledDashboard row visibility for Copilot (default: true)
provider_display_orderProvider display order in menu bar icon and dashboard ([String] rawValue array; default: allCases order)
usage_service_display_order_v2Common built-in/custom service order (UsageServiceKey.rawValue array); legacy provider order is preserved during migration
custom_usage_servicesApp-only custom service execution configuration
custom_usage_run_statusesLast attempt, last success, and last execution/validation error per custom provider
custom_usage_widget_servicesApp Group widget index containing provider ID + display name only
menu_bar_icon_hiddenHide entire menu bar icon (default: false); relaunch app to temporarily reveal
wake_up_schedulesWake Up schedules (JSON array)
threshold_notification_settingsThreshold settings (JSON array)
threshold_notification_settings_v2Version 2 notification settings keyed by common service ID and semantic window kind
app_languageLanguage preference (App Group shared)
usage_refresh_interval_minutesUsage limits auto-refresh interval (minutes)
token_usage_refresh_interval_minutesccusage auto-refresh interval (minutes)
ccusage_settingsccusage settings (JSON), including per-provider commandTemplate override
cli_path_codexFull path override for codex
cli_path_claudeFull path override for claude
cli_path_npxFull path override for npx
usage_color_donutDonut ring color (widget)
usage_color_donut_use_statusDonut uses usage status colors
usage_color_greenUsage normal color
usage_color_orangeUsage warning color
usage_color_redUsage danger color
usage_color_threshold_revisionRevision bump for threshold updates
usage_color_threshold_warning_{provider}_{window}Warning threshold used for usage status colors
usage_color_threshold_danger_{provider}_{window}Danger threshold used for usage status colors
widget_tap_actionWidget tap action (openWebsite / refreshData)
menu_bar_show_pacemaker_valuePacemaker indicator toggle (shared with widgets)
pacemaker_ring_warning_enabledPacemaker ring warning segments toggle (default: true)
usage_color_pacemaker_ringPacemaker ring color (widget)
usage_color_pacemaker_status_orangePacemaker indicator color (warning)
usage_color_pacemaker_status_redPacemaker indicator color (danger)
pacemaker_warning_deltaPacemaker mode warning threshold delta (default: 0%)
pacemaker_danger_deltaPacemaker mode danger threshold delta (default: 10%)

Widget Kinds

  • AgentLimitWidget - Codex usage limits widget
  • AgentLimitWidgetClaude - Claude Code usage limits widget
  • AgentLimitWidgetCopilot - GitHub Copilot usage limits widget
  • CustomUsageWidget - AppIntent-configurable custom service usage widget
  • TokenUsageWidgetCodex - ccusage Codex widget
  • TokenUsageWidgetClaude - ccusage Claude widget
  • TokenUsageWidgetCopilot - Copilot billing widget

Entitlements

  • App: App Groups + Network Client
  • Widget: App Groups only (reads cached data)

Notes

  • Keep README.md in English
  • Keep README_ja.md in Japanese
  • Keep AGENTS.md and CLAUDE.md in English
  • Backend APIs are undocumented and may change without notice
  • Widget refresh frequency may be throttled by the OS
  • CLI execution uses the user login shell and prefixes PATH with /opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin:$PATH
  • Full-path overrides from Advanced Settings take precedence
  • System language resolution uses a bundled localization when available and explicitly falls back to English when none of the preferred OS languages are supported; never depend on bundle localization ordering for the fallback.
  • Menu bar is managed by MenuBarController (AppKit NSStatusItem), not SwiftUI MenuBarExtra; AgentLimitsApp only declares a Window scene for the settings window
  • MenuBarController uses KVO (addObserver(_:forKeyPath:options:context:)) for specific UserDefaults keys rather than UserDefaults.didChangeNotification (which fires on every write); observedAppGroupDefaults is stored as a property so addObserver and removeObserver always use the same instance; KVO callbacks run nonisolated and dispatch to @MainActor via Task
  • AppSharedState.onSettingsWindowClosed bridges SettingsWindowController window-close → MenuBarController.endTemporaryRevealIfNeeded() and reapplies the login-history-based WebView background policy; set in AppDelegate.applicationDidFinishLaunching
  • Usage login WebViews are created without loading their provider pages by default. AppSharedState resumes only providers with cached snapshots in the background, SettingsWindowController resumes the currently selected provider when settings opens, and ContentView resumes newly selected providers for login. Clear Data deletes usage snapshots and resets provider state so providers return to the no-history background policy.
  • applicationShouldHandleReopen in AppDelegate handles relaunch-to-reveal when menu bar icon is hidden; a 2-second post-launch guard prevents accidental reveal from LaunchServices startup events
  • Dashboard rows use NSHostingView<DashboardMenuItemView> with fittingSize + autoresizingMask: [.width]; menuNeedsUpdate uses MainActor.assumeIsolated for synchronous rebuild
  • UsageLinearBarView mirrors UsageDonutView logic: warning segment clipped to min(dangerStart, totalEnd), pacemaker bar hidden when calculatePacemakerPercent() returns nil
  • AppUsageColorResolver duplicates WidgetUsageColorResolver for the app target (widgets are a separate build target)
  • Settings window minimum height is 620 (DesignTokens.WindowSize.minHeight) so the collapsed login panel remains visible
  • Usage status color thresholds are synced from notification thresholds per provider/window
  • Claude Code status line script requires jq

Release Process

  1. Bump MARKETING_VERSION / CURRENT_PROJECT_VERSION in project settings
  2. Archive → Developer ID Application signing → Notarize → create ZIP (AgentLimits.zip)
  3. Create GitHub Release with tag v{MARKETING_VERSION} and attach AgentLimits.zip
  4. In the Products repository, run python3 tools/build_appcast.py agentlimits
    • This resolves the version from the latest GitHub Release URL, downloads the ZIP, runs generate_appcast, updates TOML release.version / release.release_date, and regenerates all product pages
  5. Review the diff, then git commit & push → Cloudflare Workers auto-deploys appcast.xml

Sparkle EdDSA Key

The EdDSA private key is stored in macOS Keychain (added by generate_keys from the Sparkle package). It is not committed to the repository.

  • Public key: stored in Info.plist under SUPublicEDKey
  • Private key backup: exported from Keychain and saved as a secure note in Bitwarden

Key Recovery (new Mac or re-install)

  1. Retrieve the private key from Bitwarden secure note
  2. Import it into Keychain with:
    security import <private_key_file> -k ~/Library/Keychains/login.keychain-db
  3. Verify with generate_appcast — it should sign without prompting for a key

If the private key is lost, generate a new key pair with generate_keys, update SUPublicEDKey in Info.plist, and publish a new release. Users on old builds will need to update manually once.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.