Skip to content

Model Usage Dashboard with Model Locking#127

Open
OBenner wants to merge 1 commit intodevelopfrom
feat/model-usage-dashboard
Open

Model Usage Dashboard with Model Locking#127
OBenner wants to merge 1 commit intodevelopfrom
feat/model-usage-dashboard

Conversation

@OBenner
Copy link
Owner

@OBenner OBenner commented Mar 3, 2026

Summary

  • Add Model Usage Dashboard — view model usage analytics (cost breakdown, token usage, trends by model/agent/provider)
  • Add Model Lock system — lock specific phases or agents to a particular model version, preventing automatic updates
  • Refactor TrendsChart into reusable SVGLineChart component with i18n support
  • DRY refactor of model-costs.ts pricing database using shared tier helpers

Changes

Backend

  • core/cost_tracking.pyprovider field in UsageRecord, get_cost_by_provider() method
  • phase_config.pyModelLockConfig type, lock/unlock CRUD for phases and agents with JSON persistence
  • agents/session.pymodel field tracking per conversation round
  • analysis/analytics_utils.py — extracted shared timestamp/CLI utilities from productivity_analytics.py
  • analysis/model_usage_analytics.py — model usage analytics script
  • scripts/model_locks_manager.py — CLI for managing model locks

Frontend

  • components/model-usage/ — 6 new components (Dashboard, Card, CostChart, AgentModelDisplay, ModelLockControl, ConfirmDialog)
  • components/analytics/SVGLineChart.tsx — reusable SVG line chart component
  • components/analytics/TrendsChart.tsx — refactored to use SVGLineChart + i18n
  • components/project-settings/ModelUsageSettings.tsx — settings integration
  • IPC handlers, preload API, types, i18n (en/fr)
  • model-costs.ts — DRY refactor with tier() helper, edge case fix

Test plan

  • Verify Model Usage nav item appears in sidebar
  • Open Model Usage dashboard and verify it renders
  • Check model lock controls in Project Settings > Model Usage
  • Verify TrendsChart still renders correctly after SVGLineChart refactor
  • Test i18n — switch to French and verify translations

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added comprehensive model usage analytics dashboard tracking AI model usage, costs, and tokens
    • Introduced model locking feature to pin specific models to agents and workflow phases
    • Added cost tracking by provider with breakdown visualization
    • Integrated usage trends and metrics export (JSON/CSV formats)
    • New navigation section for model usage management and configuration
  • Bug Fixes

    • Enhanced cost calculation and tracking accuracy

Add comprehensive model usage analytics and model lock management:
- Backend: provider tracking in CostTracker, model lock CRUD in phase_config, analytics utils extraction, model usage analytics script
- Frontend: ModelUsageDashboard with cards, cost chart, agent model display, lock controls and confirmation dialog
- Frontend: SVGLineChart reusable component, TrendsChart refactored to use it with i18n
- Frontend: Model usage settings section in project settings, IPC handlers, preload API
- Refactored model-costs.ts with DRY tier helper, edge case fix in getCheapestModel
- Added session.py model field tracking per conversation round
- i18n support (en/fr) for model-usage namespace

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 3, 2026

Caution

Review failed

Failed to post review comments

📝 Walkthrough

Walkthrough

This pull request introduces comprehensive model usage analytics and model lock management across the platform. It adds analytics data aggregation, cost tracking by provider, model configuration locking mechanisms, and a full-stack dashboard for visualizing model usage metrics, trends, and enabling lock controls.

Changes

Cohort / File(s) Summary
Backend Analytics Foundation
apps/backend/analysis/analytics_utils.py, apps/backend/analysis/productivity_analytics.py
New shared analytics utilities for timestamp parsing, boundary normalization, and CLI argument standardization. Productivity analytics refactored to delegate timestamp parsing and argument handling to centralized utilities, reducing code duplication.
Model Usage Analytics Engine
apps/backend/analysis/model_usage_analytics.py
Complete new module implementing model usage aggregation across specs, including data models (ModelMetrics, AgentMetrics, ModelUsageSummary), trend extraction with configurable time windows, and CSV/JSON export functionality. Scans cost reports and builds detailed per-model and per-agent breakdowns.
Cost Tracking Enhancement
apps/backend/core/cost_tracking.py
Extended UsageRecord with provider field (default "anthropic") and corresponding serialization. CostTracker gains get_cost_by_provider method and cost summary now includes provider-level breakdown.
Session Model Propagation
apps/backend/agents/session.py
Added model field to ConversationRound with full serialization/deserialization support. ConversationHistory.add_round and run_agent_session now accept and propagate model parameter through the conversation flow.
Model Lock Management
apps/backend/phase_config.py, apps/backend/scripts/model_locks_manager.py
New model lock configuration system with ModelLockConfig type and utilities (load/save/lock/unlock operations for phases and agents). CLI script provides list, lock, unlock, and clear commands with validation and verification. get_phase_model and get_agent_model now prioritize locked models over configuration.
IPC Channel Integration
apps/frontend/src/shared/constants/ipc.ts, apps/frontend/src/shared/types/ipc.ts
Added 11 new IPC channels for model usage analytics and lock operations. Extended ElectronAPI interface with methods for retrieving summaries, trends, and exporting data.
Frontend IPC Handlers
apps/frontend/src/main/ipc-handlers/index.ts, apps/frontend/src/main/ipc-handlers/model-usage-handlers.ts
New handler module managing IPC endpoints for model usage analytics (with caching and regeneration logic) and model lock operations. Includes Python script execution, cache validation, and error handling.
Frontend API Layer
apps/frontend/src/preload/api/agent-api.ts, apps/frontend/src/preload/api/modules/model-usage-api.ts
New ModelUsageAPI interface with methods for summary/trends retrieval and lock management. Factory function createModelUsageAPI implements IPC delegation with filter/option mapping.
Model Usage Dashboard UI
apps/frontend/src/renderer/components/model-usage/*
Six new React components: ModelUsageDashboard (main dashboard with filtering and export), ModelUsageCard (per-agent metrics), CostChart (trend visualization), AgentModelDisplay (agent model configuration), ModelLockControl (lock/unlock UI), and ModelChangeConfirmationDialog (confirmation UX). Index barrel file exports all components.
SVG Chart Component
apps/frontend/src/renderer/components/analytics/SVGLineChart.tsx, apps/frontend/src/renderer/components/analytics/TrendsChart.tsx
New reusable SVGLineChart component with multi-metric support, legends, and summary stats. TrendsChart refactored to use SVGLineChart data-driven approach, replacing bespoke inline rendering.
Model Utilities
apps/frontend/src/renderer/components/model-usage/model-utils.ts
Shared utility functions: parseModelId (extracts name/version from model IDs), getAgentLabel (formats agent type labels), formatNumber (locale-aware formatting), formatCurrency (USD formatting).
Settings Integration
apps/frontend/src/renderer/components/project-settings/ModelUsageSettings.tsx, apps/frontend/src/renderer/components/project-settings/index.ts, apps/frontend/src/renderer/components/settings/AppSettings.tsx, apps/frontend/src/renderer/components/settings/ProjectSettingsContent.tsx, apps/frontend/src/renderer/components/settings/sections/SectionRouter.tsx
New ModelUsageSettings component integrated into project settings. SidebarView and ProjectSettingsSection types extended to include 'model-usage'. Settings router wired to render new section.
Navigation Updates
apps/frontend/src/renderer/App.tsx, apps/frontend/src/renderer/components/Sidebar.tsx
App.tsx conditionally renders ModelUsageDashboard based on activeView. Sidebar adds 'model-usage' navigation item with Database icon and shortcut O.
Type Definitions
apps/frontend/src/shared/types/model-usage.ts, apps/frontend/src/shared/types/index.ts
New model-usage module defining comprehensive types: BaseUsageMetrics, ModelMetrics, AgentMetrics, ModelUsageSummary, trend structures, filters, export options, and lock configuration types. Exported from shared types index.
Internationalization
apps/frontend/src/shared/i18n/index.ts, apps/frontend/src/shared/i18n/locales/en/model-usage.json, apps/frontend/src/shared/i18n/locales/en/navigation.json, apps/frontend/src/shared/i18n/locales/en/settings.json, apps/frontend/src/shared/i18n/locales/fr/model-usage.json, apps/frontend/src/shared/i18n/locales/fr/navigation.json, apps/frontend/src/shared/i18n/locales/fr/settings.json
Comprehensive i18n resources added for English and French. model-usage namespace includes 100+ keys for dashboard, charts, dialogs, settings, and error messages. Navigation and settings JSON extended with new entries.
Mock/Test Data
apps/frontend/src/renderer/lib/browser-mock.ts
Added mock implementations for getModelUsageSummary, getModelUsageTrends, and exportModelUsageAnalytics endpoints.
Cost Model Optimization
apps/frontend/src/shared/constants/model-costs.ts
Refactored to use pricing tier constants (OPUS_PRICING, SONNET_PRICING, HAIKU_PRICING, OLLAMA_FREE) instead of inline per-model entries. Reduced redundancy and improved maintainability of pricing data.
Context Configuration
context.json
Extended configuration documenting new backend modules, frontend components, patterns, and implementation references for model usage analytics and lock management.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant Frontend as Frontend<br/>(Dashboard)
    participant IPC as IPC Handler
    participant Backend as Python<br/>Analytics
    participant FileSystem as File System<br/>(.auto-claude)
    
    User->>Frontend: Open Model Usage Dashboard
    Frontend->>IPC: getModelUsageSummary(projectId, filter?)
    IPC->>FileSystem: Check cache validity
    alt Cache valid & fresh
        IPC->>IPC: Return cached summary
    else Cache missing/stale
        IPC->>Backend: execute model_usage_analytics.py
        Backend->>FileSystem: Scan specs/ for cost_report.json
        Backend->>Backend: Aggregate metrics by model & agent
        Backend->>Backend: Compute period bounds & totals
        Backend->>IPC: Return ModelUsageSummary JSON
        IPC->>FileSystem: Write updated cache
    end
    IPC->>Frontend: IPCResult<ModelUsageSummary>
    Frontend->>Frontend: Render summary metrics & cards
    
    User->>Frontend: Select time range (7d/30d/90d/all)
    Frontend->>IPC: getModelUsageTrends(projectId, filter)
    IPC->>Backend: execute model_usage_analytics.py with --window-days & --granularity
    Backend->>Backend: Build time-series by period
    Backend->>IPC: Return trend points list
    IPC->>Frontend: IPCResult<ModelUsageTrendPoint[]>
    Frontend->>Frontend: Render CostChart with trends
    
    User->>Frontend: Click lock icon on agent
    Frontend->>IPC: lockAgentModel(projectId, agentType, modelId)
    IPC->>Backend: execute model_locks_manager.py lock-agent
    Backend->>FileSystem: Read model_locks.json
    Backend->>FileSystem: Write locked model_id
    Backend->>Backend: Verify lock persisted
    Backend->>IPC: Return success
    IPC->>Frontend: IPCResult<{success: true}>
    Frontend->>Frontend: Update lock UI, show success toast
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

area/fullstack, size/XL, feature

Poem

🐰 Whiskers twitching with analytics joy,
Models tracked from deploy to destroy,
Locks and costs in dashboards so bright,
Trends and metrics dance through the night,
A rabbit's delight—full usage insight!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main features added: a Model Usage Dashboard and Model Locking system. It directly reflects the primary changes in the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 85.44% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/model-usage-dashboard

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.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Mar 3, 2026

Copy link
Contributor

@github-advanced-security github-advanced-security bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeQL found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant