---
name: Update Slide-System Integration
status: in_progress
created: 2025-10-20T15:30:53Z
updated: 2025-10-22T08:19:54Z
github: https://github.com/BuzzTrail/video-extension/issues/160
depends_on: [156]
parallel: false
conflicts_with: [004]
---

# Task: Update Slide-System Integration

## Description

Modify `slide-system` Motia steps to call bot-spawner HTTP API instead of directly spawning Python processes. This completes the service separation.

**Changes:**
1. Replace `spawn()` calls with `fetch()` to bot-spawner
2. Add error handling for HTTP failures
3. Add retry logic with exponential backoff
4. Add request/response logging
5. Update environment variables
6. Test end-to-end locally
7. Deploy to Railway staging

**Goal:** Zero breaking changes to external API contracts. Voice-demo-ui and other clients see no difference.

## Acceptance Criteria

- [ ] `bot-spawn-livekit.step.ts` modified to use HTTP client
- [ ] HTTP calls to `http://bot-spawner.railway.internal:3001/api/bots/screenshare/spawn-livekit`
- [ ] Error handling for bot-spawner unavailable (503 Service Unavailable)
- [ ] Retry logic with exponential backoff (3 attempts)
- [ ] Request/response logging for debugging
- [ ] Environment variable `BOT_SPAWNER_URL` added to slide-system
- [ ] End-to-end test: Voice demo session creates bot successfully
- [ ] Deployed to Railway staging
- [ ] Zero regressions in existing API endpoints

## Technical Details

### Implementation Approach

**1. Modify `bot-spawn-livekit.step.ts`:**

```typescript
// BEFORE (direct spawn)
const botProcess = spawn(pythonCmd, args, {
  env: { ...process.env },
  cwd: '/app/bots/screenshare-bot',
  stdio: ['ignore', 'pipe', 'pipe'],
  detached: true,
});
botProcess.unref();
const pid = botProcess.pid!;

// AFTER (HTTP call to bot-spawner)
const BOT_SPAWNER_URL = process.env.BOT_SPAWNER_URL ||
  'http://bot-spawner.railway.internal:3001';

const spawnBotViaHttp = async (payload: {
  room_name: string;
  deck_url: string;
  session_id: string;
  screenshare_token: string;
}) => {
  const maxRetries = 3;
  let lastError: Error | null = null;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      console.log(`[BOT_SPAWNER] Attempt ${attempt}/${maxRetries}:`, payload);

      const response = await fetch(
        `${BOT_SPAWNER_URL}/api/bots/screenshare/spawn-livekit`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
          signal: AbortSignal.timeout(10000), // 10s timeout
        }
      );

      if (!response.ok) {
        throw new Error(`Bot-spawner returned ${response.status}: ${await response.text()}`);
      }

      const result = await response.json();
      console.log(`[BOT_SPAWNER] Success:`, result);
      return result; // { bot_id, pid, status, log_file }

    } catch (error) {
      lastError = error as Error;
      console.error(`[BOT_SPAWNER] Attempt ${attempt} failed:`, error);

      if (attempt < maxRetries) {
        const backoffMs = Math.pow(2, attempt) * 1000; // 2s, 4s, 8s
        console.log(`[BOT_SPAWNER] Retrying in ${backoffMs}ms...`);
        await new Promise(resolve => setTimeout(resolve, backoffMs));
      }
    }
  }

  throw new Error(`Bot-spawner failed after ${maxRetries} attempts: ${lastError?.message}`);
};

// Use in Motia step handler
export const handler = async (req: any, { emit }: any) => {
  const { room_name, deck_url, session_id, screenshare_token } = req.body;

  const result = await spawnBotViaHttp({
    room_name,
    deck_url,
    session_id,
    screenshare_token,
  });

  const { bot_id, pid } = result;

  // Continue with same logic (database insert, event emission, etc.)
  // ...existing code...
};
```

**2. Update Environment Variables (Railway):**
```bash
# slide-system service
BOT_SPAWNER_URL=http://bot-spawner.railway.internal:3001

# Eventually remove (after cutover):
# LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET (moved to bot-spawner)
```

**3. Error Handling Strategy:**
- **503 Service Unavailable:** Bot-spawner is down → return 503 to client
- **Timeout (10s):** Network issue → retry with backoff
- **400 Bad Request:** Invalid payload → return 400 to client (don't retry)
- **500 Internal Error:** Bot-spawner bug → retry with backoff

### Key Considerations

- **Backward Compatibility:** External API contracts unchanged
- **Minimal Changes:** Only modify bot spawning code, nothing else
- **Observability:** Log HTTP calls for debugging
- **Graceful Degradation:** Clear error messages if bot-spawner fails
- **Rollback Ready:** Can revert to direct spawn easily

### Files Affected

**Modified files:**
- `apps/slide-system/steps/bot-spawn-livekit.step.ts`
- `apps/slide-system/steps/tool-forwarder-spawn.step.ts` (similar changes)

**Environment:**
- Railway `slide-system` service: Add `BOT_SPAWNER_URL` variable

## Dependencies

**Depends On:**
- [ ] Task 004: Bot-spawner spawn endpoints working

**Conflicts With:**
- Task 004 (both modify bot spawning flow, must be sequential)

**External:**
- [ ] Railway internal networking working (validated in Task 001)
- [ ] Bot-spawner service deployed and accessible

## Effort Estimate

- **Size:** M (Medium)
- **Hours:** 6-8 hours
  - Modify bot-spawn-livekit.step.ts: 2 hours
  - Implement retry logic: 1 hour
  - Add error handling: 1 hour
  - Update environment variables: 0.5 hours
  - Local testing: 1-2 hours
  - Deploy to staging: 1 hour
  - End-to-end validation: 1-2 hours
- **Parallel:** false (blocks Task 006)

## Definition of Done

- [ ] HTTP client implemented with retry logic
- [ ] Error handling covers all failure modes
- [ ] Logging shows request/response details
- [ ] Local testing: Voice demo session works end-to-end
- [ ] Staging deployment: Bot spawns successfully via bot-spawner
- [ ] No regressions in existing API endpoints
- [ ] Rollback tested: Can revert to direct spawn if needed
- [ ] Documentation updated

**Validation:**
```bash
# Test end-to-end from voice-demo-ui
curl -X POST http://localhost:3000/api/sessions/voice-demo \
  -H "Content-Type: application/json" \
  -d '{"customerName":"Test User"}'

# Expected:
# 1. slide-system calls bot-spawner via HTTP
# 2. bot-spawner spawns bot
# 3. Bot joins LiveKit room
# 4. Session created successfully

# Check logs
railway logs --service slide-system | grep BOT_SPAWNER
railway logs --service bot-spawner | grep "Bot spawned"
```

**Success Criteria:**
- Voice demo sessions work identically to before
- Bot-spawner logs show spawn requests
- Service-to-service latency <50ms
- Zero breaking changes to external clients
