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

Refine AI Providers, History and Stats (#955)

ALTIC0039d645aa6b
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index 8bf0e82f..0fffbeea 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -26,6 +26,7 @@
F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1BD00000000000000000001 /* StripThinkingTagsTests.swift */; };
C0DE63600000000000000002 /* AudioEngineRetirementDrainTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE63600000000000000001 /* AudioEngineRetirementDrainTests.swift */; };
DA7100020000000000000002 /* DirectAudioReliabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */; };
+ DA7200020000000000000002 /* AudioHardwareRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA7200010000000000000001 /* AudioHardwareRecoveryTests.swift */; };
7CFA1D0B2F500000C0DEF001 /* TypingServiceTransientPasteboardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CFA1D0B2F500000C0DEF002 /* TypingServiceTransientPasteboardTests.swift */; };
803000000000000000000002 /* MediaPlaybackServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 803000000000000000000001 /* MediaPlaybackServiceTests.swift */; };
0B05F11E000000000000A002 /* SupportedFileExtensionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B05F11E000000000000A001 /* SupportedFileExtensionsTests.swift */; };
@@ -73,6 +74,7 @@
F1BD00000000000000000001 /* StripThinkingTagsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StripThinkingTagsTests.swift; sourceTree = "<group>"; };
C0DE63600000000000000001 /* AudioEngineRetirementDrainTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioEngineRetirementDrainTests.swift; sourceTree = "<group>"; };
DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectAudioReliabilityTests.swift; sourceTree = "<group>"; };
+ DA7200010000000000000001 /* AudioHardwareRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioHardwareRecoveryTests.swift; sourceTree = "<group>"; };
B51800000000000000000001 /* SpokenSendTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenSendTests.swift; sourceTree = "<group>"; };
B51900000000000000000001 /* PrivateAIProviderPromptFormatTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivateAIProviderPromptFormatTests.swift; sourceTree = "<group>"; };
B52000000000000000000001 /* PrivateAIDictationTokenBudgetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivateAIDictationTokenBudgetTests.swift; sourceTree = "<group>"; };
@@ -168,6 +170,7 @@
F1BD00000000000000000001 /* StripThinkingTagsTests.swift */,
C0DE63600000000000000001 /* AudioEngineRetirementDrainTests.swift */,
DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */,
+ DA7200010000000000000001 /* AudioHardwareRecoveryTests.swift */,
7CFA1D0B2F500000C0DEF002 /* TypingServiceTransientPasteboardTests.swift */,
803000000000000000000001 /* MediaPlaybackServiceTests.swift */,
B51800000000000000000001 /* SpokenSendTests.swift */,
@@ -345,6 +348,7 @@
F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */,
C0DE63600000000000000002 /* AudioEngineRetirementDrainTests.swift in Sources */,
DA7100020000000000000002 /* DirectAudioReliabilityTests.swift in Sources */,
+ DA7200020000000000000002 /* AudioHardwareRecoveryTests.swift in Sources */,
7CFA1D0B2F500000C0DEF001 /* TypingServiceTransientPasteboardTests.swift in Sources */,
803000000000000000000002 /* MediaPlaybackServiceTests.swift in Sources */,
B51800000000000000000002 /* SpokenSendTests.swift in Sources */,
@@ -501,7 +505,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 1;
+ CURRENT_PROJECT_VERSION = 23;
DEVELOPMENT_TEAM = V4J43B279J;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
@@ -529,7 +533,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
- MARKETING_VERSION = 1.5.1;
+ MARKETING_VERSION = "1.6.10-beta.2";
PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app.debug;
PRODUCT_NAME = "FluidVoice Debug";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -556,7 +560,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 1;
+ CURRENT_PROJECT_VERSION = 23;
DEVELOPMENT_TEAM = V4J43B279J;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
@@ -584,7 +588,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
- MARKETING_VERSION = 1.5.1;
+ MARKETING_VERSION = "1.6.10-beta.2";
PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app;
PRODUCT_NAME = FluidVoice;
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/Info.plist b/Info.plist
index 95e77175..15ceb664 100644
--- a/Info.plist
+++ b/Info.plist
@@ -13,9 +13,9 @@
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleVersion</key>
- <string>22</string>
+ <string>23</string>
<key>CFBundleShortVersionString</key>
- <string>1.6.10</string>
+ <string>1.6.10-beta.2</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 79700192..d1cd30a8 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -2643,7 +2643,7 @@ struct ContentView: View {
// Prompt Test Mode: reroute dictation hotkey output into the prompt editor (no typing/clipboard/history).
if promptTest.isActive {
- await self.processDictationPromptTest(transcribedText)
+ await self.processDictationPromptTest(transcribedText, lifecycleID: expectedOverlayLifecycleID)
return
}
@@ -2993,7 +2993,7 @@ struct ContentView: View {
}
}
- private func processDictationPromptTest(_ transcribedText: String) async {
+ private func processDictationPromptTest(_ transcribedText: String, lifecycleID: UInt64) async {
let promptTest = DictationPromptTestCoordinator.shared
promptTest.lastTranscriptionText = transcribedText
promptTest.lastOutputText = ""
@@ -3003,12 +3003,18 @@ struct ContentView: View {
model: promptTest.draftModel
) else {
promptTest.lastError = "AI post-processing is not configured. Configure a provider/model (and API key for non-local endpoints) to test prompts."
- self.menuBarManager.setProcessing(false)
+ if self.overlayLifecycleID == lifecycleID {
+ self.menuBarManager.setProcessing(false)
+ }
return
}
promptTest.isProcessing = true
+ let refiningStatusTask = self.makeAIProcessingFeedback(lifecycleID: lifecycleID).statusTask
defer {
- self.menuBarManager.setProcessing(false)
+ refiningStatusTask.cancel()
+ if self.overlayLifecycleID == lifecycleID {
+ self.menuBarManager.setProcessing(false)
+ }
promptTest.isProcessing = false
}
do {
diff --git a/Sources/Fluid/Persistence/DictationAudioHistoryStore.swift b/Sources/Fluid/Persistence/DictationAudioHistoryStore.swift
index f2fc4b62..17d53330 100644
--- a/Sources/Fluid/Persistence/DictationAudioHistoryStore.swift
+++ b/Sources/Fluid/Persistence/DictationAudioHistoryStore.swift
@@ -102,6 +102,11 @@ final nonisolated class DictationAudioHistoryStore: @unchecked Sendable {
return self.fileManager.fileExists(atPath: url.path)
}
+ func audioFileExists(fileName: String) -> Bool {
+ guard let url = self.audioFileURL(fileName: fileName, createIfNeeded: false) else { return false }
+ return self.fileManager.fileExists(atPath: url.path)
+ }
+
@discardableResult
func deleteAudio(fileName: String) -> Int64 {
guard let url = self.audioFileURL(fileName: fileName, createIfNeeded: false) else {
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 111f4e84..cd10fcde 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -1846,9 +1846,9 @@ final class SettingsStore: ObservableObject {
}
}
- /// Shows optional ASR and AI performance details in transcription history.
+ /// Shows ASR and AI performance details by default; users can hide them.
var showHistoryPerformanceMetrics: Bool {
- get { self.defaults.object(forKey: Keys.showHistoryPerformanceMetrics) as? Bool ?? false }
+ get { self.defaults.object(forKey: Keys.showHistoryPerformanceMetrics) as? Bool ?? true }
set {
objectWillChange.send()
self.defaults.set(newValue, forKey: Keys.showHistoryPerformanceMetrics)
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 6a930f0a..6d90b906 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -519,6 +519,7 @@ final class ASRService: ObservableObject {
private(set) var dictionaryTrainingAudioGeneration = 0
@Published private(set) var isStarting: Bool = false // Guard against re-entrant start() calls
+ private var pendingMediaCaptureSessionID: Int?
private var audioCaptureStartWaiters: [CheckedContinuation<Void, Never>] = []
var isRunningOrStarting: Bool {
self.isRunning || self.isStarting
@@ -527,6 +528,8 @@ final class ASRService: ObservableObject {
private let audioCaptureReadinessGate = AudioCaptureReadinessGate()
private let firstPCMTimeoutNanoseconds: UInt64 = 2_000_000_000
private var audioCaptureStartGeneration: UInt64 = 0
+ private var pendingAudioCaptureBackendStart: Task<Void, Error>?
+ private var mediaPlaybackService = MediaPlaybackService.shared
private var audioCaptureAttemptID: UInt64 = 0
private var isTerminating = false
private var hasCompletedFirstTranscription: Bool = false // Track if model has warmed up with first transcription
@@ -542,6 +545,86 @@ final class ASRService: ObservableObject {
@Published var errorTitle: String = "Error"
@Published var errorMessage: String = ""
@Published var showError: Bool = false
+ let audioCaptureFailurePresented = PassthroughSubject<Void, Never>()
+
+ private func presentAudioCaptureFailure(title: String, message: String) {
+ self.errorTitle = title
+ self.errorMessage = message
+ self.showError = true
+ self.audioCaptureFailurePresented.send()
+ }
+
+ #if DEBUG
+ /// Exercise the real recovery coordinator with fake hardware, without
+ /// initializing a model, recording a physical microphone, or changing defaults.
+ var recoveryPacketHandlerForTesting: DirectCoreAudioPacketHandler {
+ let pipeline = self.audioCapturePipeline
+ return { samples, frames, rate, hostTime, sampleTime in
+ pipeline.handle(
+ samples: samples,
+ frameCount: frames,
+ sampleRate: rate,
+ inputHostTime: hostTime,
+ inputSampleTime: sampleTime
+ )
+ }
+ }
+
+ func configureAudioRouteRecoveryForTesting(
+ controller: DirectCoreAudioLifecycleController,
+ devices: [AudioDevice.Device],
+ initialSamples: [Float]
+ ) {
+ precondition(self.isRunning == false && self.isStarting == false)
+ self.directAudioLifecycleController = controller
+ self.cacheCurrentDeviceList(devices)
+ self.benchmarkSessionID = 987_654
+ self.audioCaptureStartGeneration &+= 1
+ self.audioCaptureAttemptID &+= 1
+ self.activeAudioCaptureBackend = .directCoreAudio
+ self.audioBuffer.append(initialSamples)
+ self.audioCapturePipeline.setRecordingEnabled(
+ true, sessionID: self.benchmarkSessionID, attemptID: self.audioCaptureAttemptID
+ )
+ self.isRunning = true
+ }
+
+ func triggerAudioRouteRecoveryForTesting() {
+ self.scheduleAudioRouteRecovery(
+ reason: "injected input change", requiresIdlePrewarm: true, reconcilesInputSelection: true
+ )
+ }
+
+ func useMediaPlaybackForTesting(_ service: MediaPlaybackService) {
+ self.mediaPlaybackService = service
+ }
+
+ func failAudioRouteRecoveryForTesting(stale: Bool = false) async {
+ await self.finishAudioRouteRecoveryFailure(AudioRouteRecoveryRequest(
+ generation: stale ? self.audioRouteRecoveryGeneration &- 1 : self.audioRouteRecoveryGeneration,
+ reason: "injected recovery failure",
+ requiresIdlePrewarm: true,
+ reconcilesInputSelection: false
+ ), error: BoundedAudioHardwareQueue.Failure.recovering)
+ }
+
+ var audioRouteRecoveryStateForTesting: (pending: Bool, recovering: Bool, acceptingPCM: Bool, samples: [Float]) {
+ (
+ self.pendingAudioRouteRecovery != nil,
+ self.isRecoveringAudioRoute,
+ self.audioCapturePipeline.isRecordingEnabledForTesting,
+ self.audioBuffer.getAll()
+ )
+ }
+
+ func finishAudioRouteRecoveryTest() async {
+ await self.cancelAudioRouteRecoveryAndWait()
+ self.isRunning = false
+ self.audioCapturePipeline.setRecordingEnabled(false)
+ await self.directAudioLifecycleController.shutdown(reason: "test_complete")
+ self.audioBuffer.clear()
+ }
+ #endif
/// Returns a user-friendly status message for model loading state
var modelStatusMessage: String {
@@ -622,14 +705,16 @@ final class ASRService: ObservableObject {
func shutdownForTermination() async {
self.isTerminating = true
+ // Give media restoration the same quit window as audio cleanup.
+ self.mediaPlaybackService.beginShutdown()
+ if self.isStarting, self.isRunning == false {
+ await self.cancelPendingAudioCaptureStart(reason: "app_termination")
+ }
let routeRecoveryShutdownStartedAt = Date().timeIntervalSince1970
await self.cancelAudioRouteRecoveryAndWait()
self.benchmarkLog(
"route_recovery_shutdown elapsedMs=\(self.elapsedMilliseconds(since: routeRecoveryShutdownStartedAt))"
)
- if self.isStarting, self.isRunning == false {
- await self.cancelPendingAudioCaptureStart(reason: "app_termination")
- }
if self.isRunning {
await self.stopWithoutTranscription()
}
@@ -665,6 +750,7 @@ final class ASRService: ObservableObject {
self.isAsrReady = false
self.isLoadingModel = false
self.isDownloadingModel = false
+ await self.mediaPlaybackService.shutdown()
}
/// The transcription provider, selected based on the unified SpeechModel setting.
@@ -1256,10 +1342,35 @@ final class ASRService: ObservableObject {
return snapshot
}
+ /// Bridge the app's Cancel action to the actual backend task. The task's
+ /// cancellation handler also covers cancellation before queue admission.
+ private func startCancellableAudioCapture(
+ excluding excludedInputUIDs: Set<String>,
+ forcingInputUID: String?,
+ onInputSnapshotRead: @escaping @MainActor (Int) -> Void
+ ) async throws {
+ let task = Task {
+ try await self.startConfiguredAudioCapture(
+ excluding: excludedInputUIDs,
+ forcingInputUID: forcingInputUID,
+ onInputSnapshotRead: onInputSnapshotRead
+ )
+ }
+ self.pendingAudioCaptureBackendStart = task
+ defer { self.pendingAudioCaptureBackendStart = nil }
+ try await withTaskCancellationHandler {
+ try await task.value
+ } onCancel: {
+ task.cancel()
+ }
+ }
+
private func startConfiguredAudioCapture(
excluding excludedInputUIDs: Set<String> = [],
- forcingInputUID: String? = nil
+ forcingInputUID: String? = nil,
+ onInputSnapshotRead: @MainActor (Int) -> Void = { _ in }
) async throws {
+ let startGeneration = self.audioCaptureStartGeneration
let previousAttemptIdentity = self.audioStartAttemptInputUID.map {
AudioCaptureIdlePolicy.CaptureAttemptIdentity(
uid: $0,
@@ -1278,15 +1389,17 @@ final class ASRService: ObservableObject {
// release.
await self.audioEngineRetirementDrain.waitForScheduledReleases()
do {
- let deviceSnapshot = await Task.detached(priority: .userInitiated) {
- let allDevices = AudioDevice.listAllDevices()
- return (
- allDevices: allDevices,
- defaultInputUID: AudioDevice.getDefaultInputDevice(from: allDevices)?.uid
- )
- }.value
- let allDevices = deviceSnapshot.allDevices
+ try self.checkCaptureStartGeneration(startGeneration)
+ if self.directAudioLifecycleController.isRecoveringHardware {
+ let available = await self.directAudioLifecycleController.waitForPendingHardwareRetirement()
+ try self.checkCaptureStartGeneration(startGeneration)
+ guard available else { throw BoundedAudioHardwareQueue.Failure.recovering }
+ }
+ let deviceSnapshot = try await self.directAudioLifecycleController.readCaptureDeviceSnapshot()
+ try self.checkCaptureStartGeneration(startGeneration)
+ let allDevices = deviceSnapshot.devices
let availableInputs = allDevices.filter(\.hasInput)
+ onInputSnapshotRead(availableInputs.count)
let selectedInput: AudioDevice.Device?
if let forcingInputUID {
selectedInput = availableInputs.first { $0.uid == forcingInputUID }
@@ -1326,6 +1439,7 @@ final class ASRService: ObservableObject {
selection: selection,
reason: "recording_start"
)
+ try self.checkCaptureStartGeneration(startGeneration)
self.audioStartAttemptInputUID = device.uid
self.audioStartAttemptInputName = device.name
self.audioStartAttemptIsBluetooth = device.isBluetooth
@@ -1339,7 +1453,7 @@ final class ASRService: ObservableObject {
deviceName: device.name,
reason: "recording_start"
)
- try Task.checkCancellation()
+ try self.checkCaptureStartGeneration(startGeneration)
self.activeAudioCaptureBackend = .directCoreAudio
let callbackDurationMilliseconds =
Double(snapshot.bufferFrameSize ?? 0) /
@@ -1366,6 +1480,13 @@ final class ASRService: ObservableObject {
try await self.startAVAudioEngineCapture()
}
+ private func checkCaptureStartGeneration(_ generation: UInt64) throws {
+ try Task.checkCancellation()
+ guard generation == self.audioCaptureStartGeneration, self.isTerminating == false else {
+ throw CancellationError()
+ }
+ }
+
private func startAVAudioEngineCapture() async throws {
await self.audioEngineRetirementDrain.waitForScheduledReleases()
self.benchmarkLog("audio_backend kind=av_audio_engine reason=faster_recording_start_disabled")
@@ -1383,7 +1504,8 @@ final class ASRService: ObservableObject {
case .directCoreAudio:
let report = await self.directAudioLifecycleController.stop(
retainPrepared: retainDirectPreparedCapture,
- reason: reason
+ reason: reason,
+ recoveringRoute: self.isRecoveringAudioRoute
)
if report.status != noErr {
DebugLogger.shared.warning(
@@ -1460,10 +1582,6 @@ final class ASRService: ObservableObject {
private var isEngineTapInstalled = false
private var isRecoveringAudioRoute = false
- /// Tracks whether we paused system media for this recording session.
- /// Used to resume playback only if we were the ones who paused it.
- private var didPauseMediaForThisSession: Bool = false
-
private var audioLevelSubject = PassthroughSubject<CGFloat, Never>()
var audioLevelPublisher: AnyPublisher<CGFloat, Never> {
self.audioLevelSubject.eraseToAnyPublisher()
@@ -2106,8 +2224,6 @@ final class ASRService: ObservableObject {
// alive; startConfiguredAudioCapture reuses it for zero-stop first PCM.
let handedOffMicrophonePreview = self.handOffMicrophonePreviewToCaptureStartIfNeeded()
- // Reset media pause state for this session
- self.didPauseMediaForThisSession = false
self.audioEngineStandbyTask?.cancel()
self.audioEngineStandbyTask = nil
await self.waitForPendingAudioRouteRecoveryBeforeStart()
@@ -2139,6 +2255,15 @@ final class ASRService: ObservableObject {
self.streamingHealthLastBufferCount = 0
self.silentPCMRecoveryWatchdog = AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog()
let captureSessionID = self.benchmarkSessionID
+ // Start media work alongside microphone startup; never await it on the
+ // capture path. Track only this start so cancelling a buffer-handoff wait
+ // cannot finish the previous session's still-running transcription.
+ self.pendingMediaCaptureSessionID = captureSessionID
+ defer { self.pendingMediaCaptureSessionID = nil }
+ self.mediaPlaybackService.recordingStarted(
+ sessionID: captureSessionID,
+ enabled: SettingsStore.shared.pauseMediaDuringTranscription
+ )
self.audioCaptureAttemptID &+= 1
var readinessAttemptID = self.audioCaptureAttemptID
self.audioCaptureReadinessGate.arm(
@@ -2164,10 +2289,8 @@ final class ASRService: ObservableObject {
self.isDictionaryTrainingCaptureActive = false
do {
- let maximumStartAttempts =
- SettingsStore.shared.experimentalDirectAudioCaptureEnabled
- ? max(AudioDevice.listInputDevices().count, 1) + 1
- : 1
+ var maximumStartAttempts = 1
+ var hasReadInputSnapshot = false
var startAttempt = 1
var fallbackAttempt = 1
var failedInputUIDs = Set<String>()
@@ -2178,11 +2301,23 @@ final class ASRService: ObservableObject {
while true {
let routeGenerationAtStart = self.audioRouteRecoveryGeneration
do {
- try await self.startConfiguredAudioCapture(
+ try await self.startCancellableAudioCapture(
excluding: failedInputUIDs,
- forcingInputUID: forcedInputUID
+ forcingInputUID: forcedInputUID,
+ onInputSnapshotRead: { inputCount in
+ guard hasReadInputSnapshot == false else { return }
+ // Freeze a bounded budget from the same fresh snapshot
+ // that selected the first input, including one retry.
+ hasReadInputSnapshot = true
+ maximumStartAttempts = max(inputCount, 1) + 1
+ }
)
} catch {
+ try self.checkCaptureStartGeneration(startGeneration)
+ guard error is BoundedAudioHardwareQueue.Failure == false,
+ error is CancellationError == false,
+ self.directAudioLifecycleController.isRecoveringHardware == false
+ else { throw error }
guard let failedUID = self.audioStartAttemptInputUID else { throw error }
let now = ProcessInfo.processInfo.systemUptime
let retryBluetoothInput = bluetoothStabilization.shouldRetry(
@@ -2359,23 +2494,6 @@ final class ASRService: ObservableObject {
)
onCaptureStarted?()
- // Pause only after capture is live so media control cannot delay the
- // first PCM packet. A quick stop while this await is in flight is
- // handled explicitly below.
- if SettingsStore.shared.pauseMediaDuringTranscription {
- let didPause = await MediaPlaybackService.shared.pauseIfPlaying()
- guard self.isRunning, self.isStoppingFinalTranscription == false else {
- if didPause {
- await MediaPlaybackService.shared.resumeIfWePaused(true)
- }
- return .started
- }
- self.didPauseMediaForThisSession = didPause
- if didPause {
- DebugLogger.shared.info("🎵 Paused system media for transcription", source: "ASRService")
- }
- }
-
// Direct capture already owns a required device-liveness listener
// on its off-main lifecycle queue.
if self.activeAudioCaptureBackend == .audioEngine,
@@ -2401,6 +2519,7 @@ final class ASRService: ObservableObject {
DebugLogger.shared.info("✅ START() completed successfully", source: "ASRService")
return .started
} catch {
+ self.mediaPlaybackService.sessionFinished(sessionID: captureSessionID)
await self.audioCaptureReadinessGate.cancel(
sessionID: captureSessionID,
attemptID: readinessAttemptID
@@ -2426,13 +2545,6 @@ final class ASRService: ObservableObject {
DebugLogger.shared.error("Failed to start ASR session: \(error)", source: "ASRService")
}
- // Resume media if we paused it before the failure
- if self.didPauseMediaForThisSession {
- await MediaPlaybackService.shared.resumeIfWePaused(true)
- self.didPauseMediaForThisSession = false
- DebugLogger.shared.info("🎵 Resumed system media after start failure", source: "ASRService")
- }
-
guard wasCancelled == false else { return .failed }
AppServices.shared.microphonePreferenceCoordinator.markActiveSelectionUnavailable()
@@ -2457,15 +2569,9 @@ 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 display
- NotificationCenter.default.post(
- name: NSNotification.Name("ASRServiceStartFailed"),
- object: nil,
- userInfo: ["errorMessage": errorMessage]
+ self.presentAudioCaptureFailure(
+ title: noUsableMicrophone ? "Microphone Unavailable" : "Recording Error",
+ message: errorMessage
)
return .failed
}
@@ -2560,12 +2666,24 @@ final class ASRService: ObservableObject {
)
}
- func cancelPendingAudioCaptureStart(reason: String) async {
- guard self.isStarting, self.isRunning == false else { return }
+ /// Recovery can be awaited by startup, so it must interrupt without waiting
+ /// for startup to finish. Keep task cancellation and media release together.
+ private func interruptPendingAudioCaptureStart() {
self.audioCaptureStartGeneration &+= 1
+ self.pendingAudioCaptureBackendStart?.cancel()
+ self.audioCapturePipeline.setRecordingEnabled(false)
+ self.directAudioLifecycleController.cancelPendingStartup()
+ if let sessionID = self.pendingMediaCaptureSessionID {
+ self.mediaPlaybackService.sessionFinished(sessionID: sessionID)
+ }
// A start waiting for the previous session's PCM handoff must wake to
// observe the generation change; the old stop keeps ownership of the gate.
self.recordingBufferHandoffGate.releasePendingWaiters()
+ }
+
+ func cancelPendingAudioCaptureStart(reason: String) async {
+ guard self.isStarting, self.isRunning == false else { return }
+ self.interruptPendingAudioCaptureStart()
let cancelledSessionID = self.benchmarkSessionID
self.benchmarkLog(
"capture_start_cancel reason=\(reason) session=\(cancelledSessionID) " +
@@ -2723,6 +2841,8 @@ final class ASRService: ObservableObject {
DebugLogger.shared.warning("STOP() ignored - recording buffer handoff already active", source: "ASRService")
return ""
}
+ self.mediaPlaybackService.recordingStopped(sessionID: stoppingSessionID)
+ defer { self.mediaPlaybackService.sessionFinished(sessionID: stoppingSessionID) }
self.isStoppingFinalTranscription = true
var completedBufferHandoff = false
defer {
@@ -2749,10 +2869,6 @@ final class ASRService: ObservableObject {
return ""
}
- // Capture media pause state before we reset it, for resuming at the end
- let shouldResumeMedia = self.didPauseMediaForThisSession
- self.didPauseMediaForThisSession = false // Reset for next session
-
DebugLogger.shared.debug("📍 Preparing final transcription", source: "ASRService")
// Freeze an exact acquisition boundary before stopping hardware. The
@@ -2813,7 +2929,6 @@ final class ASRService: ObservableObject {
self.beginStreamingDrainRecovery(sessionID: stoppingSessionID, token: bufferHandoffToken)
completedBufferHandoff = true // Recovery owns the PCM handoff until real work ends.
self.lastStopOutcome = .failed
- if shouldResumeMedia { await MediaPlaybackService.shared.resumeIfWePaused(true) }
self.benchmarkLog("stop_end result=error reason=streaming_drain_timeout")
return ""
}
@@ -2847,10 +2962,6 @@ final class ASRService: ObservableObject {
"Final ASR result | provider=\(self.transcriptionProvider.name) | samples=0 | textChars=0 | confidence=nil | reason=no_audio",
source: "ASRService"
)
- if shouldResumeMedia {
- await MediaPlaybackService.shared.resumeIfWePaused(true)
- DebugLogger.shared.info("🎵 Resumed system media after empty audio", source: "ASRService")
- }
self.benchmarkLog("stop_end result=empty totalMs=\(self.elapsedMilliseconds(since: stopStartedAt)) reason=no_audio")
return ""
}
@@ -2878,10 +2989,6 @@ final class ASRService: ObservableObject {
"Final ASR result | provider=\(self.transcriptionProvider.name) | samples=\(pcm.count) | textChars=0 | confidence=nil | reason=short_silence",
source: "ASRService"
)
- if shouldResumeMedia {
- await MediaPlaybackService.shared.resumeIfWePaused(true)
- DebugLogger.shared.info("🎵 Resumed system media after silent audio", source: "ASRService")
- }
self.benchmarkLog(
"stop_end result=empty totalMs=\(self.elapsedMilliseconds(since: stopStartedAt)) reason=short_silence"
)
@@ -2912,6 +3019,9 @@ final class ASRService: ObservableObject {
if self.isAsrReady, provider.isReady {
self.benchmarkLog("stop_ensure_ready skipped=true elapsedMs=0")
} else {
+ // TODO: Investigate rapid restart while this cold-provider stop is pending (PR #950).
+ // A new recording may replace output context still read by the previous transcript.
+ // Not reproduced in-app; defer changes for now and preserve responsive restarts.
self.publishStoppedState(for: stoppingSessionID)
DebugLogger.shared.debug("🔍 Calling ensureAsrReady()...", source: "ASRService")
try await self.ensureAsrReady()
@@ -2923,11 +3033,6 @@ final class ASRService: ObservableObject {
guard provider.isReady else {
DebugLogger.shared.error("Transcription provider is not ready", source: "ASRService")
self.lastStopOutcome = .failed
- // Resume media playback if we paused it
- if shouldResumeMedia {
- await MediaPlaybackService.shared.resumeIfWePaused(true)
- DebugLogger.shared.info("🎵 Resumed system media after provider not ready", source: "ASRService")
- }
self.benchmarkLog("stop_end result=empty totalMs=\(self.elapsedMilliseconds(since: stopStartedAt)) reason=provider_not_ready")
return ""
}
@@ -3031,12 +3136,6 @@ final class ASRService: ObservableObject {
)
}
- // Resume media playback if we paused it
- if shouldResumeMedia {
- await MediaPlaybackService.shared.resumeIfWePaused(true)
- DebugLogger.shared.info("🎵 Resumed system media after transcription", source: "ASRService")
- }
-
self.lastStopOutcome = outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? .empty
: .success
@@ -3065,12 +3164,6 @@ final class ASRService: ObservableObject {
// (e.g., accidental hotkey press) and would disrupt the user's workflow.
// Errors are logged for debugging purposes.
- // Resume media playback if we paused it
- if shouldResumeMedia {
- await MediaPlaybackService.shared.resumeIfWePaused(true)
- DebugLogger.shared.info("🎵 Resumed system media after transcription failure", source: "ASRService")
- }
-
self.benchmarkLog("stop_end result=error totalMs=\(self.elapsedMilliseconds(since: stopStartedAt)) error=\(error.localizedDescription)")
return ""
}
@@ -3276,12 +3369,18 @@ final class ASRService: ObservableObject {
}
func stopWithoutTranscription() async {
+ await self.stopWithoutTranscription(finishingRecovery: false)
+ }
+
+ private func stopWithoutTranscription(finishingRecovery: Bool) async {
if self.isStarting, self.isRunning == false {
await self.cancelPendingAudioCaptureStart(reason: "stop_without_transcription")
}
guard self.isRunning else { return }
let stoppingSessionID = self.benchmarkSessionID
guard let bufferHandoffToken = self.recordingBufferHandoffGate.begin() else { return }
+ self.mediaPlaybackService.recordingStopped(sessionID: stoppingSessionID)
+ defer { self.mediaPlaybackService.sessionFinished(sessionID: stoppingSessionID) }
var completedBufferHandoff = false
defer {
if completedBufferHandoff == false {
@@ -3294,17 +3393,15 @@ final class ASRService: ObservableObject {
self.isDictionaryTrainingCaptureActive = false
}
- await self.cancelAudioRouteRecoveryAndWait()
+ if finishingRecovery == false {
+ await self.cancelAudioRouteRecoveryAndWait()
+ }
guard self.isRunning, self.benchmarkSessionID == stoppingSessionID else {
self.recordingBufferHandoffGate.complete(bufferHandoffToken)
completedBufferHandoff = true
return
}
- // Capture media pause state before we reset it, for resuming at the end
- let shouldResumeMedia = self.didPauseMediaForThisSession
- self.didPauseMediaForThisSession = false // Reset for next session
-
DebugLogger.shared.info("🛑 Stopping recording - releasing audio devices", source: "ASRService")
// CRITICAL: Set isRunning to false FIRST to signal any in-flight chunks to abort early
@@ -3327,7 +3424,6 @@ final class ASRService: ObservableObject {
guard await self.drainActiveStreamingWork(sessionID: stoppingSessionID) else {
self.beginStreamingDrainRecovery(sessionID: stoppingSessionID, token: bufferHandoffToken)
completedBufferHandoff = true
- if shouldResumeMedia { await MediaPlaybackService.shared.resumeIfWePaused(true) }
return
}
@@ -3343,12 +3439,6 @@ final class ASRService: ObservableObject {
self.isProcessingChunk = false
self.skipNextChunk = false
self.refreshWordBoostStatus()
-
- // Resume media playback if we paused it
- if shouldResumeMedia {
- await MediaPlaybackService.shared.resumeIfWePaused(true)
- DebugLogger.shared.info("🎵 Resumed system media after stopping without transcription", source: "ASRService")
- }
}
private func configureSession() throws {
@@ -3966,6 +4056,14 @@ final class ASRService: ObservableObject {
self.finishAudioRouteRecovery(request)
}
+ let hardwareAvailable = await self.directAudioLifecycleController.waitForHardwareAvailability()
+ guard request.generation == self.audioRouteRecoveryGeneration,
+ Task.isCancelled == false, self.isTerminating == false else { return }
+ guard hardwareAvailable else {
+ await self.finishAudioRouteRecoveryFailure(request, error: BoundedAudioHardwareQueue.Failure.recovering)
+ return
+ }
+
if request.reconcilesInputSelection,
await self.reconcileInputSelectionAfterTopologySettles(request) == false
{
@@ -3998,16 +4096,29 @@ final class ASRService: ObservableObject {
private func reconcileInputSelectionAfterTopologySettles(
_ request: AudioRouteRecoveryRequest
) async -> Bool {
- let snapshot = await withCheckedContinuation { continuation in
- DispatchQueue.global(qos: .userInitiated).async {
- let devices = AudioDevice.listInputDevicesRefreshingLiveness()
- let defaultInputUID = AudioDevice.getDefaultInputDevice()?.uid
- continuation.resume(returning: (devices, defaultInputUID))
+ var resolvedSnapshot: DirectCoreAudioLifecycleController.DeviceSnapshot?
+ var queryError: Error = BoundedAudioHardwareQueue.Failure.recovering
+ // One bounded retry covers transient HAL queries without leaving a
+ // recording paused after its recovery request has been consumed.
+ for _ in 0..<2 {
+ let available = await self.directAudioLifecycleController.waitForDeviceQueryAvailability()
+ guard request.generation == self.audioRouteRecoveryGeneration,
+ Task.isCancelled == false, self.isTerminating == false else { return false }
+ guard available else { break }
+ do {
+ resolvedSnapshot = try await self.directAudioLifecycleController.readDeviceSnapshot(refreshLiveness: true)
+ break
+ } catch {
+ queryError = error
}
}
guard request.generation == self.audioRouteRecoveryGeneration,
- Task.isCancelled == false
- else { return false }
+ Task.isCancelled == false, self.isTerminating == false else { return false }
+ guard let devices = resolvedSnapshot else {
+ await self.finishAudioRouteRecoveryFailure(request, error: queryError)
+ return false
+ }
+ let snapshot = (devices.devices, devices.defaultInputUID)
let currentUIDs = Set(snapshot.0.map(\.uid))
guard currentUIDs == self.cachedDeviceUIDs else {
@@ -4042,7 +4153,8 @@ final class ASRService: ObservableObject {
reconcilesInputSelection: request.reconcilesInputSelection
)
await self.directAudioLifecycleController.invalidate(
- reason: "idle_route_change:\(request.reason)"
+ reason: "idle_route_change:\(request.reason)",
+ recoveringRoute: true
)
await self.retireAudioEngineAndWait(reason: "idle_route_change:\(request.reason)")
@@ -4074,18 +4186,19 @@ final class ASRService: ObservableObject {
reason: "active_route_recovery"
)
await self.retireAudioEngineAndWait(reason: "audio_route_recovery")
-
- guard request.generation == self.audioRouteRecoveryGeneration, Task.isCancelled == false else { return }
+ let hardwareAvailable = await self.directAudioLifecycleController.waitForHardwareAvailability()
+ guard request.generation == self.audioRouteRecoveryGeneration,
+ Task.isCancelled == false, self.isTerminating == false else { return }
do {
- let maximumAttempts = SettingsStore.shared.experimentalDirectAudioCaptureEnabled
- ? max(AudioDevice.listInputDevices().count, 1) + 1
- : 1
+ guard hardwareAvailable else { throw BoundedAudioHardwareQueue.Failure.recovering }
+ var maximumStartAttempts = 1
+ var hasReadInputSnapshot = false
var failedInputUIDs = Set<String>()
var immediatelyRetriedInputUID: String?
var completedAttempts = 0
- while completedAttempts < maximumAttempts {
+ while completedAttempts < maximumStartAttempts {
completedAttempts += 1
self.audioCaptureAttemptID &+= 1
let readinessAttemptID = self.audioCaptureAttemptID
@@ -4101,8 +4214,18 @@ final class ASRService: ObservableObject {
)
do {
- try await self.startConfiguredAudioCapture(excluding: failedInputUIDs)
+ try await self.startConfiguredAudioCapture(
+ excluding: failedInputUIDs,
+ onInputSnapshotRead: { inputCount in
+ guard hasReadInputSnapshot == false else { return }
+ hasReadInputSnapshot = true
+ maximumStartAttempts = max(inputCount, 1) + 1
+ }
+ )
} catch {
+ guard error is BoundedAudioHardwareQueue.Failure == false,
+ error is CancellationError == false
+ else { throw error }
if let failedUID = self.audioStartAttemptInputUID {
let retrySameInput = immediatelyRetriedInputUID == nil
if retrySameInput {
@@ -4112,7 +4235,7 @@ final class ASRService: ObservableObject {
failedInputUIDs.insert(failedUID)
}
}
- guard completedAttempts < maximumAttempts else { throw error }
+ guard completedAttempts < maximumStartAttempts else { throw error }
self.audioCapturePipeline.setRecordingEnabled(false)
await self.stopActiveAudioCapture(
retainDirectPreparedCapture: false,
@@ -4181,7 +4304,7 @@ final class ASRService: ObservableObject {
failedInputUIDs.insert(failedUID)
}
}
- guard completedAttempts < maximumAttempts else {
+ guard completedAttempts < maximumStartAttempts else {
throw NSError(
domain: "ASRService",
code: -3,
@@ -4203,25 +4326,39 @@ final class ASRService: ObservableObject {
userInfo: [NSLocalizedDescriptionKey: "No replacement microphone is available."]
)
} catch {
- guard request.generation == self.audioRouteRecoveryGeneration, Task.isCancelled == false else { return }
- self.audioCapturePipeline.setRecordingEnabled(false)
- await self.stopActiveAudioCapture(
- retainDirectPreparedCapture: false,
- reason: "active_route_recovery_failed"
- )
- DebugLogger.shared.error("Audio route recovery failed: \(error)", source: "ASRService")
- AppServices.shared.microphonePreferenceCoordinator.markActiveSelectionUnavailable()
+ await self.finishAudioRouteRecoveryFailure(request, error: error)
+ }
+ }
- // Avoid asking stopWithoutTranscription() to await the recovery task
- // that is currently executing this catch block.
- self.audioRouteRecoveryTask = nil
- await self.stopWithoutTranscription()
- NotificationCenter.default.post(
- name: NSNotification.Name("ASRServiceDeviceDisconnected"),
- object: nil,
- userInfo: ["errorMessage": "Recording stopped because the audio device changed."]
+ private func finishAudioRouteRecoveryFailure(_ request: AudioRouteRecoveryRequest, error: Error) async {
+ guard request.generation == self.audioRouteRecoveryGeneration,
+ Task.isCancelled == false, self.isTerminating == false else { return }
+ DebugLogger.shared.error("Audio route recovery failed: \(error)", source: "ASRService")
+ AppServices.shared.microphonePreferenceCoordinator.markActiveSelectionUnavailable()
+ let failedSessionID = self.benchmarkSessionID
+ var expectedStartGeneration = self.audioCaptureStartGeneration
+ let wasCapturing = self.isRunning || self.isStarting
+ if self.isRunning {
+ // This task keeps recovery ownership until its defer runs. User Stop
+ // may cancel and await it, but it must never await itself here.
+ await self.stopWithoutTranscription(finishingRecovery: true)
+ } else if self.isStarting {
+ // Startup may itself be awaiting this recovery. Invalidate it without
+ // awaiting its completion, so it can unwind after this task returns.
+ self.interruptPendingAudioCaptureStart()
+ expectedStartGeneration = self.audioCaptureStartGeneration
+ await self.audioCaptureReadinessGate.cancel(
+ sessionID: failedSessionID, attemptID: self.audioCaptureAttemptID
)
}
+ guard wasCapturing, self.benchmarkSessionID == failedSessionID,
+ self.audioCaptureStartGeneration == expectedStartGeneration,
+ request.generation == self.audioRouteRecoveryGeneration,
+ Task.isCancelled == false, self.isTerminating == false else { return }
+ self.presentAudioCaptureFailure(
+ title: "Recording Stopped",
+ message: "The microphone could not recover after the audio device changed. \(error.localizedDescription)"
+ )
}
private func handleDirectCaptureFormatInvalidation(
@@ -4421,6 +4558,7 @@ final class ASRService: ObservableObject {
private var deviceListListenerInstalled = false
private var deviceListListenerToken: AudioObjectPropertyListenerBlock?
+ private let deviceListListenerQueue = DispatchQueue(label: "com.fluidvoice.audio.topology-notifications", qos: .userInitiated)
private var monitoredDeviceID: AudioObjectID?
private var monitoredDeviceIsAliveListenerToken: AudioObjectPropertyListenerBlock?
@@ -4435,16 +4573,17 @@ final class ASRService: ObservableObject {
mElement: kAudioObjectPropertyElementMain
)
- let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
- // Defer to next runloop pass — CoreAudio may hold an internal lock during
- // this callback, and our handler makes synchronous CoreAudio queries that
- // would deadlock waiting for the same lock.
+ let controller = self.directAudioLifecycleController
+ let token: AudioObjectPropertyListenerBlock = { [weak self, weak controller] _, _ in
+ // Mark freshness immediately, even if the UI is busy. This only
+ // updates an in-memory revision; HAL queries remain outside callbacks.
+ controller?.noteHardwareTopologyChanged()
DispatchQueue.main.async { self?.handleDeviceListChanged() }
}
let status = AudioObjectAddPropertyListenerBlock(
AudioObjectID(kAudioObjectSystemObject),
&address,
- DispatchQueue.main,
+ self.deviceListListenerQueue,
token
)
@@ -6030,6 +6169,10 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
return self.levelMonitoringEnabled
}
+ #if DEBUG
+ var isRecordingEnabledForTesting: Bool { self.lock.withLock { self.recordingEnabled } }
+ #endif
+
func setLevelMonitoringEnabled(_ enabled: Bool) {
self.lock.lock()
self.levelMonitoringEnabled = enabled
diff --git a/Sources/Fluid/Services/BoundedAudioHardwareQueue.swift b/Sources/Fluid/Services/BoundedAudioHardwareQueue.swift
new file mode 100644
index 00000000..b5dd409a
--- /dev/null
+++ b/Sources/Fluid/Services/BoundedAudioHardwareQueue.swift
@@ -0,0 +1,230 @@
+import Foundation
+
+/// Cancellation releases callers, never the native operation's memory or queue.
+/// Healthy startup has no deadline. Recovery queries and teardown can explicitly
+/// bound their caller wait without aborting or freeing a native call.
+/// Interrupted hardware must finish serialized cleanup before another operation
+/// can be admitted. In particular, cancellation must not launch a second IOProc.
+final nonisolated class BoundedAudioHardwareQueue: @unchecked Sendable {
+ enum Failure: LocalizedError {
+ case timedOut
+ case recovering
+ case cleanupFailed
+ case deviceStopped
+
+ var errorDescription: String? {
+ switch self {
+ case .timedOut, .recovering, .deviceStopped:
+ "The microphone is not responding. Try again shortly. If it remains unavailable, quit and reopen FluidVoice."
+ case .cleanupFailed:
+ "The microphone could not be reset safely. Quit and reopen FluidVoice before recording again."
+ }
+ }
+ }
+
+ private final class Cancellation: @unchecked Sendable {
+ private let lock = NSLock()
+ private var cancelled = false
+
+ var isCancelled: Bool { self.lock.withLock { self.cancelled } }
+
+ func cancel() { self.lock.withLock { self.cancelled = true } }
+ }
+
+ private struct Pending {
+ let fail: @Sendable (Error) -> Void
+ let timer: DispatchWorkItem?
+ let recover: @Sendable () -> Bool
+ }
+
+ private struct AvailabilityWaiter {
+ let continuation: CheckedContinuation<Bool, Never>
+ let timer: DispatchWorkItem?
+ }
+
+ let queue: DispatchQueue
+ private let timeout: TimeInterval?
+ private let lock = NSLock()
+ private var pending: [UUID: Pending] = [:]
+ private var recovering = false
+ private var cleanupFailed = false
+ private var availabilityWaiters: [UUID: AvailabilityWaiter] = [:]
+
+ init(queue: DispatchQueue, timeout: TimeInterval? = nil) {
+ self.queue = queue
+ self.timeout = timeout
+ }
+
+ var isAvailable: Bool {
+ self.lock.withLock { self.recovering == false && self.cleanupFailed == false }
+ }
+
+ func checkAvailable() throws {
+ try self.lock.withLock {
+ if self.cleanupFailed { throw Failure.cleanupFailed }
+ if self.recovering { throw Failure.recovering }
+ }
+ }
+
+ /// Only the serialized owner can establish that an earlier cleanup failure
+ /// is now safe (for example, after a matching device-removal notification).
+ /// A running native operation must still complete its own recovery first.
+ @discardableResult
+ func clearFailureAfterSerializedRecovery() -> Bool {
+ dispatchPrecondition(condition: .onQueue(self.queue))
+ let cleared = self.lock.withLock {
+ guard self.recovering == false, self.cleanupFailed else { return false }
+ self.cleanupFailed = false
+ return true
+ }
+ if cleared { self.resumeAvailabilityWaitersIfReady() }
+ return cleared
+ }
+
+ /// Wait for serialized cleanup without starting another hardware operation.
+ /// Cancellation removes only this waiter; it must not interrupt the cleanup.
+ func waitUntilAvailable(timeout: TimeInterval? = nil) async -> Bool {
+ let id = UUID()
+ let cancellation = Cancellation()
+ return await withTaskCancellationHandler {
+ await withCheckedContinuation { continuation in
+ self.lock.lock()
+ if cancellation.isCancelled {
+ self.lock.unlock()
+ continuation.resume(returning: false)
+ return
+ }
+ if self.recovering == false, self.cleanupFailed == false {
+ self.lock.unlock()
+ continuation.resume(returning: true)
+ return
+ }
+ let timer = timeout.map { _ in DispatchWorkItem { [weak self] in self?.finishAvailabilityWaiter(id) } }
+ self.availabilityWaiters[id] = AvailabilityWaiter(continuation: continuation, timer: timer)
+ self.lock.unlock()
+ if let timeout, let timer {
+ DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + timeout, execute: timer)
+ }
+ }
+ } onCancel: {
+ cancellation.cancel()
+ self.finishAvailabilityWaiter(id)
+ }
+ }
+
+ private func finishAvailabilityWaiter(_ id: UUID) {
+ guard let waiter = self.lock.withLock({ self.availabilityWaiters.removeValue(forKey: id) }) else { return }
+ waiter.timer?.cancel()
+ waiter.continuation.resume(returning: false)
+ }
+
+ private func resumeAvailabilityWaitersIfReady() {
+ let waiters = self.lock.withLock {
+ guard self.recovering == false, self.cleanupFailed == false else { return [AvailabilityWaiter]() }
+ let waiters = Array(self.availabilityWaiters.values)
+ self.availabilityWaiters.removeAll(keepingCapacity: false)
+ return waiters
+ }
+ for waiter in waiters {
+ waiter.timer?.cancel()
+ waiter.continuation.resume(returning: true)
+ }
+ }
+
+ func run<Value: Sendable>(
+ cancellable: Bool = true,
+ timeout: TimeInterval? = nil,
+ recover: @escaping @Sendable () -> Bool,
+ operation: @escaping @Sendable () throws -> Value
+ ) async throws -> Value {
+ let id = UUID()
+ let cancellation = Cancellation()
+ return try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { continuation in
+ self.lock.lock()
+ if cancellation.isCancelled || self.recovering || self.cleanupFailed {
+ let error: Error = cancellation.isCancelled
+ ? CancellationError()
+ : (self.cleanupFailed ? Failure.cleanupFailed : Failure.recovering)
+ self.lock.unlock()
+ continuation.resume(throwing: error)
+ return
+ }
+ let deadline = timeout ?? self.timeout
+ let timer = deadline.map { _ in DispatchWorkItem { [weak self] in
+ self?.interrupt(requestID: id, error: Failure.timedOut)
+ } }
+ self.pending[id] = Pending(
+ fail: { continuation.resume(throwing: $0) },
+ timer: timer,
+ recover: recover
+ )
+ // Enqueue under the admission lock so interruption cannot put
+ // cleanup ahead of an admitted native operation.
+ self.queue.async {
+ guard self.lock.withLock({ self.pending[id] != nil }) else { return }
+ let result = Result { try operation() }
+ self.lock.lock()
+ let request = self.pending.removeValue(forKey: id)
+ self.lock.unlock()
+ guard let request else { return } // Already cancelled/timed out.
+ request.timer?.cancel()
+ continuation.resume(with: result)
+ }
+ if let deadline, let timer {
+ DispatchQueue.global(qos: .userInitiated).asyncAfter(
+ deadline: .now() + deadline,
+ execute: timer
+ )
+ }
+ self.lock.unlock()
+ }
+ } onCancel: {
+ guard cancellable else { return }
+ cancellation.cancel()
+ self.interrupt(requestID: id, error: CancellationError())
+ }
+ }
+
+ /// Used when the UI cancels a recording without cancelling its Swift task.
+ /// No work is created when startup has already finished.
+ func cancelPendingOperations() {
+ self.interrupt(requestID: nil, error: CancellationError())
+ }
+
+ /// A device notification can establish failure before a native call returns.
+ /// The caller is released, but cleanup still waits behind the native owner.
+ func failPendingOperationsAfterDeviceStopped() {
+ self.interrupt(requestID: nil, error: Failure.deviceStopped)
+ }
+
+ private func interrupt(requestID: UUID?, error: Error) {
+ self.lock.lock()
+ guard self.recovering == false,
+ let request = requestID.flatMap({ self.pending[$0] }) ??
+ (requestID == nil ? self.pending.values.first : nil)
+ else {
+ self.lock.unlock()
+ return
+ }
+ self.recovering = true
+ let requests = Array(self.pending.values)
+ self.pending.removeAll(keepingCapacity: false)
+ // The native call may still be running. Never stop/free its resources
+ // from this thread, and do not allocate replacement hardware meanwhile.
+ let recover = request.recover
+ self.queue.async {
+ let recovered = recover()
+ self.lock.withLock {
+ self.cleanupFailed = recovered == false
+ self.recovering = false
+ }
+ if recovered { self.resumeAvailabilityWaitersIfReady() }
+ }
+ self.lock.unlock()
+ for request in requests {
+ request.timer?.cancel()
+ request.fail(error)
+ }
+ }
+}
diff --git a/Sources/Fluid/Services/DirectCoreAudioInput.swift b/Sources/Fluid/Services/DirectCoreAudioInput.swift
index 58566de4..afecc745 100644
--- a/Sources/Fluid/Services/DirectCoreAudioInput.swift
+++ b/Sources/Fluid/Services/DirectCoreAudioInput.swift
@@ -668,8 +668,20 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
qos: .userInitiated
)
private let snapshotLock = NSLock()
+ private let recoveryTimeout: TimeInterval
+ private let hardwareOperations: BoundedAudioHardwareQueue
+ private let deviceQueries: BoundedAudioHardwareQueue
+ private let captureDeviceQueries: BoundedAudioHardwareQueue
+ private var shutdownRequested = false
+ // A display can change HAL topology without changing the selected input's
+ // ID or format. Refresh stopped capture on the next Start, not mid-recording.
+ private var hardwareTopologyRevision: UInt64 = 0 // snapshotLock
+ private var topologyRecoveryCheckPending = false // snapshotLock
+ private var lastStartedTopologyRevision: UInt64 = 0 // lifecycleQueue
private let stoppedHardwareLock = NSLock()
private var stoppedHardwareGenerations: Set<UInt64> = []
+ private var lastReportedAbnormalStopGeneration: UInt64?
+ private var pendingFormatInvalidationGenerations: Set<UInt64> = []
private var storedSnapshot = Snapshot(
phase: .empty,
generation: 0,
@@ -682,6 +694,9 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
private let packetHandler: PacketHandler
private let inputFactory: InputFactory
+ private let deviceSnapshotReader: @Sendable (Bool) throws -> DeviceSnapshot
+ private let deviceLivenessReader: @Sendable (AudioObjectID) -> Bool?
+ private let deviceResolver: @Sendable (DirectCoreAudioDeviceSelection) throws -> AudioDevice.Device?
private let fingerprintReader: FingerprintReader
private let onFormatInvalidated: @Sendable (FormatInvalidation) -> Void
private let installsHardwareListeners: Bool
@@ -694,6 +709,12 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
private var isShutDown = false
private var isPoisoned = false
private var inputDeviceName: String?
+ private struct FailedHardware: Equatable {
+ let generation: UInt64
+ let deviceID: AudioObjectID
+ }
+
+ private var failedHardware: FailedHardware?
init(
packetHandler: @escaping PacketHandler,
@@ -704,11 +725,28 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
try DirectCoreAudioFormatFingerprint.read(deviceID: $0)
},
installsHardwareListeners: Bool = true,
+ operationTimeout: TimeInterval? = nil,
+ deviceSnapshotReader: @escaping @Sendable (Bool) throws -> DeviceSnapshot = DirectCoreAudioLifecycleController.queryDeviceSnapshot,
+ deviceLivenessReader: @escaping @Sendable (AudioObjectID) -> Bool? = DirectCoreAudioLifecycleController.readDeviceLiveness,
+ deviceResolver: @escaping @Sendable (DirectCoreAudioDeviceSelection) throws -> AudioDevice.Device? = DirectCoreAudioLifecycleController.resolveSelectedDevice,
onFormatInvalidated: @escaping @Sendable (FormatInvalidation) -> Void
) {
+ self.recoveryTimeout = operationTimeout ?? 5
+ self.hardwareOperations = BoundedAudioHardwareQueue(queue: self.lifecycleQueue, timeout: operationTimeout)
+ self.deviceQueries = BoundedAudioHardwareQueue(
+ queue: DispatchQueue(label: "com.fluidvoice.audio.device-snapshot", qos: .userInitiated),
+ timeout: operationTimeout ?? 5
+ )
+ self.captureDeviceQueries = BoundedAudioHardwareQueue(
+ queue: DispatchQueue(label: "com.fluidvoice.audio.capture-device-snapshot", qos: .userInitiated),
+ timeout: operationTimeout
+ )
self.packetHandler = packetHandler
self.inputFactory = inputFactory
self.fingerprintReader = fingerprintReader
+ self.deviceSnapshotReader = deviceSnapshotReader
+ self.deviceLivenessReader = deviceLivenessReader
+ self.deviceResolver = deviceResolver
self.installsHardwareListeners = installsHardwareListeners
self.onFormatInvalidated = onFormatInvalidated
}
@@ -735,50 +773,192 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
}
var snapshot: Snapshot {
- self.snapshotLock.lock()
- defer { self.snapshotLock.unlock() }
- return self.storedSnapshot
+ var snapshot = self.snapshotLock.withLock { self.storedSnapshot }
+ if self.hardwareOperations.isAvailable == false {
+ snapshot = Snapshot(
+ phase: .failed,
+ generation: snapshot.generation,
+ deviceID: snapshot.deviceID,
+ deviceName: snapshot.deviceName,
+ sampleRate: snapshot.sampleRate,
+ bufferFrameSize: snapshot.bufferFrameSize,
+ fingerprint: snapshot.fingerprint
+ )
+ }
+ return snapshot
+ }
+
+ var isRecoveringHardware: Bool { self.hardwareOperations.isAvailable == false }
+
+ func waitForHardwareAvailability() async -> Bool {
+ await self.hardwareOperations.waitUntilAvailable(timeout: self.recoveryTimeout)
+ }
+
+ func waitForDeviceQueryAvailability() async -> Bool {
+ await self.deviceQueries.waitUntilAvailable(timeout: self.recoveryTimeout)
+ }
+
+ func waitForPendingHardwareRetirement() async -> Bool {
+ await self.hardwareOperations.waitUntilAvailable(timeout: self.recoveryTimeout)
+ }
+
+ func cancelPendingStartup() {
+ self.hardwareOperations.cancelPendingOperations()
+ self.captureDeviceQueries.cancelPendingOperations()
+ }
+
+ /// No HAL calls or capture mutations in the device-list notification path.
+ /// Multiple events collapse into one fresh setup at the next stopped start.
+ func noteHardwareTopologyChanged() {
+ let revision = self.snapshotLock.withLock {
+ self.hardwareTopologyRevision &+= 1
+ return self.hardwareTopologyRevision
+ }
+ Self.log("Direct capture topology changed revision=\(revision); next stopped start requires fresh input", level: .info)
+ self.scheduleFailedHardwareCheck()
+ }
+
+ private func scheduleFailedHardwareCheck() {
+ let enqueue = self.snapshotLock.withLock {
+ guard self.shutdownRequested == false, self.topologyRecoveryCheckPending == false else { return false }
+ self.topologyRecoveryCheckPending = true
+ return true
+ }
+ if enqueue {
+ // Queue behind native work and its cleanup. A topology callback must
+ // never clear failure while that work still owns capture resources.
+ // Coalesce bursts here; ordinary capture startup is never delayed.
+ self.lifecycleQueue.asyncAfter(deadline: .now() + 0.05) { [weak self] in self?.checkFailedHardwareLocked() }
+ }
+ }
+
+ private func checkFailedHardwareLocked() {
+ let revision = self.snapshotLock.withLock { self.hardwareTopologyRevision }
+ guard self.isShutDown == false,
+ self.snapshotLock.withLock({ self.shutdownRequested == false }),
+ self.isPoisoned, let failedHardware = self.failedHardware
+ else {
+ self.snapshotLock.withLock { self.topologyRecoveryCheckPending = false }
+ return
+ }
+ Task { [weak self, deviceQueries, deviceLivenessReader] in
+ // Unknown, failed, or timed-out queries cannot authorize replacement.
+ // Keep HAL queries off both the notification and lifecycle queues.
+ let isAlive = try? await deviceQueries.run(recover: { true }) {
+ deviceLivenessReader(failedHardware.deviceID)
+ }
+ self?.lifecycleQueue.async { [weak self] in
+ guard let self else { return }
+ defer {
+ // An event can arrive even while this completion is being
+ // handled. Release ownership only after applying its result,
+ // then recheck any newer revision instead of losing it.
+ let changedAgain = self.snapshotLock.withLock {
+ self.topologyRecoveryCheckPending = false
+ return revision != self.hardwareTopologyRevision
+ }
+ if changedAgain { self.scheduleFailedHardwareCheck() }
+ }
+ guard self.isShutDown == false,
+ self.snapshotLock.withLock({ self.shutdownRequested == false && revision == self.hardwareTopologyRevision }),
+ self.failedHardware == failedHardware,
+ self.generation == failedHardware.generation,
+ isAlive == false
+ else { return }
+ self.recordStoppedHardwareNotification(generation: failedHardware.generation)
+ self.handleFormatInvalidationLocked(
+ generation: failedHardware.generation,
+ reason: "device_list_confirmed_stopped"
+ )
+ }
+ }
+ }
+
+ struct DeviceSnapshot: Sendable {
+ let devices: [AudioDevice.Device]
+ let defaultInputUID: String?
+ }
+
+ /// Cancellation releases the caller even if HAL discovery is blocked. This
+ /// queue is independent of recovery queries and never stops running capture.
+ func readCaptureDeviceSnapshot() async throws -> DeviceSnapshot {
+ try await self.captureDeviceQueries.run(recover: { true }) {
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ Self.log("Direct capture startup device query begin", level: .debug)
+ let snapshot = try self.deviceSnapshotReader(false)
+ Self.log("Direct capture startup device query end elapsedMs=\(Self.elapsedMilliseconds(since: startedAt))", level: .debug)
+ return snapshot
+ }
+ }
+
+ func readDeviceSnapshot(refreshLiveness: Bool = false) async throws -> DeviceSnapshot {
+ // Only route recovery uses this bounded queue. Its cancellation cannot
+ // interrupt ordinary startup discovery or an already recording input.
+ try await self.deviceQueries.run(recover: { true }) {
+ try self.deviceSnapshotReader(refreshLiveness)
+ }
+ }
+
+ private static func queryDeviceSnapshot(refreshLiveness: Bool) -> DeviceSnapshot {
+ let devices = refreshLiveness
+ ? AudioDevice.listInputDevicesRefreshingLiveness()
+ : AudioDevice.listAllDevices()
+ return DeviceSnapshot(
+ devices: devices,
+ defaultInputUID: AudioDevice.getDefaultInputDevice(from: devices)?.uid
+ )
+ }
+
+ private func performHardwareOperation<Value: Sendable>(
+ cancellable: Bool = true,
+ timeout: TimeInterval? = nil,
+ _ operation: @escaping @Sendable () throws -> Value
+ ) async throws -> Value {
+ try await self.hardwareOperations.run(cancellable: cancellable, timeout: timeout, recover: { [self] in
+ let status = self.invalidateLocked(reason: "interrupted_hardware_operation")
+ if self.snapshotLock.withLock({ self.shutdownRequested }) {
+ self.isShutDown = true
+ self.publishSnapshot(phase: .shutDown, input: nil, fingerprint: nil)
+ }
+ Self.log("Direct capture interrupted operation drained status=\(status)", level: .info)
+ return status == noErr && self.isPoisoned == false
+ }) {
+ try self.hardwareOperations.checkAvailable()
+ return try operation()
+ }
}
func resolveDevice(
selection: DirectCoreAudioDeviceSelection,
reason: String
) async throws -> AudioDevice.Device {
- try await withCheckedThrowingContinuation { continuation in
- self.lifecycleQueue.async {
- let startedAt = ProcessInfo.processInfo.systemUptime
- let device: AudioDevice.Device?
- switch selection {
- case .systemDefault:
- device = AudioDevice.getDefaultInputDevice()
- .flatMap { AudioDevice.isInputDeviceUsable($0) ? $0 : nil }
- case let .preferredUID(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(
- throwing: Self.error(
- "No input device is available for \(selection)."
- )
- )
- return
- }
- Self.log(
- "Direct capture device resolved off-main reason=\(reason) " +
- "device='\(device.name)' id=\(device.id) " +
- "elapsedMs=\(Self.elapsedMilliseconds(since: startedAt))",
- level: .info
- )
- continuation.resume(returning: device)
+ try await self.performHardwareOperation {
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ let device = try self.deviceResolver(selection)
+ guard let device else {
+ throw Self.error("No input device is available for \(selection).")
}
+ Self.log(
+ "Direct capture device resolved off-main reason=\(reason) " +
+ "device='\(device.name)' id=\(device.id) " +
+ "elapsedMs=\(Self.elapsedMilliseconds(since: startedAt))",
+ level: .info
+ )
+ return device
+ }
+ }
+
+ private static func resolveSelectedDevice(_ selection: DirectCoreAudioDeviceSelection) -> AudioDevice.Device? {
+ switch selection {
+ case .systemDefault:
+ return AudioDevice.getDefaultInputDevice()
+ .flatMap { AudioDevice.isInputDeviceUsable($0) ? $0 : nil }
+ case let .preferredUID(uid):
+ // Keep fallback in ASRService so it always follows the app's priority.
+ guard let device = AudioDevice.getInputDevice(byUID: uid),
+ AudioDevice.isInputDeviceUsable(device)
+ else { return nil }
+ return device
}
}
@@ -787,20 +967,8 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
deviceName: String,
reason: String
) async throws -> Snapshot {
- try await withCheckedThrowingContinuation { continuation in
- self.lifecycleQueue.async {
- do {
- try continuation.resume(
- returning: self.prepareLocked(
- deviceID: deviceID,
- deviceName: deviceName,
- reason: reason
- )
- )
- } catch {
- continuation.resume(throwing: error)
- }
- }
+ try await self.performHardwareOperation {
+ try self.prepareLocked(deviceID: deviceID, deviceName: deviceName, reason: reason)
}
}
@@ -809,83 +977,62 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
deviceName: String,
reason: String
) async throws -> Snapshot {
- try await withCheckedThrowingContinuation { continuation in
- self.lifecycleQueue.async {
- do {
- guard self.isShutDown == false else {
- throw Self.error("Direct Core Audio lifecycle is shut down.")
+ try await self.performHardwareOperation {
+ do {
+ guard self.isShutDown == false,
+ self.snapshotLock.withLock({ self.shutdownRequested == false })
+ else {
+ throw Self.error("Direct Core Audio lifecycle is shut down.")
+ }
+ let topologyRevision = self.snapshotLock.withLock { self.hardwareTopologyRevision }
+ if let input = self.input, input.isRunning == false,
+ topologyRevision != self.lastStartedTopologyRevision
+ {
+ // A prewarm made during device churn can still have a stale
+ // IOProc despite an unchanged fingerprint. Rebuild once on
+ // actual demand, after the user has finished connecting it.
+ let status = self.invalidateLocked(reason: "topology_changed_before_start")
+ guard status == noErr, self.isPoisoned == false else {
+ throw BoundedAudioHardwareQueue.Failure.cleanupFailed
}
- var prepared = try self.prepareLocked(
+ }
+ var prepared = try self.prepareLocked(
+ deviceID: deviceID,
+ deviceName: deviceName,
+ reason: reason
+ )
+ guard let input = self.input else {
+ throw Self.error("Direct Core Audio input was not prepared.")
+ }
+
+ let validationStartedAt = ProcessInfo.processInfo.systemUptime
+ let currentFingerprint = try self.fingerprintReader(deviceID)
+ if currentFingerprint != input.formatFingerprint {
+ Self.log(
+ "Direct capture fingerprint changed before start; rebuilding " +
+ "generation=\(prepared.generation) old={\(input.formatFingerprint.logDescription)} " +
+ "new={\(currentFingerprint.logDescription)}",
+ level: .warning
+ )
+ self.invalidateLocked(reason: "pre_start_fingerprint_changed")
+ prepared = try self.prepareLocked(
deviceID: deviceID,
deviceName: deviceName,
- reason: reason
+ reason: "pre_start_fingerprint_changed"
)
- guard let input = self.input else {
- throw Self.error("Direct Core Audio input was not prepared.")
- }
-
- let validationStartedAt = ProcessInfo.processInfo.systemUptime
- let currentFingerprint = try self.fingerprintReader(deviceID)
- if currentFingerprint != input.formatFingerprint {
- Self.log(
- "Direct capture fingerprint changed before start; rebuilding " +
- "generation=\(prepared.generation) old={\(input.formatFingerprint.logDescription)} " +
- "new={\(currentFingerprint.logDescription)}",
- level: .warning
- )
- self.invalidateLocked(reason: "pre_start_fingerprint_changed")
- prepared = try self.prepareLocked(
- deviceID: deviceID,
- deviceName: deviceName,
- reason: "pre_start_fingerprint_changed"
- )
- }
+ }
- 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,
- fingerprint: validatedInput.formatFingerprint
- )
- let startStartedAt = ProcessInfo.processInfo.systemUptime
- Self.log(
- "Direct capture start begin generation=\(self.generation) " +
- "device='\(deviceName)' validationMs=" +
- "\(Self.elapsedMilliseconds(since: validationStartedAt))",
- level: .info
- )
- try validatedInput.start()
- let fingerprintAfterStart = try self.fingerprintReader(deviceID)
- guard fingerprintAfterStart == validatedInput.formatFingerprint,
+ 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)
+ try self.hardwareOperations.checkAvailable()
+ guard runningFingerprint == validatedInput.formatFingerprint,
validatedInput.openPacketGateIfClean()
else {
throw Self.error(
- "Direct Core Audio format changed while starting generation " +
+ "Direct Core Audio format changed while reusing running input generation " +
"\(self.generation)."
)
}
@@ -894,38 +1041,81 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
input: validatedInput,
fingerprint: validatedInput.formatFingerprint
)
+ // Reusing preview does not refresh its native setup. Keep
+ // the pending revision so the next stopped start rebuilds.
Self.log(
- "Direct capture start end generation=\(self.generation) " +
- "elapsedMs=\(Self.elapsedMilliseconds(since: startStartedAt)) " +
- "fingerprint={\(validatedInput.formatFingerprint.logDescription)}",
- level: .info
+ "Direct capture start reused running input generation=\(self.generation) " +
+ "device='\(deviceName)'",
+ level: .debug
)
- continuation.resume(returning: self.snapshot)
- } catch {
- self.publishSnapshot(
- phase: .failed,
- input: self.input,
- fingerprint: self.input?.formatFingerprint
+ return self.snapshot
+ }
+ guard topologyRevision == self.snapshotLock.withLock({ self.hardwareTopologyRevision }) else {
+ throw Self.error("Audio hardware changed while preparing the microphone. Retry with fresh capture state.")
+ }
+ self.publishSnapshot(
+ phase: .starting,
+ input: validatedInput,
+ fingerprint: validatedInput.formatFingerprint
+ )
+ let startStartedAt = ProcessInfo.processInfo.systemUptime
+ Self.log(
+ "Direct capture start begin generation=\(self.generation) " +
+ "device='\(deviceName)' validationMs=" +
+ "\(Self.elapsedMilliseconds(since: validationStartedAt))",
+ level: .info
+ )
+ try self.hardwareOperations.checkAvailable()
+ Self.log("Direct capture native start enter generation=\(self.generation) device=\(deviceID)", level: .info)
+ try validatedInput.start()
+ Self.log("Direct capture native start return generation=\(self.generation) elapsedMs=\(Self.elapsedMilliseconds(since: startStartedAt))", level: .info)
+ try self.hardwareOperations.checkAvailable()
+ Self.log("Direct capture post-start validation begin generation=\(self.generation)", level: .debug)
+ let fingerprintAfterStart = try self.fingerprintReader(deviceID)
+ Self.log("Direct capture post-start validation end generation=\(self.generation)", level: .debug)
+ try self.hardwareOperations.checkAvailable()
+ guard fingerprintAfterStart == validatedInput.formatFingerprint,
+ validatedInput.openPacketGateIfClean()
+ else {
+ throw Self.error(
+ "Direct Core Audio format changed while starting generation " +
+ "\(self.generation)."
)
- self.invalidateLocked(reason: "start_failed")
- continuation.resume(throwing: error)
}
+ self.publishSnapshot(
+ phase: .running,
+ input: validatedInput,
+ fingerprint: validatedInput.formatFingerprint
+ )
+ self.lastStartedTopologyRevision = topologyRevision
+ Self.log(
+ "Direct capture start end generation=\(self.generation) " +
+ "elapsedMs=\(Self.elapsedMilliseconds(since: startStartedAt)) " +
+ "fingerprint={\(validatedInput.formatFingerprint.logDescription)}",
+ level: .info
+ )
+ return self.snapshot
+ } catch {
+ self.publishSnapshot(
+ phase: .failed,
+ input: self.input,
+ fingerprint: self.input?.formatFingerprint
+ )
+ self.invalidateLocked(reason: "start_failed")
+ throw error
}
}
}
- func stop(retainPrepared: Bool, reason: String) async -> StopReport {
- await withCheckedContinuation { continuation in
- self.lifecycleQueue.async {
+ func stop(retainPrepared: Bool, reason: String, recoveringRoute: Bool = false) async -> StopReport {
+ do {
+ return try await self.performHardwareOperation(cancellable: false, timeout: recoveringRoute ? self.recoveryTimeout : nil) {
guard let input = self.input else {
- continuation.resume(
- returning: StopReport(
- status: noErr,
- droppedPackets: 0,
- retainedPreparedCapture: false
- )
+ return StopReport(
+ status: noErr,
+ droppedPackets: 0,
+ retainedPreparedCapture: false
)
- return
}
let startedAt = ProcessInfo.processInfo.systemUptime
@@ -965,38 +1155,31 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
"retained=\(retainPrepared && self.input != nil)",
level: .info
)
- continuation.resume(
- returning: StopReport(
- status: status,
- droppedPackets: droppedPackets,
- retainedPreparedCapture: retainPrepared && self.input != nil
- )
+ return StopReport(
+ status: status,
+ droppedPackets: droppedPackets,
+ retainedPreparedCapture: retainPrepared && self.input != nil
)
}
+ } catch {
+ Self.log("Direct capture stop interrupted reason=\(reason): \(error.localizedDescription)", level: .warning)
+ return StopReport(status: kAudioHardwareUnspecifiedError, droppedPackets: 0, retainedPreparedCapture: false)
}
}
- func invalidate(reason: String) async {
- await withCheckedContinuation { continuation in
- self.lifecycleQueue.async {
- _ = self.invalidateLocked(reason: reason)
- continuation.resume()
- }
+ func invalidate(reason: String, recoveringRoute: Bool = false) async {
+ _ = try? await self.performHardwareOperation(cancellable: false, timeout: recoveringRoute ? self.recoveryTimeout : nil) {
+ self.invalidateLocked(reason: reason)
}
}
func shutdown(reason: String) async {
- await withCheckedContinuation { continuation in
- self.lifecycleQueue.async {
- guard self.isShutDown == false else {
- continuation.resume()
- return
- }
- self.isShutDown = true
- _ = self.invalidateLocked(reason: reason)
- self.publishSnapshot(phase: .shutDown, input: nil, fingerprint: nil)
- continuation.resume()
- }
+ self.snapshotLock.withLock { self.shutdownRequested = true }
+ _ = try? await self.performHardwareOperation(cancellable: false, timeout: self.recoveryTimeout) {
+ guard self.isShutDown == false else { return }
+ self.isShutDown = true
+ _ = self.invalidateLocked(reason: reason)
+ self.publishSnapshot(phase: .shutDown, input: nil, fingerprint: nil)
}
}
@@ -1005,7 +1188,10 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
deviceName: String,
reason: String
) throws -> Snapshot {
- guard self.isShutDown == false else {
+ try self.hardwareOperations.checkAvailable()
+ guard self.isShutDown == false,
+ self.snapshotLock.withLock({ self.shutdownRequested == false })
+ else {
throw Self.error("Direct Core Audio lifecycle is shut down.")
}
guard self.isPoisoned == false else {
@@ -1015,6 +1201,7 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
}
let currentFingerprint = try self.fingerprintReader(deviceID)
+ try self.hardwareOperations.checkAvailable()
if let input = self.input,
input.deviceID == deviceID,
input.formatFingerprint == currentFingerprint
@@ -1064,9 +1251,11 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
let gate = DirectCoreAudioPacketGate()
let downstreamHandler = self.packetHandler
+ let hardwareOperations = self.hardwareOperations
let input: any DirectCoreAudioInputControlling
do {
input = try self.inputFactory(deviceID) { samples, frameCount, sampleRate, inputHostTime, inputSampleTime in
+ guard hardwareOperations.isAvailable else { return }
gate.withAcceptedPacket {
downstreamHandler(
samples,
@@ -1093,6 +1282,7 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
self.input = input
self.packetGate = gate
do {
+ try self.hardwareOperations.checkAvailable()
if self.installsHardwareListeners {
try self.installFormatListenersLocked(
fingerprint: input.formatFingerprint,
@@ -1101,6 +1291,7 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
)
}
let fingerprintAfterListeners = try self.fingerprintReader(deviceID)
+ try self.hardwareOperations.checkAvailable()
guard fingerprintAfterListeners == input.formatFingerprint else {
throw Self.error(
"Direct Core Audio format changed while installing listeners."
@@ -1180,6 +1371,12 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
)
} else {
self.isPoisoned = true
+ if let input {
+ self.failedHardware = FailedHardware(generation: self.generation, deviceID: input.deviceID)
+ // Covers removal while listeners were being detached, before
+ // cleanup had published its failure to the hardware queue.
+ self.scheduleFailedHardwareCheck()
+ }
Self.log(
"Direct capture teardown failed generation=\(self.generation) " +
"status=\(status); lifecycle poisoned and callback context quarantined",
@@ -1291,43 +1488,29 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
return
}
- let invalidationHandler = self.onFormatInvalidated
- let block: AudioObjectPropertyListenerBlock = { [weak self, weak input] listenerObjectID, _ in
+ let block = Self.makeDevicePropertyListener(objectID: objectID) { [weak self, weak input] objectID in
let deviceIsAlive =
name == "device_is_alive"
- ? Self.readDeviceLiveness(objectID: listenerObjectID)
+ ? Self.readDeviceLiveness(objectID: objectID)
: nil
- let hardwareIsKnownStopped =
- name == "audio_service_restarted" ||
- name == "io_stopped_abnormally" ||
- (name == "device_is_alive" && deviceIsAlive != true)
- if hardwareIsKnownStopped {
- self?.recordStoppedHardwareNotification(generation: generation)
- }
+ let hardwareIsKnownStopped = Self.hardwareIsKnownStopped(
+ reason: name, deviceIsAlive: deviceIsAlive
+ )
if name == "device_is_alive" {
Self.log(
"Direct capture liveness notification generation=\(generation) " +
- "device=\(listenerObjectID) " +
+ "device=\(objectID) " +
"alive=\(deviceIsAlive.map(String.init) ?? "unreadable") " +
"knownStopped=\(hardwareIsKnownStopped)",
level: hardwareIsKnownStopped ? .warning : .info
)
}
- input?.markFormatDirty()
- invalidationHandler(
- FormatInvalidation(
- generation: generation,
- deviceID: input?.deviceID ?? kAudioObjectUnknown,
- reason: name,
- wasRunning: input?.isRunning ?? false
- )
+ self?.handleFormatNotification(
+ generation: generation,
+ reason: name,
+ input: input,
+ hardwareIsKnownStopped: hardwareIsKnownStopped
)
- self?.lifecycleQueue.async { [weak self] in
- self?.handleFormatInvalidationLocked(
- generation: generation,
- reason: name
- )
- }
}
let status = AudioObjectAddPropertyListenerBlock(
objectID,
@@ -1354,6 +1537,52 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
)
}
+ private func handleFormatNotification(
+ generation: UInt64,
+ reason: String,
+ input: (any DirectCoreAudioInputControlling)?,
+ hardwareIsKnownStopped: Bool
+ ) {
+ let snapshot = self.snapshotLock.withLock { self.storedSnapshot }
+ guard generation == snapshot.generation else { return }
+ let action = self.stoppedHardwareLock.withLock {
+ if hardwareIsKnownStopped { self.stoppedHardwareGenerations.insert(generation) }
+ let report = reason != "io_stopped_abnormally" || self.lastReportedAbnormalStopGeneration != generation
+ if reason == "io_stopped_abnormally" { self.lastReportedAbnormalStopGeneration = generation }
+ let enqueue = self.pendingFormatInvalidationGenerations.insert(generation).inserted
+ return (report, enqueue)
+ }
+ input?.markFormatDirty()
+ if hardwareIsKnownStopped {
+ self.snapshotLock.withLock {
+ // Recheck under the publication lock: a late callback must not
+ // interrupt a replacement generation admitted in the meantime.
+ if self.storedSnapshot.generation == generation,
+ self.storedSnapshot.phase == .starting || self.storedSnapshot.phase == .preparing
+ {
+ self.hardwareOperations.failPendingOperationsAfterDeviceStopped()
+ }
+ }
+ }
+ if action.0 {
+ self.onFormatInvalidated(FormatInvalidation(
+ generation: generation,
+ deviceID: input?.deviceID ?? snapshot.deviceID ?? kAudioObjectUnknown,
+ reason: reason,
+ wasRunning: input?.isRunning ?? false
+ ))
+ }
+ if action.1 {
+ self.lifecycleQueue.async { [weak self] in
+ guard let self else { return }
+ self.handleFormatInvalidationLocked(generation: generation, reason: reason)
+ self.stoppedHardwareLock.withLock {
+ _ = self.pendingFormatInvalidationGenerations.remove(generation)
+ }
+ }
+ }
+ }
+
private func handleFormatInvalidationLocked(generation: UInt64, reason: String) {
guard generation == self.generation else {
_ = self.consumeStoppedHardwareNotification(generation: generation)
@@ -1363,14 +1592,20 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
let hardwareIsKnownStopped =
self.consumeStoppedHardwareNotification(generation: generation)
guard let input = self.input else {
- if hardwareIsKnownStopped, self.isPoisoned {
+ if hardwareIsKnownStopped {
+ let wasPoisoned = self.isPoisoned
self.isPoisoned = false
- self.publishSnapshot(phase: .empty, input: nil, fingerprint: nil)
- Self.log(
- "Direct capture cleared teardown poison generation=\(generation) " +
- "after delayed \(reason) notification",
- level: .warning
- )
+ self.failedHardware = nil
+ let clearedQueueFailure = self.hardwareOperations.clearFailureAfterSerializedRecovery()
+ if wasPoisoned || clearedQueueFailure {
+ let shuttingDown = self.isShutDown || self.snapshotLock.withLock { self.shutdownRequested }
+ self.publishSnapshot(phase: shuttingDown ? .shutDown : .empty, input: nil, fingerprint: nil)
+ Self.log(
+ "Direct capture cleared teardown failure generation=\(generation) " +
+ "after delayed \(reason) notification queueRecovered=\(clearedQueueFailure)",
+ level: .warning
+ )
+ }
}
return
}
@@ -1388,6 +1623,20 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
)
}
+ /// The block API supplies an address count, unlike the C proc API which
+ /// also supplies an object ID. Always use the ID from registration.
+ static func makeDevicePropertyListener(
+ objectID: AudioObjectID,
+ handler: @escaping @Sendable (AudioObjectID) -> Void
+ ) -> AudioObjectPropertyListenerBlock {
+ { _, _ in handler(objectID) }
+ }
+
+ static func hardwareIsKnownStopped(reason: String, deviceIsAlive: Bool?) -> Bool {
+ reason == "audio_service_restarted" || reason == "io_stopped_abnormally" ||
+ (reason == "device_is_alive" && deviceIsAlive == false)
+ }
+
private func recordStoppedHardwareNotification(generation: UInt64) {
self.stoppedHardwareLock.withLock {
self.stoppedHardwareGenerations.insert(generation)
@@ -1416,6 +1665,9 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
&size,
&isAlive
)
+ // An object removed from HAL is gone; other unreadable results are
+ // unknown and must not authorize replacement after failed teardown.
+ if status == kAudioHardwareBadDeviceError || status == kAudioHardwareBadObjectError { return false }
guard status == noErr, size == UInt32(MemoryLayout<UInt32>.size) else {
return nil
}
@@ -1423,6 +1675,16 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
}
#if DEBUG
+ var isTopologyRecoveryCheckPendingForTesting: Bool {
+ self.snapshotLock.withLock { self.topologyRecoveryCheckPending }
+ }
+
+ func simulateAbnormalStopNotificationForTesting(generation: UInt64) {
+ self.handleFormatNotification(
+ generation: generation, reason: "io_stopped_abnormally", input: nil, hardwareIsKnownStopped: true
+ )
+ }
+
func simulateStoppedHardwareNotificationForTesting(
generation: UInt64,
reason: String
diff --git a/Sources/Fluid/Services/MediaPlaybackService.swift b/Sources/Fluid/Services/MediaPlaybackService.swift
index 0b99208f..24556c03 100644
--- a/Sources/Fluid/Services/MediaPlaybackService.swift
+++ b/Sources/Fluid/Services/MediaPlaybackService.swift
@@ -1,244 +1,275 @@
import Foundation
-#if arch(arm64)
-import MediaRemoteAdapter
-#endif
-#if arch(arm64)
+/// One reconciler owns all media queries and commands. Recording events update
+/// intent synchronously; they never wait for media control or delay first PCM.
@MainActor
-protocol MediaPlaybackControlling {
- func getTrackInfo(_ onReceive: @escaping (TrackInfo?) -> Void)
- func pause()
- func play()
-}
+final class MediaPlaybackService {
+ static let shared = MediaPlaybackService(transport: MediaPlaybackProcessTransport())
-extension MediaController: MediaPlaybackControlling {}
-#endif
+ private struct Session {
+ let id: Int
+ var mayPause: Bool
+ }
-/// Service that wraps MediaRemoteAdapter's MediaController to provide
-/// controlled pause/resume functionality during transcription.
-///
-/// This service ensures we only pause media if it's currently playing,
-/// and only resume if we were the ones who paused it.
-@MainActor
-final class MediaPlaybackService {
- #if arch(arm64)
- typealias TimeoutScheduler = (
- _ delay: TimeInterval,
- _ action: @escaping @MainActor @Sendable () -> Void
- ) -> Void
+ private let transport: any MediaPlaybackTransport
+ private let settle: @Sendable () async -> Void
+ private let now: @Sendable () -> TimeInterval
+ private var session: Session?
+ private var revision: UInt64 = 0
+ private var attemptedSession: Int?
+ private var pausedTarget: MediaPlaybackSnapshot?
+ private var worker: Task<Void, Never>?
+ private var suspendedUntil: TimeInterval = 0
+ private var isShuttingDown = false
- /// The pinned adapter's two-second deadline can occupy roughly 2.1 seconds
- /// in run-loop slices. Leave additional time for process and callback delivery.
- static let nowPlayingQueryTimeoutSeconds: TimeInterval = 2.5
+ init(
+ transport: any MediaPlaybackTransport,
+ settle: @escaping @Sendable () async -> Void = {
+ try? await Task.sleep(nanoseconds: 150_000_000)
+ },
+ now: @escaping @Sendable () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }
+ ) {
+ self.transport = transport
+ self.settle = settle
+ self.now = now
+ }
- private static let productionTimeoutScheduler: TimeoutScheduler = { delay, action in
- DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action)
+ func recordingStarted(sessionID: Int, enabled: Bool) {
+ guard !self.isShuttingDown else { return }
+ self.session = enabled ? Session(id: sessionID, mayPause: true) : nil
+ self.revision &+= 1
+ self.log("recording_started session=\(sessionID) enabled=\(enabled)")
+ self.wake()
}
- static let shared = MediaPlaybackService(
- mediaController: MediaController(),
- queryTimeoutSeconds: MediaPlaybackService.nowPlayingQueryTimeoutSeconds,
- timeoutScheduler: MediaPlaybackService.productionTimeoutScheduler
- )
+ /// Prevent a slow query from issuing pause after the hotkey is released.
+ /// A previously confirmed pause stays owned until transcription finishes.
+ func recordingStopped(sessionID: Int) {
+ guard self.session?.id == sessionID else { return }
+ self.session?.mayPause = false
+ self.revision &+= 1
+ self.log("recording_stopped session=\(sessionID)")
+ self.wake()
+ }
- private let mediaController: any MediaPlaybackControlling
- private let queryTimeoutSeconds: TimeInterval
- private let timeoutScheduler: TimeoutScheduler
+ /// An older transcription finishing cannot resume a newer recording's media.
+ func sessionFinished(sessionID: Int) {
+ guard self.session?.id == sessionID else { return }
+ self.session = nil
+ self.revision &+= 1
+ self.log("session_finished session=\(sessionID)")
+ self.wake()
+ }
- /// Creates an isolated service with injectable dependencies for deterministic tests.
- init(
- mediaController: any MediaPlaybackControlling,
- queryTimeoutSeconds: TimeInterval,
- timeoutScheduler: @escaping TimeoutScheduler
- ) {
- self.mediaController = mediaController
- self.queryTimeoutSeconds = queryTimeoutSeconds
- self.timeoutScheduler = timeoutScheduler
- }
- #else
- static let shared = MediaPlaybackService()
-
- private init() {}
- #endif
-
- // MARK: - Public API
-
- #if arch(arm64)
- /// Pauses system media playback if something is currently playing.
- ///
- /// - Returns: `true` if a pause request was issued, `false` if nothing was playing or
- /// if we couldn't determine playback state. The media adapter does not acknowledge
- /// command completion.
- ///
- /// - Note: Uses a local one-shot gate to protect against `MediaRemoteAdapter`
- /// firing the `getTrackInfo` callback more than once, which would otherwise
- /// crash with `EXC_BREAKPOINT` (SIGTRAP) due to double-resume of a
- /// `CheckedContinuation`.
- func pauseIfPlaying() async -> Bool {
- return await withCheckedContinuation { continuation in
- let queryStartedAt = DispatchTime.now().uptimeNanoseconds
- let resumeLock = NSLock()
- var didResume = false
-
- @MainActor
- func elapsedMilliseconds() -> UInt64 {
- (DispatchTime.now().uptimeNanoseconds - queryStartedAt) / 1_000_000
- }
+ func beginShutdown() {
+ guard !self.isShuttingDown else { return }
+ self.isShuttingDown = true
+ self.session = nil
+ self.revision &+= 1
+ self.wake()
+ }
- @discardableResult
- @MainActor
- func resumeOnce(
- _ value: Bool,
- logDuplicate: Bool = true,
- beforeResume: () -> Void = {}
- ) -> Bool {
- var shouldResume = false
-
- resumeLock.lock()
- if !didResume {
- didResume = true
- shouldResume = true
- }
- resumeLock.unlock()
-
- guard shouldResume else {
- if logDuplicate {
- DebugLogger.shared.warning(
- """
- MediaPlaybackService: Suppressed late or duplicate media callback \
- (elapsedMs: \(elapsedMilliseconds()))
- """,
- source: "MediaPlaybackService"
- )
- }
- return false
- }
+ func shutdown() async {
+ self.beginShutdown()
+ await self.waitUntilSettled()
+ }
- beforeResume()
- continuation.resume(returning: value)
- return true
- }
+ /// Also used by deterministic tests; no continuous observer or polling task.
+ func waitUntilSettled() async {
+ while let worker = self.worker {
+ await worker.value
+ }
+ }
- self.timeoutScheduler(self.queryTimeoutSeconds) {
- if resumeOnce(false, logDuplicate: false) {
- DebugLogger.shared.warning(
- """
- MediaPlaybackService: Now Playing query timed out; leaving playback unchanged \
- (elapsedMs: \(elapsedMilliseconds()))
- """,
- source: "MediaPlaybackService"
- )
+ private func wake() {
+ guard self.worker == nil else { return }
+ self.worker = Task { await self.reconcile() }
+ }
+
+ private func reconcile() async {
+ while true {
+ let observedRevision = self.revision
+ if let session = self.session {
+ if session.mayPause, self.attemptedSession != session.id {
+ self.attemptedSession = session.id
+ await self.pause(sessionID: session.id)
}
+ } else if let target = self.pausedTarget {
+ await self.resume(target: target)
}
+ guard observedRevision != self.revision else {
+ self.worker = nil
+ return
+ }
+ }
+ }
- self.mediaController.getTrackInfo { [weak self] trackInfo in
- guard let self = self else {
- DebugLogger.shared.warning(
- """
- MediaPlaybackService: Service released before query completed \
- (elapsedMs: \(elapsedMilliseconds()))
- """,
- source: "MediaPlaybackService"
- )
- resumeOnce(false)
- return
- }
+ private func canPause(_ sessionID: Int) -> Bool {
+ self.session?.id == sessionID && self.session?.mayPause == true
+ }
- // If no track info is available, nothing is playing
- guard let trackInfo = trackInfo else {
- DebugLogger.shared.debug(
- """
- MediaPlaybackService: No track info available, nothing to pause \
- (elapsedMs: \(elapsedMilliseconds()))
- """,
- source: "MediaPlaybackService"
- )
- resumeOnce(false)
- return
- }
+ private func pause(sessionID: Int) async {
+ guard self.now() >= self.suspendedUntil else {
+ self.log("pause_suppressed session=\(sessionID) reason=player_backoff")
+ return
+ }
+ guard let before = await self.queryBeforePause(sessionID: sessionID) else { return }
+ guard self.canPause(sessionID) else {
+ self.log("pause_skipped session=\(sessionID) reason=stale_recording")
+ return
+ }
+ if let owned = self.pausedTarget, owned.matches(before), before.isPlaying == false {
+ self.log("pause_retained session=\(sessionID) reason=already_owned")
+ return
+ }
+ // A player change or manual playback invalidates our previous ownership.
+ self.pausedTarget = nil
+ guard before.isPlaying == true else {
+ self.log("pause_skipped session=\(sessionID) reason=not_known_playing")
+ return
+ }
+ let result = await self.transport.send(.pause)
+ self.logCommand(.pause, result: result, sessionID: sessionID)
+ // Even a timed-out helper might have sent its command before exiting.
+ // Observe state before deciding whether we own a pause to restore.
+ if let paused = await self.verify(target: before, playing: false, context: "pause session=\(sessionID)") {
+ self.pausedTarget = paused
+ self.log("pause_verified session=\(sessionID)")
+ } else {
+ self.backOff(context: "pause session=\(sessionID)")
+ }
+ }
- // Determine if media is currently playing
- // Use isPlaying if available, otherwise check playbackRate
- let isPlaying: Bool
- if let playing = trackInfo.payload.isPlaying {
- isPlaying = playing
- } else {
- // playbackRate of 1.0 typically means playing, 0.0 means paused
- isPlaying = (trackInfo.payload.playbackRate ?? 0.0) > 0.0
- }
+ private func queryBeforePause(sessionID: Int) async -> MediaPlaybackSnapshot? {
+ for attempt in 1...3 {
+ guard self.canPause(sessionID) else { return nil }
+ if let snapshot = await self.query(context: "before_pause session=\(sessionID) attempt=\(attempt)") {
+ return snapshot
+ }
+ guard self.canPause(sessionID) else { return nil }
+ if attempt < 3 { await self.settle() }
+ }
+ return nil
+ }
- // Log what we found
- DebugLogger.shared.debug(
- """
- MediaPlaybackService: Track info received
- - App: \(trackInfo.payload.applicationName ?? "Unknown")
- - Bundle: \(trackInfo.payload.bundleIdentifier ?? "Unknown")
- - Title: \(trackInfo.payload.title ?? "Unknown")
- - isPlaying: \(trackInfo.payload.isPlaying?.description ?? "nil")
- - playbackRate: \(trackInfo.payload.playbackRate?.description ?? "nil")
- - Determined playing: \(isPlaying)
- - elapsedMs: \(elapsedMilliseconds())
- """,
- source: "MediaPlaybackService"
- )
-
- if isPlaying {
- resumeOnce(true) {
- DebugLogger.shared.info(
- """
- MediaPlaybackService: Media is playing, sending pause command \
- (elapsedMs: \(elapsedMilliseconds()))
- """,
- source: "MediaPlaybackService"
- )
- self.mediaController.pause()
- }
- } else {
- DebugLogger.shared.debug(
- """
- MediaPlaybackService: Media is not playing, no action needed \
- (elapsedMs: \(elapsedMilliseconds()))
- """,
- source: "MediaPlaybackService"
- )
- resumeOnce(false)
+ private func resume(target: MediaPlaybackSnapshot) async {
+ // Retry a command only after fresh metadata confirms the same paused item.
+ // Retain ownership while a new recording may inherit the pause.
+ for attempt in 1...2 {
+ guard let before = await self.queryBeforeResume() else {
+ guard self.session == nil else { return }
+ // Missing metadata is not evidence that our confirmed pause ended.
+ // Allow one more bounded read cycle; never issue Play without a
+ // matching paused item. Keep ownership for the next session/quit
+ // event if the outage outlasts this recovery window.
+ if !self.isShuttingDown, attempt < 2 {
+ await self.settle()
+ continue
}
+ self.log("resume_deferred reason=unknown_player ownership=retained")
+ return
+ }
+ guard self.session == nil else {
+ self.log("resume_skipped reason=new_recording")
+ return
+ }
+ guard target.matches(before), before.isPlaying == false else {
+ self.pausedTarget = nil
+ self.log("resume_skipped reason=player_item_or_state_changed")
+ return
+ }
+ let result = await self.transport.send(.play)
+ self.logCommand(.play, result: result, sessionID: nil)
+ if await self.verify(target: before, playing: true, context: "resume") != nil {
+ self.pausedTarget = nil
+ self.log("resume_verified")
+ return
+ }
+ guard self.session == nil else { return }
+ // Quit is best-effort within the app's overall termination deadline.
+ // Do not add another command cycle while shutdown is in progress.
+ if self.isShuttingDown || attempt == 2 {
+ self.pausedTarget = nil
+ self.backOff(context: "resume")
+ return
}
}
}
- /// Resumes media playback only if we were the ones who paused it.
- ///
- /// - Parameter wePaused: `true` if `pauseIfPlaying()` returned `true` for this session.
- func resumeIfWePaused(_ wePaused: Bool) async {
- guard wePaused else {
- DebugLogger.shared.debug(
- "MediaPlaybackService: We didn't pause media, not resuming",
- source: "MediaPlaybackService"
- )
- return
+ private func queryBeforeResume() async -> MediaPlaybackSnapshot? {
+ // Retain confirmed ownership across brief metadata outages. Retry reads,
+ // never playback commands; give up after three bounded helper calls.
+ for attempt in 1...3 {
+ guard self.session == nil else { return nil }
+ if let snapshot = await self.query(context: "before_resume attempt=\(attempt)") {
+ return snapshot
+ }
+ guard self.session == nil else { return nil }
+ if self.isShuttingDown { return nil }
+ if attempt < 3 { await self.settle() }
}
+ return nil
+ }
- DebugLogger.shared.info(
- "MediaPlaybackService: Resuming media playback (we paused it)",
- source: "MediaPlaybackService"
- )
+ private func verify(
+ target: MediaPlaybackSnapshot, playing: Bool, context: String
+ ) async -> MediaPlaybackSnapshot? {
+ // Read at most twice; never retry a playback command blindly. This checks
+ // reported state, not rendered video: Netflix can disagree with its UI.
+ for attempt in 1...2 {
+ if attempt > 1, self.isShuttingDown { break }
+ await self.settle()
+ guard let observed = await self.query(context: "verify_\(context) attempt=\(attempt)") else {
+ continue
+ }
+ guard target.matches(observed) else {
+ self.log("verification_failed context=\(context) reason=player_or_item_changed")
+ return nil
+ }
+ if observed.isPlaying == playing { return observed }
+ }
+ self.log("verification_failed context=\(context) reason=state_not_confirmed")
+ return nil
+ }
- // Use explicit play() command - never toggle
- self.mediaController.play()
+ private func query(context: String) async -> MediaPlaybackSnapshot? {
+ let started = self.now()
+ let result = await self.transport.query()
+ let elapsed = Int((self.now() - started) * 1000)
+ switch result {
+ case let .snapshot(snapshot):
+ self.log(
+ "query context=\(context) elapsedMs=\(elapsed) " +
+ "bundle=\(snapshot.bundleIdentifier) pid=\(snapshot.processID) " +
+ "playing=\(snapshot.isPlaying.map(String.init) ?? "unknown") " +
+ "hasTitle=\(snapshot.title != nil)"
+ )
+ return snapshot
+ case let .unavailable(reason):
+ self.log("query_unavailable context=\(context) elapsedMs=\(elapsed) reason=\(reason)")
+ return nil
+ }
+ }
+
+ private func backOff(context: String) {
+ // A finite cooldown limits damage from hotkey spam against an unresponsive
+ // player. The next recording after the cooldown performs a fresh query.
+ self.suspendedUntil = self.now() + 10
+ self.log("commands_suspended context=\(context) seconds=10")
}
- #else
- // Intel Mac stub - media control not available
- func pauseIfPlaying() async -> Bool {
- DebugLogger.shared.debug(
- "MediaPlaybackService: Not available on Intel Macs",
- source: "MediaPlaybackService"
- )
- return false
+
+ private func logCommand(
+ _ command: MediaPlaybackCommand, result: MediaPlaybackCommandResult, sessionID: Int?
+ ) {
+ let status: String
+ switch result {
+ case .helperCompleted: status = "helper_completed_player_unconfirmed"
+ case let .failed(reason): status = "failed:\(reason)"
+ }
+ self.log("command=\(command.rawValue) session=\(sessionID.map(String.init) ?? "none") result=\(status)")
}
- func resumeIfWePaused(_ wePaused: Bool) async {
- // No-op on Intel
+ private func log(_ message: String) {
+ DebugLogger.shared.info("MEDIA_CONTROL \(message)", source: "MediaPlaybackService")
}
- #endif
}
diff --git a/Sources/Fluid/Services/MediaPlaybackTransport.swift b/Sources/Fluid/Services/MediaPlaybackTransport.swift
new file mode 100644
index 00000000..15363d8d
--- /dev/null
+++ b/Sources/Fluid/Services/MediaPlaybackTransport.swift
@@ -0,0 +1,250 @@
+import Foundation
+#if arch(arm64)
+import MediaRemoteAdapter
+#endif
+
+nonisolated struct MediaPlaybackSnapshot: Equatable, Sendable {
+ let bundleIdentifier: String
+ let processID: Int32
+ let title: String?
+ let isPlaying: Bool?
+
+ // Safari exposes its WebKit media process, not a tab ID. This comparison
+ // can reject a changed player/item, but cannot prove exact-tab identity.
+ func matches(_ other: Self) -> Bool {
+ self.bundleIdentifier == other.bundleIdentifier &&
+ self.processID == other.processID && self.title == other.title
+ }
+}
+
+nonisolated enum MediaPlaybackQueryResult: Sendable {
+ case snapshot(MediaPlaybackSnapshot)
+ case unavailable(String)
+}
+
+nonisolated enum MediaPlaybackCommand: String, Sendable {
+ case pause
+ case play
+}
+
+nonisolated enum MediaPlaybackCommandResult: Sendable {
+ /// The helper exited successfully. This is NOT acknowledgement from the player.
+ case helperCompleted
+ case failed(String)
+}
+
+nonisolated protocol MediaPlaybackTransport: Sendable {
+ nonisolated func query() async -> MediaPlaybackQueryResult
+ nonisolated func send(_ command: MediaPlaybackCommand) async -> MediaPlaybackCommandResult
+}
+
+/// Uses the existing bundled bridge, but owns its process completion and output.
+/// A serial queue plus a hard process deadline prevents overlapping commands,
+/// unbounded helpers, and the adapter's exit-versus-output callback race.
+final nonisolated class MediaPlaybackProcessTransport: MediaPlaybackTransport, @unchecked Sendable {
+ // The adapter owns a two-second metadata deadline and can complete slightly
+ // after it. Commands stay shorter so quit recovery remains within its budget.
+ static let queryTimeoutSeconds: TimeInterval = 2.5
+ static let commandTimeoutSeconds: TimeInterval = 1.0
+
+ private let queue = DispatchQueue(label: "media.playback.transport", qos: .utility)
+
+ func query() async -> MediaPlaybackQueryResult {
+ let result = await self.invoke("get", timeout: Self.queryTimeoutSeconds)
+ guard result.failure == nil else { return .unavailable(result.failure ?? "helper_failed") }
+ return Self.decode(result.output)
+ }
+
+ func send(_ command: MediaPlaybackCommand) async -> MediaPlaybackCommandResult {
+ let result = await self.invoke(command.rawValue, timeout: Self.commandTimeoutSeconds)
+ if let failure = result.failure { return .failed(failure) }
+ return .helperCompleted
+ }
+
+ static func decode(_ output: Data) -> MediaPlaybackQueryResult {
+ guard let text = String(data: output, encoding: .utf8) else {
+ return .unavailable("invalid_utf8")
+ }
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return .unavailable("empty_output") }
+ guard trimmed != "NIL", trimmed != "null" else { return .unavailable("no_media_reported") }
+ guard let object = try? JSONSerialization.jsonObject(with: output) as? [String: Any],
+ let payload = object["payload"] as? [String: Any]
+ else { return .unavailable("invalid_payload") }
+ let processID: Int32?
+ if let value = payload["PID"] as? String {
+ processID = Int32(value)
+ } else {
+ processID = (payload["PID"] as? NSNumber)?.int32Value
+ }
+ guard let bundle = payload["bundleIdentifier"] as? String, !bundle.isEmpty,
+ let processID, processID > 0
+ else { return .unavailable("missing_player_identity") }
+ let playing: Bool?
+ if let value = payload["isPlaying"] as? Bool {
+ playing = value
+ } else if let rate = payload["playbackRate"] as? Double {
+ playing = rate > 0
+ } else {
+ playing = nil
+ }
+ return .snapshot(MediaPlaybackSnapshot(
+ bundleIdentifier: bundle,
+ processID: processID,
+ title: payload["title"] as? String,
+ isPlaying: playing
+ ))
+ }
+
+ private func invoke(_ command: String, timeout: TimeInterval) async -> MediaHelperResult {
+ await withCheckedContinuation { continuation in
+ self.queue.async {
+ continuation.resume(returning: self.run(command, timeout: timeout))
+ }
+ }
+ }
+
+ private func run(_ command: String, timeout: TimeInterval) -> MediaHelperResult {
+ #if arch(arm64)
+ let framework = Bundle(for: MediaController.self)
+ guard let library = framework.executablePath,
+ let resourceURL = Bundle.main.url(
+ forResource: "MediaRemoteAdapter_MediaRemoteAdapter", withExtension: "bundle"
+ ),
+ let resources = Bundle(url: resourceURL),
+ let script = resources.path(forResource: "run", ofType: "pl")
+ else { return MediaHelperResult(output: Data(), failure: "bridge_resources_missing") }
+
+ // Run the shipped script unchanged. For commands, keep its run loop alive
+ // through one bounded query before exiting, as the original upstream does.
+ // The returned state is not used as command acknowledgement.
+ let wrapper = """
+ my $script = shift @ARGV;
+ my $command = $ARGV[1];
+ do $script;
+ die $@ if $@;
+ main::get() if $command eq 'pause' || $command eq 'play';
+ """
+ return MediaHelperProcess.run(
+ arguments: ["-e", wrapper, script, library, command],
+ timeout: timeout
+ )
+ #else
+ return MediaHelperResult(output: Data(), failure: "unsupported_architecture")
+ #endif
+ }
+}
+
+nonisolated struct MediaHelperResult: Sendable {
+ let output: Data
+ let failure: String?
+}
+
+/// Private process plumbing; never runs on the main actor.
+nonisolated enum MediaHelperProcess {
+ static func run(arguments: [String], timeout: TimeInterval = 1.0) -> MediaHelperResult {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/perl")
+ process.arguments = arguments
+ let output = Pipe()
+ let errors = Pipe()
+ let outputBuffer = MediaHelperBuffer(limit: 4 * 1024 * 1024)
+ let errorBuffer = MediaHelperBuffer(limit: 4096)
+ process.standardOutput = output
+ process.standardError = errors
+ output.fileHandleForReading.readabilityHandler = { handle in outputBuffer.drain(handle) }
+ errors.fileHandleForReading.readabilityHandler = { handle in errorBuffer.drain(handle) }
+ defer {
+ output.fileHandleForReading.readabilityHandler = nil
+ errors.fileHandleForReading.readabilityHandler = nil
+ try? output.fileHandleForReading.close()
+ try? errors.fileHandleForReading.close()
+ }
+ do {
+ try process.run()
+ } catch {
+ return MediaHelperResult(output: Data(), failure: "launch_failed:\(error.localizedDescription)")
+ }
+ let deadline = MediaHelperDeadline(process: process)
+ let timeoutWork = DispatchWorkItem { deadline.expire() }
+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + timeout, execute: timeoutWork)
+ process.waitUntilExit()
+ let timedOut = deadline.finish()
+ timeoutWork.cancel()
+ output.fileHandleForReading.readabilityHandler = nil
+ errors.fileHandleForReading.readabilityHandler = nil
+ let data = outputBuffer.finish(output.fileHandleForReading)
+ let stderr = errorBuffer.finish(errors.fileHandleForReading)
+ if timedOut { return MediaHelperResult(output: data, failure: "helper_timeout") }
+ if process.terminationStatus != 0 {
+ let message = (String(bytes: stderr.prefix(512), encoding: .utf8) ?? "invalid_utf8")
+ .replacingOccurrences(of: "\n", with: " ")
+ return MediaHelperResult(output: data, failure: "helper_exit_\(process.terminationStatus):\(message)")
+ }
+ if outputBuffer.overflowed { return MediaHelperResult(output: Data(), failure: "output_limit") }
+ return MediaHelperResult(output: data, failure: nil)
+ }
+}
+
+private final nonisolated class MediaHelperDeadline: @unchecked Sendable {
+ private let lock = NSLock()
+ private let process: Process
+ private var finished = false
+ private var expired = false
+
+ init(process: Process) { self.process = process }
+
+ func expire() {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ guard !self.finished, self.process.isRunning else { return }
+ self.expired = true
+ // This is our own one-shot Perl child, with no user state to flush.
+ kill(self.process.processIdentifier, SIGKILL)
+ }
+
+ func finish() -> Bool {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ self.finished = true
+ return self.expired
+ }
+}
+
+private final nonisolated class MediaHelperBuffer: @unchecked Sendable {
+ private let lock = NSLock()
+ private let limit: Int
+ private var data = Data()
+ private var didOverflow = false
+
+ init(limit: Int) { self.limit = limit }
+
+ var overflowed: Bool {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ return self.didOverflow
+ }
+
+ func drain(_ handle: FileHandle) {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ let chunk = handle.availableData
+ if chunk.isEmpty { handle.readabilityHandler = nil }
+ self.append(chunk)
+ }
+
+ func finish(_ handle: FileHandle) -> Data {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ while let chunk = try? handle.read(upToCount: 16_384), !chunk.isEmpty {
+ self.append(chunk)
+ }
+ return self.data
+ }
+
+ private func append(_ chunk: Data) {
+ let remaining = self.limit - self.data.count
+ if chunk.count > remaining { self.didOverflow = true }
+ self.data.append(chunk.prefix(remaining))
+ }
+}
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index c76c65d1..be1b75f5 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -89,6 +89,17 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
guard self.configuredASRIdentifier != identifier else { return }
self.configuredASRIdentifier = identifier
self.asrService = asrService
+ asrService.audioCaptureFailurePresented
+ .sink { [weak self, weak asrService] in
+ guard let self, let asrService,
+ self.asrService === asrService,
+ asrService.showError, asrService.isRunning == false
+ else { return }
+ // The recording error must also be visible when the user only
+ // uses the menu bar and has closed the main window.
+ self.openMainWindow()
+ }
+ .store(in: &self.cancellables)
if SettingsStore.shared.overlayPosition == .bottom {
DispatchQueue.main.async {
guard SettingsStore.shared.overlayPosition == .bottom else { return }
diff --git a/Sources/Fluid/Services/PreservedPasteboardSnapshot.swift b/Sources/Fluid/Services/PreservedPasteboardSnapshot.swift
new file mode 100644
index 00000000..7928b507
--- /dev/null
+++ b/Sources/Fluid/Services/PreservedPasteboardSnapshot.swift
@@ -0,0 +1,35 @@
+import AppKit
+
+/// Preserves every readable representation, not just the plain text used for pasting.
+struct PreservedPasteboardSnapshot {
+ let items: [[NSPasteboard.PasteboardType: Data]]
+
+ init(_ pasteboard: NSPasteboard) {
+ self.items = pasteboard.pasteboardItems?.map { item in
+ var dataByType: [NSPasteboard.PasteboardType: Data] = [:]
+ for type in item.types {
+ if let data = item.data(forType: type) {
+ dataByType[type] = data
+ }
+ }
+ return dataByType
+ } ?? []
+ }
+
+ @discardableResult
+ func restore(to pasteboard: NSPasteboard, ifUnchangedSince changeCount: Int) -> Bool {
+ // Equal text is not ownership: a user may have copied that same text with
+ // different formats since our write. Their newer clipboard always wins.
+ guard pasteboard.changeCount == changeCount else { return false }
+ pasteboard.clearContents()
+ guard !self.items.isEmpty else { return true }
+ let restoredItems = self.items.map { snapshot -> NSPasteboardItem in
+ let item = NSPasteboardItem()
+ for (type, data) in snapshot {
+ item.setData(data, forType: type)
+ }
+ return item
+ }
+ return pasteboard.writeObjects(restoredItems)
+ }
+}
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index a3849cfc..28478c7e 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -93,14 +93,6 @@ final class TypingService {
let element: AXUIElement?
}
- private struct PasteboardItemSnapshot {
- let dataByType: [NSPasteboard.PasteboardType: Data]
- }
-
- private struct PasteboardSnapshot {
- let items: [PasteboardItemSnapshot]
- }
-
private struct FocusedTextSnapshot {
let pid: pid_t
let bundleIdentifier: String?
@@ -110,15 +102,6 @@ final class TypingService {
let appScriptSelectedRange: CFRange?
}
- private enum PasteVerificationResult: String {
- case appScriptContainsText = "appscript_contains_text"
- case appScriptCaretMovedExpectedDistance = "appscript_caret_moved_expected_distance"
- case fieldContainsText = "field_contains_text"
- case caretMovedExpectedDistance = "caret_moved_expected_distance"
- case timeout
- case unavailable
- }
-
private static let focusSnapshotQueue = DispatchQueue(label: "TypingService.FocusSnapshot")
private static let pasteboardSessionSemaphore = DispatchSemaphore(value: 1)
private static let pasteboardRestoreQueue = DispatchQueue(label: "TypingService.PasteboardRestore", qos: .utility)
@@ -791,33 +774,6 @@ final class TypingService {
return ["AXTextField", "AXTextArea", "AXSearchField", "AXComboBox", "AXWebArea", "AXGroup"].contains(currentRole)
}
- private func capturePasteboardSnapshot(_ pasteboard: NSPasteboard) -> PasteboardSnapshot {
- let items: [PasteboardItemSnapshot] = pasteboard.pasteboardItems?.map { item in
- var dataByType: [NSPasteboard.PasteboardType: Data] = [:]
- for type in item.types {
- if let data = item.data(forType: type) {
- dataByType[type] = data
- }
- }
- return PasteboardItemSnapshot(dataByType: dataByType)
- } ?? []
- return PasteboardSnapshot(items: items)
- }
-
- private func restorePasteboardSnapshot(_ snapshot: PasteboardSnapshot, to pasteboard: NSPasteboard) {
- pasteboard.clearContents()
- guard !snapshot.items.isEmpty else { return }
-
- let restoredItems = snapshot.items.map { snap -> NSPasteboardItem in
- let item = NSPasteboardItem()
- for (type, data) in snap.dataByType {
- item.setData(data, forType: type)
- }
- return item
- }
- _ = pasteboard.writeObjects(restoredItems)
- }
-
/// Builds the pasteboard item for a temporary paste write, tagged with the nspasteboard.org
/// Transient and AutoGenerated marker types so clipboard managers exclude it from history.
/// `ConcealedType` is deliberately not used: it signals sensitive/password content, which
@@ -832,7 +788,6 @@ final class TypingService {
private func withTemporaryPasteboardString(
_ text: String,
- restoreDelayMicros: useconds_t,
action: () -> Bool
) -> Bool {
let pasteboardWaitStartedAt = ProcessInfo.processInfo.systemUptime
@@ -847,47 +802,38 @@ final class TypingService {
let pasteboard = NSPasteboard.general
let snapshotStartedAt = ProcessInfo.processInfo.systemUptime
- let snapshot = self.capturePasteboardSnapshot(pasteboard)
+ let snapshot = PreservedPasteboardSnapshot(pasteboard)
self.bench("pasteboard_snapshot_done elapsedMs=\(Self.elapsedMs(since: snapshotStartedAt)) items=\(snapshot.items.count)")
let writeStartedAt = ProcessInfo.processInfo.systemUptime
- pasteboard.clearContents()
+ let clearedChangeCount = pasteboard.clearContents()
guard pasteboard.writeObjects([Self.makeTransientPasteboardItem(text)]) else {
self.log("[TypingService] ERROR: Failed to set temporary clipboard string")
- self.restorePasteboardSnapshot(snapshot, to: pasteboard)
+ snapshot.restore(to: pasteboard, ifUnchangedSince: clearedChangeCount)
return false
}
let temporaryChangeCount = pasteboard.changeCount
self.bench("pasteboard_write_done elapsedMs=\(Self.elapsedMs(since: writeStartedAt))")
- let focusSnapshotStartedAt = ProcessInfo.processInfo.systemUptime
- let focusedTextSnapshot = self.captureFocusedTextSnapshot()
- self.bench("paste_focus_snapshot_done elapsedMs=\(Self.elapsedMs(since: focusSnapshotStartedAt))")
let actionStartedAt = ProcessInfo.processInfo.systemUptime
let actionResult = action()
self.bench("paste_dispatch_done elapsedMs=\(Self.elapsedMs(since: actionStartedAt)) success=\(actionResult)")
guard actionResult else {
- self.restorePasteboardSnapshot(snapshot, to: pasteboard)
- self.log("[TypingService] Restored previous clipboard snapshot after paste dispatch failure")
+ let restored = snapshot.restore(to: pasteboard, ifUnchangedSince: temporaryChangeCount)
+ self.bench("paste_dispatch_failure_restore restored=\(restored)")
return false
}
releasesPasteboardSessionOnReturn = false
Self.pasteboardRestoreQueue.async {
defer { Self.pasteboardSessionSemaphore.signal() }
- _ = self.waitForFocusedTextVerification(
- from: focusedTextSnapshot,
- expectedText: text,
- timeoutMicros: restoreDelayMicros
- )
+ // Give Cmd+V time to consume the temporary text without holding the
+ // next dictation behind the old five-second verification window.
+ Thread.sleep(forTimeInterval: 0.5)
let pasteboard = NSPasteboard.general
// Avoid clobbering user clipboard changes that happened after our insertion.
- if pasteboard.changeCount == temporaryChangeCount || pasteboard.string(forType: .string) == text {
- self.restorePasteboardSnapshot(snapshot, to: pasteboard)
- self.log("[TypingService] Restored previous clipboard snapshot")
- } else {
- self.log("[TypingService] Skipped clipboard restore because clipboard changed externally")
- }
+ let restored = snapshot.restore(to: pasteboard, ifUnchangedSince: temporaryChangeCount)
+ self.bench("paste_clipboard_restore restored=\(restored)")
}
return true
@@ -910,7 +856,7 @@ final class TypingService {
}
self.bench("paste_target_prepared elapsedMs=\(Self.elapsedMs(since: targetStartedAt))")
- return self.withTemporaryPasteboardString(text, restoreDelayMicros: 5_000_000) {
+ return self.withTemporaryPasteboardString(text) {
let dispatchStartedAt = ProcessInfo.processInfo.systemUptime
let vKey = Self.pasteVirtualKeyCode
let keyResolvedAt = ProcessInfo.processInfo.systemUptime
@@ -1035,7 +981,7 @@ final class TypingService {
/// More reliable but slightly slower - copies text to clipboard then pastes
private func insertTextViaClipboard(_ text: String) -> Bool {
self.log("[TypingService] Starting clipboard-based insertion")
- return self.withTemporaryPasteboardString(text, restoreDelayMicros: 5_000_000) {
+ return self.withTemporaryPasteboardString(text) {
let dispatchStartedAt = ProcessInfo.processInfo.systemUptime
let vKey = Self.pasteVirtualKeyCode
let keyResolvedAt = ProcessInfo.processInfo.systemUptime
@@ -1075,7 +1021,7 @@ final class TypingService {
return false
}
- return self.withTemporaryPasteboardString(text, restoreDelayMicros: 5_000_000) {
+ return self.withTemporaryPasteboardString(text) {
let escapedAppName = appName.replacingOccurrences(of: "\"", with: "\\\"")
let script = """
tell application "System Events"
@@ -1335,71 +1281,6 @@ final class TypingService {
let selectedRange: CFRange?
}
- private func waitForFocusedTextVerification(
- from snapshot: FocusedTextSnapshot?,
- expectedText: String,
- timeoutMicros: useconds_t
- ) -> PasteVerificationResult {
- guard let snapshot else {
- usleep(timeoutMicros)
- return .unavailable
- }
-
- let pollMicros: useconds_t = 50_000
- let expectedLength = max(1, (expectedText as NSString).length)
- let tolerance = max(2, expectedLength / 5)
- var waited: useconds_t = 0
-
- while waited < timeoutMicros {
- usleep(pollMicros)
- waited += pollMicros
-
- guard let current = self.captureFocusedTextSnapshot(),
- current.pid == snapshot.pid
- else {
- continue
- }
-
- if let currentValue = current.appScriptValue,
- currentValue.contains(expectedText),
- currentValue != snapshot.appScriptValue
- {
- return .appScriptContainsText
- }
-
- if let before = snapshot.appScriptSelectedRange,
- let after = current.appScriptSelectedRange,
- after.length == 0
- {
- let expectedCaretLocation = before.location + expectedLength
- let caretDelta = abs(after.location - expectedCaretLocation)
- if caretDelta <= tolerance {
- return .appScriptCaretMovedExpectedDistance
- }
- }
-
- if let currentValue = current.value,
- currentValue.contains(expectedText),
- currentValue != snapshot.value
- {
- return .fieldContainsText
- }
-
- if let before = snapshot.selectedRange,
- let after = current.selectedRange,
- after.length == 0
- {
- let expectedCaretLocation = before.location + expectedLength
- let caretDelta = abs(after.location - expectedCaretLocation)
- if caretDelta <= tolerance {
- return .caretMovedExpectedDistance
- }
- }
- }
-
- return .timeout
- }
-
private func captureAppScriptTextSnapshot(forBundleIdentifier bundleIdentifier: String?) -> AppScriptTextSnapshot? {
switch bundleIdentifier {
case "com.apple.dt.Xcode":
diff --git a/Sources/Fluid/Theme/AppTheme.swift b/Sources/Fluid/Theme/AppTheme.swift
index 3c8d48a6..efca4cfc 100644
--- a/Sources/Fluid/Theme/AppTheme.swift
+++ b/Sources/Fluid/Theme/AppTheme.swift
@@ -1,5 +1,10 @@
import SwiftUI
+/// Shared product accents. Onboarding and feature surfaces use the same source of truth.
+enum FluidBrandColors {
+ static let blue = Color(red: 0.10, green: 0.46, blue: 1.0)
+}
+
/// Central theme definition for the Fluid app. All colors, spacings and materials
/// should be defined here to keep styling consistent and easy to evolve.
struct AppTheme {
diff --git a/Sources/Fluid/Theme/Components/FluidGlassControls.swift b/Sources/Fluid/Theme/Components/FluidGlassControls.swift
new file mode 100644
index 00000000..3abe3afd
--- /dev/null
+++ b/Sources/Fluid/Theme/Components/FluidGlassControls.swift
@@ -0,0 +1,74 @@
+import SwiftUI
+
+struct ProviderDefaultButton: View {
+ let isCurrent: Bool
+ let isEnabled: Bool
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: self.action) {
+ HStack(spacing: 6) {
+ if self.isCurrent { Image(systemName: "checkmark.circle.fill") }
+ Text(self.isCurrent ? "Current default" : "Set as default")
+ }
+ }
+ .fluidGlassAction()
+ .disabled(self.isCurrent || !self.isEnabled)
+ .help(self.isCurrent ? "Used by your main dictation shortcut. App-specific cleanup styles can override it."
+ : "Use this provider for your main dictation shortcut. Choose a model and complete setup first; verification is optional.")
+ }
+}
+
+/// Opt-in native controls. Existing app-wide button styles are deliberately unchanged.
+struct FluidGlassControlGroup<Content: View>: View {
+ @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
+ @ViewBuilder let content: () -> Content
+
+ var body: some View {
+ if #available(macOS 26, *), !self.reduceTransparency {
+ GlassEffectContainer(spacing: 8) { self.content() }
+ } else {
+ self.content()
+ }
+ }
+}
+
+private struct FluidGlassActionModifier: ViewModifier {
+ @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
+ let prominent: Bool
+ let circular: Bool
+
+ @ViewBuilder func body(content: Content) -> some View {
+ if #available(macOS 26, *), !self.reduceTransparency {
+ if self.prominent {
+ content.buttonStyle(.glassProminent).tint(FluidBrandColors.blue)
+ .controlSize(.large).buttonBorderShape(.capsule)
+ } else {
+ content.buttonStyle(.glass).controlSize(.large).buttonBorderShape(self.circular ? .circle : .capsule)
+ }
+ } else {
+ content.fluidButton(self.prominent ? .accent : .secondary, size: .large)
+ }
+ }
+}
+
+extension View {
+ func fluidGlassAction(prominent: Bool = false, circular: Bool = false) -> some View {
+ self.modifier(FluidGlassActionModifier(prominent: prominent, circular: circular))
+ .fixedSize(horizontal: true, vertical: false)
+ }
+}
+
+extension AppTheme.Metrics {
+ /// Shared showcase geometry, separate from compact form rows.
+ enum Showcase {
+ static let pageMaxWidth: CGFloat = 1080
+ static let sideCardMaxWidth: CGFloat = 240
+ static let cardHeight: CGFloat = 320
+ static let cardMaxWidth: CGFloat = 320
+ static let cardRadius: CGFloat = 24
+ static let stageHeight: CGFloat = 350
+ static let metricWidth: CGFloat = 128
+ static let compactMetricWidth: CGFloat = 112
+ }
+}
diff --git a/Sources/Fluid/Theme/Components/FluidManagementSheet.swift b/Sources/Fluid/Theme/Components/FluidManagementSheet.swift
new file mode 100644
index 00000000..c4c023a7
--- /dev/null
+++ b/Sources/Fluid/Theme/Components/FluidManagementSheet.swift
@@ -0,0 +1,83 @@
+import SwiftUI
+
+/// Shared presentation only: callers retain dismissal guards and all settings ownership.
+struct FluidManagementSheet<Content: View>: View {
+ @Environment(\.theme) private var theme
+ let title: String
+ let subtitle: String
+ let symbol: String
+ var dismissDisabled = false
+ var height: CGFloat = 650
+ let close: () -> Void
+ @ViewBuilder let content: () -> Content
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: 16) {
+ Image(systemName: self.symbol)
+ .font(.system(size: 24, weight: .medium))
+ .foregroundStyle(FluidBrandColors.blue)
+ .frame(width: 52, height: 52)
+ .background(FluidBrandColors.blue.opacity(0.10), in: RoundedRectangle(cornerRadius: 16))
+ VStack(alignment: .leading, spacing: 5) {
+ Text(self.title).font(self.theme.typography.title)
+ Text(self.subtitle).font(self.theme.typography.body).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ Button("Done", action: self.close)
+ .fluidGlassAction()
+ .keyboardShortcut(.cancelAction)
+ .disabled(self.dismissDisabled)
+ }
+ .padding(28)
+ Divider()
+ ScrollView {
+ VStack(alignment: .leading, spacing: 20, content: self.content)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(28)
+ }
+ }
+ .frame(width: 720, height: self.height)
+ .background(self.theme.palette.windowBackground)
+ .tint(FluidBrandColors.blue)
+ .appTheme(self.theme)
+ }
+}
+
+/// Opaque content surfaces keep form text legible; glass is reserved for actions.
+struct FluidManagementGroup<Content: View>: View {
+ @Environment(\.theme) private var theme
+ let title: String
+ @ViewBuilder let content: () -> Content
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Text(self.title).font(self.theme.typography.bodyStrong).foregroundStyle(self.theme.palette.secondaryText)
+ VStack(alignment: .leading, spacing: 16, content: self.content)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(20)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: 16))
+ }
+ }
+}
+
+struct FluidManagementRow<Control: View>: View {
+ @Environment(\.theme) private var theme
+ let title: String
+ var detail: String = ""
+ @ViewBuilder let control: () -> Control
+
+ var body: some View {
+ HStack(spacing: 24) {
+ VStack(alignment: .leading, spacing: 5) {
+ Text(self.title).font(self.theme.typography.bodyStrong)
+ if !self.detail.isEmpty {
+ Text(self.detail).font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ Spacer(minLength: 0)
+ self.control()
+ }
+ }
+}
diff --git a/Sources/Fluid/Theme/Components/FluidModelUpdateButton.swift b/Sources/Fluid/Theme/Components/FluidModelUpdateButton.swift
new file mode 100644
index 00000000..04ee67cf
--- /dev/null
+++ b/Sources/Fluid/Theme/Components/FluidModelUpdateButton.swift
@@ -0,0 +1,29 @@
+import SwiftUI
+
+/// Reserved space prevents the neighbouring menu moving during the hover transition.
+struct FluidModelUpdateButton: View {
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var hovered = false
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: self.action) {
+ ZStack {
+ Image(systemName: "arrow.down")
+ .font(.system(size: 12, weight: .semibold))
+ .opacity(self.hovered ? 0 : 1)
+ Text("Update").font(.system(size: 12, weight: .semibold))
+ .opacity(self.hovered ? 1 : 0)
+ }
+ .foregroundStyle(.black)
+ .frame(width: self.hovered ? 76 : 34, height: 34)
+ .background(Color(red: 0.84, green: 0.50, blue: 0.24), in: Capsule())
+ .contentShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .onHover { self.hovered = $0 }
+ .animation(self.reduceMotion ? nil : .timingCurve(0.77, 0, 0.175, 1, duration: 0.16), value: self.hovered)
+ .frame(width: 76, alignment: .trailing)
+ .accessibilityLabel("Update model")
+ }
+}
diff --git a/Sources/Fluid/Theme/Components/OnboardingComponents.swift b/Sources/Fluid/Theme/Components/OnboardingComponents.swift
index 52c71d66..9a1d879c 100644
--- a/Sources/Fluid/Theme/Components/OnboardingComponents.swift
+++ b/Sources/Fluid/Theme/Components/OnboardingComponents.swift
@@ -430,7 +430,7 @@ private struct FluidOnboardingPortalGlow: View {
}
enum FluidOnboardingLandingColors {
- static let blue = Color(red: 0.10, green: 0.46, blue: 1.0)
+ static let blue = FluidBrandColors.blue
}
private struct OnboardingSelectableSurfaceModifier: ViewModifier {
diff --git a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsView.swift b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsView.swift
index 28b06f43..f100aae7 100644
--- a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsView.swift
+++ b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsView.swift
@@ -27,52 +27,9 @@ extension SidebarItem {
}
}
-enum PrivateAIModelLoadState: Equatable {
- case idle
- case downloading(modelID: String, progress: PrivateAIModelDownloadProgress?)
- case loading(modelID: String)
- case loaded(modelID: String, latencyMilliseconds: Int?)
- case failed(modelID: String, message: String)
-
- func isLoading(_ modelID: String) -> Bool {
- if case .loading(modelID) = self { return true }
- return false
- }
-
- func isDownloading(_ modelID: String) -> Bool {
- if case .downloading(modelID, _) = self { return true }
- return false
- }
-
- func isLoaded(_ modelID: String) -> Bool {
- if case .loaded(modelID, _) = self { return true }
- return false
- }
-
- func latencyMilliseconds(for modelID: String) -> Int? {
- if case let .loaded(loadedModelID, latencyMilliseconds) = self, loadedModelID == modelID {
- return latencyMilliseconds
- }
- return nil
- }
-
- func failureMessage(for modelID: String) -> String? {
- if case let .failed(failedModelID, message) = self, failedModelID == modelID {
- return message
- }
- return nil
- }
-
- func downloadProgress(for modelID: String) -> PrivateAIModelDownloadProgress? {
- if case let .downloading(downloadingModelID, progress) = self, downloadingModelID == modelID {
- return progress
- }
- return nil
- }
-}
-
struct AIEnhancementSettingsView: View {
@ObservedObject var viewModel: AIEnhancementSettingsViewModel
+ @ObservedObject var privateAIController: PrivateAISettingsController
@ObservedObject var settings: SettingsStore
@ObservedObject var promptTest: DictationPromptTestCoordinator
let theme: AppTheme
@@ -80,10 +37,10 @@ struct AIEnhancementSettingsView: View {
@Binding var activeShortcutRecordingTarget: ShortcutRecordingTarget?
@Binding var shortcutRecordingMessage: String?
@State var expandedProviderID: String? = nil
+ @State var showingAddProviderSheet = false
+ @State var managedExternalProviderID: String?
+ @State var showingRemoveProviderConfirmation = false
@State var providerSearchText: String = ""
- @State var privateAISelectedModelID: String = PrivateAIIntegrationService.configuredModelID
- @State var privateAILoadState: PrivateAIModelLoadState = .idle
- @State var privateAIModelUpdateStatusByID: [String: PrivateAIModelUpdateStatus] = [:]
@State var hoveredPromptCardKey: String? = nil
@State var selectedPromptMode: SettingsStore.PromptMode = .dictate
@State var hoveredPromptModeKey: String? = nil
@@ -99,9 +56,9 @@ struct AIEnhancementSettingsView: View {
self.aiConfigurationCard
.onAppear {
self.viewModel.onAppear()
- self.privateAISelectedModelID = PrivateAIIntegrationService.configuredModelID
- self.refreshPrivateAILoadState()
- self.refreshPrivateAIModelUpdateStatus(self.selectedPrivateAIModel)
+ self.privateAIController.synchronizeSelection()
+ self.privateAIController.refreshPrivateAILoadState()
+ self.privateAIController.refreshPrivateAIModelUpdateStatus(self.privateAIController.selectedPrivateAIModel)
}
.onChange(of: self.viewModel.connectionStatus) { oldValue, newValue in
if oldValue == .success && newValue != .success {
diff --git a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel+ProviderSetup.swift b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel+ProviderSetup.swift
new file mode 100644
index 00000000..e2bb48f0
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel+ProviderSetup.swift
@@ -0,0 +1,71 @@
+import Foundation
+
+extension AIEnhancementSettingsViewModel {
+ static let addedProviderIDsKey = "AISettingsAddedProviderIDs"
+
+ /// Preserve prompt text and hotkeys; only disconnect routes using the removed provider.
+ func clearProviderAssignments(for providerID: String) {
+ var configurations = self.settings.dictationPromptConfigurations
+ for (id, var configuration) in configurations where configuration.providerID == providerID {
+ configuration.providerID = ""
+ configuration.modelName = ""
+ configurations[id] = configuration
+ }
+ if configurations != self.settings.dictationPromptConfigurations {
+ self.settings.dictationPromptConfigurations = configurations
+ }
+ if self.settings.rewriteModeSelectedProviderID == providerID {
+ self.settings.rewriteModeSelectedProviderID = ""
+ self.settings.rewriteModeSelectedModel = nil
+ }
+ if self.settings.commandModeSelectedProviderID == providerID {
+ self.settings.commandModeSelectedProviderID = ""
+ self.settings.commandModeSelectedModel = nil
+ }
+ }
+
+ /// Keep legacy connections discoverable even when their verification or credentials expire.
+ func addedProviderItems(from items: [ProviderItemData]) -> [ProviderItemData] {
+ let explicit = Set(UserDefaults.standard.stringArray(forKey: Self.addedProviderIDsKey) ?? [])
+ let referenced = Set(self.settings.dictationPromptConfigurations.values.map(\.providerID))
+ return items.filter { item in
+ guard item.id != PrivateAIProviderFeature.shared.providerID else { return false }
+ let key = self.providerKey(for: item.id)
+ return !item.isBuiltIn || explicit.contains(item.id) || referenced.contains(item.id)
+ || self.settings.selectedProviderID == item.id
+ || !self.providerAPIKey(for: item.id).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ || self.settings.verifiedProviderFingerprints[key] != nil
+ }.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
+ }
+
+ /// Saves credentials first. Failure keeps the form open and creates no provider/model record.
+ /// Does not select a provider, change shortcuts, fetch models, or start a network request.
+ func addProvider(_ draft: ProviderSetupDraft) -> Bool {
+ guard draft.isValid, !self.isTestingConnection, !self.isFetchingModels else { return false }
+ let builtIn = !draft.providerID.isEmpty && ModelRepository.shared.isBuiltIn(draft.providerID)
+ guard draft.providerID.isEmpty || builtIn else { return false }
+ guard !builtIn || !self.cachedAddedProviderItems.contains(where: { $0.id == draft.providerID }) else { return false }
+ let models = draft.trimmedModel.isEmpty ? (builtIn ? ModelRepository.shared.defaultModels(for: draft.providerID) : []) : [draft.trimmedModel]
+ let provider = SettingsStore.SavedProvider(name: draft.trimmedName, baseURL: draft.trimmedBaseURL, models: models)
+ let id = builtIn ? draft.providerID : provider.id
+ let key = self.providerKey(for: id)
+ let previousKeys = self.providerAPIKeys
+ let apiKey = draft.apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !apiKey.isEmpty {
+ self.updateProviderAPIKey(apiKey, for: id)
+ guard self.saveProviderAPIKeys(invalidating: id) else {
+ self.providerAPIKeys = previousKeys
+ self.refreshProviderItems()
+ return false
+ }
+ }
+ if !builtIn { self.savedProviders.append(provider) }
+ self.availableModelsByProvider[key] = models
+ self.selectedModelByProvider[key] = models.first ?? ""
+ var added = Set(UserDefaults.standard.stringArray(forKey: Self.addedProviderIDsKey) ?? [])
+ added.insert(id)
+ UserDefaults.standard.set(added.sorted(), forKey: Self.addedProviderIDsKey)
+ self.saveSavedProviders()
+ return true
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift
index ebd67642..3d892393 100644
--- a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift
+++ b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift
@@ -7,6 +7,7 @@ import UniformTypeIdentifiers
@MainActor
final class AIEnhancementSettingsViewModel: ObservableObject {
+ private let modelVerifications = ProviderModelVerificationStore()
let settings: SettingsStore
let menuBarManager: MenuBarManager
let promptTest: DictationPromptTestCoordinator
@@ -46,6 +47,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
@Published var currentProvider: String = ""
@Published var savedProviders: [SettingsStore.SavedProvider] = []
private var persistsSelectedProvider = true
+ private var managedOriginalKey: String?
@Published var selectedProviderID: String {
didSet {
guard self.persistsSelectedProvider else { return }
@@ -104,6 +106,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
}
@Published var cachedProviderItems: [ProviderItemData] = []
+ @Published var cachedAddedProviderItems: [ProviderItemData] = []
@Published var cachedVerifiedProviderItems: [ProviderItemData] = []
@Published var cachedUnverifiedProviderItems: [ProviderItemData] = []
@@ -333,6 +336,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
}
self.cachedProviderItems = items
+ self.cachedAddedProviderItems = self.addedProviderItems(from: items)
self.cachedVerifiedProviderItems = items.filter { self.connectionStatus(for: $0.id) == .success }
self.cachedUnverifiedProviderItems = items.filter { self.connectionStatus(for: $0.id) != .success }
}
@@ -368,6 +372,15 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
let key = self.providerKey(for: providerID)
guard !self.isTestingConnection else { return false }
let currentModel = PrivateAIModelRegistry.model(id: model.id) ?? model
+ let configuredModelID = PrivateAIIntegrationService.configuredModelID
+ let fingerprint = self.privateAIFingerprint(for: currentModel.id)
+
+ // Navigation may expose another settings owner while verification is awaiting the runtime.
+ // Do not publish an old verification into a newly selected model/backend configuration.
+ func configurationIsCurrent() -> Bool {
+ PrivateAIIntegrationService.configuredModelID == configuredModelID
+ && self.privateAIFingerprint(for: currentModel.id) == fingerprint
+ }
self.isTestingConnection = true
self.updateConnectionStatus(.testing, for: providerID)
@@ -384,9 +397,12 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
do {
let status = try await PrivateAIIntegrationService.shared.verifyModel(currentModel)
+ guard configurationIsCurrent() else {
+ self.updateConnectionStatus(.unknown, for: providerID)
+ return false
+ }
switch status.state {
case .ready:
- let fingerprint = self.privateAIFingerprint(for: currentModel.id)
var fingerprints = self.settings.verifiedProviderFingerprints
fingerprints[key] = fingerprint
self.settings.verifiedProviderFingerprints = fingerprints
@@ -407,6 +423,10 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
return false
}
} catch {
+ guard configurationIsCurrent() else {
+ self.updateConnectionStatus(.unknown, for: providerID)
+ return false
+ }
self.updateConnectionStatus(.failed, for: providerID)
self.setConnectionError(self.privateAIErrorMessage(for: error), for: providerID)
DebugLogger.shared.error(
@@ -449,6 +469,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
}
func configureProvider(_ providerID: String) {
+ self.managedOriginalKey = self.providerAPIKey(for: providerID)
self.persistsSelectedProvider = false
self.selectProviderForUse(providerID)
self.persistsSelectedProvider = true
@@ -459,6 +480,30 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
self.persistsSelectedProvider = false
self.selectProviderForUse(self.settings.selectedProviderID)
self.persistsSelectedProvider = true
+ self.managedOriginalKey = nil
+ }
+
+ /// Commit a managed provider's key before dismissing, but never save a removed provider
+ /// or the default selected by the removal cleanup in its place.
+ func saveManagedProviderBeforeClosing(_ providerID: String) -> Bool {
+ guard !self.isFetchingModels, !self.isTestingConnection else { return false }
+ return self.saveManagedProviderAPIKeyIfNeeded(providerID)
+ }
+
+ /// Persist only an API-key edit made in the active provider manager. Selecting an
+ /// already-configured or keyless provider must not depend on Keychain write access.
+ func saveManagedProviderAPIKeyIfNeeded(_ providerID: String) -> Bool {
+ guard self.selectedProviderID == providerID,
+ let original = self.managedOriginalKey
+ else { return true }
+ let current = self.providerAPIKey(for: providerID)
+ guard original.trimmingCharacters(in: .whitespacesAndNewlines)
+ != current.trimmingCharacters(in: .whitespacesAndNewlines)
+ else { return true }
+ guard self.hasProviderAPIKeyDraft(for: providerID) else { return true }
+ guard self.saveProviderAPIKeys(invalidating: providerID) else { return false }
+ self.managedOriginalKey = current
+ return true
}
private func selectProviderForUse(_ providerID: String) {
@@ -478,6 +523,9 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
throw ProviderAPIKeySaveError.readbackMismatch
}
self.providerAPIKeys = persisted
+ if invalidationTarget == self.selectedProviderID, self.managedOriginalKey != nil {
+ self.managedOriginalKey = self.providerAPIKey(for: invalidationTarget)
+ }
self.invalidateVerificationIfNeeded(for: invalidationTarget)
return true
} catch {
@@ -795,10 +843,13 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
}
let usesResponsesAPI = self.shouldVerifyWithResponsesAPI(baseURL: baseURL, model: trimmedModel)
- await MainActor.run {
- self.isTestingConnection = true
- self.updateConnectionStatus(.testing, for: providerID)
- }
+ let verificationIdentity = ProviderModelVerificationStore.identity(
+ providerID: providerID, baseURL: baseURL, apiKey: apiKey, model: trimmedModel
+ )
+ self.isTestingConnection = true
+ self.updateConnectionStatus(.testing, for: providerID)
+ // Every validation/network exit must stop the spinner.
+ defer { self.isTestingConnection = false }
// Build the endpoint URL
let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -921,12 +972,19 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
// Make the request
do {
let (data, response) = try await URLSession.shared.data(for: request)
+ // A late result must never label a different model or changed credentials.
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
+ let payload = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
+ let apiError = payload?["error"]
+ let hasAPIError = apiError != nil && !(apiError is NSNull)
- if statusCode >= 200, statusCode < 300 {
+ if statusCode >= 200, statusCode < 300, !hasAPIError {
await MainActor.run {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
+ self.modelVerifications.recordSuccess(verificationIdentity)
self.updateConnectionStatus(.success, for: providerID)
self.setEditingAPIKey(false, for: providerID)
self.storeVerificationFingerprint(for: providerID, baseURL: baseURL, apiKey: apiKey)
@@ -942,31 +1000,53 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
source: "AISettingsView"
)
await MainActor.run {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
+ self.modelVerifications.remove(verificationIdentity)
self.updateConnectionStatus(.failed, for: providerID)
self.setConnectionError(errorMessage, for: providerID)
}
}
} else {
await MainActor.run {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
+ self.modelVerifications.remove(verificationIdentity)
self.updateConnectionStatus(.failed, for: providerID)
self.setConnectionError("Unexpected response type from server", for: providerID)
}
}
} catch {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
+ self.modelVerifications.remove(verificationIdentity)
let errorMessage = self.interpretNetworkError(error, providerID: providerID)
DebugLogger.shared.error(
"testAPIConnection network error for \(providerID): \(error.localizedDescription)",
source: "AISettingsView"
)
await MainActor.run {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
self.updateConnectionStatus(.failed, for: providerID)
self.setConnectionError(errorMessage, for: providerID)
}
}
+ }
- await MainActor.run {
- self.isTestingConnection = false
- }
+ private func modelVerificationIdentity(for providerID: String) -> String {
+ ProviderModelVerificationStore.identity(
+ providerID: providerID,
+ baseURL: self.providerBaseURL(for: providerID),
+ apiKey: self.providerAPIKey(for: providerID),
+ model: self.selectedModel(for: providerID)
+ )
+ }
+
+ func isModelVerified(for providerID: String) -> Bool {
+ self.modelVerifications.contains(self.modelVerificationIdentity(for: providerID))
+ }
+
+ func canUseProviderWithoutVerification(_ providerID: String) -> Bool {
+ let baseURL = self.providerBaseURL(for: providerID).trimmingCharacters(in: .whitespacesAndNewlines)
+ return !baseURL.isEmpty && !self.selectedModel(for: providerID).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ && (self.isLocalEndpoint(baseURL) || !self.providerAPIKey(for: providerID).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
/// Returns the provider's HTTP error body unchanged so setup errors match the real API response.
@@ -1097,25 +1177,47 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
return true
}
- func deleteCurrentProvider() {
+ @discardableResult
+ func deleteCurrentProvider() -> Bool {
+ guard !self.isFetchingModels, !self.isTestingConnection,
+ !self.selectedProviderID.isEmpty,
+ self.selectedProviderID != PrivateAIProviderFeature.shared.providerID
+ else { return false }
let deletedProviderID = self.selectedProviderID
let deletedDefaultProvider = self.settings.selectedProviderID == deletedProviderID
+ let key = self.providerKey(for: deletedProviderID)
+ let previousKeys = self.providerAPIKeys
+ let persistedKey = self.managedOriginalKey ?? self.providerAPIKey(for: deletedProviderID)
+ let hadPersistedKey = !persistedKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ self.providerAPIKeys.removeValue(forKey: key)
+ if key != deletedProviderID {
+ self.providerAPIKeys.removeValue(forKey: deletedProviderID)
+ }
+ if hadPersistedKey, !self.saveProviderAPIKeys(invalidating: deletedProviderID) {
+ self.providerAPIKeys = previousKeys
+ return false
+ }
+ self.clearProviderAssignments(for: deletedProviderID)
+ let remainingAddedIDs = (UserDefaults.standard.stringArray(forKey: Self.addedProviderIDsKey) ?? []).filter { $0 != deletedProviderID }
+ UserDefaults.standard.set(remainingAddedIDs, forKey: Self.addedProviderIDsKey)
self.savedProviders.removeAll { $0.id == deletedProviderID }
self.saveSavedProviders()
- let key = self.providerKey(for: deletedProviderID)
self.availableModelsByProvider.removeValue(forKey: key)
self.selectedModelByProvider.removeValue(forKey: key)
- self.providerAPIKeys.removeValue(forKey: key)
- self.saveProviderAPIKeys()
self.settings.verifiedProviderFingerprints.removeValue(forKey: key)
self.settings.availableModelsByProvider = self.availableModelsByProvider
self.settings.selectedModelByProvider = self.selectedModelByProvider
if deletedDefaultProvider {
self.settings.selectedProviderID = ""
+ self.settings.selectedModel = nil
}
+ self.fetchedModelsProviders.remove(key)
+ self.clearEditProviderDraft()
self.finishConfiguringProvider()
self.refreshVerifiedProviders()
+ self.refreshProviderItems()
self.selectSoleVerifiedProviderIfNeeded()
+ return true
}
func saveEditedProvider() {
@@ -1171,6 +1273,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
}
func fetchModelsForCurrentProvider() async {
+ guard !self.isFetchingModels, !self.isTestingConnection else { return }
self.refreshingProviderID = self.selectedProviderID
self.isFetchingModels = true
self.fetchModelsError = nil
@@ -1262,6 +1365,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
guard !trimmedModel.isEmpty else { return }
let key = self.providerKey(for: providerID)
+ let changed = self.selectedModelByProvider[key] != trimmedModel
self.selectedModelByProvider[key] = trimmedModel
self.settings.selectedModelByProvider = self.selectedModelByProvider
@@ -1270,6 +1374,9 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
self.selectedModel = trimmedModel
self.syncPromptSelectionForSelectedProvider()
}
+ if changed {
+ self.updateConnectionStatus(self.isModelVerified(for: providerID) ? .success : .unknown, for: providerID)
+ }
}
func fetchModels(for providerID: String) async {
@@ -1957,7 +2064,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
let modelName = (self.selectedModelByProvider[providerKey] ?? self.selectedModel)
.trimmingCharacters(in: .whitespacesAndNewlines)
guard !modelName.isEmpty else { return providerName }
- return "\(providerName) - \(modelName)"
+ return "\(providerName) - \(ModelDisplayName.forID(modelName))"
}
func selectPrivateAIPromptIfAvailable() {
diff --git a/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift b/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift
new file mode 100644
index 00000000..9f0bcea1
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift
@@ -0,0 +1,411 @@
+import SwiftUI
+
+private enum AIProvidersPreviewPanel { case manage, add, compare, external }
+
+/// Milestone 3: isolated sample data. This view intentionally has no settings/service/controller reference.
+struct AIProvidersDesignPreview: View {
+ @Environment(\.dismiss) private var dismiss
+ @State private var isLight = false
+ @State private var isCompact = false
+ @State private var showsExamples = true
+ @State private var activePanel: AIProvidersPreviewPanel?
+
+ private var theme: AppTheme { AppTheme.adaptive(accent: .blue, colorScheme: self.isLight ? .light : .dark) }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: 12) {
+ Text("Design preview · sample data")
+ .font(self.theme.typography.captionStrong)
+ Spacer()
+ Toggle("Light", isOn: self.$isLight)
+ Toggle("Compact", isOn: self.$isCompact)
+ Toggle("Example providers", isOn: self.$showsExamples)
+ Button("Done") { self.dismiss() }
+ .keyboardShortcut(self.activePanel == nil ? .cancelAction : nil)
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ }
+ .toggleStyle(.checkbox)
+ .font(self.theme.typography.caption)
+ .padding(self.theme.metrics.spacing.lg)
+ Divider()
+ AIProvidersPresentation(panel: self.$activePanel, showsExamples: self.showsExamples)
+ .frame(width: self.isCompact ? 580 : 820)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ .frame(width: 860, height: 650)
+ .background(self.theme.palette.windowBackground)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .appTheme(self.theme)
+ .environment(\.colorScheme, self.isLight ? .light : .dark)
+ }
+}
+
+private struct AIProvidersPresentation: View {
+ @Environment(\.theme) private var theme
+ @Environment(\.colorScheme) private var colorScheme
+ @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var preview = Model.mini
+ @State private var selected = Model.mini
+ @Binding var panel: AIProvidersPreviewPanel?
+ @FocusState private var panelCloseFocused: Bool
+ let showsExamples: Bool
+
+ private enum Model: String, CaseIterable, Identifiable {
+ case pico = "Pico", mini = "Fluid-1 Mini", full = "Fluid-1"
+ var id: String { self.rawValue }
+ var detail: String {
+ switch self {
+ case .pico: "Fast and lightweight.\nGreat for everyday use."
+ case .mini: "Better understanding.\nHandles more context."
+ case .full: "Most capable.\nFor complex tasks."
+ }
+ }
+
+ var tags: [String] {
+ switch self {
+ case .pico: ["Fast", "Lightweight"]
+ case .mini: ["Balanced", "Smart cleanup"]
+ case .full: ["Quality", "Long context"]
+ }
+ }
+ }
+
+ private var spacing: AppTheme.Metrics.Spacing { self.theme.metrics.spacing }
+ private var isDark: Bool { self.colorScheme == .dark }
+ private var supportingText: Color { self.isDark ? self.theme.palette.secondaryText : self.theme.palette.primaryText.opacity(0.75) }
+
+ var body: some View {
+ ZStack(alignment: .trailing) {
+ ScrollView {
+ VStack(alignment: .leading, spacing: self.spacing.xl) {
+ self.intelligence
+ self.externalProviders
+ }
+ .padding(self.spacing.xl)
+ }
+ .disabled(self.panel != nil)
+ .accessibilityHidden(self.panel != nil)
+
+ if let panel = self.panel {
+ Button { self.panel = nil } label: {
+ Color.black.opacity(0.25)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Close panel")
+ self.inspector(panel)
+ }
+ }
+ }
+
+ private var intelligence: some View {
+ VStack(alignment: .leading, spacing: self.spacing.lg) {
+ HStack(spacing: self.spacing.lg) {
+ Image("Provider_Fluid1")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 42, height: 48)
+ .clipShape(RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: self.spacing.xs) {
+ Text("Fluid Intelligence")
+ .font(self.theme.typography.title)
+ Text("Private, on-device intelligence.")
+ .font(self.theme.typography.body)
+ .foregroundStyle(self.supportingText)
+ }
+ Spacer(minLength: 0)
+ Image(systemName: "lock.shield")
+ .font(self.theme.typography.titleIcon)
+ .foregroundStyle(Color.blue)
+ .help("Your words stay on your Mac")
+ }
+
+ Divider().overlay(Color.blue.opacity(0.12))
+
+ HStack {
+ Text("Choose your model")
+ .font(self.theme.typography.sectionTitle)
+ Spacer()
+ Text("On your Mac")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.supportingText)
+ }
+
+ self.carousel
+
+ HStack(spacing: self.spacing.md) {
+ Button("Compare models", systemImage: "square.split.2x1") { self.panel = .compare }
+ .fluidButton(.inline, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ Spacer(minLength: 0)
+ if self.selected != self.preview {
+ Button("Use \(self.preview.rawValue)") { self.selected = self.preview }
+ .fluidButton(.accent, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ .help("Changes sample selection only")
+ }
+ Button("Manage", systemImage: "slider.horizontal.3") { self.panel = .manage }
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ }
+ }
+ .padding(self.spacing.xl)
+ .background {
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg)
+ .fill(self.theme.palette.cardBackground)
+ .overlay {
+ if !self.reduceTransparency {
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg)
+ .fill(LinearGradient(
+ colors: [Color.blue.opacity(self.isDark ? 0.20 : 0.09), Color.blue.opacity(0.015)],
+ startPoint: .topTrailing,
+ endPoint: .bottomLeading
+ ))
+ }
+ }
+ .overlay {
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg)
+ .strokeBorder(Color.blue.opacity(self.isDark ? 0.36 : 0.25), lineWidth: 1)
+ }
+ }
+ }
+
+ private var carousel: some View {
+ VStack(spacing: self.spacing.sm) {
+ GeometryReader { geometry in
+ let cardWidth = min(300, geometry.size.width * 0.44)
+ let sideWidth = (geometry.size.width - cardWidth - self.spacing.md * 2 - 80) / 2
+ let stride = cardWidth / 2 + sideWidth / 2 + self.spacing.md
+ ZStack {
+ ForEach(Model.allCases) { model in
+ let position = self.carouselPosition(model)
+ self.modelCard(model, compactSide: position != 0 && geometry.size.width < 640)
+ .frame(width: position == 0 ? cardWidth : sideWidth, height: 190)
+ .scaleEffect(position == 0 ? 1 : 0.86)
+ .opacity(position == 0 ? 1 : 0.85)
+ .offset(x: CGFloat(position) * stride)
+ .zIndex(position == 0 ? 1 : 0)
+ }
+ }
+ .frame(width: geometry.size.width, height: geometry.size.height)
+ .clipped()
+ .overlay(alignment: .leading) { self.carouselArrow(forward: false) }
+ .overlay(alignment: .trailing) { self.carouselArrow(forward: true) }
+ .simultaneousGesture(DragGesture(minimumDistance: 24).onEnded { value in
+ guard abs(value.translation.width) > abs(value.translation.height) else { return }
+ self.advanceCarousel(forward: value.translation.width < 0)
+ })
+ }
+ .frame(height: 214)
+
+ HStack(spacing: self.spacing.xs) {
+ ForEach(Model.allCases) { model in
+ Button { self.browse(model) } label: {
+ Circle()
+ .fill(self.preview == model ? Color.cyan : Color.blue.opacity(0.4))
+ .frame(width: self.preview == model ? 10 : 7, height: self.preview == model ? 10 : 7)
+ .frame(width: 24, height: 24)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Show \(model.rawValue)")
+ .accessibilityValue(self.preview == model ? "Current page" : "")
+ }
+ }
+ }
+ }
+
+ private func carouselPosition(_ model: Model) -> Int {
+ let models = Model.allCases
+ let index = models.firstIndex(of: model) ?? 0
+ let current = models.firstIndex(of: self.preview) ?? 0
+ let distance = (index - current + models.count) % models.count
+ return distance > models.count / 2 ? distance - models.count : distance
+ }
+
+ private func browse(_ model: Model) {
+ withAnimation(self.reduceMotion ? nil : .easeInOut(duration: 0.22)) {
+ self.preview = model
+ }
+ }
+
+ private func advanceCarousel(forward: Bool) {
+ let models = Model.allCases
+ let index = models.firstIndex(of: self.preview) ?? 0
+ self.browse(models[(index + (forward ? 1 : models.count - 1)) % models.count])
+ }
+
+ private func carouselArrow(forward: Bool) -> some View {
+ Button { self.advanceCarousel(forward: forward) } label: {
+ Image(systemName: forward ? "chevron.right" : "chevron.left")
+ .font(self.theme.typography.sectionTitle)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .frame(width: 34, height: 34)
+ .background(self.theme.palette.contentBackground, in: Circle())
+ .overlay { Circle().strokeBorder(Color.blue.opacity(0.65), lineWidth: 1) }
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(forward ? "Next model" : "Previous model")
+ }
+
+ private func modelCard(_ model: Model, compactSide: Bool) -> some View {
+ let isPreview = self.preview == model
+ return Button { self.browse(model) } label: {
+ VStack(alignment: .leading, spacing: self.spacing.md) {
+ HStack {
+ Spacer()
+ if self.selected == model {
+ Text("Selected")
+ .font(self.theme.typography.badge)
+ .foregroundStyle(self.supportingText)
+ }
+ }
+ Text(model.rawValue)
+ .font(compactSide ? self.theme.typography.sectionTitle : self.theme.typography.title)
+ if !compactSide {
+ Text(model.detail)
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.supportingText)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(minHeight: 36, alignment: .topLeading)
+ HStack(spacing: self.spacing.sm) {
+ ForEach(isPreview ? model.tags : Array(model.tags.prefix(1)), id: \.self) { tag in
+ Text(tag)
+ .font(self.theme.typography.badge)
+ .padding(.horizontal, self.spacing.sm)
+ .padding(.vertical, self.spacing.xs)
+ .background(Color.blue.opacity(0.12), in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ }
+ }
+ }
+ }
+ .padding(self.spacing.lg)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ .background {
+ self.theme.palette.contentBackground
+ if isPreview && !self.reduceTransparency {
+ Color.blue.opacity(self.isDark ? 0.16 : 0.06)
+ }
+ }
+ .clipShape(RoundedRectangle(cornerRadius: self.theme.metrics.corners.md))
+ .overlay {
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md)
+ .strokeBorder(isPreview ? Color.cyan : Color.blue.opacity(0.3), lineWidth: isPreview ? 2 : 1)
+ }
+ .shadow(color: isPreview && !self.reduceTransparency ? Color.blue.opacity(0.24) : .clear, radius: 8)
+ .contentShape(RoundedRectangle(cornerRadius: self.theme.metrics.corners.md))
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Preview \(model.rawValue)")
+ .accessibilityValue(isPreview ? "Previewed" : "")
+ .accessibilityHint("Browse without changing the selected model")
+ }
+
+ private var externalProviders: some View {
+ VStack(alignment: .leading, spacing: self.spacing.md) {
+ HStack {
+ Text("Other providers")
+ .font(self.theme.typography.sectionTitle)
+ Spacer()
+ Button("Add Provider", systemImage: "plus") { self.panel = .add }
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ }
+ VStack(spacing: 0) {
+ if self.showsExamples {
+ self.providerRow("OpenAI", subtitle: "Cloud provider", image: "Provider_OpenAI")
+ Divider().padding(.leading, 60)
+ self.providerRow("Ollama", subtitle: "Local provider", image: "Provider_Ollama")
+ } else {
+ HStack(spacing: self.spacing.md) {
+ Image(systemName: "square.stack.3d.up")
+ .foregroundStyle(self.supportingText)
+ Text("No other providers added")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.supportingText)
+ Spacer()
+ }
+ .padding(self.spacing.xl)
+ }
+ }
+ .background(self.theme.palette.cardBackground)
+ .clipShape(RoundedRectangle(cornerRadius: self.theme.metrics.corners.md))
+ }
+ }
+
+ private func providerRow(_ name: String, subtitle: String, image: String) -> some View {
+ HStack(spacing: self.spacing.md) {
+ Image(image).resizable().scaledToFit().frame(width: 26, height: 26)
+ .padding(5)
+ .background(Color.white, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: self.spacing.xs) {
+ Text(name).font(self.theme.typography.bodySmallStrong)
+ Text(subtitle).font(self.theme.typography.caption).foregroundStyle(self.supportingText)
+ }
+ Spacer()
+ Button("Manage") { self.panel = .external }
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ .accessibilityLabel("Manage \(name)")
+ }
+ .padding(self.spacing.lg)
+ }
+
+ private func inspector(_ panel: AIProvidersPreviewPanel) -> some View {
+ VStack(alignment: .leading, spacing: self.spacing.xl) {
+ HStack {
+ Text(panel == .add ? "Add Provider" : panel == .compare ? "Compare models" : "Manage")
+ .font(self.theme.typography.sectionTitle)
+ Spacer()
+ Button { self.panel = nil } label: { Image(systemName: "xmark") }
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ .accessibilityLabel("Close panel")
+ .focused(self.$panelCloseFocused)
+ .keyboardShortcut(.cancelAction)
+ }
+ Divider()
+ if panel == .add {
+ ForEach(["OpenAI", "Anthropic", "Ollama", "Custom provider"], id: \.self) { provider in
+ Label(provider, systemImage: "plus.circle")
+ .font(self.theme.typography.body)
+ }
+ } else if panel == .compare {
+ ForEach(Model.allCases) { model in
+ VStack(alignment: .leading, spacing: self.spacing.sm) {
+ Text(model.rawValue).font(self.theme.typography.sectionTitle)
+ Text(model.detail).font(self.theme.typography.bodySmall)
+ }
+ }
+ } else {
+ Text(panel == .manage ? "Fluid Intelligence" : "Provider settings")
+ .font(self.theme.typography.title)
+ Text(panel == .manage ? "\(self.selected.rawValue) · On-device" : "Connection · Models · Preferences")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.supportingText)
+ Divider()
+ ForEach(panel == .manage ? ["Model downloads", "Backend & context", "Startup preferences", "Storage & maintenance"] : ["Connection details", "Model selection", "Verification"], id: \.self) { label in
+ Text(label).font(self.theme.typography.body)
+ }
+ }
+ Spacer()
+ Text("Panel layout preview. Settings and connections are not wired yet.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.supportingText)
+ }
+ .padding(self.spacing.xl)
+ .frame(width: 290)
+ .frame(maxHeight: .infinity)
+ .background(self.theme.palette.elevatedCardBackground)
+ .overlay(alignment: .leading) {
+ Rectangle().fill(self.theme.palette.separator).frame(width: 1)
+ }
+ .onAppear { self.panelCloseFocused = true }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/AISettingsScreens.swift b/Sources/Fluid/UI/AISettings/AISettingsScreens.swift
index 565cc8b2..3480c6f4 100644
--- a/Sources/Fluid/UI/AISettings/AISettingsScreens.swift
+++ b/Sources/Fluid/UI/AISettings/AISettingsScreens.swift
@@ -34,6 +34,7 @@ struct AIEnhancementSettingsScreen: View {
@Binding var shortcutRecordingMessage: String?
@StateObject private var viewModel: AIEnhancementSettingsViewModel
+ @StateObject private var privateAIController: PrivateAISettingsController
init(
menuBarManager: MenuBarManager,
@@ -47,11 +48,13 @@ struct AIEnhancementSettingsScreen: View {
_selectedConfigurationSection = selectedConfigurationSection
_activeShortcutRecordingTarget = activeShortcutRecordingTarget
_shortcutRecordingMessage = shortcutRecordingMessage
- _viewModel = StateObject(wrappedValue: AIEnhancementSettingsViewModel(
+ let enhancementModel = AIEnhancementSettingsViewModel(
settings: SettingsStore.shared,
menuBarManager: menuBarManager,
promptTest: DictationPromptTestCoordinator.shared
- ))
+ )
+ _viewModel = StateObject(wrappedValue: enhancementModel)
+ _privateAIController = StateObject(wrappedValue: PrivateAISettingsController(viewModel: enhancementModel))
}
var body: some View {
@@ -59,6 +62,7 @@ struct AIEnhancementSettingsScreen: View {
VStack(alignment: .leading, spacing: 14) {
AIEnhancementSettingsView(
viewModel: self.viewModel,
+ privateAIController: self.privateAIController,
settings: self.viewModel.settings,
promptTest: self.viewModel.promptTest,
theme: self.theme,
diff --git a/Sources/Fluid/UI/AISettings/AddProviderSheet.swift b/Sources/Fluid/UI/AISettings/AddProviderSheet.swift
new file mode 100644
index 00000000..5432abb7
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/AddProviderSheet.swift
@@ -0,0 +1,164 @@
+import SwiftUI
+
+struct AddProviderSheet<Logo: View>: View {
+ @Environment(\.dismiss) private var dismiss
+ @Environment(\.theme) private var theme
+ @ObservedObject var viewModel: AIEnhancementSettingsViewModel
+ @ViewBuilder let logo: (String, String) -> Logo
+ @State private var draft = ProviderSetupDraft()
+ @State private var isEditing = false
+ @State private var saveFailed = false
+
+ private var providers: [AIEnhancementSettingsViewModel.ProviderItemData] {
+ let added = Set(self.viewModel.cachedAddedProviderItems.map(\.id))
+ return self.viewModel.cachedProviderItems.filter {
+ $0.isBuiltIn && $0.id != PrivateAIProviderFeature.shared.providerID && !added.contains($0.id)
+ }
+ }
+
+ var body: some View {
+ FluidGlassControlGroup {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ HStack {
+ if self.isEditing && !self.draft.providerID.isEmpty {
+ self.logo(self.draft.providerID, self.draft.name)
+ } else {
+ Image(systemName: "square.stack.3d.up")
+ .font(.system(size: 26)).foregroundStyle(FluidBrandColors.blue)
+ .frame(width: 48, height: 48)
+ }
+ VStack(alignment: .leading, spacing: 6) {
+ Text(self.isEditing ? self.draft.name : "Add a provider").font(self.theme.typography.title)
+ Text(self.isEditing ? "Add connection details to get started." : "Your preferred models. Connected to FluidVoice.")
+ .font(self.theme.typography.body).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ Button("Cancel") { self.dismiss() }
+ .keyboardShortcut(.cancelAction)
+ .fluidGlassAction()
+ }
+ Divider()
+ if self.isEditing {
+ self.form
+ } else {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 20) {
+ Text("Choose a provider").font(self.theme.typography.bodyStrong)
+ LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 12) {
+ ForEach(self.providers) { provider in
+ Button {
+ self.draft = ProviderSetupDraft(
+ providerID: provider.id,
+ name: provider.name,
+ baseURL: ModelRepository.shared.defaultBaseURL(for: provider.id)
+ )
+ self.isEditing = true
+ } label: {
+ HStack(spacing: 14) {
+ self.logo(provider.id, provider.name).accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 5) {
+ Text(provider.name).font(self.theme.typography.bodyStrong)
+ Text(["ollama", "lmstudio"].contains(provider.id) ? "Local connection" : "Connect with an API key")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ Image(systemName: "chevron.right").accessibilityHidden(true)
+ }
+ .padding(16).frame(maxWidth: .infinity, minHeight: 76, alignment: .leading)
+ .contentShape(RoundedRectangle(cornerRadius: 16))
+ }
+ .buttonStyle(ProviderChoiceStyle())
+ }
+ Button {
+ self.draft = ProviderSetupDraft(name: "Custom Provider")
+ self.isEditing = true
+ } label: {
+ HStack(spacing: 14) {
+ Image(systemName: "server.rack").font(.system(size: 24))
+ .foregroundStyle(FluidBrandColors.blue).frame(width: 38, height: 38)
+ VStack(alignment: .leading, spacing: 5) {
+ Text("Custom Provider").font(self.theme.typography.bodyStrong)
+ Text("Your service or server")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ Image(systemName: "plus").foregroundStyle(FluidBrandColors.blue)
+ }.padding(16).contentShape(RoundedRectangle(cornerRadius: 16))
+ }
+ .buttonStyle(ProviderChoiceStyle())
+ }
+ }
+ }
+ Label("Adding a provider won’t change your current dictation setup.", systemImage: "info.circle")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ }
+ }
+ .padding(28)
+ .frame(width: 720, height: 650)
+ .background(self.theme.palette.windowBackground)
+ }
+
+ private var form: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 20) {
+ FluidManagementGroup(title: "Connection details") {
+ if self.draft.providerID.isEmpty {
+ self.field("Name") { TextField("Custom Provider", text: self.$draft.name) }
+ self.field("Server URL") { TextField("https://your-server.com/v1", text: self.$draft.baseURL) }
+ }
+ self.field(self.draft.requiresAPIKey ? "API key" : "API key · Optional") {
+ SecureField("Enter API key", text: self.$draft.apiKey)
+ }
+ if let website = ModelRepository.shared.providerWebsiteURL(for: self.draft.providerID), let url = URL(string: website.url) {
+ Link(destination: url) { Label(website.label, systemImage: "arrow.up.right").font(self.theme.typography.caption) }
+ }
+ }
+ FluidManagementGroup(title: "Model") {
+ self.field("Model name · Optional") { TextField("Enter a model ID", text: self.$draft.model) }
+ Text(self.draft.providerID.isEmpty ? "Add a model now, or fetch models from Manage later." : "Leave blank to start with the provider’s default models.")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Label("Your current dictation setup stays unchanged.", systemImage: "info.circle")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ }
+ .textFieldStyle(.roundedBorder)
+ if self.saveFailed {
+ Text("Couldn’t save this provider. Check Keychain access and try again.")
+ .font(self.theme.typography.caption).foregroundStyle(.red)
+ }
+ Spacer()
+ HStack {
+ Button("Back") { self.isEditing = false; self.saveFailed = false }
+ .fluidGlassAction()
+ Spacer()
+ Button("Add Provider") {
+ if self.viewModel.addProvider(self.draft) { self.dismiss() } else { self.saveFailed = true }
+ }
+ .keyboardShortcut(.defaultAction)
+ .fluidGlassAction(prominent: true)
+ .disabled(!self.draft.isValid || self.viewModel.isTestingConnection || self.viewModel.isFetchingModels)
+ }
+ }
+ }
+
+ private func field<Control: View>(_ title: String, @ViewBuilder control: () -> Control) -> some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(title).font(self.theme.typography.bodyStrong)
+ control().textFieldStyle(.roundedBorder).controlSize(.large).accessibilityLabel(title)
+ }
+ }
+}
+
+private struct ProviderChoiceStyle: ButtonStyle {
+ @Environment(\.theme) private var theme
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label.foregroundStyle(self.theme.palette.primaryText)
+ .background(
+ configuration.isPressed ? FluidBrandColors.blue.opacity(0.12) : self.theme.palette.cardBackground,
+ in: RoundedRectangle(cornerRadius: 16, style: .continuous)
+ )
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/DictationDefaultProvider.swift b/Sources/Fluid/UI/AISettings/DictationDefaultProvider.swift
new file mode 100644
index 00000000..8db6c32f
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/DictationDefaultProvider.swift
@@ -0,0 +1,29 @@
+import Foundation
+
+/// Identifies the main shortcut's provider without reading credentials or app-specific overrides.
+enum DictationDefaultProvider {
+ static func setupIssue(requiresAPIKey: Bool, hasAPIKey: Bool, hasModel: Bool, isVerified: Bool, verificationFailed: Bool) -> String? {
+ if requiresAPIKey, !hasAPIKey { return "API key missing" }
+ if !hasModel { return "Choose a model" }
+ if verificationFailed { return "Verification failed" }
+ // A test is optional; only missing setup prevents use.
+ return nil
+ }
+
+ static func providerID(
+ selection: SettingsStore.DictationPromptSelection,
+ configuration: SettingsStore.DictationPromptConfiguration,
+ selectedProviderID: String,
+ privateProviderID: String
+ ) -> String {
+ if selection == .off { return "" }
+ if selection == .privateAI { return privateProviderID }
+ let providerID = configuration.providerID.trimmingCharacters(in: .whitespacesAndNewlines)
+ let model = configuration.modelName.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !providerID.isEmpty, !model.isEmpty { return providerID }
+ if selection == .default, selectedProviderID == privateProviderID,
+ providerID.isEmpty, model.isEmpty { return privateProviderID }
+ let fallback = selectedProviderID.trimmingCharacters(in: .whitespacesAndNewlines)
+ return fallback == privateProviderID ? "" : fallback
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift b/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift
new file mode 100644
index 00000000..9c9d80ce
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift
@@ -0,0 +1,192 @@
+import SwiftUI
+
+/// Retains controller ownership; card inspection never selects or loads a model.
+struct FluidIntelligenceLiveSection<Management: View>: View {
+ @Environment(\.theme) private var theme
+ @ObservedObject var controller: PrivateAISettingsController
+ let backendID: String
+ let isPrimary: Bool
+ let isVerified: Bool
+ let makePrimary: () -> Void
+ @ViewBuilder let management: () -> Management
+ @State private var showsManagement = false
+ @State private var pendingDeletion: PrivateAIRegisteredModel?
+ @State private var showsDeleteConfirmation = false
+ @State private var showsVerificationResult = false
+ @State private var verificationError: String?
+ @State private var verifiedModelName = ""
+ @State private var snapshots: [String: ModelFiles] = [:]
+ @State private var recommendedModelID: String?
+
+ private struct ModelFiles: Sendable {
+ let installed: Bool
+ let removable: Bool
+ }
+
+ private struct ReadIdentity: Equatable {
+ let selectedID: String
+ let backendID: String
+ let busy: Bool
+ }
+
+ private var models: [PrivateAIRegisteredModel] {
+ PrivateAIModelRegistry.modelIDs().compactMap { PrivateAIModelRegistry.model(id: $0) }
+ }
+
+ private var readIdentity: ReadIdentity {
+ ReadIdentity(selectedID: self.controller.privateAISelectedModelID, backendID: self.backendID, busy: self.controller.isBusy)
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ HStack {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Fluid Intelligence").font(self.theme.typography.title).fontWeight(.semibold)
+ Text("Polish your words. Privately, on your Mac.")
+ .font(self.theme.typography.body).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ ProviderDefaultButton(isCurrent: self.isPrimary, isEnabled: self.isVerified && !self.controller.isBusy, action: self.makePrimary)
+ Button("Manage", systemImage: "slider.horizontal.3") { self.showsManagement = true }
+ .fluidGlassAction()
+ }
+ FluidIntelligenceModelCarousel(
+ models: self.models,
+ previewID: self.controller.previewModelID,
+ selectedID: self.controller.privateAISelectedModelID,
+ recommendedModelID: self.recommendedModelID,
+ onBrowse: self.controller.previewModel
+ ) { model in
+ self.cardControls(model)
+ }
+ }
+ .padding(20)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius))
+ .task {
+ let recommendation = await Task.detached(priority: .utility) {
+ PrivateAIModelRecommendation.currentModelID
+ }.value
+ guard !Task.isCancelled else { return }
+ self.recommendedModelID = recommendation
+ }
+ .task(id: self.readIdentity) {
+ self.snapshots = [:]
+ guard !self.controller.isBusy else { return }
+ let identity = self.readIdentity
+ let models = self.models
+ let files = await Task.detached(priority: .utility) {
+ Dictionary(uniqueKeysWithValues: models.map { model in
+ (model.id, ModelFiles(
+ installed: PrivateAIIntegrationService.isModelInstalled(model),
+ removable: PrivateAIIntegrationService.canRemoveInstalledModel(model)
+ ))
+ })
+ }.value
+ guard !Task.isCancelled, identity == self.readIdentity else { return }
+ self.snapshots = files
+ for model in models {
+ self.controller.refreshPrivateAIModelUpdateStatus(model)
+ }
+ }
+ .alert("Delete downloaded model?", isPresented: self.$showsDeleteConfirmation, presenting: self.pendingDeletion) { model in
+ Button("Cancel", role: .cancel) { self.pendingDeletion = nil }
+ Button("Delete model", role: .destructive) {
+ self.controller.deletePrivateAIModel(model)
+ self.pendingDeletion = nil
+ }
+ } message: { model in
+ Text("This removes \(model.displayName) from your Mac. You’ll need to download it again to use it. Your dictation history and shortcut settings won’t change.")
+ }
+ .alert(self.verificationError == nil ? "Model verified" : "Verification failed", isPresented: self.$showsVerificationResult) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(self.verificationError ?? "\(self.verifiedModelName) is ready to use on your Mac.")
+ }
+ .sheet(isPresented: self.$showsManagement) {
+ FluidManagementSheet(title: "Manage Fluid Intelligence", subtitle: "These settings apply to all Fluid Intelligence models.", symbol: "slider.horizontal.3", close: { self.showsManagement = false }) {
+ self.management()
+ FluidManagementGroup(title: "Storage") {
+ FluidManagementRow(title: "Downloaded models", detail: "View the model files stored on your Mac.") {
+ Button("Open models folder", systemImage: "folder", action: self.controller.revealPrivateAIModelFolder)
+ .fluidGlassAction()
+ }
+ }
+ }
+ }
+ }
+
+ private func cardControls(_ model: PrivateAIRegisteredModel) -> some View {
+ let files = self.snapshots[model.id]
+ let selected = model.id == self.controller.privateAISelectedModelID
+ let active = selected && self.isVerified && self.controller.privateAILoadState.isLoaded(model.id)
+ let realUpdate = files?.installed == true && self.controller.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable
+ return VStack(alignment: .leading, spacing: 8) {
+ Divider().overlay(self.theme.palette.cardBorder)
+ if files?.installed == false, let bytes = model.artifact.byteCount, bytes > 0 {
+ Text("Download · ≈\(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file))")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ if self.controller.privateAILoadState.isDownloading(model.id) {
+ Text(PrivateAIModelDownloadProgressText.detailText(for: self.controller.privateAILoadState.downloadProgress(for: model.id)))
+ .font(self.theme.typography.caption).lineLimit(2)
+ } else if self.controller.privateAILoadState.isLoading(model.id) {
+ Text("Preparing model…").font(self.theme.typography.caption)
+ } else if let failure = self.controller.privateAILoadState.failureMessage(for: model.id) {
+ Text(failure).font(self.theme.typography.caption).foregroundStyle(.red).lineLimit(2).help(failure)
+ }
+ HStack(spacing: 8) {
+ if active {
+ Label("Active", systemImage: "checkmark.circle.fill")
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(Color.fluidGreen)
+ .frame(minWidth: 76, minHeight: 24)
+ .accessibilityLabel("Active model")
+ } else {
+ Button {
+ guard let files else { return }
+ self.controller.previewModel(model.id)
+ self.controller.usePreviewModel(isInstalled: files.installed, onReady: {})
+ } label: {
+ Text(files?.installed == false ? "Download" : "Activate")
+ .font(self.theme.typography.bodyStrong)
+ .frame(minWidth: 76, minHeight: 24)
+ }
+ .fluidGlassAction(prominent: true)
+ .disabled(self.controller.isBusy || files == nil || (files?.installed == false && !model.canDownload))
+ }
+ Spacer(minLength: 0)
+ FluidModelMetrics(modelID: model.id)
+ Menu {
+ if realUpdate {
+ Button("Update model") {
+ self.controller.updatePrivateAIModel(model)
+ }
+ .disabled(!selected || self.controller.isBusy)
+ }
+ Button("Verify model") {
+ self.controller.verifyPrivateAIConnection(model, onCompletion: { error in
+ self.verifiedModelName = model.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1")
+ self.verificationError = error
+ self.showsVerificationResult = true
+ })
+ }
+ .disabled(!selected || files?.installed != true || self.controller.isBusy)
+ if !selected {
+ Text("Activate this model to manage it")
+ }
+ Divider()
+ Button("Delete model…", role: .destructive) {
+ self.pendingDeletion = model
+ self.showsDeleteConfirmation = true
+ }
+ .disabled(!selected || files?.removable != true || self.controller.isBusy)
+ } label: {
+ Image(systemName: "ellipsis").frame(width: 32, height: 32)
+ }
+ .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()
+ .accessibilityLabel("Options for \(model.displayName)")
+ }
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/FluidIntelligenceModelCarousel.swift b/Sources/Fluid/UI/AISettings/FluidIntelligenceModelCarousel.swift
new file mode 100644
index 00000000..8aebdc3a
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/FluidIntelligenceModelCarousel.swift
@@ -0,0 +1,156 @@
+import SwiftUI
+
+/// Pure presentation: the only emitted action is browsing, never activation or persistence.
+struct FluidIntelligenceModelCarousel<Controls: View>: View {
+ @Environment(\.theme) private var theme
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.colorSchemeContrast) private var contrast
+ let models: [PrivateAIRegisteredModel]
+ let previewID: String
+ let selectedID: String
+ var recommendedModelID: String? = nil
+ let onBrowse: (String) -> Void
+ @ViewBuilder let controls: (PrivateAIRegisteredModel) -> Controls
+ @State private var upcomingPreviewID: String?
+
+ private var spacing: AppTheme.Metrics.Spacing { self.theme.metrics.spacing }
+ private var itemIDs: [String] { self.models.map(\.id) + PrivateAIUpcomingModel.allCases.map(\.id) }
+ private var displayedPreviewID: String { self.upcomingPreviewID ?? self.previewID }
+
+ var body: some View {
+ VStack(spacing: self.spacing.sm) {
+ GeometryReader { geometry in
+ let cardWidth = min(AppTheme.Metrics.Showcase.cardMaxWidth, geometry.size.width * 0.44)
+ let sideWidth = min(AppTheme.Metrics.Showcase.sideCardMaxWidth, max(60, (geometry.size.width - cardWidth - self.spacing.md * 2 - 80) / 2))
+ let stride = cardWidth / 2 + sideWidth / 2 + self.spacing.md
+ ZStack {
+ ForEach(self.itemIDs.filter { abs(self.carouselPosition($0)) <= 1 }, id: \.self) { id in
+ let position = self.carouselPosition(id)
+ Group {
+ if let model = self.models.first(where: { $0.id == id }) {
+ FluidModelShowcaseCard(
+ model: model,
+ isPreview: position == 0,
+ isSelected: self.selectedID == model.id,
+ compact: position != 0,
+ isRecommended: self.recommendedModelID == model.id,
+ browse: { self.browse(id) }
+ )
+ } else if let upcoming = PrivateAIUpcomingModel(rawValue: id) {
+ self.upcomingCard(upcoming, compact: position != 0)
+ }
+ }
+ .overlay(alignment: .bottom) {
+ if position == 0, let model = self.models.first(where: { $0.id == id }) {
+ self.controls(model).padding(.horizontal, 16).padding(.bottom, 16)
+ }
+ }
+ .frame(width: position == 0 ? cardWidth : sideWidth, height: AppTheme.Metrics.Showcase.cardHeight)
+ .saturation(position == 0 ? 1 : 0.12)
+ .opacity(position == 0 || self.contrast == .increased ? 1 : 0.65)
+ .scaleEffect(position == 0 ? 1 : 0.90)
+ .offset(x: CGFloat(position) * stride)
+ .zIndex(position == 0 ? 1 : 0)
+ }
+ }
+ .frame(width: geometry.size.width, height: geometry.size.height)
+ .clipped()
+ .overlay(alignment: .leading) { self.carouselArrow(forward: false) }
+ .overlay(alignment: .trailing) { self.carouselArrow(forward: true) }
+ .simultaneousGesture(DragGesture(minimumDistance: 24).onEnded { value in
+ guard abs(value.translation.width) > abs(value.translation.height) else { return }
+ self.advanceCarousel(forward: value.translation.width < 0)
+ })
+ }
+ .frame(height: AppTheme.Metrics.Showcase.stageHeight)
+
+ HStack(spacing: self.spacing.xs) {
+ ForEach(self.itemIDs, id: \.self) { id in
+ Button { self.browse(id) } label: {
+ Circle()
+ .fill(self.displayedPreviewID == id ? FluidBrandColors.blue : self.theme.palette.secondaryText.opacity(0.4))
+ .frame(width: self.displayedPreviewID == id ? 10 : 7, height: self.displayedPreviewID == id ? 10 : 7)
+ .frame(width: 24, height: 24)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Show \(self.title(for: id))")
+ .accessibilityValue(self.displayedPreviewID == id ? "Current page" : "")
+ }
+ }
+ }
+ .onChange(of: self.previewID) { _, _ in self.upcomingPreviewID = nil }
+ }
+
+ private func carouselPosition(_ id: String) -> Int {
+ PrivateAIModelCarouselNavigation.position(of: id, in: self.itemIDs, current: self.displayedPreviewID)
+ }
+
+ private func browse(_ id: String) {
+ withAnimation(self.reduceMotion ? nil : .easeInOut(duration: 0.22)) {
+ if PrivateAIUpcomingModel(rawValue: id) != nil {
+ self.upcomingPreviewID = id
+ } else if self.models.contains(where: { $0.id == id }) {
+ self.upcomingPreviewID = nil
+ self.onBrowse(id)
+ }
+ }
+ }
+
+ private func advanceCarousel(forward: Bool) {
+ guard let id = PrivateAIModelCarouselNavigation.next(in: self.itemIDs, current: self.displayedPreviewID, forward: forward) else { return }
+ self.browse(id)
+ }
+
+ private func carouselArrow(forward: Bool) -> some View {
+ Button { self.advanceCarousel(forward: forward) } label: {
+ Image(systemName: forward ? "chevron.right" : "chevron.left")
+ .font(self.theme.typography.sectionTitle)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .frame(width: 34, height: 34)
+ .contentShape(Circle())
+ }
+ .fluidGlassAction(circular: true)
+ .accessibilityLabel(forward ? "Next model" : "Previous model")
+ .disabled(self.itemIDs.count < 2)
+ }
+
+ private func title(for id: String) -> String {
+ PrivateAIUpcomingModel(rawValue: id)?.title
+ ?? self.models.first(where: { $0.id == id })?.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1")
+ ?? id
+ }
+
+ private func upcomingCard(_ model: PrivateAIUpcomingModel, compact: Bool) -> some View {
+ Button { self.browse(model.id) } label: {
+ VStack(alignment: .leading, spacing: self.spacing.md) {
+ Text("Coming soon")
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ Text(model.title)
+ .font(compact ? self.theme.typography.sectionTitle : self.theme.typography.title)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ Text("Not available yet")
+ .font(self.theme.typography.body)
+ .foregroundStyle(self.theme.palette.tertiaryText)
+ Spacer(minLength: 0)
+ Divider()
+ Label("Coming soon", systemImage: "clock")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ .padding(self.spacing.xl)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius))
+ .overlay {
+ RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius)
+ .strokeBorder(self.theme.palette.cardBorder, lineWidth: 1)
+ }
+ .contentShape(RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius))
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Preview \(model.title), coming soon")
+ .accessibilityHint("Preview only. This model cannot be activated or downloaded.")
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/FluidModelShowcaseCard.swift b/Sources/Fluid/UI/AISettings/FluidModelShowcaseCard.swift
new file mode 100644
index 00000000..07046f3b
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/FluidModelShowcaseCard.swift
@@ -0,0 +1,188 @@
+import SwiftUI
+
+/// Presentation only: model browsing is injected by the carousel.
+struct FluidModelShowcaseCard: View {
+ @Environment(\.theme) private var theme
+ @Environment(\.colorScheme) private var colorScheme
+ @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.colorSchemeContrast) private var contrast
+ @State private var hovered = false
+ @State private var showsInfo = false
+ let model: PrivateAIRegisteredModel
+ let isPreview: Bool
+ let isSelected: Bool
+ let compact: Bool
+ var isRecommended = false
+ let browse: () -> Void
+
+ private var shape: RoundedRectangle {
+ RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius, style: .continuous)
+ }
+
+ var body: some View {
+ let presentation = PrivateAIModelPresentation.forModel(id: self.model.id)
+ Button(action: self.browse) {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ Color.clear.frame(height: 20)
+ .overlay(alignment: .leading) {
+ if self.isRecommended {
+ Text(self.compact ? "Recommended" : "Recommended for your Mac")
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(FluidBrandColors.blue)
+ .lineLimit(1).minimumScaleFactor(0.8)
+ .padding(.trailing, 24)
+ .help("Based on your Mac’s RAM. You can choose either model.")
+ }
+ }
+ HStack(spacing: 8) {
+ Text(self.model.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1"))
+ .font(self.compact ? self.theme.typography.sectionTitle : self.theme.typography.title)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .lineLimit(2).minimumScaleFactor(0.85)
+ if self.isSelected {
+ Image(systemName: "checkmark.circle.fill")
+ .font(.system(size: 18, weight: .semibold))
+ .foregroundStyle(FluidBrandColors.blue)
+ .accessibilityLabel("Selected")
+ }
+ }
+ ZStack(alignment: .topLeading) {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ Text(presentation.summary)
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ Text(presentation.useCase)
+ .font(self.theme.typography.body)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ .lineSpacing(3)
+ }
+ .opacity(self.showsInfo ? 0 : 1)
+ .accessibilityHidden(self.showsInfo)
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ self.infoRow("Languages", value: presentation.language)
+ if let bytes = self.model.artifact.byteCount, bytes > 0 {
+ self.infoRow("Download size", value: "≈\(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file))")
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .opacity(self.showsInfo ? 1 : 0)
+ .accessibilityHidden(!self.showsInfo)
+ }
+ .animation(self.reduceMotion ? nil : .easeInOut(duration: 0.16), value: self.showsInfo)
+ Spacer(minLength: self.theme.metrics.spacing.sm)
+ // Separate sibling controls are overlaid by the carousel; never nest buttons.
+ Color.clear.frame(height: 64)
+ }
+ .padding(self.theme.metrics.spacing.xl)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ .background {
+ self.shape.fill(self.colorScheme == .dark ? Color(red: 0.025, green: 0.04, blue: 0.095) : self.theme.palette.elevatedCardBackground)
+ if !self.reduceTransparency {
+ self.shape.fill(LinearGradient(
+ colors: [FluidBrandColors.blue.opacity(self.isPreview ? 0.16 : 0.08), .clear],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ ))
+ }
+ }
+ .overlay {
+ self.shape.strokeBorder(
+ self.isPreview ? FluidBrandColors.blue.opacity(self.contrast == .increased ? 1 : 0.5) : self.theme.palette.cardBorder,
+ lineWidth: self.contrast == .increased ? 2 : 1
+ )
+ }
+ .shadow(color: .black.opacity(self.colorScheme == .dark ? 0.28 : 0.08), radius: self.isPreview ? 12 : 4, y: self.isPreview ? 8 : 2)
+ .brightness(self.hovered ? 0.01 : 0)
+ .contentShape(self.shape)
+ }
+ .buttonStyle(.plain)
+ .onHover { self.hovered = $0 }
+ .animation(self.reduceMotion ? nil : .easeOut(duration: 0.12), value: self.hovered)
+ .accessibilityLabel("Preview \(self.model.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1"))")
+ .accessibilityValue([self.isPreview ? "Previewed" : "", self.isRecommended ? "Recommended for your Mac" : ""].filter { !$0.isEmpty }.joined(separator: ", "))
+ .accessibilityHint(self.showsInfo ? self.infoAccessibilityDescription : "\(presentation.summary). \(presentation.useCase) Browse without changing the selected model.")
+ .overlay(alignment: .topTrailing) {
+ // Sibling to the browse button: opening details never selects or activates a model.
+ Button { self.showsInfo.toggle() } label: {
+ Image(systemName: self.showsInfo ? "xmark.circle" : "info.circle")
+ .font(.system(size: 19, weight: .regular))
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .frame(width: 32, height: 32)
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .help(self.showsInfo ? "Close model information" : "About \(self.model.displayName)")
+ .accessibilityLabel(self.showsInfo ? "Close information for \(self.model.displayName)" : "About \(self.model.displayName)")
+ .accessibilityValue(self.showsInfo ? "Expanded" : "Collapsed")
+ .padding(14)
+ }
+ }
+
+ private func infoRow(_ title: String, value: String) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: self.theme.metrics.spacing.sm) {
+ Text(title).foregroundStyle(self.theme.palette.secondaryText)
+ Spacer(minLength: 0)
+ Text(value).foregroundStyle(self.theme.palette.primaryText)
+ .multilineTextAlignment(.trailing)
+ }
+ .font(self.theme.typography.caption)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ private var infoAccessibilityDescription: String {
+ let language = PrivateAIModelPresentation.forModel(id: self.model.id).language
+ guard let bytes = self.model.artifact.byteCount, bytes > 0 else { return "Languages: \(language)" }
+ return "Languages: \(language). Download size: approximately \(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file))."
+ }
+}
+
+struct FluidModelMetrics: View {
+ @Environment(\.theme) private var theme
+ let modelID: String
+
+ var body: some View {
+ let presentation = PrivateAIModelPresentation.forModel(id: self.modelID)
+ if let intelligence = presentation.intelligence, let speed = presentation.speed {
+ VStack(spacing: self.theme.metrics.spacing.xs) {
+ FluidModelMetric(label: "Intelligence", value: intelligence, tint: FluidBrandColors.blue, compact: true)
+ FluidModelMetric(label: "Speed", value: speed, tint: .teal, compact: true)
+ }
+ .frame(width: AppTheme.Metrics.Showcase.compactMetricWidth)
+ .help("Illustrative design preview — not benchmark scores")
+ }
+ }
+}
+
+/// Five bounded static segments: no work beyond rendering immutable preview values.
+private struct FluidModelMetric: View {
+ @Environment(\.theme) private var theme
+ let label: String
+ let value: Int
+ let tint: Color
+ let compact: Bool
+
+ var body: some View {
+ HStack(spacing: self.theme.metrics.spacing.xs) {
+ Text(self.label)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+ .frame(width: self.compact ? 58 : 64, alignment: .leading)
+ HStack(spacing: 3) {
+ ForEach(1...5, id: \.self) { step in
+ Capsule()
+ .fill(step <= self.value ? self.tint : self.theme.palette.secondaryText.opacity(0.25))
+ .frame(maxWidth: .infinity)
+ .frame(height: 3)
+ }
+ }
+ }
+ .allowsHitTesting(false)
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel("\(self.label): illustrative level \(self.value) of 5, not a benchmark score")
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/PrivateAIModelPresentation.swift b/Sources/Fluid/UI/AISettings/PrivateAIModelPresentation.swift
new file mode 100644
index 00000000..9a65bf26
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/PrivateAIModelPresentation.swift
@@ -0,0 +1,48 @@
+import Foundation
+
+/// A RAM-based suggestion only; never selects, loads, downloads, or persists a model.
+enum PrivateAIModelRecommendation {
+ // First accessed from the settings background task; physical RAM cannot change during this process.
+ static let currentModelID = modelID(physicalMemory: ProcessInfo.processInfo.physicalMemory)
+
+ static func modelID(physicalMemory: UInt64) -> String {
+ physicalMemory >= 16 * 1024 * 1024 * 1024 ? "fluid-1-mini-96k-dflash" : "fluid-1-pico-96k-dflash"
+ }
+}
+
+/// UI-only previews. These identifiers are never registered with a runtime or download provider.
+enum PrivateAIUpcomingModel: String, CaseIterable, Identifiable {
+ case quad = "preview-upcoming-quad"
+ case multilingual = "preview-upcoming-multilingual"
+
+ var id: String { self.rawValue }
+ var title: String {
+ switch self {
+ case .quad: "Fluid 1 Quad"
+ case .multilingual: "Fluid 1.1 Multilingual"
+ }
+ }
+}
+
+/// Customer-facing copy only. Registry IDs, downloads, and runtime settings remain authoritative.
+struct PrivateAIModelPresentation {
+ let summary: String
+ let useCase: String
+ var language: String = "On-device"
+ // Illustrative design-preview values, not measured benchmark scores.
+ var intelligence: Int?
+ var speed: Int?
+
+ static func forModel(id: String) -> Self {
+ switch id {
+ case "fluid-1-pico-96k-dflash":
+ Self(summary: "Smallest & fastest", useCase: "Everyday dictation with basic cleanup and formatting.", language: "English only", intelligence: 2, speed: 5)
+ case "fluid-1-mini-96k-dflash":
+ Self(summary: "More capable", useCase: "Better structure, formatting and corrections.", language: "English only", intelligence: 4, speed: 4)
+ case "fluid-1":
+ Self(summary: "The original Fluid model", useCase: "Cleanup and formatting across languages.", language: "Multilingual", intelligence: 4, speed: 2)
+ default:
+ Self(summary: "On-device cleanup", useCase: "Polish your words privately on your Mac.")
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift b/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift
new file mode 100644
index 00000000..93cfe46c
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift
@@ -0,0 +1,497 @@
+import AppKit
+import Combine
+
+enum PrivateAIModelLoadState: Equatable {
+ case idle
+ case downloading(modelID: String, progress: PrivateAIModelDownloadProgress?)
+ case loading(modelID: String)
+ case loaded(modelID: String, latencyMilliseconds: Int?)
+ case failed(modelID: String, message: String)
+
+ func isLoading(_ modelID: String) -> Bool {
+ if case .loading(modelID) = self { return true }
+ return false
+ }
+
+ func isDownloading(_ modelID: String) -> Bool {
+ if case .downloading(modelID, _) = self { return true }
+ return false
+ }
+
+ func isLoaded(_ modelID: String) -> Bool {
+ if case .loaded(modelID, _) = self { return true }
+ return false
+ }
+
+ func latencyMilliseconds(for modelID: String) -> Int? {
+ if case let .loaded(loadedModelID, latencyMilliseconds) = self, loadedModelID == modelID {
+ return latencyMilliseconds
+ }
+ return nil
+ }
+
+ func failureMessage(for modelID: String) -> String? {
+ if case let .failed(failedModelID, message) = self, failedModelID == modelID {
+ return message
+ }
+ return nil
+ }
+
+ func downloadProgress(for modelID: String) -> PrivateAIModelDownloadProgress? {
+ if case let .downloading(downloadingModelID, progress) = self, downloadingModelID == modelID {
+ return progress
+ }
+ return nil
+ }
+}
+
+/// Retained FI settings state and actions, shared by the existing page and its controls.
+/// The runtime and persistence behavior remains in the existing services and provider view model.
+@MainActor
+final class PrivateAISettingsController: ObservableObject {
+ let viewModel: AIEnhancementSettingsViewModel
+
+ private var settings: SettingsStore { self.viewModel.settings }
+
+ @Published private var session: PrivateAISettingsSession
+
+ var privateAISelectedModelID: String { self.session.selectedModelID }
+ var previewModelID: String { self.session.previewModelID }
+ var isBusy: Bool { self.session.isBusy || self.viewModel.isTestingConnection }
+ @Published var privateAILoadState: PrivateAIModelLoadState = .idle
+ @Published var privateAIModelUpdateStatusByID: [String: PrivateAIModelUpdateStatus] = [:]
+
+ init(viewModel: AIEnhancementSettingsViewModel) {
+ self.viewModel = viewModel
+ self.session = PrivateAISettingsSession(selectedModelID: PrivateAIIntegrationService.configuredModelID)
+ }
+
+ /// Carousel arrows/dots call this; no defaults, provider, or runtime writes.
+ func previewModel(_ modelID: String) {
+ guard let model = PrivateAIModelRegistry.model(id: modelID) else { return }
+ self.session.preview(model.id)
+ }
+
+ func activatePreviewModel() {
+ self.persistPrivateAIModelSelection(self.previewModelID)
+ }
+
+ /// Only the explicit Use/Download action enters this path; browsing remains read-only.
+ func usePreviewModel(isInstalled: Bool, onReady: @escaping () -> Void) {
+ guard !self.isBusy, let model = PrivateAIModelRegistry.model(id: self.previewModelID) else { return }
+ self.persistPrivateAIModelSelection(model.id, loadIfInstalled: false)
+ if isInstalled {
+ self.verifyPrivateAIConnection(model, onReady: onReady)
+ } else {
+ self.downloadPrivateAIModel(model, onReady: onReady)
+ }
+ }
+
+ func synchronizeSelection() {
+ guard !self.isBusy else { return }
+ self.session.select(PrivateAIIntegrationService.configuredModelID)
+ }
+
+ private func beginOperation(for modelID: String) -> UUID? {
+ guard !self.isBusy, modelID == self.privateAISelectedModelID else { return nil }
+ return self.session.begin()
+ }
+
+ func refreshPrivateAIProviderModels() {
+ guard !self.isBusy else { return }
+ let providerKey = self.viewModel.providerKey(for: PrivateAIProviderFeature.shared.providerID)
+ let models = PrivateAIModelRegistry.modelIDs()
+ let selected = PrivateAIModelRegistry.canonicalModelID(for: self.privateAISelectedModelID) ?? PrivateAIModelRegistry.defaultModel.id
+
+ self.session.select(selected)
+ self.viewModel.availableModelsByProvider[providerKey] = models
+ self.viewModel.selectedModelByProvider[providerKey] = selected
+ self.viewModel.settings.availableModelsByProvider = self.viewModel.availableModelsByProvider
+ self.viewModel.settings.selectedModelByProvider = self.viewModel.selectedModelByProvider
+
+ if self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID {
+ self.viewModel.availableModels = models
+ self.viewModel.selectedModel = selected
+ }
+
+ self.refreshPrivateAILoadState()
+ self.refreshPrivateAIModelUpdateStatus(self.selectedPrivateAIModel)
+ self.viewModel.refreshProviderItems()
+ }
+
+ func refreshPrivateAIModelUpdateStatus(_ model: PrivateAIRegisteredModel) {
+ guard !self.session.isBusy else { return }
+ let revision = self.session.revision
+ Task { @MainActor in
+ let status = await PrivateAIIntegrationService.modelUpdateStatus(model)
+ guard self.session.acceptsRead(revision) else { return }
+ self.privateAIModelUpdateStatusByID[model.id] = status
+ }
+ }
+
+ func downloadPrivateAIModel(_ model: PrivateAIRegisteredModel, onReady: (() -> Void)? = nil) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ guard model.canDownload else {
+ self.session.finish(operation)
+ self.privateAILoadState = .failed(modelID: model.id, message: "Download URL is not configured yet.")
+ return
+ }
+
+ self.privateAILoadState = .downloading(
+ modelID: model.id,
+ progress: PrivateAIModelDownloadProgress(initialExpectedBytes: model.artifact.byteCount)
+ )
+ Task { @MainActor in
+ defer {
+ self.session.finish(operation)
+ self.refreshPrivateAIModelUpdateStatus(model)
+ }
+ do {
+ DebugLogger.shared.info(
+ "Private provider download button pressed model=\(model.id)",
+ source: "AISettingsView"
+ )
+ _ = try await PrivateAIIntegrationService.prepareModel(model) { progress in
+ await MainActor.run {
+ guard self.session.operationID == operation else { return }
+ self.privateAILoadState = .downloading(
+ modelID: model.id,
+ progress: progress.withFallbackExpectedBytes(model.artifact.byteCount)
+ )
+ }
+ }
+ guard self.privateAISelectedModelID == model.id else { return }
+ self.privateAILoadState = .loading(modelID: model.id)
+ let start = ContinuousClock.now
+ let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
+ let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
+ guard self.privateAISelectedModelID == model.id else { return }
+ if verified {
+ self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
+ onReady?()
+ } else {
+ let message = self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID).isEmpty
+ ? "Model downloaded, but verification failed."
+ : self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID)
+ self.privateAILoadState = .failed(modelID: model.id, message: message)
+ }
+ } catch {
+ guard self.privateAISelectedModelID == model.id else { return }
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: Self.errorMessage(for: error)
+ )
+ }
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func updatePrivateAIModel(_ model: PrivateAIRegisteredModel) {
+ guard self.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable,
+ let operation = self.beginOperation(for: model.id)
+ else { return }
+ let wasPreviouslyVerified = PrivateAIProviderPromptFormat.verifiedModelID(settings: self.settings) == model.id
+ self.privateAILoadState = .downloading(
+ modelID: model.id,
+ progress: PrivateAIModelDownloadProgress(initialExpectedBytes: model.artifact.byteCount)
+ )
+ Task { @MainActor in
+ defer {
+ self.session.finish(operation)
+ self.refreshPrivateAIModelUpdateStatus(model)
+ self.viewModel.refreshProviderItems()
+ }
+ do {
+ var verificationStart = ContinuousClock.now
+ let verified = try await PrivateAISettingsUpdateTransaction.run(
+ update: {
+ try await PrivateAIIntegrationService.updateModel(model) { progress in
+ await MainActor.run {
+ guard self.session.operationID == operation else { return }
+ self.privateAILoadState = .downloading(
+ modelID: model.id,
+ progress: progress.withFallbackExpectedBytes(model.artifact.byteCount)
+ )
+ }
+ }
+ },
+ verify: {
+ self.privateAILoadState = .loading(modelID: model.id)
+ verificationStart = .now
+ return await self.viewModel.verifyPrivateAIProvider(model: model)
+ },
+ commit: { await PrivateAIIntegrationService.commitModelUpdate($0) },
+ rollback: { await PrivateAIIntegrationService.rollbackModelUpdate($0) }
+ )
+ if verified {
+ self.privateAILoadState = .loaded(
+ modelID: model.id, latencyMilliseconds: Self.elapsedMilliseconds(since: verificationStart)
+ )
+ } else {
+ let detail = self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID)
+ if wasPreviouslyVerified {
+ self.viewModel.updateConnectionStatus(.success, for: PrivateAIProviderFeature.shared.providerID)
+ }
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: "The new model failed verification. The previous model is still active. \(detail)"
+ )
+ }
+ } catch {
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: "Update failed. The previous model is still active. \(Self.errorMessage(for: error))"
+ )
+ }
+ }
+ }
+
+ /// Explicit callers can request a result; nil means success, otherwise a user-facing failure.
+ func verifyPrivateAIConnection(_ model: PrivateAIRegisteredModel, onReady: (() -> Void)? = nil, onCompletion: ((String?) -> Void)? = nil) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ self.privateAILoadState = .loading(modelID: model.id)
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ let start = ContinuousClock.now
+ let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
+ let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
+ guard self.privateAISelectedModelID == model.id else { return }
+ if verified {
+ self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
+ onReady?()
+ onCompletion?(nil)
+ } else {
+ let message = self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID).isEmpty
+ ? "Model verification failed."
+ : self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID)
+ self.privateAILoadState = .failed(modelID: model.id, message: message)
+ onCompletion?(message)
+ }
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ var selectedPrivateAIModel: PrivateAIRegisteredModel {
+ PrivateAIModelRegistry.model(id: self.privateAISelectedModelID) ?? PrivateAIModelRegistry.defaultModel
+ }
+
+ func revealPrivateAIModelFolder() {
+ let directoryURL = PrivateAIIntegrationService.modelDirectoryURL
+ do {
+ try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
+ NSWorkspace.shared.open(directoryURL)
+ } catch {
+ DebugLogger.shared.error(
+ "Failed to open Private AI Provider models folder: \(error.localizedDescription)",
+ source: "AISettingsView"
+ )
+ }
+ }
+
+ func refreshPrivateAILoadState() {
+ guard !self.session.isBusy else { return }
+ if case .failed = self.privateAILoadState { return }
+ let revision = self.session.revision
+ Task { @MainActor in
+ let loaded = await PrivateAIIntegrationService.shared.loadedModelState()
+ guard self.session.acceptsRead(revision) else { return }
+ guard let loaded, loaded.state == .ready else {
+ self.privateAILoadState = .idle
+ return
+ }
+
+ self.privateAILoadState = .loaded(modelID: loaded.modelID, latencyMilliseconds: nil)
+ }
+ }
+
+ func loadPrivateAIModel(_ model: PrivateAIRegisteredModel) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ guard PrivateAIIntegrationService.isModelInstalled(model) else {
+ self.session.finish(operation)
+ self.privateAILoadState = .failed(modelID: model.id, message: "Model file is not installed.")
+ return
+ }
+
+ self.privateAILoadState = .loading(modelID: model.id)
+ Task { @MainActor in
+ defer {
+ self.session.finish(operation)
+ self.refreshPrivateAIModelUpdateStatus(model)
+ }
+ do {
+ let start = ContinuousClock.now
+ let status = try await PrivateAIIntegrationService.shared.loadModel(model)
+ let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
+ guard self.privateAISelectedModelID == model.id else { return }
+ switch status.state {
+ case .ready:
+ self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
+ default:
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: status.message ?? "Model did not report ready."
+ )
+ }
+ } catch {
+ guard self.privateAISelectedModelID == model.id else { return }
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: Self.errorMessage(for: error)
+ )
+ }
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func resetPrivateAIVerification(for model: PrivateAIRegisteredModel) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
+ self.privateAILoadState = .idle
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(reason: "Fluid Intelligence verification reset")
+ if PrivateAIIntegrationService.isModelInstalled(model) {
+ self.privateAILoadState = .idle
+ }
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func deletePrivateAIModel(_ model: PrivateAIRegisteredModel) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ guard PrivateAIIntegrationService.canRemoveInstalledModel(model) else {
+ self.session.finish(operation)
+ return
+ }
+ self.privateAILoadState = .loading(modelID: model.id)
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ do {
+ try await PrivateAIIntegrationService.shared.unloadAndRemoveInstalledModel(
+ model,
+ reason: "settings-delete"
+ )
+ self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
+ if self.privateAISelectedModelID == model.id {
+ self.privateAILoadState = .idle
+ }
+ self.viewModel.refreshProviderItems()
+ } catch {
+ guard self.privateAISelectedModelID == model.id else { return }
+ self.privateAILoadState = .failed(modelID: model.id, message: Self.errorMessage(for: error))
+ }
+ }
+ }
+
+ private static func errorMessage(for error: Error) -> String {
+ if let localizedError = error as? LocalizedError,
+ let description = localizedError.errorDescription
+ {
+ return description
+ }
+ return String(describing: error)
+ }
+
+ private static func elapsedMilliseconds(since start: ContinuousClock.Instant) -> Int {
+ let elapsed = start.duration(to: ContinuousClock.now)
+ return Int(elapsed.components.seconds * 1000) + Int(elapsed.components.attoseconds / 1_000_000_000_000_000)
+ }
+
+ func persistPrivateAIModelSelection(_ value: String, loadIfInstalled: Bool = true) {
+ guard let model = PrivateAIModelRegistry.model(id: value), model.id != self.privateAISelectedModelID else { return }
+ let providerKey = self.viewModel.providerKey(for: PrivateAIProviderFeature.shared.providerID)
+ let models = PrivateAIModelRegistry.modelIDs()
+
+ guard !self.isBusy, self.session.select(model.id) else { return }
+ UserDefaults.standard.set(model.id, forKey: PrivateAIIntegrationService.selectedModelDefaultsKey)
+ UserDefaults.standard.removeObject(forKey: PrivateAIIntegrationService.localModelPathDefaultsKey)
+
+ self.viewModel.availableModelsByProvider[providerKey] = models
+ self.viewModel.selectedModelByProvider[providerKey] = model.id
+ self.viewModel.settings.availableModelsByProvider = self.viewModel.availableModelsByProvider
+ self.viewModel.settings.selectedModelByProvider = self.viewModel.selectedModelByProvider
+
+ if self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID {
+ self.viewModel.availableModels = models
+ self.viewModel.selectedModel = model.id
+ }
+ self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
+ self.refreshPrivateAIModelUpdateStatus(model)
+ self.viewModel.refreshProviderItems()
+ if loadIfInstalled, PrivateAIIntegrationService.isModelInstalled(model) {
+ self.loadPrivateAIModel(model)
+ } else {
+ self.privateAILoadState = .idle
+ }
+ }
+
+ func setPrivateAIBackendPreference(_ preference: SettingsStore.PrivateAIBackendPreference) {
+ guard self.settings.privateAIBackendPreference != preference else { return }
+ guard let operation = self.beginOperation(for: self.privateAISelectedModelID) else { return }
+ let modelID = self.privateAISelectedModelID
+
+ self.settings.privateAIBackendPreference = preference
+ UserDefaults.standard.removeObject(forKey: PrivateAIIntegrationService.localModelPathDefaultsKey)
+ self.privateAILoadState = .idle
+ self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
+
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(
+ reason: "Fluid Intelligence backend changed to \(preference.displayName)"
+ )
+ guard self.privateAISelectedModelID == modelID else { return }
+ let model = self.selectedPrivateAIModel
+ if PrivateAIIntegrationService.isModelInstalled(model) {
+ self.session.finish(operation)
+ self.verifyPrivateAIConnection(model)
+ } else {
+ self.privateAILoadState = .idle
+ self.viewModel.refreshProviderItems()
+ }
+ }
+ }
+
+ func setPrefixCacheEnabled(_ enabled: Bool) {
+ guard self.settings.privateAIPrefixKVCacheEnabled != enabled else { return }
+ guard let operation = self.beginOperation(for: self.privateAISelectedModelID) else { return }
+ self.settings.privateAIPrefixKVCacheEnabled = enabled
+ self.privateAILoadState = .idle
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(
+ reason: enabled ? "prefix cache enabled" : "prefix cache disabled"
+ )
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func setBoostEnabled(_ enabled: Bool) {
+ guard self.settings.privateAIBoostEnabled != enabled else { return }
+ guard let operation = self.beginOperation(for: self.privateAISelectedModelID) else { return }
+ self.settings.privateAIBoostEnabled = enabled
+ self.privateAILoadState = .idle
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(
+ reason: enabled ? "Fluid-1 Boost enabled" : "Fluid-1 Boost disabled"
+ )
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func setContextTokenLimit(_ value: Int) {
+ let clamped = SettingsStore.clampPrivateAIContextTokenLimit(value)
+ guard self.settings.privateAIContextTokenLimit != clamped else { return }
+ guard let operation = self.beginOperation(for: self.privateAISelectedModelID) else { return }
+ self.settings.privateAIContextTokenLimit = clamped
+ self.privateAILoadState = .idle
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(
+ reason: "Fluid Intelligence context changed"
+ )
+ self.viewModel.refreshProviderItems()
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/PrivateAISettingsSession.swift b/Sources/Fluid/UI/AISettings/PrivateAISettingsSession.swift
new file mode 100644
index 00000000..356d9811
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/PrivateAISettingsSession.swift
@@ -0,0 +1,93 @@
+import Foundation
+
+/// Catalog-driven carousel math. Empty and single-model builds never wrap or invent neighbors.
+enum PrivateAIModelCarouselNavigation {
+ static func next(in ids: [String], current: String, forward: Bool) -> String? {
+ guard !ids.isEmpty else { return nil }
+ guard let index = ids.firstIndex(of: current) else { return ids.first }
+ return ids[(index + (forward ? 1 : ids.count - 1)) % ids.count]
+ }
+
+ static func position(of id: String, in ids: [String], current: String) -> Int {
+ guard let index = ids.firstIndex(of: id), !ids.isEmpty else { return 0 }
+ let center = ids.firstIndex(of: current) ?? 0
+ if ids.count == 2 { return index - center }
+ let distance = (index - center + ids.count) % ids.count
+ return distance > ids.count / 2 ? distance - ids.count : distance
+ }
+}
+
+/// Presentation-only choice and a single bounded mutation slot. Browsing never invokes an action.
+struct PrivateAISettingsSession {
+ private(set) var selectedModelID: String
+ private(set) var previewModelID: String
+ private(set) var revision = UUID()
+ private(set) var operationID: UUID?
+
+ var isBusy: Bool { self.operationID != nil }
+
+ init(selectedModelID: String) {
+ self.selectedModelID = selectedModelID
+ self.previewModelID = selectedModelID
+ }
+
+ mutating func preview(_ modelID: String) {
+ self.previewModelID = modelID
+ }
+
+ /// Explicit activation only. The caller validates IDs against the current model catalog.
+ @discardableResult
+ mutating func select(_ modelID: String) -> Bool {
+ guard !self.isBusy else { return false }
+ self.selectedModelID = modelID
+ self.previewModelID = modelID
+ self.revision = UUID()
+ return true
+ }
+
+ mutating func begin() -> UUID? {
+ guard !self.isBusy else { return nil }
+ let token = UUID()
+ self.operationID = token
+ self.revision = UUID()
+ return token
+ }
+
+ mutating func finish(_ token: UUID) {
+ guard self.operationID == token else { return }
+ self.operationID = nil
+ self.revision = UUID()
+ }
+
+ func acceptsRead(_ revision: UUID) -> Bool {
+ !self.isBusy && self.revision == revision
+ }
+}
+
+/// Injectable transaction boundary used by the real update button and deterministic tests.
+/// Keep the mutation slot occupied until commit/rollback has finished, not just verification.
+enum PrivateAISettingsUpdateTransaction {
+ @MainActor
+ static func run<Token>(
+ update: () async throws -> Token,
+ verify: () async -> Bool,
+ commit: (Token) async -> Void,
+ rollback: (Token) async -> Void
+ ) async throws -> Bool {
+ let token = try await update()
+ do {
+ try Task.checkCancellation()
+ let verified = await verify()
+ try Task.checkCancellation()
+ if verified {
+ await commit(token)
+ } else {
+ await rollback(token)
+ }
+ return verified
+ } catch {
+ await rollback(token)
+ throw error
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/ProviderModelVerificationStore.swift b/Sources/Fluid/UI/AISettings/ProviderModelVerificationStore.swift
new file mode 100644
index 00000000..0ab9d2c7
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/ProviderModelVerificationStore.swift
@@ -0,0 +1,45 @@
+import CryptoKit
+import Foundation
+
+/// Optional successful model checks, separate from legacy provider connection status.
+/// Stores only hashes and timestamps, never API keys, URLs, or request contents.
+@MainActor
+final class ProviderModelVerificationStore {
+ static let defaultsKey = "ProviderModelVerificationsV1"
+ static let maximumEntries = 256
+ private let defaults: UserDefaults
+ private var successes: [String: Double]
+
+ init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ let stored = defaults.dictionary(forKey: Self.defaultsKey) as? [String: Double] ?? [:]
+ self.successes = Dictionary(uniqueKeysWithValues: stored
+ .filter { $0.key.count == 64 && $0.value.isFinite }
+ .sorted { $0.value > $1.value }
+ .prefix(Self.maximumEntries)
+ .map { ($0.key, $0.value) })
+ }
+
+ static func identity(providerID: String, baseURL: String, apiKey: String, model: String) -> String {
+ let fields = [providerID, baseURL, apiKey, model].map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ let data = (try? JSONEncoder().encode(fields)) ?? Data()
+ return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
+ }
+
+ func contains(_ identity: String) -> Bool { self.successes[identity] != nil }
+
+ func recordSuccess(_ identity: String, now: Date = Date()) {
+ self.successes[identity] = now.timeIntervalSince1970
+ while self.successes.count > Self.maximumEntries,
+ let oldest = self.successes.min(by: { $0.value < $1.value })?.key
+ {
+ self.successes.removeValue(forKey: oldest)
+ }
+ self.defaults.set(self.successes, forKey: Self.defaultsKey)
+ }
+
+ func remove(_ identity: String) {
+ guard self.successes.removeValue(forKey: identity) != nil else { return }
+ self.defaults.set(self.successes, forKey: Self.defaultsKey)
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/ProviderSetupDraft.swift b/Sources/Fluid/UI/AISettings/ProviderSetupDraft.swift
new file mode 100644
index 00000000..76e24152
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/ProviderSetupDraft.swift
@@ -0,0 +1,24 @@
+import Foundation
+
+/// A local form value, never a live settings binding. Cancel simply discards it.
+struct ProviderSetupDraft {
+ var providerID = ""
+ var name = ""
+ var baseURL = ""
+ var apiKey = ""
+ var model = ""
+
+ var trimmedName: String { self.name.trimmingCharacters(in: .whitespacesAndNewlines) }
+ var trimmedModel: String { self.model.trimmingCharacters(in: .whitespacesAndNewlines) }
+ var trimmedBaseURL: String { self.baseURL.trimmingCharacters(in: .whitespacesAndNewlines) }
+ var requiresAPIKey: Bool { !self.providerID.isEmpty && !["ollama", "lmstudio"].contains(self.providerID) }
+ var isValid: Bool {
+ guard !self.requiresAPIKey || !self.apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return false }
+ guard !self.trimmedName.isEmpty, let url = URL(string: self.trimmedBaseURL),
+ let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme),
+ let host = url.host, !host.isEmpty,
+ url.user == nil, url.password == nil
+ else { return false }
+ return true
+ }
+}
diff --git a/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift b/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift
index 5bb97825..c0efb3aa 100644
--- a/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift
+++ b/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift
@@ -46,7 +46,140 @@ extension AIEnhancementSettingsView {
// MARK: - AI Configuration Card
- var aiConfigurationCard: some View {
+ @ViewBuilder var aiConfigurationCard: some View {
+ if self.selectedConfigurationSection == .providers, PrivateAIProviderFeature.shared.isAvailable {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xl) {
+ FluidIntelligenceLiveSection(
+ controller: self.privateAIController,
+ backendID: self.settings.privateAIBackendPreference.rawValue,
+ isPrimary: self.primaryDefaultProviderID == PrivateAIProviderFeature.shared.providerID,
+ isVerified: self.isPrivateAIModelVerified(self.privateAIController.selectedPrivateAIModel),
+ makePrimary: { self.makePrimaryDefaultProvider(PrivateAIProviderFeature.shared.providerID, isPrivateAI: true) }
+ ) {
+ self.privateAIManagementSettings(isBusy: self.privateAIController.isBusy)
+ }
+ self.addedExternalProvidersSection
+ }
+ .frame(maxWidth: AppTheme.Metrics.Showcase.pageMaxWidth)
+ .frame(maxWidth: .infinity)
+ } else {
+ self.legacyAIConfigurationCard
+ }
+ }
+
+ private var addedExternalProvidersSection: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ HStack {
+ if !self.viewModel.cachedAddedProviderItems.isEmpty {
+ Text("Other providers").font(self.theme.typography.sectionTitle)
+ }
+ Spacer()
+ Button("Add Provider", systemImage: "plus") { self.showingAddProviderSheet = true }
+ .fluidGlassAction()
+ .disabled(self.viewModel.isFetchingModels || self.viewModel.isTestingConnection)
+ }
+ ForEach(self.viewModel.cachedAddedProviderItems) { provider in
+ let item = ProviderItem(id: provider.id, name: provider.name, isBuiltIn: provider.isBuiltIn)
+ let setupIssue = DictationDefaultProvider.setupIssue(
+ requiresAPIKey: !self.viewModel.isLocalEndpoint(self.providerBaseURL(for: item)),
+ hasAPIKey: !self.viewModel.providerAPIKey(for: provider.id).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ hasModel: !self.viewModel.selectedModel(for: provider.id).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ isVerified: self.viewModel.connectionStatus(for: provider.id) == .success,
+ verificationFailed: self.viewModel.connectionStatus(for: provider.id) == .failed
+ )
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ self.providerLogoView(for: item).frame(width: 30, height: 30)
+ Text(provider.name).font(self.theme.typography.bodySmallStrong)
+ Spacer()
+ if self.viewModel.connectionStatus(for: provider.id) == .testing {
+ Text("Verifying…")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ } else if let setupIssue {
+ Label(setupIssue, systemImage: "exclamationmark.circle")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(.red)
+ }
+ ProviderDefaultButton(
+ isCurrent: self.primaryDefaultProviderID == provider.id,
+ isEnabled: self.viewModel.canUseProviderWithoutVerification(provider.id)
+ && !self.viewModel.isFetchingModels && !self.viewModel.isTestingConnection
+ ) {
+ self.makePrimaryDefaultProvider(provider.id, isPrivateAI: false)
+ }
+ Button("Manage") {
+ self.viewModel.configureProvider(provider.id)
+ self.managedExternalProviderID = provider.id
+ }
+ .fluidGlassAction()
+ .disabled(self.viewModel.isFetchingModels || self.viewModel.isTestingConnection)
+ }
+ .padding(self.theme.metrics.spacing.lg)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg, style: .continuous))
+ }
+ }
+ .sheet(isPresented: self.$showingAddProviderSheet) {
+ AddProviderSheet(viewModel: self.viewModel) { id, name in
+ self.providerLogoView(for: ProviderItem(id: id, name: name, isBuiltIn: true))
+ }.appTheme(self.theme)
+ }
+ .sheet(isPresented: Binding(
+ get: { self.managedExternalProviderID != nil },
+ set: { if !$0 { self.closeExternalProviderManager() } }
+ )) {
+ self.externalProviderManager.appTheme(self.theme)
+ }
+ }
+
+ private func closeExternalProviderManager() {
+ guard !self.viewModel.isFetchingModels, !self.viewModel.isTestingConnection else { return }
+ if let providerID = self.managedExternalProviderID,
+ !self.viewModel.saveManagedProviderBeforeClosing(providerID)
+ { return }
+ self.viewModel.clearEditProviderDraft()
+ self.viewModel.showingAddModel = false
+ self.viewModel.newModelName = ""
+ self.viewModel.showingReasoningConfig = false
+ self.viewModel.finishConfiguringProvider()
+ self.managedExternalProviderID = nil
+ }
+
+ private var externalProviderManager: some View {
+ FluidManagementSheet(
+ title: self.viewModel.cachedProviderItems.first(where: { $0.id == self.managedExternalProviderID })?.name ?? "Provider",
+ subtitle: "Connection and models.",
+ symbol: "network",
+ dismissDisabled: self.viewModel.isFetchingModels || self.viewModel.isTestingConnection,
+ height: 520,
+ close: self.closeExternalProviderManager
+ ) {
+ if let provider = self.viewModel.cachedProviderItems.first(where: { $0.id == self.managedExternalProviderID }) {
+ let item = ProviderItem(id: provider.id, name: provider.name, isBuiltIn: provider.isBuiltIn)
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ self.providerDetailsSection(for: item, managementLayout: true)
+ .disabled(self.viewModel.isFetchingModels || self.viewModel.isTestingConnection)
+ }
+ }
+ }
+ .interactiveDismissDisabled()
+ .alert("Remove provider?", isPresented: self.$showingRemoveProviderConfirmation) {
+ Button("Cancel", role: .cancel) {}
+ Button("Remove", role: .destructive) {
+ guard self.viewModel.selectedProviderID == self.managedExternalProviderID,
+ self.viewModel.deleteCurrentProvider()
+ else { return }
+ self.expandedProviderID = nil
+ self.closeExternalProviderManager()
+ }
+ } message: {
+ Text("This removes its saved API key and model setup, and clears any default or prompt assignments using it. Your prompts and shortcuts are kept. You can add the provider again later.")
+ }
+ .onChange(of: self.viewModel.cachedProviderItems.map(\.id)) { _, ids in
+ if let id = self.managedExternalProviderID, !ids.contains(id) { self.closeExternalProviderManager() }
+ }
+ }
+
+ private var legacyAIConfigurationCard: some View {
VStack(spacing: 14) {
ThemedCard(style: .prominent, hoverEffect: false) {
VStack(alignment: .leading, spacing: 16) {
@@ -265,7 +398,9 @@ extension AIEnhancementSettingsView {
var providerStepContent: some View {
VStack(alignment: .leading, spacing: 16) {
- self.verifiedProvidersSection
+ if !PrivateAIProviderFeature.shared.isAvailable || !self.verifiedProviderItems.isEmpty {
+ self.verifiedProvidersSection
+ }
self.allProvidersSection
@@ -421,13 +556,17 @@ extension AIEnhancementSettingsView {
// Use cached provider items from ViewModel for scroll performance
private var verifiedProviderItems: [ProviderItem] {
- self.viewModel.cachedVerifiedProviderItems.map {
+ self.viewModel.cachedVerifiedProviderItems.filter {
+ !PrivateAIProviderFeature.shared.isAvailable || $0.id != PrivateAIProviderFeature.shared.providerID
+ }.map {
ProviderItem(id: $0.id, name: $0.name, isBuiltIn: $0.isBuiltIn)
}
}
private var unverifiedProviderItems: [ProviderItem] {
- self.viewModel.cachedUnverifiedProviderItems.map {
+ self.viewModel.cachedUnverifiedProviderItems.filter {
+ !PrivateAIProviderFeature.shared.isAvailable || $0.id != PrivateAIProviderFeature.shared.providerID
+ }.map {
ProviderItem(id: $0.id, name: $0.name, isBuiltIn: $0.isBuiltIn)
}
}
@@ -584,19 +723,19 @@ extension AIEnhancementSettingsView {
}
private var privateAIRuntimeSection: some View {
- let model = self.selectedPrivateAIModel
+ let model = self.privateAIController.selectedPrivateAIModel
let status = self.privateAIModelStatus(for: model)
let isInstalled = PrivateAIIntegrationService.isModelInstalled(model)
- let isDownloading = self.privateAILoadState.isDownloading(model.id)
- let downloadProgress = self.privateAILoadState.downloadProgress(for: model.id)
- let isLoading = self.privateAILoadState.isLoading(model.id)
- let isLoaded = self.privateAILoadState.isLoaded(model.id)
- let hasLoadFailure = self.privateAILoadState.failureMessage(for: model.id) != nil
+ let isDownloading = self.privateAIController.privateAILoadState.isDownloading(model.id)
+ let downloadProgress = self.privateAIController.privateAILoadState.downloadProgress(for: model.id)
+ let isLoading = self.privateAIController.privateAILoadState.isLoading(model.id)
+ let isLoaded = self.privateAIController.privateAILoadState.isLoaded(model.id)
+ let hasLoadFailure = self.privateAIController.privateAILoadState.failureMessage(for: model.id) != nil
let isVerified = self.isPrivateAIModelVerified(model)
let isTesting = self.viewModel.isTestingConnection && self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID
- let isBusy = isDownloading || isLoading || isTesting
- let hasUpdate = isInstalled && self.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable
- let canVerify = isInstalled && (!isVerified || hasLoadFailure) && !self.privateAISelectedModelID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ let isBusy = self.privateAIController.isBusy || isDownloading || isLoading || isTesting
+ let hasUpdate = isInstalled && self.privateAIController.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable
+ let canVerify = isInstalled && (!isVerified || hasLoadFailure) && !self.privateAIController.privateAISelectedModelID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
return VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 8) {
@@ -615,7 +754,7 @@ extension AIEnhancementSettingsView {
)
self.companionIconButton(systemName: "folder", help: "Open downloaded model folder") {
- self.revealPrivateAIModelFolder()
+ self.privateAIController.revealPrivateAIModelFolder()
}
}
@@ -655,7 +794,7 @@ extension AIEnhancementSettingsView {
if !isInstalled {
if model.canDownload {
- Button(action: { self.downloadPrivateAIModel(model) }) {
+ Button(action: { self.privateAIController.downloadPrivateAIModel(model) }) {
HStack(spacing: 6) {
if isDownloading {
ProgressView()
@@ -682,7 +821,7 @@ extension AIEnhancementSettingsView {
.foregroundStyle(.secondary)
}
} else if hasUpdate {
- Button(action: { self.updatePrivateAIModel(model) }) {
+ Button(action: { self.privateAIController.updatePrivateAIModel(model) }) {
HStack(spacing: 6) {
if isDownloading {
ProgressView()
@@ -700,7 +839,7 @@ extension AIEnhancementSettingsView {
.fluidButton(.accent, size: .small)
.disabled(isBusy)
} else if canVerify {
- Button(action: { self.verifyPrivateAIConnection(model) }) {
+ Button(action: { self.privateAIController.verifyPrivateAIConnection(model) }) {
HStack(spacing: 6) {
if isTesting {
ProgressView()
@@ -855,34 +994,14 @@ extension AIEnhancementSettingsView {
private var privateAIPrefixCacheBinding: Binding<Bool> {
Binding(
get: { self.settings.privateAIPrefixKVCacheEnabled },
- set: { enabled in
- guard self.settings.privateAIPrefixKVCacheEnabled != enabled else { return }
- self.settings.privateAIPrefixKVCacheEnabled = enabled
- self.privateAILoadState = .idle
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(
- reason: enabled ? "prefix cache enabled" : "prefix cache disabled"
- )
- self.viewModel.refreshProviderItems()
- }
- }
+ set: { self.privateAIController.setPrefixCacheEnabled($0) }
)
}
private var privateAIBoostBinding: Binding<Bool> {
Binding(
get: { self.settings.privateAIBoostEnabled },
- set: { enabled in
- guard self.settings.privateAIBoostEnabled != enabled else { return }
- self.settings.privateAIBoostEnabled = enabled
- self.privateAILoadState = .idle
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(
- reason: enabled ? "Fluid-1 Boost enabled" : "Fluid-1 Boost disabled"
- )
- self.viewModel.refreshProviderItems()
- }
- }
+ set: { self.privateAIController.setBoostEnabled($0) }
)
}
@@ -890,7 +1009,7 @@ extension AIEnhancementSettingsView {
Binding(
get: { self.settings.privateAIBackendPreference },
set: { preference in
- self.setPrivateAIBackendPreference(preference)
+ self.privateAIController.setPrivateAIBackendPreference(preference)
}
)
}
@@ -909,208 +1028,19 @@ extension AIEnhancementSettingsView {
private var privateAIContextTokenLimitBinding: Binding<Int> {
Binding(
get: { self.settings.privateAIContextTokenLimit },
- set: { value in
- let clamped = SettingsStore.clampPrivateAIContextTokenLimit(value)
- guard self.settings.privateAIContextTokenLimit != clamped else { return }
- self.settings.privateAIContextTokenLimit = clamped
- self.privateAILoadState = .idle
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(
- reason: "Fluid Intelligence context changed"
- )
- self.viewModel.refreshProviderItems()
- }
- }
+ set: { self.privateAIController.setContextTokenLimit($0) }
)
}
private var privateAIModelBinding: Binding<String> {
Binding(
- get: { self.privateAISelectedModelID },
- set: { self.persistPrivateAIModelSelection($0) }
+ get: { self.privateAIController.privateAISelectedModelID },
+ set: { self.privateAIController.persistPrivateAIModelSelection($0) }
)
}
- private func refreshPrivateAIProviderModels() {
- let providerKey = self.viewModel.providerKey(for: PrivateAIProviderFeature.shared.providerID)
- let models = PrivateAIModelRegistry.modelIDs()
- let selected = PrivateAIModelRegistry.canonicalModelID(for: self.privateAISelectedModelID) ?? PrivateAIModelRegistry.defaultModel.id
-
- self.privateAISelectedModelID = selected
- self.viewModel.availableModelsByProvider[providerKey] = models
- self.viewModel.selectedModelByProvider[providerKey] = selected
- self.viewModel.settings.availableModelsByProvider = self.viewModel.availableModelsByProvider
- self.viewModel.settings.selectedModelByProvider = self.viewModel.selectedModelByProvider
-
- if self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID {
- self.viewModel.availableModels = models
- self.viewModel.selectedModel = selected
- }
-
- self.refreshPrivateAILoadState()
- self.refreshPrivateAIModelUpdateStatus(self.selectedPrivateAIModel)
- self.viewModel.refreshProviderItems()
- }
-
- func refreshPrivateAIModelUpdateStatus(_ model: PrivateAIRegisteredModel) {
- Task { @MainActor in
- let status = await PrivateAIIntegrationService.modelUpdateStatus(model)
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAIModelUpdateStatusByID[model.id] = status
- }
- }
-
- private func downloadPrivateAIModel(_ model: PrivateAIRegisteredModel) {
- guard model.canDownload else {
- self.privateAILoadState = .failed(modelID: model.id, message: "Download URL is not configured yet.")
- return
- }
-
- guard !self.privateAILoadState.isDownloading(model.id) else { return }
-
- self.privateAILoadState = .downloading(
- modelID: model.id,
- progress: PrivateAIModelDownloadProgress(initialExpectedBytes: model.artifact.byteCount)
- )
- Task { @MainActor in
- do {
- DebugLogger.shared.info(
- "Private provider download button pressed model=\(model.id)",
- source: "AISettingsView"
- )
- _ = try await PrivateAIIntegrationService.prepareModel(model) { progress in
- await MainActor.run {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .downloading(
- modelID: model.id,
- progress: progress.withFallbackExpectedBytes(model.artifact.byteCount)
- )
- }
- }
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .loading(modelID: model.id)
- let start = ContinuousClock.now
- let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
- let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
- guard self.privateAISelectedModelID == model.id else { return }
- if verified {
- self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
- } else {
- let message = self.viewModel.connectionErrorMessage.isEmpty
- ? "Model downloaded, but verification failed."
- : self.viewModel.connectionErrorMessage
- self.privateAILoadState = .failed(modelID: model.id, message: message)
- }
- } catch {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .failed(
- modelID: model.id,
- message: Self.errorMessage(for: error)
- )
- }
- self.viewModel.refreshProviderItems()
- }
- }
-
- private func updatePrivateAIModel(_ model: PrivateAIRegisteredModel) {
- guard self.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable,
- !self.privateAILoadState.isDownloading(model.id)
- else { return }
-
- let wasPreviouslyVerified = PrivateAIProviderPromptFormat.verifiedModelID(settings: self.settings) == model.id
-
- self.privateAILoadState = .downloading(
- modelID: model.id,
- progress: PrivateAIModelDownloadProgress(initialExpectedBytes: model.artifact.byteCount)
- )
- Task { @MainActor in
- var updateToken: PrivateAIModelUpdateToken?
- do {
- updateToken = try await PrivateAIIntegrationService.updateModel(model) { progress in
- await MainActor.run {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .downloading(
- modelID: model.id,
- progress: progress.withFallbackExpectedBytes(model.artifact.byteCount)
- )
- }
- }
- guard self.privateAISelectedModelID == model.id else {
- if let updateToken {
- await PrivateAIIntegrationService.rollbackModelUpdate(updateToken)
- }
- return
- }
-
- self.privateAILoadState = .loading(modelID: model.id)
- let start = ContinuousClock.now
- let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
- let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
- guard self.privateAISelectedModelID == model.id else {
- if let updateToken {
- await PrivateAIIntegrationService.rollbackModelUpdate(updateToken)
- }
- return
- }
-
- if verified, let updateToken {
- await PrivateAIIntegrationService.commitModelUpdate(updateToken)
- self.privateAILoadState = .loaded(
- modelID: model.id,
- latencyMilliseconds: latencyMilliseconds
- )
- } else {
- if let updateToken {
- await PrivateAIIntegrationService.rollbackModelUpdate(updateToken)
- }
- if wasPreviouslyVerified {
- self.viewModel.updateConnectionStatus(.success, for: PrivateAIProviderFeature.shared.providerID)
- }
- let detail = self.viewModel.connectionErrorMessage.isEmpty
- ? "The new model failed verification. The previous model is still active."
- : "The new model failed verification. The previous model is still active. \(self.viewModel.connectionErrorMessage)"
- self.privateAILoadState = .failed(modelID: model.id, message: detail)
- }
- } catch {
- if let updateToken {
- await PrivateAIIntegrationService.rollbackModelUpdate(updateToken)
- }
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .failed(
- modelID: model.id,
- message: "Update failed. The previous model is still active. \(Self.errorMessage(for: error))"
- )
- }
- self.refreshPrivateAIModelUpdateStatus(model)
- self.viewModel.refreshProviderItems()
- }
- }
-
- private func verifyPrivateAIConnection(_ model: PrivateAIRegisteredModel) {
- self.privateAILoadState = .loading(modelID: model.id)
- Task { @MainActor in
- let start = ContinuousClock.now
- let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
- let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
- guard self.privateAISelectedModelID == model.id else { return }
- if verified {
- self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
- } else {
- let message = self.viewModel.connectionErrorMessage.isEmpty
- ? "Model verification failed."
- : self.viewModel.connectionErrorMessage
- self.privateAILoadState = .failed(modelID: model.id, message: message)
- }
- self.viewModel.refreshProviderItems()
- }
- }
-
- var selectedPrivateAIModel: PrivateAIRegisteredModel {
- PrivateAIModelRegistry.model(id: self.privateAISelectedModelID) ?? PrivateAIModelRegistry.defaultModel
- }
-
private func privateAIModelDisplayName(_ modelID: String) -> String {
- PrivateAIModelRegistry.model(id: modelID)?.displayName ?? modelID
+ ModelDisplayName.forID(modelID)
}
private func isPrivateAIModelVerified(_ model: PrivateAIRegisteredModel) -> Bool {
@@ -1120,28 +1050,28 @@ extension AIEnhancementSettingsView {
private func privateAIModelStatus(
for model: PrivateAIRegisteredModel
) -> PrivateAIProviderModelStatus {
- if self.privateAILoadState.isDownloading(model.id) {
+ if self.privateAIController.privateAILoadState.isDownloading(model.id) {
return PrivateAIProviderModelStatus(
detail: "Downloading model.",
color: self.theme.palette.accent
)
}
- if self.privateAILoadState.isLoading(model.id) {
+ if self.privateAIController.privateAILoadState.isLoading(model.id) {
return PrivateAIProviderModelStatus(
detail: "Loading...",
color: self.theme.palette.accent
)
}
- if self.privateAILoadState.isLoaded(model.id) {
+ if self.privateAIController.privateAILoadState.isLoaded(model.id) {
return PrivateAIProviderModelStatus(
detail: "For dictation only.",
color: Color.fluidGreen
)
}
- if let message = self.privateAILoadState.failureMessage(for: model.id) {
+ if let message = self.privateAIController.privateAILoadState.failureMessage(for: model.id) {
return PrivateAIProviderModelStatus(
detail: message,
color: .red
@@ -1185,107 +1115,6 @@ extension AIEnhancementSettingsView {
)
}
- private func revealPrivateAIModelFolder() {
- let directoryURL = PrivateAIIntegrationService.modelDirectoryURL
- do {
- try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
- NSWorkspace.shared.open(directoryURL)
- } catch {
- DebugLogger.shared.error(
- "Failed to open Private AI Provider models folder: \(error.localizedDescription)",
- source: "AISettingsView"
- )
- }
- }
-
- func refreshPrivateAILoadState() {
- Task { @MainActor in
- guard let loaded = await PrivateAIIntegrationService.shared.loadedModelState(),
- loaded.state == .ready
- else {
- self.privateAILoadState = .idle
- return
- }
-
- self.privateAILoadState = .loaded(modelID: loaded.modelID, latencyMilliseconds: nil)
- }
- }
-
- private func loadPrivateAIModel(_ model: PrivateAIRegisteredModel) {
- guard PrivateAIIntegrationService.isModelInstalled(model) else {
- self.privateAILoadState = .failed(modelID: model.id, message: "Model file is not installed.")
- return
- }
-
- self.privateAILoadState = .loading(modelID: model.id)
- Task { @MainActor in
- do {
- let start = ContinuousClock.now
- let status = try await PrivateAIIntegrationService.shared.loadModel(model)
- let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
- guard self.privateAISelectedModelID == model.id else { return }
- switch status.state {
- case .ready:
- self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
- default:
- self.privateAILoadState = .failed(
- modelID: model.id,
- message: status.message ?? "Model did not report ready."
- )
- }
- } catch {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .failed(
- modelID: model.id,
- message: Self.errorMessage(for: error)
- )
- }
- self.viewModel.refreshProviderItems()
- }
- }
-
- private func resetPrivateAIVerification(for model: PrivateAIRegisteredModel) {
- self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
- self.privateAILoadState = .idle
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(reason: "Fluid Intelligence verification reset")
- if PrivateAIIntegrationService.isModelInstalled(model) {
- self.privateAILoadState = .idle
- }
- self.viewModel.refreshProviderItems()
- }
- }
-
- private func deletePrivateAIModel(_ model: PrivateAIRegisteredModel) {
- guard PrivateAIIntegrationService.canRemoveInstalledModel(model) else { return }
- self.privateAILoadState = .loading(modelID: model.id)
- Task { @MainActor in
- do {
- try await PrivateAIIntegrationService.shared.unloadAndRemoveInstalledModel(
- model,
- reason: "settings-delete"
- )
- self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
- if self.privateAISelectedModelID == model.id {
- self.privateAILoadState = .idle
- }
- self.viewModel.refreshProviderItems()
- } catch {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .failed(modelID: model.id, message: Self.errorMessage(for: error))
- }
- }
- }
-
- private static func errorMessage(for error: Error) -> String {
- if let localizedError = error as? LocalizedError,
- let description = localizedError.errorDescription
- {
- return description
- }
- return String(describing: error)
- }
-
private static func downloadButtonText(progress: PrivateAIModelDownloadProgress?) -> String {
PrivateAIModelDownloadProgressText.buttonTitle(for: progress)
}
@@ -1294,64 +1123,7 @@ extension AIEnhancementSettingsView {
PrivateAIModelDownloadProgressText.detailText(for: progress)
}
- private static func elapsedMilliseconds(since start: ContinuousClock.Instant) -> Int {
- let elapsed = start.duration(to: ContinuousClock.now)
- return Int(elapsed.components.seconds * 1000) + Int(elapsed.components.attoseconds / 1_000_000_000_000_000)
- }
-
- private func persistPrivateAIModelSelection(_ value: String) {
- let model = PrivateAIModelRegistry.model(id: value) ?? PrivateAIModelRegistry.defaultModel
- let providerKey = self.viewModel.providerKey(for: PrivateAIProviderFeature.shared.providerID)
- let models = PrivateAIModelRegistry.modelIDs()
-
- self.privateAISelectedModelID = model.id
- UserDefaults.standard.set(model.id, forKey: PrivateAIIntegrationService.selectedModelDefaultsKey)
- UserDefaults.standard.removeObject(forKey: PrivateAIIntegrationService.localModelPathDefaultsKey)
-
- self.viewModel.availableModelsByProvider[providerKey] = models
- self.viewModel.selectedModelByProvider[providerKey] = model.id
- self.viewModel.settings.availableModelsByProvider = self.viewModel.availableModelsByProvider
- self.viewModel.settings.selectedModelByProvider = self.viewModel.selectedModelByProvider
-
- if self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID {
- self.viewModel.availableModels = models
- self.viewModel.selectedModel = model.id
- }
- self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
- self.refreshPrivateAIModelUpdateStatus(model)
- self.viewModel.refreshProviderItems()
- if PrivateAIIntegrationService.isModelInstalled(model) {
- self.loadPrivateAIModel(model)
- } else {
- self.privateAILoadState = .idle
- }
- }
-
- private func setPrivateAIBackendPreference(_ preference: SettingsStore.PrivateAIBackendPreference) {
- guard self.settings.privateAIBackendPreference != preference else { return }
- let modelID = self.privateAISelectedModelID
-
- self.settings.privateAIBackendPreference = preference
- UserDefaults.standard.removeObject(forKey: PrivateAIIntegrationService.localModelPathDefaultsKey)
- self.privateAILoadState = .idle
- self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
-
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(
- reason: "Fluid Intelligence backend changed to \(preference.displayName)"
- )
- guard self.privateAISelectedModelID == modelID else { return }
- let model = self.selectedPrivateAIModel
- if PrivateAIIntegrationService.isModelInstalled(model) {
- self.verifyPrivateAIConnection(model)
- } else {
- self.privateAILoadState = .idle
- self.viewModel.refreshProviderItems()
- }
- }
- }
-
- private func providerDetailsSection(for item: ProviderItem) -> AnyView {
+ private func providerDetailsSection(for item: ProviderItem, managementLayout: Bool = false) -> AnyView {
let providerKey = self.viewModel.providerKey(for: item.id)
let isCustom = !ModelRepository.shared.isBuiltIn(item.id)
let baseURL = self.viewModel.openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -1364,6 +1136,7 @@ extension AIEnhancementSettingsView {
let hasName = isCustom ? !(self.viewModel.savedProviders.first { $0.id == item.id }?.name ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty : true
let canFetchModels = hasName && (isLocal ? !baseURL.isEmpty : (hasAPIKey && !baseURL.isEmpty))
let canVerify = hasModels && !self.viewModel.selectedModel.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && canFetchModels
+ let isModelVerified = self.viewModel.isModelVerified(for: item.id)
let apiKeyBinding = Binding(
get: { self.viewModel.providerAPIKey(for: item.id) },
set: { self.viewModel.updateProviderAPIKey($0, for: item.id, persistEmptyValue: true) }
@@ -1381,7 +1154,7 @@ extension AIEnhancementSettingsView {
}
)
- return AnyView(VStack(alignment: .leading, spacing: 10) {
+ return AnyView(VStack(alignment: .leading, spacing: managementLayout ? 20 : 10) {
Group {
if isCustom {
VStack(alignment: .leading, spacing: 8) {
@@ -1419,64 +1192,110 @@ extension AIEnhancementSettingsView {
.foregroundStyle(.secondary)
HStack(alignment: .center, spacing: 8) {
SecureField("Enter API key", text: apiKeyBinding)
- .textFieldStyle(.roundedBorder)
+ .textFieldStyle(.plain)
.font(.system(size: 13))
- .frame(maxWidth: 200)
+ .padding(.horizontal, managementLayout ? 12 : 6)
+ .frame(height: AISettingsLayout.providerRowControlHeight)
+ .frame(maxWidth: managementLayout ? .infinity : 200)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ .overlay(RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm).strokeBorder(self.theme.palette.cardBorder))
.onTapGesture {
self.viewModel.ensureKeychainAccessForAPIKeyEdit()
}
if let websiteInfo = ModelRepository.shared.providerWebsiteURL(for: item.id),
let url = URL(string: websiteInfo.url)
{
- Button(action: { NSWorkspace.shared.open(url) }) {
- HStack(spacing: 4) {
- Image(systemName: websiteInfo.label.contains("Guide") ? "book.fill" : "key.fill")
- .font(.system(size: 10))
- Text(websiteInfo.label)
- .font(.system(size: 11, weight: .medium))
+ if managementLayout {
+ Button(websiteInfo.label, systemImage: "key") { NSWorkspace.shared.open(url) }
+ .buttonStyle(.plain)
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.theme.palette.accent)
+ .frame(width: 128, height: AISettingsLayout.providerRowControlHeight)
+ } else {
+ Button(action: { NSWorkspace.shared.open(url) }) {
+ HStack(spacing: 4) {
+ Image(systemName: websiteInfo.label.contains("Guide") ? "book.fill" : "key.fill")
+ .font(.system(size: 10))
+ Text(websiteInfo.label)
+ .font(.system(size: 11, weight: .medium))
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 5)
+ .background(
+ RoundedRectangle(cornerRadius: 6, style: .continuous)
+ .fill(self.theme.palette.accent)
+ )
+ .foregroundStyle(.white)
}
- .padding(.horizontal, 10)
- .padding(.vertical, 5)
- .background(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .fill(self.theme.palette.accent)
- )
- .foregroundStyle(.white)
+ .buttonStyle(.plain)
}
- .buttonStyle(.plain)
}
}
}
- HStack(spacing: 8) {
+ (managementLayout ? AnyLayout(VStackLayout(alignment: .leading, spacing: 6)) : AnyLayout(HStackLayout(spacing: 8))) {
Text("Model")
.font(.system(size: 12, weight: .medium))
.foregroundStyle(.secondary)
- .frame(width: 50, alignment: .leading)
+ .frame(width: managementLayout ? nil : 50, alignment: .leading)
- SearchableModelPicker(
- models: models,
- selectedModel: self.modelBinding(for: item.id),
- selectionEnabled: hasModels,
- controlWidth: 180,
- controlHeight: AISettingsLayout.providerRowControlHeight
- )
+ HStack(spacing: 8) {
+ SearchableModelPicker(
+ models: models,
+ selectedModel: self.modelBinding(for: item.id),
+ selectionEnabled: hasModels,
+ controlWidth: managementLayout ? 720 - 56 - 2 * AISettingsLayout.providerRowControlHeight - 32 : 180,
+ controlHeight: AISettingsLayout.providerRowControlHeight
+ )
- self.companionIconButton(
- isRefreshing: isRefreshing,
- disabled: isRefreshing || !canFetchModels,
- opacity: canFetchModels ? 1 : 0.45,
- help: "Refresh model list"
- ) {
- self.viewModel.configureProvider(item.id)
- Task { await self.viewModel.fetchModelsForCurrentProvider() }
+ self.companionIconButton(
+ isRefreshing: isRefreshing,
+ disabled: isRefreshing || !canFetchModels,
+ opacity: canFetchModels ? 1 : 0.45,
+ help: "Refresh model list"
+ ) {
+ self.viewModel.configureProvider(item.id)
+ Task { await self.viewModel.fetchModelsForCurrentProvider() }
+ }
+ if managementLayout {
+ self.companionIconButton(systemName: "plus", help: "Add model") {
+ self.viewModel.newModelName = ""
+ self.viewModel.showingAddModel.toggle()
+ }
+ .accessibilityLabel("Add model")
+ }
}
}
- HStack(spacing: 8) {
- Color.clear
- .frame(width: 50, alignment: .leading)
- self.reasoningButton(for: item.id)
+ if managementLayout, self.viewModel.showingAddModel {
+ self.addModelSection
+ }
+
+ if managementLayout {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Reasoning")
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ HStack(spacing: 8) {
+ Text(self.viewModel.isReasoningEnabled(for: item.id) ? "Enabled" : "Not enabled")
+ .font(self.theme.typography.body)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ Spacer()
+ Button("Configure…", systemImage: "gearshape") {
+ self.viewModel.configureProvider(item.id)
+ self.viewModel.openReasoningConfig()
+ }
+ .fluidButton(.compact, size: .small)
+ }
+ .padding(10)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ .overlay(RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm).strokeBorder(self.theme.palette.cardBorder))
+ }
+ } else {
+ HStack(spacing: 8) {
+ Color.clear.frame(width: 50, alignment: .leading)
+ self.reasoningButton(for: item.id)
+ }
}
if self.viewModel.showingReasoningConfig && self.viewModel.selectedProviderID == item.id {
@@ -1506,24 +1325,34 @@ extension AIEnhancementSettingsView {
}
if canVerify {
- Button(action: {
- Task { await self.viewModel.testAPIConnection() }
- }) {
- HStack(spacing: 6) {
- if self.viewModel.isTestingConnection {
- ProgressView()
- .controlSize(.mini)
- .fixedSize()
- } else {
- Image(systemName: "checkmark.shield")
- .font(.system(size: 12))
+ if isModelVerified {
+ Label("Model verified", systemImage: "checkmark.circle.fill")
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(Color.fluidGreen)
+ .frame(maxWidth: managementLayout ? .infinity : nil, alignment: .trailing)
+ .help("Successfully tested \(ModelDisplayName.forID(self.viewModel.selectedModel(for: item.id))) with this endpoint and API key.")
+ } else {
+ Button(action: {
+ Task { await self.viewModel.testAPIConnection() }
+ }) {
+ HStack(spacing: 6) {
+ if self.viewModel.isTestingConnection {
+ ProgressView()
+ .controlSize(.mini)
+ .fixedSize()
+ } else {
+ Image(systemName: "checkmark.shield")
+ .font(.system(size: 12))
+ }
+ Text(self.viewModel.isTestingConnection ? "Verifying…" : "Verify model")
+ .font(self.theme.typography.bodyStrong)
}
- Text(self.viewModel.isTestingConnection ? "Verifying..." : "Verify Connection")
- .font(.system(size: 13, weight: .semibold))
}
+ .fluidGlassAction(prominent: true)
+ .disabled(self.viewModel.isTestingConnection)
+ .help("Optional: send a small request to test this model. You can use it without running this check.")
+ .frame(maxWidth: managementLayout ? .infinity : nil, alignment: .trailing)
}
- .fluidButton(.accent, size: .small)
- .disabled(self.viewModel.isTestingConnection)
} else {
HStack(spacing: 6) {
Image(systemName: "info.circle")
@@ -1534,21 +1363,28 @@ extension AIEnhancementSettingsView {
.foregroundStyle(.secondary)
}
- if isCustom {
+ if isCustom || managementLayout {
Divider()
.background(self.theme.palette.separator.opacity(0.5))
Button(role: .destructive) {
- self.viewModel.deleteCurrentProvider()
- self.expandedProviderID = nil
+ if managementLayout {
+ self.showingRemoveProviderConfirmation = true
+ } else if self.viewModel.deleteCurrentProvider() {
+ self.expandedProviderID = nil
+ }
} label: {
HStack(spacing: 6) {
Image(systemName: "trash")
- Text("Delete Provider")
+ Text("Remove provider")
}
- .font(.caption)
+ .font(self.theme.typography.bodyStrong)
}
- .fluidCompactButton(foreground: .red, borderColor: .red.opacity(0.6))
+ .fluidGlassAction()
+ .foregroundStyle(.red)
+ .tint(.red)
+ .disabled(self.viewModel.isFetchingModels || self.viewModel.isTestingConnection)
+ .frame(maxWidth: .infinity, alignment: .trailing)
}
}
})
@@ -1650,17 +1486,17 @@ extension AIEnhancementSettingsView {
let isDefaultProvider = isPrivateAIProvider
? primaryPromptSelection == .privateAI
: primaryPromptSelection == .default && item.id == self.settings.selectedProviderID
- let fluidModel = self.selectedPrivateAIModel
+ let fluidModel = self.privateAIController.selectedPrivateAIModel
let fluidStatus = self.privateAIModelStatus(for: fluidModel)
let isFluidInstalled = PrivateAIIntegrationService.isModelInstalled(fluidModel)
- let isFluidDownloading = self.privateAILoadState.isDownloading(fluidModel.id)
- let fluidDownloadProgress = self.privateAILoadState.downloadProgress(for: fluidModel.id)
- let isFluidLoading = self.privateAILoadState.isLoading(fluidModel.id)
- let hasFluidLoadFailure = self.privateAILoadState.failureMessage(for: fluidModel.id) != nil
- let hasFluidUpdate = self.privateAIModelUpdateStatusByID[fluidModel.id]?.state == .updateAvailable
+ let isFluidDownloading = self.privateAIController.privateAILoadState.isDownloading(fluidModel.id)
+ let fluidDownloadProgress = self.privateAIController.privateAILoadState.downloadProgress(for: fluidModel.id)
+ let isFluidLoading = self.privateAIController.privateAILoadState.isLoading(fluidModel.id)
+ let hasFluidLoadFailure = self.privateAIController.privateAILoadState.failureMessage(for: fluidModel.id) != nil
+ let hasFluidUpdate = self.privateAIController.privateAIModelUpdateStatusByID[fluidModel.id]?.state == .updateAvailable
let isFluidVerified = self.isPrivateAIModelVerified(fluidModel)
let isFluidTesting = self.viewModel.isTestingConnection && self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID
- let isFluidBusy = isFluidDownloading || isFluidLoading || isFluidTesting
+ let isFluidBusy = self.privateAIController.isBusy || isFluidDownloading || isFluidLoading || isFluidTesting
let isRefreshing = self.viewModel.isFetchingModels && self.viewModel.selectedProviderID == item.id
let baseURL = self.providerBaseURL(for: item).trimmingCharacters(in: .whitespacesAndNewlines)
let isLocal = self.viewModel.isLocalEndpoint(baseURL)
@@ -1727,7 +1563,7 @@ extension AIEnhancementSettingsView {
)
self.companionIconButton(systemName: "folder", help: "Open downloaded model folder") {
- self.revealPrivateAIModelFolder()
+ self.privateAIController.revealPrivateAIModelFolder()
}
.frame(width: iconColumnWidth, height: AISettingsLayout.providerRowControlHeight)
@@ -1736,7 +1572,7 @@ extension AIEnhancementSettingsView {
systemName: "arrow.down.circle",
help: "Update and verify model"
) {
- self.updatePrivateAIModel(fluidModel)
+ self.privateAIController.updatePrivateAIModel(fluidModel)
}
.disabled(isFluidBusy)
.frame(width: iconColumnWidth, height: AISettingsLayout.providerRowControlHeight)
@@ -1987,12 +1823,29 @@ extension AIEnhancementSettingsView {
self.viewModel.connectionStatus = self.viewModel.connectionStatus(for: providerID)
}
+ // Match the main shortcut's routing without reading API keys or resolving an
+ // app-specific override in the view. Merely opening Manage never selects it.
+ private var primaryDefaultProviderID: String {
+ let selection = self.viewModel.dictationPromptSelection(for: .primary)
+ return DictationDefaultProvider.providerID(
+ selection: selection,
+ configuration: self.settings.dictationPromptConfiguration(for: selection),
+ selectedProviderID: self.settings.selectedProviderID,
+ privateProviderID: PrivateAIProviderFeature.shared.providerID
+ )
+ }
+
private func makePrimaryDefaultProvider(_ providerID: String, isPrivateAI: Bool) {
+ guard providerID != self.primaryDefaultProviderID,
+ !self.viewModel.isFetchingModels, !self.viewModel.isTestingConnection else { return }
if isPrivateAI {
+ guard !self.privateAIController.isBusy, self.viewModel.isPrivateAIPromptAvailable() else { return }
self.viewModel.setDictationPromptSelection(.privateAI, for: .primary)
return
}
+ guard self.viewModel.canUseProviderWithoutVerification(providerID),
+ self.viewModel.saveManagedProviderAPIKeyIfNeeded(providerID) else { return }
self.activateProvider(providerID)
var defaultConfiguration = self.settings.dictationPromptConfiguration(for: .default)
@@ -2070,20 +1923,56 @@ extension AIEnhancementSettingsView {
ModelRepository.shared.builtInProvidersList()
}
+ private func privateAIManagementSettings(
+ isBusy: Bool
+ ) -> some View {
+ VStack(alignment: .leading, spacing: 20) {
+ FluidManagementGroup(title: "Performance") {
+ Group {
+ VStack(alignment: .leading, spacing: 20) {
+ FluidManagementRow(title: "Backend", detail: self.settings.privateAIBackendPreference.detail) {
+ self.privateAIBackendPicker(isBusy: isBusy).frame(width: 200)
+ }
+ Divider()
+ FluidManagementRow(title: "Dictation window", detail: "\(self.privateAIContextCueText). Longer windows use more memory.") {
+ self.privateAIContextControl(isBusy: isBusy)
+ }
+ Divider()
+ FluidManagementRow(title: "Faster first result", detail: "Keep the model ready between dictations.") {
+ Toggle("Faster first result", isOn: self.privateAIPrefixCacheBinding)
+ .labelsHidden().toggleStyle(.switch).disabled(isBusy)
+ }
+ if self.privateAIShowsBoostRow {
+ Divider()
+ FluidManagementRow(title: "Faster results", detail: "Extra local acceleration. Uses more memory.") {
+ Toggle("Faster results", isOn: self.privateAIBoostBinding)
+ .labelsHidden().toggleStyle(.switch).disabled(isBusy)
+ }
+ }
+ }
+ .padding(.top, 16)
+ }
+ .font(self.theme.typography.bodyStrong)
+ }
+ }
+ }
+
func privateAIEditProviderSection(
model: PrivateAIRegisteredModel,
isInstalled: Bool,
isBusy: Bool,
- isVerified: Bool
+ isVerified: Bool,
+ removalAllowed: Bool? = nil,
+ onDone: (() -> Void)? = nil
) -> some View {
- let canDelete = isInstalled && PrivateAIIntegrationService.canRemoveInstalledModel(model)
+ let canDelete = isInstalled && (removalAllowed ?? PrivateAIIntegrationService.canRemoveInstalledModel(model))
return VStack(alignment: .leading, spacing: 14) {
HStack(spacing: 8) {
Image(systemName: "pencil.circle.fill")
.font(.system(size: 14))
.foregroundStyle(self.theme.palette.accent)
- Text("Edit Provider")
+ Text(onDone == nil ? "Edit Provider" : "Advanced settings")
.font(.system(size: 14, weight: .semibold))
Spacer()
}
@@ -2145,8 +2034,8 @@ extension AIEnhancementSettingsView {
HStack(spacing: 8) {
if isVerified {
Button {
- self.resetPrivateAIVerification(for: model)
- self.viewModel.clearEditProviderDraft()
+ self.privateAIController.resetPrivateAIVerification(for: model)
+ if onDone == nil { self.viewModel.clearEditProviderDraft() }
} label: {
HStack(spacing: 5) {
Image(systemName: "arrow.counterclockwise")
@@ -2155,12 +2044,13 @@ extension AIEnhancementSettingsView {
.font(.caption)
}
.fluidCompactButton(foreground: .red, borderColor: .red.opacity(0.6))
+ .disabled(isBusy)
}
if canDelete {
Button(role: .destructive) {
- self.deletePrivateAIModel(model)
- self.viewModel.clearEditProviderDraft()
+ self.privateAIController.deletePrivateAIModel(model)
+ if onDone == nil { self.viewModel.clearEditProviderDraft() }
} label: {
HStack(spacing: 6) {
Image(systemName: "trash")
@@ -2174,15 +2064,17 @@ extension AIEnhancementSettingsView {
Spacer(minLength: 0)
- Button {
- self.viewModel.clearEditProviderDraft()
- } label: {
- HStack(spacing: 6) {
- Image(systemName: "checkmark")
- Text("Done")
+ if onDone == nil {
+ Button {
+ self.viewModel.clearEditProviderDraft()
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: "checkmark")
+ Text("Done")
+ }
}
+ .fluidButton(.glass, size: .compact)
}
- .fluidButton(.glass, size: .compact)
}
}
}
@@ -2391,7 +2283,7 @@ extension AIEnhancementSettingsView {
if !isBuiltIn {
Button(role: .destructive) {
- self.viewModel.deleteCurrentProvider()
+ guard self.viewModel.deleteCurrentProvider() else { return }
self.viewModel.clearEditProviderDraft()
self.expandedProviderID = nil
} label: {
@@ -2529,7 +2421,7 @@ extension AIEnhancementSettingsView {
Image(systemName: "brain.head.profile")
.font(.system(size: 14))
.foregroundStyle(self.theme.palette.accent)
- Text("Reasoning for \(self.viewModel.selectedModel)")
+ Text("Reasoning for \(ModelDisplayName.forID(self.viewModel.selectedModel))")
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(self.theme.palette.primaryText)
Spacer()
@@ -2687,22 +2579,22 @@ extension AIEnhancementSettingsView {
return VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 12) {
Button(action: { Task { await self.viewModel.testAPIConnection() } }) {
- Text(self.viewModel.isTestingConnection ? "Verifying..." : "Verify Connection")
+ Text(self.viewModel.isTestingConnection ? "Verifying…" : (self.viewModel.isModelVerified(for: self.viewModel.selectedProviderID) ? "Model verified" : "Verify model"))
.font(.caption)
.fontWeight(.semibold)
}
.fluidCompactButton(isReady: true)
.frame(minWidth: AISettingsLayout.primaryActionMinWidth, minHeight: AISettingsLayout.controlHeight)
- .disabled(self.viewModel.isTestingConnection ||
+ .disabled(self.viewModel.isTestingConnection || self.viewModel.isModelVerified(for: self.viewModel.selectedProviderID) ||
(!self.viewModel.isLocalEndpoint(self.viewModel.openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)) &&
selectedProviderAPIKey.isEmpty))
}
// Connection Status Display
- if self.viewModel.connectionStatus == .success {
+ if self.viewModel.isModelVerified(for: self.viewModel.selectedProviderID) {
HStack(spacing: 8) {
Image(systemName: "checkmark.circle.fill").foregroundStyle(Color.fluidGreen).font(.caption)
- Text("Connection verified").font(.caption).foregroundStyle(Color.fluidGreen)
+ Text("Model verified").font(.caption).foregroundStyle(Color.fluidGreen)
}
} else if self.viewModel.connectionStatus == .failed {
HStack(spacing: 8) {
diff --git a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
index 46d4b0d0..fff0b211 100644
--- a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
+++ b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
@@ -307,7 +307,7 @@ extension AIEnhancementSettingsView {
systemImage: "cpu",
text: modelPicker.selectedModel.isEmpty
? (modelPicker.providerName.isEmpty ? "No model" : modelPicker.summary)
- : modelPicker.selectedModel,
+ : ModelDisplayName.forID(modelPicker.selectedModel),
tone: tone
)
}
@@ -631,7 +631,7 @@ extension AIEnhancementSettingsView {
let providerName = self.viewModel.providerDisplayName(for: providerID)
let selectedModel = self.promptEditorModelDraft.trimmingCharacters(in: .whitespacesAndNewlines)
- let summary = selectedModel.isEmpty ? providerName : "\(providerName) - \(selectedModel)"
+ let summary = selectedModel.isEmpty ? providerName : "\(providerName) - \(ModelDisplayName.forID(selectedModel))"
return PromptCardModelPicker(
summary: summary,
@@ -889,7 +889,7 @@ extension AIEnhancementSettingsView {
) -> PromptCardModelPicker? {
if isPrivateAI {
return PromptCardModelPicker(
- summary: "fluid-1",
+ summary: ModelDisplayName.forID(PrivateAIIntegrationService.configuredModelID),
selectedModel: PrivateAIIntegrationService.configuredModelID,
models: PrivateAIModelRegistry.modelIDs(),
providerName: PrivateAIProviderFeature.displayName,
@@ -926,7 +926,7 @@ extension AIEnhancementSettingsView {
let providerName = self.viewModel.providerDisplayName(for: providerID)
let configuredModel = configuration.modelName.trimmingCharacters(in: .whitespacesAndNewlines)
let selectedModel = configuredModel.isEmpty ? self.viewModel.selectedModel(for: providerID) : configuredModel
- let summary = selectedModel.isEmpty ? providerName : "\(providerName) - \(selectedModel)"
+ let summary = selectedModel.isEmpty ? providerName : "\(providerName) - \(ModelDisplayName.forID(selectedModel))"
return PromptCardModelPicker(
summary: summary,
diff --git a/Sources/Fluid/UI/AISettingsView.swift b/Sources/Fluid/UI/AISettingsView.swift
index 816d9e81..a8268a35 100644
--- a/Sources/Fluid/UI/AISettingsView.swift
+++ b/Sources/Fluid/UI/AISettingsView.swift
@@ -104,6 +104,7 @@ struct AISettingsView: View {
@StateObject private var voiceViewModel: VoiceEngineSettingsViewModel
@StateObject private var enhancementViewModel: AIEnhancementSettingsViewModel
+ @StateObject private var privateAIController: PrivateAISettingsController
@State private var selectedEnhancementSection: AIEnhancementConfigurationSection = .providers
init(appServices: AppServices, menuBarManager: MenuBarManager, theme: AppTheme) {
@@ -114,11 +115,13 @@ struct AISettingsView: View {
settings: SettingsStore.shared,
appServices: appServices
))
- _enhancementViewModel = StateObject(wrappedValue: AIEnhancementSettingsViewModel(
+ let enhancementModel = AIEnhancementSettingsViewModel(
settings: SettingsStore.shared,
menuBarManager: menuBarManager,
promptTest: DictationPromptTestCoordinator.shared
- ))
+ )
+ _enhancementViewModel = StateObject(wrappedValue: enhancementModel)
+ _privateAIController = StateObject(wrappedValue: PrivateAISettingsController(viewModel: enhancementModel))
}
var body: some View {
@@ -131,6 +134,7 @@ struct AISettingsView: View {
)
AIEnhancementSettingsView(
viewModel: self.enhancementViewModel,
+ privateAIController: self.privateAIController,
settings: self.enhancementViewModel.settings,
promptTest: self.enhancementViewModel.promptTest,
theme: self.theme,
diff --git a/Sources/Fluid/UI/HistoryAppIcon.swift b/Sources/Fluid/UI/HistoryAppIcon.swift
new file mode 100644
index 00000000..f146d2ec
--- /dev/null
+++ b/Sources/Fluid/UI/HistoryAppIcon.swift
@@ -0,0 +1,61 @@
+import AppKit
+import SwiftUI
+
+/// Small presentation cache shared by history rows; no application lookup during rendering.
+@MainActor
+private final class HistoryAppIconCache {
+ static let shared = HistoryAppIconCache()
+
+ private final class Result {
+ let image: NSImage?
+ init(_ image: NSImage?) { self.image = image }
+ }
+
+ private let cache = NSCache<NSString, Result>()
+ private var pending: [String: Task<NSImage?, Never>] = [:]
+
+ private init() {
+ self.cache.countLimit = 48
+ }
+
+ func icon(for name: String) async -> NSImage? {
+ let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !name.isEmpty else { return nil }
+ if let result = self.cache.object(forKey: name as NSString) { return result.image }
+ if let task = self.pending[name] { return await task.value }
+ guard self.pending.count < 48 else { return nil }
+ let task = Task.detached(priority: .utility) { () -> NSImage? in
+ guard let path = NSWorkspace.shared.fullPath(forApplication: name) else { return nil }
+ return NSWorkspace.shared.icon(forFile: path)
+ }
+ self.pending[name] = task
+ let image = await task.value
+ self.cache.setObject(Result(image), forKey: name as NSString)
+ self.pending[name] = nil
+ return image
+ }
+}
+
+struct HistoryAppIcon: View {
+ let appName: String
+ @State private var image: NSImage?
+
+ var body: some View {
+ Group {
+ if let image {
+ Image(nsImage: image).resizable().scaledToFit()
+ } else {
+ Image(systemName: "app").resizable().scaledToFit().foregroundStyle(.secondary)
+ }
+ }
+ .frame(width: 22, height: 22)
+ .accessibilityLabel(self.appName.isEmpty ? "Unknown app" : self.appName)
+ .help(self.appName.isEmpty ? "Unknown app" : self.appName)
+ .task(id: self.appName) {
+ self.image = nil
+ let image = await HistoryAppIconCache.shared.icon(for: self.appName)
+ guard !Task.isCancelled else { return }
+ self.image = image
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/HistoryAudioAvailability.swift b/Sources/Fluid/UI/HistoryAudioAvailability.swift
new file mode 100644
index 00000000..560c38a5
--- /dev/null
+++ b/Sources/Fluid/UI/HistoryAudioAvailability.swift
@@ -0,0 +1,23 @@
+import Foundation
+
+/// A view-lifetime snapshot: no disk access from row rendering and no persisted state changes.
+nonisolated enum HistoryAudioAvailability {
+ static func scan(
+ fileNames: [String],
+ exists: @escaping @Sendable (String) -> Bool
+ ) async -> Set<String> {
+ let worker = Task.detached(priority: .utility) {
+ var available: Set<String> = []
+ for fileName in Set(fileNames) {
+ guard !Task.isCancelled else { return Set<String>() }
+ if exists(fileName) { available.insert(fileName) }
+ }
+ return available
+ }
+ return await withTaskCancellationHandler {
+ await worker.value
+ } onCancel: {
+ worker.cancel()
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/HistoryInlineAudioView.swift b/Sources/Fluid/UI/HistoryInlineAudioView.swift
new file mode 100644
index 00000000..9273f1b0
--- /dev/null
+++ b/Sources/Fluid/UI/HistoryInlineAudioView.swift
@@ -0,0 +1,124 @@
+import AVFoundation
+import SwiftUI
+
+/// Playback belongs only to this visible history entry, never to dictation capture.
+struct HistoryInlineAudioView: View {
+ @Environment(\.theme) private var theme
+ let entry: TranscriptionHistoryEntry
+ @State private var player: AVPlayer?
+ @State private var errorMessage: String?
+ @State private var elapsed: Double = 0
+ @State private var duration: Double = 0
+ @State private var isPlaying = false
+ @State private var isSeeking = false
+ @State private var timeObserver: Any?
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Recording").font(self.theme.typography.bodyStrong).foregroundStyle(.secondary)
+ if let errorMessage {
+ Label(errorMessage, systemImage: "exclamationmark.triangle")
+ .font(.callout).foregroundStyle(.secondary)
+ } else if let player {
+ HStack(spacing: 12) {
+ Button {
+ if self.isPlaying {
+ player.pause()
+ self.isPlaying = false
+ } else {
+ if self.elapsed >= self.duration - 0.1 {
+ player.seek(to: .zero)
+ self.elapsed = 0
+ }
+ player.play()
+ self.isPlaying = true
+ }
+ } label: {
+ Image(systemName: self.isPlaying ? "pause.fill" : "play.fill")
+ }
+ .fluidGlassAction(circular: true)
+ .accessibilityLabel(self.isPlaying ? "Pause recording" : "Play recording")
+ Text(Self.timeLabel(self.elapsed)).monospacedDigit().frame(width: 42)
+ Slider(value: self.$elapsed, in: 0...max(self.duration, 0.01)) { editing in
+ self.isSeeking = editing
+ if !editing {
+ player.seek(to: CMTime(seconds: self.elapsed, preferredTimescale: 600))
+ }
+ }
+ .tint(self.theme.palette.accent)
+ .accessibilityLabel("Recording position")
+ Text(Self.timeLabel(self.duration)).monospacedDigit().frame(width: 42)
+ }
+ .font(self.theme.typography.caption)
+ .foregroundStyle(.secondary)
+ .frame(minHeight: 40)
+ } else {
+ ProgressView("Loading recording…").controlSize(.small)
+ }
+ }
+ .task(id: self.entry.id) {
+ do {
+ let entry = self.entry
+ // Resolve the saved path off the main thread, only on an explicit Audio click.
+ let url = await Task.detached(priority: .userInitiated) {
+ DictationAudioHistoryStore.shared.audioFileURL(for: entry)
+ }.value
+ try Task.checkCancellation()
+ guard let url else { throw DictationAudioHistoryError.audioMissing }
+ let asset = AVURLAsset(url: url)
+ let deadline = Task {
+ do { try await Task.sleep(for: .seconds(15)) } catch { return }
+ asset.cancelLoading()
+ }
+ defer { deadline.cancel() }
+ let (playable, mediaDuration) = try await withTaskCancellationHandler {
+ try await asset.load(.isPlayable, .duration)
+ } onCancel: {
+ asset.cancelLoading()
+ }
+ guard playable else { throw DictationAudioHistoryError.audioMissing }
+ try Task.checkCancellation()
+ guard mediaDuration.seconds.isFinite, mediaDuration.seconds > 0 else { throw DictationAudioHistoryError.audioMissing }
+ self.duration = mediaDuration.seconds
+ let player = AVPlayer(playerItem: AVPlayerItem(asset: asset))
+ self.player = player
+ self.timeObserver = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.25, preferredTimescale: 600), queue: .main) { [weak player] time in
+ Task { @MainActor in
+ guard let player, self.player === player, !self.isSeeking, time.seconds.isFinite else { return }
+ self.elapsed = min(max(time.seconds, 0), self.duration)
+ }
+ }
+ player.play()
+ self.isPlaying = true
+ } catch {
+ // Disappearance is silent; a load cancelled by the deadline is a visible failure.
+ guard !Task.isCancelled else { return }
+ self.errorMessage = "This recording could not be played. It may have been removed."
+ }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime)) { notification in
+ guard let item = notification.object as? AVPlayerItem, item === self.player?.currentItem else { return }
+ self.isPlaying = false
+ self.elapsed = self.duration
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .AVPlayerItemFailedToPlayToEndTime)) { notification in
+ guard let item = notification.object as? AVPlayerItem, item === self.player?.currentItem else { return }
+ self.player?.pause()
+ self.isPlaying = false
+ self.errorMessage = "This recording could not be played."
+ }
+ .onDisappear {
+ self.player?.pause()
+ if let timeObserver { self.player?.removeTimeObserver(timeObserver) }
+ self.timeObserver = nil
+ self.player?.replaceCurrentItem(with: nil)
+ self.player = nil
+ self.isPlaying = false
+ }
+ }
+
+ private static func timeLabel(_ seconds: Double) -> String {
+ let value = Int(max(seconds, 0))
+ return String(format: "%d:%02d", value / 60, value % 60)
+ }
+}
diff --git a/Sources/Fluid/UI/HistoryTextComparisonView.swift b/Sources/Fluid/UI/HistoryTextComparisonView.swift
new file mode 100644
index 00000000..40785445
--- /dev/null
+++ b/Sources/Fluid/UI/HistoryTextComparisonView.swift
@@ -0,0 +1,94 @@
+import SwiftUI
+
+struct HistoryTextComparisonView: View {
+ @Environment(\.theme) private var theme
+ let entry: TranscriptionHistoryEntry
+ let copy: (String) -> Void
+ @State private var showChanges = true
+ @State private var comparison: HistoryTextDiff?
+ @State private var comparisonMessage: String?
+ @State private var hasCompared = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ if self.entry.wasAIProcessed {
+ HStack {
+ if self.showChanges, let message = self.comparisonMessage {
+ Text(message).foregroundStyle(.secondary)
+ .lineLimit(1).help(message)
+ }
+ Spacer()
+ Toggle("Show changes", isOn: self.$showChanges).toggleStyle(.switch).controlSize(.small)
+ .fixedSize()
+ }
+ .font(self.theme.typography.caption)
+ .frame(height: 24)
+ }
+ self.section(title: "Final text", content: self.entry.clipboardText ?? "", isOriginal: false)
+ if self.entry.wasAIProcessed {
+ self.section(title: "Original transcription", content: self.entry.rawText, isOriginal: true)
+ }
+ }
+ .task(id: self.showChanges) {
+ // Keep the result while toggling; only this selected entry is compared, once.
+ guard self.entry.wasAIProcessed, self.showChanges, !self.hasCompared else { return }
+ let original = self.entry.rawText
+ let final = self.entry.clipboardText ?? ""
+ let result = await Task.detached(priority: .utility) {
+ HistoryTextDiff.compare(original: original, final: final)
+ }.value
+ guard !Task.isCancelled else { return }
+ self.comparison = result
+ self.hasCompared = true
+ self.comparisonMessage = result == nil
+ ? "This entry is too long for inline comparison. Both texts remain available below."
+ : nil
+ }
+ }
+
+ private func section(title: String, content: String, isOriginal: Bool) -> some View {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack(spacing: 8) {
+ Text(title).font(self.theme.typography.bodyStrong)
+ if !isOriginal, self.entry.wasAIProcessed {
+ Text("AI enhanced").font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.accent)
+ .padding(.horizontal, 8).padding(.vertical, 4)
+ .background(self.theme.palette.accent.opacity(0.1), in: Capsule())
+ }
+ Spacer()
+ Button { self.copy(content) } label: { Image(systemName: "doc.on.doc") }
+ .buttonStyle(.plain).foregroundStyle(.secondary)
+ .help(isOriginal ? "Copy raw text" : "Copy final text")
+ .accessibilityLabel(isOriginal ? "Copy raw text" : "Copy final text")
+ }
+ self.text(content, isOriginal: isOriginal)
+ .font(self.theme.typography.body).lineSpacing(5)
+ .foregroundStyle(isOriginal ? self.theme.palette.secondaryText : self.theme.palette.primaryText)
+ .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .padding(20)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: 16))
+ .overlay(RoundedRectangle(cornerRadius: 16).strokeBorder(self.theme.palette.cardBorder.opacity(0.5)))
+ }
+
+ private func text(_ content: String, isOriginal: Bool) -> Text {
+ guard self.showChanges, let comparison else { return Text(AttributedString(content)) }
+ let runs = isOriginal ? comparison.original : comparison.final
+ var text = AttributedString()
+ for run in runs {
+ var part = AttributedString(run.text)
+ if run.changed {
+ part.foregroundColor = isOriginal ? .red : .green
+ part.backgroundColor = (isOriginal ? Color.red : Color.green).opacity(0.1)
+ if isOriginal {
+ part.strikethroughStyle = .single
+ } else {
+ part.underlineStyle = .single
+ }
+ }
+ text.append(part)
+ }
+ return Text(text)
+ }
+}
diff --git a/Sources/Fluid/UI/HistoryTextDiff.swift b/Sources/Fluid/UI/HistoryTextDiff.swift
new file mode 100644
index 00000000..64272fbe
--- /dev/null
+++ b/Sources/Fluid/UI/HistoryTextDiff.swift
@@ -0,0 +1,49 @@
+import Foundation
+
+/// Bounded, presentation-only word/punctuation comparison. Whitespace is preserved verbatim.
+struct HistoryTextDiff: Sendable {
+ struct Run: Equatable, Sendable {
+ var text: String
+ let changed: Bool
+ }
+
+ let original: [Run]
+ let final: [Run]
+ var hasChanges: Bool { self.original.contains { $0.changed } || self.final.contains { $0.changed } }
+
+ static func compare(original: String, final: String) -> HistoryTextDiff? {
+ guard original.utf8.count + final.utf8.count <= 24_000 else { return nil }
+ let pattern = #"\s+|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]"#
+ guard let expression = try? NSRegularExpression(pattern: pattern) else { return nil }
+ func tokens(_ text: String) -> [String] {
+ expression.matches(in: text, range: NSRange(text.startIndex..., in: text)).compactMap {
+ Range($0.range, in: text).map { String(text[$0]) }
+ }
+ }
+ let before = tokens(original)
+ let after = tokens(final)
+ guard before.count + after.count <= 2048 else { return nil }
+ let changes = after.difference(from: before)
+ var removed = Set<Int>()
+ var added = Set<Int>()
+ for change in changes {
+ switch change {
+ case let .remove(offset, _, _): removed.insert(offset)
+ case let .insert(offset, _, _): added.insert(offset)
+ }
+ }
+ func runs(_ tokens: [String], changed: Set<Int>) -> [Run] {
+ var result: [Run] = []
+ for (index, token) in tokens.enumerated() {
+ let isChanged = changed.contains(index)
+ if result.last?.changed == isChanged {
+ result[result.count - 1].text += token
+ } else {
+ result.append(Run(text: token, changed: isChanged))
+ }
+ }
+ return result
+ }
+ return HistoryTextDiff(original: runs(before, changed: removed), final: runs(after, changed: added))
+ }
+}
diff --git a/Sources/Fluid/UI/ModelDisplayName.swift b/Sources/Fluid/UI/ModelDisplayName.swift
new file mode 100644
index 00000000..e4050a83
--- /dev/null
+++ b/Sources/Fluid/UI/ModelDisplayName.swift
@@ -0,0 +1,11 @@
+import Foundation
+
+/// Presentation only. Picker tags, history records and API requests keep their original IDs.
+enum ModelDisplayName {
+ static func forID(_ modelID: String) -> String {
+ let id = modelID.trimmingCharacters(in: .whitespacesAndNewlines)
+ let canonical = PrivateAIModelRegistry.canonicalModelID(for: id) ?? id
+ guard let model = PrivateAIModelRegistry.model(id: canonical), !model.displayName.isEmpty else { return id }
+ return model.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1")
+ }
+}
diff --git a/Sources/Fluid/UI/SearchableModelPicker.swift b/Sources/Fluid/UI/SearchableModelPicker.swift
index f2c75aca..3169acbf 100644
--- a/Sources/Fluid/UI/SearchableModelPicker.swift
+++ b/Sources/Fluid/UI/SearchableModelPicker.swift
@@ -27,7 +27,7 @@ struct SearchableModelPicker: View {
isRefreshing: Bool = false,
refreshEnabled: Bool = true,
selectionEnabled: Bool = true,
- displayName: @escaping (String) -> String = { $0 },
+ displayName: @escaping (String) -> String = ModelDisplayName.forID,
controlWidth: CGFloat = 180,
controlHeight: CGFloat? = nil
) {
diff --git a/Sources/Fluid/UI/StatsSnapshot.swift b/Sources/Fluid/UI/StatsSnapshot.swift
new file mode 100644
index 00000000..cde26212
--- /dev/null
+++ b/Sources/Fluid/UI/StatsSnapshot.swift
@@ -0,0 +1,153 @@
+import Foundation
+
+/// A bounded, read-only summary. No transcription text is retained in the result.
+nonisolated struct StatsSnapshot: Sendable {
+ var totalWords = 0
+ var totalTranscriptions = 0
+ var aiProcessedCount = 0
+ var longestTranscriptionWords = 0
+ var mostWordsInDay = 0
+ var mostTranscriptionsInDay = 0
+ var currentStreak = 0
+ var bestStreak = 0
+ var weekdayCurrentStreak = 0
+ var weekdayBestStreak = 0
+ var peakHourFormatted = "N/A"
+ var topApps: [String] = []
+ var activity: [(date: Date, words: Int)] = []
+
+ var averageWordsPerTranscription: Int {
+ self.totalTranscriptions == 0 ? 0 : self.totalWords / self.totalTranscriptions
+ }
+
+ var aiEnhancementRate: Int {
+ self.totalTranscriptions == 0 ? 0 : self.aiProcessedCount * 100 / self.totalTranscriptions
+ }
+
+ func formattedTimeSaved(typingWPM: Int) -> String {
+ let minutes = typingWPM > 0 ? max(0, Double(self.totalWords) / Double(typingWPM) - Double(self.totalWords) / 150) : 0
+ if minutes < 1 { return "< 1m" }
+ if minutes < 60 { return "\(Int(minutes))m" }
+ let hours = Int(minutes) / 60
+ let remainder = Int(minutes) % 60
+ return remainder == 0 ? "\(hours)h" : "\(hours)h \(remainder)m"
+ }
+
+ func dailyWordCounts(days: Int) -> [(date: Date, words: Int)] {
+ Array(self.activity.suffix(max(0, days)))
+ }
+
+ func topAppsFormatted(limit: Int) -> [String] {
+ Array(self.topApps.prefix(max(0, limit)))
+ }
+
+ var wordMilestones: [(target: Int, achieved: Bool, label: String)] {
+ [(1000, "1K"), (10_000, "10K"), (50_000, "50K"), (100_000, "100K"), (500_000, "500K"), (1_000_000, "1M")]
+ .map { ($0.0, self.totalWords >= $0.0, $0.1) }
+ }
+
+ var transcriptionMilestones: [(target: Int, achieved: Bool, label: String)] {
+ [(50, "50"), (100, "100"), (500, "500"), (1000, "1K"), (5000, "5K"), (10_000, "10K")]
+ .map { ($0.0, self.totalTranscriptions >= $0.0, $0.1) }
+ }
+
+ var streakMilestones: [(target: Int, achieved: Bool, label: String)] {
+ [(7, "7 days"), (14, "14 days"), (30, "30 days"), (60, "60 days"), (100, "100 days"), (365, "1 year")]
+ .map { ($0.0, self.bestStreak >= $0.0, $0.1) }
+ }
+
+ var totalMilestonesAchieved: Int {
+ self.wordMilestones.filter(\.achieved).count + self.transcriptionMilestones.filter(\.achieved).count
+ + self.streakMilestones.filter(\.achieved).count
+ }
+
+ let totalMilestonesPossible = 18
+
+ func usingWeekdays(_ enabled: Bool) -> Self {
+ var result = self
+ if enabled {
+ result.currentStreak = self.weekdayCurrentStreak
+ result.bestStreak = self.weekdayBestStreak
+ }
+ return result
+ }
+
+ static func build(entries: [TranscriptionHistoryEntry], now: Date, calendar: Calendar) throws -> Self {
+ var result = Self()
+ var dayWords: [Date: Int] = [:]
+ var dayCounts: [Date: Int] = [:]
+ var appCounts: [String: Int] = [:]
+ var hours = Array(repeating: 0, count: 24)
+ result.totalTranscriptions = entries.count
+ for (index, entry) in entries.enumerated() {
+ if index.isMultiple(of: 128) { try Task.checkCancellation() }
+ let words = entry.processedText.components(separatedBy: .whitespacesAndNewlines).lazy.filter { !$0.isEmpty }.count
+ let day = calendar.startOfDay(for: entry.timestamp)
+ dayWords[day, default: 0] += words
+ dayCounts[day, default: 0] += 1
+ appCounts[entry.appName.isEmpty ? "Unknown" : entry.appName, default: 0] += 1
+ hours[calendar.component(.hour, from: entry.timestamp)] += 1
+ result.totalWords += words
+ result.longestTranscriptionWords = max(result.longestTranscriptionWords, words)
+ if entry.wasAIProcessed { result.aiProcessedCount += 1 }
+ }
+ try Task.checkCancellation()
+ result.mostWordsInDay = dayWords.values.max() ?? 0
+ result.mostTranscriptionsInDay = dayCounts.values.max() ?? 0
+ result.topApps = appCounts.sorted { $0.value == $1.value ? $0.key < $1.key : $0.value > $1.value }.prefix(5).map(\.key)
+ let today = calendar.startOfDay(for: now)
+ result.activity = (0..<30).reversed().compactMap { offset in
+ guard let date = calendar.date(byAdding: .day, value: -offset, to: today) else { return nil }
+ return (date, dayWords[date, default: 0])
+ }
+ let days = dayCounts.keys.sorted(by: >)
+ (result.currentStreak, result.bestStreak) = try Self.streaks(days: days, today: today, calendar: calendar, weekdays: false)
+ (result.weekdayCurrentStreak, result.weekdayBestStreak) = try Self.streaks(days: days, today: today, calendar: calendar, weekdays: true)
+ if !entries.isEmpty, let hour = hours.indices.max(by: { hours[$0] < hours[$1] }) {
+ let formatter = DateFormatter()
+ formatter.calendar = calendar
+ formatter.timeZone = calendar.timeZone
+ formatter.dateFormat = "h a"
+ if let start = calendar.date(from: DateComponents(hour: hour)),
+ let end = calendar.date(byAdding: .hour, value: 1, to: start)
+ {
+ result.peakHourFormatted = "\(formatter.string(from: start))-\(formatter.string(from: end))"
+ }
+ }
+ return result
+ }
+
+ private static func previousDay(_ day: Date, calendar: Calendar, weekdays: Bool) -> Date? {
+ var date = day
+ for _ in 0..<7 {
+ guard let previous = calendar.date(byAdding: .day, value: -1, to: date) else { return nil }
+ if !weekdays || !calendar.isDateInWeekend(previous) { return previous }
+ date = previous
+ }
+ return nil
+ }
+
+ private static func streaks(days: [Date], today: Date, calendar: Calendar, weekdays: Bool) throws -> (Int, Int) {
+ let days = weekdays ? days.filter { !calendar.isDateInWeekend($0) } : days
+ guard let first = days.first else { return (0, 0) }
+ let latest = weekdays && calendar.isDateInWeekend(today)
+ ? Self.previousDay(today, calendar: calendar, weekdays: true) : today
+ let recent = latest.map { first == $0 || first == Self.previousDay($0, calendar: calendar, weekdays: weekdays) } ?? false
+ var initialRun = 1
+ var run = 1
+ var best = 1
+ var initial = true
+ for index in 1..<days.count {
+ if index.isMultiple(of: 128) { try Task.checkCancellation() }
+ if days[index] == Self.previousDay(days[index - 1], calendar: calendar, weekdays: weekdays) {
+ run += 1
+ if initial { initialRun += 1 }
+ } else {
+ initial = false
+ run = 1
+ }
+ best = max(best, run)
+ }
+ return (recent ? initialRun : 0, best)
+ }
+}
diff --git a/Sources/Fluid/UI/StatsSnapshotStore.swift b/Sources/Fluid/UI/StatsSnapshotStore.swift
new file mode 100644
index 00000000..2b71f7a6
--- /dev/null
+++ b/Sources/Fluid/UI/StatsSnapshotStore.swift
@@ -0,0 +1,90 @@
+import AppKit
+import Combine
+
+/// Only aggregates while Stats is visible; keeps one small result for subsequent visits.
+@MainActor
+final class StatsSnapshotStore: ObservableObject {
+ static let shared = StatsSnapshotStore(history: .shared)
+
+ @Published private(set) var snapshot: StatsSnapshot?
+ @Published private(set) var isUpdating = false
+ private let history: TranscriptionHistoryStore
+ private var subscriptions = Set<AnyCancellable>()
+ private var owners = Set<UUID>()
+ private var revision: UInt64 = 0
+ private var completedRevision: UInt64?
+ private var completedDay: Date?
+ private var task: Task<Void, Never>?
+
+ init(history: TranscriptionHistoryStore) {
+ self.history = history
+ history.$entries.sink { [weak self] entries in
+ guard let self else { return }
+ self.revision &+= 1
+ self.task?.cancel()
+ self.task = nil
+ self.isUpdating = false
+ if entries.isEmpty { self.snapshot = nil }
+ if !self.owners.isEmpty { self.refresh(entries: entries) }
+ }.store(in: &self.subscriptions)
+
+ for name in [Notification.Name.NSCalendarDayChanged, .NSSystemTimeZoneDidChange, NSLocale.currentLocaleDidChangeNotification] {
+ NotificationCenter.default.publisher(for: name).receive(on: DispatchQueue.main).sink { [weak self] _ in
+ guard let self else { return }
+ self.revision &+= 1
+ if !self.owners.isEmpty { self.refresh(entries: self.history.entries) }
+ }.store(in: &self.subscriptions)
+ }
+ NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)
+ .receive(on: DispatchQueue.main).sink { [weak self] _ in
+ guard let self, !self.owners.isEmpty else { return }
+ self.refreshIfNeeded()
+ }.store(in: &self.subscriptions)
+ }
+
+ func activate(_ owner: UUID) {
+ self.owners.insert(owner)
+ self.refreshIfNeeded()
+ }
+
+ func deactivate(_ owner: UUID) {
+ self.owners.remove(owner)
+ if self.owners.isEmpty {
+ self.task?.cancel()
+ self.task = nil
+ self.isUpdating = false
+ }
+ }
+
+ private func refreshIfNeeded() {
+ guard self.completedRevision != self.revision || self.completedDay != Calendar.current.startOfDay(for: Date()) else { return }
+ self.refresh(entries: self.history.entries)
+ }
+
+ private func refresh(entries: [TranscriptionHistoryEntry]) {
+ self.task?.cancel()
+ let revision = self.revision
+ let calendar = Calendar.current
+ let now = Date()
+ self.isUpdating = true
+ self.task = Task { [weak self] in
+ let worker = Task.detached(priority: .utility) {
+ // Coalesce a burst of history mutations without delaying navigation.
+ try await Task.sleep(nanoseconds: 50_000_000)
+ return try StatsSnapshot.build(entries: entries, now: now, calendar: calendar)
+ }
+ let value = await withTaskCancellationHandler {
+ try? await worker.value
+ } onCancel: {
+ worker.cancel()
+ }
+ guard !Task.isCancelled, let self, self.revision == revision, !self.owners.isEmpty else { return }
+ self.isUpdating = false
+ self.task = nil
+ guard let value else { return }
+ self.snapshot = value
+ self.completedRevision = revision
+ self.completedDay = calendar.startOfDay(for: now)
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/StatsView.swift b/Sources/Fluid/UI/StatsView.swift
index 3519517a..26f012b4 100644
--- a/Sources/Fluid/UI/StatsView.swift
+++ b/Sources/Fluid/UI/StatsView.swift
@@ -2,6 +2,8 @@ import SwiftUI
struct StatsView: View {
@ObservedObject private var historyStore = TranscriptionHistoryStore.shared
+ @ObservedObject private var statsStore = StatsSnapshotStore.shared
+ @State private var statsOwner = UUID()
@ObservedObject private var settings = SettingsStore.shared
@Environment(\.theme) private var theme
@@ -17,43 +19,54 @@ struct StatsView: View {
return formatter
}()
+ private var stats: StatsSnapshot {
+ (self.statsStore.snapshot ?? StatsSnapshot()).usingWeekdays(self.settings.weekendsDontBreakStreak)
+ }
+
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
- VStack(spacing: 16) {
- self.todayHeaderCard
+ if self.statsStore.snapshot == nil {
+ ProgressView("Loading statistics…")
+ .frame(maxWidth: .infinity, minHeight: 240)
+ } else {
+ VStack(spacing: 16) {
+ self.todayHeaderCard
- Divider()
- .opacity(0.4)
+ Divider()
+ .opacity(0.4)
- // Header row: Time Saved + Total Words
- HStack(spacing: 16) {
- self.timeSavedCard
- self.totalWordsCard
- }
+ // Header row: Time Saved + Total Words
+ HStack(spacing: 16) {
+ self.timeSavedCard
+ self.totalWordsCard
+ }
- // Second row: Streak + Transcriptions
- HStack(spacing: 16) {
- self.streakCard
- self.transcriptionsCard
- }
+ // Second row: Streak + Transcriptions
+ HStack(spacing: 16) {
+ self.streakCard
+ self.transcriptionsCard
+ }
- // Activity Chart
- self.activityChartCard
+ // Activity Chart
+ self.activityChartCard
- // Milestones
- self.milestonesCard
+ // Milestones
+ self.milestonesCard
- // Insights
- self.insightsCard
+ // Insights
+ self.insightsCard
- // Personal Records
- self.recordsCard
+ // Personal Records
+ self.recordsCard
- // Reset Button
- self.resetSection
+ // Reset Button
+ self.resetSection
+ }
+ .padding(20)
}
- .padding(20)
}
+ .onAppear { self.statsStore.activate(self.statsOwner) }
+ .onDisappear { self.statsStore.deactivate(self.statsOwner) }
}
// MARK: - Today Header
@@ -63,7 +76,7 @@ struct StatsView: View {
let wordsToday = summary.words
let timeSavedToday = summary.formattedTimeSaved(typingWPM: self.settings.userTypingWPM)
let sessionsToday = summary.transcriptions
- let streak = self.historyStore.currentStreak
+ let streak = self.stats.currentStreak
return ThemedCard(style: .prominent, padding: 20, hoverEffect: false) {
VStack(alignment: .leading, spacing: 14) {
@@ -179,7 +192,7 @@ struct StatsView: View {
private var timeSavedCard: some View {
StatCard(title: "TIME SAVED", icon: "clock.fill") {
VStack(alignment: .leading, spacing: 8) {
- Text(self.historyStore.formattedTimeSaved(typingWPM: self.settings.userTypingWPM))
+ Text(self.stats.formattedTimeSaved(typingWPM: self.settings.userTypingWPM))
.font(.system(size: 32, weight: .bold, design: .rounded))
.foregroundStyle(.primary)
@@ -247,7 +260,7 @@ struct StatsView: View {
private var totalWordsCard: some View {
StatCard(title: "TOTAL WORDS", icon: "text.word.spacing") {
VStack(alignment: .leading, spacing: 8) {
- Text(self.formatNumber(self.historyStore.totalWords))
+ Text(self.formatNumber(self.stats.totalWords))
.font(.system(size: 32, weight: .bold, design: .rounded))
.foregroundStyle(.primary)
@@ -271,16 +284,16 @@ struct StatsView: View {
StatCard(title: "CURRENT STREAK", icon: "flame.fill") {
VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .firstTextBaseline, spacing: 4) {
- Text("\(self.historyStore.currentStreak)")
+ Text("\(self.stats.currentStreak)")
.font(.system(size: 32, weight: .bold, design: .rounded))
- .foregroundStyle(self.historyStore.currentStreak > 0 ? self.theme.palette.warning : .primary)
+ .foregroundStyle(self.stats.currentStreak > 0 ? self.theme.palette.warning : .primary)
- Text(self.historyStore.currentStreak == 1 ? "day" : "days")
+ Text(self.stats.currentStreak == 1 ? "day" : "days")
.font(.system(size: 14, weight: .medium))
.foregroundStyle(.secondary)
}
- Text("Best: \(self.historyStore.bestStreak) days")
+ Text("Best: \(self.stats.bestStreak) days")
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
@@ -296,7 +309,7 @@ struct StatsView: View {
.font(.system(size: 32, weight: .bold, design: .rounded))
.foregroundStyle(.primary)
- Text("Avg: \(self.historyStore.averageWordsPerTranscription) words each")
+ Text("Avg: \(self.stats.averageWordsPerTranscription) words each")
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
@@ -323,7 +336,7 @@ struct StatsView: View {
.frame(width: 140)
}
- let data = self.historyStore.dailyWordCounts(days: self.chartDays)
+ let data = self.stats.dailyWordCounts(days: self.chartDays)
let maxWords = data.map { $0.words }.max() ?? 0
if maxWords == 0 {
@@ -439,7 +452,7 @@ struct StatsView: View {
Spacer()
- Text("\(self.historyStore.totalMilestonesAchieved)/\(self.historyStore.totalMilestonesPossible)")
+ Text("\(self.stats.totalMilestonesAchieved)/\(self.stats.totalMilestonesPossible)")
.font(.system(size: 11, weight: .medium))
.foregroundStyle(self.theme.palette.accent)
}
@@ -448,19 +461,19 @@ struct StatsView: View {
// Word milestones
self.milestoneRow(
title: "Words",
- milestones: self.historyStore.wordMilestones
+ milestones: self.stats.wordMilestones
)
// Transcription milestones
self.milestoneRow(
title: "Transcriptions",
- milestones: self.historyStore.transcriptionMilestones
+ milestones: self.stats.transcriptionMilestones
)
// Streak milestones
self.milestoneRow(
title: "Streak",
- milestones: self.historyStore.streakMilestones
+ milestones: self.stats.streakMilestones
)
}
}
@@ -513,7 +526,7 @@ struct StatsView: View {
self.insightItem(
icon: "app.fill",
title: "Top Apps",
- value: self.historyStore.topAppsFormatted(limit: 3).joined(separator: ", "),
+ value: self.stats.topAppsFormatted(limit: 3).joined(separator: ", "),
fallback: "No data yet"
)
@@ -521,7 +534,7 @@ struct StatsView: View {
self.insightItem(
icon: "sparkles",
title: "AI Enhanced",
- value: "\(self.historyStore.aiEnhancementRate)%",
+ value: "\(self.stats.aiEnhancementRate)%",
fallback: "0%"
)
@@ -529,7 +542,7 @@ struct StatsView: View {
self.insightItem(
icon: "clock.fill",
title: "Peak Time",
- value: self.historyStore.peakHourFormatted,
+ value: self.stats.peakHourFormatted,
fallback: "N/A"
)
@@ -537,7 +550,7 @@ struct StatsView: View {
self.insightItem(
icon: "ruler.fill",
title: "Avg Length",
- value: "\(self.historyStore.averageWordsPerTranscription) words",
+ value: "\(self.stats.averageWordsPerTranscription) words",
fallback: "0 words"
)
}
@@ -582,17 +595,17 @@ struct StatsView: View {
HStack(spacing: 12) {
self.recordItem(
title: "Longest Transcription",
- value: "\(self.historyStore.longestTranscriptionWords) words"
+ value: "\(self.stats.longestTranscriptionWords) words"
)
self.recordItem(
title: "Most Words in a Day",
- value: "\(self.formatNumber(self.historyStore.mostWordsInDay)) words"
+ value: "\(self.formatNumber(self.stats.mostWordsInDay)) words"
)
self.recordItem(
title: "Most in a Day",
- value: "\(self.historyStore.mostTranscriptionsInDay) transcriptions"
+ value: "\(self.stats.mostTranscriptionsInDay) transcriptions"
)
}
}
@@ -654,15 +667,11 @@ struct StatsView: View {
// MARK: - Helpers
private func formatNumber(_ number: Int) -> String {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- return formatter.string(from: NSNumber(value: number)) ?? "\(number)"
+ number.formatted(.number)
}
private func dayLabel(_ date: Date) -> String {
- let formatter = DateFormatter()
- formatter.dateFormat = "EEE"
- return formatter.string(from: date)
+ date.formatted(.dateTime.weekday(.abbreviated))
}
}
diff --git a/Sources/Fluid/UI/TranscriptionHistoryView.swift b/Sources/Fluid/UI/TranscriptionHistoryView.swift
index 17b32cea..b8fc3e85 100644
--- a/Sources/Fluid/UI/TranscriptionHistoryView.swift
+++ b/Sources/Fluid/UI/TranscriptionHistoryView.swift
@@ -12,6 +12,23 @@ struct TranscriptionHistoryView: View {
@State private var showReportConfirmation: Bool = false
@State private var selectedReportEntry: TranscriptionHistoryEntry?
@State private var selectedEntryID: UUID?
+ @State private var audioEntryID: UUID?
+ @State private var copiedEntryID: UUID?
+ @State private var copyFeedbackTask: Task<Void, Never>?
+ @State private var availableAudioFiles: Set<String> = []
+ @State private var audioAvailabilityRevision = UUID()
+
+ private struct AudioAvailabilityRequest: Equatable {
+ let fileNames: [String]
+ let revision: UUID
+ }
+
+ private var audioAvailabilityRequest: AudioAvailabilityRequest {
+ AudioAvailabilityRequest(
+ fileNames: self.historyStore.entries.compactMap { $0.audio?.fileName },
+ revision: self.audioAvailabilityRevision
+ )
+ }
private var filteredEntries: [TranscriptionHistoryEntry] {
self.historyStore.search(query: self.searchQuery)
@@ -27,7 +44,14 @@ struct TranscriptionHistoryView: View {
// MARK: - Left Panel: Entry List
VStack(spacing: 0) {
- // Search Bar
+ HStack(spacing: 10) {
+ Image(systemName: "clock.arrow.circlepath").foregroundStyle(self.theme.palette.accent)
+ Text("History").font(self.theme.typography.sectionTitle)
+ Spacer()
+ }
+ .padding(.horizontal, 18)
+ .padding(.top, 20)
+ .padding(.bottom, 8)
self.searchBar
.padding(12)
@@ -59,7 +83,7 @@ struct TranscriptionHistoryView: View {
self.footerView
.disabled(self.historyStore.isLoading)
}
- .frame(minWidth: 280, idealWidth: 320, maxWidth: 400)
+ .frame(minWidth: 280, idealWidth: 340, maxWidth: 400)
.background(self.theme.palette.contentBackground)
// MARK: - Right Panel: Entry Detail
@@ -72,11 +96,35 @@ struct TranscriptionHistoryView: View {
.frame(minWidth: 400)
}
}
+ .onChange(of: self.selectedEntry?.id) { _, _ in
+ self.audioEntryID = nil
+ }
+ .onDisappear {
+ self.availableAudioFiles = []
+ self.audioEntryID = nil
+ self.copyFeedbackTask?.cancel()
+ self.copiedEntryID = nil
+ }
.onAppear {
+ self.audioAvailabilityRevision = UUID()
if self.selectedEntryID == nil {
self.selectedEntryID = self.filteredEntries.first?.id
}
}
+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
+ self.audioAvailabilityRevision = UUID()
+ }
+ .task(id: self.audioAvailabilityRequest) {
+ let request = self.audioAvailabilityRequest
+ let available = await HistoryAudioAvailability.scan(fileNames: request.fileNames) {
+ DictationAudioHistoryStore.shared.audioFileExists(fileName: $0)
+ }
+ guard !Task.isCancelled, request == self.audioAvailabilityRequest else { return }
+ self.availableAudioFiles = available
+ if let entry = self.selectedEntry, !self.hasAudio(entry) {
+ self.audioEntryID = nil
+ }
+ }
.alert("Clear All History", isPresented: self.$showClearConfirmation) {
Button("Cancel", role: .cancel) {}
Button("Clear All", role: .destructive) {
@@ -137,7 +185,7 @@ struct TranscriptionHistoryView: View {
private var entryListView: some View {
ScrollView {
- LazyVStack(spacing: 2) {
+ LazyVStack(spacing: 6) {
ForEach(self.filteredEntries) { entry in
self.entryRow(entry)
}
@@ -149,149 +197,132 @@ struct TranscriptionHistoryView: View {
private func entryRow(_ entry: TranscriptionHistoryEntry) -> some View {
let isSelected = self.selectedEntryID == entry.id
-
- return Button {
- withAnimation(.easeInOut(duration: 0.15)) {
+ return HStack(alignment: .top, spacing: 8) {
+ Button {
self.selectedEntryID = entry.id
- }
- } label: {
- VStack(alignment: .leading, spacing: 4) {
- // Top row: App name and time
- HStack(spacing: 6) {
- Text(entry.appName.isEmpty ? "Unknown App" : entry.appName)
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(isSelected ? .white : .secondary)
- .lineLimit(1)
-
- if self.settings.showHistoryPerformanceMetrics,
- let duration = entry.transcriptionDurationMilliseconds
- {
- self.processingBadge(
- text: "ASR \(TranscriptionHistoryEntry.formattedDuration(milliseconds: duration))",
- isSelected: isSelected,
- isAccent: false
- )
- }
-
- if self.settings.showHistoryPerformanceMetrics,
- entry.wasAIProcessed || entry.aiProcessingError != nil
- {
- self.processingBadge(
- text: entry.aiProcessingDurationMilliseconds.map {
- "AI \(TranscriptionHistoryEntry.formattedDuration(milliseconds: $0))"
- } ?? "AI",
- isSelected: isSelected,
- isAccent: true
- )
- } else if entry.wasAIProcessed {
- self.processingBadge(text: "AI", isSelected: isSelected, isAccent: true)
- }
-
- if self.settings.showHistoryPerformanceMetrics,
- let tokensPerSecond = entry.aiTokensPerSecond
- {
- self.processingBadge(
- text: TranscriptionHistoryEntry.formattedTokensPerSecond(tokensPerSecond, compact: true),
- isSelected: isSelected,
- isAccent: true
- )
- }
-
- if self.hasAudio(entry) {
- Image(systemName: "waveform")
- .font(.system(size: 10, weight: .semibold))
- .foregroundStyle(isSelected ? .white.opacity(0.8) : self.theme.palette.accent)
- .help("Saved local dictation audio")
+ } label: {
+ VStack(alignment: .leading, spacing: 7) {
+ HStack(spacing: 8) {
+ HistoryAppIcon(appName: entry.appName)
+ Spacer(minLength: 4)
+ Text(entry.relativeTimeString)
+ .font(self.theme.typography.caption).foregroundStyle(.secondary)
}
-
- if entry.aiProcessingError != nil {
- Image(systemName: "exclamationmark.triangle.fill")
- .font(.system(size: 10, weight: .bold))
- .foregroundStyle(isSelected ? .white : Color.orange)
- .help(entry.aiProcessingError ?? "")
+ Text(entry.previewText)
+ .font(self.theme.typography.body)
+ .lineLimit(2).multilineTextAlignment(.leading)
+ HStack(spacing: 10) {
+ if let model = self.recordedModel(entry) {
+ Label(model, systemImage: "sparkles")
+ .lineLimit(1).truncationMode(.middle)
+ .help("Recorded AI model: \(model)")
+ } else if entry.wasAIProcessed {
+ Label("AI enhanced", systemImage: "sparkles")
+ }
+ if self.hasAudio(entry) {
+ Image(systemName: "waveform").accessibilityLabel("Saved audio")
+ }
+ if entry.aiProcessingError != nil {
+ Image(systemName: "exclamationmark.triangle")
+ .foregroundStyle(.orange).help(entry.aiProcessingError ?? "")
+ }
+ Spacer(minLength: 0)
+ if self.settings.showHistoryPerformanceMetrics, let speed = entry.aiTokensPerSecond {
+ Text(TranscriptionHistoryEntry.formattedTokensPerSecond(speed, compact: true))
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.accent)
+ .monospacedDigit()
+ .fixedSize()
+ .help("AI generation speed, in tokens per second—not total processing time")
+ }
}
-
- Spacer()
-
- Text(entry.relativeTimeString)
- .font(.system(size: 10, weight: .medium))
- .foregroundStyle(isSelected ? .white.opacity(0.7) : Color.secondary.opacity(0.6))
+ .font(self.theme.typography.caption).foregroundStyle(.secondary)
}
-
- // Preview text
- Text(entry.previewText)
- .font(.system(size: 12))
- .foregroundStyle(isSelected ? .white.opacity(0.9) : .primary)
- .lineLimit(2)
- .multilineTextAlignment(.leading)
- }
- .padding(.horizontal, 10)
- .padding(.vertical, 8)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(
- RoundedRectangle(cornerRadius: 8)
- .fill(isSelected ? self.theme.palette.accent : Color.clear)
- )
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .contextMenu {
- Button {
- self.copyToClipboard(entry.processedText)
- } label: {
- Label(entry.wasAIProcessed ? "Copy AI Text" : "Copy Text", systemImage: "doc.on.doc")
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
}
-
- if entry.wasAIProcessed {
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(isSelected ? .isSelected : [])
+ VStack(spacing: 10) {
Button {
- self.copyToClipboard(entry.rawText)
+ self.copyFinalText(entry)
} label: {
- Label("Copy Raw Text", systemImage: "doc.on.doc.fill")
+ Image(systemName: self.copiedEntryID == entry.id ? "checkmark" : "doc.on.doc")
}
-
- Button {
- self.copyToClipboard(self.combinedText(for: entry))
- } label: {
- Label("Copy Both", systemImage: "doc.on.doc")
+ .buttonStyle(.plain)
+ .help("Copy final text")
+ .accessibilityLabel(self.copiedEntryID == entry.id ? "Copied" : "Copy final text")
+ Menu { self.entryActions(entry) } label: {
+ Image(systemName: "ellipsis")
}
+ .menuStyle(.borderlessButton).menuIndicator(.hidden)
+ .fixedSize().accessibilityLabel("Dictation actions")
}
+ .foregroundStyle(.secondary)
+ }
+ .padding(12)
+ .background(self.theme.palette.accent.opacity(isSelected ? 0.12 : 0), in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14)
+ .strokeBorder(isSelected ? self.theme.palette.accent.opacity(0.6) : self.theme.palette.cardBorder.opacity(0.25)))
+ .contextMenu { self.entryActions(entry) }
+ }
- if self.hasAudio(entry) {
- Divider()
+ @ViewBuilder
+ private func entryActions(_ entry: TranscriptionHistoryEntry) -> some View {
+ Button {
+ self.copyFinalText(entry)
+ } label: {
+ Label(entry.wasAIProcessed ? "Copy AI Text" : "Copy Text", systemImage: "doc.on.doc")
+ }
- Button {
- self.exportPair(entry)
- } label: {
- Label("Export Pair...", systemImage: "square.and.arrow.up")
- }
+ if entry.wasAIProcessed {
+ Button {
+ self.copyToClipboard(entry.rawText)
+ } label: {
+ Label("Copy Raw Text", systemImage: "doc.on.doc.fill")
+ }
- Button {
- self.revealAudio(entry)
- } label: {
- Label("Reveal Audio", systemImage: "waveform")
- }
+ Button {
+ self.copyToClipboard(self.combinedText(for: entry))
+ } label: {
+ Label("Copy Both", systemImage: "doc.on.doc")
}
+ }
+ if self.hasAudio(entry) {
Divider()
Button {
- self.openFeedbackReport(for: entry)
+ self.exportPair(entry)
} label: {
- Label("Report Bad Result...", systemImage: "hand.thumbsup.slash")
+ Label("Export Pair...", systemImage: "square.and.arrow.up")
}
- Divider()
-
- Button(role: .destructive) {
- withAnimation(.easeInOut(duration: 0.2)) {
- self.historyStore.deleteEntry(id: entry.id)
- if self.selectedEntryID == entry.id {
- self.selectedEntryID = self.filteredEntries.first(where: { $0.id != entry.id })?.id
- }
- }
+ Button {
+ self.revealAudio(entry)
} label: {
- Label("Delete", systemImage: "trash")
+ Label("Reveal Audio", systemImage: "waveform")
+ }
+ }
+
+ Divider()
+
+ Button {
+ self.openFeedbackReport(for: entry)
+ } label: {
+ Label("Report Bad Result...", systemImage: "hand.thumbsup.slash")
+ }
+
+ Divider()
+
+ Button(role: .destructive) {
+ if self.audioEntryID == entry.id { self.audioEntryID = nil }
+ self.historyStore.deleteEntry(id: entry.id)
+ if self.selectedEntryID == entry.id {
+ self.selectedEntryID = self.filteredEntries.first(where: { $0.id != entry.id })?.id
}
+ } label: {
+ Label("Delete", systemImage: "trash")
}
}
@@ -362,288 +393,178 @@ struct TranscriptionHistoryView: View {
private func entryDetailView(_ entry: TranscriptionHistoryEntry) -> some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
- // Header
- VStack(alignment: .leading, spacing: 8) {
- HStack(spacing: 8) {
- Text("Transcription Details")
- .font(.system(size: 18, weight: .semibold))
-
- Spacer()
-
- Button {
- self.copyToClipboard(entry.processedText)
- } label: {
- Label(entry.wasAIProcessed ? "Copy AI" : "Copy", systemImage: "doc.on.doc")
- .font(.system(size: 12, weight: .medium))
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: 16) {
+ self.detailHeading(entry)
+ Spacer(minLength: 12)
+ self.detailActions(entry)
+ }
+ VStack(alignment: .leading, spacing: 16) {
+ self.detailHeading(entry)
+ self.detailActions(entry)
+ }
+ }
+ if self.audioEntryID == entry.id {
+ HistoryInlineAudioView(entry: entry)
+ .id(entry.id)
+ }
+ if let error = entry.aiProcessingError {
+ Label {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("AI enhancement failed—raw transcription was used").font(self.theme.typography.bodyStrong)
+ Text(error).font(self.theme.typography.caption).textSelection(.enabled)
}
- .buttonStyle(.bordered)
- .controlSize(.small)
-
- if self.hasAudio(entry) {
- Button {
- self.exportPair(entry)
- } label: {
- Label("Export Pair", systemImage: "square.and.arrow.up")
- .font(.system(size: 12, weight: .medium))
- }
- .buttonStyle(.bordered)
- .controlSize(.small)
-
- Button {
- self.revealAudio(entry)
- } label: {
- Label("Audio", systemImage: "waveform")
- .font(.system(size: 12, weight: .medium))
+ } icon: {
+ Image(systemName: "exclamationmark.triangle").foregroundStyle(.orange)
+ }
+ .padding(16)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Color.orange.opacity(0.08), in: RoundedRectangle(cornerRadius: 16))
+ }
+ HistoryTextComparisonView(entry: entry, copy: self.copyToClipboard)
+ .id(entry.id)
+ if self.settings.showHistoryPerformanceMetrics {
+ FluidManagementGroup(title: "Processing") {
+ LazyVGrid(columns: self.detailColumns, alignment: .leading, spacing: 16) {
+ if let duration = entry.transcriptionDurationMilliseconds {
+ self.metadataItem(
+ icon: "waveform",
+ label: "Transcription",
+ value: TranscriptionHistoryEntry.formattedDuration(milliseconds: duration)
+ )
}
- .buttonStyle(.bordered)
- .controlSize(.small)
- }
-
- Button {
- self.openFeedbackReport(for: entry)
- } label: {
- Label("Report", systemImage: "hand.thumbsup.slash")
- .font(.system(size: 12, weight: .medium))
- }
- .buttonStyle(.bordered)
- .controlSize(.small)
- .help("Review and send this example to FluidVoice")
-
- if entry.wasAIProcessed {
- Button {
- self.copyToClipboard(entry.rawText)
- } label: {
- Label("Raw", systemImage: "doc.on.doc.fill")
- .font(.system(size: 12, weight: .medium))
+ if let duration = entry.aiProcessingDurationMilliseconds {
+ self.metadataItem(
+ icon: "sparkles",
+ label: "AI cleanup",
+ value: TranscriptionHistoryEntry.formattedDuration(milliseconds: duration)
+ )
}
- .buttonStyle(.bordered)
- .controlSize(.small)
-
- Button {
- self.copyToClipboard(self.combinedText(for: entry))
- } label: {
- Label("Both", systemImage: "doc.on.doc")
- .font(.system(size: 12, weight: .medium))
+ if let speed = entry.aiTokensPerSecond {
+ self.metadataItem(
+ icon: "speedometer",
+ label: "AI speed",
+ value: TranscriptionHistoryEntry.formattedTokensPerSecond(speed, compact: true)
+ )
}
- .buttonStyle(.bordered)
- .controlSize(.small)
}
}
-
- Text(entry.fullDateString)
- .font(.system(size: 13))
- .foregroundStyle(.secondary)
}
-
- Divider()
- .opacity(0.3)
-
- if let aiError = entry.aiProcessingError {
- HStack(alignment: .top, spacing: 8) {
- Image(systemName: "exclamationmark.triangle.fill")
- .foregroundStyle(Color.orange)
- VStack(alignment: .leading, spacing: 2) {
- Text("AI Enhancement failed - raw transcription was typed instead")
- .font(.system(size: 12, weight: .semibold))
- Text(aiError)
- .font(.system(size: 11))
- .foregroundStyle(.secondary)
- .textSelection(.enabled)
- }
+ FluidManagementGroup(title: "Details") {
+ LazyVGrid(columns: self.detailColumns, alignment: .leading, spacing: 16) {
+ self.metadataItem(icon: "app", label: "Application", value: entry.appName.isEmpty ? "Unknown" : entry.appName)
+ self.metadataItem(icon: "character.cursor.ibeam", label: "Characters", value: "\(entry.characterCount)")
+ self.metadataItem(icon: "waveform", label: "Recording", value: self.audioMetadataText(for: entry))
}
- .padding(10)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .fill(Color.orange.opacity(0.08))
- .overlay(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .stroke(Color.orange.opacity(0.3), lineWidth: 1)
- )
- )
- }
-
- // Final Text Section
- self.detailSection(
- title: "Final Text",
- content: entry.processedText,
- badge: entry.wasAIProcessed ? "AI Enhanced" : nil
- )
-
- // Raw Text Section (only if different)
- if entry.wasAIProcessed {
- self.detailSection(
- title: "Original Transcription",
- content: entry.rawText,
- badge: nil,
- isSecondary: true
+ Divider().opacity(0.4)
+ self.metadataItem(
+ icon: "sparkles",
+ label: entry.aiProcessingError == nil ? "AI model" : "AI model (failed)",
+ value: self.recordedModel(entry) ?? (entry.wasAIProcessed ? "Not recorded" : "No AI cleanup")
)
}
-
- Divider()
- .opacity(0.3)
-
- // Metadata Grid
- self.metadataGrid(entry)
-
- Spacer(minLength: 20)
-
- // Delete Button
- HStack {
- Spacer()
- Button(role: .destructive) {
- withAnimation(.easeInOut(duration: 0.2)) {
- let nextEntry = self.filteredEntries.first(where: { $0.id != entry.id })
- self.historyStore.deleteEntry(id: entry.id)
- self.selectedEntryID = nextEntry?.id
- }
- } label: {
- Label("Delete Entry", systemImage: "trash")
- .font(.system(size: 12, weight: .medium))
+ ViewThatFits(in: .horizontal) {
+ HStack {
+ self.secondaryActions(entry)
+ Spacer()
+ }
+ VStack(alignment: .leading, spacing: 12) {
+ self.secondaryActions(entry)
}
- .buttonStyle(.bordered)
- .tint(.red)
- .controlSize(.small)
}
}
.padding(24)
+ .frame(maxWidth: 1080, alignment: .leading)
+ .frame(maxWidth: .infinity)
}
.background(self.theme.palette.contentBackground)
}
- private func detailSection(
- title: String,
- content: String,
- badge: String?,
- isSecondary: Bool = false
- ) -> some View {
- VStack(alignment: .leading, spacing: 8) {
- HStack(spacing: 8) {
- Text(title)
- .font(.system(size: 12, weight: .semibold))
- .foregroundStyle(.secondary)
- .textCase(.uppercase)
- .tracking(0.5)
-
- if let badge = badge {
- Text(badge)
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(self.theme.palette.accent)
- .padding(.horizontal, 6)
- .padding(.vertical, 2)
- .background(
- RoundedRectangle(cornerRadius: 4)
- .fill(self.theme.palette.accent.opacity(0.15))
- )
- }
+ private func detailHeading(_ entry: TranscriptionHistoryEntry) -> some View {
+ HStack(spacing: 14) {
+ Image(systemName: "clock.arrow.circlepath")
+ .font(.system(size: 24, weight: .medium))
+ .foregroundStyle(self.theme.palette.accent)
+ .frame(width: 52, height: 52)
+ .background(self.theme.palette.accent.opacity(0.1), in: RoundedRectangle(cornerRadius: 16))
+ VStack(alignment: .leading, spacing: 5) {
+ Text("Dictation details").font(self.theme.typography.title)
+ Text(entry.fullDateString).font(self.theme.typography.caption).foregroundStyle(.secondary)
}
-
- Text(content)
- .font(.system(size: 14, design: .default))
- .foregroundStyle(isSecondary ? .secondary : .primary)
- .textSelection(.enabled)
- .padding(14)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(RoundedRectangle(cornerRadius: 10)
- .fill(self.theme.palette.cardBackground)
- .overlay(RoundedRectangle(cornerRadius: 10)
- .stroke(self.theme.palette.cardBorder.opacity(isSecondary ? 0.35 : 0.5), lineWidth: 1)))
}
}
- private func metadataGrid(_ entry: TranscriptionHistoryEntry) -> some View {
- VStack(alignment: .leading, spacing: 12) {
- Text("Details")
- .font(.system(size: 12, weight: .semibold))
- .foregroundStyle(.secondary)
- .textCase(.uppercase)
- .tracking(0.5)
-
- LazyVGrid(columns: [
- GridItem(.flexible(), spacing: 16),
- GridItem(.flexible(), spacing: 16),
- ], spacing: 12) {
- self.metadataItem(icon: "app.fill", label: "Application", value: entry.appName.isEmpty ? "Unknown" : entry.appName)
- self.metadataItem(icon: "macwindow", label: "Window", value: entry.windowTitle.isEmpty ? "Unknown" : entry.windowTitle)
- self.metadataItem(icon: "character.cursor.ibeam", label: "Characters", value: "\(entry.characterCount)")
- self.metadataItem(icon: "sparkles", label: "AI Processed", value: entry.wasAIProcessed ? "Yes" : "No")
- if self.settings.showHistoryPerformanceMetrics,
- let duration = entry.transcriptionDurationMilliseconds
- {
- self.metadataItem(
- icon: "waveform",
- label: "Transcription Time",
- value: TranscriptionHistoryEntry.formattedDuration(milliseconds: duration)
- )
- }
- if self.settings.showHistoryPerformanceMetrics,
- let duration = entry.aiProcessingDurationMilliseconds
- {
- self.metadataItem(
- icon: "sparkles",
- label: "Cleanup Time",
- value: TranscriptionHistoryEntry.formattedDuration(milliseconds: duration)
+ private var detailColumns: [GridItem] {
+ Array(repeating: GridItem(.flexible(minimum: 0), spacing: 16, alignment: .leading), count: 3)
+ }
+
+ private func recordedModel(_ entry: TranscriptionHistoryEntry) -> String? {
+ guard let model = entry.processingModel?.trimmingCharacters(in: .whitespacesAndNewlines), !model.isEmpty else { return nil }
+ return ModelDisplayName.forID(model)
+ }
+
+ private func detailActions(_ entry: TranscriptionHistoryEntry) -> some View {
+ FluidGlassControlGroup {
+ HStack(spacing: 8) {
+ Button { self.copyFinalText(entry) } label: {
+ Label(
+ self.copiedEntryID == entry.id ? "Copied" : "Copy text",
+ systemImage: self.copiedEntryID == entry.id ? "checkmark" : "doc.on.doc"
)
}
- if self.settings.showHistoryPerformanceMetrics,
- let tokensPerSecond = entry.aiTokensPerSecond
- {
- self.metadataItem(
- icon: "speedometer",
- label: "AI Speed",
- value: TranscriptionHistoryEntry.formattedTokensPerSecond(tokensPerSecond)
- )
+ .fluidGlassAction(prominent: true)
+ .disabled(entry.clipboardText == nil)
+ if self.hasAudio(entry) {
+ Button {
+ self.audioEntryID = self.audioEntryID == entry.id ? nil : entry.id
+ } label: {
+ Label(self.audioEntryID == entry.id ? "Close audio" : "Audio", systemImage: "waveform")
+ }
+ .fluidGlassAction()
}
- self.metadataItem(icon: "waveform", label: "Audio", value: self.audioMetadataText(for: entry))
+ Menu { self.entryActions(entry) } label: { Image(systemName: "ellipsis") }
+ .menuIndicator(.hidden)
+ .fluidGlassAction(circular: true)
+ .accessibilityLabel("Dictation actions")
}
}
}
- private func metadataItem(icon: String, label: String, value: String) -> some View {
- HStack(spacing: 10) {
- Image(systemName: icon)
- .font(.system(size: 12, weight: .medium))
- .foregroundStyle(.tertiary)
- .frame(width: 20)
-
- VStack(alignment: .leading, spacing: 2) {
- Text(label)
- .font(.system(size: 10, weight: .medium))
- .foregroundStyle(.tertiary)
+ @ViewBuilder
+ private func secondaryActions(_ entry: TranscriptionHistoryEntry) -> some View {
+ if self.hasAudio(entry) {
+ Button { self.exportPair(entry) } label: {
+ Label("Export pair", systemImage: "square.and.arrow.up")
+ }
+ .fluidGlassAction()
+ }
+ Button { self.openFeedbackReport(for: entry) } label: {
+ Label("Report issue", systemImage: "hand.thumbsup.slash")
+ }
+ .fluidGlassAction()
+ }
- Text(value)
- .font(.system(size: 12, weight: .medium))
- .foregroundStyle(.primary)
- .lineLimit(1)
+ private func metadataItem(icon: String, label: String, value: String) -> some View {
+ HStack(spacing: 12) {
+ Image(systemName: icon).font(.system(size: 18)).foregroundStyle(self.theme.palette.accent)
+ .frame(width: 24)
+ VStack(alignment: .leading, spacing: 5) {
+ Text(label).font(self.theme.typography.caption).foregroundStyle(.secondary)
+ Text(value).font(self.theme.typography.bodyStrong).monospacedDigit()
}
+ Spacer(minLength: 0)
+ }
+ }
- Spacer()
+ private func copyFinalText(_ entry: TranscriptionHistoryEntry) {
+ guard let text = entry.clipboardText else { return }
+ self.copyToClipboard(text)
+ self.copyFeedbackTask?.cancel()
+ self.copiedEntryID = entry.id
+ self.copyFeedbackTask = Task { @MainActor in
+ do { try await Task.sleep(for: .seconds(1.5)) } catch { return }
+ self.copiedEntryID = nil
}
- .padding(10)
- .background(RoundedRectangle(cornerRadius: 8)
- .fill(self.theme.palette.cardBackground.opacity(0.9)))
- }
-
- private func processingBadge(
- text: String,
- isSelected: Bool,
- isAccent: Bool
- ) -> some View {
- Text(text)
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(
- isSelected ? .white.opacity(0.8) : (isAccent ? self.theme.palette.accent : Color.secondary)
- )
- .padding(.horizontal, 4)
- .padding(.vertical, 1)
- .background(
- RoundedRectangle(cornerRadius: 3)
- .fill(
- isSelected
- ? .white.opacity(0.2)
- : (isAccent ? self.theme.palette.accent.opacity(0.15) : Color.secondary.opacity(0.12))
- )
- )
}
private func copyToClipboard(_ text: String) {
@@ -660,7 +581,8 @@ struct TranscriptionHistoryView: View {
}
private func hasAudio(_ entry: TranscriptionHistoryEntry) -> Bool {
- DictationAudioHistoryStore.shared.audioFileExists(for: entry)
+ guard let audio = entry.audio else { return false }
+ return self.availableAudioFiles.contains(audio.fileName)
}
private func audioMetadataText(for entry: TranscriptionHistoryEntry) -> String {
diff --git a/Tests/DictationDefaultProviderTests.swift b/Tests/DictationDefaultProviderTests.swift
new file mode 100644
index 00000000..160c59db
--- /dev/null
+++ b/Tests/DictationDefaultProviderTests.swift
@@ -0,0 +1,37 @@
+import Foundation
+
+// Minimal settings types let the production read-only resolver run without launching the app.
+enum SettingsStore {
+ enum DictationPromptSelection: Equatable { case off, `default`, privateAI, profile(String) }
+ struct DictationPromptConfiguration { var providerID: String; var modelName: String }
+}
+
+@main
+enum DictationDefaultProviderTests {
+ static func main() {
+ func resolve(_ selection: SettingsStore.DictationPromptSelection, _ global: String, _ provider: String = "", _ model: String = "") -> String {
+ DictationDefaultProvider.providerID(
+ selection: selection,
+ configuration: .init(providerID: provider, modelName: model),
+ selectedProviderID: global,
+ privateProviderID: "fluid-1"
+ )
+ }
+ precondition(resolve(.off, "openai", "openrouter", "model") == "")
+ precondition(resolve(.privateAI, "openai") == "fluid-1")
+ precondition(resolve(.default, "openai") == "openai")
+ precondition(resolve(.default, "openai", " openrouter ", " model ") == "openrouter")
+ precondition(resolve(.profile("style"), "openai", "custom-provider", "model") == "custom-provider")
+ precondition(resolve(.default, "fluid-1") == "fluid-1")
+ precondition(resolve(.profile("style"), "fluid-1") == "")
+ precondition(resolve(.default, "fluid-1", "openai", "") == "")
+ precondition(resolve(.default, "openai", "openrouter", "") == "openai")
+ precondition(resolve(.default, "openai", "", "model") == "openai")
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: false, hasModel: true, isVerified: true, verificationFailed: false) == "API key missing")
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: false, hasAPIKey: false, hasModel: true, isVerified: true, verificationFailed: false) == nil)
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: false, isVerified: false, verificationFailed: false) == "Choose a model")
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: true, isVerified: false, verificationFailed: false) == nil, "Optional verification must not block a configured provider")
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: true, isVerified: false, verificationFailed: true) == "Verification failed")
+ print("PASS: 10 default-provider cases and 5 setup-status cases")
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift
new file mode 100644
index 00000000..d8e8b42c
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift
@@ -0,0 +1,1752 @@
+import CoreAudio
+#if canImport(FluidVoice_Debug)
+@testable import FluidVoice_Debug
+#else
+@testable import AudioRecoveryTestSupport
+#endif
+import Foundation
+import XCTest
+
+final class AudioHardwareRecoveryTests: XCTestCase {
+ func testUnreadableLivenessDoesNotAuthorizeUnsafeReplacement() {
+ XCTAssertFalse(DirectCoreAudioLifecycleController.hardwareIsKnownStopped(reason: "device_is_alive", deviceIsAlive: nil))
+ XCTAssertFalse(DirectCoreAudioLifecycleController.hardwareIsKnownStopped(reason: "device_is_alive", deviceIsAlive: true))
+ XCTAssertTrue(DirectCoreAudioLifecycleController.hardwareIsKnownStopped(reason: "device_is_alive", deviceIsAlive: false))
+ XCTAssertTrue(DirectCoreAudioLifecycleController.hardwareIsKnownStopped(reason: "io_stopped_abnormally", deviceIsAlive: nil))
+ XCTAssertFalse(DirectCoreAudioLifecycleController.hardwareIsKnownStopped(reason: "nominal_sample_rate", deviceIsAlive: nil))
+ }
+
+ func testRecoveryQueryCancellationCannotFailOrdinaryStartupDiscovery() async throws {
+ let input = RecoveryInput(block: "recovery_query")
+ defer { input.release.signal() }
+ let controller = DirectCoreAudioLifecycleController(
+ packetHandler: { _, _, _, _, _ in },
+ inputFactory: { _, _ in input },
+ fingerprintReader: { _ in input.formatFingerprint },
+ installsHardwareListeners: false,
+ deviceSnapshotReader: { refreshLiveness in
+ if refreshLiveness { input.perform("recovery_query") }
+ return .init(devices: [], defaultInputUID: nil)
+ },
+ onFormatInvalidated: { _ in }
+ )
+ let recoveryQuery = Task { try await controller.readDeviceSnapshot(refreshLiveness: true) }
+ try await waitForEvent(input, "recovery_query")
+ recoveryQuery.cancel()
+ _ = try? await recoveryQuery.value
+ let began = ProcessInfo.processInfo.systemUptime
+ _ = try await controller.readCaptureDeviceSnapshot()
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - began, 0.2)
+ XCTAssertFalse(controller.isRecoveringHardware)
+ XCTAssertEqual(input.count("start"), 0)
+ input.release.signal()
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testRestartWaitCanBeCancelledWithoutTouchingBlockedNativeCall() async throws {
+ let input = RecoveryInput(block: "start")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input, timeout: nil)
+ let starting = Task { try await controller.start(deviceID: 144, deviceName: "Test", reason: "cancel") }
+ try await waitForEvent(input, "start")
+ controller.cancelPendingStartup()
+ _ = try? await starting.value
+ let waiting = Task { await controller.waitForPendingHardwareRetirement() }
+ waiting.cancel()
+ let available = await waiting.value
+ XCTAssertFalse(available)
+ XCTAssertEqual(input.count("start"), 1)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ _ = try await controller.start(deviceID: 144, deviceName: "Test", reason: "safe_restart")
+ XCTAssertEqual(input.count("start"), 2)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testAvailabilityWaitersResumeOnlyAfterCleanupAndCancellationStaysLocal() async throws {
+ let input = RecoveryInput(block: "start")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input, timeout: 1)
+ let initiallyAvailable = await controller.waitForHardwareAvailability()
+ XCTAssertTrue(initiallyAvailable)
+ let starting = Task { try await controller.start(deviceID: 144, deviceName: "Test", reason: "waiters") }
+ try await waitForEvent(input, "start")
+ starting.cancel()
+ _ = try? await starting.value
+ let waiters = (0..<40).map { _ in Task { await controller.waitForHardwareAvailability() } }
+ for waiter in waiters.prefix(20) {
+ waiter.cancel()
+ }
+ for waiter in waiters.prefix(20) {
+ let available = await waiter.value
+ XCTAssertFalse(available)
+ }
+ XCTAssertTrue(controller.isRecoveringHardware)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ input.release.signal()
+ for waiter in waiters.suffix(20) {
+ let available = await waiter.value
+ XCTAssertTrue(available)
+ }
+ XCTAssertFalse(controller.isRecoveringHardware)
+ XCTAssertEqual(input.count("start"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testAvailabilityWaitEndsWhenCleanupNeverBecomesSafe() async throws {
+ let input = RecoveryInput(block: "start", cleanupFails: true)
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input)
+ _ = try? await controller.start(deviceID: 144, deviceName: "Test", reason: "unresolved_cleanup")
+ input.release.signal()
+ let began = ProcessInfo.processInfo.systemUptime
+ let available = await controller.waitForHardwareAvailability()
+ XCTAssertFalse(available)
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - began, 0.5)
+ XCTAssertEqual(input.count("start"), 1)
+ XCTAssertTrue(controller.isRecoveringHardware)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testBlockedStartTimesOutAndDropsLatePacketsUntilCleanupCompletes() async throws {
+ let input = RecoveryInput(block: "start")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input)
+ let began = ProcessInfo.processInfo.systemUptime
+ do {
+ _ = try await controller.start(deviceID: 144, deviceName: "Test", reason: "timeout")
+ XCTFail("Blocked startup must time out")
+ } catch {
+ XCTAssertTrue(error is BoundedAudioHardwareQueue.Failure)
+ }
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - began, 1)
+ XCTAssertTrue(controller.isRecoveringHardware)
+ XCTAssertEqual(controller.snapshot.phase, .failed)
+ XCTAssertEqual(input.count("start"), 1)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 0)
+ do {
+ _ = try await controller.start(deviceID: 144, deviceName: "Test", reason: "retry_while_blocked")
+ XCTFail("A second native start must not overlap the blocked one")
+ } catch {}
+ XCTAssertEqual(input.count("start"), 1)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ XCTAssertEqual(input.count("open"), 0, "A timed-out start must never open its packet gate")
+ XCTAssertGreaterThan(input.count("invalidate"), 0)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 0, "Retired packets remain rejected after recovery")
+ let retried = try await controller.start(deviceID: 144, deviceName: "Test", reason: "retry_after_cleanup")
+ XCTAssertEqual(retried.phase, .running)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testPostStartFingerprintTimeoutNeverOpensPacketGate() async throws {
+ let input = RecoveryInput(block: "post_start_fingerprint")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input)
+ do {
+ _ = try await controller.start(deviceID: 144, deviceName: "Test", reason: "blocked_post_start_query")
+ XCTFail("Post-start hardware validation must time out")
+ } catch {
+ XCTAssertTrue(error is BoundedAudioHardwareQueue.Failure)
+ }
+ XCTAssertEqual(input.count("start"), 1)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 0)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ XCTAssertEqual(input.count("open"), 0)
+ XCTAssertFalse(input.isRunning)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testDeviceQueryTimeoutDoesNotStopRecordingOrDropItsAudio() async throws {
+ let input = RecoveryInput(block: "query")
+ defer { input.release.signal() }
+ let controller = DirectCoreAudioLifecycleController(
+ packetHandler: { _, _, _, _, _ in input.record("delivered") },
+ inputFactory: { _, handler in input.setHandler(handler); return input },
+ fingerprintReader: { _ in input.formatFingerprint },
+ installsHardwareListeners: false,
+ operationTimeout: 0.08,
+ deviceSnapshotReader: { _ in
+ input.perform("query")
+ return .init(devices: [], defaultInputUID: nil)
+ },
+ onFormatInvalidated: { _ in }
+ )
+ _ = try await controller.start(deviceID: 144, deviceName: "Test", reason: "recording")
+ do {
+ _ = try await controller.readDeviceSnapshot()
+ XCTFail("Device enumeration must time out")
+ } catch {
+ XCTAssertTrue(error is BoundedAudioHardwareQueue.Failure)
+ }
+ XCTAssertEqual(controller.snapshot.phase, .running)
+ XCTAssertFalse(controller.isRecoveringHardware)
+ XCTAssertEqual(input.count("stop"), 0)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 1)
+ input.release.signal()
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testExplicitCancellationAndShutdownReturnBeforeNativeStartDoes() async throws {
+ let input = RecoveryInput(block: "start")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input, timeout: 1)
+ let starting = Task {
+ try await controller.start(deviceID: 144, deviceName: "Test", reason: "cancel")
+ }
+ try await waitForEvent(input, "start")
+ controller.cancelPendingStartup()
+ let began = ProcessInfo.processInfo.systemUptime
+ do {
+ _ = try await starting.value
+ XCTFail("Cancelled startup must not report success")
+ } catch {
+ XCTAssertTrue(error is CancellationError)
+ }
+ await controller.shutdown(reason: "quit_while_starting")
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - began, 0.5)
+ XCTAssertEqual(input.count("invalidate"), 0, "Do not tear down a native call concurrently")
+ input.release.signal()
+ try await waitForRecovery(controller)
+ XCTAssertEqual(controller.snapshot.phase, .shutDown)
+ XCTAssertEqual(input.count("open"), 0)
+ do {
+ _ = try await controller.start(deviceID: 144, deviceName: "Test", reason: "after_quit")
+ XCTFail("Late completion must not undo shutdown")
+ } catch {}
+ XCTAssertEqual(input.count("start"), 1)
+ }
+
+ func testTaskCancellationWakesCallerAndPreservesSerializedCleanup() async throws {
+ let input = RecoveryInput(block: "start")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input, timeout: 1)
+ let starting = Task {
+ try await controller.start(deviceID: 144, deviceName: "Test", reason: "task_cancel")
+ }
+ try await waitForEvent(input, "start")
+ starting.cancel()
+ do {
+ _ = try await starting.value
+ XCTFail("Task cancellation must wake the caller")
+ } catch {
+ XCTAssertTrue(error is CancellationError)
+ }
+ XCTAssertEqual(input.count("invalidate"), 0)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ XCTAssertGreaterThan(input.count("invalidate"), 0)
+ XCTAssertEqual(input.count("open"), 0)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testBlockedPreparationIsAlsoBoundedAndLateInputIsDestroyed() async throws {
+ let input = RecoveryInput(block: "prepare")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input)
+ do {
+ _ = try await controller.prepare(deviceID: 144, deviceName: "Test", reason: "blocked_prepare")
+ XCTFail("Preparation must also have a deadline")
+ } catch {
+ XCTAssertTrue(error is BoundedAudioHardwareQueue.Failure)
+ }
+ XCTAssertEqual(input.count("start"), 0)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ XCTAssertGreaterThan(input.count("invalidate"), 0)
+ XCTAssertEqual(input.count("start"), 0)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testBlockedStopReturnsFailureWithoutStartingReplacementHardware() async throws {
+ let input = RecoveryInput(block: "stop")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input)
+ _ = try await controller.start(deviceID: 144, deviceName: "Test", reason: "before_stop")
+ let result = await controller.stop(retainPrepared: true, reason: "blocked_stop")
+ XCTAssertNotEqual(result.status, noErr)
+ XCTAssertFalse(result.retainedPreparedCapture)
+ XCTAssertTrue(controller.isRecoveringHardware)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 0)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ XCTAssertEqual(input.count("start"), 1)
+ XCTAssertFalse(controller.snapshot.isPrepared)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testFailedCleanupKeepsHardwareUnavailable() async throws {
+ let input = RecoveryInput(block: "start", cleanupFails: true)
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input)
+ _ = try? await controller.start(deviceID: 144, deviceName: "Test", reason: "timeout")
+ input.release.signal()
+ try await waitForEvent(input, "invalidate")
+ // A query must fail promptly even if cleanup cannot safely release the IOProc.
+ do {
+ _ = try await controller.prepare(deviceID: 144, deviceName: "Test", reason: "unsafe_retry")
+ XCTFail("Failed teardown must not create replacement hardware")
+ } catch {}
+ XCTAssertTrue(controller.isRecoveringHardware)
+ XCTAssertEqual(input.count("prepare"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testCancelledQueuedStartNeverCallsHardwareLater() async throws {
+ let input = RecoveryInput(block: "prepare")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input, timeout: 1)
+ let preparing = Task {
+ try await controller.prepare(deviceID: 144, deviceName: "Test", reason: "prewarm")
+ }
+ try await waitForEvent(input, "prepare")
+ let starting = Task {
+ try await controller.start(deviceID: 144, deviceName: "Test", reason: "queued_start")
+ }
+ starting.cancel()
+ _ = try? await starting.value
+ input.release.signal()
+ _ = try? await preparing.value
+ try await waitForRecovery(controller)
+ XCTAssertEqual(input.count("start"), 0)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testPropertyListenerUsesRegisteredDeviceRatherThanAddressCount() {
+ let input = RecoveryInput()
+ let listener = DirectCoreAudioLifecycleController.makeDevicePropertyListener(objectID: 144) { objectID in
+ input.record("device_\(objectID)")
+ }
+ var addresses = [
+ AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyDeviceIsAlive, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain),
+ AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyStreams, mScope: kAudioObjectPropertyScopeInput, mElement: kAudioObjectPropertyElementMain),
+ ]
+ addresses.withUnsafeMutableBufferPointer { buffer in
+ guard let base = buffer.baseAddress else { return }
+ listener(1, base)
+ listener(2, base)
+ }
+ XCTAssertEqual(input.count("device_144"), 2)
+ XCTAssertEqual(input.count("device_1"), 0)
+ XCTAssertEqual(input.count("device_2"), 0)
+ }
+}
+
+final class MonitorTopologyRecoveryTests: XCTestCase {
+ func testHealthyTopologyChangeDoesNotQueryLivenessOrInterruptCapture() async throws {
+ let input = RecoveryInput()
+ let probe = FailedDeviceLivenessProbe()
+ let controller = makeRecoveryController(input, timeout: nil, deviceLivenessReader: { probe.read($0) })
+ _ = try await controller.start(deviceID: 144, deviceName: "Healthy", reason: "recording")
+ for _ in 0..<100 { controller.noteHardwareTopologyChanged() }
+ try await waitForTopologyCheck(controller)
+ input.emit()
+ XCTAssertTrue(probe.deviceIDs.isEmpty)
+ XCTAssertEqual(controller.snapshot.phase, .running)
+ XCTAssertEqual(input.count("stop"), 0)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ XCTAssertEqual(input.count("delivered"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testGlobalTopologyRemovalClearsFailedCleanupAndAllowsNextRecording() async throws {
+ let input = RecoveryInput(block: "start", cleanupFails: true)
+ let probe = FailedDeviceLivenessProbe()
+ let controller = makeRecoveryController(input, deviceLivenessReader: { probe.read($0) })
+ defer { input.release.signal() }
+ _ = try? await controller.start(deviceID: 144, deviceName: "Removed", reason: "failed_start")
+ input.release.signal()
+ try await waitForFailedCleanup(controller)
+ try await waitForTopologyCheck(controller)
+ XCTAssertTrue(controller.isRecoveringHardware)
+ XCTAssertEqual(probe.deviceIDs, [144])
+
+ // This is the actual entry point used by the global HAL device-list
+ // listener, after invalidate() has removed all per-device listeners.
+ probe.setAlive(false)
+ controller.noteHardwareTopologyChanged()
+ try await waitForTopologyCheck(controller)
+ XCTAssertFalse(controller.isRecoveringHardware)
+ let replacement = try await controller.start(deviceID: 144, deviceName: "Replacement", reason: "next_recording")
+ input.emit()
+ XCTAssertEqual(replacement.phase, .running)
+ XCTAssertEqual(input.count("delivered"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testUnrelatedTopologyAndUnknownLivenessKeepFailedCleanupBlocked() async throws {
+ let input = RecoveryInput(block: "start", cleanupFails: true)
+ let probe = FailedDeviceLivenessProbe()
+ let controller = makeRecoveryController(input, deviceLivenessReader: { probe.read($0) })
+ defer { input.release.signal() }
+ _ = try? await controller.start(deviceID: 144, deviceName: "Still connected", reason: "failed_start")
+ input.release.signal()
+ try await waitForFailedCleanup(controller)
+ try await waitForTopologyCheck(controller)
+ for alive in [true, nil] as [Bool?] {
+ probe.setAlive(alive)
+ for _ in 0..<100 { controller.noteHardwareTopologyChanged() }
+ try await waitForTopologyCheck(controller)
+ XCTAssertTrue(controller.isRecoveringHardware)
+ XCTAssertEqual(input.count("prepare"), 1)
+ XCTAssertEqual(input.count("delivered"), 0)
+ }
+ XCTAssertTrue(probe.deviceIDs.allSatisfy { $0 == 144 })
+ XCTAssertLessThan(probe.deviceIDs.count, 10, "Coalesce event bursts instead of querying once per notification")
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testRemovalDuringBlockedNativeWorkWaitsForItsCleanup() async throws {
+ let input = RecoveryInput(block: "start", cleanupFails: true)
+ let probe = FailedDeviceLivenessProbe(alive: false)
+ let controller = makeRecoveryController(input, deviceLivenessReader: { probe.read($0) })
+ defer { input.release.signal() }
+ _ = try? await controller.start(deviceID: 144, deviceName: "Removed", reason: "failed_start")
+ for _ in 0..<100 { controller.noteHardwareTopologyChanged() }
+ try await Task.sleep(nanoseconds: 20_000_000)
+ XCTAssertTrue(controller.isRecoveringHardware)
+ XCTAssertTrue(probe.deviceIDs.isEmpty, "Do not check or unlock while native startup owns capture")
+ XCTAssertEqual(input.count("invalidate"), 0)
+ XCTAssertEqual(input.count("prepare"), 1)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ XCTAssertEqual(input.count("invalidate"), 1)
+ XCTAssertEqual(probe.deviceIDs, [144])
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testRemovalDuringLivenessQueryRechecksTheLatestTopology() async throws {
+ let input = RecoveryInput(block: "start", cleanupFails: true)
+ let probe = FailedDeviceLivenessProbe()
+ let controller = makeRecoveryController(input, timeout: 1, deviceLivenessReader: { probe.read($0) })
+ defer { input.release.signal(); probe.release.signal() }
+ let starting = Task { try await controller.start(deviceID: 144, deviceName: "Old", reason: "old_start") }
+ try await waitForEvent(input, "start")
+ starting.cancel()
+ _ = try? await starting.value
+ input.release.signal()
+ try await waitForFailedCleanup(controller)
+ try await waitForTopologyCheck(controller)
+ probe.blockNextRead(alive: true)
+ controller.noteHardwareTopologyChanged()
+ try await probe.waitForReadCount(2)
+ probe.setAlive(false)
+ controller.noteHardwareTopologyChanged()
+ probe.release.signal()
+ try await waitForRecovery(controller)
+ try await waitForTopologyCheck(controller)
+ XCTAssertEqual(probe.deviceIDs.count, 3, "Recheck after the in-flight query returns an older snapshot")
+ XCTAssertEqual(controller.snapshot.phase, .empty)
+ XCTAssertEqual(input.count("prepare"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testLateLivenessResultCannotClearOrStopNewCapture() async throws {
+ let input = RecoveryInput(block: "start", cleanupFails: true)
+ let probe = FailedDeviceLivenessProbe()
+ let controller = makeRecoveryController(input, timeout: 1, deviceLivenessReader: { probe.read($0) })
+ defer { input.release.signal(); probe.release.signal() }
+ let starting = Task { try await controller.start(deviceID: 144, deviceName: "Old", reason: "old_start") }
+ try await waitForEvent(input, "start")
+ starting.cancel()
+ _ = try? await starting.value
+ input.release.signal()
+ try await waitForFailedCleanup(controller)
+ try await waitForTopologyCheck(controller)
+ let oldGeneration = controller.snapshot.generation
+ probe.blockNextRead(alive: false)
+ controller.noteHardwareTopologyChanged()
+ try await probe.waitForReadCount(2)
+ // A valid per-device signal wins the race and admits a new generation.
+ await controller.simulateStoppedHardwareNotificationForTesting(generation: oldGeneration, reason: "device_is_alive")
+ let replacement = try await controller.start(deviceID: 144, deviceName: "New", reason: "replacement")
+ probe.release.signal()
+ try await waitForTopologyCheck(controller)
+ input.emit()
+ XCTAssertGreaterThan(replacement.generation, oldGeneration)
+ XCTAssertEqual(controller.snapshot.phase, .running)
+ XCTAssertEqual(input.count("invalidate"), 1)
+ XCTAssertEqual(input.count("delivered"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testBlockedTopologyQueryDoesNotUnlockAndShutdownCannotBeReversed() async throws {
+ let input = RecoveryInput(block: "start", cleanupFails: true)
+ let probe = FailedDeviceLivenessProbe()
+ let controller = makeRecoveryController(input, deviceLivenessReader: { probe.read($0) })
+ defer { input.release.signal(); probe.release.signal() }
+ _ = try? await controller.start(deviceID: 144, deviceName: "Old", reason: "failed_start")
+ input.release.signal()
+ try await waitForFailedCleanup(controller)
+ try await waitForTopologyCheck(controller)
+ probe.blockNextRead(alive: false)
+ controller.noteHardwareTopologyChanged()
+ try await probe.waitForReadCount(2)
+ try await waitForTopologyCheck(controller)
+ XCTAssertTrue(controller.isRecoveringHardware, "Timed-out liveness is unknown, not proof of removal")
+ await controller.shutdown(reason: "test_complete")
+ probe.release.signal()
+ controller.noteHardwareTopologyChanged()
+ try await Task.sleep(nanoseconds: 20_000_000)
+ XCTAssertTrue(controller.isRecoveringHardware)
+ XCTAssertEqual(input.count("prepare"), 1)
+ XCTAssertEqual(input.count("delivered"), 0)
+ }
+
+ func testDisplayTopologyChangeRefreshesUnchangedPreparedInputOnlyOnce() async throws {
+ let input = RecoveryInput()
+ let controller = makeDefaultRecoveryController(input)
+ let old = try await controller.prepare(deviceID: 144, deviceName: "Test", reason: "before_display")
+ for _ in 0..<100 {
+ controller.noteHardwareTopologyChanged()
+ }
+ // Even a prewarm during topology churn is refreshed at actual demand.
+ _ = try await controller.prepare(deviceID: 144, deviceName: "Test", reason: "idle_prewarm")
+ XCTAssertEqual(input.count("invalidate"), 0)
+ let fresh = try await controller.start(deviceID: 144, deviceName: "Test", reason: "after_display")
+ XCTAssertGreaterThan(fresh.generation, old.generation)
+ XCTAssertEqual(input.count("prepare"), 2)
+ XCTAssertEqual(input.count("invalidate"), 1)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 1)
+ _ = await controller.stop(retainPrepared: true, reason: "stop")
+ let reused = try await controller.start(deviceID: 144, deviceName: "Test", reason: "ordinary_next_start")
+ XCTAssertEqual(reused.generation, fresh.generation)
+ XCTAssertEqual(input.count("prepare"), 2)
+ XCTAssertEqual(input.count("invalidate"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testDisplayChangeDoesNotInterruptRunningAudioButRefreshesAfterStop() async throws {
+ let input = RecoveryInput()
+ let controller = makeDefaultRecoveryController(input)
+ let running = try await controller.start(deviceID: 144, deviceName: "Test", reason: "running")
+ controller.noteHardwareTopologyChanged()
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 1)
+ XCTAssertEqual(input.count("stop"), 0)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ XCTAssertEqual(controller.snapshot.phase, .running)
+ _ = await controller.stop(retainPrepared: true, reason: "user_stop")
+ let fresh = try await controller.start(deviceID: 144, deviceName: "Test", reason: "next_start")
+ XCTAssertGreaterThan(fresh.generation, running.generation)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testRunningPreviewHandoffDoesNotDiscardOpeningAudioAfterDisplayChange() async throws {
+ let input = RecoveryInput()
+ let controller = makeDefaultRecoveryController(input)
+ let preview = try await controller.start(deviceID: 144, deviceName: "Test", reason: "preview")
+ controller.noteHardwareTopologyChanged()
+ let handoff = try await controller.start(deviceID: 144, deviceName: "Test", reason: "handoff")
+ input.emit()
+ XCTAssertEqual(handoff.generation, preview.generation)
+ XCTAssertEqual(input.count("start"), 1)
+ XCTAssertEqual(input.count("stop"), 0)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ XCTAssertEqual(input.count("delivered"), 1)
+ _ = await controller.stop(retainPrepared: true, reason: "handoff_recording_stopped")
+ let next = try await controller.start(deviceID: 144, deviceName: "Test", reason: "after_handoff")
+ XCTAssertGreaterThan(next.generation, handoff.generation, "Handoff must preserve the pending topology rebuild")
+ XCTAssertEqual(input.count("invalidate"), 1)
+ XCTAssertEqual(input.count("start"), 2)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testCancelledStartupDiscoveryReturnsWhileHALIsBlockedAndLeavesCaptureAlone() async throws {
+ let input = RecoveryInput(block: "query")
+ defer { input.release.signal() }
+ let controller = DirectCoreAudioLifecycleController(
+ packetHandler: { _, _, _, _, _ in input.record("delivered") },
+ inputFactory: { _, handler in input.setHandler(handler); return input },
+ fingerprintReader: { _ in input.formatFingerprint },
+ installsHardwareListeners: false,
+ deviceSnapshotReader: { _ in input.perform("query"); return .init(devices: [], defaultInputUID: nil) },
+ onFormatInvalidated: { _ in }
+ )
+ _ = try await controller.start(deviceID: 144, deviceName: "Test", reason: "existing_capture")
+ let query = Task { try await controller.readCaptureDeviceSnapshot() }
+ try await waitForEvent(input, "query")
+ let began = ProcessInfo.processInfo.systemUptime
+ query.cancel()
+ do { _ = try await query.value; XCTFail("Cancelled discovery must fail") } catch { XCTAssertTrue(error is CancellationError) }
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - began, 0.2)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 1)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ XCTAssertFalse(controller.isRecoveringHardware)
+ do { _ = try await controller.readCaptureDeviceSnapshot(); XCTFail("Do not pile up blocked queries") } catch { XCTAssertTrue(error is BoundedAudioHardwareQueue.Failure) }
+ XCTAssertEqual(input.count("query"), 1)
+ input.release.signal()
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testFailedHardwareRetirementWaitHasDeadlineWithoutStartingReplacement() async throws {
+ let input = RecoveryInput(block: "start")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input, timeout: 0.08)
+ _ = try? await controller.start(deviceID: 144, deviceName: "Test", reason: "blocked")
+ let began = ProcessInfo.processInfo.systemUptime
+ let available = await controller.waitForPendingHardwareRetirement()
+ XCTAssertFalse(available)
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - began, 0.5)
+ XCTAssertEqual(input.count("start"), 1)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testAbnormalStopReleasesBlockedStartOnceAndRejectsLateGenerationEvents() async throws {
+ let input = RecoveryInput(block: "start")
+ defer { input.release.signal() }
+ let controller = DirectCoreAudioLifecycleController(
+ packetHandler: { _, _, _, _, _ in input.record("delivered") },
+ inputFactory: { _, handler in input.setHandler(handler); return input },
+ fingerprintReader: { _ in input.formatFingerprint },
+ installsHardwareListeners: false,
+ onFormatInvalidated: { _ in input.record("notification") }
+ )
+ let starting = Task { try await controller.start(deviceID: 144, deviceName: "Test", reason: "blocked") }
+ try await waitForEvent(input, "start")
+ let generation = controller.snapshot.generation
+ let began = ProcessInfo.processInfo.systemUptime
+ for _ in 0..<100 {
+ controller.simulateAbnormalStopNotificationForTesting(generation: generation)
+ }
+ do { _ = try await starting.value; XCTFail("Known failed startup must release its caller") } catch { XCTAssertTrue(error is BoundedAudioHardwareQueue.Failure) }
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - began, 0.2)
+ XCTAssertEqual(input.count("notification"), 1)
+ XCTAssertEqual(input.count("invalidate"), 0, "Native startup still owns the resources")
+ XCTAssertEqual(input.count("open"), 0)
+ _ = try? await controller.start(deviceID: 144, deviceName: "Test", reason: "unsafe_retry")
+ XCTAssertEqual(input.count("start"), 1)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ let fresh = try await controller.start(deviceID: 144, deviceName: "Test", reason: "safe_retry")
+ XCTAssertGreaterThan(fresh.generation, generation)
+ controller.simulateAbnormalStopNotificationForTesting(generation: generation)
+ XCTAssertEqual(input.count("notification"), 1)
+ XCTAssertEqual(controller.snapshot.phase, .running)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+}
+
+/// This same class is also run against the original controller for comparison.
+final class NormalAudioCaptureCompatibilityTests: XCTestCase {
+ func testHealthySlowNativeStartsAtFiveAndTenSecondsSucceed() async throws {
+ for delay in [5.2, 10.0] {
+ let input = RecoveryInput(delays: ["start": delay])
+ let controller = makeDefaultRecoveryController(input)
+ let started = try await controller.start(deviceID: 144, deviceName: "Test", reason: "healthy_slow")
+ XCTAssertEqual(started.phase, .running)
+ XCTAssertEqual(input.count("open"), 1)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 1)
+ await controller.shutdown(reason: "test_complete")
+ }
+ }
+
+ func testHealthySlowPostStartFingerprintStillSucceeds() async throws {
+ let input = RecoveryInput(delays: ["post_start_fingerprint": 5.2])
+ let controller = makeDefaultRecoveryController(input)
+ let started = try await controller.start(deviceID: 144, deviceName: "Test", reason: "healthy_slow_fingerprint")
+ XCTAssertEqual(started.phase, .running)
+ XCTAssertEqual(input.count("open"), 1)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testHealthySlowStopStillRetainsPreparedInput() async throws {
+ let input = RecoveryInput(delays: ["stop": 5.2])
+ let controller = makeDefaultRecoveryController(input)
+ _ = try await controller.start(deviceID: 144, deviceName: "Test", reason: "before_slow_stop")
+ let stopped = await controller.stop(retainPrepared: true, reason: "normal_slow_stop")
+ XCTAssertEqual(stopped.status, noErr)
+ XCTAssertTrue(stopped.retainedPreparedCapture)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testFiftyHealthyPreparedStartStopCyclesRetainOneInput() async throws {
+ let input = RecoveryInput()
+ let controller = makeDefaultRecoveryController(input)
+ _ = try await controller.prepare(deviceID: 144, deviceName: "Test", reason: "prewarm")
+ for cycle in 1...50 {
+ let started = try await controller.start(deviceID: 144, deviceName: "Test", reason: "normal_start")
+ XCTAssertEqual(started.phase, .running)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), cycle)
+ let stopped = await controller.stop(retainPrepared: true, reason: "normal_stop")
+ XCTAssertEqual(stopped.status, noErr)
+ XCTAssertTrue(stopped.retainedPreparedCapture)
+ XCTAssertFalse(input.isRunning)
+ }
+ XCTAssertEqual(input.count("prepare"), 1)
+ XCTAssertEqual(input.count("start"), 50)
+ XCTAssertEqual(input.count("stop"), 50)
+ XCTAssertEqual(input.count("invalidate"), 0)
+ await controller.shutdown(reason: "test_complete")
+ }
+}
+
+private func makeDefaultRecoveryController(_ input: RecoveryInput) -> DirectCoreAudioLifecycleController {
+ DirectCoreAudioLifecycleController(
+ packetHandler: { _, _, _, _, _ in input.record("delivered") },
+ inputFactory: { _, handler in input.perform("prepare"); input.setHandler(handler); return input },
+ fingerprintReader: { _ in
+ if input.isRunning { input.perform("post_start_fingerprint") }
+ return input.formatFingerprint
+ },
+ installsHardwareListeners: false,
+ onFormatInvalidated: { _ in }
+ )
+}
+
+private func makeRecoveryController(
+ _ input: RecoveryInput,
+ timeout: TimeInterval? = 0.08,
+ deviceLivenessReader: @escaping @Sendable (AudioObjectID) -> Bool? = { _ in true }
+) -> DirectCoreAudioLifecycleController {
+ DirectCoreAudioLifecycleController(
+ packetHandler: { _, _, _, _, _ in input.record("delivered") },
+ inputFactory: { _, handler in
+ input.perform("prepare")
+ input.setHandler(handler)
+ return input
+ },
+ fingerprintReader: { _ in
+ if input.isRunning { input.perform("post_start_fingerprint") }
+ return input.formatFingerprint
+ },
+ installsHardwareListeners: false,
+ operationTimeout: timeout,
+ deviceLivenessReader: deviceLivenessReader,
+ onFormatInvalidated: { _ in }
+ )
+}
+
+private func waitForRecovery(_ controller: DirectCoreAudioLifecycleController) async throws {
+ for _ in 0..<1000 {
+ if controller.isRecoveringHardware == false { return }
+ try await Task.sleep(nanoseconds: 1_000_000)
+ }
+ XCTFail("Serialized recovery did not finish after releasing native hardware")
+}
+
+private func waitForEvent(_ input: RecoveryInput, _ event: String) async throws {
+ for _ in 0..<1000 {
+ if input.count(event) > 0 { return }
+ try await Task.sleep(nanoseconds: 1_000_000)
+ }
+ XCTFail("Native operation did not enter: \(event)")
+}
+
+private final nonisolated class RecoveryInput: DirectCoreAudioInputControlling, @unchecked Sendable {
+ let deviceID: AudioObjectID
+ let sampleRate: Double = 48_000
+ let hardwareBufferFrameSize: UInt32 = 512
+ let release = DispatchSemaphore(value: 0)
+ private let lock = NSLock()
+ private let blockedOperation: String?
+ private let cleanupFails: Bool
+ private let delays: [String: TimeInterval]
+ private let automaticPCM: Bool
+ private var events: [String: Int] = [:]
+ private var running = false
+ private var handler: DirectCoreAudioPacketHandler?
+
+ init(deviceID: AudioObjectID = 144, block: String? = nil, cleanupFails: Bool = false, delays: [String: TimeInterval] = [:], automaticPCM: Bool = false) {
+ self.deviceID = deviceID
+ self.blockedOperation = block
+ self.cleanupFails = cleanupFails
+ self.delays = delays
+ self.automaticPCM = automaticPCM
+ }
+
+ var formatFingerprint: DirectCoreAudioFormatFingerprint {
+ DirectCoreAudioFormatFingerprint(
+ deviceID: self.deviceID,
+ streamID: self.deviceID + 1,
+ virtualFormat: DirectCoreAudioStreamFormatFingerprint(AudioStreamBasicDescription(
+ mSampleRate: 48_000,
+ mFormatID: kAudioFormatLinearPCM,
+ mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
+ mBytesPerPacket: 4,
+ mFramesPerPacket: 1,
+ mBytesPerFrame: 4,
+ mChannelsPerFrame: 1,
+ mBitsPerChannel: 32,
+ mReserved: 0
+ )),
+ physicalFormat: nil,
+ inputBufferChannels: [1],
+ nominalSampleRate: 48_000,
+ bufferFrameSize: 512,
+ variableBufferFrameSizeMaximum: nil,
+ dataSourceID: nil
+ )
+ }
+
+ var isRunning: Bool { self.lock.withLock { self.running } }
+ var droppedPacketCount: UInt64 { 0 }
+ func count(_ event: String) -> Int { self.lock.withLock { self.events[event, default: 0] } }
+ func record(_ event: String) { self.lock.withLock { self.events[event, default: 0] += 1 } }
+ func setHandler(_ handler: @escaping DirectCoreAudioPacketHandler) { self.lock.withLock { self.handler = handler } }
+
+ func perform(_ event: String) {
+ let count = self.lock.withLock {
+ self.events[event, default: 0] += 1
+ return self.events[event, default: 0]
+ }
+ if event == self.blockedOperation, count == 1 {
+ // A broken watchdog fails the timing assertions without hanging the test runner.
+ _ = self.release.wait(timeout: .now() + 3)
+ }
+ if let delay = self.delays[event] { Thread.sleep(forTimeInterval: delay) }
+ }
+
+ func start() throws {
+ self.perform("start")
+ self.lock.withLock { self.running = true }
+ }
+
+ func stop() -> OSStatus {
+ self.perform("stop")
+ self.lock.withLock { self.running = false }
+ return noErr
+ }
+
+ func invalidate() -> OSStatus {
+ self.perform("invalidate")
+ self.lock.withLock { self.running = false }
+ return self.cleanupFails ? kAudioHardwareUnspecifiedError : noErr
+ }
+
+ func markFormatDirty() {}
+ func openPacketGateIfClean() -> Bool {
+ self.record("open")
+ if self.automaticPCM { self.emit() }
+ return true
+ }
+
+ func emit() {
+ let handler = self.lock.withLock { self.handler }
+ let samples = [Float](repeating: 0.5, count: 48)
+ samples.withUnsafeBufferPointer { buffer in
+ guard let baseAddress = buffer.baseAddress else { return }
+ handler?(baseAddress, buffer.count, 48_000, 0, 0)
+ }
+ }
+}
+
+#if canImport(FluidVoice_Debug)
+final class AudioRouteRecoveryIntegrationTests: XCTestCase {
+ @MainActor
+ func testStartupTriesNewMicrophoneMissingFromDeviceCache() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ fixture.hardware.enableNewFallback()
+ let outcome = await fixture.service.start(forDictionaryTraining: true)
+ XCTAssertEqual(outcome, .started)
+ XCTAssertTrue(fixture.service.isRunning)
+ XCTAssertEqual(fixture.controller.snapshot.deviceID, 300)
+ XCTAssertEqual(fixture.hardware.resolutionAttempts, [100, 100, 300])
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 300), 1)
+ fixture.assertSettingsPreserved()
+ await fixture.service.stopWithoutTranscription()
+ }
+ }
+
+ @MainActor
+ func testActiveRecoveryTriesNewMicrophoneMissingFromDeviceCache() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0) { fixture in
+ fixture.hardware.enableNewFallback()
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ try await fixture.waitForRecoveryAttempt()
+ XCTAssertEqual(fixture.controller.snapshot.deviceID, 300)
+ XCTAssertEqual(fixture.hardware.resolutionAttempts, [100, 100, 300])
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 300), 1)
+ fixture.assertSessionPreserved()
+ }
+ }
+
+ @MainActor
+ func testFreshSnapshotBudgetStopsAfterAllStartupInputsFail() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ fixture.hardware.enableNewFallback(fails: true)
+ let outcome = await fixture.service.start(forDictionaryTraining: true)
+ XCTAssertEqual(outcome, .failed)
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.isStarting)
+ XCTAssertTrue(fixture.service.showError)
+ XCTAssertEqual(fixture.hardware.resolutionAttempts, [100, 100, 300])
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 300), 0)
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testFreshSnapshotBudgetStopsAfterAllRecoveryInputsFail() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0) { fixture in
+ fixture.hardware.enableNewFallback(fails: true)
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ try await fixture.waitForRecoveryAttempt()
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.audioRouteRecoveryStateForTesting.acceptingPCM)
+ XCTAssertTrue(fixture.service.showError)
+ XCTAssertEqual(fixture.hardware.resolutionAttempts, [100, 100, 300])
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 300), 0)
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testFailedRecoveryCancelsWaitingRetryAndResumesMediaBeforeNativeCleanup() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0, builtInStartDelay: 0.8) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ let first = Task { await fixture.service.start(forDictionaryTraining: true) }
+ try await fixture.waitForBuiltInStartCount(1)
+ await fixture.service.cancelPendingAudioCaptureStart(reason: "injected_user_cancel")
+ let firstOutcome = await first.value
+ XCTAssertEqual(firstOutcome, .failed)
+ XCTAssertTrue(fixture.controller.isRecoveringHardware)
+
+ let transport = RecoveryMediaTransport()
+ let media = MediaPlaybackService(transport: transport, settle: {})
+ fixture.service.useMediaPlaybackForTesting(media)
+ SettingsStore.shared.pauseMediaDuringTranscription = true
+ let retry = Task { await fixture.service.start(forDictionaryTraining: true) }
+ for _ in 0..<200 {
+ if await transport.commands == [.pause] { break }
+ try await Task.sleep(nanoseconds: 1_000_000)
+ }
+ await media.waitUntilSettled()
+ let paused = await transport.commands
+ XCTAssertEqual(paused, [.pause])
+ XCTAssertTrue(fixture.service.isStarting)
+ var failurePresentations = 0
+ let observation = fixture.service.audioCaptureFailurePresented.sink {
+ failurePresentations += 1
+ XCTAssertTrue(fixture.service.showError)
+ XCTAssertEqual(fixture.service.errorTitle, "Recording Stopped")
+ }
+ defer { observation.cancel() }
+ let began = ProcessInfo.processInfo.systemUptime
+ await fixture.service.failAudioRouteRecoveryForTesting()
+ let retryOutcome = await retry.value
+ await media.waitUntilSettled()
+ let elapsed = ProcessInfo.processInfo.systemUptime - began
+ print("MONITOR_RECOVERY_TEST failed_recovery_release_ms=\(elapsed * 1000)")
+ XCTAssertLessThan(elapsed, 0.2)
+ XCTAssertEqual(retryOutcome, .failed)
+ XCTAssertFalse(fixture.service.isStarting)
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertTrue(fixture.service.showError)
+ XCTAssertEqual(failurePresentations, 1)
+ XCTAssertTrue(fixture.controller.isRecoveringHardware)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 1)
+ let resumed = await transport.commands
+ XCTAssertEqual(resumed, [.pause, .play])
+ try await waitForRecovery(fixture.controller)
+ let afterDrain = await transport.commands
+ XCTAssertEqual(afterDrain, [.pause, .play], "Late cleanup must not change playback or restart recording")
+ XCTAssertFalse(fixture.service.isRunning)
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testStaleRecoveryFailureCannotStopNewRecordingOrResumeItsMedia() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ let transport = RecoveryMediaTransport()
+ let media = MediaPlaybackService(transport: transport, settle: {})
+ fixture.service.useMediaPlaybackForTesting(media)
+ SettingsStore.shared.pauseMediaDuringTranscription = true
+ let outcome = await fixture.service.start(forDictionaryTraining: true)
+ XCTAssertEqual(outcome, .started)
+ await media.waitUntilSettled()
+ var failurePresentations = 0
+ let observation = fixture.service.audioCaptureFailurePresented.sink { failurePresentations += 1 }
+ defer { observation.cancel() }
+ await fixture.service.failAudioRouteRecoveryForTesting(stale: true)
+ await media.waitUntilSettled()
+ XCTAssertTrue(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.showError)
+ XCTAssertEqual(failurePresentations, 0)
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause])
+ await fixture.service.stopWithoutTranscription()
+ await media.waitUntilSettled()
+ let stopped = await transport.commands
+ XCTAssertEqual(stopped, [.pause, .play])
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testCancelDuringSlowStartupDiscoveryKeepsMainThreadResponsive() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0.6) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ var failurePresentations = 0
+ let observation = fixture.service.audioCaptureFailurePresented.sink { failurePresentations += 1 }
+ defer { observation.cancel() }
+ let starting = Task { await fixture.service.start(forDictionaryTraining: true) }
+ for _ in 0..<200 {
+ if fixture.hardware.queryCount > 0 { break }
+ try await Task.sleep(nanoseconds: 1_000_000)
+ }
+ XCTAssertEqual(fixture.hardware.queryCount, 1)
+ let began = ProcessInfo.processInfo.systemUptime
+ await fixture.service.cancelPendingAudioCaptureStart(reason: "cancel_during_device_query")
+ let outcome = await starting.value
+ let elapsed = ProcessInfo.processInfo.systemUptime - began
+ print("MONITOR_RECOVERY_TEST cancelled_discovery_release_ms=\(elapsed * 1000)")
+ XCTAssertLessThan(elapsed, 0.2)
+ XCTAssertEqual(outcome, .failed)
+ XCTAssertFalse(fixture.service.isStarting)
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.showError)
+ XCTAssertEqual(failurePresentations, 0)
+ try await Task.sleep(nanoseconds: 650_000_000)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 0)
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testCancellingCallerTaskCancelsNativeStartupAndStaysQuiet() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0, builtInStartDelay: 0.15) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ let starting = Task { await fixture.service.start(forDictionaryTraining: true) }
+ try await fixture.waitForBuiltInStartCount(1)
+ starting.cancel()
+ let outcome = await starting.value
+ XCTAssertEqual(outcome, .failed)
+ try await Task.sleep(nanoseconds: 250_000_000)
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.isStarting)
+ XCTAssertFalse(fixture.service.showError)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 1)
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testTwentyEarlyCancelsNeverStartRecordingAfterCancelReturns() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0, builtInStartDelay: 0.01) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ for _ in 0..<20 {
+ let starting = Task { await fixture.service.start(forDictionaryTraining: true) }
+ for _ in 0..<1000 {
+ if fixture.service.isStarting { break }
+ await Task.yield()
+ }
+ XCTAssertTrue(fixture.service.isStarting)
+ await fixture.service.stopWithoutTranscription()
+ _ = await starting.value
+ let startsAtCancel = fixture.hardware.startCount(deviceID: 100)
+ try await Task.sleep(nanoseconds: 20_000_000)
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.isStarting)
+ XCTAssertFalse(fixture.service.showError)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), startsAtCancel)
+ }
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testTwentyOrdinaryStartsAndStopsKeepRecoveryIdle() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ for _ in 0..<20 {
+ let outcome = await fixture.service.start(forDictionaryTraining: true)
+ XCTAssertEqual(outcome, .started)
+ XCTAssertTrue(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.audioRouteRecoveryStateForTesting.pending)
+ var stoppedCallbacks = 0
+ _ = await fixture.service.stop(onCaptureStopped: { stoppedCallbacks += 1 }, forDictionaryTraining: true)
+ XCTAssertEqual(stoppedCallbacks, 1)
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.isStarting)
+ XCTAssertFalse(fixture.service.showError)
+ fixture.assertSettingsPreserved()
+ }
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 20)
+ }
+ }
+
+ @MainActor
+ func testOrdinarySlowStartBeyondFiveSecondsStillReachesFirstPCM() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0, builtInStartDelay: 5.2) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ let outcome = await fixture.service.start(forDictionaryTraining: true)
+ XCTAssertEqual(outcome, .started)
+ XCTAssertTrue(fixture.service.isRunning)
+ XCTAssertTrue(fixture.service.audioRouteRecoveryStateForTesting.acceptingPCM)
+ XCTAssertFalse(fixture.service.showError)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 1)
+ fixture.assertSettingsPreserved()
+ await fixture.service.stopWithoutTranscription()
+ }
+ }
+
+ @MainActor
+ func testCancelThenImmediateRestartWaitsForSafeCleanupAndSucceeds() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0, builtInStartDelay: 0.65) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ let first = Task { await fixture.service.start(forDictionaryTraining: true) }
+ try await fixture.waitForBuiltInStartCount(1)
+ let began = ProcessInfo.processInfo.systemUptime
+ await fixture.service.stopWithoutTranscription()
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - began, 0.3)
+ let firstResult = await first.value
+ XCTAssertEqual(firstResult, .failed)
+ let secondResult = await fixture.service.start(forDictionaryTraining: true)
+ XCTAssertEqual(secondResult, .started)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 2)
+ XCTAssertFalse(fixture.service.showError)
+ fixture.assertSettingsPreserved()
+ await fixture.service.stopWithoutTranscription()
+ }
+ }
+
+ @MainActor
+ func testCancellingImmediateRestartWaitDoesNotStartLater() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0, builtInStartDelay: 0.65) { fixture in
+ await fixture.service.stopWithoutTranscription()
+ fixture.service.micStatus = .authorized
+ let first = Task { await fixture.service.start(forDictionaryTraining: true) }
+ try await fixture.waitForBuiltInStartCount(1)
+ await fixture.service.stopWithoutTranscription()
+ _ = await first.value
+ let second = Task { await fixture.service.start(forDictionaryTraining: true) }
+ try await Task.sleep(nanoseconds: 30_000_000)
+ XCTAssertTrue(fixture.service.isStarting)
+ let began = ProcessInfo.processInfo.systemUptime
+ await fixture.service.stopWithoutTranscription()
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - began, 0.3)
+ let secondResult = await second.value
+ XCTAssertEqual(secondResult, .failed)
+ try await Task.sleep(nanoseconds: 800_000_000)
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.isStarting)
+ XCTAssertFalse(fixture.service.showError)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 1)
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testDelayedScanRecoversWithoutChangingRecordedAudioOrSettings() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0.12) { fixture in
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ try await fixture.waitForBuiltInRecovery()
+ fixture.assertSessionPreserved()
+ }
+ }
+
+ @MainActor
+ func testTransientScanFailureRetriesWithoutAbandoningRecording() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0.12, queryFailures: 1) { fixture in
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ try await fixture.waitForBuiltInRecovery()
+ fixture.assertSessionPreserved()
+ XCTAssertGreaterThanOrEqual(fixture.hardware.queryCount, 2)
+ }
+ }
+
+ @MainActor
+ func testCancelDuringDelayedScanNeverRestartsAfterQueryCompletes() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0.65) { fixture in
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ for _ in 0..<500 {
+ if fixture.hardware.queryCount > 0 { break }
+ try await Task.sleep(nanoseconds: 2_000_000)
+ }
+ XCTAssertGreaterThan(fixture.hardware.queryCount, 0)
+ await fixture.service.stopWithoutTranscription()
+ try await Task.sleep(nanoseconds: 800_000_000)
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.audioRouteRecoveryStateForTesting.pending)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 0)
+ XCTAssertEqual(fixture.service.audioRouteRecoveryStateForTesting.samples, [])
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testTimedOutScanWaitsForQueryCleanupThenRetriesSuccessfully() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0, operationTimeout: 0.4, firstQueryDelay: 0.6) { fixture in
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ try await fixture.waitForBuiltInRecovery()
+ fixture.assertSessionPreserved()
+ XCTAssertGreaterThanOrEqual(fixture.hardware.queryCount, 2)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 1)
+ XCTAssertFalse(fixture.service.showError)
+ }
+ }
+
+ @MainActor
+ func testRepeatedScanFailureStopsWithErrorInsteadOfRemainingSilentlyPaused() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0.02, queryFailures: 100) { fixture in
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ for _ in 0..<1500 {
+ if fixture.service.showError { break }
+ try await Task.sleep(nanoseconds: 2_000_000)
+ }
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.audioRouteRecoveryStateForTesting.pending)
+ XCTAssertFalse(fixture.service.audioRouteRecoveryStateForTesting.acceptingPCM)
+ XCTAssertTrue(fixture.service.showError)
+ XCTAssertEqual(fixture.hardware.queryCount, 2)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 0)
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testEventDuringDelayedCleanupAutomaticallyRecoversAfterCleanup() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0, externalStopDelay: 0.9, operationTimeout: 0.4) { fixture in
+ _ = await fixture.controller.stop(retainPrepared: false, reason: "injected_delayed_cleanup")
+ XCTAssertTrue(fixture.controller.isRecoveringHardware)
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ try await fixture.waitForBuiltInRecovery()
+ fixture.assertSessionPreserved()
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 1)
+ }
+ }
+
+ @MainActor
+ func testCancelDuringCleanupWaitNeverStartsReplacement() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0, externalStopDelay: 0.85, operationTimeout: 0.4) { fixture in
+ _ = await fixture.controller.stop(retainPrepared: false, reason: "injected_delayed_cleanup")
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ try await Task.sleep(nanoseconds: 330_000_000)
+ await fixture.service.stopWithoutTranscription()
+ try await Task.sleep(nanoseconds: 700_000_000)
+ XCTAssertFalse(fixture.service.isRunning)
+ XCTAssertFalse(fixture.service.audioRouteRecoveryStateForTesting.pending)
+ XCTAssertFalse(fixture.service.showError)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 0)
+ fixture.assertSettingsPreserved()
+ }
+ }
+
+ @MainActor
+ func testNewEventDuringDelayedScanRetainsLatestRecoveryOnly() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0.18) { fixture in
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ for _ in 0..<500 {
+ if fixture.hardware.queryCount > 0 { break }
+ try await Task.sleep(nanoseconds: 2_000_000)
+ }
+ for _ in 0..<20 {
+ fixture.service.triggerAudioRouteRecoveryForTesting()
+ }
+ try await fixture.waitForBuiltInRecovery()
+ fixture.assertSessionPreserved()
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 1)
+ XCTAssertFalse(fixture.service.showError)
+ }
+ }
+
+ @MainActor
+ func testHealthyCaptureWithoutRouteChangeDoesNoRecoveryWork() async throws {
+ try await withASRRecoveryFixture(queryDelay: 0) { fixture in
+ try await Task.sleep(nanoseconds: 400_000_000)
+ XCTAssertEqual(fixture.hardware.queryCount, 0)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 200), 1)
+ XCTAssertEqual(fixture.hardware.startCount(deviceID: 100), 0)
+ XCTAssertEqual(fixture.controller.snapshot.phase, .running)
+ XCTAssertTrue(fixture.service.audioRouteRecoveryStateForTesting.acceptingPCM)
+ fixture.assertSessionPreserved()
+ }
+ }
+}
+
+@MainActor
+private func withASRRecoveryFixture(
+ queryDelay: TimeInterval,
+ queryFailures: Int = 0,
+ externalStopDelay: TimeInterval = 0,
+ operationTimeout: TimeInterval? = nil,
+ firstQueryDelay: TimeInterval? = nil,
+ builtInStartDelay: TimeInterval = 0,
+ _ body: (ASRRecoveryFixture) async throws -> Void
+) async throws {
+ // The hosted app also performs its normal startup device reconciliation.
+ // Seed those existing inputs below the fake pair so that unrelated startup
+ // discovery cannot masquerade as a recovery-induced preference change.
+ let query = DirectCoreAudioLifecycleController(packetHandler: { _, _, _, _, _ in }, onFormatInvalidated: { _ in })
+ let liveInputs = try await query.readDeviceSnapshot().devices.filter(\.hasInput)
+ let fixture = ASRRecoveryFixture(
+ queryDelay: queryDelay,
+ queryFailures: queryFailures,
+ liveInputs: liveInputs,
+ externalStopDelay: externalStopDelay,
+ operationTimeout: operationTimeout,
+ firstQueryDelay: firstQueryDelay,
+ builtInStartDelay: builtInStartDelay
+ )
+ defer { fixture.restoreSettings() }
+ do {
+ try await fixture.start()
+ try await body(fixture)
+ } catch {
+ await fixture.service.finishAudioRouteRecoveryTest()
+ throw error
+ }
+ await fixture.service.finishAudioRouteRecoveryTest()
+}
+
+@MainActor
+private final class ASRRecoveryFixture {
+ let service: ASRService
+ let controller: DirectCoreAudioLifecycleController
+ let hardware: ASRRecoveryHardware
+ private let restore: () -> Void
+ private let outputUID: String?
+ private let modelID: String
+ private let providerID: String
+ private let expectedPriority: [String]
+ private let prefix: [Float] = [0.125, 0.25, 0.375]
+
+ init(queryDelay: TimeInterval, queryFailures: Int, liveInputs: [AudioDevice.Device], externalStopDelay: TimeInterval, operationTimeout: TimeInterval?, firstQueryDelay: TimeInterval?, builtInStartDelay: TimeInterval) {
+ let settings = SettingsStore.shared
+ let priority = settings.microphonePriority
+ let preferred = settings.preferredInputDeviceUID
+ let suppressed = settings.suppressedMicrophoneUIDs
+ let version = settings.microphoneSelectionMigrationVersion
+ let alerts = settings.showMicrophoneChangeAlerts
+ let pauseMedia = settings.pauseMediaDuringTranscription
+ self.restore = {
+ settings.microphonePriority = priority
+ settings.preferredInputDeviceUID = preferred
+ settings.suppressedMicrophoneUIDs = suppressed
+ settings.microphoneSelectionMigrationVersion = version
+ settings.showMicrophoneChangeAlerts = alerts
+ settings.pauseMediaDuringTranscription = pauseMedia
+ }
+ settings.microphoneSelectionMigrationVersion = 4
+ settings.microphonePriority = [
+ .init(uid: "recovery-test-external", name: "Test External"),
+ .init(uid: "recovery-test-built-in", name: "Test Built-in"),
+ ] + liveInputs.map { .init(uid: $0.uid, name: $0.name) }
+ settings.preferredInputDeviceUID = "recovery-test-external"
+ settings.suppressedMicrophoneUIDs = []
+ settings.showMicrophoneChangeAlerts = false
+ settings.pauseMediaDuringTranscription = false
+ self.expectedPriority = settings.microphonePriority.map(\.uid)
+ self.outputUID = settings.preferredOutputDeviceUID
+ self.modelID = settings.selectedSpeechModel.rawValue
+ self.providerID = settings.selectedProviderID
+ let service = ASRService()
+ self.service = service
+ let hardware = ASRRecoveryHardware(queryDelay: queryDelay, queryFailures: queryFailures, externalStopDelay: externalStopDelay, firstQueryDelay: firstQueryDelay, builtInStartDelay: builtInStartDelay)
+ self.hardware = hardware
+ self.controller = DirectCoreAudioLifecycleController(
+ packetHandler: service.recoveryPacketHandlerForTesting,
+ inputFactory: { id, handler in hardware.makeInput(id, handler: handler) },
+ fingerprintReader: { RecoveryInput(deviceID: $0).formatFingerprint },
+ installsHardwareListeners: false,
+ operationTimeout: operationTimeout,
+ deviceSnapshotReader: { refreshLiveness in try hardware.snapshot(refreshLiveness: refreshLiveness) },
+ deviceResolver: { try hardware.resolve($0) },
+ onFormatInvalidated: { _ in }
+ )
+ }
+
+ func start() async throws {
+ _ = try await self.controller.start(deviceID: 200, deviceName: "Test External", reason: "test_existing_capture")
+ self.service.configureAudioRouteRecoveryForTesting(
+ controller: self.controller, devices: [self.hardware.builtIn], initialSamples: self.prefix
+ )
+ self.service.partialTranscription = "words already captured"
+ }
+
+ func waitForRecoveryAttempt() async throws {
+ for _ in 0..<1500 {
+ let state = self.service.audioRouteRecoveryStateForTesting
+ if state.pending == false, state.recovering == false { return }
+ try await Task.sleep(nanoseconds: 2_000_000)
+ }
+ XCTFail("Recovery retry budget did not finish")
+ }
+
+ func waitForBuiltInStartCount(_ count: Int) async throws {
+ for _ in 0..<1000 {
+ if self.hardware.startCount(deviceID: 100) >= count { return }
+ try await Task.sleep(nanoseconds: 2_000_000)
+ }
+ XCTFail("Expected built-in native start count \(count)")
+ }
+
+ func waitForBuiltInRecovery() async throws {
+ for _ in 0..<1500 {
+ let state = self.service.audioRouteRecoveryStateForTesting
+ if self.controller.snapshot.deviceID == 100, self.controller.snapshot.phase == .running,
+ state.pending == false, state.recovering == false
+ { return }
+ try await Task.sleep(nanoseconds: 2_000_000)
+ }
+ let state = self.service.audioRouteRecoveryStateForTesting
+ XCTFail("Recovery did not finish: running=\(self.service.isRunning) acceptingPCM=\(state.acceptingPCM) pending=\(state.pending) phase=\(self.controller.snapshot.phase)")
+ }
+
+ func assertSessionPreserved() {
+ XCTAssertTrue(self.service.isRunning)
+ XCTAssertTrue(self.service.audioRouteRecoveryStateForTesting.acceptingPCM)
+ XCTAssertEqual(Array(self.service.audioRouteRecoveryStateForTesting.samples.prefix(self.prefix.count)), self.prefix)
+ XCTAssertEqual(self.service.partialTranscription, "words already captured")
+ self.assertSettingsPreserved()
+ }
+
+ func assertSettingsPreserved() {
+ XCTAssertEqual(SettingsStore.shared.microphonePriority.map(\.uid), self.expectedPriority)
+ XCTAssertEqual(SettingsStore.shared.preferredInputDeviceUID, "recovery-test-external")
+ XCTAssertEqual(SettingsStore.shared.preferredOutputDeviceUID, self.outputUID)
+ XCTAssertEqual(SettingsStore.shared.selectedSpeechModel.rawValue, self.modelID)
+ XCTAssertEqual(SettingsStore.shared.selectedProviderID, self.providerID)
+ }
+
+ func restoreSettings() { self.restore() }
+}
+
+private actor RecoveryMediaTransport: MediaPlaybackTransport {
+ private var playing = true
+ private(set) var commands: [MediaPlaybackCommand] = []
+
+ func query() async -> MediaPlaybackQueryResult {
+ .snapshot(MediaPlaybackSnapshot(bundleIdentifier: "test.player", processID: 1, title: "Test item", isPlaying: self.playing))
+ }
+
+ func send(_ command: MediaPlaybackCommand) async -> MediaPlaybackCommandResult {
+ self.commands.append(command)
+ self.playing = command == .play
+ return .helperCompleted
+ }
+}
+
+private final nonisolated class ASRRecoveryHardware: @unchecked Sendable {
+ private let newFallback = AudioDevice.Device(id: 300, uid: "recovery-test-new", name: "New microphone", hasInput: true, hasOutput: false)
+ private var newFallbackEnabled = false
+ private var newFallbackFails = false
+ private var resolutions: [AudioObjectID] = []
+
+ var resolutionAttempts: [AudioObjectID] { self.lock.withLock { self.resolutions } }
+
+ func enableNewFallback(fails: Bool = false) {
+ self.lock.withLock { self.newFallbackEnabled = true; self.newFallbackFails = fails }
+ }
+
+ func resolve(_ selection: DirectCoreAudioDeviceSelection) throws -> AudioDevice.Device? {
+ try self.lock.withLock {
+ let device: AudioDevice.Device?
+ switch selection {
+ case .systemDefault: device = self.builtIn
+ case let .preferredUID(uid):
+ device = uid == self.builtIn.uid ? self.builtIn : (uid == self.newFallback.uid ? self.newFallback : nil)
+ }
+ guard let device else { return nil }
+ self.resolutions.append(device.id)
+ if self.newFallbackEnabled, device.id == 100 || self.newFallbackFails {
+ throw NSError(domain: "InjectedMicrophoneStartFailure", code: 1)
+ }
+ return device
+ }
+ }
+
+ let builtIn = AudioDevice.Device(id: 100, uid: "recovery-test-built-in", name: "Test Built-in", hasInput: true, hasOutput: false)
+ private let lock = NSLock()
+ private let queryDelay: TimeInterval
+ private let builtInStartDelay: TimeInterval
+ private let externalStopDelay: TimeInterval
+ private let firstQueryDelay: TimeInterval?
+ private var queryFailures: Int
+ private var queries = 0
+ private var inputs: [RecoveryInput] = []
+
+ init(queryDelay: TimeInterval, queryFailures: Int, externalStopDelay: TimeInterval, firstQueryDelay: TimeInterval?, builtInStartDelay: TimeInterval) {
+ self.builtInStartDelay = builtInStartDelay
+ self.firstQueryDelay = firstQueryDelay
+ self.externalStopDelay = externalStopDelay
+ self.queryDelay = queryDelay
+ self.queryFailures = queryFailures
+ }
+
+ var queryCount: Int { self.lock.withLock { self.queries } }
+ func startCount(deviceID: AudioObjectID) -> Int {
+ self.lock.withLock { self.inputs.filter { $0.deviceID == deviceID }.reduce(0) { $0 + $1.count("start") } }
+ }
+
+ func makeInput(_ id: AudioObjectID, handler: @escaping DirectCoreAudioPacketHandler) -> RecoveryInput {
+ let input = RecoveryInput(deviceID: id, delays: id == 200 ? ["stop": self.externalStopDelay] : ["start": self.builtInStartDelay], automaticPCM: true)
+ input.setHandler(handler)
+ self.lock.withLock { self.inputs.append(input) }
+ return input
+ }
+
+ func snapshot(refreshLiveness: Bool) throws -> DirectCoreAudioLifecycleController.DeviceSnapshot {
+ let fail = self.lock.withLock {
+ self.queries += 1
+ let fail = self.queryFailures > 0
+ self.queryFailures = max(0, self.queryFailures - 1)
+ return fail
+ }
+ let delay = self.lock.withLock { self.queries == 1 ? (self.firstQueryDelay ?? self.queryDelay) : self.queryDelay }
+ Thread.sleep(forTimeInterval: delay)
+ if fail { throw NSError(domain: "InjectedDeviceScan", code: 1) }
+ // The event cache/reconciliation still knows one input; the newer
+ // capture-selection snapshot already contains the connected fallback.
+ let inputs = self.lock.withLock {
+ self.newFallbackEnabled && refreshLiveness == false ? [self.builtIn, self.newFallback] : [self.builtIn]
+ }
+ return .init(devices: inputs, defaultInputUID: self.builtIn.uid)
+ }
+}
+#endif
+
+/// Injected timing and device changes; these tests never open a physical mic.
+final class AudioHardwareAdversarialTests: XCTestCase {
+ func testFortyDelayedExternalToBuiltInSwitchesRejectOldDeviceEventsAndPCM() async throws {
+ let fleet = RecoveryFleet()
+ let controller = fleet.makeController()
+ for cycle in 0..<40 {
+ let externalID = AudioObjectID(200 + cycle)
+ let external = try await controller.start(deviceID: externalID, deviceName: "External", reason: "adversarial_external")
+ let oldInput = try XCTUnwrap(fleet.latest)
+ oldInput.emit()
+ await controller.simulateStoppedHardwareNotificationForTesting(generation: external.generation, reason: "device_is_alive")
+ let replacement = try await controller.start(deviceID: 100, deviceName: "Built-in", reason: "adversarial_fallback")
+ XCTAssertEqual(replacement.deviceID, 100)
+ XCTAssertEqual(replacement.phase, .running)
+ let delivered = fleet.deliveryCount
+ oldInput.emit()
+ // Delayed/duplicate unplug notifications must not retire the new mic.
+ for _ in 0..<4 {
+ await controller.simulateStoppedHardwareNotificationForTesting(generation: external.generation, reason: "device_is_alive")
+ }
+ XCTAssertEqual(fleet.deliveryCount, delivered)
+ XCTAssertEqual(controller.snapshot.generation, replacement.generation)
+ XCTAssertEqual(controller.snapshot.phase, .running)
+ try XCTUnwrap(fleet.latest).emit()
+ XCTAssertEqual(fleet.deliveryCount, delivered + 1)
+ XCTAssertEqual(fleet.runningCount, 1)
+ }
+ await controller.shutdown(reason: "test_complete")
+ XCTAssertEqual(fleet.runningCount, 0)
+ }
+
+ func testThirtyCancelledDelayedStartsRemainRetryableAfterCleanup() async throws {
+ for _ in 0..<30 {
+ let input = RecoveryInput(block: "start", delays: ["invalidate": 0.006])
+ let controller = makeRecoveryController(input, timeout: 1)
+ let start = Task { try await controller.start(deviceID: 144, deviceName: "External", reason: "cancel_race") }
+ try await waitForEvent(input, "start")
+ start.cancel()
+ _ = await start.result
+ XCTAssertTrue(controller.isRecoveringHardware)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 0)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ XCTAssertEqual(input.count("open"), 0)
+ let retry = try await controller.start(deviceID: 144, deviceName: "Built-in", reason: "after_cancel_cleanup")
+ XCTAssertEqual(retry.phase, .running)
+ await controller.shutdown(reason: "test_complete")
+ XCTAssertFalse(input.isRunning)
+ }
+ }
+
+ func testDelayedCleanupRejectsReplacementUntilOldInputIsRetired() async throws {
+ let input = RecoveryInput(block: "invalidate")
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input, timeout: 0.08)
+ _ = try await controller.start(deviceID: 144, deviceName: "External", reason: "before_unplug")
+ await controller.invalidate(reason: "unplug")
+ XCTAssertTrue(controller.isRecoveringHardware)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 0)
+ do {
+ _ = try await controller.start(deviceID: 144, deviceName: "Built-in", reason: "during_cleanup")
+ XCTFail("Replacement must not overlap unresolved native cleanup")
+ } catch {}
+ XCTAssertEqual(input.count("start"), 1)
+ input.release.signal()
+ try await waitForRecovery(controller)
+ _ = try await controller.start(deviceID: 144, deviceName: "Built-in", reason: "after_cleanup")
+ XCTAssertEqual(input.count("start"), 2)
+ await controller.shutdown(reason: "test_complete")
+ }
+
+ func testEightyDeadlineRacesNeverDeliverAudioAfterFailedStartup() async throws {
+ var successes = 0
+ var failures = 0
+ for iteration in 0..<80 {
+ let delays: [TimeInterval] = [0.002, 0.009, 0.01, 0.012, 0.02]
+ let input = RecoveryInput(delays: ["start": delays[iteration % delays.count]])
+ let controller = makeRecoveryController(input, timeout: 0.01)
+ do {
+ _ = try await controller.start(deviceID: 144, deviceName: "Delayed", reason: "deadline_race")
+ successes += 1
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 1)
+ } catch {
+ failures += 1
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 0)
+ try await waitForRecovery(controller)
+ input.emit()
+ XCTAssertEqual(input.count("delivered"), 0)
+ }
+ await controller.shutdown(reason: "test_complete")
+ }
+ XCTAssertGreaterThan(successes, 0)
+ XCTAssertGreaterThan(failures, 0)
+ print("ADVERSARIAL deadline races: successes=\(successes) failures=\(failures)")
+ }
+
+ func testLateDeviceGoneNotificationRestoresReplacementAfterTimedOutFailedCleanup() async throws {
+ // Desired behavior. This deliberately exposes any permanent timeout latch
+ // that disagrees with the existing safe late-device-removal recovery path.
+ let input = RecoveryInput(block: "start", cleanupFails: true)
+ defer { input.release.signal() }
+ let controller = makeRecoveryController(input)
+ do {
+ _ = try await controller.start(deviceID: 144, deviceName: "Removed", reason: "timeout_then_removed")
+ XCTFail("Injected blocked start must time out")
+ } catch {}
+ let generation = controller.snapshot.generation
+ input.release.signal()
+ // Wait for the actual cleanup-failed gate, not just entry into invalidate().
+ // Sending removal before cleanup finishes takes a different, healthy path.
+ var cleanupFinished = false
+ for _ in 0..<1000 {
+ do {
+ _ = try await controller.prepare(deviceID: 144, deviceName: "Probe", reason: "wait_for_failed_cleanup")
+ } catch BoundedAudioHardwareQueue.Failure.cleanupFailed {
+ cleanupFinished = true
+ break
+ } catch {}
+ try await Task.sleep(nanoseconds: 1_000_000)
+ }
+ XCTAssertTrue(cleanupFinished)
+ await controller.simulateStoppedHardwareNotificationForTesting(generation: generation &- 1, reason: "device_is_alive")
+ XCTAssertTrue(controller.isRecoveringHardware, "An old device notification must not clear the current failed generation")
+ await controller.simulateStoppedHardwareNotificationForTesting(generation: generation, reason: "device_is_alive")
+ XCTAssertFalse(controller.isRecoveringHardware, "Known-stopped old hardware must not leave the timeout gate permanently unavailable")
+ do {
+ _ = try await controller.prepare(deviceID: 144, deviceName: "Replacement", reason: "late_removal_recovery")
+ } catch {
+ XCTFail("Safe replacement is still rejected after late device removal: \(error)")
+ }
+ await controller.shutdown(reason: "test_complete")
+ }
+}
+
+private final nonisolated class RecoveryFleet: @unchecked Sendable {
+ private let lock = NSLock()
+ private var inputs: [RecoveryInput] = []
+ private var delivered = 0
+
+ var latest: RecoveryInput? { self.lock.withLock { self.inputs.last } }
+ var deliveryCount: Int { self.lock.withLock { self.delivered } }
+ var runningCount: Int { self.lock.withLock { self.inputs.filter(\.isRunning).count } }
+
+ func makeController() -> DirectCoreAudioLifecycleController {
+ DirectCoreAudioLifecycleController(
+ packetHandler: { [self] _, _, _, _, _ in self.lock.withLock { self.delivered += 1 } },
+ inputFactory: { [self] deviceID, handler in
+ let input = RecoveryInput(deviceID: deviceID, delays: ["start": 0.001, "invalidate": 0.001])
+ input.setHandler(handler)
+ self.lock.withLock { self.inputs.append(input) }
+ return input
+ },
+ fingerprintReader: { RecoveryInput(deviceID: $0).formatFingerprint },
+ installsHardwareListeners: false,
+ operationTimeout: 1,
+ onFormatInvalidated: { _ in }
+ )
+ }
+}
+
+private final nonisolated class FailedDeviceLivenessProbe: @unchecked Sendable {
+ private let lock = NSLock()
+ private var alive: Bool?
+ private var shouldBlock = false
+ private var ids: [AudioObjectID] = []
+ let release = DispatchSemaphore(value: 0)
+
+ init(alive: Bool? = true) { self.alive = alive }
+ var deviceIDs: [AudioObjectID] { self.lock.withLock { self.ids } }
+ func setAlive(_ alive: Bool?) { self.lock.withLock { self.alive = alive } }
+ func blockNextRead(alive: Bool?) {
+ self.lock.withLock { self.alive = alive; self.shouldBlock = true }
+ }
+
+ func read(_ id: AudioObjectID) -> Bool? {
+ let state = self.lock.withLock {
+ self.ids.append(id)
+ let state = (self.alive, self.shouldBlock)
+ self.shouldBlock = false
+ return state
+ }
+ if state.1 { _ = self.release.wait(timeout: .now() + 3) }
+ return state.0
+ }
+
+ func waitForReadCount(_ count: Int) async throws {
+ for _ in 0..<1000 {
+ if self.deviceIDs.count >= count { return }
+ try await Task.sleep(nanoseconds: 1_000_000)
+ }
+ XCTFail("Failed-device liveness query did not run")
+ }
+}
+
+private func waitForTopologyCheck(_ controller: DirectCoreAudioLifecycleController) async throws {
+ for _ in 0..<1000 {
+ if controller.isTopologyRecoveryCheckPendingForTesting == false { return }
+ try await Task.sleep(nanoseconds: 1_000_000)
+ }
+ XCTFail("Topology recovery did not finish within its bounded query window")
+}
+
+private func waitForFailedCleanup(_ controller: DirectCoreAudioLifecycleController) async throws {
+ for _ in 0..<1000 {
+ do {
+ _ = try await controller.prepare(deviceID: 144, deviceName: "Probe", reason: "wait_for_failed_cleanup")
+ } catch BoundedAudioHardwareQueue.Failure.cleanupFailed {
+ return
+ } catch {}
+ try await Task.sleep(nanoseconds: 1_000_000)
+ }
+ XCTFail("Serialized cleanup did not publish its failed state")
+}
diff --git a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift
index 9e72c8fb..100f39c1 100644
--- a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift
+++ b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift
@@ -734,6 +734,44 @@ final class DirectAudioReliabilityTests: XCTestCase {
)
}
+ func testPromptTestReusesDelayedFeedbackAndScopesAllOverlayCleanup() throws {
+ let repositoryRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ let source = try String(
+ contentsOf: repositoryRoot.appendingPathComponent("Sources/Fluid/ContentView.swift"),
+ encoding: .utf8
+ )
+ XCTAssertTrue(source.contains(
+ "await self.processDictationPromptTest(transcribedText, lifecycleID: expectedOverlayLifecycleID)"
+ ))
+ let promptTestSection = try XCTUnwrap(
+ source.components(separatedBy: "private func processDictationPromptTest(").last?
+ .components(separatedBy: "private func makeAIProcessingFeedback(").first
+ )
+ let feedbackIndex = try XCTUnwrap(promptTestSection.range(of:
+ "let refiningStatusTask = self.makeAIProcessingFeedback(lifecycleID: lifecycleID).statusTask"
+ ))
+ let providerIndex = try XCTUnwrap(promptTestSection.range(of: "try await self.processTextWithAI("))
+ XCTAssertLessThan(feedbackIndex.lowerBound, providerIndex.lowerBound)
+
+ let cleanup = try XCTUnwrap(
+ promptTestSection.components(separatedBy: "defer {").last?
+ .components(separatedBy: " do {").first
+ )
+ XCTAssertTrue(cleanup.contains("refiningStatusTask.cancel()"))
+ XCTAssertTrue(cleanup.contains("promptTest.isProcessing = false"))
+ // Both missing-provider and success/error cleanup must leave a newer overlay alone.
+ let scopedHide = "if self.overlayLifecycleID == lifecycleID {\n" +
+ " self.menuBarManager.setProcessing(false)\n }"
+ XCTAssertEqual(promptTestSection.components(separatedBy: scopedHide).count - 1, 2)
+ XCTAssertFalse(promptTestSection.contains("setProcessing(true)"), "Fast prompt tests must keep delayed feedback")
+ XCTAssertFalse(promptTestSection.contains("typeOutput"))
+ XCTAssertFalse(promptTestSection.contains("ClipboardService"))
+ XCTAssertFalse(promptTestSection.contains("TranscriptionHistoryStore"))
+ }
+
func testDictionaryTrackingStartsAfterDeliveryCallbackReturns() throws {
let repositoryRoot = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
@@ -1135,6 +1173,7 @@ final class DirectAudioReliabilityTests: XCTestCase {
inputFactory: { _, _ in input },
fingerprintReader: { _ in fingerprint },
installsHardwareListeners: false,
+ deviceLivenessReader: { _ in true },
onFormatInvalidated: { _ in }
)
_ = try await controller.start(
@@ -1184,6 +1223,7 @@ final class DirectAudioReliabilityTests: XCTestCase {
try fingerprintReader.read()
},
installsHardwareListeners: false,
+ deviceLivenessReader: { _ in true },
onFormatInvalidated: { _ in }
)
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index 49cc61d7..42283787 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -296,7 +296,7 @@ final class HotkeyShortcutTests: XCTestCase {
}
@MainActor
- func testHistoryPerformanceDefaultsOffAndRoundTripsWithoutBreakingLegacyBackups() async throws {
+ func testHistoryPerformanceDefaultsOnAndRoundTripsWithoutBreakingLegacyBackups() async throws {
let defaults = UserDefaults.standard
let key = "ShowHistoryPerformanceMetrics"
let originalValue = defaults.object(forKey: key)
@@ -309,7 +309,12 @@ final class HotkeyShortcutTests: XCTestCase {
}
defaults.removeObject(forKey: key)
- XCTAssertFalse(SettingsStore.shared.showHistoryPerformanceMetrics)
+ XCTAssertTrue(SettingsStore.shared.showHistoryPerformanceMetrics)
+
+ SettingsStore.shared.showHistoryPerformanceMetrics = false
+ XCTAssertFalse(SettingsStore.shared.showHistoryPerformanceMetrics, "An explicit opt-out must remain respected")
+ let optedOutDocument = try await BackupService.shared.makeBackupDocument()
+ XCTAssertEqual(optedOutDocument.settings.showHistoryPerformanceMetrics, false)
SettingsStore.shared.showHistoryPerformanceMetrics = true
let document = try await BackupService.shared.makeBackupDocument()
diff --git a/Tests/FluidDictationIntegrationTests/MediaPlaybackServiceTests.swift b/Tests/FluidDictationIntegrationTests/MediaPlaybackServiceTests.swift
index 63d727e0..a52634a9 100644
--- a/Tests/FluidDictationIntegrationTests/MediaPlaybackServiceTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MediaPlaybackServiceTests.swift
@@ -1,215 +1,646 @@
@testable import FluidVoice_Debug
import Foundation
-#if arch(arm64)
-import MediaRemoteAdapter
-#endif
import XCTest
-#if arch(arm64)
@MainActor
final class MediaPlaybackServiceTests: XCTestCase {
- func testPlayingCallbackBeforeTimeoutRequestsPause() async throws {
- let (service, controller, scheduler) = self.makeService()
- let pauseTask = Task { await service.pauseIfPlaying() }
+ func testVerifiedPauseAndResumeAreOrdered() async {
+ let transport = FakeMediaPlaybackTransport([self.state(true), self.state(false), self.state(false), self.state(true)])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.recordingStopped(sessionID: 1)
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ let maxInFlight = await transport.maximumInFlight
+ XCTAssertEqual(commands, [.pause, .play])
+ XCTAssertEqual(maxInFlight, 1)
+ }
- await controller.waitUntilQueryRegistered()
- XCTAssertEqual(scheduler.scheduledDelays, [2.5])
- controller.complete(with: try self.makeTrackInfo(isPlaying: true, playbackRate: 1))
+ func testUnavailableOrPausedMediaNeverStartsPlayback() async {
+ for result in [MediaPlaybackQueryResult.unavailable("no_media"), self.state(false), self.state(nil)] {
+ let transport = FakeMediaPlaybackTransport([result])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertTrue(commands.isEmpty)
+ }
+ }
- let didPause = await pauseTask.value
- XCTAssertTrue(didPause)
- XCTAssertEqual(controller.pauseCallCount, 1)
+ func testInitialQueryRetriesTransientFailure() async {
+ let transport = FakeMediaPlaybackTransport([
+ .unavailable("temporary"), self.state(true), self.state(false),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause])
+ }
- scheduler.advance(by: 2.5)
- XCTAssertEqual(controller.pauseCallCount, 1)
+ func testInitialQueryRetriesAreBounded() async {
+ let transport = FakeMediaPlaybackTransport([
+ .unavailable("temporary"), .unavailable("temporary"), .unavailable("temporary"),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ let count = await transport.queryCount
+ XCTAssertTrue(commands.isEmpty)
+ XCTAssertEqual(count, 3)
}
- func testCallbackAfterFormerOneSecondBoundaryStillRequestsPause() async throws {
- let (service, controller, scheduler) = self.makeService()
- let pauseTask = Task { await service.pauseIfPlaying() }
+ func testReleasedRecordingDoesNotRetryUnavailableInitialQuery() async {
+ let transport = FakeMediaPlaybackTransport([])
+ await transport.holdQuery(1)
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await transport.waitForQuery(1)
+ service.recordingStopped(sessionID: 1)
+ await transport.releaseQuery(.unavailable("temporary"))
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ let count = await transport.queryCount
+ XCTAssertTrue(commands.isEmpty)
+ XCTAssertEqual(count, 1)
+ }
- await controller.waitUntilQueryRegistered()
- XCTAssertEqual(scheduler.scheduledDelays, [MediaPlaybackService.nowPlayingQueryTimeoutSeconds])
- XCTAssertGreaterThan(MediaPlaybackService.nowPlayingQueryTimeoutSeconds, 2)
+ func testDisabledSettingDoesNoMediaIO() async {
+ let transport = FakeMediaPlaybackTransport([])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: false)
+ await service.waitUntilSettled()
+ let count = await transport.queryCount
+ XCTAssertEqual(count, 0)
+ }
- scheduler.advance(by: 1.1)
- controller.complete(with: try self.makeTrackInfo(isPlaying: true, playbackRate: 1))
+ func testStopDuringQueryPreventsLatePause() async {
+ let transport = FakeMediaPlaybackTransport([])
+ await transport.holdQuery(1)
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await transport.waitForQuery(1)
+ service.recordingStopped(sessionID: 1)
+ await transport.releaseQuery(self.state(true))
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertTrue(commands.isEmpty)
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ }
- let didPause = await pauseTask.value
- XCTAssertTrue(didPause)
- XCTAssertEqual(controller.pauseCallCount, 1)
+ func testFailedStartDuringQueryNeverPauses() async {
+ let transport = FakeMediaPlaybackTransport([])
+ await transport.holdQuery(1)
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await transport.waitForQuery(1)
+ service.sessionFinished(sessionID: 1)
+ await transport.releaseQuery(self.state(true))
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertTrue(commands.isEmpty)
+ }
- scheduler.advance(by: 1.4)
- XCTAssertEqual(controller.pauseCallCount, 1)
+ func testFailedStartDuringPauseRestoresPlaybackOnce() async {
+ let transport = FakeMediaPlaybackTransport([self.state(true), self.state(false), self.state(false), self.state(true)])
+ await transport.holdCommand(1)
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await transport.waitForCommand(1)
+ service.sessionFinished(sessionID: 1)
+ service.sessionFinished(sessionID: 1)
+ await transport.releaseCommand(.helperCompleted)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ let maxInFlight = await transport.maximumInFlight
+ XCTAssertEqual(commands, [.pause, .play])
+ XCTAssertEqual(maxInFlight, 1)
}
- func testTimeoutThenLatePlayingCallbackNeverPauses() async throws {
- let (service, controller, scheduler) = self.makeService()
- let pauseTask = Task { await service.pauseIfPlaying() }
+ func testNewRecordingSupersedesPendingQueryAndOldFinish() async {
+ let transport = FakeMediaPlaybackTransport([self.state(true), self.state(false)])
+ await transport.holdQuery(1)
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await transport.waitForQuery(1)
+ service.recordingStarted(sessionID: 2, enabled: true)
+ service.sessionFinished(sessionID: 1)
+ await transport.releaseQuery(self.state(true))
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ let count = await transport.queryCount
+ XCTAssertEqual(commands, [.pause])
+ XCTAssertEqual(count, 3)
+ }
- await controller.waitUntilQueryRegistered()
- scheduler.advance(by: 2.5)
+ func testStopDuringPauseWaitsForConfirmationBeforeResume() async {
+ let transport = FakeMediaPlaybackTransport([self.state(true), self.state(false), self.state(false), self.state(true)])
+ await transport.holdCommand(1)
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await transport.waitForCommand(1)
+ service.recordingStopped(sessionID: 1)
+ service.sessionFinished(sessionID: 1)
+ let pendingCommands = await transport.commands
+ XCTAssertEqual(pendingCommands, [.pause])
+ await transport.releaseCommand(.helperCompleted)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ let maxInFlight = await transport.maximumInFlight
+ XCTAssertEqual(commands, [.pause, .play])
+ XCTAssertEqual(maxInFlight, 1)
+ }
- let didPause = await pauseTask.value
- XCTAssertFalse(didPause)
- XCTAssertEqual(controller.pauseCallCount, 0)
+ func testNewRecordingDuringResumeQueryRetainsPause() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), self.state(false), self.state(false), self.state(true),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ await transport.holdQuery(3)
+ service.sessionFinished(sessionID: 1)
+ await transport.waitForQuery(3)
+ service.recordingStarted(sessionID: 2, enabled: true)
+ await transport.releaseQuery(self.state(false))
+ await service.waitUntilSettled()
+ let beforeFinish = await transport.commands
+ XCTAssertEqual(beforeFinish, [.pause])
+ service.sessionFinished(sessionID: 1)
+ service.sessionFinished(sessionID: 2)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play])
+ }
- controller.complete(with: try self.makeTrackInfo(isPlaying: true, playbackRate: 1))
- XCTAssertEqual(controller.pauseCallCount, 0)
+ func testFailedPlayRetriesOnlyAfterConfirmingSamePausedPlayer() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), self.state(false), self.state(false), self.state(false),
+ self.state(false), self.state(true),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play, .play])
}
- func testDuplicatePlayingCallbacksIssueOnePause() async throws {
- let (service, controller, _) = self.makeService()
- let pauseTask = Task { await service.pauseIfPlaying() }
- let playingTrack = try self.makeTrackInfo(isPlaying: true, playbackRate: 1)
+ func testFailedPlayDoesNotRetryForChangedPlayer() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), self.state(false), self.state(false), self.state(false),
+ self.state(false, pid: 2),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play])
+ }
- await controller.waitUntilQueryRegistered()
- controller.complete(with: playingTrack, retainingCallback: true)
- controller.complete(with: playingTrack)
+ func testFailedPlayRetryIsBounded() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), self.state(false), self.state(false), self.state(false),
+ self.state(false), self.state(false), self.state(false),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play, .play])
+ }
- let didPause = await pauseTask.value
- XCTAssertTrue(didPause)
- XCTAssertEqual(controller.pauseCallCount, 1)
+ func testShutdownDuringPauseUsesOneVerificationPerCommand() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), self.state(false), self.state(false),
+ ])
+ await transport.holdCommand(1)
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await transport.waitForCommand(1)
+ service.beginShutdown()
+ service.beginShutdown()
+ service.recordingStarted(sessionID: 2, enabled: true)
+ await transport.releaseCommand(.helperCompleted)
+ await service.shutdown()
+ let commands = await transport.commands
+ let count = await transport.queryCount
+ XCTAssertEqual(commands, [.pause, .play])
+ XCTAssertEqual(count, 4)
}
- func testPlaybackStateResolutionDoesNotPauseFalseCasesAndUsesRateFallback() async throws {
- let nilResult = await self.pauseResult(for: nil)
- XCTAssertFalse(nilResult.didPause)
- XCTAssertEqual(nilResult.pauseCallCount, 0)
+ func testNewRecordingDuringFailedPlayRetainsPause() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), self.state(false), self.state(false), self.state(false),
+ self.state(false), self.state(false), self.state(true),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ await transport.holdCommand(2)
+ service.sessionFinished(sessionID: 1)
+ await transport.waitForCommand(2)
+ service.recordingStarted(sessionID: 2, enabled: true)
+ await transport.releaseCommand(.failed("timeout"))
+ await service.waitUntilSettled()
+ let beforeFinish = await transport.commands
+ XCTAssertEqual(beforeFinish, [.pause, .play])
+ service.sessionFinished(sessionID: 2)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play, .play])
+ }
- let explicitlyPaused = await self.pauseResult(
- for: try self.makeTrackInfo(isPlaying: false, playbackRate: 1)
- )
- XCTAssertFalse(explicitlyPaused.didPause)
- XCTAssertEqual(explicitlyPaused.pauseCallCount, 0)
+ func testShutdownDoesNotRetryUnavailableQuery() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), .unavailable("temporary"),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ await service.shutdown()
+ let commands = await transport.commands
+ let count = await transport.queryCount
+ XCTAssertEqual(commands, [.pause])
+ XCTAssertEqual(count, 3)
+ }
- let zeroRate = await self.pauseResult(
- for: try self.makeTrackInfo(isPlaying: nil, playbackRate: 0)
- )
- XCTAssertFalse(zeroRate.didPause)
- XCTAssertEqual(zeroRate.pauseCallCount, 0)
+ func testTransientResumeQueryFailureRetriesBeforePlaying() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), .unavailable("temporary"), self.state(false), self.state(true),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play])
+ }
+
+ func testResumeQueryFailureStopsAfterBoundedRetries() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), .unavailable("temporary"),
+ .unavailable("temporary"), .unavailable("temporary"),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ let count = await transport.queryCount
+ XCTAssertEqual(commands, [.pause])
+ XCTAssertEqual(count, 8)
+ }
+
+ func testResumeRecoversAfterFirstReadCycleIsUnavailable() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false),
+ .unavailable("temporary"), .unavailable("temporary"), .unavailable("temporary"),
+ self.state(false), self.state(true),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play])
+ }
- let positiveRate = await self.pauseResult(
- for: try self.makeTrackInfo(isPlaying: nil, playbackRate: 1)
+ func testExhaustedResumeReadsRetainPauseForNextSession() async {
+ let transport = FakeMediaPlaybackTransport(
+ [self.state(true), self.state(false)]
+ + Array(repeating: .unavailable("temporary"), count: 6)
+ + [self.state(false), self.state(false), self.state(true)]
)
- XCTAssertTrue(positiveRate.didPause)
- XCTAssertEqual(positiveRate.pauseCallCount, 1)
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let before = await transport.commands
+ XCTAssertEqual(before, [.pause], "Unavailable metadata must never trigger blind Play")
+ service.recordingStarted(sessionID: 2, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 2)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play], "The original confirmed pause must survive the outage")
}
- func testResumeOnlyPlaysWhenPauseOwnershipIsTrue() async {
- let (service, controller, _) = self.makeService()
+ func testResumeRetryDoesNotPlayChangedItem() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), .unavailable("temporary"), self.state(false, title: "Other"),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause])
+ }
- await service.resumeIfWePaused(false)
- XCTAssertEqual(controller.playCallCount, 0)
+ func testNewRecordingDuringUnavailableResumeQueryRetainsPause() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), self.state(false), self.state(false), self.state(true),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ await transport.holdQuery(3)
+ service.sessionFinished(sessionID: 1)
+ await transport.waitForQuery(3)
+ service.recordingStarted(sessionID: 2, enabled: true)
+ await transport.releaseQuery(.unavailable("temporary"))
+ await service.waitUntilSettled()
+ let beforeFinish = await transport.commands
+ XCTAssertEqual(beforeFinish, [.pause])
+ service.sessionFinished(sessionID: 2)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play])
+ }
- await service.resumeIfWePaused(true)
- XCTAssertEqual(controller.playCallCount, 1)
+ func testUnconfirmedPauseDoesNotResumeOrSpamCommands() async {
+ let transport = FakeMediaPlaybackTransport([self.state(true), self.state(true), self.state(true)])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ for id in 2...10 {
+ service.recordingStarted(sessionID: id, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: id)
+ }
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ let count = await transport.queryCount
+ XCTAssertEqual(commands, [.pause])
+ XCTAssertEqual(count, 3)
}
- private func makeService() -> (
- service: MediaPlaybackService,
- controller: FakeMediaPlaybackController,
- scheduler: ManualTimeoutScheduler
- ) {
- let controller = FakeMediaPlaybackController()
- let scheduler = ManualTimeoutScheduler()
- let service = MediaPlaybackService(
- mediaController: controller,
- queryTimeoutSeconds: MediaPlaybackService.nowPlayingQueryTimeoutSeconds,
- timeoutScheduler: scheduler.schedule
- )
- return (service, controller, scheduler)
+ func testNewRecordingDuringPlayWaitsBeforePausingAgain() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(false), self.state(false), self.state(true), self.state(true), self.state(false),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ await transport.holdCommand(2)
+ service.sessionFinished(sessionID: 1)
+ await transport.waitForCommand(2)
+ service.recordingStarted(sessionID: 2, enabled: true)
+ service.sessionFinished(sessionID: 1)
+ await transport.releaseCommand(.helperCompleted)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ let maxInFlight = await transport.maximumInFlight
+ XCTAssertEqual(commands, [.pause, .play, .pause])
+ XCTAssertEqual(maxInFlight, 1)
}
- private func pauseResult(for trackInfo: TrackInfo?) async -> (
- didPause: Bool,
- pauseCallCount: Int
- ) {
- let (service, controller, _) = self.makeService()
- let pauseTask = Task { await service.pauseIfPlaying() }
+ func testPauseRemainsOwnedUntilTranscriptionFinishes() async {
+ let transport = FakeMediaPlaybackTransport([self.state(true), self.state(false), self.state(false), self.state(true)])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.recordingStopped(sessionID: 1)
+ await service.waitUntilSettled()
+ let beforeFinish = await transport.commands
+ XCTAssertEqual(beforeFinish, [.pause])
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play])
+ }
- await controller.waitUntilQueryRegistered()
- controller.complete(with: trackInfo)
+ func testCooldownHasBoundedExit() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), self.state(true), self.state(true), self.state(true), self.state(false),
+ ])
+ let clock = MediaTestClock()
+ let service = MediaPlaybackService(transport: transport, settle: {}, now: { clock.value })
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ clock.advance(11)
+ service.recordingStarted(sessionID: 2, enabled: true)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .pause])
+ }
- return (await pauseTask.value, controller.pauseCallCount)
+ func testChangedPlayerOrItemAndManualPlayAreNotResumed() async {
+ for changed in [self.state(false, pid: 2), self.state(false, title: "Other"), self.state(true)] {
+ let transport = FakeMediaPlaybackTransport([self.state(true), self.state(false), changed])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause])
+ }
}
- private func makeTrackInfo(isPlaying: Bool?, playbackRate: Double?) throws -> TrackInfo {
- var payload: [String: Any] = [:]
- if let isPlaying {
- payload["isPlaying"] = isPlaying
+ func testUnknownVerificationNeverClaimsOwnership() async {
+ let transport = FakeMediaPlaybackTransport([
+ self.state(true), .unavailable("timeout"), .unavailable("empty_output"),
+ ])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause])
+ }
+
+ func testCommandTimeoutStillChecksForAppliedPause() async {
+ let transport = FakeMediaPlaybackTransport([self.state(true), self.state(false), self.state(false), self.state(true)])
+ await transport.holdCommand(1)
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await transport.waitForCommand(1)
+ await transport.releaseCommand(.failed("helper_timeout"))
+ await service.waitUntilSettled()
+ service.sessionFinished(sessionID: 1)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play])
+ }
+
+ func testShutdownRestoresConfirmedPauseAndRejectsNewStarts() async {
+ let transport = FakeMediaPlaybackTransport([self.state(true), self.state(false), self.state(false), self.state(true)])
+ let service = self.service(transport)
+ service.recordingStarted(sessionID: 1, enabled: true)
+ await service.waitUntilSettled()
+ await service.shutdown()
+ service.recordingStarted(sessionID: 2, enabled: true)
+ await service.waitUntilSettled()
+ let commands = await transport.commands
+ XCTAssertEqual(commands, [.pause, .play])
+ }
+
+ func testRawQueryFailuresAreDistinct() {
+ for (text, reason) in [("", "empty_output"), ("NIL\n", "no_media_reported"), ("{", "invalid_payload")] {
+ guard case let .unavailable(actual) = MediaPlaybackProcessTransport.decode(Data(text.utf8)) else {
+ return XCTFail("Expected unavailable: \(reason)")
+ }
+ XCTAssertEqual(actual, reason)
}
- if let playbackRate {
- payload["playbackRate"] = playbackRate
+ }
+
+ func testRawQueryAcceptsMissingTitleAndDoesNotOverrideExplicitPause() {
+ let text = #"{"payload":{"PID":"42","bundleIdentifier":"com.apple.WebKit.GPU","isPlaying":false,"playbackRate":1}}"#
+ guard case let .snapshot(snapshot) = MediaPlaybackProcessTransport.decode(Data(text.utf8)) else {
+ return XCTFail("Expected player state")
}
- let data = try JSONSerialization.data(withJSONObject: ["payload": payload])
- return try JSONDecoder().decode(TrackInfo.self, from: data)
+ XCTAssertEqual(snapshot.processID, 42)
+ XCTAssertNil(snapshot.title)
+ XCTAssertEqual(snapshot.isPlaying, false)
}
-}
-@MainActor
-private final class FakeMediaPlaybackController: MediaPlaybackControlling {
- private var callback: ((TrackInfo?) -> Void)?
- private var registrationWaiters: [CheckedContinuation<Void, Never>] = []
- private(set) var pauseCallCount = 0
- private(set) var playCallCount = 0
+ func testProcessDrainsBothPipesBeforeCompletion() async {
+ let result = await Task.detached {
+ MediaHelperProcess.run(arguments: ["-e", "print 'x' x 200000; print STDERR 'y' x 200000;"])
+ }.value
+ XCTAssertNil(result.failure)
+ XCTAssertEqual(result.output.count, 200_000)
+ }
+
+ func testDefaultProcessTimeoutIsOneSecond() async {
+ let started = ProcessInfo.processInfo.systemUptime
+ let result = await Task.detached {
+ MediaHelperProcess.run(arguments: ["-e", "sleep 10"])
+ }.value
+ XCTAssertEqual(result.failure, "helper_timeout")
+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - started, 2.0)
+ }
+
+ func testQueryTimeoutHonorsAdapterDeadlineWithoutExtendingCommands() {
+ XCTAssertEqual(MediaPlaybackProcessTransport.queryTimeoutSeconds, 2.5)
+ XCTAssertEqual(MediaPlaybackProcessTransport.commandTimeoutSeconds, 1.0)
+ }
+
+ func testProcessTimeoutTerminatesHelper() async {
+ let result = await Task.detached {
+ MediaHelperProcess.run(arguments: ["-e", "sleep 10;"], timeout: 0.1)
+ }.value
+ XCTAssertEqual(result.failure, "helper_timeout")
+ }
- func getTrackInfo(_ onReceive: @escaping (TrackInfo?) -> Void) {
- self.callback = onReceive
- let waiters = self.registrationWaiters
- self.registrationWaiters.removeAll()
- waiters.forEach { $0.resume() }
+ func testProcessOutputIsBounded() async {
+ let result = await Task.detached {
+ MediaHelperProcess.run(arguments: ["-e", "print 'x' x 5000000;"])
+ }.value
+ XCTAssertEqual(result.failure, "output_limit")
+ XCTAssertTrue(result.output.isEmpty)
}
- func pause() {
- self.pauseCallCount += 1
+ private func service(_ transport: FakeMediaPlaybackTransport) -> MediaPlaybackService {
+ MediaPlaybackService(transport: transport, settle: {}, now: { 0 })
}
- func play() {
- self.playCallCount += 1
+ private func state(_ playing: Bool?, pid: Int32 = 1, title: String = "Netflix") -> MediaPlaybackQueryResult {
+ .snapshot(MediaPlaybackSnapshot(bundleIdentifier: "com.apple.WebKit.GPU", processID: pid, title: title, isPlaying: playing))
}
+}
- func waitUntilQueryRegistered() async {
- guard self.callback == nil else { return }
- await withCheckedContinuation { continuation in
- self.registrationWaiters.append(continuation)
+private actor FakeMediaPlaybackTransport: MediaPlaybackTransport {
+ private var results: [MediaPlaybackQueryResult]
+ private var heldQueryIndex: Int?
+ private var heldCommandIndex: Int?
+ private var queryContinuation: CheckedContinuation<MediaPlaybackQueryResult, Never>?
+ private var commandContinuation: CheckedContinuation<MediaPlaybackCommandResult, Never>?
+ private var queryWaiter: (Int, CheckedContinuation<Void, Never>)?
+ private var commandWaiter: (Int, CheckedContinuation<Void, Never>)?
+ private var inFlight = 0
+ private(set) var maximumInFlight = 0
+ private(set) var queryCount = 0
+ private(set) var commands: [MediaPlaybackCommand] = []
+
+ init(_ results: [MediaPlaybackQueryResult]) { self.results = results }
+
+ func query() async -> MediaPlaybackQueryResult {
+ self.inFlight += 1
+ self.maximumInFlight = max(self.maximumInFlight, self.inFlight)
+ defer { self.inFlight -= 1 }
+ self.queryCount += 1
+ if let (count, continuation) = self.queryWaiter, self.queryCount >= count {
+ self.queryWaiter = nil
+ continuation.resume()
}
+ if self.queryCount == self.heldQueryIndex {
+ return await withCheckedContinuation { self.queryContinuation = $0 }
+ }
+ return self.results.isEmpty ? .unavailable("exhausted") : self.results.removeFirst()
}
- func complete(with trackInfo: TrackInfo?, retainingCallback: Bool = false) {
- let callback = self.callback
- if !retainingCallback {
- self.callback = nil
+ func send(_ command: MediaPlaybackCommand) async -> MediaPlaybackCommandResult {
+ self.inFlight += 1
+ self.maximumInFlight = max(self.maximumInFlight, self.inFlight)
+ defer { self.inFlight -= 1 }
+ self.commands.append(command)
+ if let (count, continuation) = self.commandWaiter, self.commands.count >= count {
+ self.commandWaiter = nil
+ continuation.resume()
+ }
+ if self.commands.count == self.heldCommandIndex {
+ return await withCheckedContinuation { self.commandContinuation = $0 }
}
- callback?(trackInfo)
+ return .helperCompleted
}
-}
-@MainActor
-private final class ManualTimeoutScheduler {
- private struct ScheduledAction {
- let deadline: TimeInterval
- let action: @MainActor @Sendable () -> Void
+ func holdQuery(_ index: Int) { self.heldQueryIndex = index }
+ func holdCommand(_ index: Int) { self.heldCommandIndex = index }
+ func releaseQuery(_ result: MediaPlaybackQueryResult) {
+ self.queryContinuation?.resume(returning: result)
+ self.queryContinuation = nil
}
- private var currentTime: TimeInterval = 0
- private var scheduledActions: [ScheduledAction] = []
+ func releaseCommand(_ result: MediaPlaybackCommandResult) {
+ self.commandContinuation?.resume(returning: result)
+ self.commandContinuation = nil
+ }
- var scheduledDelays: [TimeInterval] {
- self.scheduledActions.map(\.deadline)
+ func waitForQuery(_ count: Int) async {
+ guard self.queryCount < count else { return }
+ await withCheckedContinuation { self.queryWaiter = (count, $0) }
}
- func schedule(after delay: TimeInterval, action: @escaping @MainActor @Sendable () -> Void) {
- self.scheduledActions.append(
- ScheduledAction(deadline: self.currentTime + delay, action: action)
- )
+ func waitForCommand(_ count: Int) async {
+ guard self.commands.count < count else { return }
+ await withCheckedContinuation { self.commandWaiter = (count, $0) }
+ }
+}
+
+private final nonisolated class MediaTestClock: @unchecked Sendable {
+ private let lock = NSLock()
+ private var time: TimeInterval = 0
+
+ var value: TimeInterval {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ return self.time
}
- func advance(by interval: TimeInterval) {
- self.currentTime += interval
- let readyActions = self.scheduledActions.filter { $0.deadline <= self.currentTime }
- self.scheduledActions.removeAll { $0.deadline <= self.currentTime }
- readyActions.forEach { $0.action() }
+ func advance(_ seconds: TimeInterval) {
+ self.lock.lock()
+ self.time += seconds
+ self.lock.unlock()
}
}
-#endif
diff --git a/Tests/HistoryPresentationTests.swift b/Tests/HistoryPresentationTests.swift
new file mode 100644
index 00000000..12bc3a6b
--- /dev/null
+++ b/Tests/HistoryPresentationTests.swift
@@ -0,0 +1,121 @@
+import Foundation
+
+// Display-only fixture; the test executable does not load the private provider or settings.
+enum PrivateAIModelRegistry {
+ struct Model { let displayName: String }
+ static func canonicalModelID(for value: String) -> String? {
+ value == "legacy-mini" ? "mini-internal" : nil
+ }
+
+ static func model(id: String) -> Model? {
+ id == "mini-internal" ? Model(displayName: "Fluid-1 Mini") : nil
+ }
+}
+
+@main
+struct HistoryPresentationTests {
+ static func main() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let savedFile = directory.appendingPathComponent("saved.wav")
+ try Data([0]).write(to: savedFile)
+ let exists: @Sendable (String) -> Bool = { name in
+ precondition(!Thread.isMainThread, "Availability checks must not run on the main thread")
+ return FileManager.default.fileExists(atPath: directory.appendingPathComponent(name).path)
+ }
+ let initial = await HistoryAudioAvailability.scan(fileNames: ["saved.wav", "missing.wav", "saved.wav"], exists: exists)
+ precondition(initial == ["saved.wav"], "Missing restored files must not appear available")
+ try FileManager.default.removeItem(at: savedFile)
+ let deleted = await HistoryAudioAvailability.scan(fileNames: ["saved.wav"], exists: exists)
+ precondition(deleted.isEmpty, "Refresh must remove externally deleted files")
+ let emptyAudio = await HistoryAudioAvailability.scan(fileNames: []) { _ in
+ preconditionFailure("No metadata must mean no file queries")
+ }
+ precondition(emptyAudio.isEmpty)
+ let cancelled = Task {
+ await HistoryAudioAvailability.scan(fileNames: ["saved.wav"], exists: exists)
+ }
+ cancelled.cancel()
+ _ = await cancelled.value
+ print("PASS: background audio availability, missing/deleted files, empty metadata and cancellation completion")
+ let audio = DictationAudioMetadata(
+ fileName: "saved.wav",
+ durationMilliseconds: 10_300,
+ byteCount: 331_000,
+ sampleRate: 16_000,
+ channels: 1,
+ model: nil
+ )
+ let enhanced = TranscriptionHistoryEntry(
+ rawText: " raw words ",
+ processedText: " final words ",
+ appName: "Notes",
+ windowTitle: "",
+ wasAIProcessed: true,
+ processingModel: "historical-model",
+ transcriptionDurationMilliseconds: 57,
+ aiProcessingDurationMilliseconds: 104,
+ aiTokensPerSecond: 746,
+ audio: audio
+ )
+ let before = enhanced
+ precondition(enhanced.clipboardText == "final words")
+ precondition(enhanced == before, "Reading copy text must not mutate an entry")
+ let raw = TranscriptionHistoryEntry(
+ rawText: " raw words ",
+ processedText: " ",
+ appName: "Notes",
+ windowTitle: "",
+ wasAIProcessed: false
+ )
+ precondition(raw.clipboardText == "raw words")
+ let empty = TranscriptionHistoryEntry(
+ rawText: " ",
+ processedText: " ",
+ appName: "Notes",
+ windowTitle: "",
+ wasAIProcessed: false
+ )
+ precondition(empty.clipboardText == nil)
+ let decoded = try JSONDecoder().decode(TranscriptionHistoryEntry.self, from: JSONEncoder().encode(enhanced))
+ precondition(decoded == enhanced, "Presentation must preserve persisted fields")
+ precondition(decoded.processingModel == "historical-model")
+ precondition(TranscriptionHistoryEntry.formattedTokensPerSecond(746, compact: true) == "746 tok/s")
+ precondition(TranscriptionHistoryEntry.formattedDuration(milliseconds: 104) == "104 ms")
+ let cases = [
+ ("Hello world", "Hello world"),
+ ("Hello world", "Hello, world!"),
+ ("red blue", "green blue"),
+ ("", "new words"),
+ ("old words", ""),
+ ("one two\nthree", "One two\n\nthree."),
+ ("hello hello world", "hello world"),
+ ("வணக்கம் 👋🏽 café", "வணக்கம் 👋🏽 Café!"),
+ ]
+ for (original, final) in cases {
+ guard let diff = HistoryTextDiff.compare(original: original, final: final) else {
+ preconditionFailure("Expected a bounded comparison")
+ }
+ precondition(diff.original.map(\.text).joined() == original)
+ precondition(diff.final.map(\.text).joined() == final)
+ precondition(diff.hasChanges == (original != final))
+ }
+ guard let replacement = HistoryTextDiff.compare(original: "red blue", final: "green blue") else {
+ preconditionFailure("Expected a replacement comparison")
+ }
+ precondition(replacement.original.filter(\.changed).map(\.text).joined() == "red")
+ precondition(replacement.final.filter(\.changed).map(\.text).joined() == "green")
+ precondition(HistoryTextDiff.compare(original: String(repeating: "a ", count: 2000), final: "") == nil)
+ precondition(HistoryTextDiff.compare(original: String(repeating: "x", count: 24_001), final: "") == nil)
+ precondition(ModelDisplayName.forID("mini-internal") == "Fluid 1 Mini")
+ precondition(ModelDisplayName.forID("legacy-mini") == "Fluid 1 Mini")
+ precondition(ModelDisplayName.forID(" mini-internal ") == "Fluid 1 Mini")
+ precondition(ModelDisplayName.forID("external/model-v2") == "external/model-v2")
+ precondition(ModelDisplayName.forID("") == "")
+ precondition(decoded.processingModel == "historical-model", "Display lookup cannot rewrite stored model IDs")
+ print("PASS: final/raw/empty copy, immutable entry, audio and timing round-trip, metric labels")
+ print("PASS: unchanged/replaced/added/deleted text, punctuation, whitespace, Unicode, repeated words and bounded diff")
+ print("PASS: display names, aliases, unknown-provider fallback and original stored model ID")
+ }
+}
diff --git a/Tests/PasteClipboardTests.swift b/Tests/PasteClipboardTests.swift
new file mode 100644
index 00000000..f3a9f1c0
--- /dev/null
+++ b/Tests/PasteClipboardTests.swift
@@ -0,0 +1,46 @@
+import AppKit
+
+@main
+enum PasteClipboardTests {
+ static func main() {
+ self.testClipboardPreservation()
+ print("PASS: rich clipboard round-trip, empty clipboard, newer and identical-text user copies preserved")
+ }
+
+ static func testClipboardPreservation() {
+ let board = NSPasteboard(name: NSPasteboard.Name("fluidvoice.paste-tests.\(UUID().uuidString)"))
+ defer { board.releaseGlobally() }
+ let original = NSPasteboardItem()
+ original.setString("original", forType: .string)
+ original.setData(Data([0, 1, 2, 255]), forType: .rtf)
+ let second = NSPasteboardItem()
+ second.setData(Data([3, 4, 5]), forType: .png)
+ board.clearContents()
+ precondition(board.writeObjects([original, second]))
+ let preserved = PreservedPasteboardSnapshot(board)
+ board.clearContents()
+ board.setString("dictated", forType: .string)
+ let owned = board.changeCount
+ precondition(preserved.restore(to: board, ifUnchangedSince: owned))
+ precondition(PreservedPasteboardSnapshot(board).items == preserved.items, "All item representations must round-trip")
+
+ board.clearContents()
+ board.setString("dictated", forType: .string)
+ let oldGeneration = board.changeCount
+ board.clearContents()
+ board.setString("dictated", forType: .string)
+ let userCopy = board.changeCount
+ precondition(!preserved.restore(to: board, ifUnchangedSince: oldGeneration), "Same text copied again belongs to the user")
+ precondition(board.changeCount == userCopy && board.string(forType: .string) == "dictated")
+ board.clearContents()
+ board.setString("new user copy", forType: .string)
+ precondition(!preserved.restore(to: board, ifUnchangedSince: oldGeneration))
+ precondition(board.string(forType: .string) == "new user copy")
+
+ board.clearContents()
+ let empty = PreservedPasteboardSnapshot(board)
+ board.setString("temporary", forType: .string)
+ precondition(empty.restore(to: board, ifUnchangedSince: board.changeCount))
+ precondition(board.string(forType: .string) == nil, "An originally empty clipboard must end empty")
+ }
+}
diff --git a/Tests/PrivateAISettingsBoundaryTests.swift b/Tests/PrivateAISettingsBoundaryTests.swift
new file mode 100644
index 00000000..36ea4186
--- /dev/null
+++ b/Tests/PrivateAISettingsBoundaryTests.swift
@@ -0,0 +1,156 @@
+import Foundation
+
+/// Standalone, deterministic tests of the production boundary. No app launch, defaults, keys or models.
+@main
+struct PrivateAISettingsBoundaryTests {
+ enum Failure: Error { case expected }
+
+ @MainActor
+ static func main() async throws {
+ var checks = 0
+ func check(_ condition: Bool, _ message: String) {
+ precondition(condition, message)
+ checks += 1
+ }
+ for gigabytes: UInt64 in [4, 8, 12] {
+ check(PrivateAIModelRecommendation.modelID(physicalMemory: gigabytes * 1024 * 1024 * 1024) == "fluid-1-pico-96k-dflash", "Below 16 GB recommends Pico")
+ }
+ for gigabytes: UInt64 in [16, 24, 32, 64, 128] {
+ check(PrivateAIModelRecommendation.modelID(physicalMemory: gigabytes * 1024 * 1024 * 1024) == "fluid-1-mini-96k-dflash", "16 GB and above recommends Mini")
+ }
+ check(PrivateAIModelRecommendation.modelID(physicalMemory: 16 * 1024 * 1024 * 1024 - 1) == "fluid-1-pico-96k-dflash", "Recommendation uses the exact 16 GB boundary")
+
+ check(PrivateAIModelCarouselNavigation.next(in: [], current: "missing", forward: true) == nil, "Empty catalog has no navigation target")
+ check(PrivateAIModelCarouselNavigation.next(in: ["mini"], current: "mini", forward: false) == "mini", "One model never fabricates a neighbor")
+ check(PrivateAIModelCarouselNavigation.next(in: ["pico", "mini"], current: "mini", forward: true) == "pico", "Two-model carousel wraps forward")
+ check(PrivateAIModelCarouselNavigation.next(in: ["pico", "mini"], current: "pico", forward: false) == "mini", "Two-model carousel wraps backward")
+ check(PrivateAIModelCarouselNavigation.next(in: ["pico", "mini"], current: "deleted", forward: true) == "pico", "Stale preview recovers to a real model")
+ check(PrivateAIModelCarouselNavigation.position(of: "pico", in: ["pico", "mini", "full"], current: "mini") == -1, "Three-model carousel places the previous card left")
+ check(PrivateAIModelCarouselNavigation.position(of: "full", in: ["pico", "mini", "full"], current: "mini") == 1, "Three-model carousel places the next card right")
+ var session = PrivateAISettingsSession(selectedModelID: "mini")
+ let initialRevision = session.revision
+ for id in ["pico", "mini", "pico"] { session.preview(id) }
+ check(session.previewModelID == "pico", "Preview follows browsing")
+ check(session.selectedModelID == "mini", "Browsing must not activate")
+ check(session.revision == initialRevision, "Browsing must not invalidate active work")
+ check(session.acceptsRead(initialRevision), "Read-only browsing retains current status")
+ check(session.select(session.previewModelID), "Explicit activation is accepted")
+ check(session.selectedModelID == "pico", "Activation changes selection")
+ check(!session.acceptsRead(initialRevision), "Old model status must be rejected")
+
+ let beforeOperation = session.revision
+ guard let first = session.begin() else { preconditionFailure("Expected first operation") }
+ check(session.begin() == nil, "Duplicate operation must not start")
+ check(!session.select("mini"), "Model activation must wait during mutation")
+ session.preview("mini")
+ check(session.previewModelID == "mini" && session.selectedModelID == "pico", "Browsing remains available during work")
+ check(!session.acceptsRead(beforeOperation), "Old refresh cannot erase loading/progress")
+ session.finish(UUID())
+ check(session.isBusy, "Foreign completion cannot release the current operation")
+ session.finish(first)
+ check(!session.isBusy, "Completion releases mutation slot")
+ check(!session.acceptsRead(beforeOperation), "Pre-operation refresh stays stale after completion")
+ guard let second = session.begin() else { preconditionFailure("Expected second operation") }
+ session.finish(first)
+ check(session.isBusy, "Late first completion cannot release second operation")
+ session.finish(second)
+
+ var events: [String] = []
+ let success = try await PrivateAISettingsUpdateTransaction.run(
+ update: { events.append("download"); return 7 },
+ verify: { events.append("verify"); return true },
+ commit: { check($0 == 7, "Commit exact update token"); events.append("commit") },
+ rollback: { _ in events.append("rollback") }
+ )
+ check(success && events == ["download", "verify", "commit"], "Success commits once, never rolls back")
+
+ events = []
+ let failedVerification = try await PrivateAISettingsUpdateTransaction.run(
+ update: { events.append("download"); return 8 },
+ verify: { events.append("verify"); return false },
+ commit: { _ in events.append("commit") },
+ rollback: { check($0 == 8, "Rollback exact update token"); events.append("rollback") }
+ )
+ check(!failedVerification && events == ["download", "verify", "rollback"], "Verification failure preserves previous artifact")
+
+ events = []
+ guard let failedOperation = session.begin() else { preconditionFailure("Expected failure operation") }
+ do {
+ defer { session.finish(failedOperation) }
+ _ = try await PrivateAISettingsUpdateTransaction.run(
+ update: { () async throws -> Int in events.append("download"); throw Failure.expected },
+ verify: { events.append("verify"); return true },
+ commit: { _ in events.append("commit") },
+ rollback: { _ in events.append("rollback") }
+ )
+ preconditionFailure("Download error must propagate")
+ } catch Failure.expected {}
+ check(events == ["download"], "Failed download must not verify/commit or roll back a nonexistent token")
+ check(!session.isBusy && session.select("mini"), "Failure permits retry/activation")
+
+ events = []
+ let cancelled = Task { @MainActor in
+ try await PrivateAISettingsUpdateTransaction.run(
+ update: {
+ withUnsafeCurrentTask { $0?.cancel() }
+ events.append("download")
+ return 9
+ },
+ verify: { events.append("verify"); return true },
+ commit: { _ in events.append("commit") },
+ rollback: { _ in events.append("rollback") }
+ )
+ }
+ do {
+ _ = try await cancelled.value
+ preconditionFailure("Cancellation must propagate")
+ } catch is CancellationError {}
+ check(events == ["download", "rollback"], "Cancellation after staging rolls back without verification")
+
+ events = []
+ let cancelDuringVerification = Task { @MainActor in
+ try await PrivateAISettingsUpdateTransaction.run(
+ update: { 10 },
+ verify: {
+ withUnsafeCurrentTask { $0?.cancel() }
+ return true
+ },
+ commit: { _ in events.append("commit") },
+ rollback: { _ in events.append("rollback") }
+ )
+ }
+ do {
+ _ = try await cancelDuringVerification.value
+ preconditionFailure("Cancellation must propagate")
+ } catch is CancellationError {}
+ check(events == ["rollback"], "Cancellation during verification never commits")
+
+ guard let rollbackOperation = session.begin() else { preconditionFailure("Expected rollback operation") }
+ _ = try await PrivateAISettingsUpdateTransaction.run(
+ update: { 11 },
+ verify: { false },
+ commit: { _ in preconditionFailure("Must not commit") },
+ rollback: { _ in
+ await Task.yield()
+ check(session.isBusy && session.begin() == nil, "Slot stays occupied across asynchronous rollback")
+ check(!session.select("pico"), "Selection cannot race rollback")
+ }
+ )
+ session.finish(rollbackOperation)
+ check(!session.isBusy, "Rollback completion allows another operation")
+ await PrivateAIControllerChecks.run(check: check)
+ let section = try String(contentsOfFile: "Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift", encoding: .utf8)
+ check(section.contains("Label(\"Active\", systemImage: \"checkmark.circle.fill\")"), "Active is informational, not a disabled action")
+ check(!section.contains("onReady: self.makePrimary"), "Model activation must not silently assign the main shortcut")
+ check(!section.contains("modelPanel") && !section.contains("Model details…"), "Model menu never opens a duplicate management sheet")
+ check(!section.contains("Reset verification") && !section.contains("Troubleshooting"), "Model menu exposes no reset or troubleshooting submenu")
+ check(section.contains(".alert(\"Delete downloaded model?\""), "Deletion requires explicit confirmation")
+ check(section.components(separatedBy: "Open models folder").count == 2, "Shared Manage sheet owns the only folder action")
+ check(section.contains("if files?.installed == false, let bytes"), "Download size is visible before installation")
+ let card = try String(contentsOfFile: "Sources/Fluid/UI/AISettings/FluidModelShowcaseCard.swift", encoding: .utf8)
+ check(!card.contains(".popover("), "Model information stays inside its card")
+ check(card.contains("Button { self.showsInfo.toggle() }"), "Information toggles only local presentation state")
+ check(card.contains("self.reduceMotion ? nil") && card.contains("ZStack(alignment: .topLeading)"), "Inline information respects reduced motion and shares stable content bounds")
+ print("Passed \(checks) FI boundary/controller assertions")
+ }
+}
diff --git a/Tests/PrivateAISettingsControllerDoubles.swift b/Tests/PrivateAISettingsControllerDoubles.swift
new file mode 100644
index 00000000..b37e644d
--- /dev/null
+++ b/Tests/PrivateAISettingsControllerDoubles.swift
@@ -0,0 +1,271 @@
+import Foundation
+
+// Test-only adapters. Compile the actual controller against these, never against user preferences,
+// Keychain, downloads or inference. The normal app build separately checks the real adapters.
+struct PrivateAIModelDownloadProgress: Equatable, Sendable {
+ init(initialExpectedBytes: Int?) {}
+ func withFallbackExpectedBytes(_ bytes: Int?) -> Self { self }
+}
+struct PrivateAIRegisteredModel: Sendable {
+ let id: String
+ var canDownload = true
+ var artifact: Artifact { Artifact() }
+ struct Artifact { var byteCount: Int? = 10 }
+}
+struct PrivateAIModelUpdateStatus {
+ enum State { case current, updateAvailable }
+ var state: State
+}
+struct PrivateAIModelUpdateToken: Sendable { let id = UUID() }
+struct PrivateAIStatus { enum State { case ready, failed }; var state: State; var message: String? }
+enum PrivateAIModelRegistry {
+ static let defaultModel = PrivateAIRegisteredModel(id: "mini")
+ static func model(id: String) -> PrivateAIRegisteredModel? {
+ modelIDs().contains(id) ? PrivateAIRegisteredModel(id: id) : nil
+ }
+ static func modelIDs() -> [String] { ["mini", "pico"] }
+ static func canonicalModelID(for id: String) -> String? { model(id: id)?.id }
+}
+struct PrivateAIProviderFeature { static let shared = Self(); let providerID = "fi" }
+enum PrivateAIProviderPromptFormat {
+ static func verifiedModelID(settings: SettingsStore) -> String? { "mini" }
+}
+final class SettingsStore {
+ enum PrivateAIBackendPreference { case auto, mlx; var displayName: String { "test" } }
+ var privateAIBackendPreference: PrivateAIBackendPreference = .auto
+ var privateAIPrefixKVCacheEnabled = false
+ var privateAIBoostEnabled = false
+ var privateAIContextTokenLimit = 1024
+ var selectedModelByProvider = ["external": "external-model"]
+ var availableModelsByProvider = ["external": ["external-model"]]
+ static func clampPrivateAIContextTokenLimit(_ value: Int) -> Int { max(1, value) }
+}
+@MainActor
+final class UserDefaults {
+ static let standard = UserDefaults()
+ var writes = 0
+ func set(_ value: String, forKey key: String) { writes += 1 }
+ func removeObject(forKey key: String) { writes += 1 }
+}
+@MainActor
+final class AIEnhancementSettingsViewModel {
+ enum ConnectionStatus { case success }
+ let settings = SettingsStore()
+ var selectedProviderID = "external"
+ var availableModelsByProvider = ["external": ["external-model"]]
+ var selectedModelByProvider = ["external": "external-model"]
+ var availableModels = ["external-model"]
+ var selectedModel = "external-model"
+ var isTestingConnection = false
+ var verificationCount = 0
+ var resetCount = 0
+ var verified = true
+ func providerKey(for id: String) -> String { id }
+ func refreshProviderItems() {}
+ func connectionErrorMessage(for id: String) -> String { "test failure" }
+ func resetVerification(for id: String) { resetCount += 1 }
+ func updateConnectionStatus(_ status: ConnectionStatus, for id: String) {}
+ func verifyPrivateAIProvider(model: PrivateAIRegisteredModel) async -> Bool {
+ verificationCount += 1
+ return verified
+ }
+}
+struct DebugLogger {
+ static let shared = Self()
+ func info(_ message: String, source: String) {}
+ func error(_ message: String, source: String) {}
+}
+@MainActor
+final class PrivateAIIntegrationService {
+ struct LoadedModelState { var state: PrivateAIStatus.State; var modelID: String }
+ static let shared = PrivateAIIntegrationService()
+ static var configuredModelID = "mini"
+ static let selectedModelDefaultsKey = "test-selection"
+ static let localModelPathDefaultsKey = "test-path"
+ static let modelDirectoryURL = URL(fileURLWithPath: "/tmp/test-not-used")
+ static var installed = false
+ static var downloads = 0
+ static var loads = 0
+ static var commits = 0
+ static var rollbacks = 0
+ static var removals = 0
+ static var failDownload = false
+ static var lastProgress: (@Sendable (PrivateAIModelDownloadProgress) async -> Void)?
+ static var readContinuation: CheckedContinuation<LoadedModelState?, Never>?
+ static var suspendRead = false
+ static var loadContinuation: CheckedContinuation<PrivateAIStatus, Never>?
+ static var suspendLoad = false
+ static func isModelInstalled(_ model: PrivateAIRegisteredModel) -> Bool { installed }
+ static func canRemoveInstalledModel(_ model: PrivateAIRegisteredModel) -> Bool { installed }
+ static func modelUpdateStatus(_ model: PrivateAIRegisteredModel) async -> PrivateAIModelUpdateStatus { .init(state: .current) }
+ static func prepareModel(
+ _ model: PrivateAIRegisteredModel,
+ progressHandler: (@Sendable (PrivateAIModelDownloadProgress) async -> Void)? = nil
+ ) async throws -> URL {
+ downloads += 1
+ lastProgress = progressHandler
+ if failDownload { throw PrivateAISettingsBoundaryTests.Failure.expected }
+ await progressHandler?(.init(initialExpectedBytes: 10))
+ return modelDirectoryURL
+ }
+ static func updateModel(
+ _ model: PrivateAIRegisteredModel,
+ progressHandler: (@Sendable (PrivateAIModelDownloadProgress) async -> Void)? = nil
+ ) async throws -> PrivateAIModelUpdateToken {
+ _ = try await prepareModel(model, progressHandler: progressHandler)
+ return .init()
+ }
+ static func commitModelUpdate(_ token: PrivateAIModelUpdateToken) async { commits += 1 }
+ static func rollbackModelUpdate(_ token: PrivateAIModelUpdateToken) async { rollbacks += 1 }
+ func loadedModelState() async -> LoadedModelState? {
+ if Self.suspendRead { return await withCheckedContinuation { Self.readContinuation = $0 } }
+ return nil
+ }
+ func loadModel(_ model: PrivateAIRegisteredModel) async throws -> PrivateAIStatus {
+ Self.loads += 1
+ if Self.suspendLoad { return await withCheckedContinuation { Self.loadContinuation = $0 } }
+ return .init(state: .ready)
+ }
+ func unloadCachedRuntime(reason: String) async {}
+ func unloadAndRemoveInstalledModel(_ model: PrivateAIRegisteredModel, reason: String) async throws { Self.removals += 1 }
+}
+
+@MainActor
+enum PrivateAIControllerChecks {
+ static func eventually(_ predicate: () -> Bool) async {
+ for _ in 0..<10000 {
+ if predicate() { return }
+ await Task.yield()
+ }
+ preconditionFailure("Controlled task did not reach expected state")
+ }
+
+ static func run(check: (Bool, String) -> Void) async {
+ let vm = AIEnhancementSettingsViewModel()
+ let controller = PrivateAISettingsController(viewModel: vm)
+ for _ in 0..<50 { controller.previewModel("pico"); controller.previewModel("mini") }
+ controller.previewModel("pico")
+ controller.previewModel("invalid")
+ check(controller.previewModelID == "pico" && controller.privateAISelectedModelID == "mini", "Controller preview remains separate and rejects invalid IDs")
+ check(UserDefaults.standard.writes == 0 && vm.resetCount == 0, "Preview makes no persistence/verification writes")
+ check(PrivateAIIntegrationService.loads == 0 && PrivateAIIntegrationService.downloads == 0, "Preview does not load/download")
+ controller.activatePreviewModel()
+ check(controller.privateAISelectedModelID == "pico" && UserDefaults.standard.writes == 2, "Explicit activation persists through existing path")
+ check(vm.selectedProviderID == "external" && vm.selectedModel == "external-model", "FI selection must not change external editor/global provider")
+ check(vm.settings.selectedModelByProvider["external"] == "external-model", "FI selection preserves external saved model")
+
+ let writesBeforeCardRead = UserDefaults.standard.writes
+ controller.refreshPrivateAIModelUpdateStatus(PrivateAIRegisteredModel(id: "mini"))
+ await eventually { controller.privateAIModelUpdateStatusByID["mini"] != nil }
+ check(controller.privateAIModelUpdateStatusByID["mini"]?.state == .current, "Inactive card receives its own update status")
+ check(controller.privateAISelectedModelID == "pico" && UserDefaults.standard.writes == writesBeforeCardRead, "Card update read never selects or persists another model")
+ let verificationBeforeInactiveAction = vm.verificationCount
+ controller.verifyPrivateAIConnection(PrivateAIRegisteredModel(id: "mini"))
+ check(!controller.isBusy && vm.verificationCount == verificationBeforeInactiveAction, "Inactive maintenance cannot run against the selected runtime")
+
+ PrivateAIIntegrationService.failDownload = true
+ let pico = PrivateAIRegisteredModel(id: "pico")
+ controller.downloadPrivateAIModel(pico)
+ controller.downloadPrivateAIModel(pico)
+ controller.persistPrivateAIModelSelection("mini")
+ check(controller.isBusy && controller.privateAISelectedModelID == "pico", "Busy controller rejects duplicate action/model switching")
+ await eventually { !controller.isBusy }
+ check(PrivateAIIntegrationService.downloads == 1 && vm.verificationCount == 0, "Failed download never verifies and only starts once")
+ check(controller.privateAILoadState.failureMessage(for: "pico") != nil, "Failure is visible and releases busy state")
+ PrivateAIIntegrationService.failDownload = false
+ controller.downloadPrivateAIModel(pico)
+ await eventually { !controller.isBusy }
+ check(controller.privateAILoadState.isLoaded("pico") && vm.verificationCount == 1, "Download retry verifies and completes")
+ await PrivateAIIntegrationService.lastProgress?(.init(initialExpectedBytes: 10))
+ check(controller.privateAILoadState.isLoaded("pico"), "Late progress from finished download cannot replace ready state")
+
+ controller.privateAIModelUpdateStatusByID["pico"] = .init(state: .updateAvailable)
+ vm.verified = false
+ controller.updatePrivateAIModel(pico)
+ await eventually { !controller.isBusy }
+ check(PrivateAIIntegrationService.rollbacks == 1 && PrivateAIIntegrationService.commits == 0, "Real controller update path rolls back failed verification")
+ check(controller.privateAILoadState.failureMessage(for: "pico") != nil, "Update verification failure remains visible")
+ check(controller.privateAILoadState.failureMessage(for: "pico")?.contains("test failure") == true, "Update error includes provider-specific detail, not literal interpolation")
+
+ let writesBeforeNoop = UserDefaults.standard.writes
+ let previewBeforeUpcoming = controller.previewModelID
+ let selectionBeforeUpcoming = controller.privateAISelectedModelID
+ for upcoming in PrivateAIUpcomingModel.allCases {
+ controller.previewModel(upcoming.id)
+ controller.persistPrivateAIModelSelection(upcoming.id)
+ check(PrivateAIModelRegistry.model(id: upcoming.id) == nil, "Coming-soon previews are not runtime models")
+ }
+ check(controller.previewModelID == previewBeforeUpcoming && controller.privateAISelectedModelID == selectionBeforeUpcoming, "Coming-soon identifiers cannot alter runtime selection")
+ check(UserDefaults.standard.writes == writesBeforeNoop, "Coming-soon identifiers never persist")
+ controller.persistPrivateAIModelSelection("invalid")
+ controller.persistPrivateAIModelSelection("pico")
+ check(UserDefaults.standard.writes == writesBeforeNoop, "Invalid/redundant selection must not persist or reset verification")
+ controller.downloadPrivateAIModel(.init(id: "pico", canDownload: false))
+ check(!controller.isBusy, "Missing download configuration releases operation slot")
+ controller.deletePrivateAIModel(pico)
+ check(!controller.isBusy, "Non-removable model deletion releases operation slot")
+ PrivateAIIntegrationService.installed = true
+ controller.deletePrivateAIModel(.init(id: "mini"))
+ check(!controller.isBusy && PrivateAIIntegrationService.removals == 0, "Stale deletion confirmation cannot delete another selection")
+ let writesBeforeDeletion = UserDefaults.standard.writes
+ controller.deletePrivateAIModel(pico)
+ controller.deletePrivateAIModel(pico)
+ await eventually { !controller.isBusy }
+ check(PrivateAIIntegrationService.removals == 1 && controller.privateAILoadState == .idle, "Confirmed deletion runs once and returns to idle")
+ check(UserDefaults.standard.writes == writesBeforeDeletion && vm.selectedProviderID == "external", "Deletion does not change model selection or shortcut provider")
+ PrivateAIIntegrationService.installed = false
+
+ PrivateAIIntegrationService.suspendRead = true
+ controller.privateAILoadState = .idle
+ controller.refreshPrivateAILoadState()
+ await eventually { PrivateAIIntegrationService.readContinuation != nil }
+ PrivateAIIntegrationService.installed = true
+ PrivateAIIntegrationService.suspendLoad = true
+ controller.loadPrivateAIModel(pico)
+ await eventually { PrivateAIIntegrationService.loadContinuation != nil }
+ PrivateAIIntegrationService.readContinuation?.resume(returning: nil)
+ PrivateAIIntegrationService.readContinuation = nil
+ for _ in 0..<20 { await Task.yield() }
+ check(controller.privateAILoadState.isLoading("pico") && controller.isBusy, "Late idle read cannot erase a newer load")
+ controller.previewModel("mini")
+ controller.activatePreviewModel()
+ check(controller.privateAISelectedModelID == "pico" && controller.previewModelID == "mini", "Pending load permits preview but not activation")
+ PrivateAIIntegrationService.loadContinuation?.resume(returning: .init(state: .ready))
+ PrivateAIIntegrationService.loadContinuation = nil
+ await eventually { !controller.isBusy }
+ check(controller.privateAILoadState.isLoaded("pico"), "Load completion stays attached to activated model, not preview")
+ var activations = 0
+ vm.verified = false
+ controller.usePreviewModel(isInstalled: true) { activations += 1 }
+ controller.usePreviewModel(isInstalled: true) { activations += 1 }
+ await eventually { !controller.isBusy }
+ check(activations == 0, "Failed activation must not switch shortcut routing")
+ controller.refreshPrivateAILoadState()
+ for _ in 0..<20 { await Task.yield() }
+ check(controller.privateAILoadState.failureMessage(for: "mini") != nil, "Passive runtime refresh preserves failed activation")
+ vm.verified = true
+ controller.usePreviewModel(isInstalled: true) { activations += 1 }
+ await eventually { !controller.isBusy }
+ check(activations == 1 && controller.privateAILoadState.isLoaded("mini"), "Explicit activation calls routing once after successful verification")
+ check(vm.selectedProviderID == "external" && vm.selectedModel == "external-model", "Activation preserves external editor configuration")
+ var completionCount = 0
+ var reportedError: String?
+ let writesBeforeVerification = UserDefaults.standard.writes
+ controller.verifyPrivateAIConnection(.init(id: "mini"), onCompletion: { error in
+ completionCount += 1
+ reportedError = error
+ })
+ controller.verifyPrivateAIConnection(.init(id: "mini"), onCompletion: { _ in completionCount += 100 })
+ await eventually { !controller.isBusy }
+ check(completionCount == 1 && reportedError == nil, "Manual verification reports success once; duplicate clicks do not report")
+ vm.verified = false
+ controller.verifyPrivateAIConnection(.init(id: "mini"), onCompletion: { error in
+ completionCount += 1
+ reportedError = error
+ })
+ await eventually { !controller.isBusy }
+ check(completionCount == 2 && reportedError?.contains("test failure") == true, "Manual verification reports the actual failure")
+ controller.verifyPrivateAIConnection(.init(id: "pico"), onCompletion: { _ in completionCount += 100 })
+ check(completionCount == 2 && UserDefaults.standard.writes == writesBeforeVerification, "Inactive verification has no result or persistence side effects")
+ }
+}
diff --git a/Tests/ProviderModelVerificationStoreTests.swift b/Tests/ProviderModelVerificationStoreTests.swift
new file mode 100644
index 00000000..36220424
--- /dev/null
+++ b/Tests/ProviderModelVerificationStoreTests.swift
@@ -0,0 +1,43 @@
+import Foundation
+
+@main
+enum ProviderModelVerificationStoreTests {
+ @MainActor
+ static func main() {
+ guard let defaults = UserDefaults(suiteName: "fluidvoice.model-verification-tests.\(UUID().uuidString)") else {
+ preconditionFailure("Could not create isolated test defaults")
+ }
+ defer { defaults.removeObject(forKey: ProviderModelVerificationStore.defaultsKey) }
+ let store = ProviderModelVerificationStore(defaults: defaults)
+ func identity(_ model: String, key: String = "secret", endpoint: String = "https://example.com/v1", provider: String = "openrouter") -> String {
+ ProviderModelVerificationStore.identity(providerID: provider, baseURL: endpoint, apiKey: key, model: model)
+ }
+ let first = identity("model-a")
+ let second = identity("model-b")
+ precondition(!store.contains(first))
+ store.recordSuccess(first)
+ precondition(store.contains(first) && !store.contains(second), "Changing models must not reuse another model's check")
+ store.recordSuccess(second)
+ precondition(store.contains(first) && store.contains(second), "Switching back should remember success")
+ let reloaded = ProviderModelVerificationStore(defaults: defaults)
+ precondition(reloaded.contains(first) && reloaded.contains(second), "Success must survive relaunch")
+ precondition(!store.contains(identity("model-a", key: "changed")))
+ precondition(!store.contains(identity("model-a", endpoint: "https://other.example/v1")))
+ precondition(!store.contains(identity("model-a", provider: "other-provider")))
+ precondition(identity(" model-a ") == first)
+ store.remove(first)
+ precondition(!store.contains(first) && store.contains(second), "Failed recheck affects only its model identity")
+ for index in 0..<300 {
+ store.recordSuccess(identity("model-\(index)"), now: Date(timeIntervalSince1970: Double(index)))
+ }
+ guard let saved = defaults.dictionary(forKey: ProviderModelVerificationStore.defaultsKey) else {
+ preconditionFailure("Expected persisted verifications")
+ }
+ precondition(saved.count == ProviderModelVerificationStore.maximumEntries)
+ precondition(saved.keys.allSatisfy { $0.count == 64 && !$0.contains("secret") })
+ precondition(!store.contains(identity("model-0")) && store.contains(identity("model-299")))
+ defaults.set(["bad": Double.nan], forKey: ProviderModelVerificationStore.defaultsKey)
+ precondition(!ProviderModelVerificationStore(defaults: defaults).contains(first))
+ print("PASS: per-model persistence, model/key/endpoint/provider isolation, failure removal, bounded history and invalid data")
+ }
+}
diff --git a/Tests/ProviderSetupBoundaryTests.swift b/Tests/ProviderSetupBoundaryTests.swift
new file mode 100644
index 00000000..34d52767
--- /dev/null
+++ b/Tests/ProviderSetupBoundaryTests.swift
@@ -0,0 +1,206 @@
+import Foundation
+
+// Compile the production draft/save adapter against isolated settings and Keychain doubles.
+final class UserDefaults {
+ static let standard = UserDefaults()
+ var values: [String: [String]] = [:]
+ // Match Foundation UserDefaults, including an absent key.
+ // swiftlint:disable:next discouraged_optional_collection
+ func stringArray(forKey key: String) -> [String]? { values[key] }
+ func set(_ value: [String], forKey key: String) { values[key] = value }
+}
+struct PrivateAIProviderFeature {
+ static let shared = PrivateAIProviderFeature()
+ let providerID = "fluid"
+}
+struct ModelRepository {
+ static let shared = ModelRepository()
+ func isBuiltIn(_ id: String) -> Bool { ["openai", "ollama", "fluid"].contains(id) }
+ func defaultModels(for id: String) -> [String] { ["default-model"] }
+}
+final class SettingsStore {
+ struct SavedProvider {
+ var id = UUID().uuidString
+ let name: String
+ let baseURL: String
+ let models: [String]
+ }
+ struct Configuration: Equatable {
+ var providerID: String
+ var modelName = "model"
+ var shortcut = "keep-shortcut"
+ }
+ var selectedProviderID = "fluid"
+ var selectedModel: String? = "mini"
+ var rewriteModeSelectedProviderID = ""
+ var rewriteModeSelectedModel: String?
+ var commandModeSelectedProviderID = ""
+ var commandModeSelectedModel: String?
+ var availableModelsByProvider: [String: [String]] = [:]
+ var selectedModelByProvider: [String: String] = [:]
+ var dictationPromptConfigurations: [String: Configuration] = [:]
+ var verifiedProviderFingerprints: [String: String] = [:]
+}
+final class AIEnhancementSettingsViewModel {
+ struct ProviderItemData {
+ let id: String
+ let name: String
+ let isBuiltIn: Bool
+ }
+ let settings = SettingsStore()
+ var isTestingConnection = false
+ var isFetchingModels = false
+ var selectedProviderID = "openai"
+ var managedOriginalKey: String?
+ var fetchedModelsProviders: Set<String> = []
+ var providerAPIKeys: [String: String] = [:]
+ var savedProviders: [SettingsStore.SavedProvider] = []
+ var availableModelsByProvider: [String: [String]] = [:]
+ var selectedModelByProvider: [String: String] = ["fluid": "mini"]
+ var cachedAddedProviderItems: [ProviderItemData] = []
+ var failKeychain = false
+ var saves = 0
+ var keySaves = 0
+ var persistedKeys: [String: String] = [:]
+ func providerKey(for id: String) -> String { id }
+ func providerAPIKey(for id: String) -> String { providerAPIKeys[id] ?? "" }
+ func updateProviderAPIKey(_ value: String, for id: String) { providerAPIKeys[id] = value }
+ func saveProviderAPIKeys(invalidating id: String) -> Bool {
+ keySaves += 1
+ guard !failKeychain else { return false }
+ persistedKeys = providerAPIKeys
+ return true
+ }
+ func hasProviderAPIKeyDraft(for id: String) -> Bool { providerAPIKeys[id] != nil }
+ func refreshProviderItems() {
+ let items = [ProviderItemData(id: "openai", name: "OpenAI", isBuiltIn: true),
+ ProviderItemData(id: "ollama", name: "Ollama", isBuiltIn: true),
+ ProviderItemData(id: "fluid", name: "Fluid", isBuiltIn: true)]
+ + savedProviders.map { ProviderItemData(id: $0.id, name: $0.name, isBuiltIn: false) }
+ cachedAddedProviderItems = addedProviderItems(from: items)
+ }
+ func saveSavedProviders() { saves += 1; refreshProviderItems() }
+ func clearEditProviderDraft() {}
+ func finishConfiguringProvider() { selectedProviderID = settings.selectedProviderID }
+ func refreshVerifiedProviders() {}
+ func selectSoleVerifiedProviderIfNeeded() {}
+}
+
+@main enum ProviderSetupBoundaryTests {
+ static func main() throws {
+ var count = 0
+ func check(_ value: Bool, _ message: String) {
+ precondition(value, message)
+ count += 1
+ }
+ let vm = AIEnhancementSettingsViewModel()
+ vm.refreshProviderItems()
+ check(vm.cachedAddedProviderItems.isEmpty, "Fresh catalog stays hidden")
+ var draft = ProviderSetupDraft(name: "Local", baseURL: "http://localhost:1234/v1", model: "tiny")
+ check(draft.isValid && vm.saves == 0, "Editing a valid draft has no persistence effects")
+ draft.baseURL = "file:///tmp/model"
+ check(!draft.isValid && !vm.addProvider(draft), "Reject non-HTTP endpoints without persistence")
+ draft.baseURL = "https://user:[email protected]"
+ check(!draft.isValid, "Reject credentials embedded in URL")
+ draft.baseURL = "http://localhost:1234/v1"
+ draft.apiKey = "test-key"
+ vm.failKeychain = true
+ check(!vm.addProvider(draft) && vm.savedProviders.isEmpty && vm.providerAPIKeys.isEmpty && vm.saves == 0,
+ "Keychain failure keeps records, keys, and model maps unchanged")
+ vm.failKeychain = false
+ check(vm.addProvider(draft) && vm.savedProviders.count == 1, "Explicit Add saves a custom provider")
+ check(vm.settings.selectedProviderID == "fluid" && vm.selectedModelByProvider["fluid"] == "mini", "Adding does not change current route/model")
+ check(vm.addProvider(draft) && vm.savedProviders.count == 2, "Same display name cannot overwrite another provider")
+ check(vm.cachedAddedProviderItems.count == 2, "Saved custom providers appear without verification")
+ let builtIn = ProviderSetupDraft(providerID: "ollama", name: "Ollama", baseURL: "http://localhost:11434/v1")
+ check(vm.addProvider(builtIn), "Keyless local provider can be added")
+ check(!vm.addProvider(builtIn), "Duplicate built-in Add is rejected")
+ check(vm.cachedAddedProviderItems.contains { $0.id == "ollama" }, "Keyless provider remains visible via explicit membership")
+ vm.providerAPIKeys["openai"] = "expired-key"
+ vm.refreshProviderItems()
+ check(vm.cachedAddedProviderItems.contains { $0.id == "openai" }, "Unverified legacy credentials remain discoverable")
+ vm.providerAPIKeys.removeValue(forKey: "openai")
+ vm.settings.dictationPromptConfigurations["legacy"] = .init(providerID: "openai")
+ vm.refreshProviderItems()
+ check(vm.cachedAddedProviderItems.contains { $0.id == "openai" }, "Referenced provider stays visible after credentials disappear")
+ vm.isFetchingModels = true
+ check(!vm.addProvider(draft), "In-flight editor request blocks another Add")
+ let source = try String(contentsOfFile: "Sources/Fluid/UI/AISettingsView+AIConfiguration.swift", encoding: .utf8)
+ let manager = source.components(separatedBy: "private var externalProviderManager: some View")[1]
+ .components(separatedBy: "private var legacyAIConfigurationCard")[0]
+ check(!manager.contains("Use for shortcut") && !manager.contains("Edit details"), "External manager has no duplicate editor or shortcut assignment action")
+ check(source.contains(".onSubmit {") && source.contains("self.viewModel.addNewModel()"), "Manual model input retains Enter-to-add behavior")
+ check(source.contains(".accessibilityLabel(\"Add model\")"), "Model add button remains accessible")
+ check(source.contains("if isCustom || managementLayout"), "Built-in management exposes removal")
+ let makeDefault = source.components(separatedBy: "private func makePrimaryDefaultProvider")[1]
+ .components(separatedBy: "private func modelBinding")[0]
+ check(makeDefault.contains("saveManagedProviderAPIKeyIfNeeded") && !makeDefault.contains("saveProviderAPIKeys"),
+ "Making a provider default only persists an active credential edit")
+ let removal = AIEnhancementSettingsViewModel()
+ removal.providerAPIKeys = ["openai": "remove-key", "other": "keep-key"]
+ removal.settings.dictationPromptConfigurations = [
+ "affected": .init(providerID: "openai"),
+ "unrelated": .init(providerID: "other"),
+ ]
+ removal.settings.rewriteModeSelectedProviderID = "openai"
+ removal.settings.rewriteModeSelectedModel = "old"
+ removal.settings.commandModeSelectedProviderID = "other"
+ removal.settings.commandModeSelectedModel = "keep-model"
+ removal.availableModelsByProvider = ["openai": ["old"], "other": ["keep"]]
+ removal.selectedModelByProvider["openai"] = "old"
+ UserDefaults.standard.set(["openai", "other"], forKey: AIEnhancementSettingsViewModel.addedProviderIDsKey)
+ let before = removal.settings.dictationPromptConfigurations
+ removal.failKeychain = true
+ check(!removal.deleteCurrentProvider(), "Failed credential removal must fail the operation")
+ check(removal.providerAPIKeys["openai"] == "remove-key" && removal.saves == 0, "Failed removal restores keys without saving provider changes")
+ check(removal.settings.dictationPromptConfigurations == before, "Failed removal preserves assignments")
+ check(UserDefaults.standard.stringArray(forKey: AIEnhancementSettingsViewModel.addedProviderIDsKey) == ["openai", "other"], "Failed removal preserves explicit membership")
+ removal.failKeychain = false
+ removal.isFetchingModels = true
+ check(!removal.deleteCurrentProvider(), "Busy editor cannot remove a provider")
+ removal.isFetchingModels = false
+ check(removal.deleteCurrentProvider(), "Built-in removal succeeds")
+ check(removal.settings.selectedProviderID == "fluid" && removal.settings.selectedModel == "mini", "Removing another provider preserves the default")
+ check(removal.settings.dictationPromptConfigurations["affected"]?.providerID == "", "Removed provider cannot remain referenced")
+ check(removal.settings.dictationPromptConfigurations["affected"]?.shortcut == "keep-shortcut", "Removal preserves hotkeys")
+ check(removal.settings.dictationPromptConfigurations["unrelated"] == before["unrelated"], "Unrelated prompt assignment is unchanged")
+ check(removal.settings.rewriteModeSelectedProviderID.isEmpty && removal.settings.rewriteModeSelectedModel == nil, "Affected rewrite route is cleared")
+ check(removal.settings.commandModeSelectedProviderID == "other" && removal.settings.commandModeSelectedModel == "keep-model", "Unrelated command route is unchanged")
+ check(removal.providerAPIKeys == ["other": "keep-key"] && removal.availableModelsByProvider["other"] == ["keep"], "Unrelated provider credentials and models survive")
+ check(!removal.cachedAddedProviderItems.contains { $0.id == "openai" }, "Removed built-in disappears from added providers")
+ removal.selectedProviderID = "ollama"
+ removal.settings.selectedProviderID = "ollama"
+ let keySavesBeforeKeylessRemoval = removal.keySaves
+ removal.failKeychain = true
+ check(removal.deleteCurrentProvider() && removal.settings.selectedProviderID.isEmpty && removal.settings.selectedModel == nil, "Removing the default clears its model without selecting another provider")
+ check(removal.keySaves == keySavesBeforeKeylessRemoval, "Removing a keyless provider does not require a Keychain write")
+ removal.selectedProviderID = "fluid"
+ check(!removal.deleteCurrentProvider(), "External provider removal cannot remove private AI")
+ let closing = AIEnhancementSettingsViewModel()
+ closing.providerAPIKeys["openai"] = "edited-key"
+ closing.managedOriginalKey = "edited-key"
+ closing.failKeychain = true
+ check(closing.saveManagedProviderBeforeClosing("openai") && closing.keySaves == 0, "Unchanged key closes without any Keychain write, even if writes would fail")
+ closing.managedOriginalKey = "old-key"
+ closing.failKeychain = true
+ check(!closing.saveManagedProviderBeforeClosing("openai"), "Keychain failure keeps Manage open")
+ check(closing.providerAPIKeys["openai"] == "edited-key" && closing.settings.selectedProviderID == "fluid", "Failed close preserves the draft and default")
+ closing.failKeychain = false
+ check(closing.saveManagedProviderBeforeClosing("openai") && closing.persistedKeys["openai"] == "edited-key", "Done persists an edited key without verification or model refresh")
+ let savedCount = closing.keySaves
+ closing.selectedProviderID = "fluid"
+ check(closing.saveManagedProviderBeforeClosing("openai") && closing.keySaves == savedCount, "Removal cleanup must not save a different selected provider")
+ closing.selectedProviderID = "ollama"
+ check(closing.saveManagedProviderBeforeClosing("ollama") && closing.keySaves == savedCount, "Keyless provider close does not touch Keychain")
+ closing.failKeychain = true
+ check(closing.saveManagedProviderAPIKeyIfNeeded("ollama") && closing.keySaves == savedCount, "Making a keyless provider default does not require a Keychain write")
+ closing.isTestingConnection = true
+ check(!closing.saveManagedProviderBeforeClosing("ollama"), "Busy editor cannot dismiss")
+ check(manager.contains(".interactiveDismissDisabled()"), "Interactive dismissal cannot bypass failed persistence")
+ let historySource = try String(contentsOfFile: "Sources/Fluid/UI/TranscriptionHistoryView.swift", encoding: .utf8)
+ let audioRequest = historySource.components(separatedBy: "private struct AudioAvailabilityRequest")[1]
+ .components(separatedBy: "private var filteredEntries")[0]
+ check(!audioRequest.contains("selectedEntry") && !audioRequest.contains("selectedID"), "Row selection cannot restart audio scans")
+ print("Passed \(count) provider setup assertions")
+ }
+}
diff --git a/Tests/StatsSnapshotStoreFixtures.swift b/Tests/StatsSnapshotStoreFixtures.swift
new file mode 100644
index 00000000..b2b983fa
--- /dev/null
+++ b/Tests/StatsSnapshotStoreFixtures.swift
@@ -0,0 +1,8 @@
+import Combine
+
+/// In-memory publisher only: tests never open the production history or settings.
+@MainActor
+final class TranscriptionHistoryStore {
+ static let shared = TranscriptionHistoryStore()
+ @Published var entries: [TranscriptionHistoryEntry] = []
+}
diff --git a/Tests/StatsSnapshotTests.swift b/Tests/StatsSnapshotTests.swift
new file mode 100644
index 00000000..f4d4e8ad
--- /dev/null
+++ b/Tests/StatsSnapshotTests.swift
@@ -0,0 +1,121 @@
+import Foundation
+
+@main
+struct StatsSnapshotTests {
+ static func main() async throws {
+ var calendar = Calendar(identifier: .gregorian)
+ guard let timeZone = TimeZone(identifier: "America/Los_Angeles") else {
+ preconditionFailure("Missing test time zone")
+ }
+ calendar.timeZone = timeZone
+ func date(_ day: Int, month: Int = 9) -> Date {
+ guard let value = calendar.date(from: DateComponents(year: 2026, month: month, day: day, hour: 12)) else {
+ preconditionFailure("Invalid test date")
+ }
+ return value
+ }
+ func entry(_ day: Int, text: String, app: String = "Notes", ai: Bool = false, month: Int = 9) -> TranscriptionHistoryEntry {
+ TranscriptionHistoryEntry(
+ timestamp: date(day, month: month),
+ rawText: "raw must not count",
+ processedText: text,
+ appName: app,
+ windowTitle: "",
+ wasAIProcessed: ai
+ )
+ }
+ let entries = [
+ entry(7, text: "one two\nthree", ai: true),
+ entry(7, text: "four", app: ""),
+ entry(6, text: "five six"),
+ entry(4, text: "seven"),
+ entry(3, text: "eight"),
+ ]
+ let original = entries
+ let snapshot = try StatsSnapshot.build(entries: entries, now: date(7), calendar: calendar)
+ precondition(entries == original, "Summary must not mutate history")
+ precondition(snapshot.totalWords == 8 && snapshot.totalTranscriptions == 5)
+ precondition(snapshot.averageWordsPerTranscription == 1 && snapshot.aiEnhancementRate == 20)
+ precondition(snapshot.currentStreak == 2 && snapshot.bestStreak == 2)
+ precondition(snapshot.usingWeekdays(true).currentStreak == 3 && snapshot.usingWeekdays(true).bestStreak == 3)
+ precondition(snapshot.currentStreak == 2, "Settings projection must not alter cached summary")
+ precondition(snapshot.longestTranscriptionWords == 3 && snapshot.mostWordsInDay == 4 && snapshot.mostTranscriptionsInDay == 2)
+ precondition(snapshot.dailyWordCounts(days: 7).count == 7 && snapshot.activity.count == 30)
+ precondition(snapshot.activity.last?.words == 4 && snapshot.activity.reduce(0) { $0 + $1.words } == 8)
+ precondition(snapshot.topAppsFormatted(limit: 3) == ["Notes", "Unknown"])
+ precondition(snapshot.formattedTimeSaved(typingWPM: 0) == "< 1m")
+ precondition(snapshot.formattedTimeSaved(typingWPM: 200) == "< 1m")
+ let empty = try StatsSnapshot.build(entries: [], now: date(7), calendar: calendar)
+ precondition(empty.totalWords == 0 && empty.currentStreak == 0 && empty.bestStreak == 0 && empty.peakHourFormatted == "N/A")
+ precondition(empty.totalMilestonesAchieved == 0 && empty.totalMilestonesPossible == 18)
+ let stale = try StatsSnapshot.build(entries: entries, now: date(10), calendar: calendar)
+ precondition(stale.currentStreak == 0 && stale.weekdayCurrentStreak == 0 && stale.bestStreak == 2)
+ let weekend = try StatsSnapshot.build(entries: [entry(3, text: "x"), entry(4, text: "x"), entry(6, text: "x")], now: date(6), calendar: calendar)
+ precondition(weekend.weekdayCurrentStreak == 2 && weekend.weekdayBestStreak == 2)
+ let dst = try StatsSnapshot.build(entries: [entry(7, text: "a", month: 3), entry(8, text: "b", month: 3), entry(9, text: "c", month: 3)], now: date(9, month: 3), calendar: calendar)
+ precondition(dst.currentStreak == 3 && dst.bestStreak == 3, "Streaks must use calendar days across DST")
+ let large = Array(repeating: entry(7, text: String(repeating: "word ", count: 100)), count: 9000)
+ let start = Date()
+ let big = try StatsSnapshot.build(entries: large, now: date(7), calendar: calendar)
+ precondition(big.totalWords == 900_000 && big.longestTranscriptionWords == 100 && big.activity.count == 30)
+ print("9,000-entry / 900,000-word summary: \(Int(Date().timeIntervalSince(start) * 1000)) ms off-main workload")
+ let cancelled = Task.detached {
+ try await Task.sleep(nanoseconds: 50_000_000)
+ return try StatsSnapshot.build(entries: large, now: Date(), calendar: Calendar.current)
+ }
+ cancelled.cancel()
+ do { _ = try await cancelled.value; preconditionFailure("Cancelled worker must not return a snapshot") } catch is CancellationError {}
+ try await self.testStore(entries: entries)
+ print("PASS: totals, records, chart bounds, immutable input, settings projection, empty, stale, weekends, DST, large history and cancellation")
+ }
+
+ @MainActor
+ static func testStore(entries: [TranscriptionHistoryEntry]) async throws {
+ let history = TranscriptionHistoryStore()
+ let store = StatsSnapshotStore(history: history)
+ let first = UUID()
+ let second = UUID()
+ history.entries = entries
+ try await Task.sleep(nanoseconds: 100_000_000)
+ precondition(store.snapshot == nil && !store.isUpdating, "Hidden Stats must not aggregate")
+ store.activate(first)
+ for _ in 0..<100 {
+ if !store.isUpdating { break }
+ try await Task.sleep(nanoseconds: 10_000_000)
+ }
+ precondition(store.snapshot?.totalWords == 8 && !store.isUpdating)
+ store.deactivate(first)
+ store.activate(first)
+ precondition(!store.isUpdating, "Reopening unchanged Stats must use the cache")
+ history.entries = Array(repeating: entries[0], count: 1000)
+ history.entries = [entries[1]]
+ for _ in 0..<100 {
+ if !store.isUpdating { break }
+ try await Task.sleep(nanoseconds: 10_000_000)
+ }
+ precondition(store.snapshot?.totalWords == 1, "Only newest publisher value may win")
+ store.activate(second)
+ store.deactivate(first)
+ history.entries = entries
+ for _ in 0..<100 {
+ if !store.isUpdating { break }
+ try await Task.sleep(nanoseconds: 10_000_000)
+ }
+ precondition(store.snapshot?.totalWords == 8, "One window closing must not cancel another")
+ history.entries = Array(repeating: entries[0], count: 1000)
+ store.deactivate(second)
+ try await Task.sleep(nanoseconds: 100_000_000)
+ precondition(!store.isUpdating && store.snapshot?.totalWords == 8, "Hidden cancelled work cannot publish")
+ history.entries = []
+ precondition(store.snapshot == nil, "Reset must discard old totals immediately")
+ store.activate(first)
+ for _ in 0..<100 {
+ if !store.isUpdating { break }
+ try await Task.sleep(nanoseconds: 10_000_000)
+ }
+ precondition(store.snapshot?.totalWords == 0 && store.snapshot?.totalTranscriptions == 0)
+ precondition(history.entries.isEmpty, "Stats must never write to history")
+ store.deactivate(first)
+ print("PASS: hidden inactivity, cache reuse, rapid replacement, multiple windows, cancellation, reset and no history writes")
+ }
+}
diff --git a/output/imagegen/external-provider-concepts/01-aligned-rows.png b/output/imagegen/external-provider-concepts/01-aligned-rows.png
new file mode 100644
index 00000000..3a684d05
Binary files /dev/null and b/output/imagegen/external-provider-concepts/01-aligned-rows.png differ
diff --git a/output/imagegen/external-provider-concepts/02-stacked-fields.png b/output/imagegen/external-provider-concepts/02-stacked-fields.png
new file mode 100644
index 00000000..9db4593a
Binary files /dev/null and b/output/imagegen/external-provider-concepts/02-stacked-fields.png differ
diff --git a/output/imagegen/external-provider-concepts/03-compact-panel.png b/output/imagegen/external-provider-concepts/03-compact-panel.png
new file mode 100644
index 00000000..b8ac80a0
Binary files /dev/null and b/output/imagegen/external-provider-concepts/03-compact-panel.png differ
diff --git a/output/imagegen/external-provider-concepts/04-footer-bar.png b/output/imagegen/external-provider-concepts/04-footer-bar.png
new file mode 100644
index 00000000..8c22690e
Binary files /dev/null and b/output/imagegen/external-provider-concepts/04-footer-bar.png differ
diff --git a/output/imagegen/external-provider-concepts/05-two-groups.png b/output/imagegen/external-provider-concepts/05-two-groups.png
new file mode 100644
index 00000000..b226fe99
Binary files /dev/null and b/output/imagegen/external-provider-concepts/05-two-groups.png differ
diff --git a/output/imagegen/external-provider-concepts/README.md b/output/imagegen/external-provider-concepts/README.md
new file mode 100644
index 00000000..ef24cf6f
--- /dev/null
+++ b/output/imagegen/external-provider-concepts/README.md
@@ -0,0 +1,15 @@
+# External provider layout concepts
+
+Generated with the built-in image-generation tool from the supplied OpenAI settings screenshot. Preview concepts only; no app implementation changed.
+
+## Shared prompt
+
+High-fidelity dark macOS OpenAI settings dialog. Simple, symmetric charcoal surfaces, restrained blue accents, system typography, equal margins and consistent control heights. Preserve API Key (masked dots only), Get API Key, Model babbage-002 with adjacent refresh and plus, Reasoning, Not enabled, Configure, Verify Connection and Done. No shortcuts, extra tabs, marketing, or invented features. Concept label outside the dialog.
+
+## Variant prompts and files
+
+- [Option 1 — Aligned rows](01-aligned-rows.png): One understated inset group with three horizontal rows, identical fixed left label column and aligned right control region. API key masked field and secondary Get API Key; Model selector with refresh and plus adjacent; Reasoning with Not enabled and Configure. Fine separators. Verify Connection bottom right below group.
+- [Option 2 — Stacked fields](02-stacked-fields.png): Two clean full-width stacked fields with labels above: API Key and Model. API key row masked field and Get API Key small text action; Model row selector refresh plus. Third full-width Reasoning row with Not enabled and Configure on the right. Verify Connection bottom right. No nested box and no redundant section heading.
+- [Option 3 — Compact panel](03-compact-panel.png): Small dense but comfortable dialog, no large empty margins. API key and Model labels left in a consistent grid. Refresh plus at right end of model row. Reasoning inline below aligned with inputs, small Configure button and Not enabled label. Verify Connection at bottom right, all controls same height. Restrained native Mac utility aesthetic.
+- [Option 4 — Footer bar](04-footer-bar.png): Elegant macOS sheet with comfortable aligned fields, API Key field and Get API Key; Model selector with refresh and plus; Reasoning Configure and Not enabled in a tidy row. Fixed thin footer separated by a hairline contains secondary Done at left and blue Verify Connection at right; no duplicate Done in header. One continuous flat content surface.
+- [Option 5 — Two quiet groups](05-two-groups.png): Two understated inset groups with same exact width and inset. First is Connection containing masked API key input with Get API Key. Second is Model containing model picker with refresh and plus, then a divider and Reasoning Not enabled with Configure. Verify Connection right aligned below groups. Header Done top right. Keep compact and no extra options.
diff --git a/output/imagegen/fluid-card-concepts/01-quiet-native.png b/output/imagegen/fluid-card-concepts/01-quiet-native.png
new file mode 100644
index 00000000..b1a2366a
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/01-quiet-native.png differ
diff --git a/output/imagegen/fluid-card-concepts/02-horizontal.png b/output/imagegen/fluid-card-concepts/02-horizontal.png
new file mode 100644
index 00000000..b7f00ba3
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/02-horizontal.png differ
diff --git a/output/imagegen/fluid-card-concepts/03-editorial.png b/output/imagegen/fluid-card-concepts/03-editorial.png
new file mode 100644
index 00000000..4c143336
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/03-editorial.png differ
diff --git a/output/imagegen/fluid-card-concepts/04-footer-rail.png b/output/imagegen/fluid-card-concepts/04-footer-rail.png
new file mode 100644
index 00000000..321f32dd
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/04-footer-rail.png differ
diff --git a/output/imagegen/fluid-card-concepts/05-soft-panel.png b/output/imagegen/fluid-card-concepts/05-soft-panel.png
new file mode 100644
index 00000000..8e45e59a
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/05-soft-panel.png differ
diff --git a/output/imagegen/fluid-card-concepts/README.md b/output/imagegen/fluid-card-concepts/README.md
new file mode 100644
index 00000000..9378caeb
--- /dev/null
+++ b/output/imagegen/fluid-card-concepts/README.md
@@ -0,0 +1,23 @@
+# Fluid model card concepts
+
+Generated with the built-in image generation tool, using the supplied card screenshot as a reference. Preview concepts only; none is implemented in the app.
+
+## Images
+
+- [Quiet native](01-quiet-native.png)
+- [Horizontal utility](02-horizontal.png)
+- [Editorial](03-editorial.png)
+- [Footer rail](04-footer-rail.png)
+- [Soft panel](05-soft-panel.png)
+
+## Prompt set
+
+Shared specification: High-fidelity, flat, front-facing native macOS model-card mockup. Single card on charcoal canvas, dark navy/blue identity, crisp typography, no device frame. Preserve exact copy: Fluid 1 Pico; Smallest & fastest; Everyday dictation with basic cleanup and formatting.; Intelligence; Speed; Activate. Retain info and overflow controls. Intelligence uses two of five segments, Speed five of five, as illustrative design indicators rather than benchmark percentages. Inactive state: Activate is the primary action, with no selected checkmark. Avoid large circles, rings, illustrations, excessive glow, oversized empty space and additional marketing text. Make the card smaller, quieter, clearer and more symmetrical.
+
+1. Quiet native: Compact portrait, matte charcoal-navy, subtle border, 18px corners, 22px semibold title, compact description, small stacked metrics at bottom-right, blue rounded-rectangle Activate at bottom-left.
+2. Horizontal utility: Compact landscape, copy in left two-thirds, small aligned metrics in right third, footer Activate left and overflow right, info top-right, muted navy and 16px corners.
+3. Editorial: Almost-black blue compact portrait with thin blue top accent. Tight title/subtitle/body hierarchy. Two equal-width metric groups side by side, labels above thin segments. Quiet separator, Activate right and overflow left.
+4. Footer rail: Refined navy card, title and info in header, grouped copy. Lower utility rail places Activate left and tiny stacked metrics right, vertically balanced. Overflow near info, subtle gradient, 20px corners.
+5. Soft panel: Graphite with faint navy tint, header title/info/overflow, small metrics beside descriptive content in a secondary column, slim full-width Activate footer, consistent 20px padding.
+
+Image generation can vary exact proportions and indicator details; these are visual directions, not final UI specifications.
diff --git a/scripts/test_dictation_default_provider.sh b/scripts/test_dictation_default_provider.sh
new file mode 100644
index 00000000..8b7865a0
--- /dev/null
+++ b/scripts/test_dictation_default_provider.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-default-provider.XXXXXX)
+xcrun swiftc -parse-as-library Sources/Fluid/UI/AISettings/DictationDefaultProvider.swift Tests/DictationDefaultProviderTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/scripts/test_history_presentation.sh b/scripts/test_history_presentation.sh
new file mode 100644
index 00000000..2d454184
--- /dev/null
+++ b/scripts/test_history_presentation.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-history-presentation.XXXXXX)
+# Compile the real value types without starting the app or accessing user history.
+sed '/^\/\/ MARK: - Transcription History Store/,$d' Sources/Fluid/Persistence/TranscriptionHistoryStore.swift > "$task_test_dir/Entry.swift"
+sed '/^final nonisolated class DictationAudioHistoryStore/,$d' Sources/Fluid/Persistence/DictationAudioHistoryStore.swift > "$task_test_dir/Audio.swift"
+xcrun swiftc -parse-as-library "$task_test_dir/Entry.swift" "$task_test_dir/Audio.swift" Sources/Fluid/UI/HistoryTextDiff.swift Sources/Fluid/UI/HistoryAudioAvailability.swift Sources/Fluid/UI/ModelDisplayName.swift Tests/HistoryPresentationTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/scripts/test_paste_clipboard.sh b/scripts/test_paste_clipboard.sh
new file mode 100644
index 00000000..56a8275e
--- /dev/null
+++ b/scripts/test_paste_clipboard.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-clipboard-tests.XXXXXX)
+xcrun swiftc -O -parse-as-library Sources/Fluid/Services/PreservedPasteboardSnapshot.swift Tests/PasteClipboardTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/scripts/test_private_ai_settings_boundary.sh b/scripts/test_private_ai_settings_boundary.sh
new file mode 100644
index 00000000..51a01f1d
--- /dev/null
+++ b/scripts/test_private_ai_settings_boundary.sh
@@ -0,0 +1,18 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+if [ ! -d "$task_developer_dir/Platforms/MacOSX.platform" ]; then
+ echo "Select a full Xcode with DEVELOPER_DIR before running these tests." >&2
+ exit 1
+fi
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-fi-boundary.XXXXXX)
+xcrun swiftc -parse-as-library \
+ Sources/Fluid/UI/AISettings/PrivateAISettingsSession.swift \
+ Sources/Fluid/UI/AISettings/PrivateAIModelPresentation.swift \
+ Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift \
+ Tests/PrivateAISettingsControllerDoubles.swift \
+ Tests/PrivateAISettingsBoundaryTests.swift \
+ -o "$task_test_dir/boundary-tests"
+"$task_test_dir/boundary-tests"
diff --git a/scripts/test_provider_model_verification.sh b/scripts/test_provider_model_verification.sh
new file mode 100644
index 00000000..9860ced2
--- /dev/null
+++ b/scripts/test_provider_model_verification.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-model-verification.XXXXXX)
+xcrun swiftc -parse-as-library Sources/Fluid/UI/AISettings/ProviderModelVerificationStore.swift Tests/ProviderModelVerificationStoreTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/scripts/test_provider_setup_boundary.sh b/scripts/test_provider_setup_boundary.sh
new file mode 100644
index 00000000..4d55e684
--- /dev/null
+++ b/scripts/test_provider_setup_boundary.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+if [ ! -d "$task_developer_dir/Platforms/MacOSX.platform" ]; then
+ echo "Select a full Xcode with DEVELOPER_DIR before running these tests." >&2
+ exit 1
+fi
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-provider-setup.XXXXXX)
+# Exercise the exact production removal method against the same isolated settings doubles.
+{ echo 'extension AIEnhancementSettingsViewModel {'
+ sed -n '/^ func deleteCurrentProvider() -> Bool {/,/^ func saveEditedProvider() {/p' Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift | sed '$d'
+ sed -n '/^ func saveManagedProviderBeforeClosing(/,/^ private func selectProviderForUse(/p' Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift | sed '$d'
+ echo '}'
+} > "$task_test_dir/Removal.swift"
+xcrun swiftc -parse-as-library \
+ "$task_test_dir/Removal.swift" \
+ Sources/Fluid/UI/AISettings/ProviderSetupDraft.swift \
+ Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel+ProviderSetup.swift \
+ Tests/ProviderSetupBoundaryTests.swift \
+ -o "$task_test_dir/provider-tests"
+"$task_test_dir/provider-tests"
diff --git a/scripts/test_stats_snapshot.sh b/scripts/test_stats_snapshot.sh
new file mode 100644
index 00000000..aabc87fe
--- /dev/null
+++ b/scripts/test_stats_snapshot.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-stats-snapshot.XXXXXX)
+sed '/^\/\/ MARK: - Transcription History Store/,$d' Sources/Fluid/Persistence/TranscriptionHistoryStore.swift > "$task_test_dir/Entry.swift"
+sed '/^final nonisolated class DictationAudioHistoryStore/,$d' Sources/Fluid/Persistence/DictationAudioHistoryStore.swift > "$task_test_dir/Audio.swift"
+xcrun swiftc -parse-as-library "$task_test_dir/Entry.swift" "$task_test_dir/Audio.swift" Sources/Fluid/UI/StatsSnapshot.swift Sources/Fluid/UI/StatsSnapshotStore.swift Tests/StatsSnapshotStoreFixtures.swift Tests/StatsSnapshotTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"