# Chat Feature Development Workflow

This document describes the development workflow for the Chat feature in the super-repo, including how to reference Android source code and pull UI components from the swift-vibes reference project.

## Super-Repo Structure

This repository is a **monorepo** containing multiple projects:

```
vibes1/
├── app-android/          # Android source code (Kotlin)
├── app-ios/              # iOS source code (Swift)
└── swift-vibes/          # Reference UI implementation (SwiftUI)
```

The Chat feature is located at:
- **iOS**: `app-ios/Sources/FeatureCreateClip/Chat/`
- **Android**: `app-android/app/src/main/java/com/suno/android/ui/screens/orpheus/`
- **Reference UI**: `swift-vibes/vibes/Views/ChatView.swift` and related components

---

## Working with the Chat Feature

### Target Location

The Chat feature lives in:
```
app-ios/Sources/FeatureCreateClip/Chat/
├── Chat.swift                    # Main TCA reducer and view
├── Components/                  # SwiftUI views
│   ├── ChatsView.swift          # Message list
│   ├── ChatBar.swift            # Input bar
│   ├── CustomChatView.swift     # Expanded chat view
│   └── ...
├── OrpheusClient/               # Business logic layer
│   ├── Services/                # Repository, connection management
│   ├── Handlers/                # Event handlers
│   └── Models/                  # Domain models
├── ARCHITECTURE.md              # Technical architecture docs
├── MODEL_AND_WORKSPACE.md       # Model/workspace handling
├── STREAMING_TEXT.md            # Streaming text behavior
└── WORKSPACE_AND_MODEL.md       # Additional workspace docs
```

### Key Architecture Patterns

1. **TCA (The Composable Architecture)**: State management via `Chat` reducer
2. **Repository Pattern**: `OrpheusChatRepository` handles all backend communication
3. **Event-Driven**: Real-time events processed through handler chain
4. **Actor Isolation**: Thread-safe state management via Swift actors

See `ARCHITECTURE.md` for detailed technical documentation.

---

## Android SHA-Based Workflow

When migrating features from Android, we use **commit SHAs** to reference specific Android implementations. This ensures we're working with the exact version of code that matches the desired behavior.

### How to Reference Android Commits

#### 1. Find the Relevant Android Commit

Navigate to the Android codebase and identify the commit that contains the feature you want to migrate:

```bash
cd app-android
git log --oneline --grep="orpheus" --grep="chat" -i
# Or search for specific files
git log --oneline --all -- "**/OrpheusChat*.kt"
```

#### 2. View the Commit

Use `git show` to examine the commit:

```bash
cd app-android
git show <SHA>
# Example:
git show 3b683012c468014f285350a1af6c88ff739ee5e2
```

#### 3. Reference in iOS Code

When implementing the iOS equivalent, reference the Android commit in comments:

```swift
// Migrated from Android commit 3b683012c468014f285350a1af6c88ff739ee5e2
// See: app-android/common-data/src/main/java/com/suno/android/common_data/repos/orpheus/OrpheusChatRepository.kt
public func sendMessage(content: String) async throws {
    // Implementation matches Android's sendMessage() behavior
}
```

#### 4. Document Migration in Commit Messages

When committing iOS changes, reference the Android commit:

```
Migrate OrpheusChatRepository from Android

- Implements sendMessage, startNewSession, registerModelChange
- Matches Android commit: 3b683012c468014f285350a1af6c88ff739ee5e2
- See: app-android/common-data/src/main/java/com/suno/android/common_data/repos/orpheus/
```

### Example Workflow: Migrating a Feature

1. **Identify Android Source**:
   ```bash
   cd app-android
   git log --oneline --all -- "**/OrpheusChatVM.kt"
   # Find: aa383a4a68ec514dbdd898b913c0c22084ccf9d
   ```

2. **Examine the Implementation**:
   ```bash
   git show aa383a4a68ec514dbdd898b913c0c22084ccf9d
   ```

3. **Read the Android Code**:
   ```bash
   git show aa383a4a68ec514dbdd898b913c0c22084ccf9d:app/src/main/java/com/suno/android/ui/screens/orpheus/OrpheusChatVM.kt
   ```

4. **Implement iOS Equivalent**:
   - Convert Kotlin to Swift
   - Adapt Android patterns (Flow → AsyncStream, Coroutines → async/await)
   - Match behavior exactly

5. **Document the Migration**:
   - Add comments referencing the Android commit
   - Update relevant `.md` files if behavior differs

### Key Android Files for Chat Feature

| Android Path | Purpose | iOS Equivalent |
|-------------|---------|----------------|
| `app/src/main/java/com/suno/android/ui/screens/orpheus/OrpheusChatVM.kt` | ViewModel/State management | `Chat.swift` (TCA reducer) |
| `common-data/src/main/java/com/suno/android/common_data/repos/orpheus/OrpheusChatRepository.kt` | Repository/Business logic | `OrpheusChatRepository.swift` |
| `common-data/src/main/java/com/suno/android/common_data/repos/orpheus/handlers/` | Event handlers | `OrpheusClient/Handlers/` |
| `common-networking/src/main/java/com/suno/android/common_networking/remote/orpheus/` | Network models | `OrpheusNetworkModels.swift` |
| `app/src/main/java/com/suno/android/ui/screens/orpheus/components/` | UI components | `Components/` |

### Language Conversion Patterns

| Android (Kotlin) | iOS (Swift) |
|------------------|-------------|
| `Flow<T>` | `AsyncStream<T>` |
| `suspend fun` | `async func` |
| `data class` | `struct` |
| `sealed class` | `enum` with associated values |
| `ImmutableList` | `Array` or `IdentifiedArrayOf` |
| `Id<T>` (value class) | `String` (type-safe IDs handled via naming) |
| `withContext(Dispatchers.IO)` | `Task` or `async` context |
| `launchIn(viewModelScope)` | `.task` or `.run` effect in TCA |

---

## Pulling UI from swift-vibes

The `swift-vibes` directory contains a **reference implementation** of the Chat UI. When implementing or updating UI components, reference this project to match the design.

### How to Reference swift-vibes

#### 1. Locate the Component

Find the relevant component in swift-vibes:

```bash
cd swift-vibes
find . -name "*Chat*.swift" -o -name "*Song*.swift"
# Example results:
# vibes/Views/ChatView.swift
# vibes/Components/Players/InlineChatPlayer.swift
# vibes/Components/Messages/SongGenerationMessage.swift
```

#### 2. Examine the Reference Implementation

Read the swift-vibes file to understand the UI structure:

```bash
cat swift-vibes/vibes/Views/ChatView.swift
# Or open in your editor
```

#### 3. Adapt to iOS App Structure

When copying/adapting components:

1. **Match the Visual Design**: Copy layout, spacing, colors, typography
2. **Adapt to TCA**: Convert `@State` to TCA state management
3. **Use App Dependencies**: Replace reference dependencies with app dependencies
4. **Maintain Functionality**: Keep all interactive behaviors

#### 4. Example: Migrating a Component

**Reference (swift-vibes)**:
```swift
// swift-vibes/vibes/Components/Players/InlineChatPlayer.swift
struct InlineChatPlayer: View {
    let songTitle: String
    let isPlaying: Bool
    // ...
}
```

**iOS App Implementation**:
```swift
// app-ios/Sources/FeatureCreateClip/Chat/Components/ChatsView.swift
struct SimpleSongCard: View {
    let song: Song
    let isPlaying: Bool
    // Adapted from swift-vibes/vibes/Components/Players/InlineChatPlayer.swift
    // - Uses TCA state management instead of @State
    // - Integrates with AudioManager.shared
    // - Matches visual design exactly
}
```

### Key swift-vibes Files for Chat UI

| swift-vibes Path | Purpose | iOS App Location |
|------------------|---------|------------------|
| `vibes/Views/ChatView.swift` | Main chat view | `Chat.swift` (ChatView) |
| `vibes/Views/ChatsView.swift` | Message list | `Components/ChatsView.swift` |
| `vibes/Components/Players/InlineChatPlayer.swift` | Song card | `Components/ChatsView.swift` (SimpleSongCard) |
| `vibes/Components/Footers/ChatBar.swift` | Input bar | `Components/ChatBar.swift` |
| `vibes/Components/Messages/SongGenerationMessage.swift` | Song display | `Components/ChatsView.swift` (SimpleSongGenerationView) |
| `vibes/Components/Effects/ArtworkShader.swift` | Album art shader | `Components/ChatsView.swift` (ArtworkShader) |
| `vibes/Components/Players/InlineChatPlayer.swift` (WaveformScrubber) | Waveform | `Components/ChatsView.swift` (WaveformScrubber) |

### UI Adaptation Guidelines

1. **Visual Fidelity**: Match spacing, colors, typography exactly
2. **Component Structure**: Keep the same view hierarchy
3. **State Management**: Convert `@State` → TCA state, `@ObservedObject` → TCA dependencies
4. **Dependencies**: Replace reference dependencies with app equivalents:
   - `AudioManager` → `AudioManager.shared` (already exists)
   - `Constants` → `ChatConstants` or `ComponentLibrary`
   - Custom components → Use Figma MCP components where available

### Example: Songs Grid View Migration

**Reference (swift-vibes)**:
```swift
// swift-vibes/vibes/Views/ChatView.swift:695
private var songsGridView: some View {
    ScrollView {
        LazyVGrid(columns: [
            GridItem(.flexible(), spacing: 16),
            GridItem(.flexible(), spacing: 16)
        ], spacing: 16) {
            ForEach(getAllGeneratedSongs(), id: \.id) { song in
                InlineChatPlayer(...)
            }
        }
        .padding(.vertical, 12)
        .padding(.horizontal, 16)
    }
}
```

**iOS App Implementation**:
```swift
// app-ios/Sources/FeatureCreateClip/Chat/Chat.swift:1198
struct SongGridView: View {
    // Adapted from swift-vibes/vibes/Views/ChatView.swift:695
    // - Uses LazyVGrid with 2 columns (matches reference)
    // - Uses SimpleSongCard (adapted from InlineChatPlayer)
    // - Same padding and spacing
    var body: some View {
        ScrollView {
            LazyVGrid(columns: [
                GridItem(.flexible(), spacing: 16),
                GridItem(.flexible(), spacing: 16)
            ], spacing: 16) {
                ForEach(allSongs) { song in
                    SimpleSongCard(...)
                }
            }
            .padding(.vertical, 12)
            .padding(.horizontal, 16)
        }
    }
}
```

---

## Development Workflow Summary

### Typical Feature Migration Flow

1. **Identify Source**:
   - Android commit SHA for business logic
   - swift-vibes file for UI components

2. **Examine Reference**:
   ```bash
   # Android
   cd app-android
   git show <SHA>
   
   # swift-vibes
   cat swift-vibes/vibes/Views/ChatView.swift
   ```

3. **Implement iOS Version**:
   - Convert Kotlin → Swift (for Android logic)
   - Adapt UI components (from swift-vibes)
   - Integrate with TCA and app dependencies

4. **Test & Verify**:
   - Match Android behavior exactly
   - Match swift-vibes visual design
   - Ensure TCA patterns are followed

5. **Document**:
   - Add comments referencing source commits/files
   - Update relevant `.md` files
   - Commit with clear message referencing sources

### Best Practices

1. **Always Reference Sources**: Include commit SHAs and file paths in comments
2. **Match Behavior First**: Ensure functional parity with Android before optimizing
3. **Match Design Exactly**: Use swift-vibes as the visual reference
4. **Document Differences**: If iOS implementation differs, explain why in comments
5. **Test Thoroughly**: Verify both behavior (vs Android) and appearance (vs swift-vibes)

### Common Commands

```bash
# View Android commit
cd app-android && git show <SHA>

# View specific file from commit
cd app-android && git show <SHA>:path/to/file.kt

# Search Android codebase
cd app-android && git grep "OrpheusChat" -- "*.kt"

# View swift-vibes component
cat swift-vibes/vibes/Views/ChatView.swift

# Search swift-vibes
cd swift-vibes && find . -name "*.swift" -exec grep -l "InlineChatPlayer" {} \;
```

---

## Additional Resources

- **Architecture**: See `ARCHITECTURE.md` for technical details
- **Model/Workspace**: See `MODEL_AND_WORKSPACE.md` for backend integration
- **Streaming Text**: See `STREAMING_TEXT.md` for SSE text handling
- **Android Docs**: `app-android/docs/architecture.md`
- **swift-vibes Guide**: `swift-vibes/swift.md` and `swift-vibes/CLAUDE.md`

---

## Questions?

If you're unsure about:
- **Android behavior**: Check the referenced commit SHA
- **UI design**: Check the swift-vibes reference file
- **Architecture**: See `ARCHITECTURE.md`
- **Implementation details**: Check existing code comments for SHA references

