# Setup Guide: Orphy Assistant & Song Generation

Quick guide to get the Orphy assistant up and running.

## Prerequisites

- Suno API access (base URL and session token)
- OpenAI API key
- Convex account and project set up

## Installation Steps

### 1. Install Dependencies

```bash
npm install
# or
pnpm install
# or
yarn install
```

This will install:
- `openai` (^4.77.3) - OpenAI SDK
- `lucide-react` (^0.468.0) - Icons
- All other existing dependencies

### 2. Configure Environment Variables

Set these in your **Convex Dashboard** (https://dashboard.convex.dev):

```
SUNO_BASE_URL=https://studio-api.suno.ai
SUNO_SESSION_TOKEN=<your-suno-session-token>
OPENAI_KEY=<your-openai-api-key>
```

**Where to find them:**
1. Go to https://dashboard.convex.dev
2. Select your project
3. Navigate to "Settings" → "Environment Variables"
4. Add each variable with its value

**Note**: For local development, you can also create `.env.local` in the project root with `OPENAI_KEY`, but Suno credentials should be in Convex dashboard for security.

### 3. Deploy Schema Changes

The schema includes new tables and fields. Deploy them:

```bash
npx convex dev
```

This will:
- Push the new `atoms` table to your database
- Add `isAssistantMessage`, `atomReferences`, `assistantStatus` to messages table
- Set up all required indexes

### 4. Verify Deployment

Check that the schema is deployed:

```bash
npx convex dashboard
```

Look for:
- `atoms` table in the data browser
- New fields in `messages` table

## Testing the Implementation

### Basic Test Flow

1. **Start the development server:**
   ```bash
   npm run dev
   ```

2. **Navigate to a space** in your browser (e.g., `http://localhost:3000/space/<space-id>`)

3. **Send a message with @suno mention:**
   ```
   @suno create a happy birthday song
   ```

4. **Observe the double loading states:**
   - **State 1** (~1-3 seconds): "Orphy is thinking..." spinner
   - **State 2** (~30-90 seconds): Two song rows appear with generation progress

5. **Watch the songs generate in real-time:**
   - Status updates every 2 seconds
   - Progress bar fills as generation continues
   - Album art appears when songs complete
   - Play buttons become enabled

### Example Prompts to Test

Try these different prompt styles:

1. **Simple prompt:**
   ```
   @suno create a chill lofi beat
   ```

2. **With genre specification:**
   ```
   @suno make a happy upbeat pop song
   ```

3. **Instrumental request:**
   ```
   @suno create an instrumental jazz piano piece
   ```

4. **With lyrics:**
   ```
   @suno make a song with these lyrics: "Happy birthday to you..."
   ```

### What to Expect

**Successful Flow:**
1. Your message appears in chat
2. Orphy's thinking indicator shows for 1-3 seconds
3. Orphy responds: "🎵 Creating 2 songs: '[your prompt]'. I'll let you know when they're ready!"
4. Two song rows appear below with "Generating..." state
5. Status updates: Queued → Generating → Finalizing
6. Progress bars fill up (0% → 25% → 50% → 75% → 100%)
7. Album art appears, song metadata populates
8. Play buttons become enabled (playback TODO)

**If Something Goes Wrong:**
- Check browser console for errors
- Check Convex dashboard logs
- Verify environment variables are set correctly
- Ensure Suno API credentials are valid

## Troubleshooting

### "Orphy is thinking..." never completes

**Possible causes:**
- OpenAI API key is missing or invalid
- Network connectivity issues

**Fix:**
1. Check Convex logs: `npx convex dashboard` → "Logs"
2. Verify `OPENAI_KEY` is set in Convex dashboard
3. Check OpenAI API quota/billing

### Songs stuck in "Generating..." state

**Possible causes:**
- Suno API credentials invalid
- Suno API rate limiting
- Network issues

**Fix:**
1. Check Convex logs for Suno API errors
2. Verify `SUNO_BASE_URL` and `SUNO_SESSION_TOKEN`
3. Check Suno API status
4. Wait a few minutes (rate limiting)

### "Orphy" shows as regular user

**This is expected!** The current implementation uses the first user in the system as Orphy. Future improvement: create a dedicated system user.

### TypeError: Cannot read properties of null

**Possible cause:** Schema not deployed

**Fix:**
```bash
npx convex dev
```

Wait for schema to fully deploy, then refresh your browser.

### Import errors for 'openai' or 'lucide-react'

**Possible cause:** Dependencies not installed

**Fix:**
```bash
npm install
```

## Architecture Quick Reference

### Key Files

**Backend:**
- `convex/schema.ts` - Database schema (atoms + message extensions)
- `convex/atoms.ts` - Atom CRUD and song generation
- `convex/assistant.ts` - OpenAI integration and message handling
- `convex/messages.ts` - Message mutations (updated for @suno detection)
- `lib/sunoClient.ts` - Suno API client

**Frontend:**
- `components/SongAtomRow.tsx` - Song display component
- `app/space/[id]/page.tsx` - Space page (updated for atom rendering)

### Data Flow

```
User types "@suno create a song"
    ↓
messages.send mutation
    ↓
Detects @suno mention → schedules assistant.handleMessage
    ↓
[LOADING STATE 1: "Orphy is thinking..."]
    ↓
assistant.classifyIntent (OpenAI) → extracts prompt/tags
    ↓
atoms.generateSong → calls Suno API → returns 2 song IDs
    ↓
Creates 2 atom records with status='pending'
    ↓
assistant.createAssistantMessage → creates Orphy's response
    ↓
Attaches atom IDs to message
    ↓
[LOADING STATE 2: Song rows with spinners]
    ↓
atoms.pollSongStatus (every 2s) → checks Suno API
    ↓
Updates atoms with latest metadata/status
    ↓
UI automatically re-renders (Convex subscriptions)
    ↓
Songs complete → album art + play buttons appear
```

## Next Steps

After basic testing works:

1. **Implement audio playback** (play button currently disabled)
2. **Create dedicated system user** for Orphy
3. **Add queue management** (add songs to room queue)
4. **Extend assistant capabilities** (DJ, suggestions, Q&A)
5. **Add remix/sampling** using stored `sunoClipId`
6. **Mobile optimization** for SongAtomRow component

## Support

If you encounter issues:

1. Check Convex logs: https://dashboard.convex.dev
2. Check browser console
3. Review implementation summary: `IMPLEMENTATION_SUMMARY.md`
4. Check plans: `plans/004_atoms_system.md`, `plans/005_assistant_song_generation.md`

---

Happy song generating! 🎵
