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

68.5 KB
Raw Blame
import AppKit
import Combine
import SwiftUI

enum MenuBarNavigationDestination: String {
    case customDictionary
    case microphoneSettings
    case settings
    case meetingTranscription
    case preferences
    case cleanupStyles
    case aiSettings
}

@MainActor
final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
    private enum MeetingMenuActivity: Equatable {
        case inactive
        case preparing
        case recording
        case stopping
        case processing
        case interrupted
        case failed
        case completed
    }

    private struct MeetingMenuPresentation {
        var activity: MeetingMenuActivity = .inactive
        var sourceName: String?
        var startedAt: Date?
        var attentionStatus: String?
    }

    private var statusItem: NSStatusItem?
    private var menu: NSMenu?
    private var isSetup: Bool = false
    private var hostedWindow: NSWindow?

    // Cached menu items to avoid rebuilding entire menu
    private var statusMenuItem: NSMenuItem?
    private var copyLastTranscriptMenuItem: NSMenuItem?
    private var rollbackMenuItem: NSMenuItem?
    private var microphoneMenuItem: NSMenuItem?
    private var microphoneSubmenu: NSMenu?
    private var startMeetingRecordingMenuItem: NSMenuItem?
    private(set) var meetingStartRequested = false
    private(set) var meetingStartError: String?
    private var stopMeetingRecordingMenuItem: NSMenuItem?
    private var meetingStatusMenuItem: NSMenuItem?
    private var openMeetingTranscriptionMenuItem: NSMenuItem?
    private var meetingMenuSeparator: NSMenuItem?
    private var meetingMenuPresentation = MeetingMenuPresentation()
    private var meetingStopRequested = false
    private var stopMeetingRecordingHandler: (() -> Void)?

    // References to app state
    private weak var asrService: ASRService?
    private weak var meetingCoordinator: MeetingSessionCoordinator?
    private var cancellables = Set<AnyCancellable>()
    private var hasDeferredStopMenuRefresh = false
    private var hasDeferredStoppedRecordingState = false
    private var configuredASRIdentifier: ObjectIdentifier?
    private var meetingCancellables = Set<AnyCancellable>()

    /// Overlay management (persistent, independent of window lifecycle)
    private var overlayVisible: Bool = false

    /// Track when AI processing is active.
    /// When recording stops, ASRService flips `isRunning` to false, which would normally hide the
    /// overlay. During post-processing we want the overlay to stay visible until processing ends.
    private var isProcessingActive: Bool = false

    @Published var isRecording: Bool = false

    /// One-shot navigation requests from the menu bar into the main window UI.
    /// The manager clears each generation after the front-most view has handled it.
    @Published var requestedNavigationDestination: MenuBarNavigationDestination? = nil
    private var navigationRequestGeneration: UInt64 = 0

    /// Track current overlay mode for notch
    private var currentOverlayMode: OverlayMode = .dictation

    // Track pending overlay operations to prevent spam
    private var pendingShowOperation: DispatchWorkItem?
    private var pendingHideOperation: DispatchWorkItem?
    private var pendingProcessingShowOperation: DispatchWorkItem?
    /// Show immediately so users see the processing state right away.
    private let processingVisualDelay: DispatchTimeInterval = .milliseconds(0)
    /// Legacy debounce used by generic processing callers. Successful dictation
    /// completion dispatches output first, then hides the overlay asynchronously.
    private let processingHideDelay: DispatchTimeInterval = .milliseconds(80)

    /// Subscription for forwarding audio levels to expanded command notch
    private var expandedModeAudioSubscription: AnyCancellable?

    override init() {
        super.init()
        NotificationCenter.default.publisher(for: .fluidMeetEnabledChanged)
            .sink { [weak self] _ in
                MainActor.assumeIsolated { self?.updateMeetingMenuItemsText() }
            }
            .store(in: &self.cancellables)
        NotificationCenter.default.publisher(for: .openMicrophoneSettingsRequested)
            .receive(on: RunLoop.main)
            .sink { [weak self] _ in
                self?.openMicrophoneSettingsFromUI()
            }
            .store(in: &self.cancellables)
    }

    func initializeMenuBar() {
        guard !self.isSetup else { return }

        // Ensure we're on main thread and app is active
        DispatchQueue.main.async { [weak self] in
            self?.setupMenuBarSafely()
        }
    }

    deinit {
        statusItem = nil
    }

    func configure(asrService: ASRService) {
        let identifier = ObjectIdentifier(asrService)
        guard self.configuredASRIdentifier != identifier else { return }
        self.configuredASRIdentifier = identifier
        self.asrService = asrService
        asrService.audioCaptureFailurePresented
            .sink { [weak self, weak asrService] in
                guard let self, let asrService,
                      self.asrService === asrService,
                      asrService.showError, asrService.isRunning == false
                else { return }
                // The recording error must also be visible when the user only
                // uses the menu bar and has closed the main window.
                self.openMainWindow()
            }
            .store(in: &self.cancellables)
        if SettingsStore.shared.overlayPosition == .bottom {
            DispatchQueue.main.async {
                guard SettingsStore.shared.overlayPosition == .bottom else { return }
                BottomOverlayWindowController.shared.prepare()
            }
        }
        NotificationCenter.default.publisher(for: NSNotification.Name("OverlayPositionChanged"))
            .receive(on: DispatchQueue.main)
            .sink { _ in
                guard SettingsStore.shared.overlayPosition == .bottom else { return }
                BottomOverlayWindowController.shared.prepare()
            }
            .store(in: &self.cancellables)

        NotificationCenter.default.addObserver(forName: .fluidPasteNotLanded, object: nil, queue: .main) { [weak self] note in
            guard let transcript = note.userInfo?["transcript"] as? String,
                  let verificationID = note.userInfo?["verificationID"] as? UInt64,
                  let postedAt = note.userInfo?["postedAt"] as? TimeInterval else { return }
            Task { @MainActor [weak self] in self?.showPasteNotLandedFailure(transcript: transcript, verificationID: verificationID, postedAt: postedAt) }
        }

        // Subscribe to recording state changes
        asrService.$isRunning
            .receive(on: DispatchQueue.main)
            .sink { [weak self] isRunning in
                guard let self else { return }
                if isRunning == false, self.isProcessingActive {
                    self.hasDeferredStoppedRecordingState = true
                    self.overlayBench("recording_state_deferred reason=processing_active")
                    self.handleOverlayState(isRunning: false, asrService: asrService)
                    return
                }
                if isRunning {
                    self.hasDeferredStoppedRecordingState = false
                    OverlayAudioLevelState.shared.isLive = true
                    DebugLogger.shared.debug("WAVEFORM_LIVE", source: "StopTiming")
                }
                self.isRecording = isRunning
                self.updateMenuBarIcon()
                if asrService.defersStopUIInvalidation {
                    self.hasDeferredStopMenuRefresh = true
                } else {
                    self.updateMenu()
                }

                // Handle overlay lifecycle (independent of window state)
                self.handleOverlayState(isRunning: isRunning, asrService: asrService)
            }
            .store(in: &self.cancellables)

        asrService.deferredStopUIInvalidationDidFlush
            .receive(on: DispatchQueue.main)
            .sink { [weak self] in
                guard let self,
                      self.hasDeferredStopMenuRefresh,
                      self.hasDeferredStoppedRecordingState == false
                else { return }
                self.hasDeferredStopMenuRefresh = false
                self.updateMenu()
            }
            .store(in: &self.cancellables)

        // Subscribe to partial transcription updates for streaming preview
        asrService.$partialTranscription
            .receive(on: DispatchQueue.main)
            .sink { [weak self] newText in
                guard self != nil else { return }
                if NotchOverlayManager.shared.shouldShowOrTrackLivePreviewText {
                    NotchOverlayManager.shared.updateTranscriptionText(newText)
                }
            }
            .store(in: &self.cancellables)
    }

    func configure(meetingCoordinator: MeetingSessionCoordinator) {
        guard self.meetingCoordinator !== meetingCoordinator else {
            self.applyMeetingPresentation(
                state: meetingCoordinator.state,
                activeSession: meetingCoordinator.activeSession,
                latestCompletedSession: meetingCoordinator.latestCompletedSession
            )
            return
        }

        self.meetingCancellables.removeAll()
        self.meetingCoordinator = meetingCoordinator
        self.stopMeetingRecordingHandler = { [weak meetingCoordinator] in
            guard let meetingCoordinator else { return }
            Task { @MainActor in
                do {
                    _ = try await meetingCoordinator.stopAndTranscribe()
                } catch {
                    DebugLogger.shared.error(
                        "Menu action: Stop meeting recording failed: \(error.localizedDescription)",
                        source: "MenuBarManager"
                    )
                }
            }
        }

        Publishers.CombineLatest3(
            meetingCoordinator.$state,
            meetingCoordinator.$activeSession,
            meetingCoordinator.$latestCompletedSession
        )
        .receive(on: DispatchQueue.main)
        .sink { [weak self] state, activeSession, latestCompletedSession in
            self?.applyMeetingPresentation(
                state: state,
                activeSession: activeSession,
                latestCompletedSession: latestCompletedSession
            )
        }
        .store(in: &self.meetingCancellables)
    }

    private func applyMeetingPresentation(
        state: MeetingCoordinatorState,
        activeSession: MeetingSession?,
        latestCompletedSession: MeetingSession?
    ) {
        let previousActivity = self.meetingMenuPresentation.activity
        switch state {
        case .recording, .recordingDegraded:
            break
        default:
            self.meetingStopRequested = false
        }

        switch state {
        case .idle:
            self.meetingMenuPresentation = MeetingMenuPresentation()
        case .preparing:
            self.meetingStartError = nil
            self.meetingMenuPresentation = MeetingMenuPresentation(
                activity: .preparing,
                sourceName: activeSession?.capturedApplication?.displayName,
                startedAt: activeSession?.startedAt
            )
        case .recording, .recordingDegraded:
            self.meetingMenuPresentation = MeetingMenuPresentation(
                activity: .recording,
                sourceName: activeSession?.capturedApplication?.displayName ?? "In-room meeting",
                startedAt: activeSession?.startedAt
            )
        case .stopping:
            self.meetingMenuPresentation = MeetingMenuPresentation(
                activity: .stopping,
                sourceName: activeSession?.capturedApplication?.displayName ?? "In-room meeting",
                startedAt: activeSession?.startedAt
            )
        case .processing:
            self.meetingMenuPresentation = MeetingMenuPresentation(
                activity: .processing,
                sourceName: activeSession?.capturedApplication?.displayName,
                startedAt: nil
            )
        case .completed:
            self.meetingMenuPresentation = MeetingMenuPresentation(
                activity: .completed,
                sourceName: latestCompletedSession?.capturedApplication?.displayName,
                startedAt: nil
            )
        case .interrupted:
            self.meetingMenuPresentation = MeetingMenuPresentation(
                activity: .interrupted,
                sourceName: activeSession?.capturedApplication?.displayName,
                startedAt: activeSession?.startedAt,
                attentionStatus: Self.interruptionStatus(for: activeSession)
            )
        case let .failed(_, failure):
            self.meetingMenuPresentation = MeetingMenuPresentation(
                activity: .failed,
                sourceName: activeSession?.capturedApplication?.displayName,
                startedAt: activeSession?.startedAt,
                attentionStatus: Self.failureStatus(for: activeSession, failure: failure)
            )
        }

        if self.meetingMenuPresentation.activity != previousActivity {
            self.announceMeetingActivity(self.meetingMenuPresentation)
        }

        self.updateMenuBarIcon()
        self.updateMenu()
    }

    private func announceMeetingActivity(_ presentation: MeetingMenuPresentation) {
        let announcement: String?
        switch presentation.activity {
        case .inactive:
            announcement = nil
        case .preparing:
            announcement = "Starting meeting recording"
        case .recording:
            announcement = "Meeting recording started"
        case .stopping:
            announcement = "Stopping meeting recording"
        case .processing:
            announcement = "Meeting transcription started"
        case .interrupted:
            announcement = presentation.attentionStatus ?? "Meeting recording interrupted"
        case .failed:
            announcement = presentation.attentionStatus ?? "Meeting setup failed"
        case .completed:
            announcement = "Meeting transcription complete"
        }
        guard let announcement else { return }
        AccessibilityNotification.Announcement(announcement).post()
    }

    private static func interruptionStatus(for session: MeetingSession?) -> String {
        guard let session else { return "Meeting setup interrupted" }
        if session.endedAt != nil, !session.processingAttempts.isEmpty {
            return "Meeting transcription interrupted"
        }
        return "Meeting recording interrupted"
    }

    private static func failureStatus(
        for session: MeetingSession?,
        failure: MeetingSessionFailure
    ) -> String {
        if failure.domain == .processing {
            return "Meeting transcription failed"
        }
        let hasRecoverableAudio = session.map { session in
            session.endedAt != nil && session.audioTracks.contains { track in
                track.chunks.contains {
                    $0.finalizationState == .finalized && $0.byteCount > 0
                }
            }
        } ?? false
        return hasRecoverableAudio ? "Meeting recording failed" : "Meeting setup failed"
    }

    private func handleOverlayState(isRunning: Bool, asrService: ASRService) {
        self.overlayBench("handle_state isRunning=\(isRunning) overlayVisible=\(self.overlayVisible) processing=\(self.isProcessingActive) mode=\(self.currentOverlayMode.rawValue)")

        // Dictionary training owns its recording controls, so showing the
        // regular dictation notch here would create two competing overlays.
        if asrService.isDictionaryTrainingCaptureActive {
            self.pendingShowOperation?.cancel()
            self.pendingShowOperation = nil
            if self.overlayVisible {
                self.overlayVisible = false
                NotchOverlayManager.shared.hide()
            }
            return
        }

        // Don't hide the overlay while AI processing is active.
        // Without this, the notch can disappear during the short "Refining..." phase because
        // `isRunning` becomes false before post-processing completes.
        if !isRunning, self.isProcessingActive {
            self.overlayBench("handle_state_return reason=processing_active")
            return
        }

        // Prevent rapid state changes that could cause cycles
        guard self.overlayVisible != isRunning else {
            self.overlayBench("handle_state_return reason=visibility_unchanged")
            return
        }

        if isRunning {
            // Cancel any pending hide operation
            self.pendingHideOperation?.cancel()
            self.pendingHideOperation = nil

            self.overlayVisible = true
            self.overlayBench("show_request mode=\(self.currentOverlayMode.rawValue)")

            // If expanded command output is showing, check if we should keep it or close it
            if NotchOverlayManager.shared.isCommandOutputExpanded {
                // Only keep expanded notch if this is a command mode recording (follow-up)
                // For other modes (dictation, rewrite), close it and show regular notch
                if self.currentOverlayMode == .command, NotchOverlayManager.shared.supportsCommandNotchUI {
                    // Enable recording visualization in the expanded notch
                    NotchContentState.shared.setRecordingInExpandedMode(true)

                    // Subscribe to audio levels and forward to expanded notch
                    self.expandedModeAudioSubscription = asrService.audioLevelPublisher
                        .receive(on: DispatchQueue.main)
                        .sink { level in
                            NotchContentState.shared.updateExpandedModeAudioLevel(level)
                        }

                    self.pendingShowOperation = nil
                    return
                } else {
                    // Close expanded command notch to transition to regular notch
                    NotchOverlayManager.shared.hideExpandedCommandOutput()
                }
            }

            let showItem = DispatchWorkItem { [weak self] in
                guard let self = self, self.overlayVisible else { return }

                // Double-check expanded notch isn't showing (could have changed during delay)
                // But only block if we're in command mode
                if NotchOverlayManager.shared.isCommandOutputExpanded,
                   self.currentOverlayMode == .command,
                   NotchOverlayManager.shared.supportsCommandNotchUI
                {
                    self.pendingShowOperation = nil
                    return
                }

                // Show notch overlay
                self.overlayBench("show_workitem_execute mode=\(self.currentOverlayMode.rawValue)")
                NotchOverlayManager.shared.show(
                    audioLevelPublisher: asrService.audioLevelPublisher,
                    mode: self.currentOverlayMode
                )
                self.overlayBench("show_workitem_return mode=\(self.currentOverlayMode.rawValue)")

                self.pendingShowOperation = nil
            }
            self.pendingShowOperation = showItem
            DispatchQueue.main.async(execute: showItem)
        } else {
            // Cancel any pending show operation
            self.pendingShowOperation?.cancel()
            self.pendingShowOperation = nil

            self.overlayVisible = false
            self.overlayBench("hide_request delayMs=30")

            // If expanded command output is showing, don't hide it - let it stay visible
            if NotchOverlayManager.shared.isCommandOutputExpanded {
                // Stop recording visualization in expanded notch
                NotchContentState.shared.setRecordingInExpandedMode(false)
                self.expandedModeAudioSubscription?.cancel()
                self.expandedModeAudioSubscription = nil

                self.pendingHideOperation = nil
                return
            }

            let hideItem = DispatchWorkItem { [weak self] in
                guard let self = self, !self.overlayVisible else { return }

                // Don't hide if expanded command output is now showing
                if NotchOverlayManager.shared.isCommandOutputExpanded {
                    self.pendingHideOperation = nil
                    return
                }

                // Hide notch overlay
                self.overlayBench("hide_workitem_execute")
                NotchOverlayManager.shared.hide()
                self.overlayBench("hide_workitem_return")

                self.pendingHideOperation = nil
            }
            self.pendingHideOperation = hideItem
            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(30), execute: hideItem)
        }
    }

    /// A verified non-landing paste re-presents the overlay in its failure
    /// state so the transcript can be copied.
    func showPasteNotLandedFailure(transcript: String, verificationID: UInt64, postedAt: TimeInterval) {
        guard PasteRecoveryPresentationPolicy.shared.claim(
            verificationID,
            alertsEnabled: SettingsStore.shared.showPasteCheckAlerts,
            isBusy: self.overlayVisible || self.isProcessingActive || self.asrService?.isRunning == true,
            userActed: PasteVerifier.userActedAfterPaste(secondsSinceLastInput: PasteVerifier.secondsSinceLastUserInput(), secondsSincePaste: ProcessInfo.processInfo.systemUptime - postedAt)
        ) else { return }
        DeliveryFailureOverlayController.shared.show(kind: .pasteNotLanded, transcript: transcript)
    }

    func showRecordingOverlayImmediately() {
        AutomaticDictionaryCorrectionTracker.shared.cancel()

        guard let asrService else {
            self.overlayBench("instant_show_return reason=no_asr_service")
            return
        }

        PasteRecoveryPresentationPolicy.shared.beginDelivery()

        self.pendingHideOperation?.cancel()
        self.pendingHideOperation = nil
        self.pendingShowOperation?.cancel()
        self.pendingShowOperation = nil

        guard !self.overlayVisible else {
            self.overlayBench("instant_show_return reason=already_visible")
            return
        }

        self.overlayVisible = true
        DeliveryFailureOverlayController.shared.hide()
        self.overlayBench("instant_show_request mode=\(self.currentOverlayMode.rawValue)")

        if NotchOverlayManager.shared.isCommandOutputExpanded {
            if self.currentOverlayMode == .command, NotchOverlayManager.shared.supportsCommandNotchUI {
                NotchContentState.shared.setRecordingInExpandedMode(true)
                self.expandedModeAudioSubscription = asrService.audioLevelPublisher
                    .receive(on: DispatchQueue.main)
                    .sink { level in
                        NotchContentState.shared.updateExpandedModeAudioLevel(level)
                    }
                return
            }
            NotchOverlayManager.shared.hideExpandedCommandOutput()
        }

        self.overlayBench("show_workitem_execute mode=\(self.currentOverlayMode.rawValue)")
        NotchOverlayManager.shared.show(
            audioLevelPublisher: asrService.audioLevelPublisher,
            mode: self.currentOverlayMode
        )
        self.overlayBench("show_workitem_return mode=\(self.currentOverlayMode.rawValue)")
    }

    func hideRecordingOverlayImmediately(reason: String) {
        self.pendingShowOperation?.cancel()
        self.pendingShowOperation = nil
        self.pendingHideOperation?.cancel()
        self.pendingHideOperation = nil

        guard !self.isProcessingActive else {
            self.overlayBench("instant_hide_return reason=\(reason) processing_active")
            return
        }

        guard self.overlayVisible else {
            self.overlayBench("instant_hide_return reason=\(reason) already_hidden")
            return
        }

        self.overlayVisible = false
        self.overlayBench("instant_hide_request reason=\(reason)")

        if NotchOverlayManager.shared.isCommandOutputExpanded {
            NotchContentState.shared.setRecordingInExpandedMode(false)
            self.expandedModeAudioSubscription?.cancel()
            self.expandedModeAudioSubscription = nil
            self.overlayBench("instant_hide_return reason=expanded_command_output")
            return
        }

        NotchOverlayManager.shared.hide()
        self.overlayBench("instant_hide_return")
    }

    // MARK: - Public API for overlay management

    func updateOverlayTranscription(_ text: String) {
        NotchOverlayManager.shared.updateTranscriptionText(text)
    }

    func setOverlayMode(_ mode: OverlayMode) {
        self.overlayBench("set_mode mode=\(mode.rawValue)")
        self.currentOverlayMode = mode
        NotchOverlayManager.shared.setMode(mode)
    }

    /// Keeps the recording overlay owned by the active pipeline without
    /// publishing processing UI. The latency-critical stop path uses this so
    /// SwiftUI work cannot queue ahead of final transcription.
    func reserveProcessingOverlay() {
        self.overlayBench(
            "reserve_processing overlayVisible=\(self.overlayVisible) active=\(self.isProcessingActive)"
        )
        self.isProcessingActive = true
        NotchOverlayManager.shared.freezeForStop()
        // Diagnostics only: three Accessibility round-trips on the stop path
        // are not worth paying in Release just to audit the focused element.
        if DebugLogger.diagnosticsEnabled {
            let assessStartedAt = ProcessInfo.processInfo.systemUptime
            let assessment = DeliveryTargetAssessment.assessFocusedElement()
            DebugLogger.shared.info(
                "FOCUS_ASSESS at=stop \(assessment.logDescription) " +
                    "frontApp=\(NSWorkspace.shared.frontmostApplication?.bundleIdentifier ?? "nil") " +
                    "elapsedUs=\(Int((ProcessInfo.processInfo.systemUptime - assessStartedAt) * 1_000_000))",
                source: "TypingService"
            )
        }
        self.pendingProcessingShowOperation?.cancel()
        self.pendingProcessingShowOperation = nil
        self.pendingHideOperation?.cancel()
        self.pendingHideOperation = nil
        self.overlayVisible = true
    }

    func setProcessing(_ processing: Bool) {
        self.overlayBench("set_processing_request processing=\(processing) overlayVisible=\(self.overlayVisible) active=\(self.isProcessingActive)")

        if processing {
            self.reserveProcessingOverlay()

            let showItem = DispatchWorkItem { [weak self] in
                guard let self = self, self.isProcessingActive else { return }
                self.overlayBench("processing_show_workitem_execute delayMs=0")
                NotchOverlayManager.shared.setProcessing(true)
                self.overlayBench("processing_show_workitem_return")
                self.pendingProcessingShowOperation = nil
            }
            self.pendingProcessingShowOperation = showItem
            DispatchQueue.main.asyncAfter(deadline: .now() + self.processingVisualDelay, execute: showItem)
        } else {
            defer { self.flushDeferredStoppedRecordingState() }
            self.isProcessingActive = false
            self.pendingProcessingShowOperation?.cancel()
            self.pendingProcessingShowOperation = nil
            // When processing ends, schedule the hide (unless expanded output is showing)
            self.overlayVisible = false

            // If expanded command output is showing, don't hide it
            if NotchOverlayManager.shared.isCommandOutputExpanded {
                self.pendingHideOperation = nil
                NotchOverlayManager.shared.setProcessing(processing)
                self.overlayBench("set_processing_return reason=expanded_command_output")
                return
            }

            let hideItem = DispatchWorkItem { [weak self] in
                guard let self = self, !self.overlayVisible else { return }

                // Don't hide if expanded command output is now showing
                if NotchOverlayManager.shared.isCommandOutputExpanded {
                    self.pendingHideOperation = nil
                    return
                }

                self.overlayBench("processing_hide_workitem_execute delayMs=80")
                NotchOverlayManager.shared.hide()
                self.overlayBench("processing_hide_workitem_return")
                self.pendingHideOperation = nil
            }
            self.pendingHideOperation = hideItem
            DispatchQueue.main.asyncAfter(deadline: .now() + self.processingHideDelay, execute: hideItem)
            NotchOverlayManager.shared.setProcessing(false)
            self.overlayBench("processing_forwarded processing=false hideDelayMs=80")
            return
        }
    }

    /// Removes the completed recording overlay immediately unless the optional
    /// closing transition is enabled.
    func beginProcessingCompletionAndHideOverlay() {
        let startedAt = ProcessInfo.processInfo.systemUptime
        self.prepareForProcessingCompletion()
        self.overlayBench("finish_hide_request closingAnimation=\(SettingsStore.shared.overlayClosingAnimationEnabled)")
        NotchOverlayManager.shared.hide()
        let windowHideReturnedAt = ProcessInfo.processInfo.systemUptime
        // The status item refresh is a WindowServer fence; keep it out of the
        // transaction that removes the overlay.
        CATransaction.setCompletionBlock { [weak self] in
            MainActor.assumeIsolated {
                let refreshStartedAt = ProcessInfo.processInfo.systemUptime
                self?.flushDeferredStoppedRecordingState()
                DebugLogger.shared.debug(
                    "HIDE_NOW postCommitMenuRefreshUs=\(Int((ProcessInfo.processInfo.systemUptime - refreshStartedAt) * 1_000_000))",
                    source: "StopTiming"
                )
            }
        }
        DebugLogger.shared.debug(
            "HIDE_NOW windowHideUs=\(Int((windowHideReturnedAt - startedAt) * 1_000_000)) " +
                "menuRefreshUs=\(Int((ProcessInfo.processInfo.systemUptime - windowHideReturnedAt) * 1_000_000))",
            source: "StopTiming"
        )
        DebugLogger.shared.debug(
            "STOP_TRACE phase=hide_dispatched closingAnimation=\(SettingsStore.shared.overlayClosingAnimationEnabled) elapsedMs=\(Int((ProcessInfo.processInfo.systemUptime - startedAt) * 1000))",
            source: "StopTiming"
        )
        self.overlayBench(
            "finish_hide_dispatched elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))"
        )
    }

    /// Ends processing and waits for the recording overlay's exit transition.
    /// Use only when the caller must know the overlay has fully disappeared.
    func finishProcessingAndHideOverlay() async {
        guard SettingsStore.shared.overlayClosingAnimationEnabled else {
            self.beginProcessingCompletionAndHideOverlay()
            return
        }
        let startedAt = ProcessInfo.processInfo.systemUptime
        self.prepareForProcessingCompletion()
        DebugLogger.shared.debug("HIDE_TRACE phase=completion_prepared elapsedUs=\(Int((ProcessInfo.processInfo.systemUptime - startedAt) * 1_000_000))", source: "StopTiming")

        NotchOverlayManager.shared.setProcessing(false)
        DebugLogger.shared.debug("HIDE_TRACE phase=processing_cleared elapsedUs=\(Int((ProcessInfo.processInfo.systemUptime - startedAt) * 1_000_000))", source: "StopTiming")
        self.overlayBench("finish_hide_request mode=awaited")
        let hideOutcome = await NotchOverlayManager.shared.hideAndWait()
        let hiddenAt = ProcessInfo.processInfo.systemUptime
        self.flushDeferredStoppedRecordingState()
        DebugLogger.shared.debug(
            "STOP_TRACE phase=overlay_hidden hideMs=\(Int((hiddenAt - startedAt) * 1000)) menuRefreshMs=\(Int((ProcessInfo.processInfo.systemUptime - hiddenAt) * 1000))",
            source: "StopTiming"
        )
        self.overlayBench(
            "finish_hide_complete outcome=\(hideOutcome) elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))"
        )
    }

    /// Ends processing without dismissing an actionable overlay, such as the
    /// AI fallback state that offers reprocessing and settings actions.
    func finishProcessingKeepingOverlayVisible() {
        // A delivery failure must always be visible. The transient card is
        // used when the dictation overlay is already gone (the no-AI fast
        // path hides it before delivery), when the failure needs the
        // Accessibility settings action, or for the no-text-field case.
        let state = NotchContentState.shared
        if state.isTextDeliveryFailureVisible,
           let failure = state.textDeliveryFailure,
           let kind = DeliveryFailureOverlayController.Kind(failure: failure),
           Self.usesTransientFailureCard(kind: kind, overlayVisible: NotchOverlayManager.shared.isOverlayVisible)
        {
            let transcript = state.textDeliveryFailureTranscript
            state.clearTextDeliveryFailure()
            self.beginProcessingCompletionAndHideOverlay()
            DeliveryFailureOverlayController.shared.show(kind: kind, transcript: transcript)
            return
        }
        self.cancelPendingProcessingCompletionOperations()
        self.isProcessingActive = false
        // Keep the physical overlay visible, but release recording/processing
        // ownership so the next recording can establish a fresh lifecycle.
        self.overlayVisible = false
        NotchOverlayManager.shared.setProcessing(false)
        self.flushDeferredStoppedRecordingState()
        self.overlayBench("finish_keep_visible")
    }

    nonisolated static func usesTransientFailureCard(kind: DeliveryFailureOverlayController.Kind, overlayVisible: Bool) -> Bool {
        kind == .noEditableTarget || kind.offersAccessibilitySettings || !overlayVisible
    }

    /// Recording-state observers rebuild AppKit/SwiftUI surfaces. Hold that work
    /// while a fast ASR/AI result is in flight, then publish it after output.
    /// Slow paths call this when their processing status becomes visible.
    func flushDeferredStoppedRecordingState() {
        guard self.hasDeferredStoppedRecordingState else { return }
        let startedAt = ProcessInfo.processInfo.systemUptime
        self.hasDeferredStoppedRecordingState = false
        self.hasDeferredStopMenuRefresh = false
        self.isRecording = false
        self.updateMenuBarIcon()
        self.updateMenu()
        self.overlayBench(
            "recording_state_flushed elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))"
        )
    }

    private func cancelPendingProcessingCompletionOperations() {
        self.pendingProcessingShowOperation?.cancel()
        self.pendingProcessingShowOperation = nil
        self.pendingHideOperation?.cancel()
        self.pendingHideOperation = nil
        self.pendingShowOperation?.cancel()
        self.pendingShowOperation = nil
    }

    private func prepareForProcessingCompletion() {
        self.cancelPendingProcessingCompletionOperations()
        self.isProcessingActive = false
        self.overlayVisible = false
    }

    private func overlayBench(_ message: @autoclosure () -> String) {
        DebugLogger.shared.benchmark("OVERLAY_BENCH", message: "manager \(message())", source: "OverlayBenchmark")
    }

    private func setupMenuBarSafely() {
        do {
            try self.setupMenuBar()
            self.isSetup = true
        } catch {
            // If setup fails, retry after delay
            DebugLogger.shared.error("MenuBar setup failed, retrying: \(error)", source: "MenuBarManager")
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
                self?.setupMenuBarSafely()
            }
        }
    }

    private func setupMenuBar() throws {
        // Ensure we're not already set up
        guard !self.isSetup else { return }

        // Create status item with error handling
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)

        guard let statusItem = statusItem else {
            throw NSError(domain: "MenuBarManager", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to create status item"])
        }

        // Set initial icon
        self.updateMenuBarIcon()

        // Create menu
        self.menu = NSMenu()
        self.menu?.autoenablesItems = false
        self.menu?.delegate = self
        statusItem.menu = self.menu

        self.updateMenu()
    }

    private func updateMenuBarIcon() {
        guard let statusItem = statusItem, statusItem.button?.image == nil else { return }

        // The template icon is identical in every state. Assigning a fresh
        // NSImage on each recording change forced a status item redraw plus a
        // WindowServer fence (about 200 ms measured) on every start and stop.
        if let image = NSImage(named: "MenuBarIcon") {
            switch self.meetingMenuPresentation.activity {
            case .recording, .stopping:
                statusItem.button?.image = self.menuBarActivityImage(baseImage: image, activity: .recording)
                statusItem.button?.setAccessibilityLabel(
                    self.meetingMenuPresentation.activity == .stopping
                        ? "FluidVoice, stopping meeting recording"
                        : "FluidVoice, meeting recording"
                )
            case .preparing, .processing:
                statusItem.button?.image = self.menuBarActivityImage(baseImage: image, activity: .processing)
                statusItem.button?.setAccessibilityLabel(
                    self.meetingMenuPresentation.activity == .preparing
                        ? "FluidVoice, starting meeting recording"
                        : "FluidVoice, transcribing meeting"
                )
            case .interrupted, .failed:
                statusItem.button?.image = self.menuBarActivityImage(baseImage: image, activity: .interrupted)
                let status = self.meetingMenuPresentation.attentionStatus ?? "Meeting needs attention"
                statusItem.button?.setAccessibilityLabel("FluidVoice, \(status.lowercased())")
            case .inactive:
                image.isTemplate = true
                statusItem.button?.image = image
                statusItem.button?.setAccessibilityLabel("FluidVoice")
            case .completed:
                image.isTemplate = true
                statusItem.button?.image = image
                statusItem.button?.setAccessibilityLabel("FluidVoice, meeting transcription complete")
            }
        }
    }

    private func menuBarActivityImage(baseImage: NSImage, activity: MeetingMenuActivity) -> NSImage {
        let image = NSImage(size: NSSize(width: 18, height: 18), flipped: false) { _ in
            baseImage.draw(
                in: NSRect(x: 0, y: 1, width: 15, height: 15),
                from: .zero,
                operation: .sourceOver,
                fraction: 1
            )

            let badgeRect = NSRect(x: 10, y: 0, width: 8, height: 8)
            let badgePath = NSBezierPath()
            switch activity {
            case .recording, .stopping:
                badgePath.appendOval(in: badgeRect)
                badgePath.appendRoundedRect(
                    NSRect(x: 12.25, y: 2.25, width: 3.5, height: 3.5),
                    xRadius: 0.7,
                    yRadius: 0.7
                )
            case .preparing, .processing:
                badgePath.move(to: NSPoint(x: badgeRect.midX, y: badgeRect.maxY))
                badgePath.line(to: NSPoint(x: badgeRect.maxX, y: badgeRect.midY))
                badgePath.line(to: NSPoint(x: badgeRect.midX, y: badgeRect.minY))
                badgePath.line(to: NSPoint(x: badgeRect.minX, y: badgeRect.midY))
                badgePath.close()
                badgePath.appendOval(in: NSRect(x: 12.5, y: 2.5, width: 3, height: 3))
            case .interrupted, .failed:
                badgePath.move(to: NSPoint(x: badgeRect.midX, y: badgeRect.maxY))
                badgePath.line(to: NSPoint(x: badgeRect.maxX, y: badgeRect.minY))
                badgePath.line(to: NSPoint(x: badgeRect.minX, y: badgeRect.minY))
                badgePath.close()
                badgePath.appendOval(in: NSRect(x: 13, y: 2.2, width: 2, height: 2))
            case .inactive, .completed:
                break
            }
            badgePath.windingRule = .evenOdd
            NSColor.black.setFill()
            badgePath.fill()
            return true
        }
        image.isTemplate = true
        image.accessibilityDescription = "FluidVoice meeting status"
        return image
    }

    private func buildMenuStructure() {
        guard let menu = menu else { return }

        menu.removeAllItems()

        let startMeetingItem = NSMenuItem(
            title: "Start Meeting Recording",
            action: #selector(startMeetingRecording),
            keyEquivalent: ""
        )
        startMeetingItem.target = self
        menu.addItem(startMeetingItem)
        self.startMeetingRecordingMenuItem = startMeetingItem

        let stopMeetingItem = NSMenuItem(
            title: "Stop Meeting Recording",
            action: #selector(stopMeetingRecording),
            keyEquivalent: ""
        )
        stopMeetingItem.target = self
        menu.addItem(stopMeetingItem)
        self.stopMeetingRecordingMenuItem = stopMeetingItem

        let meetingStatusItem = NSMenuItem(title: "", action: nil, keyEquivalent: "")
        meetingStatusItem.isEnabled = false
        menu.addItem(meetingStatusItem)
        self.meetingStatusMenuItem = meetingStatusItem

        let openMeetingItem = NSMenuItem(
            title: "Open FluidMeet",
            action: #selector(openMeetingTranscription),
            keyEquivalent: ""
        )
        openMeetingItem.target = self
        menu.addItem(openMeetingItem)
        self.openMeetingTranscriptionMenuItem = openMeetingItem

        let meetingSeparator = NSMenuItem.separator()
        menu.addItem(meetingSeparator)
        self.meetingMenuSeparator = meetingSeparator

        // Status indicator with hotkey info
        self.statusMenuItem = NSMenuItem(title: "", action: nil, keyEquivalent: "")
        self.statusMenuItem?.isEnabled = false
        if let statusItem = statusMenuItem {
            menu.addItem(statusItem)
        }

        let copyLastTranscriptItem = NSMenuItem(
            title: "Copy Last Transcript",
            action: #selector(copyLastTranscript(_:)),
            keyEquivalent: ""
        )
        copyLastTranscriptItem.target = self
        menu.addItem(copyLastTranscriptItem)
        self.copyLastTranscriptMenuItem = copyLastTranscriptItem

        menu.addItem(.separator())

        // Open Main Window
        let openItem = NSMenuItem(title: "Open Fluid Voice", action: #selector(openMainWindow), keyEquivalent: "")
        openItem.target = self
        menu.addItem(openItem)

        // Preferences
        let preferencesItem = NSMenuItem(title: "Settings...", action: #selector(openPreferences), keyEquivalent: ",")
        preferencesItem.target = self
        preferencesItem.keyEquivalentModifierMask = [.command]
        menu.addItem(preferencesItem)

        let customDictionaryItem = NSMenuItem(
            title: "Custom Dictionary",
            action: #selector(openCustomDictionary),
            keyEquivalent: ""
        )
        customDictionaryItem.target = self
        menu.addItem(customDictionaryItem)

        let microphoneSubmenu = NSMenu(title: "Microphone")
        let microphoneMenuItem = NSMenuItem(title: "Microphone", action: nil, keyEquivalent: "")
        microphoneMenuItem.submenu = microphoneSubmenu
        menu.addItem(microphoneMenuItem)
        self.microphoneMenuItem = microphoneMenuItem
        self.microphoneSubmenu = microphoneSubmenu

        // Check for Updates
        let updateItem = NSMenuItem(
            title: "Check for Updates...",
            action: #selector(checkForUpdates(_:)),
            keyEquivalent: ""
        )
        updateItem.target = self
        menu.addItem(updateItem)

        menu.addItem(.separator())

        let rollbackMenuItem = NSMenuItem(
            title: "Rollback to Previous Version...",
            action: #selector(rollbackToPreviousVersion(_:)),
            keyEquivalent: ""
        )
        rollbackMenuItem.target = self
        rollbackMenuItem.isEnabled = SimpleUpdater.shared.hasRollbackBackup()
        menu.addItem(rollbackMenuItem)
        self.rollbackMenuItem = rollbackMenuItem

        menu.addItem(.separator())

        // Quit
        let quitItem = NSMenuItem(
            title: "Quit Fluid Voice",
            action: #selector(NSApplication.terminate(_:)),
            keyEquivalent: "q"
        )
        quitItem.target = NSApp
        menu.addItem(quitItem)

        // Now update the text content
        self.updateMenuItemsText()
    }

    private func updateMenu() {
        // If menu structure hasn't been built yet, build it
        if self.statusMenuItem == nil {
            self.buildMenuStructure()
        } else {
            // Just update the text of existing items
            self.updateMenuItemsText()
        }
    }

    private func updateMenuItemsText() {
        self.updateMeetingMenuItemsText()

        // Update status text with hotkey info
        let hotkeyDisplay = SettingsStore.shared.primaryDictationShortcutDisplayString
        let hotkeyInfo = hotkeyDisplay.isEmpty ? "" : " (\(hotkeyDisplay))"
        let statusTitle: String = switch self.meetingMenuPresentation.activity {
        case .preparing:
            "Starting Meeting Recording…"
        case .recording:
            "Meeting Recording in Progress"
        case .stopping:
            "Stopping Meeting Recording…"
        case .processing:
            "Transcribing Meeting…"
        case .interrupted, .failed:
            self.meetingMenuPresentation.attentionStatus ?? "Meeting Needs Attention"
        case .inactive, .completed:
            self.isRecording ? "Recording...\(hotkeyInfo)" : "Ready to Record\(hotkeyInfo)"
        }
        self.statusMenuItem?.title = statusTitle
        self.copyLastTranscriptMenuItem?.isEnabled = self.canCopyLastTranscript
        self.microphoneMenuItem?.isEnabled = true

        // Update rollback availability text
        self.rollbackMenuItem?.isEnabled = SimpleUpdater.shared.hasRollbackBackup()
    }

    private func updateMeetingMenuItemsText(now: Date = Date()) {
        guard SettingsStore.shared.fluidMeetEnabled else {
            for item in [
                self.startMeetingRecordingMenuItem,
                self.stopMeetingRecordingMenuItem,
                self.meetingStatusMenuItem,
                self.openMeetingTranscriptionMenuItem,
                self.meetingMenuSeparator,
            ] {
                item?.isHidden = true
            }
            return
        }
        let activity = self.meetingMenuPresentation.activity
        let hasMeetingStatus = activity != .inactive || self.meetingStartError != nil
        let isRecording = activity == .recording
        let isStopping = activity == .stopping || self.meetingStopRequested

        self.startMeetingRecordingMenuItem?.isHidden = !self.canStartMeetingRecording && !self.meetingStartRequested
        self.startMeetingRecordingMenuItem?.isEnabled = self.canStartMeetingRecording &&
            !self.meetingStartRequested && self.meetingCoordinator != nil
        self.startMeetingRecordingMenuItem?.title = self.meetingStartRequested
            ? "Starting Meeting Recording…" : "Start Meeting Recording"
        self.stopMeetingRecordingMenuItem?.isHidden = !isRecording && !isStopping
        self.stopMeetingRecordingMenuItem?.isEnabled = isRecording &&
            !self.meetingStopRequested &&
            self.stopMeetingRecordingHandler != nil
        self.stopMeetingRecordingMenuItem?.title = isStopping
            ? "Stopping Meeting Recording…"
            : "Stop Meeting Recording"
        self.meetingStatusMenuItem?.isHidden = !hasMeetingStatus || activity == .completed
        self.openMeetingTranscriptionMenuItem?.isHidden = !hasMeetingStatus
        self.meetingMenuSeparator?.isHidden = false

        switch activity {
        case .inactive:
            self.openMeetingTranscriptionMenuItem?.title = "Open FluidMeet"
        case .preparing:
            self.meetingStatusMenuItem?.title = "Starting meeting recording…"
            self.openMeetingTranscriptionMenuItem?.title = "Open FluidMeet"
        case .recording:
            let source = self.meetingMenuPresentation.sourceName ?? "Meeting"
            let elapsed = self.meetingMenuPresentation.startedAt.map { Self.elapsedText(now.timeIntervalSince($0)) } ?? "0:00"
            self.meetingStatusMenuItem?.title = "Recording \(source) · \(elapsed)"
            self.openMeetingTranscriptionMenuItem?.title = "Open FluidMeet"
        case .stopping:
            self.meetingStatusMenuItem?.title = "Finalizing meeting audio…"
            self.openMeetingTranscriptionMenuItem?.title = "Open FluidMeet"
        case .processing:
            self.meetingStatusMenuItem?.title = "Transcribing meeting…"
            self.openMeetingTranscriptionMenuItem?.title = "Open FluidMeet"
        case .interrupted:
            self.meetingStatusMenuItem?.title = self.meetingMenuPresentation.attentionStatus ?? "Recording interrupted"
            self.openMeetingTranscriptionMenuItem?.title = "Open FluidMeet"
        case .failed:
            self.meetingStatusMenuItem?.title = self.meetingMenuPresentation.attentionStatus ?? "Meeting setup failed"
            self.openMeetingTranscriptionMenuItem?.title = "Open FluidMeet"
        case .completed:
            self.openMeetingTranscriptionMenuItem?.title = "Open Latest Meeting Transcript"
        }
        if let error = self.meetingStartError {
            self.meetingStatusMenuItem?.isHidden = false
            self.meetingStatusMenuItem?.title = "Could not start: \(error)"
            self.meetingStatusMenuItem?.toolTip = error
        } else {
            self.meetingStatusMenuItem?.toolTip = nil
        }
    }

    private static func elapsedText(_ duration: TimeInterval) -> String {
        let total = max(0, Int(duration.rounded(.down)))
        let hours = total / 3600
        let minutes = (total % 3600) / 60
        let seconds = total % 60
        if hours > 0 {
            return String(format: "%d:%02d:%02d", hours, minutes, seconds)
        }
        return String(format: "%d:%02d", minutes, seconds)
    }

    func menuWillOpen(_ menu: NSMenu) {
        if menu === self.menu {
            AnalyticsService.shared.recordAppActivity()
            self.updateMenuItemsText()
            self.refreshMicrophoneMenu()
        }
    }

    private func refreshMicrophoneMenu() {
        guard let submenu = self.microphoneSubmenu else { return }

        submenu.removeAllItems()
        let loadingItem = NSMenuItem(title: "Loading...", action: nil, keyEquivalent: "")
        loadingItem.isEnabled = false
        submenu.addItem(loadingItem)

        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            let inputDevices = AudioDevice.listInputDevicesRefreshingLiveness()
            let defaultInputUID = AudioDevice.getDefaultInputDevice()?.uid

            DispatchQueue.main.async { [weak self] in
                guard let self else { return }
                self.populateMicrophoneMenu(
                    inputDevices: inputDevices,
                    defaultInputUID: defaultInputUID
                )
            }
        }
    }

    private func populateMicrophoneMenu(inputDevices: [AudioDevice.Device], defaultInputUID: String?) {
        guard let submenu = self.microphoneSubmenu else { return }

        submenu.removeAllItems()

        guard !inputDevices.isEmpty else {
            let emptyItem = NSMenuItem(title: "No microphones found", action: nil, keyEquivalent: "")
            emptyItem.isEnabled = false
            submenu.addItem(emptyItem)
            return
        }

        let microphonePreferenceCoordinator = AppServices.shared.microphonePreferenceCoordinator
        let currentUID = microphonePreferenceCoordinator.reconcileMicrophoneSelection(
            availableInputs: inputDevices,
            defaultInputUID: defaultInputUID
        )?.uid

        guard SettingsStore.shared.microphonePriority.isEmpty == false else {
            let emptyItem = NSMenuItem(title: "No microphones in priority", action: nil, keyEquivalent: "")
            emptyItem.isEnabled = false
            submenu.addItem(emptyItem)
            return
        }

        let devicesByUID = Dictionary(
            inputDevices.map { ($0.uid, $0) },
            uniquingKeysWith: { current, _ in current }
        )
        for (index, entry) in SettingsStore.shared.microphonePriority.enumerated() {
            guard let device = devicesByUID[entry.uid],
                  microphonePreferenceCoordinator.isInputDeviceAvailable(device)
            else {
                let item = NSMenuItem(
                    title: "\(index + 1). \(entry.name) (Unavailable)",
                    action: nil,
                    keyEquivalent: ""
                )
                item.isEnabled = false
                submenu.addItem(item)
                continue
            }
            let title = "\(index + 1). \(device.name)"
            let item = NSMenuItem(title: title, action: #selector(selectMicrophone(_:)), keyEquivalent: "")
            item.target = self
            item.representedObject = device
            item.state = device.uid == currentUID ? .on : .off
            item.isEnabled = !self.isRecording
            submenu.addItem(item)
        }

        if self.isRecording {
            submenu.addItem(.separator())
            let recordingItem = NSMenuItem(title: "Unavailable while recording", action: nil, keyEquivalent: "")
            recordingItem.isEnabled = false
            submenu.addItem(recordingItem)
        }
    }

    private var canCopyLastTranscript: Bool {
        !self.isProcessingActive && TranscriptionHistoryStore.shared.latestClipboardText != nil
    }

    @objc private func copyLastTranscript(_ sender: Any?) {
        guard self.canCopyLastTranscript,
              let text = TranscriptionHistoryStore.shared.latestClipboardText
        else {
            DebugLogger.shared.info("Menu action: Copy last transcript requested but history is empty", source: "MenuBarManager")
            return
        }

        _ = ClipboardService.copyToClipboard(text)
        DebugLogger.shared.info("Menu action: Copied latest transcription to clipboard", source: "MenuBarManager")
    }

    @objc private func selectMicrophone(_ sender: NSMenuItem) {
        guard self.isRecording == false else { return }
        guard let device = sender.representedObject as? AudioDevice.Device else { return }

        SettingsStore.shared.recordInputDeviceSelection(device.uid, name: device.name)

        self.refreshMicrophoneMenu()
    }

    @objc private func checkForUpdates(_ sender: Any?) {
        DebugLogger.shared.info("🔎 Menu action: Check for Updates…", source: "MenuBarManager")

        SimpleUpdater.shared.checkForUpdatesManually()
    }

    @objc private func rollbackToPreviousVersion(_ sender: Any?) {
        let availableVersion = SimpleUpdater.shared.latestRollbackVersion() ?? ""
        guard !availableVersion.isEmpty else {
            let msg = NSAlert()
            msg.messageText = "No rollback backup found"
            msg.informativeText = "No previous version backup is available on this device."
            msg.alertStyle = .informational
            msg.addButton(withTitle: "Get Previous Builds")
            msg.addButton(withTitle: "Cancel")
            if msg.runModal() == .alertFirstButtonReturn {
                self.openPreviousBuildPicker()
            }
            return
        }

        let confirm = NSAlert()
        confirm.messageText = "Rollback to \(availableVersion)?"
        confirm.informativeText = "This will restore the backup and relaunch FluidVoice."
        confirm.alertStyle = .warning
        confirm.addButton(withTitle: "Rollback")
        confirm.addButton(withTitle: "Cancel")

        guard confirm.runModal() == .alertFirstButtonReturn else { return }

        Task { @MainActor in
            do {
                try await SimpleUpdater.shared.rollbackToLatestBackup()
                let success = NSAlert()
                success.messageText = "Rollback Successful"
                success.informativeText = "Rolled back to \(availableVersion). FluidVoice will relaunch shortly."
                success.alertStyle = .informational
                success.addButton(withTitle: "Report Bug")
                success.addButton(withTitle: "OK")
                let response = success.runModal()
                if response == .alertFirstButtonReturn {
                    self.openIssueReportingPage()
                }
            } catch {
                let fail = NSAlert()
                fail.messageText = "Rollback Failed"
                fail.informativeText = error.localizedDescription
                fail.alertStyle = .critical
                fail.addButton(withTitle: "OK")
                fail.runModal()
            }
        }
    }

    private func openIssueReportingPage() {
        guard let url = URL(string: "https://github.com/altic-dev/Fluid-oss/issues/new/choose") else { return }
        NSWorkspace.shared.open(url)
    }

    private func openPreviousBuildPicker() {
        Task { @MainActor in
            do {
                let options = try await SimpleUpdater.shared.fetchRecentReleaseBuildOptions(
                    owner: "altic-dev",
                    repo: "Fluid-oss",
                    limit: 3,
                    includePrerelease: SettingsStore.shared.betaReleasesEnabled
                )
                self.presentPreviousBuildPicker(options)
            } catch {
                self.openAllReleasesPage()
            }
        }
    }

    private func presentPreviousBuildPicker(_ options: [SimpleUpdater.ReleaseBuildOption]) {
        guard !options.isEmpty else {
            self.openAllReleasesPage()
            return
        }

        let picker = NSAlert()
        picker.messageText = "Download Previous Build"
        picker.informativeText = "Choose one of the latest release builds to install manually."
        picker.alertStyle = .informational

        for option in options {
            picker.addButton(withTitle: option.version)
        }
        picker.addButton(withTitle: "All Releases")
        picker.addButton(withTitle: "Cancel")

        let response = picker.runModal()
        let first = NSApplication.ModalResponse.alertFirstButtonReturn.rawValue
        let index = response.rawValue - first

        if index >= 0, index < options.count {
            NSWorkspace.shared.open(options[index].url)
            return
        }
        if index == options.count {
            self.openAllReleasesPage()
        }
    }

    private func openAllReleasesPage() {
        guard let url = URL(string: "https://github.com/altic-dev/Fluid-oss/releases") else { return }
        NSWorkspace.shared.open(url)
    }

    @objc private func openMainWindow() {
        // First, unhide the app if it's hidden
        if NSApp.isHidden {
            NSApp.unhide(nil)
        }

        // Activate the app and bring it to the front
        NSApp.activate(ignoringOtherApps: true)

        var mainWindows = NSApp.windows.filter(self.isFluidMainWindow)
        if let hostedWindow,
           mainWindows.contains(where: { $0 !== hostedWindow })
        {
            hostedWindow.close()
            self.hostedWindow = nil
            mainWindows = NSApp.windows.filter(self.isFluidMainWindow)
        }

        // Find an existing *non-minimized* primary window.
        // Important: avoid programmatic deminiaturize() — it creates internal window transform animations
        // (NSWindowTransformAnimation) that have been unstable on macOS 26.x for this app.
        if let window = mainWindows.first {
            self.ensureUsableMainWindow(window)
            window.animationBehavior = .none
            self.bringToFront(window)
            if let hostedWindow, window !== hostedWindow {
                self.hostedWindow = nil
            }
        } else if let window = hostedWindow, window.isReleasedWhenClosed == false {
            self.ensureUsableMainWindow(window)
            window.animationBehavior = .none
            self.bringToFront(window)
        } else {
            // If there is no suitable window (or it's minimized), create a fresh one.
            self.createAndShowMainWindow()
        }

        // Final attempt: ensure app is active and visible
        NSApp.activate(ignoringOtherApps: true)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) {
            NSApp.activate(ignoringOtherApps: true)
        }
    }

    func isFluidMainWindow(_ window: NSWindow) -> Bool {
        guard MainWindowIdentity.matches(window) else { return false }
        guard window.canBecomeKey else { return false }
        guard window.isMiniaturized == false else { return false }
        return true
    }

    @objc private func openPreferences() {
        self.openNavigationDestination(.settings)
    }

    @objc private func openCustomDictionary() {
        self.openNavigationDestination(.customDictionary)
    }

    @objc private func openMeetingTranscription() {
        self.openNavigationDestination(.meetingTranscription)
    }

    private var canStartMeetingRecording: Bool {
        switch self.meetingMenuPresentation.activity {
        case .inactive, .completed, .interrupted, .failed:
            return true
        case .preparing, .recording, .stopping, .processing:
            return false
        }
    }

    #if DEBUG
    func configureMeetingShortcutForTesting(state: MeetingCoordinatorState, onStop: @escaping () -> Void) {
        self.applyMeetingPresentation(state: state, activeSession: nil, latestCompletedSession: nil)
        self.stopMeetingRecordingHandler = onStop
    }
    #endif

    /// Reuse the menu's guarded actions; a meeting shortcut never starts dictation or navigates.
    func toggleMeetingRecordingFromShortcut(using operation: () async throws -> Void) async {
        guard SettingsStore.shared.fluidMeetEnabled, !self.meetingStartRequested else { return }
        if self.meetingMenuPresentation.activity == .recording {
            self.stopMeetingRecording()
            return
        }
        guard self.asrService?.activeExclusiveActivity == nil,
              self.asrService?.isRunningOrStarting != true else { return }
        await self.startMeetingRecordingInBackground(using: operation)
    }

    @objc private func startMeetingRecording() {
        Task { @MainActor in
            await self.startMeetingRecordingInBackground {
                MeetingRecordingSourcePromptController.shared.handleShortcut()
            }
        }
    }

    /// Keep source discovery and permission waits inside the duplicate-click guard.
    /// Errors stay in the menu; starting must never request main-window navigation.
    func startMeetingRecordingInBackground(using operation: () async throws -> Void) async {
        guard SettingsStore.shared.fluidMeetEnabled, self.canStartMeetingRecording, !self.meetingStartRequested else { return }
        self.meetingStartRequested = true
        self.meetingStartError = nil
        self.updateMeetingMenuItemsText()
        defer {
            self.meetingStartRequested = false
            self.updateMeetingMenuItemsText()
        }
        do {
            try await operation()
        } catch {
            self.meetingStartError = error.localizedDescription
            DebugLogger.shared.error("Menu action: Start meeting recording failed: \(error.localizedDescription)", source: "MenuBarManager")
            AccessibilityNotification.Announcement("Meeting recording could not start. \(error.localizedDescription)").post()
        }
    }

    @objc private func stopMeetingRecording() {
        guard self.meetingMenuPresentation.activity == .recording,
              !self.meetingStopRequested
        else {
            return
        }
        self.meetingStopRequested = true
        self.updateMeetingMenuItemsText()
        self.stopMeetingRecordingHandler?()
    }

    func openAISettings() {
        self.openNavigationDestination(.aiSettings)
    }

    func openCleanupStyles() {
        self.openNavigationDestination(.cleanupStyles)
    }

    private func openNavigationDestination(_ destination: MenuBarNavigationDestination) {
        self.navigationRequestGeneration &+= 1
        let requestGeneration = self.navigationRequestGeneration
        // Ensure a fresh one-shot request every time the menu item is clicked.
        self.requestedNavigationDestination = nil
        self.requestedNavigationDestination = destination

        self.openMainWindow()

        // Nudge again after the window is front-most, so an already-open ContentView
        // will still switch tabs even if it consumed a previous navigation request.
        DispatchQueue.main.async { [weak self] in
            guard let self, self.navigationRequestGeneration == requestGeneration else { return }
            self.requestedNavigationDestination = nil
            self.requestedNavigationDestination = destination
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
                guard let self,
                      self.navigationRequestGeneration == requestGeneration,
                      self.requestedNavigationDestination == destination
                else { return }
                self.requestedNavigationDestination = nil
            }
        }
    }

    /// Public entry-point for non-menu UI surfaces (e.g. overlay controls) to open Preferences.
    func openPreferencesFromUI() {
        self.openPreferences()
    }

    func openMicrophoneSettingsFromUI() {
        self.openNavigationDestination(.microphoneSettings)
    }

    /// Create and present a fresh main window hosting `ContentView`
    private func createAndShowMainWindow() {
        // Build the SwiftUI root view with required environment
        let rootView = AdaptiveAppTheme(accent: SettingsStore.shared.accentColor) {
            ContentView()
                .environmentObject(self)
                .environmentObject(AppServices.shared)
        }

        // Host inside an AppKit window
        let hostingController = NSHostingController(rootView: rootView)
        let window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 1000, height: 700),
            styleMask: [.titled, .closable, .miniaturizable, .resizable],
            backing: .buffered,
            defer: false
        )
        window.title = "FluidVoice"
        // Match the SwiftUI main scene when recreating a closed window.
        window.toolbarStyle = .unified
        window.animationBehavior = .none
        window.minSize = self.mainWindowMinimumSize
        window.isReleasedWhenClosed = false
        window.contentViewController = hostingController
        window.setFrame(self.defaultWindowFrame(), display: false)
        self.bringToFront(window)
        self.hostedWindow = window

        // Bring app to front in case we're running as an accessory app (no Dock)
        NSApp.activate(ignoringOtherApps: true)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) {
            NSApp.activate(ignoringOtherApps: true)
        }
    }

    private func ensureUsableMainWindow(_ window: NSWindow) {
        guard !window.styleMask.contains(.fullScreen) else { return }
        // If the window is too small (e.g., height collapsed), reset to the default frame.
        let minSize = self.mainWindowMinimumSize
        if window.minSize != minSize { window.minSize = minSize }

        let frame = window.frame
        if frame.height < minSize.height || frame.width < minSize.width {
            window.setFrame(self.defaultWindowFrame(), display: false)
        }
    }

    private func defaultWindowFrame() -> NSRect {
        // Center a sensible default frame on the main screen.
        let size = NSSize(width: 1000, height: 700)
        let screenFrame = NSScreen.main?.visibleFrame ?? NSRect(x: 0, y: 0, width: size.width, height: size.height)
        let origin = NSPoint(
            x: screenFrame.midX - size.width / 2,
            y: screenFrame.midY - size.height / 2
        )
        return NSRect(origin: origin, size: size)
    }

    private var mainWindowMinimumSize: NSSize {
        let window = AppTheme.dark.metrics.window
        return NSSize(width: window.mainMinWidth, height: window.mainMinHeight)
    }

    private func bringToFront(_ window: NSWindow) {
        // Keep ordering explicit to avoid "opened but behind other apps" behavior.
        if window.alphaValue <= 0.01 {
            window.alphaValue = 1
        }
        window.orderFrontRegardless()
        window.makeKeyAndOrderFront(nil)
    }
}