# Lemma Dashboard

Real-time visualization and monitoring dashboard for the Lemma agent orchestration hub.

## Features

### 1. Agent Graph
- Live visualization of connected agents
- Node graph showing agent relationships
- Real-time status updates (active, idle, busy)
- Agent capabilities display
- Connection lines to central hub

### 2. Token Economics
- Real-time cost savings tracking
- Token usage metrics
- Cache hit rate visualization
- Performance charts:
  - Cache performance over time
  - Latency trends
  - Cumulative cost savings
- ROI calculator with projections

### 3. Time-Travel Debugger
- Event timeline with all agent interactions
- State inspector for any point in time
- Playback controls (pause, step back/forward)
- State editing capabilities
- Event filtering by type

## Quick Start

### Installation

```bash
cd dashboard
npm install
```

### Development

```bash
npm run dev
```

Dashboard will be available at `http://localhost:3000`

### Production Build

```bash
npm run build
npm run preview
```

## Configuration

Create a `.env` file:

```env
VITE_ROUTER_URL=ws://localhost:8080
VITE_API_URL=http://localhost:8080
```

## Architecture

### Tech Stack

- **React 18**: UI framework
- **TypeScript**: Type safety
- **Vite**: Build tool and dev server
- **TailwindCSS**: Styling
- **Recharts**: Data visualization
- **Zustand**: State management
- **WebSocket**: Real-time communication

### Project Structure

```
dashboard/
├── src/
│   ├── components/
│   │   ├── AgentGraph.tsx      # Agent visualization
│   │   ├── MetricsPanel.tsx    # Token economics
│   │   ├── TimeTravel.tsx      # State debugger
│   │   ├── ConnectionStatus.tsx # WebSocket status
│   │   └── Layout.tsx          # App layout
│   ├── hooks/
│   │   └── useWebSocket.ts     # WebSocket connection
│   ├── App.tsx                 # Main app component
│   ├── main.tsx               # Entry point
│   └── index.css              # Global styles
├── index.html
├── package.json
├── tsconfig.json
├── vite.config.ts
└── tailwind.config.js
```

## WebSocket Protocol

The dashboard connects to the Lemma router via WebSocket and exchanges IAP (Inter-Agent Protocol) messages.

### Connection

```typescript
const ws = new WebSocket('ws://localhost:8080');

// Send handshake
ws.send(JSON.stringify({
  type: 'HANDSHAKE',
  messageId: crypto.randomUUID(),
  timestamp: Date.now(),
  payload: {
    agentId: 'dashboard-client',
    agentName: 'Dashboard',
    version: '1.0.0',
    capabilities: [{ name: 'monitoring', version: '1.0.0' }],
  },
}));
```

### Message Types

#### Metrics Update
```json
{
  "type": "METRICS_UPDATE",
  "payload": {
    "totalRequests": 1000,
    "cacheHits": 800,
    "cacheMisses": 200,
    "averageLatency": 45.2,
    "tokensSaved": 150000,
    "costSaved": 0.3,
    "hitRate": "80.0%"
  }
}
```

#### Agent Connected
```json
{
  "type": "AGENT_CONNECTED",
  "payload": {
    "id": "agent-123",
    "name": "Research Agent",
    "capabilities": ["research", "analysis"],
    "status": "idle",
    "connectedAt": 1234567890
  }
}
```

#### State Event
```json
{
  "type": "STATE_EVENT",
  "payload": {
    "id": "event-uuid",
    "timestamp": 1234567890,
    "type": "TASK_REQUEST",
    "agentId": "agent-123",
    "data": {},
    "snapshot": {}
  }
}
```

## Components

### AgentGraph

Visualizes the agent swarm as a node graph.

**Props:**
- `agents: Agent[]` - Array of connected agents

**Features:**
- Circular layout around central hub
- Color-coded status indicators
- Capability badges
- Connection lines with animation

### MetricsPanel

Displays token economics and performance metrics.

**Props:**
- `metrics: Metrics` - Current metrics object

**Features:**
- 6 key metric cards
- 3 interactive charts
- ROI calculator
- Historical data tracking

### TimeTravel

State debugger with time-travel capabilities.

**Props:**
- `events: StateEvent[]` - Array of captured events

**Features:**
- Event timeline
- State inspector
- Playback controls
- State editing

### ConnectionStatus

Shows WebSocket connection status.

**Props:**
- `isConnected: boolean` - Connection state

## Customization

### Theme

Edit `tailwind.config.js` to customize colors:

```javascript
theme: {
  extend: {
    colors: {
      primary: { /* your colors */ },
      success: { /* your colors */ },
      // ...
    },
  },
}
```

### Metrics

Add custom metrics in `useWebSocket.ts`:

```typescript
export interface Metrics {
  // ... existing metrics
  customMetric: number;
}
```

### Charts

Add new charts in `MetricsPanel.tsx` using Recharts:

```typescript
<LineChart data={historicalData}>
  <Line dataKey="customMetric" stroke="#color" />
</LineChart>
```

## Performance

### Optimizations

- **Lazy Loading**: Components loaded on-demand
- **Memoization**: React.memo for expensive components
- **Virtual Scrolling**: For large event lists
- **Data Limiting**: Keep only recent data points

### Metrics

- **Bundle Size**: ~200KB gzipped
- **Initial Load**: <1s on fast connection
- **Memory Usage**: ~50MB typical
- **CPU Usage**: <5% idle, <15% active

## Deployment

### Static Hosting

Build and deploy to any static host:

```bash
npm run build
# Upload dist/ folder to:
# - Vercel
# - Netlify
# - AWS S3 + CloudFront
# - GitHub Pages
```

### Docker

```dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
```

### Environment Variables

Set in deployment platform:

- `VITE_ROUTER_URL`: WebSocket URL of Lemma router
- `VITE_API_URL`: HTTP API URL (if different)

## Troubleshooting

### WebSocket Connection Failed

1. Check router is running
2. Verify URL in `.env`
3. Check CORS settings
4. Verify firewall rules

### Metrics Not Updating

1. Check WebSocket connection status
2. Verify router is broadcasting metrics
3. Check browser console for errors
4. Verify message format

### Charts Not Rendering

1. Check data format matches Recharts requirements
2. Verify ResponsiveContainer has height
3. Check for console errors
4. Verify data is not empty

## Development

### Adding a New Tab

1. Create component in `src/components/`
2. Add tab button in `App.tsx`
3. Add route in tab navigation
4. Update state management

### Adding a New Metric

1. Update `Metrics` interface in `useWebSocket.ts`
2. Add metric card in `MetricsPanel.tsx`
3. Update backend to send metric
4. Add to historical data tracking

## License

MIT
