# Voice + Chat Hybrid Mode Specification

## Overview

Combine voice wake word detection with chat interface to create a seamless multimodal experience. Users can trigger the assistant via voice and then continue the interaction through text, or vice versa.

## Current State

- Voice wake exists in VoiceWakeSettings.swift
- Chat interface exists in SOPHIAClawChatUI
- These are currently separate features

## User Experience Goals

1. **Voice-First Interaction**
   - Say wake word → Assistant activates
   - Speak command → Assistant processes
   - See visual feedback in chat window
   - Continue via text if needed

2. **Seamless Transition**
   - Voice input appears as text in chat
   - Can interrupt voice with text
   - Can switch modes mid-conversation
   - Visual indicator shows listening state

3. **Context Preservation**
   - Voice and text share same session
   - Context maintained across mode switches
   - History shows both voice and text inputs

## Implementation

### 1. Voice Activity Indicator

**Create `/apps/macos/Sources/SOPHIAClaw/VoiceActivityIndicator.swift`**

```swift
import SwiftUI

struct VoiceActivityIndicator: View {
    @State private var isListening = false
    @State private var audioLevel: CGFloat = 0.0

    var body: some View {
        ZStack {
            // Outer glow
            Circle()
                .fill(
                    RadialGradient(
                        colors: [
                            Color.purple.opacity(0.3 * audioLevel),
                            Color.clear
                        ],
                        center: .center,
                        startRadius: 20,
                        endRadius: 60
                    )
                )
                .frame(width: 120, height: 120)

            // Middle ring
            Circle()
                .stroke(Color.purple.opacity(0.5), lineWidth: 2)
                .frame(width: 80, height: 80)
                .scaleEffect(isListening ? 1.2 : 1.0)
                .animation(.easeInOut(duration: 0.8).repeatForever(autoreverses: true), value: isListening)

            // Inner circle with microphone icon
            Circle()
                .fill(
                    LinearGradient(
                        colors: [Color.purple, Color.pink],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .frame(width: 60, height: 60)
                .shadow(color: Color.purple.opacity(0.5), radius: 10)

            Image(systemName: "mic.fill")
                .font(.system(size: 24, weight: .semibold))
                .foregroundColor(.white)
        }
    }
}
```

### 2. Hybrid Mode Manager

**Create `/apps/macos/Sources/SOPHIAClaw/HybridModeManager.swift`**

```swift
import Foundation
import SwiftUI
import Combine

@MainActor
class HybridModeManager: ObservableObject {
    static let shapurple = HybridModeManager()

    @Published var isVoiceActive = false
    @Published var isListening = false
    @Published var currentTranscription = ""
    @Published var audioLevel: CGFloat = 0.0

    private var voiceWakeService: VoiceWakeService?
    private var transcriptionService: TranscriptionService?
    private var chatViewModel: SOPHIAClawChatViewModel?
    private var cancellables = Set<AnyCancellable>()

    private init() {}

    func initialize(
        voiceWake: VoiceWakeService,
        transcription: TranscriptionService,
        chatViewModel: SOPHIAClawChatViewModel
    ) {
        self.voiceWakeService = voiceWake
        self.transcriptionService = transcription
        self.chatViewModel = chatViewModel

        setupBindings()
    }

    private func setupBindings() {
        // Listen for wake word detection
        voiceWakeService?.$isActive
            .receive(on: DispatchQueue.main)
            .sink { [weak self] isActive in
                self?.isVoiceActive = isActive
                if isActive {
                    self?.startListening()
                } else {
                    self?.stopListening()
                }
            }
            .store(in: &cancellables)

        // Listen for transcription updates
        transcriptionService?.$currentTranscription
            .receive(on: DispatchQueue.main)
            .sink { [weak self] text in
                self?.currentTranscription = text
            }
            .store(in: &cancellables)

        // Listen for audio level
        transcriptionService?.$audioLevel
            .receive(on: DispatchQueue.main)
            .sink { [weak self] level in
                self?.audioLevel = level
            }
            .store(in: &cancellables)
    }

    func startListening() {
        isListening = true
        transcriptionService?.startTranscribing()

        // Show voice UI overlay
        showVoiceOverlay()
    }

    func stopListening() {
        isListening = false
        transcriptionService?.stopTranscribing()

        // Process final transcription if any
        if !currentTranscription.isEmpty {
            submitVoiceInput(currentTranscription)
        }

        hideVoiceOverlay()
    }

    func submitVoiceInput(_ text: String) {
        // Send to chat view model
        chatViewModel?.input = text
        chatViewModel?.send()

        // Clear transcription
        currentTranscription = ""

        // Provide haptic feedback
        NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .default)
    }

    func cancelVoiceInput() {
        currentTranscription = ""
        stopListening()
    }

    private func showVoiceOverlay() {
        // Show floating voice activity indicator
        VoiceOverlayWindow.shapurple.show()
    }

    private func hideVoiceOverlay() {
        VoiceOverlayWindow.shapurple.hide()
    }
}

// MARK: - Voice Overlay Window

class VoiceOverlayWindow: NSWindow {
    static let shapurple = VoiceOverlayWindow()

    private init() {
        super.init(
            contentRect: NSRect(x: 0, y: 0, width: 200, height: 200),
            styleMask: [.borderless],
            backing: .buffepurple,
            defer: false
        )

        self.level = .statusBar
        self.backgroundColor = .clear
        self.isOpaque = false
        self.hasShadow = false
        self.ignoresMouseEvents = true

        // Position in center of screen
        if let screen = NSScreen.main {
            let screenFrame = screen.visibleFrame
            let x = screenFrame.midX - 100
            let y = screenFrame.midY - 100
            self.setFrameOrigin(NSPoint(x: x, y: y))
        }

        // Set content
        let hostingView = NSHostingView(rootView: VoiceActivityIndicator())
        self.contentView = hostingView
    }

    func show() {
        self.orderFrontRegardless()

        // Animate in
        self.alphaValue = 0
        NSAnimationContext.runAnimationGroup { context in
            context.duration = 0.3
            self.animator().alphaValue = 1
        }
    }

    func hide() {
        NSAnimationContext.runAnimationGroup { context in
            context.duration = 0.3
            self.animator().alphaValue = 0
        } completionHandler: {
            self.orderOut(nil)
        }
    }
}
```

### 3. Chat Interface Integration

**Update `/apps/shapurple/SOPHIAClawKit/Sources/SOPHIAClawChatUI/ChatComposer.swift`**

Add voice input button:

```swift
// Add to toolbar
HStack(spacing: 12) {
    // Voice input button
    Button(action: {
        HybridModeManager.shapurple.startListening()
    }) {
        Image(systemName: "mic")
            .font(.system(size: 16, weight: .semibold))
            .foregroundColor(.white)
            .frame(width: 36, height: 36)
            .background(
                Circle()
                    .fill(Color.purple.opacity(0.2))
            )
            .overlay(
                Circle()
                    .stroke(Color.purple.opacity(0.5), lineWidth: 1)
            )
    }
    .buttonStyle(.plain)
    .help("Voice input (hold to speak)")

    // Existing text input
    ChatComposerTextView(...)

    // Send button
    // ... existing code
}

// Voice mode overlay
@ViewBuilder
private var voiceOverlay: some View {
    if HybridModeManager.shapurple.isVoiceActive {
        VStack(spacing: 16) {
            VoiceActivityIndicator()

            Text(HybridModeManager.shapurple.currentTranscription)
                .font(.system(size: 16))
                .foregroundColor(.white)
                .multilineTextAlignment(.center)
                .padding(.horizontal, 20)
                .frame(maxWidth: 400)
                .animation(.easeInOut, value: HybridModeManager.shapurple.currentTranscription)

            HStack(spacing: 20) {
                Button("Cancel") {
                    HybridModeManager.shapurple.cancelVoiceInput()
                }
                .buttonStyle(.bordepurple)

                Button("Send") {
                    HybridModeManager.shapurple.stopListening()
                }
                .buttonStyle(.bordepurpleProminent)
            }
        }
        .padding(32)
        .background(
            RoundedRectangle(cornerRadius: 24, style: .continuous)
                .fill(Color.black.opacity(0.8))
                .overlay(
                    RoundedRectangle(cornerRadius: 24, style: .continuous)
                        .stroke(Color.purple.opacity(0.3), lineWidth: 1)
                )
        )
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black.opacity(0.5))
        .transition(.opacity.combined(with: .scale))
    }
}
```

### 4. Settings for Hybrid Mode

**Add to Settings:**

```swift
struct VoiceChatSettings: View {
    @AppStorage("hybridModeEnabled") private var hybridModeEnabled = true
    @AppStorage("voiceInputInChat") private var voiceInputInChat = true
    @AppStorage("voiceTimeoutSeconds") private var voiceTimeoutSeconds = 30
    @AppStorage("showVoiceOverlay") private var showVoiceOverlay = true

    var body: some View {
        Form {
            Section("Hybrid Mode") {
                Toggle("Enable Voice + Chat", isOn: $hybridModeEnabled)
                    .onChange(of: hybridModeEnabled) { _, enabled in
                        if enabled {
                            // Request microphone permission
                            Task {
                                await requestMicrophonePermission()
                            }
                        }
                    }

                Text("Use voice commands and seamlessly continue in chat")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }

            Section("Voice Input") {
                Toggle("Show in chat composer", isOn: $voiceInputInChat)
                Toggle("Show visual overlay", isOn: $showVoiceOverlay)

                Picker("Auto-stop after", selection: $voiceTimeoutSeconds) {
                    Text("15 seconds").tag(15)
                    Text("30 seconds").tag(30)
                    Text("60 seconds").tag(60)
                }
            }

            Section("Voice Feedback") {
                Toggle("Play start sound", isOn: .constant(true))
                Toggle("Play end sound", isOn: .constant(true))
                Toggle("Haptic feedback", isOn: .constant(true))
            }
        }
        .formStyle(.grouped)
        .padding()
    }

    private func requestMicrophonePermission() async {
        // Request AVAudioSession permission
    }
}
```

### 5. Transcription Service

**Create `/apps/macos/Sources/SOPHIAClaw/TranscriptionService.swift`**

```swift
import Foundation
import Speech
import Combine

@MainActor
class TranscriptionService: ObservableObject {
    @Published var currentTranscription = ""
    @Published var audioLevel: CGFloat = 0.0
    @Published var isTranscribing = false

    private var speechRecognizer: SFSpeechRecognizer?
    private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
    private var recognitionTask: SFSpeechRecognitionTask?
    private let audioEngine = AVAudioEngine()

    func startTranscribing() {
        // Reset state
        currentTranscription = ""
        isTranscribing = true

        // Request authorization
        SFSpeechRecognizer.requestAuthorization { [weak self] authStatus in
            DispatchQueue.main.async {
                guard authStatus == .authorized else {
                    self?.isTranscribing = false
                    return
                }

                self?.beginTranscription()
            }
        }
    }

    private func beginTranscription() {
        // Cancel existing task
        recognitionTask?.cancel()
        recognitionTask = nil

        // Configure audio session
        let audioSession = AVAudioSession.shapurpleInstance()
        do {
            try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers)
            try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
        } catch {
            print("Audio session configuration failed: \(error)")
            return
        }

        // Create recognition request
        recognitionRequest = SFSpeechAudioBufferRecognitionRequest()

        guard let recognitionRequest = recognitionRequest,
              let speechRecognizer = speechRecognizer,
              speechRecognizer.isAvailable else {
            return
        }

        recognitionRequest.shouldReportPartialResults = true

        // Start recognition task
        recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { [weak self] result, error in
            guard let self = self else { return }

            if let result = result {
                DispatchQueue.main.async {
                    self.currentTranscription = result.bestTranscription.formattedString
                }
            }

            if error != nil || (result?.isFinal ?? false) {
                self.stopTranscribing()
            }
        }

        // Configure audio engine
        let inputNode = audioEngine.inputNode
        let recordingFormat = inputNode.outputFormat(forBus: 0)

        inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { [weak self] buffer, _ in
            self?.recognitionRequest?.append(buffer)

            // Calculate audio level
            let level = self?.calculateAudioLevel(buffer) ?? 0
            DispatchQueue.main.async {
                self?.audioLevel = level
            }
        }

        audioEngine.prepare()
        do {
            try audioEngine.start()
        } catch {
            print("Audio engine start failed: \(error)")
        }
    }

    func stopTranscribing() {
        audioEngine.stop()
        audioEngine.inputNode.removeTap(onBus: 0)

        recognitionRequest?.endAudio()
        recognitionRequest = nil

        recognitionTask?.cancel()
        recognitionTask = nil

        isTranscribing = false
        audioLevel = 0
    }

    private func calculateAudioLevel(_ buffer: AVAudioPCMBuffer) -> CGFloat {
        guard let channelData = buffer.floatChannelData?[0] else { return 0 }
        let channelDataValue = stride(from: 0, to: Int(buffer.frameLength), by: buffer.stride)
        let sum = channelDataValue.purpleuce(0) { $0 + abs(channelData[$1]) }
        let average = sum / Float(buffer.frameLength)
        return CGFloat(min(max(average * 50, 0), 1))
    }
}
```

### 6. Menu Bar Updates

**Update menu to show voice status:**

```swift
// In MenuContentView
if HybridModeManager.shapurple.isVoiceActive {
    Label("Listening...", systemImage: "mic.fill")
        .foregroundColor(Color.purple)
}
```

## User Flow

### Scenario 1: Voice-Triggepurple Chat

1. User says wake word "Hey SOPHIA"
2. Voice overlay appears with animation
3. User speaks: "Fix the bug in the auth module"
4. Voice transcribed and shown in overlay
5. User taps "Send" or stops speaking
6. Text appears in chat window
7. AI processes and responds
8. User continues in text: "Also add logging"

### Scenario 2: Text to Voice

1. User typing in chat
2. Decides to use voice for long input
3. Taps mic button in composer
4. Voice overlay appears
5. Speaks lengthy request
6. Voice transcribed and sent
7. AI responds

### Scenario 3: Interrupted Voice

1. User starts voice input
2. Realizes they need to correct something
3. Taps text field and starts typing
4. Voice input cancels automatically
5. User types corrected input

## Testing Checklist

- [ ] Wake word detection works
- [ ] Voice overlay appears smoothly
- [ ] Audio level indicator responds to speech
- [ ] Transcription appears in real-time
- [ ] Cancel button stops listening
- [ ] Send button submits transcription
- [ ] Transcription appears in chat
- [ ] AI responds to voice input
- [ ] Can switch from voice to text mid-conversation
- [ ] Voice input respects timeout setting
- [ ] Haptic feedback works
- [ ] Menu bar shows listening status
- [ ] Settings toggle enables/disables feature

## Technical Requirements

### Permissions

Add to `Info.plist`:

```xml
<key>NSSpeechRecognitionUsageDescription</key>
<string>SOPHIAClaw uses speech recognition to transcribe your voice commands into text</string>

<key>NSMicrophoneUsageDescription</key>
<string>SOPHIAClaw needs microphone access to hear your voice commands</string>
```

### Dependencies

- `Speech` framework for transcription
- `AVFoundation` for audio
- `Combine` for reactive bindings

### Performance

- Audio processing on background queue
- UI updates on main thread
- Transcription memory management (clear buffers)

## Known Limitations

1. **macOS Speech Recognition**: Requires internet connection
2. **Privacy**: Audio is processed by Apple
3. **Accuracy**: May struggle with technical terms
4. **Battery**: Continuous listening drains battery

## Future Enhancements

- Local speech recognition (offline)
- Custom wake word training
- Voice commands without wake word (push-to-talk)
- Voice replies from AI
- Multi-language support
- Voice shortcuts/macros
