Skip to content

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

feat: format literal dictation tokens

altic-dev2d6cbe817acc
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 73325d28..90ef067c 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -2152,7 +2152,14 @@ struct ContentView: View {
do {
let result = try await self.processTextWithAI(transcribedText, overrideSystemPrompt: promptTest.draftPromptText)
- promptTest.lastOutputText = ASRService.applyGAAVFormatting(result)
+ let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()
+ let literalFormattedResult = ASRService.applyDictationLiteralFormatting(
+ result,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
+ promptTest.lastOutputText = ASRService.applyGAAVFormatting(literalFormattedResult)
} catch {
DebugLogger.shared.error("Prompt test AI call failed: \(error.localizedDescription)", source: "ContentView")
promptTest.lastError = error.localizedDescription
@@ -2268,12 +2275,25 @@ struct ContentView: View {
finalText = transcribedText
}
+ // Normalize literal command and mention syntax after AI cleanup and before final user preferences.
+ finalText = ASRService.applyDictationLiteralFormatting(
+ finalText,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
// Apply GAAV formatting as the FINAL step (after AI post-processing)
// This ensures the user's preference for no capitalization/period is respected
finalText = ASRService.applyGAAVFormatting(finalText)
// Apply Continuous Dictation Mode after GAAV so smart caps use the field
// context captured at recording start, and the trailing space enables chaining.
finalText = ASRService.applyContinuousDictationFormatting(finalText, precedingText: self.recordingPrecedingText)
+ finalText = ASRService.applyTerminalLiteralAutocompleteSpacing(
+ finalText,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
self.recordingPrecedingText = ""
self.asr.finalText = finalText
if route == .onboardingSandbox,
@@ -2287,6 +2307,12 @@ struct ContentView: View {
DebugLogger.shared.info("Transcription finalized (chars: \(finalText.count))", source: "ContentView")
let finalTextReadyAt = ProcessInfo.processInfo.systemUptime
+ let finalOutputPlan = ASRService.makeDictationLiteralOutputPlan(
+ for: finalText,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
self.appBench("transcription_finalized chars=\(finalText.count)")
self.appBench("text_ready chars=\(finalText.count)")
@@ -2380,8 +2406,8 @@ struct ContentView: View {
self.appBench(
"text_ready_to_type_request elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - finalTextReadyAt) * 1000).rounded()))"
)
- self.asr.typeTextToActiveField(
- finalText,
+ self.asr.typeOutputPlanToActiveField(
+ finalOutputPlan,
preferredTargetPID: typingTarget.pid,
textReadyAt: finalTextReadyAt
)
@@ -2621,7 +2647,14 @@ struct ContentView: View {
if typingTarget.shouldRestoreOriginalFocus {
await self.restoreFocusToRecordingTarget()
}
- self.asr.typeTextToActiveField(text, preferredTargetPID: typingTarget.pid)
+ let appInfo = self.getCurrentAppInfo()
+ let outputPlan = ASRService.makeDictationLiteralOutputPlan(
+ for: text,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
+ self.asr.typeOutputPlanToActiveField(outputPlan, preferredTargetPID: typingTarget.pid)
DebugLogger.shared.info("Actions: Pasted latest transcription into focused field", source: "ContentView")
}
}
@@ -2679,12 +2712,30 @@ struct ContentView: View {
self.cancelPrewarmDictationIfNeeded()
}
- let gaavText = ASRService.applyGAAVFormatting(text)
+ let appInfo = self.getCurrentAppInfo()
+ let literalFormattedText = ASRService.applyDictationLiteralFormatting(
+ text,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
+ let gaavText = ASRService.applyGAAVFormatting(literalFormattedText)
let precedingText = SettingsStore.shared.needsDictationFormattingContext
? TypingService.textBeforeCursorInFocusedField()
: ""
- let finalText = ASRService.applyContinuousDictationFormatting(gaavText, precedingText: precedingText)
- let appInfo = self.getCurrentAppInfo()
+ var finalText = ASRService.applyContinuousDictationFormatting(gaavText, precedingText: precedingText)
+ finalText = ASRService.applyTerminalLiteralAutocompleteSpacing(
+ finalText,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
+ let outputPlan = ASRService.makeDictationLiteralOutputPlan(
+ for: finalText,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
if saveToHistory, SettingsStore.shared.saveTranscriptionHistory {
TranscriptionHistoryStore.shared.addEntry(
@@ -2713,8 +2764,8 @@ struct ContentView: View {
if typingTarget.shouldRestoreOriginalFocus {
await self.restoreFocusToRecordingTarget()
}
- self.asr.typeTextToActiveField(
- finalText,
+ self.asr.typeOutputPlanToActiveField(
+ outputPlan,
preferredTargetPID: typingTarget.pid
)
}
@@ -2760,12 +2811,30 @@ struct ContentView: View {
NotchOverlayManager.shared.updateTranscriptionText("")
+ finalText = ASRService.applyDictationLiteralFormatting(
+ finalText,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
finalText = ASRService.applyGAAVFormatting(finalText)
let precedingText = SettingsStore.shared.needsDictationFormattingContext
? TypingService.textBeforeCursorInFocusedField()
: ""
finalText = ASRService.applyContinuousDictationFormatting(finalText, precedingText: precedingText)
+ finalText = ASRService.applyTerminalLiteralAutocompleteSpacing(
+ finalText,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
self.recordingPrecedingText = ""
+ let outputPlan = ASRService.makeDictationLiteralOutputPlan(
+ for: finalText,
+ appName: appInfo.name,
+ bundleID: appInfo.bundleId,
+ windowTitle: appInfo.windowTitle
+ )
if SettingsStore.shared.saveTranscriptionHistory {
TranscriptionHistoryStore.shared.addEntry(
@@ -2802,8 +2871,8 @@ struct ContentView: View {
if typingTarget.shouldRestoreOriginalFocus {
await self.restoreFocusToRecordingTarget()
}
- self.asr.typeTextToActiveField(
- finalText,
+ self.asr.typeOutputPlanToActiveField(
+ outputPlan,
preferredTargetPID: typingTarget.pid
)
}
diff --git a/Sources/Fluid/Services/ASRService+DictationLiteralFormatting.swift b/Sources/Fluid/Services/ASRService+DictationLiteralFormatting.swift
new file mode 100644
index 00000000..85331aba
--- /dev/null
+++ b/Sources/Fluid/Services/ASRService+DictationLiteralFormatting.swift
@@ -0,0 +1,458 @@
+import Foundation
+
+struct DictationLiteralOutputPlan: Equatable {
+ enum Step: Equatable {
+ case text(String)
+ }
+
+ let steps: [Step]
+
+ var plainText: String {
+ self.steps.reduce(into: "") { result, step in
+ if case let .text(text) = step {
+ result += text
+ }
+ }
+ }
+
+ static func plain(_ text: String) -> DictationLiteralOutputPlan {
+ DictationLiteralOutputPlan(steps: [.text(text)])
+ }
+}
+
+extension ASRService {
+ static func applyDictationLiteralFormatting(
+ _ text: String,
+ appName: String? = nil,
+ bundleID: String? = nil,
+ windowTitle: String? = nil
+ ) -> String {
+ DictationLiteralFormatter.applyDictationLiteralFormatting(
+ text,
+ appName: appName,
+ bundleID: bundleID,
+ windowTitle: windowTitle
+ )
+ }
+
+ static func applySlashCommandFormatting(_ text: String) -> String {
+ DictationLiteralFormatter.applySlashCommandFormatting(text)
+ }
+
+ static func applyMentionFormatting(
+ _ text: String,
+ appName: String? = nil,
+ bundleID: String? = nil,
+ windowTitle: String? = nil
+ ) -> String {
+ DictationLiteralFormatter.applyMentionFormatting(
+ text,
+ appName: appName,
+ bundleID: bundleID,
+ windowTitle: windowTitle
+ )
+ }
+
+ static func makeDictationLiteralOutputPlan(
+ for text: String,
+ appName: String? = nil,
+ bundleID: String? = nil,
+ windowTitle: String? = nil
+ ) -> DictationLiteralOutputPlan {
+ DictationLiteralFormatter.makeOutputPlan(
+ for: text,
+ appName: appName,
+ bundleID: bundleID,
+ windowTitle: windowTitle
+ )
+ }
+
+ static func applyTerminalLiteralAutocompleteSpacing(
+ _ text: String,
+ appName: String? = nil,
+ bundleID: String? = nil,
+ windowTitle: String? = nil
+ ) -> String {
+ DictationLiteralFormatter.applyTerminalLiteralAutocompleteSpacing(
+ text,
+ appName: appName,
+ bundleID: bundleID,
+ windowTitle: windowTitle
+ )
+ }
+}
+
+private enum DictationLiteralFormatter {
+ private enum SlashCommandMatchKind {
+ case literal
+ case spoken
+ }
+
+ private static let slashCommandLiteralRegex = try? NSRegularExpression(
+ pattern: #"(?<![\p{L}\p{N}_])/\s+([A-Za-z][A-Za-z0-9_-]{1,39})(?![A-Za-z0-9_-])"#,
+ options: []
+ )
+
+ private static let slashCommandSpokenRegex = try? NSRegularExpression(
+ pattern: #"(?i)(?<![\p{L}\p{N}_])(?:forward\s+slash|slash)\s+([A-Za-z][A-Za-z0-9_-]{1,39})(?![A-Za-z0-9_-])"#,
+ options: []
+ )
+
+ private static let slashCommandRejectedTokens: Set<String> = [
+ "a", "an", "and", "as", "at", "back", "backslash", "be", "been", "being",
+ "bin", "by", "comma", "desktop", "documents", "dot", "downloads", "etc",
+ "for", "forward", "from", "home", "in", "is", "library", "local", "mark",
+ "of", "on", "or", "period", "private", "question", "quote", "quotes",
+ "semicolon", "slash", "slashes", "source", "sources", "src", "the", "tmp",
+ "to", "user", "users", "usr", "var", "volumes", "was", "were", "with",
+ "without",
+ ]
+
+ private static let slashCommandSpokenLeadInWords: Set<String> = [
+ "call", "choose", "do", "enter", "execute", "open", "pick", "press", "run",
+ "say", "select", "send", "start", "try", "type", "use", "write",
+ ]
+
+ private enum MentionMatchKind {
+ case explicit
+ case relaxed
+ }
+
+ private static let explicitMentionRegex = try? NSRegularExpression(
+ pattern: #"(?<![\p{L}\p{N}_@])(?i:(?:at\s+(?:sign|the\s+rate)|tag|mention))\s+([A-Za-z][A-Za-z0-9_.-]*(?:\s+[A-Z][A-Za-z0-9_.-]*){0,2})(?![A-Za-z0-9_.-])"#,
+ options: []
+ )
+
+ private static let relaxedMentionRegex = try? NSRegularExpression(
+ pattern: #"(?<![\p{L}\p{N}_@])[Aa]t\s+([A-Z][A-Za-z0-9_.-]*(?:\s+[A-Z][A-Za-z0-9_.-]*){0,2})(?![A-Za-z0-9_.-])"#,
+ options: []
+ )
+
+ private static let terminalMentionTokenRegex = try? NSRegularExpression(
+ pattern: #"(?<![\p{L}\p{N}_@])@([A-Za-z][A-Za-z0-9_.-]*(?:\s+[A-Z][A-Za-z0-9_.-]*){0,2})$"#,
+ options: []
+ )
+
+ private static let standaloneSlashCommandRegex = try? NSRegularExpression(
+ pattern: #"^/[A-Za-z][A-Za-z0-9_-]{1,39}$"#,
+ options: []
+ )
+
+ private static let mentionRejectedTokens: Set<String> = [
+ "a", "an", "airport", "breakfast", "brunch", "class", "dinner", "home",
+ "hotel", "house", "lunch", "meeting", "night", "noon", "office", "place",
+ "restaurant", "school", "shop", "store", "the", "today", "tomorrow",
+ "work", "yesterday",
+ ]
+
+ private static let relaxedMentionLeadInWords: Set<String> = [
+ "add", "ask", "cc", "dm", "hello", "hey", "hi", "invite", "message",
+ "notify", "ping", "send", "tag", "tell",
+ ]
+
+ static func applyDictationLiteralFormatting(
+ _ text: String,
+ appName: String? = nil,
+ bundleID: String? = nil,
+ windowTitle: String? = nil
+ ) -> String {
+ let commandFormatted = self.applySlashCommandFormatting(text)
+ return self.applyMentionFormatting(
+ commandFormatted,
+ appName: appName,
+ bundleID: bundleID,
+ windowTitle: windowTitle
+ )
+ }
+
+ static func applySlashCommandFormatting(_ text: String) -> String {
+ guard !text.isEmpty,
+ text.contains("/") || text.range(of: "slash", options: .caseInsensitive) != nil
+ else {
+ return text
+ }
+
+ let literalFormatted = self.replacingSlashCommandMatches(
+ in: text,
+ regex: self.slashCommandLiteralRegex,
+ kind: .literal
+ )
+ return self.replacingSlashCommandMatches(
+ in: literalFormatted,
+ regex: self.slashCommandSpokenRegex,
+ kind: .spoken
+ )
+ }
+
+ static func applyMentionFormatting(
+ _ text: String,
+ appName: String? = nil,
+ bundleID: String? = nil,
+ windowTitle: String? = nil
+ ) -> String {
+ guard !text.isEmpty,
+ text.range(of: "at ", options: .caseInsensitive) != nil ||
+ text.range(of: "tag ", options: .caseInsensitive) != nil ||
+ text.range(of: "mention ", options: .caseInsensitive) != nil
+ else {
+ return text
+ }
+
+ let explicitFormatted = self.replacingMentionMatches(
+ in: text,
+ regex: self.explicitMentionRegex,
+ kind: .explicit
+ )
+ guard self.isRelaxedMentionApp(appName: appName, bundleID: bundleID, windowTitle: windowTitle) else {
+ return explicitFormatted
+ }
+ return self.replacingMentionMatches(
+ in: explicitFormatted,
+ regex: self.relaxedMentionRegex,
+ kind: .relaxed
+ )
+ }
+
+ static func makeOutputPlan(
+ for text: String,
+ appName: String? = nil,
+ bundleID: String? = nil,
+ windowTitle: String? = nil
+ ) -> DictationLiteralOutputPlan {
+ .plain(
+ self.applyTerminalLiteralAutocompleteSpacing(
+ text,
+ appName: appName,
+ bundleID: bundleID,
+ windowTitle: windowTitle
+ )
+ )
+ }
+
+ static func applyTerminalLiteralAutocompleteSpacing(
+ _ text: String,
+ appName: String? = nil,
+ bundleID: String? = nil,
+ windowTitle: String? = nil
+ ) -> String {
+ guard text.last?.isHorizontalWhitespace == true else { return text }
+
+ let withoutTrailingWhitespace = self.removingTrailingHorizontalWhitespace(from: text)
+ guard !withoutTrailingWhitespace.isEmpty else { return text }
+
+ if self.isSlashCommandAutocompleteApp(appName: appName, bundleID: bundleID, windowTitle: windowTitle),
+ self.matchesWholeString(withoutTrailingWhitespace, regex: self.standaloneSlashCommandRegex)
+ {
+ return withoutTrailingWhitespace
+ }
+
+ if self.isRelaxedMentionApp(appName: appName, bundleID: bundleID, windowTitle: windowTitle),
+ self.matchesTerminalToken(withoutTrailingWhitespace, regex: self.terminalMentionTokenRegex)
+ {
+ return withoutTrailingWhitespace
+ }
+
+ return text
+ }
+
+ private static func replacingSlashCommandMatches(
+ in text: String,
+ regex: NSRegularExpression?,
+ kind: SlashCommandMatchKind
+ ) -> String {
+ guard let regex else { return text }
+ let source = text as NSString
+ let fullRange = NSRange(location: 0, length: source.length)
+ let matches = regex.matches(in: text, range: fullRange)
+ guard !matches.isEmpty else { return text }
+
+ let result = NSMutableString(string: text)
+ for match in matches.reversed() {
+ let token = source.substring(with: match.range(at: 1))
+ guard self.isValidSlashCommandToken(token) else { continue }
+ if kind == .spoken,
+ !self.hasSpokenSlashCommandContext(in: source, matchLocation: match.range.location)
+ {
+ continue
+ }
+ result.replaceCharacters(in: match.range, with: "/\(token.lowercased())")
+ }
+
+ return result as String
+ }
+
+ private static func isValidSlashCommandToken(_ token: String) -> Bool {
+ let lowercased = token.lowercased()
+ guard !self.slashCommandRejectedTokens.contains(lowercased),
+ lowercased.first?.isASCIIAlphabetic == true,
+ lowercased.last?.isASCIICommandTokenCharacter == true
+ else {
+ return false
+ }
+
+ return lowercased.allSatisfy(\.isASCIICommandTokenCharacter)
+ }
+
+ private static func hasSpokenSlashCommandContext(in text: NSString, matchLocation: Int) -> Bool {
+ guard matchLocation > 0 else { return true }
+ let prefix = text.substring(to: matchLocation).trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !prefix.isEmpty else { return true }
+
+ if let last = prefix.unicodeScalars.last,
+ CharacterSet(charactersIn: ".!?:;([{").contains(last)
+ {
+ return true
+ }
+
+ let words = prefix.split { scalar in
+ !(scalar.isASCIIAlphabetic || scalar.isASCIIDigit || scalar == "-" || scalar == "_")
+ }
+ guard let previousWord = words.last else { return true }
+ return self.slashCommandSpokenLeadInWords.contains(String(previousWord).lowercased())
+ }
+
+ private static func replacingMentionMatches(
+ in text: String,
+ regex: NSRegularExpression?,
+ kind: MentionMatchKind
+ ) -> String {
+ guard let regex else { return text }
+ let source = text as NSString
+ let fullRange = NSRange(location: 0, length: source.length)
+ let matches = regex.matches(in: text, range: fullRange)
+ guard !matches.isEmpty else { return text }
+
+ let result = NSMutableString(string: text)
+ for match in matches.reversed() {
+ let name = source.substring(with: match.range(at: 1))
+ guard self.isValidMentionName(name, kind: kind),
+ !self.isPossessiveMentionMatch(in: source, match: match)
+ else {
+ continue
+ }
+ if kind == .relaxed,
+ !self.hasRelaxedMentionContext(in: source, matchLocation: match.range.location)
+ {
+ continue
+ }
+ result.replaceCharacters(in: match.range, with: "@\(name.trimmingCharacters(in: .whitespaces))")
+ }
+
+ return result as String
+ }
+
+ private static func isValidMentionName(_ name: String, kind: MentionMatchKind) -> Bool {
+ let tokens = name
+ .split(separator: " ")
+ .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ guard !tokens.isEmpty, tokens.count <= 3 else { return false }
+
+ for token in tokens {
+ let lowercased = token.lowercased()
+ guard !self.mentionRejectedTokens.contains(lowercased),
+ token.allSatisfy(\.isASCIIMentionTokenCharacter)
+ else {
+ return false
+ }
+ if kind == .relaxed,
+ token.first?.isASCIIAlphabetic != true ||
+ token.first?.isUppercase != true
+ {
+ return false
+ }
+ }
+
+ return true
+ }
+
+ private static func isPossessiveMentionMatch(in text: NSString, match: NSTextCheckingResult) -> Bool {
+ let end = match.range.location + match.range.length
+ guard end < text.length else { return false }
+ let next = text.substring(with: NSRange(location: end, length: 1))
+ return next == "'" || next == "’"
+ }
+
+ private static func hasRelaxedMentionContext(in text: NSString, matchLocation: Int) -> Bool {
+ guard matchLocation > 0 else { return true }
+ let prefix = text.substring(to: matchLocation).trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !prefix.isEmpty else { return true }
+
+ if let last = prefix.unicodeScalars.last,
+ CharacterSet(charactersIn: ".!?:;([{").contains(last)
+ {
+ return true
+ }
+
+ let words = prefix.split { scalar in
+ !(scalar.isASCIIAlphabetic || scalar.isASCIIDigit || scalar == "-" || scalar == "_")
+ }
+ guard let previousWord = words.last else { return true }
+ return self.relaxedMentionLeadInWords.contains(String(previousWord).lowercased())
+ }
+
+ private static func isRelaxedMentionApp(appName: String?, bundleID: String?, windowTitle: String?) -> Bool {
+ let haystack = [appName, bundleID, windowTitle]
+ .compactMap { $0?.lowercased() }
+ .joined(separator: " ")
+ return haystack.contains("slack") ||
+ haystack.contains("discord") ||
+ haystack.contains("teams")
+ }
+
+ private static func isSlashCommandAutocompleteApp(appName: String?, bundleID: String?, windowTitle: String?) -> Bool {
+ let haystack = [appName, bundleID, windowTitle]
+ .compactMap { $0?.lowercased() }
+ .joined(separator: " ")
+ return haystack.contains("codex") ||
+ haystack.contains("chatgpt") ||
+ haystack.contains("claude") ||
+ haystack.contains("cursor") ||
+ haystack.contains("windsurf")
+ }
+
+ private static func matchesWholeString(_ text: String, regex: NSRegularExpression?) -> Bool {
+ guard let regex else { return false }
+ let range = NSRange(location: 0, length: (text as NSString).length)
+ guard let match = regex.firstMatch(in: text, range: range) else { return false }
+ return match.range.location == 0 && match.range.length == range.length
+ }
+
+ private static func matchesTerminalToken(_ text: String, regex: NSRegularExpression?) -> Bool {
+ guard let regex else { return false }
+ let range = NSRange(location: 0, length: (text as NSString).length)
+ return regex.firstMatch(in: text, range: range) != nil
+ }
+
+ private static func removingTrailingHorizontalWhitespace(from text: String) -> String {
+ var result = text
+ while result.last?.isHorizontalWhitespace == true {
+ result.removeLast()
+ }
+ return result
+ }
+}
+
+private extension Character {
+ var isASCIIAlphabetic: Bool {
+ guard self.unicodeScalars.count == 1, let scalar = self.unicodeScalars.first else { return false }
+ return (65...90).contains(scalar.value) || (97...122).contains(scalar.value)
+ }
+
+ var isASCIIDigit: Bool {
+ guard self.unicodeScalars.count == 1, let scalar = self.unicodeScalars.first else { return false }
+ return (48...57).contains(scalar.value)
+ }
+
+ var isASCIICommandTokenCharacter: Bool {
+ self.isASCIIAlphabetic || self.isASCIIDigit || self == "-" || self == "_"
+ }
+
+ var isASCIIMentionTokenCharacter: Bool {
+ self.isASCIIAlphabetic || self.isASCIIDigit || self == "-" || self == "_" || self == "."
+ }
+
+ var isHorizontalWhitespace: Bool {
+ self.unicodeScalars.allSatisfy { CharacterSet.whitespaces.contains($0) }
+ }
+}
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 294f8bc5..122e105f 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -3229,18 +3229,30 @@ final class ASRService: ObservableObject {
}
func typeTextToActiveField(_ text: String, preferredTargetPID: pid_t?, textReadyAt: TimeInterval? = nil) {
+ self.typeOutputPlanToActiveField(.plain(text), preferredTargetPID: preferredTargetPID, textReadyAt: textReadyAt)
+ }
+
+ func typeOutputPlanToActiveField(
+ _ plan: DictationLiteralOutputPlan,
+ preferredTargetPID: pid_t?,
+ textReadyAt: TimeInterval? = nil
+ ) {
let requestedAt = ProcessInfo.processInfo.systemUptime
let textReadyAge = textReadyAt.map { Int(((requestedAt - $0) * 1000).rounded()) }
+ let text = plan.plainText
DebugLogger.shared.benchmark(
"TYPING_BENCH",
message: "asr_type_request chars=\(text.count) preferredPID=\(preferredTargetPID.map { String($0) } ?? "nil") textReadyAgeMs=\(textReadyAge.map { String($0) } ?? "nil")",
source: "TypingBenchmark"
)
- self.typingService.typeTextInstantly(text, preferredTargetPID: preferredTargetPID, textReadyAt: textReadyAt)
+ self.typingService.typeOutputPlanInstantly(plan, preferredTargetPID: preferredTargetPID, textReadyAt: textReadyAt)
let dispatchedAt = ProcessInfo.processInfo.systemUptime
+ let textReadyToDispatchMs = textReadyAt.map {
+ String(Int(((dispatchedAt - $0) * 1000).rounded()))
+ } ?? "nil"
DebugLogger.shared.benchmark(
"TYPING_BENCH",
- message: "asr_type_dispatched chars=\(text.count) preferredPID=\(preferredTargetPID.map { String($0) } ?? "nil") textReadyToDispatchMs=\(textReadyAt.map { String(Int(((dispatchedAt - $0) * 1000).rounded())) } ?? "nil")",
+ message: "asr_type_dispatched chars=\(text.count) preferredPID=\(preferredTargetPID.map { String($0) } ?? "nil") textReadyToDispatchMs=\(textReadyToDispatchMs)",
source: "TypingBenchmark"
)
}
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index 259c9a05..c52c4de6 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -256,7 +256,16 @@ final class TypingService {
/// Types/inserts text, optionally preferring a specific target PID for CGEvent posting.
/// This helps when our overlay temporarily has focus; we can still target the original app.
func typeTextInstantly(_ text: String, preferredTargetPID: pid_t?, textReadyAt: TimeInterval?) {
+ self.typeOutputPlanInstantly(.plain(text), preferredTargetPID: preferredTargetPID, textReadyAt: textReadyAt)
+ }
+
+ func typeOutputPlanInstantly(
+ _ plan: DictationLiteralOutputPlan,
+ preferredTargetPID: pid_t?,
+ textReadyAt: TimeInterval?
+ ) {
let requestedAt = ProcessInfo.processInfo.systemUptime
+ let text = plan.plainText
let mode = self.textInsertionMode
let settleDelayMs: Int = {
if mode == .reliablePaste {
@@ -266,7 +275,7 @@ final class TypingService {
}()
let textReadyAge = textReadyAt.map { Self.elapsedMs(from: $0, to: requestedAt) }
self.bench(
- "request chars=\(text.count) mode=\(mode.rawValue) preferredPID=\(preferredTargetPID.map { String($0) } ?? "nil") textReadyAgeMs=\(textReadyAge.map { String($0) } ?? "nil")"
+ "request chars=\(text.count) mode=\(mode.rawValue) autocompleteSteps=\(plan.steps.count) preferredPID=\(preferredTargetPID.map { String($0) } ?? "nil") textReadyAgeMs=\(textReadyAge.map { String($0) } ?? "nil")"
)
self.log("[TypingService] ENTRY: typeTextInstantly called with text length: \(text.count)")
self.log("[TypingService] Text preview: \"\(String(text.prefix(100)))\"")
diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
index e370d290..12f9c424 100644
--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
@@ -261,6 +261,194 @@ final class DictationE2ETests: XCTestCase {
}
}
+ func testSlashCommandFormattingNormalizesSpokenAndLiteralCommands() {
+ XCTAssertEqual(
+ ASRService.applySlashCommandFormatting("Run slash status and then / model."),
+ "Run /status and then /model."
+ )
+ XCTAssertEqual(
+ ASRService.applySlashCommandFormatting("Type forward slash fix-ci."),
+ "Type /fix-ci."
+ )
+ XCTAssertEqual(
+ ASRService.applySlashCommandFormatting("slash compact"),
+ "/compact"
+ )
+ }
+
+ func testSlashCommandFormattingLeavesNonCommandSlashUsageAlone() {
+ let text = "Use 1/2 and and/or. Open src slash services. Go to https slash slash example dot com. Slash and burn."
+
+ XCTAssertEqual(
+ ASRService.applySlashCommandFormatting(text),
+ text
+ )
+ }
+
+ func testMentionFormattingExplicitPhrasesWorkWithoutAppContext() {
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting("tag Paul"),
+ "@Paul"
+ )
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting("mention Paul Heinz, please"),
+ "@Paul Heinz, please"
+ )
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting("at sign maxgaav"),
+ "@maxgaav"
+ )
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting("at the rate Sarah"),
+ "@Sarah"
+ )
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting("mention Paul please"),
+ "@Paul please"
+ )
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting("tag Paul tomorrow"),
+ "@Paul tomorrow"
+ )
+ }
+
+ func testMentionFormattingRelaxedAtNameRequiresMentionAppContext() {
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting(
+ "at Paul can you check this",
+ appName: "Slack",
+ bundleID: "com.tinyspeck.slackmacgap"
+ ),
+ "@Paul can you check this"
+ )
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting(
+ "hey at Paul Heinz can you check this",
+ appName: "Discord",
+ bundleID: "com.hnc.Discord"
+ ),
+ "hey @Paul Heinz can you check this"
+ )
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting("at Paul can you check this", appName: "Notes", bundleID: "com.apple.Notes"),
+ "at Paul can you check this"
+ )
+ }
+
+ func testMentionFormattingLeavesProseAlone() {
+ let text = "I am at the store. Meet me at lunch. I am at Paul. Look at Paul's message."
+
+ XCTAssertEqual(
+ ASRService.applyMentionFormatting(text, appName: "Slack", bundleID: "com.tinyspeck.slackmacgap"),
+ text
+ )
+ }
+
+ func testMentionOutputPlanDoesNotAutoConfirmAutocomplete() {
+ let plan = ASRService.makeDictationLiteralOutputPlan(
+ for: "@Paul can you check this",
+ appName: "Slack",
+ bundleID: "com.tinyspeck.slackmacgap"
+ )
+
+ XCTAssertEqual(plan.steps, [.text("@Paul can you check this")])
+ XCTAssertEqual(plan.plainText, "@Paul can you check this")
+ }
+
+ func testMentionOutputPlanStaysPlainOutsideMentionApps() {
+ let text = "@Paul can you check this"
+
+ XCTAssertEqual(
+ ASRService.makeDictationLiteralOutputPlan(
+ for: text,
+ appName: "Notes",
+ bundleID: "com.apple.Notes"
+ ).steps,
+ [.text(text)]
+ )
+ }
+
+ func testTerminalLiteralAutocompleteSpacingRemovesTrailingSpaceForTargetApps() {
+ XCTAssertEqual(
+ ASRService.applyTerminalLiteralAutocompleteSpacing(
+ "/model ",
+ appName: "Codex",
+ bundleID: "com.openai.codex"
+ ),
+ "/model"
+ )
+ XCTAssertEqual(
+ ASRService.applyTerminalLiteralAutocompleteSpacing(
+ "hey @Paul Heinz ",
+ appName: "Slack",
+ bundleID: "com.tinyspeck.slackmacgap"
+ ),
+ "hey @Paul Heinz"
+ )
+ XCTAssertEqual(
+ ASRService.applyTerminalLiteralAutocompleteSpacing(
+ " @Paul ",
+ appName: "Slack",
+ bundleID: "com.tinyspeck.slackmacgap"
+ ),
+ " @Paul"
+ )
+ XCTAssertEqual(
+ ASRService.makeDictationLiteralOutputPlan(
+ for: "@ross.winn ",
+ appName: "Discord",
+ bundleID: "com.hnc.Discord"
+ ).plainText,
+ "@ross.winn"
+ )
+ }
+
+ func testTerminalLiteralAutocompleteSpacingLeavesNonAutocompleteTextAlone() {
+ XCTAssertEqual(
+ ASRService.applyTerminalLiteralAutocompleteSpacing(
+ "/model ",
+ appName: "Notes",
+ bundleID: "com.apple.Notes"
+ ),
+ "/model "
+ )
+ XCTAssertEqual(
+ ASRService.applyTerminalLiteralAutocompleteSpacing(
+ "Run /status please ",
+ appName: "Codex",
+ bundleID: "com.openai.codex"
+ ),
+ "Run /status please "
+ )
+ XCTAssertEqual(
+ ASRService.applyTerminalLiteralAutocompleteSpacing(
+ "@Paul can you check this ",
+ appName: "Slack",
+ bundleID: "com.tinyspeck.slackmacgap"
+ ),
+ "@Paul can you check this "
+ )
+ }
+
+ func testSlashCommandOutputPlanDoesNotAutoConfirmAutocomplete() {
+ XCTAssertEqual(
+ ASRService.makeDictationLiteralOutputPlan(
+ for: "/goal update the plan",
+ appName: "Codex",
+ bundleID: "com.openai.codex"
+ ).steps,
+ [.text("/goal update the plan")]
+ )
+ XCTAssertEqual(
+ ASRService.makeDictationLiteralOutputPlan(
+ for: "Run /status please",
+ appName: "Codex",
+ bundleID: "com.openai.codex"
+ ).steps,
+ [.text("Run /status please")]
+ )
+ }
+
func testDictionaryTrainingNormalizesSamplesAndIgnoresIntendedText() {
let triggers = CustomDictionaryTrainingMerge.normalizedTriggers(
from: [" Fluid Voice. ", "FluidVoice", "fluid voice", " "],