# slide-system Documentation

**App:** slide-system
**Framework:** Motia (Event-Driven Backend)
**Database:** Supabase (PostgreSQL)
**Purpose:** AI-powered slide generation and presentation bot management

---

## Quick Start

```bash
# Start development server
cd apps/slide-system
export DAILY_PIPECAT_API_KEY=xxx
export SUPABASE_URL=https://...
export SUPABASE_SERVICE_KEY=yyy
pnpx motia dev --port 3002
```

**Server will be available at:** http://localhost:3002

---

## Documentation Index

### Architecture & Design

| Document | Purpose | When to Read |
|----------|---------|--------------|
| **[MOTIA_SUPABASE_ARCHITECTURE.md](./MOTIA_SUPABASE_ARCHITECTURE.md)** | **Comprehensive architecture guide** for Motia + Supabase. Required reading for anyone working on slide-system. | **First priority** - Read before writing any code |
| **[ARCHITECTURE_REFACTOR.md](./ARCHITECTURE_REFACTOR.md)** | Historical document explaining the migration from singleton-based to event-driven architecture. | Background/context on why we use Supabase |

### Reference Material

| Document | Purpose |
|----------|---------|
| **[_TEMPLATE_MOTIA_ARCHITECTURE.md](../../.claude/prds/_TEMPLATE_MOTIA_ARCHITECTURE.md)** | PRD template with Motia architecture guidelines. Copy into new PRDs. |
| **[pipecat-based-screenshare-bot.md](../../.claude/prds/pipecat-based-screenshare-bot.md)** | Full PRD for the Pipecat screenshare bot (updated with Motia architecture) |

---

## Critical Architecture Rules

### 1. **No Singletons or In-Memory State**

```typescript
// ❌ WRONG - State lost on module reload
class BotManager {
  private bots: Map<string, Bot> = new Map();
}
export const botManager = new BotManager();

// ✅ CORRECT - Query external state
export async function getBots() {
  const supabase = createSupabaseClient();
  return supabase.from('active_bots').select();
}
```

**Why?** Motia dynamically reloads modules on each request → in-memory state is lost.

### 2. **All State Lives in Supabase**

```typescript
// Store bot metadata
await supabase.from('active_bots').insert({
  bot_id,
  pid: botProcess.pid,
  session_id,
  status: 'spawning'
});

// Query bot state
const { data: bot } = await supabase
  .from('active_bots')
  .select('*')
  .eq('bot_id', botId)
  .single();
```

### 3. **Spawn Detached Processes**

```typescript
const botProcess = spawn(pythonCmd, args, {
  detached: true,  // Survives parent termination
  stdio: ['ignore', 'pipe', 'pipe']
});

botProcess.unref();  // Detach from event loop
```

### 4. **Use OS-Level Process Control**

```typescript
// Check if alive (signal 0 doesn't kill)
function isProcessAlive(pid: number): boolean {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

// Graceful kill
process.kill(pid, 'SIGTERM');
setTimeout(() => process.kill(pid, 'SIGKILL'), 10000);
```

---

## Project Structure

```
apps/slide-system/
├── docs/
│   ├── README.md                              ← You are here
│   ├── MOTIA_SUPABASE_ARCHITECTURE.md        ← Primary architecture guide
│   └── ARCHITECTURE_REFACTOR.md               ← Historical context
├── steps/
│   ├── bot-spawn.step.ts                      ← POST /api/bots/screenshare/spawn
│   ├── bot-status.step.ts                     ← GET /api/bots/screenshare/status
│   ├── bot-kill.step.ts                       ← POST /api/bots/screenshare/kill
│   ├── slidev-generate.step.ts                ← Slidev deck generation
│   └── slidev-control.step.ts                 ← Slide navigation commands
├── src/
│   └── lib/
│       └── supabase.ts                        ← Shared Supabase client + helpers
├── supabase/
│   ├── .temp/                                 ← Supabase CLI cache
│   └── migrations/
│       ├── 20251012_create_active_bots.sql   ← Bot metadata table
│       └── README.md                          ← Migration instructions
├── bots/
│   └── screenshare-bot/
│       ├── bot.py                             ← Python Pipecat bot
│       ├── screenshot_capture.py              ← Stream A: Browser automation
│       ├── frame_processor.py                 ← Stream B: Image processing
│       ├── slide_navigator.py                 ← Slide control
│       ├── slide_control_listener.py          ← Supabase listener
│       └── lifecycle_manager.py               ← Bot lifecycle (Task #116)
└── .env.motia                                 ← Environment variables (gitignored)
```

---

## API Endpoints

### Health & Monitoring

| Endpoint | Method | Purpose | Step File |
|----------|--------|---------|-----------|
| `/api/health` | GET | Production health check | `steps/health.step.ts` |

### Bot Management

| Endpoint | Method | Purpose | Step File |
|----------|--------|---------|-----------|
| `/api/bots/screenshare/spawn` | POST | Spawn new bot | `steps/bot-spawn.step.ts` |
| `/api/bots/screenshare/status` | GET | Get all bots | `steps/bot-status.step.ts` |
| `/api/bots/screenshare/status/:bot_id` | GET | Get specific bot | `steps/bot-status.step.ts` |
| `/api/bots/screenshare/kill/:bot_id` | POST | Kill bot | `steps/bot-kill.step.ts` |

### Slidev Integration

| Endpoint | Method | Purpose | Step File |
|----------|--------|---------|-----------|
| `/api/slidev/generate` | POST | Generate Slidev deck | `steps/slidev-generate.step.ts` |
| `/api/slidev/control` | POST | Send slide navigation command | `steps/slidev-control.step.ts` |

---

## Database Schema

### Table: `active_bots`

| Column | Type | Description |
|--------|------|-------------|
| `bot_id` | UUID | Primary key, bot identifier |
| `pid` | INTEGER | OS process ID |
| `session_id` | UUID | Associated session (for filtering) |
| `room_url` | TEXT | Daily.co room URL |
| `deck_url` | TEXT | Slidev deck URL |
| `status` | TEXT | `spawning`, `running`, `stopping`, `stopped`, `error` |
| `spawned_at` | TIMESTAMPTZ | Bot spawn timestamp |
| `stopped_at` | TIMESTAMPTZ | Bot termination timestamp |
| `error_message` | TEXT | Error details if status='error' |
| `log_file_path` | TEXT | Path to bot log file |

**Indexes:**
- `idx_active_bots_session_id` - Fast session lookup
- `idx_active_bots_status` - Filter by status
- `idx_active_bots_pid` - Process ID lookup
- `idx_active_bots_spawned_at` - Sort by spawn time

---

## Development Workflow

### 1. **Read Architecture Guide First**

```bash
open apps/slide-system/docs/MOTIA_SUPABASE_ARCHITECTURE.md
```

### 2. **Apply Supabase Migrations**

```bash
cd apps/slide-system
supabase link --project-ref <your-project>
supabase db push
```

### 3. **Configure Environment**

```bash
# .env.motia (create if doesn't exist)
DAILY_PIPECAT_API_KEY=xxx
SUPABASE_URL=https://xxx.supabase.co
SUPABASE_SERVICE_KEY=eyJhbGc...
```

### 4. **Start Development Server**

```bash
pnpx motia dev --port 3002
```

### 5. **Test Endpoints**

```bash
# Spawn bot
curl -X POST http://localhost:3002/api/bots/screenshare/spawn \
  -H "Content-Type: application/json" \
  -d '{
    "room_url": "https://buzztrail.daily.co/test",
    "deck_url": "https://example.com/deck",
    "session_id": "550e8400-e29b-41d4-a716-446655440000"
  }'

# Check status
curl http://localhost:3002/api/bots/screenshare/status
```

---

## Common Patterns

### Creating a New Motia Step

```typescript
// steps/my-feature.step.ts
import { createSupabaseClient } from '../src/lib/supabase';

export const config = {
  name: 'MyFeature',
  type: 'api',
  path: '/api/my-feature',
  method: 'POST',
  emits: ['feature.created']
};

export const handler = async (req: any, { emit }: any) => {
  // 1. Query external state
  const supabase = createSupabaseClient();
  const { data } = await supabase.from('table').select();

  // 2. Process request
  const result = processData(req.body, data);

  // 3. Update external state
  await supabase.from('table').insert(result);

  // 4. Emit events
  await emit({ topic: 'feature.created', data: result });

  // 5. Return response
  return { status: 200, body: result };
};
```

### Spawning Long-Running Processes

```typescript
import { spawn } from 'child_process';
import { createSupabaseClient } from '../src/lib/supabase';

// Spawn detached process
const process = spawn(cmd, args, {
  detached: true,
  stdio: ['ignore', 'pipe', 'pipe'],
  cwd: workingDir
});

process.unref();

// Store PID in database
const supabase = createSupabaseClient();
await supabase.from('processes').insert({
  process_id: id,
  pid: process.pid,
  status: 'running'
});
```

---

## Troubleshooting

### "Bot spawned but status shows 0 active bots"

**Cause:** You're using in-memory state (singleton) instead of Supabase.
**Solution:** Query Supabase for bot status, not in-memory Map.

### "Process dies when Motia restarts"

**Cause:** Missing `detached: true` and `unref()`.
**Solution:** Use detached process spawning pattern (see architecture guide).

### "State lost between requests"

**Cause:** Using module-level variables or singletons.
**Solution:** Store all state in Supabase, query on every request.

### "Supabase connection error"

**Cause:** Missing environment variables.
**Solution:** Set `SUPABASE_URL` and `SUPABASE_SERVICE_KEY` in `.env.motia`.

---

## Deployment

### Railway (Production)

```bash
# Set environment variables
railway variables set DAILY_PIPECAT_API_KEY=xxx
railway variables set SUPABASE_URL=https://...
railway variables set SUPABASE_SERVICE_KEY=yyy

# Deploy
railway up
```

### Health Check Endpoint

```bash
curl https://slide-system-production-5813.up.railway.app/api/health
```

Returns:
```json
{
  "status": "healthy",
  "timestamp": "2025-10-12T12:00:00.000Z",
  "service": "slide-system",
  "version": "1.0.0",
  "checks": {
    "database": {
      "status": "up",
      "error": null
    },
    "api": {
      "status": "up",
      "response_time_ms": 50
    }
  },
  "uptime_seconds": 1234
}
```

**For detailed deployment procedures**, see [PRODUCTION_DEPLOYMENT_RUNBOOK.md](./PRODUCTION_DEPLOYMENT_RUNBOOK.md)

---

## Resources

### Official Documentation

- **Motia**: https://www.motia.dev/docs
- **Motia Manifesto**: https://www.motia.dev/manifesto
- **Supabase**: https://supabase.com/docs
- **Pipecat**: https://docs.pipecat.ai/

### Internal Documentation

- **Architecture Guide**: [MOTIA_SUPABASE_ARCHITECTURE.md](./MOTIA_SUPABASE_ARCHITECTURE.md)
- **PRD Template**: [_TEMPLATE_MOTIA_ARCHITECTURE.md](../../.claude/prds/_TEMPLATE_MOTIA_ARCHITECTURE.md)
- **Bot PRD**: [pipecat-based-screenshare-bot.md](../../.claude/prds/pipecat-based-screenshare-bot.md)

---

## Getting Help

1. **Read the architecture guide first**: Most questions answered there
2. **Check troubleshooting section**: Common issues documented
3. **Review existing steps**: See `steps/*.step.ts` for patterns
4. **Check PRD template**: Architecture guidelines and patterns

---

## Contributing

When adding new features to slide-system:

1. ✅ Read [MOTIA_SUPABASE_ARCHITECTURE.md](./MOTIA_SUPABASE_ARCHITECTURE.md)
2. ✅ Follow stateless, event-driven patterns
3. ✅ Store state in Supabase, not memory
4. ✅ Use detached processes for long-running tasks
5. ✅ Emit events for cross-step communication
6. ✅ Update documentation for significant changes

---

**Last Updated:** October 12, 2025
**Version:** 2.0 (Event-Driven + Supabase Architecture)
