# Analytics Dashboard

> This documentation covers Pro edition features available in the agents-orchestrator/agents-orchestrator private repository.

## Overview

The Analytics Dashboard provides historical cost and usage visibility across all projects. It reads from the community `session_metrics` table (no additional data collection required) and presents aggregated views through three commands and corresponding UI components.

## Data Source

All analytics are derived from the existing `session_metrics` table in `sessions.db`:

```sql
-- Community table (read-only access from Pro plugin)
CREATE TABLE session_metrics (
    id INTEGER PRIMARY KEY,
    project_id TEXT NOT NULL,
    session_id TEXT NOT NULL,
    started_at TEXT,
    ended_at TEXT,
    peak_tokens INTEGER,
    turn_count INTEGER,
    tool_call_count INTEGER,
    cost_usd REAL,
    model TEXT,
    status TEXT,
    error_message TEXT
);
```

The Pro plugin opens a read-only connection to `sessions.db` and queries this table. It never writes to community databases.

## Commands

### pro_analytics_summary

Returns an aggregated summary for the specified period.

**Arguments:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `period` | `u32` | Yes | Number of days to look back (7, 14, 30, or 90) |
| `projectId` | `String` | No | Filter to a single project. Omit for all projects. |

**Response: `AnalyticsSummary`**

```typescript
interface AnalyticsSummary {
  totalCostUsd: number;
  totalSessions: number;
  totalTurns: number;
  totalToolCalls: number;
  avgCostPerSession: number;
  avgTurnsPerSession: number;
  peakTokensMax: number;
  periodDays: number;
  projectCount: number;
}
```

### pro_analytics_daily

Returns per-day statistics for charting.

**Arguments:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `period` | `u32` | Yes | Number of days (7, 14, 30, or 90) |
| `projectId` | `String` | No | Filter to a single project |

**Response: `Vec<DailyStats>`**

```typescript
interface DailyStats {
  date: string;          // ISO 8601 date (YYYY-MM-DD)
  costUsd: number;
  sessionCount: number;
  turnCount: number;
  toolCallCount: number;
}
```

Days with no sessions are included with zero values to ensure continuous chart data.

### pro_analytics_model_breakdown

Returns usage grouped by model.

**Arguments:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `period` | `u32` | Yes | Number of days (7, 14, 30, or 90) |
| `projectId` | `String` | No | Filter to a single project |

**Response: `Vec<ModelBreakdown>`**

```typescript
interface ModelBreakdown {
  model: string;
  sessionCount: number;
  totalCostUsd: number;
  avgCostPerSession: number;
  totalTurns: number;
  totalToolCalls: number;
  pctOfTotalCost: number;  // 0.0 to 100.0
}
```

Results are sorted by `totalCostUsd` descending.

## Period Selection

The UI presents four period options:

| Period | Label | Use Case |
|--------|-------|----------|
| 7 | Last 7 days | Recent activity check |
| 14 | Last 14 days | Sprint review |
| 30 | Last 30 days | Monthly cost review |
| 90 | Last 90 days | Quarterly trend analysis |

The selected period is stored in the component state and defaults to 30 days. Changing the period triggers a fresh query (no client-side caching).

## UI Components

### AnalyticsDashboard.svelte

Top-level Pro tab component. Contains:

1. **Period selector** -- segmented button group (7/14/30/90).
2. **Summary cards** -- four stat cards showing total cost, sessions, avg cost/session, peak tokens.
3. **Daily cost chart** -- SVG bar chart rendered from `DailyStats[]`.
4. **Model breakdown table** -- sortable table from `ModelBreakdown[]`.

### Daily Cost Chart

The chart is a pure SVG element (no charting library). Implementation details:

- Bars are sized relative to the maximum daily cost in the period.
- X-axis labels show abbreviated dates (e.g., "Mar 5").
- Y-axis shows cost in USD with appropriate precision ($0.01 for small values, $1.00 for large).
- Hover tooltip shows exact cost, session count, and turn count for the day.
- Colors use `var(--ctp-blue)` for bars, `var(--ctp-surface1)` for gridlines.
- Responsive: adapts bar width to container via `container-type: inline-size`.

### Model Breakdown Table

Standard sortable table with columns: Model, Sessions, Cost, Avg Cost, Turns, Tools, % of Total. Default sort by cost descending. The `% of Total` column includes a proportional bar using `var(--ctp-sapphire)`.

## IPC Examples

```typescript
// Get 30-day summary across all projects
const summary = await invoke('plugin:agor-pro|pro_analytics_summary', {
  period: 30,
});

// Get daily stats for a specific project
const daily = await invoke('plugin:agor-pro|pro_analytics_daily', {
  period: 14,
  projectId: 'my-project',
});

// Get model breakdown
const models = await invoke('plugin:agor-pro|pro_analytics_model_breakdown', {
  period: 90,
});
```

## Limitations

- Analytics are computed on-demand from raw session_metrics rows. For large datasets (10,000+ sessions), queries may take 100-200ms. No materialized views or pre-aggregation.
- Historical data depends on community session_metrics persistence. If sessions.db is deleted or migrated, analytics history resets.
- Cost values are only available for providers that report cost (Claude, Codex). Ollama sessions show $0.00.
