# Bzzz Chat-to-Code Integration Test Suite

This subproject demonstrates a complete chat-triggered workflow that integrates N8N with Bzzz agents for real-time code execution in ephemeral sandboxes.

## 🚀 Overview

The chat integration allows users to send natural language requests through a chat interface, which are then:
1. **Parsed and validated** by N8N workflow
2. **Enhanced with LLM analysis** for better task understanding  
3. **Sent to Bzzz agents** for execution in isolated Docker sandboxes
4. **Results returned** to the chat with code artifacts and execution logs

## 📁 Files

```
test/
├── chat-to-code-integration.json   # N8N workflow definition
├── chat_api_handler.go              # Go API server for Bzzz integration
├── run_chat_api.sh                  # Build and run script
├── test_chat_api.py                 # Python test client
└── CHAT_INTEGRATION_README.md       # This file
```

## 🛠️ Setup Instructions

### 1. Prerequisites

**Infrastructure:**
- N8N instance running at `https://n8n.home.deepblack.cloud/`
- Ollama endpoints: WALNUT (`192.168.1.27:11434`), IRONWOOD (`192.168.1.113:11434`)
- Docker with Bzzz sandbox image: `registry.home.deepblack.cloud/tony/bzzz-sandbox:latest`

**Dependencies:**
```bash
# Go dependencies (auto-installed)
go get github.com/gorilla/mux

# Python dependencies
pip install requests
```

### 2. Start the Bzzz Chat API

```bash
# Build and run the API server
cd /home/tony/AI/projects/Bzzz
./test/run_chat_api.sh
```

This starts the API server on `http://localhost:8080` with endpoints:
- `POST /bzzz/api/execute-task` - Execute task in sandbox
- `GET /bzzz/api/health` - Health check

### 3. Test the API

```bash
# Run the test suite
./test/test_chat_api.py
```

Expected output:
```
🧪 Bzzz Chat API Test Suite
========================================
🔍 Testing health check endpoint...
✅ Health check passed: {'status': 'healthy', 'service': 'bzzz-chat-api'}
🚀 Testing task execution...
✅ Task accepted: {'task_id': 9999, 'status': 'accepted'}
✅ All tests passed!
```

### 4. Import N8N Workflow

1. **Open N8N Interface**
   ```
   https://n8n.home.deepblack.cloud/
   ```

2. **Import Workflow**
   - Go to `Workflows` → `Import from File`
   - Upload `chat-to-code-integration.json`
   - Configure webhook URLs and API endpoints

3. **Configure Endpoints**
   ```json
   {
     "bzzz_api_url": "http://localhost:8080/bzzz/api/execute-task",
     "ollama_walnut": "http://192.168.1.27:11434/api/generate",
     "ollama_ironwood": "http://192.168.1.113:11434/api/generate"
   }
   ```

4. **Activate Workflow**
   - Enable the chat trigger
   - Test with sample chat messages

## 💬 Usage Examples

### Simple Requests
```
"Create a simple hello world function in Python"
"Build a calculator in JavaScript"
"Write a sorting algorithm in Go"
```

### Structured Requests
```
Task: Implement user authentication API
Repo: https://github.com/myorg/api-server.git
Language: Python

Task: Fix memory leak in session handler
Repo: https://github.com/myorg/web-app.git
Language: JavaScript
```

### Complex Requests
```
Build a React component that displays a todo list with add/remove functionality. 
Include proper TypeScript types and basic styling. Make it responsive and 
add unit tests using Jest.
```

## 🔄 Workflow Flow

1. **Chat Input** → User sends message via chat interface
2. **Parse Request** → Extract task details, repo, language
3. **LLM Validation** → Validate and enhance task description
4. **Create Bzzz Request** → Format for Bzzz API
5. **Submit to Bzzz** → Send to chat API handler
6. **Sandbox Execution** → Execute in isolated Docker container
7. **Collect Results** → Gather code artifacts and logs
8. **Return to Chat** → Send formatted results back

## 📊 API Reference

### POST /bzzz/api/execute-task

**Request:**
```json
{
  "method": "execute_task_in_sandbox",
  "task": {
    "task_id": 1001,
    "title": "Create hello world function",
    "description": "Create a simple Python function that prints hello world",
    "repository": {"owner": "test", "repository": "demo"},
    "git_url": "",
    "task_type": "development"
  },
  "execution_options": {
    "sandbox_image": "registry.home.deepblack.cloud/tony/bzzz-sandbox:latest",
    "timeout": "300s",
    "max_iterations": 5,
    "cleanup_on_complete": true
  },
  "callback": {
    "webhook_url": "https://n8n.home.deepblack.cloud/webhook/bzzz-result/1001",
    "include_artifacts": true
  }
}
```

**Response:**
```json
{
  "task_id": 1001,
  "status": "accepted",
  "message": "Task accepted for execution"
}
```

**Callback (Async):**
```json
{
  "task_id": 1001,
  "status": "success",
  "execution_time": "45.2s",
  "artifacts": {
    "files_created": [
      {
        "name": "hello.py",
        "size": 156,
        "content": "def hello_world():\n    print('Hello, World!')\n\nif __name__ == '__main__':\n    hello_world()",
        "language": "python"
      }
    ],
    "code_generated": "def hello_world():\n    print('Hello, World!')",
    "language": "python"
  },
  "execution_log": [
    {
      "step": 1,
      "action": "Starting task execution",
      "success": true,
      "timestamp": "2025-01-17T10:30:00Z"
    },
    {
      "step": 2,
      "action": "Created sandbox",
      "result": "Sandbox ID: abc123def456",
      "success": true,
      "timestamp": "2025-01-17T10:30:05Z"
    }
  ]
}
```

This chat integration provides a seamless bridge between natural language requests and actual code execution, making Bzzz agents accessible through familiar chat interfaces!