# Concave DevTools

Professional development tools for Convex/Concave applications. A high-signal browser DevTools focused on operation debugging, subscriptions, logs, and performance.

## Features

### 🔎 Activity Panel
- Unified list of queries, mutations, and actions
- Fast filter/search with keyboard navigation
- Search across function path, IDs, args, results, errors, and log lines
- Incremental history loading for long sessions
- Arguments and results inspection
- Inline error visibility with focused details pane

### 📈 Performance Monitoring
- Average, P50/P90/P95/P99 latency metrics per operation type
- Per-function breakdown: calls, avg/P95 latency, error rate (sortable)
- Error count and rate across all operations
- Slowest operations tracking
- Live 60-second latency sparklines per operation type
- Click-through from slow operations and functions to full Activity details

### 📡 Subscriptions Panel
- Live subscribed query tracking
- Update counts, status, and component context

### 📝 Logs Panel
- Centralized console logs from all functions
- Filter by log level (log, info, warn, error)
- Auto-scroll and search
- Search by related operation path/ID
- Related event tracking

### ⚙️ Settings & Advanced Features
- **Pause/Resume Recording**: Control when events are captured
- **Export/Import Sessions**: Save and share debugging sessions
- **Time-Travel Debugging**: Create snapshots and restore state
- **Persistent Storage**: Events persist across page reloads
- **Keyboard Shortcuts**: Fast access to all features

## Installation

```bash
npm install @concavejs/devtools
```

## Usage

### Vite Plugin

Add the devtools plugin to your `vite.config.ts`:

```typescript
import { defineConfig } from "vite";
import { concaveDevTools } from "@concavejs/devtools/vite";

export default defineConfig({
  plugins: [
    concaveDevTools({
      // Only enable in development (default: true in dev mode)
      enabled: true,
      
      // Position of the devtools overlay
      position: "bottom-right", // "bottom-right" | "bottom-left" | "top-right" | "top-left"
    }),
  ],
});
```

That's it! The devtools will automatically initialize when your app loads in development mode.

### Manual Installation (without Vite plugin)

If you're not using Vite or want manual control:

```typescript
import { initDevTools } from "@concavejs/devtools/client";

// Initialize devtools
initDevTools({
  position: "bottom-right",
});
```

## Keyboard Shortcuts

- **Cmd/Ctrl + Shift + D**: Toggle DevTools
- **Cmd/Ctrl + K**: Focus search
- **Cmd/Ctrl + E**: Export session
- **Cmd/Ctrl + P**: Pause/Resume recording

## API

### Event Store

The devtools use a global event store that you can access programmatically:

```typescript
import { getGlobalEventStore } from "@concavejs/devtools";

const store = getGlobalEventStore();

// Subscribe to events (one callback per event, delivered synchronously)
const unsubscribe = store.subscribe((event) => {
  console.log("New event:", event);
});

// Subscribe in coalesced batches (at most ~12 deliveries/second).
// Prefer this for UI rendering so chatty apps don't re-render per event.
const unsubscribeBatched = store.subscribeBatched((events) => {
  console.log(`${events.length} new events`);
});

// Get all events
const events = store.getAllEvents();

// Get events by type
const queries = store.getEventsByType("query");

// Get active subscriptions
const subscriptions = store.getActiveSubscriptions();

// Get performance metrics
const metrics = store.getPerformanceMetrics();

// Per-function aggregates (calls, errors, error rate, avg/p50/p95/max)
const functionStats = store.getFunctionStats();

// Export session
const session = store.exportSession();

// Import session
store.importSession(session);

// Pause/Resume
store.pause();
store.resume();

// Clear all data
store.clear();
```

### WebSocket Interceptor

The devtools automatically intercept WebSocket communication with the Convex/Concave backend. You can also use the interceptor directly:

```typescript
import { WebSocketInterceptor, EventStore } from "@concavejs/devtools";

const eventStore = new EventStore();
const interceptor = new WebSocketInterceptor(eventStore);

// Install the interceptor
interceptor.install();

// Uninstall when done
interceptor.uninstall();
```

## Components

You can use the devtools components in your own React application:

```typescript
import { DevToolbar } from "@concavejs/devtools";
import { getGlobalEventStore } from "@concavejs/devtools";

function MyApp() {
  const eventStore = getGlobalEventStore();

  return <DevToolbar eventStore={eventStore} position="bottom-right" />;
}
```

## Session Management

### Export Session

Export your debugging session to share with team members or for later analysis:

1. Open DevTools
2. Click the 💾 button or press **Cmd/Ctrl + E**
3. Save the `.json` file

### Import Session

Import a previously exported session:

1. Open DevTools
2. Go to Settings tab
3. Click "Import"
4. Select the `.json` file

Importing pauses recording so live traffic doesn't mix into the imported
session; resume from the Settings tab or with **Cmd/Ctrl + P** when done.

### Time-Travel Debugging

Create snapshots of your application state:

1. Open DevTools → Settings
2. Click "Snapshot"
3. Continue using your app
4. Click "Restore" on any snapshot to go back in time

Snapshots survive "Clear", so you can save a known-good state, clear the
noise, and still get back to it.

## Configuration

### Event Store Settings

Configure the event store behavior:

```typescript
import { getGlobalEventStore } from "@concavejs/devtools";

const store = getGlobalEventStore();

store.saveSettings({
  // Persist events across page reloads
  persistEvents: true,
  
  // Maximum number of events to store
  maxEvents: 1000,
  
  // Capture console logs from functions
  captureLogLines: true,
});
```

## Performance

The devtools are designed to have minimal impact on your application:

- Events are stored in a circular buffer (configurable max size)
- WebSocket interception uses native proxies for minimal overhead
- React components are optimized with proper memoization
- Persistence uses localStorage with size limits

## Browser Support

- Chrome/Edge: ✅ Full support
- Firefox: ✅ Full support
- Safari: ✅ Full support

## Development

```bash
# Install dependencies
npm install

# Build the package
npm run build

# Type check
npm run type-check

# Watch mode (for development)
npm run dev
```

## Architecture

The devtools consist of several key components:

1. **Vite Plugin**: Injects the devtools into your app during development
2. **WebSocket Interceptor**: Captures Convex sync protocol messages
3. **Event Store**: Maintains a history of all captured events
4. **React UI**: Full-featured devtools interface
5. **Client Entry**: Initializes everything and mounts the UI

## License

MIT

## Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.
