codex-multi-auth icon indicating copy to clipboard operation
codex-multi-auth copied to clipboard

feat(contrib): SwiftBar menu bar quota plugin for macOS

Open plustar35 opened this issue 5 months ago • 4 comments

What

Adds an optional SwiftBar plugin under contrib/swiftbar/ that renders per-account quota cards in the macOS menu bar:

⚡88·[90]        ← title: 5h-window remaining % per account, brackets = account currently serving requests

╭──────────────────────────────────╮
│ ● account-a               ACTIVE │
│ 5h █████████░   88%  → 4h 42m    │
│ 7d ████████░░   83%  → 6d 18h    │
╰──────────────────────────────────╯
╭──────────────────────────────────╮
│ ○ account-b                 IDLE │
│ 5h █████████░   90%  → 4h 33m    │
│ 7d █████████░   86%  → 8h 16m    │
╰──────────────────────────────────╯
  • Active account resolved from runtime observability (lastAccountId), falling back to the stored active index
  • 5h/7d windows with remaining %, text progress bar, and reset countdown; rows turn orange <30% and red <10%
  • Reads only the local quota cache → zero quota cost; an explicit "Live refresh" menu action runs codex-multi-auth check (one probe per account)
  • Single self-contained script (re-invokes itself with a livecheck arg for the menu action); honors CODEX_MULTI_AUTH_DIR

Why

With runtime rotation, "how much quota does each account have left, and which one is serving right now" becomes the question users ask most. A glanceable menu bar view answers it without shelling out to check (and without spending probes).

Notes

  • contrib/ is outside the npm files whitelist, so the published package is unchanged
  • Fails soft (⚡?) if the internal cache format changes
  • Card interior is restricted to Menlo-native glyphs; the README documents why (CJK/emoji fallback fonts break border alignment)
  • Tested on macOS 15 + SwiftBar 2.x against a live two-account pool

🤖 Generated with Claude Code

note: greptile review for oc-chatgpt-multi-auth. cite files like lib/foo.ts:123. confirm regression tests + windows concurrency/token redaction coverage.

Greptile Summary

adds a self-contained swiftbar plugin under contrib/swiftbar/ that renders per-account codex quota cards in the macOS menu bar, reading only the local cache (zero quota cost) with an optional live-refresh menu action.

  • codex-quota.5m.sh embeds a python3 heredoc that parses quota-cache.json, openai-codex-accounts.json, and runtime-observability.json to render 5h/7d progress bars with color-coded thresholds and reset countdowns; active account is resolved from lastAccountId with fallback to activeIndex
  • the livecheck dispatch re-invokes the script with a hardcoded PATH that misses nvm/volta installs, causing silent failures for users who installed via nvm; the header row's pad() also has no truncation guard for long email local-parts, which can blow past W=32 and break border alignment

Confidence Score: 5/5

safe to merge — contrib-only change, outside npm files whitelist, no core lib or proxy code touched

the plugin is fully isolated in contrib/, cache reads are read-only, clamp_pct correctly bounds floats to ints, and fail-soft behavior is consistent throughout; the two issues found are cosmetic display concerns that don’t affect the rotation proxy or auth flow

contrib/swiftbar/codex-quota.5m.sh — header truncation and livecheck PATH coverage worth a second look before publicising the install guide widely

Important Files Changed

Filename Overview
contrib/swiftbar/codex-quota.5m.sh new self-contained bash+python3 swiftbar plugin; quota % rows are correctly bounded via clamp_pct, but the header row has no truncation guard for long email local-parts, and the livecheck PATH omits nvm/volta bin dirs causing silent failures for common installs
contrib/swiftbar/README.md new readme covering install, data source, refresh model, and glyph constraints; accurate and complete

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A([SwiftBar invokes script]) --> B{arg == livecheck?}
    B -- yes --> C[export hardcoded PATH]
    C --> D[codex-multi-auth check]
    D --> E([exit])
    B -- no --> F{uname == Darwin?}
    F -- no --> G([show error, exit])
    F -- yes --> H[invoke python3 heredoc]
    H --> I[load quota-cache.json]
    I --> J{files readable?}
    J -- no --> K([print error])
    J -- yes --> L[resolve active_id]
    L --> M[build quota rows per account]
    M --> N[print title bar]
    N --> O[print card blocks]
    O --> P[print Live refresh action]
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
contrib/swiftbar/codex-quota.5m.sh:119
`pad()` adds spaces but never truncates. the header row is `pad(f"{dot} {short}", W - len(tag)) + tag`, so if `short` exceeds `W - len(tag) - 2` chars (24 chars for ACTIVE, 26 for IDLE) the right border blows past `W=32` — the same alignment issue the Menlo-glyph note is guarding against. org emails like `[email protected]` easily hit this. clipping `short` to `W - len(tag) - 3` (with a trailing `…`) before building the row keeps the card width bounded.

### Issue 2 of 2
contrib/swiftbar/codex-quota.5m.sh:22-25
the hardcoded PATH for `livecheck` omits nvm paths (`~/.nvm/versions/node/*/bin`) and volta paths (`~/.volta/bin`). most macOS devs who followed the codex-multi-auth install docs used nvm, so `codex-multi-auth` lives in an nvm-managed bin and won't be found here. since `terminal=false` is set, the 127 exit is invisible — the menu item appears to do nothing. appending `$HOME/.nvm/versions/node/*/bin` via glob, or delegating to `npx --no codex-multi-auth check`, would cover the common case.

Reviews (2): Last reviewed commit: "fix(contrib): address review feedback on..." | Re-trigger Greptile

plustar35 avatar Jun 11 '26 13:06 plustar35

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. Credits must be used to enable repository wide code reviews.

📝 Walkthrough

Walkthrough

adds a new swiftbar menu bar plugin for codex multi-auth quota display. a bash entrypoint wraps embedded python that reads local cache and account store json files, renders per-account quota cards with active/idle indicators and remaining percentages, and outputs swiftbar-formatted menu sections. supports both passive cache reads and live probes via codex-multi-auth check.

Changes

SwiftBar Codex Quota Plugin

Layer / File(s) Summary
Plugin documentation and bash entrypoint
contrib/swiftbar/README.md, contrib/swiftbar/codex-quota.5m.sh:1–18
README describes the menu bar widget display (per-account quota cards with active/idle markers, color thresholds, 5h/7d remaining), installation steps (Homebrew, plugin placement, permissions), and notes on macOS-only rendering and cache format soft failure. Bash entrypoint defines livecheck parameter to trigger explicit codex-multi-auth check probes.
Python initialization, paths, and error handling
contrib/swiftbar/codex-quota.5m.sh:22–81
Embeds Python script with filesystem paths (quota cache, account store, runtime observability), color/display constants, JSON loading helpers, reset time formatting, and error card output. Early exit on missing or unreadable cache/store files.
Account selection and per-account quota cards
contrib/swiftbar/codex-quota.5m.sh:82–120
Builds account lookup structures from store, determines active account from runtime observability (fallback to activeIndex), and generates per-account SwiftBar card blocks: active/idle markers, 5h/7d remaining percentages derived from cached usedPercent, bar visuals, and reset countdowns.
Menu bar rendering and output
contrib/swiftbar/codex-quota.5m.sh:121–134
Prints composed SwiftBar output: headline, card grid with color-overridden rows based on quota level, cache update timestamp, and menu items for live refresh and cache reload.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes


notes for review

  • no regression tests: this plugin has no test coverage. consider adding a fixture-based test for the python card-generation logic, especially the usedPercent → 5h/7d remaining derivation and account selection fallback paths.
  • windows not addressed: the README correctly notes macOS-only behavior (font, menu bar rendering), but the script has no guards or error messages if run on non-darwin systems. consider a minimal safety check or explicit documentation of the skip-on-windows expectation.
  • cache format stability assumption: the code assumes cache usedPercent field always exists and is a number. if cache format evolves, the soft failure (⚡?) relies on shell stderr handling. verify that the JSON parsing errors will bubble cleanly to the menu bar rather than silently dropping quota info.
  • active account fallback logic: determines active account from runtime observability first, then falls back to store activeIndex. confirm that both signals are kept in sync and that the fallback doesn't mask stale activeIndex values during concurrent account switching.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive PR description covers objectives well but lacks validation and docs checklist completion; greptile flagged two cosmetic issues (header truncation and livecheck PATH coverage) requiring fixes before merge. address greptile findings on header truncation (pad() has no guard for long email local-parts) and livecheck PATH missing nvm/volta bin dirs; confirm regression tests cover quota cache parsing and menu rendering edge cases; verify macos-only constraints don't mask windows build breaks.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed title follows conventional commits format with type(scope): summary, 55 chars, lowercase imperative—fully meets requirements.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
✨ Simplify code
  • [ ] Create PR with simplified code

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Jun 11 '26 13:06 coderabbitai[bot]

您好,您的邮件已经收到,我会尽快回复,谢谢。祝好——中山大学管理学院蔡佳新

plustar35 avatar Jun 11 '26 13:06 plustar35

Thanks for the review. Pushed fixes for the actionable items:

  • Non-macOS guard: soft-exits with a friendly line on non-Darwin.
  • Clamp 0–100: quota percentages are clamped before the bar and title are built, so malformed cache values can't produce broken bars or noisy titles.
  • Exit code: the livecheck action now runs codex-multi-auth check without discarding output and exits with its status, so refresh failures are detectable.
  • README: code fences tagged with a language (MD040).
  • Also corrected a misleading comment — the quota cache is written by quota-bearing commands (check, forecast --live, the dashboard), not passively by proxied traffic.

On the suggestion to refactor the renderer into testable functions with golden/structured fixtures: I'd prefer to skip that here. This is a self-contained, fail-soft contrib/ helper outside the published package, and a Python test harness for a single display script feels disproportionate to its scope. The clamp/threshold logic is small and now defensive against bad input. Happy to add it if you'd rather have the coverage.

plustar35 avatar Jun 11 '26 13:06 plustar35

Thanks a lot for this, @plustar35 — and for promptly pushing the review fixups (non-macOS guard, 0–100 clamping, exit codes). Closing this one as a project-scope decision rather than a reflection on the work: we're keeping the core repo focused and not taking on bundled macOS menu-bar integrations (SwiftBar/native) as maintained contrib/ surface area right now. The quota-display approach you took is genuinely useful, so please feel free to keep it as a standalone gist/repo — happy to link to it from the docs. Really appreciate the contribution. 🙏

ndycode avatar Jun 19 '26 06:06 ndycode