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

Fixed sound sync issue - added new sync settings to sync b/w FV and system sound ; also have independent control

altic-dev6ef68cca44c1
diff --git a/Info.plist b/Info.plist
index 9ebf6a3f..d422388b 100644
--- a/Info.plist
+++ b/Info.plist
@@ -11,7 +11,7 @@
<key>CFBundleVersion</key>
<string>1</string>
<key>CFBundleShortVersionString</key>
- <string>1.5.1-beta.3</string>
+ <string>1.5.1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>LSApplicationCategoryType</key>
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index c94475a9..67770a96 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -36,12 +36,17 @@ enum SidebarItem: Hashable {
// NOTE: Streaming and AI response parsing is now handled by LLMClient
struct ContentView: View {
- @StateObject private var audioObserver = AudioHardwareObserver()
- @StateObject private var asr = ASRService()
+ @EnvironmentObject private var appServices: AppServices
@StateObject private var mouseTracker = MousePositionTracker()
@StateObject private var commandModeService = CommandModeService()
@StateObject private var rewriteModeService = RewriteModeService()
@EnvironmentObject private var menuBarManager: MenuBarManager
+
+ // Computed properties to access shared services from AppServices container
+ // This maintains backward compatibility with the existing code while
+ // removing the duplicate service instances that cause startup crashes.
+ private var asr: ASRService { self.appServices.asr }
+ private var audioObserver: AudioHardwareObserver { self.appServices.audioObserver }
@Environment(\.theme) private var theme
@State private var hotkeyManager: GlobalHotkeyManager? = nil
@State private var hotkeyManagerInitialized: Bool = false
@@ -160,21 +165,30 @@ struct ContentView: View {
// Initialize menu bar after app is ready (prevents window server crash)
self.menuBarManager.initializeMenuBar()
- // Configure menu bar manager with ASR service
- self.menuBarManager.configure(asrService: self.asr)
-
- // CRITICAL FIX: Defer all audio subsystem initialization by 1.5 seconds.
- // There is a known race condition between CoreAudio's HALSystem initialization (triggered by
- // AudioObjectAddPropertyListenerBlock) and SwiftUI's AttributeGraph metadata processing during app launch.
- // This race causes an EXC_BAD_ACCESS (SIGSEGV) at 0x0.
- // By waiting for the main runloop to settle and SwiftUI to finish its initial layout passes,
- // we ensure the audio system initializes safely.
+ // DEFENSIVE STRATEGY: Multi-layer protection against startup crash
+ // Layer 1: Service consolidation (already done - no duplicate @StateObjects)
+ // Layer 2: Lazy service initialization (services created on first access)
+ // Layer 3: Startup gate (signalUIReady + 1.5s delay)
+ // Layer 4: Delayed audio initialization (CoreAudio listeners start after UI is stable)
+ //
+ // This delay ensures SwiftUI's AttributeGraph has finished processing before
+ // any heavy audio system work begins. The race condition between CoreAudio's
+ // HALSystem initialization and SwiftUI metadata processing causes EXC_BAD_ACCESS at 0x0.
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
+ DebugLogger.shared.info("🚦 Startup delay complete, signaling UI ready...", source: "ContentView")
+
+ // Signal that UI is ready - this enables service initialization
+ self.appServices.signalUIReady()
+
DebugLogger.shared.info("🔊 Starting delayed audio initialization...", source: "ContentView")
+ // Now it's safe to access services (they'll be lazily created)
self.audioObserver.startObserving()
self.asr.initialize()
+ // Configure menu bar manager with ASR service AFTER services are initialized
+ self.menuBarManager.configure(asrService: self.appServices.asr)
+
// Load available devices
self.refreshDevices()
@@ -510,24 +524,52 @@ struct ContentView: View {
}
}
.overlay(alignment: .center) {}
- .alert(self.asr.errorTitle, isPresented: self.$asr.showError) {
+ .alert(
+ self.asr.errorTitle,
+ isPresented: Binding(
+ get: { self.asr.showError },
+ set: { self.asr.showError = $0 }
+ )
+ ) {
Button("OK", role: .cancel) {}
} message: {
Text(self.asr.errorMessage)
}
.onChange(of: self.audioObserver.changeTick) { _, _ in
- // Hardware change detected → refresh device lists only
- // NOTE: We do NOT force system defaults here anymore.
- // FluidVoice should not hijack system-wide audio routing.
- // The saved preferences are only used when FluidVoice actively records.
+ // Hardware change detected → refresh device lists
self.refreshDevices()
- // Just sync the UI to show current system defaults (don't force them)
- if let sysIn = AudioDevice.getDefaultInputDevice()?.uid {
- self.selectedInputUID = sysIn
- }
- if let sysOut = AudioDevice.getDefaultOutputDevice()?.uid {
- self.selectedOutputUID = sysOut
+ // Only sync UI with system defaults when sync is enabled
+ // When sync is disabled, keep the user's preferred device selection
+ if SettingsStore.shared.syncAudioDevicesWithSystem {
+ // Sync mode: Update UI to match current system defaults
+ if let sysIn = AudioDevice.getDefaultInputDevice()?.uid {
+ self.selectedInputUID = sysIn
+ }
+ if let sysOut = AudioDevice.getDefaultOutputDevice()?.uid {
+ self.selectedOutputUID = sysOut
+ }
+ } else {
+ // Independent mode: Only update if preferred device is no longer available
+ if let prefIn = SettingsStore.shared.preferredInputDeviceUID,
+ inputDevices.contains(where: { $0.uid == prefIn })
+ {
+ self.selectedInputUID = prefIn
+ } else if let sysIn = AudioDevice.getDefaultInputDevice()?.uid {
+ // Fallback to system default if preferred device disconnected
+ self.selectedInputUID = sysIn
+ SettingsStore.shared.preferredInputDeviceUID = sysIn
+ }
+
+ if let prefOut = SettingsStore.shared.preferredOutputDeviceUID,
+ outputDevices.contains(where: { $0.uid == prefOut })
+ {
+ self.selectedOutputUID = prefOut
+ } else if let sysOut = AudioDevice.getDefaultOutputDevice()?.uid {
+ // Fallback to system default if preferred device disconnected
+ self.selectedOutputUID = sysOut
+ SettingsStore.shared.preferredOutputDeviceUID = sysOut
+ }
}
}
.onDisappear {
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index a9a15bb8..71bd6988 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -29,6 +29,7 @@ final class SettingsStore: ObservableObject {
static let hotkeyShortcutKey = "HotkeyShortcutKey"
static let preferredInputDeviceUID = "PreferredInputDeviceUID"
static let preferredOutputDeviceUID = "PreferredOutputDeviceUID"
+ static let syncAudioDevicesWithSystem = "SyncAudioDevicesWithSystem"
static let visualizerNoiseThreshold = "VisualizerNoiseThreshold"
static let launchAtStartup = "LaunchAtStartup"
static let showInDock = "ShowInDock"
@@ -290,6 +291,19 @@ final class SettingsStore: ObservableObject {
set { self.defaults.set(newValue, forKey: Keys.preferredOutputDeviceUID) }
}
+ /// When enabled, changing audio devices in FluidVoice will also update macOS system audio settings.
+ /// When disabled (default), FluidVoice manages its own device selection independently.
+ var syncAudioDevicesWithSystem: Bool {
+ get {
+ let value = self.defaults.object(forKey: Keys.syncAudioDevicesWithSystem)
+ return value as? Bool ?? false // Default to false (decoupled from system)
+ }
+ set {
+ objectWillChange.send()
+ self.defaults.set(newValue, forKey: Keys.syncAudioDevicesWithSystem)
+ }
+ }
+
var visualizerNoiseThreshold: Double {
get {
let value = self.defaults.double(forKey: Keys.visualizerNoiseThreshold)
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index bd4556be..fbdf2ece 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -6,6 +6,7 @@ import Foundation
import FluidAudio
#endif
import AppKit
+import AudioToolbox
import CoreAudio
/// Serializes all CoreML transcription operations to prevent concurrent access issues.
@@ -449,7 +450,73 @@ final class ASRService: ObservableObject {
self.engine.stop()
}
self.engine.reset()
+ // Force input node instantiation (ensures the underlying AUHAL AudioUnit exists)
_ = self.engine.inputNode
+
+ // If we're running in "independent" mode, bind the engine to the preferred input device
+ // instead of inheriting macOS' current system-default input.
+ self.bindPreferredInputDeviceIfNeeded()
+ }
+
+ /// In independent mode, attempt to bind AVAudioEngine's input to the user's preferred input device.
+ /// In sync-with-system mode, we intentionally do nothing so the engine follows macOS defaults.
+ private func bindPreferredInputDeviceIfNeeded() {
+ guard SettingsStore.shared.syncAudioDevicesWithSystem == false else { return }
+ guard let preferredUID = SettingsStore.shared.preferredInputDeviceUID, preferredUID.isEmpty == false else { return }
+
+ guard let device = AudioDevice.getInputDevice(byUID: preferredUID) else {
+ DebugLogger.shared.warning(
+ "Preferred input device not found (uid: \(preferredUID)). Falling back to system default input.",
+ source: "ASRService"
+ )
+ return
+ }
+
+ let ok = self.setEngineInputDevice(deviceID: device.id, deviceUID: device.uid, deviceName: device.name)
+ if ok == false {
+ DebugLogger.shared.warning(
+ "Failed to bind engine input to preferred device '\(device.name)' (uid: \(device.uid)). Using system default input.",
+ source: "ASRService"
+ )
+ }
+ }
+
+ /// Selects a specific CoreAudio device for AVAudioEngine's input node without changing system defaults.
+ /// This uses the AUHAL AudioUnit backing `engine.inputNode` on macOS.
+ @discardableResult
+ private func setEngineInputDevice(deviceID: AudioObjectID, deviceUID: String, deviceName: String) -> Bool {
+ let inputNode = self.engine.inputNode
+
+ // `AVAudioInputNode` is backed by an AudioUnit on macOS. Setting this property selects
+ // which physical device the node captures from.
+ guard let audioUnit = inputNode.audioUnit else {
+ DebugLogger.shared.error(
+ "Unable to access AudioUnit for AVAudioEngine.inputNode; cannot bind to '\(deviceName)' (uid: \(deviceUID))",
+ source: "ASRService"
+ )
+ return false
+ }
+
+ var mutableDeviceID = deviceID
+ let status = AudioUnitSetProperty(
+ audioUnit,
+ kAudioOutputUnitProperty_CurrentDevice,
+ kAudioUnitScope_Global,
+ 0,
+ &mutableDeviceID,
+ UInt32(MemoryLayout<AudioObjectID>.size)
+ )
+
+ if status != noErr {
+ DebugLogger.shared.error(
+ "AudioUnitSetProperty(CurrentDevice) failed for '\(deviceName)' (uid: \(deviceUID), id: \(deviceID)) with status \(status)",
+ source: "ASRService"
+ )
+ return false
+ }
+
+ DebugLogger.shared.info("Bound ASR input to '\(deviceName)' (uid: \(deviceUID))", source: "ASRService")
+ return true
}
private func startEngine() throws {
@@ -463,6 +530,10 @@ final class ASRService: ObservableObject {
attempts += 1
Thread.sleep(forTimeInterval: 0.1)
self.engine.reset()
+ // After a reset, the underlying AUHAL unit may revert to system-default input.
+ // Re-create the input node and re-bind the preferred device (independent mode).
+ _ = self.engine.inputNode
+ self.bindPreferredInputDeviceIfNeeded()
}
}
throw NSError(domain: "ASRService", code: -1)
@@ -482,6 +553,13 @@ final class ASRService: ObservableObject {
}
private func handleDefaultInputChanged() {
+ // If we're not syncing with macOS system settings, ignore system-default changes.
+ // In independent mode, we explicitly bind to `preferredInputDeviceUID` on start/restart.
+ guard SettingsStore.shared.syncAudioDevicesWithSystem else {
+ DebugLogger.shared.debug("Ignoring system default input change (sync disabled)", source: "ASRService")
+ return
+ }
+
// Restart engine to bind to the new default input and resume level publishing
if self.isRunning {
self.removeEngineTap()
diff --git a/Sources/Fluid/Services/AppServices.swift b/Sources/Fluid/Services/AppServices.swift
index 2dbdabf8..0c73e026 100644
--- a/Sources/Fluid/Services/AppServices.swift
+++ b/Sources/Fluid/Services/AppServices.swift
@@ -7,6 +7,12 @@
// we reduce the generic type signature of ContentView, which helps avoid
// Swift runtime type metadata crashes at app launch.
//
+// DEFENSIVE STRATEGY (2025-12-21):
+// This file implements multiple layers of defense against startup crashes:
+// 1. Services are lazily initialized (not created until first access)
+// 2. A startup gate prevents any heavy work before UI is ready
+// 3. Combined with the 1.5s delay in ContentView for belt-and-suspenders approach
+//
import Combine
import Foundation
@@ -20,30 +26,91 @@ final class AppServices: ObservableObject {
/// Shared singleton instance
static let shared = AppServices()
- /// Audio hardware observation service
- let audioObserver = AudioHardwareObserver()
+ // MARK: - Startup Gate
+
+ /// Flag indicating the UI has completed its initial render.
+ /// Heavy operations should wait until this is true.
+ @Published private(set) var isUIReady: Bool = false
+
+ /// Call this once the main UI has finished its initial layout.
+ /// This signals that it's safe to start heavy services.
+ func signalUIReady() {
+ guard !self.isUIReady else { return }
+ DebugLogger.shared.info("🚦 UI Ready signal received - services can now initialize", source: "AppServices")
+ self.isUIReady = true
+ }
+
+ // MARK: - Lazy Services
+
+ /// Audio hardware observation service (lazily initialized)
+ private var _audioObserver: AudioHardwareObserver?
+ var audioObserver: AudioHardwareObserver {
+ if let existing = self._audioObserver {
+ return existing
+ }
+ DebugLogger.shared.info("🔊 Lazily creating AudioHardwareObserver", source: "AppServices")
+ let observer = AudioHardwareObserver()
+ self._audioObserver = observer
+ self.setupAudioObserverForwarding()
+ return observer
+ }
- /// Automatic speech recognition service
- let asr = ASRService()
+ /// Automatic speech recognition service (lazily initialized)
+ private var _asr: ASRService?
+ var asr: ASRService {
+ if let existing = self._asr {
+ return existing
+ }
+ DebugLogger.shared.info("🎤 Lazily creating ASRService", source: "AppServices")
+ let service = ASRService()
+ self._asr = service
+ self.setupASRForwarding()
+ return service
+ }
private var cancellables = Set<AnyCancellable>()
private init() {
- // Services are created but NOT started here.
- // Actual initialization (CoreAudio listeners, model loading) is deferred
- // to when the UI is ready, via AudioStartupGate.
+ // CRITICAL: Services are NOT created here.
+ // They are created lazily on first access, which happens AFTER the UI is ready.
+ // This ensures SwiftUI's AttributeGraph has finished processing before
+ // any heavy audio system work begins.
+ DebugLogger.shared.info("📦 AppServices singleton created (services not yet initialized)", source: "AppServices")
+ }
- // CRITICAL: Forward changes from child services to this container.
- // This allows ContentView to observe 'AppServices' (which is metadata-safe)
- // instead of observing 'ASRService' directly (which causes metadata crashes),
- // while still triggering UI updates when transcription or audio state changes.
+ // MARK: - Change Forwarding
- self.audioObserver.objectWillChange
+ /// Forward AudioHardwareObserver changes to trigger UI updates
+ private func setupAudioObserverForwarding() {
+ guard let observer = _audioObserver else { return }
+ observer.objectWillChange
.sink { [weak self] _ in self?.objectWillChange.send() }
.store(in: &self.cancellables)
+ }
- self.asr.objectWillChange
+ /// Forward ASRService changes to trigger UI updates
+ private func setupASRForwarding() {
+ guard let asr = _asr else { return }
+ asr.objectWillChange
.sink { [weak self] _ in self?.objectWillChange.send() }
.store(in: &self.cancellables)
}
+
+ // MARK: - Safe Initialization
+
+ /// Safely initialize all services after the UI is ready.
+ /// This is the recommended way to start services - call this from ContentView.onAppear
+ /// after the delay has passed.
+ func initializeServicesIfNeeded() {
+ guard self.isUIReady else {
+ DebugLogger.shared.warning("⚠️ initializeServicesIfNeeded called before UI ready - deferring", source: "AppServices")
+ return
+ }
+
+ // Access the properties to trigger lazy initialization
+ _ = self.audioObserver
+ _ = self.asr
+
+ DebugLogger.shared.info("✅ All services initialized", source: "AppServices")
+ }
}
diff --git a/Sources/Fluid/Services/AudioDeviceService.swift b/Sources/Fluid/Services/AudioDeviceService.swift
index 23c81b34..0a85a675 100644
--- a/Sources/Fluid/Services/AudioDeviceService.swift
+++ b/Sources/Fluid/Services/AudioDeviceService.swift
@@ -97,6 +97,16 @@ enum AudioDevice {
return self.setDefaultDeviceId(device.id, selector: kAudioHardwarePropertyDefaultOutputDevice)
}
+ /// Get input device by UID without affecting system settings
+ static func getInputDevice(byUID uid: String) -> Device? {
+ return self.listInputDevices().first { $0.uid == uid }
+ }
+
+ /// Get device AudioObjectID from UID
+ static func getDeviceId(forUID uid: String) -> AudioObjectID? {
+ return self.listAllDevices().first { $0.uid == uid }?.id
+ }
+
private static func getDefaultDeviceId(selector: AudioObjectPropertySelector) -> AudioObjectID? {
var address = AudioObjectPropertyAddress(
mSelector: selector,
diff --git a/Sources/Fluid/Services/CommandModeService.swift b/Sources/Fluid/Services/CommandModeService.swift
index b4ca34a7..8dbf73f6 100644
--- a/Sources/Fluid/Services/CommandModeService.swift
+++ b/Sources/Fluid/Services/CommandModeService.swift
@@ -831,7 +831,7 @@ final class CommandModeService: ObservableObject {
streaming: enableStreaming,
tools: [TerminalService.toolDefinition],
temperature: isReasoningModel ? nil : 0.1,
- maxTokens: isReasoningModel ? 32000 : nil, // Reasoning models like o1 need a large budget for extended thought chains
+ maxTokens: isReasoningModel ? 32_000 : nil, // Reasoning models like o1 need a large budget for extended thought chains
extraParameters: extraParams
)
diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swift
index a39db9e3..32c56041 100644
--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift
+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift
@@ -214,6 +214,26 @@ final class GlobalHotkeyManager: NSObject {
}
private func handleKeyEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {
+ // macOS can temporarily disable event taps (e.g. timeouts, user input protection).
+ // If we don't immediately re-enable here, hotkeys will silently stop working until our
+ // periodic health check kicks in, and the OS may handle the key (e.g. system dictation).
+ if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {
+ let reason = (type == .tapDisabledByTimeout) ? "timeout" : "user input"
+ DebugLogger.shared.warning("Event tap disabled by \(reason) — attempting immediate re-enable", source: "GlobalHotkeyManager")
+
+ if let tap = self.eventTap {
+ CGEvent.tapEnable(tap: tap, enable: true)
+ }
+
+ // If re-enable failed, recreate the tap.
+ if !self.isEventTapEnabled() {
+ DebugLogger.shared.warning("Event tap re-enable failed — recreating tap", source: "GlobalHotkeyManager")
+ self.setupGlobalHotkeyWithRetry()
+ }
+
+ return nil
+ }
+
let keyCode = UInt16(event.getIntegerValueField(.keyboardEventKeycode))
let flags = event.flags
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index a378c7ad..b8be29ab 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -287,7 +287,7 @@ final class MenuBarManager: ObservableObject {
// Use MenuBarIcon asset - vectorized from logo
if let image = NSImage(named: "MenuBarIcon") {
- image.isTemplate = true // Adapts to light/dark mode and tints red when recording
+ image.isTemplate = true // Adapts to light/dark mode and tints red when recording
statusItem.button?.image = image
}
}
diff --git a/Sources/Fluid/Services/RewriteModeService.swift b/Sources/Fluid/Services/RewriteModeService.swift
index ca2e7713..5eb0ae12 100644
--- a/Sources/Fluid/Services/RewriteModeService.swift
+++ b/Sources/Fluid/Services/RewriteModeService.swift
@@ -214,7 +214,7 @@ final class RewriteModeService: ObservableObject {
streaming: enableStreaming,
tools: [],
temperature: isReasoningModel ? nil : 0.7,
- maxTokens: isReasoningModel ? 32000 : nil, // Reasoning models like o1 need a large budget for extended thought chains
+ maxTokens: isReasoningModel ? 32_000 : nil, // Reasoning models like o1 need a large budget for extended thought chains
extraParameters: extraParams
)
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index a19335a1..f197997b 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -448,9 +448,24 @@ struct SettingsView: View {
// Audio Devices Card
ThemedCard(style: .standard) {
VStack(alignment: .leading, spacing: 14) {
- Label("Audio Devices", systemImage: "speaker.wave.2.fill")
- .font(.headline)
- .foregroundStyle(.primary)
+ HStack {
+ Label("Audio Devices", systemImage: "speaker.wave.2.fill")
+ .font(.headline)
+ .foregroundStyle(.primary)
+
+ Spacer()
+
+ Button {
+ self.refreshDevices()
+ // Update cached default device names on refresh
+ self.cachedDefaultInputName = AudioDevice.getDefaultInputDevice()?.name ?? ""
+ self.cachedDefaultOutputName = AudioDevice.getDefaultOutputDevice()?.name ?? ""
+ } label: {
+ Label("Refresh", systemImage: "arrow.clockwise")
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ }
VStack(alignment: .leading, spacing: 12) {
HStack {
@@ -472,7 +487,10 @@ struct SettingsView: View {
.onChange(of: self.selectedInputUID) { _, newUID in
guard !newUID.isEmpty else { return }
SettingsStore.shared.preferredInputDeviceUID = newUID
- _ = AudioDevice.setDefaultInputDevice(uid: newUID)
+ // Only change system default if sync is enabled
+ if SettingsStore.shared.syncAudioDevicesWithSystem {
+ _ = AudioDevice.setDefaultInputDevice(uid: newUID)
+ }
if self.asr.isRunning {
Task {
await self.asr.stopWithoutTranscription()
@@ -521,7 +539,10 @@ struct SettingsView: View {
.onChange(of: self.selectedOutputUID) { _, newUID in
guard !newUID.isEmpty else { return }
SettingsStore.shared.preferredOutputDeviceUID = newUID
- _ = AudioDevice.setDefaultOutputDevice(uid: newUID)
+ // Only change system default if sync is enabled
+ if SettingsStore.shared.syncAudioDevicesWithSystem {
+ _ = AudioDevice.setDefaultOutputDevice(uid: newUID)
+ }
}
// Sync selection when devices load or change
.onChange(of: self.outputDevices) { _, newDevices in
@@ -544,29 +565,45 @@ struct SettingsView: View {
}
}
- HStack(spacing: 10) {
- Button {
- self.refreshDevices()
- // Update cached default device names on refresh
- self.cachedDefaultInputName = AudioDevice.getDefaultInputDevice()?.name ?? ""
- self.cachedDefaultOutputName = AudioDevice.getDefaultOutputDevice()?.name ?? ""
- } label: {
- Label("Refresh", systemImage: "arrow.clockwise")
- }
- .buttonStyle(.bordered)
- .controlSize(.regular)
-
- Spacer()
-
- // CRITICAL FIX: Use cached values instead of querying CoreAudio in view body.
- // Querying AudioDevice here triggers HALSystem::InitializeShell() race condition.
- if !self.cachedDefaultInputName.isEmpty && !self.cachedDefaultOutputName.isEmpty {
+ // CRITICAL FIX: Use cached values instead of querying CoreAudio in view body.
+ // Querying AudioDevice here triggers HALSystem::InitializeShell() race condition.
+ if !self.cachedDefaultInputName.isEmpty && !self.cachedDefaultOutputName.isEmpty {
+ HStack {
+ Spacer()
Text("Default: \(self.cachedDefaultInputName) / \(self.cachedDefaultOutputName)")
.font(.caption)
.foregroundStyle(.tertiary)
.lineLimit(1)
}
}
+
+ Divider().padding(.vertical, 4)
+
+ self.optionToggleRow(
+ title: "Sync with System Settings",
+ description: "When enabled, FV and macOS share the same audio devices (bidirectional sync).",
+ isOn: Binding(
+ get: { SettingsStore.shared.syncAudioDevicesWithSystem },
+ set: { newValue in
+ SettingsStore.shared.syncAudioDevicesWithSystem = newValue
+
+ // When sync is toggled ON, adopt system's current devices as the source of truth
+ if newValue {
+ if let sysInputUID = AudioDevice.getDefaultInputDevice()?.uid {
+ self.selectedInputUID = sysInputUID
+ SettingsStore.shared.preferredInputDeviceUID = sysInputUID
+ }
+ if let sysOutputUID = AudioDevice.getDefaultOutputDevice()?.uid {
+ self.selectedOutputUID = sysOutputUID
+ SettingsStore.shared.preferredOutputDeviceUID = sysOutputUID
+ }
+ DebugLogger.shared.info("Sync enabled: adopted system audio devices", source: "SettingsView")
+ } else {
+ DebugLogger.shared.info("Sync disabled: FV will use independent audio device selection", source: "SettingsView")
+ }
+ }
+ )
+ )
}
}
.padding(16)
diff --git a/Sources/Fluid/fluidApp.swift b/Sources/Fluid/fluidApp.swift
index e512d8f4..aeaeb548 100644
--- a/Sources/Fluid/fluidApp.swift
+++ b/Sources/Fluid/fluidApp.swift
@@ -12,10 +12,15 @@ import SwiftUI
@main
struct FluidApp: App {
@StateObject private var menuBarManager = MenuBarManager()
- @StateObject private var appServices = AppServices.shared
+ @StateObject private var appServices: AppServices
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@State private var theme = AppTheme.dark
+ init() {
+ // Use the shared singleton instance
+ _appServices = StateObject(wrappedValue: AppServices.shared)
+ }
+
var body: some Scene {
WindowGroup(id: "main") {
ContentView()