-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathAppState.swift
More file actions
1703 lines (1493 loc) · 70.9 KB
/
Copy pathAppState.swift
File metadata and controls
1703 lines (1493 loc) · 70.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// AppState.swift
// VocaMac
//
// Central observable state for the entire application.
// All UI and services react to changes in AppState.
import Foundation
import SwiftUI
import Combine
import ServiceManagement
// MARK: - Enums
/// Application status representing the current state of the transcription pipeline
enum AppStatus: String {
case idle // Ready for input, not recording
case recording // Actively capturing microphone audio
case processing // Transcribing audio via WhisperKit
case error // Something went wrong
}
/// How recording is activated by the user
enum ActivationMode: String, CaseIterable, Codable, Identifiable {
case pushToTalk // Hold key to record, release to stop
case doubleTapToggle // Double-tap key to start/stop
var id: String { rawValue }
var displayName: String {
switch self {
case .pushToTalk: return "Push to Talk (Hold)"
case .doubleTapToggle: return "Double-Tap Toggle"
}
}
var description: String {
switch self {
case .pushToTalk:
return "Hold the hotkey to record. Release to stop and transcribe."
case .doubleTapToggle:
return "Double-tap the hotkey to start recording. Double-tap again to stop."
}
}
}
/// Permission status for system permissions
enum PermissionStatus: String {
case notDetermined
case granted
case denied
}
// MARK: - AppState
@MainActor
final class AppState: ObservableObject {
// MARK: - Published State
/// Current application status
@Published var appStatus: AppStatus = .idle
/// Whether the app is actively recording audio
@Published var isRecording: Bool = false
/// Current audio input level (0.0 - 1.0) for visual feedback
@Published var audioLevel: Float = 0.0
/// The most recent transcription result
@Published var lastTranscription: VocaTranscription?
/// Last Settings → Test Dictation result (shown in the sidebar footer; not injected).
@Published var settingsTestResultText: String?
/// Error message to display, if any
@Published var errorMessage: String?
/// Currently loaded/active whisper model info
@Published var currentModel: WhisperModelInfo?
/// All available models and their statuses
@Published var availableModels: [WhisperModelInfo] = []
// Permissions are managed by PermissionManager.
// These computed properties maintain backward compatibility for views.
var micPermission: PermissionStatus { permissionManager.micPermission }
var accessibilityPermission: PermissionStatus { permissionManager.accessibilityPermission }
var inputMonitoringPermission: PermissionStatus { permissionManager.inputMonitoringPermission }
/// Detected system capabilities
@Published var systemCapabilities: SystemCapabilities?
/// WhisperKit's recommended model for this device
@Published var deviceRecommendedModel: String?
// MARK: - User Settings (persisted via UserDefaults)
@AppStorage("vocamac.hasCompletedOnboarding") var hasCompletedOnboarding: Bool = false
@AppStorage("vocamac.activationMode") var activationMode: ActivationMode = .pushToTalk
@AppStorage("vocamac.hotKeyCode") var hotKeyCode: Int = 61 // Right Option
@AppStorage("vocamac.hotKeyModifiers") var hotKeyModifiers: HotKeyModifiers = []
@AppStorage("vocamac.doubleTapThreshold") var doubleTapThreshold: Double = 0.4
@AppStorage("vocamac.silenceThreshold") var silenceThreshold: Double = 0.01
@AppStorage("vocamac.silenceDuration") var silenceDuration: Double = SilenceDetectionSettings.defaultDuration
@AppStorage("vocamac.maxRecordingDuration") var maxRecordingDuration: Int = 60
@AppStorage("vocamac.selectedAudioDeviceID") var selectedAudioDeviceID: String = ""
@AppStorage("vocamac.selectedAudioDeviceName") var selectedAudioDeviceName: String = ""
@AppStorage("vocamac.selectedAudioChannel") var selectedAudioChannel: Int = 0
@AppStorage("vocamac.selectedAudioChannelDeviceID") var selectedAudioChannelDeviceID: String = ""
@AppStorage("vocamac.selectedAudioChannelCount") var selectedAudioChannelCount: Int = 0
@AppStorage(PreferenceKey.selectedModelSize) var selectedModelSize: String = ModelSize.tiny.rawValue
@AppStorage(PreferenceKey.selectedLanguage) var selectedLanguage: String = "auto"
@AppStorage("vocamac.launchAtLogin") var launchAtLogin: Bool = false
@AppStorage("vocamac.preserveClipboard") var preserveClipboard: Bool = true
@AppStorage("vocamac.soundEffectsEnabled") var soundEffectsEnabled: Bool = true
@AppStorage(PreferenceKey.dictationTone) var dictationTone: DictationTone = .voca
@AppStorage("vocamac.overlayStyle") var overlayStyle: OverlayStyle = .minimal
@AppStorage("vocamac.overlayPosition") var overlayPosition: OverlayPosition = .bottom
/// Legacy preference retained so existing installs that disabled the old
/// cursor indicator continue to keep the overlay hidden after upgrading.
@AppStorage("vocamac.showCursorIndicator") var showCursorIndicator: Bool = true
@AppStorage("vocamac.translationEnabled") var translationEnabled: Bool = false
@AppStorage("vocamac.customVocabulary") var customVocabulary: String = ""
@AppStorage("vocamac.logLevel") var logLevel: String = "info"
@AppStorage(PreferenceKey.appendTrailingSpace) var appendTrailingSpace: Bool = true
@AppStorage(PreferenceKey.autoCapitalize) var autoCapitalize: Bool = true
@AppStorage(PreferenceKey.autoPauseEnabled) var autoPauseEnabled: Bool = false
@AppStorage(PreferenceKey.autoPausePollInterval) var autoPausePollIntervalSeconds: Double = 5
@AppStorage(PreferenceKey.modelKeepAliveEnabled) var modelKeepAliveEnabled: Bool = false
@AppStorage(PreferenceKey.modelKeepAliveIdleTimeout) var modelKeepAliveIdleTimeoutSeconds: Double = 300
/// JSON-encoded `[AutoPauseAppEntry]` list (complex value not stored via `@AppStorage`).
var autoPauseAppsJSON: String {
get { UserDefaults.standard.string(forKey: PreferenceKey.autoPauseApps) ?? "[]" }
set { UserDefaults.standard.set(newValue, forKey: PreferenceKey.autoPauseApps) }
}
/// Decoded auto-pause app list. Empty when unset or invalid JSON.
var autoPauseApps: [AutoPauseAppEntry] {
get {
guard let data = autoPauseAppsJSON.data(using: .utf8),
let decoded = try? JSONDecoder().decode([AutoPauseAppEntry].self, from: data) else {
return []
}
return decoded
}
set {
if let data = try? JSONEncoder().encode(newValue),
let json = String(data: data, encoding: .utf8) {
autoPauseAppsJSON = json
} else {
autoPauseAppsJSON = "[]"
}
objectWillChange.send()
}
}
/// True while a configured auto-pause app is running and dictation is blocked.
@Published var isAutoPaused: Bool = false
/// Set when the last recording could not use the pinned microphone.
/// Cleared when a recording starts on the requested device.
@Published var inputDeviceFallbackNotice: String?
/// True while the audio engine is negotiating its input route. Bluetooth
/// headsets can take seconds to switch to their microphone, and a stop
/// arriving in that window has to be deferred rather than blocked on.
private var isStartingAudio = false
/// How to finish a start that the user interrupted while it was still
/// negotiating the route.
private var pendingStopDuringStart: PendingStopKind?
private enum PendingStopKind {
/// Push-to-talk released: keep whatever the engine managed to capture.
case transcribe
/// Overlay cancel: throw the recording away.
case discard
}
/// Last reason the speech model was unloaded (nil while a model is loaded).
@Published var lastModelUnloadReason: ModelUnloadReason?
/// Display name of the app that triggered the current auto-pause, if any.
@Published var autoPauseTriggerDisplayName: String?
/// Approximate process RSS (MB) sampled just before the last unload.
@Published var processMemoryBeforeUnloadMB: Double?
/// Approximate process RSS (MB) sampled right after the last unload.
@Published var processMemoryAfterUnloadMB: Double?
private var hotKeySafetyTimeout: Double {
Double(maxRecordingDuration) + 5.0
}
/// Persist the microphone VocaMac should use for future recordings.
/// Passing nil restores the system-default input behavior.
func selectAudioDevice(_ device: AudioDevice?) {
let newDeviceID = device?.id ?? ""
if selectedAudioDeviceID != newDeviceID {
selectedAudioChannel = 0
selectedAudioChannelDeviceID = newDeviceID
selectedAudioChannelCount = device?.channelCount ?? 0
}
selectedAudioDeviceID = newDeviceID
selectedAudioDeviceName = device?.name ?? ""
if let device {
syncSelectedAudioChannel(with: device)
}
}
/// Persist the physical interface input selected for a specific device layout.
func selectAudioChannel(_ channel: Int, for device: AudioDevice) {
selectedAudioChannelDeviceID = device.id
selectedAudioChannelCount = device.channelCount
guard device.channelCount > 0, channel >= 0, channel < device.channelCount else {
selectedAudioChannel = 0
return
}
selectedAudioChannel = channel
}
/// Reset a saved channel when the active device or its channel layout changes.
func syncSelectedAudioChannel(with device: AudioDevice) {
let mappingIsCurrent = selectedAudioChannelDeviceID == device.id
&& selectedAudioChannelCount == device.channelCount
let channelIsValid = selectedAudioChannel >= 0
&& selectedAudioChannel < device.channelCount
if !mappingIsCurrent || !channelIsValid {
selectedAudioChannel = 0
}
selectedAudioChannelDeviceID = device.id
selectedAudioChannelCount = device.channelCount
}
/// Custom text snippets for expansion
@Published var snippets: [Snippet] = []
// MARK: - Services
let audioEngine: AudioRecording
let whisperService: SpeechTranscribing
let textInjector: TextInjecting
let hotKeyManager: HotKeyMonitoring
let modelManager: ModelManaging
let soundManager: SoundPlaying
let cursorOverlay: CursorOverlayManaging
let statsManager: StatsManaging
let snippetExpander: SnippetExpanding
let updateChecker = UpdateChecker()
let permissionManager: any PermissionManaging
/// Polls configured apps and pauses dictation while they run.
let autoPauseMonitor = AutoPauseMonitor()
/// Unloads the model after an idle timeout when enabled.
let modelKeepAlive = ModelKeepAlive()
/// Sleep/wake recovery hooks.
let sleepWakeMonitor = SleepWakeMonitor()
// MARK: - Private
private var cancellables = Set<AnyCancellable>()
private var hasStarted = false
/// Why the model was last unloaded (for logs / UI).
enum ModelUnloadReason: String {
case autoPause = "auto_pause"
case idleKeepAlive = "idle_keepalive"
case manual = "manual"
}
/// Bumped when each load operation starts. Failure restores and success UI
/// updates only apply when the generation is still current, so a stale
/// failure cannot undo a newer successful load.
private var loadGeneration: UInt64 = 0
/// Serializes model downloads and loads at the AppState boundary. The
/// engine router also protects its own load/transcribe lifecycle, but UI
/// actions can otherwise start several downloads or model-management
/// operations before they reach those lower-level services.
private let modelOperationSerializer = LoadSerializer()
/// AudioEngine serializes its own lifecycle internally; this wrapper makes
/// the intentional background handoff explicit for Dispatch's @Sendable API.
private struct AudioEngineWorker: @unchecked Sendable {
let audioEngine: AudioRecording
func startRecording(
silenceThreshold: Float,
silenceDuration: Double,
maxDuration: TimeInterval,
preferredInputDeviceID: String?,
preferredInputChannel: Int,
preferredInputChannelDeviceID: String?,
preferredInputChannelCount: Int
) -> Bool {
audioEngine.startRecording(
silenceThreshold: silenceThreshold,
silenceDuration: silenceDuration,
maxDuration: maxDuration,
preferredInputDeviceID: preferredInputDeviceID,
preferredInputChannel: preferredInputChannel,
preferredInputChannelDeviceID: preferredInputChannelDeviceID,
preferredInputChannelCount: preferredInputChannelCount
)
}
func stopRecording() -> [Float] {
audioEngine.stopRecording()
}
}
/// Process-level flag that prevents performStartup from running more than
/// once even when SwiftUI instantiates multiple AppState objects (which it
/// does during MenuBarExtra scene setup). Instance-level `hasStarted` guards
/// re-entry on the same object; this static flag guards across all instances.
///
/// Internal (not private) so test teardown can reset it between test cases.
static var hasStartedGlobally = false
/// Whether to skip system integration calls (SMAppService, etc.) during init.
/// Set to `true` in tests to avoid side effects.
let skipSystemIntegration: Bool
/// Pre-load memory gate. Production defaults to SystemInfo; tests stub this
/// so CI free+inactive pages cannot flake medium/large mock loads.
var modelFitsInMemory: (ModelSize) -> Bool = { SystemInfo.canFitModelInMemory($0) }
// MARK: - Initialization
init(
audioEngine: AudioRecording = AudioEngine(),
whisperService: SpeechTranscribing = TranscriptionRouter(),
textInjector: TextInjecting = TextInjector(),
hotKeyManager: HotKeyMonitoring = HotKeyManager(),
modelManager: ModelManaging = ModelManager(),
soundManager: SoundPlaying = SoundManager(),
cursorOverlay: CursorOverlayManaging,
statsManager: StatsManaging,
snippetExpander: SnippetExpanding = SnippetExpander(),
permissionManager: (any PermissionManaging)? = nil,
skipSystemIntegration: Bool = false
) {
self.audioEngine = audioEngine
self.whisperService = whisperService
self.textInjector = textInjector
self.hotKeyManager = hotKeyManager
self.modelManager = modelManager
self.soundManager = soundManager
self.cursorOverlay = cursorOverlay
self.statsManager = statsManager
self.snippetExpander = snippetExpander
self.permissionManager = permissionManager ?? PermissionManager(audioEngine: audioEngine, hotKeyManager: hotKeyManager)
self.skipSystemIntegration = skipSystemIntegration
VocaLogger.info(.appState, "Initializing... id=\(ObjectIdentifier(self))")
loadSnippets()
if !skipSystemIntegration {
syncLaunchAtLogin()
}
setupServices()
// Forward updateChecker changes so SwiftUI views observing AppState
// re-render when updateState changes (nested ObservableObject fix).
updateChecker.objectWillChange
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in self?.objectWillChange.send() }
.store(in: &cancellables)
// Forward statsManager changes
statsManager.objectWillChangePublisher
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.objectWillChange.send()
}
.store(in: &cancellables)
}
/// Single production AppState instance for the process.
///
/// SwiftUI can recreate the `App` value during scene setup, especially for
/// menu bar apps. Keeping the production instance outside the `App` value's
/// stored-property initialization prevents duplicate service graphs, event
/// taps, audio observers, and stale SwiftUI environment objects.
@MainActor
private static let sharedProductionInstance = AppState(
cursorOverlay: CursorOverlayManager(),
statsManager: StatsManager()
)
/// Convenience factory for creating AppState with all real services.
/// Needed because CursorOverlayManager is @MainActor and can't be a default parameter.
@MainActor
static func production() -> AppState {
VocaLogger.debug(.appState, "Using production AppState id=\(ObjectIdentifier(sharedProductionInstance))")
return sharedProductionInstance
}
/// Called once from the SwiftUI lifecycle to complete initialization.
/// Safe to call multiple times and across multiple instances — only the
/// first call across the entire process takes effect.
func triggerStartupIfNeeded() {
guard !hasStarted, !AppState.hasStartedGlobally else {
VocaLogger.debug(.appState, "triggerStartupIfNeeded called again — skipping (already started)")
return
}
hasStarted = true
AppState.hasStartedGlobally = true
Task {
await performStartup()
}
}
// MARK: - Launch at Login
/// Sync the persisted launchAtLogin preference with SMAppService.
/// Called once on init to reconcile state (e.g. if the user toggled it
/// in System Settings directly, or if the app was re-installed).
private func syncLaunchAtLogin() {
let currentStatus = SMAppService.mainApp.status
let isRegistered = currentStatus == .enabled
if launchAtLogin && !isRegistered {
// User wants launch-at-login but it's not registered — register now
setLaunchAtLogin(true)
} else if !launchAtLogin && isRegistered {
// Persisted preference says disabled but system says enabled — unregister
setLaunchAtLogin(false)
}
}
/// Register or unregister the app as a login item via SMAppService.
/// Updates the persisted `launchAtLogin` preference to match.
func setLaunchAtLogin(_ enabled: Bool) {
do {
if enabled {
try SMAppService.mainApp.register()
VocaLogger.info(.appState, "Registered as login item")
} else {
try SMAppService.mainApp.unregister()
VocaLogger.info(.appState, "Unregistered as login item")
}
launchAtLogin = enabled
} catch {
VocaLogger.error(.appState, "Failed to \(enabled ? "register" : "unregister") login item: \(error.localizedDescription)")
// Revert the preference to match the actual system state
launchAtLogin = SMAppService.mainApp.status == .enabled
}
}
// MARK: - Setup
private func setupServices() {
// Detect system capabilities
systemCapabilities = SystemInfo.detect()
// Get WhisperKit's device recommendation.
// WhisperKit's `.default` may not be in the supported list for some
// devices. If so, fall back to the best supported model instead.
let recommendation = modelManager.deviceRecommendation()
VocaLogger.info(.appState, "WhisperKit recommendation — default: \(recommendation.defaultModel), supported: [\(recommendation.supported.joined(separator: ", "))], disabled: [\(recommendation.disabled.joined(separator: ", "))]")
let defaultIsSupported = recommendation.supported.contains(recommendation.defaultModel)
if !defaultIsSupported, let bestSupported = recommendation.supported.last {
deviceRecommendedModel = bestSupported
} else {
deviceRecommendedModel = recommendation.defaultModel
}
rebuildAvailableModels()
// Validate that the recommended model maps to a supported ModelSize.
// If the recommendation points to an unsupported model, fall back to
// the largest supported model instead.
if let recommended = deviceRecommendedModel {
let recommendedSize = modelManager.modelSize(from: recommended)
let isRecommendedSupported = recommendedSize.map { size in
availableModels.first(where: { $0.size == size })?.isSupported == true
} ?? false
if !isRecommendedSupported {
// Fall back to the largest supported WhisperKit model — the
// recommendation badge reflects WhisperKit's per-device tuning,
// so other engines are not candidates here.
if let bestSupported = availableModels.last(where: { $0.isSupported && $0.size.engine == .whisperKit }) {
deviceRecommendedModel = modelManager.modelIdentifier(for: bestSupported.size)
} else {
// No models are supported — clear the recommendation
deviceRecommendedModel = nil
}
}
}
// Setup audio level reporting
audioEngine.onAudioLevel = { [weak self] level in
Task { @MainActor in
self?.audioLevel = level
self?.cursorOverlay.updateAudioLevel(level)
}
}
// Setup silence detection callback
audioEngine.onSilenceDetected = { [weak self] in
Task { @MainActor in
guard let self = self else { return }
if self.activationMode == .doubleTapToggle && self.isRecording {
VocaLogger.info(.appState, "Silence detected — auto-stopping recording (double-tap mode)")
await self.stopRecordingAndTranscribe()
}
}
}
// Setup max recording duration callback.
// AudioEngine fires this when the recording reaches maxRecordingDuration.
// This is the primary duration limit — the HotKeyManager safety timer
// (maxRecordingDuration + 5s) acts as a backstop in case this callback
// fails or the key-up event is lost entirely.
audioEngine.onMaxDurationReached = { [weak self] in
Task { @MainActor in
guard let self = self, self.isRecording else { return }
VocaLogger.info(.appState, "Max recording duration (\(self.maxRecordingDuration)s) reached — auto-stopping")
await self.stopRecordingAndTranscribe()
}
}
// Setup audio device change callback.
// Fires when the microphone is unplugged/replugged, Bluetooth disconnects,
// or the default audio device changes (e.g., after sleep). AudioEngine has
// already stopped and reset itself — we just need to recover the app state.
audioEngine.onAudioDeviceChanged = { [weak self] in
Task { @MainActor in
guard let self = self else { return }
VocaLogger.warning(.appState, "Audio device changed — recovering from interrupted recording")
self.isRecording = false
self.audioLevel = 0.0
self.cursorOverlay.hide()
self.hotKeyManager.resetKeyState()
self.appStatus = .idle
self.errorMessage = nil
}
}
// The pinned microphone could not be configured and recording fell back
// to another device. Surface it so the user isn't left wondering why the
// transcript came from the built-in mic.
audioEngine.onInputDeviceFallback = { [weak self] notice in
Task { @MainActor in
guard let self else { return }
VocaLogger.warning(.appState, notice)
self.inputDeviceFallbackNotice = notice
}
}
// Setup hotkey callbacks
hotKeyManager.onRecordingStart = { [weak self] in
Task { @MainActor in
await self?.startRecording()
}
}
hotKeyManager.onRecordingStop = { [weak self] in
Task { @MainActor in
await self?.stopRecordingAndTranscribe()
}
}
// Wire permission manager: start hotkey listener when permissions granted
permissionManager.onAllPermissionsGranted = { [weak self] in
guard let self = self else { return }
self.hotKeyManager.startListening(
keyCode: self.hotKeyCode,
mode: self.activationMode,
doubleTapThreshold: self.doubleTapThreshold,
safetyTimeout: self.hotKeySafetyTimeout,
modifiers: self.hotKeyModifiers
)
VocaLogger.info(.appState, "Hotkey listener started after permission grant")
}
// Forward PermissionManager state changes to trigger SwiftUI updates
permissionManager.objectWillChangePublisher
.sink { [weak self] _ in self?.objectWillChange.send() }
.store(in: &cancellables)
// Auto-save snippets when changed. @Published emits on willSet, so
// persist the emitted array — reading self.snippets here would save
// the previous state and leave the latest change unsaved.
$snippets
.dropFirst() // skip the subscription replay of the just-loaded value
.sink { [weak self] snippets in
self?.saveSnippets(snippets)
}
.store(in: &cancellables)
// Check permissions
checkPermissions()
if !skipSystemIntegration {
setupPowerManagement()
}
}
// MARK: - Power Management
/// Wire auto-pause, idle unload, and sleep/wake monitors.
private func setupPowerManagement() {
autoPauseMonitor.getConfig = { [weak self] in
guard let self else {
return (false, [], AutoPauseMonitor.defaultPollIntervalSeconds)
}
return (
self.autoPauseEnabled,
self.autoPauseApps,
self.autoPausePollIntervalSeconds
)
}
autoPauseMonitor.onPause = { [weak self] in
Task { @MainActor in
await self?.handleAutoPauseEntered()
}
}
autoPauseMonitor.onResume = { [weak self] in
Task { @MainActor in
await self?.handleAutoPauseCleared()
}
}
modelKeepAlive.getConfig = { [weak self] in
guard let self else {
return (false, ModelKeepAlive.defaultIdleTimeoutSeconds)
}
return (self.modelKeepAliveEnabled, self.modelKeepAliveIdleTimeoutSeconds)
}
modelKeepAlive.isSafeToUnload = { [weak self] in
guard let self else { return false }
return self.appStatus == .idle
&& !self.isAutoPaused
&& self.whisperService.isModelLoaded
}
modelKeepAlive.onIdleUnload = { [weak self] in
Task { @MainActor in
await self?.unloadActiveModel(reason: .idleKeepAlive)
}
}
sleepWakeMonitor.onWillSleep = { [weak self] in
self?.modelKeepAlive.cancel()
if self?.isRecording == true || self?.appStatus == .recording {
self?.forceRecovery()
}
}
sleepWakeMonitor.onDidWake = { [weak self] in
guard let self else { return }
VocaLogger.info(.appState, "Wake recovery: refreshing hotkey health")
if self.permissionManager.allPermissionsGranted {
self.syncHotKeyConfiguration()
if !self.hotKeyManager.isListening {
self.hotKeyManager.startListening(
keyCode: self.hotKeyCode,
mode: self.activationMode,
doubleTapThreshold: self.doubleTapThreshold,
safetyTimeout: self.hotKeySafetyTimeout,
modifiers: self.hotKeyModifiers
)
}
}
if !self.isAutoPaused {
self.modelKeepAlive.bump()
}
}
$appStatus
.sink { [weak self] status in
guard let self else { return }
switch status {
case .idle:
if !self.isAutoPaused {
self.modelKeepAlive.bump()
}
case .recording, .processing, .error:
self.modelKeepAlive.cancel()
}
}
.store(in: &cancellables)
autoPauseMonitor.start()
modelKeepAlive.start()
sleepWakeMonitor.start()
if !skipSystemIntegration {
AudioDeviceMonitor.shared.start()
}
}
/// Unload the resident model and clear active UI flags.
func unloadActiveModel(reason: ModelUnloadReason) async {
VocaLogger.info(.appState, "Unloading model (reason=\(reason.rawValue))")
modelKeepAlive.cancel()
let beforeMB = ProcessMonitor.currentResidentMemoryMB()
processMemoryBeforeUnloadMB = beforeMB
await whisperService.unloadModel()
// Give the allocator a beat to release pages before sampling again.
try? await Task.sleep(nanoseconds: 150_000_000)
let afterMB = ProcessMonitor.currentResidentMemoryMB()
processMemoryAfterUnloadMB = afterMB
lastModelUnloadReason = reason
for i in availableModels.indices {
availableModels[i].isActive = false
availableModels[i].isLoading = false
}
currentModel = nil
VocaLogger.info(
.appState,
"Unload complete (reason=\(reason.rawValue), RSS \(String(format: "%.0f", beforeMB))→\(String(format: "%.0f", afterMB)) MB)"
)
}
/// Approximate RAM freed by the last unload, when both samples exist.
var approximateMemoryFreedMB: Double? {
guard let before = processMemoryBeforeUnloadMB,
let after = processMemoryAfterUnloadMB,
before > after else {
return nil
}
return before - after
}
/// User-facing summary of why the model is currently unloaded.
var modelUnloadStatusMessage: String? {
guard !whisperService.isModelLoaded else { return nil }
if isAutoPaused {
if let name = autoPauseTriggerDisplayName, !name.isEmpty {
return "Paused while \(name) is running. The speech model was unloaded to free memory."
}
return "Paused by a listed app. The speech model was unloaded to free memory."
}
switch lastModelUnloadReason {
case .idleKeepAlive:
return "Model unloaded after idle timeout. Next dictation reloads it."
case .autoPause:
return "Model unloaded by auto-pause."
case .manual:
return "Model unloaded."
case .none:
return nil
}
}
/// Ensure a model is loaded before dictation (lazy reload after idle unload).
func ensureModelLoaded() async {
guard !whisperService.isModelLoaded else { return }
let size = ModelSize(rawValue: selectedModelSize)
?? currentModel?.size
?? .tiny
VocaLogger.info(.appState, "Ensuring model loaded: \(size.displayName)")
await loadModel(size)
}
private func handleAutoPauseEntered() async {
isAutoPaused = true
autoPauseTriggerDisplayName = autoPauseMonitor.activeTrigger?.displayName
modelKeepAlive.cancel()
if isRecording || appStatus == .recording {
VocaLogger.warning(.appState, "Auto-pause entered while recording: stopping without inject")
_ = await stopAudioEngine()
isRecording = false
audioLevel = 0
cursorOverlay.hide()
hotKeyManager.resetKeyState()
appStatus = .idle
}
if whisperService.isModelLoaded {
await unloadActiveModel(reason: .autoPause)
} else {
lastModelUnloadReason = .autoPause
}
}
private func handleAutoPauseCleared() async {
isAutoPaused = false
autoPauseTriggerDisplayName = nil
// Warm-reload so the next hotkey is ready (Linux behavior).
await ensureModelLoaded()
modelKeepAlive.bump()
}
/// Build the model list shown in Settings and onboarding.
///
/// The base catalog is curated for M-series Macs, then extended with any
/// exact variants WhisperKit marks supported for the current device.
/// Models whose engine cannot run on this system at all (e.g. Apple
/// Speech before macOS 26, Parakeet on Intel) are excluded entirely.
private func modelCatalog() -> [ModelSize] {
var catalog = ModelSize.standardCatalog.filter { $0.isAvailableOnThisSystem }
for size in ModelSize.allCases
where size.isAvailableOnThisSystem && modelManager.isModelSupported(size) {
if !catalog.contains(size) {
catalog.append(size)
}
}
if let selected = ModelSize(rawValue: selectedModelSize),
!catalog.contains(selected) {
catalog.append(selected)
}
return catalog
}
/// Recreate model UI state from the latest catalog and local cache status.
private func rebuildAvailableModels() {
availableModels = modelCatalog().map { size in
WhisperModelInfo(
size: size,
filePath: modelManager.modelFolder(for: size),
isDownloaded: modelManager.isModelDownloaded(size),
isActive: size.rawValue == selectedModelSize,
isSupported: modelManager.isModelSupported(size)
)
}
}
/// Resolve WhisperKit's recommended exact model variant into app metadata.
private func recommendedModelSize() -> ModelSize? {
guard let recommended = deviceRecommendedModel,
let size = modelManager.modelSize(from: recommended),
modelManager.isModelSupported(size) else {
return nil
}
return size
}
/// Pick a supported startup model when the stored preference is no longer valid.
private func startupFallbackModel(for preferred: ModelSize) -> ModelSize {
guard !modelManager.isModelSupported(preferred) else {
return preferred
}
// Stay on the engine the user was already using where possible.
// Without this, the catalog order alone decides the fallback, and a
// Whisper user could land on a different engine — notably Apple
// Speech, which always counts as downloaded because macOS owns it.
if let sameEngine = availableModels.last(where: {
$0.size.engine == preferred.engine && $0.isSupported && $0.isDownloaded
})?.size {
return sameEngine
}
if let downloadedSupported = availableModels.last(where: { $0.isSupported && $0.isDownloaded })?.size {
return downloadedSupported
}
if let recommended = recommendedModelSize() {
return recommended
}
return .tiny
}
// MARK: - Permission Handling (delegated to PermissionManager)
func checkPermissions() { permissionManager.checkPermissions() }
func startPermissionPolling() { permissionManager.startPermissionPolling() }
func stopPermissionPolling() { permissionManager.stopPermissionPolling() }
var allPermissionsGranted: Bool { permissionManager.allPermissionsGranted }
func requestMicrophonePermission() { permissionManager.requestMicrophonePermission() }
func openMicrophoneSettings() { permissionManager.openMicrophoneSettings() }
func requestAccessibilityPermission() { permissionManager.requestAccessibilityPermission() }
func requestInputMonitoringPermission() { permissionManager.requestInputMonitoringPermission() }
// MARK: - Hotkey Configuration
/// Apply persisted hotkey settings to the active listener.
/// `@AppStorage` updates save preferences immediately, but an already-running
/// event tap also needs its in-memory configuration refreshed.
func syncHotKeyConfiguration() {
hotKeyManager.updateConfiguration(
keyCode: hotKeyCode,
mode: activationMode,
doubleTapThreshold: doubleTapThreshold,
safetyTimeout: hotKeySafetyTimeout,
modifiers: hotKeyModifiers
)
VocaLogger.debug(.appState, "Hotkey configuration synced (keyCode=\(hotKeyCode), modifiers=\(hotKeyModifiers.rawValue), mode=\(activationMode.rawValue))")
}
// MARK: - Force Recovery
/// Forcibly reset the entire recording pipeline to idle state.
/// This is a last-resort recovery mechanism callable from the menu bar UI.
/// It unconditionally resets the audio engine, hotkey state, cursor overlay,
/// and all published state back to idle.
func forceRecovery() {
VocaLogger.warning(.appState, "Force recovery: resetting all state to idle (was appStatus=\(appStatus.rawValue), isRecording=\(isRecording))")
// Reset audio engine unconditionally
audioEngine.forceReset()
// Reset hotkey tracking state
hotKeyManager.resetKeyState()
// Reset UI state
isRecording = false
audioLevel = 0.0
cursorOverlay.hide()
appStatus = .idle
errorMessage = nil
}
/// Play start, then stop, for the tone currently selected in Settings.
/// Off is silence. Preview is not gated by the sound-effects switch.
func previewDictationTone() async {
await soundManager.previewStartThenStop()
}
// MARK: - Recording Flow
func startRecording() async {
// If we're already recording, this is a recovery attempt — the user
// pressed the hotkey again because a previous key-up was missed.
// Stop the current recording and transcribe what we have.
if appStatus == .recording || isRecording {
VocaLogger.warning(.appState, "startRecording called while already recording — treating as stop (recovery)")
await stopRecordingAndTranscribe()
return
}
if isAutoPaused {
let message = "Dictation is paused while a listed app is running."
VocaLogger.info(.appState, message)
showTemporaryError(message)
return
}
guard appStatus == .idle else {
// If stuck in .processing or .error for too long, force recovery
// so the user can start a fresh recording.
if appStatus == .error || appStatus == .processing {
VocaLogger.warning(.appState, "startRecording called in \(appStatus.rawValue) state — force recovering to allow new recording")
forceRecovery()
// Don't start recording in the same call — let the user press again
return
}
VocaLogger.warning(.appState, "startRecording called in non-idle state: \(appStatus.rawValue) — ignoring")
return
}
guard micPermission == .granted else {
errorMessage = "Microphone permission is required. Please grant access in System Settings."
appStatus = .error
return
}
// Lazy-reload after idle unload (or any other cold start).
if !whisperService.isModelLoaded {
appStatus = .processing
await ensureModelLoaded()
guard whisperService.isModelLoaded else {
showTemporaryError("Could not load the speech model. Open Settings → Speech Model and try again.")
return
}
appStatus = .idle
}
appStatus = .recording
isRecording = true
errorMessage = nil
inputDeviceFallbackNotice = nil
// Show the overlay in its connecting state. It only claims to be
// listening once the audio engine confirms the route is live — on
// Bluetooth that can be seconds later, and anything said before then is
// not captured by anyone.
if showCursorIndicator && overlayStyle != .off {
cursorOverlay.show(style: overlayStyle, position: overlayPosition)
}
// Start recording immediately for instant responsiveness.
// The start sound is played concurrently — any brief bleed into the
// mic buffer is negligible and handled well by WhisperKit's noise model.
isStartingAudio = true
pendingStopDuringStart = nil
let didStartRecording = await startAudioEngine(
silenceThreshold: Float(silenceThreshold),
silenceDuration: silenceDuration,
maxDuration: TimeInterval(maxRecordingDuration),
preferredInputDeviceID: selectedAudioDeviceID.isEmpty ? nil : selectedAudioDeviceID,
preferredInputChannel: selectedAudioChannel,
preferredInputChannelDeviceID: selectedAudioChannelDeviceID.isEmpty
? nil
: selectedAudioChannelDeviceID,
preferredInputChannelCount: selectedAudioChannelCount
)
isStartingAudio = false
// The hotkey was released (or the overlay cancelled) while the route was
// still coming up. That stop was deferred so it wouldn't block behind the
// Bluetooth settle; finish it now.