mecha10-cli 0.1.21

Mecha10 CLI tool
Documentation
# UI Migration to Ratatui - Summary

## ✅ Completed

The CLI has been fully migrated to use **ratatui** for all TUI interfaces. The 3-panel layout provides enhanced user experience with logs sidebar and footer links.

## Architecture

### UI Abstraction Layer

**Location**: `packages/cli/src/ui/traits.rs`

```rust
pub enum UiMode {
    Simple,    // Basic terminal output (crossterm only)
    Advanced,  // Rich TUI with ratatui (logs sidebar, etc.)
}

pub trait TeleopUiTrait: Send {
    async fn run_with_interrupt(&mut self, running: Arc<AtomicBool>) -> Result<()>;
}
```

### UI Implementation

**All modes use ratatui TUI**: 3-panel layout with logs sidebar and footer

```bash
# Run dev mode with TUI
mecha10 dev

# Press 't' to enter teleop with full TUI interface
```

### Components

| Component | Location | Purpose |
|-----------|----------|---------|
| `TeleopUiTrait` | `ui/traits.rs` | Trait for teleop implementations |
| `LogBuffer` | `ui/dev_tui.rs` | Thread-safe log collection |
| `TeleopUi` | `ui/teleop.rs` | TUI implementation with 3-panel layout |

## Changes Made

### 1. UI Layer (`packages/cli/src/ui/`)

**New Files**:
- `traits.rs` - UI abstraction traits and types
- `dev_tui.rs` - Generic TUI components (LogBuffer, etc.)
- `teleop_tui.rs` - Advanced teleop TUI with logs sidebar

**Modified Files**:
- `mod.rs` - Updated exports and documentation
- `teleop.rs` - Added trait implementation and factory method

### 2. Dev Mode (`packages/cli/src/handlers/dev/`)

**Modified Files**:
- `session.rs` - Added `ui_mode` and `log_buffer` to `DevSession`
- `ops.rs` - Updated to pass UI mode and log buffer to teleop

**Changes**:
```rust
// Before (simple terminal output)
let mut teleop_ui = TeleopUi::new(redis_url.to_string());

// After (TUI with logs sidebar)
let mut teleop_ui = TeleopUi::new(
    redis_url.to_string(),
    log_buffer
);
```

### 3. Session State

`DevSession` now includes:
- `log_buffer: LogBuffer` - Shared log buffer for TUI logs

`InteractiveModeState` now includes:
- `log_buffer: LogBuffer` - Passed to UI components

### 4. Enhanced Teleop TUI Layout (Latest Update)

**3-Panel Layout**:
```
┌─────────────────────────────────────────────────────────────┐
│                    Main Area (60%)         │ Logs (40%)     │
│   ┌───────────────────────────┐           │                │
│   │  🎮 Teleop Controls       │           │ ⚡ MODE: ...   │
│   │                           │           │ ✅ STARTED: .. │
│   │  Controls:                │           │ 🛑 STOPPED: .. │
│   │    ↑/W  Forward           │           │ ℹ️  INFO: ...  │
│   │    ↓/S  Backward          │           │ ❌ ERROR: ...  │
│   │    ←/A  Turn Left         │           │                │
│   │    →/D  Turn Right        │           │                │
│   │                           │           │                │
│   │  Status:                  │           │                │
│   │    Linear: 0.00 m/s       │           │                │
│   │    Angular: 0.00 rad/s    │           │                │
│   └───────────────────────────┘           │                │
│                                            │                │
├────────────────────────────────────────────┴────────────────┤
│ Dashboard: http://localhost:3000  Docs: https://mecha10.dev│
│ Q/ESC: Exit                                                 │
└─────────────────────────────────────────────────────────────┘
```

**Automatic Event Logging**:
- Mode changes logged when pressing 's' or 't'
- Node start/stop events logged with PID
- Errors and warnings highlighted with icons
- All logs color-coded and scrollable

## Usage

### Dev Mode with TUI

```bash
# Run dev mode
mecha10 dev

# Press 's' to switch to simulation mode (logs mode change in sidebar)
# Press 't' to switch to teleop mode (logs mode change in sidebar)
# Ratatui TUI with 3-panel layout: main + logs + footer
```

**TUI Features**:
- ✅ 3-panel layout: Main area (60%) / Logs sidebar (40%) / Footer (3 lines)
- ✅ Real-time log streaming with automatic mode/node event logging
- ✅ Color-coded log levels with icons:
  - ERROR: ❌ (red, bold)
  - WARN: ⚠️  (yellow)
  - MODE changes: ⚡ (cyan, bold)
  - Node STARTED: ✅ (green)
  - Node STOPPED: 🛑 (red)
  - INFO: ℹ️  (green)
  - DEBUG: 🔍 (blue)
- ✅ Scrollable logs (PgUp/PgDn)
- ✅ Status display (velocity, commands sent)
- ✅ Footer with links (Dashboard: http://localhost:3000, Docs: https://mecha10.dev)
- ✅ Automatic logging of mode changes and node lifecycle events

## Future Enhancements

### Phase 2: Dev Mode TUI
- Add logs sidebar to main dev mode (not just teleop)
- Show all node logs in real-time
- Multiple tabs: Logs | Metrics | Diagnostics

### Phase 3: Log Collection
- Collect logs from running nodes via Redis pub/sub
- Filter logs by level
- Search logs
- Export logs to file

### Phase 4: Metrics Dashboard
- CPU, memory, network usage
- Message throughput
- Node health status
- Charts and graphs

## API

### Creating Teleop UI

```rust
use mecha10_cli::ui::{TeleopUi, LogBuffer};

// Create TUI with logs
let log_buffer = LogBuffer::new(1000);
let mut ui = TeleopUi::new(redis_url, log_buffer);

// Run
ui.run_with_interrupt(running).await?;
```

### LogBuffer

```rust
use mecha10_cli::ui::LogBuffer;

// Create
let buffer = LogBuffer::new(1000); // Keep last 1000 logs

// Add logs
buffer.push("INFO: System started".to_string());
buffer.push("WARN: Low battery".to_string());
buffer.push("ERROR: Connection failed".to_string());

// Get logs
let logs = buffer.get_logs(); // Returns Vec<String>

// Share across threads (Clone is cheap - Arc internally)
let buffer2 = buffer.clone();
tokio::spawn(async move {
    buffer2.push("DEBUG: Background task".to_string());
});
```

## Testing

```bash
# Build
cargo build -p mecha10-cli

# Test TUI
cargo run -p mecha10-cli -- dev

# Press 't' to enter teleop and see 3-panel layout
# Press 's' to enter simulation and see mode change logs

# Format
pnpm format:rust

# Check
cargo check -p mecha10-cli
```

## Migration Notes

### For Developers

**Backward compatibility removed** - TUI is now the only mode!

- `TeleopUi::new()` now creates full TUI (requires log_buffer)
- Removed `UiMode` enum
- Removed factory pattern `with_mode()`
- All handlers pass log_buffer to teleop
- Mode changes and node lifecycle events automatically logged

### For Users

**Enhanced experience** - rich TUI for all interactions!

- 3-panel layout: main area + logs sidebar + footer
- Real-time logs with mode changes and node events
- Color-coded log levels with icons
- Dashboard and docs links in footer

## Files Changed

### Initial Migration
### Phase 1: Initial TUI Migration
```
packages/cli/src/
├── ui/
│   ├── mod.rs                 ✏️  Updated exports
│   ├── traits.rs              ✨  New - UI trait definitions
│   ├── dev_tui.rs             ✨  New - LogBuffer, shared components
│   ├── teleop_tui.rs          ✨  New - TUI implementation
│   └── teleop.rs              ✏️  Kept for backward compat
├── handlers/dev/
│   ├── session.rs             ✏️  Added log_buffer
│   └── ops.rs                 ✏️  Added log_buffer handling
```

### Phase 2: 3-Panel Layout + Event Logging
```
packages/cli/src/
├── ui/
│   ├── teleop_tui.rs          ✏️  Enhanced - 3-panel layout with footer
│   └── mod.rs                 ✏️  Updated exports
├── handlers/dev/
│   ├── ops.rs                 ✏️  Added logging to mode changes & spawning
│   └── session.rs             ✏️  Log initial mode on startup
```

### Phase 3: Remove Backward Compatibility (Latest)
```
packages/cli/src/
├── ui/
│   ├── teleop.rs              ✏️  Replaced with TUI version (teleop_tui.rs renamed)
│   ├── mod.rs                 ✏️  Removed UiMode exports
│   └── traits.rs              ✏️  Removed UiMode enum
├── handlers/dev/
│   ├── ops.rs                 ✏️  Removed UiMode parameters
│   ├── session.rs             ✏️  Removed UiMode field
│   └── InteractiveModeConfig  ✏️  Removed ui_mode field
```

**Key Changes in Phase 3**:
- Removed `UiMode` enum entirely
- `teleop_tui.rs` renamed to `teleop.rs` (replaced old simple version)
- All functions now require `LogBuffer` (no optional)
- Removed factory pattern `with_mode()`
- `TeleopUi::new()` now creates full TUI implementation
- Removed `MECHA10_SIMPLE_UI` environment variable check

## Documentation

- **This file**: Migration summary and API reference
- **`RATATUI_GUIDE.md`**: Detailed ratatui usage guide
- **Code comments**: Updated with UI mode information

## Verification

✅ Compiles without errors
✅ Backward compatibility removed - TUI only
✅ 3-panel layout with logs sidebar and footer
✅ Mode changes and node events automatically logged
✅ Code formatted and linted

## Next Steps

1. **Test in real usage**: Run `mecha10 dev` and test both modes
2. **Add log collection**: Implement actual log streaming from nodes
3. **Extend to dev mode**: Add logs sidebar to main dev session
4. **Add metrics**: CPU, memory, node status displays
5. **Documentation**: Update user guides with new UI features

---

**Status**: ✅ Migration Complete - TUI Only Mode
**Date**: 2025-11-19
**Breaking Changes**: Removed backward compatibility, TUI is now the only mode
**Environment Variables**: None (removed `MECHA10_SIMPLE_UI`)