forked from VocaHQ/vocamac
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppState.swift
More file actions
793 lines (679 loc) · 33.2 KB
/
Copy pathAppState.swift
File metadata and controls
793 lines (679 loc) · 33.2 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
// 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?
/// 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.doubleTapThreshold") var doubleTapThreshold: Double = 0.4
@AppStorage("vocamac.silenceThreshold") var silenceThreshold: Double = 0.01
@AppStorage("vocamac.silenceDuration") var silenceDuration: Double = 2.0
@AppStorage("vocamac.maxRecordingDuration") var maxRecordingDuration: Int = 60
@AppStorage("vocamac.selectedModelSize") var selectedModelSize: String = ModelSize.tiny.rawValue
@AppStorage("vocamac.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("vocamac.showCursorIndicator") var showCursorIndicator: Bool = true
@AppStorage("vocamac.translationEnabled") var translationEnabled: Bool = false
@AppStorage("vocamac.logLevel") var logLevel: String = "info"
// 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 updateChecker = UpdateChecker()
let permissionManager: any PermissionManaging
// MARK: - Private
private var cancellables = Set<AnyCancellable>()
private var hasStarted = false
/// 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
// MARK: - Initialization
init(
audioEngine: AudioRecording = AudioEngine(),
whisperService: SpeechTranscribing = WhisperService(),
textInjector: TextInjecting = TextInjector(),
hotKeyManager: HotKeyMonitoring = HotKeyManager(),
modelManager: ModelManaging = ModelManager(),
soundManager: SoundPlaying = SoundManager(),
cursorOverlay: CursorOverlayManaging,
statsManager: StatsManaging,
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.permissionManager = permissionManager ?? PermissionManager(audioEngine: audioEngine, hotKeyManager: hotKeyManager)
self.skipSystemIntegration = skipSystemIntegration
VocaLogger.info(.appState, "Initializing... id=\(ObjectIdentifier(self))")
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
}
// Initialize available models list
availableModels = ModelSize.allCases.map { size in
WhisperModelInfo(
size: size,
filePath: modelManager.modelFolder(for: size),
isDownloaded: modelManager.isModelDownloaded(size),
isActive: size.rawValue == selectedModelSize,
isSupported: modelManager.isModelSupported(size)
)
}
// Enforce monotonic support ordering: if a smaller model is unsupported,
// all larger models must also be unsupported. This prevents contradictory
// UI states like Medium="Too Large" but Large v3="Recommended".
var foundUnsupported = false
for i in availableModels.indices {
if !availableModels[i].isSupported {
foundUnsupported = true
}
if foundUnsupported {
availableModels[i].isSupported = false
}
}
// 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 model
if let bestSupported = availableModels.last(where: { $0.isSupported }) {
deviceRecommendedModel = modelManager.whisperKitModelName(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
}
}
// 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: Double(self.maxRecordingDuration) + 5.0
)
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)
// Check permissions
checkPermissions()
}
// 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: - 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
}
// 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
}
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
}
appStatus = .recording
isRecording = true
errorMessage = nil
// Show cursor indicator
if showCursorIndicator {
cursorOverlay.show()
}
// 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.
audioEngine.startRecording(
silenceThreshold: Float(silenceThreshold),
silenceDuration: silenceDuration,
maxDuration: TimeInterval(maxRecordingDuration)
)
// Play start sound after mic is active (fire-and-forget)
if soundEffectsEnabled {
soundManager.playStartSound()
}
}
func stopRecordingAndTranscribe() async {
// Accept stop if we're recording OR if the audio engine thinks
// it's recording (covers stuck-state recovery scenarios where
// isRecording and appStatus may be out of sync).
guard isRecording || appStatus == .recording else { return }
let audioData = audioEngine.stopRecording()
isRecording = false
audioLevel = 0.0
// Play stop sound
if soundEffectsEnabled {
soundManager.playStopSound()
}
// Transition cursor indicator to processing state (red -> purple)
// Keeps the overlay visible so the user knows text is on its way
cursorOverlay.transitionToProcessing()
guard !audioData.isEmpty else {
cursorOverlay.hide()
appStatus = .idle
return
}
appStatus = .processing
do {
let language = selectedLanguage == "auto" ? nil : selectedLanguage
let result = try await whisperService.transcribe(
audioData: audioData,
language: language,
translate: translationEnabled
)
lastTranscription = result
// Update stats
statsManager.recordTranscription(result)
// Inject text at cursor position
// by WhisperService to remove hallucination tokens like [BLANK_AUDIO])
let trimmedText = result.text.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmedText.isEmpty {
textInjector.inject(
text: trimmedText,
preserveClipboard: preserveClipboard
)
} else {
VocaLogger.info(.appState, "Transcription produced no usable text (silence or blank audio)")
}
cursorOverlay.hide()
appStatus = .idle
} catch {
cursorOverlay.hide()
errorMessage = "Transcription failed: \(error.localizedDescription)"
appStatus = .error
// Auto-recover after 3 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { [weak self] in
if self?.appStatus == .error {
self?.appStatus = .idle
self?.errorMessage = nil
}
}
}
}
// MARK: - Model Management
func loadModel(_ size: ModelSize? = nil) async {
let modelName: String?
if let size = size {
modelName = modelManager.whisperKitModelName(for: size)
} else {
modelName = nil // Let WhisperKit auto-select
}
// Resolve which ModelSize we're loading. When size is nil (auto-select),
// we don't know yet — we'll detect it after loading completes.
let targetSize = size
// Mark the model as loading in the UI
if let targetSize = targetSize, let idx = availableModels.firstIndex(where: { $0.size == targetSize }) {
availableModels[idx].isLoading = true
availableModels[idx].loadingStatus = "Preparing…"
}
do {
// If model is downloaded locally, pass the folder URL so WhisperKit
// loads from disk instead of downloading again. WhisperKit handles
// tokenizer fetching itself — we don't pre-validate those files.
let folderURL: URL?
if let targetSize = targetSize, modelManager.isModelDownloaded(targetSize) {
folderURL = modelManager.modelFolder(for: targetSize)
} else {
folderURL = nil
}
// Update status: unpacking
if let targetSize = targetSize, let idx = availableModels.firstIndex(where: { $0.size == targetSize }) {
availableModels[idx].loadingStatus = "Unpacking model…"
}
// Load model with status callback
try await whisperService.loadModel(name: modelName, folder: folderURL) { [weak self] phase in
Task { @MainActor in
guard let self = self else { return }
if let targetSize = targetSize,
let idx = self.availableModels.firstIndex(where: { $0.size == targetSize }) {
self.availableModels[idx].loadingStatus = phase
}
}
}
// Determine which ModelSize was actually loaded.
// When auto-selecting, WhisperKit chooses the model and we need
// to detect which one it picked by inspecting the loaded model name.
let resolvedSize: ModelSize
if let targetSize = targetSize {
resolvedSize = targetSize
} else {
let loadedName = (whisperService.loadedModelName ?? "").lowercased()
// Check from largest to smallest to avoid "base" matching inside "large-v3"
if loadedName.contains("large") {
resolvedSize = .largeV3
} else if loadedName.contains("medium") {
resolvedSize = .medium
} else if loadedName.contains("small") {
resolvedSize = .small
} else if loadedName.contains("base") {
resolvedSize = .base
} else {
resolvedSize = .tiny
}
VocaLogger.info(.appState, "Auto-selected model resolved to: \(resolvedSize.displayName) (from '\(whisperService.loadedModelName ?? "unknown")')")
}
// Persist the resolved model as the user's preference
selectedModelSize = resolvedSize.rawValue
// Update model states — clear all, then mark the loaded one as active
for i in availableModels.indices {
let matches = availableModels[i].size == resolvedSize
availableModels[i].isActive = matches
availableModels[i].isLoading = false
availableModels[i].loadingStatus = "Loading…"
if matches {
// Refresh download status in case the auto-select downloaded it
availableModels[i].isDownloaded = modelManager.isModelDownloaded(resolvedSize)
currentModel = availableModels[i]
}
}
VocaLogger.info(.appState, "Model ready: \(resolvedSize.displayName)")
} catch {
// Clear loading state on error for all models (covers auto-select case)
for i in availableModels.indices {
availableModels[i].isLoading = false
availableModels[i].loadingStatus = "Loading…"
}
errorMessage = "Failed to load model: \(error.localizedDescription)"
VocaLogger.error(.appState, "Failed to load model: \(error.localizedDescription)")
}
}
func downloadModel(_ size: ModelSize) async {
guard let index = availableModels.firstIndex(where: { $0.size == size }) else { return }
availableModels[index].downloadProgress = 0.0
do {
try await modelManager.downloadModel(size: size) { [weak self] progress in
Task { @MainActor in
guard let self = self else { return }
if let idx = self.availableModels.firstIndex(where: { $0.size == size }) {
// Only update progress if we haven't already completed (1.0)
// This prevents race conditions with the simulated progress task
if progress >= 1.0 || self.availableModels[idx].downloadProgress != nil {
self.availableModels[idx].downloadProgress = progress
}
}
}
}
// Small delay to let the final progress (1.0) callback settle on MainActor
try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
// Refresh all model statuses to ensure previously downloaded models are preserved
refreshModelStatuses()
VocaLogger.info(.appState, "Download complete for \(size.displayName), isDownloaded=\(modelManager.isModelDownloaded(size))")
} catch {
if let idx = availableModels.firstIndex(where: { $0.size == size }) {
availableModels[idx].downloadProgress = nil
}
errorMessage = "Download failed: \(error.localizedDescription)"
VocaLogger.error(.appState, "Download failed for \(size.displayName): \(error.localizedDescription)")
}
}
/// Refresh the download status of all models
/// This ensures that all previously downloaded models are detected and marked correctly
private func refreshModelStatuses() {
for i in availableModels.indices {
let size = availableModels[i].size
availableModels[i].isDownloaded = modelManager.isModelDownloaded(size)
availableModels[i].downloadProgress = nil
availableModels[i].filePath = modelManager.modelFolder(for: size)
}
}
// MARK: - Startup
private func installBundledOrFallback(preferred: ModelSize) async -> Bool {
do {
return try modelManager.installBundledModelIfAvailable(for: preferred)
} catch {
VocaLogger.warning(.appState, "Bundled model install failed for \(preferred.displayName): \(error.localizedDescription)")
return false
}
}
func performStartup() async {
VocaLogger.info(.appState, "performStartup beginning...")
// 1. Detect hardware
systemCapabilities = SystemInfo.detect()
let sysInfo = systemCapabilities
VocaLogger.info(.appState, "System: \(sysInfo?.processorName ?? "unknown") | \(sysInfo?.physicalMemoryGB ?? 0) GB RAM | \(sysInfo?.coreCount ?? 0) cores")
// 2. Check/request permissions
checkPermissions()
VocaLogger.info(.appState, "Mic permission: \(micPermission.rawValue) | Accessibility: \(accessibilityPermission.rawValue) | Input Monitoring: \(inputMonitoringPermission.rawValue)")
// Auto-prompt for microphone permission on first launch
if micPermission == .notDetermined {
VocaLogger.info(.appState, "Mic permission not determined — requesting...")
requestMicrophonePermission()
}
// Start polling if any permission is still missing
startPermissionPolling()
// 3. Load the user's preferred model.
// On first launch the preferred model (tiny by default) won't be
// downloaded yet. We download it explicitly so the UI can show real
// progress, rather than delegating to WhisperKit's opaque auto-select
// which provides no progress callbacks and may pick a different model.
var modelToLoad = ModelSize(rawValue: selectedModelSize) ?? .tiny
if !modelManager.isModelDownloaded(modelToLoad) {
// Try bundled model for the preferred size first
let installedPreferred = await installBundledOrFallback(preferred: modelToLoad)
if installedPreferred {
refreshModelStatuses()
} else {
VocaLogger.info(.appState, "Preferred model \(modelToLoad.displayName) not downloaded — downloading now...")
await downloadModel(modelToLoad)
}
// If preferred model still isn't ready, try bundled tiny as a last resort
if !modelManager.isModelDownloaded(modelToLoad), modelToLoad != .tiny {
let installedTiny = await installBundledOrFallback(preferred: .tiny)
if installedTiny {
modelToLoad = .tiny
refreshModelStatuses()
VocaLogger.info(.appState, "Falling back to bundled Tiny model")
}
}
}
VocaLogger.info(.appState, "Loading model: \(modelToLoad.displayName)...")
await loadModel(modelToLoad)
VocaLogger.info(.appState, "Model loaded: \(whisperService.loadedModelName ?? "none")")
// 4. Always attempt to start hotkey listener
// The event tap creation itself will fail if permissions aren't granted,
// and we handle that gracefully in HotKeyManager.
VocaLogger.info(.appState, "Attempting to start hotkey listener...")
hotKeyManager.startListening(
keyCode: hotKeyCode,
mode: activationMode,
doubleTapThreshold: doubleTapThreshold,
safetyTimeout: Double(maxRecordingDuration) + 5.0
)
if hotKeyManager.isListening {
VocaLogger.info(.appState, "Hotkey listener active (keyCode=\(hotKeyCode), mode=\(activationMode.rawValue))")
} else {
VocaLogger.warning(.appState, "Hotkey listener failed to start. Check Accessibility & Input Monitoring permissions.")
}
await updateChecker.checkOnLaunchIfNeeded()
VocaLogger.info(.appState, "Startup complete!")
}
func completeOnboarding() {
hasCompletedOnboarding = true
VocaLogger.info(.appState, "Onboarding completed")
}
}