CodexBar

repository·main·Indexed 9 days ago

https://github.com/steipete/codexbar

A macOS 14+ menu bar application that provides real-time visibility into AI coding provider limits, credits, and usage windows (session, weekly, monthly). It includes a CLI for managing providers and API keys, as well as tracking cost usage.

Tokens
128.8K
Snippets
295
Records
596
Agent score
97%

What's inside CodexBar

  1. Overview of AdaptiveReplayKit

    main

    AdaptiveReplayKit is an offline harness designed to compare refresh-timing policies against an explicit JSONL trace. It allows developers to test how different policies would have performed against recorded historical data.

    Key characteristics:

    • Offline Testing: It does not record app behavior, scan directories, or call providers. It operates purely on provided trace files.
    • Decoupled from Production: It does not import CodexBar or CodexBarCore. It only shares the AdaptiveRefreshCore target.
    • Input-Only Schema: Optional activity fields in the trace schema are treated as inputs only; the kit does not discover or collect them.
    • CLI Wrapper: AdaptiveReplayCLI provides the command-line interface for running replays and generating reports.
  2. What is CQuickJS?

    main
    CQuickJS is a SwiftPM C target that vendors the minimal embeddable engine from quickjs-ng (version v0.15.1). It provides the core engine translation units and required headers needed to embed QuickJS into Swift projects, while intentionally excluding CLIs (qjs/qjsc), the REPL, libc modules, and build-system files to remain minimal.
  3. Alibaba Token Plan provider features and limitations

    main

    Features

    • Token-plan usage display: Shows used, total, and remaining credits.
    • Personal/Solo windows: Displays 5-hour and 7-day usage, reset times, and tier-specific quotas.
    • Cookie-based auth: Supports browser cookies or manual Cookie: header pasting.
    • Expiry awareness: Shows the nearest expiration date as the reset time if provided by the subscription summary.

    Limitations

    • Supports the Bailian web-cookie path only.
    • Does NOT support: API-key auth, token cost summaries, or automatic status polling.
  4. Understand OpenAI data sources and fallback behavior

    main

    CodexBar uses two different methods to retrieve OpenAI data depending on the key provided:

    1. Admin API (Preferred): Uses OPENAI_ADMIN_KEY to access organization costs (/v1/organization/costs) and completion usage (/v1/organization/usage/completions). This provides daily buckets, cost grouping by line_item, and usage grouping by model. It supports project scoping via workspaceID or OPENAI_PROJECT_ID.
    2. Legacy Fallback (Best-effort): If a standard OPENAI_API_KEY is used that lacks Admin access, CodexBar attempts to use the legacy /v1/dashboard/billing/credit_grants endpoint. This only provides a basic available/used credit summary and does not support organization-wide graphs or project scoping.
  5. Automatic Session Keepalive for Augment

    main

    To prevent session expiration, the Augment provider runs an automatic keepalive system:

    • Check Interval: Every 1 minute.
    • Refresh Buffer: Triggers a refresh 5 minutes before a cookie is set to expire.
    • Rate Limiting: Ensures at least 1 minute between refresh attempts.
    • Session Cookies: Refreshed every 30 minutes (for cookies without an explicit expiration date).

    The refresh mechanism pings /api/auth/session to trigger a cookie update in the browser, waits 1 second, and then re-imports the fresh cookies.

  6. How Claude Web session import works

    main

    CodexBar can fetch Claude usage data via web session cookies. The process follows these steps:

    1. Manual Configuration: If a manual cookie header is provided, it extracts the sessionKey from it.
    2. Automatic Discovery: If no manual header is provided, it enumerates cookie import candidates.
    3. Browser Import: It attempts to import cookies from the claude.ai domain.
    4. Candidate Filtering:
      • For Chromium-based browsers that use the keychain for decryption, candidates are dropped if the keychain is disabled or if the BrowserCookieAccessGate cooldown is active.
      • For Safari, Firefox, or Zen, candidates are kept even if the keychain is disabled.

    If a sessionKey is successfully found, CodexBar calls the organizations and usage endpoints to build the usage snapshot.

  7. Understand sub2api display modes and data

    main

    CodexBar reads data from the GET /v1/usage endpoint. The information displayed depends on the type of sub2api group configured:

    Group TypeDisplayed Information
    Quota-limited keyTotal quota plus optional 5-hour, daily, and 7-day rate-limit windows.
    Subscription groupDaily, weekly, and monthly spend against configured limits, plus expiration.
    Wallet groupCurrent wallet balance.
    All modesToday and total key-scoped requests, tokens, and actual cost (if returned by sub2api).

    Important Scoping Rules:

    • Usage Totals: Requests, tokens, and costs are scoped to the authenticated key.
    • Wallet Balance: Scoped to the owning user. CodexBar displays this on each account card individually and does not sum it across multiple keys.
    • Subscription Counters: Daily, weekly, and monthly counters follow the subscription's billing anchors. If multiple keys share one group, subscription counters may be shared, while request/cost totals remain key-scoped.
  8. Compare Lite Row vs. Rich Row for Overview UI

    main

    When deciding how to optimize the Overview UI performance, choose between two primary architectural directions:

    Lite Row

    Best if: You want a fast, high-level summary and prefer reducing SwiftUI content density.

    • Approach: Makes Overview row content lightweight; avoids dashboard-heavy SwiftUI content.
    • Pros: Simplest performance path; uses a compact summary with a monitor-resolved live model.

    Rich Row

    Best if: You want to preserve current information density and are willing to accept a narrow AppKit boundary.

    • Approach: Keeps rich UI but moves hover/hit-test/highlight propagation to AppKit.
    • Pros: Preserves UI density; addresses the performance problem at the interaction layer (hover/hit-test) rather than the content layer.
  9. How Fireworks spend data is displayed

    main

    The Fireworks provider calculates spend based on the account billing summary API.

    • Display Metric: The menu card shows the total spend for the last 30 days (e.g., $0.53) under a "Spend" label.
    • Calculation Logic: CodexBar requests a 30-day window using ISO 8601 timestamps. It sums the totalCost (combining units and nanos) from the lineItems in the API response. It uses the first rated currency found in the response as the display currency and ignores rows in other currencies.
    • Limitations:
      • There is no balance display (use the Fireworks web console at app.fireworks.ai for authoritative balance info).
      • There is no session or weekly window support as the API does not expose per-window quotas.
    • Error Handling:
      • 401/403 errors result in an invalid-key message.
      • 429 errors result in a rate-limit message.
  10. How the Grok provider fetches usage data

    main

    The Grok provider retrieves usage data using a multi-layered fallback strategy to ensure maximum availability. The order of operations is:

    1. ~/.grok/auth.json: The primary source for identity (email, team ID, name) and plan hints.
    2. grok agent stdio ACP JSON-RPC: The preferred method. It spawns the grok CLI and calls the x.ai/billing extension method. Note: In grok version 0.1.210, this method is currently only available in the TUI, so the agent-stdio surface may return -32601 Method not found.
    3. grok.com billing gRPC-web fallback: If the CLI method fails, CodexBar attempts to fetch data from https://grok.com/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig using browser session cookies.
    4. Local session signals: As a final informational fallback, CodexBar scans ~/.grok/sessions/ to aggregate token usage and model data from local signals.json files.
  11. Antigravity Provider Data Mapping and UI

    main

    The Antigravity provider maps raw API responses into two primary usage pools for the CodexBar UI:

    • Gemini: Groups Gemini Pro and Gemini Flash models.
    • Claude + GPT: Groups Claude text models and GPT/GPT-OSS text models.

    Key Mapping Details:

    • Quota Metrics: CodexBar uses the most constrained known bucket (the one with the lowest remainingFraction) as the primary metric for the menu bar.
    • Reset Metadata: It uses remainingFraction and resetTime (supporting ISO-8601 or numeric epoch seconds) to determine when quotas refresh.
    • Identity: Account email and plan names are extracted from the GetUserStatus endpoint.
    • Status Badges: The UI includes Google Workspace incident status for the Gemini product.
  12. How model pricing units are calculated

    main

    CodexBar consumes pricing data from models.dev which is expressed in USD per 1M tokens. To ensure compatibility with internal calculations, CodexBar converts these values into USD per token using the following formula:

    perToken = modelsDevCost / 1,000,000

    This conversion rule also applies to specialized pricing lanes, such as cost.context_over_200k (pricing for contexts exceeding 200k tokens).

    perToken = modelsDevCost / 1_000_000