# Voice Agent Creation Fix — Design Doc

**Date:** 2026-02-26
**Branch:** voiceagent
**Status:** Approved

## Problem

Voice agent creation fails 100% of the time from the dashboard `?tab=voice-agent` page.

Two confirmed bugs:

### Bug 1 — greetingMessage schema mismatch (immediate 400)

- `VoiceAgentSetupWizard.tsx` sends `greetingMessage: "Hello..."` (plain string)
- `provisionAgentSchema` expects `greetingMessage: { ar?: string, en?: string }` (object)
- Zod throws → API returns 400 "Invalid configuration provided"
- User sees generic error, no agent created

### Bug 2 — Tools registration rollback (500 on localhost / tools failure)

- After successful agent creation, `registerTools()` registers webhook URLs with ElevenLabs
- On failure (e.g. localhost URLs), the route calls `deleteAgent()` then returns 500
- A successfully created agent is destroyed; user sees "Voice agent was created but tools setup failed"

## Solution

### Option B (chosen): Schema alignment + graceful tools errors

**3 files changed:**

### 1. `VoiceAgentSetupWizard.tsx`

- Replace `greetingMessage: string` state with `greetingEn: string` + `greetingAr: string`
- Add two inputs in the greeting step: English greeting + Arabic greeting
- Send `greetingMessage: { en: greetingEn || undefined, ar: greetingAr || undefined }`
- Handle `toolsWarning: true` in response: call `onComplete()` + show note to user

### 2. `app/api/voice-agent/provision/route.ts`

- Remove `deleteAgent()` rollback on tools registration failure
- Save agent to DB regardless of tools outcome
- Add `toolsWarning: true` to 201 response if tools failed
- Log the tools error for debugging

### No schema changes needed

`provisionAgentSchema` already expects the correct `{ ar?, en? }` shape.

## Data Flow (fixed)

```
Wizard
  greetingEn = "Hello, welcome to our clinic!"
  greetingAr = "أهلاً، مرحباً بك في عيادتنا!"

POST /api/voice-agent/provision
  { greetingMessage: { en: "Hello...", ar: "أهلاً..." }, ... }

Validator → passes ✅

elevenLabsService.createConversationAgent() → ElevenLabs API → agent_id

registerTools()
  → success: agent saved with full tools
  → failure: agent saved with toolsWarning, tools can be retried

prisma.users.update({ voiceAgentId }) → DB saved ✅

→ 201 { agentId, toolsWarning? }
→ Wizard calls onComplete() → Dashboard loads ✅
```

## Error State Matrix

| Scenario | Before | After |
|---|---|---|
| greetingMessage sent as string | 400 ZodError | Never happens |
| Tools registration fails | 500 + agent deleted | 201 + toolsWarning |
| ElevenLabs API key invalid | 500 ElevenLabsServiceError | Unchanged (correct) |
| Agent already exists | 409 | Unchanged |

## Verification Plan

1. `npx tsc --noEmit` — no type errors
2. `npm run lint` on changed files
3. Browser: log in → dashboard → voice-agent tab → wizard → create → confirm success
4. ElevenLabs MCP `list_agents` — confirm new agent appears
5. GET `/api/voice-agent/provision` — confirm `voiceAgentId` saved to DB
