Skip to content

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

fix(dictionary): preserve completed pronunciation replacements

altic-dev5457b0c125c7
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 11582e1f..4320febb 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -6840,16 +6840,18 @@ final class ASRService: ObservableObject {
/// Cache for compiled custom dictionary regexes.
/// Key: trigger word, Value: (compiled regex, escaped replacement template)
/// Cleared when dictionary entries change.
- private static var cachedDictionaryPatterns: [(regex: NSRegularExpression, template: String)] = []
+ private static var cachedDictionaryPatterns: [(regex: NSRegularExpression, template: String, canonical: NSRegularExpression?)] = []
private static var dictionaryCacheNeedsRebuild: Bool = true
/// Rebuilds the regex cache if dictionary has changed.
/// Called lazily on first apply after settings change.
private static func rebuildDictionaryCache() {
let entries = SettingsStore.shared.customDictionaryEntries
- var patterns: [(regex: NSRegularExpression, template: String)] = []
+ var patterns: [(regex: NSRegularExpression, template: String, canonical: NSRegularExpression?)] = []
for entry in entries {
+ var canonical: NSRegularExpression?
+ let replacementRange = NSRange(entry.replacement.startIndex..., in: entry.replacement)
for trigger in entry.triggers {
guard !trigger.isEmpty else { continue }
@@ -6864,7 +6866,13 @@ final class ASRService: ObservableObject {
options: .caseInsensitive
) else { continue }
- patterns.append((regex: regex, template: NSRegularExpression.escapedTemplate(for: entry.replacement)))
+ let needsProtection = regex.matches(in: entry.replacement, range: replacementRange).contains {
+ $0.range.length < replacementRange.length
+ }
+ if needsProtection, canonical == nil {
+ canonical = try? NSRegularExpression(pattern: self.dictionaryPattern(for: entry.replacement), options: .caseInsensitive)
+ }
+ patterns.append((regex: regex, template: NSRegularExpression.escapedTemplate(for: entry.replacement), canonical: needsProtection ? canonical : nil))
}
}
@@ -6926,10 +6934,11 @@ final class ASRService: ObservableObject {
// Apply cached regexes - O(n) where n = number of patterns
for pattern in self.cachedDictionaryPatterns {
- result = pattern.regex.stringByReplacingMatches(
+ result = DictionaryReplacementProtection.replacingMatches(
in: result,
- range: NSRange(result.startIndex..., in: result),
- withTemplate: pattern.template
+ regex: pattern.regex,
+ template: pattern.template,
+ canonical: pattern.canonical
)
}
diff --git a/Sources/Fluid/Services/DictionaryReplacementProtection.swift b/Sources/Fluid/Services/DictionaryReplacementProtection.swift
new file mode 100644
index 00000000..97f8e28a
--- /dev/null
+++ b/Sources/Fluid/Services/DictionaryReplacementProtection.swift
@@ -0,0 +1,42 @@
+import Foundation
+
+/// Prevents a rule from expanding a completed occurrence of its own replacement.
+/// Only rules whose output contains a partial trigger need this extra scan.
+nonisolated enum DictionaryReplacementProtection {
+ static func replacingMatches(
+ in text: String,
+ regex: NSRegularExpression,
+ template: String,
+ canonical: NSRegularExpression?
+ ) -> String {
+ let fullRange = NSRange(text.startIndex..., in: text)
+ guard let canonical else {
+ return regex.stringByReplacingMatches(in: text, range: fullRange, withTemplate: template)
+ }
+ let completed = canonical.matches(in: text, range: fullRange).map(\.range)
+ guard !completed.isEmpty else {
+ return regex.stringByReplacingMatches(in: text, range: fullRange, withTemplate: template)
+ }
+
+ var completedIndex = 0
+ let matches = regex.matches(in: text, range: fullRange).filter { match in
+ while completedIndex < completed.count, NSMaxRange(completed[completedIndex]) <= match.range.location {
+ completedIndex += 1
+ }
+ guard completedIndex < completed.count else { return true }
+ let range = completed[completedIndex]
+ let isPartialTriggerInsideCompletedOutput = range.location <= match.range.location &&
+ NSMaxRange(match.range) <= NSMaxRange(range) && match.range.length < range.length
+ return !isPartialTriggerInsideCompletedOutput
+ }
+ guard !matches.isEmpty else { return text }
+ let output = NSMutableString(string: text)
+ for match in matches.reversed() {
+ output.replaceCharacters(
+ in: match.range,
+ with: regex.replacementString(for: match, in: text, offset: 0, template: template)
+ )
+ }
+ return output as String
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
index 506d17b2..5d272084 100644
--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
@@ -3459,3 +3459,64 @@ extension DictationE2ETests {
}
#endif
}
+
+extension DictationE2ETests {
+ func testDictionaryCanonicalReplacementDoesNotExpandAgain() {
+ defer { ASRService.invalidateDictionaryCache() }
+ self.withRestoredDefaults(keys: [self.customDictionaryEntriesKey]) {
+ SettingsStore.shared.customDictionaryEntries = [
+ .init(triggers: ["fluid"], replacement: "Fluid Voice"),
+ .init(triggers: ["api"], replacement: "API Client"),
+ ]
+ ASRService.invalidateDictionaryCache()
+ XCTAssertEqual(ASRService.applyCustomDictionary("Fluid Voice and fluid"), "Fluid Voice and Fluid Voice")
+ XCTAssertEqual(ASRService.applyCustomDictionary("API Client, api!"), "API Client, API Client!")
+ XCTAssertEqual(ASRService.applyCustomDictionary("fluid voice"), "fluid voice")
+ let once = ASRService.applyCustomDictionary("fluid and api")
+ XCTAssertEqual(ASRService.applyCustomDictionary(once), once)
+ }
+ }
+}
+
+extension DictationE2ETests {
+ func testDictionaryCanonicalProtectionPreservesOtherRulesAndLiteralText() {
+ defer { ASRService.invalidateDictionaryCache() }
+ self.withRestoredDefaults(keys: [self.customDictionaryEntriesKey]) {
+ SettingsStore.shared.customDictionaryEntries = [
+ .init(triggers: ["client"], replacement: "API Client"),
+ .init(triggers: ["apí"], replacement: "$apí client"),
+ .init(triggers: ["plain"], replacement: "PLAIN"),
+ ]
+ ASRService.invalidateDictionaryCache()
+ XCTAssertEqual(ASRService.applyCustomDictionary("API Client; client"), "API Client; API Client")
+ XCTAssertEqual(ASRService.applyCustomDictionary("apí!"), "$apí client!")
+ XCTAssertEqual(ASRService.applyCustomDictionary("plain"), "PLAIN", "Whole-trigger capitalization still applies")
+ XCTAssertEqual(ASRService.applyCustomDictionary("clientele"), "clientele", "Word boundaries remain intact")
+ }
+ }
+
+ #if arch(arm64)
+ func testDictionaryCombinedRecoveryDoesNotOverwriteAcousticOutput() {
+ defer { ASRService.invalidateDictionaryCache() }
+ self.withRestoredDefaults(keys: [self.customDictionaryEntriesKey]) {
+ let entry = SettingsStore.CustomDictionaryEntry(triggers: ["fluid"], replacement: "Fluid Voice")
+ SettingsStore.shared.customDictionaryEntries = [entry]
+ ASRService.invalidateDictionaryCache()
+ let result = ASRResult(text: "fluent voice plus fluid", confidence: 1, duration: 2, processingTime: 0, tokenTimings: [
+ TokenTiming(token: "▁fluent", tokenId: 1, startTime: 0, endTime: 0.24, confidence: 1),
+ TokenTiming(token: "▁voice", tokenId: 2, startTime: 0.24, endTime: 0.48, confidence: 1),
+ TokenTiming(token: "▁plus", tokenId: 3, startTime: 0.8, endTime: 1.0, confidence: 1),
+ TokenTiming(token: "▁fluid", tokenId: 4, startTime: 1.2, endTime: 1.5, confidence: 1),
+ ])
+ let capture = PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 6, modelKey: "parakeet-v3", originalAudioID: UUID(), observedText: "fluid")
+ let profile = PronunciationDictionaryProfile(dictionaryEntryID: entry.id, label: entry.replacement, modelKey: capture.modelKey, hiddenSize: 2, enrollments: [capture])
+ let audioOnly = FluidAudioProvider.applyPronunciationMatches(result: result, matches: [PronunciationWindowMatch(prototypeIndex: 0, score: 0.95, frameRange: 0..<6)], profiles: [profile], labels: [entry.id: entry.replacement])
+ let textOnly = ASRService.applyCustomDictionary(result.text)
+ let combined = ASRService.applyCustomDictionary(audioOnly)
+ XCTAssertEqual(audioOnly, "Fluid Voice plus fluid")
+ XCTAssertEqual(textOnly, "fluent voice plus Fluid Voice")
+ XCTAssertEqual(combined, "Fluid Voice plus Fluid Voice")
+ }
+ }
+ #endif
+}
diff --git a/docs/design/original-audio-learning-implementation.md b/docs/design/original-audio-learning-implementation.md
index 68ddbd59..5dccb64f 100644
--- a/docs/design/original-audio-learning-implementation.md
+++ b/docs/design/original-audio-learning-implementation.md
@@ -34,3 +34,7 @@ An initial experiment required acoustic confirmation before applying a learned t
Evaluation scripts and raw outputs: `scratch/original-audio-learning/evaluation/`. They are local research artifacts, not production app assets. There is no guarantee of perfect accuracy, no new UI, no model-weight training, no enabling of vocabulary boosting, and no migration of every legacy voice-training adapter in this patch.
Validation status: scoped service lint is clean. Full-source format and strict lint ran; restoring unrelated formatting left 623 pre-existing lint findings, with none on the changed tracked code lines. The signed private FI build is the local packaging check; it is not a production bridge/release gate.
+
+## Composition regression follow-up
+
+A verified failure showed that `fluid -> Fluid Voice` expanded an already-correct acoustic output into `Fluid Voice Voice`. The text matcher now protects completed occurrences of a rule's own output when that output contains a partial trigger. Ordinary rules retain the existing fast path. Tests cover independent uncorrected occurrences, capitalization, word boundaries, literal replacement text, and a combined sentence where text-only and acoustic-only each miss a different occurrence. This is deterministic composition proof, not a new field-accuracy claim. All 65 affected app tests passed, and the signed private FI build succeeded.