Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more
fix(spoken-send): hold the armed phrase across noisy partials
altic-dev60480451a5e9
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex b7b57bdd..b1eb2499 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -358,6 +358,7 @@ struct ContentView: View {@State private var overlayLifecycleID: UInt64 = 0@State private var spokenSendAutoStopTask: Task<Void, Never>?@State private var spokenSendAutoStopTriggered = false+ @State private var spokenSendArming = SpokenSendArmingState()@State private var spokenSendCountdownStartedAt: TimeInterval?@State private var spokenSendLastVoiceActivityAt: TimeInterval = 0@State private var spokenSendVoiceActivityCancellable: AnyCancellable?@@ -2884,10 +2885,11 @@ struct ContentView: View {bundleID: appInfo.bundleId,windowTitle: appInfo.windowTitle)- let spokenSendParse = SpokenSendParser.parse(+ let spokenSendParse = SpokenSendParser.parseArmed(punctuationFormattedText,phrase: self.settings.spokenSendPhrase,- enabled: route == .normal && self.settings.spokenSendEnabled+ enabled: route == .normal && self.settings.spokenSendEnabled,+ wasArmed: self.spokenSendArming.wasArmed)self.updateSpokenSendIndicatorForFinalParse(shouldSend: spokenSendParse.shouldSend)let normalizedTranscribedText = spokenSendParse.text@@ -3481,6 +3483,7 @@ struct ContentView: View {self.spokenSendAutoStopTask = nilself.stopSpokenSendVoiceActivityMonitoring()self.spokenSendAutoStopTriggered = false+ self.spokenSendArming.reset()self.spokenSendCountdownStartedAt = nilself.spokenSendLastVoiceActivityAt = ProcessInfo.processInfo.systemUptimeself.overlayLifecycleID &+= 1@@ -3491,18 +3494,24 @@ struct ContentView: View {private func handleSpokenSendPartialTranscription(_ text: String) {guard self.settings.spokenSendEnabled else { return }let isDictationMode = self.activeRecordingMode == .dictate || self.activeRecordingMode == .promptMode- let shouldStop = isDictationMode &&+ let isEligible = isDictationMode &&self.currentDictationOutputRouteForHotkeyStop() == .normal &&self.asr.isRunning &&- !self.spokenSendAutoStopTriggered &&- SpokenSendParser.shouldStopImmediately(- text,- phrase: self.settings.spokenSendPhrase,- spokenSendEnabled: self.settings.spokenSendEnabled,- sendImmediatelyEnabled: self.settings.spokenSendImmediatelyEnabled- )+ !self.spokenSendAutoStopTriggered+ let isArmed = self.spokenSendArming.update(+ partial: text,+ isEligible: isEligible,+ phrase: self.settings.spokenSendPhrase+ )++ guard self.settings.spokenSendImmediatelyEnabled else {+ if isEligible {+ NotchContentState.shared.setSpokenSendIndicatorState(isArmed ? .detected : .hidden)+ }+ return+ }- guard shouldStop else {+ guard isArmed else {self.spokenSendAutoStopTask?.cancel()self.spokenSendAutoStopTask = nilself.stopSpokenSendVoiceActivityMonitoring()@@ -3541,7 +3550,8 @@ struct ContentView: View {phrase: self.settings.spokenSendPhrase,spokenSendEnabled: self.settings.spokenSendEnabled,sendImmediatelyEnabled: self.settings.spokenSendImmediatelyEnabled,- quietDuration: quietDuration+ quietDuration: quietDuration,+ armedText: self.spokenSendArming.armedText)else {if self.overlayLifecycleID == expectedOverlayLifecycleID,diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swiftindex a3653bf2..d11035d8 100644--- a/Sources/Fluid/Services/MenuBarManager.swift+++ b/Sources/Fluid/Services/MenuBarManager.swift@@ -165,18 +165,6 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {.receive(on: DispatchQueue.main).sink { [weak self] newText inguard self != nil else { return }- if asrService.isRunning,- NotchContentState.shared.mode == .dictation,- SettingsStore.shared.spokenSendEnabled,- !SettingsStore.shared.spokenSendImmediatelyEnabled- {- let detected = SpokenSendParser.parse(- newText,- phrase: SettingsStore.shared.spokenSendPhrase,- enabled: true- ).shouldSend- NotchContentState.shared.setSpokenSendIndicatorState(detected ? .detected : .hidden)- }if NotchOverlayManager.shared.shouldShowOrTrackLivePreviewText {NotchOverlayManager.shared.updateTranscriptionText(newText)}diff --git a/Sources/Fluid/Services/SpokenSendParser.swift b/Sources/Fluid/Services/SpokenSendParser.swiftindex 35ac9804..226be135 100644--- a/Sources/Fluid/Services/SpokenSendParser.swift+++ b/Sources/Fluid/Services/SpokenSendParser.swift@@ -5,6 +5,34 @@ struct SpokenSendParseResult: Equatable {let shouldSend: Bool}+/// Tracks whether streaming partials have armed the spoken send.+struct SpokenSendArmingState: Equatable {+ private(set) var armedText: String?++ var wasArmed: Bool { self.armedText != nil }++ mutating func reset() {+ self.armedText = nil+ }++ /// Returns whether this partial keeps the send armed. Only a live partial may+ /// disarm, so the final stop still knows the send was armed.+ mutating func update(partial: String, isEligible: Bool, phrase: String) -> Bool {+ guard isEligible else { return false }+ if SpokenSendParser.parse(partial, phrase: phrase, enabled: true).shouldSend {+ self.armedText = partial+ return true+ }+ if let armedText = self.armedText,+ SpokenSendParser.wordCount(partial) <= SpokenSendParser.wordCount(armedText)+ {+ return true+ }+ self.armedText = nil+ return false+ }+}+enum SpokenSendParser {static let immediateStopSettleDuration: TimeInterval = 1.5static let immediateStopSettleNanoseconds: UInt64 = 1_500_000_000@@ -16,10 +44,11 @@ enum SpokenSendParser {_ text: String,phrase: String,spokenSendEnabled: Bool,- sendImmediatelyEnabled: Bool+ sendImmediatelyEnabled: Bool,+ armedText: String? = nil) -> Bool {sendImmediatelyEnabled &&- self.parse(text, phrase: phrase, enabled: spokenSendEnabled).shouldSend+ self.isArmed(text, armedText: armedText, phrase: phrase, enabled: spokenSendEnabled)}static func canCompleteImmediateStop(@@ -27,17 +56,64 @@ enum SpokenSendParser {phrase: String,spokenSendEnabled: Bool,sendImmediatelyEnabled: Bool,- quietDuration: TimeInterval+ quietDuration: TimeInterval,+ armedText: String? = nil) -> Bool {quietDuration >= self.immediateStopRequiredSilenceDuration &&self.shouldStopImmediately(text,phrase: phrase,spokenSendEnabled: spokenSendEnabled,- sendImmediatelyEnabled: sendImmediatelyEnabled+ sendImmediatelyEnabled: sendImmediatelyEnabled,+ armedText: armedText)}+ /// Streaming partials re-decode the same audio every few hundred milliseconds, so the trailing+ /// phrase can flip between "send it", "sent it" and "send" without the speaker saying anything new.+ /// Once armed, stay armed while a later partial has no more words than the armed transcript.+ static func isArmed(_ text: String, armedText: String?, phrase: String, enabled: Bool) -> Bool {+ guard enabled else { return false }+ if self.parse(text, phrase: phrase, enabled: true).shouldSend {+ return true+ }+ guard let armedText else { return false }+ return self.wordCount(text) <= self.wordCount(armedText)+ }++ /// Like `parse`, but when the send was already armed from streaming partials it also accepts+ /// a final transcript whose trailing words are a near miss of the phrase, such as "sent it".+ static func parseArmed(_ text: String, phrase: String, enabled: Bool, wasArmed: Bool) -> SpokenSendParseResult {+ let strict = self.parse(text, phrase: phrase, enabled: enabled)+ guard enabled, wasArmed, !strict.shouldSend, strict.text == text else { return strict }++ let phraseWords = self.words(phrase)+ let textWords = self.words(text)+ guard !phraseWords.isEmpty else { return strict }++ let normalizedPhrase = phraseWords.map { self.normalizeWord($0.text) }.joined()+ // Very short phrases have no room for a near miss ("end" must not pass as "send").+ let tolerance = normalizedPhrase.count >= 5 ? max(1, normalizedPhrase.count / 5) : 0+ guard tolerance > 0 else { return strict }++ // The phrase may come back merged ("sendit") or split, so try every tail length up to the phrase length.+ for tailLength in stride(from: min(phraseWords.count, textWords.count), through: 1, by: -1) {+ let tail = textWords.suffix(tailLength)+ let precedingWord = textWords.dropLast(tailLength).last+ if precedingWord.map({ self.normalizeWord($0.text) }) == "literal" { continue }++ let normalizedTail = tail.map { self.normalizeWord($0.text) }.joined()+ guard normalizedTail.first == normalizedPhrase.first,+ self.editDistance(normalizedTail, normalizedPhrase) <= tolerance,+ let firstTailWord = tail.first+ else { continue }++ let prefix = String(text[..<firstTailWord.range.lowerBound])+ return SpokenSendParseResult(text: self.polishCommandPrefix(prefix), shouldSend: true)+ }+ return strict+ }+static func shouldCancelCountdownForVoiceActivity(countdownStartedAt: TimeInterval,voiceActivityAt: TimeInterval@@ -111,6 +187,56 @@ enum SpokenSendParser {return SpokenSendParseResult(text: cleaned, shouldSend: true)}+ private struct Word {+ let text: Substring+ let range: Range<String.Index>+ }++ private static func words(_ text: String) -> [Word] {+ var words: [Word] = []+ var index = text.startIndex+ while index < text.endIndex {+ guard !text[index].isWhitespace else {+ index = text.index(after: index)+ continue+ }+ let start = index+ while index < text.endIndex, !text[index].isWhitespace {+ index = text.index(after: index)+ }+ let word = text[start..<index]+ if word.contains(where: { $0.isLetter || $0.isNumber }) {+ words.append(Word(text: word, range: start..<index))+ }+ }+ return words+ }++ static func wordCount(_ text: String) -> Int {+ self.words(text).count+ }++ private static func normalizeWord<S: StringProtocol>(_ word: S) -> String {+ String(word.lowercased().filter { $0.isLetter || $0.isNumber })+ }++ private static func editDistance(_ lhs: String, _ rhs: String) -> Int {+ let a = Array(lhs), b = Array(rhs)+ guard !a.isEmpty else { return b.count }+ guard !b.isEmpty else { return a.count }+ var previous = Array(0...b.count)+ for (i, ca) in a.enumerated() {+ var current = [i + 1]+ current.reserveCapacity(b.count + 1)+ for (j, cb) in b.enumerated() {+ let substitution = previous[j] + (ca == cb ? 0 : 1)+ current.append(min(previous[j + 1] + 1, current[j] + 1, substitution))+ }+ previous = current+ }+ return previous[b.count]+ }+private static func polishCommandPrefix(_ text: String) -> String {var polished = text.trimmingCharacters(in: .whitespacesAndNewlines)while let last = polished.last, [",", ";", ":", "-", "–", "—"].contains(last) {diff --git a/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift b/Tests/FluidDictationIntegrationTests/SpokenSendTests.swiftindex 95b81e06..b426afa5 100644--- a/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift+++ b/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift@@ -144,6 +144,198 @@ final class SpokenSendTests: XCTestCase {)}+ func testArmedSendSurvivesNoisyStreamingRefinements() {+ let armed = "Ready to go, send it."+ for noisy in ["Ready to go, sent it.", "Ready to go, send", "Ready to go send it", "Ready to go —", ""] {+ XCTAssertTrue(+ SpokenSendParser.isArmed(noisy, armedText: armed, phrase: "send it", enabled: true),+ "\(noisy) must keep the send armed"+ )+ }+ XCTAssertFalse(+ SpokenSendParser.isArmed("Ready to go, send it to Bob", armedText: armed, phrase: "send it", enabled: true)+ )+ XCTAssertFalse(+ SpokenSendParser.isArmed("Ready to go, sent it.", armedText: nil, phrase: "send it", enabled: true)+ )+ XCTAssertFalse(+ SpokenSendParser.isArmed("Ready to go, send it.", armedText: armed, phrase: "send it", enabled: false)+ )+ }++ func testArmedCountdownCompletesThroughNoisyPartial() {+ XCTAssertTrue(+ SpokenSendParser.canCompleteImmediateStop(+ "Ready, sent it.",+ phrase: "send it",+ spokenSendEnabled: true,+ sendImmediatelyEnabled: true,+ quietDuration: SpokenSendParser.immediateStopRequiredSilenceDuration,+ armedText: "Ready, send it."+ )+ )+ XCTAssertFalse(+ SpokenSendParser.canCompleteImmediateStop(+ "Ready, send it after I finish this sentence.",+ phrase: "send it",+ spokenSendEnabled: true,+ sendImmediatelyEnabled: true,+ quietDuration: SpokenSendParser.immediateStopRequiredSilenceDuration,+ armedText: "Ready, send it."+ )+ )+ }++ func testArmedFinalParseAcceptsNearMissPhrase() {+ XCTAssertEqual(+ SpokenSendParser.parseArmed("Ready to go, sent it.", phrase: "send it", enabled: true, wasArmed: true),+ SpokenSendParseResult(text: "Ready to go.", shouldSend: true)+ )+ XCTAssertEqual(+ SpokenSendParser.parseArmed("Ready to go, Send It", phrase: "send it", enabled: true, wasArmed: false),+ SpokenSendParseResult(text: "Ready to go.", shouldSend: true)+ )+ XCTAssertEqual(+ SpokenSendParser.parseArmed("Ready to go, sent it.", phrase: "send it", enabled: true, wasArmed: false),+ SpokenSendParseResult(text: "Ready to go, sent it.", shouldSend: false)+ )+ XCTAssertEqual(+ SpokenSendParser.parseArmed("Ready to go, send it to Bob", phrase: "send it", enabled: true, wasArmed: true),+ SpokenSendParseResult(text: "Ready to go, send it to Bob", shouldSend: false)+ )+ XCTAssertEqual(+ SpokenSendParser.parseArmed("Please type literal send it.", phrase: "send it", enabled: true, wasArmed: true),+ SpokenSendParseResult(text: "Please type send it", shouldSend: false)+ )+ }++ // MARK: - Adversarial: arming state machine++ private func run(_ partials: [String], phrase: String = "send it", eligible: Bool = true) -> (results: [Bool], state: SpokenSendArmingState) {+ var state = SpokenSendArmingState()+ let results = partials.map { state.update(partial: $0, isEligible: eligible, phrase: phrase) }+ return (results, state)+ }++ func testArmingSurvivesRealisticNoisyStream() {+ let stream = ["Ready", "Ready send", "Ready send it", "Ready sent it.", "Ready send", "Ready, send it.", "Ready, SEND IT"]+ let (results, state) = self.run(stream)+ XCTAssertEqual(results, [false, false, true, true, true, true, true])+ XCTAssertTrue(state.wasArmed)+ }++ func testArmingDisarmsWhenSpeechContinues() {+ let (results, state) = self.run(["Ready send it", "Ready send it to", "Ready send it to Bob"])+ XCTAssertEqual(results, [true, false, false])+ XCTAssertFalse(state.wasArmed)+ }++ func testArmingReArmsAfterContinuation() {+ let (results, state) = self.run(["Ready send it", "Ready send it to Bob", "Ready send it to Bob send it"])+ XCTAssertEqual(results, [true, false, true])+ XCTAssertEqual(state.armedText, "Ready send it to Bob send it")+ }++ func testArmingIsKeptAcrossTheStopPartial() {+ var state = SpokenSendArmingState()+ XCTAssertTrue(state.update(partial: "Ready send it", isEligible: true, phrase: "send it"))+ XCTAssertFalse(state.update(partial: "", isEligible: false, phrase: "send it"))+ XCTAssertTrue(state.wasArmed, "an ineligible partial must not forget the armed send")+ state.reset()+ XCTAssertFalse(state.wasArmed)+ }++ func testArmingNeverStartsFromANearMiss() {+ let (results, state) = self.run(["Ready sent it", "Ready sent it.", "Ready send"])+ XCTAssertEqual(results, [false, false, false])+ XCTAssertFalse(state.wasArmed)+ }++ func testArmingIgnoresPhraseInTheMiddle() {+ let (results, _) = self.run(["send it now please", "send it now please thanks"])+ XCTAssertEqual(results, [false, false])+ }++ func testArmingHoldsThroughPunctuationOnlyRefinements() {+ let (results, _) = self.run(["Ready send it", "Ready — send it …", "Ready, send it. —"])+ XCTAssertEqual(results, [true, true, true])+ }++ func testArmingWithCustomPhraseContainingRegexCharacters() {+ let (results, state) = self.run(["Done. ship it (now)", "Done. ship it (now"], phrase: "ship it (now)")+ XCTAssertEqual(results, [true, true])+ XCTAssertTrue(state.wasArmed)+ }++ func testArmingWithPunctuationOnlyPhraseDoesNotCrash() {+ var state = SpokenSendArmingState()+ _ = state.update(partial: "Hi !!!", isEligible: true, phrase: "!!!")+ _ = SpokenSendParser.parseArmed("Hi !!!", phrase: "!!!", enabled: true, wasArmed: true)+ _ = SpokenSendParser.parseArmed("Hi", phrase: " ", enabled: true, wasArmed: true)+ }++ func testArmingStaysFastOnVeryLongPartials() {+ let long = Array(repeating: "word", count: 5000).joined(separator: " ") + " send it"+ var state = SpokenSendArmingState()+ let started = Date()+ for _ in 0..<20 {+ XCTAssertTrue(state.update(partial: long, isEligible: true, phrase: "send it"))+ XCTAssertTrue(state.update(partial: long + ".", isEligible: true, phrase: "send it"))+ }+ XCTAssertLessThan(Date().timeIntervalSince(started), 1.0)+ }++ // MARK: - Adversarial: near-miss final parse++ func testNearMissIsRefusedForVeryShortPhrases() {+ XCTAssertEqual(+ SpokenSendParser.parseArmed("The end", phrase: "send", enabled: true, wasArmed: true),+ SpokenSendParseResult(text: "The end", shouldSend: false)+ )+ XCTAssertEqual(+ SpokenSendParser.parseArmed("The send", phrase: "send", enabled: true, wasArmed: true),+ SpokenSendParseResult(text: "The.", shouldSend: true)+ )+ }++ func testNearMissAllowsOneEditForTwoWordPhrase() {+ for tail in ["sent it", "sand it", "send if", "sendit", "Send It"] {+ XCTAssertEqual(+ SpokenSendParser.parseArmed("Ready \(tail)", phrase: "send it", enabled: true, wasArmed: true),+ SpokenSendParseResult(text: "Ready.", shouldSend: true),+ tail+ )+ }+ for tail in ["sending", "send", "sent him", "end it", "spend a bit", "bend it", "tend it"] {+ XCTAssertFalse(+ SpokenSendParser.parseArmed("Ready \(tail)", phrase: "send it", enabled: true, wasArmed: true).shouldSend,+ tail+ )+ }+ }++ func testNearMissRequiresPhraseAtTheVeryEnd() {+ XCTAssertFalse(+ SpokenSendParser.parseArmed("Ready sent it now", phrase: "send it", enabled: true, wasArmed: true).shouldSend+ )+ }++ func testNearMissIsIgnoredWhenDisabledOrNotArmed() {+ XCTAssertFalse(SpokenSendParser.parseArmed("Ready sent it", phrase: "send it", enabled: false, wasArmed: true).shouldSend)+ XCTAssertFalse(SpokenSendParser.parseArmed("Ready sent it", phrase: "send it", enabled: true, wasArmed: false).shouldSend)+ }++ func testNearMissOnEmptyOrShortTextIsSafe() {+ XCTAssertEqual(+ SpokenSendParser.parseArmed("", phrase: "send it", enabled: true, wasArmed: true),+ SpokenSendParseResult(text: "", shouldSend: false)+ )+ XCTAssertEqual(+ SpokenSendParser.parseArmed("it", phrase: "send it", enabled: true, wasArmed: true),+ SpokenSendParseResult(text: "it", shouldSend: false)+ )+ }+func testImmediateStopCompletionRequiresTerminalPhraseAndSilence() {let arguments = (text: "Ready, send it.",