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

feat(dictionary): train from corrected dictation

altic-dev8dea5d901bd4
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index ba15c5b6..4291f5ee 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -240,6 +240,7 @@ struct ContentView: View {
@State private var selectedSidebarItem: SidebarItem?
@State private var previousSidebarItem: SidebarItem? = nil // Track previous for mode transitions
+ @State private var pendingDictionaryTrainingPrefill: DictionaryTrainingPrefill?
@State private var playgroundUsed: Bool = SettingsStore.shared.playgroundUsed
@State private var recordingAppInfo: (name: String, bundleId: String, windowTitle: String)? = nil
@State private var recordingPrecedingText: String = ""
@@ -1012,6 +1013,9 @@ struct ContentView: View {
self.selectedSidebarItem = .aiEnhancements
case .history:
self.selectedSidebarItem = .history
+ case let .customDictionaryTraining(prefill):
+ self.pendingDictionaryTrainingPrefill = prefill
+ self.selectedSidebarItem = .customDictionary
}
}
@@ -1308,7 +1312,12 @@ struct ContentView: View {
case .meetingTools:
return AnyView(self.meetingToolsView)
case .customDictionary:
- return AnyView(CustomDictionaryView())
+ return AnyView(CustomDictionaryView(
+ trainingPrefill: self.pendingDictionaryTrainingPrefill,
+ onTrainingPrefillConsumed: {
+ self.pendingDictionaryTrainingPrefill = nil
+ }
+ ))
case .stats:
return AnyView(self.statsView)
case .feedback:
@@ -2485,7 +2494,8 @@ struct ContentView: View {
self.asr.typeOutputPlanToActiveField(
finalOutputPlan,
preferredTargetPID: typingTarget.pid,
- textReadyAt: finalTextReadyAt
+ textReadyAt: finalTextReadyAt,
+ tracksDictionaryCorrections: true
)
didTypeExternally = true
if !shouldShowAIProcessingFailure, !didRequestOverlayHideOnStop {
diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swift
index 5acd775e..4261af6c 100644
--- a/Sources/Fluid/Persistence/BackupService.swift
+++ b/Sources/Fluid/Persistence/BackupService.swift
@@ -86,6 +86,7 @@ struct SettingsBackupPayload: Codable, Equatable {
let continuousDictationSpacingEnabled: Bool?
let contextAwareCapitalizationEnabled: Bool?
let pauseMediaDuringTranscription: Bool
+ let automaticDictionaryLearningEnabled: Bool?
let vocabularyBoostingEnabled: Bool
let customDictionaryEntries: [SettingsStore.CustomDictionaryEntry]
let selectedDictationPromptID: String?
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index b5aaeeef..b8e3b54d 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -2962,6 +2962,7 @@ final class SettingsStore: ObservableObject {
continuousDictationSpacingEnabled: self.continuousDictationSpacingEnabled,
contextAwareCapitalizationEnabled: self.contextAwareCapitalizationEnabled,
pauseMediaDuringTranscription: self.pauseMediaDuringTranscription,
+ automaticDictionaryLearningEnabled: self.automaticDictionaryLearningEnabled,
vocabularyBoostingEnabled: self.vocabularyBoostingEnabled,
customDictionaryEntries: self.customDictionaryEntries,
selectedDictationPromptID: self.selectedDictationPromptID,
@@ -3086,6 +3087,9 @@ final class SettingsStore: ObservableObject {
self.continuousDictationSpacingEnabled = payload.continuousDictationSpacingEnabled ?? restoredContinuousDictationModeEnabled
self.contextAwareCapitalizationEnabled = payload.contextAwareCapitalizationEnabled ?? restoredContinuousDictationModeEnabled
self.pauseMediaDuringTranscription = payload.pauseMediaDuringTranscription
+ if let automaticDictionaryLearningEnabled = payload.automaticDictionaryLearningEnabled {
+ self.automaticDictionaryLearningEnabled = automaticDictionaryLearningEnabled
+ }
self.vocabularyBoostingEnabled = payload.vocabularyBoostingEnabled
self.customDictionaryEntries = payload.customDictionaryEntries
@@ -3955,6 +3959,14 @@ final class SettingsStore: ObservableObject {
}
}
+ var automaticDictionaryLearningEnabled: Bool {
+ get { self.defaults.object(forKey: Keys.automaticDictionaryLearningEnabled) as? Bool ?? true }
+ set {
+ objectWillChange.send()
+ self.defaults.set(newValue, forKey: Keys.automaticDictionaryLearningEnabled)
+ }
+ }
+
/// Custom dictionary entries for word replacement
var customDictionaryEntries: [CustomDictionaryEntry] {
get {
@@ -4827,6 +4839,7 @@ private extension SettingsStore {
// Custom Dictionary
static let customDictionaryEntries = "CustomDictionaryEntries"
+ static let automaticDictionaryLearningEnabled = "AutomaticDictionaryLearningEnabled"
static let vocabularyBoostingEnabled = "VocabularyBoostingEnabled"
// Transcription Provider (ASR)
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 6735e281..2e0c0040 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -3313,8 +3313,6 @@ final class ASRService: ObservableObject {
}
}
- // MARK: - Typing convenience for compatibility
-
private let typingService = TypingService() // Reuse instance to avoid conflicts
func typeTextToActiveField(_ text: String) {
@@ -3328,7 +3326,8 @@ final class ASRService: ObservableObject {
func typeOutputPlanToActiveField(
_ plan: DictationLiteralOutputPlan,
preferredTargetPID: pid_t?,
- textReadyAt: TimeInterval? = nil
+ textReadyAt: TimeInterval? = nil,
+ tracksDictionaryCorrections: Bool = false
) {
let requestedAt = ProcessInfo.processInfo.systemUptime
let textReadyAge = textReadyAt.map { Int(((requestedAt - $0) * 1000).rounded()) }
@@ -3338,7 +3337,12 @@ final class ASRService: ObservableObject {
message: "asr_type_request chars=\(text.count) preferredPID=\(preferredTargetPID.map { String($0) } ?? "nil") textReadyAgeMs=\(textReadyAge.map { String($0) } ?? "nil")",
source: "TypingBenchmark"
)
- self.typingService.typeOutputPlanInstantly(plan, preferredTargetPID: preferredTargetPID, textReadyAt: textReadyAt)
+ self.typingService.typeOutputPlanInstantly(
+ plan,
+ preferredTargetPID: preferredTargetPID,
+ textReadyAt: textReadyAt,
+ tracksDictionaryCorrections: tracksDictionaryCorrections
+ )
let dispatchedAt = ProcessInfo.processInfo.systemUptime
let textReadyToDispatchMs = textReadyAt.map {
String(Int(((dispatchedAt - $0) * 1000).rounded()))
diff --git a/Sources/Fluid/Services/AppNavigationRouter.swift b/Sources/Fluid/Services/AppNavigationRouter.swift
index f71845ea..c3d65c94 100644
--- a/Sources/Fluid/Services/AppNavigationRouter.swift
+++ b/Sources/Fluid/Services/AppNavigationRouter.swift
@@ -1,19 +1,35 @@
import Foundation
+struct DictionaryTrainingPrefill: Equatable, Identifiable {
+ let id = UUID()
+ let intendedText: String
+ let capturedVariants: [String]
+}
+
enum AppNavigationDestination {
case aiEnhancements
case history
+ case customDictionaryTraining(DictionaryTrainingPrefill)
}
+@MainActor
final class AppNavigationRouter {
static let shared = AppNavigationRouter()
private var pendingDestination: AppNavigationDestination?
+ private var presentMainWindow: (() -> Void)?
private init() {}
- func request(_ destination: AppNavigationDestination) {
+ func configureWindowPresenter(_ presenter: @escaping () -> Void) {
+ self.presentMainWindow = presenter
+ }
+
+ func request(_ destination: AppNavigationDestination, presentsMainWindow: Bool = false) {
self.pendingDestination = destination
+ if presentsMainWindow {
+ self.presentMainWindow?()
+ }
NotificationCenter.default.post(name: .appNavigationRequested, object: nil)
}
diff --git a/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
new file mode 100644
index 00000000..4c8a7e5e
--- /dev/null
+++ b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
@@ -0,0 +1,616 @@
+import AppKit
+import ApplicationServices
+import Foundation
+
+struct AutomaticDictionaryCorrectionCandidate: Equatable, Identifiable {
+ let id = UUID()
+ let heardText: String
+ let correctedText: String
+}
+
+struct AutomaticDictionaryTextChange: Equatable {
+ let oldRange: NSRange
+ let newRange: NSRange
+}
+
+enum AutomaticDictionaryCorrectionDetector {
+ private static let edgeCharacters = CharacterSet.whitespacesAndNewlines.union(
+ CharacterSet(charactersIn: ".,!?;:\"“”‘’()[]{}")
+ )
+ private static let boundaryCharacters = CharacterSet.whitespacesAndNewlines.union(
+ CharacterSet(charactersIn: ",!?;:\"“”()[]{}<>")
+ )
+ private static let maxCandidateLength = 40
+ private static let maxCombinedLength = 70
+ private static let maxWords = 3
+
+ static func textChange(before: String, after: String) -> AutomaticDictionaryTextChange? {
+ guard before != after else { return nil }
+
+ let oldText = before as NSString
+ let newText = after as NSString
+ let sharedLength = min(oldText.length, newText.length)
+ var prefixLength = 0
+
+ while prefixLength < sharedLength,
+ oldText.character(at: prefixLength) == newText.character(at: prefixLength)
+ {
+ prefixLength += 1
+ }
+
+ var suffixLength = 0
+ let oldRemaining = oldText.length - prefixLength
+ let newRemaining = newText.length - prefixLength
+ while suffixLength < min(oldRemaining, newRemaining),
+ oldText.character(at: oldText.length - suffixLength - 1) ==
+ newText.character(at: newText.length - suffixLength - 1)
+ {
+ suffixLength += 1
+ }
+
+ return AutomaticDictionaryTextChange(
+ oldRange: NSRange(
+ location: prefixLength,
+ length: oldText.length - prefixLength - suffixLength
+ ),
+ newRange: NSRange(
+ location: prefixLength,
+ length: newText.length - prefixLength - suffixLength
+ )
+ )
+ }
+
+ static func isChangeInsideInsertedRange(
+ _ change: AutomaticDictionaryTextChange,
+ insertedRange: NSRange,
+ allowsInsertionAtEnd: Bool = false
+ ) -> Bool {
+ guard insertedRange.location != NSNotFound, insertedRange.length > 0 else { return false }
+ let insertedEnd = NSMaxRange(insertedRange)
+
+ if change.oldRange.length == 0 {
+ return change.oldRange.location >= insertedRange.location &&
+ (change.oldRange.location < insertedEnd ||
+ (allowsInsertionAtEnd && change.oldRange.location == insertedEnd))
+ }
+
+ return change.oldRange.location >= insertedRange.location &&
+ NSMaxRange(change.oldRange) <= insertedEnd
+ }
+
+ static func candidate(
+ before: String,
+ after: String,
+ insertedRange: NSRange
+ ) -> AutomaticDictionaryCorrectionCandidate? {
+ guard let change = self.textChange(before: before, after: after),
+ self.isChangeInsideInsertedRange(change, insertedRange: insertedRange)
+ else {
+ return nil
+ }
+
+ let oldTokenRange = self.expandedTokenRange(in: before, around: change.oldRange)
+ let newTokenRange = self.expandedTokenRange(in: after, around: change.newRange)
+ guard oldTokenRange.location >= insertedRange.location,
+ NSMaxRange(oldTokenRange) <= NSMaxRange(insertedRange)
+ else {
+ return nil
+ }
+
+ let heard = self.cleanedCandidate((before as NSString).substring(with: oldTokenRange))
+ let corrected = self.cleanedCandidate((after as NSString).substring(with: newTokenRange))
+ guard self.isValidCandidate(heard),
+ self.isValidCandidate(corrected),
+ heard != corrected,
+ heard.caseInsensitiveCompare(corrected) != .orderedSame,
+ heard.count + corrected.count <= self.maxCombinedLength
+ else {
+ return nil
+ }
+
+ return AutomaticDictionaryCorrectionCandidate(
+ heardText: heard,
+ correctedText: corrected
+ )
+ }
+
+ static func correctedTokenRange(before: String, after: String) -> NSRange? {
+ guard let change = self.textChange(before: before, after: after) else { return nil }
+ return self.expandedTokenRange(in: after, around: change.newRange)
+ }
+
+ static func selectionTouchesCandidate(_ selection: NSRange, candidateRange: NSRange) -> Bool {
+ guard selection.location != NSNotFound, candidateRange.location != NSNotFound else { return false }
+ if selection.length == 0 {
+ return selection.location >= candidateRange.location &&
+ selection.location <= NSMaxRange(candidateRange)
+ }
+ return NSIntersectionRange(selection, candidateRange).length > 0
+ }
+
+ static func changeContinuesCandidate(
+ _ change: AutomaticDictionaryTextChange,
+ after: String,
+ candidateRange: NSRange
+ ) -> Bool {
+ if change.oldRange.length > 0 {
+ return NSIntersectionRange(change.oldRange, candidateRange).length > 0
+ }
+
+ guard change.oldRange.location >= candidateRange.location,
+ change.oldRange.location <= NSMaxRange(candidateRange)
+ else {
+ return false
+ }
+
+ guard change.oldRange.location == NSMaxRange(candidateRange) else { return true }
+ let text = after as NSString
+ guard change.newRange.location != NSNotFound,
+ NSMaxRange(change.newRange) <= text.length
+ else {
+ return false
+ }
+ let insertedText = text.substring(with: change.newRange)
+ return insertedText.unicodeScalars.allSatisfy { !self.boundaryCharacters.contains($0) }
+ }
+
+ private static func expandedTokenRange(in text: String, around range: NSRange) -> NSRange {
+ let nsText = text as NSString
+ let safeLocation = max(0, min(range.location, nsText.length))
+ let safeEnd = max(safeLocation, min(NSMaxRange(range), nsText.length))
+ var start = safeLocation
+ var end = safeEnd
+
+ while start > 0, !self.isBoundary(nsText.character(at: start - 1)) {
+ start -= 1
+ }
+ while end < nsText.length, !self.isBoundary(nsText.character(at: end)) {
+ end += 1
+ }
+
+ return NSRange(location: start, length: end - start)
+ }
+
+ private static func isBoundary(_ character: unichar) -> Bool {
+ guard let scalar = Unicode.Scalar(character) else { return false }
+ return self.boundaryCharacters.contains(scalar)
+ }
+
+ private static func cleanedCandidate(_ value: String) -> String {
+ value.trimmingCharacters(in: self.edgeCharacters)
+ }
+
+ private static func isValidCandidate(_ value: String) -> Bool {
+ guard !value.isEmpty,
+ value.count <= self.maxCandidateLength,
+ value.rangeOfCharacter(from: .alphanumerics) != nil
+ else {
+ return false
+ }
+
+ let words = value.split(whereSeparator: { $0.isWhitespace })
+ return !words.isEmpty && words.count <= self.maxWords
+ }
+}
+
+@MainActor
+final class AutomaticDictionaryCorrectionTracker {
+ static let shared = AutomaticDictionaryCorrectionTracker()
+
+ private struct InsertionSeed {
+ let element: AXUIElement
+ let pid: pid_t
+ let expectedValue: String
+ let insertedRange: NSRange
+ }
+
+ private struct PendingCorrection {
+ let id = UUID()
+ let beforeValue: String
+ var afterValue: String
+ let insertedRange: NSRange
+ var correctedRange: NSRange?
+ }
+
+ private struct ObservationSession {
+ let element: AXUIElement
+ let applicationElement: AXUIElement
+ let pid: pid_t
+ let observesSelectionChanges: Bool
+ let observesFocusChanges: Bool
+ var lastValue: String
+ var insertedRange: NSRange
+ var pendingCorrection: PendingCorrection?
+ }
+
+ private static let maximumFieldLength = 100_000
+ private static let verificationAttempts = 20
+ private static let verificationDelayNanoseconds: UInt64 = 50_000_000
+ private static let observationDurationNanoseconds: UInt64 = 30_000_000_000
+ private static let completionSignalDelayNanoseconds: UInt64 = 1_000_000_000
+ private static let inactivityFallbackNanoseconds: UInt64 = 3_000_000_000
+
+ private var observer: AXObserver?
+ private var session: ObservationSession?
+ private var verificationTask: Task<Void, Never>?
+ private var timeoutTask: Task<Void, Never>?
+ private var debounceTask: Task<Void, Never>?
+
+ private init() {}
+
+ func beginObservingInsertion(_ insertedText: String, targetPID: pid_t?) {
+ self.cancel()
+ guard SettingsStore.shared.automaticDictionaryLearningEnabled,
+ !insertedText.isEmpty
+ else {
+ return
+ }
+
+ self.verificationTask = Task { @MainActor [weak self] in
+ for _ in 0..<Self.verificationAttempts {
+ guard !Task.isCancelled, let self else { return }
+ if let seed = self.captureAnchoredInsertion(
+ insertedText: insertedText,
+ targetPID: targetPID
+ ) {
+ self.installObserver(for: seed)
+ return
+ }
+ try? await Task.sleep(nanoseconds: Self.verificationDelayNanoseconds)
+ }
+ }
+ }
+
+ func cancel() {
+ self.verificationTask?.cancel()
+ self.verificationTask = nil
+ self.timeoutTask?.cancel()
+ self.timeoutTask = nil
+ self.debounceTask?.cancel()
+ self.debounceTask = nil
+ self.removeObserver()
+ self.session = nil
+ DictionaryCorrectionOverlayController.shared.hide()
+ }
+
+ func handleObservedValueChange() {
+ guard var session = self.session,
+ let currentValue = self.stringValue(of: session.element),
+ currentValue != session.lastValue,
+ (currentValue as NSString).length <= Self.maximumFieldLength,
+ let change = AutomaticDictionaryCorrectionDetector.textChange(
+ before: session.lastValue,
+ after: currentValue
+ )
+ else {
+ return
+ }
+
+ let isInside = AutomaticDictionaryCorrectionDetector.isChangeInsideInsertedRange(
+ change,
+ insertedRange: session.insertedRange,
+ allowsInsertionAtEnd: session.pendingCorrection != nil
+ )
+
+ if var pending = session.pendingCorrection {
+ let continuesCandidate = pending.correctedRange.map {
+ AutomaticDictionaryCorrectionDetector.changeContinuesCandidate(
+ change,
+ after: currentValue,
+ candidateRange: $0
+ )
+ } ?? isInside
+
+ if continuesCandidate {
+ pending.afterValue = currentValue
+ pending.correctedRange = AutomaticDictionaryCorrectionDetector.correctedTokenRange(
+ before: pending.beforeValue,
+ after: currentValue
+ )
+ session.pendingCorrection = pending
+ session.insertedRange.length = max(
+ 0,
+ session.insertedRange.length + change.newRange.length - change.oldRange.length
+ )
+ self.scheduleCandidateEvaluation(
+ for: pending.id,
+ after: Self.inactivityFallbackNanoseconds
+ )
+ } else {
+ self.scheduleCandidateEvaluation(
+ for: pending.id,
+ after: Self.completionSignalDelayNanoseconds
+ )
+ }
+ } else if isInside {
+ let pending = PendingCorrection(
+ beforeValue: session.lastValue,
+ afterValue: currentValue,
+ insertedRange: session.insertedRange,
+ correctedRange: AutomaticDictionaryCorrectionDetector.correctedTokenRange(
+ before: session.lastValue,
+ after: currentValue
+ )
+ )
+ session.pendingCorrection = pending
+ session.insertedRange.length = max(
+ 0,
+ session.insertedRange.length + change.newRange.length - change.oldRange.length
+ )
+ self.scheduleCandidateEvaluation(
+ for: pending.id,
+ after: Self.inactivityFallbackNanoseconds
+ )
+ } else if NSMaxRange(change.oldRange) <= session.insertedRange.location {
+ session.insertedRange.location = max(
+ 0,
+ session.insertedRange.location + change.newRange.length - change.oldRange.length
+ )
+ } else if change.oldRange.location < NSMaxRange(session.insertedRange) {
+ self.cancel()
+ return
+ }
+
+ session.lastValue = currentValue
+ self.session = session
+ }
+
+ func handleObservedSelectionChange() {
+ guard let session = self.session,
+ let pending = session.pendingCorrection,
+ let correctedRange = pending.correctedRange,
+ let selection = self.selectedRange(of: session.element)
+ else {
+ return
+ }
+
+ let delay = AutomaticDictionaryCorrectionDetector.selectionTouchesCandidate(
+ selection,
+ candidateRange: correctedRange
+ ) ? Self.inactivityFallbackNanoseconds : Self.completionSignalDelayNanoseconds
+ self.scheduleCandidateEvaluation(for: pending.id, after: delay)
+ }
+
+ func handleObservedFocusChange() {
+ guard let session = self.session,
+ let pending = session.pendingCorrection,
+ let focus = self.focusedElementAndPID(),
+ focus.pid != session.pid || !CFEqual(focus.element, session.element)
+ else {
+ return
+ }
+ self.scheduleCandidateEvaluation(
+ for: pending.id,
+ after: Self.completionSignalDelayNanoseconds
+ )
+ }
+
+ private func captureAnchoredInsertion(
+ insertedText: String,
+ targetPID: pid_t?
+ ) -> InsertionSeed? {
+ guard let focus = self.focusedElementAndPID(),
+ targetPID == nil || focus.pid == targetPID,
+ let value = self.stringValue(of: focus.element),
+ (value as NSString).length <= Self.maximumFieldLength,
+ let selectedRange = self.selectedRange(of: focus.element),
+ selectedRange.length == 0
+ else {
+ return nil
+ }
+
+ let insertedLength = (insertedText as NSString).length
+ let start = selectedRange.location - insertedLength
+ guard start >= 0 else { return nil }
+ let insertedRange = NSRange(location: start, length: insertedLength)
+ guard NSMaxRange(insertedRange) <= (value as NSString).length,
+ (value as NSString).substring(with: insertedRange) == insertedText
+ else {
+ return nil
+ }
+
+ return InsertionSeed(
+ element: focus.element,
+ pid: focus.pid,
+ expectedValue: value,
+ insertedRange: insertedRange
+ )
+ }
+
+ private func installObserver(for seed: InsertionSeed) {
+ self.verificationTask = nil
+ var createdObserver: AXObserver?
+ let createResult = AXObserverCreate(seed.pid, automaticDictionaryAXObserverCallback, &createdObserver)
+ guard createResult == .success, let createdObserver else { return }
+
+ let context = Unmanaged.passUnretained(self).toOpaque()
+ let addResult = AXObserverAddNotification(
+ createdObserver,
+ seed.element,
+ kAXValueChangedNotification as CFString,
+ context
+ )
+ guard addResult == .success else { return }
+
+ let applicationElement = AXUIElementCreateApplication(seed.pid)
+ let selectionResult = AXObserverAddNotification(
+ createdObserver,
+ seed.element,
+ kAXSelectedTextChangedNotification as CFString,
+ context
+ )
+ let focusResult = AXObserverAddNotification(
+ createdObserver,
+ applicationElement,
+ kAXFocusedUIElementChangedNotification as CFString,
+ context
+ )
+
+ self.observer = createdObserver
+ self.session = ObservationSession(
+ element: seed.element,
+ applicationElement: applicationElement,
+ pid: seed.pid,
+ observesSelectionChanges: selectionResult == .success,
+ observesFocusChanges: focusResult == .success,
+ lastValue: seed.expectedValue,
+ insertedRange: seed.insertedRange,
+ pendingCorrection: nil
+ )
+ CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(createdObserver), .commonModes)
+
+ self.timeoutTask = Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: Self.observationDurationNanoseconds)
+ guard !Task.isCancelled else { return }
+ self?.cancel()
+ }
+ }
+
+ private func scheduleCandidateEvaluation(for pendingID: UUID?, after delay: UInt64) {
+ guard let pendingID else { return }
+ self.debounceTask?.cancel()
+ self.debounceTask = Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: delay)
+ guard !Task.isCancelled,
+ let self,
+ let pending = self.session?.pendingCorrection,
+ pending.id == pendingID
+ else {
+ return
+ }
+ self.evaluate(pending)
+ }
+ }
+
+ private func evaluate(_ pending: PendingCorrection) {
+ let candidate = AutomaticDictionaryCorrectionDetector.candidate(
+ before: pending.beforeValue,
+ after: pending.afterValue,
+ insertedRange: pending.insertedRange
+ )
+ self.stopObservation()
+
+ guard let candidate, !self.isAlreadySaved(candidate) else { return }
+ DictionaryCorrectionOverlayController.shared.show(candidate: candidate) {
+ let prefill = DictionaryTrainingPrefill(
+ intendedText: candidate.correctedText,
+ capturedVariants: [candidate.heardText]
+ )
+ AppNavigationRouter.shared.request(
+ .customDictionaryTraining(prefill),
+ presentsMainWindow: true
+ )
+ }
+ }
+
+ private func isAlreadySaved(_ candidate: AutomaticDictionaryCorrectionCandidate) -> Bool {
+ let trigger = candidate.heardText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ return SettingsStore.shared.customDictionaryEntries.contains { entry in
+ entry.replacement.caseInsensitiveCompare(candidate.correctedText) == .orderedSame &&
+ entry.triggers.contains {
+ $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == trigger
+ }
+ }
+ }
+
+ private func stringValue(of element: AXUIElement) -> String? {
+ var value: CFTypeRef?
+ let result = AXUIElementCopyAttributeValue(element, kAXValueAttribute as CFString, &value)
+ guard result == .success else { return nil }
+ return value as? String
+ }
+
+ private func selectedRange(of element: AXUIElement) -> NSRange? {
+ var value: CFTypeRef?
+ let result = AXUIElementCopyAttributeValue(element, kAXSelectedTextRangeAttribute as CFString, &value)
+ guard result == .success,
+ let value,
+ CFGetTypeID(value) == AXValueGetTypeID()
+ else {
+ return nil
+ }
+
+ var range = CFRange()
+ guard AXValueGetValue(unsafeBitCast(value, to: AXValue.self), .cfRange, &range),
+ range.location != kCFNotFound,
+ range.location >= 0,
+ range.length >= 0
+ else {
+ return nil
+ }
+ return NSRange(location: range.location, length: range.length)
+ }
+
+ private func focusedElementAndPID() -> (element: AXUIElement, pid: pid_t)? {
+ let systemWideElement = AXUIElementCreateSystemWide()
+ var focusedElement: CFTypeRef?
+ let result = AXUIElementCopyAttributeValue(
+ systemWideElement,
+ kAXFocusedUIElementAttribute as CFString,
+ &focusedElement
+ )
+ guard result == .success,
+ let focusedElement,
+ CFGetTypeID(focusedElement) == AXUIElementGetTypeID()
+ else {
+ return nil
+ }
+
+ let element = unsafeBitCast(focusedElement, to: AXUIElement.self)
+ var pid: pid_t = 0
+ AXUIElementGetPid(element, &pid)
+ return pid > 0 ? (element, pid) : nil
+ }
+
+ private func stopObservation() {
+ self.verificationTask?.cancel()
+ self.verificationTask = nil
+ self.timeoutTask?.cancel()
+ self.timeoutTask = nil
+ self.debounceTask?.cancel()
+ self.debounceTask = nil
+ self.removeObserver()
+ self.session = nil
+ }
+
+ private func removeObserver() {
+ guard let observer = self.observer else { return }
+ if let session = self.session {
+ AXObserverRemoveNotification(observer, session.element, kAXValueChangedNotification as CFString)
+ if session.observesSelectionChanges {
+ AXObserverRemoveNotification(
+ observer,
+ session.element,
+ kAXSelectedTextChangedNotification as CFString
+ )
+ }
+ if session.observesFocusChanges {
+ AXObserverRemoveNotification(
+ observer,
+ session.applicationElement,
+ kAXFocusedUIElementChangedNotification as CFString
+ )
+ }
+ }
+ CFRunLoopRemoveSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observer), .commonModes)
+ self.observer = nil
+ }
+}
+
+private let automaticDictionaryAXObserverCallback: AXObserverCallback = { _, _, notification, context in
+ guard let context else { return }
+
+ let tracker = Unmanaged<AutomaticDictionaryCorrectionTracker>.fromOpaque(context).takeUnretainedValue()
+ Task { @MainActor in
+ switch notification as String {
+ case kAXValueChangedNotification as String:
+ tracker.handleObservedValueChange()
+ case kAXSelectedTextChangedNotification as String:
+ tracker.handleObservedSelectionChange()
+ case kAXFocusedUIElementChangedNotification as String:
+ tracker.handleObservedFocusChange()
+ default:
+ break
+ }
+ }
+}
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index c7119af5..63dea037 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -58,6 +58,9 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
override init() {
super.init()
+ AppNavigationRouter.shared.configureWindowPresenter { [weak self] in
+ self?.openMainWindow()
+ }
// Don't setup menu bar immediately - defer until app is ready
}
@@ -216,6 +219,8 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
}
func showRecordingOverlayImmediately() {
+ AutomaticDictionaryCorrectionTracker.shared.cancel()
+
guard let asrService else {
self.overlayBench("instant_show_return reason=no_asr_service")
return
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index c52c4de6..3d76d70e 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -262,7 +262,8 @@ final class TypingService {
func typeOutputPlanInstantly(
_ plan: DictationLiteralOutputPlan,
preferredTargetPID: pid_t?,
- textReadyAt: TimeInterval?
+ textReadyAt: TimeInterval?,
+ tracksDictionaryCorrections: Bool = false
) {
let requestedAt = ProcessInfo.processInfo.systemUptime
let text = plan.plainText
@@ -329,6 +330,14 @@ final class TypingService {
self.bench(
"insert_return elapsedMs=\(Self.elapsedMs(since: insertStartedAt)) totalMs=\(Self.elapsedMs(since: requestedAt))"
)
+ if tracksDictionaryCorrections {
+ Task { @MainActor in
+ AutomaticDictionaryCorrectionTracker.shared.beginObservingInsertion(
+ text,
+ targetPID: preferredTargetPID
+ )
+ }
+ }
}
}
diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swift
index d396f6cd..c3b69dc1 100644
--- a/Sources/Fluid/UI/CustomDictionaryView.swift
+++ b/Sources/Fluid/UI/CustomDictionaryView.swift
@@ -15,6 +15,9 @@ struct CustomDictionaryView: View {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@EnvironmentObject private var appServices: AppServices
+ private let trainingPrefill: DictionaryTrainingPrefill?
+ private let onTrainingPrefillConsumed: () -> Void
+
private var asr: ASRService { self.appServices.asr }
@State private var entries: [SettingsStore.CustomDictionaryEntry] = SettingsStore.shared.customDictionaryEntries
@@ -23,6 +26,7 @@ struct CustomDictionaryView: View {
@State private var boostStatusMessage = "Add custom words for better Parakeet recognition."
@State private var boostHasError = false
+ @State private var automaticDictionaryLearningEnabled = SettingsStore.shared.automaticDictionaryLearningEnabled
@State private var vocabBoostingEnabled: Bool = SettingsStore.shared.vocabularyBoostingEnabled
@State private var isCustomWordsPresented = false
@State private var isBoostWordEditorPresented = false
@@ -58,6 +62,16 @@ struct CustomDictionaryView: View {
@State private var editingPunctuationRuleID: UUID?
@State private var punctuationAliasesText = ""
@State private var punctuationSymbolText = ""
+ @State private var appliedTrainingPrefillID: UUID?
+ @State private var programmaticTrainingReplacementKey: String?
+
+ init(
+ trainingPrefill: DictionaryTrainingPrefill? = nil,
+ onTrainingPrefillConsumed: @escaping () -> Void = {}
+ ) {
+ self.trainingPrefill = trainingPrefill
+ self.onTrainingPrefillConsumed = onTrainingPrefillConsumed
+ }
private var normalizedTrainingReplacement: String {
self.trainingReplacement.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -292,7 +306,12 @@ struct CustomDictionaryView: View {
}
.onAppear {
self.loadBoostTerms()
+ self.automaticDictionaryLearningEnabled = SettingsStore.shared.automaticDictionaryLearningEnabled
self.punctuationAutoConvertEnabled = SettingsStore.shared.autoConvertPunctuationEnabled
+ self.applyTrainingPrefillIfNeeded()
+ }
+ .onChange(of: self.trainingPrefill?.id) { _, _ in
+ self.applyTrainingPrefillIfNeeded()
}
.onDisappear {
guard self.isTrainingRecording else { return }
@@ -319,6 +338,8 @@ struct CustomDictionaryView: View {
Spacer(minLength: self.theme.metrics.spacing.md)
HStack(spacing: self.theme.metrics.spacing.sm) {
+ self.automaticLearningToggle
+
Button(action: self.importDictionary) {
Label("Import", systemImage: "square.and.arrow.down")
}
@@ -332,6 +353,49 @@ struct CustomDictionaryView: View {
}
}
+ private var automaticLearningToggle: some View {
+ HStack(spacing: self.theme.metrics.spacing.sm) {
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Auto-learn words")
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .lineLimit(1)
+
+ Text("Show notifications")
+ .font(self.theme.typography.captionSmall)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .lineLimit(1)
+ }
+
+ Toggle("Auto-learn words while typing", isOn: self.$automaticDictionaryLearningEnabled)
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .tint(self.theme.palette.accent)
+ }
+ .padding(.horizontal, 10)
+ .frame(height: 40)
+ .background(
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)
+ .fill(self.theme.palette.contentBackground.opacity(0.72))
+ .overlay(
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)
+ .stroke(
+ self.automaticDictionaryLearningEnabled
+ ? self.theme.palette.accent.opacity(0.42)
+ : self.theme.palette.cardBorder.opacity(0.3),
+ lineWidth: 1
+ )
+ )
+ )
+ .onChange(of: self.automaticDictionaryLearningEnabled) { _, newValue in
+ SettingsStore.shared.automaticDictionaryLearningEnabled = newValue
+ if !newValue {
+ AutomaticDictionaryCorrectionTracker.shared.cancel()
+ }
+ }
+ .help("Notice corrections to recent dictation and show Train by Voice suggestions.")
+ }
+
private func settingsIconTile(systemName: String) -> some View {
ZStack {
RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)
@@ -1543,6 +1607,40 @@ struct CustomDictionaryView: View {
self.composerMode = mode
}
+ private func applyTrainingPrefillIfNeeded() {
+ guard let trainingPrefill,
+ self.appliedTrainingPrefillID != trainingPrefill.id
+ else {
+ return
+ }
+
+ let intendedText = CustomDictionaryTrainingMerge.normalizedReplacement(trainingPrefill.intendedText)
+ let savedVariants = SettingsStore.shared.customDictionaryEntries
+ .filter { $0.replacement.caseInsensitiveCompare(intendedText) == .orderedSame }
+ .flatMap(\.triggers)
+ let variants = CustomDictionaryTrainingMerge.normalizedTriggers(
+ from: savedVariants + trainingPrefill.capturedVariants,
+ intendedReplacement: intendedText
+ )
+
+ self.appliedTrainingPrefillID = trainingPrefill.id
+ self.composerMode = .train
+ self.programmaticTrainingReplacementKey = intendedText.lowercased()
+ self.trainingReplacement = intendedText
+ self.trainingVariants = variants
+ self.trainingSampleCount = 0
+ self.lastTrainingOutput = ""
+ self.lastTrainingOutputIsCovered = false
+ self.consecutiveCoveredCaptures = 0
+ self.trainingStatusMessage = variants.isEmpty ? "" : "Correction loaded."
+ self.trainingHasError = false
+ self.isTrainingActive = !intendedText.isEmpty
+
+ DispatchQueue.main.async {
+ self.onTrainingPrefillConsumed()
+ }
+ }
+
private func addManualReplacementIfValid() {
guard self.canAddManualReplacement else { return }
let entry = SettingsStore.CustomDictionaryEntry(
@@ -1905,6 +2003,12 @@ struct CustomDictionaryView: View {
private func handleTrainingReplacementChange(oldValue: String, newValue: String) {
let oldKey = CustomDictionaryTrainingMerge.normalizedReplacement(oldValue).lowercased()
let newKey = CustomDictionaryTrainingMerge.normalizedReplacement(newValue).lowercased()
+ if let programmaticKey = self.programmaticTrainingReplacementKey {
+ self.programmaticTrainingReplacementKey = nil
+ if newKey == programmaticKey {
+ return
+ }
+ }
guard oldKey != newKey else { return }
self.trainingVariants = self.existingTrainingVariants(for: newValue)
diff --git a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
new file mode 100644
index 00000000..b8caee29
--- /dev/null
+++ b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
@@ -0,0 +1,271 @@
+import AppKit
+import SwiftUI
+
+@MainActor
+final class DictionaryCorrectionOverlayController {
+ static let shared = DictionaryCorrectionOverlayController()
+
+ private static let displayDurationNanoseconds: UInt64 = 5_000_000_000
+ private static let presentationDuration: TimeInterval = 0.05
+ private static let dismissalDuration: TimeInterval = 0.05
+
+ private var panel: NSPanel?
+ private var hostingView: NSHostingView<AutomaticDictionaryCorrectionOverlayView>?
+ private var dismissTask: Task<Void, Never>?
+ private var generation: UInt64 = 0
+
+ private init() {}
+
+ func show(
+ candidate: AutomaticDictionaryCorrectionCandidate,
+ onTrain: @escaping () -> Void
+ ) {
+ self.generation &+= 1
+ let currentGeneration = self.generation
+ self.dismissTask?.cancel()
+
+ let rootView = AutomaticDictionaryCorrectionOverlayView(
+ candidate: candidate,
+ displayDuration: Double(Self.displayDurationNanoseconds) / 1_000_000_000,
+ onTrain: { [weak self] in
+ self?.hide()
+ onTrain()
+ },
+ onDismiss: { [weak self] in
+ self?.hide()
+ }
+ )
+
+ if let hostingView = self.hostingView {
+ hostingView.rootView = rootView
+ } else {
+ self.createPanel(rootView: rootView)
+ }
+
+ guard let panel = self.panel, let hostingView = self.hostingView else { return }
+ let fittingSize = hostingView.fittingSize
+ hostingView.frame = NSRect(origin: .zero, size: fittingSize)
+ panel.setContentSize(fittingSize)
+ self.position(panel)
+
+ panel.alphaValue = 0
+ panel.orderFrontRegardless()
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = Self.presentationDuration
+ context.allowsImplicitAnimation = true
+ panel.animator().alphaValue = 1
+ }
+
+ self.dismissTask = Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: Self.displayDurationNanoseconds)
+ guard !Task.isCancelled,
+ let self,
+ self.generation == currentGeneration
+ else {
+ return
+ }
+ self.hide()
+ }
+ }
+
+ func hide() {
+ self.generation &+= 1
+ self.dismissTask?.cancel()
+ self.dismissTask = nil
+ guard let panel, panel.isVisible else { return }
+
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = Self.dismissalDuration
+ context.allowsImplicitAnimation = true
+ panel.animator().alphaValue = 0
+ } completionHandler: { [weak panel] in
+ panel?.orderOut(nil)
+ panel?.alphaValue = 1
+ }
+ }
+
+ private func createPanel(rootView: AutomaticDictionaryCorrectionOverlayView) {
+ let panel = NSPanel(
+ contentRect: .zero,
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered,
+ defer: false
+ )
+ panel.isFloatingPanel = true
+ panel.level = .floating
+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = true
+ panel.isMovableByWindowBackground = false
+ panel.hidesOnDeactivate = false
+ panel.animationBehavior = .none
+
+ let hostingView = NSHostingView(rootView: rootView)
+ hostingView.wantsLayer = true
+ hostingView.layer?.backgroundColor = .clear
+ panel.contentView = hostingView
+
+ self.panel = panel
+ self.hostingView = hostingView
+ }
+
+ private func position(_ panel: NSPanel) {
+ guard let screen = OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main else { return }
+ let visibleFrame = screen.visibleFrame
+ let size = panel.frame.size
+ let x = screen.frame.midX - size.width / 2
+ let requestedY = visibleFrame.minY + CGFloat(SettingsStore.shared.overlayBottomOffset)
+ let y = max(visibleFrame.minY + 10, min(requestedY, visibleFrame.maxY - size.height - 40))
+ panel.setFrameOrigin(NSPoint(x: x, y: y))
+ }
+}
+
+private struct AutomaticDictionaryCorrectionOverlayView: View {
+ let candidate: AutomaticDictionaryCorrectionCandidate
+ let displayDuration: TimeInterval
+ let onTrain: () -> Void
+ let onDismiss: () -> Void
+
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var isTrainHovered = false
+ @State private var isDismissHovered = false
+ @State private var progress: CGFloat = 1
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 7) {
+ Image(systemName: "mic.fill")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.78))
+
+ Text("Correction noticed")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(.white.opacity(0.72))
+
+ Spacer(minLength: 8)
+
+ Button(action: self.onDismiss) {
+ Image(systemName: "xmark")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(.white.opacity(self.isDismissHovered ? 0.95 : 0.68))
+ .frame(width: 24, height: 24)
+ .background(
+ Circle()
+ .fill(Color.white.opacity(self.isDismissHovered ? 0.13 : 0.06))
+ )
+ }
+ .buttonStyle(.plain)
+ .contentShape(Circle())
+ .onHover { self.isDismissHovered = $0 }
+ .help("Dismiss")
+ }
+
+ HStack(alignment: .center, spacing: 12) {
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 8) {
+ Text(self.candidate.heardText)
+ .foregroundStyle(.white.opacity(0.9))
+
+ Image(systemName: "arrow.right")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.48))
+
+ Text(self.candidate.correctedText)
+ .foregroundStyle(.white)
+ }
+ .font(.system(size: 16, weight: .semibold))
+ .lineLimit(1)
+ .minimumScaleFactor(0.78)
+
+ Text("Train FluidVoice to remember this?")
+ .font(.system(size: 11, weight: .regular))
+ .foregroundStyle(.white.opacity(0.58))
+ .lineLimit(1)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Button(action: self.onTrain) {
+ Label("Train by Voice", systemImage: "mic.fill")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.92))
+ .padding(.horizontal, 12)
+ .frame(height: 34)
+ .background(self.trainButtonBackground)
+ }
+ .buttonStyle(.plain)
+ .contentShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ .onHover { self.isTrainHovered = $0 }
+ .help("Open Train by Voice")
+ }
+ }
+ .padding(.horizontal, 14)
+ .padding(.top, 10)
+ .padding(.bottom, 12)
+ .frame(width: 440)
+ .background(self.overlayBackground)
+ .overlay(alignment: .bottomLeading) {
+ GeometryReader { proxy in
+ Capsule()
+ .fill(Color.white.opacity(0.75))
+ .frame(width: proxy.size.width * self.progress, height: 2)
+ .frame(maxHeight: .infinity, alignment: .bottom)
+ }
+ .padding(.horizontal, 14)
+ .padding(.bottom, 3)
+ .allowsHitTesting(false)
+ }
+ .preferredColorScheme(.dark)
+ .onAppear {
+ self.startProgressAnimation()
+ }
+ .onChange(of: self.candidate.id) { _, _ in
+ self.startProgressAnimation()
+ }
+ }
+
+ private func startProgressAnimation() {
+ self.progress = 1
+ guard !self.reduceMotion else { return }
+ DispatchQueue.main.async {
+ withAnimation(.linear(duration: self.displayDuration)) {
+ self.progress = 0
+ }
+ }
+ }
+
+ private var trainButtonBackground: some View {
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.isTrainHovered ? Color(red: 0.13, green: 0.13, blue: 0.16) : .black)
+ .overlay(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .strokeBorder(
+ LinearGradient(
+ colors: [
+ .white.opacity(self.isTrainHovered ? 0.38 : 0.24),
+ .white.opacity(self.isTrainHovered ? 0.22 : 0.12),
+ ],
+ startPoint: .top,
+ endPoint: .bottom
+ ),
+ lineWidth: 1
+ )
+ )
+ }
+
+ private var overlayBackground: some View {
+ RoundedRectangle(cornerRadius: 18, style: .continuous)
+ .fill(Color.black)
+ .overlay(
+ RoundedRectangle(cornerRadius: 18, style: .continuous)
+ .strokeBorder(
+ LinearGradient(
+ colors: [.white.opacity(0.15), .white.opacity(0.08)],
+ startPoint: .top,
+ endPoint: .bottom
+ ),
+ lineWidth: 1
+ )
+ )
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
index 2d5864b9..393685bb 100644
--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
@@ -772,6 +772,122 @@ final class DictationE2ETests: XCTestCase {
XCTAssertEqual(entries.first?.triggers, ["fluid voice"])
}
+ func testAutomaticDictionaryCorrectionDetectsEditedWordInsideDictation() {
+ let before = "Notes: I met Barad yesterday."
+ let after = "Notes: I met Barath yesterday."
+ let insertedRange = (before as NSString).range(of: "I met Barad yesterday.")
+
+ let candidate = AutomaticDictionaryCorrectionDetector.candidate(
+ before: before,
+ after: after,
+ insertedRange: insertedRange
+ )
+
+ XCTAssertEqual(candidate?.heardText, "Barad")
+ XCTAssertEqual(candidate?.correctedText, "Barath")
+ }
+
+ func testAutomaticDictionaryCorrectionDetectsInsertionOnlySpellingFix() {
+ let before = "Barat joined the call"
+ let after = "Barath joined the call"
+ let insertedRange = NSRange(location: 0, length: (before as NSString).length)
+
+ let candidate = AutomaticDictionaryCorrectionDetector.candidate(
+ before: before,
+ after: after,
+ insertedRange: insertedRange
+ )
+
+ XCTAssertEqual(candidate?.heardText, "Barat")
+ XCTAssertEqual(candidate?.correctedText, "Barath")
+ }
+
+ func testAutomaticDictionaryCorrectionIgnoresTypingAfterDictation() {
+ let before = "FluidVoice works"
+ let after = "FluidVoice works well"
+ let insertedRange = NSRange(location: 0, length: (before as NSString).length)
+
+ XCTAssertNil(AutomaticDictionaryCorrectionDetector.candidate(
+ before: before,
+ after: after,
+ insertedRange: insertedRange
+ ))
+ }
+
+ func testAutomaticDictionaryCorrectionAllowsContinuedCorrectionAtRangeEnd() {
+ let change = AutomaticDictionaryTextChange(
+ oldRange: NSRange(location: 5, length: 0),
+ newRange: NSRange(location: 5, length: 1)
+ )
+ let insertedRange = NSRange(location: 0, length: 5)
+
+ XCTAssertFalse(AutomaticDictionaryCorrectionDetector.isChangeInsideInsertedRange(
+ change,
+ insertedRange: insertedRange
+ ))
+ XCTAssertTrue(AutomaticDictionaryCorrectionDetector.isChangeInsideInsertedRange(
+ change,
+ insertedRange: insertedRange,
+ allowsInsertionAtEnd: true
+ ))
+ }
+
+ func testAutomaticDictionaryCorrectionKeepsWaitingWhileCaretTouchesCorrectedWord() {
+ let correctedRange = NSRange(location: 8, length: 6)
+
+ XCTAssertTrue(AutomaticDictionaryCorrectionDetector.selectionTouchesCandidate(
+ NSRange(location: 14, length: 0),
+ candidateRange: correctedRange
+ ))
+ XCTAssertFalse(AutomaticDictionaryCorrectionDetector.selectionTouchesCandidate(
+ NSRange(location: 15, length: 0),
+ candidateRange: correctedRange
+ ))
+ }
+
+ func testAutomaticDictionaryCorrectionTreatsSpaceAfterWordAsCompletion() {
+ let change = AutomaticDictionaryTextChange(
+ oldRange: NSRange(location: 6, length: 0),
+ newRange: NSRange(location: 6, length: 1)
+ )
+ let correctedRange = NSRange(location: 0, length: 6)
+
+ XCTAssertFalse(AutomaticDictionaryCorrectionDetector.changeContinuesCandidate(
+ change,
+ after: "Barath ",
+ candidateRange: correctedRange
+ ))
+ XCTAssertTrue(AutomaticDictionaryCorrectionDetector.changeContinuesCandidate(
+ change,
+ after: "Baratha",
+ candidateRange: correctedRange
+ ))
+ }
+
+ func testAutomaticDictionaryCorrectionIgnoresEditOutsideDictation() {
+ let before = "Title: I met Barad"
+ let after = "Heading: I met Barad"
+ let insertedRange = (before as NSString).range(of: "I met Barad")
+
+ XCTAssertNil(AutomaticDictionaryCorrectionDetector.candidate(
+ before: before,
+ after: after,
+ insertedRange: insertedRange
+ ))
+ }
+
+ func testAutomaticDictionaryCorrectionIgnoresCaseOnlyEdit() {
+ let before = "fluidvoice"
+ let after = "FluidVoice"
+ let insertedRange = NSRange(location: 0, length: (before as NSString).length)
+
+ XCTAssertNil(AutomaticDictionaryCorrectionDetector.candidate(
+ before: before,
+ after: after,
+ insertedRange: insertedRange
+ ))
+ }
+
func testDictionaryTransferImport_rejectsInvalidReplacementTriggerType() {
let json = """
{