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

Add optional hold-Space mute during dictation (#1052)

Alex Modond0b5e8aeb1e7
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index 1d143099..35602882 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -7,6 +7,8 @@
objects = {
/* Begin PBXBuildFile section */
+ AD1030000000000000000004 /* HoldToMutePresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD1030000000000000000003 /* HoldToMutePresentationTests.swift */; };
+ AD1030000000000000000002 /* HoldToMuteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD1030000000000000000001 /* HoldToMuteTests.swift */; };
D63B0F8456B440F1A123B987 /* PronunciationModelRevisionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFA73C8D5E7647C4AB125DEE /* PronunciationModelRevisionTests.swift */; };
5D4A9F54826FD6BB32CE13F8 /* SpeechModelInstallationSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D47EF42AC1B641A705AC302 /* SpeechModelInstallationSnapshotTests.swift */; };
B51B7EE5BA8CE09BC09A47DB /* ProgressiveFileDownloaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70362FCD2F941BFB800AD8E8 /* ProgressiveFileDownloaderTests.swift */; };
@@ -175,6 +177,8 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
+ AD1030000000000000000003 /* HoldToMutePresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HoldToMutePresentationTests.swift; sourceTree = "<group>"; };
+ AD1030000000000000000001 /* HoldToMuteTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HoldToMuteTests.swift; sourceTree = "<group>"; };
AFA73C8D5E7647C4AB125DEE /* PronunciationModelRevisionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PronunciationModelRevisionTests.swift; sourceTree = "<group>"; };
7D47EF42AC1B641A705AC302 /* SpeechModelInstallationSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpeechModelInstallationSnapshotTests.swift; sourceTree = "<group>"; };
70362FCD2F941BFB800AD8E8 /* ProgressiveFileDownloaderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProgressiveFileDownloaderTests.swift; sourceTree = "<group>"; };
@@ -416,6 +420,8 @@
7CDB0A292F3C4D5600FB7CAD /* DictationE2ETests.swift */,
CD1C7A0000000000000000B1 /* CustomDictionaryManualEntryTests.swift */,
7C91B0022F42AA0100C0DEF0 /* HotkeyShortcutTests.swift */,
+ AD1030000000000000000003 /* HoldToMutePresentationTests.swift */,
+ AD1030000000000000000001 /* HoldToMuteTests.swift */,
DAB600000000000000000002 /* DashboardLayoutTests.swift */,
FEB700000000000000000002 /* FeedbackClientTests.swift */,
7C91B0A22F42AA0100C0DEF0 /* DeliveryTargetAssessmentTests.swift */,
@@ -789,6 +795,8 @@
B52000000000000000000002 /* PrivateAIDictationTokenBudgetTests.swift in Sources */,
CD1C7A0000000000000000B2 /* CustomDictionaryManualEntryTests.swift in Sources */,
7C91B0012F42AA0100C0DEF0 /* HotkeyShortcutTests.swift in Sources */,
+ AD1030000000000000000004 /* HoldToMutePresentationTests.swift in Sources */,
+ AD1030000000000000000002 /* HoldToMuteTests.swift in Sources */,
DAB600000000000000000001 /* DashboardLayoutTests.swift in Sources */,
FEB700000000000000000001 /* FeedbackClientTests.swift in Sources */,
7C91B0A12F42AA0100C0DEF0 /* DeliveryTargetAssessmentTests.swift in Sources */,
diff --git a/README.md b/README.md
index 3e4151d4..585ce16c 100644
--- a/README.md
+++ b/README.md
@@ -113,6 +113,7 @@ https://github.com/user-attachments/assets/c57ef6d5-f0a1-4a3f-a121-637533442c24
- **Today-Usage Stats** — daily usage tracking at a glance with a stats header card and toolbar pill
- **Adaptive Theming** — light/dark theme that follows your system, with a compact toolbar switcher
- **Global Hotkey** — instant voice capture from anywhere, no app switching needed
+- **Hold Space to Mute** — optional temporary mute within a dictation: hold Space while thinking, then release to continue the same recording; quick taps still type spaces
- **Smart Typing** — direct insertion into any app via accessibility APIs for reliable, app-independent text entry
- **Menu Bar Integration** — quick access, status, and settings from the menu bar
- **Auto-Updates** — seamless updates with an optional beta channel for early previews
@@ -180,6 +181,8 @@ Whisper supports up to 99 languages, depending on the model size you choose.
7. **(Optional) Opt in to beta builds** — `Settings → Automatic Updates → Beta Releases` for early access to new features.
+To pause listening without ending a hands-free dictation, enable **Settings → Dictation → Hold Space to Mute**. Start dictation with your usual shortcut, hold Space to mute, and release it to resume. The overlay shows a muted microphone. A quick tap (up to 250 ms) types one space on release; a longer hold types nothing. Muting starts immediately in both cases. Your normal shortcut still finishes the recording. Muted audio is excluded from live transcription, the final transcript, and saved audio history. Space works normally outside dictation; modifier-plus-Space and configured Space shortcuts keep their existing behavior. The option is off by default and applies to Dictation mode.
+
---
## Requirements
diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swift
index a36c30dd..37bc2046 100644
--- a/Sources/Fluid/Persistence/BackupService.swift
+++ b/Sources/Fluid/Persistence/BackupService.swift
@@ -63,6 +63,7 @@ struct SettingsBackupPayload: Codable, Equatable {
let shareAnonymousAnalytics: Bool
let pressAndHoldMode: Bool
let hotkeyMode: HotkeyActivationMode?
+ var holdSpaceToMute: Bool? = nil
let enableStreamingPreview: Bool
// Optional so backups created before incremental Parakeet finalization still decode.
let experimentalParakeetUnifiedFinalEnabled: Bool?
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 9fcd2e55..9231c47a 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -1925,6 +1925,15 @@ final class SettingsStore: ObservableObject {
set { objectWillChange.send(); self.defaults.set(newValue.rawValue, forKey: Keys.hotkeyMode); self.defaults.set(newValue == .hold, forKey: Keys.pressAndHoldMode) }
}
+ var holdSpaceToMute: Bool {
+ get { self.defaults.bool(forKey: Keys.holdSpaceToMute) }
+ set {
+ self.objectWillChange.send()
+ self.defaults.set(newValue, forKey: Keys.holdSpaceToMute)
+ NotificationCenter.default.post(name: .init("HoldSpaceToMuteChanged"), object: nil)
+ }
+ }
+
var enableStreamingPreview: Bool {
get {
let value = self.defaults.object(forKey: Keys.enableStreamingPreview)
@@ -3635,6 +3644,7 @@ final class SettingsStore: ObservableObject {
shareAnonymousAnalytics: self.shareDetailedAnalytics,
pressAndHoldMode: self.pressAndHoldMode,
hotkeyMode: self.hotkeyMode,
+ holdSpaceToMute: self.holdSpaceToMute,
enableStreamingPreview: self.enableStreamingPreview,
experimentalParakeetUnifiedFinalEnabled: self.experimentalParakeetUnifiedFinalEnabled,
returnDictationToStartingField: self.returnDictationToStartingField,
@@ -3792,6 +3802,7 @@ final class SettingsStore: ObservableObject {
self.enableDebugLogs = payload.enableDebugLogs
self.shareDetailedAnalytics = payload.shareAnonymousAnalytics
self.hotkeyMode = payload.hotkeyMode ?? (payload.pressAndHoldMode ? .hold : .toggle)
+ self.holdSpaceToMute = payload.holdSpaceToMute ?? false
self.enableStreamingPreview = payload.enableStreamingPreview
if let experimentalParakeetUnifiedFinalEnabled = payload.experimentalParakeetUnifiedFinalEnabled {
self.experimentalParakeetUnifiedFinalEnabled = experimentalParakeetUnifiedFinalEnabled
@@ -5864,6 +5875,7 @@ private extension SettingsStore {
static let transcriptionSoundVolume = "TranscriptionSoundVolume"
static let pressAndHoldMode = "PressAndHoldMode"
static let hotkeyMode = "HotkeyMode"
+ static let holdSpaceToMute = "HoldSpaceToMute"
static let enableStreamingPreview = "EnableStreamingPreview"
static let experimentalParakeetUnifiedFinalEnabled = "ExperimentalParakeetUnifiedFinalEnabled"
static let returnDictationToStartingField = "ReturnDictationToStartingField"
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 24dcaab6..e9a50245 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -576,7 +576,36 @@ final class ASRService: ObservableObject {
)
}
- @Published var isRunning: Bool = false
+ @Published var isRunning: Bool = false {
+ didSet {
+ if !self.isRunning {
+ self.dictationMuteGeneration &+= 1
+ self.clearDictationMuteIndicator()
+ }
+ }
+ }
+
+ @Published private(set) var isDictationMuted = false
+ private(set) var dictationMuteGeneration: UInt64 = 0
+
+ func setDictationMuted(_ muted: Bool) {
+ guard self.isRunningOrStarting, !self.isDictionaryTrainingCaptureActive,
+ !self.isStoppingFinalTranscription, muted != self.isDictationMuted else { return }
+ self.audioCapturePipeline.setDictationMuted(muted, at: mach_absolute_time())
+ self.isDictationMuted = muted
+ NotchContentState.shared.isDictationMuted = muted
+ if muted {
+ self.audioLevelSubject.send(0)
+ }
+ }
+
+ private func clearDictationMuteIndicator() {
+ if self.isDictationMuted {
+ self.isDictationMuted = false
+ }
+ if NotchContentState.shared.isDictationMuted { NotchContentState.shared.isDictationMuted = false }
+ }
+
@Published var finalText: String = ""
@Published var partialTranscription: String = ""
@Published var wordBoostStatusText: String = "Word boost: off"
@@ -618,7 +647,17 @@ final class ASRService: ObservableObject {
private var lastFinalParakeetProcessingMs: Int?
private(set) var dictionaryTrainingAudioGeneration = 0
- @Published private(set) var isStarting: Bool = false // Guard against re-entrant start() calls
+ @Published private(set) var isStarting: Bool = false { // Guard against re-entrant start() calls
+ didSet {
+ if self.isStarting {
+ self.dictationMuteGeneration &+= 1
+ }
+ if !self.isStarting, !self.isRunning {
+ self.clearDictationMuteIndicator()
+ }
+ }
+ }
+
private var pendingMediaCaptureSessionID: Int?
@Published private(set) var activeExclusiveActivity: ASRExclusiveActivity?
private var audioCaptureStartWaiters: [CheckedContinuation<Void, Never>] = []
@@ -2816,6 +2855,9 @@ final class ASRService: ObservableObject {
}
}
+ self.audioCapturePipeline.resetDictationMute()
+ self.audioCapturePipeline.setDictationMuted(self.isDictationMuted, at: mach_absolute_time())
+
// Reserve the start before relinquishing preview ownership so a
// press-and-hold release can cancel the handoff. Keep the running input
// alive; startConfiguredAudioCapture reuses it for zero-stop first PCM.
@@ -6990,7 +7032,8 @@ final class ASRService: ObservableObject {
self.streamingHealthCheckCount += 1
if self.streamingHealthCheckCount >= 3 {
let currentBufferCount = self.audioBuffer.count
- if currentBufferCount == self.streamingHealthLastBufferCount,
+ if !self.isDictationMuted,
+ currentBufferCount == self.streamingHealthLastBufferCount,
currentBufferCount < 16_000
{
DebugLogger.shared.warning(
@@ -7018,6 +7061,7 @@ final class ASRService: ObservableObject {
operationID: operationID
)
else { return }
+ guard !self.isDictationMuted else { return }
self.benchmarkStreamingChunkIndex += 1
let chunkIndex = self.benchmarkStreamingChunkIndex
let chunkAgeMs = self.elapsedMilliseconds(since: self.benchmarkRecordingStartedAt)
@@ -7781,7 +7825,7 @@ private extension ASRService {
// conversion, levels, and session-safe delivery without touching ASRService from
// a realtime callback.
-private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
+final nonisolated class AudioCapturePipeline: @unchecked Sendable {
private let audioBuffer: ThreadSafeAudioBuffer
private let onFirstAudio: (Int, UInt64, Int, Int, Double, Int, Int) -> Void
private let onLevel: (CGFloat) -> Void
@@ -7789,6 +7833,8 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
private let lock = NSLock()
private var recordingEnabled: Bool = false
+ private var muteTimeline = DictationMuteTimeline()
+ private var needsMuteSeparation = false
private var levelMonitoringEnabled: Bool = false
private var firstAudioReported: Bool = false
private var recordingSessionID: Int = 0
@@ -7863,6 +7909,18 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
self.lock.unlock()
}
+ func setDictationMuted(_ muted: Bool, at hostTime: UInt64) {
+ self.lock.withLock { self.muteTimeline.setMuted(muted, at: hostTime) }
+ }
+
+ /// Reset only between logical recordings, not during an audio-route retry.
+ func resetDictationMute() {
+ self.lock.withLock {
+ self.muteTimeline = DictationMuteTimeline()
+ self.needsMuteSeparation = false
+ }
+ }
+
var isLevelMonitoringEnabled: Bool {
self.lock.lock()
defer { self.lock.unlock() }
@@ -7980,12 +8038,6 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
return
}
- let acceptedSamples: [Float]
- if acceptedRange.lowerBound == 0, acceptedRange.upperBound == samples.count {
- acceptedSamples = samples
- } else {
- acceptedSamples = Array(samples[acceptedRange])
- }
self.lock.lock()
guard self.recordingEnabled,
self.recordingSessionID == recordingSessionID,
@@ -7994,22 +8046,14 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
self.lock.unlock()
return
}
- if inputSampleTime >= 0 {
- let acceptedSampleStart = inputSampleTime + Int64(acceptedRange.lowerBound)
- if let lastInputSampleEnd = self.lastInputSampleEnd,
- lastInputSampleEnd != acceptedSampleStart
- {
- // Do not interpolate across a hardware discontinuity or a
- // packet dropped under extreme consumer backpressure.
- self.resetResamplerLocked()
- }
- self.lastInputSampleEnd = inputSampleTime + Int64(acceptedRange.upperBound)
- }
- let mono16k = self.resampleTo16kLocked(
- acceptedSamples,
- sourceSampleRate: sampleRate
+ let mono16k = self.resampleAudibleRangesLocked(
+ samples,
+ acceptedRange: acceptedRange,
+ sampleRate: sampleRate,
+ inputHostTime: inputHostTime,
+ inputSampleTime: inputSampleTime
)
- guard mono16k.isEmpty == false else {
+ guard !mono16k.isEmpty || self.muteTimeline.hasExclusions else {
self.lock.unlock()
return
}
@@ -8047,6 +8091,10 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
)
}
self.lock.unlock()
+ guard !mono16k.isEmpty else {
+ self.onLevel(0)
+ return
+ }
let measurement = self.measureAudioLevel(mono16k)
AudioSpectrumMeter.shared.ingest(mono16k)
self.onLevel(measurement.level)
@@ -8127,6 +8175,61 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
self.resamplePreviousSample = nil
}
+ /// Remove muted samples before resampling, streaming, or history storage. Reset
+ /// interpolation at every excluded range so a muted sample cannot cross a seam.
+ private func resampleAudibleRangesLocked(
+ _ samples: [Float],
+ acceptedRange: Range<Int>,
+ sampleRate: Double,
+ inputHostTime: UInt64,
+ inputSampleTime: Int64
+ ) -> [Float] {
+ if !self.muteTimeline.hasExclusions {
+ return self.resampleCapturedRangeLocked(samples, range: acceptedRange, sampleRate: sampleRate, inputSampleTime: inputSampleTime)
+ }
+ let ranges = self.muteTimeline.audibleRanges(
+ in: acceptedRange,
+ packetHostTime: inputHostTime,
+ sampleRate: sampleRate,
+ hostTicksPerSecond: Self.hostTicksPerSecond
+ )
+ var output: [Float] = []
+ var cursor = acceptedRange.lowerBound
+ for range in ranges {
+ if range.lowerBound > cursor {
+ self.needsMuteSeparation = true
+ }
+ if self.needsMuteSeparation { self.resetResamplerLocked() }
+ if self.needsMuteSeparation {
+ // Keep a short word boundary, without accumulating minutes of silence.
+ if !self.audioBuffer.isEmpty || !output.isEmpty {
+ output.append(contentsOf: repeatElement(0, count: 1600))
+ }
+ self.needsMuteSeparation = false
+ }
+ output.append(contentsOf: self.resampleCapturedRangeLocked(samples, range: range, sampleRate: sampleRate, inputSampleTime: inputSampleTime))
+ cursor = range.upperBound
+ }
+ if cursor < acceptedRange.upperBound {
+ self.needsMuteSeparation = true
+ self.resetResamplerLocked()
+ self.lastInputSampleEnd = nil
+ }
+ return output
+ }
+
+ private func resampleCapturedRangeLocked(_ samples: [Float], range: Range<Int>, sampleRate: Double, inputSampleTime: Int64) -> [Float] {
+ if inputSampleTime >= 0 {
+ let sampleStart = inputSampleTime + Int64(range.lowerBound)
+ if let lastInputSampleEnd = self.lastInputSampleEnd, lastInputSampleEnd != sampleStart {
+ self.resetResamplerLocked()
+ }
+ self.lastInputSampleEnd = inputSampleTime + Int64(range.upperBound)
+ }
+ let acceptedSamples = range == samples.indices ? samples : Array(samples[range])
+ return self.resampleTo16kLocked(acceptedSamples, sourceSampleRate: sampleRate)
+ }
+
private func resetCaptureHealthLocked() {
self.captureHealthSampleCount = 0
self.captureHealthTotalSampleCount = 0
diff --git a/Sources/Fluid/Services/DictationMuteTimeline.swift b/Sources/Fluid/Services/DictationMuteTimeline.swift
new file mode 100644
index 00000000..17442231
--- /dev/null
+++ b/Sources/Fluid/Services/DictationMuteTimeline.swift
@@ -0,0 +1,54 @@
+import Foundation
+
+/// Acquisition-time exclusions, accessed under AudioCapturePipeline's capture lock.
+/// Retaining closed intervals rejects audio delivered after the key has been released.
+nonisolated struct DictationMuteTimeline {
+ private struct Interval {
+ let start: UInt64
+ var end: UInt64?
+ }
+
+ private var intervals: [Interval] = []
+ private(set) var isMuted = false
+ var hasExclusions: Bool { !self.intervals.isEmpty }
+
+ mutating func setMuted(_ muted: Bool, at hostTime: UInt64) {
+ guard muted != self.isMuted else { return }
+ self.isMuted = muted
+ if muted {
+ self.intervals.append(Interval(start: hostTime))
+ } else if let last = self.intervals.indices.last {
+ self.intervals[last].end = max(hostTime, self.intervals[last].start)
+ }
+ }
+
+ func audibleRanges(
+ in range: Range<Int>,
+ packetHostTime: UInt64,
+ sampleRate: Double,
+ hostTicksPerSecond: Double
+ ) -> [Range<Int>] {
+ guard !range.isEmpty else { return [] }
+ guard !self.intervals.isEmpty else { return [range] }
+ // Once a session has muted audio, an untimestamped packet cannot safely be
+ // attributed to either side of a mute boundary. Do not leak it into ASR.
+ guard packetHostTime > 0 else { return [] }
+ var cursor = range.lowerBound
+ var result: [Range<Int>] = []
+ for interval in self.intervals {
+ let start = (Double(interval.start) - Double(packetHostTime)) * sampleRate / hostTicksPerSecond
+ let end = interval.end.map { (Double($0) - Double(packetHostTime)) * sampleRate / hostTicksPerSecond }
+ ?? Double(range.upperBound)
+ let lower = Int(max(Double(range.lowerBound), min(Double(range.upperBound), floor(start))))
+ let upper = Int(max(Double(range.lowerBound), min(Double(range.upperBound), ceil(end))))
+ if lower > cursor {
+ result.append(cursor..<lower)
+ }
+ cursor = max(cursor, upper)
+ }
+ if cursor < range.upperBound {
+ result.append(cursor..<range.upperBound)
+ }
+ return result
+ }
+}
diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swift
index 7a1a7965..a735c648 100644
--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift
+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift
@@ -311,6 +311,12 @@ final class GlobalHotkeyManager: NSObject {
private var pasteLastTranscriptionCallback: (() -> Void)?
private var hotkeyMode: HotkeyActivationMode = SettingsStore.shared.hotkeyMode
private let automaticTapThresholdSeconds: TimeInterval = 0.4
+ private var holdToMuteKeyState = HoldToMuteKeyState()
+ let holdToMuteSpaceTap = HoldToMuteSpaceTap()
+ private var muteRecordingGeneration: UInt64?
+ private var muteReleaseRecoveryTask: Task<Void, Never>?
+ // Event-replay tests opt out of consulting the real keyboard.
+ var holdToMuteChecksPhysicalKeyState = true
private var currentInputTiming: HotkeyInputTiming?
private var modifierPressReceivedAt: TimeInterval?
private var currentStopPressReceivedAt: TimeInterval?
@@ -568,6 +574,12 @@ final class GlobalHotkeyManager: NSObject {
self.shortcutCaptureHandler = shortcutCaptureHandler
self.isSessionLockedProvider = isSessionLockedProvider
super.init()
+ NotificationCenter.default.addObserver(
+ self,
+ selector: #selector(self.holdSpaceSettingChanged),
+ name: .init("HoldSpaceToMuteChanged"),
+ object: nil
+ )
self.initializeWithDelay()
}
@@ -736,7 +748,7 @@ final class GlobalHotkeyManager: NSObject {
place: .headInsertEventTap,
options: .defaultTap,
eventsOfInterest: Self.keyboardEventMask(),
- callback: { _, type, event, refcon -> Unmanaged<CGEvent>? in
+ callback: { proxy, type, event, refcon -> Unmanaged<CGEvent>? in
guard let refcon = refcon else { return Unmanaged.passUnretained(event) }
ClipboardAudit.recordShortcut(type: type, event: event)
if GlobalHotkeyManager.isSynthesizedTypingEvent(event) {
@@ -746,12 +758,12 @@ final class GlobalHotkeyManager: NSObject {
.takeUnretainedValue()
if Thread.isMainThread {
return MainActor.assumeIsolated {
- manager.handleKeyEvent(type: type, event: event)
+ manager.handleKeyEvent(type: type, event: event, proxy: proxy)
}
}
return DispatchQueue.main.sync {
MainActor.assumeIsolated {
- manager.handleKeyEvent(type: type, event: event)
+ manager.handleKeyEvent(type: type, event: event, proxy: proxy)
}
}
},
@@ -1243,7 +1255,7 @@ final class GlobalHotkeyManager: NSObject {
)
}
- func handleKeyEvent(type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {
+ func handleKeyEvent(type: CGEventType, event: CGEvent, proxy: CGEventTapProxy? = nil) -> Unmanaged<CGEvent>? {
let previousInput = self.currentInputTiming
self.currentInputTiming = HotkeyInputTiming(
receivedAt: ProcessInfo.processInfo.systemUptime,
@@ -1261,6 +1273,10 @@ final class GlobalHotkeyManager: NSObject {
return Unmanaged.passUnretained(event)
}
+ if self.handleHoldToMute(type: type, event: event, proxy: proxy) {
+ return nil
+ }
+
if self.isShortcutCaptureActiveProvider?() ?? false {
self.resetModifierOnlyShortcutTracking()
if Self.captureKeyboardEvent(type: type, event: event, isAppActive: NSApp.isActive, handler: self.shortcutCaptureHandler) { return nil }
@@ -1646,30 +1662,6 @@ final class GlobalHotkeyManager: NSObject {
return Unmanaged.passUnretained(event)
}
- private func handleTapDisableEvent(type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {
- // macOS can temporarily disable event taps (e.g. timeouts, user input protection).
- // If we don't immediately re-enable here, hotkeys will silently stop working until our
- // periodic health check kicks in, and the OS may handle the key (e.g. system dictation).
- guard type == .tapDisabledByTimeout || type == .tapDisabledByUserInput else {
- return nil
- }
-
- let reason = (type == .tapDisabledByTimeout) ? "timeout" : "user input"
- DebugLogger.shared.warning("Event tap disabled by \(reason) — attempting immediate re-enable", source: "GlobalHotkeyManager")
- self.resetModifierOnlyShortcutTracking(reason: .tapDisabled)
-
- if let tap = self.eventTap {
- CGEvent.tapEnable(tap: tap, enable: true)
- }
-
- if !self.isEventTapEnabled() {
- DebugLogger.shared.warning("Event tap re-enable failed — recreating tap", source: "GlobalHotkeyManager")
- self.setupGlobalHotkeyWithRetry()
- }
-
- return Unmanaged.passUnretained(event)
- }
-
private func synchronizedPressedModifierKeyCodes(
changedKeyCode: UInt16,
modifiers: NSEvent.ModifierFlags
@@ -2538,6 +2530,8 @@ final class GlobalHotkeyManager: NSObject {
deinit {
initializationTask?.cancel()
healthCheckTask?.cancel()
+ muteReleaseRecoveryTask?.cancel()
+ NotificationCenter.default.removeObserver(self)
cleanupEventTap()
}
}
@@ -2729,3 +2723,153 @@ extension GlobalHotkeyManager {
return handler(appEvent) == nil
}
}
+
+extension GlobalHotkeyManager {
+ private func handleTapDisableEvent(type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {
+ // macOS can temporarily disable event taps (e.g. timeouts, user input protection).
+ // If we don't immediately re-enable here, hotkeys will silently stop working until our
+ // periodic health check kicks in, and the OS may handle the key (e.g. system dictation).
+ guard type == .tapDisabledByTimeout || type == .tapDisabledByUserInput else {
+ return nil
+ }
+
+ self.holdToMuteSpaceTap.cancel()
+ let reason = (type == .tapDisabledByTimeout) ? "timeout" : "user input"
+ DebugLogger.shared.warning("Event tap disabled by \(reason) — attempting immediate re-enable", source: "GlobalHotkeyManager")
+ self.resetModifierOnlyShortcutTracking(reason: .tapDisabled)
+ if self.holdToMuteChecksPhysicalKeyState {
+ self.reconcileHoldToMute(isPhysicallyDown: CGEventSource.keyState(.hidSystemState, key: 49))
+ }
+
+ if let tap = self.eventTap {
+ CGEvent.tapEnable(tap: tap, enable: true)
+ }
+
+ if !self.isEventTapEnabled() {
+ DebugLogger.shared.warning("Event tap re-enable failed — recreating tap", source: "GlobalHotkeyManager")
+ self.setupGlobalHotkeyWithRetry()
+ }
+
+ return Unmanaged.passUnretained(event)
+ }
+
+ @objc private func holdSpaceSettingChanged() {
+ if !SettingsStore.shared.holdSpaceToMute {
+ self.holdToMuteSpaceTap.cancel()
+ self.muteRecordingGeneration = nil
+ self.asrService.setDictationMuted(false)
+ }
+ }
+
+ private func hasConfiguredShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool {
+ var shortcuts = self.primaryShortcuts + self.promptShortcutAssignments.map(\.shortcut)
+ if self.promptModeShortcutEnabled {
+ shortcuts.append(self.promptModeShortcut)
+ }
+ if self.rewriteModeShortcutEnabled {
+ shortcuts.append(self.rewriteModeShortcut)
+ }
+ if self.commandModeShortcutEnabled, let shortcut = self.commandModeShortcut {
+ shortcuts.append(shortcut)
+ }
+ if let shortcut = SettingsStore.shared.cancelRecordingHotkeyShortcut {
+ shortcuts.append(shortcut)
+ }
+ if SettingsStore.shared.pasteLastTranscriptionShortcutEnabled,
+ let shortcut = SettingsStore.shared.pasteLastTranscriptionHotkeyShortcut
+ {
+ shortcuts.append(shortcut)
+ }
+ return shortcuts.contains { $0.matches(keyCode: keyCode, modifiers: modifiers) }
+ }
+
+ private var canTypeMuteTap: Bool {
+ self.muteRecordingGeneration == self.asrService.dictationMuteGeneration &&
+ SettingsStore.shared.holdSpaceToMute && self.asrService.isRunningOrStarting &&
+ !self.asrService.isDictionaryTrainingCaptureActive &&
+ (self.isDictateRecordingProvider?() ?? false) &&
+ !(self.isShortcutCaptureActiveProvider?() ?? false)
+ }
+
+ private func handleHoldToMute(type: CGEventType, event: CGEvent, proxy: CGEventTapProxy?) -> Bool {
+ let keyCode = UInt16(event.getIntegerValueField(.keyboardEventKeycode))
+ let modifiers = Self.modifierFlags(from: event.flags)
+ guard keyCode == 49, type == .keyDown || type == .keyUp else {
+ if self.holdToMuteKeyState.ownsSpace, type != .keyUp {
+ // Fast typing can overlap Space and the next letter. Flush before the
+ // letter, but never before navigation, shortcuts, or modifier changes.
+ let typing = type == .keyDown && HoldToMuteSpaceTap.isPlainTextKey(event) &&
+ !self.hasConfiguredShortcut(keyCode: keyCode, modifiers: modifiers)
+ self.holdToMuteSpaceTap.finish(at: event.timestamp, proxy: proxy, allowed: typing && self.canTypeMuteTap)
+ }
+ return false
+ }
+ let wasOwned = self.holdToMuteKeyState.ownsSpace
+ let consumed: Bool
+ var beginTap = false
+ var finishTap = false
+ switch type {
+ case .keyDown:
+ let isRepeat = event.getIntegerValueField(.keyboardEventAutorepeat) != 0
+ let canBegin = SettingsStore.shared.holdSpaceToMute && self.asrService.isRunningOrStarting &&
+ !self.asrService.isDictionaryTrainingCaptureActive &&
+ (self.isDictateRecordingProvider?() ?? false) &&
+ !(self.isShortcutCaptureActiveProvider?() ?? false) &&
+ modifiers.isDisjoint(with: HotkeyShortcut.relevantModifierMask) &&
+ !self.hasConfiguredShortcut(keyCode: 49, modifiers: [])
+ consumed = self.holdToMuteKeyState.keyDown(isRepeat: isRepeat, canBegin: canBegin)
+ self.holdToMuteSpaceTap.cancel()
+ if consumed, !isRepeat {
+ self.muteRecordingGeneration = self.asrService.dictationMuteGeneration
+ self.startMuteReleaseRecovery()
+ beginTap = true
+ }
+ case .keyUp:
+ consumed = self.holdToMuteKeyState.keyUp()
+ finishTap = consumed && self.canTypeMuteTap && modifiers.isDisjoint(with: HotkeyShortcut.relevantModifierMask)
+ self.muteRecordingGeneration = nil
+ self.muteReleaseRecoveryTask?.cancel()
+ self.muteReleaseRecoveryTask = nil
+ default:
+ return false
+ }
+ if consumed || wasOwned {
+ let muted = self.holdToMuteKeyState.ownsSpace &&
+ self.muteRecordingGeneration == self.asrService.dictationMuteGeneration &&
+ SettingsStore.shared.holdSpaceToMute
+ self.asrService.setDictationMuted(muted)
+ }
+ // Muting and unmuting always precede any destination/event bookkeeping.
+ if beginTap {
+ self.holdToMuteSpaceTap.begin(event)
+ } else if type == .keyUp {
+ self.holdToMuteSpaceTap.finish(at: event.timestamp, proxy: proxy, allowed: finishTap)
+ }
+ return consumed
+ }
+
+ /// Recover a missed key-up without unmuting while Space is physically held.
+ func reconcileHoldToMute(isPhysicallyDown: Bool) {
+ guard self.holdToMuteKeyState.ownsSpace else { return }
+ self.holdToMuteKeyState.reconcile(isPhysicallyDown: isPhysicallyDown)
+ if !self.holdToMuteKeyState.ownsSpace {
+ self.holdToMuteSpaceTap.cancel()
+ self.muteRecordingGeneration = nil
+ self.asrService.setDictationMuted(false)
+ }
+ }
+
+ private func startMuteReleaseRecovery() {
+ self.muteReleaseRecoveryTask?.cancel()
+ guard self.holdToMuteChecksPhysicalKeyState else { return }
+ self.muteReleaseRecoveryTask = Task { [weak self] in
+ // Give a normal short tap its key-up before recovering a lost release.
+ do { try await Task.sleep(nanoseconds: HoldToMuteSpaceTap.maximumDuration) } catch { return }
+ while !Task.isCancelled {
+ do { try await Task.sleep(nanoseconds: 100_000_000) } catch { return }
+ guard let self, self.holdToMuteKeyState.ownsSpace else { return }
+ self.reconcileHoldToMute(isPhysicallyDown: CGEventSource.keyState(.hidSystemState, key: 49))
+ }
+ }
+ }
+}
diff --git a/Sources/Fluid/Services/HoldToMuteKeyState.swift b/Sources/Fluid/Services/HoldToMuteKeyState.swift
new file mode 100644
index 00000000..903634cf
--- /dev/null
+++ b/Sources/Fluid/Services/HoldToMuteKeyState.swift
@@ -0,0 +1,95 @@
+import AppKit
+
+/// Keeps ownership until key-up, even if the recording stops or the setting changes.
+/// This prevents a held Space from typing repeats into the destination application.
+nonisolated struct HoldToMuteKeyState {
+ private(set) var ownsSpace = false
+
+ mutating func keyDown(isRepeat: Bool, canBegin: Bool) -> Bool {
+ if self.ownsSpace, isRepeat {
+ return true
+ }
+ // A fresh key-down proves a prior key-up was missed.
+ self.ownsSpace = !isRepeat && canBegin
+ return self.ownsSpace
+ }
+
+ mutating func keyUp() -> Bool {
+ let consumed = self.ownsSpace
+ self.ownsSpace = false
+ return consumed
+ }
+
+ mutating func reconcile(isPhysicallyDown: Bool) {
+ if !isPhysicallyDown {
+ self.ownsSpace = false
+ }
+ }
+}
+
+/// Defers an ordinary Space until a short tap is known, without delaying audio mute.
+/// Events go downstream of our tap, before the current event, preserving typing order
+/// without re-entering the hotkey handler or changing the clipboard.
+@MainActor
+final class HoldToMuteSpaceTap {
+ static let maximumDuration: UInt64 = 250_000_000
+
+ struct Context: Equatable {
+ let pid: pid_t
+ let leftClicks: UInt32
+ let rightClicks: UInt32
+ let otherClicks: UInt32
+ }
+
+ var contextProvider: () -> Context? = {
+ guard let pid = NSWorkspace.shared.frontmostApplication?.processIdentifier else { return nil }
+ return Context(
+ pid: pid,
+ leftClicks: CGEventSource.counterForEventType(.combinedSessionState, eventType: .leftMouseDown),
+ rightClicks: CGEventSource.counterForEventType(.combinedSessionState, eventType: .rightMouseDown),
+ otherClicks: CGEventSource.counterForEventType(.combinedSessionState, eventType: .otherMouseDown)
+ )
+ }
+
+ var postEvent: (CGEventTapProxy?, CGEvent) -> Void = { proxy, event in
+ guard let proxy else { return }
+ event.tapPostEvent(proxy)
+ }
+
+ private var keyDown: CGEvent?
+ private var context: Context?
+
+ func begin(_ event: CGEvent) {
+ self.keyDown = event.copy()
+ self.context = self.contextProvider()
+ }
+
+ func cancel() {
+ self.keyDown = nil
+ self.context = nil
+ }
+
+ func finish(at timestamp: CGEventTimestamp, proxy: CGEventTapProxy?, allowed: Bool) {
+ defer { self.cancel() }
+ guard allowed, let down = self.keyDown, let context = self.context,
+ timestamp >= down.timestamp, timestamp - down.timestamp <= Self.maximumDuration,
+ context == self.contextProvider(), let up = down.copy()
+ else { return }
+ // A completed tap, even when flushed before the next letter while Space is
+ // still physically down. Later repeats and the physical release stay owned.
+ down.timestamp = timestamp
+ up.timestamp = timestamp
+ up.type = .keyUp
+ self.postEvent(proxy, down)
+ self.postEvent(proxy, up)
+ }
+
+ static func isPlainTextKey(_ event: CGEvent) -> Bool {
+ guard event.flags.isDisjoint(with: [.maskCommand, .maskControl, .maskAlternate, .maskSecondaryFn]) else { return false }
+ var length = 0
+ var characters = [UniChar](repeating: 0, count: 4)
+ event.keyboardGetUnicodeString(maxStringLength: characters.count, actualStringLength: &length, unicodeString: &characters)
+ guard length > 0 else { return false }
+ return characters.prefix(length).allSatisfy { $0 >= 0x20 && $0 != 0x7f && !(0xf700...0xf8ff).contains($0) }
+ }
+}
diff --git a/Sources/Fluid/Services/ThreadSafeAudioBuffer.swift b/Sources/Fluid/Services/ThreadSafeAudioBuffer.swift
index b7648f80..69a1223d 100644
--- a/Sources/Fluid/Services/ThreadSafeAudioBuffer.swift
+++ b/Sources/Fluid/Services/ThreadSafeAudioBuffer.swift
@@ -21,6 +21,8 @@ final nonisolated class ThreadSafeAudioBuffer {
}
/// Returns the current number of samples
+ var isEmpty: Bool { self.lock.withLock { self.buffer.isEmpty } }
+
var count: Int {
self.lock.lock()
defer { lock.unlock() }
diff --git a/Sources/Fluid/UI/SettingsSearch.swift b/Sources/Fluid/UI/SettingsSearch.swift
index 6408fe95..27cdb43e 100644
--- a/Sources/Fluid/UI/SettingsSearch.swift
+++ b/Sources/Fluid/UI/SettingsSearch.swift
@@ -30,6 +30,7 @@ enum SettingsSearchTarget: Hashable {
case cancelRecordingShortcut
case pasteLastTranscriptionShortcut
case activationMode
+ case holdSpaceToMute
case copyToClipboard
case textInsertionMode
case spokenSend
@@ -86,6 +87,7 @@ enum SettingsSearchTarget: Hashable {
.analyticsPrivacy,
.microphonePermission,
.activationMode,
+ .holdSpaceToMute,
.copyToClipboard,
.textInsertionMode,
.spokenSend,
@@ -287,6 +289,7 @@ enum SettingsSearchIndex {
terms: ["reinsert recent text hotkey shortcut clipboard"]
),
.init(target: .activationMode, title: "Activation Mode", terms: ["hold toggle hotkey behavior"]),
+ .init(target: .holdSpaceToMute, title: "Hold Space to Mute", terms: ["pause microphone spacebar resume silence"]),
.init(
target: .copyToClipboard,
title: "Copy to Clipboard",
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 51a9f1ea..0e7c93b2 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -833,6 +833,14 @@ struct SettingsView: View {
.settingsSearchTarget(.activationMode)
Divider().opacity(0.2)
+ self.optionToggleRow(
+ title: "Hold Space to Mute",
+ description: "During dictation, hold Space to mute and release to resume. A quick tap types a space. Other Space shortcuts take priority.",
+ isOn: self.$settings.holdSpaceToMute
+ )
+ .settingsSearchTarget(.holdSpaceToMute)
+ Divider().opacity(0.2)
+
self.optionToggleRow(
title: "Copy to Clipboard",
description: "Automatically copy transcribed text to clipboard as a backup.",
diff --git a/Sources/Fluid/Views/BottomWaveformView.swift b/Sources/Fluid/Views/BottomWaveformView.swift
index 97b57b88..07cd6df7 100644
--- a/Sources/Fluid/Views/BottomWaveformView.swift
+++ b/Sources/Fluid/Views/BottomWaveformView.swift
@@ -71,18 +71,22 @@ struct BottomWaveformView: View {
var body: some View {
ZStack {
- self.barsView
- .foregroundStyle(self.barFillColor)
-
- if self.isProcessingVisualActive {
- CompositorShimmerSweep(duration: 1.05, peakOpacity: 0.9)
- .mask {
- self.barsView
- }
- .shadow(color: .white.opacity(0.28), radius: 2.5, x: 0, y: 0)
+ if self.contentState.isDictationMuted {
+ DictationMutedIndicator(compact: self.layout.waveformWidth < 80)
+ } else {
+ self.barsView
+ .foregroundStyle(self.barFillColor)
+
+ if self.isProcessingVisualActive {
+ CompositorShimmerSweep(duration: 1.05, peakOpacity: 0.9)
+ .mask {
+ self.barsView
+ }
+ .shadow(color: .white.opacity(0.28), radius: 2.5, x: 0, y: 0)
+ }
}
}
- .opacity(self.isWaitingForMicrophone ? 0.45 : 1)
+ .opacity(self.isWaitingForMicrophone && !self.contentState.isDictationMuted ? 0.45 : 1)
.animation(.easeOut(duration: 0.22), value: self.isWaitingForMicrophone)
.onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in
// Update threshold when user changes sensitivity setting
diff --git a/Sources/Fluid/Views/DictationMutedIndicator.swift b/Sources/Fluid/Views/DictationMutedIndicator.swift
new file mode 100644
index 00000000..bc0f0a7a
--- /dev/null
+++ b/Sources/Fluid/Views/DictationMutedIndicator.swift
@@ -0,0 +1,20 @@
+import SwiftUI
+
+struct DictationMutedIndicator: View {
+ var compact = false
+
+ var body: some View {
+ HStack(spacing: 5) {
+ Image(systemName: "mic.slash.fill")
+ if !self.compact {
+ Text("Muted")
+ }
+ }
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(.orange)
+ .fixedSize()
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel("Dictation muted. Release Space to resume.")
+ .help("Release Space to resume dictation")
+ }
+}
diff --git a/Sources/Fluid/Views/NotchContentViews.swift b/Sources/Fluid/Views/NotchContentViews.swift
index 634a8502..92d36964 100644
--- a/Sources/Fluid/Views/NotchContentViews.swift
+++ b/Sources/Fluid/Views/NotchContentViews.swift
@@ -101,6 +101,7 @@ class NotchContentState: ObservableObject {
@Published var mode: OverlayMode = .dictation
@Published var promptPickerMode: SettingsStore.PromptMode = .dictate
@Published var isProcessing: Bool = false // AI processing state
+ @Published var isDictationMuted = false
@Published var isAIProcessingFailureVisible: Bool = false
@Published private(set) var aiProcessingFailureMessage: String = "AI Enhancement failed"
@Published private(set) var canRetryAIProcessingFailure: Bool = true
@@ -1942,19 +1943,23 @@ struct CompactNotchWaveformView: View {
var body: some View {
ZStack {
- self.barsView(using: { index in
- self.displayHeight(for: index)
- })
- .foregroundStyle(self.color.opacity(self.contentState.isProcessing ? 0.16 : 1.0))
-
- if self.contentState.isProcessing {
- CompositorShimmerSweep(duration: 1.05, peakOpacity: 0.9)
- .mask {
- self.barsView(using: { index in
- self.displayHeight(for: index)
- })
- }
- .shadow(color: .white.opacity(0.28), radius: 2.5, x: 0, y: 0)
+ if self.contentState.isDictationMuted {
+ DictationMutedIndicator(compact: true)
+ } else {
+ self.barsView(using: { index in
+ self.displayHeight(for: index)
+ })
+ .foregroundStyle(self.color.opacity(self.contentState.isProcessing ? 0.16 : 1.0))
+
+ if self.contentState.isProcessing {
+ CompositorShimmerSweep(duration: 1.05, peakOpacity: 0.9)
+ .mask {
+ self.barsView(using: { index in
+ self.displayHeight(for: index)
+ })
+ }
+ .shadow(color: .white.opacity(0.28), radius: 2.5, x: 0, y: 0)
+ }
}
}
.onChange(of: self.data.audioLevel) { _, level in
diff --git a/Tests/FluidDictationIntegrationTests/HoldToMutePresentationTests.swift b/Tests/FluidDictationIntegrationTests/HoldToMutePresentationTests.swift
new file mode 100644
index 00000000..c8b1f943
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/HoldToMutePresentationTests.swift
@@ -0,0 +1,55 @@
+import AppKit
+@testable import FluidVoice_Debug
+import SwiftUI
+import XCTest
+
+@MainActor
+final class HoldToMutePresentationTests: XCTestCase {
+ func testMutedOverlayFitsEverySizeAndPreservesPreview() throws {
+ let state = NotchContentState.shared
+ let settings = SettingsStore.shared
+ let priorSize = settings.overlaySize
+ let priorMuted = state.isDictationMuted
+ let priorText = state.transcriptionText
+ let priorProcessing = state.isProcessing
+ let priorMode = state.mode
+ defer {
+ settings.overlaySize = priorSize
+ state.isDictationMuted = priorMuted
+ state.updateTranscription(priorText)
+ state.isProcessing = priorProcessing
+ state.mode = priorMode
+ }
+ state.mode = .dictation
+ state.isProcessing = false
+ state.isDictationMuted = true
+ state.updateTranscription("This is the thought I want to keep.")
+
+ for size in SettingsStore.OverlaySize.allCases {
+ settings.overlaySize = size
+ for scheme in [ColorScheme.light, .dark] {
+ let layout = BottomOverlayView.LayoutConstants.get(for: size)
+ let view = BottomOverlayView()
+ .padding(24)
+ .frame(width: max(400, layout.overlayWidth + 48), height: max(220, layout.overlayHeight + 80))
+ .background(scheme == .dark ? Color(white: 0.08) : Color(white: 0.94))
+ .appTheme(.adaptive(accent: FluidBrandColors.blue, colorScheme: scheme))
+ .environment(\.colorScheme, scheme)
+ let host = NSHostingView(rootView: view)
+ host.frame.size = host.fittingSize
+ host.layoutSubtreeIfNeeded()
+ XCTAssertTrue(host.frame.width.isFinite)
+ XCTAssertTrue(host.frame.height.isFinite)
+ let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
+ host.cacheDisplay(in: host.bounds, to: bitmap)
+ let png = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
+ let attachment = XCTAttachment(data: png, uniformTypeIdentifier: "public.png")
+ attachment.name = "hold-to-mute-\(size.rawValue)-\(scheme)"
+ attachment.lifetime = .keepAlways
+ add(attachment)
+ }
+ }
+ XCTAssertEqual(state.transcriptionText, "This is the thought I want to keep.")
+ XCTAssertTrue(state.isDictationMuted)
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/HoldToMuteTests.swift b/Tests/FluidDictationIntegrationTests/HoldToMuteTests.swift
new file mode 100644
index 00000000..b422e1f4
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/HoldToMuteTests.swift
@@ -0,0 +1,487 @@
+import AppKit
+import AVFoundation
+@testable import FluidVoice_Debug
+import XCTest
+
+final class HoldToMuteTests: XCTestCase {
+ func testTimelineRejectsClosedIntervalsAndKeepsSpeechOnBothSides() {
+ var timeline = DictationMuteTimeline()
+ timeline.setMuted(true, at: 1200)
+ timeline.setMuted(false, at: 1600)
+ XCTAssertEqual(timeline.audibleRanges(in: 0..<1000, packetHostTime: 1000, sampleRate: 1000, hostTicksPerSecond: 1000), [0..<200, 600..<1000])
+ // A whole delayed packet acquired while muted must still be excluded.
+ XCTAssertEqual(timeline.audibleRanges(in: 0..<200, packetHostTime: 1300, sampleRate: 1000, hostTicksPerSecond: 1000), [])
+ }
+
+ func testTimelineHandlesMultipleCyclesAndPartialFramesConservatively() {
+ var timeline = DictationMuteTimeline()
+ timeline.setMuted(true, at: 1025)
+ timeline.setMuted(false, at: 1075)
+ timeline.setMuted(true, at: 1150)
+ timeline.setMuted(false, at: 1175)
+ XCTAssertEqual(timeline.audibleRanges(in: 0..<30, packetHostTime: 1000, sampleRate: 100, hostTicksPerSecond: 1000), [0..<2, 8..<15, 18..<30])
+ XCTAssertEqual(timeline.audibleRanges(in: 10..<20, packetHostTime: 1000, sampleRate: 100, hostTicksPerSecond: 1000), [10..<15, 18..<20])
+ }
+
+ func testUntimestampedAudioCannotLeakAfterMute() {
+ var timeline = DictationMuteTimeline()
+ XCTAssertEqual(timeline.audibleRanges(in: 0..<10, packetHostTime: 0, sampleRate: 100, hostTicksPerSecond: 1000), [0..<10])
+ timeline.setMuted(true, at: 1000)
+ timeline.setMuted(false, at: 2000)
+ XCTAssertEqual(timeline.audibleRanges(in: 0..<10, packetHostTime: 0, sampleRate: 100, hostTicksPerSecond: 1000), [])
+ }
+
+ func testPipelineExcludesBackgroundSpeechAcrossPacketBoundariesAndSampleRates() {
+ for rate in [16_000.0, 44_100.0, 48_000.0] {
+ let buffer = ThreadSafeAudioBuffer()
+ let pipeline = self.pipeline(buffer: buffer)
+ pipeline.setRecordingEnabled(true, sessionID: 1, startHostTime: self.hostTime(1))
+ pipeline.setDictationMuted(true, at: self.hostTime(1.1))
+ pipeline.setDictationMuted(false, at: self.hostTime(1.3))
+ // All packets are delivered after release. Muted samples are distinct and loud.
+ let frameCount = Int(rate * 0.4)
+ let samples: [Float] = (0..<frameCount).map { frame in
+ let time = Double(frame) / rate
+ return time < 0.1 ? 0.1 : (time < 0.3 ? 0.9 : 0.2)
+ }
+ var offset = 0
+ for length in [83, 517, 4096, frameCount] {
+ let end = min(frameCount, offset + length)
+ self.feed(pipeline, samples: Array(samples[offset..<end]), rate: rate, time: 1 + Double(offset) / rate, sampleTime: Int64(offset))
+ offset = end
+ if offset == frameCount {
+ break
+ }
+ }
+ let captured = buffer.getAll()
+ XCTAssertTrue(captured.contains(0.1), "Leading speech missing at \(rate)")
+ XCTAssertTrue(captured.contains(0.2), "Resumed speech missing at \(rate)")
+ XCTAssertTrue(captured.allSatisfy { $0 <= 0.201 }, "Muted audio leaked through resampling at \(rate)")
+ XCTAssertEqual(captured.count, 4800, accuracy: 5, "Expected 200 ms of speech plus a 100 ms boundary")
+ }
+ }
+
+ func testLongMuteDoesNotAccumulateAudioAndStillSignalsCaptureReadiness() {
+ let buffer = ThreadSafeAudioBuffer()
+ let ready = expectation(description: "Capture is ready even if initially muted")
+ let pipeline = AudioCapturePipeline(audioBuffer: buffer, onFirstAudio: { _, _, _, _, _, _, _ in ready.fulfill() }, onLevel: { _ in }, onCaptureHealth: { _, _, _, _, _, _ in })
+ pipeline.setRecordingEnabled(true, sessionID: 1, startHostTime: self.hostTime(1))
+ pipeline.setDictationMuted(true, at: self.hostTime(1))
+ for second in 1...60 {
+ self.feed(pipeline, samples: Array(repeating: 0.9, count: 16_000), time: Double(second))
+ }
+ XCTAssertEqual(buffer.count, 0)
+ pipeline.setDictationMuted(false, at: self.hostTime(61))
+ self.feed(pipeline, samples: Array(repeating: 0.2, count: 1600), time: 61)
+ XCTAssertEqual(buffer.getAll(), Array(repeating: Float(0.2), count: 1600))
+ wait(for: [ready], timeout: 1)
+ }
+
+ func testStopWhileMutedRejectsTailAndNewSessionResets() {
+ let buffer = ThreadSafeAudioBuffer()
+ let pipeline = self.pipeline(buffer: buffer)
+ pipeline.setRecordingEnabled(true, sessionID: 1, startHostTime: self.hostTime(1))
+ self.feed(pipeline, samples: Array(repeating: 0.1, count: 1600), time: 1)
+ pipeline.setDictationMuted(true, at: self.hostTime(1.1))
+ pipeline.markRecordingEnd(atHostTime: self.hostTime(1.2))
+ self.feed(pipeline, samples: Array(repeating: 0.9, count: 3200), time: 1.1)
+ pipeline.finishRecording()
+ XCTAssertEqual(buffer.getAll(), Array(repeating: Float(0.1), count: 1600))
+ buffer.clear()
+ pipeline.resetDictationMute()
+ pipeline.setRecordingEnabled(true, sessionID: 2, startHostTime: self.hostTime(2))
+ self.feed(pipeline, samples: Array(repeating: 0.2, count: 1600), time: 2)
+ XCTAssertEqual(buffer.getAll(), Array(repeating: Float(0.2), count: 1600))
+ }
+
+ func testAudioRouteRetryRetainsMute() {
+ let buffer = ThreadSafeAudioBuffer()
+ let pipeline = self.pipeline(buffer: buffer)
+ pipeline.setRecordingEnabled(true, sessionID: 1, attemptID: 1, startHostTime: self.hostTime(1))
+ pipeline.setDictationMuted(true, at: self.hostTime(1))
+ pipeline.setRecordingEnabled(false)
+ pipeline.setRecordingEnabled(true, sessionID: 1, attemptID: 2, startHostTime: self.hostTime(2))
+ self.feed(pipeline, samples: Array(repeating: 0.9, count: 1600), time: 2)
+ XCTAssertEqual(buffer.count, 0)
+ }
+
+ func testSpeechFixtureIsPreservedAndMutedFixtureIsExcluded() throws {
+ let speech = try AudioFixtureLoader.load16kMonoFloatSamples(named: "dictation_fixture", ext: "wav")
+ let buffer = ThreadSafeAudioBuffer()
+ let pipeline = self.pipeline(buffer: buffer)
+ let duration = Double(speech.count) / 16_000
+ pipeline.setRecordingEnabled(true, sessionID: 1, startHostTime: self.hostTime(1))
+ self.feed(pipeline, samples: speech, time: 1)
+ pipeline.setDictationMuted(true, at: self.hostTime(1 + duration))
+ pipeline.setDictationMuted(false, at: self.hostTime(1 + duration * 2))
+ // Even speech delivered after release is discarded by acquisition time.
+ self.feed(pipeline, samples: speech, time: 1 + duration)
+ self.feed(pipeline, samples: speech, time: 1 + duration * 2)
+ XCTAssertEqual(buffer.getAll(), speech + Array(repeating: Float(0), count: 1600) + speech)
+ }
+
+ func testDisabledPipelinePreservesExactAudio() {
+ let buffer = ThreadSafeAudioBuffer()
+ let pipeline = self.pipeline(buffer: buffer)
+ let samples = (0..<1600).map { Float($0) / 1600 }
+ pipeline.setRecordingEnabled(true, sessionID: 1, startHostTime: self.hostTime(1))
+ self.feed(pipeline, samples: samples, time: 1)
+ XCTAssertEqual(buffer.getAll(), samples)
+ }
+
+ @MainActor
+ func testSpaceMutesOnlyActiveDictationAndConsumesRepeatsAndRelease() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ let manager = self.manager(asr: asr)
+ XCTAssertNotNil(try self.send(manager, type: .keyDown))
+ XCTAssertFalse(asr.isDictationMuted)
+ _ = try self.send(manager, type: .keyUp)
+ asr.isRunning = true
+ XCTAssertNil(try self.send(manager, type: .keyDown))
+ XCTAssertTrue(asr.isDictationMuted)
+ XCTAssertTrue(NotchContentState.shared.isDictationMuted)
+ XCTAssertNil(try self.send(manager, type: .keyDown, isRepeat: true))
+ XCTAssertNil(try self.send(manager, type: .keyUp, modifiers: .maskShift))
+ XCTAssertFalse(asr.isDictationMuted)
+ XCTAssertFalse(NotchContentState.shared.isDictationMuted)
+ asr.isRunning = false
+ }
+ }
+
+ @MainActor
+ func testExistingSpaceChordsAndOtherModesPassThrough() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ asr.isRunning = true
+ defer { asr.isRunning = false }
+ let manager = self.manager(asr: asr)
+ for modifier: CGEventFlags in [.maskCommand, .maskAlternate, .maskControl, .maskShift, .maskSecondaryFn] {
+ XCTAssertNotNil(try self.send(manager, type: .keyDown, modifiers: modifier))
+ XCTAssertFalse(asr.isDictationMuted)
+ XCTAssertNotNil(try self.send(manager, type: .keyUp, modifiers: modifier))
+ }
+ let otherMode = self.manager(asr: asr, isDictation: false)
+ XCTAssertNotNil(try self.send(otherMode, type: .keyDown))
+ XCTAssertFalse(asr.isDictationMuted)
+ }
+ }
+
+ @MainActor
+ func testStopDoesNotLeakHeldSpaceOrMuteNextSession() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ let manager = self.manager(asr: asr)
+ asr.isRunning = true
+ _ = try self.send(manager, type: .keyDown)
+ asr.isRunning = false
+ XCTAssertFalse(asr.isDictationMuted)
+ XCTAssertNil(try self.send(manager, type: .keyDown, isRepeat: true))
+ asr.isRunning = true
+ XCTAssertNil(try self.send(manager, type: .keyDown, isRepeat: true))
+ XCTAssertFalse(asr.isDictationMuted)
+ XCTAssertNil(try self.send(manager, type: .keyUp))
+ asr.isRunning = false
+ }
+ }
+
+ @MainActor
+ func testDisablingSettingUnmutesImmediatelyAndPreservesKeyOwnership() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ let manager = self.manager(asr: asr)
+ asr.isRunning = true
+ _ = try self.send(manager, type: .keyDown)
+ SettingsStore.shared.holdSpaceToMute = false
+ XCTAssertFalse(asr.isDictationMuted)
+ XCTAssertNil(try self.send(manager, type: .keyDown, isRepeat: true))
+ XCTAssertNil(try self.send(manager, type: .keyUp))
+ XCTAssertNotNil(try self.send(manager, type: .keyDown))
+ asr.isRunning = false
+ }
+ }
+
+ @MainActor
+ func testMissedReleaseRecoversWithoutUnmutingHeldKey() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ let manager = self.manager(asr: asr)
+ asr.isRunning = true
+ _ = try self.send(manager, type: .keyDown)
+ manager.reconcileHoldToMute(isPhysicallyDown: true)
+ XCTAssertTrue(asr.isDictationMuted)
+ manager.reconcileHoldToMute(isPhysicallyDown: false)
+ XCTAssertFalse(asr.isDictationMuted)
+ XCTAssertNotNil(try self.send(manager, type: .keyUp))
+ asr.isRunning = false
+ }
+ }
+
+ @MainActor
+ func testConfiguredSpaceShortcutHasPriorityOverMute() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ asr.isRunning = true
+ let manager = self.manager(asr: asr)
+ manager.updatePrimaryShortcuts([HotkeyShortcut(keyCode: 49, modifierFlags: [])])
+ _ = try self.send(manager, type: .keyDown)
+ XCTAssertFalse(asr.isDictationMuted)
+ asr.isRunning = false
+ }
+ }
+
+ @MainActor
+ func testNewSettingDefaultsOffAndIsSearchable() {
+ let defaults = UserDefaults.standard
+ let previous = defaults.object(forKey: "HoldSpaceToMute")
+ defer {
+ if let previous {
+ defaults.set(previous, forKey: "HoldSpaceToMute")
+ } else {
+ defaults.removeObject(forKey: "HoldSpaceToMute")
+ }
+ }
+ defaults.removeObject(forKey: "HoldSpaceToMute")
+ XCTAssertFalse(SettingsStore.shared.holdSpaceToMute)
+ XCTAssertEqual(SettingsSearchTarget.holdSpaceToMute.section, .dictation)
+ }
+
+ @MainActor
+ func testQuickTapMutesImmediatelyThenTypesExactlyOneSpaceOnRelease() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ asr.isRunning = true
+ defer { asr.isRunning = false }
+ let manager = self.manager(asr: asr)
+ let context = HoldToMuteSpaceTap.Context(pid: 100, leftClicks: 0, rightClicks: 0, otherClicks: 0)
+ var captureCount = 0
+ manager.holdToMuteSpaceTap.contextProvider = {
+ if captureCount == 0 {
+ XCTAssertTrue(asr.isDictationMuted, "Mute must precede context capture")
+ }
+ captureCount += 1
+ return context
+ }
+ var posted: [CGEvent] = []
+ manager.holdToMuteSpaceTap.postEvent = { _, event in
+ XCTAssertFalse(asr.isDictationMuted, "Resume must precede replay")
+ posted.append(event)
+ }
+ XCTAssertNil(try self.send(manager, type: .keyDown, at: 1_000_000_000))
+ XCTAssertTrue(asr.isDictationMuted)
+ XCTAssertTrue(posted.isEmpty)
+ XCTAssertNil(try self.send(manager, type: .keyUp, at: 1_100_000_000))
+ XCTAssertFalse(asr.isDictationMuted)
+ XCTAssertEqual(posted.map(\.type), [.keyDown, .keyUp])
+ for event in posted {
+ XCTAssertEqual(event.getIntegerValueField(.keyboardEventKeycode), 49)
+ XCTAssertEqual(event.getIntegerValueField(.keyboardEventAutorepeat), 0)
+ XCTAssertEqual(event.timestamp, 1_100_000_000)
+ var length = 0
+ var character: UniChar = 0
+ event.keyboardGetUnicodeString(maxStringLength: 1, actualStringLength: &length, unicodeString: &character)
+ XCTAssertEqual(length, 1)
+ XCTAssertEqual(character, 0x20)
+ }
+ _ = try self.send(manager, type: .keyUp, at: 1_110_000_000)
+ XCTAssertEqual(posted.count, 2)
+ }
+ }
+
+ @MainActor
+ func testLongHoldAndAutorepeatNeverTypeSpaces() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ asr.isRunning = true
+ defer { asr.isRunning = false }
+ let manager = self.manager(asr: asr)
+ manager.holdToMuteSpaceTap.postEvent = { _, _ in XCTFail("A hold must not type") }
+ for repeatKey in [false, true] {
+ _ = try self.send(manager, type: .keyDown, at: 1_000_000_000)
+ if repeatKey {
+ _ = try self.send(manager, type: .keyDown, isRepeat: true, at: 1_050_000_000)
+ }
+ XCTAssertTrue(asr.isDictationMuted)
+ let release: UInt64 = repeatKey ? 1_100_000_000 : 1_250_000_001
+ _ = try self.send(manager, type: .keyUp, at: release)
+ XCTAssertFalse(asr.isDictationMuted)
+ }
+ }
+ }
+
+ @MainActor
+ func testFastTypingFlushesSpaceBeforeNextLetterAndIgnoresPreviousLetterRelease() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ asr.isRunning = true
+ defer { asr.isRunning = false }
+ let manager = self.manager(asr: asr)
+ var posted: [CGEventType] = []
+ manager.holdToMuteSpaceTap.postEvent = { _, event in posted.append(event.type) }
+ _ = try self.send(manager, type: .keyDown, at: 1_000_000_000)
+ XCTAssertNotNil(try self.send(manager, type: .keyUp, at: 1_020_000_000, keyCode: 0, text: "a"))
+ XCTAssertTrue(posted.isEmpty)
+ XCTAssertNotNil(try self.send(manager, type: .keyDown, at: 1_050_000_000, keyCode: 11, text: "b"))
+ XCTAssertEqual(posted, [.keyDown, .keyUp], "Space must be posted before the next letter returns from the tap")
+ XCTAssertTrue(asr.isDictationMuted, "Typing does not release the physical mute hold")
+ _ = try self.send(manager, type: .keyDown, isRepeat: true, at: 1_060_000_000)
+ _ = try self.send(manager, type: .keyUp, at: 1_090_000_000)
+ XCTAssertEqual(posted.count, 2)
+ XCTAssertFalse(asr.isDictationMuted)
+ }
+ }
+
+ @MainActor
+ func testAppSwitchOrMouseClickCancelsPendingSpace() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ asr.isRunning = true
+ defer { asr.isRunning = false }
+ let manager = self.manager(asr: asr)
+ let original = HoldToMuteSpaceTap.Context(pid: 100, leftClicks: 1, rightClicks: 2, otherClicks: 3)
+ let changed = [
+ HoldToMuteSpaceTap.Context(pid: 101, leftClicks: 1, rightClicks: 2, otherClicks: 3),
+ HoldToMuteSpaceTap.Context(pid: 100, leftClicks: 2, rightClicks: 2, otherClicks: 3),
+ HoldToMuteSpaceTap.Context(pid: 100, leftClicks: 1, rightClicks: 3, otherClicks: 3),
+ HoldToMuteSpaceTap.Context(pid: 100, leftClicks: 1, rightClicks: 2, otherClicks: 4),
+ nil,
+ ]
+ var context: HoldToMuteSpaceTap.Context? = original
+ manager.holdToMuteSpaceTap.contextProvider = { context }
+ manager.holdToMuteSpaceTap.postEvent = { _, _ in XCTFail("Destination changed") }
+ for destination in changed {
+ context = original
+ _ = try self.send(manager, type: .keyDown, at: 1_000_000_000)
+ context = destination
+ _ = try self.send(manager, type: .keyUp, at: 1_100_000_000)
+ XCTAssertFalse(asr.isDictationMuted)
+ }
+ }
+ }
+
+ @MainActor
+ func testNavigationAndModifierChangesCancelTapWithoutEndingMute() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ asr.isRunning = true
+ defer { asr.isRunning = false }
+ let manager = self.manager(asr: asr)
+ manager.holdToMuteSpaceTap.postEvent = { _, _ in XCTFail("Interrupted gesture must not type") }
+ for keyCode: CGKeyCode in [48, 51, 123] {
+ _ = try self.send(manager, type: .keyDown, at: 1_000_000_000)
+ _ = try self.send(manager, type: .keyDown, at: 1_050_000_000, keyCode: keyCode, text: "\t")
+ XCTAssertTrue(asr.isDictationMuted)
+ _ = try self.send(manager, type: .keyUp, at: 1_100_000_000)
+ }
+ _ = try self.send(manager, type: .keyDown, at: 2_000_000_000)
+ _ = try self.send(manager, type: .flagsChanged, modifiers: .maskShift, at: 2_050_000_000, keyCode: 56, text: "")
+ XCTAssertTrue(asr.isDictationMuted)
+ _ = try self.send(manager, type: .keyUp, at: 2_100_000_000)
+ XCTAssertFalse(asr.isDictationMuted)
+ }
+ }
+
+ @MainActor
+ func testStoppedSessionDisabledSettingAndLostReleaseCannotReplaySpace() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ let manager = self.manager(asr: asr)
+ manager.holdToMuteSpaceTap.postEvent = { _, _ in XCTFail("Cancelled tap must not type") }
+ for reason in 0..<4 {
+ SettingsStore.shared.holdSpaceToMute = true
+ asr.isRunning = true
+ _ = try self.send(manager, type: .keyDown, at: 1_000_000_000)
+ switch reason {
+ case 0: asr.isRunning = false
+ case 1:
+ asr.isRunning = false
+ asr.isRunning = true
+ case 2: SettingsStore.shared.holdSpaceToMute = false
+ default: manager.reconcileHoldToMute(isPhysicallyDown: false)
+ }
+ _ = try self.send(manager, type: .keyUp, at: 1_100_000_000)
+ XCTAssertFalse(asr.isDictationMuted)
+ asr.isRunning = false
+ }
+ }
+ }
+
+ @MainActor
+ func testRepeatedQuickTapsEachTypeOneSpace() throws {
+ try self.withMuteSetting {
+ let asr = ASRService()
+ asr.isRunning = true
+ defer { asr.isRunning = false }
+ let manager = self.manager(asr: asr)
+ var count = 0
+ manager.holdToMuteSpaceTap.postEvent = { _, _ in count += 1 }
+ for index in 0..<10 {
+ let time = UInt64(index) * 200_000_000 + 1_000_000_000
+ _ = try self.send(manager, type: .keyDown, at: time)
+ _ = try self.send(manager, type: .keyUp, at: time + 100_000_000)
+ }
+ XCTAssertEqual(count, 20)
+ }
+ }
+
+ private func hostTime(_ seconds: Double) -> UInt64 {
+ AVAudioTime.hostTime(forSeconds: seconds)
+ }
+
+ private func pipeline(buffer: ThreadSafeAudioBuffer) -> AudioCapturePipeline {
+ AudioCapturePipeline(audioBuffer: buffer, onFirstAudio: { _, _, _, _, _, _, _ in }, onLevel: { _ in }, onCaptureHealth: { _, _, _, _, _, _ in })
+ }
+
+ private func feed(_ pipeline: AudioCapturePipeline, samples: [Float], rate: Double = 16_000, time: Double, sampleTime: Int64 = -1) {
+ samples.withUnsafeBufferPointer { pointer in
+ guard let base = pointer.baseAddress else { return }
+ pipeline.handle(samples: base, frameCount: samples.count, sampleRate: rate, inputHostTime: self.hostTime(time), inputSampleTime: sampleTime)
+ }
+ }
+
+ @MainActor
+ private func withMuteSetting(_ body: () throws -> Void) rethrows {
+ let previous = SettingsStore.shared.holdSpaceToMute
+ defer { SettingsStore.shared.holdSpaceToMute = previous }
+ SettingsStore.shared.holdSpaceToMute = true
+ try body()
+ }
+
+ @MainActor
+ private func manager(asr: ASRService, isDictation: Bool = true) -> GlobalHotkeyManager {
+ let manager = GlobalHotkeyManager(
+ asrService: asr,
+ primaryShortcuts: [HotkeyShortcut(keyCode: 61, modifierFlags: [])],
+ promptModeShortcut: HotkeyShortcut(keyCode: 60, modifierFlags: []),
+ commandModeShortcut: nil,
+ rewriteModeShortcut: HotkeyShortcut(keyCode: 15, modifierFlags: [.option]),
+ promptModeShortcutEnabled: false,
+ commandModeShortcutEnabled: false,
+ rewriteModeShortcutEnabled: false,
+ startRecordingCallback: {},
+ stopAndProcessCallback: { _ in },
+ isDictateRecordingProvider: { isDictation }
+ )
+ manager.setHotkeyMode(.toggle)
+ manager.holdToMuteChecksPhysicalKeyState = false
+ manager.holdToMuteSpaceTap.contextProvider = {
+ HoldToMuteSpaceTap.Context(pid: 100, leftClicks: 0, rightClicks: 0, otherClicks: 0)
+ }
+ return manager
+ }
+
+ @MainActor
+ private func send(_ manager: GlobalHotkeyManager, type: CGEventType, modifiers: CGEventFlags = [], isRepeat: Bool = false, at timestamp: UInt64? = nil, keyCode: CGKeyCode = 49, text: String = " ") throws -> CGEvent? {
+ let event = try XCTUnwrap(CGEvent(keyboardEventSource: nil, virtualKey: keyCode, keyDown: type == .keyDown))
+ if let timestamp {
+ event.timestamp = timestamp
+ }
+ let characters = Array(text.utf16)
+ event.keyboardSetUnicodeString(stringLength: characters.count, unicodeString: characters)
+ event.flags = modifiers
+ event.setIntegerValueField(.keyboardEventAutorepeat, value: isRepeat ? 1 : 0)
+ return withExtendedLifetime(event) {
+ manager.handleKeyEvent(type: type, event: event)?.takeUnretainedValue()
+ }
+ }
+}