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

Improve dictation startup, dictionary and shortcuts (#1220)

ALTIC2845f772eab6
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index d4f88567..af833e0c 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -1149,7 +1149,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 29;
+ CURRENT_PROJECT_VERSION = 30;
DEVELOPMENT_TEAM = V4J43B279J;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
@@ -1177,7 +1177,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
- MARKETING_VERSION = "1.6.12-beta.1";
+ MARKETING_VERSION = "1.6.12";
PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app.debug;
PRODUCT_NAME = "FluidVoice Debug";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -1204,7 +1204,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 29;
+ CURRENT_PROJECT_VERSION = 30;
DEVELOPMENT_TEAM = V4J43B279J;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
@@ -1232,7 +1232,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
- MARKETING_VERSION = "1.6.12-beta.1";
+ MARKETING_VERSION = "1.6.12";
PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app;
PRODUCT_NAME = FluidVoice;
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/Info.plist b/Info.plist
index 8e90343b..d2fcccfb 100644
--- a/Info.plist
+++ b/Info.plist
@@ -13,9 +13,9 @@
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleVersion</key>
- <string>29</string>
+ <string>30</string>
<key>CFBundleShortVersionString</key>
- <string>1.6.12-beta.1</string>
+ <string>1.6.12</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 9d436c8a..13a28fde 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -1256,7 +1256,7 @@ struct ContentView: View {
self.pendingModifierOnly = false
}
- private func shortcutConflictMessage(for shortcut: HotkeyShortcut, target: ShortcutRecordingTarget) -> String? {
+ func shortcutConflictMessage(for shortcut: HotkeyShortcut, target: ShortcutRecordingTarget) -> String? {
if target == .meeting, !shortcut.isMeetingRecordingShortcut {
return "Use a keyboard key with a modifier for meeting recording"
}
@@ -1287,11 +1287,15 @@ struct ContentView: View {
if self.isPromptModeShortcutEnabled {
configuredShortcuts.append((.secondaryDictation, self.promptModeHotkeyShortcut))
}
+ if self.isCommandModeShortcutEnabled, let shortcut = self.commandModeHotkeyShortcut {
+ configuredShortcuts.append((.command, shortcut))
+ }
+ if self.isPasteLastTranscriptionShortcutEnabled, let shortcut = self.pasteLastTranscriptionHotkeyShortcut {
+ configuredShortcuts.append((.pasteLast, shortcut))
+ }
let optionalConfiguredShortcuts: [(ShortcutRecordingTarget, HotkeyShortcut?)] = [
(.meeting, SettingsStore.shared.meetingRecordingHotkeyShortcut),
(.cancel, self.cancelRecordingHotkeyShortcut),
- (.command, self.commandModeHotkeyShortcut),
- (.pasteLast, self.pasteLastTranscriptionHotkeyShortcut),
]
for (otherTarget, configuredShortcut) in configuredShortcuts where otherTarget != target {
@@ -4758,22 +4762,23 @@ struct ContentView: View {
private func prewarmPrivateAIDictationIfNeeded(for slot: SettingsStore.DictationShortcutSlot) {
let appBundleID = self.asr.isRunningOrStarting ? self.recordingAppInfo?.bundleId : DictationAppSession.shared.appID
- let settings = SettingsStore.shared
- let route = DictationProviderRoute.resolve(
- settings: settings,
- dictationSlot: slot,
+ self.prewarmDictationTask?.cancel()
+ self.prewarmDictationTask = nil
+ guard let verification = DictationProviderRoute.privateAIWarmupVerification(
+ settings: .shared,
+ slot: slot,
appBundleID: appBundleID
- )
- guard route.usesPrivateAI,
- DictationAIPostProcessingGate.isConfigured(for: slot, appBundleID: appBundleID)
- else { return }
+ ) else { return }
- // Cancel any prior prewarm so rapid start/stop doesn't queue duplicate
- // actor work on PrivateAIIntegrationService.
- self.prewarmDictationTask?.cancel()
let warmupGeneration = MeetingModelResidencyCoordinator.shared.warmupGeneration
self.prewarmDictationTask = Task {
+ defer {
+ if !Task.isCancelled { self.prewarmDictationTask = nil }
+ }
guard !Task.isCancelled, MeetingModelResidencyCoordinator.shared.canRunWarmup(warmupGeneration) else { return }
+ let modelID = await Task.detached(priority: .utility) { verification.verifiedModelID() }.value
+ guard modelID != nil, !Task.isCancelled,
+ MeetingModelResidencyCoordinator.shared.canRunWarmup(warmupGeneration) else { return }
DebugLogger.shared.debug(
"ContentView: AI dictation prewarm started slot=\(slot.rawValue)",
source: "ContentView"
@@ -4783,9 +4788,6 @@ struct ContentView: View {
"AI dictation prewarm complete slot=\(slot.rawValue)",
source: "ContentView"
)
- if !Task.isCancelled {
- self.prewarmDictationTask = nil
- }
}
}
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 54ea7850..c33f3b4b 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -518,11 +518,11 @@ final class SettingsStore: ObservableObject {
self.setDictationPromptSelection(selection, for: .primary)
}
- func dictationPromptSelection(for slot: DictationShortcutSlot) -> DictationPromptSelection {
+ func dictationPromptSelection(for slot: DictationShortcutSlot, privateAIAvailable: Bool? = nil) -> DictationPromptSelection {
if self.isDictationPromptOff(for: slot) { return .off }
if let promptID = self.selectedDictationPromptID(for: slot) {
if promptID == PrivateAIProviderPromptFormat.promptSelectionID {
- return PrivateAIProviderPromptFormat.isAvailable(settings: self) ? .privateAI : .default
+ return (privateAIAvailable ?? PrivateAIProviderPromptFormat.isAvailable(settings: self)) ? .privateAI : .default
}
return .profile(promptID)
}
@@ -745,9 +745,9 @@ final class SettingsStore: ObservableObject {
return self.dictationPromptProfiles.first(where: { $0.id == id && $0.mode.normalized == .dictate })
}
- func resolvedDictationPromptSelection(for slot: DictationShortcutSlot, appBundleID: String?) -> DictationPromptSelection {
+ func resolvedDictationPromptSelection(for slot: DictationShortcutSlot, appBundleID: String?, privateAIAvailable: Bool? = nil) -> DictationPromptSelection {
if let manual = DictationAppSession.shared.choice(for: slot, appID: appBundleID) { return manual }
- let selection = self.dictationPromptSelection(for: slot)
+ let selection = self.dictationPromptSelection(for: slot, privateAIAvailable: privateAIAvailable)
guard selection != .off else { return .off }
let appOnly = self.promptRoutingScope(for: .dictate) == .selectedAppsOnly
guard appOnly || Self.dictationSelectionSupportsAppOverride(selection) else { return selection }
@@ -774,8 +774,8 @@ final class SettingsStore: ObservableObject {
return system ? fallback.systemPrompt : fallback.promptBody
}
- func resolvedDictationPromptProfile(for slot: DictationShortcutSlot, appBundleID: String?) -> DictationPromptProfile? {
- switch self.resolvedDictationPromptSelection(for: slot, appBundleID: appBundleID) {
+ func resolvedDictationPromptProfile(for slot: DictationShortcutSlot, appBundleID: String?, privateAIAvailable: Bool? = nil) -> DictationPromptProfile? {
+ switch self.resolvedDictationPromptSelection(for: slot, appBundleID: appBundleID, privateAIAvailable: privateAIAvailable) {
case .off:
return nil
case let .profile(promptID):
@@ -790,9 +790,9 @@ final class SettingsStore: ObservableObject {
}
}
- func isAppDictationPromptBindingActive(for slot: DictationShortcutSlot, appBundleID: String?) -> Bool {
+ func isAppDictationPromptBindingActive(for slot: DictationShortcutSlot, appBundleID: String?, privateAIAvailable: Bool? = nil) -> Bool {
guard DictationAppSession.shared.choice(for: slot, appID: appBundleID) == nil else { return false }
- let selection = self.dictationPromptSelection(for: slot)
+ let selection = self.dictationPromptSelection(for: slot, privateAIAvailable: privateAIAvailable)
guard Self.dictationSelectionSupportsAppOverride(selection) else { return false }
return self.hasAppPromptBinding(for: .dictate, appBundleID: appBundleID)
}
@@ -813,19 +813,19 @@ final class SettingsStore: ObservableObject {
return model.isEmpty ? "Basic" : "\(mode) · \(model)"
}
- func dictationPromptDisplayName(for slot: DictationShortcutSlot, appBundleID: String?) -> String {
- switch self.resolvedDictationPromptSelection(for: slot, appBundleID: appBundleID) {
+ func dictationPromptDisplayName(for slot: DictationShortcutSlot, appBundleID: String?, privateAIAvailable: Bool? = nil) -> String {
+ switch self.resolvedDictationPromptSelection(for: slot, appBundleID: appBundleID, privateAIAvailable: privateAIAvailable) {
case .off:
return "Basic"
case .default:
- if let profile = self.resolvedDictationPromptProfile(for: slot, appBundleID: appBundleID) {
+ if let profile = self.resolvedDictationPromptProfile(for: slot, appBundleID: appBundleID, privateAIAvailable: privateAIAvailable) {
let name = profile.name.trimmingCharacters(in: .whitespacesAndNewlines)
return name.isEmpty ? "Untitled" : name
}
return "Default"
case .privateAI:
- if self.isAppDictationPromptBindingActive(for: slot, appBundleID: appBundleID) {
- if let profile = self.resolvedDictationPromptProfile(for: slot, appBundleID: appBundleID) {
+ if self.isAppDictationPromptBindingActive(for: slot, appBundleID: appBundleID, privateAIAvailable: privateAIAvailable) {
+ if let profile = self.resolvedDictationPromptProfile(for: slot, appBundleID: appBundleID, privateAIAvailable: privateAIAvailable) {
let name = profile.name.trimmingCharacters(in: .whitespacesAndNewlines)
return name.isEmpty ? "Untitled" : name
}
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index fcea0e49..5530b049 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -2228,12 +2228,12 @@ final class ASRService: ObservableObject {
return AudioCapturePipeline(
audioBuffer: self.audioBuffer,
onFirstAudio: { sessionID, attemptID, sampleCount, frameLength, sampleRate, acquisitionMs, elapsedMs in
- Task {
- readinessGate.signalFirstPCM(
- sessionID: sessionID,
- attemptID: attemptID
- )
- }
+ // This gate is lock-protected. Signal from the capture worker;
+ // a Task created here inherits MainActor and can wait behind UI work.
+ readinessGate.signalFirstPCM(
+ sessionID: sessionID,
+ attemptID: attemptID
+ )
DispatchQueue.main.async {
let bufferMs = Int((Double(frameLength) / sampleRate * 1000).rounded())
DebugLogger.shared.benchmark(
diff --git a/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
index 6775456c..17bcbe6d 100644
--- a/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
+++ b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
@@ -490,7 +490,8 @@ final class AutomaticDictionaryTrainingSession: ObservableObject {
)
}
guard mergedEntries != currentEntries else {
- self.completeSave(title: "Already in Dictionary")
+ self.hasError = true
+ self.statusMessage = "These spellings are already covered. No new spelling corrections were saved."
return
}
diff --git a/Sources/Fluid/Services/DictationOverlayPresentation.swift b/Sources/Fluid/Services/DictationOverlayPresentation.swift
new file mode 100644
index 00000000..3efdae31
--- /dev/null
+++ b/Sources/Fluid/Services/DictationOverlayPresentation.swift
@@ -0,0 +1,180 @@
+import AppKit
+import Combine
+import Foundation
+
+nonisolated struct DictationOverlayPresentation: Equatable, Sendable {
+ var label: String
+ var builtInLabel: String?
+ var hasAppOverride: Bool
+
+ static let pending = Self(label: "Dictation", builtInLabel: nil, hasAppOverride: false)
+}
+
+nonisolated struct DictationOverlayPresentationInput: Equatable, Sendable {
+ struct Candidate: Equatable, Sendable {
+ var name: String
+ var builtInLabel: String?
+ var hasAppOverride: Bool
+ var usesSelectedPrivateModel: Bool
+ var modelID: String
+
+ func resolve(verifiedModelID: String?, modelName: (String) -> String) -> DictationOverlayPresentation {
+ let modelID = self.usesSelectedPrivateModel ? (verifiedModelID ?? "") : self.modelID
+ let model = modelName(modelID).replacingOccurrences(of: "Fluid-1 ", with: "")
+ return DictationOverlayPresentation(
+ label: model.isEmpty ? "Basic" : "\(self.name) · \(model)",
+ builtInLabel: self.builtInLabel,
+ hasAppOverride: self.hasAppOverride
+ )
+ }
+ }
+
+ struct Choices: Equatable, Sendable {
+ let available: Candidate
+ let unavailable: Candidate
+
+ func resolve(verifiedModelID: String?, modelName: (String) -> String) -> DictationOverlayPresentation {
+ (verifiedModelID == nil ? self.unavailable : self.available)
+ .resolve(verifiedModelID: verifiedModelID, modelName: modelName)
+ }
+ }
+
+ let verification: PrivateAIProviderPromptFormat.VerificationInput
+ let primary: Choices
+ let secondary: Choices
+
+ @MainActor
+ init(settings: SettingsStore, appBundleID: String?) {
+ self.verification = .init(settings: settings)
+ self.primary = Self.choices(settings: settings, slot: .primary, appBundleID: appBundleID)
+ self.secondary = Self.choices(settings: settings, slot: .secondary, appBundleID: appBundleID)
+ }
+
+ @MainActor
+ private static func choices(settings: SettingsStore, slot: SettingsStore.DictationShortcutSlot, appBundleID: String?) -> Choices {
+ Choices(
+ available: self.candidate(settings: settings, slot: slot, appBundleID: appBundleID, available: true),
+ unavailable: self.candidate(settings: settings, slot: slot, appBundleID: appBundleID, available: false)
+ )
+ }
+
+ @MainActor
+ private static func candidate(settings: SettingsStore, slot: SettingsStore.DictationShortcutSlot, appBundleID: String?, available: Bool) -> Candidate {
+ let selection = settings.resolvedDictationPromptSelection(for: slot, appBundleID: appBundleID, privateAIAvailable: available)
+ let appOverride = settings.isAppDictationPromptBindingActive(for: slot, appBundleID: appBundleID, privateAIAvailable: available)
+ let builtInLabel: String?
+ switch selection {
+ case .off: builtInLabel = "Basic"
+ case .privateAI: builtInLabel = appOverride ? nil : SettingsStore.DictationModeLabels.smart
+ case .default:
+ builtInLabel = settings.resolvedDictationPromptProfile(for: slot, appBundleID: appBundleID, privateAIAvailable: available) == nil
+ ? SettingsStore.DictationModeLabels.externalDefault : nil
+ case .profile: builtInLabel = nil
+ }
+ let choice = DictationProviderRoute.modelChoice(settings: settings, selection: selection, appBundleID: appBundleID)
+ let modelID: String
+ if case let .provider(provider, configuredModel) = choice {
+ modelID = DictationProviderRoute.modelID(settings: settings, providerID: provider, configuredModel: configuredModel)
+ } else {
+ modelID = ""
+ }
+ return Candidate(
+ name: settings.dictationPromptDisplayName(for: slot, appBundleID: appBundleID, privateAIAvailable: available),
+ builtInLabel: builtInLabel,
+ hasAppOverride: appOverride,
+ usesSelectedPrivateModel: choice == .privateAI,
+ modelID: modelID
+ )
+ }
+
+ func resolve() -> DictationOverlayPresentations {
+ let verifiedModelID = self.verification.verifiedModelID(recheckInstallation: true)
+ let modelName: (String) -> String = { id in
+ guard !id.isEmpty else { return "" }
+ return PrivateAIModelRegistry.model(id: id)?.displayName ?? id
+ }
+ return DictationOverlayPresentations(
+ primary: self.primary.resolve(verifiedModelID: verifiedModelID, modelName: modelName),
+ secondary: self.secondary.resolve(verifiedModelID: verifiedModelID, modelName: modelName)
+ )
+ }
+}
+
+nonisolated struct DictationOverlayPresentations: Equatable, Sendable {
+ var primary: DictationOverlayPresentation
+ var secondary: DictationOverlayPresentation
+
+ static let pending = Self(primary: .pending, secondary: .pending)
+}
+
+/// One worker and one pending snapshot, regardless of how many settings events arrive.
+/// Rendering reads strings only; it cannot trigger model, disk, or Keychain queries.
+@MainActor
+final class DictationOverlayPresentationStore: ObservableObject {
+ static let shared = DictationOverlayPresentationStore()
+ @Published private(set) var value = DictationOverlayPresentations.pending
+ private var subscriptions = Set<AnyCancellable>()
+ private var refreshQueued = false
+ private var forceRefreshQueued = false
+ private var revision: UInt64 = 0
+ private var requestedInput: DictationOverlayPresentationInput?
+ private var worker: Task<Void, Never>?
+ private let resolve: @Sendable (DictationOverlayPresentationInput) async -> DictationOverlayPresentations
+
+ init(resolve: @escaping @Sendable (DictationOverlayPresentationInput) async -> DictationOverlayPresentations = { $0.resolve() }) {
+ self.resolve = resolve
+ }
+
+ func start() {
+ guard self.subscriptions.isEmpty else { return }
+ SettingsStore.shared.objectWillChange
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] in self?.scheduleRefresh() }
+ .store(in: &self.subscriptions)
+ NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] _ in self?.scheduleRefresh() }
+ .store(in: &self.subscriptions)
+ for name in [PrivateAIIntegrationService.installedModelsDidChangeNotification, NSApplication.didBecomeActiveNotification] {
+ NotificationCenter.default.publisher(for: name)
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] _ in self?.scheduleRefresh(force: true) }
+ .store(in: &self.subscriptions)
+ }
+ self.scheduleRefresh(force: true)
+ }
+
+ private func scheduleRefresh(force: Bool = false) {
+ self.forceRefreshQueued = self.forceRefreshQueued || force
+ guard !self.refreshQueued else { return }
+ self.refreshQueued = true
+ // Read after objectWillChange's originating setter finishes.
+ DispatchQueue.main.async { [weak self] in
+ guard let self else { return }
+ self.refreshQueued = false
+ let force = self.forceRefreshQueued
+ self.forceRefreshQueued = false
+ self.update(.init(settings: .shared, appBundleID: DictationAppSession.shared.appID), force: force)
+ }
+ }
+
+ func update(_ input: DictationOverlayPresentationInput, force: Bool = false) {
+ guard force || input != self.requestedInput else { return }
+ self.requestedInput = input
+ self.revision &+= 1
+ guard self.worker == nil else { return }
+ self.worker = Task { [weak self] in
+ guard let self else { return }
+ while let input = self.requestedInput {
+ let revision = self.revision
+ let resolve = self.resolve
+ let result = await Task.detached(priority: .utility) { await resolve(input) }.value
+ // Model removal, a prompt edit, or a new target app supersedes this result.
+ guard revision == self.revision else { continue }
+ if self.value != result { self.value = result }
+ break
+ }
+ self.worker = nil
+ }
+ }
+}
diff --git a/Sources/Fluid/Services/DictationPostProcessingService.swift b/Sources/Fluid/Services/DictationPostProcessingService.swift
index 32eace99..f5c3329d 100644
--- a/Sources/Fluid/Services/DictationPostProcessingService.swift
+++ b/Sources/Fluid/Services/DictationPostProcessingService.swift
@@ -18,46 +18,82 @@ struct DictationProviderRoute: Equatable {
dictationSlot: SettingsStore.DictationShortcutSlot? = nil,
appBundleID: String? = nil
) -> Self {
- let selectedProviderID: String
- let configuredModel: String?
-
- if let dictationSlot {
- let selection = settings.resolvedDictationPromptSelection(for: dictationSlot, appBundleID: appBundleID)
- if selection == .off {
- return Self(providerID: "", providerKey: "", baseURL: "", model: "", apiKey: "")
- }
- if selection == .privateAI {
- return self.privateAIRoute(settings: settings)
- }
-
- let configuration = settings.dictationPromptConfiguration(for: selection)
- let providerID = configuration.providerID.trimmingCharacters(in: .whitespacesAndNewlines)
- let model = configuration.modelName.trimmingCharacters(in: .whitespacesAndNewlines)
- if !providerID.isEmpty, !model.isEmpty {
- selectedProviderID = providerID
- configuredModel = model
- } else {
- let hasAppBinding = settings.appPromptBinding(for: .dictate, appBundleID: appBundleID) != nil
- if selection == .default, !hasAppBinding, self.shouldUseLegacyPrivateAIRoute(
- selectedProviderID: settings.selectedProviderID,
- configuredProviderID: providerID,
- configuredModel: model
- ) {
- return self.privateAIRoute(settings: settings)
- }
- selectedProviderID = self.externalFallbackProviderID(from: settings.selectedProviderID)
- configuredModel = nil
- }
- } else {
- selectedProviderID = settings.selectedProviderID
- configuredModel = nil
+ guard let dictationSlot else {
+ return self.build(settings: settings, selectedProviderID: settings.selectedProviderID, configuredModel: nil)
}
+ let selection = settings.resolvedDictationPromptSelection(for: dictationSlot, appBundleID: appBundleID)
+ switch self.modelChoice(settings: settings, selection: selection, appBundleID: appBundleID) {
+ case .none:
+ return Self(providerID: "", providerKey: "", baseURL: "", model: "", apiKey: "")
+ case .privateAI:
+ return self.privateAIRoute(settings: settings)
+ case let .provider(providerID, model):
+ return self.build(settings: settings, selectedProviderID: providerID, configuredModel: model)
+ }
+ }
- return self.build(settings: settings, selectedProviderID: selectedProviderID, configuredModel: configuredModel)
+ /// Model routing without credentials or private-model installation checks.
+ /// The overlay can snapshot this on main and resolve its display name off main.
+ enum ModelChoice: Equatable, Sendable {
+ case none
+ case privateAI
+ case provider(String, String?)
}
- private static func build(settings: SettingsStore, selectedProviderID: String, configuredModel: String?) -> Self {
+ /// Capture only the intended route here. Installation verification belongs
+ /// on the warmup worker, never in the microphone's started callback.
+ static func privateAIWarmupVerification(
+ settings: SettingsStore,
+ slot: SettingsStore.DictationShortcutSlot,
+ appBundleID: String?
+ ) -> PrivateAIProviderPromptFormat.VerificationInput? {
+ let selection = settings.resolvedDictationPromptSelection(for: slot, appBundleID: appBundleID, privateAIAvailable: true)
+ switch self.modelChoice(settings: settings, selection: selection, appBundleID: appBundleID) {
+ case .none: return nil
+ case .privateAI: break
+ case let .provider(providerID, _):
+ let privateID = PrivateAIProviderFeature.shared.providerID
+ guard providerID == privateID || providerID == "custom:\(privateID)" else { return nil }
+ }
+ return .init(settings: settings)
+ }
+
+ static func modelChoice(
+ settings: SettingsStore,
+ selection: SettingsStore.DictationPromptSelection,
+ appBundleID: String?
+ ) -> ModelChoice {
+ if selection == .off { return .none }
+ if selection == .privateAI { return .privateAI }
+ let configuration = settings.dictationPromptConfiguration(for: selection)
+ let providerID = configuration.providerID.trimmingCharacters(in: .whitespacesAndNewlines)
+ let model = configuration.modelName.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !providerID.isEmpty, !model.isEmpty { return .provider(providerID, model) }
+ let hasAppBinding = settings.appPromptBinding(for: .dictate, appBundleID: appBundleID) != nil
+ if selection == .default, !hasAppBinding, self.shouldUseLegacyPrivateAIRoute(
+ selectedProviderID: settings.selectedProviderID,
+ configuredProviderID: providerID,
+ configuredModel: model
+ ) {
+ return .privateAI
+ }
+ return .provider(self.externalFallbackProviderID(from: settings.selectedProviderID), nil)
+ }
+
+ static func modelID(settings: SettingsStore, providerID: String, configuredModel: String?) -> String {
+ if let configuredModel { return configuredModel }
let selectedModels = settings.selectedModelByProvider
+ if let saved = settings.savedProviders.first(where: { $0.id == providerID }) {
+ return selectedModels["custom:\(saved.id)"] ?? saved.models.first ?? ""
+ }
+ if ModelRepository.shared.isBuiltIn(providerID) {
+ return selectedModels[providerID] ?? ModelRepository.shared.defaultModels(for: providerID).first ?? ""
+ }
+ return selectedModels[providerID] ?? ""
+ }
+
+ private static func build(settings: SettingsStore, selectedProviderID: String, configuredModel: String?) -> Self {
+ let model = self.modelID(settings: settings, providerID: selectedProviderID, configuredModel: configuredModel)
let providerKeys = settings.providerAPIKeys
if let saved = settings.savedProviders.first(where: { $0.id == selectedProviderID }) {
@@ -66,7 +102,7 @@ struct DictationProviderRoute: Equatable {
providerID: selectedProviderID,
providerKey: key,
baseURL: saved.baseURL,
- model: configuredModel ?? selectedModels[key] ?? saved.models.first ?? "",
+ model: model,
apiKey: providerKeys[key] ?? providerKeys[selectedProviderID] ?? ""
)
}
@@ -76,7 +112,7 @@ struct DictationProviderRoute: Equatable {
providerID: selectedProviderID,
providerKey: selectedProviderID,
baseURL: ModelRepository.shared.defaultBaseURL(for: selectedProviderID),
- model: configuredModel ?? selectedModels[selectedProviderID] ?? ModelRepository.shared.defaultModels(for: selectedProviderID).first ?? "",
+ model: model,
apiKey: providerKeys[selectedProviderID] ?? ""
)
}
@@ -85,7 +121,7 @@ struct DictationProviderRoute: Equatable {
providerID: selectedProviderID,
providerKey: selectedProviderID,
baseURL: "",
- model: configuredModel ?? selectedModels[selectedProviderID] ?? "",
+ model: model,
apiKey: providerKeys[selectedProviderID] ?? ""
)
}
diff --git a/Sources/Fluid/Services/DictionaryExperimentalMatcher.swift b/Sources/Fluid/Services/DictionaryExperimentalMatcher.swift
index 298887f0..c5292064 100644
--- a/Sources/Fluid/Services/DictionaryExperimentalMatcher.swift
+++ b/Sources/Fluid/Services/DictionaryExperimentalMatcher.swift
@@ -1,9 +1,13 @@
import Accelerate
import Foundation
-/// Master pronunciation switch. Off disables all audio matching and enrollment.
+/// Pronunciation is on by default; a saved Off choice disables matching and enrollment.
nonisolated enum DictionaryMatcherExperiment {
- static var sharedFeaturesEnabled: Bool { UserDefaults.standard.bool(forKey: "DictionarySharedFeatureMatcherEnabled") }
+ static let defaultEnabled = true
+ static var sharedFeaturesEnabled: Bool {
+ UserDefaults.standard.object(forKey: "DictionarySharedFeatureMatcherEnabled") as? Bool ?? self.defaultEnabled
+ }
+
static let didChangeNotification = Notification.Name("DictionaryPronunciationDidChange")
static var generation: String { UserDefaults.standard.string(forKey: "DictionaryPronunciationGeneration") ?? "initial" }
static func setEnabled(_ enabled: Bool) {
diff --git a/Sources/Fluid/Services/DictionaryPronunciationExperiment.swift b/Sources/Fluid/Services/DictionaryPronunciationExperiment.swift
index 39310c79..225d335c 100644
--- a/Sources/Fluid/Services/DictionaryPronunciationExperiment.swift
+++ b/Sources/Fluid/Services/DictionaryPronunciationExperiment.swift
@@ -1,6 +1,6 @@
import Foundation
-/// Local opt-in. Both switches default off in a fresh installation.
+/// Pronunciation follows the master switch; diagnostic audio capture remains opt-in.
nonisolated enum DictionaryPronunciationExperiment {
static var enabled: Bool { DictionaryMatcherExperiment.sharedFeaturesEnabled }
static var captureEnabled: Bool { enabled && UserDefaults.standard.bool(forKey: "DictionaryPronunciationDebugCapture") }
diff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swift
index b5cbe80a..806ce290 100644
--- a/Sources/Fluid/Services/FluidAudioProvider.swift
+++ b/Sources/Fluid/Services/FluidAudioProvider.swift
@@ -257,6 +257,7 @@ final class FluidAudioProvider: TranscriptionProvider {
private var incrementalAcceptedSampleCount = 0
private var recordingGeneration = UUID()
private var incrementalPronunciationProfiles: [PronunciationDictionaryProfile] = []
+ private var hasEligibleExplicitPronunciationProfiles = false
private var automaticPronunciationProfiles: [PronunciationDictionaryProfile] = []
private var didLoadAutomaticPronunciationProfiles = false
@@ -357,19 +358,22 @@ final class FluidAudioProvider: TranscriptionProvider {
}
private var effectivePronunciationMatchingEnabled: Bool {
- DictionaryMatcherExperiment.sharedFeaturesEnabled && (self.explicitPronunciationMatchingEnabled
+ DictionaryMatcherExperiment.sharedFeaturesEnabled && ((self.explicitPronunciationMatchingEnabled && self.hasEligibleExplicitPronunciationProfiles)
|| (self.automaticPronunciationMatchingEnabled && !self.automaticPronunciationProfiles.isEmpty))
}
/// Read the actor-owned store once after capture begins, never on the microphone startup path.
private func refreshAutomaticPronunciationProfiles(warmReferences: Bool = true) async throws {
guard DictionaryMatcherExperiment.sharedFeaturesEnabled else {
+ self.hasEligibleExplicitPronunciationProfiles = false
self.automaticPronunciationProfiles = []
+ self.didLoadAutomaticPronunciationProfiles = false
return
}
guard !self.didLoadAutomaticPronunciationProfiles else { return }
let generation = self.recordingGeneration
guard self.meetingOptions == nil, self.enhancementOptions == nil || self.explicitPronunciationMatchingEnabled, !self.effectiveCustomDictionaryEntries.isEmpty else {
+ self.hasEligibleExplicitPronunciationProfiles = false
self.automaticPronunciationProfiles = []
self.didLoadAutomaticPronunciationProfiles = true
return
@@ -384,6 +388,8 @@ final class FluidAudioProvider: TranscriptionProvider {
)
self.didLoadAutomaticPronunciationProfiles = true
let activeProfiles = Self.matchingProfiles(stored, entries: self.effectiveCustomDictionaryEntries, includeManual: self.explicitPronunciationMatchingEnabled)
+ // The switch allows matching; only eligible saved words should change dictation routing.
+ self.hasEligibleExplicitPronunciationProfiles = self.explicitPronunciationMatchingEnabled && !activeProfiles.isEmpty
let activeKeys = Set(activeProfiles.map(DictionaryNegativeEvidenceResolver.profileKey))
self.temporalReferenceCache.retain(keys: activeKeys)
let inspectionIDs = Set(activeProfiles.flatMap(\.enrollments).compactMap(\.inspectionID))
@@ -419,6 +425,12 @@ final class FluidAudioProvider: TranscriptionProvider {
self.isWordBoostingActive = active
}
+ func refreshPronunciationRoutingForTesting(modelKey: String) async throws -> Bool {
+ self.pronunciationModelKey = modelKey
+ try await self.refreshAutomaticPronunciationProfiles(warmReferences: false)
+ return self.usesIncrementalDictation
+ }
+
/// Read-only snapshot of the actual effective enhancement getters for baseline tests.
var effectiveEnhancementOptionsForTesting: FluidAudioProviderEnhancementOptions {
FluidAudioProviderEnhancementOptions(
@@ -632,6 +644,7 @@ final class FluidAudioProvider: TranscriptionProvider {
self.latestStreamingPreviewSampleCount = 0
self.latestStreamingPreviewFinishedAt = nil
self.recordingGeneration = UUID()
+ self.hasEligibleExplicitPronunciationProfiles = false
self.automaticPronunciationProfiles = []
self.didLoadAutomaticPronunciationProfiles = false
self.resetIncrementalSession()
@@ -654,6 +667,7 @@ final class FluidAudioProvider: TranscriptionProvider {
self.latestStreamingPreviewSampleCount = 0
self.latestStreamingPreviewFinishedAt = nil
self.recordingGeneration = UUID()
+ self.hasEligibleExplicitPronunciationProfiles = false
self.automaticPronunciationProfiles = []
self.didLoadAutomaticPronunciationProfiles = false
self.resetIncrementalSession()
@@ -1207,13 +1221,14 @@ final class FluidAudioProvider: TranscriptionProvider {
private func transcribeFinalResult(
_ samples: [Float], manager: AsrManager
) async throws -> (result: ASRTranscriptionResult, tokenTimings: [TokenTiming]?, textMayBeCorrected: Bool) { // swiftlint:disable:this discouraged_optional_collection
- if self.effectivePronunciationMatchingEnabled, samples.count > Self.incrementalChunkingThresholdSamples {
+ let generation = self.recordingGeneration
+ let profiles = self.effectivePronunciationMatchingEnabled ? Self.preparedEdgeProfiles(await self.pronunciationProfiles(), cache: self.edgeReferenceCache) : []
+ try self.requireCurrentRecording(generation)
+ if !profiles.isEmpty, samples.count > Self.incrementalChunkingThresholdSamples {
self.resetIncrementalSession()
try await self.startIncrementalSession(manager: manager)
return try (await self.transcribeIncrementalFinal(samples), nil, true)
}
- let matchingEnabled = self.effectivePronunciationMatchingEnabled && samples.count <= 16_000 * 15
- let profiles = matchingEnabled ? Self.preparedEdgeProfiles(await self.pronunciationProfiles(), cache: self.edgeReferenceCache) : []
// Rewritten text leaves timings on the old tokens; realigning would revert corrections.
let textMayBeCorrected = self.isWordBoostingActive || !profiles.isEmpty
await manager.setPronunciationCustomizationEnabled(!profiles.isEmpty)
diff --git a/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift b/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift
index dd608541..ff6dc052 100644
--- a/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift
@@ -651,8 +651,36 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
@MainActor
final class CoreAudioProcessActivityProvider: AudioProcessActivityProviding {
+ // LaunchServices may block while reading NSRunningApplication properties.
+ // Keep it away from both MainActor and the audio topology control queue.
+ private nonisolated static let ownerQueue = DispatchQueue(label: "com.fluidvoice.meeting-process-owners", qos: .utility)
+ private let readOwners: @Sendable () -> [MeetingProcessOwner]
+ private let readActivity: @Sendable ([MeetingProcessOwner]) -> AudioProcessActivitySnapshot
+
+ init(
+ readOwners: @escaping @Sendable () -> [MeetingProcessOwner] = CoreAudioProcessActivityProvider.runningOwners,
+ readActivity: @escaping @Sendable ([MeetingProcessOwner]) -> AudioProcessActivitySnapshot = CoreAudioProcessActivityProvider.readAudioActivity
+ ) {
+ self.readOwners = readOwners
+ self.readActivity = readActivity
+ }
+
func snapshot() async -> AudioProcessActivitySnapshot {
- let owners = NSWorkspace.shared.runningApplications.compactMap { app -> MeetingProcessOwner? in
+ let readOwners = self.readOwners
+ let owners = await withCheckedContinuation { continuation in
+ Self.ownerQueue.async { continuation.resume(returning: readOwners()) }
+ }
+ guard !Task.isCancelled else {
+ return AudioProcessActivitySnapshot(processes: [], owners: [], queryState: .unknown)
+ }
+ let readActivity = self.readActivity
+ return await AudioTopologyListenerExecution.perform { readActivity(owners) }
+ }
+
+ private nonisolated static func runningOwners() -> [MeetingProcessOwner] {
+ // AppKit documents runningApplications and these properties as thread safe.
+ // The returned value contains no NSRunningApplication instances.
+ NSWorkspace.shared.runningApplications.compactMap { app -> MeetingProcessOwner? in
// Browsers are listed too: their microphone tells when a web meeting is over.
guard let bundle = app.bundleIdentifier,
MeetingAppRegistry.tier(forBundleIdentifier: bundle) != nil,
@@ -660,36 +688,37 @@ final class CoreAudioProcessActivityProvider: AudioProcessActivityProviding {
let path = app.bundleURL?.path else { return nil }
return MeetingProcessOwner(processID: app.processIdentifier, bundleIdentifier: bundle, bundlePath: path)
}
- return await AudioTopologyListenerExecution.perform {
- guard #available(macOS 14.4, *) else {
- return AudioProcessActivitySnapshot(processes: [], owners: [], queryState: .unknown)
- }
- guard let processIDs = Self.processObjectIDs() else {
- return AudioProcessActivitySnapshot(processes: [], owners: owners, queryState: .unknown)
- }
- var queryFailed = false
- let processes = processIDs.compactMap { processObjectID -> AudioProcessDescriptor? in
- guard let input = Self.isRunning(processObjectID, selector: kAudioProcessPropertyIsRunningInput),
- let output = Self.isRunning(processObjectID, selector: kAudioProcessPropertyIsRunningOutput)
- else { queryFailed = true; return nil }
- guard input || output else { return nil }
- guard let pid = Self.processID(for: processObjectID), pid > 0,
- let path = Self.executablePath(for: pid),
- Self.processID(for: processObjectID) == pid
- else { queryFailed = true; return nil }
- return AudioProcessDescriptor(
- processID: pid,
- bundleIdentifier: Self.bundleIdentifier(for: processObjectID),
- executablePath: path,
- isInputRunning: input,
- isOutputRunning: output
- )
- }
- // Missing executable identity is not equivalent to silence. Keep the whole sample
- // unknown so the detector preserves continuity without inventing an inactive edge.
- let state: AudioProcessActivitySnapshot.QueryState = queryFailed ? .unknown : .valid
- return AudioProcessActivitySnapshot(processes: processes, owners: owners, queryState: state)
+ }
+
+ private nonisolated static func readAudioActivity(owners: [MeetingProcessOwner]) -> AudioProcessActivitySnapshot {
+ guard #available(macOS 14.4, *) else {
+ return AudioProcessActivitySnapshot(processes: [], owners: [], queryState: .unknown)
+ }
+ guard let processIDs = processObjectIDs() else {
+ return AudioProcessActivitySnapshot(processes: [], owners: owners, queryState: .unknown)
+ }
+ var queryFailed = false
+ let processes = processIDs.compactMap { processObjectID -> AudioProcessDescriptor? in
+ guard let input = Self.isRunning(processObjectID, selector: kAudioProcessPropertyIsRunningInput),
+ let output = Self.isRunning(processObjectID, selector: kAudioProcessPropertyIsRunningOutput)
+ else { queryFailed = true; return nil }
+ guard input || output else { return nil }
+ guard let pid = Self.processID(for: processObjectID), pid > 0,
+ let path = Self.executablePath(for: pid),
+ Self.processID(for: processObjectID) == pid
+ else { queryFailed = true; return nil }
+ return AudioProcessDescriptor(
+ processID: pid,
+ bundleIdentifier: Self.bundleIdentifier(for: processObjectID),
+ executablePath: path,
+ isInputRunning: input,
+ isOutputRunning: output
+ )
}
+ // Missing executable identity is not equivalent to silence. Keep the whole sample
+ // unknown so the detector preserves continuity without inventing an inactive edge.
+ let state: AudioProcessActivitySnapshot.QueryState = queryFailed ? .unknown : .valid
+ return AudioProcessActivitySnapshot(processes: processes, owners: owners, queryState: state)
}
private nonisolated static func processID(for objectID: AudioObjectID) -> Int32? {
diff --git a/Sources/Fluid/Services/Meeting/MeetingSummaryController.swift b/Sources/Fluid/Services/Meeting/MeetingSummaryController.swift
index 353a0abb..138249ea 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSummaryController.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSummaryController.swift
@@ -144,6 +144,7 @@ final class MeetingSummaryController: ObservableObject {
@Published private(set) var progress: PrivateAIModelDownloadProgress?
@Published private(set) var output = ""
@Published private(set) var outputProvenance = ""
+ @Published private(set) var outputNotice = ""
@Published private(set) var error: String?
private var operation: Task<Void, Never>?
private var generation = UUID()
@@ -173,6 +174,12 @@ final class MeetingSummaryController: ObservableObject {
"\(self.providerName ?? "Fluid Intelligence") · \(self.modelName ?? self.modelID)"
}
+ var notice: String {
+ self.providerID == MeetingSummaryOnDevice.providerID
+ ? "Generated by AI on your Mac. May contain mistakes."
+ : "Generated by AI. May contain mistakes."
+ }
+
/// Summaries saved before providers were recorded came from the earlier on-device
/// model, which was withdrawn for accuracy; they stay hidden.
func isCurrent(transcriptHash: String, promptHash: String?) -> Bool {
@@ -186,6 +193,7 @@ final class MeetingSummaryController: ObservableObject {
self.generation = generation
self.output = ""
self.outputProvenance = ""
+ self.outputNotice = ""
self.error = nil
self.checking = true
let model = self.model
@@ -207,6 +215,7 @@ final class MeetingSummaryController: ObservableObject {
self.installed = snapshot.0
self.output = snapshot.1?.text ?? ""
self.outputProvenance = snapshot.1?.provenance ?? ""
+ self.outputNotice = snapshot.1?.notice ?? ""
self.checking = false
}
@@ -304,6 +313,7 @@ final class MeetingSummaryController: ObservableObject {
}.value
self.output = text
self.outputProvenance = saved.provenance
+ self.outputNotice = saved.notice
}
} catch is CancellationError {
self.error = nil
@@ -377,6 +387,7 @@ final class MeetingSummaryController: ObservableObject {
}.value
self.output = text
self.outputProvenance = saved.provenance
+ self.outputNotice = saved.notice
}
} catch is CancellationError {
self.error = nil
diff --git a/Sources/Fluid/Services/PrivateAIIntegrationService.swift b/Sources/Fluid/Services/PrivateAIIntegrationService.swift
index 43164a1e..895e907f 100644
--- a/Sources/Fluid/Services/PrivateAIIntegrationService.swift
+++ b/Sources/Fluid/Services/PrivateAIIntegrationService.swift
@@ -126,7 +126,10 @@ actor PrivateAIIntegrationService {
private nonisolated(unsafe) static var installedModelCache: [String: (installed: Bool, checkedAt: TimeInterval)] = [:]
private nonisolated static let installedModelCacheLifetime: TimeInterval = 2
- nonisolated static func isModelInstalled(_ model: PrivateAIRegisteredModel) -> Bool {
+ nonisolated static func isModelInstalled(_ model: PrivateAIRegisteredModel, useCache: Bool = true) -> Bool {
+ // Event-driven presentation refreshes must see removals even when an
+ // older, concurrent check populated the short-lived runtime cache.
+ if !useCache { return self.provider.isModelInstalled(model) }
let now = ProcessInfo.processInfo.systemUptime
self.installedModelCacheLock.lock()
let cached = self.installedModelCache[model.id]
@@ -142,10 +145,13 @@ actor PrivateAIIntegrationService {
return installed
}
+ nonisolated static let installedModelsDidChangeNotification = Notification.Name("PrivateAIInstalledModelsDidChange")
+
nonisolated static func invalidateInstalledModelCache() {
self.installedModelCacheLock.lock()
self.installedModelCache.removeAll()
self.installedModelCacheLock.unlock()
+ NotificationCenter.default.post(name: self.installedModelsDidChangeNotification, object: nil)
}
nonisolated static func canRemoveInstalledModel(_ model: PrivateAIRegisteredModel) -> Bool {
@@ -252,12 +258,14 @@ actor PrivateAIIntegrationService {
@MainActor private static var updateAdmissions: [UUID: UUID] = [:]
nonisolated static func commitModelUpdate(_ token: PrivateAIModelUpdateToken) async {
+ defer { self.invalidateInstalledModelCache() }
guard let admission = await MainActor.run(body: { Self.updateAdmissions.removeValue(forKey: token.id) }) else { return }
await self.provider.commitModelUpdate(token)
await MeetingModelResidencyCoordinator.shared.endOperation(admission)
}
nonisolated static func rollbackModelUpdate(_ token: PrivateAIModelUpdateToken) async {
+ defer { self.invalidateInstalledModelCache() }
guard let admission = await MainActor.run(body: { Self.updateAdmissions.removeValue(forKey: token.id) }) else { return }
await self.provider.rollbackModelUpdate(token)
await MeetingModelResidencyCoordinator.shared.endOperation(admission)
diff --git a/Sources/Fluid/Services/PrivateAIProvider.swift b/Sources/Fluid/Services/PrivateAIProvider.swift
index 53a07215..61d0e3c0 100644
--- a/Sources/Fluid/Services/PrivateAIProvider.swift
+++ b/Sources/Fluid/Services/PrivateAIProvider.swift
@@ -400,9 +400,14 @@ enum PrivateAIProviderFeature {
}
nonisolated static func verificationFingerprint(for modelID: String) -> String {
- let backendPreference = UserDefaults.standard.string(forKey: SettingsStore.privateAIBackendPreferenceDefaultsKey)?
- .trimmingCharacters(in: .whitespacesAndNewlines)
- .lowercased()
+ self.verificationFingerprint(
+ for: modelID,
+ backendPreference: UserDefaults.standard.string(forKey: SettingsStore.privateAIBackendPreferenceDefaultsKey)
+ )
+ }
+
+ nonisolated static func verificationFingerprint(for modelID: String, backendPreference: String?) -> String {
+ let backendPreference = backendPreference?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let normalizedBackendPreference: String
if let backendPreference,
!backendPreference.isEmpty,
diff --git a/Sources/Fluid/Services/PrivateAIProviderPromptFormat.swift b/Sources/Fluid/Services/PrivateAIProviderPromptFormat.swift
index 3cc7a962..d83200f1 100644
--- a/Sources/Fluid/Services/PrivateAIProviderPromptFormat.swift
+++ b/Sources/Fluid/Services/PrivateAIProviderPromptFormat.swift
@@ -9,31 +9,53 @@ enum PrivateAIProviderPromptFormat {
self.verifiedModelID(settings: settings) != nil
}
+ /// Immutable settings only. Resolving this may query the model directory, so
+ /// presentation callers resolve it on a worker, never while drawing a view.
+ nonisolated struct VerificationInput: Equatable, Sendable {
+ let providerAvailable: Bool
+ let selectedModelID: String?
+ let providerFingerprint: String?
+ let modelFingerprints: [String: String]
+ let backendPreference: String?
+ let configuredModelSelection: String?
+ let configuredLocalModelPath: String?
+
+ @MainActor
+ init(settings: SettingsStore) {
+ let key = PrivateAIProviderPromptFormat.providerKey(for: PrivateAIProviderFeature.shared.providerID)
+ self.providerAvailable = PrivateAIProviderFeature.shared.isAvailable
+ self.selectedModelID = settings.selectedModelByProvider[key]
+ self.providerFingerprint = settings.verifiedProviderFingerprints[key]
+ self.modelFingerprints = settings.verifiedPrivateAIModelFingerprints
+ self.backendPreference = UserDefaults.standard.string(forKey: SettingsStore.privateAIBackendPreferenceDefaultsKey)
+ self.configuredModelSelection = UserDefaults.standard.string(forKey: PrivateAIProviderFeature.shared.selectedModelDefaultsKey)
+ self.configuredLocalModelPath = UserDefaults.standard.string(forKey: PrivateAIProviderFeature.shared.localModelPathDefaultsKey)
+ }
+
+ func verifiedModelID(recheckInstallation: Bool = false) -> String? {
+ let configured = PrivateAIIntegrationService.configuredModelID
+ let modelID = PrivateAIModelRegistry.canonicalModelID(for: self.selectedModelID ?? configured) ?? configured
+ return self.verifiedModelID(for: modelID, recheckInstallation: recheckInstallation)
+ }
+
+ func verifiedModelID(for selectedModelID: String, recheckInstallation: Bool = false) -> String? {
+ guard self.providerAvailable else { return nil }
+ let modelID = PrivateAIModelRegistry.canonicalModelID(for: selectedModelID) ?? selectedModelID
+ let fingerprint = PrivateAIProviderFeature.verificationFingerprint(for: modelID, backendPreference: self.backendPreference)
+ guard let model = PrivateAIModelRegistry.model(id: modelID),
+ PrivateAIIntegrationService.isModelInstalled(model, useCache: !recheckInstallation),
+ self.modelFingerprints[modelID] == fingerprint || self.providerFingerprint == fingerprint
+ else { return nil }
+ return modelID
+ }
+ }
+
static func verifiedModelID(settings: SettingsStore = .shared) -> String? {
- let key = self.providerKey(for: PrivateAIProviderFeature.shared.providerID)
- let configuredModelID = PrivateAIIntegrationService.configuredModelID
- let modelID = PrivateAIModelRegistry.canonicalModelID(for: settings.selectedModelByProvider[key] ?? configuredModelID) ?? configuredModelID
- return self.verifiedModelID(for: modelID, settings: settings)
+ VerificationInput(settings: settings).verifiedModelID()
}
static func verifiedModelID(for selectedModelID: String, settings: SettingsStore = .shared) -> String? {
- guard PrivateFeatures.privateAIProvider else { return nil }
- let key = self.providerKey(for: PrivateAIProviderFeature.shared.providerID)
- let modelID = PrivateAIModelRegistry.canonicalModelID(for: selectedModelID) ?? selectedModelID
- let expectedFingerprint = PrivateAIProviderFeature.verificationFingerprint(for: modelID)
- guard let model = PrivateAIModelRegistry.model(id: modelID),
- PrivateAIIntegrationService.isModelInstalled(model),
- self.hasStoredVerification(
- for: modelID,
- providerKey: key,
- expectedFingerprint: expectedFingerprint,
- settings: settings
- )
- else {
- return nil
- }
-
- return modelID
+ VerificationInput(settings: settings).verifiedModelID(for: selectedModelID)
}
static func hasStoredVerification(
diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swift
index 48f869b6..323f9de8 100644
--- a/Sources/Fluid/UI/CustomDictionaryView.swift
+++ b/Sources/Fluid/UI/CustomDictionaryView.swift
@@ -53,7 +53,7 @@ struct CustomDictionaryView: View {
@State private var trainingSaveID: UUID?
@State private var trainingVariants: [String] = []
@State private var manualTrainingSpellings = Set<String>()
- @AppStorage("DictionarySharedFeatureMatcherEnabled") private var pronunciationEnabled = false
+ @AppStorage("DictionarySharedFeatureMatcherEnabled") private var pronunciationEnabled = DictionaryMatcherExperiment.defaultEnabled
@State private var pronunciationMatchingEnabled = SettingsStore.shared.pronunciationMatchingEnabled
@State private var trainingPronunciationEnrollments: [PronunciationEnrollmentCapture] = []
@State private var trainingSampleCount = 0
@@ -560,7 +560,7 @@ struct CustomDictionaryView: View {
}
}
}
- Text("\(self.entries.count) saved words")
+ Text(self.wordSearch.isEmpty ? "\(self.entries.count) saved words" : "\(self.drawerEntries.count) of \(self.entries.count) words")
.font(self.theme.typography.caption)
.foregroundStyle(self.theme.palette.secondaryText)
}
@@ -651,13 +651,7 @@ struct CustomDictionaryView: View {
Task { await self.startAutomaticTrainingIfIdle() }
},
onSave: {
- if self.trainingAlreadyCorrectWithoutReplacement {
- self.wizardSavedWord = self.normalizedTrainingReplacement
- self.resetTraining()
- self.wizardStep = .saved
- } else {
- Task { await self.addTrainedReplacement() }
- }
+ Task { await self.addTrainedReplacement() }
},
onBack: { self.wizardStep = .spelling },
onNewWord: self.startNewDictionaryWord,
@@ -808,13 +802,13 @@ struct CustomDictionaryView: View {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
ViewThatFits(in: .horizontal) {
HStack(alignment: .top, spacing: self.theme.metrics.spacing.md) {
- self.manualReplacementField
self.manualTriggerField
+ self.manualReplacementField
}
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
- self.manualReplacementField
self.manualTriggerField
+ self.manualReplacementField
}
}
@@ -855,12 +849,12 @@ struct CustomDictionaryView: View {
private var manualTriggerField: some View {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
- Text("What FluidVoice types wrong")
+ Text("Replace")
.font(self.theme.typography.captionStrong)
TextField("fluid voice, fluid boys", text: self.$manualTriggerDraft)
.dictionaryInputChrome()
- .accessibilityLabel("Misheard words")
+ .accessibilityLabel("Text to replace")
.onSubmit { self.addManualReplacementIfValid() }
Text("Separate different versions with commas. Enter only commas to replace comma punctuation.")
@@ -871,12 +865,12 @@ struct CustomDictionaryView: View {
private var manualReplacementField: some View {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
- Text("Correct word")
+ Text("With")
.font(self.theme.typography.captionStrong)
TextField("FluidVoice", text: self.$manualReplacement)
.dictionaryInputChrome()
.focused(self.$manualReplacementFocused)
- .accessibilityLabel("Correct word")
+ .accessibilityLabel("Correct spelling")
.onSubmit { self.addManualReplacementIfValid() }
.task(id: self.manualEntryFocusRequest) {
await Task.yield()
@@ -2518,7 +2512,13 @@ struct CustomDictionaryView: View {
}
private func addTrainedReplacement() async {
- guard self.canAddTrainedReplacement else { return }
+ guard !Task.isCancelled, !self.isTrainingRecording, !self.isTrainingProcessing,
+ self.canAddTrainedReplacement || self.trainingAlreadyCorrectWithoutReplacement else { return }
+ if self.trainingAlreadyCorrectWithoutReplacement {
+ self.trainingHasError = true
+ self.trainingStatusMessage = "FluidVoice already recognises this word. Nothing new was saved."
+ return
+ }
self.isTrainingProcessing = true
let saveID = UUID()
self.trainingSaveID = saveID
@@ -2551,6 +2551,11 @@ struct CustomDictionaryView: View {
triggers: filtered.accepted,
savePronunciation: savePronunciation
)
+ guard savePronunciation || updatedEntries != originalEntries else {
+ self.trainingHasError = true
+ self.trainingStatusMessage = "These spellings are already covered. Nothing new was saved."
+ return
+ }
let entry = updatedEntries.first {
$0.replacement.caseInsensitiveCompare(replacementText) == .orderedSame
}
diff --git a/Sources/Fluid/UI/DictionaryMatcherExperimentSettings.swift b/Sources/Fluid/UI/DictionaryMatcherExperimentSettings.swift
index af6bce91..d6ed176f 100644
--- a/Sources/Fluid/UI/DictionaryMatcherExperimentSettings.swift
+++ b/Sources/Fluid/UI/DictionaryMatcherExperimentSettings.swift
@@ -2,7 +2,7 @@ import SwiftUI
struct DictionaryMatcherExperimentSettings: View {
@Environment(\.theme) private var theme
- @AppStorage("DictionarySharedFeatureMatcherEnabled") private var enabled = false
+ @AppStorage("DictionarySharedFeatureMatcherEnabled") private var enabled = DictionaryMatcherExperiment.defaultEnabled
var body: some View {
HStack {
diff --git a/Sources/Fluid/UI/MeetingSummaryView.swift b/Sources/Fluid/UI/MeetingSummaryView.swift
index 31c2a8d2..3a9bc697 100644
--- a/Sources/Fluid/UI/MeetingSummaryView.swift
+++ b/Sources/Fluid/UI/MeetingSummaryView.swift
@@ -411,6 +411,10 @@ struct MeetingSummaryView: View {
.help("Copy summary")
}
CommandMarkdownContent(text: self.controller.output)
+ Text(self.controller.outputNotice)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
}
.padding(self.theme.metrics.spacing.lg)
.frame(maxWidth: .infinity, alignment: .leading)
diff --git a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
index b8d18085..5a282944 100644
--- a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
+++ b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
@@ -646,7 +646,7 @@ extension Notification.Name {
}
private struct AutomaticDictionaryCorrectionOverlayView: View {
- @AppStorage("DictionarySharedFeatureMatcherEnabled") private var pronunciationEnabled = false
+ @AppStorage("DictionarySharedFeatureMatcherEnabled") private var pronunciationEnabled = DictionaryMatcherExperiment.defaultEnabled
@ObservedObject var session: AutomaticDictionaryTrainingSession
@ObservedObject private var settings = SettingsStore.shared
diff --git a/Sources/Fluid/Views/BottomOverlayView.swift b/Sources/Fluid/Views/BottomOverlayView.swift
index 1593e259..2cd059c8 100644
--- a/Sources/Fluid/Views/BottomOverlayView.swift
+++ b/Sources/Fluid/Views/BottomOverlayView.swift
@@ -2372,6 +2372,7 @@ struct BottomOverlayView: View {
@ObservedObject private var activeAppMonitor = ActiveAppMonitor.shared
@ObservedObject private var historyStore = TranscriptionHistoryStore.shared
@ObservedObject private var settings = SettingsStore.shared
+ @ObservedObject private var promptPresentation = DictationOverlayPresentationStore.shared
@Environment(\.theme) private var theme
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var isHoveringModeChip = false
@@ -2631,33 +2632,22 @@ struct BottomOverlayView: View {
self.contentState.activeDictationShortcutSlot ?? .primary
}
+ private var dictationPresentation: DictationOverlayPresentation {
+ self.activeDictationShortcutSlot == .secondary ? self.promptPresentation.value.secondary : self.promptPresentation.value.primary
+ }
+
private var isAppPromptOverrideActive: Bool {
guard let activePromptMode else { return false }
- if activePromptMode.normalized == .dictate {
- return self.settings.isAppDictationPromptBindingActive(
- for: self.activeDictationShortcutSlot,
- appBundleID: self.promptResolutionBundleID
- )
- }
- return self.settings.hasAppPromptBinding(
- for: activePromptMode,
- appBundleID: self.promptResolutionBundleID
- )
+ if activePromptMode.normalized == .dictate { return self.dictationPresentation.hasAppOverride }
+ return self.settings.hasAppPromptBinding(for: activePromptMode, appBundleID: self.promptResolutionBundleID)
}
private var selectedPromptLabel: String {
guard let activePromptMode else { return "N/A" }
if activePromptMode.normalized == .dictate {
- if let label = self.contentState.stopSnapshotLabel { return label }
- return self.settings.dictationOverlayLabel(
- for: self.activeDictationShortcutSlot,
- appBundleID: self.promptResolutionBundleID
- )
+ return self.contentState.stopSnapshotLabel ?? self.dictationPresentation.label
}
- if let profile = self.settings.resolvedPromptProfile(
- for: activePromptMode,
- appBundleID: self.promptResolutionBundleID
- ) {
+ if let profile = self.settings.resolvedPromptProfile(for: activePromptMode, appBundleID: self.promptResolutionBundleID) {
let name = profile.name.trimmingCharacters(in: .whitespacesAndNewlines)
return name.isEmpty ? "Untitled" : name
}
@@ -2666,27 +2656,8 @@ struct BottomOverlayView: View {
private var promptSelectorBuiltInLabel: String? {
guard let activePromptMode else { return nil }
- if activePromptMode.normalized == .dictate {
- switch self.settings.resolvedDictationPromptSelection(for: self.activeDictationShortcutSlot, appBundleID: self.promptResolutionBundleID) {
- case .off:
- return "Basic"
- case .privateAI:
- return self.isAppPromptOverrideActive ? nil : SettingsStore.DictationModeLabels.smart
- case .default:
- let hasAppOverride = self.settings.resolvedDictationPromptProfile(
- for: self.activeDictationShortcutSlot,
- appBundleID: self.promptResolutionBundleID
- ) != nil
- return hasAppOverride ? nil : SettingsStore.DictationModeLabels.externalDefault
- case .profile:
- return nil
- }
- }
-
- return self.settings.resolvedPromptProfile(
- for: activePromptMode,
- appBundleID: self.promptResolutionBundleID
- ) == nil ? "Default" : nil
+ if activePromptMode.normalized == .dictate { return self.dictationPresentation.builtInLabel }
+ return self.settings.resolvedPromptProfile(for: activePromptMode, appBundleID: self.promptResolutionBundleID) == nil ? "Default" : nil
}
private var promptSelectorDisplayLabel: String {
@@ -3758,6 +3729,7 @@ struct BottomOverlayView: View {
)
// Reserve space around the pill so its drop shadow isn't clipped by the (content-sized) window.
.padding(self.isPillSize ? 26 : 0)
+ .onAppear { self.promptPresentation.start() }
.onChange(of: self.contentState.isBottomOverlayPresented) { _, presented in
self.borderAnimationStartedAt = presented ? Date() : nil
if !presented { self.collapsePillImmediately() }
diff --git a/Sources/Fluid/Views/BottomWaveformView.swift b/Sources/Fluid/Views/BottomWaveformView.swift
index 2d4a5fae..434db75d 100644
--- a/Sources/Fluid/Views/BottomWaveformView.swift
+++ b/Sources/Fluid/Views/BottomWaveformView.swift
@@ -100,8 +100,9 @@ struct BottomWaveformView: View {
/// Drawn at display rate so the bars move on springs instead of stepping with each level tick.
@ViewBuilder
private var barsView: some View {
- // The panel stays alive while hidden; never tick the simulation unless it is on screen.
- if !self.contentState.isBottomOverlayPresented || self.isReleaseAnimationActive || self.contentState.isProcessing {
+ // Waiting bars are static. Starting a 50 Hz Canvas before first PCM
+ // needlessly competes with the capture-start continuation on main.
+ if !self.contentState.isBottomOverlayPresented || self.isWaitingForMicrophone || self.isReleaseAnimationActive || self.contentState.isProcessing {
self.bars(heights: Array(repeating: self.minHeight, count: self.barCount))
} else {
TimelineView(.animation(minimumInterval: 1.0 / 50.0)) { timeline in
diff --git a/Sources/Fluid/Views/NotchContentViews.swift b/Sources/Fluid/Views/NotchContentViews.swift
index 6bae93e5..04499bb7 100644
--- a/Sources/Fluid/Views/NotchContentViews.swift
+++ b/Sources/Fluid/Views/NotchContentViews.swift
@@ -529,6 +529,7 @@ struct NotchExpandedView: View {
let audioPublisher: AnyPublisher<CGFloat, Never>
@ObservedObject private var contentState = NotchContentState.shared
@ObservedObject private var settings = SettingsStore.shared
+ @ObservedObject private var promptPresentation = DictationOverlayPresentationStore.shared
@ObservedObject private var activeAppMonitor = ActiveAppMonitor.shared
@Environment(\.theme) private var theme
@State private var isHoveringPromptChip = false
@@ -631,13 +632,14 @@ struct NotchExpandedView: View {
self.contentState.activeDictationShortcutSlot ?? .primary
}
+ private var dictationPresentation: DictationOverlayPresentation {
+ self.activeDictationShortcutSlot == .secondary ? self.promptPresentation.value.secondary : self.promptPresentation.value.primary
+ }
+
private var isAppPromptOverrideActive: Bool {
guard let activePromptMode else { return false }
if activePromptMode.normalized == .dictate {
- return self.settings.isAppDictationPromptBindingActive(
- for: self.activeDictationShortcutSlot,
- appBundleID: self.promptResolutionBundleID
- )
+ return self.dictationPresentation.hasAppOverride
}
return self.settings.hasAppPromptBinding(
for: activePromptMode,
@@ -648,11 +650,7 @@ struct NotchExpandedView: View {
private var selectedPromptLabel: String {
guard let activePromptMode else { return "N/A" }
if activePromptMode.normalized == .dictate {
- if let label = self.contentState.stopSnapshotLabel { return label }
- return self.settings.dictationOverlayLabel(
- for: self.activeDictationShortcutSlot,
- appBundleID: self.promptResolutionBundleID
- )
+ return self.contentState.stopSnapshotLabel ?? self.dictationPresentation.label
}
if let profile = self.settings.resolvedPromptProfile(
for: activePromptMode,
@@ -1165,6 +1163,7 @@ struct NotchExpandedView: View {
}
}
}
+ .onAppear { self.promptPresentation.start() }
.coordinateSpace(name: Self.notchContentCoordinateSpace)
.frame(width: self.notchContentWidth)
.padding(.horizontal, 6)
diff --git a/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift b/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift
index 3243f584..bbe3dd4e 100644
--- a/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift
+++ b/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift
@@ -9,7 +9,7 @@ import FluidAudio
@MainActor
final class CustomDictionaryManualEntryTests: XCTestCase {
- // Pronunciation features are opt-in in the app; these tests exercise the enabled paths.
+ // Keep these tests independent of a saved pronunciation preference.
private var priorSharedFeaturesFlag: Any?
override func setUp() {
@@ -23,6 +23,51 @@ final class CustomDictionaryManualEntryTests: XCTestCase {
super.tearDown()
}
+ func testPronunciationDefaultsOnWithoutEnablingDiagnosticsAndPreservesOff() {
+ let defaults = UserDefaults.standard
+ let keys = [
+ "DictionarySharedFeatureMatcherEnabled", "DictionaryPronunciationGeneration",
+ "DictionaryPronunciationDebugCapture", "DictionaryNegativeLearningEnabled", "DictionaryNegativeComparisonEnabled",
+ ]
+ let savedPreferences = keys.map { defaults.object(forKey: $0) }
+ defer {
+ for (key, value) in zip(keys, savedPreferences) {
+ defaults.set(value, forKey: key)
+ }
+ }
+ for key in keys {
+ defaults.removeObject(forKey: key)
+ }
+
+ XCTAssertTrue(DictionaryMatcherExperiment.sharedFeaturesEnabled)
+ XCTAssertTrue(DictionaryMatcherExperiment.positiveEnabled)
+ XCTAssertTrue(DictionaryMatcherExperiment.needsFrames)
+ XCTAssertFalse(DictionaryPronunciationExperiment.captureEnabled)
+ XCTAssertFalse(DictionaryMatcherExperiment.collectNegatives)
+ XCTAssertFalse(DictionaryMatcherExperiment.compareNegatives)
+
+ let defaultGeneration = DictionaryMatcherExperiment.generation
+ DictionaryMatcherExperiment.setEnabled(true)
+ XCTAssertEqual(DictionaryMatcherExperiment.generation, defaultGeneration)
+
+ DictionaryMatcherExperiment.setEnabled(false)
+ XCTAssertEqual(defaults.object(forKey: keys[0]) as? Bool, false)
+ XCTAssertFalse(DictionaryMatcherExperiment.sharedFeaturesEnabled)
+ XCTAssertFalse(DictionaryMatcherExperiment.needsFrames)
+ let disabledGeneration = DictionaryMatcherExperiment.generation
+ XCTAssertNotEqual(disabledGeneration, defaultGeneration)
+ DictionaryMatcherExperiment.setEnabled(false)
+ XCTAssertEqual(DictionaryMatcherExperiment.generation, disabledGeneration)
+
+ DictionaryMatcherExperiment.setEnabled(true)
+ XCTAssertEqual(defaults.object(forKey: keys[0]) as? Bool, true)
+ XCTAssertTrue(DictionaryMatcherExperiment.sharedFeaturesEnabled)
+ XCTAssertNotEqual(DictionaryMatcherExperiment.generation, disabledGeneration)
+ XCTAssertFalse(DictionaryPronunciationExperiment.captureEnabled)
+ XCTAssertFalse(DictionaryMatcherExperiment.collectNegatives)
+ XCTAssertFalse(DictionaryMatcherExperiment.compareNegatives)
+ }
+
func testTrainingRestartWaitsBeforeStartingAndClearsWaitingState() async {
let restart = DictionaryTrainingRestart()
let started = expectation(description: "Next example starts after the break")
@@ -294,6 +339,98 @@ final class CustomDictionaryManualEntryTests: XCTestCase {
#endif
#if arch(arm64)
+ func testPronunciationRoutingRequiresEligibleProfiles() async throws {
+ UserDefaults.standard.removeObject(forKey: "DictionarySharedFeatureMatcherEnabled")
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let store = PronunciationDictionaryStore(fileURL: directory.appendingPathComponent("profiles.json"))
+ let entry = SettingsStore.CustomDictionaryEntry(triggers: ["fluid"], replacement: "FluidVoice")
+ let provider = FluidAudioProvider(
+ enhancementOptions: .init(experimentalUnifiedFinalEnabled: false, pronunciationMatchingEnabled: true, customDictionaryEntries: [entry]),
+ pronunciationStore: store
+ )
+ let empty = try await provider.refreshPronunciationRoutingForTesting(modelKey: "parakeet-v2")
+ XCTAssertFalse(empty, "Default-on must preserve ordinary dictation for text-only dictionaries")
+
+ let capture = PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 6, modelKey: "parakeet-v2")
+ try await store.upsert(dictionaryEntryID: entry.id, label: entry.replacement, modelKey: capture.modelKey, enrollments: [capture, capture])
+ provider.resetStreamingPreviewCache()
+ let incomplete = try await provider.refreshPronunciationRoutingForTesting(modelKey: capture.modelKey)
+ XCTAssertFalse(incomplete, "Two recordings are not an eligible pronunciation profile")
+
+ try await store.upsert(dictionaryEntryID: entry.id, label: entry.replacement, modelKey: capture.modelKey, enrollments: [capture])
+ provider.resetStreamingPreviewCache()
+ let enrolled = try await provider.refreshPronunciationRoutingForTesting(modelKey: capture.modelKey)
+ XCTAssertTrue(enrolled, "A trained word still enables long-dictation matching")
+
+ UserDefaults.standard.set(false, forKey: "DictionarySharedFeatureMatcherEnabled")
+ let disabled = try await provider.refreshPronunciationRoutingForTesting(modelKey: capture.modelKey)
+ XCTAssertFalse(disabled, "Saved Off must override loaded profiles")
+ UserDefaults.standard.removeObject(forKey: "DictionarySharedFeatureMatcherEnabled")
+ let reenabled = try await provider.refreshPronunciationRoutingForTesting(modelKey: capture.modelKey)
+ XCTAssertTrue(reenabled, "Re-enabling must reload profiles even before the next recording")
+
+ provider.resetStreamingPreviewCache()
+ let incompatible = try await provider.refreshPronunciationRoutingForTesting(modelKey: "unrelated-model")
+ XCTAssertFalse(incompatible, "Another model's profile must not change dictation routing")
+
+ try await store.delete(dictionaryEntryID: entry.id)
+ provider.resetStreamingPreviewCache()
+ let deleted = try await provider.refreshPronunciationRoutingForTesting(modelKey: capture.modelKey)
+ XCTAssertFalse(deleted, "Deleting the last voice word restores ordinary dictation")
+ }
+
+ func testProfileFreeRoutingPreservesExplicitUnifiedFinalAndMeetingPolicy() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let store = PronunciationDictionaryStore(fileURL: directory.appendingPathComponent("profiles.json"))
+ for unified in [false, true] {
+ let provider = FluidAudioProvider(
+ enhancementOptions: .init(experimentalUnifiedFinalEnabled: unified, pronunciationMatchingEnabled: true, customDictionaryEntries: []),
+ pronunciationStore: store
+ )
+ let incremental = try await provider.refreshPronunciationRoutingForTesting(modelKey: "parakeet-v2")
+ XCTAssertEqual(incremental, unified, "The separate unified-final opt-in must keep its existing behavior")
+ }
+ let meeting = try FluidAudioProvider(meetingConfiguration: MeetingFinalProcessingConfiguration())
+ let incremental = try await meeting.refreshPronunciationRoutingForTesting(modelKey: "parakeet-v2")
+ XCTAssertFalse(incremental, "Meeting transcription must remain independent of dictation pronunciation")
+ }
+
+ func testProfileFreeLongDictationPreservesTextAndWordTimings() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let provider = FluidAudioProvider(
+ modelOverride: .parakeetTDTv2,
+ configureWordBoosting: false,
+ enhancementOptions: .init(experimentalUnifiedFinalEnabled: false, pronunciationMatchingEnabled: true, customDictionaryEntries: []),
+ pronunciationStore: PronunciationDictionaryStore(fileURL: directory.appendingPathComponent("profiles.json"))
+ )
+ try await provider.prepare()
+ let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
+ .appendingPathComponent("Resources/dictation_fixture.wav")
+ let clip = try AudioConverter().resampleAudioFile(path: fixture.path)
+ XCTAssertFalse(clip.isEmpty)
+ let samples = Array(repeating: clip, count: 240_000 / max(1, clip.count) + 1).flatMap { $0 }
+ XCTAssertGreaterThan(samples.count, 240_000)
+
+ UserDefaults.standard.set(false, forKey: "DictionarySharedFeatureMatcherEnabled")
+ provider.resetStreamingPreviewCache()
+ let baseline = try await provider.transcribeWithWordTimings(samples)
+ UserDefaults.standard.removeObject(forKey: "DictionarySharedFeatureMatcherEnabled")
+ provider.resetStreamingPreviewCache()
+ let preview = try await provider.transcribeStreaming(samples)
+ XCTAssertFalse(preview.text.isEmpty)
+ XCTAssertNil(provider.incrementalPreviewDeltaStart(totalSampleCount: samples.count + 16_000), "No unnecessary incremental session may start")
+ let defaultOn = try await provider.transcribeWithWordTimings(samples)
+ XCTAssertFalse(baseline.result.text.isEmpty)
+ XCTAssertFalse(baseline.words.isEmpty)
+ XCTAssertEqual(defaultOn.result.text, baseline.result.text)
+ XCTAssertEqual(defaultOn.words.map(\.text), baseline.words.map(\.text))
+ let final = try await provider.transcribeFinal(samples)
+ XCTAssertEqual(final.text, baseline.result.text)
+ }
+
func testTrainingTranscribesSpellingsAcrossPronunciationToggle() async throws {
let provider = FluidAudioProvider(modelOverride: .parakeetTDTv2, configureWordBoosting: false)
try await provider.prepare()
@@ -440,6 +577,48 @@ final class CustomDictionaryManualEntryTests: XCTestCase {
XCTAssertEqual(Set(entries.first?.triggers ?? []), Set(["hello", "right now", "fluid voice"]))
}
+ func testRepeatedCorrectionKeepsTheReviewOpenWithoutReportingSuccess() {
+ let entry = SettingsStore.CustomDictionaryEntry(triggers: ["super base"], replacement: "Supabase")
+ let unrelated = SettingsStore.CustomDictionaryEntry(triggers: ["other"], replacement: "Other")
+ self.withRestoredDictionary([entry, unrelated]) {
+ let session = AutomaticDictionaryTrainingSession(
+ candidate: .init(heardText: "Super base", correctedText: "Supabase"),
+ asr: AppServices.shared.asr
+ )
+ var successes = 0
+ session.onSuccess = { successes += 1 }
+
+ session.addOnlyCorrection()
+
+ XCTAssertEqual(SettingsStore.shared.customDictionaryEntries, [entry, unrelated])
+ XCTAssertEqual(session.screen, .choice)
+ XCTAssertEqual(successes, 0)
+ XCTAssertTrue(session.hasError)
+ XCTAssertTrue(session.statusMessage.contains("No new spelling corrections were saved"))
+ }
+ }
+
+ func testANewCorrectionStillSavesAndReportsSuccess() {
+ let unrelated = SettingsStore.CustomDictionaryEntry(triggers: ["other"], replacement: "Other")
+ self.withRestoredDictionary([unrelated]) {
+ let session = AutomaticDictionaryTrainingSession(
+ candidate: .init(heardText: "Super base", correctedText: "Supabase"),
+ asr: AppServices.shared.asr
+ )
+ var successes = 0
+ session.onSuccess = { successes += 1 }
+
+ session.addOnlyCorrection()
+
+ let entries = SettingsStore.shared.customDictionaryEntries
+ XCTAssertTrue(entries.contains(unrelated))
+ XCTAssertEqual(entries.first(where: { $0.replacement == "Supabase" })?.triggers, ["super base"])
+ XCTAssertEqual(session.screen, .success)
+ XCTAssertEqual(successes, 1)
+ XCTAssertFalse(session.hasError)
+ }
+ }
+
func testKeepsWhitespaceOnlyReplacements() {
XCTAssertEqual(CustomDictionaryManualEntry.sanitizedReplacement("\n"), "\n")
XCTAssertEqual(CustomDictionaryManualEntry.sanitizedReplacement(" "), " ")
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index 87974690..cff3d7ae 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -814,6 +814,156 @@ final class HotkeyShortcutTests: XCTestCase {
}
}
+ @MainActor
+ func testControlCommandAndControlOptionCanBelongToDifferentActions() {
+ for (command, option, _, _) in self.sharedControlShortcutPairs {
+ XCTAssertNotEqual(command, option)
+ XCTAssertFalse(command.conflictsWith(option))
+ XCTAssertFalse(option.conflictsWith(command))
+ for (primary, secondary) in [(command, option), (option, command)] {
+ for target: ShortcutRecordingTarget in [.command, .edit, .secondaryDictation, .pasteLast] {
+ self.withIsolatedShortcutConflicts { settings in
+ settings.primaryDictationShortcuts = [primary]
+ switch target {
+ case .command:
+ settings.commandModeHotkeyShortcut = secondary
+ settings.commandModeShortcutEnabled = true
+ case .edit:
+ settings.rewriteModeHotkeyShortcut = secondary
+ settings.rewriteModeShortcutEnabled = true
+ case .secondaryDictation:
+ settings.promptModeHotkeyShortcut = secondary
+ settings.promptModeShortcutEnabled = true
+ case .pasteLast:
+ settings.pasteLastTranscriptionHotkeyShortcut = secondary
+ settings.pasteLastTranscriptionShortcutEnabled = true
+ default:
+ XCTFail("Unexpected test target")
+ }
+ let view = ContentView()
+ XCTAssertNil(view.shortcutConflictMessage(for: secondary, target: target), "\(primary.displayString) versus \(secondary.displayString) for \(target)")
+ XCTAssertNil(view.shortcutConflictMessage(for: primary, target: .primaryDictation(.replace(0))))
+ XCTAssertEqual(view.shortcutConflictMessage(for: primary, target: target), "Duplicate with Primary Dictation Shortcut")
+ }
+ }
+ }
+ }
+ }
+
+ @MainActor
+ func testStandaloneRightOptionBlocksOnlyChordsContainingThatKey() {
+ self.withIsolatedShortcutConflicts { settings in
+ settings.primaryDictationShortcuts = [HotkeyShortcut(keyCode: 61, modifierFlags: [], modifierKeyCodes: [61])]
+ settings.commandModeHotkeyShortcut = HotkeyShortcut(keyCode: 55, modifierFlags: [], modifierKeyCodes: [55, 59])
+ settings.commandModeShortcutEnabled = true
+ let rightOptionChord = HotkeyShortcut(keyCode: 61, modifierFlags: [], modifierKeyCodes: [61, 59])
+ let leftOptionChord = HotkeyShortcut(keyCode: 58, modifierFlags: [], modifierKeyCodes: [58, 59])
+ let view = ContentView()
+ XCTAssertEqual(view.shortcutConflictMessage(for: rightOptionChord, target: .edit), "Overlaps Primary Dictation Shortcut — use a different modifier key")
+ XCTAssertNil(view.shortcutConflictMessage(for: leftOptionChord, target: .edit), "Sharing Control with Command is allowed; the standalone Right Option is the conflict")
+ settings.primaryDictationShortcuts = []
+ XCTAssertNil(ContentView().shortcutConflictMessage(for: rightOptionChord, target: .edit))
+ }
+ }
+
+ @MainActor
+ func testControlCommandAndControlOptionRouteIndependentlyInEveryKeyOrder() async throws {
+ for activation: HotkeyActivationMode in [.toggle, .hold, .automatic] {
+ for secondaryMode: HotkeyHoldModeType in [.commandMode, .rewriteMode, .promptMode, .promptAssignment] {
+ for (command, option, commandKeys, optionKeys) in self.sharedControlShortcutPairs {
+ let asr = ASRService()
+ var routes: [HotkeyHoldModeType] = []
+ var active: HotkeyHoldModeType?
+ let route: (HotkeyHoldModeType) -> Void = { mode in
+ routes.append(mode)
+ active = mode
+ asr.isRunning = true
+ }
+ let manager = GlobalHotkeyManager(
+ asrService: asr,
+ primaryShortcuts: [command],
+ promptModeShortcut: option,
+ commandModeShortcut: option,
+ rewriteModeShortcut: option,
+ promptShortcutAssignments: secondaryMode == .promptAssignment ? [(selection: .default, shortcut: option)] : [],
+ promptModeShortcutEnabled: secondaryMode == .promptMode,
+ commandModeShortcutEnabled: secondaryMode == .commandMode,
+ rewriteModeShortcutEnabled: secondaryMode == .rewriteMode,
+ startRecordingCallback: { route(.transcription) },
+ dictationModeCallback: { route(.transcription) },
+ stopAndProcessCallback: { _ in asr.isRunning = false; active = nil },
+ promptModeCallback: { route(.promptMode) },
+ promptSelectionCallback: { _ in route(.promptAssignment) },
+ commandModeCallback: { route(.commandMode) },
+ rewriteModeCallback: { route(.rewriteMode) },
+ isDictateRecordingProvider: { active == .transcription },
+ isPromptModeRecordingProvider: { active == .promptMode || active == .promptAssignment },
+ isCommandRecordingProvider: { active == .commandMode },
+ isRewriteRecordingProvider: { active == .rewriteMode },
+ isSessionLockedProvider: { false }
+ )
+ manager.setHotkeyMode(activation)
+ for reversePress in [false, true] {
+ for reverseRelease in [false, true] {
+ for useOption in [false, true, false, true] {
+ let count = routes.count
+ try await self.replaySharedControlShortcut(
+ useOption ? option : command,
+ keys: useOption ? optionKeys : commandKeys,
+ manager: manager,
+ reversePress: reversePress,
+ reverseRelease: reverseRelease
+ )
+ XCTAssertEqual(Array(routes.dropFirst(count)), [useOption ? secondaryMode : .transcription], "\(activation), \(secondaryMode), \(command.displayString), press=\(reversePress), release=\(reverseRelease)")
+ asr.isRunning = false
+ active = nil
+ }
+ }
+ }
+ manager.resetModifierOnlyShortcutTracking()
+ asr.isRunning = false
+ }
+ }
+ }
+ }
+
+ private var sharedControlShortcutPairs: [(HotkeyShortcut, HotkeyShortcut, [UInt16], [UInt16])] {
+ [
+ (HotkeyShortcut(keyCode: 55, modifierFlags: [], modifierKeyCodes: [55, 59]), HotkeyShortcut(keyCode: 58, modifierFlags: [], modifierKeyCodes: [58, 59]), [55, 59], [58, 59]),
+ (HotkeyShortcut(keyCode: 54, modifierFlags: [], modifierKeyCodes: [54, 62]), HotkeyShortcut(keyCode: 61, modifierFlags: [], modifierKeyCodes: [61, 62]), [54, 62], [61, 62]),
+ (HotkeyShortcut(keyCode: 59, modifierFlags: .command), HotkeyShortcut(keyCode: 59, modifierFlags: .option), [55, 59], [58, 59]),
+ (HotkeyShortcut(keyCode: 55, modifierFlags: .control), HotkeyShortcut(keyCode: 58, modifierFlags: .control), [55, 59], [58, 59]),
+ (HotkeyShortcut(keyCode: 40, modifierFlags: [.control, .command]), HotkeyShortcut(keyCode: 40, modifierFlags: [.control, .option]), [55, 59], [58, 59]),
+ ]
+ }
+
+ @MainActor
+ private func replaySharedControlShortcut(_ shortcut: HotkeyShortcut, keys: [UInt16], manager: GlobalHotkeyManager, reversePress: Bool, reverseRelease: Bool) async throws {
+ var held: Set<UInt16> = []
+ for key in reversePress ? keys.reversed().map({ $0 }) : keys {
+ held.insert(key)
+ let flags = held.reduce(into: NSEvent.ModifierFlags()) { $0.formUnion(HotkeyShortcut.modifierFlag(forKeyCode: $1) ?? []) }
+ _ = try manager.handleKeyEvent(type: .flagsChanged, event: self.primaryReleaseTestEvent(type: .flagsChanged, keyCode: key, modifiers: CGEventFlags(rawValue: UInt64(flags.rawValue))))
+ }
+ if !shortcut.isModifierOnlyShortcut {
+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: shortcut.keyCode, modifiers: CGEventFlags(rawValue: UInt64(shortcut.relevantModifierFlags.rawValue))))
+ }
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ if !shortcut.isModifierOnlyShortcut {
+ _ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp, keyCode: shortcut.keyCode, modifiers: CGEventFlags(rawValue: UInt64(shortcut.relevantModifierFlags.rawValue))))
+ }
+ for key in reverseRelease ? keys.reversed().map({ $0 }) : keys {
+ held.remove(key)
+ let flags = held.reduce(into: NSEvent.ModifierFlags()) { $0.formUnion(HotkeyShortcut.modifierFlag(forKeyCode: $1) ?? []) }
+ _ = try manager.handleKeyEvent(type: .flagsChanged, event: self.primaryReleaseTestEvent(type: .flagsChanged, keyCode: key, modifiers: CGEventFlags(rawValue: UInt64(flags.rawValue))))
+ }
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ }
+
@MainActor
func testIssue498DeletingHeldPrimaryModifierDoesNotBlockRemainingShortcut() async throws {
var starts = 0
@@ -1157,18 +1307,133 @@ final class HotkeyShortcutTests: XCTestCase {
}
}
- func testSavedCommandShortcutRemainsReservedWhileDisabled() throws {
- let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
- let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/ContentView.swift"), encoding: .utf8)
- let start = try XCTUnwrap(source.range(of: "private func shortcutConflictMessage("))
- let end = try XCTUnwrap(source.range(of: "private func applyPrimaryDictationShortcut", range: start.upperBound..<source.endIndex))
- let conflicts = String(source[start.lowerBound..<end.lowerBound])
- let optional = try XCTUnwrap(conflicts.components(separatedBy: "let optionalConfiguredShortcuts:").last?.components(separatedBy: "for (otherTarget").first)
- XCTAssertTrue(optional.contains("(.command, self.commandModeHotkeyShortcut)"), "The saved binding must remain reserved when Command Mode is toggled off")
- XCTAssertFalse(conflicts.contains("if self.isCommandModeShortcutEnabled"))
- XCTAssertTrue(conflicts.contains("configuredShortcut == shortcut"))
- XCTAssertTrue(conflicts.contains("shortcut.conflictsWith(configuredShortcut,"))
- XCTAssertTrue(conflicts.contains("otherTarget != target"), "Editing the Command binding must not conflict with itself")
+ @MainActor
+ func testCommandShortcutIsReservedOnlyWhileEnabled() {
+ self.withIsolatedShortcutConflicts { settings in
+ let shortcut = HotkeyShortcut(keyCode: 40, modifierFlags: [.control, .command])
+ settings.commandModeHotkeyShortcut = shortcut
+ for enabled in [true, false, true, false] {
+ settings.commandModeShortcutEnabled = enabled
+ let view = ContentView()
+ for target: ShortcutRecordingTarget in [.primaryDictation(.add), .edit, .secondaryDictation, .meeting, .pasteLast, .newPrompt] {
+ XCTAssertEqual(view.shortcutConflictMessage(for: shortcut, target: target), enabled ? "Duplicate with Command Mode" : nil, "\(target), enabled=\(enabled)")
+ }
+ XCTAssertNil(view.shortcutConflictMessage(for: shortcut, target: .command), "Editing Command must not conflict with itself")
+ XCTAssertEqual(settings.commandModeHotkeyShortcut, shortcut, "Validation must preserve the saved binding")
+ XCTAssertEqual(settings.commandModeShortcutEnabled, enabled)
+ XCTAssertTrue(settings.primaryDictationShortcuts.isEmpty, "Validation must not assign a shortcut")
+ }
+ }
+ }
+
+ @MainActor
+ func testPasteLastShortcutIsReservedOnlyWhileEnabled() {
+ self.withIsolatedShortcutConflicts { settings in
+ let shortcut = HotkeyShortcut(keyCode: 40, modifierFlags: [.control, .command])
+ settings.pasteLastTranscriptionHotkeyShortcut = shortcut
+ for enabled in [true, false, true, false] {
+ settings.pasteLastTranscriptionShortcutEnabled = enabled
+ let view = ContentView()
+ for target: ShortcutRecordingTarget in [.primaryDictation(.add), .edit, .secondaryDictation, .meeting, .command, .newPrompt] {
+ XCTAssertEqual(view.shortcutConflictMessage(for: shortcut, target: target), enabled ? "Duplicate with Paste Last Transcription" : nil, "\(target), enabled=\(enabled)")
+ }
+ XCTAssertNil(view.shortcutConflictMessage(for: shortcut, target: .pasteLast))
+ XCTAssertEqual(settings.pasteLastTranscriptionHotkeyShortcut, shortcut)
+ XCTAssertEqual(settings.pasteLastTranscriptionShortcutEnabled, enabled)
+ XCTAssertTrue(settings.primaryDictationShortcuts.isEmpty)
+ }
+ }
+ }
+
+ @MainActor
+ func testEditAndSmartShortcutsAreReservedOnlyWhileEnabled() {
+ self.withIsolatedShortcutConflicts { settings in
+ let edit = HotkeyShortcut(keyCode: 40, modifierFlags: [.control, .command])
+ let smart = HotkeyShortcut(keyCode: 46, modifierFlags: [.control, .command])
+ settings.rewriteModeHotkeyShortcut = edit
+ settings.promptModeHotkeyShortcut = smart
+ for enabled in [true, false] {
+ settings.rewriteModeShortcutEnabled = enabled
+ settings.promptModeShortcutEnabled = enabled
+ let view = ContentView()
+ XCTAssertEqual(view.shortcutConflictMessage(for: edit, target: .primaryDictation(.add)), enabled ? "Duplicate with Edit Mode" : nil)
+ XCTAssertEqual(view.shortcutConflictMessage(for: smart, target: .primaryDictation(.add)), enabled ? "Duplicate with Secondary Dictation Shortcut" : nil)
+ XCTAssertEqual(settings.rewriteModeHotkeyShortcut, edit)
+ XCTAssertEqual(settings.promptModeHotkeyShortcut, smart)
+ }
+ }
+ }
+
+ @MainActor
+ func testDisabledCommandShortcutDoesNotReserveMeetingModifierPrefix() {
+ self.withIsolatedShortcutConflicts { settings in
+ settings.commandModeHotkeyShortcut = HotkeyShortcut(keyCode: 55, modifierFlags: .command)
+ let meeting = HotkeyShortcut(keyCode: 40, modifierFlags: [.control, .command])
+ for enabled in [true, false] {
+ settings.commandModeShortcutEnabled = enabled
+ XCTAssertEqual(ContentView().shortcutConflictMessage(for: meeting, target: .meeting), enabled ? "Overlaps Command Mode — use a different modifier key" : nil)
+ }
+ }
+ }
+
+ @MainActor
+ func testReassigningCommandStillRejectsOtherActiveShortcuts() {
+ self.withIsolatedShortcutConflicts { settings in
+ let shortcut = HotkeyShortcut(keyCode: 40, modifierFlags: [.control, .command])
+ settings.commandModeHotkeyShortcut = shortcut
+ settings.commandModeShortcutEnabled = false
+ settings.primaryDictationShortcuts = [shortcut]
+ XCTAssertEqual(ContentView().shortcutConflictMessage(for: shortcut, target: .command), "Duplicate with Primary Dictation Shortcut")
+ XCTAssertEqual(settings.primaryDictationShortcuts, [shortcut])
+ XCTAssertFalse(settings.commandModeShortcutEnabled)
+
+ settings.primaryDictationShortcuts = []
+ settings.meetingRecordingHotkeyShortcut = shortcut
+ let modifier = HotkeyShortcut(keyCode: 55, modifierFlags: .command)
+ XCTAssertEqual(ContentView().shortcutConflictMessage(for: modifier, target: .command), "Overlaps Start / Stop Meeting — use a different modifier key")
+ XCTAssertEqual(settings.meetingRecordingHotkeyShortcut, shortcut)
+ XCTAssertFalse(settings.commandModeShortcutEnabled)
+ }
+ }
+
+ @MainActor
+ func testReaddingReusedCommandOrPasteKeysRejectsTheActiveOwner() {
+ self.withIsolatedShortcutConflicts { settings in
+ let shortcut = HotkeyShortcut(keyCode: 40, modifierFlags: [.control, .command])
+ settings.commandModeHotkeyShortcut = shortcut
+ settings.pasteLastTranscriptionHotkeyShortcut = shortcut
+ for commandEnabled in [false, true] {
+ settings.commandModeShortcutEnabled = commandEnabled
+ settings.pasteLastTranscriptionShortcutEnabled = !commandEnabled
+ let target: ShortcutRecordingTarget = commandEnabled ? .pasteLast : .command
+ let owner = commandEnabled ? "Command Mode" : "Paste Last Transcription"
+ XCTAssertEqual(ContentView().shortcutConflictMessage(for: shortcut, target: target), "Duplicate with \(owner)")
+ XCTAssertEqual(settings.commandModeShortcutEnabled, commandEnabled)
+ XCTAssertEqual(settings.pasteLastTranscriptionShortcutEnabled, !commandEnabled)
+ XCTAssertEqual(settings.commandModeHotkeyShortcut, shortcut)
+ XCTAssertEqual(settings.pasteLastTranscriptionHotkeyShortcut, shortcut)
+ }
+ }
+ }
+
+ @MainActor
+ private func withIsolatedShortcutConflicts(run: (SettingsStore) -> Void) {
+ let keys = [
+ self.primaryDictationShortcutsKey, self.legacyHotkeyShortcutKey,
+ "DictationPromptConfigurations", "PromptModeHotkeyShortcut", "PromptModeShortcutEnabled",
+ "CommandModeHotkeyShortcut", "CommandModeShortcutEnabled", "RewriteModeHotkeyShortcut", "RewriteModeShortcutEnabled",
+ "CancelRecordingHotkeyShortcut", "MeetingRecordingHotkeyShortcut",
+ self.pasteLastTranscriptionShortcutKey, self.pasteLastTranscriptionEnabledKey,
+ ]
+ self.withRestoredDefaults(keys: keys) {
+ for key in keys {
+ UserDefaults.standard.removeObject(forKey: key)
+ }
+ let settings = SettingsStore.shared
+ settings.primaryDictationShortcuts = []
+ settings.cancelRecordingHotkeyShortcut = nil
+ run(settings)
+ }
}
func testBareKeyPolicyCoversLettersNumbersAndEditingKeysButAllowsPunctuation() {
@@ -1847,6 +2112,7 @@ final class HotkeyShortcutTests: XCTestCase {
manager.updatePrimaryShortcuts([first, modifier])
if mouse {
let down = try XCTUnwrap(CGEvent(mouseEventSource: nil, mouseType: .otherMouseDown, mouseCursorPosition: .zero, mouseButton: .center))
+ down.flags = []
_ = manager.handleMouseShortcutEvent(type: .otherMouseDown, event: down)
} else {
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
@@ -1860,6 +2126,7 @@ final class HotkeyShortcutTests: XCTestCase {
XCTAssertEqual(starts, 0, "A second modifier shortcut must not activate before the owning key/button releases")
if mouse {
let up = try XCTUnwrap(CGEvent(mouseEventSource: nil, mouseType: .otherMouseUp, mouseCursorPosition: .zero, mouseButton: .center))
+ up.flags = []
_ = manager.handleMouseShortcutEvent(type: .otherMouseUp, event: up)
} else {
_ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp, modifiers: []))
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
index 47c9f168..1b6f945f 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
@@ -427,6 +427,54 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.prompts.first?.tier, .browserTier2)
}
+ func testProcessOwnerLookupDoesNotBlockMainAndPreservesSnapshot() async {
+ let entered = expectation(description: "owner lookup on worker")
+ let release = DispatchSemaphore(value: 0)
+ let owners = [MeetingProcessOwner(processID: 42, bundleIdentifier: "us.zoom.xos", bundlePath: "/Applications/zoom.us.app")]
+ let provider = CoreAudioProcessActivityProvider(
+ readOwners: {
+ XCTAssertFalse(Thread.isMainThread)
+ entered.fulfill()
+ XCTAssertEqual(release.wait(timeout: .now() + 2), .success)
+ return owners
+ },
+ readActivity: { snapshotOwners in
+ XCTAssertFalse(Thread.isMainThread)
+ return .init(processes: [], owners: snapshotOwners, queryState: .valid)
+ }
+ )
+ let task = Task { await provider.snapshot() }
+ await fulfillment(of: [entered], timeout: 1)
+ // This main-actor continuation must run while the owner lookup is blocked.
+ release.signal()
+ let snapshot = await task.value
+ XCTAssertEqual(snapshot.owners, owners)
+ XCTAssertEqual(snapshot.queryState, .valid)
+ }
+
+ func testCancelledProcessOwnerLookupSkipsAudioQuery() async {
+ let entered = expectation(description: "owner lookup on worker")
+ let release = DispatchSemaphore(value: 0)
+ let provider = CoreAudioProcessActivityProvider(
+ readOwners: {
+ entered.fulfill()
+ _ = release.wait(timeout: .now() + 2)
+ return []
+ },
+ readActivity: { _ in
+ XCTFail("A cancelled meeting poll must not start an audio query")
+ return .init(processes: [], owners: [], queryState: .valid)
+ }
+ )
+ let task = Task { await provider.snapshot() }
+ await fulfillment(of: [entered], timeout: 1)
+ task.cancel()
+ release.signal()
+ let snapshot = await task.value
+ XCTAssertEqual(snapshot.queryState, .unknown)
+ XCTAssertTrue(snapshot.owners.isEmpty)
+ }
+
func testLiveAudioProcessOwnershipProbe() async throws {
guard ProcessInfo.processInfo.environment["FV_DETECTOR_LIVE_PROBE"] == "1" else {
throw XCTSkip("Opt-in read-only live Core Audio ownership probe")
diff --git a/Tests/FluidDictationIntegrationTests/MeetingSummaryProviderTests.swift b/Tests/FluidDictationIntegrationTests/MeetingSummaryProviderTests.swift
index 2a09b85a..0a7e872d 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingSummaryProviderTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingSummaryProviderTests.swift
@@ -55,10 +55,12 @@ final class MeetingSummaryProviderTests: XCTestCase {
modelName: "Local Model"
)
XCTAssertEqual(saved.provenance, "On device - Provider · Local Model")
+ XCTAssertEqual(saved.notice, "Generated by AI on your Mac. May contain mistakes.")
XCTAssertTrue(saved.isCurrent(transcriptHash: "t", promptHash: nil))
XCTAssertFalse(saved.isCurrent(transcriptHash: "changed", promptHash: nil))
let restored = try JSONDecoder().decode(MeetingSummaryController.SavedSummary.self, from: JSONEncoder().encode(saved))
XCTAssertEqual(restored.modelName, "Local Model")
+ XCTAssertEqual(restored.notice, saved.notice)
}
func testDictationWritesOnlyIntoEditorsThatOptedIn() {
@@ -88,6 +90,7 @@ final class MeetingSummaryProviderTests: XCTestCase {
let data = Data(#"{"transcriptHash":"old","modelID":"local-summary","text":"Previous summary"}"#.utf8)
let saved = try JSONDecoder().decode(MeetingSummaryController.SavedSummary.self, from: data)
XCTAssertEqual(saved.text, "Previous summary")
+ XCTAssertEqual(saved.notice, "Generated by AI. May contain mistakes.")
XCTAssertEqual(saved.provenance, "Fluid Intelligence · local-summary")
XCTAssertNil(saved.generatedAt)
}
@@ -105,6 +108,7 @@ final class MeetingSummaryProviderTests: XCTestCase {
generatedAt: Date()
)
let data = try JSONEncoder().encode(saved)
+ XCTAssertEqual(saved.notice, "Generated by AI. May contain mistakes.")
XCTAssertFalse(try XCTUnwrap(String(data: data, encoding: .utf8)).contains(route.apiKey))
XCTAssertEqual(try JSONDecoder().decode(MeetingSummaryController.SavedSummary.self, from: data).provenance, route.provenance)
}
diff --git a/Tests/FluidDictationIntegrationTests/PrivateAIProviderPromptFormatTests.swift b/Tests/FluidDictationIntegrationTests/PrivateAIProviderPromptFormatTests.swift
index 7e5764cb..e65ea180 100644
--- a/Tests/FluidDictationIntegrationTests/PrivateAIProviderPromptFormatTests.swift
+++ b/Tests/FluidDictationIntegrationTests/PrivateAIProviderPromptFormatTests.swift
@@ -1,3 +1,4 @@
+import Combine
@testable import FluidVoice_Debug
import XCTest
@@ -88,6 +89,175 @@ final class PrivateAIProviderPromptFormatTests: XCTestCase {
}
}
+ func testOverlaySnapshotMatchesRoutingAndDoesNotChangeSettings() async {
+ let settings = SettingsStore.shared
+ let restore = self.saveOverlaySettings(settings)
+ defer { restore() }
+ let profile = SettingsStore.DictationPromptProfile(id: "snapshot-profile", name: "Work", prompt: "Clean up")
+ settings.dictationPromptProfiles = [profile]
+ settings.appPromptBindings = [.init(mode: .dictate, appBundleID: "snapshot.editor", appName: "Editor", promptID: profile.id)]
+ settings.selectedProviderID = "openai"
+ settings.selectedModelByProvider = ["openai": "test-model"]
+ settings.dictationPromptConfigurations = [:]
+ settings.setDictationPromptConfiguration(.init(providerID: "openai", modelName: "profile-model"), for: .profile(profile.id))
+ let selections: [SettingsStore.DictationPromptSelection] = [.off, .default, .privateAI, .profile(profile.id)]
+ for selection in selections {
+ for scope in [SettingsStore.PromptRoutingScope.allApps, .selectedAppsOnly] {
+ settings.dictationPromptRoutingScope = scope
+ settings.setDictationPromptSelection(selection, for: .primary)
+ settings.setDictationPromptSelection(.off, for: .secondary)
+ for app in ["snapshot.editor", "snapshot.other"] {
+ let selectedBefore = settings.selectedDictationPromptID
+ let configurationBefore = settings.dictationPromptConfigurations
+ let input = DictationOverlayPresentationInput(settings: settings, appBundleID: app)
+ let expected = settings.dictationOverlayLabel(for: .primary, appBundleID: app)
+ let result = await Task.detached { input.resolve() }.value
+ XCTAssertEqual(result.primary.label, expected, "\(selection), \(scope), \(app)")
+ XCTAssertEqual(result.secondary.label, "Basic")
+ XCTAssertEqual(result.primary.hasAppOverride, settings.isAppDictationPromptBindingActive(for: .primary, appBundleID: app))
+ XCTAssertEqual(settings.selectedDictationPromptID, selectedBefore)
+ XCTAssertEqual(settings.dictationPromptConfigurations, configurationBefore)
+ }
+ }
+ }
+ }
+
+ func testOverlaySnapshotKeepsManualChoiceAndUpdatesAfterAppSwitch() {
+ let settings = SettingsStore.shared
+ let restore = self.saveOverlaySettings(settings)
+ let session = DictationAppSession.shared
+ let previousApp = session.appID
+ defer {
+ restore()
+ session.activate(previousApp ?? "snapshot.finished")
+ }
+ settings.selectedProviderID = "openai"
+ settings.selectedModelByProvider = ["openai": "test-model"]
+ settings.dictationPromptConfigurations = [:]
+ settings.appPromptBindings = []
+ settings.dictationPromptRoutingScope = .allApps
+ settings.setDictationPromptSelection(.default, for: .primary)
+ session.activate("snapshot.editor")
+ session.select(.off, slot: .primary, appID: "snapshot.editor")
+ let input = DictationOverlayPresentationInput(settings: settings, appBundleID: session.appID)
+ XCTAssertEqual(input.primary.unavailable.resolve(verifiedModelID: nil, modelName: { $0 }).label, "Basic")
+ session.activate("snapshot.other")
+ let next = DictationOverlayPresentationInput(settings: settings, appBundleID: session.appID)
+ XCTAssertEqual(next.primary.unavailable.resolve(verifiedModelID: nil, modelName: { $0 }).label, "Default · test-model")
+ XCTAssertEqual(settings.dictationPromptSelection(for: .primary), .default)
+ }
+
+ func testOverlayAvailabilityFallbackAndModelName() {
+ let smart = DictationOverlayPresentationInput.Candidate(
+ name: "Smart", builtInLabel: "Smart", hasAppOverride: false, usesSelectedPrivateModel: true, modelID: ""
+ )
+ let fallback = DictationOverlayPresentationInput.Candidate(
+ name: "Default", builtInLabel: "Default", hasAppOverride: false, usesSelectedPrivateModel: false, modelID: ""
+ )
+ let choices = DictationOverlayPresentationInput.Choices(available: smart, unavailable: fallback)
+ XCTAssertEqual(choices.resolve(verifiedModelID: "mini", modelName: { $0.isEmpty ? "" : "Fluid-1 Mini" }).label, "Smart · Mini")
+ XCTAssertEqual(choices.resolve(verifiedModelID: nil, modelName: { $0 }).label, "Basic")
+ XCTAssertEqual(smart.resolve(verifiedModelID: nil, modelName: { $0 }).label, "Basic")
+ }
+
+ func testWarmupRequestRespectsOffExternalPrivateAndAppOverrides() {
+ let settings = SettingsStore.shared
+ let restore = self.saveOverlaySettings(settings)
+ defer { restore() }
+ let profile = SettingsStore.DictationPromptProfile(id: "warmup-profile", name: "Work", prompt: "Clean up")
+ settings.dictationPromptProfiles = [profile]
+ settings.appPromptBindings = []
+ settings.dictationPromptRoutingScope = .allApps
+ settings.selectedProviderID = "openai"
+ settings.dictationPromptConfigurations = [:]
+ settings.setDictationPromptConfiguration(.init(providerID: "openai", modelName: "external-model"), for: .default)
+ func request(_ slot: SettingsStore.DictationShortcutSlot = .primary, app: String = "warmup.editor") -> PrivateAIProviderPromptFormat.VerificationInput? {
+ DictationProviderRoute.privateAIWarmupVerification(settings: settings, slot: slot, appBundleID: app)
+ }
+ settings.setDictationPromptSelection(.off, for: .primary)
+ XCTAssertNil(request())
+ settings.setDictationPromptSelection(.default, for: .primary)
+ XCTAssertNil(request())
+ settings.setDictationPromptSelection(.privateAI, for: .primary)
+ XCTAssertNotNil(request())
+ settings.setDictationPromptSelection(.off, for: .secondary)
+ XCTAssertNil(request(.secondary))
+
+ settings.setDictationPromptConfiguration(.init(providerID: "openai", modelName: "external-model"), for: .profile(profile.id))
+ settings.appPromptBindings = [.init(mode: .dictate, appBundleID: "warmup.editor", appName: "Editor", promptID: profile.id)]
+ XCTAssertNil(request(), "An external app rule must not warm a private model")
+ XCTAssertNotNil(request(app: "warmup.other"))
+ settings.setDictationPromptConfiguration(.init(providerID: PrivateAIProviderFeature.shared.providerID, modelName: "private-model"), for: .profile(profile.id))
+ XCTAssertNotNil(request(), "A profile using the private provider still needs warmup")
+ settings.dictationPromptRoutingScope = .selectedAppsOnly
+ XCTAssertNil(request(app: "warmup.other"))
+ XCTAssertEqual(settings.selectedDictationPromptID, PrivateAIProviderPromptFormat.promptSelectionID)
+ }
+
+ func testOverlayWorkerCoalescesChangesRejectsStaleResultAndNeverRunsOnMain() async {
+ let settings = SettingsStore.shared
+ let restore = self.saveOverlaySettings(settings)
+ defer { restore() }
+ settings.setDictationPromptSelection(.off, for: .primary)
+ let first = DictationOverlayPresentationInput(settings: settings, appBundleID: nil)
+ settings.setDictationPromptSelection(.default, for: .primary)
+ let latest = DictationOverlayPresentationInput(settings: settings, appBundleID: nil)
+ let entered = expectation(description: "worker entered")
+ let finished = expectation(description: "latest value published")
+ let gate = OverlayPresentationTestGate()
+ let store = DictationOverlayPresentationStore { input in
+ XCTAssertFalse(Thread.isMainThread)
+ if input == first {
+ entered.fulfill()
+ await gate.wait()
+ }
+ let label = input == first ? "stale" : "latest"
+ let value = DictationOverlayPresentation(label: label, builtInLabel: nil, hasAppOverride: false)
+ return DictationOverlayPresentations(primary: value, secondary: value)
+ }
+ var published: [String] = []
+ let subscription = store.$value.sink { value in
+ published.append(value.primary.label)
+ if value.primary.label == "latest" { finished.fulfill() }
+ }
+ store.update(first)
+ await fulfillment(of: [entered], timeout: 2)
+ for _ in 0..<20 {
+ store.update(latest)
+ }
+ await gate.release()
+ await fulfillment(of: [finished], timeout: 2)
+ XCTAssertFalse(published.contains("stale"))
+ XCTAssertEqual(published.filter { $0 == "latest" }.count, 1)
+ XCTAssertEqual(settings.selectedDictationPromptID, nil)
+ withExtendedLifetime(subscription) {}
+ }
+
+ private func saveOverlaySettings(_ settings: SettingsStore) -> () -> Void {
+ let profiles = settings.dictationPromptProfiles
+ let bindings = settings.appPromptBindings
+ let primary = settings.selectedDictationPromptID
+ let secondary = settings.promptModeSelectedPromptID
+ let primaryOff = settings.isDictationPromptOff
+ let secondaryOff = settings.isSecondaryDictationPromptOff
+ let scope = settings.dictationPromptRoutingScope
+ let configurations = settings.dictationPromptConfigurations
+ let provider = settings.selectedProviderID
+ let models = settings.selectedModelByProvider
+ return {
+ settings.dictationPromptProfiles = profiles
+ settings.appPromptBindings = bindings
+ settings.selectedDictationPromptID = primary
+ settings.promptModeSelectedPromptID = secondary
+ settings.isDictationPromptOff = primaryOff
+ settings.isSecondaryDictationPromptOff = secondaryOff
+ settings.dictationPromptRoutingScope = scope
+ settings.dictationPromptConfigurations = configurations
+ settings.selectedProviderID = provider
+ settings.selectedModelByProvider = models
+ }
+ }
+
private func withRestoredFingerprints(_ body: (SettingsStore) -> Void) {
let settings = SettingsStore.shared
let providerFingerprints = settings.verifiedProviderFingerprints
@@ -117,3 +287,19 @@ private struct TaskDefaultPrivateAIProvider: PrivateAIProviderFeatureProviding {
func canonicalModelID(for _: String) -> String? { nil }
func isKnownModelID(_: String) -> Bool { false }
}
+
+private actor OverlayPresentationTestGate {
+ private var continuation: CheckedContinuation<Void, Never>?
+ private var released = false
+
+ func wait() async {
+ guard !self.released else { return }
+ await withCheckedContinuation { self.continuation = $0 }
+ }
+
+ func release() {
+ self.released = true
+ self.continuation?.resume()
+ self.continuation = nil
+ }
+}
diff --git a/Tests/Standalone/DictionaryMatcherExperimentTests.swift b/Tests/Standalone/DictionaryMatcherExperimentTests.swift
index 8f2df7a0..211f6ff4 100644
--- a/Tests/Standalone/DictionaryMatcherExperimentTests.swift
+++ b/Tests/Standalone/DictionaryMatcherExperimentTests.swift
@@ -1,6 +1,13 @@
#if DICTIONARY_EXPERIMENT_STANDALONE
import Foundation
+// The real catalog is used for model identity; model files are absent from this fixture.
+enum HuggingFaceModelDownloader {
+ static func artifactIsComplete(at _: URL, isDirectory _: Bool) -> Bool {
+ false
+ }
+}
+
// Minimal surrounding types; the matcher, resolver and persistence implementations under test are production sources.
struct ASRWordTiming: Sendable { let text: String; let start: Double; let end: Double }
struct PronunciationEnrollmentCapture { let inspectionID: UUID?; let originalAudioID: UUID?; let values: [Float] }
diff --git a/Tests/run_dictionary_matcher_experiment_tests.sh b/Tests/run_dictionary_matcher_experiment_tests.sh
index 2b4af595..faa8608d 100644
--- a/Tests/run_dictionary_matcher_experiment_tests.sh
+++ b/Tests/run_dictionary_matcher_experiment_tests.sh
@@ -10,6 +10,7 @@ task_repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
task_test_dir=$(mktemp -d /tmp/fluidvoice-dictionary-tests.XXXXXX)
trap 'rm -rf "$task_test_dir"' EXIT
xcrun swiftc -D DICTIONARY_EXPERIMENT_STANDALONE -O -parse-as-library \
+ "$task_repo_dir/Sources/Fluid/Services/ParakeetSpeechModelCatalog.swift" \
"$task_repo_dir/Sources/Fluid/Services/DictionaryCorrectionEditPolicy.swift" \
"$task_repo_dir/Sources/Fluid/Services/DictionaryExperimentalMatcher.swift" \
"$task_repo_dir/Sources/Fluid/Services/DictionaryNegativeExamples.swift" \
diff --git a/Tests/run_dictionary_training_save_tests.py b/Tests/run_dictionary_training_save_tests.py
index df6224ce..b76b3501 100644
--- a/Tests/run_dictionary_training_save_tests.py
+++ b/Tests/run_dictionary_training_save_tests.py
@@ -21,6 +21,7 @@ source = (repo / 'Sources/Fluid/UI/CustomDictionaryView.swift').read_text()
method = source[source.index(' private func addTrainedReplacement() async {'):source.index(' private func removeTrainingVariant(')].replace('private func addTrainedReplacement', 'func addTrainedReplacement')
progress = source[source.index('struct DictionaryTrainingProgress {'):source.index('enum CustomDictionaryTrainingMerge {')]
readiness = source[source.index(' private var trainingProgress:'):source.index(' private var trainingAlreadyCorrectWithoutReplacement:')]
+already_correct = source[source.index(' private var trainingAlreadyCorrectWithoutReplacement:'):source.index(' private var trainingReadinessProgress:')]
can_save = source[source.index(' private var canAddTrainedReplacement:'):source.index(' private var shouldPulseTrainedReplacementButton:')]
merge = source[source.index('enum CustomDictionaryTrainingMerge {'):source.index('private struct ReplacementConfirmation:')]
settings = (repo / 'Sources/Fluid/Persistence/SettingsStore.swift').read_text()
@@ -46,7 +47,7 @@ struct VoiceTrainingAliasFilter {
init(accepted: [String]) { self.accepted = accepted }
}
static var response: Result?
- static func filter(_ values: [String]) async -> Result { response ?? Result(accepted: values) }
+ static func filter(_ values: [String], manuallyConfirmed: Set<String> = []) async -> Result { response ?? Result(accepted: values) }
}
final class DebugLogger {
static let shared = DebugLogger()
@@ -82,6 +83,7 @@ PROGRESS
MERGE
@MainActor final class SaveHarness {
READINESS
+ ALREADY_CORRECT
CAN_SAVE
var trainingSampleCount = 3
var isTrainingRecording = false
@@ -91,12 +93,14 @@ MERGE
var trainingPronunciationEnrollments = Array(repeating: PronunciationEnrollmentCapture(), count: 3)
var activePronunciationMatching = true
var trainingVariants = ["fluid boys"]
+ var manualTrainingSpellings = Set<String>()
+ var lastTrainingOutput = "fluid boys"
var pronunciationEnabled = true
var trainingHasError = false
var trainingStatusMessage = ""
var entries: [SettingsStore.CustomDictionaryEntry] = []
var wizardSavedWord = ""
- enum Step { case recording, saved }
+ enum Step { case recording, review, saved }
var wizardStep = Step.recording
var writes = 0
func saveEntries() { writes += 1; SettingsStore.shared.customDictionaryEntries = entries }
@@ -255,6 +259,75 @@ func check(_ condition: @autoclosure () -> Bool, _ message: String) {
check(!view.trainingVariants.isEmpty && !view.isTrainingProcessing && view.trainingSaveID == nil, "Alias failure retains recordings and releases busy state")
passes += 1
}
+ // Repeating an existing text correction keeps captures without claiming a new save.
+ do {
+ let original = baseline()
+ let view = reset(original)
+ view.activePronunciationMatching = false
+ view.trainingPronunciationEnrollments = []
+ view.trainingVariants = ["fluid voice"]
+ view.wizardStep = .review
+ await PronunciationDictionaryStore.shared.configure(gate: nil)
+ await view.addTrainedReplacement()
+ let calls = await PronunciationDictionaryStore.shared.calls
+ check(view.writes == 0 && calls == 0, "Unchanged spelling must not write text rules or voice profiles")
+ check(SettingsStore.shared.customDictionaryEntries == original, "Unchanged save must preserve all entries and IDs")
+ check(view.wizardStep == .review && view.trainingHasError, "Unchanged spelling must stay in review with feedback")
+ check(view.trainingStatusMessage.contains("Nothing new was saved"), "Unchanged spelling must explain the result")
+ check(view.trainingVariants == ["fluid voice"], "Unchanged save must retain recordings for retry")
+ check(!view.isTrainingProcessing && view.trainingSaveID == nil, "Unchanged save must release its busy state")
+ passes += 1
+ }
+ // Already-correct captures must explain that no new correction was saved.
+ do {
+ let original = baseline()
+ let view = reset(original)
+ view.activePronunciationMatching = false
+ view.trainingPronunciationEnrollments = []
+ view.normalizedTrainingReplacement = "Palermo"
+ view.trainingVariants = []
+ view.lastTrainingOutput = "palermo"
+ view.wizardStep = .review
+ await PronunciationDictionaryStore.shared.configure(gate: nil)
+ await view.addTrainedReplacement()
+ let calls = await PronunciationDictionaryStore.shared.calls
+ check(view.writes == 0 && calls == 0, "Already-recognized words must not save text rules or voice profiles")
+ check(SettingsStore.shared.customDictionaryEntries == original, "Already-recognized words must preserve the dictionary")
+ check(view.wizardStep == .review && view.trainingHasError, "Already-recognized words must stay in review with feedback")
+ check(view.trainingStatusMessage.contains("Nothing new was saved"), "Already-recognized words must explain the result")
+ check(view.trainingSampleCount == 3 && view.lastTrainingOutput == "palermo", "Already-correct feedback must retain captures")
+ check(!view.isTrainingProcessing && view.trainingSaveID == nil, "Already-correct feedback must leave the editor idle")
+ passes += 1
+ }
+ // Existing correct captures must not make Save available during a new recording or save.
+ for recording in [true, false] {
+ let original = baseline()
+ let view = reset(original)
+ view.activePronunciationMatching = false
+ view.trainingPronunciationEnrollments = []
+ view.trainingVariants = []
+ view.lastTrainingOutput = "FluidVoice"
+ view.isTrainingRecording = recording
+ view.isTrainingProcessing = !recording
+ await view.addTrainedReplacement()
+ check(view.writes == 0 && !view.trainingHasError, "Busy captures must not save or replace their status with no-change feedback")
+ check(SettingsStore.shared.customDictionaryEntries == original, "Busy captures must preserve saved entries")
+ check(view.isTrainingRecording == recording && view.isTrainingProcessing == !recording, "Busy Save must leave the current recording or save alone")
+ passes += 1
+ }
+ // New voice samples are a real save even when the spelling rules are unchanged.
+ do {
+ let original = baseline()
+ let view = reset(original)
+ view.trainingVariants = ["fluid voice"]
+ await PronunciationDictionaryStore.shared.configure(gate: nil)
+ await view.addTrainedReplacement()
+ let profiles = await PronunciationDictionaryStore.shared.writes
+ check(profiles == [original[0].id], "Pronunciation-only retraining must still save its profile")
+ check(SettingsStore.shared.customDictionaryEntries == original, "Voice-only retraining must preserve text rules")
+ check(view.wizardStep == .saved && !view.trainingHasError, "New voice samples must still complete successfully")
+ passes += 1
+ }
// Insufficient spellings use the production save gate, even with enough voice examples.
do {
let original = baseline()
@@ -319,7 +392,7 @@ func check(_ condition: @autoclosure () -> Bool, _ message: String) {
print("PASS \(passes) dictionary save scenarios using the production save method, readiness and merge code")
}
}
-'''.replace('ENTRY', entry).replace('PROGRESS', progress).replace('MERGE', merge).replace('READINESS', readiness).replace('CAN_SAVE', can_save).replace('METHOD', method)
+'''.replace('ENTRY', entry).replace('PROGRESS', progress).replace('MERGE', merge).replace('READINESS', readiness).replace('ALREADY_CORRECT', already_correct).replace('CAN_SAVE', can_save).replace('METHOD', method)
swift = swift.replace('check(await PronunciationDictionaryStore.shared.writes.isEmpty,', 'let textOnlyWrites = await PronunciationDictionaryStore.shared.writes\n check(textOnlyWrites.isEmpty,')
isolation_swift = r'''
import Foundation