Skip to content

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

improve dictation formatting flow

altic-dev713bd135b47a
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 26e617e6..454b2c8d 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -45,6 +45,41 @@ enum AIProcessingError: LocalizedError {
}
}
+@MainActor
+private final class DictationAIStreamPreviewBuffer {
+ private let originalText: String
+ private var chunks: [String] = []
+ private var lastUIUpdate = CFAbsoluteTimeGetCurrent()
+ private let minimumUpdateInterval: CFTimeInterval = 0.033
+
+ init(originalText: String) {
+ self.originalText = originalText
+ }
+
+ func append(_ chunk: String) {
+ guard !chunk.isEmpty else { return }
+ self.chunks.append(chunk)
+
+ let now = CFAbsoluteTimeGetCurrent()
+ guard now - self.lastUIUpdate >= self.minimumUpdateInterval else { return }
+ self.lastUIUpdate = now
+ self.publish()
+ }
+
+ func flush() {
+ self.publish()
+ }
+
+ private func publish() {
+ let processedText = self.chunks.joined()
+ NotchContentState.shared.updateDictationAIDiffPreview(
+ originalText: self.originalText,
+ processedText: processedText
+ )
+ NotchOverlayManager.shared.updateTranscriptionText(processedText)
+ }
+}
+
// MARK: - Sidebar Item Enum
enum SidebarItem: Hashable {
@@ -1777,7 +1812,8 @@ struct ContentView: View {
private func processTextWithAI(
_ inputText: String,
overrideSystemPrompt: String? = nil,
- dictationSlot: SettingsStore.DictationShortcutSlot? = nil
+ dictationSlot: SettingsStore.DictationShortcutSlot? = nil,
+ streamHandler: PrivateAIStreamHandler? = nil
) async throws -> String {
// CRITICAL FIX: Read current settings from SettingsStore, not stale @State copies
// This ensures AI provider/model changes in AISettingsView take effect immediately
@@ -1855,7 +1891,8 @@ struct ContentView: View {
bundleID: appInfo.bundleId,
windowTitle: appInfo.windowTitle,
appVersion: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
- )
+ ),
+ streamHandler: streamHandler
)
if self.shouldTracePromptProcessing {
@@ -2012,15 +2049,10 @@ struct ContentView: View {
}
messages.append(["role": "user", "content": userMessageContent])
- // NOTE: Transcription doesn't need streaming - the full result appears at once
- // Streaming is only useful for Command/Rewrite modes where real-time display helps
- // Using non-streaming is simpler and more reliable for transcription enhancement
- let enableStreaming = false // Hardcoded off for transcription
+ let enableStreaming = streamHandler != nil
// Build LLMClient configuration
- // Note: No onContentChunk callback needed since we don't display real-time
- // Thinking tokens are extracted but not displayed (no onThinkingChunk)
- let config = LLMClient.Config(
+ var config = LLMClient.Config(
messages: messages,
model: derivedSelectedModel,
baseURL: derivedBaseURL,
@@ -2030,6 +2062,11 @@ struct ContentView: View {
temperature: isTemperatureUnsupported ? nil : 0.2,
extraParameters: extraParams
)
+ if enableStreaming {
+ config.onContentChunk = { chunk in
+ streamHandler?(chunk)
+ }
+ }
DebugLogger.shared.info("Using LLMClient for transcription (streaming=\(enableStreaming))", source: "ContentView")
@@ -2229,18 +2266,28 @@ struct ContentView: View {
// Update overlay text to show we're now refining (processing already true)
self.appBench("processing_ui_request status=Refining")
+ NotchContentState.shared.clearDictationAIDiffPreview()
NotchOverlayManager.shared.updateTranscriptionText("Refining")
self.appBench("processing_ui_requested status=Refining")
// Ensure the status label becomes visible immediately.
await Task.yield()
+ let streamPreview = DictationAIStreamPreviewBuffer(originalText: normalizedTranscribedText)
+ let streamHandler: PrivateAIStreamHandler = { chunk in
+ Task { @MainActor in
+ streamPreview.append(chunk)
+ }
+ }
+
do {
finalText = try await self.processTextWithAI(
normalizedTranscribedText,
overrideSystemPrompt: promptOverride,
- dictationSlot: activeDictationSlot
+ dictationSlot: activeDictationSlot,
+ streamHandler: streamHandler
)
+ await streamPreview.flush()
} catch {
// Fall back to the raw transcription so the user still gets
// their words typed instead of an error string.
@@ -2277,6 +2324,7 @@ struct ContentView: View {
// Clear transient status text before leaving processing state to avoid
// a brief non-shimmer "Refining..." preview flash.
+ NotchContentState.shared.clearDictationAIDiffPreview()
NotchOverlayManager.shared.updateTranscriptionText("")
} else {
diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swift
index f69a7966..4be78d15 100644
--- a/Sources/Fluid/Persistence/BackupService.swift
+++ b/Sources/Fluid/Persistence/BackupService.swift
@@ -75,6 +75,9 @@ struct SettingsBackupPayload: Codable, Equatable {
let fillerWords: [String]
let removeFillerWordsEnabled: Bool
let autoConvertPunctuationEnabled: Bool?
+ let punctuationDictionaryPrefix: String?
+ // swiftlint:disable:next discouraged_optional_collection
+ let punctuationDictionaryRules: [SettingsStore.PunctuationDictionaryRule]?
let gaavModeEnabled: Bool
let gaavLowercaseFirstLetterEnabled: Bool?
let gaavRemoveTrailingPeriodEnabled: Bool?
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index ce3860e4..46313e66 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -2191,6 +2191,7 @@ final class SettingsStore: ObservableObject {
self.defaults.set(newValue, forKey: Keys.onboardingCompleted)
if newValue {
self.defaults.set(false, forKey: Keys.manualOnboardingResetRequested)
+ self.defaults.removeObject(forKey: Keys.manualOnboardingResetRequestedAt)
}
}
}
@@ -2306,6 +2307,7 @@ final class SettingsStore: ObservableObject {
objectWillChange.send()
self.defaults.set(false, forKey: Keys.onboardingCompleted)
self.defaults.set(true, forKey: Keys.manualOnboardingResetRequested)
+ self.defaults.set(Date(), forKey: Keys.manualOnboardingResetRequestedAt)
self.defaults.set(0, forKey: Keys.onboardingCurrentStep)
self.defaults.set(false, forKey: Keys.onboardingAISkipped)
self.defaults.set(false, forKey: Keys.onboardingPlaygroundValidated)
@@ -2321,14 +2323,18 @@ final class SettingsStore: ObservableObject {
$0 < Self.forcedOnboardingResetIntroducedAt
} ?? false
let hasExistingInstallSignal = self.hasLegacyUsageSignals() || hadOpenedBeforeForcedReset
+ let hasCurrentManualReset = self.defaults.bool(forKey: Keys.manualOnboardingResetRequested)
+ && self.defaults.object(forKey: Keys.manualOnboardingResetRequestedAt) != nil
guard self.defaults.object(forKey: Keys.onboardingGeneration) != nil,
self.defaults.bool(forKey: Keys.onboardingCompleted) == false,
- self.defaults.bool(forKey: Keys.manualOnboardingResetRequested) == false,
+ !hasCurrentManualReset,
hasExistingInstallSignal
else { return }
objectWillChange.send()
self.defaults.set(true, forKey: Keys.onboardingCompleted)
+ self.defaults.set(false, forKey: Keys.manualOnboardingResetRequested)
+ self.defaults.removeObject(forKey: Keys.manualOnboardingResetRequestedAt)
self.defaults.set(0, forKey: Keys.onboardingCurrentStep)
self.defaults.set(false, forKey: Keys.onboardingAISkipped)
self.defaults.set(false, forKey: Keys.onboardingPlaygroundValidated)
@@ -2885,6 +2891,8 @@ final class SettingsStore: ObservableObject {
fillerWords: self.fillerWords,
removeFillerWordsEnabled: self.removeFillerWordsEnabled,
autoConvertPunctuationEnabled: self.autoConvertPunctuationEnabled,
+ punctuationDictionaryPrefix: self.punctuationDictionaryPrefix,
+ punctuationDictionaryRules: self.punctuationDictionaryRules,
gaavModeEnabled: self.gaavModeEnabled,
gaavLowercaseFirstLetterEnabled: self.gaavLowercaseFirstLetterEnabled,
gaavRemoveTrailingPeriodEnabled: self.gaavRemoveTrailingPeriodEnabled,
@@ -2998,6 +3006,12 @@ final class SettingsStore: ObservableObject {
if let autoConvertPunctuationEnabled = payload.autoConvertPunctuationEnabled {
self.autoConvertPunctuationEnabled = autoConvertPunctuationEnabled
}
+ if let punctuationDictionaryPrefix = payload.punctuationDictionaryPrefix {
+ self.punctuationDictionaryPrefix = punctuationDictionaryPrefix
+ }
+ if let punctuationDictionaryRules = payload.punctuationDictionaryRules {
+ self.punctuationDictionaryRules = punctuationDictionaryRules
+ }
let restoredGaavModeEnabled = payload.gaavModeEnabled
let restoredContinuousDictationModeEnabled = payload.continuousDictationModeEnabled ?? false
self.gaavModeEnabled = restoredGaavModeEnabled
@@ -3606,6 +3620,162 @@ final class SettingsStore: ObservableObject {
}
}
+ static let defaultPunctuationDictionaryPrefix = "literal"
+
+ static let defaultPunctuationDictionaryRules: [PunctuationDictionaryRule] = [
+ PunctuationDictionaryRule(aliases: ["comma"], symbol: ","),
+ PunctuationDictionaryRule(aliases: ["period", "full stop"], symbol: "."),
+ PunctuationDictionaryRule(aliases: ["dot"], symbol: "."),
+ PunctuationDictionaryRule(aliases: ["question mark", "questionmark"], symbol: "?"),
+ PunctuationDictionaryRule(aliases: ["exclamation mark", "exclamation point", "bang"], symbol: "!"),
+ PunctuationDictionaryRule(aliases: ["colon"], symbol: ":"),
+ PunctuationDictionaryRule(aliases: ["semicolon", "semi colon"], symbol: ";"),
+ PunctuationDictionaryRule(aliases: ["ellipsis", "dot dot dot", "three dots"], symbol: "..."),
+ PunctuationDictionaryRule(aliases: ["slash", "forward slash", "forwardslash"], symbol: "/"),
+ PunctuationDictionaryRule(aliases: ["backslash", "back slash"], symbol: "\\"),
+ PunctuationDictionaryRule(aliases: ["hyphen"], symbol: "-"),
+ PunctuationDictionaryRule(aliases: ["dash", "minus sign"], symbol: "-"),
+ PunctuationDictionaryRule(aliases: ["em dash", "long dash"], symbol: "—"),
+ PunctuationDictionaryRule(aliases: ["en dash"], symbol: "–"),
+ PunctuationDictionaryRule(
+ aliases: ["open parenthesis", "open parentheses", "left parenthesis", "left parentheses", "open paren", "left paren"],
+ symbol: "("
+ ),
+ PunctuationDictionaryRule(
+ aliases: ["close parenthesis", "close parentheses", "right parenthesis", "right parentheses", "close paren", "right paren"],
+ symbol: ")"
+ ),
+ PunctuationDictionaryRule(aliases: ["open bracket", "left bracket", "open square bracket", "left square bracket"], symbol: "["),
+ PunctuationDictionaryRule(aliases: ["close bracket", "right bracket", "close square bracket", "right square bracket"], symbol: "]"),
+ PunctuationDictionaryRule(
+ aliases: ["open brace", "left brace", "open curly brace", "left curly brace", "open curly bracket", "left curly bracket"],
+ symbol: "{"
+ ),
+ PunctuationDictionaryRule(
+ aliases: ["close brace", "right brace", "close curly brace", "right curly brace", "close curly bracket", "right curly bracket"],
+ symbol: "}"
+ ),
+ PunctuationDictionaryRule(aliases: ["open angle bracket", "left angle bracket", "less than sign"], symbol: "<"),
+ PunctuationDictionaryRule(aliases: ["close angle bracket", "right angle bracket", "greater than sign"], symbol: ">"),
+ PunctuationDictionaryRule(aliases: ["quote", "quotes", "quotation mark", "double quote"], symbol: "\""),
+ PunctuationDictionaryRule(aliases: ["open quote", "opening quote", "open double quote", "opening double quote"], symbol: "\""),
+ PunctuationDictionaryRule(aliases: ["close quote", "closing quote", "close double quote", "closing double quote"], symbol: "\""),
+ PunctuationDictionaryRule(aliases: ["single quote"], symbol: "'"),
+ PunctuationDictionaryRule(aliases: ["apostrophe"], symbol: "'"),
+ PunctuationDictionaryRule(aliases: ["at the rate", "at sign", "commercial at"], symbol: "@"),
+ PunctuationDictionaryRule(aliases: ["ampersand", "and sign"], symbol: "&"),
+ PunctuationDictionaryRule(aliases: ["plus sign", "plus"], symbol: "+"),
+ PunctuationDictionaryRule(aliases: ["equals sign", "equal sign", "equal", "equals"], symbol: "="),
+ PunctuationDictionaryRule(aliases: ["percent sign", "percentage sign", "percent"], symbol: "%"),
+ PunctuationDictionaryRule(aliases: ["dollar sign", "dollar"], symbol: "$"),
+ PunctuationDictionaryRule(aliases: ["hash", "hash sign", "hashtag", "pound sign", "number sign"], symbol: "#"),
+ PunctuationDictionaryRule(aliases: ["asterisk", "star symbol"], symbol: "*"),
+ PunctuationDictionaryRule(aliases: ["underscore"], symbol: "_"),
+ PunctuationDictionaryRule(aliases: ["pipe", "vertical bar"], symbol: "|"),
+ PunctuationDictionaryRule(aliases: ["tilde"], symbol: "~"),
+ PunctuationDictionaryRule(aliases: ["caret"], symbol: "^"),
+ PunctuationDictionaryRule(aliases: ["backtick", "back tick"], symbol: "`"),
+ ]
+
+ struct PunctuationDictionaryRule: Codable, Identifiable, Hashable {
+ let id: UUID
+ var aliases: [String]
+ var symbol: String
+
+ init(aliases: [String], symbol: String) {
+ self.id = UUID()
+ self.aliases = Self.normalizedAliases(aliases)
+ self.symbol = Self.normalizedSymbol(symbol) ?? symbol
+ }
+
+ init(id: UUID, aliases: [String], symbol: String) {
+ self.id = id
+ self.aliases = Self.normalizedAliases(aliases)
+ self.symbol = Self.normalizedSymbol(symbol) ?? symbol
+ }
+
+ static func normalizedAlias(_ value: String) -> String? {
+ let alias = value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ return alias.isEmpty ? nil : alias
+ }
+
+ static func normalizedAliases(_ values: [String]) -> [String] {
+ var seen: Set<String> = []
+ var aliases: [String] = []
+ aliases.reserveCapacity(values.count)
+
+ for value in values {
+ guard let alias = self.normalizedAlias(value), !seen.contains(alias) else { continue }
+ seen.insert(alias)
+ aliases.append(alias)
+ }
+
+ return aliases
+ }
+
+ static func normalizedSymbol(_ value: String) -> String? {
+ let symbol = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ return symbol.isEmpty ? nil : symbol
+ }
+ }
+
+ static func normalizedPunctuationDictionaryPrefix(_ value: String) -> String? {
+ let prefix = value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ return prefix.isEmpty ? nil : prefix
+ }
+
+ var punctuationDictionaryPrefix: String {
+ get {
+ guard let stored = self.defaults.string(forKey: Keys.punctuationDictionaryPrefix),
+ let normalized = Self.normalizedPunctuationDictionaryPrefix(stored)
+ else {
+ return Self.defaultPunctuationDictionaryPrefix
+ }
+ return normalized
+ }
+ set {
+ objectWillChange.send()
+ self.defaults.set(
+ Self.normalizedPunctuationDictionaryPrefix(newValue) ?? Self.defaultPunctuationDictionaryPrefix,
+ forKey: Keys.punctuationDictionaryPrefix
+ )
+ }
+ }
+
+ var punctuationDictionaryRules: [PunctuationDictionaryRule] {
+ get {
+ guard let data = defaults.data(forKey: Keys.punctuationDictionaryRules),
+ let decoded = try? JSONDecoder().decode([PunctuationDictionaryRule].self, from: data)
+ else {
+ return Self.defaultPunctuationDictionaryRules
+ }
+ return decoded.compactMap { rule in
+ let aliases = PunctuationDictionaryRule.normalizedAliases(rule.aliases)
+ guard !aliases.isEmpty,
+ let symbol = PunctuationDictionaryRule.normalizedSymbol(rule.symbol)
+ else {
+ return nil
+ }
+ return PunctuationDictionaryRule(id: rule.id, aliases: aliases, symbol: symbol)
+ }
+ }
+ set {
+ objectWillChange.send()
+ let normalizedRules = newValue.compactMap { rule -> PunctuationDictionaryRule? in
+ let aliases = PunctuationDictionaryRule.normalizedAliases(rule.aliases)
+ guard !aliases.isEmpty,
+ let symbol = PunctuationDictionaryRule.normalizedSymbol(rule.symbol)
+ else {
+ return nil
+ }
+ return PunctuationDictionaryRule(id: rule.id, aliases: aliases, symbol: symbol)
+ }
+ if let encoded = try? JSONEncoder().encode(normalizedRules) {
+ self.defaults.set(encoded, forKey: Keys.punctuationDictionaryRules)
+ }
+ }
+ }
+
// MARK: - GAAV Mode
/// Legacy combined GAAV setting. New behavior uses the split formatting toggles below.
@@ -4503,6 +4673,7 @@ private extension SettingsStore {
static let onboardingCompleted = "OnboardingCompleted"
static let onboardingGeneration = "OnboardingGeneration"
static let manualOnboardingResetRequested = "ManualOnboardingResetRequested"
+ static let manualOnboardingResetRequestedAt = "ManualOnboardingResetRequestedAt"
static let onboardingCurrentStep = "OnboardingCurrentStep"
static let onboardingAISkipped = "OnboardingAISkipped"
static let onboardingPlaygroundValidated = "OnboardingPlaygroundValidated"
@@ -4551,6 +4722,8 @@ private extension SettingsStore {
static let fillerWords = "FillerWords"
static let removeFillerWordsEnabled = "RemoveFillerWordsEnabled"
static let autoConvertPunctuationEnabled = "AutoConvertPunctuationEnabled"
+ static let punctuationDictionaryPrefix = "PunctuationDictionaryPrefix"
+ static let punctuationDictionaryRules = "PunctuationDictionaryRules"
/// 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.swift
index 528c8451..486d97ca 100644
--- a/Sources/Fluid/Services/ASRService+SpokenPunctuationFormatting.swift
+++ b/Sources/Fluid/Services/ASRService+SpokenPunctuationFormatting.swift
@@ -7,9 +7,12 @@ extension ASRService {
bundleID: String? = nil,
windowTitle: String? = nil
) -> String {
- guard SettingsStore.shared.autoConvertPunctuationEnabled else { return text }
+ let settings = SettingsStore.shared
+ guard settings.autoConvertPunctuationEnabled else { return text }
return SpokenPunctuationFormatter.apply(
text,
+ prefix: settings.punctuationDictionaryPrefix,
+ rules: settings.punctuationDictionaryRules,
appName: appName,
bundleID: bundleID,
windowTitle: windowTitle
@@ -113,13 +116,22 @@ private enum SpokenPunctuationFormatter {
static func apply(
_ text: String,
+ prefix: String,
+ rules dictionaryRules: [SettingsStore.PunctuationDictionaryRule],
appName: String? = nil,
bundleID: String? = nil,
windowTitle: String? = nil
) -> String {
- guard !text.isEmpty else { return text }
+ guard !text.isEmpty,
+ text.range(of: prefix, options: .caseInsensitive) != nil
+ else { return text }
let context = FormattingContext(appName: appName, bundleID: bundleID, windowTitle: windowTitle)
+ let prefixWords = self.words(in: prefix)
+ let phraseRules = self.makeRules(from: dictionaryRules)
+ guard !prefixWords.isEmpty, !phraseRules.isEmpty else { return text }
+
+ let rulesByFirstWord = self.groupedRulesByFirstWord(for: phraseRules)
let tokens = self.tokenize(text)
guard tokens.contains(where: { $0.normalizedWord != nil }) else {
return text
@@ -128,7 +140,13 @@ private enum SpokenPunctuationFormatter {
var output: [OutputPart] = []
var index = 0
while index < tokens.count {
- if let match = self.matchRule(in: tokens, at: index, context: context) {
+ if let match = self.matchPrefixedRule(
+ in: tokens,
+ at: index,
+ prefixWords: prefixWords,
+ rulesByFirstWord: rulesByFirstWord,
+ context: context
+ ) {
output.append(.punctuation(symbol: match.rule.symbol, spacing: match.rule.spacing))
index = match.endIndex
} else if let text = tokens[index].text {
@@ -142,6 +160,62 @@ private enum SpokenPunctuationFormatter {
return self.render(self.removingGeneratedCommaNoise(from: output))
}
+ private static func groupedRulesByFirstWord(for rules: [PhraseRule]) -> [String: [PhraseRule]] {
+ let grouped = Dictionary(grouping: rules) { $0.words.first ?? "" }
+ return grouped.mapValues {
+ $0.sorted {
+ if $0.words.count != $1.words.count { return $0.words.count > $1.words.count }
+ return $0.words.joined(separator: " ").count > $1.words.joined(separator: " ").count
+ }
+ }
+ }
+
+ private static func makeRules(from dictionaryRules: [SettingsStore.PunctuationDictionaryRule]) -> [PhraseRule] {
+ dictionaryRules.flatMap { rule in
+ self.rules(
+ symbol: rule.symbol,
+ spacing: self.spacing(for: rule),
+ phrases: rule.aliases
+ )
+ }
+ }
+
+ private static func spacing(for rule: SettingsStore.PunctuationDictionaryRule) -> Spacing {
+ let aliases = Set(rule.aliases)
+
+ switch rule.symbol {
+ case ".":
+ return aliases.contains("dot") ? .noSpaceAround : .rightAttached
+ case ",", "?", "!", ":", ";", "...", ")", "]", "}", ">", "%":
+ return .rightAttached
+ case "(", "[", "{", "<", "$":
+ return .leftAttached
+ case "+", "=", "&", "—", "–":
+ return .spaceAround
+ case "-":
+ return aliases.contains("dash") || aliases.contains("minus sign") ? .spaceAround : .noSpaceAround
+ case "\"":
+ if aliases.contains(where: { $0.hasPrefix("open ") || $0.hasPrefix("opening ") }) {
+ return .leftAttached
+ }
+ if aliases.contains(where: { $0.hasPrefix("close ") || $0.hasPrefix("closing ") }) {
+ return .rightAttached
+ }
+ return .toggleDoubleQuote
+ case "'":
+ return aliases.contains("apostrophe") ? .noSpaceAround : .toggleSingleQuote
+ default:
+ return .noSpaceAround
+ }
+ }
+
+ private static func words(in phrase: String) -> [String] {
+ phrase
+ .split(whereSeparator: \.isWhitespace)
+ .map { String($0).lowercased() }
+ .filter { !$0.isEmpty }
+ }
+
private static func makeRules() -> [PhraseRule] {
self.rules(
symbol: ",",
@@ -424,13 +498,65 @@ private enum SpokenPunctuationFormatter {
return tokens
}
+ private static func matchPrefixedRule(
+ in tokens: [Token],
+ at index: Int,
+ prefixWords: [String],
+ rulesByFirstWord: [String: [PhraseRule]],
+ context: FormattingContext
+ ) -> (rule: PhraseRule, endIndex: Int)? {
+ guard let aliasIndex = self.indexAfterPrefix(prefixWords, in: tokens, at: index) else {
+ return nil
+ }
+ return self.matchRule(
+ in: tokens,
+ at: aliasIndex,
+ rulesByFirstWord: rulesByFirstWord,
+ context: context
+ )
+ }
+
+ private static func indexAfterPrefix(
+ _ prefixWords: [String],
+ in tokens: [Token],
+ at index: Int
+ ) -> Int? {
+ guard !prefixWords.isEmpty else { return nil }
+
+ var cursor = index
+ for (wordIndex, prefixWord) in prefixWords.enumerated() {
+ if wordIndex > 0 {
+ guard cursor < tokens.count, tokens[cursor].isHorizontalWhitespaceText else {
+ return nil
+ }
+ while cursor < tokens.count, tokens[cursor].isHorizontalWhitespaceText {
+ cursor += 1
+ }
+ }
+
+ guard cursor < tokens.count, tokens[cursor].normalizedWord == prefixWord else {
+ return nil
+ }
+ cursor += 1
+ }
+
+ guard cursor < tokens.count, tokens[cursor].isHorizontalWhitespaceText else {
+ return nil
+ }
+ while cursor < tokens.count, tokens[cursor].isHorizontalWhitespaceText {
+ cursor += 1
+ }
+ return cursor < tokens.count ? cursor : nil
+ }
+
private static func matchRule(
in tokens: [Token],
at index: Int,
+ rulesByFirstWord: [String: [PhraseRule]],
context: FormattingContext
) -> (rule: PhraseRule, endIndex: Int)? {
guard let firstWord = tokens[index].normalizedWord,
- let candidates = self.rulesByFirstWord[firstWord]
+ let candidates = rulesByFirstWord[firstWord]
else {
return nil
}
diff --git a/Sources/Fluid/Services/PrivateAIIntegrationService.swift b/Sources/Fluid/Services/PrivateAIIntegrationService.swift
index 5d274bdb..2d2e7c18 100644
--- a/Sources/Fluid/Services/PrivateAIIntegrationService.swift
+++ b/Sources/Fluid/Services/PrivateAIIntegrationService.swift
@@ -161,6 +161,20 @@ actor PrivateAIIntegrationService {
) async throws -> EnhancementResult {
try await Self.provider.enhanceDictation(inputText, runtime: runtime, context: context)
}
+
+ func enhanceDictation(
+ _ inputText: String,
+ runtime: RuntimeConfiguration,
+ context: AppContext,
+ streamHandler: PrivateAIStreamHandler?
+ ) async throws -> EnhancementResult {
+ try await Self.provider.enhanceDictation(
+ inputText,
+ runtime: runtime,
+ context: context,
+ streamHandler: streamHandler
+ )
+ }
}
private struct PrivateAIModelRemovalError: LocalizedError {
diff --git a/Sources/Fluid/Services/PrivateAIProvider.swift b/Sources/Fluid/Services/PrivateAIProvider.swift
index b376cea1..4a0b57da 100644
--- a/Sources/Fluid/Services/PrivateAIProvider.swift
+++ b/Sources/Fluid/Services/PrivateAIProvider.swift
@@ -1,5 +1,7 @@
import Foundation
+typealias PrivateAIStreamHandler = @Sendable (String) -> Void
+
struct PrivateAIModelArtifact: Sendable, Codable, Hashable {
var identifier: String
var filename: String
@@ -220,6 +222,12 @@ protocol PrivateAIIntegrationProviding: Sendable {
runtime: PrivateAIIntegrationService.RuntimeConfiguration,
context: PrivateAIIntegrationService.AppContext
) async throws -> PrivateAIIntegrationService.EnhancementResult
+ func enhanceDictation(
+ _ inputText: String,
+ runtime: PrivateAIIntegrationService.RuntimeConfiguration,
+ context: PrivateAIIntegrationService.AppContext,
+ streamHandler: PrivateAIStreamHandler?
+ ) async throws -> PrivateAIIntegrationService.EnhancementResult
}
extension PrivateAIIntegrationProviding {
@@ -235,6 +243,15 @@ extension PrivateAIIntegrationProviding {
func shutdownForTermination() async {
await self.unloadCachedRuntime(reason: "termination")
}
+
+ func enhanceDictation(
+ _ inputText: String,
+ runtime: PrivateAIIntegrationService.RuntimeConfiguration,
+ context: PrivateAIIntegrationService.AppContext,
+ streamHandler _: PrivateAIStreamHandler?
+ ) async throws -> PrivateAIIntegrationService.EnhancementResult {
+ try await self.enhanceDictation(inputText, runtime: runtime, context: context)
+ }
}
enum PrivateAIProviderRegistry {
diff --git a/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift b/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift
index d54f64ee..bd561f02 100644
--- a/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift
+++ b/Sources/Fluid/UI/AISettings/VoiceEngineSettingsViewModel.swift
@@ -45,7 +45,6 @@ final class VoiceEngineSettingsViewModel: ObservableObject {
}
@Published var removeFillerWordsEnabled: Bool
- @Published var autoConvertPunctuationEnabled: Bool
init(settings: SettingsStore, appServices: AppServices) {
self.settings = settings
@@ -53,7 +52,6 @@ final class VoiceEngineSettingsViewModel: ObservableObject {
self.previewSpeechModel = settings.selectedSpeechModel
self.selectedSpeechProvider = settings.selectedSpeechModel.provider
self.removeFillerWordsEnabled = settings.removeFillerWordsEnabled
- self.autoConvertPunctuationEnabled = settings.autoConvertPunctuationEnabled
appServices.objectWillChange
.sink { [weak self] _ in
Task { @MainActor in
@@ -67,7 +65,6 @@ final class VoiceEngineSettingsViewModel: ObservableObject {
self.previewSpeechModel = self.settings.selectedSpeechModel
self.selectedSpeechProvider = self.settings.selectedSpeechModel.provider
self.removeFillerWordsEnabled = self.settings.removeFillerWordsEnabled
- self.autoConvertPunctuationEnabled = self.settings.autoConvertPunctuationEnabled
Task {
await self.asr.checkIfModelsExistAsync()
diff --git a/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift b/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift
index 269c633e..131ffc5d 100644
--- a/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift
+++ b/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift
@@ -724,27 +724,6 @@ extension VoiceEngineSettingsView {
var fillerWordsSection: some View {
VStack(alignment: .leading, spacing: 8) {
- HStack(alignment: .center) {
- VStack(alignment: .leading, spacing: 2) {
- Text("Auto-Convert Punctuation")
- .font(self.theme.typography.bodyStrong)
- .foregroundStyle(self.voiceEngineTitleText)
- Text("Turn spoken punctuation like comma, slash, and at sign into symbols before AI cleanup")
- .font(self.theme.typography.bodySmall)
- .foregroundStyle(self.voiceEngineSecondaryText)
- }
- Spacer()
- Toggle("", isOn: self.$viewModel.autoConvertPunctuationEnabled)
- .toggleStyle(.switch)
- .labelsHidden()
- .onChange(of: self.viewModel.autoConvertPunctuationEnabled) { _, newValue in
- self.settings.autoConvertPunctuationEnabled = newValue
- }
- }
-
- Divider()
- .opacity(0.2)
-
HStack(alignment: .center) {
VStack(alignment: .leading, spacing: 2) {
Text("Remove Filler Words")
diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swift
index dc737a70..d396f6cd 100644
--- a/Sources/Fluid/UI/CustomDictionaryView.swift
+++ b/Sources/Fluid/UI/CustomDictionaryView.swift
@@ -20,13 +20,15 @@ struct CustomDictionaryView: View {
@State private var entries: [SettingsStore.CustomDictionaryEntry] = SettingsStore.shared.customDictionaryEntries
@State private var boostTerms: [ParakeetVocabularyStore.VocabularyConfig.Term] = []
@State private var editingEntry: SettingsStore.CustomDictionaryEntry?
- @State private var showAddBoostSheet = false
- @State private var editingBoostTerm: EditableBoostTerm?
@State private var boostStatusMessage = "Add custom words for better Parakeet recognition."
@State private var boostHasError = false
@State private var vocabBoostingEnabled: Bool = SettingsStore.shared.vocabularyBoostingEnabled
- @State private var isBoostingInfoPresented = false
+ @State private var isCustomWordsPresented = false
+ @State private var isBoostWordEditorPresented = false
+ @State private var editingBoostTermIndex: Int?
+ @State private var boostTermText = ""
+ @State private var boostTermStrength: BoostStrengthPreset = .balanced
@State private var trainingReplacement = ""
@State private var trainingVariants: [String] = []
@@ -46,7 +48,16 @@ struct CustomDictionaryView: View {
@State private var manualTriggerDraft = ""
@State private var manualTriggerChips: [String] = []
@State private var manualReplacement = ""
- @State private var isDictionaryExpanded = false
+ @State private var isYourDictionaryPresented = false
+ @State private var isPunctuationDictionaryPresented = false
+ @State private var punctuationAutoConvertEnabled = SettingsStore.shared.autoConvertPunctuationEnabled
+ @State private var punctuationPrefix = SettingsStore.shared.punctuationDictionaryPrefix
+ @State private var punctuationRules = SettingsStore.shared.punctuationDictionaryRules
+ @State private var isPunctuationInfoExpanded = false
+ @State private var isPunctuationRuleEditorPresented = false
+ @State private var editingPunctuationRuleID: UUID?
+ @State private var punctuationAliasesText = ""
+ @State private var punctuationSymbolText = ""
private var normalizedTrainingReplacement: String {
self.trainingReplacement.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -198,6 +209,53 @@ struct CustomDictionaryView: View {
self.manualDuplicateTriggers.isEmpty
}
+ private var punctuationEditorTitle: String {
+ self.editingPunctuationRuleID == nil ? "Add Rule" : "Edit Rule"
+ }
+
+ private var normalizedPunctuationAliases: [String] {
+ SettingsStore.PunctuationDictionaryRule.normalizedAliases(
+ self.punctuationAliasesText.components(separatedBy: .newlines)
+ )
+ }
+
+ private var normalizedPunctuationSymbol: String? {
+ SettingsStore.PunctuationDictionaryRule.normalizedSymbol(self.punctuationSymbolText)
+ }
+
+ private var canSavePunctuationRule: Bool {
+ !self.normalizedPunctuationAliases.isEmpty && self.normalizedPunctuationSymbol != nil
+ }
+
+ private var punctuationPreviewPrefix: String {
+ SettingsStore.normalizedPunctuationDictionaryPrefix(self.punctuationPrefix) ?? SettingsStore.defaultPunctuationDictionaryPrefix
+ }
+
+ private var boostEditorTitle: String {
+ self.editingBoostTermIndex == nil ? "Add Word" : "Edit Word"
+ }
+
+ private var normalizedBoostTermText: String {
+ self.boostTermText.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ private var isBoostTermDuplicate: Bool {
+ self.existingBoostTerms(excludingIndex: self.editingBoostTermIndex)
+ .contains(self.normalizedBoostTermText.lowercased())
+ }
+
+ private var canSaveBoostTerm: Bool {
+ !self.normalizedBoostTermText.isEmpty && !self.isBoostTermDuplicate
+ }
+
+ private enum DictionaryHeaderControlLayout {
+ static let controlsWidth: CGFloat = 194
+ static let toggleColumnWidth: CGFloat = 54
+ static let actionButtonWidth: CGFloat = 128
+ static let actionButtonLabelWidth: CGFloat = 104
+ static let controlHeight: CGFloat = 36
+ }
+
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xl) {
@@ -206,6 +264,7 @@ struct CustomDictionaryView: View {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xxl) {
self.trainReplacementSection
self.yourDictionarySection
+ self.punctuationDictionarySection
self.aiPostProcessingSection
}
}
@@ -231,24 +290,9 @@ struct CustomDictionaryView: View {
}
}
}
- .sheet(isPresented: self.$showAddBoostSheet) {
- AddBoostTermSheet(existingTerms: self.existingBoostTerms()) { newTerm in
- self.boostTerms.append(newTerm)
- self.saveBoostTerms()
- }
- }
- .sheet(item: self.$editingBoostTerm) { editable in
- EditBoostTermSheet(
- term: editable.term,
- existingTerms: self.existingBoostTerms(excludingIndex: editable.index)
- ) { updatedTerm in
- guard self.boostTerms.indices.contains(editable.index) else { return }
- self.boostTerms[editable.index] = updatedTerm
- self.saveBoostTerms()
- }
- }
.onAppear {
self.loadBoostTerms()
+ self.punctuationAutoConvertEnabled = SettingsStore.shared.autoConvertPunctuationEnabled
}
.onDisappear {
guard self.isTrainingRecording else { return }
@@ -747,69 +791,122 @@ struct CustomDictionaryView: View {
private var yourDictionarySection: some View {
ThemedCard(style: .standard, hoverEffect: false) {
- VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
- HStack(alignment: .center, spacing: self.theme.metrics.spacing.md) {
- self.settingsIconTile(systemName: "book.closed.fill")
+ HStack(alignment: .center, spacing: self.theme.metrics.spacing.md) {
+ self.settingsIconTile(systemName: "book.closed.fill")
- VStack(alignment: .leading, spacing: 3) {
- HStack(spacing: 6) {
- Text("Your Dictionary")
- .font(self.theme.typography.sectionTitle)
- if !self.entries.isEmpty {
- Text("(\(self.entries.count))")
- .font(self.theme.typography.captionSmall)
- .foregroundStyle(self.theme.palette.tertiaryText)
- }
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 6) {
+ Text("Your Dictionary")
+ .font(self.theme.typography.sectionTitle)
+ if !self.entries.isEmpty {
+ Text("(\(self.entries.count))")
+ .font(self.theme.typography.captionSmall)
+ .foregroundStyle(self.theme.palette.tertiaryText)
}
- Text("Words and phrases FluidVoice will correct automatically.")
- .font(self.theme.typography.caption)
- .foregroundStyle(self.theme.palette.secondaryText)
}
+ Text("Words and phrases FluidVoice will correct automatically.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
- Spacer()
+ self.yourDictionaryControls
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
- Button {
- withAnimation(self.reduceMotion ? nil : .easeOut(duration: 0.16)) {
- self.isDictionaryExpanded.toggle()
+ private var yourDictionaryControls: some View {
+ HStack(alignment: .center, spacing: self.theme.metrics.spacing.md) {
+ Button {
+ self.presentYourDictionary()
+ } label: {
+ Label("Modify", systemImage: "slider.horizontal.3")
+ .frame(width: Self.DictionaryHeaderControlLayout.actionButtonLabelWidth)
+ }
+ .frame(width: Self.DictionaryHeaderControlLayout.actionButtonWidth)
+ .fluidButton(.compact, size: .medium)
+ .help("Modify dictionary replacements")
+ .popover(isPresented: self.$isYourDictionaryPresented, arrowEdge: .top) {
+ self.yourDictionaryPopover
+ }
+
+ Color.clear
+ .frame(width: Self.DictionaryHeaderControlLayout.toggleColumnWidth)
+ .accessibilityHidden(true)
+ }
+ .frame(width: Self.DictionaryHeaderControlLayout.controlsWidth, height: Self.DictionaryHeaderControlLayout.controlHeight, alignment: .leading)
+ }
+
+ private var punctuationDictionarySection: some View {
+ ThemedCard(style: .standard, hoverEffect: false) {
+ HStack(alignment: .center, spacing: self.theme.metrics.spacing.md) {
+ self.settingsIconTile(systemName: "textformat")
+
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 6) {
+ Text("Punctuation Dictionary")
+ .font(self.theme.typography.sectionTitle)
+ if !self.punctuationRules.isEmpty {
+ Text("(\(self.punctuationRules.count))")
+ .font(self.theme.typography.captionSmall)
+ .foregroundStyle(self.theme.palette.tertiaryText)
}
- } label: {
- Image(systemName: self.isDictionaryExpanded ? "chevron.up" : "chevron.down")
- .font(.system(size: 12, weight: .semibold))
- .foregroundStyle(self.theme.palette.secondaryText)
- .frame(width: 28, height: 28)
- .background(
- RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm, style: .continuous)
- .fill(self.theme.palette.contentBackground.opacity(0.45))
- )
}
- .buttonStyle(.plain)
- .help(self.isDictionaryExpanded ? "Collapse dictionary" : "Expand dictionary")
- .accessibilityLabel(self.isDictionaryExpanded ? "Collapse dictionary" : "Expand dictionary")
+ Text("Say a start word first, then a punctuation name, to type punctuation symbols.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
}
+ .frame(maxWidth: .infinity, alignment: .leading)
- if self.isDictionaryExpanded {
- if self.entries.isEmpty {
- self.dictionaryEmptyState(
- title: "No replacements yet",
- detail: "Use Train Replacement or Manual Add above to create your first one."
- )
- .frame(maxWidth: 760)
- .frame(maxWidth: .infinity, alignment: .center)
- } else {
- self.entriesListView
- }
- }
+ self.punctuationDictionaryControls
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
+ private var punctuationDictionaryControls: some View {
+ HStack(alignment: .center, spacing: self.theme.metrics.spacing.md) {
+ Button {
+ self.presentPunctuationDictionary()
+ } label: {
+ Label("Modify", systemImage: "slider.horizontal.3")
+ .frame(width: Self.DictionaryHeaderControlLayout.actionButtonLabelWidth)
+ }
+ .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.")
+ .popover(isPresented: self.$isPunctuationDictionaryPresented, arrowEdge: .top) {
+ self.punctuationDictionaryPopover
+ }
+
+ self.punctuationDictionaryToggle
+ }
+ .frame(width: Self.DictionaryHeaderControlLayout.controlsWidth, height: Self.DictionaryHeaderControlLayout.controlHeight, alignment: .leading)
+ }
+
+ private var punctuationDictionaryToggle: some View {
+ Toggle("Punctuation Dictionary", isOn: self.$punctuationAutoConvertEnabled)
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .onChange(of: self.punctuationAutoConvertEnabled) { _, newValue in
+ SettingsStore.shared.autoConvertPunctuationEnabled = newValue
+ }
+ .frame(width: Self.DictionaryHeaderControlLayout.toggleColumnWidth, alignment: .trailing)
+ .help("Turn Punctuation Dictionary on or off.")
+ }
+
private var entriesListView: some View {
VStack(spacing: self.theme.metrics.spacing.sm) {
ForEach(self.entries) { entry in
DictionaryEntryRow(
entry: entry,
- onEdit: { self.editingEntry = entry },
+ onEdit: {
+ self.closeYourDictionary()
+ self.editingEntry = entry
+ },
onDelete: { self.deleteEntry(entry) }
)
}
@@ -818,117 +915,573 @@ struct CustomDictionaryView: View {
.frame(maxWidth: .infinity, alignment: .center)
}
+ private var yourDictionaryPopover: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ HStack(alignment: .top, spacing: self.theme.metrics.spacing.md) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Your Dictionary")
+ .font(self.theme.typography.sectionTitle)
+
+ Text("FluidVoice automatically corrects these words and phrases.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+
+ Spacer()
+
+ Button {
+ self.closeYourDictionary()
+ } label: {
+ Image(systemName: "xmark")
+ .font(.system(size: 11, weight: .bold))
+ .frame(width: 28, height: 28)
+ }
+ .buttonStyle(SquareIconButtonStyle())
+ .help("Close")
+ }
+
+ self.yourDictionaryHelpNote
+
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Saved Replacements")
+ .font(self.theme.typography.captionStrong)
+ Text("These run automatically after dictation.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+
+ if self.entries.isEmpty {
+ self.dictionaryEmptyState(
+ title: "No replacements yet",
+ detail: "Use Teach Words above to create your first one."
+ )
+ } else {
+ ScrollView(.vertical, showsIndicators: true) {
+ self.entriesListView
+ }
+ .frame(maxHeight: 235)
+ }
+ }
+ }
+ .padding(self.theme.metrics.spacing.lg)
+ .frame(width: 640, alignment: .leading)
+ }
+
+ private var yourDictionaryHelpNote: some View {
+ Label {
+ Text("Use the Teach Words area above to add dictionary entries by voice or manually.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ } icon: {
+ Image(systemName: "info.circle")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(self.theme.palette.accent)
+ }
+ .padding(self.theme.metrics.spacing.md)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .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)
+ )
+ )
+ }
+
// MARK: - Custom Words
private var aiPostProcessingSection: some View {
ThemedCard(style: .standard, hoverEffect: false) {
- VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
- HStack(alignment: .center, spacing: self.theme.metrics.spacing.md) {
- self.settingsIconTile(systemName: "character.book.closed")
+ HStack(alignment: .center, spacing: self.theme.metrics.spacing.md) {
+ self.settingsIconTile(systemName: "character.book.closed")
- VStack(alignment: .leading, spacing: 3) {
- HStack(spacing: 6) {
- Text("Custom Words")
- .font(self.theme.typography.sectionTitle)
- if !self.boostTerms.isEmpty {
- Text("(\(self.boostTerms.count))")
- .font(self.theme.typography.captionSmall)
- .foregroundStyle(self.theme.palette.tertiaryText)
- }
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 6) {
+ Text("Custom Words")
+ .font(self.theme.typography.sectionTitle)
+ if !self.boostTerms.isEmpty {
+ Text("(\(self.boostTerms.count))")
+ .font(self.theme.typography.captionSmall)
+ .foregroundStyle(self.theme.palette.tertiaryText)
}
- Text("Help the Parakeet voice engine recognize names, products, and uncommon terms.")
- .font(self.theme.typography.caption)
- .foregroundStyle(self.theme.palette.secondaryText)
}
+ Text("Help the Parakeet voice engine recognize names, products, and uncommon terms.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ self.customWordsControls
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ private var customWordsControls: some View {
+ HStack(alignment: .center, spacing: self.theme.metrics.spacing.md) {
+ Button {
+ self.presentCustomWords()
+ } label: {
+ Label("Modify", systemImage: "slider.horizontal.3")
+ .frame(width: Self.DictionaryHeaderControlLayout.actionButtonLabelWidth)
+ }
+ .frame(width: Self.DictionaryHeaderControlLayout.actionButtonWidth)
+ .fluidButton(.compact, size: .medium)
+ .disabled(!self.vocabBoostingEnabled)
+ .opacity(self.vocabBoostingEnabled ? 1 : 0.45)
+ .help(self.vocabBoostingEnabled ? "Modify custom words" : "Turn on Boosting to modify custom words.")
+ .popover(isPresented: self.$isCustomWordsPresented, arrowEdge: .top) {
+ self.customWordsPopover
+ }
+
+ self.customWordsBoostingToggle
+ }
+ .frame(width: Self.DictionaryHeaderControlLayout.controlsWidth, height: Self.DictionaryHeaderControlLayout.controlHeight, alignment: .leading)
+ }
+
+ private var customWordsBoostingToggle: some View {
+ Toggle("Custom Words Boosting", isOn: self.$vocabBoostingEnabled)
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .onChange(of: self.vocabBoostingEnabled) { _, newValue in
+ SettingsStore.shared.vocabularyBoostingEnabled = newValue
+ }
+ .frame(width: Self.DictionaryHeaderControlLayout.toggleColumnWidth, alignment: .trailing)
+ .help("Improve recognition of your custom words when using Parakeet.")
+ }
+
+ private var customWordsPopover: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ HStack(alignment: .top, spacing: self.theme.metrics.spacing.md) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Custom Words")
+ .font(self.theme.typography.sectionTitle)
+
+ Text("Add names, products, and uncommon terms for Parakeet to recognize.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+
+ Spacer()
+
+ Button {
+ self.closeCustomWords()
+ } label: {
+ Image(systemName: "xmark")
+ .font(.system(size: 11, weight: .bold))
+ .frame(width: 28, height: 28)
+ }
+ .buttonStyle(SquareIconButtonStyle())
+ .help("Close")
+ }
+
+ if self.isBoostWordEditorPresented {
+ self.boostWordEditor
+ } else {
+ HStack {
+ Button {
+ self.startAddingBoostTerm()
+ } label: {
+ Label("Add Word", systemImage: "plus")
+ }
+ .fluidButton(.accent, size: .small)
Spacer()
+ }
+ }
- Toggle("Boosting", isOn: self.$vocabBoostingEnabled)
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Saved Words")
.font(self.theme.typography.captionStrong)
- .toggleStyle(.switch)
- .controlSize(.mini)
- .help("Improve recognition of your custom words when using Parakeet.")
- .onChange(of: self.vocabBoostingEnabled) { _, newValue in
- SettingsStore.shared.vocabularyBoostingEnabled = newValue
+ Text("These words get extra recognition help while Boosting is enabled.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+
+ if self.boostTerms.isEmpty {
+ self.dictionaryEmptyState(
+ title: "No custom words yet",
+ detail: "Add a name or term that needs a little extra recognition help."
+ )
+ } else {
+ ScrollView(.vertical, showsIndicators: true) {
+ VStack(spacing: self.theme.metrics.spacing.sm) {
+ ForEach(Array(self.boostTerms.enumerated()), id: \.offset) { index, term in
+ BoostTermRow(
+ term: term,
+ onEdit: {
+ self.editBoostTerm(at: index)
+ },
+ onDelete: {
+ self.deleteBoostTerm(at: index)
+ }
+ )
+ }
}
+ }
+ .frame(maxHeight: 235)
+ }
+ }
+ if self.boostHasError {
+ Label(self.boostStatusMessage, systemImage: "exclamationmark.triangle.fill")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.warning)
+ }
+ }
+ .padding(self.theme.metrics.spacing.lg)
+ .frame(width: 640, alignment: .leading)
+ .onDisappear {
+ self.dismissBoostTermEditor()
+ }
+ }
+
+ private var boostWordEditor: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ Text(self.boostEditorTitle)
+ .font(self.theme.typography.captionStrong)
+
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Word or Phrase")
+ .font(self.theme.typography.captionStrong)
+ TextField("FluidVoice", text: self.$boostTermText)
+ .font(self.theme.typography.bodySmall)
+ .textFieldStyle(.roundedBorder)
+ .onSubmit { self.saveBoostTermIfValid() }
+ }
+
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Word Priority")
+ .font(self.theme.typography.captionStrong)
+ Picker("Word Priority", selection: self.$boostTermStrength) {
+ ForEach(BoostStrengthPreset.allCases) { preset in
+ Text(preset.rawValue).tag(preset)
+ }
+ }
+ .pickerStyle(.segmented)
+ Text(self.boostTermStrength.hint)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+
+ if self.isBoostTermDuplicate {
+ Text("This word already exists.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.warning)
+ }
+
+ HStack {
+ Spacer()
+
+ Button("Clear") {
+ self.clearBoostTermFields()
+ }
+ .fluidButton(.compact, size: .compact)
+
+ Spacer()
+
+ Button("Cancel") {
+ self.dismissBoostTermEditor()
+ }
+ .fluidButton(.compact, size: .compact)
+
+ Button("Save Word") {
+ self.saveBoostTermIfValid()
+ }
+ .fluidButton(.accent, size: .small)
+ .disabled(!self.canSaveBoostTerm)
+ .opacity(self.canSaveBoostTerm ? 1 : 0.45)
+ }
+ }
+ .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 punctuationDictionaryPopover: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ HStack(alignment: .top, spacing: self.theme.metrics.spacing.md) {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 8) {
+ Text("Punctuation Dictionary")
+ .font(self.theme.typography.sectionTitle)
+
+ Button {
+ withAnimation(self.reduceMotion ? nil : .easeOut(duration: 0.14)) {
+ self.isPunctuationInfoExpanded.toggle()
+ }
+ } label: {
+ Image(systemName: "info.circle")
+ .font(.system(size: 12, weight: .semibold))
+ .frame(width: 28, height: 28)
+ }
+ .buttonStyle(SquareIconButtonStyle())
+ .help("About punctuation rules")
+ .accessibilityLabel("About punctuation rules")
+ }
+
+ Text("Say the start word first, then the punctuation name you want to type.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+
+ Spacer()
+
+ Button {
+ self.closePunctuationDictionary()
+ } label: {
+ Image(systemName: "xmark")
+ .font(.system(size: 11, weight: .bold))
+ .frame(width: 28, height: 28)
+ }
+ .buttonStyle(SquareIconButtonStyle())
+ .help("Close")
+ }
+
+ 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)
+ .textFieldStyle(.roundedBorder)
+ .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)
+ }
+
+ if self.isPunctuationRuleEditorPresented {
+ self.punctuationRuleEditor
+ } else {
+ HStack {
Button {
- self.isBoostingInfoPresented.toggle()
+ self.startAddingPunctuationRule()
} label: {
- Image(systemName: "info.circle")
- .font(.system(size: 12, weight: .semibold))
- .frame(width: 32, height: 32)
+ Label("Add Rule", systemImage: "plus")
}
- .buttonStyle(SquareIconButtonStyle())
- .help("About Vocabulary Boosting")
- .popover(isPresented: self.$isBoostingInfoPresented, arrowEdge: .top) {
- self.boostingInfoPopover
+ .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.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) }
+ )
+ }
+ }
}
+ .frame(maxHeight: 235)
+ }
+ }
+
+ HStack {
+ Spacer()
+ Button("Reset Defaults") {
+ self.resetPunctuationDictionary()
+ }
+ .fluidButton(.compact, size: .compact)
+ }
+ }
+ .padding(self.theme.metrics.spacing.lg)
+ .frame(width: 640, alignment: .leading)
+ .onDisappear {
+ self.savePunctuationDictionaryPrefix()
+ }
+ }
+
+ private var punctuationDictionaryInfoPanel: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Say the start word first, then say the punctuation name.")
+ 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.")
+ }
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(self.theme.metrics.spacing.md)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .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 punctuationTrySayingPreview: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ self.punctuationExampleText(
+ spoken: "\(self.punctuationPreviewPrefix) comma",
+ typed: ","
+ )
+ self.punctuationExampleText(
+ spoken: "\(self.punctuationPreviewPrefix) question mark",
+ typed: "?"
+ )
+ }
+ .font(self.theme.typography.caption)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, self.theme.metrics.spacing.md)
+ .padding(.vertical, 7)
+ .background(
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm, style: .continuous)
+ .fill(self.theme.palette.contentBackground.opacity(0.5))
+ .overlay(
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.25), lineWidth: 1)
+ )
+ )
+ }
+
+ private func punctuationExampleText(spoken: String, typed: String) -> Text {
+ Text("When you say ")
+ .foregroundStyle(self.theme.palette.secondaryText) +
+ Text("\"\(spoken)\"")
+ .foregroundStyle(self.theme.palette.accent) +
+ Text(", it types ")
+ .foregroundStyle(self.theme.palette.secondaryText) +
+ Text("\"\(typed)\"")
+ .foregroundStyle(self.theme.palette.accent)
+ }
+
+ private var punctuationRuleEditor: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ Text(self.punctuationEditorTitle)
+ .font(self.theme.typography.captionStrong)
+
+ ViewThatFits(in: .horizontal) {
+ HStack(alignment: .top, spacing: self.theme.metrics.spacing.md) {
+ self.punctuationAliasesEditor
+ self.punctuationSymbolEditor
+ }
+
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ self.punctuationAliasesEditor
+ self.punctuationSymbolEditor
+ }
+ }
- Button {
- self.showAddBoostSheet = true
- } label: {
- Label("Add Word", systemImage: "plus")
- }
- .fluidButton(.accent, size: .small)
+ HStack {
+ Spacer()
+
+ Button("Clear") {
+ self.clearPunctuationRuleFields()
}
+ .fluidButton(.compact, size: .compact)
- if self.boostTerms.isEmpty {
- self.dictionaryEmptyState(
- title: "No custom words yet",
- detail: "Add a name or term that needs a little extra recognition help."
- ) {
- self.showAddBoostSheet = true
- }
- } else {
- VStack(spacing: self.theme.metrics.spacing.sm) {
- ForEach(Array(self.boostTerms.enumerated()), id: \.offset) { index, term in
- BoostTermRow(
- term: term,
- onEdit: {
- self.editingBoostTerm = EditableBoostTerm(index: index, term: term)
- },
- onDelete: {
- self.deleteBoostTerm(at: index)
- }
- )
- }
- }
+ Spacer()
+
+ Button("Cancel") {
+ self.dismissPunctuationRuleEditor()
}
+ .fluidButton(.compact, size: .compact)
- if self.boostHasError {
- Label(self.boostStatusMessage, systemImage: "exclamationmark.triangle.fill")
- .font(self.theme.typography.caption)
- .foregroundStyle(self.theme.palette.warning)
+ Button("Save Rule") {
+ self.savePunctuationRuleIfValid()
}
+ .fluidButton(.accent, size: .small)
+ .disabled(!self.canSavePunctuationRule)
+ .opacity(self.canSavePunctuationRule ? 1 : 0.45)
}
}
- .frame(maxWidth: .infinity, alignment: .leading)
+ .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 boostingInfoPopover: some View {
- VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
- HStack(spacing: 8) {
- Image(systemName: "testtube.2")
- .foregroundStyle(self.theme.palette.accent)
- Text("Vocabulary Boosting · Alpha")
- .font(self.theme.typography.bodySmallStrong)
- }
-
- Text("Vocabulary Boosting is an experimental feature that helps Parakeet recognize your custom words.")
- .font(self.theme.typography.caption)
- .foregroundStyle(self.theme.palette.secondaryText)
-
- Text("It can add close to a second to transcription time.")
+ private var punctuationAliasesEditor: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("What You Say")
+ .font(self.theme.typography.captionStrong)
+ Text("One way per line, like comma or full stop.")
.font(self.theme.typography.caption)
.foregroundStyle(self.theme.palette.secondaryText)
+ TextEditor(text: self.$punctuationAliasesText)
+ .font(self.theme.typography.bodySmall)
+ .frame(minHeight: 64, maxHeight: 86)
+ .scrollContentBackground(.hidden)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 4)
+ .background(
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm, style: .continuous)
+ .fill(self.theme.palette.contentBackground.opacity(0.55))
+ .overlay(
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.35), lineWidth: 1)
+ )
+ )
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
- Text("If recognition gets worse, the model behaves unexpectedly, or you notice other issues after enabling it, turn Boosting off.")
+ private var punctuationSymbolEditor: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("What It Types")
+ .font(self.theme.typography.captionStrong)
+ TextField(",", text: self.$punctuationSymbolText)
+ .font(self.theme.typography.bodySmallStrong)
+ .textFieldStyle(.roundedBorder)
+ .frame(width: 92)
+ Text("One punctuation symbol, like , or ?.")
.font(self.theme.typography.caption)
.foregroundStyle(self.theme.palette.secondaryText)
}
- .padding(self.theme.metrics.spacing.lg)
- .frame(width: 310, alignment: .leading)
}
private func dictionaryEmptyState(
@@ -1012,6 +1565,161 @@ struct CustomDictionaryView: View {
self.manualTriggerDraft = ""
}
+ private func presentYourDictionary() {
+ self.entries = SettingsStore.shared.customDictionaryEntries
+ self.isYourDictionaryPresented = true
+ }
+
+ private func closeYourDictionary() {
+ self.isYourDictionaryPresented = false
+ }
+
+ private func presentPunctuationDictionary() {
+ self.punctuationPrefix = SettingsStore.shared.punctuationDictionaryPrefix
+ self.punctuationRules = SettingsStore.shared.punctuationDictionaryRules
+ self.isPunctuationInfoExpanded = false
+ self.dismissPunctuationRuleEditor()
+ self.isPunctuationDictionaryPresented = true
+ }
+
+ private func closePunctuationDictionary() {
+ self.savePunctuationDictionaryPrefix()
+ self.isPunctuationInfoExpanded = false
+ self.isPunctuationDictionaryPresented = false
+ }
+
+ private func savePunctuationDictionaryPrefix() {
+ SettingsStore.shared.punctuationDictionaryPrefix = self.punctuationPrefix
+ self.punctuationPrefix = SettingsStore.shared.punctuationDictionaryPrefix
+ }
+
+ private func savePunctuationRules() {
+ SettingsStore.shared.punctuationDictionaryRules = self.punctuationRules
+ self.punctuationRules = SettingsStore.shared.punctuationDictionaryRules
+ }
+
+ private func startAddingPunctuationRule() {
+ self.editingPunctuationRuleID = nil
+ self.clearPunctuationRuleFields()
+ self.isPunctuationRuleEditorPresented = true
+ }
+
+ private func savePunctuationRuleIfValid() {
+ guard self.canSavePunctuationRule, let symbol = self.normalizedPunctuationSymbol else { return }
+ self.savePunctuationDictionaryPrefix()
+ let rule = SettingsStore.PunctuationDictionaryRule(
+ id: self.editingPunctuationRuleID ?? UUID(),
+ aliases: self.normalizedPunctuationAliases,
+ symbol: symbol
+ )
+
+ if let editingID = self.editingPunctuationRuleID,
+ let index = self.punctuationRules.firstIndex(where: { $0.id == editingID })
+ {
+ self.punctuationRules[index] = rule
+ } else {
+ self.punctuationRules.insert(rule, at: 0)
+ }
+
+ self.savePunctuationRules()
+ self.dismissPunctuationRuleEditor()
+ }
+
+ private func editPunctuationRule(_ rule: SettingsStore.PunctuationDictionaryRule) {
+ self.editingPunctuationRuleID = rule.id
+ self.punctuationAliasesText = rule.aliases.joined(separator: "\n")
+ self.punctuationSymbolText = rule.symbol
+ self.isPunctuationRuleEditorPresented = true
+ }
+
+ private func deletePunctuationRule(_ rule: SettingsStore.PunctuationDictionaryRule) {
+ self.punctuationRules.removeAll { $0.id == rule.id }
+ if self.editingPunctuationRuleID == rule.id {
+ self.dismissPunctuationRuleEditor()
+ }
+ self.savePunctuationRules()
+ }
+
+ private func resetPunctuationDictionary() {
+ self.punctuationPrefix = SettingsStore.defaultPunctuationDictionaryPrefix
+ self.punctuationRules = SettingsStore.defaultPunctuationDictionaryRules
+ self.dismissPunctuationRuleEditor()
+ self.savePunctuationDictionaryPrefix()
+ self.savePunctuationRules()
+ }
+
+ private func clearPunctuationRuleFields() {
+ self.punctuationAliasesText = ""
+ self.punctuationSymbolText = ""
+ }
+
+ private func dismissPunctuationRuleEditor() {
+ self.editingPunctuationRuleID = nil
+ self.clearPunctuationRuleFields()
+ self.isPunctuationRuleEditorPresented = false
+ }
+
+ private func presentCustomWords() {
+ self.loadBoostTerms()
+ self.dismissBoostTermEditor()
+ self.isCustomWordsPresented = true
+ }
+
+ private func closeCustomWords() {
+ self.dismissBoostTermEditor()
+ self.isCustomWordsPresented = false
+ }
+
+ private func startAddingBoostTerm() {
+ self.editingBoostTermIndex = nil
+ self.clearBoostTermFields()
+ self.isBoostWordEditorPresented = true
+ }
+
+ private func editBoostTerm(at index: Int) {
+ guard self.boostTerms.indices.contains(index) else { return }
+ let term = self.boostTerms[index]
+ self.editingBoostTermIndex = index
+ self.boostTermText = term.text
+ self.boostTermStrength = BoostStrengthPreset.nearest(for: term.weight ?? BoostStrengthPreset.balanced.weight)
+ self.isBoostWordEditorPresented = true
+ }
+
+ private func saveBoostTermIfValid() {
+ guard self.canSaveBoostTerm else { return }
+ let updatedTerm = ParakeetVocabularyStore.VocabularyConfig.Term(
+ text: self.normalizedBoostTermText,
+ weight: self.boostTermStrength.weight,
+ aliases: []
+ )
+
+ if let index = self.editingBoostTermIndex,
+ self.boostTerms.indices.contains(index)
+ {
+ self.boostTerms[index] = ParakeetVocabularyStore.VocabularyConfig.Term(
+ text: updatedTerm.text,
+ weight: updatedTerm.weight,
+ aliases: self.boostTerms[index].aliases
+ )
+ } else {
+ self.boostTerms.append(updatedTerm)
+ }
+
+ self.saveBoostTerms()
+ self.dismissBoostTermEditor()
+ }
+
+ private func clearBoostTermFields() {
+ self.boostTermText = ""
+ self.boostTermStrength = .balanced
+ }
+
+ private func dismissBoostTermEditor() {
+ self.editingBoostTermIndex = nil
+ self.clearBoostTermFields()
+ self.isBoostWordEditorPresented = false
+ }
+
private func beginTrainingReplacement() {
guard self.canStartTraining else { return }
self.isTrainingActive = true
@@ -1376,6 +2084,11 @@ struct CustomDictionaryView: View {
private func deleteBoostTerm(at index: Int) {
guard self.boostTerms.indices.contains(index) else { return }
self.boostTerms.remove(at: index)
+ if self.editingBoostTermIndex == index {
+ self.dismissBoostTermEditor()
+ } else if let editingIndex = self.editingBoostTermIndex, index < editingIndex {
+ self.editingBoostTermIndex = editingIndex - 1
+ }
self.saveBoostTerms()
}
@@ -1404,12 +2117,6 @@ struct CustomDictionaryView: View {
}
}
-private struct EditableBoostTerm: Identifiable {
- let id = UUID()
- let index: Int
- let term: ParakeetVocabularyStore.VocabularyConfig.Term
-}
-
private enum DictionaryComposerMode: CaseIterable, Identifiable {
case train
case manual
@@ -1887,188 +2594,6 @@ struct BoostTermRow: View {
}
}
-// MARK: - Add Boost Term Sheet
-
-struct AddBoostTermSheet: View {
- @Environment(\.dismiss) private var dismiss
-
- let existingTerms: Set<String>
- let onSave: (ParakeetVocabularyStore.VocabularyConfig.Term) -> Void
-
- @State private var termText = ""
- @State private var strength: BoostStrengthPreset = .balanced
-
- private var normalizedTerm: String {
- self.termText.trimmingCharacters(in: .whitespacesAndNewlines)
- }
-
- private var isDuplicate: Bool {
- self.existingTerms.contains(self.normalizedTerm.lowercased())
- }
-
- private var canSave: Bool {
- !self.normalizedTerm.isEmpty && !self.isDuplicate
- }
-
- var body: some View {
- ScrollView(.vertical, showsIndicators: false) {
- VStack(alignment: .leading, spacing: 14) {
- Text("Add Custom Word")
- .font(.headline)
-
- VStack(alignment: .leading, spacing: 6) {
- Text("Preferred Word or Phrase")
- .font(.subheadline.weight(.medium))
- TextField("FluidVoice", text: self.$termText)
- .textFieldStyle(.roundedBorder)
- .onSubmit { self.saveIfValid() }
- }
-
- VStack(alignment: .leading, spacing: 6) {
- Text("Word Priority")
- .font(.subheadline.weight(.medium))
- Picker("Word Priority", selection: self.$strength) {
- ForEach(BoostStrengthPreset.allCases) { preset in
- Text(preset.rawValue).tag(preset)
- }
- }
- .pickerStyle(.segmented)
- Text(self.strength.hint)
- .font(.caption2)
- .foregroundStyle(.secondary)
- }
-
- if self.isDuplicate {
- Text("This term already exists.")
- .font(.caption)
- .foregroundStyle(.orange)
- }
-
- HStack {
- Button("Cancel") { self.dismiss() }
- .buttonStyle(.bordered)
- Spacer()
- Button("Save") { self.saveIfValid() }
- .buttonStyle(.borderedProminent)
- .disabled(!self.canSave)
- .keyboardShortcut(.return, modifiers: [])
- }
- }
- }
- .padding(20)
- .frame(minWidth: 420, idealWidth: 460, maxWidth: 520)
- .frame(minHeight: 300, idealHeight: 340, maxHeight: 460)
- .onAppear {
- // Always start new entries at the recommended default.
- self.termText = ""
- self.strength = .balanced
- }
- }
-
- private func saveIfValid() {
- guard self.canSave else { return }
- self.onSave(
- ParakeetVocabularyStore.VocabularyConfig.Term(
- text: self.normalizedTerm,
- weight: self.strength.weight,
- aliases: []
- )
- )
- self.dismiss()
- }
-}
-
-// MARK: - Edit Boost Term Sheet
-
-struct EditBoostTermSheet: View {
- @Environment(\.dismiss) private var dismiss
-
- let term: ParakeetVocabularyStore.VocabularyConfig.Term
- let existingTerms: Set<String>
- let onSave: (ParakeetVocabularyStore.VocabularyConfig.Term) -> Void
-
- @State private var termText = ""
- @State private var strength: BoostStrengthPreset = .balanced
-
- private var normalizedTerm: String {
- self.termText.trimmingCharacters(in: .whitespacesAndNewlines)
- }
-
- private var isDuplicate: Bool {
- self.existingTerms.contains(self.normalizedTerm.lowercased())
- }
-
- private var canSave: Bool {
- !self.normalizedTerm.isEmpty && !self.isDuplicate
- }
-
- var body: some View {
- ScrollView(.vertical, showsIndicators: false) {
- VStack(alignment: .leading, spacing: 14) {
- Text("Edit Custom Word")
- .font(.headline)
-
- VStack(alignment: .leading, spacing: 6) {
- Text("Preferred Word or Phrase")
- .font(.subheadline.weight(.medium))
- TextField("FluidVoice", text: self.$termText)
- .textFieldStyle(.roundedBorder)
- .onSubmit { self.saveIfValid() }
- }
-
- VStack(alignment: .leading, spacing: 6) {
- Text("Word Priority")
- .font(.subheadline.weight(.medium))
- Picker("Word Priority", selection: self.$strength) {
- ForEach(BoostStrengthPreset.allCases) { preset in
- Text(preset.rawValue).tag(preset)
- }
- }
- .pickerStyle(.segmented)
- Text(self.strength.hint)
- .font(.caption2)
- .foregroundStyle(.secondary)
- }
-
- if self.isDuplicate {
- Text("This term already exists.")
- .font(.caption)
- .foregroundStyle(.orange)
- }
-
- HStack {
- Button("Cancel") { self.dismiss() }
- .buttonStyle(.bordered)
- Spacer()
- Button("Save") { self.saveIfValid() }
- .buttonStyle(.borderedProminent)
- .disabled(!self.canSave)
- .keyboardShortcut(.return, modifiers: [])
- }
- }
- }
- .padding(20)
- .frame(minWidth: 420, idealWidth: 460, maxWidth: 520)
- .frame(minHeight: 300, idealHeight: 340, maxHeight: 460)
- .onAppear {
- self.termText = self.term.text
- self.strength = BoostStrengthPreset.nearest(for: self.term.weight ?? BoostStrengthPreset.balanced.weight)
- }
- }
-
- private func saveIfValid() {
- guard self.canSave else { return }
- self.onSave(
- ParakeetVocabularyStore.VocabularyConfig.Term(
- text: self.normalizedTerm,
- weight: self.strength.weight,
- aliases: self.term.aliases
- )
- )
- self.dismiss()
- }
-}
-
// MARK: - Dictionary Entry Row
struct DictionaryEntryRow: View {
@@ -2135,6 +2660,67 @@ struct DictionaryEntryRow: View {
}
}
+private struct PunctuationDictionaryRuleRow: View {
+ let rule: SettingsStore.PunctuationDictionaryRule
+ let onEdit: () -> Void
+ let onDelete: () -> Void
+
+ @Environment(\.theme) private var theme
+
+ var body: some View {
+ HStack(alignment: .center, spacing: self.theme.metrics.spacing.sm) {
+ Text(self.rule.aliases.joined(separator: ", "))
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Image(systemName: "arrow.right")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.tertiaryText)
+
+ Text(self.rule.symbol)
+ .font(self.theme.typography.bodySmallStrong)
+ .foregroundStyle(self.theme.palette.accent)
+ .frame(width: 60, alignment: .leading)
+ .lineLimit(1)
+
+ HStack(spacing: 2) {
+ Button {
+ self.onEdit()
+ } label: {
+ Image(systemName: "slider.horizontal.3")
+ .font(.system(size: 12, weight: .semibold))
+ .frame(width: 32, height: 32)
+ }
+ .buttonStyle(SquareIconButtonStyle())
+ .help("Edit punctuation rule")
+
+ Button(role: .destructive) {
+ self.onDelete()
+ } label: {
+ Image(systemName: "trash")
+ .font(.system(size: 12, weight: .semibold))
+ .frame(width: 32, height: 32)
+ }
+ .buttonStyle(SquareIconButtonStyle(foreground: .red, borderColor: .red))
+ .help("Delete punctuation rule")
+ }
+ }
+ .padding(.horizontal, self.theme.metrics.spacing.md)
+ .padding(.vertical, 9)
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.theme.palette.contentBackground.opacity(0.52))
+ .overlay(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.28), lineWidth: 1)
+ )
+ )
+ }
+}
+
// MARK: - Add Entry Sheet
struct AddDictionaryEntrySheet: View {
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 5b551d40..e2530106 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -939,16 +939,6 @@ struct SettingsView: View {
)
Divider().opacity(0.2)
- self.optionToggleRow(
- title: "Auto-Convert Punctuation",
- description: "Turn spoken punctuation like comma, question mark, slash, and at sign into symbols before AI cleanup.",
- isOn: Binding(
- get: { SettingsStore.shared.autoConvertPunctuationEnabled },
- set: { SettingsStore.shared.autoConvertPunctuationEnabled = $0 }
- )
- )
- Divider().opacity(0.2)
-
self.optionToggleRow(
title: "Space Between Dictations",
description: "Add spacing so consecutive dictations chain without manually pressing the spacebar.",
@@ -1491,23 +1481,6 @@ struct SettingsView: View {
Text("Crash diagnostics are written to Library/Logs/Fluid/Fluid.log by default.")
.font(self.theme.typography.bodySmall)
.foregroundStyle(self.settingsSecondaryText)
-
- #if DEBUG
- Divider().padding(.vertical, 8)
-
- Button(role: .destructive) {
- self.settings.resetOnboardingProgress()
- DebugLogger.shared.info("Developer action: onboarding reset", source: "SettingsView")
- } label: {
- Label("Reset Onboarding (Dev)", systemImage: "arrow.counterclockwise")
- }
- .buttonStyle(.bordered)
- .controlSize(.regular)
-
- Text("Developer-only action. Immediately re-enters first-run onboarding flow.")
- .font(.caption)
- .foregroundStyle(self.settingsSecondaryText)
- #endif
}
}
.padding(16)
diff --git a/Sources/Fluid/Views/BottomOverlayView.swift b/Sources/Fluid/Views/BottomOverlayView.swift
index 47a29e89..21b236f7 100644
--- a/Sources/Fluid/Views/BottomOverlayView.swift
+++ b/Sources/Fluid/Views/BottomOverlayView.swift
@@ -2244,6 +2244,9 @@ struct BottomOverlayView: View {
private var currentPreviewSizingText: String {
guard self.shouldReservePreviewArea else { return "" }
+ if self.shouldShowProcessingPreview {
+ return self.processingPreviewText
+ }
return self.shouldShowProcessingStatus ? self.processingStatusText : self.transcriptionPreviewText
}
@@ -2256,7 +2259,10 @@ struct BottomOverlayView: View {
}
private var shouldSuppressPreviewDuringRelease: Bool {
- self.contentState.isBottomOverlayReleaseTransitioning || self.contentState.isBottomOverlayDismissing
+ if self.shouldShowProcessingPreview {
+ return false
+ }
+ return self.contentState.isBottomOverlayReleaseTransitioning || self.contentState.isBottomOverlayDismissing
}
private func previewResizeBucket(for previewText: String) -> Int {
@@ -2297,6 +2303,48 @@ struct BottomOverlayView: View {
return ""
}
+ private var processingPreviewText: String {
+ guard self.contentState.isProcessing else { return "" }
+ let preview = self.transcriptionPreviewText.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !Self.transientOverlayStatusTexts.contains(preview) else { return "" }
+ return self.transcriptionPreviewText
+ }
+
+ private var shouldShowProcessingPreview: Bool {
+ !self.processingPreviewText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ private var processingPreviewSegments: [DictationAIDiffSegment] {
+ self.contentState.dictationAIDiffPreviewSegments
+ }
+
+ private func richPreviewText(_ previewText: String) -> Text {
+ let segments = self.processingPreviewSegments
+ guard !segments.isEmpty else {
+ return Text(previewText)
+ .foregroundColor(.white.opacity(0.9))
+ }
+
+ return segments.reduce(Text("")) { partial, segment in
+ partial + self.segmentText(segment)
+ }
+ }
+
+ private func segmentText(_ segment: DictationAIDiffSegment) -> Text {
+ switch segment.kind {
+ case .unchanged:
+ return Text(segment.text)
+ .foregroundColor(.white.opacity(0.9))
+ case .inserted:
+ return Text(segment.text)
+ .foregroundColor(Color(red: 0.36, green: 0.95, blue: 0.58))
+ case .removed:
+ return Text(segment.text)
+ .foregroundColor(Color(red: 1.0, green: 0.36, blue: 0.38))
+ .strikethrough(true, color: Color(red: 1.0, green: 0.36, blue: 0.38))
+ }
+ }
+
private var overlayBorderLineWidth: CGFloat {
self.settings.overlaySize == .large ? 0.8 : 1
}
@@ -2705,6 +2753,49 @@ struct BottomOverlayView: View {
.frame(maxWidth: self.previewMaxWidth, alignment: .leading)
}
+ private func scrollablePreviewText(_ previewText: String) -> some View {
+ ScrollViewReader { proxy in
+ ScrollView(.vertical, showsIndicators: false) {
+ self.richPreviewText(previewText)
+ .font(.system(size: self.layout.transFontSize, weight: .medium))
+ .multilineTextAlignment(.leading)
+ .lineLimit(nil)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ Color.clear.frame(height: 1).id("bottom")
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .clipped()
+ .onChange(of: previewText) { _, _ in
+ DispatchQueue.main.async {
+ proxy.scrollTo("bottom", anchor: .bottom)
+ }
+ }
+ }
+ }
+
+ @ViewBuilder
+ private func dynamicPreviewText(_ previewText: String) -> some View {
+ if self.settings.overlaySize == .small {
+ self.richPreviewText(previewText)
+ .font(.system(size: self.layout.transFontSize, weight: .medium))
+ .multilineTextAlignment(.leading)
+ .lineLimit(1)
+ .truncationMode(.head)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.vertical, max(2, self.transcriptionVerticalPadding - 1))
+ } else {
+ self.richPreviewText(previewText)
+ .font(.system(size: self.layout.transFontSize, weight: .medium))
+ .multilineTextAlignment(.leading)
+ .lineLimit(Int(self.previewMaxHeight / max(self.estimatedPreviewLineHeight, 1)))
+ .truncationMode(.head)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(width: self.previewMaxWidth, alignment: .leading)
+ .padding(.vertical, self.transcriptionVerticalPadding)
+ }
+ }
+
var body: some View {
VStack(spacing: max(4, self.layout.vPadding / 2)) {
if self.layout.showsTopControls {
@@ -2730,6 +2821,8 @@ struct BottomOverlayView: View {
Color.clear
} else if self.shouldShowAIProcessingFailure {
self.aiProcessingFailureView
+ } else if self.shouldShowProcessingPreview {
+ self.scrollablePreviewText(self.processingPreviewText)
} else if self.shouldShowProcessingStatus {
// Temporarily hidden; the waveform sweep carries processing state.
// ShimmerText(
@@ -2788,6 +2881,8 @@ struct BottomOverlayView: View {
Color.clear
} else if self.shouldShowAIProcessingFailure {
self.aiProcessingFailureView
+ } else if self.shouldShowProcessingPreview {
+ self.dynamicPreviewText(self.processingPreviewText)
} else if self.hasTranscription && !self.contentState.isProcessing {
let previewText = self.transcriptionPreviewText
if !previewText.isEmpty {
diff --git a/Sources/Fluid/Views/NotchContentViews.swift b/Sources/Fluid/Views/NotchContentViews.swift
index 6b32e15f..bc1fc6ae 100644
--- a/Sources/Fluid/Views/NotchContentViews.swift
+++ b/Sources/Fluid/Views/NotchContentViews.swift
@@ -10,6 +10,137 @@ import Combine
import QuartzCore
import SwiftUI
+struct DictationAIDiffSegment: Equatable {
+ enum Kind: Equatable {
+ case unchanged
+ case inserted
+ case removed
+ }
+
+ var text: String
+ var kind: Kind
+}
+
+private enum DictationAIDiffBuilder {
+ private struct WordToken: Equatable {
+ let text: String
+ let normalized: String
+ }
+
+ private static let maximumDiffWordCount = 180
+ private static let punctuation = CharacterSet.punctuationCharacters
+
+ static func segments(originalText: String, processedText: String) -> [DictationAIDiffSegment] {
+ let originalWords = self.wordTokens(in: originalText)
+ let processedWords = self.wordTokens(in: processedText)
+
+ guard !processedWords.isEmpty else {
+ return self.render(words: originalWords, kind: .removed)
+ }
+
+ guard !originalWords.isEmpty else {
+ return self.render(words: processedWords, kind: .inserted)
+ }
+
+ guard originalWords.count <= self.maximumDiffWordCount,
+ processedWords.count <= self.maximumDiffWordCount
+ else {
+ return [DictationAIDiffSegment(text: processedText, kind: .unchanged)]
+ }
+
+ let table = self.lcsTable(originalWords: originalWords, processedWords: processedWords)
+ let columns = processedWords.count + 1
+ var merged: [DictationAIDiffSegment] = []
+ var rendered: [(String, DictationAIDiffSegment.Kind)] = []
+ var sourceIndex = 0
+ var targetIndex = 0
+
+ while sourceIndex < originalWords.count || targetIndex < processedWords.count {
+ if sourceIndex < originalWords.count,
+ targetIndex < processedWords.count,
+ originalWords[sourceIndex].normalized == processedWords[targetIndex].normalized
+ {
+ rendered.append((processedWords[targetIndex].text, .unchanged))
+ sourceIndex += 1
+ targetIndex += 1
+ } else if sourceIndex < originalWords.count,
+ targetIndex == processedWords.count ||
+ table[(sourceIndex + 1) * columns + targetIndex] >= table[sourceIndex * columns + targetIndex + 1]
+ {
+ rendered.append((originalWords[sourceIndex].text, .removed))
+ sourceIndex += 1
+ } else if targetIndex < processedWords.count {
+ rendered.append((processedWords[targetIndex].text, .inserted))
+ targetIndex += 1
+ }
+ }
+
+ for index in rendered.indices {
+ let suffix = index == rendered.count - 1 ? "" : " "
+ self.appendSegment(
+ text: rendered[index].0 + suffix,
+ kind: rendered[index].1,
+ to: &merged
+ )
+ }
+
+ return merged
+ }
+
+ private static func wordTokens(in text: String) -> [WordToken] {
+ text
+ .split { $0.isWhitespace }
+ .compactMap { part in
+ let raw = String(part)
+ let normalized = raw
+ .trimmingCharacters(in: self.punctuation)
+ .folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
+ guard !raw.isEmpty else { return nil }
+ return WordToken(text: raw, normalized: normalized.isEmpty ? raw.lowercased() : normalized)
+ }
+ }
+
+ private static func lcsTable(originalWords: [WordToken], processedWords: [WordToken]) -> [Int] {
+ let columns = processedWords.count + 1
+ var table = Array(repeating: 0, count: (originalWords.count + 1) * columns)
+
+ for sourceIndex in stride(from: originalWords.count - 1, through: 0, by: -1) {
+ for targetIndex in stride(from: processedWords.count - 1, through: 0, by: -1) {
+ let index = sourceIndex * columns + targetIndex
+ if originalWords[sourceIndex].normalized == processedWords[targetIndex].normalized {
+ table[index] = table[(sourceIndex + 1) * columns + targetIndex + 1] + 1
+ } else {
+ table[index] = max(
+ table[(sourceIndex + 1) * columns + targetIndex],
+ table[sourceIndex * columns + targetIndex + 1]
+ )
+ }
+ }
+ }
+
+ return table
+ }
+
+ private static func render(words: [WordToken], kind: DictationAIDiffSegment.Kind) -> [DictationAIDiffSegment] {
+ let text = words.map(\.text).joined(separator: " ")
+ guard !text.isEmpty else { return [] }
+ return [DictationAIDiffSegment(text: text, kind: kind)]
+ }
+
+ private static func appendSegment(
+ text: String,
+ kind: DictationAIDiffSegment.Kind,
+ to segments: inout [DictationAIDiffSegment]
+ ) {
+ guard !text.isEmpty else { return }
+ if let last = segments.indices.last, segments[last].kind == kind {
+ segments[last].text += text
+ } else {
+ segments.append(DictationAIDiffSegment(text: text, kind: kind))
+ }
+ }
+}
+
// MARK: - Observable state for notch content (Singleton)
@MainActor
@@ -40,6 +171,7 @@ class NotchContentState: ObservableObject {
/// Cached transcription preview text to avoid recomputing on every render
@Published private(set) var cachedPreviewText: String = ""
+ @Published private(set) var dictationAIDiffPreviewSegments: [DictationAIDiffSegment] = []
// MARK: - Expanded Command Output State
@@ -92,6 +224,8 @@ class NotchContentState: ObservableObject {
func setProcessing(_ processing: Bool) {
if processing {
self.clearAIProcessingFailure()
+ } else {
+ self.clearDictationAIDiffPreview()
}
self.isProcessing = processing
}
@@ -104,12 +238,29 @@ class NotchContentState: ObservableObject {
self.isAIProcessingFailureVisible = false
}
+ func updateDictationAIDiffPreview(originalText: String, processedText: String) {
+ let segments = DictationAIDiffBuilder.segments(
+ originalText: originalText,
+ processedText: processedText
+ )
+ guard segments != self.dictationAIDiffPreviewSegments else { return }
+ self.dictationAIDiffPreviewSegments = segments
+ }
+
+ func clearDictationAIDiffPreview() {
+ guard !self.dictationAIDiffPreviewSegments.isEmpty else { return }
+ self.dictationAIDiffPreviewSegments = []
+ }
+
/// Update transcription and recompute cached lines
func updateTranscription(_ text: String) {
let boundedText = Self.tailCharacters(in: text, maxCharacters: Self.maxStoredTranscriptionCharacters)
guard boundedText != self.transcriptionText else { return }
self.transcriptionText = boundedText
+ if boundedText.isEmpty {
+ self.clearDictationAIDiffPreview()
+ }
self.recomputeTranscriptionLines()
}
diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
index ac26d2b9..6c38f3bd 100644
--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
@@ -20,6 +20,8 @@ final class DictationE2ETests: XCTestCase {
private let selectedModelByProviderKey = "SelectedModelByProvider"
private let customDictionaryEntriesKey = "CustomDictionaryEntries"
private let autoConvertPunctuationEnabledKey = "AutoConvertPunctuationEnabled"
+ private let punctuationDictionaryPrefixKey = "PunctuationDictionaryPrefix"
+ private let punctuationDictionaryRulesKey = "PunctuationDictionaryRules"
private let commandModeLinkedToGlobalKey = "CommandModeLinkedToGlobal"
private let commandModeSelectedProviderIDKey = "CommandModeSelectedProviderID"
private let commandModeSelectedModelKey = "CommandModeSelectedModel"
@@ -44,6 +46,14 @@ final class DictationE2ETests: XCTestCase {
private let verifiedProviderFingerprintsKey = "VerifiedProviderFingerprints"
+ private var punctuationFormattingDefaultsKeys: [String] {
+ [
+ self.autoConvertPunctuationEnabledKey,
+ self.punctuationDictionaryPrefixKey,
+ self.punctuationDictionaryRulesKey,
+ ]
+ }
+
func testTranscriptionHistoryEntryClipboardTextPrefersProcessedText() {
let entry = TranscriptionHistoryEntry(
rawText: " raw transcript ",
@@ -427,32 +437,36 @@ final class DictationE2ETests: XCTestCase {
)
}
- func testSpokenPunctuationFormattingConvertsCommonPhrases() {
- self.withRestoredDefaults(keys: [self.autoConvertPunctuationEnabledKey]) {
+ func testSpokenPunctuationFormattingRequiresDictionaryPrefix() {
+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {
UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)
XCTAssertEqual(
ASRService.applySpokenPunctuationFormatting(
- "Hello comma world question mark open paren yes close paren quote done quote"
+ "Hello literal comma world literal question mark literal open paren yes literal close paren literal quote done literal quote"
),
"Hello, world? (yes) \"done\""
)
+ XCTAssertEqual(
+ ASRService.applySpokenPunctuationFormatting("Hello comma world question mark"),
+ "Hello comma world question mark"
+ )
}
}
- func testSpokenPunctuationFormattingConvertsCodeAndContactPunctuation() {
- self.withRestoredDefaults(keys: [self.autoConvertPunctuationEnabledKey]) {
+ func testSpokenPunctuationFormattingConvertsCodeAndContactPunctuationWithPrefix() {
+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {
UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)
XCTAssertEqual(
ASRService.applySpokenPunctuationFormatting(
- "email at the rate example dot com slash help underscore me"
+ "email literal at the rate example literal dot com literal slash help literal underscore me"
),
)
XCTAssertEqual(
ASRService.applySpokenPunctuationFormatting(
- "email at sign example dot com",
+ "email literal at sign example literal dot com",
appName: "Codex",
bundleID: "com.openai.codex"
),
@@ -463,13 +477,21 @@ final class DictationE2ETests: XCTestCase {
"email at sign example"
)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("x hyphen ray costs 50 percent"),
+ ASRService.applySpokenPunctuationFormatting("x literal hyphen ray costs 50 literal percent"),
"x-ray costs 50%"
)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("a plus b equals c"),
+ ASRService.applySpokenPunctuationFormatting("a literal plus b literal equals c"),
"a + b = c"
)
+ XCTAssertEqual(
+ ASRService.applySpokenPunctuationFormatting("plus equal percent"),
+ "plus equal percent"
+ )
+ XCTAssertEqual(
+ ASRService.applySpokenPunctuationFormatting("literal plus literal equal 50 literal percent"),
+ "+ = 50%"
+ )
XCTAssertEqual(
ASRService.applySpokenPunctuationFormatting("plus I need the normal word"),
"plus I need the normal word"
@@ -478,7 +500,7 @@ final class DictationE2ETests: XCTestCase {
}
func testSpokenPunctuationFormattingKeepsBareDotInProse() {
- self.withRestoredDefaults(keys: [self.autoConvertPunctuationEnabledKey]) {
+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {
UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)
XCTAssertEqual(
@@ -486,58 +508,58 @@ final class DictationE2ETests: XCTestCase {
"the polka dot dress"
)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("example dot com"),
+ ASRService.applySpokenPunctuationFormatting("example literal dot com"),
"example.com"
)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("version 1 dot 2"),
+ ASRService.applySpokenPunctuationFormatting("version 1 literal dot 2"),
"version 1.2"
)
}
}
func testSpokenPunctuationFormattingPreservesSlashCommandSpacing() {
- self.withRestoredDefaults(keys: [self.autoConvertPunctuationEnabledKey]) {
+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {
UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)
let text = ASRService.applySpokenPunctuationFormatting("Run slash status and open src slash services")
- XCTAssertEqual(text, "Run slash status and open src/services")
+ XCTAssertEqual(text, "Run slash status and open src slash services")
XCTAssertEqual(
ASRService.applySlashCommandFormatting(text),
- "Run /status and open src/services"
+ "Run /status and open src slash services"
)
}
}
- func testSpokenPunctuationFormattingCleansGeneratedCommaNoise() {
- self.withRestoredDefaults(keys: [self.autoConvertPunctuationEnabledKey]) {
+ func testSpokenPunctuationFormattingCleansGeneratedCommaNoiseWithPrefix() {
+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {
UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("hyphen comma hyphen comma hyphen"),
+ ASRService.applySpokenPunctuationFormatting("literal hyphen literal comma literal hyphen literal comma literal hyphen"),
"---"
)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("50 comma percent"),
+ ASRService.applySpokenPunctuationFormatting("50 literal comma literal percent"),
"50%"
)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("open bracket comma close bracket"),
+ ASRService.applySpokenPunctuationFormatting("literal open bracket literal comma literal close bracket"),
"[]"
)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("open paren comma close paren"),
+ ASRService.applySpokenPunctuationFormatting("literal open paren literal comma literal close paren"),
"()"
)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("question mark comma exclamation mark"),
+ ASRService.applySpokenPunctuationFormatting("literal question mark literal comma literal exclamation mark"),
"?!"
)
}
}
func testSpokenPunctuationFormattingPreservesExistingCommasNearSymbols() {
- self.withRestoredDefaults(keys: [self.autoConvertPunctuationEnabledKey]) {
+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {
UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)
XCTAssertEqual(
@@ -560,12 +582,61 @@ final class DictationE2ETests: XCTestCase {
}
func testSpokenPunctuationFormattingRespectsSetting() {
- self.withRestoredDefaults(keys: [self.autoConvertPunctuationEnabledKey]) {
+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {
UserDefaults.standard.set(false, forKey: self.autoConvertPunctuationEnabledKey)
XCTAssertEqual(
- ASRService.applySpokenPunctuationFormatting("Hello comma world question mark"),
- "Hello comma world question mark"
+ ASRService.applySpokenPunctuationFormatting("Hello literal comma world literal question mark"),
+ "Hello literal comma world literal question mark"
+ )
+ }
+ }
+
+ func testSpokenPunctuationFormattingUsesCustomPrefixAndRules() {
+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {
+ let settings = SettingsStore.shared
+ UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)
+ settings.punctuationDictionaryPrefix = "type"
+ settings.punctuationDictionaryRules = [
+ SettingsStore.PunctuationDictionaryRule(
+ aliases: ["right arrow", "arrow"],
+ symbol: "->"
+ ),
+ ]
+
+ XCTAssertEqual(
+ ASRService.applySpokenPunctuationFormatting("type right arrow"),
+ "->"
+ )
+ XCTAssertEqual(
+ ASRService.applySpokenPunctuationFormatting("literal right arrow"),
+ "literal right arrow"
+ )
+ XCTAssertEqual(
+ ASRService.applySpokenPunctuationFormatting("type comma"),
+ "type comma"
+ )
+ }
+ }
+
+ func testSpokenPunctuationFormattingUsesEditedRules() {
+ self.withRestoredDefaults(keys: self.punctuationFormattingDefaultsKeys) {
+ let settings = SettingsStore.shared
+ UserDefaults.standard.set(true, forKey: self.autoConvertPunctuationEnabledKey)
+ settings.punctuationDictionaryRules = [
+ SettingsStore.PunctuationDictionaryRule(
+ aliases: ["full stop"],
+ symbol: "."
+ ),
+ ]
+
+ XCTAssertEqual(
+ ASRService.applySpokenPunctuationFormatting("literal full stop"),
+ "."
+ )
+ XCTAssertEqual(
+ ASRService.applySpokenPunctuationFormatting("literal period"),
+ "literal period"
)
}
}