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

speed up recording overlays

altic-dev16b74b1fc1fa
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 2410fd45..5dd4b03e 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -3041,10 +3041,16 @@ struct ContentView: View {
"ContentView: startRecording() for model=\(model.displayName), supportsStreaming=\(model.supportsStreaming)",
source: "ContentView"
)
+ guard !self.asr.isRunningOrStarting else {
+ DebugLogger.shared.debug("ContentView: start ignored because capture is already active", source: "ContentView")
+ return
+ }
self.advanceOverlayLifecycle()
self.setActiveRecordingMode(.dictate)
- let shouldShowDictationOverlay = !self.isRecordingForCommand && !self.isRecordingForRewrite
+ let shouldShowDictationOverlay = !self.isRecordingForCommand
+ && !self.isRecordingForRewrite
+ && self.asr.micStatus == .authorized
let shouldPlayStartSound = !self.isRecordingForCommand
&& !self.isRecordingForRewrite
&& self.asr.micStatus == .authorized
@@ -3052,20 +3058,18 @@ struct ContentView: View {
// Ensure normal dictation mode is set (command/rewrite modes set their own)
if shouldShowDictationOverlay {
self.menuBarManager.setOverlayMode(.dictation)
+ self.menuBarManager.showRecordingOverlayImmediately()
}
Task {
if shouldPlayStartSound, !self.asr.isRunning {
TranscriptionSoundPlayer.shared.playStartSound()
}
- await self.asr.start(onCaptureStarted: {
+ let startOutcome = await self.asr.start(onCaptureStarted: {
self.captureRecordingContext()
self.prewarmPrivateAIDictationIfNeeded(for: .primary)
- if shouldShowDictationOverlay {
- self.menuBarManager.showRecordingOverlayImmediately()
- }
})
- if !self.asr.isRunning {
+ if startOutcome == .failed {
self.menuBarManager.hideRecordingOverlayImmediately(reason: "asr_start_failed")
}
}
@@ -3457,7 +3461,7 @@ struct ContentView: View {
handled = true
}
- if self.asr.isRunning {
+ if self.asr.isRunningOrStarting {
DebugLogger.shared.debug("Cancel shortcut: cancelling ASR recording", source: "ContentView")
Task { await self.asr.stopWithoutTranscription() }
self.cancelPrewarmDictationIfNeeded()
@@ -3672,26 +3676,28 @@ extension ContentView {
self.setActiveRecordingMode(mode)
self.rewriteModeService.clearState()
- guard !self.asr.isRunning else {
- self.appBench("asr_start_skipped reason=already_running")
+ guard !self.asr.isRunningOrStarting else {
+ self.appBench("asr_start_skipped reason=already_running_or_starting")
return
}
self.advanceOverlayLifecycle()
+ if self.asr.micStatus == .authorized {
+ self.appBench("overlay_mode_request mode=Dictation")
+ self.menuBarManager.setOverlayMode(.dictation)
+ self.menuBarManager.showRecordingOverlayImmediately()
+ self.appBench("overlay_mode_requested mode=Dictation")
+ }
Task {
let asrStartStartedAt = ProcessInfo.processInfo.systemUptime
DebugLogger.shared.benchmark("APP_BENCH", message: "asr_start_call", source: "AppBenchmark")
if SettingsStore.shared.enableTranscriptionSounds, !self.asr.isRunning {
TranscriptionSoundPlayer.shared.playStartSound()
}
- await self.asr.start(onCaptureStarted: {
+ let startOutcome = await self.asr.start(onCaptureStarted: {
self.captureRecordingContext()
- self.appBench("overlay_mode_request mode=Dictation")
- self.menuBarManager.setOverlayMode(.dictation)
- self.menuBarManager.showRecordingOverlayImmediately()
- self.appBench("overlay_mode_requested mode=Dictation")
self.prewarmPrivateAIDictationIfNeeded(for: slot)
})
- if !self.asr.isRunning {
+ if startOutcome == .failed {
self.menuBarManager.hideRecordingOverlayImmediately(reason: "asr_start_failed")
}
DebugLogger.shared.benchmark(
diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swift
index 03528d67..cf3fc71e 100644
--- a/Sources/Fluid/Persistence/BackupService.swift
+++ b/Sources/Fluid/Persistence/BackupService.swift
@@ -57,6 +57,8 @@ struct SettingsBackupPayload: Codable, Equatable {
let pressAndHoldMode: Bool
let hotkeyMode: HotkeyActivationMode?
let enableStreamingPreview: Bool
+ // Optional so backups created before the silence filter still decode.
+ let skipSilentRecordingsEnabled: Bool?
let enableAIStreaming: Bool
let copyTranscriptionToClipboard: Bool
let textInsertionMode: SettingsStore.TextInsertionMode
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index e786893f..6a357658 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -1760,6 +1760,16 @@ final class SettingsStore: ObservableObject {
}
}
+ /// Skips clearly silent recordings up to four seconds before invoking ASR.
+ /// Opt-in so quiet speech keeps the existing transcription behavior by default.
+ var skipSilentRecordingsEnabled: Bool {
+ get { self.defaults.object(forKey: Keys.skipSilentRecordingsEnabled) as? Bool ?? false }
+ set {
+ objectWillChange.send()
+ self.defaults.set(newValue, forKey: Keys.skipSilentRecordingsEnabled)
+ }
+ }
+
var enableAIStreaming: Bool {
get {
let value = self.defaults.object(forKey: Keys.enableAIStreaming)
@@ -1939,6 +1949,7 @@ final class SettingsStore: ObservableObject {
set {
objectWillChange.send()
self.defaults.set(newValue.rawValue, forKey: Keys.overlayPosition)
+ NotificationCenter.default.post(name: NSNotification.Name("OverlayPositionChanged"), object: nil)
}
}
@@ -3044,6 +3055,7 @@ final class SettingsStore: ObservableObject {
pressAndHoldMode: self.pressAndHoldMode,
hotkeyMode: self.hotkeyMode,
enableStreamingPreview: self.enableStreamingPreview,
+ skipSilentRecordingsEnabled: self.skipSilentRecordingsEnabled,
enableAIStreaming: self.enableAIStreaming,
copyTranscriptionToClipboard: self.copyTranscriptionToClipboard,
textInsertionMode: self.textInsertionMode,
@@ -3158,6 +3170,9 @@ final class SettingsStore: ObservableObject {
self.shareAnonymousAnalytics = payload.shareAnonymousAnalytics
self.hotkeyMode = payload.hotkeyMode ?? (payload.pressAndHoldMode ? .hold : .toggle)
self.enableStreamingPreview = payload.enableStreamingPreview
+ if let skipSilentRecordingsEnabled = payload.skipSilentRecordingsEnabled {
+ self.skipSilentRecordingsEnabled = skipSilentRecordingsEnabled
+ }
self.enableAIStreaming = payload.enableAIStreaming
self.copyTranscriptionToClipboard = payload.copyTranscriptionToClipboard
self.textInsertionMode = payload.textInsertionMode
@@ -4910,6 +4925,7 @@ private extension SettingsStore {
static let pressAndHoldMode = "PressAndHoldMode"
static let hotkeyMode = "HotkeyMode"
static let enableStreamingPreview = "EnableStreamingPreview"
+ static let skipSilentRecordingsEnabled = "SkipSilentRecordingsEnabled"
static let enableAIStreaming = "EnableAIStreaming"
static let experimentalDirectAudioCaptureEnabled = "ExperimentalDirectAudioCaptureEnabled"
static let experimentalDirectAudioCaptureForcedOff = "ExperimentalDirectAudioCaptureForcedOff"
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 8c3855c1..96a4c052 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -39,6 +39,21 @@ private actor TranscriptionExecutor {
}
}
+struct ShortAudioSilenceAssessment: Equatable {
+ let durationMilliseconds: Int
+ let isEligible: Bool
+ let shouldSkipTranscription: Bool
+ let peakAmplitude: Float
+ let rmsAmplitude: Float
+ let maximumFrameRMS: Float
+}
+
+enum AudioCaptureStartOutcome: Equatable {
+ case started
+ case alreadyActive
+ case failed
+}
+
// swiftlint:disable file_length type_body_length
/// A comprehensive speech recognition service that handles real-time audio transcription.
///
@@ -72,6 +87,90 @@ private actor TranscriptionExecutor {
/// Models are cached locally to avoid repeated downloads.
@MainActor
final class ASRService: ObservableObject {
+ nonisolated static func shouldAssessShortAudioSilence(
+ isEnabled: Bool,
+ useDictionaryTrainingPath: Bool,
+ hasRecognizedStreamingPreview: Bool
+ ) -> Bool {
+ isEnabled && !useDictionaryTrainingPath && !hasRecognizedStreamingPreview
+ }
+
+ nonisolated static func assessShortAudioSilence(
+ _ samples: [Float],
+ sampleRate: Int = 16_000
+ ) -> ShortAudioSilenceAssessment {
+ let durationMilliseconds = sampleRate > 0
+ ? Int((Double(samples.count) / Double(sampleRate) * 1000).rounded())
+ : 0
+ let maximumSampleCount = max(sampleRate, 0) * 4
+ guard !samples.isEmpty, sampleRate > 0, samples.count <= maximumSampleCount else {
+ return ShortAudioSilenceAssessment(
+ durationMilliseconds: durationMilliseconds,
+ isEligible: false,
+ shouldSkipTranscription: false,
+ peakAmplitude: 0,
+ rmsAmplitude: 0,
+ maximumFrameRMS: 0
+ )
+ }
+
+ let frameSize = max(sampleRate / 50, 1) // 20 ms
+ var peak: Float = 0
+ var totalSquareSum = 0.0
+ var frameSquareSum = 0.0
+ var frameSampleCount = 0
+ var maximumFrameRMS: Float = 0
+
+ for sample in samples {
+ guard sample.isFinite else {
+ return ShortAudioSilenceAssessment(
+ durationMilliseconds: durationMilliseconds,
+ isEligible: true,
+ shouldSkipTranscription: false,
+ peakAmplitude: peak,
+ rmsAmplitude: 0,
+ maximumFrameRMS: maximumFrameRMS
+ )
+ }
+
+ let magnitude = abs(sample)
+ peak = max(peak, magnitude)
+ let square = Double(sample) * Double(sample)
+ totalSquareSum += square
+ frameSquareSum += square
+ frameSampleCount += 1
+
+ if frameSampleCount == frameSize {
+ maximumFrameRMS = max(
+ maximumFrameRMS,
+ Float(sqrt(frameSquareSum / Double(frameSampleCount)))
+ )
+ frameSquareSum = 0
+ frameSampleCount = 0
+ }
+ }
+
+ if frameSampleCount > 0 {
+ maximumFrameRMS = max(
+ maximumFrameRMS,
+ Float(sqrt(frameSquareSum / Double(frameSampleCount)))
+ )
+ }
+ let rms = Float(sqrt(totalSquareSum / Double(samples.count)))
+
+ // Calibrated conservatively against real FluidVoice captures. Requiring
+ // all three conditions keeps quiet speech and short words on the ASR path.
+ let shouldSkip = peak < 0.01 && rms < 0.002 && maximumFrameRMS < 0.0045
+ return ShortAudioSilenceAssessment(
+ durationMilliseconds: durationMilliseconds,
+ isEligible: true,
+ shouldSkipTranscription: shouldSkip,
+ peakAmplitude: peak,
+ rmsAmplitude: rms,
+ maximumFrameRMS: maximumFrameRMS
+ )
+ }
+
nonisolated static func directCaptureDurationIsMismatched(
capturedMilliseconds: Int,
elapsedMilliseconds: Int
@@ -1319,19 +1418,20 @@ final class ASRService: ObservableObject {
/// ## Errors
/// If audio session configuration fails, the method will silently fail
/// and `isRunning` will remain `false`. Check the debug logs for details.
+ @discardableResult
func start(
forDictionaryTraining: Bool = false,
onCaptureStarted: (@MainActor () -> Void)? = nil
- ) async {
+ ) async -> AudioCaptureStartOutcome {
DebugLogger.shared.info("🎤 START() called - beginning recording session", source: "ASRService")
guard self.micStatus == .authorized else {
DebugLogger.shared.error("❌ START() blocked - mic not authorized", source: "ASRService")
- return
+ return .failed
}
guard self.isRunning == false, self.isStarting == false else {
DebugLogger.shared.warning("⚠️ START() blocked - already running (started: \(self.isRunning), starting: \(self.isStarting))", source: "ASRService")
- return
+ return .alreadyActive
}
self.isStarting = true
defer { self.finishAudioCaptureStart() }
@@ -1391,7 +1491,7 @@ final class ASRService: ObservableObject {
if didPause {
await MediaPlaybackService.shared.resumeIfWePaused(true)
}
- return
+ return .started
}
self.didPauseMediaForThisSession = didPause
if didPause {
@@ -1419,6 +1519,7 @@ final class ASRService: ObservableObject {
DebugLogger.shared.debug("⏸️ Skipping streaming - model '\(model.displayName)' does not support real-time chunk processing", source: "ASRService")
}
DebugLogger.shared.info("✅ START() completed successfully", source: "ASRService")
+ return .started
} catch {
self.isDictionaryTrainingCaptureActive = false
self.audioCapturePipeline.setRecordingEnabled(false)
@@ -1457,6 +1558,7 @@ final class ASRService: ObservableObject {
object: nil,
userInfo: ["errorMessage": errorMessage]
)
+ return .failed
}
}
@@ -1634,6 +1736,45 @@ final class ASRService: ObservableObject {
return ""
}
+ let hasRecognizedStreamingPreview = !self.partialTranscription
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ .isEmpty
+ if Self.shouldAssessShortAudioSilence(
+ isEnabled: SettingsStore.shared.skipSilentRecordingsEnabled,
+ useDictionaryTrainingPath: useDictionaryTrainingPath,
+ hasRecognizedStreamingPreview: hasRecognizedStreamingPreview
+ ) {
+ let silenceGateStartedAt = ProcessInfo.processInfo.systemUptime
+ let silenceAssessment = Self.assessShortAudioSilence(pcm)
+ let silenceGateMicroseconds = Int(
+ ((ProcessInfo.processInfo.systemUptime - silenceGateStartedAt) * 1_000_000).rounded()
+ )
+ self.benchmarkLog(
+ "silence_gate eligible=\(silenceAssessment.isEligible) skip=\(silenceAssessment.shouldSkipTranscription) " +
+ "audioMs=\(silenceAssessment.durationMilliseconds) analysisUs=\(silenceGateMicroseconds) " +
+ "peak=\(String(format: "%.6f", silenceAssessment.peakAmplitude)) " +
+ "rms=\(String(format: "%.6f", silenceAssessment.rmsAmplitude)) " +
+ "maxFrameRms=\(String(format: "%.6f", silenceAssessment.maximumFrameRMS))"
+ )
+
+ if silenceAssessment.shouldSkipTranscription {
+ DebugLogger.shared.info(
+ "Final ASR result | provider=\(self.transcriptionProvider.name) | samples=\(pcm.count) | textChars=0 | confidence=nil | reason=short_silence",
+ source: "ASRService"
+ )
+ if shouldResumeMedia {
+ await MediaPlaybackService.shared.resumeIfWePaused(true)
+ DebugLogger.shared.info("🎵 Resumed system media after silent audio", source: "ASRService")
+ }
+ self.benchmarkLog(
+ "stop_end result=empty totalMs=\(self.elapsedMilliseconds(since: stopStartedAt)) reason=short_silence"
+ )
+ return ""
+ }
+ } else if hasRecognizedStreamingPreview {
+ self.benchmarkLog("silence_gate eligible=false skip=false reason=streaming_preview")
+ }
+
// Pad sub-1s buffers with trailing silence so short utterances (e.g.
// "yes", "stop") still transcribe. whisper.cpp asserts on buffers
// shorter than 1s; every other provider handles silence padding
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index d331201a..f131ac48 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -71,6 +71,19 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
func configure(asrService: ASRService) {
self.asrService = asrService
+ if SettingsStore.shared.overlayPosition == .bottom {
+ DispatchQueue.main.async {
+ guard SettingsStore.shared.overlayPosition == .bottom else { return }
+ BottomOverlayWindowController.shared.prepare()
+ }
+ }
+ NotificationCenter.default.publisher(for: NSNotification.Name("OverlayPositionChanged"))
+ .receive(on: DispatchQueue.main)
+ .sink { _ in
+ guard SettingsStore.shared.overlayPosition == .bottom else { return }
+ BottomOverlayWindowController.shared.prepare()
+ }
+ .store(in: &self.cancellables)
// Subscribe to recording state changes
asrService.$isRunning
@@ -377,9 +390,9 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
NotchOverlayManager.shared.setProcessing(false)
self.overlayBench("finish_hide_request")
- await NotchOverlayManager.shared.hideAndWait()
+ let hideOutcome = await NotchOverlayManager.shared.hideAndWait()
self.overlayBench(
- "finish_hide_complete elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))"
+ "finish_hide_complete outcome=\(hideOutcome) elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))"
)
}
diff --git a/Sources/Fluid/Services/NotchOverlayManager.swift b/Sources/Fluid/Services/NotchOverlayManager.swift
index 0ffa9365..799570a9 100644
--- a/Sources/Fluid/Services/NotchOverlayManager.swift
+++ b/Sources/Fluid/Services/NotchOverlayManager.swift
@@ -24,6 +24,13 @@ enum OverlayMode: String {
final class NotchOverlayManager {
static let shared = NotchOverlayManager()
+ private typealias RecordingNotch = DynamicNotch<
+ NotchExpandedView,
+ NotchCompactLeadingView,
+ NotchCompactTrailingView,
+ NotchCompactBottomView
+ >
+
struct NotchPresentationPolicy: Equatable {
let usesCompactPresentation: Bool
let showsPromptSelector: Bool
@@ -34,7 +41,7 @@ final class NotchOverlayManager {
let allowsExpandedCommandOutput: Bool
}
- private var notch: DynamicNotch<NotchExpandedView, NotchCompactLeadingView, NotchCompactTrailingView, NotchCompactBottomView>?
+ private var notch: RecordingNotch?
private var commandOutputNotch: DynamicNotch<
NotchCommandOutputExpandedView,
NotchCompactLeadingView,
@@ -82,10 +89,10 @@ final class NotchOverlayManager {
private var generation: UInt64 = 0
private var commandOutputGeneration: UInt64 = 0
private var isHideInProgress = false
- private var hideWaiters: [CheckedContinuation<Void, Never>] = []
-
- /// Track pending retry task for cancellation
- private var pendingRetryTask: Task<Void, Never>?
+ private var activeHideGeneration: UInt64?
+ private var hideWaiters: [CheckedContinuation<RecordingOverlayHideOutcome, Never>] = []
+ private var notchAnimationTask: Task<Void, Never>?
+ private var notchPresentationTask: Task<Void, Never>?
// Cancel shortcut monitors for dismissing notch / overlay
private var globalEscapeMonitor: Any?
@@ -145,6 +152,7 @@ final class NotchOverlayManager {
func show(audioLevelPublisher: AnyPublisher<CGFloat, Never>, mode: OverlayMode) {
self.refreshNotchPresentationPolicy()
Self.overlayBench("show_called mode=\(mode.rawValue) state=\(self.state) commandExpanded=\(self.isCommandOutputExpanded)")
+ self.cancelInFlightHideForNewPresentation()
// Don't show regular notch if expanded command output is visible
if self.isCommandOutputExpanded {
@@ -154,35 +162,13 @@ final class NotchOverlayManager {
return
}
- // Cancel any pending retry operations
- self.pendingRetryTask?.cancel()
- self.pendingRetryTask = nil
-
- // If already visible or in transition, wait for cleanup to complete
+ // A rapid restart should never wait for the previous notch animation.
+ // Remove the old panel from the screen synchronously, then let its
+ // internal cleanup finish without blocking the new presentation.
if self.notch != nil || self.state != .idle {
- Self.overlayBench("show_retry_after_cleanup state=\(self.state) notchExists=\(self.notch != nil)")
-
- // Increment generation to invalidate stale operations
+ Self.overlayBench("show_replace_existing state=\(self.state) notchExists=\(self.notch != nil)")
self.generation &+= 1
- let targetGeneration = self.generation
-
- // Start async cleanup and retry
- self.pendingRetryTask = Task { [weak self] in
- guard let self = self else { return }
-
- // Perform cleanup synchronously first
- await self.performCleanup()
-
- // Small delay to ensure cleanup completes
- try? await Task.sleep(nanoseconds: 50_000_000) // 50ms
-
- // Check if we're still the active operation
- guard !Task.isCancelled, self.generation == targetGeneration else { return }
-
- // Retry show
- self.showInternal(audioLevelPublisher: audioLevelPublisher, mode: mode)
- }
- return
+ self.retireCurrentNotchImmediately(reason: "rapid_restart")
}
self.showInternal(audioLevelPublisher: audioLevelPublisher, mode: mode)
@@ -217,11 +203,6 @@ final class NotchOverlayManager {
Self.overlayBench("bottom_route_start mode=\(mode.rawValue)")
self.generation &+= 1
- // Hide any existing notch first
- if self.notch != nil {
- Task { await self.performCleanup() }
- }
-
self.lastAudioPublisher = audioLevelPublisher
self.currentMode = self.normalizedOverlayMode(mode)
@@ -268,6 +249,12 @@ final class NotchOverlayManager {
} compactBottom: {
NotchCompactBottomView()
}
+ newNotch.transitionConfiguration = .init(
+ openingAnimation: .snappy(duration: 0.1),
+ closingAnimation: .linear(duration: 0.02),
+ conversionAnimation: .snappy(duration: 0.1),
+ skipIntermediateHides: true
+ )
self.notch = newNotch
let shouldUseCompactPresentation = self.currentNotchPresentationPolicy.usesCompactPresentation
@@ -275,13 +262,43 @@ final class NotchOverlayManager {
Self.overlayBench("notch_task_scheduled mode=\(self.currentMode.rawValue) presentation=\(presentation) screen=\(targetScreen.localizedName)")
// Resolve presentation from policy so future notch modes don't require call-site changes.
- Task { [weak self] in
- Self.overlayBench("notch_animation_start presentation=\(presentation)")
+ let animationTask = Task { @MainActor in
+ guard !Task.isCancelled else { return }
if shouldUseCompactPresentation {
await newNotch.compact(on: targetScreen)
} else {
await newNotch.expand(on: targetScreen)
}
+ }
+ self.notchAnimationTask = animationTask
+
+ self.notchPresentationTask = Task { [weak self] in
+ Self.overlayBench("notch_animation_start presentation=\(presentation)")
+
+ // DynamicNotchKit applies a fixed 150 ms window fade. The content
+ // animation is already running before the panel is ordered front,
+ // so make that panel opaque on its first run-loop opportunity.
+ let windowDeadline = ProcessInfo.processInfo.systemUptime + 0.05
+ while newNotch.windowController?.window == nil,
+ !Task.isCancelled,
+ !animationTask.isCancelled,
+ ProcessInfo.processInfo.systemUptime < windowDeadline
+ {
+ await Task.yield()
+ }
+ guard !Task.isCancelled, !animationTask.isCancelled else { return }
+ if newNotch.windowController?.window == nil {
+ await animationTask.value
+ }
+ guard let window = newNotch.windowController?.window else {
+ Self.overlayBench("notch_visible_drop reason=no_window")
+ return
+ }
+ window.alphaValue = 1
+ Self.overlayBench("notch_window_visible elapsedMs=\(Self.elapsedMs(since: startedAt))")
+
+ await animationTask.value
+ guard !Task.isCancelled else { return }
Self.overlayBench("notch_animation_complete presentation=\(presentation) elapsedMs=\(Self.elapsedMs(since: startedAt))")
// Only update state if we're still the active generation
guard let self = self, self.generation == currentGeneration else {
@@ -298,36 +315,38 @@ final class NotchOverlayManager {
self.isHideInProgress = true
self.generation &+= 1
let currentGeneration = self.generation
+ self.activeHideGeneration = currentGeneration
Task { [weak self] in
guard let self else { return }
- await self.performHideAndWait(generation: currentGeneration)
- self.completeHideOperation()
+ let outcome = await self.performHideAndWait(generation: currentGeneration)
+ self.completeHideOperation(generation: currentGeneration, outcome: outcome)
}
}
- /// Dismisses the active recording overlay and returns only after its visual
- /// exit is complete. This gives output delivery an explicit ordering point.
- func hideAndWait() async {
+ /// Reports whether the active overlay finished hiding or a newer
+ /// presentation superseded this request.
+ func hideAndWait() async -> RecordingOverlayHideOutcome {
if self.isHideInProgress {
- await withCheckedContinuation { continuation in
+ return await withCheckedContinuation { continuation in
self.hideWaiters.append(continuation)
}
- return
}
self.isHideInProgress = true
self.generation &+= 1
let currentGeneration = self.generation
- await self.performHideAndWait(generation: currentGeneration)
- self.completeHideOperation()
+ self.activeHideGeneration = currentGeneration
+ let outcome = await self.performHideAndWait(generation: currentGeneration)
+ self.completeHideOperation(generation: currentGeneration, outcome: outcome)
+ return outcome
}
- private func performHideAndWait(generation currentGeneration: UInt64) async {
+ private func performHideAndWait(generation currentGeneration: UInt64) async -> RecordingOverlayHideOutcome {
let startedAt = ProcessInfo.processInfo.systemUptime
Self.overlayBench("hide_called state=\(self.state) bottomVisible=\(self.isBottomOverlayVisible)")
guard self.generation == currentGeneration else {
Self.overlayBench("hide_return reason=stale_generation")
- return
+ return .superseded
}
// Stop monitoring active app changes
@@ -335,69 +354,76 @@ final class NotchOverlayManager {
// Hide bottom overlay if visible
if self.isBottomOverlayVisible {
- await BottomOverlayWindowController.shared.hideAndWait()
+ let bottomOutcome = await BottomOverlayWindowController.shared.hideAndWait()
+ guard bottomOutcome == .hidden else {
+ Self.overlayBench("hide_return reason=bottom_superseded")
+ return .superseded
+ }
guard self.generation == currentGeneration else {
Self.overlayBench("hide_return reason=stale_generation")
- return
+ return .superseded
}
self.isBottomOverlayVisible = false
}
- // Cancel any pending retry operations
- self.pendingRetryTask?.cancel()
- self.pendingRetryTask = nil
-
// Safety: reset processing state when hiding
NotchContentState.shared.setProcessing(false)
// Handle visible or showing states (can hide while still expanding)
- guard self.state == .visible || self.state == .showing, let currentNotch = notch else {
+ guard self.state == .visible || self.state == .showing, self.notch != nil else {
// A bottom overlay has already completed its dismissal. Clean up
// any inconsistent notch state without scheduling another task.
Self.overlayBench("hide_return reason=not_visible state=\(self.state) notchExists=\(self.notch != nil)")
- if let existingNotch = self.notch {
- await existingNotch.hide()
- }
- guard self.generation == currentGeneration else { return }
- self.notch = nil
- self.state = .idle
+ self.retireCurrentNotchImmediately(reason: "inconsistent_state")
Self.overlayBench("hide_complete target=none elapsedMs=\(Self.elapsedMs(since: startedAt))")
- return
+ return .hidden
}
self.state = .hiding
- Self.overlayBench("hide_animation_start")
- await currentNotch.hide()
- Self.overlayBench("hide_animation_complete elapsedMs=\(Self.elapsedMs(since: startedAt))")
- // Only clear if we're still the active operation
- guard self.generation == currentGeneration else { return }
- self.notch = nil
- self.state = .idle
- Self.overlayBench("state_idle target=notch")
+ Self.overlayBench("hide_visual_start")
+ self.retireCurrentNotchImmediately(reason: "hide")
+ Self.overlayBench("hide_visual_complete elapsedMs=\(Self.elapsedMs(since: startedAt))")
+ return .hidden
}
- private func completeHideOperation() {
+ private func completeHideOperation(generation: UInt64, outcome: RecordingOverlayHideOutcome) {
+ guard self.activeHideGeneration == generation else { return }
+ self.activeHideGeneration = nil
self.isHideInProgress = false
let waiters = self.hideWaiters
self.hideWaiters.removeAll(keepingCapacity: true)
- waiters.forEach { $0.resume() }
+ waiters.forEach { $0.resume(returning: outcome) }
}
- /// Async cleanup that properly waits for hide to complete
- private func performCleanup() async {
- let startedAt = ProcessInfo.processInfo.systemUptime
- Self.overlayBench("cleanup_start state=\(self.state) notchExists=\(self.notch != nil)")
-
- // Cancel any pending retry operations
- self.pendingRetryTask?.cancel()
- self.pendingRetryTask = nil
+ private func cancelInFlightHideForNewPresentation() {
+ guard self.isHideInProgress else { return }
+ self.activeHideGeneration = nil
+ self.isHideInProgress = false
+ let waiters = self.hideWaiters
+ self.hideWaiters.removeAll(keepingCapacity: true)
+ waiters.forEach { $0.resume(returning: .superseded) }
+ Self.overlayBench("hide_cancelled_for_new_presentation")
+ }
- if let existingNotch = notch {
- await existingNotch.hide()
+ private func retireCurrentNotchImmediately(reason: String) {
+ guard let existingNotch = self.notch else {
+ self.state = .idle
+ return
}
+
+ existingNotch.windowController?.window?.orderOut(nil)
+ self.notchAnimationTask?.cancel()
+ self.notchAnimationTask = nil
+ self.notchPresentationTask?.cancel()
+ self.notchPresentationTask = nil
self.notch = nil
self.state = .idle
- Self.overlayBench("cleanup_complete elapsedMs=\(Self.elapsedMs(since: startedAt))")
+ Self.overlayBench("notch_retired reason=\(reason)")
+
+ Task {
+ await existingNotch.hide()
+ Self.overlayBench("notch_retire_cleanup_complete reason=\(reason)")
+ }
}
func setMode(_ mode: OverlayMode) {
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 115ebc21..224cc131 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -994,6 +994,17 @@ struct SettingsView: View {
)
Divider().opacity(0.2)
+ self.optionToggleRow(
+ title: "Skip Silent Recordings",
+ description: "Avoid transcription when a recording up to four seconds contains only clear silence. Disabled by default to preserve quiet speech.",
+ isOn: Binding(
+ get: { SettingsStore.shared.skipSilentRecordingsEnabled },
+ set: { SettingsStore.shared.skipSilentRecordingsEnabled = $0 }
+ ),
+ allowsDescriptionWrapping: true
+ )
+ Divider().opacity(0.2)
+
self.optionToggleRow(
title: "Pause Media During Transcription",
description: "Automatically pause currently playing audio/video when transcription starts. Resumes only if FluidVoice paused it.",
diff --git a/Sources/Fluid/Views/BottomOverlayView.swift b/Sources/Fluid/Views/BottomOverlayView.swift
index 97fa741d..456c56f1 100644
--- a/Sources/Fluid/Views/BottomOverlayView.swift
+++ b/Sources/Fluid/Views/BottomOverlayView.swift
@@ -7,6 +7,7 @@
import AppKit
import Combine
+import QuartzCore
import SwiftUI
private enum OverlayShortcutResolver {
@@ -22,6 +23,19 @@ private enum OverlayShortcutResolver {
}
}
+enum RecordingOverlayHideOutcome: Equatable {
+ case hidden
+ case superseded
+}
+
+private final class BottomOverlayPanel: NSPanel {
+ var allowsOffscreenParking = false
+
+ override func constrainFrameRect(_ frameRect: NSRect, to screen: NSScreen?) -> NSRect {
+ self.allowsOffscreenParking ? frameRect : super.constrainFrameRect(frameRect, to: screen)
+ }
+}
+
// MARK: - Bottom Overlay Window Controller
@MainActor
@@ -38,10 +52,10 @@ final class BottomOverlayWindowController {
private var releaseTransitionActiveUntil: Date?
private var deferredResizePending = false
private var presentationGeneration: UInt64 = 0
- private let presentationDuration: TimeInterval = 0.05
private let dismissalDuration: TimeInterval = 0.02
private var isHideInProgress = false
- private var hideWaiters: [CheckedContinuation<Void, Never>] = []
+ private var activeHideGeneration: UInt64?
+ private var hideWaiters: [CheckedContinuation<RecordingOverlayHideOutcome, Never>] = []
private init() {
NotificationCenter.default.addObserver(forName: NSNotification.Name("OverlayOffsetChanged"), object: nil, queue: .main) { [weak self] _ in
@@ -54,13 +68,43 @@ final class BottomOverlayWindowController {
self?.scheduleSizeAndPositionUpdate(after: 0)
}
}
+ NotificationCenter.default.addObserver(
+ forName: NSApplication.didChangeScreenParametersNotification,
+ object: nil,
+ queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor [weak self] in
+ guard let self else { return }
+ self.targetScreen = OverlayScreenResolver.screenForCurrentPointer()
+ if NotchContentState.shared.isBottomOverlayPresented {
+ self.positionWindow()
+ } else {
+ self.parkWindowOffscreen()
+ }
+ }
+ }
+ }
+
+ /// Pay the one-time SwiftUI/WindowServer surface cost after launch and keep
+ /// the static panel outside the entire desktop so its surface is not evicted.
+ func prepare() {
+ guard self.window == nil else { return }
+ self.createWindow()
+ self.targetScreen = OverlayScreenResolver.screenForCurrentPointer()
+ guard let window else { return }
+
+ self.parkWindowOffscreen()
+ window.alphaValue = 1
+ window.orderFrontRegardless()
+ CATransaction.flush()
+ Self.overlayBench("bottom_prepared")
}
func show(audioPublisher: AnyPublisher<CGFloat, Never>, mode: OverlayMode) {
let startedAt = ProcessInfo.processInfo.systemUptime
Self.overlayBench("bottom_show_start mode=\(mode.rawValue) windowExists=\(self.window != nil)")
+ self.cancelInFlightHideForNewPresentation()
self.presentationGeneration &+= 1
- let currentGeneration = self.presentationGeneration
self.endReleaseTransition(flushDeferredUpdate: false)
self.pendingResizeWorkItem?.cancel()
@@ -70,7 +114,15 @@ final class BottomOverlayWindowController {
BottomOverlayActionsMenuController.shared.hide()
self.ensureMouseDownMonitors()
- // Update mode in content state
+ // Create window if needed
+ if self.window == nil {
+ self.createWindow()
+ }
+
+ // Prepare the complete first frame while the cached panel is still
+ // offscreen. Revealing the neutral shell first causes a visible flash
+ // that reads as the overlay appearing twice.
+ NotchContentState.shared.setBottomOverlayPresented(true)
NotchContentState.shared.mode = mode
switch mode {
case .dictation: NotchContentState.shared.promptPickerMode = .dictate
@@ -82,36 +134,26 @@ final class BottomOverlayWindowController {
NotchContentState.shared.setBottomOverlayDismissOffsetY(8)
NotchContentState.shared.setBottomOverlayDismissing(false)
- // Subscribe to audio levels and route through NotchContentState
+ self.targetScreen = OverlayScreenResolver.screenForCurrentPointer()
+ self.positionWindow()
+
+ // Submit one complete frame to WindowServer.
+ self.window?.setAccessibilityChildren(nil)
+ self.window?.setAccessibilityElement(true)
+ self.window?.alphaValue = 1
+ self.window?.orderFrontRegardless()
+ self.window?.contentView?.displayIfNeeded()
+ self.window?.displayIfNeeded()
+ CATransaction.flush()
+ Self.overlayBench("bottom_order_front elapsedMs=\(Self.elapsedMs(since: startedAt))")
+ Self.overlayBench("bottom_visible elapsedMs=\(Self.elapsedMs(since: startedAt))")
+
self.audioSubscription?.cancel()
self.audioSubscription = audioPublisher
.receive(on: DispatchQueue.main)
.sink { level in
NotchContentState.shared.bottomOverlayAudioLevel = level
}
-
- // Create window if needed
- if self.window == nil {
- self.createWindow()
- }
-
- self.targetScreen = OverlayScreenResolver.screenForCurrentPointer()
- self.positionWindow()
-
- // Order the panel immediately, then use a very short fade so the first
- // response is instant without the overlay visually popping into place.
- self.window?.alphaValue = 0
- self.window?.orderFrontRegardless()
- Self.overlayBench("bottom_order_front elapsedMs=\(Self.elapsedMs(since: startedAt))")
- NSAnimationContext.runAnimationGroup { context in
- context.duration = self.presentationDuration
- context.allowsImplicitAnimation = true
- self.window?.animator().alphaValue = 1
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + self.presentationDuration) { [weak self] in
- guard let self, self.presentationGeneration == currentGeneration else { return }
- Self.overlayBench("bottom_fade_complete elapsedMs=\(Self.elapsedMs(since: startedAt))")
- }
}
func hide() {
@@ -119,91 +161,97 @@ final class BottomOverlayWindowController {
self.isHideInProgress = true
self.presentationGeneration &+= 1
let currentGeneration = self.presentationGeneration
+ self.activeHideGeneration = currentGeneration
Task { [weak self] in
guard let self else { return }
- await self.performHideAndWait(generation: currentGeneration)
- self.completeHideOperation()
+ let outcome = await self.performHideAndWait(generation: currentGeneration)
+ self.completeHideOperation(generation: currentGeneration, outcome: outcome)
}
}
- /// Performs the brief exit animation and returns after the panel is fully
- /// ordered out, allowing callers to deliver text only after it disappears.
- func hideAndWait() async {
+ /// Returns whether the panel finished hiding or a newer presentation
+ /// superseded this request.
+ func hideAndWait() async -> RecordingOverlayHideOutcome {
if self.isHideInProgress {
- await withCheckedContinuation { continuation in
+ return await withCheckedContinuation { continuation in
self.hideWaiters.append(continuation)
}
- return
}
self.isHideInProgress = true
self.presentationGeneration &+= 1
let currentGeneration = self.presentationGeneration
- await self.performHideAndWait(generation: currentGeneration)
- self.completeHideOperation()
+ self.activeHideGeneration = currentGeneration
+ let outcome = await self.performHideAndWait(generation: currentGeneration)
+ self.completeHideOperation(generation: currentGeneration, outcome: outcome)
+ return outcome
+ }
+
+ private func completeHideOperation(generation: UInt64, outcome: RecordingOverlayHideOutcome) {
+ guard self.activeHideGeneration == generation else { return }
+ self.activeHideGeneration = nil
+ self.isHideInProgress = false
+ let waiters = self.hideWaiters
+ self.hideWaiters.removeAll(keepingCapacity: true)
+ waiters.forEach { $0.resume(returning: outcome) }
}
- private func completeHideOperation() {
+ private func cancelInFlightHideForNewPresentation() {
+ guard self.isHideInProgress else { return }
+ self.activeHideGeneration = nil
self.isHideInProgress = false
let waiters = self.hideWaiters
self.hideWaiters.removeAll(keepingCapacity: true)
- waiters.forEach { $0.resume() }
+ waiters.forEach { $0.resume(returning: .superseded) }
+ Self.overlayBench("bottom_hide_cancelled_for_new_presentation")
}
- private func performHideAndWait(generation currentGeneration: UInt64) async {
+ private func performHideAndWait(generation currentGeneration: UInt64) async -> RecordingOverlayHideOutcome {
let startedAt = ProcessInfo.processInfo.systemUptime
Self.overlayBench("bottom_hide_start windowExists=\(self.window != nil)")
guard self.presentationGeneration == currentGeneration else {
Self.overlayBench("bottom_hide_return reason=stale_generation")
- return
+ return .superseded
}
- guard let window = self.window, window.isVisible else {
+ guard let window = self.window, NotchContentState.shared.isBottomOverlayPresented else {
self.clearPresentationResources()
self.endReleaseTransition(flushDeferredUpdate: false)
NotchContentState.shared.setBottomOverlayDismissing(false)
NotchContentState.shared.targetAppIcon = nil
Self.overlayBench("bottom_hide_return reason=no_window")
- return
+ return .hidden
}
NotchContentState.shared.setBottomOverlayReleaseTransitioning(true)
NotchContentState.shared.setBottomOverlayDismissOffsetY(8)
NotchContentState.shared.setBottomOverlayDismissing(true)
- // Start the visual response first. Resource cleanup then happens inside
- // this same short budget instead of delaying the beginning of the fade.
- let animationStartedAt = ProcessInfo.processInfo.systemUptime
+ // SwiftUI owns the dismissal animation. Keeping AppKit alpha at 1
+ // prevents an old implicit window animation from hiding a rapid restart.
Self.overlayBench("bottom_hide_animation_start")
- await NSAnimationContext.runAnimationGroup { context in
- context.duration = self.dismissalDuration
- context.allowsImplicitAnimation = true
- window.animator().alphaValue = 0
- }
await Task.yield()
guard self.presentationGeneration == currentGeneration else {
Self.overlayBench("bottom_hide_return reason=stale_generation")
- return
+ return .superseded
}
self.clearPresentationResources()
- let elapsed = ProcessInfo.processInfo.systemUptime - animationStartedAt
- let remainingDuration = max(0, self.dismissalDuration - elapsed)
- if remainingDuration > 0 {
- try? await Task.sleep(nanoseconds: UInt64(remainingDuration * 1_000_000_000))
- }
+ try? await Task.sleep(nanoseconds: UInt64(self.dismissalDuration * 1_000_000_000))
guard self.presentationGeneration == currentGeneration else {
Self.overlayBench("bottom_hide_return reason=stale_generation")
- return
+ return .superseded
}
- window.orderOut(nil)
+ self.parkWindowOffscreen()
window.alphaValue = 1
+ NotchContentState.shared.setBottomOverlayPresented(false)
self.endReleaseTransition(flushDeferredUpdate: false)
NotchContentState.shared.setBottomOverlayDismissing(false)
NotchContentState.shared.targetAppIcon = nil
Self.overlayBench("bottom_hide_complete elapsedMs=\(Self.elapsedMs(since: startedAt))")
+ return .hidden
}
private func clearPresentationResources() {
@@ -323,7 +371,7 @@ final class BottomOverlayWindowController {
}
private func createWindow() {
- let panel = NSPanel(
+ let panel = BottomOverlayPanel(
contentRect: .zero,
styleMask: [.borderless, .nonactivatingPanel],
backing: .buffered,
@@ -353,6 +401,8 @@ final class BottomOverlayWindowController {
panel.setContentSize(fittingSize)
panel.contentView = hostingView
+ hostingView.layoutSubtreeIfNeeded()
+ hostingView.display()
self.window = panel
}
@@ -416,6 +466,11 @@ final class BottomOverlayWindowController {
private func positionWindow() {
// Safe check for window and screen availability
guard let window = window else { return }
+ guard NotchContentState.shared.isBottomOverlayPresented else {
+ self.parkWindowOffscreen()
+ return
+ }
+ (window as? BottomOverlayPanel)?.allowsOffscreenParking = false
let screen = self.targetScreen ?? window.screen ?? OverlayScreenResolver.screenForCurrentPointer()
guard let screen = screen else { return }
@@ -444,6 +499,21 @@ final class BottomOverlayWindowController {
// Apply position directly to avoid implicit frame animations during hover-driven resizes.
window.setFrameOrigin(NSPoint(x: x, y: y))
}
+
+ private func parkWindowOffscreen() {
+ guard let window else { return }
+ window.setAccessibilityChildren([])
+ window.setAccessibilityElement(false)
+ (window as? BottomOverlayPanel)?.allowsOffscreenParking = true
+ let desktopFrame = NSScreen.screens.reduce(NSRect.null) { partial, screen in
+ partial.union(screen.frame)
+ }
+ let edge = desktopFrame.isNull ? NSPoint(x: 100_000, y: 100_000) : NSPoint(
+ x: desktopFrame.maxX + window.frame.width + 1024,
+ y: desktopFrame.maxY + window.frame.height + 1024
+ )
+ window.setFrameOrigin(edge)
+ }
}
@MainActor
@@ -1904,6 +1974,7 @@ struct BottomOverlayView: View {
@State private var processingStatusVisible = false
@State private var processingStatusCycleID = 0
@State private var lastResolvedAppIcon: NSImage?
+ @State private var borderAnimationStartedAt: Date?
struct LayoutConstants {
let hPadding: CGFloat
@@ -2981,7 +3052,7 @@ struct BottomOverlayView: View {
if self.isPillSize {
// Glossy border: a bright highlight that slowly rotates around the edge.
// Paused under reduce-motion to avoid continuous redraws on low-resource Macs.
- if self.reduceMotion {
+ if self.reduceMotion || !self.contentState.isBottomOverlayPresented {
RoundedRectangle(cornerRadius: self.layout.cornerRadius)
.strokeBorder(
AngularGradient(
@@ -3000,7 +3071,10 @@ struct BottomOverlayView: View {
)
} else {
TimelineView(.animation(minimumInterval: 1.0 / 30.0)) { timeline in
- let seconds = timeline.date.timeIntervalSinceReferenceDate
+ let seconds = max(
+ 0,
+ timeline.date.timeIntervalSince(self.borderAnimationStartedAt ?? timeline.date)
+ )
let angle = (seconds.truncatingRemainder(dividingBy: 6.0) / 6.0) * 360.0
RoundedRectangle(cornerRadius: self.layout.cornerRadius)
.strokeBorder(
@@ -3061,6 +3135,9 @@ struct BottomOverlayView: View {
self.frozenDynamicPreviewHeight = nil
BottomOverlayWindowController.shared.refreshSizeForContent()
}
+ .onChange(of: self.contentState.isBottomOverlayPresented) { _, presented in
+ self.borderAnimationStartedAt = presented ? Date() : nil
+ }
.onChange(of: self.settings.enableStreamingPreview) { _, _ in
self.dynamicPreviewResizeBucket = self.previewResizeBucket(for: self.currentPreviewSizingText)
self.frozenDynamicPreviewHeight = nil
diff --git a/Sources/Fluid/Views/NotchContentViews.swift b/Sources/Fluid/Views/NotchContentViews.swift
index 6b32e15f..8777d985 100644
--- a/Sources/Fluid/Views/NotchContentViews.swift
+++ b/Sources/Fluid/Views/NotchContentViews.swift
@@ -145,6 +145,7 @@ class NotchContentState: ObservableObject {
// MARK: - Bottom Overlay Audio Level
@Published var bottomOverlayAudioLevel: CGFloat = 0 // Audio level for bottom overlay waveform
+ @Published var isBottomOverlayPresented: Bool = false
@Published var isBottomOverlayReleaseTransitioning: Bool = false
@Published var isBottomOverlayDismissing: Bool = false
@Published var bottomOverlayDismissOffsetY: CGFloat = 8
@@ -185,6 +186,11 @@ class NotchContentState: ObservableObject {
self.isBottomOverlayReleaseTransitioning = transitioning
}
+ func setBottomOverlayPresented(_ presented: Bool) {
+ guard self.isBottomOverlayPresented != presented else { return }
+ self.isBottomOverlayPresented = presented
+ }
+
func setBottomOverlayDismissing(_ dismissing: Bool) {
guard self.isBottomOverlayDismissing != dismissing else { return }
self.isBottomOverlayDismissing = dismissing
@@ -1134,6 +1140,7 @@ struct NotchCompactLeadingView: View {
.frame(width: 8, height: 8)
}
}
+ .frame(width: 34, height: 16)
}
}
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index 65bd2b5e..2fa39b99 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -1,4 +1,5 @@
import AppKit
+import Combine
import CoreAudio
@testable import FluidVoice_Debug
import Foundation
@@ -13,6 +14,42 @@ final class HotkeyShortcutTests: XCTestCase {
private let preferredInputDeviceUIDKey = "PreferredInputDeviceUID"
private let systemInputDeviceUIDBeforeManualKey = "SystemInputDeviceUIDBeforeManual"
+ @MainActor
+ func testBottomOverlayRapidStopStartStopDoesNotDropFinalHide() async {
+ let audioPublisher = Just(CGFloat.zero).eraseToAnyPublisher()
+ let controller = BottomOverlayWindowController.shared
+
+ controller.prepare()
+ await Task.yield()
+ controller.show(audioPublisher: audioPublisher, mode: .dictation)
+ controller.hide()
+ controller.show(audioPublisher: audioPublisher, mode: .dictation)
+ let outcome = await controller.hideAndWait()
+
+ XCTAssertEqual(outcome, .hidden)
+ XCTAssertFalse(NotchContentState.shared.isBottomOverlayPresented)
+ }
+
+ @MainActor
+ func testBottomOverlayReportsWhenRapidRestartSupersedesHide() async {
+ let audioPublisher = Just(CGFloat.zero).eraseToAnyPublisher()
+ let controller = BottomOverlayWindowController.shared
+
+ controller.prepare()
+ await Task.yield()
+ controller.show(audioPublisher: audioPublisher, mode: .dictation)
+ let hideTask = Task { @MainActor in
+ await controller.hideAndWait()
+ }
+ await Task.yield()
+ controller.show(audioPublisher: audioPublisher, mode: .dictation)
+
+ let hideOutcome = await hideTask.value
+ XCTAssertEqual(hideOutcome, .superseded)
+ XCTAssertTrue(NotchContentState.shared.isBottomOverlayPresented)
+ _ = await controller.hideAndWait()
+ }
+
func testCoreAudioFrameCountUsesActualBufferChannelLayout() {
XCTAssertEqual(fv_core_audio_buffer_frame_count(512 * 4, 4, 1), 512)
XCTAssertEqual(fv_core_audio_buffer_frame_count(512 * 8, 4, 2), 512)
@@ -56,6 +93,80 @@ final class HotkeyShortcutTests: XCTestCase {
XCTAssertTrue(ASRService.directCaptureShouldDisable(afterFailureCount: 4))
}
+ func testShortAudioSilenceGateRejectsOnlyClearShortSilence() {
+ let silence = [Float](repeating: 0.0005, count: 16_000)
+ let silenceAssessment = ASRService.assessShortAudioSilence(silence)
+ XCTAssertTrue(silenceAssessment.isEligible)
+ XCTAssertTrue(silenceAssessment.shouldSkipTranscription)
+
+ var quietSpeech = [Float](repeating: 0.0005, count: 16_000)
+ for index in 4000..<4320 {
+ quietSpeech[index] = index.isMultiple(of: 2) ? 0.012 : -0.012
+ }
+ let quietSpeechAssessment = ASRService.assessShortAudioSilence(quietSpeech)
+ XCTAssertTrue(quietSpeechAssessment.isEligible)
+ XCTAssertFalse(quietSpeechAssessment.shouldSkipTranscription)
+
+ let longSilence = [Float](repeating: 0, count: 64_001)
+ let longAssessment = ASRService.assessShortAudioSilence(longSilence)
+ XCTAssertFalse(longAssessment.isEligible)
+ XCTAssertFalse(longAssessment.shouldSkipTranscription)
+ }
+
+ func testShortAudioSilenceGateFailsOpenForInvalidSamples() {
+ var samples = [Float](repeating: 0, count: 8000)
+ samples[100] = .nan
+
+ let assessment = ASRService.assessShortAudioSilence(samples)
+
+ XCTAssertTrue(assessment.isEligible)
+ XCTAssertFalse(assessment.shouldSkipTranscription)
+ }
+
+ func testShortAudioSilenceGateRunsOnlyWhenEnabledForUnrecognizedDictation() {
+ XCTAssertFalse(ASRService.shouldAssessShortAudioSilence(
+ isEnabled: false,
+ useDictionaryTrainingPath: false,
+ hasRecognizedStreamingPreview: false
+ ))
+ XCTAssertFalse(ASRService.shouldAssessShortAudioSilence(
+ isEnabled: true,
+ useDictionaryTrainingPath: true,
+ hasRecognizedStreamingPreview: false
+ ))
+ XCTAssertFalse(ASRService.shouldAssessShortAudioSilence(
+ isEnabled: true,
+ useDictionaryTrainingPath: false,
+ hasRecognizedStreamingPreview: true
+ ))
+ XCTAssertTrue(ASRService.shouldAssessShortAudioSilence(
+ isEnabled: true,
+ useDictionaryTrainingPath: false,
+ hasRecognizedStreamingPreview: false
+ ))
+ }
+
+ @MainActor
+ func testSilentRecordingSettingRoundTripsAndOlderBackupsStillDecode() async throws {
+ let settingsStore = SettingsStore.shared
+ let originalValue = settingsStore.skipSilentRecordingsEnabled
+ defer { settingsStore.skipSilentRecordingsEnabled = originalValue }
+
+ settingsStore.skipSilentRecordingsEnabled = true
+ let document = await BackupService.shared.makeBackupDocument()
+ XCTAssertEqual(document.settings.skipSilentRecordingsEnabled, true)
+
+ let encoded = try BackupService.shared.encode(document)
+ var root = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any])
+ var settings = try XCTUnwrap(root["settings"] as? [String: Any])
+ settings.removeValue(forKey: "skipSilentRecordingsEnabled")
+ root["settings"] = settings
+
+ let legacyData = try JSONSerialization.data(withJSONObject: root)
+ let decoded = try BackupService.shared.decode(legacyData)
+ XCTAssertNil(decoded.settings.skipSilentRecordingsEnabled)
+ }
+
func testLegacyKeyboardShortcutPayloadDefaultsToKeyboardKind() throws {
let json = #"{"keyCode":61,"modifierFlagsRawValue":0}"#
let data = try XCTUnwrap(json.data(using: .utf8))