Skip to content

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

fix microphone onboarding edge cases

altic-dev444bf1e6e6e3
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 16d7fead..50b378d4 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -1867,6 +1867,10 @@ final class SettingsStore: ObservableObject {
return mode
}
+ var hasStoredMicSelectionModeForMigration: Bool {
+ self.defaults.object(forKey: Keys.microphoneSelectionMode) != nil
+ }
+
var microphoneSelectionMode: MicrophoneSelectionMode {
get {
guard let rawValue = self.defaults.string(forKey: Keys.microphoneSelectionMode),
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 79d59f15..c0688010 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -1528,8 +1528,12 @@ final class ASRService: ObservableObject {
self.isMicrophonePreviewRequested,
self.isRunning == false,
self.isStarting == false,
- self.isTerminating == false
- else { return }
+ self.isTerminating == false,
+ Task.isCancelled == false
+ else {
+ self.abandonMicrophonePreviewRequestIfOwned(operationGeneration)
+ return
+ }
self.activeAudioCaptureBackend = .none
self.isMicrophonePreviewActive = false
self.audioLevelSubject.send(0)
@@ -1542,8 +1546,12 @@ final class ASRService: ObservableObject {
self.isMicrophonePreviewRequested,
self.isRunning == false,
self.isStarting == false,
- self.isTerminating == false
- else { return }
+ self.isTerminating == false,
+ Task.isCancelled == false
+ else {
+ self.abandonMicrophonePreviewRequestIfOwned(operationGeneration)
+ return
+ }
self.microphonePreviewError = nil
self.audioCapturePipeline.setLevelMonitoringEnabled(true)
@@ -1608,6 +1616,7 @@ final class ASRService: ObservableObject {
self.microphonePreviewOperationGeneration &+= 1
let operationGeneration = self.microphonePreviewOperationGeneration
self.isMicrophonePreviewRequested = false
+ self.microphonePreviewError = nil
guard self.isMicrophonePreviewActive || self.audioCapturePipeline.isLevelMonitoringEnabled else {
return
}
@@ -1623,6 +1632,33 @@ final class ASRService: ObservableObject {
self.audioLevelSubject.send(0)
}
+ private func abandonMicrophonePreviewRequestIfOwned(_ operationGeneration: UInt64) {
+ guard operationGeneration == self.microphonePreviewOperationGeneration else { return }
+ self.isMicrophonePreviewRequested = false
+ self.audioCapturePipeline.setLevelMonitoringEnabled(false)
+ self.activeAudioCaptureBackend = .none
+ self.isMicrophonePreviewActive = false
+ self.microphonePreviewError = nil
+ self.audioLevelSubject.send(0)
+ }
+
+ private func handOffMicrophonePreviewToCaptureStartIfNeeded() {
+ guard self.isMicrophonePreviewRequested ||
+ self.isMicrophonePreviewActive ||
+ self.audioCapturePipeline.isLevelMonitoringEnabled
+ else { return }
+
+ // Invalidate preview ownership without stopping Core Audio. The direct
+ // lifecycle serializes any in-flight preview start, and recording can
+ // reuse the already-running input without losing opening PCM.
+ self.microphonePreviewOperationGeneration &+= 1
+ self.isMicrophonePreviewRequested = false
+ self.audioCapturePipeline.setLevelMonitoringEnabled(false)
+ self.isMicrophonePreviewActive = false
+ self.microphonePreviewError = nil
+ self.audioLevelSubject.send(0)
+ }
+
func openSystemSettingsForMic() {
if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone") {
NSWorkspace.shared.open(url)
@@ -1673,20 +1709,10 @@ final class ASRService: ObservableObject {
self.isStarting = true
defer { self.finishAudioCaptureStart() }
- // Reserve the start before preview teardown yields. Press-and-hold release
- // must be able to see and cancel this handoff before capture hardware starts.
- if self.isMicrophonePreviewActive || self.audioCapturePipeline.isLevelMonitoringEnabled {
- await self.stopMicrophonePreview()
- guard startGeneration == self.audioCaptureStartGeneration,
- self.isTerminating == false
- else {
- DebugLogger.shared.debug(
- "Audio capture start cancelled during microphone preview handoff",
- source: "ASRService"
- )
- return .failed
- }
- }
+ // Reserve the start before relinquishing preview ownership so a
+ // press-and-hold release can cancel the handoff. Keep the running input
+ // alive; startConfiguredAudioCapture reuses it for zero-stop first PCM.
+ self.handOffMicrophonePreviewToCaptureStartIfNeeded()
// Reset media pause state for this session
self.didPauseMediaForThisSession = false
diff --git a/Sources/Fluid/Services/DirectCoreAudioInput.swift b/Sources/Fluid/Services/DirectCoreAudioInput.swift
index 779b826b..58566de4 100644
--- a/Sources/Fluid/Services/DirectCoreAudioInput.swift
+++ b/Sources/Fluid/Services/DirectCoreAudioInput.swift
@@ -844,6 +844,29 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
guard let validatedInput = self.input else {
throw Self.error("Direct Core Audio input disappeared before start.")
}
+ if validatedInput.isRunning {
+ let runningFingerprint = try self.fingerprintReader(deviceID)
+ guard runningFingerprint == validatedInput.formatFingerprint,
+ validatedInput.openPacketGateIfClean()
+ else {
+ throw Self.error(
+ "Direct Core Audio format changed while reusing running input generation " +
+ "\(self.generation)."
+ )
+ }
+ self.publishSnapshot(
+ phase: .running,
+ input: validatedInput,
+ fingerprint: validatedInput.formatFingerprint
+ )
+ Self.log(
+ "Direct capture start reused running input generation=\(self.generation) " +
+ "device='\(deviceName)'",
+ level: .debug
+ )
+ continuation.resume(returning: self.snapshot)
+ return
+ }
self.publishSnapshot(
phase: .starting,
input: validatedInput,
diff --git a/Sources/Fluid/Services/MicrophonePreferenceCoordinator.swift b/Sources/Fluid/Services/MicrophonePreferenceCoordinator.swift
index b996f037..c32fac79 100644
--- a/Sources/Fluid/Services/MicrophonePreferenceCoordinator.swift
+++ b/Sources/Fluid/Services/MicrophonePreferenceCoordinator.swift
@@ -97,6 +97,14 @@ final class MicrophonePreferenceCoordinator: ObservableObject {
[input] + availableInputs.filter { $0.uid != input.uid }
} ?? availableInputs
let previousMode = self.settings.storedMicSelectionModeForMigration
+ let hasStoredMode = self.settings.hasStoredMicSelectionModeForMigration
+ let preserveLegacyStoredSelection =
+ migrationVersion == 0 &&
+ hasStoredMode == false &&
+ self.settings.preferredInputDeviceUID?.isEmpty == false &&
+ self.settings.suppressedMicrophoneUIDs.contains(
+ self.settings.preferredInputDeviceUID ?? ""
+ ) == false
if migrationVersion >= 2,
let preferredUID = self.settings.preferredInputDeviceUID,
preferredUID.isEmpty == false
@@ -115,7 +123,9 @@ final class MicrophonePreferenceCoordinator: ObservableObject {
enumeratedPreferredInput?.isBuiltIn != true &&
Self.isLikelyBuiltInMicrophoneUID(self.settings.preferredInputDeviceUID) == false
if preferredInput == nil,
- preserveDisconnectedManualSelection || preserveDisconnectedVersionOneExternal,
+ preserveDisconnectedManualSelection ||
+ preserveDisconnectedVersionOneExternal ||
+ preserveLegacyStoredSelection,
let preferredUID = self.settings.preferredInputDeviceUID,
preferredUID.isEmpty == false
{
@@ -135,6 +145,10 @@ final class MicrophonePreferenceCoordinator: ObservableObject {
selectedInput = preferredInput
?? defaultInput
?? self.fallbackInput(from: usableInputs, defaultInputUID: defaultInputUID)
+ } else if preserveLegacyStoredSelection {
+ selectedInput = preferredInput
+ ?? defaultInput
+ ?? self.fallbackInput(from: usableInputs, defaultInputUID: defaultInputUID)
} else if migrationVersion == 0 {
// A fresh install must mirror macOS's selected input, not permanently
// promote whichever fallback happened to enumerate first at launch.
@@ -159,6 +173,13 @@ final class MicrophonePreferenceCoordinator: ObservableObject {
if migrationVersion == 0,
previousMode == .system
{
+ // Keep the visible priority list and removal bookkeeping useful
+ // while HAL has not exposed its default input yet. Migration stays
+ // pending, so a later default-input event can still promote the
+ // actual macOS selection to first place.
+ let preferredUIDBeforePendingReconciliation = self.settings.preferredInputDeviceUID
+ self.settings.reconcileMicrophonePriority(with: availableInputs)
+ self.settings.preferredInputDeviceUID = preferredUIDBeforePendingReconciliation
return
}
self.settings.reconcileMicrophonePriority(with: migrationInputs)
@@ -205,6 +226,10 @@ final class MicrophonePreferenceCoordinator: ObservableObject {
self.lastResolvedInputUID = uid
self.lastResolvedInputName = name
+ // Onboarding owns microphone feedback inside its setup panel. A global
+ // floating notice here would cover that flow and duplicate the picker.
+ guard self.settings.shouldShowOnboarding == false else { return }
+
guard previousUID != nil, uid != previousUID else {
if self.startupNoticeEligibilityEnabled {
self.scheduleStartupNoticeAfterSelectionSettles()
diff --git a/Sources/Fluid/UI/WelcomeView.swift b/Sources/Fluid/UI/WelcomeView.swift
index 24377be0..fb4b5b11 100644
--- a/Sources/Fluid/UI/WelcomeView.swift
+++ b/Sources/Fluid/UI/WelcomeView.swift
@@ -993,7 +993,12 @@ struct OnboardingFlowView: View {
self.stopOnboardingMicrophonePreview()
}
.onReceive(self.asr.audioLevelPublisher) { level in
- guard self.step == .permissions, self.isMicrophoneReady else { return }
+ guard self.step == .permissions,
+ self.isMicrophoneReady,
+ self.asr.isMicrophonePreviewActive,
+ self.asr.isRunning == false,
+ self.asr.isStarting == false
+ else { return }
let now = ProcessInfo.processInfo.systemUptime
guard level == 0 || now - self.lastOnboardingMicrophoneLevelUpdate >= 0.05 else {
return
diff --git a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift
index 2ca8207f..f8497f4c 100644
--- a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift
+++ b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift
@@ -253,6 +253,42 @@ final class DirectAudioReliabilityTests: XCTestCase {
XCTAssertEqual(recorder.maximumConcurrentOperations, 1)
}
+ func testStartingRunningInputReusesHardwareWithoutStopOrRestart() async throws {
+ let fingerprint = makeFingerprint(sampleRate: 48_000, bufferFrameSize: 512)
+ let recorder = DirectAudioEventRecorder()
+ let factory = FakeDirectAudioInputFactory(
+ fingerprints: [fingerprint],
+ recorder: recorder
+ )
+ let controller = DirectCoreAudioLifecycleController(
+ packetHandler: { _, _, _, _, _ in },
+ inputFactory: { deviceID, _ in
+ try factory.make(deviceID: deviceID)
+ },
+ fingerprintReader: { _ in fingerprint },
+ installsHardwareListeners: false,
+ onFormatInvalidated: { _ in }
+ )
+
+ _ = try await controller.start(
+ deviceID: fingerprint.deviceID,
+ deviceName: "Test microphone",
+ reason: "preview"
+ )
+ let reused = try await controller.start(
+ deviceID: fingerprint.deviceID,
+ deviceName: "Test microphone",
+ reason: "dictation_handoff"
+ )
+ await controller.shutdown(reason: "test_complete")
+
+ XCTAssertEqual(reused.phase, .running)
+ XCTAssertEqual(
+ recorder.events,
+ ["make:48000", "start:48000", "invalidate:48000"]
+ )
+ }
+
func testFailedStopPoisonsLifecycleAndPreventsReplacement() async throws {
let fingerprint = makeFingerprint(sampleRate: 48_000, bufferFrameSize: 512)
let recorder = DirectAudioEventRecorder()
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index 0275b5bf..c1976cd4 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -698,16 +698,41 @@ final class HotkeyShortcutTests: XCTestCase {
}
@MainActor
- func testFreshInstallWaitsForMacOSDefaultInsteadOfPersistingFallback() throws {
+ func testLegacyStoredMicrophoneWithoutModeKeyKeepsUserSelection() throws {
try self.withRestoredDefaults(keys: [
self.microphoneSelectionModeKey,
self.preferredInputDeviceUIDKey,
self.microphoneSelectionMigrationVersionKey,
]) {
- UserDefaults.standard.set(
- SettingsStore.MicrophoneSelectionMode.system.rawValue,
- forKey: self.microphoneSelectionModeKey
+ UserDefaults.standard.removeObject(forKey: self.microphoneSelectionModeKey)
+ SettingsStore.shared.preferredInputDeviceUID = "studio-mic"
+ SettingsStore.shared.microphoneSelectionMigrationVersion = 0
+ let devices = FakeAudioDeviceManager(
+ inputs: [
+ Self.device(uid: "internal", name: "MacBook Pro Microphone"),
+ Self.device(uid: "studio-mic", name: "Studio Mic"),
+ ],
+ defaultInputUID: "internal"
)
+ let coordinator = MicrophonePreferenceCoordinator(settings: .shared, devices: devices)
+
+ coordinator.migrateMicrophonePriorityIfNeeded()
+
+ XCTAssertEqual(SettingsStore.shared.microphonePriority.first?.uid, "studio-mic")
+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "studio-mic")
+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMode, .manual)
+ XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 4)
+ }
+ }
+
+ @MainActor
+ func testFreshInstallKeepsPriorityUsableWhileWaitingForMacOSDefault() throws {
+ try self.withRestoredDefaults(keys: [
+ self.microphoneSelectionModeKey,
+ self.preferredInputDeviceUIDKey,
+ self.microphoneSelectionMigrationVersionKey,
+ ]) {
+ UserDefaults.standard.removeObject(forKey: self.microphoneSelectionModeKey)
SettingsStore.shared.preferredInputDeviceUID = nil
SettingsStore.shared.microphoneSelectionMigrationVersion = 0
let fallback = Self.device(uid: "fallback", name: "Available Fallback")
@@ -726,7 +751,7 @@ final class HotkeyShortcutTests: XCTestCase {
)
XCTAssertEqual(temporarySelection, fallback)
- XCTAssertTrue(SettingsStore.shared.microphonePriority.isEmpty)
+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), [fallback.uid])
XCTAssertNil(SettingsStore.shared.preferredInputDeviceUID)
XCTAssertEqual(SettingsStore.shared.microphoneSelectionMigrationVersion, 0)