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
fix microphone priority routing
altic-dev2dce5cd572eb
diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swiftindex b41052b5..77c9a444 100644--- a/Sources/Fluid/AppDelegate.swift+++ b/Sources/Fluid/AppDelegate.swift@@ -19,6 +19,10 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDeleprivate var wasLaunchedAsLoginItem = falseprivate var hasDeferredMLXUpgradeOffer = false+ var shouldPresentStartupMicrophoneNotice: Bool {+ !self.wasLaunchedAsLoginItem || SettingsStore.shared.showMainWindowAtLoginLaunch+ }+func applicationDidFinishLaunching(_ notification: Notification) {// Bring up file logging + crash handlers immediately during launch._ = FileLogger.shareddiff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex 353ba102..9bba5c98 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -309,6 +309,7 @@ struct ContentView: View {@State private var savedProviders: [SettingsStore.SavedProvider] = []@State private var selectedProviderID: String = SettingsStore.shared.selectedProviderID@State private var columnVisibility: NavigationSplitViewVisibility = .all+ @State private var microphoneSettingsScrollRequest = 0var body: some View {let layout = AnyView(@@ -602,10 +603,6 @@ struct ContentView: View {self.menuBarManager.configure(asrService: self.appServices.asr)self.refreshDevices()- if let preferredUID = SettingsStore.shared.preferredInputDeviceUID, !preferredUID.isEmpty {- self.selectedInputUID = preferredUID- }-if self.selectedOutputUID.isEmpty, let defOut = AudioDevice.getDefaultOutputDevice()?.uid {self.selectedOutputUID = defOut}@@ -952,12 +949,14 @@ struct ContentView: View {@MainActorprivate func handleMenuBarNavigation(_ destination: MenuBarNavigationDestination?) {guard let destination else { return }- defer { menuBarManager.requestedNavigationDestination = nil }guard !self.settings.shouldShowOnboarding else { return }switch destination {case .customDictionary:self.selectedSidebarItem = .customDictionary+ case .microphoneSettings:+ self.selectedSidebarItem = .preferences+ self.microphoneSettingsScrollRequest &+= 1case .preferences:self.selectedSidebarItem = .preferences}@@ -1446,6 +1445,7 @@ struct ContentView: View {private var preferencesView: some View {SettingsView(+ microphonePreferenceCoordinator: self.appServices.microphonePreferenceCoordinator,appear: self.$appear,visualizerNoiseThreshold: self.$visualizerNoiseThreshold,selectedInputUID: self.$selectedInputUID,@@ -1474,7 +1474,8 @@ struct ContentView: View {openAccessibilitySettings: self.openAccessibilitySettings,restartApp: self.restartApp,revealAppInFinder: self.revealAppInFinder,- openApplicationsFolder: self.openApplicationsFolder+ openApplicationsFolder: self.openApplicationsFolder,+ microphoneSettingsScrollRequest: self.microphoneSettingsScrollRequest)}@@ -1520,11 +1521,15 @@ struct ContentView: View {DispatchQueue.global(qos: .userInitiated).async {let inputs = AudioDevice.listInputDevices()let outputs = AudioDevice.listOutputDevices()+ let defaultInputUID = AudioDevice.getDefaultInputDevice()?.uidDispatchQueue.main.async {self.inputDevices = inputsself.outputDevices = outputsif let selectedInput = self.appServices.microphonePreferenceCoordinator- .inputDeviceForCapture(availableInputs: inputs)+ .reconcileMicrophoneSelection(+ availableInputs: inputs,+ defaultInputUID: defaultInputUID+ ){self.selectedInputUID = selectedInput.uid}@@ -4381,7 +4386,6 @@ private extension ContentView {self.isRewriteModeShortcutEnabled = SettingsStore.shared.rewriteModeShortcutEnabledself.playgroundUsed = SettingsStore.shared.playgroundUsedself.visualizerNoiseThreshold = SettingsStore.shared.visualizerNoiseThreshold- self.selectedInputUID = SettingsStore.shared.preferredInputDeviceUID ?? ""self.selectedOutputUID = SettingsStore.shared.preferredOutputDeviceUID ?? ""self.enableDebugLogs = SettingsStore.shared.enableDebugLogsself.hotkeyMode = SettingsStore.shared.hotkeyModediff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swiftindex 1b43ae34..4953a598 100644--- a/Sources/Fluid/Persistence/BackupService.swift+++ b/Sources/Fluid/Persistence/BackupService.swift@@ -63,6 +63,12 @@ struct SettingsBackupPayload: Codable, Equatable {let copyTranscriptionToClipboard: Boollet textInsertionMode: SettingsStore.TextInsertionModelet preferredInputDeviceUID: String?+ // Optional so backups created before microphone priority ordering still decode.+ // swiftlint:disable:next discouraged_optional_collection+ let microphonePriority: [SettingsStore.MicrophonePriorityEntry]?+ // Optional so backups created before microphone removal history still decode.+ // swiftlint:disable:next discouraged_optional_collection+ let suppressedMicrophoneUIDs: [String]?let preferredOutputDeviceUID: String?let microphoneSelectionMode: SettingsStore.MicrophoneSelectionMode?let visualizerNoiseThreshold: Doublediff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swiftindex d4b6e60b..3e3f18a2 100644--- a/Sources/Fluid/Persistence/SettingsStore.swift+++ b/Sources/Fluid/Persistence/SettingsStore.swift@@ -11,6 +11,8 @@ import FluidAudio// swiftlint:disable file_length type_body_lengthfinal class SettingsStore: ObservableObject {+ static let microphonePriorityMigrationVersion = 4+static let shared = SettingsStore()static let transcriptionPreviewCharLimitRange: ClosedRange<Int> = 50...800static let transcriptionPreviewCharLimitStep = 50@@ -197,6 +199,13 @@ final class SettingsStore: ObservableObject {}}+ struct MicrophonePriorityEntry: Codable, Hashable, Identifiable {+ let uid: String+ var name: String++ var id: String { self.uid }+ }+enum DictationPromptSelection: Equatable {case off, `default`, privateAIcase profile(String)@@ -1813,30 +1822,184 @@ final class SettingsStore: ObservableObject {set { self.defaults.set(newValue, forKey: Keys.preferredInputDeviceUID) }}+ var microphonePriority: [MicrophonePriorityEntry] {+ get {+ guard let data = self.defaults.data(forKey: Keys.microphonePriority),+ let entries = try? JSONDecoder().decode([MicrophonePriorityEntry].self, from: data)+ else { return [] }+ return Self.normalizedMicrophonePriority(entries)+ }+ set {+ let entries = Self.normalizedMicrophonePriority(newValue)+ guard entries != self.microphonePriority else { return }+ objectWillChange.send()+ if let data = try? JSONEncoder().encode(entries) {+ self.defaults.set(data, forKey: Keys.microphonePriority)+ } else {+ self.defaults.removeObject(forKey: Keys.microphonePriority)+ }+ if let firstUID = entries.first?.uid {+ self.preferredInputDeviceUID = firstUID+ }+ }+ }++ var suppressedMicrophoneUIDs: Set<String> {+ get { Set(self.defaults.stringArray(forKey: Keys.suppressedMicrophoneUIDs) ?? []) }+ set {+ if newValue.isEmpty {+ self.defaults.removeObject(forKey: Keys.suppressedMicrophoneUIDs)+ } else {+ self.defaults.set(newValue.sorted(), forKey: Keys.suppressedMicrophoneUIDs)+ }+ }+ }+var preferredOutputDeviceUID: String? {get { self.defaults.string(forKey: Keys.preferredOutputDeviceUID) }set { self.defaults.set(newValue, forKey: Keys.preferredOutputDeviceUID) }}- var microphoneSelectionMode: MicrophoneSelectionMode { .manual }+ var storedMicSelectionModeForMigration: MicrophoneSelectionMode {+ guard let rawValue = self.defaults.string(forKey: Keys.microphoneSelectionMode),+ let mode = MicrophoneSelectionMode(rawValue: rawValue)+ else { return .system }+ return mode+ }- func enforceAppOnlyMicrophoneSelection() {- guard self.defaults.string(forKey: Keys.microphoneSelectionMode) != MicrophoneSelectionMode.manual.rawValue else {- return+ var microphoneSelectionMode: MicrophoneSelectionMode {+ get {+ guard let rawValue = self.defaults.string(forKey: Keys.microphoneSelectionMode),+ let mode = MicrophoneSelectionMode(rawValue: rawValue)+ else { return .manual }+ return mode}- objectWillChange.send()- self.defaults.set(MicrophoneSelectionMode.manual.rawValue, forKey: Keys.microphoneSelectionMode)+ set {+ objectWillChange.send()+ self.defaults.set(newValue.rawValue, forKey: Keys.microphoneSelectionMode)+ }+ }++ func recordInputDeviceSelection(_ uid: String, name: String? = nil) {+ guard uid.isEmpty == false else { return }++ var suppressedUIDs = self.suppressedMicrophoneUIDs+ suppressedUIDs.remove(uid)+ self.suppressedMicrophoneUIDs = suppressedUIDs++ var entries = self.microphonePriority.filter { $0.uid != uid }+ let existingName = self.microphonePriority.first { $0.uid == uid }?.name+ entries.insert(+ MicrophonePriorityEntry(uid: uid, name: name ?? existingName ?? "Microphone"),+ at: 0+ )+ self.microphonePriority = entries+ self.microphoneSelectionMode = .manual}- func recordInputDeviceSelection(_ uid: String) {+ func reconcileMicrophonePriority(with devices: [AudioDevice.Device]) {+ var entries = self.microphonePriority+ let preferredUID = self.preferredInputDeviceUID+ let connectedUIDs = Set(devices.map(\.uid))+ var suppressedUIDs = self.suppressedMicrophoneUIDs+ suppressedUIDs.formIntersection(connectedUIDs)+ self.suppressedMicrophoneUIDs = suppressedUIDs++ if entries.isEmpty,+ let preferredUID,+ preferredUID.isEmpty == false+ {+ let name = devices.first { $0.uid == preferredUID }?.name ?? "Previously selected microphone"+ entries.append(MicrophonePriorityEntry(uid: preferredUID, name: name))+ }++ var knownUIDs = Set(entries.map(\.uid))+ let newEntries = devices.compactMap { device -> MicrophonePriorityEntry? in+ guard suppressedUIDs.contains(device.uid) == false,+ knownUIDs.insert(device.uid).inserted+ else { return nil }+ return MicrophonePriorityEntry(uid: device.uid, name: device.name)+ }+ if newEntries.isEmpty == false {+ // Keep the user's first choice stable while making a newly connected+ // microphone the immediate fallback. Its position remains persisted+ // when the device later disconnects.+ entries.insert(contentsOf: newEntries, at: min(1, entries.count))+ }++ let namesByUID = Dictionary(+ devices.map { ($0.uid, $0.name) },+ uniquingKeysWith: { current, _ in current }+ )+ entries = entries.map { entry in+ MicrophonePriorityEntry(uid: entry.uid, name: namesByUID[entry.uid] ?? entry.name)+ }+ self.microphonePriority = entries+ }++ func removeMicrophoneFromPriority(uid: String, isConnected: Bool) {guard uid.isEmpty == false else { return }- self.preferredInputDeviceUID = uid+ var suppressedUIDs = self.suppressedMicrophoneUIDs+ if isConnected {+ suppressedUIDs.insert(uid)+ } else {+ suppressedUIDs.remove(uid)+ }+ self.suppressedMicrophoneUIDs = suppressedUIDs++ let entries = self.microphonePriority.filter { $0.uid != uid }+ self.microphonePriority = entries+ if entries.isEmpty {+ self.preferredInputDeviceUID = nil+ }}- var appMicSelectionMigrationVersion: Int {- get { self.defaults.integer(forKey: Keys.appMicSelectionMigrationVersion) }- set { self.defaults.set(newValue, forKey: Keys.appMicSelectionMigrationVersion) }+ func restoreRemovedMicrophones(with devices: [AudioDevice.Device]) {+ self.suppressedMicrophoneUIDs = []+ self.reconcileMicrophonePriority(with: devices)+ }++ func reorderMicrophonePriority(fromOffsets: IndexSet, toOffset: Int) {+ var entries = self.microphonePriority+ entries.move(fromOffsets: fromOffsets, toOffset: toOffset)+ self.microphonePriority = entries+ }++ func moveMicrophonePriority(uid: String, before targetUID: String) {+ guard uid != targetUID else { return }+ var entries = self.microphonePriority+ guard let sourceIndex = entries.firstIndex(where: { $0.uid == uid }),+ let targetIndex = entries.firstIndex(where: { $0.uid == targetUID })+ else { return }++ let entry = entries.remove(at: sourceIndex)+ let adjustedTargetIndex = sourceIndex < targetIndex ? targetIndex - 1 : targetIndex+ entries.insert(entry, at: adjustedTargetIndex)+ self.microphonePriority = entries+ }++ func moveMicrophonePriority(uid: String, by offset: Int) {+ var entries = self.microphonePriority+ guard let sourceIndex = entries.firstIndex(where: { $0.uid == uid }) else { return }+ let destination = min(max(sourceIndex + offset, 0), entries.count - 1)+ guard destination != sourceIndex else { return }+ entries.swapAt(sourceIndex, destination)+ self.microphonePriority = entries+ }++ private static func normalizedMicrophonePriority(+ _ entries: [MicrophonePriorityEntry]+ ) -> [MicrophonePriorityEntry] {+ var seen = Set<String>()+ return entries.filter { entry in+ entry.uid.isEmpty == false && seen.insert(entry.uid).inserted+ }+ }++ var microphoneSelectionMigrationVersion: Int {+ get { self.defaults.integer(forKey: Keys.microphoneSelectionMigrationVersion) }+ set { self.defaults.set(newValue, forKey: Keys.microphoneSelectionMigrationVersion) }}var visualizerNoiseThreshold: Double {@@ -3023,8 +3186,12 @@ final class SettingsStore: ObservableObject {copyTranscriptionToClipboard: self.copyTranscriptionToClipboard,textInsertionMode: self.textInsertionMode,preferredInputDeviceUID: self.preferredInputDeviceUID,+ microphonePriority: self.microphonePriority,+ suppressedMicrophoneUIDs: self.suppressedMicrophoneUIDs.sorted(),preferredOutputDeviceUID: self.preferredOutputDeviceUID,- microphoneSelectionMode: self.microphoneSelectionMode,+ // Kept in the backup schema for compatibility with older builds.+ // Current builds always resolve microphones from the priority list.+ microphoneSelectionMode: .manual,visualizerNoiseThreshold: self.visualizerNoiseThreshold,overlayPosition: self.overlayPosition,overlayBottomOffset: self.overlayBottomOffset,@@ -3142,11 +3309,22 @@ final class SettingsStore: ObservableObject {self.copyTranscriptionToClipboard = payload.copyTranscriptionToClipboardself.textInsertionMode = payload.textInsertionModeself.preferredInputDeviceUID = payload.preferredInputDeviceUID+ self.suppressedMicrophoneUIDs = Set(payload.suppressedMicrophoneUIDs ?? [])+ if let microphonePriority = payload.microphonePriority {+ self.microphonePriority = microphonePriority+ } else {+ self.microphonePriority = []+ }self.preferredOutputDeviceUID = payload.preferredOutputDeviceUID- if payload.microphoneSelectionMode == .system {- self.appMicSelectionMigrationVersion = 0+ if payload.microphonePriority != nil {+ self.microphoneSelectionMode = .manual+ self.microphoneSelectionMigrationVersion = Self.microphonePriorityMigrationVersion+ } else if payload.microphoneSelectionMode == .system {+ self.microphoneSelectionMode = .system+ self.microphoneSelectionMigrationVersion = 0+ } else {+ self.microphoneSelectionMode = .manual}- self.enforceAppOnlyMicrophoneSelection()self.visualizerNoiseThreshold = payload.visualizerNoiseThresholdself.overlayPosition = payload.overlayPositionself.overlayBottomOffset = payload.overlayBottomOffset@@ -4884,9 +5062,12 @@ private extension SettingsStore {static let hotkeyShortcutKey = "HotkeyShortcutKey"static let primaryDictationShortcutsKey = "PrimaryDictationShortcuts"static let preferredInputDeviceUID = "PreferredInputDeviceUID"+ static let microphonePriority = "MicrophonePriority"+ static let suppressedMicrophoneUIDs = "SuppressedMicrophoneUIDs"static let preferredOutputDeviceUID = "PreferredOutputDeviceUID"static let microphoneSelectionMode = "MicrophoneSelectionMode"- static let appMicSelectionMigrationVersion = "AppOnlyMicrophoneSelectionMigrationVersion"+ // Keep the original persisted key so existing installs migrate in place.+ static let microphoneSelectionMigrationVersion = "AppOnlyMicrophoneSelectionMigrationVersion"static let visualizerNoiseThreshold = "VisualizerNoiseThreshold"static let launchAtStartup = "LaunchAtStartup"static let showInDock = "ShowInDock"diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex 81f6223c..1085205a 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -205,6 +205,8 @@ final class ASRService: ObservableObject {private var hasPendingParakeetVocabularyReload: Bool = falseprivate var vocabularyChangeObserver: NSObjectProtocol?private var settingsBackupRestoreObserver: NSObjectProtocol?+ private var clamshellStateChangeObserver: NSObjectProtocol?+ private var inputDeviceAvailabilityChangeObserver: NSObjectProtocol?// MARK: - Error Handling@@ -755,6 +757,8 @@ final class ASRService: ObservableObject {}()private var activeAudioCaptureBackend: AudioCaptureBackend = .none+ private var audioStartAttemptInputUID: String?+ private var audioStartAttemptInputName: String?private var hasPreparedAudioCapture: Bool {self.directAudioLifecycleController.snapshot.isPrepared || self.hasWarmAudioEngine@@ -904,17 +908,24 @@ final class ASRService: ObservableObject {}}- private func resolvedInputDeviceForCapture() -> AudioDevice.Device? {- AppServices.shared.microphonePreferenceCoordinator.inputDeviceForCapture()+ private func resolvedInputDeviceForCapture(+ excluding excludedUIDs: Set<String> = []+ ) -> AudioDevice.Device? {+ let inputs = AudioDevice.listInputDevices()+ return AppServices.shared.microphonePreferenceCoordinator.inputDeviceForCapture(+ availableInputs: inputs,+ defaultInputUID: AudioDevice.getDefaultInputDevice()?.uid,+ excluding: excludedUIDs+ )}- private func directCoreAudioDeviceSelection() -> DirectCoreAudioDeviceSelection {- if let preferredUID = SettingsStore.shared.preferredInputDeviceUID,- preferredUID.isEmpty == false- {- return .preferredUID(preferredUID)+ private func directCoreAudioDeviceSelection(+ excluding excludedUIDs: Set<String> = []+ ) -> DirectCoreAudioDeviceSelection? {+ if let inputUID = self.resolvedInputDeviceForCapture(excluding: excludedUIDs)?.uid {+ return .preferredUID(inputUID)}- return .systemDefault+ return nil}/// Prepares the direct device callback without starting hardware IO. This@@ -930,8 +941,15 @@ final class ASRService: ObservableObject {userInfo: [NSLocalizedDescriptionKey: "Microphone access is not authorized."])}+ guard let selection = self.directCoreAudioDeviceSelection() else {+ throw NSError(+ domain: "ASRService",+ code: -4,+ userInfo: [NSLocalizedDescriptionKey: "No usable microphone is available."]+ )+ }let device = try await self.directAudioLifecycleController.resolveDevice(- selection: self.directCoreAudioDeviceSelection(),+ selection: selection,reason: "prepare:\(reason)")let snapshot = try await self.directAudioLifecycleController.prepare(@@ -949,17 +967,35 @@ final class ASRService: ObservableObject {return snapshot}- private func startConfiguredAudioCapture() async throws {+ private func startConfiguredAudioCapture(+ excluding excludedInputUIDs: Set<String> = []+ ) async throws {+ self.audioStartAttemptInputUID = nil+ self.audioStartAttemptInputName = nilif SettingsStore.shared.experimentalDirectAudioCaptureEnabled {// A non-route path may have scheduled a fire-and-forget retirement.// Do not let direct capture startup overlap a queued AVAudioEngine// release.await self.audioEngineRetirementDrain.waitForScheduledReleases()do {+ guard let selection = self.directCoreAudioDeviceSelection(+ excluding: excludedInputUIDs+ ) else {+ throw NSError(+ domain: "ASRService",+ code: -4,+ userInfo: [NSLocalizedDescriptionKey: "No remaining microphone is available."]+ )+ }+ if case let .preferredUID(uid) = selection {+ self.audioStartAttemptInputUID = uid+ }let device = try await self.directAudioLifecycleController.resolveDevice(- selection: self.directCoreAudioDeviceSelection(),+ selection: selection,reason: "recording_start")+ self.audioStartAttemptInputUID = device.uid+ self.audioStartAttemptInputName = device.namelet snapshot = try await self.directAudioLifecycleController.start(deviceID: device.id,deviceName: device.name,@@ -1181,6 +1217,26 @@ final class ASRService: ObservableObject {)}}+ self.clamshellStateChangeObserver = NotificationCenter.default.addObserver(+ forName: .clamshellStateDidChange,+ object: nil,+ queue: .main+ ) { [weak self] notification in+ let isClosed = notification.userInfo?["isClosed"] as? Bool ?? ClamshellState.isClosed+ Task { @MainActor [weak self] in+ self?.handleClamshellStateChanged(isClosed: isClosed)+ }+ }+ self.inputDeviceAvailabilityChangeObserver = NotificationCenter.default.addObserver(+ forName: .inputDeviceAvailabilityDidChange,+ object: nil,+ queue: .main+ ) { [weak self] notification in+ let deviceID = notification.userInfo?["deviceID"] as? AudioObjectID+ Task { @MainActor [weak self] in+ self?.handleInputDeviceAvailabilityChanged(deviceID: deviceID)+ }+ }}deinit {@@ -1193,6 +1249,39 @@ final class ASRService: ObservableObject {if let observer = self.settingsBackupRestoreObserver {NotificationCenter.default.removeObserver(observer)}+ if let observer = self.clamshellStateChangeObserver {+ NotificationCenter.default.removeObserver(observer)+ }+ if let observer = self.inputDeviceAvailabilityChangeObserver {+ NotificationCenter.default.removeObserver(observer)+ }+ }++ private func handleClamshellStateChanged(isClosed: Bool) {+ DebugLogger.shared.info(+ "Clamshell \(isClosed ? "closed" : "opened"); refreshing microphone availability",+ source: "ASRService"+ )+ self.scheduleAudioRouteRecovery(+ reason: isClosed ? "clamshell closed" : "clamshell opened",+ requiresIdlePrewarm: true,+ reconcilesInputSelection: true+ )+ }++ private func handleInputDeviceAvailabilityChanged(deviceID: AudioObjectID?) {+ let resolvedInput = AppServices.shared.microphonePreferenceCoordinator.inputDeviceForCapture()+ let preparedDeviceID = self.directAudioLifecycleController.snapshot.deviceID+ let confirmedUID = AppServices.shared.microphonePreferenceCoordinator.confirmedActiveInputUID+ let activeSelectionChanged = self.isRunning && resolvedInput?.uid != confirmedUID+ let preparedSelectionChanged = self.hasPreparedAudioCapture && resolvedInput?.id != preparedDeviceID+ guard activeSelectionChanged || preparedSelectionChanged else { return }++ self.scheduleAudioRouteRecovery(+ reason: "input availability changed:\(deviceID ?? 0)",+ requiresIdlePrewarm: true,+ reconcilesInputSelection: true+ )}@MainActor@@ -1285,10 +1374,15 @@ final class ASRService: ObservableObject {guard self.isTerminating == false else { return }let microphonePreferenceCoordinator = AppServices.shared.microphonePreferenceCoordinator- microphonePreferenceCoordinator.reconcileAppOnlySelection(+ microphonePreferenceCoordinator.reconcileMicrophoneSelection(availableInputs: initialInputSnapshot.0,defaultInputUID: initialInputSnapshot.1)+ microphonePreferenceCoordinator.scheduleStartupNoticeIfEligible(+ microphoneAuthorized: self.micStatus == .authorized,+ launchAllowsPresentation: (NSApp.delegate as? AppDelegate)?+ .shouldPresentStartupMicrophoneNotice ?? true+ )self.registerDefaultDeviceChangeListener()self.registerEngineConfigurationChangeObserver()@@ -1296,7 +1390,7 @@ final class ASRService: ObservableObject {// Initialize device list cacheself.cacheCurrentDeviceList(initialInputSnapshot.0)- if microphonePreferenceCoordinator.needsAppOnlySelectionMigration {+ if microphonePreferenceCoordinator.needsMicrophonePriorityMigration {self.scheduleAudioRouteRecovery(reason: "app microphone migration pending",requiresIdlePrewarm: true,@@ -1489,13 +1583,26 @@ final class ASRService: ObservableObject {do {let maximumStartAttempts =- SettingsStore.shared.experimentalDirectAudioCaptureEnabled ? 3 : 1+ SettingsStore.shared.experimentalDirectAudioCaptureEnabled+ ? max(AudioDevice.listInputDevices().count, 1) + 1+ : 1var startAttempt = 1+ var failedInputUIDs = Set<String>()+ var immediatelyRetriedInputUID: String?+ self.audioStartAttemptInputUID = nilwhile true {let routeGenerationAtStart = self.audioRouteRecoveryGenerationdo {- try await self.startConfiguredAudioCapture()+ try await self.startConfiguredAudioCapture(excluding: failedInputUIDs)} catch {+ guard let failedUID = self.audioStartAttemptInputUID else { throw error }+ let retrySameInput = immediatelyRetriedInputUID == nil+ if retrySameInput {+ immediatelyRetriedInputUID = failedUID+ }+ if retrySameInput == false {+ failedInputUIDs.insert(failedUID)+ }guard startAttempt < maximumStartAttempts,startGeneration == self.audioCaptureStartGeneration,self.isTerminating == false@@ -1506,7 +1613,8 @@ final class ASRService: ObservableObject {sessionID: captureSessionID,startGeneration: startGeneration,completedAttempt: startAttempt,- reason: "backend_start_error:\(error.localizedDescription)"+ reason: "backend_start_error:\(error.localizedDescription)",+ waitForTopologyQuiet: retrySameInput == false)startAttempt += 1continue@@ -1533,6 +1641,10 @@ final class ASRService: ObservableObject {self.pendingAudioRouteRecovery == nil &&self.isRecoveringAudioRoute == falseif readiness == .ready, routeStayedStable {+ AppServices.shared.microphonePreferenceCoordinator.confirmActiveSelection(+ uid: self.audioStartAttemptInputUID,+ name: self.audioStartAttemptInputName+ )self.benchmarkLog("first_pcm_wait_end result=ready attempt=\(startAttempt) " +"attemptID=\(readinessAttemptID) " +@@ -1549,6 +1661,17 @@ final class ASRService: ObservableObject {if readiness == .cancelled {throw CancellationError()}+ var retrySameInput = false+ if let failedUID = self.audioStartAttemptInputUID {+ retrySameInput = readiness == .formatInvalidated &&+ immediatelyRetriedInputUID == nil+ if retrySameInput {+ immediatelyRetriedInputUID = failedUID+ }+ if retrySameInput == false {+ failedInputUIDs.insert(failedUID)+ }+ }guard startAttempt < maximumStartAttempts else {let message: Stringswitch readiness {@@ -1574,7 +1697,8 @@ final class ASRService: ObservableObject {sessionID: captureSessionID,startGeneration: startGeneration,completedAttempt: startAttempt,- reason: "readiness_\(readiness)_routeStable_\(routeStayedStable)"+ reason: "readiness_\(readiness)_routeStable_\(routeStayedStable)",+ waitForTopologyQuiet: retrySameInput == false)startAttempt += 1}@@ -1661,11 +1785,16 @@ final class ASRService: ObservableObject {}guard wasCancelled == false else { return .failed }+ AppServices.shared.microphonePreferenceCoordinator.markActiveSelectionUnavailable()// Provide user-friendly error feedback+ let nsError = error as NSError+ let noUsableMicrophone = nsError.domain == "ASRService" && nsError.code == -4let errorMessage: String- if let nsError = error as NSError?, nsError.domain == "ASRService" {- if let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError {+ if nsError.domain == "ASRService" {+ if noUsableMicrophone {+ errorMessage = "No usable microphone is available. Open your MacBook or connect a microphone, then try again."+ } else if let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError {// Extract useful info from AVFoundation errorif underlyingError.domain == AVFoundationErrorDomain || underlyingError.domain == NSOSStatusErrorDomain {errorMessage = "Failed to start audio recording. The audio device may be in use by another application or unavailable. Please check your audio settings and try again."@@ -1679,6 +1808,10 @@ final class ASRService: ObservableObject {errorMessage = "Failed to start audio recording: \(error.localizedDescription)"}+ self.errorTitle = noUsableMicrophone ? "Microphone Unavailable" : "Recording Error"+ self.errorMessage = errorMessage+ self.showError = true+// Post notification for UI to displayNotificationCenter.default.post(name: NSNotification.Name("ASRServiceStartFailed"),@@ -1704,7 +1837,8 @@ final class ASRService: ObservableObject {sessionID: Int,startGeneration: UInt64,completedAttempt: Int,- reason: String+ reason: String,+ waitForTopologyQuiet: Bool = true) async throws -> UInt64 {self.audioCapturePipeline.setRecordingEnabled(false)await self.directAudioLifecycleController.invalidate(@@ -1720,7 +1854,7 @@ final class ASRService: ObservableObject {else {throw CancellationError()}- if routeRecoveryWasPending == false {+ if routeRecoveryWasPending == false, waitForTopologyQuiet {try await Task.sleep(nanoseconds: self.audioRouteRecoveryDelayNanoseconds)}guard startGeneration == self.audioCaptureStartGeneration,@@ -2871,7 +3005,7 @@ final class ASRService: ObservableObject {return false}- AppServices.shared.microphonePreferenceCoordinator.reconcileAppOnlySelection(+ AppServices.shared.microphonePreferenceCoordinator.reconcileMicrophoneSelection(availableInputs: snapshot.0,defaultInputUID: snapshot.1)@@ -2920,69 +3054,129 @@ final class ASRService: ObservableObject {guard request.generation == self.audioRouteRecoveryGeneration, Task.isCancelled == false else { return }do {- self.audioCaptureAttemptID &+= 1- let readinessAttemptID = self.audioCaptureAttemptID- self.audioCaptureReadinessGate.arm(- sessionID: self.benchmarkSessionID,- attemptID: readinessAttemptID- )- self.audioCapturePipeline.setRecordingEnabled(- true,- sessionID: self.benchmarkSessionID,- attemptID: readinessAttemptID,- startHostTime: mach_absolute_time()- )- try await self.startConfiguredAudioCapture()- guard request.generation == self.audioRouteRecoveryGeneration,- Task.isCancelled == false- else {- self.audioCapturePipeline.setRecordingEnabled(false)- await self.stopActiveAudioCapture(- retainDirectPreparedCapture: false,- reason: "superseded_route_recovery_start"+ let maximumAttempts = SettingsStore.shared.experimentalDirectAudioCaptureEnabled+ ? max(AudioDevice.listInputDevices().count, 1) + 1+ : 1+ var failedInputUIDs = Set<String>()+ var immediatelyRetriedInputUID: String?+ var completedAttempts = 0++ while completedAttempts < maximumAttempts {+ completedAttempts += 1+ self.audioCaptureAttemptID &+= 1+ let readinessAttemptID = self.audioCaptureAttemptID+ self.audioCaptureReadinessGate.arm(+ sessionID: self.benchmarkSessionID,+ attemptID: readinessAttemptID)- return- }- let readiness = await self.audioCaptureReadinessGate.wait(- sessionID: self.benchmarkSessionID,- attemptID: readinessAttemptID,- timeoutNanoseconds: self.firstPCMTimeoutNanoseconds- )- guard request.generation == self.audioRouteRecoveryGeneration,- Task.isCancelled == false- else {+ self.audioCapturePipeline.setRecordingEnabled(+ true,+ sessionID: self.benchmarkSessionID,+ attemptID: readinessAttemptID,+ startHostTime: mach_absolute_time()+ )++ do {+ try await self.startConfiguredAudioCapture(excluding: failedInputUIDs)+ } catch {+ if let failedUID = self.audioStartAttemptInputUID {+ let retrySameInput = immediatelyRetriedInputUID == nil+ if retrySameInput {+ immediatelyRetriedInputUID = failedUID+ }+ if retrySameInput == false {+ failedInputUIDs.insert(failedUID)+ }+ }+ guard completedAttempts < maximumAttempts else { throw error }+ self.audioCapturePipeline.setRecordingEnabled(false)+ await self.stopActiveAudioCapture(+ retainDirectPreparedCapture: false,+ reason: "active_route_recovery_start_retry"+ )+ continue+ }++ guard request.generation == self.audioRouteRecoveryGeneration,+ Task.isCancelled == false+ else {+ self.audioCapturePipeline.setRecordingEnabled(false)+ await self.stopActiveAudioCapture(+ retainDirectPreparedCapture: false,+ reason: "superseded_route_recovery_start"+ )+ return+ }+ let readiness = await self.audioCaptureReadinessGate.wait(+ sessionID: self.benchmarkSessionID,+ attemptID: readinessAttemptID,+ timeoutNanoseconds: self.firstPCMTimeoutNanoseconds+ )+ guard request.generation == self.audioRouteRecoveryGeneration,+ Task.isCancelled == false+ else {+ self.audioCapturePipeline.setRecordingEnabled(false)+ await self.stopActiveAudioCapture(+ retainDirectPreparedCapture: false,+ reason: "superseded_route_recovery_readiness"+ )+ return+ }+ if readiness == .ready {+ AppServices.shared.microphonePreferenceCoordinator.confirmActiveSelection(+ uid: self.audioStartAttemptInputUID,+ name: self.audioStartAttemptInputName+ )+ self.benchmarkLog(+ "route_recovery_first_pcm generation=\(request.generation) " ++ "attempt=\(completedAttempts) attemptID=\(readinessAttemptID) " ++ "bufferedSamples=\(self.audioBuffer.count)"+ )++ if self.activeAudioCaptureBackend == .audioEngine,+ let currentDevice = self.getCurrentlyBoundInputDevice()+ {+ self.startMonitoringDevice(currentDevice.id)+ }++ DebugLogger.shared.info(+ "Audio route recovery succeeded (generation=\(request.generation), " ++ "attempt=\(completedAttempts))",+ source: "ASRService"+ )+ return+ }++ if let failedUID = self.audioStartAttemptInputUID {+ let retrySameInput = readiness == .formatInvalidated &&+ immediatelyRetriedInputUID == nil+ if retrySameInput {+ immediatelyRetriedInputUID = failedUID+ }+ if retrySameInput == false {+ failedInputUIDs.insert(failedUID)+ }+ }+ guard completedAttempts < maximumAttempts else {+ throw NSError(+ domain: "ASRService",+ code: -3,+ userInfo: [+ NSLocalizedDescriptionKey:+ "No replacement microphone delivered audio (\(readiness)).",+ ]+ )+ }self.audioCapturePipeline.setRecordingEnabled(false)await self.stopActiveAudioCapture(retainDirectPreparedCapture: false,- reason: "superseded_route_recovery_readiness"- )- return- }- guard readiness == .ready else {- throw NSError(- domain: "ASRService",- code: -3,- userInfo: [- NSLocalizedDescriptionKey:- "The replacement microphone did not deliver audio (\(readiness)).",- ]+ reason: "active_route_recovery_readiness_retry")}- self.benchmarkLog(- "route_recovery_first_pcm generation=\(request.generation) " +- "attemptID=\(readinessAttemptID) " +- "bufferedSamples=\(self.audioBuffer.count)"- )-- if self.activeAudioCaptureBackend == .audioEngine,- let currentDevice = self.getCurrentlyBoundInputDevice()- {- self.startMonitoringDevice(currentDevice.id)- }-- DebugLogger.shared.info(- "Audio route recovery succeeded (generation=\(request.generation))",- source: "ASRService"+ throw NSError(+ domain: "ASRService",+ code: -3,+ userInfo: [NSLocalizedDescriptionKey: "No replacement microphone is available."])} catch {guard request.generation == self.audioRouteRecoveryGeneration, Task.isCancelled == false else { return }@@ -2992,6 +3186,7 @@ final class ASRService: ObservableObject {reason: "active_route_recovery_failed")DebugLogger.shared.error("Audio route recovery failed: \(error)", source: "ASRService")+ AppServices.shared.microphonePreferenceCoordinator.markActiveSelectionUnavailable()// Avoid asking stopWithoutTranscription() to await the recovery task// that is currently executing this catch block.@@ -3029,6 +3224,7 @@ final class ASRService: ObservableObject {"device=\(invalidation.deviceID) property=\(invalidation.reason) " +"wasRunning=\(invalidation.wasRunning) isStarting=\(self.isStarting)")+ AppServices.shared.audioObserver.signalInputAvailabilityChanged()if invalidation.reason == "audio_service_restarted" {self.reestablishAudioHardwareListenersAfterServiceReset()AppServices.shared.audioObserver.restartObservingAfterAudioServiceReset()@@ -3045,8 +3241,8 @@ final class ASRService: ObservableObject {}private func handleDefaultInputChanged() {- // FluidVoice owns only its app-specific input selection. A macOS- // default-input change must not move or restart the selected mic.+ // Microphone priority is app-owned. A macOS default-input change must+ // never move or restart FluidVoice's selected microphone.}private func handleDefaultOutputChanged() {@@ -3296,23 +3492,38 @@ final class ASRService: ObservableObject {// the HAL may still be settling, and synchronous queries on main can deadlock.DispatchQueue.global(qos: .userInitiated).async { [weak self] inlet currentDevices = AudioDevice.listInputDevices()+ let defaultInputUID = AudioDevice.getDefaultInputDevice()?.uidDispatchQueue.main.async { [weak self] inguard let self else { return }let cachedUIDs = self.cachedDeviceUIDs+ let cachedDeviceIDsByUID = self.cachedInputDeviceIDsByUIDlet currentUIDs = Set(currentDevices.map(\.uid))+ let currentDeviceIDsByUID = Dictionary(+ currentDevices.map { ($0.uid, $0.id) },+ uniquingKeysWith: { current, _ in current }+ )DebugLogger.shared.debug("Current input devices: \(currentDevices.map { $0.name }.joined(separator: ", "))", source: "ASRService")- if currentUIDs != cachedUIDs {- let previousPreferredUID = SettingsStore.shared.preferredInputDeviceUID+ if currentUIDs != cachedUIDs || currentDeviceIDsByUID != cachedDeviceIDsByUID {let microphonePreferenceCoordinator =AppServices.shared.microphonePreferenceCoordinator+ let migrationPending = microphonePreferenceCoordinator.needsMicrophonePriorityMigration+ microphonePreferenceCoordinator.reconcileMicrophoneSelection(+ availableInputs: currentDevices,+ defaultInputUID: defaultInputUID+ )+ let priorityUIDs = SettingsStore.shared.microphonePriority.map(\.uid)let shouldReconcileInputSelection = AudioCaptureIdlePolicy.shouldReconcileInputSelection(- preferredInputUID: previousPreferredUID,- migrationPending: microphonePreferenceCoordinator.needsAppOnlySelectionMigration,+ priorityInputUIDs: priorityUIDs,+ migrationPending: migrationPending,previousInputUIDs: cachedUIDs,currentInputUIDs: currentUIDs+ ) || AudioCaptureIdlePolicy.didResolvedPriorityInputIdentityChange(+ priorityInputUIDs: priorityUIDs,+ previousInputDeviceIDsByUID: cachedDeviceIDsByUID,+ currentInputDeviceIDsByUID: currentDeviceIDsByUID)if shouldReconcileInputSelection {self.scheduleAudioRouteRecovery(@@ -3404,9 +3615,14 @@ final class ASRService: ObservableObject {/// Device caching for change detectionprivate var cachedDeviceUIDs: Set<String> = []+ private var cachedInputDeviceIDsByUID: [String: AudioObjectID] = [:]private func cacheCurrentDeviceList(_ devices: [AudioDevice.Device]) {self.cachedDeviceUIDs = Set(devices.map { $0.uid })+ self.cachedInputDeviceIDsByUID = Dictionary(+ devices.map { ($0.uid, $0.id) },+ uniquingKeysWith: { current, _ in current }+ )}// Audio tap processing is handled by AudioCapturePipeline (thread-safe).diff --git a/Sources/Fluid/Services/AudioCaptureIdlePolicy.swift b/Sources/Fluid/Services/AudioCaptureIdlePolicy.swiftindex 81b6e49a..37f2d6c1 100644--- a/Sources/Fluid/Services/AudioCaptureIdlePolicy.swift+++ b/Sources/Fluid/Services/AudioCaptureIdlePolicy.swift@@ -1,27 +1,47 @@+import CoreAudio+enum AudioCaptureIdlePolicy {static func shouldPrewarmCapture(experimentalDirectAudioCaptureEnabled: Bool) -> Bool {experimentalDirectAudioCaptureEnabled}- static func didPreferredInputAvailabilityChange(- preferredInputUID: String?,+ static func didResolvedPriorityInputChange(+ priorityInputUIDs: [String],previousInputUIDs: Set<String>,currentInputUIDs: Set<String>) -> Bool {- guard let preferredInputUID, preferredInputUID.isEmpty == false else { return false }- return previousInputUIDs.contains(preferredInputUID) != currentInputUIDs.contains(preferredInputUID)+ let previousChoice = priorityInputUIDs.first(where: previousInputUIDs.contains)+ let currentChoice = priorityInputUIDs.first(where: currentInputUIDs.contains)+ return previousChoice != currentChoice+ }++ static func didResolvedPriorityInputIdentityChange(+ priorityInputUIDs: [String],+ previousInputDeviceIDsByUID: [String: AudioObjectID],+ currentInputDeviceIDsByUID: [String: AudioObjectID]+ ) -> Bool {+ let previousChoice = priorityInputUIDs.first { previousInputDeviceIDsByUID[$0] != nil }+ let currentChoice = priorityInputUIDs.first { currentInputDeviceIDsByUID[$0] != nil }+ guard previousChoice == currentChoice else { return true }+ guard let currentChoice else { return false }+ return previousInputDeviceIDsByUID[currentChoice] != currentInputDeviceIDsByUID[currentChoice]}static func shouldReconcileInputSelection(- preferredInputUID: String?,+ priorityInputUIDs: [String],migrationPending: Bool,previousInputUIDs: Set<String>,currentInputUIDs: Set<String>) -> Bool {- guard currentInputUIDs.isEmpty == false else { return false }- let needsInitialSelection = preferredInputUID?.isEmpty ?? true- return migrationPending || needsInitialSelection || self.didPreferredInputAvailabilityChange(- preferredInputUID: preferredInputUID,+ if currentInputUIDs.isEmpty {+ return previousInputUIDs.isEmpty == false && self.didResolvedPriorityInputChange(+ priorityInputUIDs: priorityInputUIDs,+ previousInputUIDs: previousInputUIDs,+ currentInputUIDs: currentInputUIDs+ )+ }+ return migrationPending || priorityInputUIDs.isEmpty || self.didResolvedPriorityInputChange(+ priorityInputUIDs: priorityInputUIDs,previousInputUIDs: previousInputUIDs,currentInputUIDs: currentInputUIDs)diff --git a/Sources/Fluid/Services/AudioDeviceService.swift b/Sources/Fluid/Services/AudioDeviceService.swiftindex 0998d89b..66b63bf5 100644--- a/Sources/Fluid/Services/AudioDeviceService.swift+++ b/Sources/Fluid/Services/AudioDeviceService.swift@@ -8,6 +8,8 @@import Combineimport CoreAudioimport Foundation+import IOKit+import IOKit.pwr_mgt// MARK: - Audio Device Manager@@ -145,6 +147,35 @@ nonisolated enum AudioDevice {return self.listInputDevices().first { $0.uid == uid }}+ /// Core Audio may continue enumerating an input after it has stopped being usable,+ /// notably the internal microphone during some clamshell transitions.+ /// Fail open when the property cannot be queried so unusual/virtual devices still work.+ static func isInputDeviceAlive(_ device: Device) -> Bool {+ var address = AudioObjectPropertyAddress(+ mSelector: kAudioDevicePropertyDeviceIsAlive,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ var value: UInt32 = 1+ var dataSize = UInt32(MemoryLayout<UInt32>.size)+ let status = AudioObjectGetPropertyData(+ device.id,+ &address,+ 0,+ nil,+ &dataSize,+ &value+ )+ return status != noErr || value != 0+ }++ /// The built-in microphone remains enumerated and may still report itself+ /// alive while a MacBook is closed. Treat it as unavailable in that state,+ /// while leaving external and virtual inputs eligible.+ static func isInputDeviceUsable(_ device: Device) -> Bool {+ self.isInputDeviceAlive(device) && (device.isBuiltIn == false || ClamshellState.isClosed == false)+ }+/// Get output device by UID without affecting system settingsstatic func getOutputDevice(byUID uid: String) -> Device? {return self.listOutputDevices().first { $0.uid == uid }@@ -260,6 +291,30 @@ nonisolated enum AudioDevice {}}+nonisolated enum ClamshellState {+ static var isClosed: Bool {+ let rootDomain = IOServiceGetMatchingService(+ kIOMainPortDefault,+ IOServiceMatching("IOPMrootDomain")+ )+ guard rootDomain != IO_OBJECT_NULL else { return false }+ defer { IOObjectRelease(rootDomain) }++ let property = IORegistryEntryCreateCFProperty(+ rootDomain,+ kAppleClamshellStateKey as CFString,+ kCFAllocatorDefault,+ 0+ )?.takeRetainedValue()+ return (property as? NSNumber)?.boolValue ?? false+ }+}++extension Notification.Name {+ static let clamshellStateDidChange = Notification.Name("ClamshellStateDidChange")+ static let inputDeviceAvailabilityDidChange = Notification.Name("InputDeviceAvailabilityDidChange")+}+// MARK: - Audio Hardware Observerfinal class AudioHardwareObserver: ObservableObject {@@ -272,6 +327,12 @@ final class AudioHardwareObserver: ObservableObject {private var devicesListenerToken: AudioObjectPropertyListenerBlock?private var defaultInputListenerToken: AudioObjectPropertyListenerBlock?private var defaultOutputListenerToken: AudioObjectPropertyListenerBlock?+ private var inputAvailabilityListenerTokens: [AudioObjectID: AudioObjectPropertyListenerBlock] = [:]+ private var inputAvailabilityRefreshGeneration: UInt64 = 0+ private var clamshellRootDomain: io_service_t = IO_OBJECT_NULL+ private var clamshellNotificationPort: IONotificationPortRef?+ private var clamshellNotification: io_object_t = IO_OBJECT_NULL+ private var lastClamshellClosed: Bool?init() {// IMPORTANT: Do NOT call register() here!@@ -286,12 +347,19 @@ final class AudioHardwareObserver: ObservableObject {self.register()}+ @MainActor+ func signalInputAvailabilityChanged() {+ self.changeTick &+= 1+ }+func restartObservingAfterAudioServiceReset() {// Core Audio discards every previously registered listener when its// service resets, so the old tokens must not be removed or reused.self.devicesListenerToken = nilself.defaultInputListenerToken = nilself.defaultOutputListenerToken = nil+ self.inputAvailabilityListenerTokens.removeAll()+ self.inputAvailabilityRefreshGeneration &+= 1self.installed = falseself.register()self.changeTick &+= 1@@ -335,6 +403,7 @@ final class AudioHardwareObserver: ObservableObject {let devicesToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ inself?.changeTick &+= 1+ self?.refreshInputAvailabilityListeners()}let defaultInToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ inself?.changeTick &+= 1@@ -369,10 +438,11 @@ final class AudioHardwareObserver: ObservableObject {self.defaultInputListenerToken = defaultInTokenself.defaultOutputListenerToken = defaultOutTokenself.installed = true+ self.refreshInputAvailabilityListeners()+ self.registerClamshellStateListener()}private func unregister() {- guard self.installed else { return }var addrDevices = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDevices,mScope: kAudioObjectPropertyScopeGlobal,@@ -392,19 +462,191 @@ final class AudioHardwareObserver: ObservableObject {let queue = DispatchQueue.mainlet sys = AudioObjectID(kAudioObjectSystemObject)- if let token = self.devicesListenerToken {- _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDevices, queue, token)- }- if let token = self.defaultInputListenerToken {- _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultIn, queue, token)- }- if let token = self.defaultOutputListenerToken {- _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultOut, queue, token)+ if self.installed {+ if let token = self.devicesListenerToken {+ _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDevices, queue, token)+ }+ if let token = self.defaultInputListenerToken {+ _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultIn, queue, token)+ }+ if let token = self.defaultOutputListenerToken {+ _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultOut, queue, token)+ }+ self.removeInputAvailabilityListeners()}self.devicesListenerToken = nilself.defaultInputListenerToken = nilself.defaultOutputListenerToken = nilself.installed = false+ self.inputAvailabilityRefreshGeneration &+= 1+ self.unregisterClamshellStateListener()}++ private func refreshInputAvailabilityListeners() {+ self.inputAvailabilityRefreshGeneration &+= 1+ let generation = self.inputAvailabilityRefreshGeneration+ DispatchQueue.global(qos: .utility).async { [weak self] in+ let devices = AudioDevice.listInputDevices()+ DispatchQueue.main.async { [weak self] in+ guard let self,+ self.inputAvailabilityRefreshGeneration == generation+ else { return }+ self.replaceInputAvailabilityListeners(with: devices)+ }+ }+ }++ private func replaceInputAvailabilityListeners(with devices: [AudioDevice.Device]) {+ guard self.installed else { return }+ let currentIDs = Set(devices.map(\.id))+ for (deviceID, token) in self.inputAvailabilityListenerTokens where currentIDs.contains(deviceID) == false {+ var address = Self.inputAvailabilityAddress+ _ = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)+ self.inputAvailabilityListenerTokens.removeValue(forKey: deviceID)+ }++ for device in devices where self.inputAvailabilityListenerTokens[device.id] == nil {+ let deviceID = device.id+ var address = Self.inputAvailabilityAddress+ let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in+ // Never query Core Audio synchronously from its property callback.+ // Hop to the next main-queue turn before observers resolve priority.+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.changeTick &+= 1+ NotificationCenter.default.post(+ name: .inputDeviceAvailabilityDidChange,+ object: self,+ userInfo: ["deviceID": deviceID]+ )+ }+ }+ let status = AudioObjectAddPropertyListenerBlock(+ deviceID,+ &address,+ DispatchQueue.main,+ token+ )+ if status == noErr {+ self.inputAvailabilityListenerTokens[deviceID] = token+ }+ }+ }++ private func removeInputAvailabilityListeners() {+ for (deviceID, token) in self.inputAvailabilityListenerTokens {+ var address = Self.inputAvailabilityAddress+ _ = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)+ }+ self.inputAvailabilityListenerTokens.removeAll()+ }++ private static var inputAvailabilityAddress: AudioObjectPropertyAddress {+ AudioObjectPropertyAddress(+ mSelector: kAudioDevicePropertyDeviceIsAlive,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ }++ private func registerClamshellStateListener() {+ guard self.clamshellNotificationPort == nil else { return }++ let rootDomain = IOServiceGetMatchingService(+ kIOMainPortDefault,+ IOServiceMatching("IOPMrootDomain")+ )+ guard rootDomain != IO_OBJECT_NULL,+ let notificationPort = IONotificationPortCreate(kIOMainPortDefault)+ else {+ if rootDomain != IO_OBJECT_NULL {+ IOObjectRelease(rootDomain)+ }+ DebugLogger.shared.warning(+ "Unable to observe MacBook clamshell state",+ source: "AudioHardwareObserver"+ )+ return+ }++ IONotificationPortSetDispatchQueue(notificationPort, DispatchQueue.main)+ var notification = io_object_t(IO_OBJECT_NULL)+ let status = IOServiceAddInterestNotification(+ notificationPort,+ rootDomain,+ kIOGeneralInterest,+ clamshellStateInterestCallback,+ Unmanaged.passUnretained(self).toOpaque(),+ ¬ification+ )+ guard status == KERN_SUCCESS else {+ IONotificationPortSetDispatchQueue(notificationPort, nil)+ IONotificationPortDestroy(notificationPort)+ IOObjectRelease(rootDomain)+ DebugLogger.shared.warning(+ "Unable to register clamshell state listener (status=\(status))",+ source: "AudioHardwareObserver"+ )+ return+ }++ self.clamshellRootDomain = rootDomain+ self.clamshellNotificationPort = notificationPort+ self.clamshellNotification = notification+ self.lastClamshellClosed = ClamshellState.isClosed+ DebugLogger.shared.info(+ "Clamshell state listener registered (closed=\(self.lastClamshellClosed == true))",+ source: "AudioHardwareObserver"+ )+ }++ private func unregisterClamshellStateListener() {+ if let notificationPort = self.clamshellNotificationPort {+ IONotificationPortSetDispatchQueue(notificationPort, nil)+ }+ if self.clamshellNotification != IO_OBJECT_NULL {+ IOObjectRelease(self.clamshellNotification)+ }+ if let notificationPort = self.clamshellNotificationPort {+ IONotificationPortDestroy(notificationPort)+ }+ if self.clamshellRootDomain != IO_OBJECT_NULL {+ IOObjectRelease(self.clamshellRootDomain)+ }++ self.clamshellRootDomain = IO_OBJECT_NULL+ self.clamshellNotificationPort = nil+ self.clamshellNotification = IO_OBJECT_NULL+ self.lastClamshellClosed = nil+ }++ func handleClamshellInterestMessage() {+ let isClosed = ClamshellState.isClosed+ guard isClosed != self.lastClamshellClosed else { return }+ self.lastClamshellClosed = isClosed+ self.changeTick &+= 1+ DebugLogger.shared.info(+ "MacBook clamshell state changed (closed=\(isClosed))",+ source: "AudioHardwareObserver"+ )+ NotificationCenter.default.post(+ name: .clamshellStateDidChange,+ object: self,+ userInfo: ["isClosed": isClosed]+ )+ }+}++private func clamshellStateInterestCallback(+ refcon: UnsafeMutableRawPointer?,+ _: io_service_t,+ _: natural_t,+ _: UnsafeMutableRawPointer?+) {+ guard let refcon else { return }+ Unmanaged<AudioHardwareObserver>+ .fromOpaque(refcon)+ .takeUnretainedValue()+ .handleClamshellInterestMessage()}diff --git a/Sources/Fluid/Services/DirectCoreAudioInput.swift b/Sources/Fluid/Services/DirectCoreAudioInput.swiftindex 7a742749..779b826b 100644--- a/Sources/Fluid/Services/DirectCoreAudioInput.swift+++ b/Sources/Fluid/Services/DirectCoreAudioInput.swift@@ -751,8 +751,17 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendableswitch selection {case .systemDefault:device = AudioDevice.getDefaultInputDevice()+ .flatMap { AudioDevice.isInputDeviceUsable($0) ? $0 : nil }case let .preferredUID(uid):- device = AudioDevice.getInputDevice(byUID: uid)+ if let preferredDevice = AudioDevice.getInputDevice(byUID: uid),+ AudioDevice.isInputDeviceUsable(preferredDevice)+ {+ device = preferredDevice+ } else {+ // Let ASRService retry the next app-priority device. Falling back+ // here would silently bypass the user's order during a HAL race.+ device = nil+ }}guard let device else {continuation.resume(diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swiftindex 0e513a8a..b1ab0784 100644--- a/Sources/Fluid/Services/MenuBarManager.swift+++ b/Sources/Fluid/Services/MenuBarManager.swift@@ -5,6 +5,7 @@ import SwiftUIenum MenuBarNavigationDestination: String {case customDictionary+ case microphoneSettingscase preferences}@@ -25,6 +26,7 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {// References to app stateprivate weak var asrService: ASRService?private var cancellables = Set<AnyCancellable>()+ private var configuredASRIdentifier: ObjectIdentifier?/// Overlay management (persistent, independent of window lifecycle)private var overlayVisible: Bool = false@@ -37,8 +39,9 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {@Published var isRecording: Bool = false/// One-shot navigation requests from the menu bar into the main window UI.- /// `ContentView` consumes this and clears it.+ /// 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 notchprivate var currentOverlayMode: OverlayMode = .dictation@@ -56,6 +59,16 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {/// Subscription for forwarding audio levels to expanded command notchprivate var expandedModeAudioSubscription: AnyCancellable?+ override init() {+ super.init()+ 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 }@@ -70,6 +83,9 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {}func configure(asrService: ASRService) {+ let identifier = ObjectIdentifier(asrService)+ guard self.configuredASRIdentifier != identifier else { return }+ self.configuredASRIdentifier = identifierself.asrService = asrServiceif SettingsStore.shared.overlayPosition == .bottom {DispatchQueue.main.async {@@ -616,18 +632,41 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {return}- let currentUID = AppServices.shared.microphonePreferenceCoordinator- .inputDeviceForCapture(- availableInputs: inputDevices,- defaultInputUID: defaultInputUID- )?.uid+ let microphonePreferenceCoordinator = AppServices.shared.microphonePreferenceCoordinator+ microphonePreferenceCoordinator.reconcileMicrophoneSelection(+ availableInputs: inputDevices,+ defaultInputUID: defaultInputUID+ )+ let currentUID = microphonePreferenceCoordinator.confirmedActiveInputUID- for device in inputDevices {- let isSystemDefault = device.uid == defaultInputUID- let title = isSystemDefault ? "\(device.name) (System Default)" : device.name+ 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.uid+ item.representedObject = deviceitem.state = device.uid == currentUID ? .on : .offitem.isEnabled = !self.isRecordingsubmenu.addItem(item)@@ -659,9 +698,9 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {@objc private func selectMicrophone(_ sender: NSMenuItem) {guard self.isRecording == false else { return }- guard let uid = sender.representedObject as? String, !uid.isEmpty else { return }+ guard let device = sender.representedObject as? AudioDevice.Device else { return }- SettingsStore.shared.recordInputDeviceSelection(uid)+ SettingsStore.shared.recordInputDeviceSelection(device.uid, name: device.name)self.refreshMicrophoneMenu()}@@ -868,6 +907,8 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {}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 = nilself.requestedNavigationDestination = destination@@ -877,8 +918,16 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {// 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- self?.requestedNavigationDestination = nil- self?.requestedNavigationDestination = destination+ 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+ }}}@@ -887,6 +936,10 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {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 environmentdiff --git a/Sources/Fluid/Services/MicrophonePreferenceCoordinator.swift b/Sources/Fluid/Services/MicrophonePreferenceCoordinator.swiftindex 998beb6a..a8865a62 100644--- a/Sources/Fluid/Services/MicrophonePreferenceCoordinator.swift+++ b/Sources/Fluid/Services/MicrophonePreferenceCoordinator.swift@@ -3,11 +3,22 @@ import Foundation@MainActorprotocol AudioDeviceManaging {+ var isClamshellClosed: Bool { get }func listInputDevices() -> [AudioDevice.Device]func defaultInputDevice() -> AudioDevice.Device?+ func isInputDeviceUsable(_ device: AudioDevice.Device) -> Bool+}++extension AudioDeviceManaging {+ var isClamshellClosed: Bool { false }+ func isInputDeviceUsable(_: AudioDevice.Device) -> Bool { true }}struct CoreAudioDeviceManager: AudioDeviceManaging {+ var isClamshellClosed: Bool {+ ClamshellState.isClosed+ }+func listInputDevices() -> [AudioDevice.Device] {AudioDevice.listInputDevices()}@@ -15,14 +26,27 @@ struct CoreAudioDeviceManager: AudioDeviceManaging {func defaultInputDevice() -> AudioDevice.Device? {AudioDevice.getDefaultInputDevice()}++ func isInputDeviceUsable(_ device: AudioDevice.Device) -> Bool {+ AudioDevice.isInputDeviceAlive(device)+ }}@MainActorfinal class MicrophonePreferenceCoordinator: ObservableObject {- private static let appOnlyMigrationVersion = 1-private let settings: SettingsStoreprivate let devices: any AudioDeviceManaging+ private var lastResolvedInputUID: String?+ private var lastResolvedInputName: String?+ private var hasConfirmedActiveSelection = false+ private var lastConfirmedInputUID: String?+ private var lastConfirmedInputName: String?+ @Published private(set) var confirmedActiveInputUID: String?+ private var startupNoticeTask: Task<Void, Never>?+ private var startupNoticeEligibilityEnabled = false+ private var didPresentStartupNotice = false+ private var startupNoticePresentedUID: String?+ private var startupNoticePresentedName: String?init(settings: SettingsStore? = nil,@@ -32,62 +56,248 @@ final class MicrophonePreferenceCoordinator: ObservableObject {self.devices = devices ?? CoreAudioDeviceManager()}- var needsAppOnlySelectionMigration: Bool {- self.settings.appMicSelectionMigrationVersion < Self.appOnlyMigrationVersion+ var needsMicrophonePriorityMigration: Bool {+ self.settings.microphoneSelectionMigrationVersion < SettingsStore.microphonePriorityMigrationVersion}- func migrateToAppOnlySelectionIfNeeded() {- guard self.needsAppOnlySelectionMigration else {- self.settings.enforceAppOnlyMicrophoneSelection()- return- }+ func migrateMicrophonePriorityIfNeeded() {+ guard self.needsMicrophonePriorityMigration else { return }let inputs = self.devices.listInputDevices()let defaultInputUID = self.devices.defaultInputDevice()?.uid- self.migrateToAppOnlySelectionIfNeeded(+ self.migrateMicrophonePriorityIfNeeded(availableInputs: inputs,defaultInputUID: defaultInputUID)}- func migrateToAppOnlySelectionIfNeeded(+ func migrateMicrophonePriorityIfNeeded(availableInputs: [AudioDevice.Device],defaultInputUID: String?) {- guard self.needsAppOnlySelectionMigration else {- self.settings.enforceAppOnlyMicrophoneSelection()+ guard self.needsMicrophonePriorityMigration else {+ self.settings.reconcileMicrophonePriority(with: availableInputs)return}- let preferredInput = availableInputs.first { input in+ let migrationVersion = self.settings.microphoneSelectionMigrationVersion+ let clamshellClosed = self.devices.isClamshellClosed+ let usableInputs = availableInputs.filter {+ self.isInputDeviceAvailable($0, clamshellClosed: clamshellClosed)+ }+ let preferredInput = usableInputs.first { input ininput.uid == self.settings.preferredInputDeviceUID}- guard let selectedInput = availableInputs.first(where: \.isBuiltIn)- ?? preferredInput- ?? self.fallbackInput(from: availableInputs, defaultInputUID: defaultInputUID)- else { return }+ let enumeratedPreferredInput = availableInputs.first { input in+ input.uid == self.settings.preferredInputDeviceUID+ }+ let defaultInput = defaultInputUID.flatMap { uid in+ usableInputs.first { $0.uid == uid }+ }+ let migrationInputs = defaultInput.map { input in+ [input] + availableInputs.filter { $0.uid != input.uid }+ } ?? availableInputs+ let previousMode = self.settings.storedMicSelectionModeForMigration+ if migrationVersion >= 2,+ let preferredUID = self.settings.preferredInputDeviceUID,+ preferredUID.isEmpty == false+ {+ let preferredName = preferredInput?.name ?? "Previously selected microphone"+ self.settings.recordInputDeviceSelection(preferredUID, name: preferredName)+ self.settings.reconcileMicrophonePriority(with: migrationInputs)+ self.settings.microphoneSelectionMode = .manual+ self.settings.microphoneSelectionMigrationVersion = SettingsStore.microphonePriorityMigrationVersion+ return+ }+ let preserveDisconnectedManualSelection =+ migrationVersion == 0 && previousMode == .manual+ let preserveDisconnectedVersionOneExternal =+ migrationVersion == 1 &&+ enumeratedPreferredInput?.isBuiltIn != true &&+ Self.isLikelyBuiltInMicrophoneUID(self.settings.preferredInputDeviceUID) == false+ if preferredInput == nil,+ preserveDisconnectedManualSelection || preserveDisconnectedVersionOneExternal,+ let preferredUID = self.settings.preferredInputDeviceUID,+ preferredUID.isEmpty == false+ {+ self.settings.recordInputDeviceSelection(+ preferredUID,+ name: "Previously selected microphone"+ )+ self.settings.reconcileMicrophonePriority(with: migrationInputs)+ self.settings.microphoneSelectionMode = .manual+ self.settings.microphoneSelectionMigrationVersion = SettingsStore.microphonePriorityMigrationVersion+ return+ }+ let selectedInput: AudioDevice.Device?+ if migrationVersion == 0,+ previousMode == .manual+ {+ selectedInput = preferredInput+ ?? defaultInput+ ?? self.fallbackInput(from: usableInputs, defaultInputUID: defaultInputUID)+ } else if migrationVersion == 0 {+ selectedInput = defaultInput+ ?? preferredInput+ ?? self.fallbackInput(from: usableInputs, defaultInputUID: defaultInputUID)+ } else if migrationVersion == 1,+ let preferredInput,+ preferredInput.isBuiltIn,+ defaultInput?.uid != preferredInput.uid+ {+ // Repair only the known v1 built-in-first migration. Runtime priority+ // resolution itself never ranks a device by transport type.+ selectedInput = defaultInput+ ?? self.fallbackInput(from: usableInputs, defaultInputUID: defaultInputUID)+ } else {+ selectedInput = preferredInput+ ?? defaultInput+ ?? self.fallbackInput(from: usableInputs, defaultInputUID: defaultInputUID)+ }+ guard let selectedInput else {+ self.settings.reconcileMicrophonePriority(with: migrationInputs)+ return+ }- self.settings.preferredInputDeviceUID = selectedInput.uid- self.settings.enforceAppOnlyMicrophoneSelection()- self.settings.appMicSelectionMigrationVersion = Self.appOnlyMigrationVersion+ self.settings.recordInputDeviceSelection(selectedInput.uid, name: selectedInput.name)+ self.settings.reconcileMicrophonePriority(with: migrationInputs)+ self.settings.microphoneSelectionMode = .manual+ self.settings.microphoneSelectionMigrationVersion = SettingsStore.microphonePriorityMigrationVersionDebugLogger.shared.info(- "Migrated FluidVoice microphone selection to app-only input '\(selectedInput.name)'",+ "Migrated FluidVoice microphone priority with '\(selectedInput.name)' first",source: "MicrophonePreferenceCoordinator")}@discardableResult- func reconcileAppOnlySelection(+ func reconcileMicrophoneSelection(availableInputs: [AudioDevice.Device],defaultInputUID: String?) -> AudioDevice.Device? {- self.migrateToAppOnlySelectionIfNeeded(+ self.migrateMicrophonePriorityIfNeeded(availableInputs: availableInputs,defaultInputUID: defaultInputUID)- return self.inputDeviceForCapture(+ let selectedInput = self.inputDeviceForCapture(availableInputs: availableInputs,- defaultInputUID: defaultInputUID,- persistFallback: true+ defaultInputUID: defaultInputUID)+ self.lastResolvedInputUID = selectedInput?.uid+ self.lastResolvedInputName = selectedInput?.name+ if self.startupNoticeEligibilityEnabled {+ self.scheduleStartupNoticeAfterSelectionSettles()+ }+ if let confirmedActiveInputUID,+ availableInputs.contains(where: { device in+ device.uid == confirmedActiveInputUID && self.isInputDeviceAvailable(device)+ }) == false+ {+ self.confirmedActiveInputUID = nil+ }+ return selectedInput+ }++ func confirmActiveSelection(uid: String?, name: String?) {+ let previousUID = self.lastConfirmedInputUID+ let previousName = self.lastConfirmedInputName+ self.lastConfirmedInputUID = uid+ self.lastConfirmedInputName = name ?? previousName+ self.confirmedActiveInputUID = uid++ guard self.hasConfirmedActiveSelection else {+ self.hasConfirmedActiveSelection = true+ DebugLogger.shared.debug(+ "Confirmed active microphone as '\(name ?? "none")'",+ source: "MicrophonePreferenceCoordinator"+ )+ if let startupNoticePresentedUID = self.startupNoticePresentedUID,+ uid != startupNoticePresentedUID+ {+ MicrophoneChangeOverlayController.shared.show(+ MicrophoneChangeNotice(+ previousName: self.startupNoticePresentedName,+ currentName: name,+ presentation: .activeChange+ )+ )+ }+ return+ }+ guard uid != previousUID else { return }++ let notice = MicrophoneChangeNotice(+ previousName: previousName,+ currentName: name,+ presentation: .activeChange+ )+ DebugLogger.shared.info(+ "Active microphone changed from '\(notice.previousName ?? "none")' " ++ "to '\(notice.currentName ?? "none")' after first PCM",+ source: "MicrophonePreferenceCoordinator"+ )+ MicrophoneChangeOverlayController.shared.show(notice)+ }++ func markActiveSelectionUnavailable() {+ guard self.hasConfirmedActiveSelection,+ self.lastConfirmedInputUID != nil+ else { return }++ let previousName = self.lastConfirmedInputName+ self.confirmedActiveInputUID = nil+ self.lastConfirmedInputUID = nil+ self.lastConfirmedInputName = nil+ MicrophoneChangeOverlayController.shared.show(+ MicrophoneChangeNotice(+ previousName: previousName,+ currentName: nil,+ presentation: .activeChange+ )+ )+ }++ func scheduleStartupNoticeIfEligible(+ microphoneAuthorized: Bool,+ launchAllowsPresentation: Bool+ ) {+ guard microphoneAuthorized,+ launchAllowsPresentation,+ self.settings.shouldShowOnboarding == false,+ self.lastResolvedInputUID != nil,+ self.lastResolvedInputName != nil+ else { return }++ self.startupNoticeEligibilityEnabled = true+ self.scheduleStartupNoticeAfterSelectionSettles()+ }++ private func scheduleStartupNoticeAfterSelectionSettles() {+ guard self.startupNoticeEligibilityEnabled,+ self.didPresentStartupNotice == false,+ self.lastResolvedInputUID != nil,+ self.lastResolvedInputName != nil+ else { return }++ let expectedUID = self.lastResolvedInputUID+ self.startupNoticeTask?.cancel()+ self.startupNoticeTask = Task { @MainActor [weak self] in+ try? await Task.sleep(nanoseconds: 750_000_000)+ guard !Task.isCancelled,+ let self,+ self.settings.shouldShowOnboarding == false,+ self.lastResolvedInputUID == expectedUID,+ let currentName = self.lastResolvedInputName+ else { return }+ self.startupNoticeTask = nil+ self.didPresentStartupNotice = true+ self.startupNoticePresentedUID = expectedUID+ self.startupNoticePresentedName = currentName+ MicrophoneChangeOverlayController.shared.show(+ MicrophoneChangeNotice(+ previousName: nil,+ currentName: currentName,+ presentation: .startupSelection+ )+ )+ }}func inputDeviceForCapture() -> AudioDevice.Device? {@@ -100,27 +310,42 @@ final class MicrophonePreferenceCoordinator: ObservableObject {func inputDeviceForCapture(availableInputs: [AudioDevice.Device],defaultInputUID: String? = nil,- persistFallback: Bool = false+ excluding excludedUIDs: Set<String> = []) -> AudioDevice.Device? {+ let clamshellClosed = self.devices.isClamshellClosed+ let usableInputs = availableInputs.filter { device in+ excludedUIDs.contains(device.uid) == false &&+ self.isInputDeviceAvailable(device, clamshellClosed: clamshellClosed)+ }+ guard usableInputs.isEmpty == false else { return nil }++ for entry in self.settings.microphonePriority {+ if let input = usableInputs.first(where: { $0.uid == entry.uid }) {+ return input+ }+ }+if let preferredUID = self.settings.preferredInputDeviceUID,- preferredUID.isEmpty == false,- let preferredDevice = availableInputs.first(where: { $0.uid == preferredUID })+ let preferredInput = usableInputs.first(where: { $0.uid == preferredUID }){- return preferredDevice+ return preferredInput}- guard let fallback = self.fallbackInput(- from: availableInputs,+ return self.fallbackInput(+ from: usableInputs,defaultInputUID: defaultInputUID- ) else { return nil }- if persistFallback {- self.settings.preferredInputDeviceUID = fallback.uid- DebugLogger.shared.info(- "Selected fallback FluidVoice microphone '\(fallback.name)'",- source: "MicrophonePreferenceCoordinator"- )- }- return fallback+ )+ }++ func isInputDeviceAvailable(_ device: AudioDevice.Device) -> Bool {+ self.isInputDeviceAvailable(+ device,+ clamshellClosed: self.devices.isClamshellClosed+ )+ }++ func movePriority(fromOffsets: IndexSet, toOffset: Int) {+ self.settings.reorderMicrophonePriority(fromOffsets: fromOffsets, toOffset: toOffset)}private func fallbackInput(@@ -128,14 +353,34 @@ final class MicrophonePreferenceCoordinator: ObservableObject {defaultInputUID: String?) -> AudioDevice.Device? {guard inputs.isEmpty == false else { return nil }- if let builtInInput = inputs.first(where: \.isBuiltIn) {- return builtInInput- }- if let defaultUID = defaultInputUID,- let defaultInput = inputs.first(where: { $0.uid == defaultUID })- {+ if let defaultInput = self.device(uid: defaultInputUID, in: inputs) {return defaultInput}return inputs.first}++ private func device(+ uid: String?,+ in inputs: [AudioDevice.Device]+ ) -> AudioDevice.Device? {+ guard let uid else { return nil }+ return inputs.first { $0.uid == uid }+ }++ private static func isLikelyBuiltInMicrophoneUID(_ uid: String?) -> Bool {+ guard let uid else { return false }+ let normalized = uid.lowercased()+ return normalized.contains("builtin") ||+ normalized.contains("built-in") ||+ normalized.contains("internal")+ }++ private func isInputDeviceAvailable(+ _ device: AudioDevice.Device,+ clamshellClosed: Bool+ ) -> Bool {+ guard self.settings.suppressedMicrophoneUIDs.contains(device.uid) == false else { return false }+ guard clamshellClosed == false || device.isBuiltIn == false else { return false }+ return self.devices.isInputDeviceUsable(device)+ }}diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swiftindex 03574604..a116fb94 100644--- a/Sources/Fluid/UI/SettingsView.swift+++ b/Sources/Fluid/UI/SettingsView.swift@@ -26,7 +26,9 @@ struct SettingsView: View {@Environment(\.colorScheme) private var colorScheme@Environment(\.theme) private var theme+ @Environment(\.accessibilityReduceMotion) private var accessibilityReduceMotion@ObservedObject private var settings = SettingsStore.shared+ @ObservedObject var microphonePreferenceCoordinator: MicrophonePreferenceCoordinator@Binding var appear: Bool@Binding var visualizerNoiseThreshold: Double@Binding var selectedInputUID: String@@ -52,7 +54,7 @@ struct SettingsView: View {// CRITICAL FIX: Cache default device names to avoid CoreAudio calls during view body evaluation.// Querying AudioDevice.getDefaultInputDevice() in the view body triggers HALSystem::InitializeShell()// which races with SwiftUI's AttributeGraph metadata processing and causes EXC_BAD_ACCESS crashes.- @State private var cachedDefaultInputName: String = ""+ @State private var cachedDefaultInputUID: String = ""@State private var cachedDefaultOutputName: String = ""// Analytics consent UI state (default ON; user can opt-out)@@ -64,6 +66,8 @@ struct SettingsView: View {@State private var isRollingBack: Bool = false@State private var audioHistoryBudgetText: String = Self.audioBudgetText(for: SettingsStore.shared.audioHistoryBudgetGB)@State private var audioHistoryUsageBytes: Int64 = DictationAudioHistoryStore.shared.audioUsageBytes()+ @State private var draggedMicrophoneUID: String?+ @State private var hoveredMicrophoneUID: String?let hotkeyManager: GlobalHotkeyManager?let menuBarManager: MenuBarManager@@ -73,25 +77,7 @@ struct SettingsView: View {let restartApp: () -> Voidlet revealAppInFinder: () -> Voidlet openApplicationsFolder: () -> Void-- private var inputDeviceSelection: Binding<String> {- Binding(- get: { self.selectedInputUID },- set: { newUID in- guard !newUID.isEmpty else { return }- guard !self.asr.isRunning else {- DebugLogger.shared.warning(- "Cannot change input device during recording",- source: "SettingsView"- )- return- }-- self.selectedInputUID = newUID- SettingsStore.shared.recordInputDeviceSelection(newUID)- }- )- }+ let microphoneSettingsScrollRequest: Intprivate var isRecordingAnyShortcut: Bool {self.activeShortcutRecordingTarget != nil@@ -229,7 +215,11 @@ struct SettingsView: View {}var body: some View {- SettingsPersistentScrollView(theme: self.theme, colorScheme: self.colorScheme) {+ SettingsPersistentScrollView(+ theme: self.theme,+ colorScheme: self.colorScheme,+ microphoneSettingsScrollRequest: self.microphoneSettingsScrollRequest+ ) {VStack(spacing: 16) {// App Settings CardThemedCard(style: .standard) {@@ -1101,7 +1091,8 @@ struct SettingsView: View {Button {self.refreshDevices()// Update cached default device names on refresh- self.cachedDefaultInputName = AudioDevice.getDefaultInputDevice()?.name ?? ""+ let defaultInput = AudioDevice.getDefaultInputDevice()+ self.cachedDefaultInputUID = defaultInput?.uid ?? ""self.cachedDefaultOutputName = AudioDevice.getDefaultOutputDevice()?.name ?? ""} label: {Label("Refresh", systemImage: "arrow.clockwise")@@ -1110,41 +1101,21 @@ struct SettingsView: View {.controlSize(.small)}- self.microphoneModeInfo-VStack(alignment: .leading, spacing: 12) {- HStack {- Text("Input Device")- .font(self.theme.typography.bodyStrong)- .foregroundStyle(self.settingsTitleText)- Spacer()- Picker("", selection: self.inputDeviceSelection) {- // Handle empty state gracefully- if self.inputDevices.isEmpty {- Text("Loading...").tag("")- } else {- ForEach(self.inputDevices, id: \.uid) { dev in- Text(self.inputDeviceTitle(dev)).tag(dev.uid)- }- }- }- .pickerStyle(.menu)- .frame(width: 240)- .disabled(self.asr.isRunning)- // Sync selection when devices load or change+ self.microphonePrioritySection.onChange(of: self.inputDevices) { _, newDevices in- // Update cached default device name when device list changes- self.cachedDefaultInputName = AudioDevice.getDefaultInputDevice()?.name ?? ""-- guard !newDevices.isEmpty else { return }-+ let defaultInput = AudioDevice.getDefaultInputDevice()+ self.cachedDefaultInputUID = defaultInput?.uid ?? ""+ guard newDevices.isEmpty == false else { return }if let selectedInput = self.appServices.microphonePreferenceCoordinator- .inputDeviceForCapture(availableInputs: newDevices)+ .reconcileMicrophoneSelection(+ availableInputs: newDevices,+ defaultInputUID: self.cachedDefaultInputUID+ ){self.selectedInputUID = selectedInput.uid}}- }HStack {Text("Output Device")@@ -1209,6 +1180,7 @@ struct SettingsView: View {}.padding(16)}+ .background(MicrophoneSettingsScrollAnchor())// Overlay Settings CardThemedCard(style: .standard) {@@ -1507,15 +1479,15 @@ struct SettingsView: View {// Sync input device selection after refreshif !self.inputDevices.isEmpty {- let inputValid = self.inputDevices.contains { $0.uid == self.selectedInputUID }- if !inputValid || self.selectedInputUID.isEmpty {- if let defaultUID = AudioDevice.getDefaultInputDevice()?.uid,- self.inputDevices.contains(where: { $0.uid == defaultUID })- {- self.selectedInputUID = defaultUID- } else {- self.selectedInputUID = self.inputDevices.first?.uid ?? ""- }+ let defaultInput = AudioDevice.getDefaultInputDevice()+ self.cachedDefaultInputUID = defaultInput?.uid ?? ""+ if let selectedInput = self.appServices.microphonePreferenceCoordinator+ .reconcileMicrophoneSelection(+ availableInputs: self.inputDevices,+ defaultInputUID: self.cachedDefaultInputUID+ )+ {+ self.selectedInputUID = selectedInput.uid}}@@ -1539,7 +1511,8 @@ struct SettingsView: View {// CRITICAL FIX: Populate cached default device names after onAppear, not during view body evaluation.// This avoids the CoreAudio/SwiftUI AttributeGraph race condition that causes EXC_BAD_ACCESS.- self.cachedDefaultInputName = AudioDevice.getDefaultInputDevice()?.name ?? ""+ let defaultInput = AudioDevice.getDefaultInputDevice()+ self.cachedDefaultInputUID = defaultInput?.uid ?? ""self.cachedDefaultOutputName = AudioDevice.getDefaultOutputDevice()?.name ?? ""self.refreshRollbackState()self.settings.refreshLaunchAtStartupStatus(clearError: true, logMismatch: false)@@ -2255,38 +2228,248 @@ struct SettingsView: View {}private extension SettingsView {- var selectedInputDevice: AudioDevice.Device? {- self.inputDevices.first { $0.uid == self.selectedInputUID }+ var microphonePrioritySection: some View {+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ Text("Input Device Priority")+ .font(self.theme.typography.bodyStrong)+ .foregroundStyle(self.settingsTitleText)++ Spacer()++ if self.settings.suppressedMicrophoneUIDs.isEmpty == false {+ Button {+ self.settings.restoreRemovedMicrophones(with: self.inputDevices)+ self.refreshActiveInputSelection()+ } label: {+ Label("Restore Removed", systemImage: "arrow.uturn.backward")+ }+ .buttonStyle(.plain)+ .font(self.theme.typography.bodySmall)+ .foregroundStyle(self.theme.palette.accent)+ .disabled(self.isMicrophonePriorityEditingDisabled)+ }+ }++ VStack(spacing: 0) {+ if self.settings.microphonePriority.isEmpty {+ HStack(spacing: 8) {+ Image(systemName: "mic.slash")+ .foregroundStyle(self.settingsSecondaryText)+ Text(self.inputDevices.isEmpty ? "No microphones available" : "No microphones in priority")+ .font(self.theme.typography.bodySmall)+ .foregroundStyle(self.settingsSecondaryText)+ Spacer()+ }+ .padding(.horizontal, 12)+ .frame(minHeight: 42)+ } else {+ ForEach(Array(self.settings.microphonePriority.enumerated()), id: \.element.uid) { index, entry in+ if index > 0 {+ Divider().opacity(0.55)+ }+ self.microphonePriorityRow(entry, rank: index + 1)+ }+ }+ }+ .background(+ RoundedRectangle(cornerRadius: 12, style: .continuous)+ .fill(self.theme.palette.cardBackground.opacity(self.colorScheme == .light ? 0.72 : 0.52))+ .overlay(+ RoundedRectangle(cornerRadius: 12, style: .continuous)+ .stroke(self.theme.palette.cardBorder.opacity(0.7), lineWidth: 1)+ )+ )+ .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))++ Text("FluidVoice tries microphones from top to bottom. Drag to reorder; unavailable devices keep their place.")+ .font(self.theme.typography.bodySmall)+ .foregroundStyle(self.settingsSecondaryText)+ .fixedSize(horizontal: false, vertical: true)+ }}- func inputDeviceTitle(_ device: AudioDevice.Device) -> String {- var annotations: [String] = []- if self.cachedDefaultInputName.isEmpty == false,- device.name == self.cachedDefaultInputName- {- annotations.append("System Default")+ func microphonePriorityRow(+ _ entry: SettingsStore.MicrophonePriorityEntry,+ rank: Int+ ) -> some View {+ let connectedDevice = self.inputDevices.first { $0.uid == entry.uid }+ let isAvailable = connectedDevice.map {+ self.appServices.microphonePreferenceCoordinator.isInputDeviceAvailable($0)+ } ?? false+ let isActive = entry.uid == self.microphonePreferenceCoordinator.confirmedActiveInputUID && isAvailable+ let isHovered = self.hoveredMicrophoneUID == entry.uid++ return HStack(spacing: 10) {+ Image(systemName: "line.3.horizontal")+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(self.settingsTertiaryText.opacity(self.isMicrophonePriorityEditingDisabled ? 0.35 : 0.72))+ .frame(width: 18, height: 30)+ .contentShape(Rectangle())+ .onDrag {+ self.draggedMicrophoneUID = entry.uid+ return NSItemProvider(object: entry.uid as NSString)+ } preview: {+ ZStack {+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .fill(self.theme.palette.cardBackground)+ .overlay(+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .stroke(self.theme.palette.cardBorder.opacity(0.8), lineWidth: 1)+ )++ Image(systemName: "line.3.horizontal")+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(self.settingsTitleText)+ }+ .frame(width: 30, height: 30)+ .shadow(color: Color.black.opacity(0.18), radius: 5, y: 2)+ }+ .allowsHitTesting(self.isMicrophonePriorityEditingDisabled == false)+ .accessibilityHidden(true)++ Text("\(rank).")+ .font(self.theme.typography.bodySmall)+ .foregroundStyle(self.settingsSecondaryText)+ .monospacedDigit()+ .frame(width: 22, alignment: .trailing)++ Text(entry.name)+ .font(self.theme.typography.bodyStrong)+ .foregroundStyle(isAvailable ? self.settingsTitleText : self.settingsSecondaryText)+ .lineLimit(1)++ Spacer(minLength: 8)++ if isHovered {+ Button(role: .destructive) {+ self.removeMicrophonePriorityEntry(entry)+ } label: {+ Image(systemName: "trash")+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(Color(nsColor: .systemRed).opacity(0.82))+ .frame(width: 24, height: 24)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .disabled(self.isMicrophonePriorityEditingDisabled)+ .help("Remove \(entry.name) from microphone priority")+ .accessibilityLabel("Remove \(entry.name)")+ .transition(.opacity)+ } else if isActive {+ Circle()+ .fill(Color(nsColor: .systemGreen))+ .frame(width: 7, height: 7)+ .shadow(color: Color(nsColor: .systemGreen).opacity(0.45), radius: 3)+ .accessibilityLabel("Active microphone")+ } else if isAvailable == false {+ Text("Unavailable")+ .font(self.theme.typography.bodySmall)+ .foregroundStyle(self.settingsSecondaryText)+ }+ }+ .padding(.horizontal, 12)+ .frame(minHeight: 42)+ .contentShape(Rectangle())+ .opacity(isAvailable ? 1 : 0.62)+ .onHover { isHovering in+ let animation: Animation? = self.accessibilityReduceMotion ? nil : .easeOut(duration: 0.12)+ withAnimation(animation) {+ if isHovering {+ self.hoveredMicrophoneUID = entry.uid+ } else if self.hoveredMicrophoneUID == entry.uid {+ self.hoveredMicrophoneUID = nil+ }+ }+ }+ .onDrop(+ of: [UTType.plainText.identifier],+ delegate: MicrophonePriorityDropDelegate(+ targetUID: entry.uid,+ settings: self.settings,+ draggedUID: self.$draggedMicrophoneUID,+ reorderAnimation: self.accessibilityReduceMotion ? nil : .easeInOut(duration: 0.16),+ onDropCompleted: self.refreshActiveInputSelection+ )+ )+ .contextMenu {+ Button("Move Up") {+ self.settings.moveMicrophonePriority(uid: entry.uid, by: -1)+ self.refreshActiveInputSelection()+ }+ .disabled(self.isMicrophonePriorityEditingDisabled || rank == 1)++ Button("Move Down") {+ self.settings.moveMicrophonePriority(uid: entry.uid, by: 1)+ self.refreshActiveInputSelection()+ }+ .disabled(self.isMicrophonePriorityEditingDisabled || rank == self.settings.microphonePriority.count)++ Divider()++ Button("Remove from Priority", role: .destructive) {+ self.removeMicrophonePriorityEntry(entry)+ }+ .disabled(self.isMicrophonePriorityEditingDisabled)+ }+ .accessibilityElement(children: .ignore)+ .accessibilityLabel("Priority \(rank), \(entry.name)")+ .accessibilityValue(isActive ? "Active" : (isAvailable ? "Available" : "Unavailable"))+ .accessibilityAction(named: "Move up") {+ guard self.isMicrophonePriorityEditingDisabled == false, rank > 1 else { return }+ self.settings.moveMicrophonePriority(uid: entry.uid, by: -1)+ self.refreshActiveInputSelection()}- if device.isBuiltIn {- annotations.append("Recommended")- } else if device.isBluetooth {- annotations.append("Reduces output quality")+ .accessibilityAction(named: "Move down") {+ guard self.isMicrophonePriorityEditingDisabled == false,+ rank < self.settings.microphonePriority.count+ else { return }+ self.settings.moveMicrophonePriority(uid: entry.uid, by: 1)+ self.refreshActiveInputSelection()}+ .accessibilityAction(named: "Remove from priority") {+ guard self.isMicrophonePriorityEditingDisabled == false else { return }+ self.removeMicrophonePriorityEntry(entry)+ }+ }++ var isMicrophonePriorityEditingDisabled: Bool {+ self.asr.isRunning || self.asr.isStarting+ }- guard annotations.isEmpty == false else { return device.name }- return "\(device.name) (\(annotations.joined(separator: ", ")))"+ func refreshActiveInputSelection() {+ // Reuse the existing off-main hardware refresh so the green active+ // indicator and next capture resolve from live Core Audio.+ self.refreshDevices()+ }++ func removeMicrophonePriorityEntry(_ entry: SettingsStore.MicrophonePriorityEntry) {+ self.hoveredMicrophoneUID = nil+ self.settings.removeMicrophoneFromPriority(+ uid: entry.uid,+ isConnected: self.inputDevices.contains { $0.uid == entry.uid }+ )+ self.refreshActiveInputSelection()+ }++ var selectedInputDevice: AudioDevice.Device? {+ guard let confirmedUID = self.microphonePreferenceCoordinator.confirmedActiveInputUID else {+ return nil+ }+ return self.inputDevices.first { $0.uid == confirmedUID }}@ViewBuildervar microphoneQualityGuidance: some View {if self.selectedInputDevice?.isBluetooth == true {self.microphoneQualityGuidanceRow(- message: "AirPods and other Bluetooth microphones reduce headphone audio quality. Use your Mac’s microphone or another non-Bluetooth mic.",+ message: "Bluetooth microphone mode can reduce headphone playback quality. Prefer a wired, USB, or display microphone when available.",systemImage: "exclamationmark.triangle.fill",color: self.theme.palette.warning)} else {self.microphoneQualityGuidanceRow(- message: "For the best audio quality, use your Mac’s microphone or another non-Bluetooth mic.",+ message: "This order applies only to FluidVoice and does not change your macOS input.",systemImage: "info.circle",color: self.settingsSecondaryText)@@ -2307,20 +2490,45 @@ private extension SettingsView {.fixedSize(horizontal: false, vertical: true)}}+}++private struct MicrophonePriorityDropDelegate: DropDelegate {+ let targetUID: String+ let settings: SettingsStore+ @Binding var draggedUID: String?+ let reorderAnimation: Animation?+ let onDropCompleted: () -> Void++ func validateDrop(info _: DropInfo) -> Bool {+ self.draggedUID != nil+ }- var microphoneModeInfo: some View {- HStack(alignment: .top, spacing: 8) {- Image(systemName: "info.circle")- .foregroundStyle(self.settingsSecondaryText)- .font(self.theme.typography.bodyStrong)- Text(- "FluidVoice uses this microphone independently from the macOS default."+ func dropEntered(info _: DropInfo) {+ guard let draggedUID = self.draggedUID,+ draggedUID != self.targetUID+ else { return }++ let entries = self.settings.microphonePriority+ guard let sourceIndex = entries.firstIndex(where: { $0.uid == draggedUID }),+ let targetIndex = entries.firstIndex(where: { $0.uid == self.targetUID })+ else { return }++ withAnimation(self.reorderAnimation) {+ self.settings.reorderMicrophonePriority(+ fromOffsets: IndexSet(integer: sourceIndex),+ toOffset: targetIndex > sourceIndex ? targetIndex + 1 : targetIndex)- .font(self.theme.typography.bodySmall)- .foregroundStyle(self.settingsSecondaryText)- .fixedSize(horizontal: false, vertical: true)}- .padding(.vertical, 4)+ }++ func dropUpdated(info _: DropInfo) -> DropProposal? {+ DropProposal(operation: .move)+ }++ func performDrop(info _: DropInfo) -> Bool {+ self.draggedUID = nil+ self.onDropCompleted()+ return true}}@@ -2333,14 +2541,25 @@ private final class SettingsPersistentScroller: NSScroller {private struct SettingsPersistentScrollView<Content: View>: NSViewRepresentable {private let theme: AppThemeprivate let colorScheme: ColorScheme+ private let microphoneSettingsScrollRequest: Intprivate let content: Content- init(theme: AppTheme, colorScheme: ColorScheme, @ViewBuilder content: () -> Content) {+ init(+ theme: AppTheme,+ colorScheme: ColorScheme,+ microphoneSettingsScrollRequest: Int,+ @ViewBuilder content: () -> Content+ ) {self.theme = themeself.colorScheme = colorScheme+ self.microphoneSettingsScrollRequest = microphoneSettingsScrollRequestself.content = content()}+ func makeCoordinator() -> Coordinator {+ Coordinator()+ }+private var hostedContent: AnyView {AnyView(self.content@@ -2378,7 +2597,7 @@ private struct SettingsPersistentScrollView<Content: View>: NSViewRepresentablereturn scrollView}- func updateNSView(_ scrollView: NSScrollView, context _: Context) {+ func updateNSView(_ scrollView: NSScrollView, context: Context) {(scrollView.documentView as? NSHostingView<AnyView>)?.rootView = self.hostedContentscrollView.hasVerticalScroller = truescrollView.hasHorizontalScroller = false@@ -2389,6 +2608,56 @@ private struct SettingsPersistentScrollView<Content: View>: NSViewRepresentable}scrollView.verticalScroller?.isHidden = falsescrollView.verticalScroller?.alphaValue = 1++ guard self.microphoneSettingsScrollRequest > 0,+ context.coordinator.lastMicrophoneSettingsScrollRequest != self.microphoneSettingsScrollRequest+ else { return }+ context.coordinator.lastMicrophoneSettingsScrollRequest = self.microphoneSettingsScrollRequest+ DispatchQueue.main.async {+ Self.scrollToMicrophoneSettings(in: scrollView)+ }+ }++ private static func scrollToMicrophoneSettings(in scrollView: NSScrollView) {+ guard let documentView = scrollView.documentView else { return }+ documentView.layoutSubtreeIfNeeded()+ guard let anchor = documentView.descendant(withIdentifier: MicrophoneSettingsScrollAnchor.identifier) else {+ return+ }++ let targetRect = anchor.convert(anchor.bounds, to: documentView)+ let maximumY = max(0, documentView.bounds.height - scrollView.contentView.bounds.height)+ let targetY = min(maximumY, max(0, targetRect.minY - 12))+ scrollView.contentView.scroll(to: NSPoint(x: 0, y: targetY))+ scrollView.reflectScrolledClipView(scrollView.contentView)+ }++ final class Coordinator {+ var lastMicrophoneSettingsScrollRequest = 0+ }+}++private struct MicrophoneSettingsScrollAnchor: NSViewRepresentable {+ static let identifier = NSUserInterfaceItemIdentifier("FluidVoice.MicrophoneSettingsScrollAnchor")++ func makeNSView(context _: Context) -> NSView {+ let view = NSView()+ view.identifier = Self.identifier+ return view+ }++ func updateNSView(_: NSView, context _: Context) {}+}++private extension NSView {+ func descendant(withIdentifier identifier: NSUserInterfaceItemIdentifier) -> NSView? {+ if self.identifier == identifier { return self }+ for subview in self.subviews {+ if let match = subview.descendant(withIdentifier: identifier) {+ return match+ }+ }+ return nil}}diff --git a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swiftindex 4b2d8403..5efa4fcd 100644--- a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift+++ b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift@@ -26,6 +26,11 @@ final class DictionaryCorrectionOverlayController {self.panel?.isVisible == true}+ func transientOverlayLayoutDidChange() {+ guard self.isPresented else { return }+ self.resizeAndPositionPanel(animated: true)+ }+func show(candidate: AutomaticDictionaryCorrectionCandidate,onOutcome: @escaping (AutomaticDictionarySuggestionOutcome) -> Void@@ -199,7 +204,9 @@ final class DictionaryCorrectionOverlayController {let visibleFrame = screen.visibleFramelet requestedY = visibleFrame.minY + CGFloat(SettingsStore.shared.overlayBottomOffset)- let y = max(visibleFrame.minY + 10, min(requestedY, visibleFrame.maxY - size.height - 40))+ let microphoneToastY = MicrophoneChangeOverlayController.shared.topEdge(on: screen).map { $0 + 10 }+ let stackedY = max(requestedY, microphoneToastY ?? requestedY)+ let y = max(visibleFrame.minY + 10, min(stackedY, visibleFrame.maxY - size.height - 40))let frame = NSRect(x: screen.frame.midX - size.width / 2,y: y,@@ -219,6 +226,347 @@ final class DictionaryCorrectionOverlayController {}}+enum MicrophoneChangePresentation: Hashable {+ case startupSelection+ case activeChange+}++struct MicrophoneChangeNotice: Hashable {+ let previousName: String?+ let currentName: String?+ let presentation: MicrophoneChangePresentation+}++@MainActor+final class MicrophoneChangeOverlayController {+ static let shared = MicrophoneChangeOverlayController()++ private static let displayDurationNanoseconds: UInt64 = 5_000_000_000+ private var panel: NSPanel?+ private var hostingView: NSHostingView<MicrophoneChangeOverlayView>?+ private var dismissTask: Task<Void, Never>?+ private var generation: UInt64 = 0++ private init() {}++ func show(_ notice: MicrophoneChangeNotice) {+ guard Bundle.main.bundleIdentifier == "com.FluidApp.app" else { return }+ self.generation &+= 1+ let currentGeneration = self.generation+ self.dismissTask?.cancel()++ let rootView = MicrophoneChangeOverlayView(+ notice: notice,+ displayDuration: Double(Self.displayDurationNanoseconds) / 1_000_000_000,+ startedAt: Date(),+ onSettings: { [weak self] in+ self?.hide()+ NotificationCenter.default.post(name: .openMicrophoneSettingsRequested, object: nil)+ },+ onDismiss: { [weak self] in self?.hide() }+ )+ if let hostingView = self.hostingView {+ hostingView.rootView = rootView+ } else {+ self.createPanel(rootView: rootView)+ }++ guard let panel = self.panel else { return }+ self.resizeAndPositionPanel()+ DebugLogger.shared.debug(+ "Showing microphone change overlay frame=\(NSStringFromRect(panel.frame))",+ source: "MicrophoneChangeOverlay"+ )+ panel.alphaValue = 0+ panel.orderFrontRegardless()+ self.animate(duration: 0.12) {+ panel.animator().alphaValue = 1+ }+ DictionaryCorrectionOverlayController.shared.transientOverlayLayoutDidChange()++ self.dismissTask = Task { @MainActor [weak self] in+ try? await Task.sleep(nanoseconds: Self.displayDurationNanoseconds)+ guard !Task.isCancelled,+ let self,+ self.generation == currentGeneration+ else { return }+ self.hide()+ }+ }++ func hide() {+ self.generation &+= 1+ let hideGeneration = self.generation+ self.dismissTask?.cancel()+ self.dismissTask = nil+ guard let panel, panel.isVisible else { return }+ self.animate(duration: 0.1) {+ panel.animator().alphaValue = 0+ } completion: { [weak self] in+ MainActor.assumeIsolated {+ guard let self, self.generation == hideGeneration else { return }+ self.panel?.orderOut(nil)+ self.panel?.alphaValue = 1+ DictionaryCorrectionOverlayController.shared.transientOverlayLayoutDidChange()+ }+ }+ }++ func topEdge(on screen: NSScreen) -> CGFloat? {+ guard let panel, panel.isVisible, panel.frame.intersects(screen.frame) else { return nil }+ return panel.frame.maxY+ }++ private func createPanel(rootView: MicrophoneChangeOverlayView) {+ let panel = NSPanel(+ contentRect: .zero,+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered,+ defer: false+ )+ panel.isFloatingPanel = true+ panel.level = .floating+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]+ panel.isOpaque = false+ panel.backgroundColor = .clear+ panel.hasShadow = true+ panel.hidesOnDeactivate = false+ panel.animationBehavior = .none++ let hostingView = NSHostingView(rootView: rootView)+ hostingView.wantsLayer = true+ hostingView.layer?.backgroundColor = .clear+ panel.contentView = hostingView+ self.panel = panel+ self.hostingView = hostingView+ }++ private func resizeAndPositionPanel() {+ guard let panel, let hostingView,+ let screen = OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main+ else { return }+ hostingView.layoutSubtreeIfNeeded()+ let fittingSize = hostingView.fittingSize+ let size = NSSize(width: ceil(fittingSize.width), height: ceil(fittingSize.height))+ guard size.width > 0, size.height > 0 else { return }+ hostingView.frame = NSRect(origin: .zero, size: size)+ let visibleFrame = screen.visibleFrame+ let frame = NSRect(+ x: screen.frame.midX - size.width / 2,+ y: visibleFrame.minY + 10,+ width: size.width,+ height: size.height+ )+ panel.setFrame(frame, display: true)+ }++ private func animate(+ duration: TimeInterval,+ changes: () -> Void,+ completion: (() -> Void)? = nil+ ) {+ guard NSWorkspace.shared.accessibilityDisplayShouldReduceMotion == false else {+ changes()+ completion?()+ return+ }+ NSAnimationContext.runAnimationGroup { context in+ context.duration = duration+ context.timingFunction = CAMediaTimingFunction(name: .easeOut)+ changes()+ } completionHandler: {+ completion?()+ }+ }+}++private struct MicrophoneChangeOverlayView: View {+ let notice: MicrophoneChangeNotice+ let displayDuration: TimeInterval+ let startedAt: Date+ let onSettings: () -> Void+ let onDismiss: () -> Void++ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var isCloseHovered = false+ @State private var isSettingsHovered = false++ var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ HStack(spacing: 7) {+ Image(systemName: self.notice.currentName == nil ? "mic.slash.fill" : "mic.fill")+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(.white.opacity(0.78))+ .frame(width: 24, height: 24)++ Text(self.title)+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.white.opacity(0.72))++ Spacer(minLength: 8)++ Button(action: self.onDismiss) {+ Image(systemName: "xmark")+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(.white.opacity(self.isCloseHovered ? 0.95 : 0.68))+ .frame(width: 24, height: 24)+ .background(Circle().fill(Color.white.opacity(self.isCloseHovered ? 0.13 : 0.06)))+ }+ .buttonStyle(.plain)+ .contentShape(Circle())+ .onHover { self.isCloseHovered = $0 }+ .help("Dismiss")+ .accessibilityLabel("Dismiss microphone change")+ }++ Text(self.detailText)+ .font(.system(size: 16, weight: .semibold))+ .foregroundStyle(.white)+ .lineLimit(1)+ .minimumScaleFactor(0.72)+ .frame(maxWidth: .infinity, alignment: .leading)++ HStack(spacing: 8) {+ Text(self.explanation)+ .font(.system(size: 11))+ .foregroundStyle(.white.opacity(0.58))+ .lineLimit(1)++ Spacer(minLength: 8)++ Button("Settings", action: self.onSettings)+ .buttonStyle(TransientOverlaySettingsButtonStyle(isHovered: self.isSettingsHovered))+ .onHover { self.isSettingsHovered = $0 }+ .help("Open microphone settings")+ }+ }+ .padding(.horizontal, 14)+ .padding(.vertical, 12)+ .frame(width: 460)+ .background(TransientOverlayBackground())+ .overlay(alignment: .bottomLeading) {+ TransientOverlayCountdownBar(+ startedAt: self.startedAt,+ duration: self.displayDuration,+ reduceMotion: self.reduceMotion+ )+ }+ .preferredColorScheme(.dark)+ .id(self.notice)+ }++ private var detailText: String {+ if self.notice.presentation == .startupSelection,+ let currentName = self.notice.currentName+ {+ return currentName+ }+ switch (self.notice.previousName, self.notice.currentName) {+ case let (previous?, current?):+ return "\(previous) → \(current)"+ case let (previous?, nil):+ return "\(previous) is no longer available"+ case let (nil, current?):+ return "Now using \(current)"+ case (nil, nil):+ return "Connect or restore a microphone in Settings"+ }+ }++ private var title: String {+ if self.notice.presentation == .startupSelection {+ return "Microphone selected"+ }+ return self.notice.currentName == nil ? "Microphone unavailable" : "Microphone changed"+ }++ private var explanation: String {+ if self.notice.currentName == nil {+ return "Choose an available microphone in Settings."+ }+ if self.notice.presentation == .startupSelection {+ return "FluidVoice will try this microphone first when you dictate."+ }+ return "FluidVoice confirmed this microphone is capturing audio."+ }+}++private struct TransientOverlaySettingsButtonStyle: ButtonStyle {+ let isHovered: Bool++ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(.white.opacity(configuration.isPressed ? 1 : 0.9))+ .padding(.horizontal, 10)+ .frame(height: 28)+ .background(+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .fill(Color.white.opacity(configuration.isPressed ? 0.20 : self.isHovered ? 0.14 : 0.09))+ .overlay(+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .strokeBorder(+ Color.white.opacity(configuration.isPressed ? 0.28 : 0.12),+ lineWidth: 1+ )+ )+ )+ .scaleEffect(configuration.isPressed ? 0.97 : 1)+ .animation(.easeOut(duration: 0.1), value: configuration.isPressed)+ }+}++private struct TransientOverlayCountdownBar: View {+ let startedAt: Date+ let duration: TimeInterval+ let reduceMotion: Bool++ var body: some View {+ TimelineView(.animation(minimumInterval: self.reduceMotion ? 1 : 1 / 30)) { context in+ GeometryReader { proxy in+ ZStack(alignment: .leading) {+ Capsule()+ .fill(Color.white.opacity(0.12))+ Capsule()+ .fill(Color.white.opacity(0.82))+ .frame(width: proxy.size.width * self.remainingProgress(at: context.date))+ }+ }+ }+ .frame(height: 3)+ .padding(.horizontal, 14)+ .padding(.bottom, 3)+ .allowsHitTesting(false)+ }++ private func remainingProgress(at date: Date) -> CGFloat {+ guard self.duration > 0 else { return 0 }+ return CGFloat(max(0, min(1, 1 - date.timeIntervalSince(self.startedAt) / self.duration)))+ }+}++private struct TransientOverlayBackground: View {+ var body: some View {+ RoundedRectangle(cornerRadius: 18, style: .continuous)+ .fill(Color.black)+ .overlay(+ RoundedRectangle(cornerRadius: 18, style: .continuous)+ .strokeBorder(+ LinearGradient(+ colors: [.white.opacity(0.15), .white.opacity(0.08)],+ startPoint: .top,+ endPoint: .bottom+ ),+ lineWidth: 1+ )+ )+ }+}++extension Notification.Name {+ static let openMicrophoneSettingsRequested = Notification.Name("OpenMicrophoneSettingsRequested")+}+private struct AutomaticDictionaryCorrectionOverlayView: View {@ObservedObject var session: AutomaticDictionaryTrainingSession@ObservedObject private var settings = SettingsStore.shared@@ -246,7 +594,7 @@ private struct AutomaticDictionaryCorrectionOverlayView: View {.padding(.horizontal, 14).padding(.vertical, 12).frame(width: 460)- .background(self.overlayBackground)+ .background(TransientOverlayBackground()).overlay(alignment: .bottomLeading) {if self.session.screen == .choice {GeometryReader { proxy in@@ -558,22 +906,6 @@ private struct AutomaticDictionaryCorrectionOverlayView: View {.strokeBorder(Color.white.opacity(0.09), lineWidth: 1))}-- private var overlayBackground: some View {- RoundedRectangle(cornerRadius: 18, style: .continuous)- .fill(Color.black)- .overlay(- RoundedRectangle(cornerRadius: 18, style: .continuous)- .strokeBorder(- LinearGradient(- colors: [.white.opacity(0.15), .white.opacity(0.08)],- startPoint: .top,- endPoint: .bottom- ),- lineWidth: 1- )- )- }}private struct CorrectionOverlayReadinessRing: View {diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swiftindex 8292a846..5ed8960c 100644--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift@@ -12,7 +12,9 @@ final class HotkeyShortcutTests: XCTestCase {private let pasteLastTranscriptionEnabledKey = "PasteLastTranscriptionShortcutEnabled"private let microphoneSelectionModeKey = "MicrophoneSelectionMode"private let preferredInputDeviceUIDKey = "PreferredInputDeviceUID"- private let appOnlyMicMigrationVersionKey = "AppOnlyMicrophoneSelectionMigrationVersion"+ private let microphonePriorityKey = "MicrophonePriority"+ private let suppressedMicrophoneUIDsKey = "SuppressedMicrophoneUIDs"+ private let microphoneSelectionMigrationVersionKey = "AppOnlyMicrophoneSelectionMigrationVersion"private let experimentalDirectAudioCaptureEnabledKey = "ExperimentalDirectAudioCaptureEnabled"@MainActor@@ -138,44 +140,66 @@ final class HotkeyShortcutTests: XCTestCase {}@MainActor- func testSystemModeBackupRestartsAppOnlyMicrophoneMigration() async throws {+ func testLegacySystemModeBackupQueuesMicrophonePriorityMigration() async throws {let document = await BackupService.shared.makeBackupDocument()try self.withRestoredDefaults(keys: [self.microphoneSelectionModeKey,self.preferredInputDeviceUIDKey,- self.appOnlyMicMigrationVersionKey,+ self.microphoneSelectionMigrationVersionKey,]) {- SettingsStore.shared.appMicSelectionMigrationVersion = 1+ SettingsStore.shared.microphoneSelectionMigrationVersion = 4let encoded = try BackupService.shared.encode(document)var root = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any])var settings = try XCTUnwrap(root["settings"] as? [String: Any])settings["microphoneSelectionMode"] = SettingsStore.MicrophoneSelectionMode.system.rawValuesettings["preferredInputDeviceUID"] = "legacy-system-mic"+ settings.removeValue(forKey: "microphonePriority")root["settings"] = settingslet backup = try BackupService.shared.decode(JSONSerialization.data(withJSONObject: root))SettingsStore.shared.restore(from: backup.settings)XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "legacy-system-mic")- XCTAssertEqual(SettingsStore.shared.microphoneSelectionMode, .manual)- XCTAssertEqual(SettingsStore.shared.appMicSelectionMigrationVersion, 0)+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMode, .system)+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 0)}}@MainActor- func testAppOnlyBackupKeepsCompletedMicrophoneMigration() async {+ func testPriorityBackupKeepsCompletedMicrophoneMigration() async {let document = await BackupService.shared.makeBackupDocument()- self.withRestoredDefaults(keys: [self.appOnlyMicMigrationVersionKey]) {- SettingsStore.shared.appMicSelectionMigrationVersion = 1+ self.withRestoredDefaults(keys: [self.microphoneSelectionMigrationVersionKey]) {+ SettingsStore.shared.microphoneSelectionMigrationVersion = 4SettingsStore.shared.restore(from: document.settings)- XCTAssertEqual(SettingsStore.shared.appMicSelectionMigrationVersion, 1)+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 4)}}+ @MainActor+ func testPriorityBackupRoundTripsRemovedConnectedMicrophones() async {+ let originalPriority = SettingsStore.shared.microphonePriority+ let originalSuppressedUIDs = SettingsStore.shared.suppressedMicrophoneUIDs+ defer {+ SettingsStore.shared.microphonePriority = originalPriority+ SettingsStore.shared.suppressedMicrophoneUIDs = originalSuppressedUIDs+ }++ SettingsStore.shared.microphonePriority = [+ .init(uid: "kept-mic", name: "Kept Microphone"),+ ]+ SettingsStore.shared.suppressedMicrophoneUIDs = ["removed-connected-mic"]+ let document = await BackupService.shared.makeBackupDocument()++ XCTAssertEqual(document.settings.suppressedMicrophoneUIDs, ["removed-connected-mic"])+ SettingsStore.shared.suppressedMicrophoneUIDs = []+ SettingsStore.shared.restore(from: document.settings)+ XCTAssertEqual(SettingsStore.shared.suppressedMicrophoneUIDs, ["removed-connected-mic"])+ }+func testDirectAudioCaptureIsEnabledWhenLegacyPreferenceIsUnset() {self.withRestoredDefaults(keys: [self.experimentalDirectAudioCaptureEnabledKey]) {UserDefaults.standard.removeObject(forKey: self.experimentalDirectAudioCaptureEnabledKey)@@ -204,45 +228,62 @@ final class HotkeyShortcutTests: XCTestCase {))}- func testDirectRecoveryTracksOnlyPreferredInputAvailability() {+ func testDirectRecoveryTracksPriorityInputAvailability() {let previousUIDs = Set(["preferred", "built-in"])- XCTAssertFalse(AudioCaptureIdlePolicy.didPreferredInputAvailabilityChange(- preferredInputUID: "preferred",+ XCTAssertFalse(AudioCaptureIdlePolicy.didResolvedPriorityInputChange(+ priorityInputUIDs: ["preferred"],previousInputUIDs: previousUIDs,currentInputUIDs: previousUIDs.union(["unrelated"])))- XCTAssertTrue(AudioCaptureIdlePolicy.didPreferredInputAvailabilityChange(- preferredInputUID: "preferred",+ XCTAssertTrue(AudioCaptureIdlePolicy.didResolvedPriorityInputChange(+ priorityInputUIDs: ["preferred"],previousInputUIDs: previousUIDs,currentInputUIDs: ["built-in"]))- XCTAssertTrue(AudioCaptureIdlePolicy.didPreferredInputAvailabilityChange(- preferredInputUID: "preferred",+ XCTAssertTrue(AudioCaptureIdlePolicy.didResolvedPriorityInputChange(+ priorityInputUIDs: ["preferred"],previousInputUIDs: ["built-in"],currentInputUIDs: previousUIDs))+ XCTAssertFalse(AudioCaptureIdlePolicy.didResolvedPriorityInputChange(+ priorityInputUIDs: ["preferred", "built-in", "lower-priority"],+ previousInputUIDs: previousUIDs,+ currentInputUIDs: previousUIDs.union(["lower-priority"])+ ))}func testPendingMicrophoneMigrationRetriesWhenDevicesAppear() {XCTAssertFalse(AudioCaptureIdlePolicy.shouldReconcileInputSelection(- preferredInputUID: "disconnected-usb",+ priorityInputUIDs: ["disconnected-usb"],migrationPending: true,previousInputUIDs: [],currentInputUIDs: []))XCTAssertTrue(AudioCaptureIdlePolicy.shouldReconcileInputSelection(- preferredInputUID: "disconnected-usb",+ priorityInputUIDs: ["disconnected-usb"],migrationPending: true,previousInputUIDs: [],currentInputUIDs: ["built-in"]))XCTAssertTrue(AudioCaptureIdlePolicy.shouldReconcileInputSelection(- preferredInputUID: nil,+ priorityInputUIDs: [],migrationPending: false,previousInputUIDs: [],currentInputUIDs: ["built-in"]))+ XCTAssertTrue(AudioCaptureIdlePolicy.shouldReconcileInputSelection(+ priorityInputUIDs: ["preferred", "fallback"],+ migrationPending: false,+ previousInputUIDs: ["fallback"],+ currentInputUIDs: []+ ))+ XCTAssertTrue(AudioCaptureIdlePolicy.shouldReconcileInputSelection(+ priorityInputUIDs: ["unavailable", "new", "fallback"],+ migrationPending: false,+ previousInputUIDs: ["fallback"],+ currentInputUIDs: ["new", "fallback"]+ ))}func testEngineConfigurationChangesRecoverOnlyDuringCaptureTransitions() {@@ -406,14 +447,14 @@ final class HotkeyShortcutTests: XCTestCase {}}- func testMicrophoneSelectionModeIsAlwaysAppOnly() throws {+ func testLegacySystemModeRemainsReadableForPriorityMigration() throws {try self.withRestoredDefaults(keys: [self.microphoneSelectionModeKey]) {UserDefaults.standard.set(SettingsStore.MicrophoneSelectionMode.system.rawValue,forKey: self.microphoneSelectionModeKey)- XCTAssertEqual(SettingsStore.shared.microphoneSelectionMode, .manual)+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMode, .system)}}@@ -424,6 +465,8 @@ final class HotkeyShortcutTests: XCTestCase {SettingsStore.shared.recordInputDeviceSelection("studio-mic")XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "studio-mic")+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), ["studio-mic"])+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMode, .manual)}}@@ -457,18 +500,18 @@ final class HotkeyShortcutTests: XCTestCase {}@MainActor- func testMicrophoneMigrationChoosesBuiltInOnce() throws {+ func testLegacySystemModeSeedsPriorityFromCurrentDefault() throws {try self.withRestoredDefaults(keys: [self.microphoneSelectionModeKey,self.preferredInputDeviceUIDKey,- self.appOnlyMicMigrationVersionKey,+ self.microphoneSelectionMigrationVersionKey,]) {UserDefaults.standard.set(SettingsStore.MicrophoneSelectionMode.system.rawValue,forKey: self.microphoneSelectionModeKey)- SettingsStore.shared.preferredInputDeviceUID = "airpods"- SettingsStore.shared.appMicSelectionMigrationVersion = 0+ SettingsStore.shared.preferredInputDeviceUID = "internal"+ SettingsStore.shared.microphoneSelectionMigrationVersion = 0let devices = FakeAudioDeviceManager(inputs: [Self.device(@@ -482,20 +525,20 @@ final class HotkeyShortcutTests: XCTestCase {)let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)- coordinator.migrateToAppOnlySelectionIfNeeded()+ coordinator.migrateMicrophonePriorityIfNeeded()- XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "internal")+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "airpods")XCTAssertEqual(SettingsStore.shared.microphoneSelectionMode, .manual)- XCTAssertEqual(SettingsStore.shared.appMicSelectionMigrationVersion, 1)+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 4)XCTAssertEqual(UserDefaults.standard.string(forKey: self.microphoneSelectionModeKey),SettingsStore.MicrophoneSelectionMode.manual.rawValue)XCTAssertEqual(devices.defaultInputUID, "airpods")- SettingsStore.shared.recordInputDeviceSelection("airpods")- coordinator.migrateToAppOnlySelectionIfNeeded()- XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "airpods")+ SettingsStore.shared.recordInputDeviceSelection("internal")+ coordinator.migrateMicrophonePriorityIfNeeded()+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "internal")}}@@ -503,28 +546,33 @@ final class HotkeyShortcutTests: XCTestCase {func testMicrophoneMigrationWaitsForAUsableDeviceList() throws {try self.withRestoredDefaults(keys: [self.preferredInputDeviceUIDKey,- self.appOnlyMicMigrationVersionKey,+ self.microphoneSelectionMigrationVersionKey,]) {SettingsStore.shared.preferredInputDeviceUID = "airpods"- SettingsStore.shared.appMicSelectionMigrationVersion = 0+ SettingsStore.shared.microphoneSelectionMigrationVersion = 0let devices = FakeAudioDeviceManager(inputs: [], defaultInputUID: nil)let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)- coordinator.migrateToAppOnlySelectionIfNeeded()+ coordinator.migrateMicrophonePriorityIfNeeded()XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "airpods")- XCTAssertEqual(SettingsStore.shared.appMicSelectionMigrationVersion, 0)+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 0)}}@MainActor- func testMicrophoneMigrationWithoutBuiltInPreservesAvailableSelection() throws {+ func testManualMicrophoneMigrationPreservesAvailableSelection() throws {try self.withRestoredDefaults(keys: [+ self.microphoneSelectionModeKey,self.preferredInputDeviceUIDKey,- self.appOnlyMicMigrationVersionKey,+ self.microphoneSelectionMigrationVersionKey,]) {+ UserDefaults.standard.set(+ SettingsStore.MicrophoneSelectionMode.manual.rawValue,+ forKey: self.microphoneSelectionModeKey+ )SettingsStore.shared.preferredInputDeviceUID = "studio-mic"- SettingsStore.shared.appMicSelectionMigrationVersion = 0+ SettingsStore.shared.microphoneSelectionMigrationVersion = 0let devices = FakeAudioDeviceManager(inputs: [Self.device(uid: "display-mic", name: "Display Mic"),@@ -534,10 +582,10 @@ final class HotkeyShortcutTests: XCTestCase {)let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)- coordinator.migrateToAppOnlySelectionIfNeeded()+ coordinator.migrateMicrophonePriorityIfNeeded()XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "studio-mic")- XCTAssertEqual(SettingsStore.shared.appMicSelectionMigrationVersion, 1)+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 4)XCTAssertEqual(devices.defaultInputUID, "display-mic")}}@@ -546,10 +594,10 @@ final class HotkeyShortcutTests: XCTestCase {func testMicrophoneMigrationWithoutBuiltInReplacesMissingSelectionWithDefault() throws {try self.withRestoredDefaults(keys: [self.preferredInputDeviceUIDKey,- self.appOnlyMicMigrationVersionKey,+ self.microphoneSelectionMigrationVersionKey,]) {- SettingsStore.shared.preferredInputDeviceUID = "disconnected-usb"- SettingsStore.shared.appMicSelectionMigrationVersion = 0+ SettingsStore.shared.preferredInputDeviceUID = "internal"+ SettingsStore.shared.microphoneSelectionMigrationVersion = 0let devices = FakeAudioDeviceManager(inputs: [Self.device(uid: "display-mic", name: "Display Mic"),@@ -559,22 +607,22 @@ final class HotkeyShortcutTests: XCTestCase {)let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)- coordinator.migrateToAppOnlySelectionIfNeeded()+ coordinator.migrateMicrophonePriorityIfNeeded()XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "studio-mic")- XCTAssertEqual(SettingsStore.shared.appMicSelectionMigrationVersion, 1)+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 4)XCTAssertEqual(devices.defaultInputUID, "studio-mic")}}@MainActor- func testCompletedMigrationReconcilesMissingSavedInputAtLaunch() throws {+ func testVersionOneMigrationRepairsForcedBuiltInSelection() throws {try self.withRestoredDefaults(keys: [self.preferredInputDeviceUIDKey,- self.appOnlyMicMigrationVersionKey,+ self.microphoneSelectionMigrationVersionKey,]) {- SettingsStore.shared.preferredInputDeviceUID = "disconnected-usb"- SettingsStore.shared.appMicSelectionMigrationVersion = 1+ SettingsStore.shared.preferredInputDeviceUID = "internal"+ SettingsStore.shared.microphoneSelectionMigrationVersion = 1let builtIn = Self.device(uid: "internal",name: "MacBook Pro Microphone",@@ -586,17 +634,74 @@ final class HotkeyShortcutTests: XCTestCase {)let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)- let reconciled = coordinator.reconcileAppOnlySelection(+ let reconciled = coordinator.reconcileMicrophoneSelection(availableInputs: devices.inputs,defaultInputUID: devices.defaultInputUID)- XCTAssertEqual(reconciled, builtIn)- XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "internal")+ XCTAssertEqual(reconciled?.uid, "usb")+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "usb")+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 4)XCTAssertEqual(devices.defaultInputUID, "usb")}}+ @MainActor+ func testVersionOneMigrationRepairsUnavailableBuiltInForClamshellUser() throws {+ try self.withRestoredDefaults(keys: [+ self.preferredInputDeviceUIDKey,+ self.microphoneSelectionMigrationVersionKey,+ ]) {+ SettingsStore.shared.preferredInputDeviceUID = "internal"+ SettingsStore.shared.microphoneSelectionMigrationVersion = 1+ let webcam = Self.device(uid: "webcam", name: "Webcam Microphone")+ let devices = FakeAudioDeviceManager(+ inputs: [webcam],+ defaultInputUID: webcam.uid+ )+ let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)++ let reconciled = coordinator.reconcileMicrophoneSelection(+ availableInputs: devices.inputs,+ defaultInputUID: devices.defaultInputUID+ )++ XCTAssertEqual(reconciled, webcam)+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "webcam")+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 4)+ }+ }++ @MainActor+ func testVersionOneMigrationPreservesDisconnectedExternalSelection() throws {+ try self.withRestoredDefaults(keys: [+ self.preferredInputDeviceUIDKey,+ self.microphoneSelectionMigrationVersionKey,+ ]) {+ SettingsStore.shared.preferredInputDeviceUID = "disconnected-studio-mic"+ SettingsStore.shared.microphoneSelectionMigrationVersion = 1+ let fallback = Self.device(uid: "internal", name: "MacBook Pro Microphone")+ let devices = FakeAudioDeviceManager(+ inputs: [fallback],+ defaultInputUID: fallback.uid+ )+ let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)++ let reconciled = coordinator.reconcileMicrophoneSelection(+ availableInputs: devices.inputs,+ defaultInputUID: devices.defaultInputUID+ )++ XCTAssertEqual(reconciled, fallback)+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "disconnected-studio-mic")+ XCTAssertEqual(+ SettingsStore.shared.microphonePriority.map(\.uid),+ ["disconnected-studio-mic", fallback.uid]+ )+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 4)+ }+ }+@MainActorfunc testMicrophoneCoordinatorKeepsAvailableUserSelection() throws {try self.withRestoredDefaults(keys: [@@ -625,11 +730,13 @@ final class HotkeyShortcutTests: XCTestCase {}@MainActor- func testMicrophoneCoordinatorFallsBackToBuiltInWhenSelectionDisappears() throws {+ func testMicrophoneCoordinatorUsesDefaultTemporarilyAndRestoresSelection() throws {try self.withRestoredDefaults(keys: [self.preferredInputDeviceUIDKey,+ self.microphoneSelectionMigrationVersionKey,]) {SettingsStore.shared.preferredInputDeviceUID = "airpods"+ SettingsStore.shared.microphoneSelectionMigrationVersion = 2let builtIn = Self.device(uid: "internal",name: "MacBook Pro Microphone",@@ -643,32 +750,36 @@ final class HotkeyShortcutTests: XCTestCase {let previewFallback = coordinator.inputDeviceForCapture()- XCTAssertEqual(previewFallback, builtIn)+ XCTAssertEqual(previewFallback?.uid, "usb")XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "airpods")XCTAssertEqual(devices.defaultInputUID, "usb")- let settledFallback = coordinator.inputDeviceForCapture(+ let settledFallback = coordinator.reconcileMicrophoneSelection(availableInputs: devices.inputs,- defaultInputUID: devices.defaultInputUID,- persistFallback: true+ defaultInputUID: devices.defaultInputUID)- XCTAssertEqual(settledFallback, builtIn)- XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "internal")+ XCTAssertEqual(settledFallback?.uid, "usb")+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "airpods")XCTAssertEqual(devices.defaultInputUID, "usb")- let afterReconnect = coordinator.inputDeviceForCapture(availableInputs: [- builtIn,- Self.device(uid: "airpods", name: "AirPods"),- ])- XCTAssertEqual(afterReconnect, builtIn)- XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "internal")+ let airPods = Self.device(uid: "airpods", name: "AirPods")+ let afterReconnect = coordinator.reconcileMicrophoneSelection(+ availableInputs: [builtIn, airPods],+ defaultInputUID: builtIn.uid+ )+ XCTAssertEqual(afterReconnect, airPods)+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "airpods")}}@MainActorfunc testMicrophoneCoordinatorUsesCurrentInputWhenNoBuiltInExists() throws {- try self.withRestoredDefaults(keys: [self.preferredInputDeviceUIDKey]) {+ try self.withRestoredDefaults(keys: [+ self.preferredInputDeviceUIDKey,+ self.microphoneSelectionMigrationVersionKey,+ ]) {SettingsStore.shared.preferredInputDeviceUID = "disconnected"+ SettingsStore.shared.microphoneSelectionMigrationVersion = 2let currentInput = Self.device(uid: "usb", name: "USB Mic")let devices = FakeAudioDeviceManager(inputs: [Self.device(uid: "other", name: "Other Mic"), currentInput],@@ -681,13 +792,306 @@ final class HotkeyShortcutTests: XCTestCase {XCTAssertEqual(previewFallback, currentInput)XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "disconnected")- let settledFallback = coordinator.inputDeviceForCapture(+ let settledFallback = coordinator.reconcileMicrophoneSelection(availableInputs: devices.inputs,- defaultInputUID: devices.defaultInputUID,- persistFallback: true+ defaultInputUID: devices.defaultInputUID)XCTAssertEqual(settledFallback, currentInput)- XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "usb")+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "disconnected")+ }+ }++ @MainActor+ func testMicrophonePriorityWinsOverDefaultAndBuiltIn() throws {+ try self.withRestoredDefaults(keys: [+ self.microphoneSelectionModeKey,+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ self.microphoneSelectionMigrationVersionKey,+ ]) {+ let builtIn = Self.device(+ uid: "internal",+ name: "MacBook Pro Microphone",+ transportType: kAudioDeviceTransportTypeBuiltIn+ )+ let usb = Self.device(uid: "usb", name: "USB Microphone")+ SettingsStore.shared.microphonePriority = [+ .init(uid: usb.uid, name: usb.name),+ .init(uid: builtIn.uid, name: builtIn.name),+ ]+ SettingsStore.shared.microphoneSelectionMode = .manual+ SettingsStore.shared.microphoneSelectionMigrationVersion = 4+ let devices = FakeAudioDeviceManager(+ inputs: [builtIn, usb],+ defaultInputUID: builtIn.uid+ )+ let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)++ XCTAssertEqual(coordinator.inputDeviceForCapture(), usb)+ }+ }++ @MainActor+ func testResolvedMicrophoneIsNotMarkedActiveUntilFirstPCMConfirmation() throws {+ try self.withRestoredDefaults(keys: [+ self.microphoneSelectionModeKey,+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ self.microphoneSelectionMigrationVersionKey,+ ]) {+ let preferred = Self.device(uid: "preferred", name: "Preferred")+ SettingsStore.shared.microphonePriority = [+ .init(uid: preferred.uid, name: preferred.name),+ ]+ SettingsStore.shared.microphoneSelectionMode = .manual+ SettingsStore.shared.microphoneSelectionMigrationVersion = 4+ let coordinator = MicrophonePreferenceCoordinator(+ settings: SettingsStore.shared,+ devices: FakeAudioDeviceManager(+ inputs: [preferred],+ defaultInputUID: preferred.uid+ )+ )++ XCTAssertEqual(+ coordinator.reconcileMicrophoneSelection(+ availableInputs: [preferred],+ defaultInputUID: preferred.uid+ ),+ preferred+ )+ XCTAssertNil(coordinator.confirmedActiveInputUID)++ coordinator.confirmActiveSelection(uid: preferred.uid, name: preferred.name)+ XCTAssertEqual(coordinator.confirmedActiveInputUID, preferred.uid)+ }+ }++ @MainActor+ func testFailedPriorityDeviceAdvancesWithoutChangingSavedOrder() throws {+ try self.withRestoredDefaults(keys: [+ self.microphoneSelectionModeKey,+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ self.microphoneSelectionMigrationVersionKey,+ ]) {+ let studio = Self.device(uid: "studio", name: "Studio Microphone")+ let webcam = Self.device(uid: "webcam", name: "Webcam Microphone")+ SettingsStore.shared.microphonePriority = [+ .init(uid: studio.uid, name: studio.name),+ .init(uid: webcam.uid, name: webcam.name),+ ]+ SettingsStore.shared.microphoneSelectionMode = .manual+ SettingsStore.shared.microphoneSelectionMigrationVersion = 4+ let devices = FakeAudioDeviceManager(+ inputs: [studio, webcam],+ defaultInputUID: studio.uid+ )+ let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)++ let fallback = coordinator.inputDeviceForCapture(+ availableInputs: devices.inputs,+ defaultInputUID: devices.defaultInputUID,+ excluding: [studio.uid]+ )++ XCTAssertEqual(fallback, webcam)+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), [studio.uid, webcam.uid])+ }+ }++ @MainActor+ func testLegacySystemModeIsNormalizedWithoutReorderingPriority() throws {+ try self.withRestoredDefaults(keys: [+ self.microphoneSelectionModeKey,+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ self.microphoneSelectionMigrationVersionKey,+ ]) {+ let studio = Self.device(uid: "studio", name: "Studio Microphone")+ let system = Self.device(uid: "system", name: "System Microphone")+ SettingsStore.shared.microphonePriority = [+ .init(uid: studio.uid, name: studio.name),+ .init(uid: system.uid, name: system.name),+ ]+ SettingsStore.shared.microphoneSelectionMode = .system+ SettingsStore.shared.microphoneSelectionMigrationVersion = 3+ let devices = FakeAudioDeviceManager(+ inputs: [studio, system],+ defaultInputUID: system.uid+ )+ let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)++ let selected = coordinator.reconcileMicrophoneSelection(+ availableInputs: devices.inputs,+ defaultInputUID: devices.defaultInputUID+ )++ XCTAssertEqual(selected, studio)+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), [studio.uid, system.uid])+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMode, .manual)+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 4)+ }+ }++ @MainActor+ func testPrioritySkipsUnusableEnumeratedDeviceAndRestoresItAfterReconnect() throws {+ try self.withRestoredDefaults(keys: [+ self.microphoneSelectionModeKey,+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ self.microphoneSelectionMigrationVersionKey,+ ]) {+ let external = Self.device(uid: "external", name: "External Microphone")+ let builtIn = Self.device(+ uid: "internal",+ name: "MacBook Pro Microphone",+ transportType: kAudioDeviceTransportTypeBuiltIn+ )+ SettingsStore.shared.microphonePriority = [+ .init(uid: external.uid, name: external.name),+ .init(uid: builtIn.uid, name: builtIn.name),+ ]+ SettingsStore.shared.microphoneSelectionMode = .manual+ SettingsStore.shared.microphoneSelectionMigrationVersion = 4+ let devices = FakeAudioDeviceManager(+ inputs: [external, builtIn],+ defaultInputUID: builtIn.uid,+ unusableInputUIDs: [external.uid]+ )+ let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)++ XCTAssertEqual(coordinator.inputDeviceForCapture(), builtIn)++ devices.unusableInputUIDs.remove(external.uid)++ XCTAssertEqual(coordinator.inputDeviceForCapture(), external)+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), [external.uid, builtIn.uid])+ }+ }++ @MainActor+ func testClamshellSkipsEnumeratedUnusableBuiltInMicrophone() throws {+ try self.withRestoredDefaults(keys: [+ self.microphoneSelectionModeKey,+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ self.microphoneSelectionMigrationVersionKey,+ ]) {+ let builtIn = Self.device(+ uid: "internal",+ name: "MacBook Pro Microphone",+ transportType: kAudioDeviceTransportTypeBuiltIn+ )+ let external = Self.device(uid: "external", name: "External Microphone")+ SettingsStore.shared.microphonePriority = [+ .init(uid: builtIn.uid, name: builtIn.name),+ .init(uid: external.uid, name: external.name),+ ]+ SettingsStore.shared.microphoneSelectionMode = .manual+ SettingsStore.shared.microphoneSelectionMigrationVersion = 4+ let devices = FakeAudioDeviceManager(+ inputs: [builtIn, external],+ defaultInputUID: builtIn.uid,+ isClamshellClosed: true+ )+ let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)++ XCTAssertEqual(coordinator.inputDeviceForCapture(), external)+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), [builtIn.uid, external.uid])++ devices.isClamshellClosed = false++ XCTAssertEqual(coordinator.inputDeviceForCapture(), builtIn)+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), [builtIn.uid, external.uid])+ }+ }++ func testNewMicrophoneEntersSecondAndStaysAfterDisconnecting() throws {+ try self.withRestoredDefaults(keys: [+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ ]) {+ let airPods = Self.device(uid: "airpods", name: "AirPods Microphone")+ let builtIn = Self.device(+ uid: "internal",+ name: "MacBook Pro Microphone",+ transportType: kAudioDeviceTransportTypeBuiltIn+ )+ let usb = Self.device(uid: "usb", name: "USB Microphone")+ SettingsStore.shared.microphonePriority = [+ .init(uid: airPods.uid, name: airPods.name),+ ]++ SettingsStore.shared.reconcileMicrophonePriority(with: [builtIn])+ XCTAssertEqual(+ SettingsStore.shared.microphonePriority.map(\.uid),+ [airPods.uid, builtIn.uid]+ )++ SettingsStore.shared.reconcileMicrophonePriority(with: [builtIn, usb])+ XCTAssertEqual(+ SettingsStore.shared.microphonePriority.map(\.uid),+ [airPods.uid, usb.uid, builtIn.uid]+ )++ SettingsStore.shared.reconcileMicrophonePriority(with: [builtIn])+ XCTAssertEqual(+ SettingsStore.shared.microphonePriority.map(\.uid),+ [airPods.uid, usb.uid, builtIn.uid]+ )+ }+ }++ @MainActor+ func testRemovedConnectedMicrophoneReturnsAtSecondAfterReconnect() throws {+ try self.withRestoredDefaults(keys: [+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ self.suppressedMicrophoneUIDsKey,+ ]) {+ let builtIn = Self.device(uid: "internal", name: "MacBook Pro Microphone")+ let usb = Self.device(uid: "usb", name: "USB Microphone")+ SettingsStore.shared.microphonePriority = [+ .init(uid: builtIn.uid, name: builtIn.name),+ .init(uid: usb.uid, name: usb.name),+ ]+ SettingsStore.shared.removeMicrophoneFromPriority(uid: builtIn.uid, isConnected: true)++ let devices = FakeAudioDeviceManager(inputs: [builtIn, usb], defaultInputUID: builtIn.uid)+ let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), [usb.uid])+ XCTAssertEqual(coordinator.inputDeviceForCapture(), usb)++ SettingsStore.shared.reconcileMicrophonePriority(with: [builtIn, usb])+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), [usb.uid])++ SettingsStore.shared.reconcileMicrophonePriority(with: [usb])+ SettingsStore.shared.reconcileMicrophonePriority(with: [builtIn, usb])+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), [usb.uid, builtIn.uid])+ }+ }++ @MainActor+ func testSelectingOrRestoringMicrophoneClearsRemovalSuppression() async {+ let originalSuppressedUIDs = SettingsStore.shared.suppressedMicrophoneUIDs+ SettingsStore.shared.suppressedMicrophoneUIDs = []+ let document = await BackupService.shared.makeBackupDocument()+ defer { SettingsStore.shared.suppressedMicrophoneUIDs = originalSuppressedUIDs }++ self.withRestoredDefaults(keys: [+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ self.suppressedMicrophoneUIDsKey,+ ]) {+ let microphone = Self.device(uid: "restored", name: "Restored Microphone")+ SettingsStore.shared.suppressedMicrophoneUIDs = [microphone.uid]+ SettingsStore.shared.recordInputDeviceSelection(microphone.uid, name: microphone.name)+ XCTAssertFalse(SettingsStore.shared.suppressedMicrophoneUIDs.contains(microphone.uid))++ SettingsStore.shared.suppressedMicrophoneUIDs = [microphone.uid]+ SettingsStore.shared.restore(from: document.settings)+ XCTAssertTrue(SettingsStore.shared.suppressedMicrophoneUIDs.isEmpty)}}@@ -708,15 +1112,35 @@ final class HotkeyShortcutTests: XCTestCase {private func withRestoredDefaults(keys: [String], run: () throws -> Void) rethrows {let defaults = UserDefaults.standard+ let touchesMicrophoneSettings = keys.contains { key in+ key == self.microphoneSelectionModeKey ||+ key == self.preferredInputDeviceUIDKey ||+ key == self.microphoneSelectionMigrationVersionKey ||+ key == self.microphonePriorityKey ||+ key == self.suppressedMicrophoneUIDsKey+ }+ let managedKeys = touchesMicrophoneSettings+ ? Array(Set(keys + [+ self.microphoneSelectionModeKey,+ self.preferredInputDeviceUIDKey,+ self.microphonePriorityKey,+ self.suppressedMicrophoneUIDsKey,+ self.microphoneSelectionMigrationVersionKey,+ ]))+ : keysvar snapshot: [String: Any] = [:]- for key in keys {+ for key in managedKeys {if let value = defaults.object(forKey: key) {snapshot[key] = value}}+ if touchesMicrophoneSettings {+ defaults.removeObject(forKey: self.microphonePriorityKey)+ defaults.removeObject(forKey: self.suppressedMicrophoneUIDsKey)+ }defer {- for key in keys {+ for key in managedKeys {if let previous = snapshot[key] {defaults.set(previous, forKey: key)} else {@@ -733,10 +1157,19 @@ final class HotkeyShortcutTests: XCTestCase {private final class FakeAudioDeviceManager: AudioDeviceManaging {let inputs: [AudioDevice.Device]var defaultInputUID: String?-- init(inputs: [AudioDevice.Device], defaultInputUID: String?) {+ var unusableInputUIDs: Set<String>+ var isClamshellClosed: Bool++ init(+ inputs: [AudioDevice.Device],+ defaultInputUID: String?,+ unusableInputUIDs: Set<String> = [],+ isClamshellClosed: Bool = false+ ) {self.inputs = inputsself.defaultInputUID = defaultInputUID+ self.unusableInputUIDs = unusableInputUIDs+ self.isClamshellClosed = isClamshellClosed}func listInputDevices() -> [AudioDevice.Device] {@@ -747,4 +1180,8 @@ private final class FakeAudioDeviceManager: AudioDeviceManaging {guard let defaultInputUID else { return nil }return self.inputs.first { $0.uid == defaultInputUID }}++ func isInputDeviceUsable(_ device: AudioDevice.Device) -> Bool {+ self.unusableInputUIDs.contains(device.uid) == false+ }}