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

stop canceled insertion fallbacks and preserve suggestion dismissal

altic-dev40f6c7bd2bff
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index daa5edf5..92dac7d3 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -4989,9 +4989,9 @@ struct ContentView: View {
self.hotkeyManager?.setHotkeyMode(self.hotkeyMode)
// Set cancel callback for Escape key handling (closes transient UI, resets recording state)
- // Returns true if it handled something (so GlobalHotkeyManager knows to consume the event)
+ // Distinguishes suggestion dismissal from recording cancellation.
self.hotkeyManager?.setCancelCallback {
- self.handleCancelShortcut()
+ self.handleCancelShortcutResult()
}
// Re-insert the most recent transcription on demand (no clipboard involved).
@@ -5025,12 +5025,16 @@ struct ContentView: View {
@discardableResult
private func handleCancelShortcut() -> Bool {
- if self.isSavingCancelledRecording { return true }
+ self.handleCancelShortcutResult() != .unhandled
+ }
+
+ private func handleCancelShortcutResult() -> GlobalHotkeyManager.CancelHandlingResult {
+ if self.isSavingCancelledRecording { return .cancelled }
var handled = false
if DictionaryCorrectionOverlayController.shared.isPresented {
DictionaryCorrectionOverlayController.shared.dismiss()
- handled = true
+ return .dismissedOverlay
}
if NotchOverlayManager.shared.isCommandOutputExpanded {
NotchOverlayManager.shared.hideExpandedCommandOutput()
@@ -5091,7 +5095,7 @@ struct ContentView: View {
self.spokenSendCountdownStartedAt = nil
self.hotkeyManager?.resetModifierOnlyShortcutTracking(reason: .cancel)
}
- return handled
+ return handled ? .cancelled : .unhandled
}
// MARK: - Model Management Helpers
diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swift
index a91b2f74..052eef81 100644
--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift
+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift
@@ -262,6 +262,12 @@ private final nonisolated class HotkeyState: @unchecked Sendable {
@MainActor
final class GlobalHotkeyManager: NSObject {
+ enum CancelHandlingResult {
+ case unhandled
+ case dismissedOverlay
+ case cancelled
+ }
+
private nonisolated(unsafe) var state = HotkeyState()
private nonisolated(unsafe) var eventTap: CFMachPort?
private nonisolated(unsafe) var runLoopSource: CFRunLoopSource?
@@ -300,7 +306,7 @@ final class GlobalHotkeyManager: NSObject {
private var isRewriteRecordingProvider: (() -> Bool)?
private var isShortcutCaptureActiveProvider: (() -> Bool)?
private var shortcutCaptureHandler: ((NSEvent) -> NSEvent?)?
- private var cancelCallback: (() -> Bool)? // Returns true if handled
+ private var cancelCallback: (() -> CancelHandlingResult)?
private var pasteLastTranscriptionCallback: (() -> Void)?
private var hotkeyMode: HotkeyActivationMode = SettingsStore.shared.hotkeyMode
private let automaticTapThresholdSeconds: TimeInterval = 0.4
@@ -678,7 +684,7 @@ final class GlobalHotkeyManager: NSObject {
self.scheduleActiveShortcutLog(reason: "shortcuts updated")
}
- func setCancelCallback(_ callback: @escaping () -> Bool) {
+ func setCancelCallback(_ callback: @escaping () -> CancelHandlingResult) {
self.cancelCallback = callback
}
@@ -1270,21 +1276,27 @@ final class GlobalHotkeyManager: NSObject {
!isAutorepeat,
self.activePrimaryShortcutPress?.keyboardKeyCode == keyCode
{ self.activePrimaryShortcutPress = nil }
- self.markOtherInputDuringModifierOnly()
-
// The application owns cancellation output; fallback managers only discard capture.
if SettingsStore.shared.cancelRecordingHotkeyShortcut?.matches(keyCode: keyCode, modifiers: eventModifiers) == true {
- var handled = self.cancelCallback?() ?? false
+ let result = self.cancelCallback?() ?? .unhandled
+ // Closing a suggestion must preserve the held shortcut and capture.
+ if result == .dismissedOverlay { return nil }
+ var handled = result == .cancelled
if !handled, self.asrService.isRunningOrStarting {
Task { @MainActor in await self.asrService.stopWithoutTranscription() }
handled = true
}
- if handled || self.pendingRecordingActionCounts.values.contains(where: { $0 > 0 }) {
+ let hasPendingPress = self.state.withLock {
+ self.state.activePrimaryShortcutPress != nil || self.state.activeModifierOnlyType != nil
+ }
+ if handled || hasPendingPress || self.pendingRecordingActionCounts.values.contains(where: { $0 > 0 }) {
self.resetModifierOnlyShortcutTracking(reason: .cancel)
return nil
}
}
+ self.markOtherInputDuringModifierOnly()
+
// Check the "paste last transcription" shortcut (a one-shot action, like cancel).
if SettingsStore.shared.pasteLastTranscriptionShortcutEnabled,
let pasteShortcut = SettingsStore.shared.pasteLastTranscriptionHotkeyShortcut,
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index 7f1898c7..d500c76d 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -772,25 +772,34 @@ final class TypingService {
let valid = DispatchQueue.main.sync { MainActor.assumeIsolated { isOutputValid() } }
guard valid else { continuation.resume(returning: false); return }
continuation.resume(
- returning: self.insertTextDirectly(text, preferredTargetPID: preferredTargetPID)
+ returning: self.insertTextDirectly(text, preferredTargetPID: preferredTargetPID, isOutputValid: {
+ DispatchQueue.main.sync { MainActor.assumeIsolated { isOutputValid() } }
+ })
)
}
}
}
- private nonisolated func insertTextDirectly(_ text: String, preferredTargetPID: pid_t?) -> Bool {
+ nonisolated static func attemptDirectInsertion(isOutputValid: () -> Bool, insert: () -> Bool) -> Bool {
+ guard isOutputValid() else { return false }
+ return insert()
+ }
+
+ private nonisolated func insertTextDirectly(_ text: String, preferredTargetPID: pid_t?, isOutputValid: () -> Bool) -> Bool {
self.log("[TypingService] insertTextInstantly called with \(text.count) characters")
self.log("[TypingService] Attempting to type text: \"\(text.prefix(50))\(text.count > 50 ? "..." : "")\"")
if let preferredTargetPID, preferredTargetPID > 0 {
self.log("[TypingService] Experimental Direct Typing mode: trying preferred PID unicode insertion first")
- if self.insertTextBulkInstant(text, targetPID: preferredTargetPID) {
+ if Self.attemptDirectInsertion(isOutputValid: isOutputValid, insert: { self.insertTextBulkInstant(text, targetPID: preferredTargetPID, isOutputValid: isOutputValid) }) {
self.log("[TypingService] SUCCESS: Preferred PID CGEvent insertion completed")
return true
}
self.log("[TypingService] Preferred PID CGEvent insertion failed, continuing fallback pipeline")
}
+ guard isOutputValid() else { return false }
+
// Get frontmost app info
if let frontApp = NSWorkspace.shared.frontmostApplication {
self.log("[TypingService] Target app: \(frontApp.localizedName ?? "Unknown") (\(frontApp.bundleIdentifier ?? "Unknown"))")
@@ -818,7 +827,7 @@ final class TypingService {
// This is the most reliable method for Terminals, Electron apps (Discord, VSCode), etc.
if let focusedPID = focusInfo?.pid {
self.log("[TypingService] Trying CGEvent insertion targeting focused PID \(focusedPID)")
- if self.insertTextBulkInstant(text, targetPID: focusedPID) {
+ if Self.attemptDirectInsertion(isOutputValid: isOutputValid, insert: { self.insertTextBulkInstant(text, targetPID: focusedPID, isOutputValid: isOutputValid) }) {
self.log("[TypingService] SUCCESS: CGEvent focused-PID insertion completed")
return true
}
@@ -826,7 +835,7 @@ final class TypingService {
// Secondary: Try Accessibility insertion into the actual focused element
self.log("[TypingService] Trying Accessibility focused-element insertion")
- if self.insertTextViaAccessibility(text) {
+ if Self.attemptDirectInsertion(isOutputValid: isOutputValid, insert: { self.insertTextViaAccessibility(text, isOutputValid: isOutputValid) }) {
self.log("[TypingService] SUCCESS: Accessibility insertion completed")
return true
}
@@ -834,7 +843,7 @@ final class TypingService {
// HID Fallback if PID targeting failed
if focusInfo?.pid == nil {
self.log("[TypingService] No focused PID available, trying HID CGEvent insertion")
- if self.insertTextBulkHIDInstant(text) {
+ if Self.attemptDirectInsertion(isOutputValid: isOutputValid, insert: { self.insertTextBulkHIDInstant(text, isOutputValid: isOutputValid) }) {
self.log("[TypingService] SUCCESS: CGEvent HID insertion completed")
return true
}
@@ -993,7 +1002,7 @@ final class TypingService {
return ["AXTextField", "AXTextArea", "AXSearchField", "AXComboBox", "AXWebArea", "AXGroup"].contains(currentRole)
}
- private nonisolated func insertTextBulkInstant(_ text: String, targetPID: pid_t) -> Bool {
+ private nonisolated func insertTextBulkInstant(_ text: String, targetPID: pid_t, isOutputValid: () -> Bool) -> Bool {
self.log("[TypingService] Starting chunked bulk CGEvent insertion (NO CLIPBOARD) to PID \(targetPID)")
guard targetPID > 0 else {
@@ -1004,17 +1013,17 @@ final class TypingService {
let utf16Array = Array(text.utf16)
self.log("[TypingService] Converting \(text.count) characters to CGEvents (UTF16 count \(utf16Array.count))")
- return self.postUnicodeChunks(utf16Array, destinationDescription: "PID \(targetPID)") { event in
+ return self.postUnicodeChunks(utf16Array, destinationDescription: "PID \(targetPID)", isOutputValid: isOutputValid) { event in
event.postToPid(targetPID)
}
}
- private nonisolated func insertTextBulkHIDInstant(_ text: String) -> Bool {
+ private nonisolated func insertTextBulkHIDInstant(_ text: String, isOutputValid: () -> Bool) -> Bool {
self.log("[TypingService] Starting chunked bulk CGEvent insertion via HID (NO PID)")
let utf16Array = Array(text.utf16)
- return self.postUnicodeChunks(utf16Array, destinationDescription: "HID tap") { event in
+ return self.postUnicodeChunks(utf16Array, destinationDescription: "HID tap", isOutputValid: isOutputValid) { event in
event.post(tap: .cghidEventTap)
}
}
@@ -1022,6 +1031,7 @@ final class TypingService {
private nonisolated func postUnicodeChunks(
_ utf16Array: [UInt16],
destinationDescription: String,
+ isOutputValid: () -> Bool,
post: (CGEvent) -> Void
) -> Bool {
guard utf16Array.isEmpty == false else { return true }
@@ -1046,6 +1056,7 @@ final class TypingService {
keyDown.keyboardSetUnicodeString(stringLength: chunkLength, unicodeString: chunkPointer)
keyUp.keyboardSetUnicodeString(stringLength: chunkLength, unicodeString: chunkPointer)
+ guard isOutputValid() else { return -1 }
post(keyDown)
post(keyUp)
@@ -1081,7 +1092,7 @@ final class TypingService {
(0xdc00...0xdfff).contains(value)
}
- private nonisolated func insertTextViaAccessibility(_ text: String) -> Bool {
+ private nonisolated func insertTextViaAccessibility(_ text: String, isOutputValid: () -> Bool) -> Bool {
self.log("[TypingService] Starting Accessibility API insertion")
// Try multiple strategies to find text input element
@@ -1090,25 +1101,29 @@ final class TypingService {
self.log("[TypingService] Strategy 1: Getting focused UI element...")
if let textElement = getFocusedTextElement() {
self.log("[TypingService] Found focused text element")
- if self.tryAllTextInsertionMethods(textElement, text) {
+ if self.tryAllTextInsertionMethods(textElement, text, isOutputValid: isOutputValid) {
return true
}
}
+ guard isOutputValid() else { return false }
+
// Strategy 2: Traverse frontmost app UI hierarchy to find text elements
self.log("[TypingService] Strategy 2: Traversing app UI hierarchy...")
if let textElement = findTextElementInFrontmostApp() {
self.log("[TypingService] Found text element in app hierarchy")
- if self.tryAllTextInsertionMethods(textElement, text) {
+ if self.tryAllTextInsertionMethods(textElement, text, isOutputValid: isOutputValid) {
return true
}
}
+ guard isOutputValid() else { return false }
+
// Strategy 3: Find element with keyboard focus
self.log("[TypingService] Strategy 3: Looking for keyboard focus...")
if let textElement = findKeyboardFocusedElement() {
self.log("[TypingService] Found keyboard focused element")
- if self.tryAllTextInsertionMethods(textElement, text) {
+ if self.tryAllTextInsertionMethods(textElement, text, isOutputValid: isOutputValid) {
return true
}
}
@@ -1194,7 +1209,7 @@ final class TypingService {
return nil
}
- private nonisolated func tryAllTextInsertionMethods(_ element: AXUIElement, _ text: String) -> Bool {
+ private nonisolated func tryAllTextInsertionMethods(_ element: AXUIElement, _ text: String, isOutputValid: () -> Bool) -> Bool {
// Get element info for debugging
if let role = getElementAttribute(element, kAXRoleAttribute as CFString) {
self.log("[TypingService] Trying insertion on element with role: \(role)")
@@ -1205,23 +1220,23 @@ final class TypingService {
}
self.log("[TypingService] Trying approach 0: Insert at cursor via kAXSelectedTextRangeAttribute + kAXValueAttribute")
- if self.insertTextAtCursorUsingSelectedRange(element, text) {
+ if self.insertTextAtCursorUsingSelectedRange(element, text, isOutputValid: isOutputValid) {
return true
}
// Try multiple approaches for text insertion
self.log("[TypingService] Trying approach 1: Direct kAXValueAttribute")
- if self.setTextViaValue(element, text) {
+ if self.setTextViaValue(element, text, isOutputValid: isOutputValid) {
return true
}
self.log("[TypingService] Trying approach 2: kAXSelectedTextAttribute (replace selection)")
- if self.setTextViaSelection(element, text) {
+ if self.setTextViaSelection(element, text, isOutputValid: isOutputValid) {
return true
}
self.log("[TypingService] Trying approach 3: Insert text at insertion point")
- if self.insertTextAtInsertionPoint(element, text) {
+ if self.insertTextAtInsertionPoint(element, text, isOutputValid: isOutputValid) {
return true
}
@@ -1380,7 +1395,7 @@ final class TypingService {
return CFRange(location: start, length: end - start)
}
- private nonisolated func insertTextAtCursorUsingSelectedRange(_ element: AXUIElement, _ text: String) -> Bool {
+ private nonisolated func insertTextAtCursorUsingSelectedRange(_ element: AXUIElement, _ text: String, isOutputValid: () -> Bool) -> Bool {
guard let currentValue = self.getElementStringValue(element) else {
self.log("[TypingService] Cursor insert failed: could not read kAXValueAttribute")
return false
@@ -1402,6 +1417,7 @@ final class TypingService {
mutable.replaceCharacters(in: NSRange(location: range.location, length: range.length), with: text)
let newValue = mutable as String
+ guard isOutputValid() else { return false }
let setResult = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, newValue as CFString)
guard setResult == .success else {
self.log("[TypingService] Cursor insert failed: setting kAXValueAttribute error \(setResult.rawValue)")
@@ -1411,7 +1427,7 @@ final class TypingService {
// Move caret to just after inserted text (best-effort)
let insertedLen = (text as NSString).length
var newRange = CFRange(location: range.location + insertedLen, length: 0)
- if let axRange = AXValueCreate(.cfRange, &newRange) {
+ if isOutputValid(), let axRange = AXValueCreate(.cfRange, &newRange) {
_ = AXUIElementSetAttributeValue(element, kAXSelectedTextRangeAttribute as CFString, axRange)
}
@@ -1420,8 +1436,9 @@ final class TypingService {
}
/// Why is it working now? And why is it not working now?
- private nonisolated func setTextViaValue(_ element: AXUIElement, _ text: String) -> Bool {
+ private nonisolated func setTextViaValue(_ element: AXUIElement, _ text: String, isOutputValid: () -> Bool) -> Bool {
let cfText = text as CFString
+ guard isOutputValid() else { return false }
let result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, cfText)
if result == .success {
@@ -1433,13 +1450,15 @@ final class TypingService {
}
}
- private nonisolated func setTextViaSelection(_ element: AXUIElement, _ text: String) -> Bool {
+ private nonisolated func setTextViaSelection(_ element: AXUIElement, _ text: String, isOutputValid: () -> Bool) -> Bool {
// First, select all existing text
+ guard isOutputValid() else { return false }
let selectAllResult = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, "" as CFString)
self.log("[TypingService] Select all result: \(selectAllResult.rawValue)")
// Then replace the selection with our text
let cfText = text as CFString
+ guard isOutputValid() else { return false }
let result = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, cfText)
if result == .success {
@@ -1451,7 +1470,7 @@ final class TypingService {
}
}
- private nonisolated func insertTextAtInsertionPoint(_ element: AXUIElement, _ text: String) -> Bool {
+ private nonisolated func insertTextAtInsertionPoint(_ element: AXUIElement, _ text: String, isOutputValid: () -> Bool) -> Bool {
// Try to get the insertion point
var insertionPoint: CFTypeRef?
let getResult = AXUIElementCopyAttributeValue(element, kAXInsertionPointLineNumberAttribute as CFString, &insertionPoint)
@@ -1459,6 +1478,7 @@ final class TypingService {
// Try to insert text using parameterized attribute
let cfText = text as CFString
+ guard isOutputValid() else { return false }
let result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, cfText)
if result == .success {
diff --git a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift
index 2f35489d..7df007fd 100644
--- a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift
+++ b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift
@@ -957,10 +957,12 @@ final class DirectAudioReliabilityTests: XCTestCase {
let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/ContentView.swift"), encoding: .utf8)
let callback = try XCTUnwrap(source.components(separatedBy: "self.hotkeyManager?.setCancelCallback {").last?.components(separatedBy: "// Re-insert").first)
- XCTAssertTrue(callback.contains("self.handleCancelShortcut()"))
+ XCTAssertTrue(callback.contains("self.handleCancelShortcutResult()"))
XCTAssertFalse(callback.contains("clearActiveRecordingMode()"), "Keep the selected style until the History pipeline snapshots it")
- let cancel = try XCTUnwrap(source.components(separatedBy: "private func handleCancelShortcut() -> Bool {").last?.components(separatedBy: "// MARK: - Model Management Helpers").first)
- XCTAssertTrue(cancel.contains("if self.isSavingCancelledRecording { return true }"))
+ let cancel = try XCTUnwrap(source.components(separatedBy: "private func handleCancelShortcutResult() -> GlobalHotkeyManager.CancelHandlingResult {").last?
+ .components(separatedBy: "// MARK: - Model Management Helpers").first)
+ XCTAssertTrue(cancel.contains("if self.isSavingCancelledRecording { return .cancelled }"))
+ XCTAssertTrue(cancel.contains("DictionaryCorrectionOverlayController.shared.dismiss()\n return .dismissedOverlay"))
XCTAssertTrue(cancel.contains("self.settings.saveTranscriptionHistory"))
XCTAssertTrue(cancel.contains("!self.asr.isDictionaryTrainingCaptureActive"))
XCTAssertTrue(cancel.contains("!= .onboardingSandbox"))
@@ -977,7 +979,8 @@ final class DirectAudioReliabilityTests: XCTestCase {
func testCancelledProcessingCannotPublishDelayedOverlayOrPracticeResult() throws {
let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/ContentView.swift"), encoding: .utf8)
- let status = try XCTUnwrap(source.components(separatedBy: "let onFinalTranscriptionStarted: @MainActor () -> Void = {").last?.components(separatedBy: "return (false, onFinalTranscriptionStarted)").first)
+ let status = try XCTUnwrap(source.components(separatedBy: "let onFinalTranscriptionStarted: @MainActor () -> Void = {").last?
+ .components(separatedBy: "return (false, onFinalTranscriptionStarted)").first)
XCTAssertTrue(status.contains("self.cancelledOutputLifecycleID != lifecycleID"))
let prompt = try XCTUnwrap(source.components(separatedBy: "private func processDictationPromptTest(").last?.components(separatedBy: "private func routePromptTestResult(").first)
XCTAssertTrue(prompt.contains("guard promptTest.acceptsResult(for: sessionID), self.cancelledOutputLifecycleID != lifecycleID"))
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index 9ceb5906..9d223fff 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -407,7 +407,7 @@ final class HotkeyShortcutTests: XCTestCase {
settings.cancelRecordingHotkeyShortcut = HotkeyShortcut(keyCode: 53, modifierFlags: [])
var starts = 0
let manager = self.makePrimaryReleaseTestManager(asr: ASRService(), onStart: { starts += 1 })
- manager.setCancelCallback { true }
+ manager.setCancelCallback { .cancelled }
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: []))
_ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp))
@@ -1531,7 +1531,7 @@ final class HotkeyShortcutTests: XCTestCase {
func testCancelAfterToggleReleaseInvalidatesQueuedStart() async throws {
var starts = 0
let manager = self.makePrimaryReleaseTestManager(asr: ASRService(), onStart: { starts += 1 })
- manager.setCancelCallback { true }
+ manager.setCancelCallback { .cancelled }
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
_ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp))
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: []))
@@ -1874,7 +1874,7 @@ final class HotkeyShortcutTests: XCTestCase {
defer { asr.isRunning = false }
var cancellations = 0
let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {})
- manager.setCancelCallback { cancellations += 1; return true }
+ manager.setCancelCallback { cancellations += 1; return .cancelled }
let result = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: []))
XCTAssertNil(result)
for _ in 0..<20 {
@@ -1892,7 +1892,7 @@ final class HotkeyShortcutTests: XCTestCase {
var stops = 0
let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: { starts += 1; asr.isRunning = true }, onStop: { stops += 1; asr.isRunning = false })
manager.setHotkeyMode(.hold)
- manager.setCancelCallback { true }
+ manager.setCancelCallback { .cancelled }
_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
for _ in 0..<20 {
await Task.yield()
@@ -1927,7 +1927,7 @@ final class HotkeyShortcutTests: XCTestCase {
let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {})
manager.setCancelCallback {
if !recoveryQueued { recoveryQueued = true; saves += 1 }
- return true
+ return .cancelled
}
for _ in 0..<5 {
XCTAssertNil(try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: [])))
@@ -1939,10 +1939,78 @@ final class HotkeyShortcutTests: XCTestCase {
XCTAssertTrue(asr.isRunning)
}
+ @MainActor
+ func testSuggestionDismissalPreservesHoldRecordingAndOwnedRelease() async throws {
+ let settings = SettingsStore.shared
+ let previous = settings.cancelRecordingHotkeyShortcut
+ defer { settings.cancelRecordingHotkeyShortcut = previous }
+ for modifierOnly in [false, true] {
+ let asr = ASRService()
+ defer { asr.isRunning = false }
+ var starts = 0
+ var stops = 0
+ let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: { starts += 1; asr.isRunning = true }, onStop: { stops += 1; asr.isRunning = false })
+ manager.setHotkeyMode(.hold)
+ if modifierOnly { manager.updatePrimaryShortcuts([HotkeyShortcut(keyCode: 61, modifierFlags: [], modifierKeyCodes: [61])]) }
+ let heldModifiers: CGEventFlags = modifierOnly ? .maskAlternate : [.maskControl, .maskCommand]
+ settings.cancelRecordingHotkeyShortcut = HotkeyShortcut(keyCode: 53, modifierFlags: modifierOnly ? .option : [.control, .command])
+ manager.setCancelCallback { .dismissedOverlay }
+ let down = try self.primaryReleaseTestEvent(
+ type: modifierOnly ? .flagsChanged : .keyDown,
+ keyCode: modifierOnly ? 61 : 2,
+ modifiers: heldModifiers
+ )
+ _ = manager.handleKeyEvent(type: down.type, event: down)
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertTrue(asr.isRunning)
+ let escape = try self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: heldModifiers)
+ XCTAssertNil(manager.handleKeyEvent(type: .keyDown, event: escape))
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertTrue(asr.isRunning, "Only dismiss the suggestion; keep the current recording")
+ XCTAssertEqual(stops, 0)
+ let up = try self.primaryReleaseTestEvent(type: modifierOnly ? .flagsChanged : .keyUp, keyCode: modifierOnly ? 61 : 2, modifiers: modifierOnly ? [] : heldModifiers)
+ _ = manager.handleKeyEvent(type: up.type, event: up)
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertEqual(starts, 1)
+ XCTAssertEqual(stops, 1, "Dismissal must not orphan the held recording's release")
+ XCTAssertFalse(asr.isRunning)
+ }
+ }
+
+ @MainActor
+ func testCancelBeforeToggleReleaseDoesNotNeedApplicationUIToHandleIt() async throws {
+ let settings = SettingsStore.shared
+ let previous = settings.cancelRecordingHotkeyShortcut
+ defer { settings.cancelRecordingHotkeyShortcut = previous }
+ settings.cancelRecordingHotkeyShortcut = HotkeyShortcut(keyCode: 53, modifierFlags: [.control, .command])
+ var starts = 0
+ let manager = self.makePrimaryReleaseTestManager(asr: ASRService(), onStart: { starts += 1 })
+ manager.setCancelCallback { .unhandled }
+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: [.maskControl, .maskCommand]))
+ _ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp))
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertEqual(starts, 0)
+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))
+ _ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp))
+ for _ in 0..<20 {
+ await Task.yield()
+ }
+ XCTAssertEqual(starts, 1)
+ }
+
@MainActor
func testIdleCancelPassesThroughWhenApplicationHasNothingToHandle() throws {
let manager = self.makePrimaryReleaseTestManager(asr: ASRService(), onStart: {})
- manager.setCancelCallback { false }
+ manager.setCancelCallback { .unhandled }
let event = try self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: [])
let result = manager.handleKeyEvent(type: .keyDown, event: event)
withExtendedLifetime(event) { XCTAssertNotNil(result) }
diff --git a/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift b/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift
index 2c320cd9..853faa8a 100644
--- a/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift
+++ b/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift
@@ -488,6 +488,82 @@ final class TypingServiceTransientPasteboardTests: XCTestCase {
XCTAssertEqual(restoredItems.last?.string(forType: .string), "item 100")
}
+ func testCancelledFailedDirectAttemptSuppressesFallbackAndNextDeliveryWorks() {
+ var valid = true
+ var attempts = [String]()
+ let first = TypingService.attemptDirectInsertion(isOutputValid: { valid }) {
+ attempts.append("preferred")
+ valid = false
+ return false
+ }
+ XCTAssertFalse(first)
+
+ for fallback in ["focused", "accessibility", "hid"] {
+ XCTAssertFalse(TypingService.attemptDirectInsertion(isOutputValid: { valid }) {
+ attempts.append(fallback)
+ return true
+ })
+ }
+ XCTAssertEqual(attempts, ["preferred"])
+
+ valid = true
+ XCTAssertTrue(TypingService.attemptDirectInsertion(isOutputValid: { valid }) {
+ attempts.append("next delivery")
+ return true
+ })
+ XCTAssertEqual(attempts, ["preferred", "next delivery"])
+ }
+
+ func testFailedDirectAttemptKeepsValidFallbackAvailable() {
+ var attempts = 0
+ XCTAssertFalse(TypingService.attemptDirectInsertion(isOutputValid: { true }) {
+ attempts += 1
+ return false
+ })
+ XCTAssertTrue(TypingService.attemptDirectInsertion(isOutputValid: { true }) {
+ attempts += 1
+ return true
+ })
+ XCTAssertEqual(attempts, 2)
+ }
+
+ func testDirectFallbacksAndAXWritesForwardAndRecheckOutputValidity() throws {
+ let root = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/Services/TypingService.swift"), encoding: .utf8)
+ let pipelineStart = try XCTUnwrap(source.range(of: "private nonisolated func insertTextDirectly("))
+ let pipelineEnd = try XCTUnwrap(source.range(of: "private static let physicalModifierKeys", range: pipelineStart.upperBound..<source.endIndex))
+ let pipeline = String(source[pipelineStart.lowerBound..<pipelineEnd.lowerBound])
+ XCTAssertEqual(pipeline.components(separatedBy: "Self.attemptDirectInsertion(isOutputValid: isOutputValid").count - 1, 4)
+ for dispatch in [
+ "insertTextBulkInstant(text, targetPID: preferredTargetPID",
+ "insertTextBulkInstant(text, targetPID: focusedPID",
+ "insertTextViaAccessibility(text",
+ "insertTextBulkHIDInstant(text",
+ ] {
+ let callStart = try XCTUnwrap(pipeline.range(of: dispatch))
+ let callEnd = try XCTUnwrap(pipeline.range(of: "})", range: callStart.upperBound..<pipeline.endIndex))
+ XCTAssertTrue(pipeline[callStart.lowerBound..<callEnd.lowerBound].contains("isOutputValid: isOutputValid"))
+ }
+ let wrapperStart = try XCTUnwrap(source.range(of: "private func insertTextDirectlyOffMain("))
+ let wrapperEnd = try XCTUnwrap(source.range(of: "nonisolated static func attemptDirectInsertion", range: wrapperStart.upperBound..<source.endIndex))
+ let wrapper = source[wrapperStart.lowerBound..<wrapperEnd.lowerBound]
+ XCTAssertTrue(wrapper.contains("isOutputValid: {"))
+ XCTAssertTrue(wrapper.contains("DispatchQueue.main.sync { MainActor.assumeIsolated { isOutputValid() } }"))
+
+ let writeStart = try XCTUnwrap(source.range(of: "private nonisolated func insertTextAtCursorUsingSelectedRange("))
+ let writes = String(source[writeStart.lowerBound...])
+ let lines = writes.components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespaces) }
+ for (index, line) in lines.enumerated() where line.contains("= AXUIElementSetAttributeValue(") && !line.hasPrefix("_ =") {
+ XCTAssertGreaterThan(index, 0)
+ XCTAssertEqual(lines[index - 1], "guard isOutputValid() else { return false }")
+ }
+ XCTAssertTrue(writes.contains("if isOutputValid(), let axRange"))
+ XCTAssertTrue(source.contains("guard isOutputValid() else { return -1 }\n post(keyDown)\n post(keyUp)"))
+ }
+
private func makePasteboard() -> NSPasteboard {
let name = NSPasteboard.Name("com.fluidvoice.tests.transient.\(UUID().uuidString)")
let pasteboard = NSPasteboard(name: name)