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

feat(contrib): native SwiftUI menu bar app for account quota (macOS)

Open plustar35 opened this issue 5 months ago • 2 comments

What

A native macOS menu bar app (contrib/macos-app/) showing per-account Codex quota cards, as an alternative to the SwiftBar plugin in #603.

menu bar:  ⚡68%        ← active account's 5h remaining

panel (click to open, refreshes live):
┌─────────────────────────────┐
│ ● account-a          ACTIVE │
│ 5h ▓▓▓▓▓▓▓▓░  68%     4h 24m │
│ 7d ▓▓▓▓▓▓▓▓░  79%     6d 18h │
│ ● account-b            IDLE │
│ 5h ▓▓▓▓▓▓▓▓▓  90%     4h 14m │
│ updating…          [Refresh]│
└─────────────────────────────┘

Why, on top of the SwiftBar plugin

SwiftBar/xbar render the dropdown as an NSMenu, and macOS does not repaint an NSMenu while it is held open (menu tracking mode). So a probe fired on open can't visibly update the panel — you must close and reopen to see fresh numbers. That's a real wart for a "check my quota" widget.

This app uses SwiftUI MenuBarExtra with .menuBarExtraStyle(.window), which renders the panel as a window. On open it shows cached values instantly, runs a background codex-multi-auth check, and updates the cards in place when it returns. Same data source as the plugin — just a UI that can update while you're looking at it.

Contents

  • CodexQuota.swift — the app (~240 lines, no dependencies)
  • build.sh — compiles with swiftc and assembles a minimal ad-hoc-signed .app (no Xcode project required)
  • local.codex.quota.plist — optional login autostart LaunchAgent
  • README.md — build/install steps and the NSMenu-vs-window rationale

Behavior

  • Menu bar title ⚡<n>%: active account's 5h remaining (active resolved from runtime observability, falling back to the stored active index)
  • On open: instant cache render → background live check if cache >60s old → live update; explicit Refresh button
  • Reading cache costs no quota; the live check sends one minimal probe per account; rows go orange <30% and red <10%

Notes

  • macOS 13+; needs the Swift toolchain (Xcode or Command Line Tools)
  • Same local files as the plugin (~/.codex/multi-auth/, honors CODEX_MULTI_AUTH_DIR); fails soft (⚡?) on missing fields
  • contrib/ is outside the npm files whitelist, so the published package is unchanged
  • Build script verified from a clean checkout on macOS 26 / Swift 5.8

Complements rather than replaces #603 — some users prefer dropping a script into an existing SwiftBar setup, others prefer a standalone app that updates live. Happy to land only one if you'd rather not carry both.

🤖 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 native swiftui menu bar app (contrib/macos-app/) as a standalone alternative to the swiftbar plugin, showing per-account codex quota cards with live in-place updates while the panel is open.

  • CodexQuota.swift (~254 lines, no dependencies) reads the same local cache files as the swiftbar plugin and spawns codex-multi-auth check in a background process for live probing; refreshIfStale now correctly uses cache file mtime (synchronous) rather than the async-committed lastUpdated.
  • build.sh compiles with swiftc and assembles an ad-hoc-signed .app bundle; local.codex.quota.plist provides an optional login autostart launchagent with a HOME_PLACEHOLDER that users substitute via the documented sed one-liner.

Confidence Score: 3/5

the panel live-update story works correctly, but the menu bar title is frozen while the panel is closed, and a launch failure in refresh() can crash the app

the 60s timer in CodexQuotaApp is declared but never connected via onReceive — model.loadCache() is never called from it, so the menu bar percentage is stale from the moment the panel is closed. separately, try? task.run() followed by unconditional waitUntilExit() is a crash path if the process launch is denied. both issues affect the primary code file and the core user-facing behaviour described in the pr.

contrib/macos-app/CodexQuota.swift — the timer wiring in CodexQuotaApp and the try?/waitUntilExit pattern in refresh() both need attention before this lands

Important Files Changed

Filename Overview
contrib/macos-app/CodexQuota.swift core app logic; timer in CodexQuotaApp is declared but never subscribed to so the menu bar title doesn't auto-refresh while the panel is closed; try?/waitUntilExit crash path in refresh().
contrib/macos-app/build.sh compiles and assembles the .app bundle; codesign failure is intentionally silenced; no -sdk/-target flags (noted in existing thread).
contrib/macos-app/local.codex.quota.plist optional LaunchAgent plist; HOME_PLACEHOLDER substitution is manual but documented; CODEX_MULTI_AUTH_DIR gap noted in existing thread.
contrib/macos-app/README.md clear build/install docs; notes the CODEX_MULTI_AUTH_DIR/LaunchAgent caveat; claims menu bar title 'refreshes from cache on a timer' which is currently broken.
contrib/macos-app/.gitignore single-line ignore for .build/; correct.

Sequence Diagram

sequenceDiagram
    participant App as CodexQuotaApp (init)
    participant Model as QuotaModel
    participant FS as Local Cache Files
    participant View as QuotaView (onAppear)
    participant Proc as /bin/zsh codex-multi-auth check

    App->>Model: loadCache()
    Model->>FS: read cache files
    FS-->>Model: data
    Model-->>App: DispatchQueue.main.async accounts updated

    View->>Model: refreshIfStale()
    Model->>FS: cacheFileMTime()
    alt "mtime < 60s"
        Model-->>View: return cache fresh
    else "mtime >= 60s"
        Model->>Proc: Process run via DispatchQueue.global
        Proc-->>Model: waitUntilExit
        Model->>FS: loadCache
        FS-->>Model: updated data
        Model-->>View: DispatchQueue.main.async accounts updated
    end

    Note over App: tick timer 60s declared but never subscribed title won't auto-refresh
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 3
contrib/macos-app/CodexQuota.swift:233-234
**Dead timer — menu bar title never auto-refreshes while panel is closed**

`tick` is declared and `autoconnect()`ed, but `App.body` returns a `Scene` — you can't attach `.onReceive` to a `Scene`, and there's no such call anywhere in this file. `titleTick` is assigned nowhere in `body`. As a result, `model.loadCache()` is never called from this timer; `model.accounts` (which drives `model.titleRemaining`) only changes when the panel is opened or a refresh completes. The README says the title "refreshes from cache on a timer," but with the panel closed the percentage is frozen at whatever it was at startup/last panel close — a user glancing at the icon after an hour sees stale data. To fix, drive the periodic reload from inside `QuotaModel` (e.g., schedule an `NSTimer` in `init`) so it isn't tied to a view's `onReceive`.

### Issue 2 of 3
contrib/macos-app/CodexQuota.swift:98-99
`try? task.run()` silently discards any launch error and then falls through to `task.waitUntilExit()` unconditionally. If `run()` throws (e.g., sandbox denial, unexpected fs state), `waitUntilExit()` on an un-started `Process` hits a `preconditionFailure("task not launched")` and crashes the app. Guard the wait behind a successful launch.

```suggestion
            guard (try? task.run()) != nil else {
                DispatchQueue.main.async { self.updating = false }
                return
            }
            task.waitUntilExit()
```

### Issue 3 of 3
contrib/macos-app/CodexQuota.swift:96-97
`standardError` is discarded, so when `codex-multi-auth check` fails (missing binary, auth error, network timeout), `updating` flips back to `false`, the spinner disappears, and the numbers stay stale — with zero indication of what went wrong. capturing stderr into a `Pipe` and storing the output in the model (or at least logging it to `stderr` of the host process) would make the failure mode visible without changing the UX significantly.

```suggestion
            task.standardOutput = FileHandle.nullDevice
            let stderrPipe = Pipe()
            task.standardError = stderrPipe
```

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

Greptile also left 2 inline comments on this PR.

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

Low-risk contrib utility: This PR adds a native macOS menu bar app for displaying account quota status as a pure UI companion to existing TypeScript quota functionality. No tests are required (contrib/ excluded from npm publishing), no data-loss risks (read-only access to local cache files), and no architectural changes to core code.

Key implementation notes:

  • Subprocess execution: The refresh() method runs codex-multi-auth check via /bin/zsh with an extended PATH to locate the CLI tool. The command is hardcoded (no injection risk) and output is discarded; no error checking on the subprocess exit code (graceful degradation).
  • File staleness detection: Uses quota-cache.json modification time rather than the optional updatedAt field to avoid async-commit race conditions (addressed in follow-up fix commit).
  • Window-based UI: Intentionally uses SwiftUI MenuBarExtra(.window) instead of menu style to show live updates while the panel remains open—differentiates from the existing SwiftBar plugin (#603).
  • Environment override: Respects CODEX_MULTI_AUTH_DIR for alternative cache locations; documented and optional in LaunchAgent plist.
  • Graceful fallbacks: All JSON file reads and field accesses use optional chaining; missing data displays "no data" or "-" rather than crashing.

The build script (swiftc-based ad-hoc codesign) and LaunchAgent plist are minimalist and well-documented. The app targets macOS 13+ and requires Swift toolchain and codex-multi-auth CLI on PATH.

Walkthrough

new macOS SwiftUI menu-bar app displays per-account Codex quota from the local codex-multi-auth cache. the app loads account data, derives remaining percentages, refreshes by running codex-multi-auth check, renders quota cards with reset timing, and provides optional autostart via LaunchAgent.

Changes

macOS Quota Display App

Layer / File(s) Summary
Quota data models and observable state
contrib/macos-app/CodexQuota.swift (lines 5–129)
QuotaModel loads quota cache from ~/.codex/multi-auth/, reconstructs accounts with five-hour and seven-day remaining percentages, derives lastUpdated from metadata, and implements refresh() to run codex-multi-auth check via zsh before reloading. includes refreshIfStale() for age-gated updates and titleRemaining computed property for the menu title.
UI views and formatting helpers
contrib/macos-app/CodexQuota.swift (lines 133–228)
WindowRow renders progress and reset text per quota window; AccountCard composes two rows with account name and active status; QuotaView lists accounts, shows updating/last-updated indicators, provides refresh/quit controls, refreshes on appear when stale, and reloads cache every 30 seconds via timer. helper functions format reset times, map percentages to colors, and age Date objects to readable strings.
App entry and menu-bar wiring
contrib/macos-app/CodexQuota.swift (lines 230–254)
@main CodexQuotaApp application entry wires QuotaView with the QuotaModel observable, configures menu-bar presentation with dynamic title showing active account's remaining percentage.
Build script and launch agent
contrib/macos-app/build.sh, contrib/macos-app/local.codex.quota.plist, contrib/macos-app/.gitignore
build.sh compiles Swift source with swiftc, assembles the CodexQuota.app bundle under ~/Applications, writes Info.plist for macOS 13+, applies executable permissions, and ad-hoc codesigns. local.codex.quota.plist defines the launch agent with RunAtLoad, KeepAlive, and optional CODEX_MULTI_AUTH_DIR environment variable. .gitignore excludes .build/ directory.
Documentation
contrib/macos-app/README.md
README documents the app's purpose, UI refresh mechanics (live updates in open panel, cache staleness check, manual refresh button, color thresholds), system requirements, build/install steps, optional login autostart setup, cache location under ~/.codex/multi-auth/, soft failure for missing fields, and that contrib/ is not included in npm files whitelist.

Sequence Diagram(s)

N/A — the app's primary flow is cache reload on timer and manual refresh, not a multi-component interaction. UI rendering and state update are straightforward unidirectional bindings.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

key review points:

  • concurrency risk: refresh() in range_ea4c6a822c91:line 92–129 executes codex-multi-auth check via /bin/zsh without explicit error handling if the subprocess fails or times out. no cancellation token; if refresh hangs, the app blocks. check whether zsh invocation can fail gracefully or hang the event loop.
  • cache staleness logic: refreshIfStale() checks file modification time; verify that the 60-second default threshold matches the intended user experience and that the comparison is robust across system clock changes.
  • platform coverage: SwiftUI app only targets macOS 13+. no Windows/Linux equivalent provided, but app is optional contrib; verify that README notes this is macOS-only.
  • missing test coverage: no unit tests for QuotaModel cache loading, refresh logic, or percentage calculations. no tests for the UI rendering or interaction flows. recommend regression tests for cache parsing, active account selection, and refresh state transitions.
  • json parsing: cache files are decoded directly with JSONDecoder. verify that missing or malformed files fail gracefully (code appears to use try?, so soft failure is in place) and that the UI handles nil quota windows correctly.
  • timer lifecycle: QuotaView starts a 30-second timer on appear. verify timer is cancelled on disappear to avoid multiple concurrent timers if the view is recreated.
  • environment variable override: CODEX_MULTI_AUTH_DIR documented in LaunchAgent plist but needs verification that the app actually reads and respects it; check range_ea4c6a822c91 for the env lookup code.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Title follows conventional commits format with feat type, (contrib) scope, and 68-char lowercase imperative summary.
Description check ✅ Passed Description covers what/why/contents/behavior/notes thoroughly, but skips the validation checklist and docs/governance checklist sections from the template.
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]

Thank you for this, @plustar35 — a native SwiftUI menu-bar app is a polished piece of work. Closing for the same project-scope reason as #603: we're not taking on maintained macOS menu-bar apps inside this repo's contrib/ at the moment, since each adds a Swift toolchain/runtime surface we can't currently CI-verify here. This isn't a quality judgment — please keep it alive as a standalone project and we'd gladly point users to it from the docs. Grateful for the effort. 🙏

ndycode avatar Jun 19 '26 06:06 ndycode