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): add spoken formatting actions
altic-dev6b4e7de0fc46
diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swiftindex ff6139e4..e4909bbb 100644--- a/Sources/Fluid/Persistence/BackupService.swift+++ b/Sources/Fluid/Persistence/BackupService.swift@@ -90,6 +90,9 @@ struct SettingsBackupPayload: Codable, Equatable {let punctuationDictionaryPrefix: String?// swiftlint:disable:next discouraged_optional_collectionlet punctuationDictionaryRules: [SettingsStore.PunctuationDictionaryRule]?+ // Optional so backups created before spoken formatting actions still decode.+ // swiftlint:disable:next discouraged_optional_collection+ let spokenFormattingActionRules: [SettingsStore.SpokenFormattingActionRule]?let gaavModeEnabled: Boollet gaavLowercaseFirstLetterEnabled: Bool?let gaavRemoveTrailingPeriodEnabled: Bool?diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swiftindex ceae55ab..55a2f3c7 100644--- a/Sources/Fluid/Persistence/SettingsStore.swift+++ b/Sources/Fluid/Persistence/SettingsStore.swift@@ -3232,6 +3232,7 @@ final class SettingsStore: ObservableObject {literalDictationFormattingEnabled: self.literalDictationFormattingEnabled,punctuationDictionaryPrefix: self.punctuationDictionaryPrefix,punctuationDictionaryRules: self.punctuationDictionaryRules,+ spokenFormattingActionRules: self.spokenFormattingActionRules,gaavModeEnabled: self.gaavModeEnabled,gaavLowercaseFirstLetterEnabled: self.gaavLowercaseFirstLetterEnabled,gaavRemoveTrailingPeriodEnabled: self.gaavRemoveTrailingPeriodEnabled,@@ -3382,6 +3383,9 @@ final class SettingsStore: ObservableObject {if let punctuationDictionaryRules = payload.punctuationDictionaryRules {self.punctuationDictionaryRules = punctuationDictionaryRules}+ if let spokenFormattingActionRules = payload.spokenFormattingActionRules {+ self.spokenFormattingActionRules = spokenFormattingActionRules+ }let restoredGaavModeEnabled = payload.gaavModeEnabledlet restoredContinuousDictationModeEnabled = payload.continuousDictationModeEnabled ?? falseself.gaavModeEnabled = restoredGaavModeEnabled@@ -4008,6 +4012,63 @@ final class SettingsStore: ObservableObject {static let defaultPunctuationDictionaryPrefix = "literal"+ enum SpokenFormattingAction: String, Codable, CaseIterable, Identifiable {+ case newLine+ case newParagraph+ case tab+ case space++ var id: Self { self }++ var title: String {+ switch self {+ case .newLine: return "New Line"+ case .newParagraph: return "New Paragraph"+ case .tab: return "Tab"+ case .space: return "Space"+ }+ }++ var displaySymbol: String {+ switch self {+ case .newLine: return "⏎"+ case .newParagraph: return "¶"+ case .tab: return "⇥"+ case .space: return "␣"+ }+ }++ var output: String {+ switch self {+ case .newLine: return "\n"+ case .newParagraph: return "\n\n"+ case .tab: return "\t"+ case .space: return " "+ }+ }+ }++ struct SpokenFormattingActionRule: Codable, Identifiable, Hashable {+ var action: SpokenFormattingAction+ var aliases: [String]+ var isEnabled: Bool++ var id: SpokenFormattingAction { self.action }++ init(action: SpokenFormattingAction, aliases: [String], isEnabled: Bool = true) {+ self.action = action+ self.aliases = PunctuationDictionaryRule.normalizedAliases(aliases)+ self.isEnabled = isEnabled && !self.aliases.isEmpty+ }+ }++ static let defaultSpokenFormattingActionRules: [SpokenFormattingActionRule] = [+ SpokenFormattingActionRule(action: .newLine, aliases: ["new line", "next line"]),+ SpokenFormattingActionRule(action: .newParagraph, aliases: ["new paragraph", "next paragraph"]),+ SpokenFormattingActionRule(action: .tab, aliases: ["tab"]),+ SpokenFormattingActionRule(action: .space, aliases: ["space"]),+ ]+static let defaultPunctuationDictionaryRules: [PunctuationDictionaryRule] = [PunctuationDictionaryRule(aliases: ["comma"], symbol: ","),PunctuationDictionaryRule(aliases: ["period", "full stop"], symbol: "."),@@ -4162,6 +4223,68 @@ final class SettingsStore: ObservableObject {}}+ var spokenFormattingActionRules: [SpokenFormattingActionRule] {+ get {+ guard let data = defaults.data(forKey: Keys.spokenFormattingActionRules),+ let decoded = try? JSONDecoder().decode([SpokenFormattingActionRule].self, from: data)+ else {+ return Self.defaultSpokenFormattingActionRules+ }++ var rulesByAction: [SpokenFormattingAction: SpokenFormattingActionRule] = [:]+ for rule in decoded where rulesByAction[rule.action] == nil {+ rulesByAction[rule.action] = rule+ }+ let orderedRules = SpokenFormattingAction.allCases.map { action in+ guard let rule = rulesByAction[action] else {+ return Self.defaultSpokenFormattingActionRules.first { $0.action == action }+ ?? SpokenFormattingActionRule(action: action, aliases: [], isEnabled: false)+ }+ return SpokenFormattingActionRule(+ action: action,+ aliases: rule.aliases,+ isEnabled: rule.isEnabled+ )+ }+ return self.removingDuplicateSpokenFormattingAliases(from: orderedRules)+ }+ set {+ objectWillChange.send()+ var rulesByAction: [SpokenFormattingAction: SpokenFormattingActionRule] = [:]+ for rule in newValue where rulesByAction[rule.action] == nil {+ rulesByAction[rule.action] = rule+ }+ let orderedRules = SpokenFormattingAction.allCases.map { action in+ guard let rule = rulesByAction[action] else {+ return SpokenFormattingActionRule(action: action, aliases: [], isEnabled: false)+ }+ return SpokenFormattingActionRule(+ action: action,+ aliases: rule.aliases,+ isEnabled: rule.isEnabled+ )+ }+ let normalizedRules = self.removingDuplicateSpokenFormattingAliases(from: orderedRules)+ if let encoded = try? JSONEncoder().encode(normalizedRules) {+ self.defaults.set(encoded, forKey: Keys.spokenFormattingActionRules)+ }+ }+ }++ private func removingDuplicateSpokenFormattingAliases(+ from rules: [SpokenFormattingActionRule]+ ) -> [SpokenFormattingActionRule] {+ var claimedAliases = Set(self.punctuationDictionaryRules.flatMap(\.aliases))+ return rules.map { rule in+ let uniqueAliases = rule.aliases.filter { claimedAliases.insert($0).inserted }+ return SpokenFormattingActionRule(+ action: rule.action,+ aliases: uniqueAliases,+ isEnabled: rule.isEnabled+ )+ }+ }+// MARK: - GAAV Mode/// Legacy combined GAAV setting. New behavior uses the split formatting toggles below.@@ -4262,6 +4385,13 @@ final class SettingsStore: ObservableObject {self.triggers = triggers.map { $0.trimmingCharacters(in: .whitespaces).lowercased() }self.replacement = replacement}++ /// Trims padding around visible replacement text while preserving an intentional+ /// all-whitespace payload such as a newline, space, or tab.+ static func sanitizedReplacement(_ text: String) -> String {+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmed.isEmpty ? text : trimmed+ }}var vocabularyBoostingEnabled: Bool {@@ -5172,6 +5302,7 @@ private extension SettingsStore {static let literalDictationFormattingEnabled = "LiteralDictationFormattingEnabled"static let punctuationDictionaryPrefix = "PunctuationDictionaryPrefix"static let punctuationDictionaryRules = "PunctuationDictionaryRules"+ static let spokenFormattingActionRules = "SpokenFormattingActionRules"/// GAAV Mode (removes capitalization and trailing punctuation)static let gaavModeEnabled = "GAAVModeEnabled"diff --git a/Sources/Fluid/Services/ASRService+SpokenPunctuationFormatting.swift b/Sources/Fluid/Services/ASRService+SpokenPunctuationFormatting.swiftindex 37640bea..8efc08c3 100644--- a/Sources/Fluid/Services/ASRService+SpokenPunctuationFormatting.swift+++ b/Sources/Fluid/Services/ASRService+SpokenPunctuationFormatting.swift@@ -13,6 +13,7 @@ extension ASRService {text,prefix: settings.punctuationDictionaryPrefix,rules: settings.punctuationDictionaryRules,+ actionRules: settings.spokenFormattingActionRules,appName: appName,bundleID: bundleID,windowTitle: windowTitle@@ -57,6 +58,10 @@ private enum SpokenPunctuationFormatter {case spaceAroundcase toggleDoubleQuotecase toggleSingleQuote+ case lineBreak+ case paragraphBreak+ case tab+ case singleSpace}private struct PhraseRule {@@ -101,12 +106,28 @@ private enum SpokenPunctuationFormatter {guard case let .text(text) = self, !text.isEmpty else { return false }return text.allSatisfy(\.isHorizontalWhitespace)}++ var isFormattingAction: Bool {+ guard case let .punctuation(_, spacing) = self else { return false }+ switch spacing {+ case .lineBreak, .paragraphBreak, .tab, .singleSpace:+ return true+ default:+ return false+ }+ }++ var startsNewLine: Bool {+ guard case let .punctuation(_, spacing) = self else { return false }+ return spacing == .lineBreak || spacing == .paragraphBreak+ }}static func apply(_ text: String,prefix: String,rules dictionaryRules: [SettingsStore.PunctuationDictionaryRule],+ actionRules: [SettingsStore.SpokenFormattingActionRule],appName: String? = nil,bundleID: String? = nil,windowTitle: String? = nil@@ -117,7 +138,7 @@ private enum SpokenPunctuationFormatter {let context = FormattingContext(appName: appName, bundleID: bundleID, windowTitle: windowTitle)let prefixWords = self.words(in: prefix)- let phraseRules = self.makeRules(from: dictionaryRules)+ let phraseRules = self.makeRules(from: dictionaryRules) + self.makeActionRules(from: actionRules)guard !prefixWords.isEmpty, !phraseRules.isEmpty else { return text }let rulesByFirstWord = self.groupedRulesByFirstWord(for: phraseRules)@@ -146,7 +167,8 @@ private enum SpokenPunctuationFormatter {}}- return self.render(self.removingGeneratedCommaNoise(from: output))+ let withoutGeneratedCommas = self.removingGeneratedCommaNoise(from: output)+ return self.render(self.removingGeneratedSentencePunctuationBesideActions(from: withoutGeneratedCommas))}private static func groupedRulesByFirstWord(for rules: [PhraseRule]) -> [String: [PhraseRule]] {@@ -169,6 +191,26 @@ private enum SpokenPunctuationFormatter {}}+ private static func makeActionRules(+ from actionRules: [SettingsStore.SpokenFormattingActionRule]+ ) -> [PhraseRule] {+ actionRules.flatMap { rule -> [PhraseRule] in+ guard rule.isEnabled, !rule.aliases.isEmpty else { return [] }+ let spacing: Spacing+ switch rule.action {+ case .newLine: spacing = .lineBreak+ case .newParagraph: spacing = .paragraphBreak+ case .tab: spacing = .tab+ case .space: spacing = .singleSpace+ }+ return self.rules(+ symbol: rule.action.output,+ spacing: spacing,+ phrases: rule.aliases+ )+ }+ }+private static func spacing(for rule: SettingsStore.PunctuationDictionaryRule) -> Spacing {let aliases = Set(rule.aliases)@@ -778,6 +820,57 @@ private enum SpokenPunctuationFormatter {return result}+ private static func removingGeneratedSentencePunctuationBesideActions(from parts: [OutputPart]) -> [OutputPart] {+ var cleaned = parts+ for index in cleaned.indices where cleaned[index].isFormattingAction {+ if index > cleaned.startIndex, case let .text(text) = cleaned[index - 1] {+ cleaned[index - 1] = .text(self.removingTrailingGeneratedPeriod(from: text))+ }+ if index + 1 < cleaned.endIndex, case let .text(text) = cleaned[index + 1] {+ cleaned[index + 1] = .text(+ self.removingLeadingGeneratedPunctuation(+ from: text,+ includesComma: cleaned[index].startsNewLine+ )+ )+ }+ }+ return cleaned+ }++ private static func removingTrailingGeneratedPeriod(from text: String) -> String {+ var cleaned = text+ while cleaned.last?.isHorizontalWhitespace == true {+ cleaned.removeLast()+ }+ guard cleaned.last == "." else { return text }+ let periodIndex = cleaned.index(before: cleaned.endIndex)+ guard periodIndex == cleaned.startIndex || cleaned[cleaned.index(before: periodIndex)] != "." else {+ return text+ }+ cleaned.removeLast()+ return cleaned+ }++ private static func removingLeadingGeneratedPunctuation(from text: String, includesComma: Bool) -> String {+ var punctuationIndex = text.startIndex+ while punctuationIndex < text.endIndex, text[punctuationIndex].isHorizontalWhitespace {+ punctuationIndex = text.index(after: punctuationIndex)+ }+ guard punctuationIndex < text.endIndex else { return text }+ let punctuation = text[punctuationIndex]+ guard punctuation == "." || (includesComma && punctuation == ",") else { return text }++ let afterPunctuation = text.index(after: punctuationIndex)+ guard afterPunctuation == text.endIndex || text[afterPunctuation] != punctuation else { return text }++ var remainderStart = afterPunctuation+ while remainderStart < text.endIndex, text[remainderStart].isHorizontalWhitespace {+ remainderStart = text.index(after: remainderStart)+ }+ return String(text[remainderStart...])+ }+private static func shouldRemoveGeneratedComma(at index: Int, in parts: [OutputPart]) -> Bool {let previous = self.significantPart(before: index, in: parts)let next = self.significantPart(after: index, in: parts)@@ -884,6 +977,22 @@ private enum SpokenPunctuationFormatter {if self.hasFollowingNonWhitespacePart(in: parts, from: index) {result += " "}+ case .lineBreak:+ self.removeTrailingHorizontalWhitespace(from: &result)+ result += "\n"+ index = self.indexSkippingWhitespace(after: index, in: parts)+ case .paragraphBreak:+ self.removeTrailingHorizontalWhitespace(from: &result)+ result += "\n\n"+ index = self.indexSkippingWhitespace(after: index, in: parts)+ case .tab:+ self.removeTrailingHorizontalWhitespace(from: &result)+ result += "\t"+ index = self.indexSkippingWhitespace(after: index, in: parts)+ case .singleSpace:+ self.removeTrailingHorizontalWhitespace(from: &result)+ result += " "+ index = self.indexSkippingWhitespace(after: index, in: parts)case .toggleDoubleQuote, .toggleSingleQuote:index += 1}diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex 5b5c111e..adf32c1e 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -4576,7 +4576,12 @@ final class ASRService: ObservableObject {for trigger in entry.triggers {guard !trigger.isEmpty else { continue }- let escapedTrigger = self.dictionaryPattern(for: trigger)+ let consumesHorizontalSeparators = !entry.replacement.isEmpty &&+ entry.replacement.allSatisfy(\.isWhitespace)+ let escapedTrigger = self.dictionaryPattern(+ for: trigger,+ consumesHorizontalSeparators: consumesHorizontalSeparators+ )guard let regex = try? NSRegularExpression(pattern: escapedTrigger,options: .caseInsensitive@@ -4592,11 +4597,15 @@ final class ASRService: ObservableObject {self.dictionaryCacheNeedsRebuild = false}- private static func dictionaryPattern(for trigger: String) -> String {+ private static func dictionaryPattern(+ for trigger: String,+ consumesHorizontalSeparators: Bool = false+ ) -> String {let escapedTrigger = NSRegularExpression.escapedPattern(for: trigger)let prefix = self.startsWithWordCharacter(trigger) ? "\\b" : ""let suffix = self.endsWithWordCharacter(trigger) ? "\\b" : ""- return prefix + escapedTrigger + suffix+ let separator = consumesHorizontalSeparators ? "[ \\t]*" : ""+ return separator + prefix + escapedTrigger + suffix + separator}private static func startsWithWordCharacter(_ text: String) -> Bool {diff --git a/Sources/Fluid/Services/DictionaryTransferService.swift b/Sources/Fluid/Services/DictionaryTransferService.swiftindex a9f5a185..a9e8866f 100644--- a/Sources/Fluid/Services/DictionaryTransferService.swift+++ b/Sources/Fluid/Services/DictionaryTransferService.swift@@ -325,14 +325,14 @@ final class DictionaryTransferService {private static func exportReplacement(from entry: SettingsStore.CustomDictionaryEntry) -> DictionaryTransferReplacement? {let from = self.normalizedUniqueStrings(entry.triggers, lowercased: true)- let to = entry.replacement.trimmingCharacters(in: .whitespacesAndNewlines)+ let to = SettingsStore.CustomDictionaryEntry.sanitizedReplacement(entry.replacement)guard !from.isEmpty, !to.isEmpty else { return nil }return DictionaryTransferReplacement(from: from, to: to)}private static func exportReplacement(from replacement: DictionaryTransferReplacement) -> DictionaryTransferReplacement? {let from = self.normalizedUniqueStrings(replacement.from, lowercased: true)- let to = replacement.to.trimmingCharacters(in: .whitespacesAndNewlines)+ let to = SettingsStore.CustomDictionaryEntry.sanitizedReplacement(replacement.to)guard !from.isEmpty, !to.isEmpty else { return nil }return DictionaryTransferReplacement(from: from, to: to)}@@ -341,7 +341,7 @@ final class DictionaryTransferService {from replacement: DictionaryTransferReplacement) -> SettingsStore.CustomDictionaryEntry? {let from = self.normalizedUniqueStrings(replacement.from, lowercased: true)- let to = replacement.to.trimmingCharacters(in: .whitespacesAndNewlines)+ let to = SettingsStore.CustomDictionaryEntry.sanitizedReplacement(replacement.to)guard !from.isEmpty, !to.isEmpty else { return nil }return SettingsStore.CustomDictionaryEntry(triggers: from, replacement: to)}diff --git a/Sources/Fluid/Services/LocalAPI/DictionaryAPIController.swift b/Sources/Fluid/Services/LocalAPI/DictionaryAPIController.swiftindex 99641ae9..10e63b43 100644--- a/Sources/Fluid/Services/LocalAPI/DictionaryAPIController.swift+++ b/Sources/Fluid/Services/LocalAPI/DictionaryAPIController.swift@@ -136,7 +136,7 @@ struct DictionaryAPIController: LocalAPIRouteHandler {for entry in incoming {let normalized = Self.storeEntry(from: entry)guard !normalized.triggers.isEmpty,- !normalized.replacement.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ !SettingsStore.CustomDictionaryEntry.sanitizedReplacement(normalized.replacement).isEmptyelse {continue}diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swiftindex cea4ec2a..d151292b 100644--- a/Sources/Fluid/UI/CustomDictionaryView.swift+++ b/Sources/Fluid/UI/CustomDictionaryView.swift@@ -10,6 +10,8 @@ import AppKitimport SwiftUIimport UniformTypeIdentifiers+// This legacy screen still owns several dictionary editors; split them into standalone views incrementally.+// swiftlint:disable:next type_body_lengthstruct CustomDictionaryView: View {@Environment(\.theme) private var theme@Environment(\.accessibilityReduceMotion) private var reduceMotion@@ -56,6 +58,10 @@ struct CustomDictionaryView: View {@State private var punctuationAutoConvertEnabled = SettingsStore.shared.autoConvertPunctuationEnabled@State private var punctuationPrefix = SettingsStore.shared.punctuationDictionaryPrefix@State private var punctuationRules = SettingsStore.shared.punctuationDictionaryRules+ @State private var formattingActionRules = SettingsStore.shared.spokenFormattingActionRules+ @State private var editingFormattingAction: SettingsStore.SpokenFormattingAction?+ @State private var formattingActionAliasesText = ""+ @State private var isFormattingResetAlertPresented = false@State private var isPunctuationInfoExpanded = false@State private var isPunctuationRuleEditorPresented = false@State private var editingPunctuationRuleID: UUID?@@ -304,6 +310,7 @@ struct CustomDictionaryView: View {SettingsStore.shared.pronunciationMatchingEnabled = false}self.punctuationAutoConvertEnabled = SettingsStore.shared.autoConvertPunctuationEnabled+ self.formattingActionRules = SettingsStore.shared.spokenFormattingActionRules}.onReceive(NotificationCenter.default.publisher(for: .parakeetVocabularyDidChange)) { _ inself.entries = SettingsStore.shared.customDictionaryEntries@@ -900,15 +907,13 @@ struct CustomDictionaryView: View {VStack(alignment: .leading, spacing: 3) {HStack(spacing: 6) {- Text("Punctuation Dictionary")+ Text("Spoken Formatting").font(self.theme.typography.sectionTitle)- if !self.punctuationRules.isEmpty {- Text("(\(self.punctuationRules.count))")- .font(self.theme.typography.captionSmall)- .foregroundStyle(self.theme.palette.tertiaryText)- }+ Text("\(SettingsStore.SpokenFormattingAction.allCases.count) actions · \(self.punctuationRules.count) punctuation")+ .font(self.theme.typography.captionSmall)+ .foregroundStyle(self.theme.palette.tertiaryText)}- Text("Say a start word first, then a punctuation name, to type punctuation symbols.")+ Text("Use a start word to safely insert formatting actions, punctuation, and symbols.").font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)}@@ -930,9 +935,7 @@ struct CustomDictionaryView: View {}.frame(width: Self.DictionaryHeaderControlLayout.actionButtonWidth).fluidButton(.compact, size: .medium)- .disabled(!self.punctuationAutoConvertEnabled)- .opacity(self.punctuationAutoConvertEnabled ? 1 : 0.45)- .help(self.punctuationAutoConvertEnabled ? "Modify punctuation rules" : "Turn on Punctuation Dictionary to modify rules.")+ .help("Modify spoken formatting").popover(isPresented: self.$isPunctuationDictionaryPresented, arrowEdge: .top) {self.punctuationDictionaryPopover}@@ -943,14 +946,14 @@ struct CustomDictionaryView: View {}private var punctuationDictionaryToggle: some View {- Toggle("Punctuation Dictionary", isOn: self.$punctuationAutoConvertEnabled)+ Toggle("Spoken Formatting", isOn: self.$punctuationAutoConvertEnabled).labelsHidden().toggleStyle(.switch).onChange(of: self.punctuationAutoConvertEnabled) { _, newValue inSettingsStore.shared.autoConvertPunctuationEnabled = newValue}.frame(width: Self.DictionaryHeaderControlLayout.toggleColumnWidth, alignment: .trailing)- .help("Turn Punctuation Dictionary on or off.")+ .help("Turn Spoken Formatting on or off.")}private var entriesListView: some View {@@ -1263,11 +1266,11 @@ struct CustomDictionaryView: View {}private var punctuationDictionaryPopover: some View {- VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {+ VStack(alignment: .leading, spacing: 0) {HStack(alignment: .top, spacing: self.theme.metrics.spacing.md) {VStack(alignment: .leading, spacing: 4) {HStack(spacing: 8) {- Text("Punctuation Dictionary")+ Text("Spoken Formatting").font(self.theme.typography.sectionTitle)Button {@@ -1280,11 +1283,11 @@ struct CustomDictionaryView: View {.frame(width: 28, height: 28)}.buttonStyle(SquareIconButtonStyle())- .help("About punctuation rules")- .accessibilityLabel("About punctuation rules")+ .help("About spoken formatting")+ .accessibilityLabel("About spoken formatting")}- Text("Say the start word first, then the punctuation name you want to type.")+ Text("Use one start word for formatting actions, punctuation, and symbols.").font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)}@@ -1301,101 +1304,278 @@ struct CustomDictionaryView: View {.buttonStyle(SquareIconButtonStyle()).help("Close")}+ .padding(.horizontal, self.theme.metrics.spacing.lg)+ .padding(.top, self.theme.metrics.spacing.lg)+ .padding(.bottom, self.theme.metrics.spacing.md)++ ScrollView(.vertical, showsIndicators: true) {+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {+ self.spokenFormattingStatusRow++ if self.isPunctuationInfoExpanded {+ self.punctuationDictionaryInfoPanel+ }++ HStack(alignment: .top, spacing: self.theme.metrics.spacing.md) {+ VStack(alignment: .leading, spacing: 6) {+ Text("Start Word")+ .font(self.theme.typography.captionStrong)+ Text("Say this first so normal words do not change.")+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.secondaryText)+ TextField("literal", text: self.$punctuationPrefix)+ .dictionaryInputChrome()+ .onSubmit { self.savePunctuationDictionaryPrefix() }+ }+ .frame(maxWidth: .infinity, alignment: .topLeading)++ VStack(alignment: .leading, spacing: 6) {+ Text("Try Saying")+ .font(self.theme.typography.captionStrong)+ Text("Examples of what FluidVoice will type.")+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.secondaryText)+ self.punctuationTrySayingPreview+ }+ .frame(maxWidth: .infinity, alignment: .topLeading)+ }++ self.formattingActionsSection+ self.punctuationRulesSection++ HStack {+ Spacer()+ Button("Reset All Defaults") {+ self.isFormattingResetAlertPresented = true+ }+ .fluidButton(.compact, size: .compact)+ }+ }+ .padding(.horizontal, self.theme.metrics.spacing.lg)+ .padding(.bottom, self.theme.metrics.spacing.lg)+ }+ .frame(maxHeight: 650)+ }+ .frame(width: 680, alignment: .leading)+ .onDisappear {+ self.savePunctuationDictionaryPrefix()+ }+ .alert(+ "Reset Spoken Formatting?",+ isPresented: self.$isFormattingResetAlertPresented+ ) {+ Button("Reset All Defaults", role: .destructive) {+ self.resetPunctuationDictionary()+ }+ Button("Cancel", role: .cancel) {}+ } message: {+ Text("This replaces the start word, formatting action phrases and enabled states, and every punctuation rule with their defaults.")+ }+ }++ private var spokenFormattingStatusRow: some View {+ HStack(spacing: self.theme.metrics.spacing.md) {+ Image(systemName: self.punctuationAutoConvertEnabled ? "checkmark.circle.fill" : "pause.circle.fill")+ .foregroundStyle(+ self.punctuationAutoConvertEnabled+ ? self.theme.palette.accent+ : self.theme.palette.secondaryText+ )- if self.isPunctuationInfoExpanded {- self.punctuationDictionaryInfoPanel+ VStack(alignment: .leading, spacing: 2) {+ Text(self.punctuationAutoConvertEnabled ? "Spoken Formatting is On" : "Spoken Formatting is Off")+ .font(self.theme.typography.bodySmallStrong)+ Text(+ self.punctuationAutoConvertEnabled+ ? "Formatting actions and punctuation will run after the start word."+ : "Your rules stay saved, but they will not change dictated text."+ )+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.secondaryText)}- HStack(alignment: .top, spacing: self.theme.metrics.spacing.md) {- VStack(alignment: .leading, spacing: 6) {- Text("Start Word")- .font(self.theme.typography.captionStrong)- Text("Say this first so normal words do not change.")- .font(self.theme.typography.caption)- .foregroundStyle(self.theme.palette.secondaryText)- TextField("literal", text: self.$punctuationPrefix)- .dictionaryInputChrome()- .onSubmit { self.savePunctuationDictionaryPrefix() }+ Spacer()++ Toggle("Spoken Formatting", isOn: self.$punctuationAutoConvertEnabled)+ .labelsHidden()+ .toggleStyle(.switch)+ .tint(self.theme.palette.accent)+ .accessibilityLabel("Spoken Formatting")+ .onChange(of: self.punctuationAutoConvertEnabled) { _, newValue in+ SettingsStore.shared.autoConvertPunctuationEnabled = newValue+ }+ }+ .padding(self.theme.metrics.spacing.md)+ .background(+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)+ .fill(self.theme.palette.contentBackground.opacity(0.5))+ .overlay(+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)+ .stroke(self.theme.palette.cardBorder.opacity(0.25), lineWidth: 1)+ )+ )+ }++ private var formattingActionsSection: some View {+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {+ VStack(alignment: .leading, spacing: 2) {+ Text("Formatting Actions")+ .font(self.theme.typography.bodySmallStrong)+ Text("Fixed invisible actions with spoken phrases you can personalize.")+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.secondaryText)+ }++ VStack(spacing: self.theme.metrics.spacing.sm) {+ ForEach(SettingsStore.SpokenFormattingAction.allCases) { action in+ self.formattingActionRow(action)}- .frame(maxWidth: .infinity, alignment: .topLeading)+ }- VStack(alignment: .leading, spacing: 6) {- Text("Try Saying")- .font(self.theme.typography.captionStrong)- Text("Examples of what FluidVoice will type.")+ if let action = self.editingFormattingAction {+ self.formattingActionEditor(action)+ }+ }+ }++ private var punctuationRulesSection: some View {+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {+ HStack(alignment: .center) {+ VStack(alignment: .leading, spacing: 2) {+ Text("Punctuation")+ .font(self.theme.typography.bodySmallStrong)+ Text("Spoken names that type punctuation or symbols after the start word.").font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)- self.punctuationTrySayingPreview}- .frame(maxWidth: .infinity, alignment: .topLeading)- }- if self.isPunctuationRuleEditorPresented {- self.punctuationRuleEditor- } else {- HStack {+ Spacer()++ if !self.isPunctuationRuleEditorPresented {Button {self.startAddingPunctuationRule()} label: {Label("Add Rule", systemImage: "plus")}.fluidButton(.accent, size: .small)-- Spacer()}}- VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {- VStack(alignment: .leading, spacing: 2) {- Text("Saved Rules")- .font(self.theme.typography.captionStrong)- Text("After the start word, these spoken versions type the punctuation symbol.")- .font(self.theme.typography.caption)- .foregroundStyle(self.theme.palette.secondaryText)- }+ if self.isPunctuationRuleEditorPresented {+ self.punctuationRuleEditor+ }- if self.punctuationRules.isEmpty {- self.dictionaryEmptyState(- title: "No punctuation rules",- detail: "Add what you say and what FluidVoice should type."- )- } else {- ScrollView(.vertical, showsIndicators: true) {- VStack(spacing: self.theme.metrics.spacing.sm) {- ForEach(self.punctuationRules) { rule in- PunctuationDictionaryRuleRow(- rule: rule,- onEdit: { self.editPunctuationRule(rule) },- onDelete: { self.deletePunctuationRule(rule) }- )- }- }+ if self.punctuationRules.isEmpty {+ self.dictionaryEmptyState(+ title: "No punctuation rules",+ detail: "Add what you say and what FluidVoice should type."+ )+ } else {+ LazyVStack(spacing: self.theme.metrics.spacing.sm) {+ ForEach(self.punctuationRules) { rule in+ PunctuationDictionaryRuleRow(+ rule: rule,+ onEdit: { self.editPunctuationRule(rule) },+ onDelete: { self.deletePunctuationRule(rule) }+ )}- .frame(maxHeight: 235)}}+ }+ }++ private func formattingActionRow(_ action: SettingsStore.SpokenFormattingAction) -> some View {+ let rule = self.formattingActionRule(for: action)+ return HStack(spacing: self.theme.metrics.spacing.md) {+ Text(action.displaySymbol)+ .font(.system(size: 18, weight: .semibold, design: .rounded))+ .foregroundStyle(self.theme.palette.accent)+ .frame(width: 32, height: 32)+ .background(+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm, style: .continuous)+ .fill(self.theme.palette.contentBackground.opacity(0.7))+ )++ VStack(alignment: .leading, spacing: 2) {+ Text(action.title)+ .font(self.theme.typography.bodySmallStrong)+ Text(rule.aliases.isEmpty ? "No spoken phrases set" : rule.aliases.joined(separator: ", "))+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.secondaryText)+ .lineLimit(1)+ }++ Spacer(minLength: self.theme.metrics.spacing.md)++ Button("Edit") {+ self.startEditingFormattingAction(action)+ }+ .fluidButton(.compact, size: .compact)++ Toggle(action.title, isOn: self.formattingActionEnabledBinding(for: action))+ .labelsHidden()+ .toggleStyle(.switch)+ .tint(self.theme.palette.accent)+ .disabled(rule.aliases.isEmpty)+ .help(rule.aliases.isEmpty ? "Add a spoken phrase before enabling this action." : "Enable \(action.title)")+ }+ .padding(.horizontal, self.theme.metrics.spacing.md)+ .padding(.vertical, 8)+ .background(+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)+ .fill(self.theme.palette.contentBackground.opacity(0.5))+ .overlay(+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)+ .stroke(self.theme.palette.cardBorder.opacity(0.25), lineWidth: 1)+ )+ )+ }++ private func formattingActionEditor(_ action: SettingsStore.SpokenFormattingAction) -> some View {+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {+ Text("Edit \(action.title) Phrases")+ .font(self.theme.typography.captionStrong)+ Text("Enter one phrase per line. Clearing every phrase disables this action.")+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.secondaryText)++ TextEditor(text: self.$formattingActionAliasesText)+ .font(self.theme.typography.bodySmall)+ .frame(minHeight: 68, maxHeight: 92)+ .scrollContentBackground(.hidden)+ .dictionaryInputChrome(minHeight: 68)+ .accessibilityLabel("Spoken phrases for \(action.title)")HStack {Spacer()- Button("Reset Defaults") {- self.resetPunctuationDictionary()+ Button("Cancel") {+ self.dismissFormattingActionEditor()}.fluidButton(.compact, size: .compact)++ Button("Save Phrases") {+ self.saveFormattingActionAliases(action)+ }+ .fluidButton(.accent, size: .small)}}- .padding(self.theme.metrics.spacing.lg)- .frame(width: 640, alignment: .leading)- .onDisappear {- self.savePunctuationDictionaryPrefix()- }+ .padding(self.theme.metrics.spacing.md)+ .background(+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)+ .fill(self.theme.palette.contentBackground.opacity(0.5))+ .overlay(+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)+ .stroke(self.theme.palette.accent.opacity(0.35), lineWidth: 1)+ )+ )}private var punctuationDictionaryInfoPanel: some View {VStack(alignment: .leading, spacing: 6) {- Text("Say the start word first, then say the punctuation name.")+ Text("Say the start word first, then a formatting action or punctuation name.")+ Text("When you say \"\(self.punctuationPreviewPrefix) next line\", it starts a new line.")Text("When you say \"\(self.punctuationPreviewPrefix) comma\", it types \",\".")- Text("When you say \"\(self.punctuationPreviewPrefix) question mark\", it types \"?\".")- Text("For each rule, add one spoken version per line. Then choose what FluidVoice types.")+ Text("Add one spoken phrase per line. Formatting actions always keep their fixed output.")}.font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)@@ -1419,8 +1599,8 @@ struct CustomDictionaryView: View {typed: ",")self.punctuationExampleText(- spoken: "\(self.punctuationPreviewPrefix) question mark",- typed: "?"+ spoken: "\(self.punctuationPreviewPrefix) next line",+ typed: "New Line")}.font(self.theme.typography.caption)@@ -1626,7 +1806,9 @@ struct CustomDictionaryView: View {private func presentPunctuationDictionary() {self.punctuationPrefix = SettingsStore.shared.punctuationDictionaryPrefixself.punctuationRules = SettingsStore.shared.punctuationDictionaryRules+ self.formattingActionRules = SettingsStore.shared.spokenFormattingActionRulesself.isPunctuationInfoExpanded = false+ self.dismissFormattingActionEditor()self.dismissPunctuationRuleEditor()self.isPunctuationDictionaryPresented = true}@@ -1647,6 +1829,55 @@ struct CustomDictionaryView: View {self.punctuationRules = SettingsStore.shared.punctuationDictionaryRules}+ private func formattingActionRule(+ for action: SettingsStore.SpokenFormattingAction+ ) -> SettingsStore.SpokenFormattingActionRule {+ self.formattingActionRules.first { $0.action == action }+ ?? SettingsStore.SpokenFormattingActionRule(action: action, aliases: [], isEnabled: false)+ }++ private func formattingActionEnabledBinding(+ for action: SettingsStore.SpokenFormattingAction+ ) -> Binding<Bool> {+ Binding(+ get: { self.formattingActionRule(for: action).isEnabled },+ set: { isEnabled in+ guard let index = self.formattingActionRules.firstIndex(where: { $0.action == action }) else { return }+ self.formattingActionRules[index].isEnabled = isEnabled+ self.saveFormattingActionRules()+ }+ )+ }++ private func startEditingFormattingAction(_ action: SettingsStore.SpokenFormattingAction) {+ self.editingFormattingAction = action+ self.formattingActionAliasesText = self.formattingActionRule(for: action).aliases.joined(separator: "\n")+ }++ private func dismissFormattingActionEditor() {+ self.editingFormattingAction = nil+ self.formattingActionAliasesText = ""+ }++ private func saveFormattingActionAliases(_ action: SettingsStore.SpokenFormattingAction) {+ let aliases = SettingsStore.PunctuationDictionaryRule.normalizedAliases(+ self.formattingActionAliasesText.components(separatedBy: .newlines)+ )+ guard let index = self.formattingActionRules.firstIndex(where: { $0.action == action }) else { return }+ self.formattingActionRules[index] = SettingsStore.SpokenFormattingActionRule(+ action: action,+ aliases: aliases,+ isEnabled: aliases.isEmpty ? false : self.formattingActionRules[index].isEnabled+ )+ self.saveFormattingActionRules()+ self.dismissFormattingActionEditor()+ }++ private func saveFormattingActionRules() {+ SettingsStore.shared.spokenFormattingActionRules = self.formattingActionRules+ self.formattingActionRules = SettingsStore.shared.spokenFormattingActionRules+ }+private func startAddingPunctuationRule() {self.editingPunctuationRuleID = nilself.clearPunctuationRuleFields()@@ -1692,9 +1923,12 @@ struct CustomDictionaryView: View {private func resetPunctuationDictionary() {self.punctuationPrefix = SettingsStore.defaultPunctuationDictionaryPrefixself.punctuationRules = SettingsStore.defaultPunctuationDictionaryRules+ self.formattingActionRules = SettingsStore.defaultSpokenFormattingActionRules+ self.dismissFormattingActionEditor()self.dismissPunctuationRuleEditor()self.savePunctuationDictionaryPrefix()self.savePunctuationRules()+ self.saveFormattingActionRules()}private func clearPunctuationRuleFields() {@@ -2675,8 +2909,7 @@ enum CustomDictionaryManualEntry {/// A replacement that is entirely whitespace (e.g. a pasted newline or space)/// is a deliberate payload — keep it verbatim instead of trimming it to empty.static func sanitizedReplacement(_ text: String) -> String {- let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)- return trimmed.isEmpty ? text : trimmed+ SettingsStore.CustomDictionaryEntry.sanitizedReplacement(text)}/// Whitespace-only replacements render as invisible/blank text, so showdiff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swiftindex f4d03b74..3e9ac0d6 100644--- a/Sources/Fluid/UI/SettingsView.swift+++ b/Sources/Fluid/UI/SettingsView.swift@@ -917,58 +917,6 @@ struct SettingsView: View {)Divider().opacity(0.2)- self.optionToggleRow(- title: "Lowercase First Letter",- description: "Start each transcription with a lowercase letter. Useful for search queries, form fields, or casual text.",- isOn: Binding(- get: { SettingsStore.shared.gaavLowercaseFirstLetterEnabled },- set: { SettingsStore.shared.gaavLowercaseFirstLetterEnabled = $0 }- )- )- Divider().opacity(0.2)-- self.optionToggleRow(- title: "Remove Trailing Period",- description: "Drop a final period from transcriptions. Feature requested by MaxGaav.",- isOn: Binding(- get: { SettingsStore.shared.gaavRemoveTrailingPeriodEnabled },- set: { SettingsStore.shared.gaavRemoveTrailingPeriodEnabled = $0 }- )- )- Divider().opacity(0.2)-- self.optionToggleRow(- title: "Slash Commands & @ Formatting",- description: "When on, \"slash status\" becomes \"/status\"; \"tag Paul\", \"mention Paul\", \"at sign Paul\", and \"at the rate Paul\" become \"@Paul\". " +- "In chat apps, \"at Paul\" also works. Turn it off to leave all of these unchanged.",- isOn: Binding(- get: { SettingsStore.shared.literalDictationFormattingEnabled },- set: { SettingsStore.shared.literalDictationFormattingEnabled = $0 }- ),- allowsDescriptionWrapping: true- )- Divider().opacity(0.2)-- self.optionToggleRow(- title: "Space Between Dictations",- description: "Add spacing so consecutive dictations chain without manually pressing the spacebar.",- isOn: Binding(- get: { SettingsStore.shared.continuousDictationSpacingEnabled },- set: { SettingsStore.shared.continuousDictationSpacingEnabled = $0 }- )- )- Divider().opacity(0.2)-- self.optionToggleRow(- title: "Smart Capitalization",- description: "Use text before the cursor to decide whether the next dictation should start capitalized or lowercase.",- isOn: Binding(- get: { SettingsStore.shared.contextAwareCapitalizationEnabled },- set: { SettingsStore.shared.contextAwareCapitalizationEnabled = $0 }- )- )- Divider().opacity(0.2)-self.optionToggleRow(title: "Skip Silent Recordings",description: "Avoid transcription when a recording up to four seconds contains only clear silence. Disabled by default to preserve quiet speech.",@@ -1068,6 +1016,66 @@ struct SettingsView: View {.padding(16)}+ ThemedCard(style: .standard) {+ VStack(alignment: .leading, spacing: 14) {+ Label("Text Formatting", systemImage: "textformat")+ .font(.headline)+ .foregroundStyle(.primary)++ VStack(spacing: 16) {+ self.settingsToggleRow(+ title: "Lowercase First Letter",+ description: "Start each transcription with a lowercase letter.",+ isOn: Binding(+ get: { self.settings.gaavLowercaseFirstLetterEnabled },+ set: { self.settings.gaavLowercaseFirstLetterEnabled = $0 }+ )+ )+ Divider().opacity(0.2)++ self.settingsToggleRow(+ title: "Remove Trailing Period",+ description: "Drop a final period from transcriptions.",+ isOn: Binding(+ get: { self.settings.gaavRemoveTrailingPeriodEnabled },+ set: { self.settings.gaavRemoveTrailingPeriodEnabled = $0 }+ )+ )+ Divider().opacity(0.2)++ self.settingsToggleRow(+ title: "Slash Commands & @ Formatting",+ description: "Convert spoken slash commands and supported @ mentions into symbols.",+ isOn: Binding(+ get: { self.settings.literalDictationFormattingEnabled },+ set: { self.settings.literalDictationFormattingEnabled = $0 }+ )+ )+ Divider().opacity(0.2)++ self.settingsToggleRow(+ title: "Space Between Dictations",+ description: "Add spacing when consecutive dictations are joined.",+ isOn: Binding(+ get: { self.settings.continuousDictationSpacingEnabled },+ set: { self.settings.continuousDictationSpacingEnabled = $0 }+ )+ )+ Divider().opacity(0.2)++ self.settingsToggleRow(+ title: "Smart Capitalization",+ description: "Use text before the cursor to choose uppercase or lowercase.",+ isOn: Binding(+ get: { self.settings.contextAwareCapitalizationEnabled },+ set: { self.settings.contextAwareCapitalizationEnabled = $0 }+ )+ )+ }+ }+ .padding(16)+ }+// Notification Settings CardThemedCard(style: .standard) {VStack(alignment: .leading, spacing: 14) {@@ -1821,10 +1829,11 @@ struct SettingsView: View {Spacer()- Toggle("", isOn: isOn)+ Toggle(title, isOn: isOn).toggleStyle(.switch).tint(self.theme.palette.accent).labelsHidden()+ .accessibilityLabel(title)}if let footnote = footnote {diff --git a/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift b/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swiftindex 736e1446..a0c79b74 100644--- a/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift+++ b/Tests/FluidDictationIntegrationTests/CustomDictionaryManualEntryTests.swift@@ -1,6 +1,8 @@@testable import FluidVoice_Debug+import Foundationimport XCTest+@MainActorfinal class CustomDictionaryManualEntryTests: XCTestCase {func testKeepsWhitespaceOnlyReplacements() {XCTAssertEqual(CustomDictionaryManualEntry.sanitizedReplacement("\n"), "\n")@@ -18,4 +20,97 @@ final class CustomDictionaryManualEntryTests: XCTestCase {XCTAssertEqual(CustomDictionaryManualEntry.replacementDisplayText("FluidVoice"), "FluidVoice")XCTAssertEqual(CustomDictionaryManualEntry.replacementDisplayText(""), "")}++ func testWhitespaceReplacementSurvivesTransferAndReplacement() throws {+ let document = DictionaryTransferDocument(+ replacements: [DictionaryTransferReplacement(from: ["new line"], to: "\n")],+ customWords: []+ )++ let data = try DictionaryTransferService.shared.encode(document)+ let decoded = try DictionaryTransferService.shared.decode(data)+ let state = try DictionaryTransferService.importState(+ document: decoded,+ mode: .replace,+ currentReplacements: [],+ currentCustomWords: []+ )++ XCTAssertEqual(state.replacements.first?.replacement, "\n")+ self.withRestoredDictionary(state.replacements) {+ XCTAssertEqual(ASRService.applyCustomDictionary("first new line second"), "first\nsecond")+ }+ }++ func testWhitespaceReplacementsOwnAdjacentHorizontalSeparators() {+ let entries = [+ SettingsStore.CustomDictionaryEntry(triggers: ["new line"], replacement: "\n"),+ SettingsStore.CustomDictionaryEntry(triggers: ["new paragraph"], replacement: "\n\n"),+ SettingsStore.CustomDictionaryEntry(triggers: ["tab over"], replacement: "\t"),+ SettingsStore.CustomDictionaryEntry(triggers: ["little space"], replacement: " "),+ ]++ self.withRestoredDictionary(entries) {+ XCTAssertEqual(ASRService.applyCustomDictionary("first new line second"), "first\nsecond")+ XCTAssertEqual(ASRService.applyCustomDictionary("first new paragraph second"), "first\n\nsecond")+ XCTAssertEqual(ASRService.applyCustomDictionary("first tab over second"), "first\tsecond")+ XCTAssertEqual(ASRService.applyCustomDictionary("first little space second"), "first second")+ XCTAssertEqual(ASRService.applyCustomDictionary("first\n new line second"), "first\n\nsecond")+ }+ }++ func testTransferStillRejectsEmptyAndTrimsVisibleReplacement() throws {+ let document = DictionaryTransferDocument(+ replacements: [+ DictionaryTransferReplacement(from: ["empty"], to: ""),+ DictionaryTransferReplacement(from: ["fluid voice"], to: " FluidVoice \n"),+ ],+ customWords: []+ )++ let decoded = try DictionaryTransferService.shared.decode(DictionaryTransferService.shared.encode(document))++ XCTAssertEqual(decoded.replacements.count, 1)+ XCTAssertEqual(decoded.replacements.first?.to, "FluidVoice")+ }++ func testLocalAPIAcceptsWhitespaceReplacementAndRejectsEmpty() async throws {+ let body = Data(#"{"mode":"replace","entries":[{"triggers":["new line"],"replacement":"\n"},{"triggers":["empty"],"replacement":""}]}"#.utf8)+ let request = LocalAPI.Request(+ method: "POST",+ path: "/v1/dictionary/replacements",+ query: [:],+ headers: ["content-type": "application/json"],+ body: body+ )++ try await self.withRestoredDictionaryAsync {+ let response = await DictionaryAPIController().handle(request)++ XCTAssertEqual(response.status, 200)+ XCTAssertEqual(SettingsStore.shared.customDictionaryEntries.count, 1)+ XCTAssertEqual(SettingsStore.shared.customDictionaryEntries.first?.triggers, ["new line"])+ XCTAssertEqual(SettingsStore.shared.customDictionaryEntries.first?.replacement, "\n")+ }+ }++ private func withRestoredDictionary(_ entries: [SettingsStore.CustomDictionaryEntry], run: () -> Void) {+ let original = SettingsStore.shared.customDictionaryEntries+ defer {+ SettingsStore.shared.customDictionaryEntries = original+ ASRService.invalidateDictionaryCache()+ }+ SettingsStore.shared.customDictionaryEntries = entries+ ASRService.invalidateDictionaryCache()+ run()+ }++ private func withRestoredDictionaryAsync(run: () async throws -> Void) async throws {+ let original = SettingsStore.shared.customDictionaryEntries+ defer {+ SettingsStore.shared.customDictionaryEntries = original+ ASRService.invalidateDictionaryCache()+ }+ try await run()+ }}diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swiftindex aaf71efc..5481da78 100644--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift@@ -26,6 +26,7 @@ final class DictationE2ETests: XCTestCase {private let literalDictationFormattingEnabledKey = "LiteralDictationFormattingEnabled"private let punctuationDictionaryPrefixKey = "PunctuationDictionaryPrefix"private let punctuationDictionaryRulesKey = "PunctuationDictionaryRules"+ private let spokenFormattingActionRulesKey = "SpokenFormattingActionRules"private let commandModeLinkedToGlobalKey = "CommandModeLinkedToGlobal"private let commandModeSelectedProviderIDKey = "CommandModeSelectedProviderID"private let commandModeSelectedModelKey = "CommandModeSelectedModel"@@ -57,6 +58,7 @@ final class DictationE2ETests: XCTestCase {self.autoConvertPunctuationEnabledKey,self.punctuationDictionaryPrefixKey,self.punctuationDictionaryRulesKey,+ self.spokenFormattingActionRulesKey,]}@@ -599,6 +601,195 @@ final class DictationE2ETests: XCTestCase {}}+ func testSpokenFormattingActionsUseSharedPrefix() {+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {+ let settings = SettingsStore.shared+ UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)+ settings.punctuationDictionaryPrefix = "literal"+ settings.spokenFormattingActionRules = SettingsStore.defaultSpokenFormattingActionRules++ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First literal next line second"),+ "First\nsecond"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First literal next paragraph second"),+ "First\n\nsecond"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("one literal tab two"),+ "one\ttwo"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("one literal space two"),+ "one two"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First next line second"),+ "First next line second"+ )+ }+ }++ func testSpokenFormattingActionsRemoveAdjacentGeneratedPeriodsOnly() {+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {+ let settings = SettingsStore.shared+ UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)+ settings.punctuationDictionaryPrefix = "literal"+ settings.spokenFormattingActionRules = SettingsStore.defaultSpokenFormattingActionRules++ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First. literal new line. Second"),+ "First\nSecond"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First. literal new paragraph. Second"),+ "First\n\nSecond"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("one. literal tab. two"),+ "one\ttwo"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("one. literal space. two"),+ "one two"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First literal period literal new line Second"),+ "First.\nSecond"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First literal new line, Second"),+ "First\nSecond"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First literal new paragraph, Second"),+ "First\n\nSecond"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First literal new line literal comma Second"),+ "First\n, Second"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("one literal tab, two"),+ "one\t, two"+ )+ }+ }++ func testSpokenFormattingActionsCanBeCustomizedAndUnset() {+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {+ let settings = SettingsStore.shared+ UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)+ settings.spokenFormattingActionRules = [+ SettingsStore.SpokenFormattingActionRule(+ action: .newLine,+ aliases: ["drop down"]+ ),+ SettingsStore.SpokenFormattingActionRule(+ action: .tab,+ aliases: [],+ isEnabled: true+ ),+ SettingsStore.SpokenFormattingActionRule(+ action: .space,+ aliases: ["little gap"],+ isEnabled: false+ ),+ ]++ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("First literal drop down second"),+ "First\nsecond"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("literal tab"),+ "literal tab"+ )+ XCTAssertEqual(+ ASRService.applySpokenPunctuationFormatting("literal little gap"),+ "literal little gap"+ )+ }+ }++ func testSpokenFormattingActionAliasesRejectPunctuationAndActionConflicts() {+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {+ let settings = SettingsStore.shared+ settings.spokenFormattingActionRules = [+ SettingsStore.SpokenFormattingActionRule(+ action: .newLine,+ aliases: ["comma", "shared action", "drop down"]+ ),+ SettingsStore.SpokenFormattingActionRule(+ action: .newParagraph,+ aliases: ["shared action", "paragraph break"]+ ),+ ]++ let rules = settings.spokenFormattingActionRules+ XCTAssertEqual(rules.first { $0.action == .newLine }?.aliases, ["shared action", "drop down"])+ XCTAssertEqual(rules.first { $0.action == .newParagraph }?.aliases, ["paragraph break"])++ UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)+ XCTAssertEqual(ASRService.applySpokenPunctuationFormatting("literal comma"), ",")+ XCTAssertEqual(ASRService.applySpokenPunctuationFormatting("literal shared action"), "\n")+ }+ }++ func testSpokenFormattingActionRulesRoundTripAndLegacyBackupsPreserveCurrentRules() async throws {+ let defaults = UserDefaults.standard+ let originalValue = defaults.object(forKey: self.spokenFormattingActionRulesKey)+ defer {+ if let originalValue {+ defaults.set(originalValue, forKey: self.spokenFormattingActionRulesKey)+ } else {+ defaults.removeObject(forKey: self.spokenFormattingActionRulesKey)+ }+ }++ let settings = SettingsStore.shared+ let backedUpRules = [+ SettingsStore.SpokenFormattingActionRule(+ action: .newLine,+ aliases: ["line break"]+ ),+ SettingsStore.SpokenFormattingActionRule(+ action: .tab,+ aliases: ["indent"],+ isEnabled: false+ ),+ ]+ settings.spokenFormattingActionRules = backedUpRules++ let document = await BackupService.shared.makeBackupDocument()+ let encoded = try BackupService.shared.encode(document)+ let decoded = try BackupService.shared.decode(encoded)+ XCTAssertEqual(decoded.settings.spokenFormattingActionRules, settings.spokenFormattingActionRules)++ settings.spokenFormattingActionRules = SettingsStore.defaultSpokenFormattingActionRules+ settings.restore(from: decoded.settings)+ XCTAssertEqual(settings.spokenFormattingActionRules, decoded.settings.spokenFormattingActionRules)++ var root = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ var encodedSettings = try XCTUnwrap(root["settings"] as? [String: Any])+ encodedSettings.removeValue(forKey: "spokenFormattingActionRules")+ root["settings"] = encodedSettings+ let legacyBackup = try BackupService.shared.decode(JSONSerialization.data(withJSONObject: root))+ XCTAssertNil(legacyBackup.settings.spokenFormattingActionRules)++ let rulesBeforeLegacyRestore = [+ SettingsStore.SpokenFormattingActionRule(+ action: .newParagraph,+ aliases: ["keep this paragraph"]+ ),+ ]+ settings.spokenFormattingActionRules = rulesBeforeLegacyRestore+ let normalizedRulesBeforeLegacyRestore = settings.spokenFormattingActionRules+ settings.restore(from: legacyBackup.settings)+ XCTAssertEqual(settings.spokenFormattingActionRules, normalizedRulesBeforeLegacyRestore)+ }+func testTerminalLiteralAutocompleteSpacingLeavesNonAutocompleteTextAlone() {XCTAssertEqual(ASRService.applyTerminalLiteralAutocompleteSpacing(@@ -819,14 +1010,14 @@ final class DictationE2ETests: XCTestCase {let store = PronunciationDictionaryStore(fileURL: fileURL)let entryID = UUID()- let initialEnrollments = (0 ..< 8).map { value in+ let initialEnrollments = (0..<8).map { value inPronunciationEnrollmentCapture(values: [Float(value), Float(value)],sourceFrameCount: 1,modelKey: "model-a")}- let retrainedEnrollments = (8 ..< 13).map { value in+ let retrainedEnrollments = (8..<13).map { value inPronunciationEnrollmentCapture(values: [Float(value), Float(value)],sourceFrameCount: 1,@@ -849,7 +1040,7 @@ final class DictationE2ETests: XCTestCase {let profiles = await store.profiles(modelKey: "model-a")XCTAssertEqual(profiles.count, 1)- XCTAssertEqual(profiles.first?.enrollments.compactMap(\.values.first), (3 ..< 13).map { Float($0) })+ XCTAssertEqual(profiles.first?.enrollments.compactMap(\.values.first), (3..<13).map { Float($0) })}func testPronunciationStoreRestoreRejectsMalformedProfiles() async {@@ -902,9 +1093,9 @@ final class DictationE2ETests: XCTestCase {func testDictionaryTrainingAudioCursorResetsAfterBufferGenerationChange() {var cursor = DictionaryTrainingAudioCursor(generation: 4)- cursor.consume(1_600)+ cursor.consume(1600)cursor.synchronize(generation: 4)- XCTAssertEqual(cursor.sampleOffset, 1_600)+ XCTAssertEqual(cursor.sampleOffset, 1600)cursor.synchronize(generation: 5)XCTAssertEqual(cursor.sampleOffset, 0)