Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

44.2 KB
Raw Blame
//
//  AISettingsView+SpeechRecognition.swift
//  fluid
//
//  Extracted from AISettingsView.swift to keep view body under lint limit.
//

import SwiftUI

extension VoiceEngineSettingsView {
    // MARK: - Speech Recognition Card

    var speechRecognitionCard: some View {
        let selectedModel = self.settings.selectedSpeechModel
        let activeModel = self.viewModel.isSpeechModelInstalled(selectedModel) ? selectedModel : nil
        let hasActiveModel = activeModel != nil
        let otherModels = self.viewModel.filteredSpeechModels.filter { model in
            guard let activeModel else { return true }
            return model != activeModel
        }

        return VStack(alignment: .leading, spacing: 0) {
            VStack(alignment: .leading, spacing: FluidPageLayout.sectionSpacing) {
                // Stats Panel - Dynamic bars that update based on selected model
                self.modelStatsPanel
                    .padding(12)
                    .background(
                        RoundedRectangle(cornerRadius: 12)
                            .fill(self.theme.palette.contentBackground.opacity(0.6))
                            .overlay(
                                RoundedRectangle(cornerRadius: 12)
                                    .stroke(self.theme.palette.cardBorder.opacity(0.3), lineWidth: 1)
                            )
                            .shadow(
                                color: self.theme.metrics.cardShadow.color.opacity(self.theme.metrics.cardShadow.opacity),
                                radius: self.theme.metrics.cardShadow.radius,
                                x: self.theme.metrics.cardShadow.x,
                                y: self.theme.metrics.cardShadow.y
                            )
                    )

                ScrollView(.vertical, showsIndicators: false) {
                    VStack(alignment: .leading, spacing: 14) {
                        HStack(spacing: 6) {
                            Image(systemName: "info.circle")
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                            Text("Click a row to preview. Press Activate to load the model.")
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                            Spacer()
                            Menu {
                                ForEach(SpeechProviderFilter.allCases) { option in
                                    Button(option.displayName) {
                                        self.viewModel.providerFilter = option
                                    }
                                }
                            } label: {
                                Text("Filter: \(self.viewModel.providerFilter.displayName)")
                            }
                            .fluidDropdownStyle()
                            Menu {
                                ForEach(ModelSortOption.allCases) { option in
                                    Button(option.rawValue) {
                                        self.viewModel.modelSortOption = option
                                    }
                                }
                            } label: {
                                Text("Sort by: \(self.viewModel.modelSortOption.rawValue)")
                            }
                            .fluidDropdownStyle()
                        }

                        // Active + Other models list
                        VStack(alignment: .leading, spacing: 10) {
                            if let activeModel {
                                VStack(alignment: .leading, spacing: 6) {
                                    Text("Active Model")
                                        .font(self.theme.typography.sectionTitle)
                                        .foregroundStyle(self.voiceEngineTitleText)
                                    self.speechModelCard(for: activeModel)
                                }
                            } else {
                                VStack(alignment: .leading, spacing: 6) {
                                    Text("Active Model")
                                        .font(self.theme.typography.sectionTitle)
                                        .foregroundStyle(self.voiceEngineTitleText)
                                    Label(
                                        self.viewModel.installations.isChecking ? "Checking downloaded models…"
                                            : (self.viewModel.installations.state == .failed ? "Couldn't check downloaded models. Try again." : "No active model yet. Download and activate one below."),
                                        systemImage: self.viewModel.installations.canUseModelActions ? "arrow.down.circle" : "info.circle"
                                    )
                                    .font(self.theme.typography.bodySmall)
                                    .foregroundStyle(self.voiceEngineSecondaryText)
                                    if self.viewModel.installations.state == .failed {
                                        Button("Retry check") { self.viewModel.installations.refresh() }
                                            .fluidGlassAction(quiet: true)
                                    }
                                }
                            }

                            Divider().padding(.vertical, 2)

                            VStack(alignment: .leading, spacing: 6) {
                                Text(hasActiveModel ? "Other Models" : "Available Models")
                                    .font(self.theme.typography.sectionTitle)
                                    .foregroundStyle(self.voiceEngineTitleText)
                                VStack(spacing: 8) {
                                    ForEach(otherModels) { model in
                                        self.speechModelCard(for: model)
                                    }
                                }
                            }
                        }
                        .padding(12)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(self.theme.palette.cardBackground.opacity(0.9))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 12)
                                        .stroke(self.theme.palette.cardBorder.opacity(0.3), lineWidth: 1)
                                )
                                .shadow(
                                    color: self.theme.metrics.cardShadow.color.opacity(self.theme.metrics.cardShadow.opacity),
                                    radius: self.theme.metrics.cardShadow.radius,
                                    x: self.theme.metrics.cardShadow.x,
                                    y: self.theme.metrics.cardShadow.y
                                )
                        )
                    }
                }
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
    }

    /// Stats panel showing speed/accuracy bars that animate when model changes
    var modelStatsPanel: some View {
        let model = self.viewModel.previewSpeechModel

        return VStack(alignment: .leading, spacing: 12) {
            HStack(alignment: .center, spacing: 20) {
                VStack(alignment: .leading, spacing: 8) {
                    VStack(alignment: .leading, spacing: 4) {
                        HStack {
                            Text(model.humanReadableName)
                                .font(.fluidSystem(size: 16, weight: .bold))
                                .foregroundStyle(self.theme.palette.primaryText)

                            if let badge = model.badgeText {
                                Text(badge)
                                    .font(.fluidSystem(.caption2))
                                    .fontWeight(.semibold)
                                    .padding(.horizontal, 6)
                                    .padding(.vertical, 2)
                                    .background(Capsule().fill(badge == "FluidVoice Pick" ? .cyan.opacity(0.2) : .orange.opacity(0.2)))
                                    .foregroundStyle(badge == "FluidVoice Pick" ? .cyan : .orange)
                            }

                            Spacer()
                        }

                        Text(model.cardDescription)
                            .font(self.theme.typography.bodySmall)
                            .foregroundStyle(self.voiceEngineSecondaryText)
                            .lineLimit(2)

                        if let descriptor = model.parakeetDescriptor {
                            Text(descriptor.creditLine)
                                .font(self.theme.typography.caption)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                                // A fixed vertical size here can push the page above the toolbar.
                                .lineLimit(2)
                        }
                    }

                    HStack(spacing: 8) {
                        Label(self.viewModel.speechModelDownloadSize(model), systemImage: "internaldrive")
                            .font(self.theme.typography.bodySmall)
                            .foregroundStyle(self.voiceEngineSecondaryText)

                        if model.requiresAppleSilicon {
                            Text("Apple Silicon")
                                .font(self.theme.typography.bodySmallStrong)
                                .padding(.horizontal, 6)
                                .padding(.vertical, 2)
                                .background(Capsule().fill(self.theme.palette.accent.opacity(0.2)))
                                .foregroundStyle(self.theme.palette.accent)
                        }

                        Text(model.languageSupport)
                            .font(self.theme.typography.bodySmallStrong)
                            .padding(.horizontal, 6)
                            .padding(.vertical, 2)
                            .background(Capsule().fill(.quaternary))
                            .foregroundStyle(self.voiceEngineSecondaryText)

                        Spacer()
                    }

                    if let supportedLanguageCodes = model.supportedLanguageCodes {
                        Text(supportedLanguageCodes)
                            .font(self.theme.typography.bodySmall)
                            .foregroundStyle(self.voiceEngineSecondaryText)
                            .lineLimit(2)
                            .help(model.supportedLanguageNames ?? supportedLanguageCodes)
                    }

                    // Memory warning for large models
                    if let memoryWarning = model.memoryWarning {
                        HStack(spacing: 6) {
                            Image(systemName: "exclamationmark.triangle.fill")
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(.orange)
                            Text(memoryWarning)
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(.orange)
                        }
                        .padding(.horizontal, 8)
                        .padding(.vertical, 4)
                        .background(
                            RoundedRectangle(cornerRadius: 6)
                                .fill(.orange.opacity(0.1))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 6)
                                        .stroke(.orange.opacity(0.3), lineWidth: 1)
                                )
                        )
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)

                if model.hasPerformanceRatings {
                    HStack(spacing: 16) {
                        LiquidBar(
                            fillPercent: model.speedPercent,
                            color: .yellow,
                            secondaryColor: .orange,
                            icon: "bolt.fill",
                            label: "Speed"
                        )

                        LiquidBar(
                            fillPercent: model.accuracyPercent,
                            color: Color.fluidGreen,
                            secondaryColor: .cyan,
                            icon: "target",
                            label: "Accuracy"
                        )
                    }
                    .frame(width: 140, alignment: .center)
                    .help("Relative ratings for comparing models, not measured transcription accuracy.")
                    .animation(.spring(response: 0.5, dampingFraction: 0.7), value: model.id)
                }
            }
        }
        .padding(.vertical, 6)
    }

    func speechModelCard(for model: SettingsStore.SpeechModel) -> some View {
        let isSelected = self.viewModel.previewSpeechModel == model
        let isConfiguredActive = self.viewModel.isActiveSpeechModel(model)
        let isActive = isConfiguredActive && self.viewModel.isSpeechModelInstalled(model) && self.viewModel.asr.isAsrReady

        return HStack(alignment: .top, spacing: 10) {
            Circle()
                .fill(isSelected ? Color.fluidGreen : self.theme.palette.cardBorder.opacity(0.25))
                .frame(width: 8, height: 8)
                .overlay(
                    Circle()
                        .stroke(isSelected ? Color.fluidGreen : self.theme.palette.cardBorder.opacity(0.5), lineWidth: 1)
                )

            self.speechModelLogoView(for: model)
                .frame(width: 28, height: 28)

            VStack(alignment: .leading, spacing: 4) {
                Text(model.humanReadableName)
                    .font(self.theme.typography.bodyStrong)
                    .foregroundStyle(self.voiceEngineTitleText)
                Text(self.speechModelSubtitle(for: model))
                    .font(self.theme.typography.body)
                    .foregroundStyle(self.voiceEngineSecondaryText)

                HStack(spacing: 12) {
                    if model.hasPerformanceRatings {
                        HStack(spacing: 4) {
                            Image(systemName: "bolt.fill")
                                .font(.fluidSystem(size: 11))
                                .foregroundStyle(.yellow)
                            Text("Speed \(Int(model.speedPercent * 100))%")
                                .font(self.theme.typography.bodyStrong)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                        }

                        HStack(spacing: 4) {
                            Image(systemName: "target")
                                .font(.fluidSystem(size: 11))
                                .foregroundStyle(Color.fluidGreen)
                            Text("Acc \(Int(model.accuracyPercent * 100))%")
                                .font(self.theme.typography.bodyStrong)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                        }
                    }

                    if isSelected && !isActive {
                        Text("Previewing")
                            .font(self.theme.typography.bodyStrong)
                            .foregroundStyle(self.voiceEngineSecondaryText)
                    }
                }
            }
            .frame(maxWidth: .infinity, alignment: .leading)

            // Action area: Show progress if THIS model is being downloaded
            if self.viewModel.asr.deletingModelID == model.id {
                HStack(spacing: 8) {
                    ProgressView().controlSize(.mini)
                    Text("Deleting…")
                        .font(self.theme.typography.bodySmall)
                        .foregroundStyle(self.voiceEngineSecondaryText)
                }
                .accessibilityLabel("Deleting \(model.humanReadableName)")
            } else if self.viewModel.downloadingModel == model {
                // This specific model is currently being downloaded
                HStack(spacing: 8) {
                    VStack(alignment: .trailing, spacing: 4) {
                        if self.viewModel.isCancellingModelDownload {
                            ProgressView()
                                .controlSize(.mini)
                            Text("Cancelling…")
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                        } else if self.viewModel.asr.modelPreparationPhase == .downloading,
                                  let progress = self.viewModel.asr.downloadProgress
                        {
                            ProgressView(value: progress)
                                .progressViewStyle(.linear)
                                .frame(width: 90)
                            Text("\(Int(progress * 100))%")
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                        } else {
                            ProgressView()
                                .controlSize(.mini)
                            Text(self.viewModel.asr.modelPreparationStatusText)
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                        }
                    }

                    Button(self.viewModel.isCancellingModelDownload ? "Cancelling…" : "Cancel") {
                        self.viewModel.cancelSpeechModelDownload()
                    }
                    .fluidOutlinedButton()
                    .controlSize(.small)
                    .disabled(self.viewModel.isCancellingModelDownload)
                }
            } else if (self.viewModel.asr.isDownloadingModel
                || self.viewModel.asr.isLoadingModel
                || self.viewModel.asr.isCancellingModelPreparation)
                && isConfiguredActive
                && !self.viewModel.asr.isAsrReady
            {
                // Active model is loading/downloading (for Activate flow)
                HStack(spacing: 8) {
                    VStack(alignment: .trailing, spacing: 4) {
                        if self.viewModel.asr.isCancellingModelPreparation {
                            ProgressView()
                                .controlSize(.mini)
                            Text("Cancelling…")
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                        } else if self.viewModel.asr.isDownloadingModel,
                                  self.viewModel.asr.modelPreparationPhase == .downloading,
                                  let progress = self.viewModel.asr.downloadProgress
                        {
                            ProgressView(value: progress)
                                .progressViewStyle(.linear)
                                .frame(width: 90)
                            Text("\(Int(progress * 100))%")
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                        } else {
                            ProgressView()
                                .controlSize(.mini)
                            Text(self.viewModel.asr.modelPreparationStatusText)
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(self.voiceEngineSecondaryText)
                        }
                    }

                    Button(self.viewModel.asr.isCancellingModelPreparation ? "Cancelling…" : "Cancel") {
                        self.viewModel.cancelActiveModelPreparation()
                    }
                    .fluidOutlinedButton()
                    .controlSize(.small)
                    .disabled(self.viewModel.asr.isCancellingModelPreparation)
                }
            } else if !self.viewModel.installations.canUseModelActions {
                if self.viewModel.installations.isChecking {
                    HStack(spacing: 6) {
                        ProgressView().controlSize(.mini)
                        Text("Checking downloads…")
                            .font(self.theme.typography.bodySmall)
                            .foregroundStyle(self.voiceEngineSecondaryText)
                    }
                } else {
                    Button("Retry check") { self.viewModel.installations.refresh() }
                        .fluidGlassAction(quiet: true)
                }
            } else if self.viewModel.isSpeechModelInstalled(model) {
                HStack(spacing: 8) {
                    if self.viewModel.isSpeechModelUpdateAvailable(model) {
                        Button("Update") {
                            self.viewModel.downloadSpeechModel(model, updateWeights: true)
                        }
                        .fluidGlassAction(prominent: true, tone: .orange)
                        .disabled(self.viewModel.areSpeechModelActionsBlocked)
                        .accessibilityLabel("Update \(model.humanReadableName)")
                    }

                    if isActive {
                        self.speechModelLanguagePicker(for: model)
                            .disabled(self.viewModel.areSpeechModelActionsBlocked)

                        Text("Active")
                            .font(self.theme.typography.bodySmallStrong)
                            .padding(.horizontal, 10)
                            .padding(.vertical, 4)
                            .background(Capsule().fill(Color.fluidGreen.opacity(0.25)))
                            .foregroundStyle(Color.fluidGreen)
                    } else {
                        // A failed or cancelled locale download leaves Apple Speech configured but not ready.
                        // Keep the picker so people can switch back to an installed locale.
                        if isConfiguredActive, model == .appleSpeechAnalyzer {
                            self.appleSpeechLocalePickerButton
                                .disabled(self.viewModel.areSpeechModelActionsBlocked)
                        }

                        Button("Activate") {
                            self.viewModel.activateSpeechModel(model)
                        }
                        .fluidGlassAction(prominent: true)
                        .disabled(self.viewModel.areSpeechModelActionsBlocked)
                    }

                    if !model.usesAppleLogo {
                        if isSelected {
                            Button {
                                self.viewModel.deleteSpeechModel(model)
                            } label: {
                                Image(systemName: "trash")
                                    .font(.fluidSystem(size: 15))
                                    .foregroundStyle(.red.opacity(0.7))
                            }
                            .buttonStyle(.plain)
                            .disabled(self.viewModel.areSpeechModelActionsBlocked)
                            .opacity(isSelected ? 1 : 0)
                            .allowsHitTesting(isSelected)
                            .accessibilityHidden(!isSelected)
                        }
                    }
                }
            } else {
                ZStack(alignment: .trailing) {
                    if model.requiresExternalArtifacts {
                        HStack(spacing: 8) {
                            if model.externalCoreMLSpec?.sourceURL != nil {
                                Button {
                                    self.viewModel.openExternalModelSource(for: model)
                                } label: {
                                    Image(systemName: "arrow.up.right.square")
                                        .font(.fluidSystem(size: 14))
                                }
                                .buttonStyle(.plain)
                                .foregroundStyle(self.voiceEngineTertiaryText)
                                .disabled(self.viewModel.areSpeechModelActionsBlocked)
                            }

                            Button("Download") {
                                self.viewModel.previewSpeechModel = model
                                self.viewModel.downloadSpeechModel(model)
                            }
                            .fluidGlassAction(prominent: true)
                            .disabled(self.viewModel.areSpeechModelActionsBlocked)
                        }
                        .opacity(isSelected ? 1 : 0)
                        .allowsHitTesting(isSelected)
                        .accessibilityHidden(!isSelected)
                    } else {
                        Text("Not downloaded")
                            .font(self.theme.typography.bodySmall)
                            .foregroundStyle(self.voiceEngineTertiaryText)
                            .opacity(isSelected ? 0 : 1)

                        Button("Download") {
                            self.viewModel.previewSpeechModel = model
                            self.viewModel.downloadSpeechModel(model)
                        }
                        .fluidGlassAction(prominent: true)
                        .disabled(self.viewModel.areSpeechModelActionsBlocked)
                        .opacity(isSelected ? 1 : 0)
                        .allowsHitTesting(isSelected)
                        .accessibilityHidden(!isSelected)
                    }
                }
                .frame(width: model.requiresExternalArtifacts ? 150 : 120, alignment: .trailing)
            }
        }
        .padding(.horizontal, 12)
        .padding(.vertical, 10)
        .contentShape(Rectangle())
        .animation(.easeInOut(duration: 0.2), value: isSelected)
        .background(
            RoundedRectangle(cornerRadius: 8)
                .fill(isSelected ? self.theme.palette.cardBackground.opacity(0.8) : .clear)
                .overlay(
                    RoundedRectangle(cornerRadius: 8)
                        .stroke(isSelected ? self.theme.palette.cardBorder.opacity(0.6) : self.theme.palette.cardBorder.opacity(0.25), lineWidth: 1)
                )
                .overlay(
                    RoundedRectangle(cornerRadius: 8)
                        .stroke(isActive ? Color.fluidGreen.opacity(0.9) : .clear, lineWidth: 2)
                )
        )
        .onTapGesture {
            self.viewModel.previewSpeechModel = model
        }
        .opacity(self.viewModel.asr.isRunning ? 0.6 : 1.0)
        .allowsHitTesting(!self.viewModel.asr.isRunning)
    }

    @ViewBuilder
    private func speechModelLanguagePicker(for model: SettingsStore.SpeechModel) -> some View {
        if model.isWhisperModel {
            self.whisperLanguagePickerButton
        } else if model == .cohereTranscribeSixBit {
            Menu {
                ForEach(SettingsStore.CohereLanguage.allCases) { language in
                    Button {
                        guard language != self.settings.selectedCohereLanguage else { return }
                        self.settings.selectedCohereLanguage = language
                    } label: {
                        HStack {
                            Text(language.displayName)
                            if language == self.settings.selectedCohereLanguage {
                                Image(systemName: "checkmark")
                            }
                        }
                    }
                }
            } label: { Label(self.settings.selectedCohereLanguage.displayName, systemImage: "globe") }
                .fluidDropdownStyle()
        } else if model == .nemotronOffline || model == .nemotronStreaming || model == .nemotronStreaming320 {
            self.nemotronLanguagePickerButton
        } else if model == .appleSpeechAnalyzer {
            self.appleSpeechLocalePickerButton
        }
    }

    private var appleSpeechLocalePickerButton: some View {
        Button {
            self.appleSpeechLocaleSearchText = ""
            self.isShowingAppleSpeechLocalePicker.toggle()
        } label: {
            self.languageChipLabel(self.selectedAppleSpeechLocaleName)
        }
        .buttonStyle(.plain)
        .popover(isPresented: self.$isShowingAppleSpeechLocalePicker, arrowEdge: .bottom) {
            self.appleSpeechLocalePickerPopover
        }
    }

    private var selectedAppleSpeechLocaleName: String {
        let localeIdentifier = self.settings.selectedAppleSpeechLocaleIdentifier
        return Locale.current.localizedString(forIdentifier: localeIdentifier) ?? localeIdentifier
    }

    private var filteredAppleSpeechLocaleOptions: [AppleSpeechLocaleOption] {
        let query = self.appleSpeechLocaleSearchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        guard !query.isEmpty else { return self.appleSpeechLocaleOptions }
        return self.appleSpeechLocaleOptions.filter { option in
            option.displayName.lowercased().contains(query) || option.id.lowercased().contains(query)
        }
    }

    private var appleSpeechLocalePickerPopover: some View {
        VStack(spacing: 0) {
            HStack(spacing: 8) {
                Image(systemName: "magnifyingglass")
                    .foregroundStyle(self.voiceEngineTertiaryText)
                TextField("Search languages", text: self.$appleSpeechLocaleSearchText)
                    .textFieldStyle(.plain)
            }
            .padding(.horizontal, 12)
            .frame(height: 36)

            Divider()

            ScrollView(.vertical, showsIndicators: true) {
                LazyVStack(alignment: .leading, spacing: 0) {
                    ForEach(self.filteredAppleSpeechLocaleOptions) { option in
                        Button {
                            self.viewModel.selectAppleSpeechLocale(option.id)
                            self.isShowingAppleSpeechLocalePicker = false
                        } label: {
                            self.whisperLanguagePickerRow(
                                title: option.displayName,
                                isSelected: option.id == self.settings.selectedAppleSpeechLocaleIdentifier
                            )
                        }
                        .buttonStyle(.plain)
                    }
                }
                .padding(.vertical, 6)
            }
        }
        .frame(width: 280, height: 420)
        .task {
            guard #available(macOS 26, *) else { return }
            let identifiers = await AppleSpeechAnalyzerProvider.supportedLocaleIdentifiers()
            self.appleSpeechLocaleOptions = VoiceEngineLanguageCatalog.appleSpeechLocaleOptions(identifiers: identifiers)
        }
    }

    private var whisperLanguagePickerButton: some View {
        Button {
            self.whisperLanguageSearchText = ""
            self.isShowingWhisperLanguagePicker.toggle()
        } label: {
            self.languageChipLabel(self.selectedWhisperLanguageName)
        }
        .buttonStyle(.plain)
        .popover(isPresented: self.$isShowingWhisperLanguagePicker, arrowEdge: .bottom) {
            self.whisperLanguagePickerPopover
        }
    }

    private var selectedWhisperLanguageName: String {
        guard let languageCode = self.settings.selectedWhisperLanguageCode,
              let language = VoiceEngineLanguageCatalog.whisperLanguage(forCode: languageCode)
        else {
            return "Automatic"
        }
        return language.displayName
    }

    private var filteredWhisperLanguages: [VoiceEngineLanguage] {
        let query = self.normalizedWhisperLanguageSearchText
        guard !query.isEmpty else { return VoiceEngineLanguageCatalog.whisperLanguages }
        return VoiceEngineLanguageCatalog.whisperLanguages.filter { language in
            language.displayName.lowercased().contains(query) ||
                language.id.lowercased().contains(query) ||
                language.aliases.contains { $0.lowercased().contains(query) }
        }
    }

    private var normalizedWhisperLanguageSearchText: String {
        self.whisperLanguageSearchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
    }

    private var whisperLanguagePickerPopover: some View {
        VStack(spacing: 0) {
            HStack(spacing: 8) {
                Image(systemName: "magnifyingglass")
                    .foregroundStyle(self.voiceEngineTertiaryText)
                TextField("Search languages", text: self.$whisperLanguageSearchText)
                    .textFieldStyle(.plain)
            }
            .padding(.horizontal, 12)
            .frame(height: 36)

            Divider()

            ScrollView(.vertical, showsIndicators: true) {
                LazyVStack(alignment: .leading, spacing: 0) {
                    if self.normalizedWhisperLanguageSearchText.isEmpty ||
                        "automatic".contains(self.normalizedWhisperLanguageSearchText)
                    {
                        Button {
                            self.settings.selectedWhisperLanguageCode = nil
                            self.isShowingWhisperLanguagePicker = false
                        } label: {
                            self.whisperLanguagePickerRow(
                                title: "Automatic",
                                isSelected: self.settings.selectedWhisperLanguageCode == nil
                            )
                        }
                        .buttonStyle(.plain)

                        Divider()
                            .padding(.vertical, 4)
                    }

                    ForEach(self.filteredWhisperLanguages) { language in
                        let languageCode = VoiceEngineLanguageCatalog.whisperLanguageCode(for: language.id)
                        Button {
                            self.settings.selectedWhisperLanguageCode = languageCode
                            self.isShowingWhisperLanguagePicker = false
                        } label: {
                            self.whisperLanguagePickerRow(
                                title: language.displayName,
                                isSelected: languageCode == self.settings.selectedWhisperLanguageCode
                            )
                        }
                        .buttonStyle(.plain)
                    }
                }
                .padding(.vertical, 6)
            }
        }
        .frame(width: 280, height: 420)
    }

    private func whisperLanguagePickerRow(title: String, isSelected: Bool) -> some View {
        HStack(spacing: 8) {
            Text(title)
                .font(self.theme.typography.bodySmall)
                .foregroundStyle(.primary)
            Spacer(minLength: 12)
            if isSelected {
                Image(systemName: "checkmark")
                    .font(self.theme.typography.bodySmall)
                    .foregroundStyle(self.theme.palette.accent)
            }
        }
        .contentShape(Rectangle())
        .padding(.horizontal, 12)
        .frame(height: 28)
    }

    private func languageChipLabel(_ title: String) -> some View {
        HStack(spacing: 10) {
            Image(systemName: "globe").foregroundStyle(self.theme.palette.accent)
            Text(title).lineLimit(1)
            FluidDropdownChevron()
        }
        .font(self.theme.typography.bodySmall)
        .padding(.horizontal, 12)
        .padding(.vertical, 9)
        .fluidDropdownSurface()
    }

    private func speechModelSubtitle(for model: SettingsStore.SpeechModel) -> String {
        if [.fluidParakeetMini, .fluidParakeetPico, .fluidParakeetPro].contains(model) {
            return model.languageSupport
        }
        switch model {
        case .nemotronStreaming, .nemotronStreaming320:
            return "Nemotron Speech 3.5 - Streaming Capable"
        default:
            return model.displayName
        }
    }

    private var nemotronLanguagePickerButton: some View {
        Button {
            self.isShowingNemotronLanguagePicker.toggle()
        } label: {
            self.languageChipLabel(self.settings.selectedNemotronLanguage.compactDisplayName)
        }
        .buttonStyle(.plain)
        .popover(isPresented: self.$isShowingNemotronLanguagePicker, arrowEdge: .bottom) {
            self.nemotronLanguagePickerPopover
        }
    }

    private var nemotronLanguagePickerPopover: some View {
        ScrollView(.vertical, showsIndicators: true) {
            LazyVStack(alignment: .leading, spacing: 0) {
                ForEach(SettingsStore.NemotronLanguage.allCases) { language in
                    Button {
                        self.settings.selectedNemotronLanguage = language
                        self.isShowingNemotronLanguagePicker = false
                    } label: {
                        HStack(spacing: 8) {
                            Text(language.displayName)
                                .font(self.theme.typography.bodySmall)
                                .foregroundStyle(.primary)
                            Spacer(minLength: 12)
                            if language == self.settings.selectedNemotronLanguage {
                                Image(systemName: "checkmark")
                                    .font(self.theme.typography.bodySmall)
                                    .foregroundStyle(self.theme.palette.accent)
                            }
                        }
                        .contentShape(Rectangle())
                        .padding(.horizontal, 12)
                        .frame(height: 26)
                    }
                    .buttonStyle(.plain)
                }
            }
            .padding(.vertical, 6)
        }
        .frame(width: 260, height: 532)
    }

    var modelStatusView: some View {
        HStack(spacing: 12) {
            if (self.viewModel.asr.isDownloadingModel || self.viewModel.asr.isLoadingModel) && !self.viewModel.asr.isAsrReady {
                HStack(spacing: 8) {
                    ProgressView().controlSize(.small).fixedSize()
                    Text(self.viewModel.asr.isLoadingModel ? "Loading model…" : "Downloading model…")
                        .font(self.theme.typography.bodySmall)
                        .foregroundStyle(self.voiceEngineSecondaryText)
                }
            } else if self.viewModel.asr.isAsrReady {
                Image(systemName: "checkmark.circle.fill").foregroundStyle(Color.fluidGreen).font(self.theme.typography.bodySmall)
                Text("Ready").font(self.theme.typography.bodySmall).foregroundStyle(self.voiceEngineSecondaryText)

                Button(action: { Task { await self.viewModel.deleteModels() } }) {
                    HStack(spacing: 4) {
                        Image(systemName: "trash")
                        Text("Delete")
                    }
                    .font(self.theme.typography.bodySmall)
                    .foregroundStyle(.red)
                }
                .buttonStyle(.plain)
            } else if self.viewModel.asr.modelsExistOnDisk {
                Image(systemName: "doc.fill").foregroundStyle(self.theme.palette.accent).font(self.theme.typography.bodySmall)
                Text("Cached")
                    .font(self.theme.typography.bodySmall)
                    .foregroundStyle(self.voiceEngineSecondaryText)

                Button(action: { Task { await self.viewModel.deleteModels() } }) {
                    HStack(spacing: 4) {
                        Image(systemName: "trash")
                        Text("Delete")
                    }
                    .font(self.theme.typography.bodySmall)
                    .foregroundStyle(.red)
                }
                .buttonStyle(.plain)
            } else {
                HStack(spacing: 8) {
                    if self.settings.selectedSpeechModel.requiresExternalArtifacts,
                       self.settings.selectedSpeechModel.externalCoreMLSpec?.sourceURL != nil
                    {
                        Button(action: { self.viewModel.openExternalModelSource(for: self.settings.selectedSpeechModel) }) {
                            HStack(spacing: 4) {
                                Image(systemName: "arrow.up.right.square")
                                Text("Hugging Face")
                            }
                            .font(self.theme.typography.bodySmall)
                        }
                        .buttonStyle(.plain)
                        .foregroundStyle(self.theme.palette.accent)
                    }

                    Button(action: { Task { await self.viewModel.downloadModels() } }) {
                        HStack(spacing: 4) {
                            Image(systemName: "arrow.down.circle.fill")
                            Text("Download")
                        }
                        .font(self.theme.typography.bodySmall)
                    }
                    .buttonStyle(.borderedProminent)
                    .controlSize(.small)
                    .tint(.blue)
                }
            }
        }
        .padding(.horizontal, 12)
        .padding(.vertical, 8)
        .background(RoundedRectangle(cornerRadius: 8)
            .fill(self.theme.palette.cardBackground.opacity(0.8))
            .overlay(RoundedRectangle(cornerRadius: 8).stroke(self.theme.palette.cardBorder.opacity(0.5), lineWidth: 1)))
    }

    // MARK: - Speech Model Logo View

    private func speechModelLogoView(for model: SettingsStore.SpeechModel) -> some View {
        let bgColor = self.speechModelBackgroundColor(for: model)
        let imageName = self.speechModelImageName(for: model)
        let isNvidia = model.brandName.lowercased().contains("nvidia")

        return ZStack {
            RoundedRectangle(cornerRadius: 7, style: .continuous)
                .fill(bgColor)

            if model.brandName == "FluidVoice" {
                FluidVoiceBrandIcon(size: 28)
            } else if model.usesAppleLogo {
                Image(systemName: "apple.logo")
                    .font(.fluidSystem(size: 14, weight: .medium))
                    .foregroundStyle(.primary)
            } else if let imageName {
                Image(imageName)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    // NVIDIA logo larger to fill more of the container
                    .frame(width: isNvidia ? 24 : 18, height: isNvidia ? 24 : 18)
            } else {
                Text(String(model.brandName.prefix(2)).uppercased())
                    .font(.fluidSystem(size: 10, weight: .bold, design: .rounded))
                    .foregroundStyle(self.theme.palette.primaryText)
            }
        }
        .frame(width: 28, height: 28)
        .clipShape(RoundedRectangle(cornerRadius: 7, style: .continuous))
    }

    private func speechModelBackgroundColor(for model: SettingsStore.SpeechModel) -> Color {
        let brand = model.brandName.lowercased()

        // Keep these provider marks on a light background in both appearances.
        if brand.contains("nvidia") || brand.contains("openai") || brand.contains("whisper") || brand.contains("qwen") {
            return Color(red: 0.97, green: 0.97, blue: 0.97)
        }
        if brand.contains("apple") || model.usesAppleLogo {
            return self.theme.palette.cardBackground.opacity(0.9)
        }
        return Color(hex: model.brandColorHex)?.opacity(0.2) ?? self.theme.palette.cardBackground
    }

    private func speechModelImageName(for model: SettingsStore.SpeechModel) -> String? {
        let brand = model.brandName.lowercased()

        if brand.contains("nvidia") {
            return "Provider_NVIDIA"
        }
        if brand.contains("cohere") {
            return "Provider_Cohere"
        }
        if brand.contains("qwen") {
            // Official organization mark from https://github.com/QwenLM.
            return "Provider_Qwen"
        }
        if brand.contains("openai") || brand.contains("whisper") {
            return "Provider_OpenAI"
        }
        return nil
    }
}

extension Notification.Name {
    static let openCustomDictionaryFromVoiceEngine = Notification.Name("OpenCustomDictionaryFromVoiceEngine")
}