# BotDojo Chat SDK Playground

> **Beta** - Interactive playground for the BotDojo Chat SDK

Explore chat widgets, MCP Apps, and headless integrations with live examples and real-time debugging.

[![npm version](https://img.shields.io/npm/v/@botdojo/chat-sdk.svg)](https://www.npmjs.com/package/@botdojo/chat-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

## Features

- 🚀 **Chat SDK Examples**: Inline, popup, side panel, and headless chat modes
- 🎨 **Beautiful UI**: Modern theme with three-column layout
- 🐛 **Debug Panel**: Real-time event logging for all SDK interactions
- ⚡ **Quick Actions**: Pre-configured test scenarios for each example
- 🔧 **Easy Setup**: Automated setup script using BotDojo CLI

## Quick Start

### Prerequisites

1. **Node.js 18+** installed
2. **BotDojo CLI** installed:
   ```bash
   npm install -g @botdojo/cli
   ```
3. **BotDojo Account** - [Sign up free](https://app.botdojo.com/signup)

### Installation

```bash
# Clone the repository
git clone https://github.com/botdojo-ai/chat-sdk-playground.git
cd chat-sdk-playground

# Install dependencies
npm install
```

### Setup

Run the setup script to configure your environment:

```bash
npm run setup
```

This will:
- Authenticate you with BotDojo (opens browser with user confirmation)
- Use your current CLI project context (never auto-switches)
- Clone test agent flows to your project (or update existing ones)
- Create public API keys for newly cloned flows
- Generate `.env.local` with all configuration

**Note:** The setup script is idempotent - safe to run multiple times. It will:
- Update existing flows from their origin instead of creating duplicates
- Preserve existing API keys from `.env.local`
- Only create new API keys for freshly cloned flows
- Never automatically switch your CLI project context

### Start Development Server

```bash
npm run dev
```

Open [http://localhost:3500](http://localhost:3500) in your browser.

## Examples

### Chat SDK Examples

| Example | Description | Key Patterns | Path |
|---------|-------------|--------------|------|
| **Getting Started** | Minimal inline widget example | Basic setup | `/examples/chat-sdk/getting-started` |
| **Chat Widget Modes** | Popup, side panel, inline configurations | Widget config | `/examples/chat-sdk/basic` |
| **Headless Chat + MCP Apps** | Build your own UI with SDK hooks | Custom UI | `/examples/chat-sdk/headless-mcp` |
| **Document Editor** | Agent edits markdown with MCP Apps diff cards | `notifyToolInputPartial`, refs | `/examples/chat-sdk/document-edit` |
| **Product Enhance** | AI-powered product description enhancement | Streaming, `onToolInputPartial`, `callTool`, persistence | `/examples/product-enhance` |
| **MCP App Exercise** | Test `ui/message`, `tools/call`, `ui/open-link` | MCP App protocol | `/examples/chat-sdk/mcp-app-example` |
| **Bonsai Shop** | E-commerce demo with checkout flows | Full integration | `/examples/chat-sdk/bonsai-shop` |

### Key Patterns Demonstrated

The examples contain inline JSDoc comments explaining important patterns:

- **Using refs for state**: Tool execute functions capture state via refs to avoid stale closures
- **resourceUri matching**: Tool `_meta.ui.resourceUri` must exactly match resource `uri`
- **Streaming with onToolInputPartial**: Receive partial tool arguments as the AI generates
- **Detecting completion with tool.result**: Transition UI when tool execution finishes
- **Persisting state with botdojo/persist**: Save MCP App state across page reloads
- **Calling host tools with callTool**: MCP Apps can trigger actions on the host
- **Size reporting**: Use `reportSize` for dynamic content in iframes

## Project Structure

```
chat-sdk-playground/
├── pages/                    # Next.js pages
│   ├── index.tsx             # Landing page
│   └── examples/             # Example pages
│       └── chat-sdk/         # Chat SDK examples
│
├── src/
│   ├── components/
│   │   └── layout/
│   │       ├── MainLayout.tsx      # Three-column layout
│   │       ├── ExampleNav.tsx      # Left navigation
│   │       └── DebugPanel.tsx      # Right debug panel
│   │
│   ├── lib/
│   │   └── eventBus.ts            # Centralized event logging
│   │
│   └── styles/
│       └── globals.css            # Global styles and theme
│
├── scripts/
│   └── setup.sh              # Automated setup script
│
├── .env.local               # Generated by setup script (gitignored)
└── package.json
```

## Layout

The playground uses a three-column layout:

```
┌─────────────────────────────────────────────────────────────┐
│  [Example Nav]  │  [Main Content]  │  [Debug Panel]         │
│                 │                  │                        │
│  Examples:      │  Example Demo    │  Event Log:            │
│  • Chat Modes   │                  │  🟢 onNewToken         │
│  • Headless UI  │  [Component]     │  🔵 onStepUpdate       │
│  • MCP Apps     │                  │  🟡 toolCall           │
│                 │  Quick Actions:  │  🔴 error              │
└─────────────────────────────────────────────────────────────┘
```

## Debug Panel

The debug panel shows real-time events from SDK interactions:

- **Event Types**: Token, Step, Tool Call, Error, Info, MCP App
- **Filters**: Toggle event types on/off
- **Auto-scroll**: Automatically scroll to latest events
- **Export**: Download events as JSON
- **Clear**: Clear all events

## Environment Variables

The setup script generates `.env.local` with these variables:

```bash
# User-specific configuration (keep private)
NEXT_PUBLIC_ACCOUNT_ID=<your-account-id>
NEXT_PUBLIC_PROJECT_ID=<your-project-id>

# Flow IDs (client-side)
NEXT_PUBLIC_BOTDOJO_BASIC_FLOW_ID=<your-flow-id>
NEXT_PUBLIC_BOTDOJO_MODEL_CONTEXT_FLOW_ID=<your-flow-id>

# Server-side API key for JWT token generation
# This key is NOT exposed to the browser - tokens are generated server-side
BOTDOJO_MODEL_CONTEXT_API=<your-api-key>
```

## Scripts

| Command | Description |
|---------|-------------|
| `npm run setup` | Run setup script (authenticate, clone flows, create API keys) |
| `npm run dev` | Start development server on port 3500 |
| `npm run build` | Build for production |
| `npm run start` | Start production server |
| `npm run lint` | Run ESLint |
| `npm run clean` | Remove build artifacts and node_modules |
| `npm run install:test-deps` | Install optional test dependencies (Puppeteer) |
| `npm run test` | Run all tests (requires dev server running and test deps) |

## Testing

The playground includes Puppeteer-based browser tests:

```bash
# Prerequisites: 
# 1. Install test dependencies (Puppeteer is optional and not installed by default)
npm run install:test-deps

# 2. Dev server must be running
npm run dev  # In one terminal

# 3. Run tests
npm run test  # In another terminal
```

**Special URL Parameters:**
- `?newsession=true` - Forces a new session (useful for testing)

## Troubleshooting

### Environment Variables Not Loading

Next.js only reads `.env.local` at startup. After running setup:
```bash
# Restart the dev server
npm run dev
```

### Setup Script Fails

Make sure BotDojo CLI is installed:
```bash
npm install -g @botdojo/cli
```

### Connection Errors

For local development, update `.env.local` with your local server URLs and restart the dev server.

### Port 3500 Already in Use

Change the port in `package.json`:
```json
"dev": "next dev -p 3600",
"start": "next start -p 3600"
```

## Deployment

### Vercel

The playground is configured to skip optional dependencies (like Puppeteer) during deployment via `vercel.json`:

```json
{
  "installCommand": "npm install --no-optional"
}
```

This keeps build times fast and avoids unnecessary dependencies in production.

## Tech Stack

- **Next.js 13+** - React framework
- **TypeScript** - Type safety
- **@botdojo/chat-sdk** - Chat widget and headless hooks
- **@botdojo/sdk** - Core SDK for flow execution
- **mcp-app-view** - MCP Apps rendering
- **Tailwind CSS** - Styling

## Contributing

Want to add a new example?

1. Create a new page in `pages/examples/chat-sdk/`
2. Add the route to `EXAMPLES` in `src/components/layout/ExampleNav.tsx`
3. Use the event bus to log events: `eventBus.logInfo()`, `eventBus.logToken()`, etc.
4. Include quick action buttons for common test scenarios

## Links

- [BotDojo Website](https://botdojo.com)
- [About Agentic UI](https://www.botdojo.com/solutions/agentic-ui)
- [@botdojo/chat-sdk on npm](https://www.npmjs.com/package/@botdojo/chat-sdk)
- [@botdojo/sdk on npm](https://www.npmjs.com/package/@botdojo/sdk)
- [mcp-app-view on npm](https://www.npmjs.com/package/mcp-app-view)

## License

MIT © [BotDojo](https://botdojo.com)
