-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathProactiveAssistantsPlugin.swift
More file actions
1585 lines (1349 loc) · 65.9 KB
/
Copy pathProactiveAssistantsPlugin.swift
File metadata and controls
1585 lines (1349 loc) · 65.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
import Cocoa
import UserNotifications
/// Service that manages proactive assistants - screen monitoring, frame capture, and assistant coordination
@MainActor
public class ProactiveAssistantsPlugin: NSObject {
// MARK: - Singleton
/// Shared instance
public static let shared = ProactiveAssistantsPlugin()
// MARK: - Properties
private var screenCaptureService: ScreenCaptureService?
private var windowMonitor: WindowMonitor?
private var focusAssistant: FocusAssistant?
/// Public read-only accessor for memory diagnostics
var currentFocusAssistant: FocusAssistant? { focusAssistant }
private var taskAssistant: TaskAssistant?
private var insightAssistant: InsightAssistant?
private var memoryAssistant: MemoryAssistant?
private var captureTimer: Timer?
private var analysisDelayTimer: Timer?
private var isInDelayPeriod = false
private(set) var isMonitoring = false
private var isStartingMonitoring = false // Prevents race condition with async startMonitoring
private var _hasScreenRecordingPermission: Bool? // Cached permission state
private var currentApp: String?
private var currentWindowID: CGWindowID?
private var currentWindowTitle: String?
private var lastStatus: FocusStatus?
private var frameCount = 0
// Backpressure: prevents unbounded CGImage accumulation (~24MB each) when video
// encoding is slower than the capture rate — the primary cause of multi-GB memory growth.
private(set) var isProcessingRewindFrame = false
private(set) var droppedFrameCount = 0
/// Periodic screen recording permission recheck interval (60 seconds).
/// Detects permission revocation while monitoring is active (issue #5792).
private var lastPermissionCheckTime: Date = .distantPast
private let permissionCheckInterval: TimeInterval = 60
// Failure tracking for screen capture recovery
private var consecutiveFailures = 0
private let maxConsecutiveFailures = 5
private var lastCaptureSucceeded = true
private var wasMonitoringBeforeSleep = false
private var wasMonitoringBeforeLock = false
private var systemEventObservers: [NSObjectProtocol] = []
// Video call throttling: reduce capture frequency when a call app is frontmost
// to avoid competing with the call app for CPU/GPU (ScreenCaptureKit, encoding, OCR).
private var videoCallFrameCounter = 0
private let videoCallThrottleFactor = 5 // Capture 1 out of every 5 frames (effective ~5s interval)
// Screenshot-app yielding: pause capture entirely while another screenshot/recording
// app is frontmost, and hold a short backoff after it resigns so its editor UI isn't
// disturbed. Prevents Omi's 3s capture loop from locking WindowServer at the moment
// the user is trying to take a screenshot (CleanShot, Shottr, macOS screenshot, etc.).
private var wasScreenshotAppFrontmost = false
private var screenshotAppBackoffUntil: Date = .distantPast
// Change-gated distribution: only distribute frames to assistants when context changes.
// Eliminates continuous polling when the user stays on the same app/window.
private var lastDistributedApp: String?
private var lastDistributedWindowTitle: String?
private var distributionDebounceTimer: Timer?
private var latestCapturedFrame: CapturedFrame?
private var lastDistributionTime: Date = .distantPast
/// Fallback interval: re-distribute even without context change to catch visual-only updates.
private let distributionFallbackInterval: TimeInterval = 60
/// Apps whose primary purpose is video/audio calls.
private static let videoCallApps: Set<String> = [
"Microsoft Teams",
"zoom.us",
"FaceTime",
"Webex",
"Cisco Webex Meetings",
"GoTo Meeting",
"GoToMeeting",
]
/// Bundle IDs of third-party and system screenshot/screen-recording apps.
/// When one of these is frontmost, Omi's 3s capture loop contends with the
/// user's active capture (WindowServer locks + SCK arbitration), which can
/// freeze the other app's capture UI for 20-60 seconds. We pause Omi's
/// capture entirely while any of these is frontmost.
private static let screenshotAppBundleIDs: Set<String> = [
"pl.maketheweb.cleanshotx", // CleanShot X
"cc.ffitch.shottr", // Shottr
"com.apple.screencaptureui", // macOS screenshot.app overlay
"com.apple.screenshot.launcher", // macOS screenshot hotkey launcher
"com.loom.desktop-app", // Loom
"com.loom.desktop", // Loom (alt)
"com.techsmith.snagit2025", // Snagit (current)
"com.techsmith.snagit2024", // Snagit (prior)
"com.techsmith.snagit2023", // Snagit (older)
"com.obsproject.obs-studio", // OBS Studio
"com.screenium.Screenium3", // Screenium
"com.kapeli.screenium", // Screenium (alt)
"com.skitch.skitch", // Skitch
"com.evernote.skitch", // Skitch (alt)
"com.monosnap.monosnap", // Monosnap
"com.lightshot.app", // Lightshot
"com.capto.Capto", // Capto
"com.pixelmatorteam.screenshot", // Pixelmator screenshot
"com.tencent.xin.lemon", // WeCom screenshot
]
/// Keywords in browser window titles that indicate a video call.
private static let videoCallBrowserKeywords: [String] = [
"Google Meet",
"meet.google.com",
"Teams - Microsoft", // Teams web app
]
/// Browser app names (for window-title-based call detection).
private static let browserApps: Set<String> = [
"Google Chrome",
"Arc",
"Safari",
"Firefox",
"Microsoft Edge",
"Brave Browser",
"Opera",
]
// Auto-retry state for transient failures (Exposé, Mission Control, etc.)
private var isInRecoveryMode = false
private var recoveryRetryCount = 0
private let maxRecoveryRetries = 30 // Try up to 30 attempts before giving up
private let recoveryInterval: TimeInterval = 5.0 // Seconds between recovery attempts
// Background polling state for extended recovery after initial retry fails
private var isInBackgroundPolling = false
private var backgroundPollTimer: Timer?
private var backgroundPollCount = 0
private let maxBackgroundPollAttempts = 5 // 5 attempts × 60s = 5 minutes
private static var hasAutoResetThisSession = false
private static var hasSoftRecoveryThisSession = false
// Retain distributed notification observer tokens
private var testNotificationObservers: [NSObjectProtocol] = []
// MARK: - Initialization
private override init() {
super.init()
// Load environment variables
loadEnvironment()
// Set up the coordinator event callback
AssistantCoordinator.shared.setEventCallback { [weak self] type, data in
self?.sendEvent(type: type, data: data)
}
// Set up system event observers for sleep/wake/lock recovery
setupSystemEventObservers()
// Listen for CLI-triggered test notifications
setupTestNotificationListeners()
log("ProactiveAssistantsPlugin initialized")
}
// MARK: - Environment Loading
private func loadEnvironment() {
let envPaths = [
Bundle.main.path(forResource: ".env", ofType: nil),
FileManager.default.currentDirectoryPath + "/.env",
NSHomeDirectory() + "/.omi.env",
NSHomeDirectory() + "/.hartford.env"
].compactMap { $0 }
for path in envPaths {
if let contents = try? String(contentsOfFile: path, encoding: .utf8) {
for line in contents.components(separatedBy: .newlines) {
let parts = line.split(separator: "=", maxSplits: 1)
if parts.count == 2 {
let key = String(parts[0]).trimmingCharacters(in: .whitespaces)
let value = String(parts[1]).trimmingCharacters(in: .whitespaces)
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
setenv(key, value, 1)
}
}
log("Loaded environment from: \(path)")
break
}
}
DesktopBackendEnvironment.applyReleaseChannelDefaults()
}
// MARK: - Assistant Management
private func enableAssistant(identifier: String, enabled: Bool) {
switch identifier {
case "focus":
FocusAssistantSettings.shared.isEnabled = enabled
case "task-extraction":
TaskAssistantSettings.shared.isEnabled = enabled
case "insight":
InsightAssistantSettings.shared.isEnabled = enabled
case "memory-extraction":
MemoryAssistantSettings.shared.isEnabled = enabled
default:
log("Unknown assistant: \(identifier)")
}
}
// MARK: - Public Monitoring Control
/// Start monitoring with optional retry for transient permission failures
public func startMonitoring(retryCount: Int = 0, completion: @escaping (Bool, String?) -> Void) {
let maxRetries = 3
let retryDelays: [Double] = [2.0, 4.0, 8.0] // exponential backoff
// Guard against both active monitoring and pending startup (race condition fix)
guard !isMonitoring && !isStartingMonitoring else {
completion(isMonitoring, nil)
return
}
// Set flag synchronously before async call to prevent race condition
isStartingMonitoring = true
// Check screen recording permission (and update cache)
refreshScreenRecordingPermission()
guard hasScreenRecordingPermission else {
if retryCount == 0 {
// First attempt: request permissions and schedule retry
ScreenCaptureService.requestAllScreenCapturePermissions()
}
if retryCount < maxRetries {
let delay = retryDelays[retryCount]
log("Screen recording permission not yet granted, retrying in \(delay)s (attempt \(retryCount + 1)/\(maxRetries))")
isStartingMonitoring = false
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
self?.startMonitoring(retryCount: retryCount + 1, completion: completion)
}
return
}
log("Screen recording permission not granted after \(maxRetries) retries, giving up")
isStartingMonitoring = false
completion(false, "Screen recording permission not granted")
return
}
// Request notification permission in parallel — don't block monitoring on it.
// Screen analysis can work without notifications - users just won't get alerts.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
DispatchQueue.main.async {
if let error = error {
let nsError = error as NSError
log("Notification permission request error: \(error.localizedDescription) (domain=\(nsError.domain) code=\(nsError.code))")
// UNErrorDomain code 1 = notificationsNotAllowed
// This happens when LaunchServices has the app marked as launch-disabled,
// preventing notification center registration. Repair and retry once.
if nsError.domain == "UNErrorDomain" && nsError.code == 1 {
AnalyticsManager.shared.notificationRepairTriggered(
reason: "launch_disabled_error_startup",
previousStatus: "notDetermined",
currentStatus: "error_code_1"
)
Self.repairNotificationRegistration()
}
}
if !granted {
log("Notification permission not granted - screen analysis will work but notifications will be disabled")
}
}
}
// Start monitoring immediately — don't wait for notification permission callback
continueStartMonitoring(completion: completion)
}
/// Repair LaunchServices registration when notification authorization fails with "not allowed".
/// The launch-disabled flag in LaunchServices prevents notification center registration.
/// Unregistering and re-registering clears the flag, then retries authorization.
static func repairNotificationRegistration() {
let appPath = Bundle.main.bundlePath
let bundleURL = Bundle.main.bundleURL
log("Repairing LaunchServices registration for notifications: \(appPath)")
let lsregister = "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
// Run blocking Process calls on a background thread
DispatchQueue.global(qos: .utility).async {
// Unregister to clear stale/launch-disabled entries
let unregister = Process()
unregister.executableURL = URL(fileURLWithPath: lsregister)
unregister.arguments = ["-u", appPath]
try? unregister.run()
unregister.waitUntilExit()
// Force re-register
let register = Process()
register.executableURL = URL(fileURLWithPath: lsregister)
register.arguments = ["-f", appPath]
try? register.run()
register.waitUntilExit()
// Restart usernoted (notification center daemon) to pick up fresh registration
// Runs as current user (no sudo needed), auto-restarts within ~1 second
let killUsernoted = Process()
killUsernoted.executableURL = URL(fileURLWithPath: "/usr/bin/killall")
killUsernoted.arguments = ["usernoted"]
killUsernoted.standardOutput = FileHandle.nullDevice
killUsernoted.standardError = FileHandle.nullDevice
try? killUsernoted.run()
killUsernoted.waitUntilExit()
log("Restarted usernoted to force notification re-discovery")
// Wait for usernoted to restart before retrying
Thread.sleep(forTimeInterval: 1.5)
DispatchQueue.main.async {
// Also re-register via LSRegisterURL (must be on main thread)
if let cfURL = bundleURL as CFURL? {
LSRegisterURL(cfURL, true)
}
log("LaunchServices re-registration complete, retrying notification authorization...")
// Retry authorization after a short delay
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
NSApp.activate()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
log("Notification retry after repair failed: \(error.localizedDescription)")
} else if granted {
log("Notification permission granted after LaunchServices repair")
}
}
}
}
}
}
private func continueStartMonitoring(completion: @escaping (Bool, String?) -> Void) {
// Report resources before starting heavy monitoring
ResourceMonitor.shared.reportResourcesNow(context: "before_monitoring_start")
// Initialize services
screenCaptureService = ScreenCaptureService()
do {
focusAssistant = try FocusAssistant(
onAlert: { [weak self] message in
self?.sendEvent(type: "alert", data: ["message": message])
},
onStatusChange: { [weak self] status in
Task { @MainActor in
self?.lastStatus = status
self?.sendEvent(type: "statusChange", data: ["status": status.rawValue])
}
},
onRefocus: {
Task { @MainActor in
OverlayService.shared.showGlowAroundActiveWindow(colorMode: .focused)
}
},
onDistraction: {
Task { @MainActor in
OverlayService.shared.showGlowAroundActiveWindow(colorMode: .distracted)
}
}
)
if let focus = focusAssistant {
AssistantCoordinator.shared.register(focus)
}
taskAssistant = try TaskAssistant()
if let task = taskAssistant {
AssistantCoordinator.shared.register(task)
}
Task { await TaskDeduplicationService.shared.start() }
Task { await TaskPrioritizationService.shared.start() }
Task { await TaskPromotionService.shared.start() }
insightAssistant = try InsightAssistant()
if let insight = insightAssistant {
AssistantCoordinator.shared.register(insight)
}
memoryAssistant = try MemoryAssistant()
if let memory = memoryAssistant {
AssistantCoordinator.shared.register(memory)
}
} catch {
log("ProactiveAssistantsPlugin: Failed to initialize assistants: \(error.localizedDescription)")
logError("ProactiveAssistantsPlugin: Assistant initialization failed", error: error)
isStartingMonitoring = false
completion(false, error.localizedDescription)
return
}
// Get initial app state
let (appName, _, _) = WindowMonitor.getActiveWindowInfoStatic()
if let appName = appName {
currentApp = appName
// Update FocusStorage with initial detected app
FocusStorage.shared.updateDetectedApp(appName)
AssistantCoordinator.shared.notifyAppSwitch(newApp: appName)
}
// Start window monitor
windowMonitor = WindowMonitor { [weak self] appName in
Task { @MainActor in
self?.onAppActivated(appName: appName)
}
}
windowMonitor?.start()
// Start capture timer (invalidate any orphaned timer first as safety measure)
captureTimer?.invalidate()
captureTimer = Timer.scheduledTimer(withTimeInterval: RewindSettings.shared.captureInterval, repeats: true) { [weak self] _ in
Task { @MainActor in
await self?.captureFrame()
}
}
isMonitoring = true
// Capture the first frame immediately so screenshots appear right away
// (don't wait for the first timer interval to elapse)
Task { @MainActor in
await self.captureFrame()
}
isStartingMonitoring = false
// Report resources after initialization
ResourceMonitor.shared.reportResourcesNow(context: "after_monitoring_start")
sendEvent(type: "monitoringStarted", data: [:])
AnalyticsManager.shared.monitoringStarted()
NotificationCenter.default.post(
name: .assistantMonitoringStateDidChange,
object: nil,
userInfo: ["isMonitoring": true]
)
log("Proactive assistants started")
completion(true, nil)
}
/// Stop monitoring
public func stopMonitoring() {
guard isMonitoring else { return }
captureTimer?.invalidate()
captureTimer = nil
analysisDelayTimer?.invalidate()
analysisDelayTimer = nil
distributionDebounceTimer?.invalidate()
distributionDebounceTimer = nil
isInDelayPeriod = false
lastDistributedApp = nil
lastDistributedWindowTitle = nil
latestCapturedFrame = nil
lastDistributionTime = .distantPast
windowMonitor?.stop()
windowMonitor = nil
if let focus = focusAssistant {
Task {
await focus.stop()
}
}
if let task = taskAssistant {
Task {
await task.stop()
}
}
Task { await TaskDeduplicationService.shared.stop() }
Task { await TaskPromotionService.shared.stop() }
if let insight = insightAssistant {
Task {
await insight.stop()
}
}
if let memory = memoryAssistant {
Task {
await memory.stop()
}
}
focusAssistant = nil
taskAssistant = nil
insightAssistant = nil
memoryAssistant = nil
screenCaptureService = nil
isMonitoring = false
isStartingMonitoring = false // Reset in case stop was called during startup
isProcessingRewindFrame = false
if droppedFrameCount > 0 {
log("RewindBackpressure: Session total dropped frames: \(droppedFrameCount)")
}
droppedFrameCount = 0
currentApp = nil
currentWindowID = nil
currentWindowTitle = nil
lastStatus = nil
frameCount = 0
// Clear FocusStorage real-time state
FocusStorage.shared.clearRealtimeStatus()
// Report resources after stopping
ResourceMonitor.shared.reportResourcesNow(context: "after_monitoring_stop")
sendEvent(type: "monitoringStopped", data: [:])
AnalyticsManager.shared.monitoringStopped()
NotificationCenter.default.post(
name: .assistantMonitoringStateDidChange,
object: nil,
userInfo: ["isMonitoring": false]
)
log("Proactive assistants stopped")
}
/// Toggle monitoring state
public func toggleMonitoring() {
if isMonitoring {
stopMonitoring()
} else {
startMonitoring { success, error in
if !success, let error = error {
logError("Failed to start monitoring: \(error)")
}
}
}
}
/// Check if screen recording permission is granted
/// Uses cached value to avoid excessive permission check logging
public var hasScreenRecordingPermission: Bool {
if let cached = _hasScreenRecordingPermission {
return cached
}
// First access - check and cache
let result = ScreenCaptureService.checkPermission()
_hasScreenRecordingPermission = result
return result
}
/// Refresh the cached screen recording permission state
public func refreshScreenRecordingPermission() {
_hasScreenRecordingPermission = ScreenCaptureService.checkPermission()
}
/// Get current monitoring status
var currentStatus: (isMonitoring: Bool, currentApp: String?, lastStatus: FocusStatus?) {
return (isMonitoring, currentApp, lastStatus)
}
// MARK: - Frame Capture
private func onAppActivated(appName: String) {
guard appName != currentApp else { return }
currentApp = appName
currentWindowID = nil
currentWindowTitle = nil // Reset window title on app switch
// Update FocusStorage immediately with detected app (before analysis)
FocusStorage.shared.updateDetectedApp(appName)
// Notify all assistants
AssistantCoordinator.shared.notifyAppSwitch(newApp: appName)
sendEvent(type: "appSwitch", data: ["app": appName])
// Start/restart the analysis delay timer
let delaySeconds = AssistantSettings.shared.analysisDelay
analysisDelayTimer?.invalidate()
analysisDelayTimer = nil
if delaySeconds > 0 {
isInDelayPeriod = true
AssistantCoordinator.shared.clearAllPendingWork()
log("App switch detected, starting \(delaySeconds)s analysis delay")
// Update FocusStorage with delay end time
let delayEndTime = Date().addingTimeInterval(TimeInterval(delaySeconds))
FocusStorage.shared.updateDelayEndTime(delayEndTime)
analysisDelayTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(delaySeconds), repeats: false) { [weak self] _ in
Task { @MainActor in
self?.isInDelayPeriod = false
self?.analysisDelayTimer = nil
FocusStorage.shared.updateDelayEndTime(nil)
log("Analysis delay ended, resuming frame processing")
}
}
} else {
isInDelayPeriod = false
FocusStorage.shared.updateDelayEndTime(nil)
Task { @MainActor in
await captureFrame()
}
}
}
private func captureFrame() async {
guard isMonitoring, let screenCaptureService = screenCaptureService else { return }
// Periodic screen recording permission recheck (issue #5792).
// Detects when the user revokes permission via System Settings while monitoring is active,
// and stops gracefully instead of silently failing on every capture.
let now = Date()
if now.timeIntervalSince(lastPermissionCheckTime) >= permissionCheckInterval {
lastPermissionCheckTime = now
let permissionGranted = ScreenCaptureService.checkPermission()
_hasScreenRecordingPermission = permissionGranted
if !permissionGranted {
log("ProactiveAssistantsPlugin: Screen recording permission revoked — stopping monitoring")
// Send user-visible notification about lost permission
sendEvent(type: "permissionLost", data: ["permission": "screenRecording"])
stopMonitoring()
return
}
}
// Skip capture during system modes that block ScreenCaptureKit (Mission Control, Expose, etc.)
// This avoids burning through consecutive failures and generating unnecessary error events
if isInSpecialSystemMode() {
return
}
// Skip capture while a screenshot / screen-recording app is frontmost.
// Both apps using ScreenCaptureKit at the same time contend for WindowServer
// locks, which can stall the user's capture UI for 20-60s. Yield to the user.
if isScreenshotAppFrontmost() {
if !wasScreenshotAppFrontmost {
log("ProactiveAssistantsPlugin: Screenshot app frontmost — pausing capture to avoid WindowServer contention")
wasScreenshotAppFrontmost = true
}
screenshotAppBackoffUntil = Date().addingTimeInterval(10)
return
} else if wasScreenshotAppFrontmost {
log("ProactiveAssistantsPlugin: Screenshot app no longer frontmost, holding backoff for \(Int(max(0, screenshotAppBackoffUntil.timeIntervalSinceNow)))s")
wasScreenshotAppFrontmost = false
}
// Continue honoring the backoff window after the screenshot app resigns so its
// post-capture editor UI (e.g. CleanShot's annotation window) isn't disturbed.
if Date() < screenshotAppBackoffUntil {
return
}
// Get current window info (use real app name, not cached)
let (realAppName, windowTitle, windowID) = await WindowMonitor.getActiveWindowInfoAsync()
// Check if the current app is excluded from Rewind capture
let isRewindExcluded = realAppName.map { RewindSettings.shared.isAppExcluded($0) } ?? false
// Throttle capture when a video call app is frontmost to reduce CPU contention.
// Captures 1 out of every N frames (e.g., effective ~5s interval at default 1s capture rate).
if isVideoCallApp(appName: realAppName, windowTitle: windowTitle) {
videoCallFrameCounter += 1
if videoCallFrameCounter < videoCallThrottleFactor {
if videoCallFrameCounter == 1 {
log("VideoCallThrottle: Detected call app '\(realAppName ?? "unknown")', throttling capture to 1/\(videoCallThrottleFactor) frames")
}
return // Skip this frame
}
// This frame will be captured — reset counter for next cycle
videoCallFrameCounter = 0
} else if videoCallFrameCounter > 0 {
log("VideoCallThrottle: Left call app, resuming normal capture")
videoCallFrameCounter = 0
}
// Unified context switch detection (covers app changes, window ID changes, and title changes)
// Called BEFORE trackFrame so the coordinator's departing frame is from the previous context
if let appForCheck = realAppName ?? currentApp {
let switched = AssistantCoordinator.shared.checkContextSwitch(
newApp: appForCheck,
newWindowTitle: windowTitle
)
if switched && !isInDelayPeriod {
let delaySeconds = AssistantSettings.shared.analysisDelay
if delaySeconds > 0 {
isInDelayPeriod = true
AssistantCoordinator.shared.clearAllPendingWork()
log("Context switch detected, starting \(delaySeconds)s analysis delay")
analysisDelayTimer?.invalidate()
let delayEndTime = Date().addingTimeInterval(TimeInterval(delaySeconds))
FocusStorage.shared.updateDelayEndTime(delayEndTime)
analysisDelayTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(delaySeconds), repeats: false) { [weak self] _ in
Task { @MainActor in
self?.isInDelayPeriod = false
self?.analysisDelayTimer = nil
FocusStorage.shared.updateDelayEndTime(nil)
log("Analysis delay ended, resuming frame processing")
}
}
}
}
}
// Update local window tracking
if let windowID = windowID {
currentWindowID = windowID
}
currentWindowTitle = windowTitle
// Use real app name from window info, fall back to cached if unavailable
let appName = realAppName ?? currentApp
// Always capture frames (other features may need them)
// macOS 14+: capture CGImage directly, encode JPEG once for assistants,
// pass CGImage to RewindIndexer (avoids redundant encode/decode round-trips)
if #available(macOS 14.0, *) {
// Use the window ID already resolved above (line 624) to avoid stale cache hits
// from a second getActiveWindowInfoAsync() call inside captureActiveWindowCGImage()
var cgImage: CGImage? = nil
if let wid = windowID {
switch await screenCaptureService.captureWindowCGImage(windowID: wid) {
case .success(let image):
cgImage = image
case .windowGone:
// The window disappeared between resolution and capture (user closed
// a tab, dismissed a modal, app destroyed the window). Re-resolve the
// active window fresh and retry once — do NOT count this as a capture
// failure. This used to trip the consecutive-failure counter and falsely
// declare "screen recording permission lost" after normal user actions.
cgImage = await screenCaptureService.captureActiveWindowCGImage()
case .failed:
cgImage = nil
}
} else {
cgImage = await screenCaptureService.captureActiveWindowCGImage()
}
if let cgImage = cgImage,
let appName = appName {
if !lastCaptureSucceeded {
log("Screen capture recovered after \(consecutiveFailures) failures")
}
consecutiveFailures = 0
lastCaptureSucceeded = true
frameCount += 1
let captureTime = Date()
// Encode JPEG off main actor — CGImageDestinationFinalize is CPU-heavy
let captureService = screenCaptureService
let jpegData = await Task.detached(priority: .userInitiated) {
captureService.encodeJPEG(from: cgImage)
}.value
if let jpegData = jpegData {
let frame = CapturedFrame(
jpegData: jpegData,
appName: appName,
windowTitle: currentWindowTitle,
frameNumber: frameCount,
captureTime: captureTime
)
// Always track the frame for context switch detection (even during delay)
AssistantCoordinator.shared.trackFrame(frame)
if !isInDelayPeriod {
distributeFrameIfChanged(frame)
} else {
// During delay, still distribute to assistants that need it (e.g. refocus detection)
AssistantCoordinator.shared.distributeFrameDuringDelay(frame)
}
}
// Pass CGImage directly to RewindIndexer (only if not excluded from Rewind)
// Backpressure: skip this frame if the previous one is still being processed.
// Without this, fire-and-forget Tasks queue up holding CGImages (~24MB each),
// causing multi-GB memory growth when encoding can't keep up with capture rate.
if !isRewindExcluded {
if isProcessingRewindFrame {
droppedFrameCount += 1
if droppedFrameCount == 1 || droppedFrameCount % 30 == 0 {
log("RewindBackpressure: Dropped frame (encoder busy), total dropped: \(droppedFrameCount)")
}
} else {
isProcessingRewindFrame = true
let windowTitle = self.currentWindowTitle
Task { [weak self] in
await RewindIndexer.shared.processFrame(
cgImage: cgImage,
appName: appName,
windowTitle: windowTitle,
captureTime: captureTime
)
await MainActor.run {
self?.isProcessingRewindFrame = false
}
}
}
}
} else {
consecutiveFailures += 1
lastCaptureSucceeded = false
if consecutiveFailures == 1 || consecutiveFailures % 5 == 0 {
log("ProactiveAssistantsPlugin: Capture failed (\(consecutiveFailures) consecutive), frontmost: \(getFrontmostAppInfo())")
}
if consecutiveFailures >= maxConsecutiveFailures {
handleRepeatedCaptureFailures()
}
return
}
} else if let jpegData = await screenCaptureService.captureActiveWindowAsync(),
let appName = appName {
// macOS 13.x fallback: existing JPEG-based path
if !lastCaptureSucceeded {
log("Screen capture recovered after \(consecutiveFailures) failures")
}
consecutiveFailures = 0
lastCaptureSucceeded = true
frameCount += 1
let frame = CapturedFrame(
jpegData: jpegData,
appName: appName,
windowTitle: currentWindowTitle,
frameNumber: frameCount
)
// Always track the frame for context switch detection (even during delay)
AssistantCoordinator.shared.trackFrame(frame)
if !isInDelayPeriod {
distributeFrameIfChanged(frame)
} else {
// During delay, still distribute to assistants that need it (e.g. refocus detection)
AssistantCoordinator.shared.distributeFrameDuringDelay(frame)
}
if !isRewindExcluded {
if isProcessingRewindFrame {
droppedFrameCount += 1
if droppedFrameCount == 1 || droppedFrameCount % 30 == 0 {
log("RewindBackpressure: Dropped frame (encoder busy), total dropped: \(droppedFrameCount)")
}
} else {
isProcessingRewindFrame = true
Task { [weak self] in
await RewindIndexer.shared.processFrame(frame)
await MainActor.run {
self?.isProcessingRewindFrame = false
}
}
}
}
} else {
// Track capture failures
consecutiveFailures += 1
lastCaptureSucceeded = false
// Log first failure and every 5th failure to avoid spam
if consecutiveFailures == 1 || consecutiveFailures % 5 == 0 {
log("ProactiveAssistantsPlugin: Capture failed (\(consecutiveFailures) consecutive), frontmost: \(getFrontmostAppInfo())")
}
if consecutiveFailures >= maxConsecutiveFailures {
handleRepeatedCaptureFailures()
}
}
}
// MARK: - Change-Gated Distribution
/// Distribute a frame to assistants only when context changed (app or window title),
/// with a 3-second debounce to let rapid switches settle, and a 60-second fallback
/// for periodic re-analysis within the same context.
private func distributeFrameIfChanged(_ frame: CapturedFrame) {
latestCapturedFrame = frame
// First frame after monitoring starts — distribute immediately, no debounce
if lastDistributedApp == nil {
flushDebouncedFrame()
return
}
let contextChanged = ContextDetection.didContextChange(
fromApp: lastDistributedApp,
fromWindowTitle: lastDistributedWindowTitle,
toApp: frame.appName,
toWindowTitle: frame.windowTitle
)
let timeSinceLastDistribution = Date().timeIntervalSince(lastDistributionTime)
let fallbackDue = timeSinceLastDistribution >= distributionFallbackInterval
if contextChanged {
// Update tracking immediately so subsequent captures in the same new context
// don't keep resetting the debounce timer (fixes starvation bug).
lastDistributedApp = frame.appName
lastDistributedWindowTitle = frame.windowTitle
// Restart the 3s debounce timer — fires 3s after the last context change
distributionDebounceTimer?.invalidate()
distributionDebounceTimer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: false) { [weak self] _ in
Task { @MainActor in
self?.flushDebouncedFrame()
}
}
} else if fallbackDue {
// Same context but fallback interval elapsed — distribute for periodic re-analysis
distributionDebounceTimer?.invalidate()
flushDebouncedFrame()
}
// Otherwise: same context, within fallback interval — skip distribution
}
/// Flush the latest captured frame to all assistants (called when debounce timer fires or fallback is due).
private func flushDebouncedFrame() {
guard let frame = latestCapturedFrame else { return }
lastDistributedApp = frame.appName
lastDistributedWindowTitle = frame.windowTitle
lastDistributionTime = Date()
distributionDebounceTimer = nil
AssistantCoordinator.shared.distributeFrame(frame)
}
// MARK: - Event Broadcasting
private func sendEvent(type: String, data: [String: Any]) {
var event = data
event["type"] = type
event["timestamp"] = ISO8601DateFormatter().string(from: Date())
// Post notification for any listeners
NotificationCenter.default.post(
name: .assistantEvent,
object: nil,
userInfo: event
)
}
// MARK: - Utility Methods
/// Open screen recording preferences
public func openScreenRecordingPreferences() {
ScreenCaptureService.openScreenRecordingPreferences()
}
/// Trigger glow effect manually (for testing)
func triggerGlow(colorMode: GlowColorMode = .focused) {
OverlayService.shared.showGlowAroundActiveWindow(colorMode: colorMode)
}
// MARK: - CLI Test Triggers
/// Listen for distributed notifications from CLI to trigger test runs
private func setupTestNotificationListeners() {
// Use selector-based observer (more reliable with DistributedNotificationCenter)
DistributedNotificationCenter.default().addObserver(
self,
selector: #selector(handleInsightTestNotification(_:)),
name: NSNotification.Name("com.omi.test.insight"),
object: nil
)
DistributedNotificationCenter.default().addObserver(
self,
selector: #selector(handleFocusTestNotification(_:)),
name: NSNotification.Name("com.omi.test.focus"),
object: nil
)
DistributedNotificationCenter.default().addObserver(
self,
selector: #selector(handleNotificationTestNotification(_:)),
name: NSNotification.Name("com.omi.test.notification"),
object: nil