# Slidev System Architecture

Complete architectural documentation for the Slidev presentation generation and control system.

**Last Updated:** 2025-10-09

---

## Table of Contents

1. [System Overview](#system-overview)
2. [Component Architecture](#component-architecture)
3. [Data Flow](#data-flow)
4. [Database Schema](#database-schema)
5. [Technology Stack](#technology-stack)
6. [Deployment Architecture](#deployment-architecture)

---

## System Overview

The Slidev system enables automated generation and real-time control of presentation slides through a REST API deployed on Railway and hosted on GitHub Pages.

### Key Components

1. **Motia.dev API** (Railway) - Generation and control endpoints
2. **Supabase** - Database and Realtime messaging
3. **GitHub Pages** - Static hosting for presentations
4. **Client Browser** - Presentation rendering and Realtime subscription

### Design Principles

- **Serverless-First:** Leverage managed services (Railway, Supabase, GitHub Pages)
- **Real-time Control:** Supabase Realtime for instant slide navigation
- **Static Hosting:** GitHub Pages CDN for fast, reliable delivery
- **Simple MVP:** Start with essential features, iterate based on usage

---

## Component Architecture

```mermaid
graph TB
    subgraph "Client Layer"
        Agent[Pipecat Agent]
        Browser[Customer Browser]
    end

    subgraph "API Layer - Railway"
        API[slide-system<br/>Motia.dev App]
        GenStep[slidev-generate.step.ts]
        CtrlStep[slidev-control.step.ts]
        SessStep[demo-session-create.step.ts]
    end

    subgraph "Data Layer - Supabase"
        DB[(PostgreSQL)]
        RT[Realtime Engine]
        Tables[Tables:<br/>- conversation_sessions<br/>- slidev_decks<br/>- slide_control_commands]
    end

    subgraph "Hosting Layer"
        GH[GitHub Pages<br/>buzztrail.github.io/buzztrail-presentations/]
        CDN[GitHub CDN]
    end

    Agent -->|POST /api/slidev/generate| API
    Agent -->|POST /api/slidev/control| API
    API --> GenStep
    API --> CtrlStep
    API --> SessStep

    GenStep -->|Store metadata| DB
    GenStep -->|Publish deck| GH
    CtrlStep -->|Insert command| DB

    DB --> RT
    RT -.->|postgres_changes| Browser
    GH --> CDN
    CDN -->|Serve HTML/JS| Browser

    style API fill:#667eea
    style DB fill:#3ecf8e
    style GH fill:#f39c12
    style Browser fill:#e74c3c
```

### Component Details

#### 1. slide-system (Motia.dev App on Railway)

**Location:** `apps/slide-system/`

**Purpose:** API server providing generation and control endpoints

**Framework:** Motia.dev (serverless-style step functions)

**Endpoints:**
- `POST /api/slidev/generate` - Generate and publish presentation
- `POST /api/slidev/control` - Send navigation commands
- `POST /demo-sessions` - Create demo session

**Implementation Files:**
- `steps/slidev-generate.step.ts` - Deck generation logic
- `steps/slidev-control.step.ts` - Control command logic
- `steps/demo-session-create.step.ts` - Session creation logic

**Deployment:** Railway (production URL: `https://slide-system-production-5813.up.railway.app`)

#### 2. Supabase (Database + Realtime)

**Purpose:** Data persistence and real-time message broadcasting

**Tables:**
- `conversation_sessions` - Demo session metadata
- `slidev_decks` - Generated deck metadata
- `slide_control_commands` - Control commands (triggers Realtime)

**Realtime:** Postgres changes subscription for instant command delivery

**Connection:** REST API (no SDK in Motia.dev steps)

#### 3. GitHub Pages

**Purpose:** Static hosting for generated presentations

**Repository:** `buzztrail/buzztrail-presentations` (or similar)

**Base URL:** `https://buzztrail.github.io/buzztrail-presentations/`

**Deck URLs:** `https://buzztrail.github.io/buzztrail-presentations/{deckId}/`

**Publishing:** Automated via GitHub API (future: GitHub Actions workflow)

#### 4. Presentation Client

**Technology:** HTML + JavaScript + Supabase JS SDK

**Features:**
- Slide rendering (currently simple HTML, future: full Slidev)
- Supabase Realtime subscription
- Keyboard navigation (arrow keys, space)
- Manual controls (prev/next buttons)
- Real-time command execution

**Realtime Subscription:**
```javascript
supabase
  .channel(`deck:${deckId}`)
  .on('postgres_changes', {
    event: 'INSERT',
    schema: 'public',
    table: 'slide_control_commands',
    filter: `deck_id=eq.${deckId}`
  }, (payload) => {
    // Execute navigation command
  })
  .subscribe();
```

---

## Data Flow

### 1. Deck Generation Flow

```mermaid
sequenceDiagram
    participant Agent as Pipecat Agent
    participant API as slide-system<br/>(Railway)
    participant DB as Supabase
    participant GH as GitHub Pages

    Agent->>API: POST /api/slidev/generate<br/>{sessionId, templateId, data}
    API->>DB: Verify session exists
    DB-->>API: Session found
    API->>API: Generate deck ID<br/>Replace placeholders
    API->>DB: Store deck metadata
    API->>GH: Publish HTML (future)
    GH-->>API: Published
    API->>DB: Update session with deck URL
    API-->>Agent: {deckId, deckUrl}
    Agent->>Agent: Screenshare deckUrl<br/>to customer
```

**Step-by-Step:**

1. **Request:** Agent sends generation request with session ID and data
2. **Validation:** API verifies session exists in Supabase
3. **Generation:** API generates unique deck ID (12 chars: `xxxx-xxxx-xxxx`)
4. **Template Processing:** Replace placeholders with provided data
5. **Storage:** Store deck metadata in `slidev_decks` table
6. **Publishing:** Publish HTML to GitHub Pages (TODO: actual implementation)
7. **Response:** Return deck ID and GitHub Pages URL
8. **Display:** Agent screenshares URL to customer

**Performance Targets:**
- Validation: < 1s
- Generation: < 30s
- GitHub Pages publish: < 60s
- **Total:** < 90s

### 2. Control Command Flow

```mermaid
sequenceDiagram
    participant Agent as Pipecat Agent
    participant API as slide-system<br/>(Railway)
    participant DB as Supabase<br/>(slide_control_commands)
    participant RT as Supabase<br/>Realtime
    participant Client as Presentation<br/>(Browser)

    Agent->>API: POST /api/slidev/control<br/>{deckId, command: "next"}
    API->>API: Validate API key
    API->>DB: Verify deck exists
    DB-->>API: Deck found
    API->>DB: INSERT command
    Note over DB,RT: Postgres trigger
    DB->>RT: Broadcast INSERT event
    RT-->>Client: postgres_changes notification
    Client->>Client: Execute next()
    API-->>Agent: {success: true}
```

**Step-by-Step:**

1. **Request:** Agent sends control command with API key
2. **Authentication:** API validates `x-api-key` header
3. **Validation:** API verifies deck exists in Supabase
4. **Broadcast:** API inserts command into `slide_control_commands` table
5. **Realtime:** Supabase automatically broadcasts to subscribed clients
6. **Execution:** Client receives command and executes navigation
7. **Response:** API returns success confirmation

**Performance Targets:**
- Authentication: < 10ms
- Validation: < 100ms
- Broadcast: < 200ms
- **Total:** < 500ms (typical: ~200ms)

### 3. Session Creation Flow

```mermaid
sequenceDiagram
    participant Agent as Pipecat Agent
    participant API as slide-system<br/>(Railway)
    participant DB as Supabase

    Agent->>API: POST /demo-sessions<br/>{session_type, environment}
    API->>DB: INSERT session
    DB-->>API: session_id
    API-->>Agent: {session_id, status}
    Note over Agent: Use session_id<br/>for deck generation
```

---

## Database Schema

### conversation_sessions

Stores demo session metadata.

```sql
CREATE TABLE conversation_sessions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  session_type TEXT NOT NULL,
  status TEXT DEFAULT 'initiated',
  daily_room_url TEXT,
  daily_room_name TEXT,
  slidev_url TEXT,
  discovery_transcript JSONB,
  discovery_insights JSONB,
  presentation_transcript JSONB,
  discovery_duration_seconds INTEGER,
  presentation_duration_seconds INTEGER,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);
```

### slidev_decks

Stores generated deck metadata.

```sql
CREATE TABLE slidev_decks (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  deck_id TEXT UNIQUE NOT NULL,
  session_id UUID REFERENCES conversation_sessions(id),
  template_id TEXT NOT NULL DEFAULT 'starter',
  generation_data JSONB,
  deck_url TEXT,
  html_content TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);
```

**Indexes:**
```sql
CREATE UNIQUE INDEX idx_slidev_decks_deck_id ON slidev_decks(deck_id);
CREATE INDEX idx_slidev_decks_session_id ON slidev_decks(session_id);
```

### slide_control_commands

Stores control commands for Realtime broadcast.

```sql
CREATE TABLE slide_control_commands (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  deck_id TEXT NOT NULL,
  command TEXT NOT NULL,
  slide_id TEXT,
  timestamp TIMESTAMPTZ DEFAULT NOW()
);
```

**Indexes:**
```sql
CREATE INDEX idx_slide_control_commands_deck_id ON slide_control_commands(deck_id);
CREATE INDEX idx_slide_control_commands_timestamp ON slide_control_commands(timestamp);
```

**Realtime Configuration:**

Enable Realtime broadcasting for `slide_control_commands`:
```sql
-- Enable Realtime for table
ALTER PUBLICATION supabase_realtime ADD TABLE slide_control_commands;
```

---

## Technology Stack

### Backend

| Component | Technology | Version | Purpose |
|-----------|-----------|---------|---------|
| API Framework | Motia.dev | Latest | Serverless-style step functions |
| Runtime | Node.js | 18+ | JavaScript execution |
| Hosting | Railway | - | API deployment and hosting |
| Database | PostgreSQL (Supabase) | 15+ | Data persistence |
| Realtime | Supabase Realtime | Latest | WebSocket broadcasting |

### Frontend

| Component | Technology | Purpose |
|-----------|-----------|---------|
| HTML/CSS/JS | Vanilla | Presentation rendering |
| Supabase JS | @supabase/supabase-js | Realtime subscription |
| Hosting | GitHub Pages | Static site hosting |

### Infrastructure

| Service | Provider | Purpose |
|---------|----------|---------|
| API Hosting | Railway | Production API |
| Database | Supabase | PostgreSQL + Realtime |
| Static Hosting | GitHub Pages | Presentation delivery |
| CDN | GitHub CDN | Fast global delivery |

### Development Tools

| Tool | Purpose |
|------|---------|
| TypeScript | Type-safe development |
| pnpm | Package management |
| Playwright | E2E testing |
| Custom scripts | Performance testing |

---

## Deployment Architecture

### Production Environment

```mermaid
graph LR
    subgraph "Railway"
        API[slide-system<br/>Node.js App]
        ENV[Environment Variables:<br/>- SUPABASE_URL<br/>- SUPABASE_SERVICE_KEY<br/>- SLIDEV_API_KEY]
    end

    subgraph "Supabase Cloud"
        DB[(PostgreSQL)]
        RT[Realtime Engine]
    end

    subgraph "GitHub"
        Repo[buzztrail-presentations Repository]
        Pages[GitHub Pages<br/>CDN]
    end

    subgraph "Global"
        Users[Customer Browsers]
    end

    API -->|REST API| DB
    DB --> RT
    API -->|GitHub API| Repo
    Repo --> Pages
    RT -.->|WebSocket| Users
    Pages -->|HTTPS| Users

    style API fill:#667eea
    style DB fill:#3ecf8e
    style Pages fill:#f39c12
    style Users fill:#e74c3c
```

### Deployment Details

**Railway Configuration:**
- **Root Directory:** `apps/slide-system/`
- **Build Command:** Auto-detected (Motia.dev)
- **Start Command:** Auto-detected (Motia.dev)
- **Port:** Auto-assigned by Railway
- **Domain:** `https://slide-system-production-5813.up.railway.app`

**Environment Variables:**
```bash
SUPABASE_URL=https://dwdytxxqcvlrmyemonxz.supabase.co
SUPABASE_SERVICE_KEY=<configured>
SLIDEV_API_KEY=<configured>
GITHUB_TOKEN=<future>
```

**Supabase Configuration:**
- **Region:** Closest to Railway deployment
- **Plan:** Pro (for Realtime and higher limits)
- **Realtime:** Enabled on `slide_control_commands` table

**GitHub Pages:**
- **Repository:** Public (for free GitHub Pages)
- **Branch:** `main` or `gh-pages`
- **HTTPS:** Enabled (automatic)
- **Custom Domain:** Optional future enhancement

### Scaling Considerations

**Current Capacity:**
- **API:** Railway auto-scales based on traffic
- **Database:** Supabase managed scaling
- **GitHub Pages:** CDN handles high traffic
- **Realtime:** Supabase handles 1000+ concurrent connections

**Bottlenecks:**
- Deck generation: Limited by build time (~15-30s per deck)
- GitHub API rate limits: 5000 requests/hour (authenticated)
- Supabase connections: Limited by plan (Pro: 1000 connections)

**Optimization Strategies:**
- Pre-build common templates
- Implement caching for template processing
- Use GitHub Actions for background publishing
- Monitor and optimize Supabase query performance

---

## Security

### API Security

**Authentication:**
- Generation endpoint: Session-based (implicit)
- Control endpoint: API key via `x-api-key` header

**Transport Security:**
- All requests over HTTPS
- Railway enforces TLS 1.2+

**Input Validation:**
- Request payload validation in all endpoints
- SQL injection protection via Supabase REST API

### Database Security

**Supabase Configuration:**
- Service key stored in Railway environment (not in code)
- RLS policies on tables (future enhancement)
- Network restricted to Railway IP (future enhancement)

### GitHub Security

**GitHub Token:**
- Personal access token with minimal permissions
- Only `public_repo` scope needed
- Rotate token periodically

---

## Monitoring

See `docs/operations/monitoring.md` for complete monitoring setup.

**Key Metrics:**
- API response times
- Deck generation duration
- Control command latency
- GitHub API rate limit usage
- Supabase connection pool
- Error rates

---

## Future Enhancements

### Short-term (1-3 months)

1. **Full Slidev Integration**
   - Replace simple HTML with actual Slidev builds
   - Support multiple templates
   - Advanced theming and customization

2. **GitHub Actions Publishing**
   - Automated CI/CD for deck publishing
   - Faster publish times
   - Better error handling

3. **Caching Layer**
   - Redis for template caching
   - CDN caching headers
   - Database query caching

### Long-term (3-6 months)

1. **Multi-template Support**
   - Library of professional templates
   - Template marketplace
   - Custom template builder

2. **Advanced Control Features**
   - Drawing/annotation tools
   - Slide notes and speaker view
   - Multi-user control

3. **Analytics and Insights**
   - Viewer tracking
   - Engagement metrics
   - Deck performance analytics

---

## References

- **API Documentation:** `docs/api/slidev-api.md`
- **Deployment Guide:** `docs/deployment/railway-deployment.md`
- **Setup Guide:** `.claude/docs/phase0-setup-guide.md`
- **Debugging Guide:** `.claude/docs/phase0-debugging-guide.md`

---

**Last Updated:** 2025-10-09
**Status:** Production - Deployed on Railway
