# CodexBar Architecture: A Deep Dive into the Swift 6 Modular Design

> Explore the CodexBar architecture, a modular Swift 6 design using Core UI and CLI packages. Discover its layered approach, concurrency, and dependency injection for separated data and presentation.

- Repository: [Peter Steinberger/CodexBar](https://github.com/steipete/CodexBar)
- Tags: architecture
- Published: 2026-07-10

---

**CodexBar follows a layered, modular architecture built on three distinct Swift packages—Core, UI, and CLI—that leverage Swift 6 concurrency and dependency injection to separate data logic from platform-specific presentation.**

The **CodexBar** repository by steipete is a modern macOS-only menu-bar application that tracks API usage across multiple AI providers. Its architecture cleanly separates concerns into a reusable core library, a native AppKit UI layer, and command-line utilities, enabling extensive testability and maintainability. Below is a comprehensive breakdown of how these components interact, including specific file paths and implementation details extracted directly from the source code.

## Package Structure and Layered Design

The project organizes functionality into three logical layers defined in the root [`Package.swift`](https://github.com/steipete/CodexBar/blob/main/Package.swift). This separation allows the core business logic to remain platform-agnostic while multiple executables consume it for different interfaces.

- **CodexBarCore**: A pure Swift library containing data models, network fetching, caching, and security utilities
- **CodexBar**: The macOS executable that hosts the status-bar item and SwiftUI widgets
- **CodexBarCLI**: A command-line interface for diagnostics and scripting
- **Auxiliary Executables**: `CodexBarWidget`, `CodexBarClaudeWatchdog`, and `CodexBarClaudeWebProbe` for specific background tasks

Each executable depends on `CodexBarCore`, ensuring that usage tracking logic remains centralized and consistent across all interfaces.

## Core Layer: Data and Business Logic

The `CodexBarCore` package implements the entire usage-tracking pipeline, from secure token storage to background refresh scheduling. This layer knows nothing about AppKit or SwiftUI, making it highly testable and reusable.

### Observable State Management

At the heart of the core lies `UsageStore`, an `@Observable` class (Swift 6) that automatically drives UI updates when underlying data changes. The store maintains per-provider snapshots, credit information, and error states in thread-safe dictionaries.

```swift
@Observable final class UsageStore {
    var snapshots: [UsageProvider: UsageSnapshot] = [:]
    var errors: [UsageProvider: Error] = [:]
    var refreshingProviders: Set<UsageProvider> = []
    // ...
}

```

*Source:* [`Sources/CodexBarCore/UsageStore.swift`](https://github.com/steipete/CodexBar/blob/main/Sources/CodexBarCore/UsageStore.swift), lines 22-30.

The store reacts to settings changes via `withObservationTracking`, triggering `refreshHistoricalDatasetIfNeeded()` when configuration updates occur. This observation mechanism ensures that background data fetches automatically propagate to UI layers without manual delegate callbacks.

### Security and Keychain Access

Token storage is mediated through `KeychainSecurity`, a wrapper around the macOS Security framework that includes test-safety guards. The class prevents real keychain access during test execution by checking `KeychainTestSafety.shouldBlockRealKeychainAccess()` before invoking `SecItemCopyMatching`.

```swift
var tokenData: Data?
let query: CFDictionary = [
    kSecClass: kSecClassGenericPassword,
    kSecAttrAccount: "codexbar-token",
    kSecReturnData: kCFBooleanTrue
] as CFDictionary
let status = KeychainSecurity.copyMatching(query, &tokenData)

```

*Source:* [`Sources/CodexBarCore/KeychainSecurity.swift`](https://github.com/steipete/CodexBar/blob/main/Sources/CodexBarCore/KeychainSecurity.swift), lines 34-48.

### Background Agents

The `AgentSessionsStore` (referenced by `StatusItemController`) manages per-provider background agents that poll usage data periodically. These agents coordinate with the `UsageStore` to update snapshots while respecting memory pressure signals through `trimRebuildableCachesForMemoryPressure()`.

## UI Layer: Status Bar and Widgets

The `CodexBar` executable contains the AppKit-specific presentation logic, bridging the observable core models to native macOS UI elements.

### Status Item Controller

`StatusItemController` serves as the central coordinator, instantiated through a factory pattern that enables dependency injection for testing. The controller owns multiple `NSStatusItem` instances and lazily constructs `NSMenu` objects for different provider states.

```swift
let controller = StatusItemController.makeDefaultController(
    store: usageStore,
    settings: settingsStore,
    account: accountInfo,
    updater: updater,
    selection: preferences,
    managedCodexAccountCoordinator: managedCoordinator,
    codexAccountPromotionCoordinator: promotionCoordinator
)

```

*Source:* [`Sources/CodexBar/StatusItemController.swift`](https://github.com/steipete/CodexBar/blob/main/Sources/CodexBar/StatusItemController.swift), lines 98-107.

The controller manages:
- `mergedMenu` and `providerMenus` for displaying usage across multiple AI services
- `ProviderSwitcherShortcutEventMonitor` for global keyboard shortcuts
- `celebrationOriginPoint` and menu card rendering preferences

### Menu Rendering Strategy

The UI layer dynamically switches between rich SwiftUI "menu cards" (`UsageMenuCardLayout`, `BurnDownWidgetViews`) and classic AppKit menus based on the runtime environment. When running tests (`SettingsStore.isRunningTests`), the system disables menu card rendering to ensure stable UI testing.

### Widget Implementation

`CodexBarWidget` provides a macOS widget that reads from the same `UsageStore` via `CodexBarWidgetProvider`. The provider acts as a bridge between the observable core and the widget extension's timeline API, returning SwiftUI views based on current snapshot data.

## CLI and Auxiliary Executables

Beyond the GUI, CodexBar exposes its functionality through specialized executables that import `CodexBarCore` for specific tasks.

### Command-Line Interface

`CLIEntry` in [`Sources/CodexBarCLI/CLIEntry.swift`](https://github.com/steipete/CodexBar/blob/main/Sources/CodexBarCLI/CLIEntry.swift) parses sub-commands (e.g., `usage`, `config`, `diagnose`) and forwards them to the core. Commands like `CLICostCommand` and `CLICacheCommand` expose internal state for troubleshooting without requiring the GUI to run.

### Background Monitoring

- **CodexBarClaudeWatchdog**: Monitors Claude’s status page and restarts the main application if connectivity issues are detected
- **CodexBarClaudeWebProbe**: Performs HTTP probing of Claude’s dashboard specifically for token-refresh detection
- **CodexBarWidget**: Hosts the SwiftUI widget extension for Notification Center integration

Each auxiliary executable contains a minimal [`main.swift`](https://github.com/steipete/CodexBar/blob/main/main.swift) entry point that imports the core and initializes the specific service.

## Cross-Cutting Concerns

### Concurrency Model

The architecture adopts Swift 6's strict concurrency checking. UI-interacting objects like `StatusItemController` are marked `@MainActor`, while background network fetches run in detached `Task`s. The `@Observable` macro ensures that state changes propagate safely across actor boundaries without requiring manual dispatch queue management.

### Dependency Injection

The `StatusItemController` utilizes a static factory property (`static var factory: Factory`) that can be overridden during unit tests. This pattern allows test suites to inject mock `UsageStore` instances or fake coordinators, decoupling the UI from concrete implementations and enabling isolated testing of view logic.

### Memory Management

The core exposes `trimRebuildableCachesForMemoryPressure()` through the `StatusItemControlling` protocol, allowing the system to clear non-essential caches when macOS reports memory pressure. The default implementation in `StatusItemController` provides a no-op stub, while concrete implementations may purge historical data snapshots.

## Summary

- **CodexBar** organizes code into three distinct Swift packages: `CodexBarCore` (business logic), `CodexBar` (UI), and `CodexBarCLI` (command-line tools)
- The **@Observable** `UsageStore` in `CodexBarCore` provides automatic UI updates and reactive data fetching across all application layers
- **StatusItemController** uses factory-based dependency injection to bridge AppKit menus with the core library while remaining testable
- **KeychainSecurity** wraps macOS Security framework calls with test-safety guards to prevent keychain modification during automated testing
- Auxiliary executables like `ClaudeWatchdog` and `ClaudeWebProbe` demonstrate the reusability of the core library for specialized background tasks
- Swift 6 concurrency features (`@MainActor`, `@Observable`, `withObservationTracking`) ensure thread-safe state management throughout the application

## Frequently Asked Questions

### What is the primary architectural pattern used in CodexBar?

CodexBar implements a **layered architecture** with clear separation between the core library (`CodexBarCore`), the user interface (`CodexBar`), and command-line tools (`CodexBarCLI`). This modularity ensures that business logic for tracking API usage remains isolated from AppKit-specific presentation code, making the core logic reusable across multiple interfaces and highly testable through dependency injection.

### How does CodexBar handle data updates between the core and UI layers?

The application leverages **Swift 6's `@Observable` macro** in the `UsageStore` class ([`Sources/CodexBarCore/UsageStore.swift`](https://github.com/steipete/CodexBar/blob/main/Sources/CodexBarCore/UsageStore.swift)). When the store's properties change—such as when new usage data arrives from a provider—the observable mechanism automatically notifies SwiftUI views and other observers without requiring manual delegate patterns or NotificationCenter posts. This creates a reactive data flow from the core through to the menu bar and widgets.

### How does CodexBar ensure secure token storage while remaining testable?

Token storage is handled by the `KeychainSecurity` class in [`Sources/CodexBarCore/KeychainSecurity.swift`](https://github.com/steipete/CodexBar/blob/main/Sources/CodexBarCore/KeychainSecurity.swift), which wraps the macOS Security framework. The implementation includes a safety check via `KeychainTestSafety.shouldBlockRealKeychainAccess()` that returns `errSecInteractionNotAllowed` when running in test processes. This prevents automated tests from attempting to access the actual system keychain while still allowing the production application to store and retrieve API keys securely.

### What is the role of the StatusItemController factory pattern?

The `StatusItemController` uses a **static factory property** (`static var factory: Factory`) to enable dependency injection during initialization. This pattern allows the production application to create controllers with real stores and coordinators, while unit tests can override the factory to inject mock objects. This decoupling is essential for testing UI logic without requiring live network connections or actual keychain access.