forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppState.swift
More file actions
1092 lines (999 loc) · 47.9 KB
/
Copy pathAppState.swift
File metadata and controls
1092 lines (999 loc) · 47.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
@preconcurrency import AVFoundation
import Combine
@preconcurrency import ObjectiveC
import OmiSupport
import SwiftUI
@preconcurrency import UserNotifications
enum SystemAudioPermissionStatus: String {
case unknown
case granted
case denied
case unsupported
/// Map a capture-start failure to an honest permission status. A TCC denial
/// manifests as the tap failing to create or the device failing to start;
/// format/converter/aggregate failures are provably NOT permission problems
/// and must not claim a denial.
@available(macOS 14.4, *)
static func classify(captureError error: Error) -> SystemAudioPermissionStatus {
guard let captureError = error as? SystemAudioCaptureService.SystemAudioCaptureError else {
return .unknown
}
switch captureError {
case .tapCreationFailed, .deviceStartFailed:
return .denied
case .aggregateDeviceFailed, .ioProcCreationFailed, .formatError, .converterCreationFailed:
return .unknown
case .unsupportedOS:
return .unsupported
}
}
}
/// Translation from backend (e.g., Japanese speech translated to English)
struct SegmentTranslation: Identifiable {
var id: String { lang }
let lang: String
let text: String
}
/// Speaker segment for diarized transcription
struct SpeakerSegment: Identifiable {
/// Stable identity — uses backend segment ID when available, otherwise speaker + start time
var id: String { segmentId ?? "\(speaker)-\(start)" }
var segmentId: String? // Backend-assigned UUID
var speaker: Int
var text: String
var start: Double
var end: Double
var isUser: Bool = false
var personId: String? // Backend-assigned person ID from speaker identification
var translations: [SegmentTranslation] = []
}
/// Result of finalizing a conversation
enum FinishConversationResult {
case saved
case discarded
case error(String)
}
enum DesktopConversationMatchPolicy {
/// Backend and local clocks can differ slightly around WebSocket close/reconnect.
static let startedAtTolerance: TimeInterval = 10
static let cloudReconciliationStatuses: [ConversationStatus] = [.inProgress, .processing, .completed]
static func matchesDesktopConversation(
startedAt conversationStartedAt: Date?,
source: ConversationSource?,
sessionStartedAt: Date
) -> Bool {
guard let conversationStartedAt else { return false }
guard source == .desktop else { return false }
return abs(conversationStartedAt.timeIntervalSince(sessionStartedAt)) < startedAtTolerance
}
static func memoryEventMatchesFinishedSession(
_ memory: [String: Any]?,
sessionStartedAt: Date
) -> Bool {
guard let memory else { return false }
// Older backend lifecycle events may omit source; accept missing source for
// compatibility, but reject an explicit non-desktop source.
if let source = memory["source"] as? String, source != "desktop" {
return false
}
guard let memoryStartedAt = parseMemoryEventDate(memory["started_at"] ?? memory["startedAt"]) else {
return false
}
return abs(memoryStartedAt.timeIntervalSince(sessionStartedAt)) < startedAtTolerance
}
static func shouldBindConversationSession(
incomingBackendId: String,
expectedBackendId: String? = nil,
activeBackendId: String?,
ignoredRotatedBackendIds: Set<String>
) -> Bool {
guard !incomingBackendId.isEmpty else { return false }
if let expectedBackendId, !expectedBackendId.isEmpty, incomingBackendId != expectedBackendId {
return false
}
if let activeBackendId, !activeBackendId.isEmpty {
return incomingBackendId == activeBackendId
}
if ignoredRotatedBackendIds.contains(incomingBackendId) {
return false
}
return true
}
/// Remember a newly observed rollover without allowing duplicate stale
/// callbacks to evict a different guard entry.
static func rememberingRotatedBackendId(
_ backendId: String,
activeBackendId: String?,
ignoredRotatedBackendIds: Set<String>,
maxCount: Int
) -> Set<String> {
guard let activeBackendId,
activeBackendId != backendId,
!ignoredRotatedBackendIds.contains(backendId)
else { return ignoredRotatedBackendIds }
var updated = ignoredRotatedBackendIds
if updated.count >= maxCount, let evicted = updated.first {
updated.remove(evicted)
}
updated.insert(backendId)
return updated
}
/// Identified listen sessions may only consume lifecycle events produced by
/// their own recording. Older backend versions omit `recording_session_id`,
/// so the matching conversation id remains the compatibility proof.
static func lifecycleEventBelongsToRecording(
memoryId: String,
recordingSessionId: String?,
expectedBackendId: String?
) -> Bool {
guard let expectedBackendId, !expectedBackendId.isEmpty else { return true }
guard memoryId == expectedBackendId else { return false }
return recordingSessionId == nil || recordingSessionId == expectedBackendId
}
/// A completed backend event is telemetry-eligible only when it can be
/// attributed to the local recording that just ended. Durable SQLite
/// binding is intentionally not required: an exact client conversation id
/// or the legacy source/timestamp proof is sufficient.
static func acceptsCompletedLocalRecording(
memoryId: String,
memory: [String: Any]?,
recordingSessionId: String?,
expectedBackendId: String?,
finishedRecordingStartTime: Date?
) -> Bool {
guard !memoryId.isEmpty, memoryId != "?" else { return false }
guard
lifecycleEventBelongsToRecording(
memoryId: memoryId,
recordingSessionId: recordingSessionId,
expectedBackendId: expectedBackendId
)
else {
return false
}
if let expectedBackendId, !expectedBackendId.isEmpty {
return memoryId == expectedBackendId
}
guard let finishedRecordingStartTime else { return false }
return memoryEventMatchesFinishedSession(memory, sessionStartedAt: finishedRecordingStartTime)
}
static func matchingFinishedRecordingIndex(
memoryId: String,
memory: [String: Any]?,
recordingSessionId: String?,
pending: [FinishedRecordingEnvelope]
) -> Int? {
pending.firstIndex { envelope in
acceptsCompletedLocalRecording(
memoryId: memoryId,
memory: memory,
recordingSessionId: recordingSessionId,
expectedBackendId: envelope.clientConversationId,
finishedRecordingStartTime: envelope.startedAt
)
}
}
/// Versioned lifecycle envelopes are an ordered protocol. A client only
/// accepts a newer event for its own durable recording-session binding;
/// omitted fields use the legacy compatibility path above.
static func acceptsLifecycleEnvelope(
recordingSessionId: String?,
conversationId: String,
lifecycleVersion: Int?,
lifecyclePhase: String?,
lifecycleSequence: Int?,
expectedLifecyclePhase: String,
expectedBackendId: String?,
lastAcceptedSequence: Int?
) -> Bool {
guard lifecycleVersion != nil || lifecycleSequence != nil else { return true }
guard lifecycleVersion == 1,
let recordingSessionId,
!recordingSessionId.isEmpty,
lifecyclePhase == expectedLifecyclePhase,
let lifecycleSequence,
lifecycleSequence >= 0
else { return false }
if let expectedBackendId, !expectedBackendId.isEmpty {
guard recordingSessionId == expectedBackendId, conversationId == expectedBackendId else { return false }
}
guard let lastAcceptedSequence else { return true }
return lifecycleSequence > lastAcceptedSequence
}
static func canCompleteBoundBackendConversation(
id conversationId: String,
boundBackendId: String,
status: ConversationStatus,
source: ConversationSource?
) -> Bool {
conversationId == boundBackendId && source == .desktop && status != .inProgress
}
static func shouldFinalizeTimestampMatchedConversation(status: ConversationStatus) -> Bool {
status == .inProgress
}
static func canCompleteTimestampMatchedConversation(
status: ConversationStatus,
source: ConversationSource?
) -> Bool {
source == .desktop && status != .inProgress
}
static func canForceProcessBoundCloudSession(
capturedBackendId: String?,
persistedBackendId: String?
) -> Bool {
guard let capturedBackendId, !capturedBackendId.isEmpty else { return false }
return persistedBackendId == capturedBackendId
}
static func parseMemoryEventDate(_ value: Any?) -> Date? {
if let date = value as? Date {
return date
}
guard let string = value as? String else {
return nil
}
let fractionalFormatter = ISO8601DateFormatter()
fractionalFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
if let date = fractionalFormatter.date(from: string) {
return date
}
let formatter = ISO8601DateFormatter()
return formatter.date(from: string)
}
}
struct FinishedRecordingEnvelope: Equatable, Sendable {
let sessionId: Int64?
let clientConversationId: String?
let startedAt: Date
let source: ConversationSource
}
@MainActor
protocol DesktopAlertPresenting: AnyObject {
func present(title: String, message: String, completion: (@MainActor () -> Void)?)
/// Stop draining the alert queue until Omi is the active app again.
///
/// Completions that hand the foreground to another app (System Settings)
/// must call this *before* that hand-off. `NSWorkspace.open` can return
/// while Omi is still active, so inferring a pause from the current shell
/// window would drain the next alert and hide it behind Settings.
func pauseQueueUntilAppActive()
}
@MainActor
extension DesktopAlertPresenting {
func present(title: String, message: String) {
present(title: title, message: message, completion: nil)
}
func pauseQueueUntilAppActive() {}
}
@MainActor
class AppState: ObservableObject {
/// Weak reference to the current AppState instance, set on init.
/// Used by background services (e.g. TranscriptionRetryService) to check recording state.
static weak var current: AppState?
@AppStorage("hasCompletedOnboarding") var hasCompletedOnboarding = false
// Transcription state
@Published var isTranscribing = false {
didSet {
// Preferred-mic reconnect must track live Listening even when Settings is closed (#10921).
if isTranscribing {
preferredMicrophoneReconnectMonitor.start(observing: self)
} else {
preferredMicrophoneReconnectMonitor.stop()
}
}
}
/// A terminal live-STT failure reported by `/v4/listen`. Audio capture can
/// continue into the WAL while the transport reconnects, so this stays
/// visible until the backend is ready or the active session is reset.
@Published var transcriptionServiceError: String?
/// Assigned in `init()` rather than here: the pinned Xcode 16.4 toolchain
/// segfaults (signal 11 in `silgen emitStoredPropertyInitialization`) when
/// lowering this existential-erasure default initializer, introduced with
/// the presenter itself in d49f978512. Every desktop CI lane was red from
/// that commit until this dodge; behavior is identical on both toolchains.
var alertPresenter: any DesktopAlertPresenting
/// Monotonically increasing counter — incremented for each recording start or stop request.
/// Used to prevent asynchronous work from mutating a newer recording decision.
var recordingGeneration: UInt64 = 0
@Published var isSavingConversation = false
/// True from the moment a capture stops until its conversation has been
/// loaded into the list. Keeps the Live card's slot occupied so the meeting
/// visibly lands as a row instead of vanishing and reappearing.
@Published var isFinalizingCapture = false
/// Follows visible processing rows to a terminal state (see the type).
lazy var processingWatcher = ProcessingConversationWatcher.live(
fetch: ProcessingConversationWatcher.fetchDetail,
onResolved: { [weak self] refreshed in self?.conversationRepository.replace(refreshed) }
)
// currentTranscript is internal-only (not observed by views), so no @Published needed
var currentTranscript: String = ""
@Published var hasMicrophonePermission = false
@Published var hasSystemAudioPermission = false
@Published var systemAudioPermissionStatus: SystemAudioPermissionStatus = .unknown
@Published var isSystemAudioSupported = false
// Audio source (microphone or BLE device)
@Published var audioSource: AudioSource = .microphone
/// Tracks the source for the current recording (for API tagging)
var currentConversationSource: ConversationSource = .desktop
/// Guards against re-entering the silent-mic fallback path multiple times in a single session.
/// The user-visible banner lives in `SilentMicNoticeMonitor.shared`.
var silentMicFallbackInProgress: Bool = false
// Audio levels moved to AudioLevelMonitor to avoid triggering global re-renders
// Access via AudioLevelMonitor.shared.microphoneLevel / .systemLevel
var microphoneAudioLevel: Float { AudioLevelMonitor.shared.microphoneLevel }
var systemAudioLevel: Float { AudioLevelMonitor.shared.systemLevel }
// Recording timer moved to RecordingTimer to avoid triggering global re-renders
// Access via RecordingTimer.shared.duration
var recordingDuration: TimeInterval { RecordingTimer.shared.duration }
var hasActiveConversationFilters: Bool {
showStarredOnly || selectedDateFilter != nil || selectedFolderId != nil
}
// Live speaker segments moved to LiveTranscriptMonitor to avoid triggering global re-renders
// Access via LiveTranscriptMonitor.shared.segments
var liveSpeakerSegments: [SpeakerSegment] { LiveTranscriptMonitor.shared.segments }
// Conversation state
@Published var conversations: [ServerConversation] = []
@Published var isLoadingConversations: Bool = false
@Published var conversationsError: String? = nil
@Published var totalConversationsCount: Int? = nil // Unfiltered total count for dashboard metrics.
@Published var filteredConversationsCount: Int? = nil // Count matching the active conversations filters.
let conversationRepository = ConversationRepository()
// Conversation filters
@Published var showStarredOnly: Bool = false
@Published var selectedDateFilter: Date? = nil
@Published var selectedFolderId: String? = nil
// Folders
@Published var folders: [Folder] = []
@Published var isLoadingFolders: Bool = false
// People (speaker voice profiles)
@Published var people: [Person] = []
var peopleById: [String: Person] {
// Last-write-wins: the API can return duplicate person ids.
Dictionary(lastWriteWins: people.map { ($0.id, $0) })
}
/// Maps live speaker IDs to person IDs during recording (cleared on finalize)
@Published var liveSpeakerPersonMap: [Int: String] = [:]
// Permission states for onboarding
@Published var hasNotificationPermission = false
@Published var notificationAuthorizationStatus: UNAuthorizationStatus = .notDetermined
@Published var notificationAlertStyle: UNAlertStyle = .none // .none, .banner, or .alert
@Published var hasScreenRecordingPermission = false
/// TCC state captured once at process launch. A grant that arrives while the
/// app is running doesn't apply to this process until relaunch
/// (see ScreenRecordingPermissionPolicy.needsRelaunchToApply).
let screenRecordingGrantedAtLaunch = ScreenCaptureService.checkPermission()
@Published var hasBluetoothPermission = false
// Track last notification settings for change detection (avoid duplicate analytics)
var lastNotificationAuthStatus: String?
var lastNotificationAlertStyle: String?
var lastNotificationSoundEnabled: Bool?
var lastNotificationBadgeEnabled: Bool?
var notificationPermissionRefreshGeneration = 0
@Published var isScreenCaptureKitBroken = false // Capture engine issue; not the source of permission truth
@Published var isScreenRecordingStale = false // Deprecated: no longer inferred from capture failures
var screenRecordingGrantAttempts = 0 // Track how many times user clicked Grant without success
@Published var hasAutomationPermission = false
// Non-zero when check fails unexpectedly (e.g. -600 procNotFound).
@Published var automationPermissionError: OSStatus = 0
// Prevent concurrent checks (retry path has a 1s sleep).
var isCheckingAutomationPermission = false
/// In-flight guard for the accessibility probe, mirroring the automation one above.
/// The probe is several `AXUIElementCopyAttributeValue` round trips against OTHER
/// processes, and AX messaging to a hung app blocks for the full AX timeout (seconds).
/// Without this, a repeating caller (onboarding polls once a second) stacks a fresh
/// detached probe on every tick against an app that is not answering.
var isCheckingAccessibilityPermission = false
@Published var hasAccessibilityPermission = false
// TCC says yes but AX calls actually fail (common after macOS updates/app re-signs).
@Published var isAccessibilityBroken = false
/// Token for the `com.apple.accessibility.api` observer, so the live permission refresh is
/// installed exactly once. See `startAccessibilityChangeObserver()`.
var accessibilityChangeObserver: NSObjectProtocol?
@Published var hasFullDiskAccess = false
/// Usage-limit popup state. Set by `triggerUsageLimitPopup(reason:)` when the
/// user hits a free-tier cap (transcription minutes, monthly chat messages, etc).
/// The popup is mounted as an overlay in `DesktopHomeView` and is closable.
@Published var showUsageLimitPopup: Bool = false
@Published var usageLimitReason: String = ""
/// True once the backend has told us this desktop user is past their trial
/// (e.g. via the `freemium_threshold_reached` listen-WS event). When true,
/// every $-incurring toggle on the desktop client should refuse to enable
/// and show the paywall popup instead. Stays sticky until the app restarts
/// or the user successfully reactivates (chat-quota allows / paid plan).
///
/// Mirrored to UserDefaults `desktop_isPaywalled` so non-AppState singletons
/// (e.g. `ProactiveAssistantsPlugin`) can synchronously gate without holding
/// an AppState reference.
@Published var isPaywalled: Bool = false {
didSet { UserDefaults.standard.set(isPaywalled, forKey: "desktop_isPaywalled") }
}
/// Trial metadata from `/v1/users/me/trial`. Updated every 60s.
@Published var trialMetadata: TrialMetadataResponse?
var trialRefreshTimer: Timer?
/// Trigger the monthly-limit popup. Safe to call repeatedly — SwiftUI's
/// `@Published` dedupes identical-value writes automatically.
nonisolated(unsafe) let servicesCoordinator = AppServicesCoordinator()
var audioCaptureService: AudioCaptureService? {
get { servicesCoordinator.audioCaptureService }
set { servicesCoordinator.audioCaptureService = newValue }
}
var transcriptionService: TranscriptionService? {
get { servicesCoordinator.transcriptionService }
set { servicesCoordinator.transcriptionService = newValue }
}
var systemAudioCaptureService: Any? {
get { servicesCoordinator.systemAudioCaptureService }
set { servicesCoordinator.systemAudioCaptureService = newValue }
}
var audioMixer: AudioMixer? {
get { servicesCoordinator.audioMixer }
set { servicesCoordinator.audioMixer = newValue }
}
var meetingDetector: MeetingDetector? {
get { servicesCoordinator.meetingDetector }
set { servicesCoordinator.meetingDetector = newValue }
}
var captureGateInFlight = false
var captureReconcilePending = false
var pendingCoreAudioCaptureRecoveryReason: String?
/// While ambient transcription is live, reapply a preferred mic when it reconnects (#10921).
let preferredMicrophoneReconnectMonitor = PreferredMicrophoneReconnectMonitor()
/// Counts CoreAudio rebuilds caused by a zero-sample microphone during one
/// transcription session. This lives above `AudioCaptureService` because each
/// rebuild creates a fresh service (and therefore a fresh service-local watchdog).
var silentMicRecoveryAttempts = 0
var currentConversationRole: MeetingConversationBoundaryPolicy.Role = .ambient
var meetingDetectorMode: AssistantSettings.AudioRecordingMode?
var meetingBoundaryInProgress = false
var pendingMeetingState: Bool?
/// The input device a silent-mic fallback healed onto, held for the rest of the session.
///
/// Without this the heal is undone by its own recovery: `handleSilentMicFallback` pins
/// capture to the built-in mic, then the next watchdog trip rebuilds the CoreAudio stack
/// with a plain `AudioCaptureService()`, which re-resolves the *system default* input —
/// still the silent Bluetooth device. The two fight until the attempt cap is hit and the
/// user gets an alert, then it starts over.
var silentMicHealedDeviceID: AudioDeviceID?
var meetingEndFinalizationInProgress = false
@Published var isAwaitingMeeting = false
/// Audio is actually reaching STT — not merely that a transcription session is armed.
///
/// Only Meetings keeps `isTranscribing` true while waiting for a call so capture can start
/// instantly, and sets `isAwaitingMeeting` while the mic is paused. Live UI (the Conversations
/// card, the expanded transcript, the top-bar mic dot) must follow this, not `isTranscribing`.
var isLiveCapturing: Bool { isTranscribing && !isAwaitingMeeting }
var audioRecordingMode: AssistantSettings.AudioRecordingMode {
AssistantSettings.shared.audioRecordingMode
}
/// A hidden developer override may suppress the system tap, but it cannot change the user's
/// recording policy or whether the microphone/meeting gate runs.
var shouldCaptureSystemAudio: Bool {
!UserDefaults.standard.bool(forKey: .disableSystemAudioCapture)
&& !UserDefaults.standard.bool(forKey: .onboardingSystemAudioSkipped)
}
var vadGateService: VADGateService? {
get { servicesCoordinator.vadGateService }
set { servicesCoordinator.vadGateService = newValue }
}
var localMicService: LocalTranscriptionService? {
get { servicesCoordinator.localMicService }
set { servicesCoordinator.localMicService = newValue }
}
var localSystemService: LocalTranscriptionService? {
get { servicesCoordinator.localSystemService }
set { servicesCoordinator.localSystemService = newValue }
}
var sttSession = STTSessionState()
static let isAppleSilicon: Bool = {
var value: Int32 = 0
var size = MemoryLayout<Int32>.size
if sysctlbyname("hw.optional.arm64", &value, &size, nil, 0) == 0 {
return value == 1
}
return false
}()
var speakerSegments: [SpeakerSegment] = []
let maxInMemorySegments = 200
var totalSegmentCount = 0
var totalWordCount = 0
var recordingStartTime: Date?
/// Published: the capture-source label renders this, and the preferred-mic
/// resolution assigns it after `isTranscribing` has already published — a
/// plain var would leave the UI showing the default device until unrelated
/// state churned.
@Published var recordingInputDeviceName: String?
var maxRecordingTimer: Timer? {
get { servicesCoordinator.maxRecordingTimer }
set { servicesCoordinator.maxRecordingTimer = newValue }
}
let maxRecordingDuration: TimeInterval = 4 * 60 * 60
var notificationHealthTimer: Timer? {
get { servicesCoordinator.notificationHealthTimer }
set { servicesCoordinator.notificationHealthTimer = newValue }
}
var currentSessionId: Int64?
/// Serializes segment persistence so a local duplicate replacement cannot race
/// the original mic segment's upsert in SQLite.
var transcriptPersistenceTail: Task<Void, Never>?
/// True while a bridge-owned hermetic capture session is active (T2 E2E only).
var automationCaptureTestSessionActive = false
var currentBackendConversationId: String?
/// The UUID created by desktop before opening an identified `/v4/listen` stream.
/// In the current compatible protocol it is also the backend conversation id.
var currentClientConversationId: String?
var pendingBackendConversationId: String?
/// Last accepted server event sequence per durable recording session. This
/// is display state only; Firestore remains the authoritative sequence owner.
var lifecycleSequenceByRecordingSession: [String: Int] = [:]
static let maxLifecycleRecordingSessions = 32
var ignoredRotatedBackendConversationIds: Set<String> = []
static let maxIgnoredRotatedBackendConversationIds = 16
var pendingFinishedRecordings: [FinishedRecordingEnvelope] = []
static let maxPendingFinishedRecordings = 16
var willTerminateObserver: NSObjectProtocol? {
get { servicesCoordinator.willTerminateObserver }
set { servicesCoordinator.willTerminateObserver = newValue }
}
var willSleepObserver: NSObjectProtocol? {
get { servicesCoordinator.willSleepObserver }
set { servicesCoordinator.willSleepObserver = newValue }
}
var didWakeObserver: NSObjectProtocol? {
get { servicesCoordinator.didWakeObserver }
set { servicesCoordinator.didWakeObserver = newValue }
}
var screenLockedObserver: NSObjectProtocol? {
get { servicesCoordinator.screenLockedObserver }
set { servicesCoordinator.screenLockedObserver = newValue }
}
var screenUnlockedObserver: NSObjectProtocol? {
get { servicesCoordinator.screenUnlockedObserver }
set { servicesCoordinator.screenUnlockedObserver = newValue }
}
var screenCapturePermissionLostObserver: NSObjectProtocol? {
get { servicesCoordinator.screenCapturePermissionLostObserver }
set { servicesCoordinator.screenCapturePermissionLostObserver = newValue }
}
var screenCaptureKitBrokenObserver: NSObjectProtocol? {
get { servicesCoordinator.screenCaptureKitBrokenObserver }
set { servicesCoordinator.screenCaptureKitBrokenObserver = newValue }
}
var audioRecordingModeObserver: NSObjectProtocol? {
get { servicesCoordinator.audioRecordingModeObserver }
set { servicesCoordinator.audioRecordingModeObserver = newValue }
}
var coreAudioCaptureRecoveryObserver: NSObjectProtocol? {
get { servicesCoordinator.coreAudioCaptureRecoveryObserver }
set { servicesCoordinator.coreAudioCaptureRecoveryObserver = newValue }
}
var wasTranscribingBeforeSleep = false
var conversationRoleBeforeSleep: MeetingConversationBoundaryPolicy.Role = .ambient
var lastScreenLockTime: Date?
var lastScreenUnlockTime: Date?
var buttonStreamTask: Task<Void, Never>? {
get { servicesCoordinator.buttonStreamTask }
set { servicesCoordinator.buttonStreamTask = newValue }
}
var bluetoothStateCancellable: AnyCancellable? {
get { servicesCoordinator.bluetoothStateCancellable }
set { servicesCoordinator.bluetoothStateCancellable = newValue }
}
nonisolated(unsafe) private var ownerChangeObserver: NSObjectProtocol?
/// Bumped on every in-place account switch. Owner-scoped loads capture it
/// before awaiting and drop their result if it moved — a previous account's
/// in-flight response must never repopulate state after the reset (the
/// skip-while-non-empty reload guards would then pin the stale data).
private(set) var ownerScopeGeneration: UInt64 = 0
/// Clear account-owned conversation UI state on an in-place account switch.
/// The .userDidSignOut handler in DesktopHomeView covers full sign-out (and
/// additionally resets onboarding and stops transcription); an in-place
/// switch posts only .runtimeOwnerDidChange, so without this the previous
/// account's folders, filters, counts, and people kept rendering.
func resetOwnerScopedContent() {
ownerScopeGeneration &+= 1
folders = []
selectedFolderId = nil
selectedDateFilter = nil
showStarredOnly = false
totalConversationsCount = nil
filteredConversationsCount = nil
conversationsError = nil
isLoadingConversations = false
isLoadingFolders = false
people = []
}
init() {
alertPresenter = AppKitSheetAlertPresenter()
// Fold any legacy PTT-only microphone choice into the shared preference before
// anything reads it. Running this only from PTT routing meant a user who had picked a
// PTT microphone saw "System Default" in Transcription — and was recorded by it —
// until they happened to take a push-to-talk turn.
ShortcutSettings.migratePTTMicrophoneChoiceIfNeeded()
// Register as the current instance so background services can check recording state
AppState.current = self
ownerChangeObserver = NotificationCenter.default.addObserver(
forName: .runtimeOwnerDidChange, object: nil, queue: nil
) { [weak self] _ in
MainActor.assumeIsolated {
self?.resetOwnerScopedContent()
}
}
conversationRepository.onSnapshot = { [weak self] snapshot in
guard let self else { return }
self.conversations = snapshot.conversations
self.processingWatcher.sync(with: snapshot.conversations)
self.isLoadingConversations = snapshot.isLoading
self.conversationsError = snapshot.error
if self.hasActiveConversationFilters {
self.filteredConversationsCount = snapshot.count
} else {
self.totalConversationsCount = snapshot.count
self.filteredConversationsCount = nil
}
}
// Restore paywall flag from prior session so toggles + auto-restart respect
// it before any backend call has a chance to refresh state — but never for
// a BYOK user (all four keys configured) or a user whose cached plan is
// paid. The paid-plan carve-out fixes a popup-on-launch bug for Neo
// subscribers grandfathered onto desktop by #7513: their last session
// pre-grandfather wrote isPaywalled=true; without this clear, the next
// launch shows the monthly-limit popup until fetchTrialMetadata returns
// (~1-2s) AND callers that read UserDefaults synchronously
// (ProactiveAssistantsPlugin, isPaywalledEffective) keep blocking until
// didSet writes the new value. Only basic-tier users have a legitimate
// pre-fetch paywalled state to preserve.
// Freemium: the desktop trial paywall is disabled by default
// (backend TRIAL_PAYWALL_ENABLED off), so a stale cached
// `desktop_isPaywalled=true` from a pre-freemium session must not gate
// anything on launch. Previously basic-tier users trusted that cache and
// flashed the "monthly limit" popup until fetchTrialMetadata refreshed
// (~1-2s) — and synchronous readers (ProactiveAssistantsPlugin,
// isPaywalledEffective) blocked for that whole window. Always start
// non-paywalled and let the backend's trial metadata be authoritative:
// fetchTrialMetadata re-sets isPaywalled only if the backend genuinely
// reports trial_expired (it won't under freemium).
self.isPaywalled = false
// didSet doesn't fire from init, so flush UserDefaults explicitly for
// singletons that read the key directly.
UserDefaults.standard.set(false, forKey: "desktop_isPaywalled")
// Load API key from environment or .env file
loadEnvironment()
// Setup lifecycle observers for saving conversations
setupLifecycleObservers()
// Wire up memory pressure callback so ResourceMonitor can trim transcript state
ResourceMonitor.shared.onMemoryPressureTrimTranscript = { [weak self] in
self?.trimTranscriptStateForMemoryPressure()
}
// Listen for screen capture permission loss notifications
screenCapturePermissionLostObserver = NotificationCenter.default.addObserver(
forName: .screenCapturePermissionLost,
object: nil,
queue: .main
) { [weak self] _ in
Task { @MainActor in
let granted = ScreenCaptureService.checkPermission()
self?.hasScreenRecordingPermission = ScreenRecordingPermissionPolicy.uiPermissionGranted(
tccGranted: granted)
self?.isScreenCaptureKitBroken = false // Not broken, just lost
self?.isScreenRecordingStale = false
log("AppState: Screen recording permission lost notification; TCC granted=\(granted)")
}
}
// Listen for ScreenCaptureKit broken notifications (TCC granted but SCK declined)
screenCaptureKitBrokenObserver = NotificationCenter.default.addObserver(
forName: .screenCaptureKitBroken,
object: nil,
queue: .main
) { [weak self] _ in
Task { @MainActor in
let granted = ScreenCaptureService.checkPermission()
self?.hasScreenRecordingPermission = ScreenRecordingPermissionPolicy.uiPermissionGranted(
tccGranted: granted)
self?.isScreenCaptureKitBroken = ScreenRecordingPermissionPolicy.shouldMarkCaptureKitBroken(
tccGranted: granted)
self?.isScreenRecordingStale = false
log("AppState: ScreenCaptureKit broken notification; TCC granted=\(granted)")
}
}
// Check if system audio capture is supported (macOS 14.4+)
// Note: hasSystemAudioPermission stays false until actually tested during onboarding
if #available(macOS 14.4, *) {
isSystemAudioSupported = true
}
// Note: Bluetooth subscription is initialized lazily via initializeBluetoothIfNeeded()
// to avoid triggering the permission dialog before the user reaches the Bluetooth step
// Start periodic notification health check (every 30 min).
// Detects when macOS silently revokes notification authorization. NOTE: this only
// *observes* — it reads `UNUserNotificationCenter.notificationSettings` and updates
// published state. It does NOT auto-repair (the repair path this comment used to
// describe, `NotificationRegistrationRepair`, has no live caller), and it must not
// be wired to one: the repair unregisters the app from LaunchServices and
// re-requests authorization, which is not something to do on a timer.
notificationHealthTimer = Timer.scheduledTimer(withTimeInterval: 30 * 60, repeats: true) {
[weak self] _ in
MainActor.assumeIsolated {
self?.checkNotificationPermission()
}
}
}
/// Initialize Bluetooth manager and subscribe to state changes
/// Call this only when the user reaches the Bluetooth onboarding step
func initializeBluetoothIfNeeded() {
guard bluetoothStateCancellable == nil else {
log("Bluetooth already initialized, skipping")
return
}
log("Initializing Bluetooth manager...")
// Also initialize DeviceProvider's Bluetooth bindings
DeviceProvider.shared.initializeBluetoothBindingsIfNeeded()
// Subscribe to Bluetooth state changes for reactive permission updates
bluetoothStateCancellable = BluetoothManager.shared.$bluetoothState
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
guard let self = self else { return }
let oldValue = self.hasBluetoothPermission
// poweredOn = ready to use, poweredOff = allowed but BT is off
let newValue = state == .poweredOn || state == .poweredOff
log(
"BLUETOOTH_SUBSCRIPTION: state=\(BluetoothManager.shared.bluetoothStateDescription), stateRaw=\(state.rawValue), auth=\(BluetoothManager.shared.authorizationDescription), granted=\(newValue)"
)
if newValue != oldValue {
log(
"Bluetooth permission changed via subscription: \(oldValue) -> \(newValue), state=\(BluetoothManager.shared.bluetoothStateDescription)"
)
self.hasBluetoothPermission = newValue
}
}
}
/// Setup observers for app quit and system sleep to finalize conversations
private func setupLifecycleObservers() {
// App is about to quit
willTerminateObserver = NotificationCenter.default.addObserver(
forName: NSApplication.willTerminateNotification,
object: nil,
queue: .main
) { [weak self] _ in
guard let self = self else { return }
Task { @MainActor in
if self.isTranscribing {
log("App terminating - stopping transcription (backend handles conversation)")
let sessionId = self.currentSessionId
self.stopAudioCapture()
if let sessionId {
try? await TranscriptionStorage.shared.finishSession(id: sessionId, reason: .userStop)
}
self.clearTranscriptionState(
finalizationReason: .userStop,
runFinalizer: false,
allowCloudForceProcess: false,
finishSession: false
)
}
}
}
// Computer is about to sleep
willSleepObserver = NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.willSleepNotification,
object: nil,
queue: .main
) { [weak self] _ in
guard let self = self else { return }
Task { @MainActor in
self.wasTranscribingBeforeSleep = self.isTranscribing
if self.isTranscribing {
log("Computer sleeping - stopping transcription (backend handles conversation)")
self.conversationRoleBeforeSleep = self.currentConversationRole
let sessionId = self.currentSessionId
self.stopAudioCapture()
if let sessionId {
try? await TranscriptionStorage.shared.finishSession(id: sessionId, reason: .userStop)
}
self.clearTranscriptionState(
finalizationReason: .userStop,
runFinalizer: false,
allowCloudForceProcess: false,
finishSession: false
)
}
// Flush final sync changes before sleep
await AgentSyncService.shared.stop()
}
}
// Computer woke from sleep
didWakeObserver = NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didWakeNotification,
object: nil,
queue: .main
) { [weak self] _ in
log("System woke from sleep")
NotificationCenter.default.post(name: .systemDidWake, object: nil)
// Restart transcription if it was active before sleep
Task { @MainActor in
guard let self = self else { return }
if self.wasTranscribingBeforeSleep && AssistantSettings.shared.audioRecordingMode != .off {
log("System wake: Restarting transcription (was active before sleep)")
// Brief delay to let audio subsystem settle after wake
try? await Task.sleep(for: .seconds(2))
if !self.isTranscribing {
self.startTranscription(
conversationRole: self.conversationRoleBeforeSleep, userInitiated: false)
}
}
self.wasTranscribingBeforeSleep = false
}
}
// Screen locked (debounced - macOS sometimes fires multiple times)
screenLockedObserver = DistributedNotificationCenter.default().addObserver(
forName: NSNotification.Name("com.apple.screenIsLocked"),
object: nil,
queue: .main
) { [weak self] _ in
Task { @MainActor in
let now = Date()
if let lastTime = self?.lastScreenLockTime, now.timeIntervalSince(lastTime) < 1.0 {
return // Ignore duplicate within 1 second
}
self?.lastScreenLockTime = now
log("Screen locked")
NotificationCenter.default.post(name: .screenDidLock, object: nil)
}
}
// Screen unlocked (debounced - macOS sometimes fires multiple times)
screenUnlockedObserver = DistributedNotificationCenter.default().addObserver(
forName: NSNotification.Name("com.apple.screenIsUnlocked"),
object: nil,
queue: .main
) { [weak self] _ in
Task { @MainActor in
let now = Date()
if let lastTime = self?.lastScreenUnlockTime, now.timeIntervalSince(lastTime) < 1.0 {
return // Ignore duplicate within 1 second
}
self?.lastScreenUnlockTime = now
log("Screen unlocked")
NotificationCenter.default.post(name: .screenDidUnlock, object: nil)
}
}
// One preference owns both intent and meeting gating. Apply every change live so no stale
// boolean or secondary picker can disagree with the selected mode.
audioRecordingModeObserver = NotificationCenter.default.addObserver(
forName: .audioRecordingModeDidChange,
object: nil,
queue: .main
) { [weak self] _ in
Task { @MainActor in
guard let self else { return }
switch AssistantSettings.shared.audioRecordingMode {
case .off:
self.stopTranscription()
case .always, .onlyMeetings:
if self.isTranscribing {
await self.reconcileCapture()
} else {
self.startTranscription(userInitiated: false)
}
}
}
}
coreAudioCaptureRecoveryObserver = NotificationCenter.default.addObserver(
forName: .coreAudioCaptureRecoveryRequested,
object: nil,
queue: .main
) { [weak self] note in
let reason = note.userInfo?["reason"] as? String ?? "unspecified"
Task { @MainActor in
await self?.rebuildCoreAudioCaptureStack(reason: reason)
}
}
}
deinit {
servicesCoordinator.removeLifecycleObservers()
if let ownerChangeObserver {
NotificationCenter.default.removeObserver(ownerChangeObserver)
}
}
}
extension Notification.Name {
static let resetOnboardingRequested = Notification.Name("resetOnboardingRequested")
/// Posted by the onboarding arrow-key monitor with a "targetStep" Int in
/// userInfo. The mounted OnboardingView applies it to its live @AppStorage —
/// the monitor closure must not mutate its own captured copy (writes there
/// never reach UserDefaults or the UI on all macOS versions).
static let onboardingStepNavigationRequested = Notification.Name(
"onboardingStepNavigationRequested")
/// Automation bridge → onboarding screen-demo step: open the three-doors page (same code path as
/// the step's "Open the doors" button), so agents can exercise the demo without the cursor.
static let onboardingOpenDoorsRequested = Notification.Name("onboardingOpenDoorsRequested")
/// The three-doors page finished and handed the user back to Omi via the app URL scheme.
static let onboardingDoorsCompleted = Notification.Name("onboardingDoorsCompleted")
/// Posted when the system wakes from sleep
static let systemDidWake = Notification.Name("systemDidWake")