# TUI Usage Guide

Complete guide to using the Cleave interactive terminal UI for task decomposition.

## Table of Contents

1. [Installation](#installation)
2. [Launching the TUI](#launching-the-tui)
3. [Backend Configuration](#backend-configuration)
4. [Session Management](#session-management)
5. [Keyboard Shortcuts](#keyboard-shortcuts)
6. [TUI Commands](#tui-commands)
7. [Troubleshooting](#troubleshooting)

## Installation

### Install TUI Dependencies

The TUI requires additional dependencies beyond the core CLI:

```bash
# TUI with Claude backend (default, requires Anthropic API key)
pipx install styrene-cleave[tui]

# TUI with local inference support (Ollama, vLLM, llama.cpp)
pipx install styrene-cleave[tui-local]

# All features
pipx install styrene-cleave[full]
```

### Verify Installation

```bash
cleave --version
cleave tui --help
```

## Launching the TUI

### Basic Launch

```bash
# Launch in current directory
cleave tui

# Launch in specific directory
cleave tui /path/to/project

# Launch with specific backend
cleave config set backend ollama
cleave tui
```

### Session Management

```bash
# List existing sessions
cleave tui --list-sessions

# Resume a session
cleave tui --session session-name

# Start new session with name
cleave tui --session-name my-feature
```

## Backend Configuration

The TUI supports multiple LLM backends for flexible deployment.

### Available Backends

1. **Claude** (via Anthropic API) - Default
2. **Ollama** (local inference)
3. **OpenAI** (via OpenAI API)
4. **vLLM** (self-hosted inference server)
5. **llama.cpp** (local inference)

### Configuration File

Create or edit `~/.cleave/settings.yaml`:

```yaml
# Active backend
backend: claude

# Backend-specific settings
backends:
  claude:
    default_model: claude-sonnet-4-20250514
    # api_key_env: ANTHROPIC_API_KEY  # Default

  ollama:
    base_url: http://localhost:11434/v1
    default_model: qwen2.5-coder:7b

  openai:
    base_url: https://api.openai.com/v1
    api_key_env: OPENAI_API_KEY
    default_model: gpt-4o

  vllm:
    base_url: http://localhost:8000/v1
    default_model: meta-llama/Llama-3.1-70B-Instruct

  llamacpp:
    base_url: http://localhost:8080/v1
    default_model: llama-3.1-70b-instruct
```

See [examples/tui/custom-backend-config.yaml](../../examples/tui/custom-backend-config.yaml) for a complete example.

### Using Claude Backend

```bash
# Set API key
export ANTHROPIC_API_KEY=your-api-key

# Configure backend
cleave config set backend claude
cleave config set backends.claude.default_model claude-sonnet-4-20250514

# Launch TUI
cleave tui
```

### Using Ollama Backend

```bash
# Start Ollama server
ollama serve

# Pull a model
ollama pull qwen2.5-coder:7b

# Configure backend
cleave config set backend ollama
cleave config set backends.ollama.default_model qwen2.5-coder:7b

# Launch TUI
cleave tui
```

Recommended Ollama models:
- `qwen2.5-coder:7b` - Fast, good for simple tasks
- `codellama:13b` - Better reasoning, slower
- `deepseek-coder:6.7b` - Good code generation

### Using vLLM Backend

```bash
# Start vLLM server
python -m vllm.entrypoints.openai.api_server \
  --model meta-llama/Llama-3.1-70B-Instruct \
  --port 8000

# Configure backend
cleave config set backend vllm
cleave config set backends.vllm.base_url http://localhost:8000/v1

# Launch TUI
cleave tui
```

### Switching Backends During a Session

```
# In the TUI input area, type:
/backend ollama
```

The TUI will reconnect with the new backend for subsequent messages.

## Session Management

### Creating Sessions

Sessions are created automatically when you launch the TUI:

```bash
# Auto-generated session name
cleave tui

# Custom session name
cleave tui --session-name auth-migration
```

### Saving Sessions

**Auto-save** (default):
Sessions are saved automatically on exit to `~/.cleave/sessions/`.

**Manual save**:
```
# In TUI input
/save session-name
```

Or use keyboard shortcut: `Ctrl+S`

### Resuming Sessions

```bash
# List sessions
cleave tui --list-sessions

# Resume session
cleave tui --session session-name
```

### Session Storage

Sessions are stored in `~/.cleave/sessions/`:

```
~/.cleave/sessions/
├── auth-migration-2026-01-27.json
├── api-refactor-2026-01-26.json
└── websocket-collab-2026-01-25.json
```

Each session file contains:
- Conversation history
- Backend configuration
- Execution state
- Workspace path

### Exporting Sessions

```
# In TUI input
/export session.md
```

Exports conversation to markdown format for documentation or sharing.

## Keyboard Shortcuts

### Input Area

| Shortcut | Action |
|----------|--------|
| `Enter` | Submit message |
| `Shift+Enter` | New line in message |
| `Up/Down` | Navigate input history |
| `Ctrl+A` | Start of line |
| `Ctrl+E` | End of line |
| `Ctrl+K` | Delete to end of line |

### Chat Panel

| Shortcut | Action |
|----------|--------|
| `Ctrl+L` | Clear chat |
| `Escape` | Cancel current operation |
| `PgUp/PgDown` | Scroll chat history |

### Session Management

| Shortcut | Action |
|----------|--------|
| `Ctrl+S` | Save session |

### Global

| Shortcut | Action |
|----------|--------|
| `Tab` | Focus next panel |
| `Shift+Tab` | Focus previous panel |
| `q` | Quit (prompts to save) |
| `Ctrl+C` | Force quit |

See [examples/tui/keyboard-shortcuts.md](../../examples/tui/keyboard-shortcuts.md) for complete reference.

## TUI Commands

Slash commands are entered in the input area.

### Session Commands

- `/save <name>` - Save session with name
- `/export <file>` - Export conversation to markdown
- `/clear` - Clear chat history
- `/status` - Show session status

### File Commands

- `/load <file>` - Load CALF file as directive
- `/cwd` - Show current working directory

### Backend Commands

- `/backend <name>` - Switch backend (claude, ollama, openai, vllm, llamacpp)
- `/model <name>` - Change model for current backend

### Help Commands

- `/help` - Show command help
- `/shortcuts` - Show keyboard shortcuts

## TUI Features

### Multi-Line Input

Use `Shift+Enter` to create multi-line directives:

```
Add JWT authentication with:
[Shift+Enter]
- Access tokens (15min expiry)
[Shift+Enter]
- Refresh tokens (7day expiry)
[Shift+Enter]
- Token blacklist for logout
[Enter to submit]
```

### Input History

Navigate previous messages with `Up/Down` arrows:
- Last 100 messages saved
- Persisted with session
- Editable before resubmit

### Live Streaming

LLM responses stream in real-time:
- Token-by-token display
- Cancel anytime with `Escape`
- Progress indicators for tool use

### Tool Use Display

When the LLM uses tools, you see:
- Tool name and parameters (syntax highlighted)
- Tool execution status
- Tool output (truncated if long)

Example:
```
[Tool: cleave assess]
Parameters:
  directive: "Add JWT authentication..."

[Output]
Pattern: Authentication System (0.85)
Complexity: 6.0
Decision: Cleave
```

### CALF File Support

Load directives from CALF files:

```
/load auth-migration.calf
```

The TUI reads the file and submits its contents as your message.

## Troubleshooting

### TUI Won't Launch

**Issue**: `ModuleNotFoundError: No module named 'textual'`

**Solution**:
```bash
pipx reinstall styrene-cleave[tui]
```

### Backend Connection Failed

**Issue**: `ConnectionError: Cannot connect to backend`

**Claude Backend**:
```bash
# Check API key
echo $ANTHROPIC_API_KEY

# Verify key is valid
curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{"model":"claude-sonnet-4-20250514","max_tokens":10,"messages":[{"role":"user","content":"Hi"}]}'
```

**Ollama Backend**:
```bash
# Check if Ollama is running
curl http://localhost:11434/api/tags

# Start Ollama if not running
ollama serve
```

**vLLM Backend**:
```bash
# Check if vLLM server is running
curl http://localhost:8000/v1/models

# Start vLLM if not running
python -m vllm.entrypoints.openai.api_server --model <model-name> --port 8000
```

### Session Not Saving

**Issue**: Session doesn't persist after exit

**Solution**:
```bash
# Check session directory exists
ls ~/.cleave/sessions/

# Create if missing
mkdir -p ~/.cleave/sessions/

# Verify permissions
chmod 755 ~/.cleave/sessions/
```

### Slow Response Times

**Issue**: LLM responses are very slow

**Claude Backend**:
- Check your API rate limits
- Ensure stable internet connection

**Ollama Backend**:
```bash
# Switch to smaller/faster model
cleave config set backends.ollama.default_model qwen2.5-coder:1.5b

# Or check system resources (CPU/RAM/GPU)
ollama ps
```

**vLLM Backend**:
- Check GPU memory usage
- Reduce `--max-num-seqs` flag on vLLM server

### Terminal Display Issues

**Issue**: Characters rendering incorrectly

**Solution**:
```bash
# Ensure UTF-8 locale
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

# Use high-contrast theme
cleave config set tui.theme default
```

### Keyboard Shortcuts Not Working

**Issue**: Shortcuts like `Ctrl+L` don't work

**Possible causes**:
1. Terminal emulator capturing the shortcut
2. Conflicting keybindings

**Solution**:
- Check terminal settings for conflicting bindings
- Try alternative terminal (iTerm2, Alacritty, Windows Terminal)

## Best Practices

### 1. Use CALF Files for Complex Directives

Instead of typing long directives:
```bash
# Create CALF file
cat > feature.calf << 'EOF'
Implement real-time collaboration with WebSocket support...
EOF

# Load in TUI
/load feature.calf
```

### 2. Save Sessions Regularly

Don't rely on auto-save alone:
```
# Manual save during long sessions
Ctrl+S
```

### 3. Export Important Conversations

```
# Export for documentation
/export auth-implementation.md
```

### 4. Use Smaller Models for Simple Tasks

Switch to lighter models for speed:
```
/backend ollama
/model qwen2.5-coder:1.5b
```

### 5. Clear Chat for Fresh Context

```
Ctrl+L
```

Clears UI without losing session state.

## Advanced Usage

### Custom Backend Setup

For team/enterprise deployments:

1. Set up shared vLLM server
2. Distribute `~/.cleave/settings.yaml` config
3. Point all clients to shared endpoint

### Session Collaboration

Export and share sessions:
```bash
# Export session
/export session.md

# Share session.md with team
# Others can follow the conversation history
```

### Scripting TUI Sessions

Use CALF files + CLI for automated workflows:
```bash
# Generate directive programmatically
./generate-directive.sh > feature.calf

# Launch TUI with directive
cleave tui
# Then: /load feature.calf
```

## Next Steps

- **Examples**: [Session Workflow](../../examples/tui/session-workflow.md)
- **Keyboard Reference**: [Full Shortcuts](../../examples/tui/keyboard-shortcuts.md)
- **Backend Config**: [Custom Config Example](../../examples/tui/custom-backend-config.yaml)
- **Architecture**: [Backend Interface](../architecture/backend-interface.md)
