forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesktopHomeView.swift
More file actions
1418 lines (1324 loc) · 59.7 KB
/
Copy pathDesktopHomeView.swift
File metadata and controls
1418 lines (1324 loc) · 59.7 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 AppKit
import OmiTheme
import SwiftUI
private struct AnySendableBox: @unchecked Sendable { let value: Any? }
/// Decides whether a persisted capture intent needs its runtime service restored.
///
/// Intent is stored independently from the running services. A fresh launch and a
/// settings sync therefore both need to reconcile the two states instead of using
/// a one-time readiness check as the source of truth.
enum PersistedCaptureLaunchPolicy {
static func shouldStartTranscription(intentEnabled: Bool, isTranscribing: Bool) -> Bool {
intentEnabled && !isTranscribing
}
static func shouldStartScreenAnalysis(intentEnabled: Bool, isMonitoring: Bool) -> Bool {
intentEnabled && !isMonitoring
}
}
// MARK: - NSHostingView sizingOptions access
/// Protocol to access sizingOptions on any NSHostingView<Content> regardless of the generic parameter.
/// NSHostingView is generic so we can't cast to it without knowing Content.
/// This protocol + extension lets us access sizingOptions through existential dispatch.
@MainActor
private protocol HostingSizingConfigurable: AnyObject {
var sizingOptions: NSHostingSizingOptions { get set }
}
extension NSHostingView: HostingSizingConfigurable {}
struct DesktopHomeView: View {
private let minimumWindowWidth: CGFloat = 1200
private let minimumWindowHeight: CGFloat = 680
private static let pageNavigationAnimation = Animation.easeOut(duration: 0.08)
@EnvironmentObject private var appState: AppState
@StateObject private var viewModelContainer = ViewModelContainer()
@ObservedObject private var authState = AuthState.shared
@ObservedObject private var apiKeyService = APIKeyService.shared
@ObservedObject private var updatePolicyManager = DesktopUpdatePolicyManager.shared
@ObservedObject private var automationPresentationCoordinator =
DesktopAutomationPresentationCoordinator.shared
@State private var selectedIndex: Int = {
if OMIApp.launchMode == .rewind { return SidebarNavItem.rewind.rawValue }
let tier = UserDefaults.standard.integer(forKey: "currentTierLevel")
return SidebarNavItem.dashboard.rawValue
}()
@State private var isSidebarCollapsed: Bool = true
@AppStorage("currentTierLevel") private var currentTierLevel = 0
@AppStorage("onboardingStep") private var onboardingStep = 0
@AppStorage("onboardingFurthestStep") private var onboardingFurthestStep = 0
@AppStorage("onboardingJustCompleted") private var onboardingJustCompleted = false
@AppStorage("useLegacyHomeDesign") private var useLegacyHomeDesign = false
/// Reference instant for the top bar's "new since you were last here" counts —
/// updated to now whenever Omi resigns front (see the didResignActive handler).
@AppStorage("topBarNewSince") private var topBarNewSinceRaw: Double = 0
// Settings sidebar state
@State private var selectedSettingsSection: SettingsContentView.SettingsSection = .general
@State private var highlightedSettingId: String? = nil
@State private var showTryAskingPopup = false
@State private var previousIndexBeforeSettings: Int = 0
@State private var logoPulse = false
@State private var lastActivationRefresh = Date.distantPast
@State private var didScheduleAgentVMProvisioning = false
@State private var proactiveMonitoringStartGate = RetryableDelayedStartGate()
@State private var isWaitingForScreenAnalysisKeys = false
// Anchor for the proactive-monitoring warmup budget. Captured at view
// creation (≈ launch) so the delay is spent once per session, not once per
// trigger — see StartupWarmupPolicy.remainingProactiveAssistantsStartDelay.
@State private var proactiveMonitoringWarmupAnchor = Date()
@State private var didScheduleConversationWarmup = false
@State private var initialFileIndexingBackfill = DelayedFileIndexingBackfillState()
@State private var automationPresentationReadinessGate =
DesktopAutomationPresentationReadinessGate()
// Pre-loaded hero logo to avoid NSImage init crashes during SwiftUI body evaluation
private static let heroLogoImage: NSImage? = {
guard let url = Bundle.resourceBundle.url(forResource: "herologo", withExtension: "png"),
let data = try? Data(contentsOf: url)
else { return nil }
return NSImage(data: data)
}()
/// Whether we're currently viewing the settings page
private var isInSettings: Bool {
selectedIndex == SidebarNavItem.settings.rawValue
}
var body: some View {
Group {
if authState.isRestoringAuth {
// State 0: Restoring auth session - show loading
VStack(spacing: OmiSpacing.lg) {
if let nsImage = Self.heroLogoImage {
Image(nsImage: nsImage)
.resizable()
.scaledToFit()
.frame(width: 64, height: 64)
}
ProgressView()
.scaleEffect(0.8)
.tint(.white.opacity(0.6))
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear {
log("DesktopHomeView: Showing auth loading splash")
}
} else if authState.sessionPhase == .recoveryRequired {
SessionRecoveryView()
.onAppear {
log("DesktopHomeView: Showing recoverable auth state")
}
} else if !authState.isSignedIn {
// State 1: Not signed in - show sign in
SignInView(authState: authState)
.onAppear {
log("DesktopHomeView: Showing SignInView (not signed in)")
}
} else if !appState.hasCompletedOnboarding {
// State 2: Signed in but onboarding not complete
if shouldSkipOnboarding() {
Color.clear.onAppear {
log("DesktopHomeView: --skip-onboarding flag detected, skipping onboarding")
appState.hasCompletedOnboarding = true
}
} else {
SBOnboardingView(
appState: appState, chatProvider: viewModelContainer.chatProvider, onComplete: nil
)
.onAppear {
log("DesktopHomeView: Showing SBOnboardingView (signed in, not onboarded)")
}
}
} else {
// State 3: Signed in and onboarded - show main content
ZStack {
// After onboarding completes, navigate to Tasks page
Color.clear
.frame(width: 0, height: 0)
.onAppear {
if UserDefaults.standard.bool(forKey: "onboardingJustCompleted") {
UserDefaults.standard.removeObject(forKey: "onboardingJustCompleted")
log("DesktopHomeView: Onboarding just completed — landing on Home")
// Land on Home in the chat-first layout with the old rail collapsed.
selectedIndex = SidebarNavItem.dashboard.rawValue
isSidebarCollapsed = true
}
}
mainContent
.opacity(viewModelContainer.isInitialLoadComplete ? 1 : 0)
.overlay {
if appState.showUsageLimitPopup {
UsageLimitPopupView(
reason: appState.usageLimitReason,
onUpgrade: {
appState.showUsageLimitPopup = false
selectedSettingsSection = .planUsage
// Plan and Usage now lives below Account on the merged
// "Account & Plan" page — scroll straight to the plan card.
highlightedSettingId = "planusage.current"
OmiMotion.withGated(Self.pageNavigationAnimation) {
selectedIndex = SidebarNavItem.settings.rawValue
}
},
onDismiss: {
appState.showUsageLimitPopup = false
},
onBringYourOwnKeys: {
appState.showUsageLimitPopup = false
selectedSettingsSection = .advanced
OmiMotion.withGated(Self.pageNavigationAnimation) {
selectedIndex = SidebarNavItem.settings.rawValue
}
}
)
}
}
.overlay(alignment: .top) {
if let policy = updatePolicyManager.visiblePolicy, !policy.isRequired {
DesktopUpdatePolicyBanner(
policy: policy,
onDownload: { updatePolicyManager.openDownload(policy) },
onDismiss: { updatePolicyManager.dismiss(policy) }
)
.padding(.top, OmiSpacing.md)
.padding(.horizontal, OmiSpacing.xl)
.transition(.move(edge: .top).combined(with: .opacity))
}
}
.onReceive(NotificationCenter.default.publisher(for: .showUsageLimitPopup)) { notification in
let reason = notification.userInfo?["reason"] as? String ?? ""
appState.triggerUsageLimitPopup(reason: reason)
}
.onAppear {
log("DesktopHomeView: Showing mainContent (signed in and onboarded)")
updatePolicyManager.refresh(force: true)
// Check all permissions on launch
appState.checkAllPermissions()
// For existing users who haven't indexed files yet, run a background scan
if !AppBuild.usesLazyDevPermissions
&& !UserDefaults.standard.bool(forKey: "hasCompletedFileIndexing")
{
scheduleInitialFileIndexing()
}
// Migration: one-time reset for users whose screenAnalysisEnabled
// was incorrectly set to false by a bug in syncMonitoringState() that
// persisted false whenever monitoring stopped for any reason.
// v2: re-run because the root cause (syncMonitoringState disabling the
// setting) was only fixed in this release, so v1 users got re-broken.
let migrationKey = "screenAnalysisAutoStartFixed_v2"
if !UserDefaults.standard.bool(forKey: migrationKey) {
UserDefaults.standard.set(true, forKey: "screenAnalysisEnabled")
AssistantSettings.shared.screenAnalysisEnabled = true
UserDefaults.standard.set(true, forKey: migrationKey)
log(
"DesktopHomeView: Applied screenAnalysisAutoStart v2 migration — reset to enabled"
)
// Push true to server so syncFromServer() doesn't revert it
Task { await SettingsSyncManager.shared.syncToServer() }
}
// Named development bundles used to seed screen analysis off to
// avoid permission prompts. Screen capture no longer requests
// TCC during startup, so restore the default once: a granted
// named-bundle permission must actually begin storing frames.
let quietBundleCaptureMigrationKey = "screenAnalysisAutoStartFixed_v3"
if RewindCaptureState.shouldRepairQuietBundleCaptureDefault(
usesLazyDevPermissions: AppBuild.usesLazyDevPermissions,
migrationApplied: UserDefaults.standard.bool(forKey: quietBundleCaptureMigrationKey)
) {
AssistantSettings.shared.screenAnalysisEnabled = true
UserDefaults.standard.set(true, forKey: quietBundleCaptureMigrationKey)
log("DesktopHomeView: Restored screen capture default for quiet named bundle")
}
restorePersistedCaptureServices(reason: "launch")
// Start Crisp chat in background for notifications, scoped to the signed-in user
CrispManager.shared.start(
initialPollDelay: StartupWarmupPolicy.crispInitialPollDelay,
sessionUserId: UserDefaults.standard.string(forKey: "auth_userId")
)
// Set up floating control bar. Product invariant: normal signed-in
// launches must show the enabled bar immediately; hide-until-PTT is
// only for explicit onboarding/demo/minimal-mode contexts.
FloatingControlBarManager.shared.setup(
appState: appState, chatProvider: viewModelContainer.chatProvider)
FloatingControlBarManager.shared.presentForLaunch(context: .normalSignedInDesktop)
// Set up push-to-talk voice input
if let barState = FloatingControlBarManager.shared.barState {
PushToTalkManager.shared.setup(barState: barState)
}
}
.task {
// Trigger eager data loading when main content appears
await viewModelContainer.loadAllData()
scheduleConversationWarmup()
scheduleAgentVMProvisioning()
}
// Refresh conversations when app becomes active (e.g. switching back from another app)
.onReceive(
NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)
) { _ in
// Cooldown: only refresh conversations if last activation was 60+ seconds ago
let now = Date()
if PollingConfig.shouldAllowActivationRefresh(now: now, lastRefresh: lastActivationRefresh) {
lastActivationRefresh = now
Task { await appState.refreshConversations() }
}
updatePolicyManager.refresh()
// Reconcile persisted intent after returning from System Settings or
// after a runtime service stopped while the app was inactive.
restorePersistedCaptureServices(reason: "app active")
}
.onChange(of: apiKeyService.isLoaded) { _, loaded in
guard loaded else { return }
log("DesktopHomeView: API keys loaded — retrying deferred services")
restorePersistedCaptureServices(reason: "key load")
}
.onReceive(NotificationCenter.default.publisher(for: .assistantSettingsDidSyncFromServer)) { _ in
reconcileCaptureServicesAfterSettingsSync()
}
// Cmd+R: refresh all data (conversations, chat, tasks, memories)
.onReceive(NotificationCenter.default.publisher(for: .refreshAllData)) { _ in
Task { await appState.refreshConversations() }
}
// On sign-out: reset @AppStorage-backed onboarding flag and stop transcription.
// hasCompletedOnboarding must be set here (in a View) because @AppStorage
// on ObservableObject caches internally and ignores UserDefaults.removeObject().
// Stopping transcription here prevents FOREIGN KEY errors from an old
// transcription session writing to a new user's database.
.onReceive(NotificationCenter.default.publisher(for: .userDidSignOut)) { _ in
log(
"DesktopHomeView: userDidSignOut — resetting hasCompletedOnboarding and stopping transcription"
)
resetSessionScopedStartupWarmups(preserveCrispReadState: false)
appState.conversationRepository.reset()
appState.folders = []
appState.selectedFolderId = nil
appState.selectedDateFilter = nil
appState.showStarredOnly = false
appState.totalConversationsCount = nil
appState.conversationsError = nil
appState.isLoadingConversations = false
appState.isLoadingFolders = false
appState.hasCompletedOnboarding = false
appState.stopTranscription()
}
.onReceive(NotificationCenter.default.publisher(for: .resetOnboardingRequested)) { _ in
log(
"DesktopHomeView: resetOnboardingRequested — clearing live onboarding state for current app"
)
resetSessionScopedStartupWarmups(preserveCrispReadState: false)
appState.hasCompletedOnboarding = false
onboardingStep = 0
onboardingFurthestStep = 0
onboardingJustCompleted = false
appState.stopTranscription()
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in
log("DesktopHomeView: app terminating — cancelling startup warmups")
resetSessionScopedStartupWarmups(preserveCrispReadState: true)
}
// Handle transcription toggle from menu bar
.onReceive(NotificationCenter.default.publisher(for: .toggleTranscriptionRequested)) {
notification in
if let enabled = notification.userInfo?["enabled"] as? Bool {
log("DesktopHomeView: Menu bar toggled transcription: \(enabled)")
if enabled {
appState.startTranscription()
} else {
appState.stopTranscription()
}
}
}
// Periodic file re-scan (every 3 hours)
.task {
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(3 * 60 * 60))
guard !Task.isCancelled else { break }
guard !AppBuild.usesLazyDevPermissions else { continue }
guard UserDefaults.standard.bool(forKey: "hasCompletedFileIndexing") else {
continue
}
log("DesktopHomeView: Triggering background file rescan")
await FileIndexerService.shared.backgroundRescan()
}
}
.onReceive(NotificationCenter.default.publisher(for: .triggerFileIndexing)) { _ in
// Background rescan — no loading screen needed
Task {
log(
"DesktopHomeView: File indexing triggered from settings, running background rescan"
)
await FileIndexerService.shared.backgroundRescan()
}
}
if !viewModelContainer.isInitialLoadComplete {
VStack(spacing: OmiSpacing.xxl) {
if let nsImage = Self.heroLogoImage {
Image(nsImage: nsImage)
.resizable()
.scaledToFit()
.frame(width: 72, height: 72)
.scaleEffect(logoPulse ? 1.08 : 1.0)
.opacity(logoPulse ? 1.0 : 0.7)
.omiAnimation(
.easeInOut(duration: 1.2).repeatForever(autoreverses: true),
value: logoPulse
)
.onAppear { logoPulse = true }
}
Text(viewModelContainer.initStatusMessage)
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(OmiColors.textTertiary)
ProgressView()
.scaleEffect(0.8)
.tint(OmiColors.accent.opacity(0.6))
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(OmiColors.backgroundPrimary)
.transition(.opacity.animation(OmiMotion.gated(.easeOut(duration: 0.3))))
}
if let policy = updatePolicyManager.visiblePolicy, policy.isRequired {
Color.black.opacity(0.62)
.ignoresSafeArea()
.zIndex(20)
DesktopRequiredUpdatePrompt(
policy: policy,
onDownload: { updatePolicyManager.openDownload(policy) }
)
.zIndex(21)
}
}
}
}
.background(OmiColors.backgroundPrimary)
.frame(minWidth: minimumWindowWidth, minHeight: minimumWindowHeight)
.preferredColorScheme(.dark)
.tint(OmiColors.accent)
.onAppear {
log(
"DesktopHomeView: View appeared - isSignedIn=\(authState.isSignedIn), hasCompletedOnboarding=\(appState.hasCompletedOnboarding)"
)
// Register Geist/Geist Mono for the sign-in + conversational onboarding surfaces.
// (Kept out of OmiApp to respect the product-file line-count ratchet.)
OmiFontRegistration.registerAll()
// Drive the notch "moments" (live receipts + conversation-end) off real state.
NotchMomentsCoordinator.shared.start(appState: appState)
// Force dark appearance and disable minSize computation on NSHostingView.
// By default, every @Published change triggers
// updateWindowContentSizeExtremaIfNecessary() → minSize() → sizeThatFits()
// which traverses the ENTIRE view tree (~200 samples per window per trigger).
// Removing .minSize from sizingOptions prevents this full-tree traversal.
// The window's min size is enforced at the AppKit level instead.
enforceMainWindowMinimumSize()
// SwiftUI's automatic resizability later re-derives the window min from content
// extrema and resets our pin, after which the window can be dragged small enough
// to hide content. Re-pin on every live resize so AppKit keeps clamping the drag.
installMinimumSizeGuardIfNeeded()
// Redirect if current page isn't visible at current tier
redirectIfPageHidden()
reportAutomationState()
handleAutomationPresentationReadinessChange(viewModelContainer.isInitialLoadComplete)
}
.onChange(of: currentTierLevel) { _, _ in
redirectIfPageHidden()
reportAutomationState()
}
.onChange(of: selectedIndex) { _, _ in
// Page nav recreates the content hosting view with default sizingOptions, which
// resets the window min — re-pin + re-disable to hold the minimum.
enforceMainWindowMinimumSize()
reportAutomationState()
}
.onChange(of: automationPresentationCoordinator.activeCommand?.generation) { _, _ in
guard
let command = automationPresentationReadinessGate.commandForConsumption(
automationPresentationCoordinator.activeCommand)
else { return }
handleAutomationPresentationCommand(command)
}
.onChange(of: viewModelContainer.isInitialLoadComplete) { _, isReady in
handleAutomationPresentationReadinessChange(isReady)
}
.onChange(of: selectedSettingsSection) { _, _ in reportAutomationState() }
.onChange(of: highlightedSettingId) { _, _ in reportAutomationState() }
.onChange(of: authState.isSignedIn) { _, _ in reportAutomationState() }
.onChange(of: authState.isRestoringAuth) { _, _ in reportAutomationState() }
.onChange(of: appState.hasCompletedOnboarding) { _, _ in reportAutomationState() }
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
enforceMainWindowMinimumSize()
reportAutomationState()
// First-run seed so the counter doesn't count the entire backlog as "new".
if topBarNewSinceRaw == 0 { topBarNewSinceRaw = Date().timeIntervalSince1970 }
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didResignActiveNotification)) { _ in
reportAutomationState()
// Mark the moment Omi went to the background; anything created after this
// shows in the top bar's "new since you were last here" counter.
topBarNewSinceRaw = Date().timeIntervalSince1970
}
.onReceive(NotificationCenter.default.publisher(for: .desktopAutomationNavigateRequested)) {
notification in
handleAutomationNavigation(notification)
}
.onReceive(NotificationCenter.default.publisher(for: .navigateToChat)) { _ in
// The global shortcut / notch "Ask Omi" opens the continuous chat, which
// lives on the chat-first home. DashboardPage focuses the input when it's
// already mounted; if we're on another tab, switch home first and re-emit
// so the now-mounted page catches it. Guard on the tab to avoid a loop.
if selectedIndex != SidebarNavItem.dashboard.rawValue {
selectedIndex = SidebarNavItem.dashboard.rawValue
DispatchQueue.main.async {
NotificationCenter.default.post(name: .navigateToChat, object: nil)
}
}
}
// "Continue in Omi" from the floating bar: switch to the Home tab; the
// dashboard consumes the pending request and opens the chat panel.
.onReceive(NotificationCenter.default.publisher(for: .openMainChatRequested)) { _ in
selectedIndex = SidebarNavItem.dashboard.rawValue
}
}
private func enforceMainWindowMinimumSize() {
let minimumContentSize = NSSize(width: minimumWindowWidth, height: minimumWindowHeight)
DispatchQueue.main.async {
for window in NSApp.windows where window.title.lowercased().hasPrefix("omi") {
window.appearance = NSAppearance(named: .darkAqua)
window.contentMinSize = minimumContentSize
window.minSize = window.frameRect(forContentRect: NSRect(origin: .zero, size: minimumContentSize)).size
let currentContentSize = window.contentView?.bounds.size ?? window.contentLayoutRect.size
let widthDelta = max(0, minimumContentSize.width - currentContentSize.width)
let heightDelta = max(0, minimumContentSize.height - currentContentSize.height)
if widthDelta > 0 || heightDelta > 0 {
var frame = window.frame
frame.size.width += widthDelta
frame.size.height += heightDelta
frame.origin.y -= heightDelta
window.setFrame(frame, display: true, animate: false)
}
// Remove .minSize from hosting view's sizingOptions.
// Search contentView itself + all descendants.
Self.disableMinSizeComputation(in: window)
}
}
}
/// Re-pin the window minimum on every live resize. SwiftUI's `.automatic` window
/// resizability periodically recomputes content-size extrema and overwrites the
/// one-shot pin from `enforceMainWindowMinimumSize()`, after which the window can be
/// dragged small enough to hide content. Observing `didResize` and re-pinning keeps
/// AppKit clamping the live drag at the minimum. Installed once for the app's lifetime.
private static var minimumSizeGuardInstalled = false
private func installMinimumSizeGuardIfNeeded() {
guard !Self.minimumSizeGuardInstalled else { return }
Self.minimumSizeGuardInstalled = true
let minimumContentSize = NSSize(width: minimumWindowWidth, height: minimumWindowHeight)
NotificationCenter.default.addObserver(
forName: NSWindow.didResizeNotification, object: nil, queue: .main
) { notification in
let objectBox = AnySendableBox(value: notification.object)
MainActor.assumeIsolated {
guard let window = objectBox.value as? NSWindow,
window.title.lowercased().hasPrefix("omi")
else { return }
let frameMin = window.frameRect(
forContentRect: NSRect(origin: .zero, size: minimumContentSize)
).size
if window.contentMinSize != minimumContentSize { window.contentMinSize = minimumContentSize }
if window.minSize != frameMin { window.minSize = frameMin }
}
}
}
/// Recursively find all NSHostingViews in a window and set sizingOptions to [],
/// disabling ALL size computations to prevent full-tree sizeThatFits() traversals.
/// Window min/max sizes are enforced at the AppKit level via NSWindow.minSize instead.
/// NOTE: ClickThroughHostingView is excluded because it wraps the sidebar and needs
/// intrinsicContentSize for SwiftUI's .fixedSize() layout to compute the correct width.
private static func disableMinSizeComputation(in window: NSWindow) {
func visit(_ view: NSView) {
if let hosting = view as? any HostingSizingConfigurable {
// Skip ClickThroughHostingView — it's an NSViewRepresentable boundary
// that needs intrinsicContentSize for the sidebar's .fixedSize() to work.
let typeName = String(describing: type(of: view))
guard !typeName.contains("ClickThroughHostingView") else {
// Still visit children
for subview in view.subviews { visit(subview) }
return
}
let before = hosting.sizingOptions
if before != [] {
hosting.sizingOptions = []
}
}
for subview in view.subviews {
visit(subview)
}
}
if let contentView = window.contentView {
visit(contentView)
}
}
/// Redirect to conversations if current page isn't visible at the current tier level
private func redirectIfPageHidden() {
// Tier 0 or tier 6+ shows everything — no redirect needed
guard currentTierLevel > 0 && currentTierLevel < 6 else { return }
// Don't redirect from settings/permissions/help pages
let nonMainPages: Set<Int> = [
SidebarNavItem.settings.rawValue, SidebarNavItem.permissions.rawValue,
SidebarNavItem.help.rawValue,
]
guard !nonMainPages.contains(selectedIndex) else { return }
var visibleRawValues: Set<Int> = [
SidebarNavItem.dashboard.rawValue, SidebarNavItem.rewind.rawValue,
]
if currentTierLevel >= 2 { visibleRawValues.insert(SidebarNavItem.memories.rawValue) }
if currentTierLevel >= 3 { visibleRawValues.insert(SidebarNavItem.tasks.rawValue) }
// Conversations replaced Chat in the sidebar; tier 1 unlocks it.
if currentTierLevel >= 1 { visibleRawValues.insert(SidebarNavItem.conversations.rawValue) }
if !visibleRawValues.contains(selectedIndex) {
selectedIndex = SidebarNavItem.dashboard.rawValue
}
}
/// Whether to hide the sidebar (rewind mode)
private var hideSidebar: Bool {
OMIApp.launchMode == .rewind
}
private var showsPrimarySidebar: Bool {
useLegacyHomeDesign && !hideSidebar
}
/// The constant floating top bar (nav + new-item counts + Capture/Listening)
/// replaces the old left nav rail. It shows on every main content page —
/// including Settings, whose page has no back button, so the bar's nav pills
/// are the way out. Permissions/help are full-screen utility flows with their
/// own chrome and stay bar-less.
private var showsTopBar: Bool {
guard !useLegacyHomeDesign, let item = SidebarNavItem(rawValue: selectedIndex) else { return false }
return ![.permissions, .help].contains(item)
}
/// Reference instant for the top bar's "new since you were last here" counts.
private var topBarSinceDate: Date {
topBarNewSinceRaw > 0 ? Date(timeIntervalSince1970: topBarNewSinceRaw) : Date()
}
private var currentAppStateLabel: String {
if authState.isRestoringAuth { return "restoring_auth" }
if authState.sessionPhase == .recoveryRequired { return "auth_recovery" }
if !authState.isSignedIn { return "signed_out" }
if !appState.hasCompletedOnboarding { return "onboarding" }
return "main"
}
private func reportAutomationState() {
guard DesktopAutomationLaunchOptions.isEnabled else { return }
let currentWindow = NSApp.windows.first(where: {
$0.title.lowercased().hasPrefix("omi") && $0.isVisible
})
let onDashboard = selectedIndex == SidebarNavItem.dashboard.rawValue
let priorHomeMode = DesktopAutomationStateStore.shared.current().homeMode
let snapshot = DesktopAutomationSnapshot(
bridgeEnabled: true,
bridgePort: DesktopAutomationLaunchOptions.port,
bundleIdentifier: Bundle.main.bundleIdentifier ?? "unknown",
appState: currentAppStateLabel,
selectedTab: SidebarNavItem(rawValue: selectedIndex)?.title,
selectedTabIndex: selectedIndex,
selectedSettingsSection: isInSettings ? selectedSettingsSection.rawValue : nil,
highlightedSettingId: highlightedSettingId,
usesLegacyHomeDesign: useLegacyHomeDesign,
homeMode: onDashboard && !useLegacyHomeDesign ? (priorHomeMode ?? "hub") : nil,
showsPrimarySidebar: showsPrimarySidebar,
isSidebarCollapsed: isSidebarCollapsed,
hasCompletedOnboarding: appState.hasCompletedOnboarding,
isSignedIn: authState.isSignedIn,
isRestoringAuth: authState.isRestoringAuth,
isAppActive: NSApp.isActive,
mainWindowTitle: currentWindow?.title,
floatingBarVisible: FloatingControlBarManager.shared.automationState.isVisible,
askOmiOpen: FloatingControlBarManager.shared.automationState.isAskOmiOpen,
askOmiFocused: FloatingControlBarManager.shared.automationState.isAskOmiFocused,
floatingBarFrame: FloatingControlBarManager.shared.automationState.frame,
floatingBarVoiceListening: FloatingControlBarManager.shared.automationState.isVoiceListening,
floatingBarVoiceResponseActive: FloatingControlBarManager.shared.automationState.isVoiceResponseActive,
floatingBarUsesNotchIsland: FloatingControlBarManager.shared.automationState.usesNotchIsland,
updatedAt: ISO8601DateFormatter().string(from: Date())
)
DesktopAutomationStateStore.shared.update(snapshot)
}
private func handleAutomationNavigation(_ notification: Notification) {
guard DesktopAutomationLaunchOptions.isEnabled else { return }
guard let target = notification.userInfo?["target"] as? String else { return }
let settingsSectionRaw = notification.userInfo?["settingsSection"] as? String
let settingId = notification.userInfo?["highlightedSettingId"] as? String
let activateApp = notification.userInfo?["activateApp"] as? Bool ?? true
if activateApp {
NSApp.activate()
if let window = NSApp.windows.first(where: { $0.title.lowercased().hasPrefix("omi") }) {
window.makeKeyAndOrderFront(nil)
}
}
if let sectionRaw = settingsSectionRaw {
// Tolerant match (SET-01): omi-ctl sends the caller's casing verbatim (docs use
// lowercase, raw values are Title Case), so a strict rawValue init silently left
// navigation on General for every sub-section command.
if let section = SettingsContentView.SettingsSection.automationMatch(sectionRaw) {
selectedSettingsSection = section
} else {
log("AutomationNavigation: unknown settings section '\(sectionRaw)'")
}
}
highlightedSettingId = settingId
if let item = resolvedAutomationTarget(target) {
selectedIndex = item.rawValue
}
reportAutomationState()
}
private func handleAutomationPresentationCommand(
_ command: DesktopAutomationPresentationCommand
) {
NSApp.activate()
if let window = NSApp.windows.first(where: { $0.title.lowercased().hasPrefix("omi") }) {
window.makeKeyAndOrderFront(nil)
}
selectedIndex = SidebarNavItem.apps.rawValue
reportAutomationState()
}
private func handleAutomationPresentationReadinessChange(_ isReady: Bool) {
guard
let command = automationPresentationReadinessGate.transition(
to: isReady,
activeCommand: automationPresentationCoordinator.activeCommand)
else { return }
handleAutomationPresentationCommand(command)
}
private func resolvedAutomationTarget(_ target: String) -> SidebarNavItem? {
let normalized = target.lowercased().replacingOccurrences(of: "-", with: "_")
switch normalized {
case "dashboard", "home":
return .dashboard
case "conversations":
return .conversations
case "chat":
return .chat
case "memories":
return .memories
case "tasks":
return .tasks
case "focus":
return .focus
case "insight":
return .insight
case "rewind":
return .rewind
case "apps", "integrations":
return .apps
case "settings":
return .settings
case "permissions":
return .permissions
case "help":
return .help
default:
return nil
}
}
/// Update store auto-refresh based on which page is visible
/// On launch, if the user quit with the task chat panel open, macOS restores the
/// expanded window frame but the chat panel itself is not shown. Shrink the window
/// back to its pre-chat width so the layout isn't unexpectedly wide.
private func restorePreChatWindowWidth() {
let key = "tasksPreChatWindowWidth"
let saved = UserDefaults.standard.double(forKey: key)
guard saved > 0 else { return }
// Reset the persisted value immediately so TasksPage won't double-shrink
UserDefaults.standard.set(Double(0), forKey: key)
// Delay slightly so the window is fully visible
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
guard let window = NSApp.windows.first(where: { $0.title.hasPrefix("Omi") && $0.isVisible })
else { return }
var frame = window.frame
frame.size.width = saved
window.setFrame(frame, display: true)
}
}
private func resetSessionScopedStartupWarmups(preserveCrispReadState: Bool) {
viewModelContainer.resetStartupState()
didScheduleConversationWarmup = false
didScheduleAgentVMProvisioning = false
proactiveMonitoringStartGate.finishAttempt()
initialFileIndexingBackfill.releaseReservation()
CrispManager.shared.stop(preserveReadState: preserveCrispReadState)
}
private func scheduleAgentVMProvisioning() {
guard !didScheduleAgentVMProvisioning else { return }
didScheduleAgentVMProvisioning = true
let scheduled = viewModelContainer.scheduleSessionWarmup(
id: .agentVMProvisioning,
delay: StartupWarmupPolicy.agentVMProvisioningDelay,
onCancel: { didScheduleAgentVMProvisioning = false }
) {
await AgentVMService.shared.ensureProvisioned()
}
if !scheduled { didScheduleAgentVMProvisioning = false }
}
private func scheduleConversationWarmup() {
guard !didScheduleConversationWarmup else { return }
didScheduleConversationWarmup = true
let scheduled = viewModelContainer.scheduleSessionWarmup(
id: .conversationWarmup,
delay: StartupWarmupPolicy.conversationWarmupDelay,
onCancel: { didScheduleConversationWarmup = false }
) {
async let conversations: Void = loadConversationsIfNeeded()
async let folders: Void = loadFoldersIfNeeded()
// Warm memories + tasks too so the top bar's new-item counter has data
// even before those tabs are visited.
async let memories: Void = viewModelContainer.memoriesViewModel.loadMemoriesIfNeeded()
async let tasks: Void = viewModelContainer.tasksStore.loadTasksIfNeeded()
_ = await (conversations, folders, memories, tasks)
}
if !scheduled { didScheduleConversationWarmup = false }
}
private func loadConversationsIfNeeded() async {
guard appState.conversations.isEmpty else { return }
await appState.loadConversations()
}
private func loadFoldersIfNeeded() async {
guard appState.folders.isEmpty else { return }
await appState.loadFolders()
}
private func scheduleInitialFileIndexing() {
guard
initialFileIndexingBackfill.reserveIfNeeded(
hasCompletedBackfill: UserDefaults.standard.bool(forKey: "hasCompletedFileIndexing"))
else { return }
let sessionScope = StartupWarmupSessionScope(
userId: UserDefaults.standard.string(forKey: "auth_userId"))
let scheduled = viewModelContainer.scheduleSessionWarmup(
id: .initialFileIndexing,
delay: StartupWarmupPolicy.initialFileIndexingDelay,
onCancel: { initialFileIndexingBackfill.releaseReservation() }
) {
log("DesktopHomeView: Running delayed background file scan for existing user")
await FileIndexerService.shared.backgroundRescan()
guard !Task.isCancelled,
sessionScope.matches(
currentUserId: UserDefaults.standard.string(forKey: "auth_userId"),
isSignedIn: AuthState.shared.isSignedIn)
else {
initialFileIndexingBackfill.releaseReservation()
return
}
initialFileIndexingBackfill.markScanCompleted()
if initialFileIndexingBackfill.shouldMarkComplete {
UserDefaults.standard.set(true, forKey: "hasCompletedFileIndexing")
log(
"DesktopHomeView: Marked existing-user file indexing backfill complete after background scan returned"
)
}
}
if !scheduled { initialFileIndexingBackfill.releaseReservation() }
}
private func scheduleProactiveMonitoringStart(reason: String) {
guard proactiveMonitoringStartGate.reserve() else { return }
let delay = StartupWarmupPolicy.remainingProactiveAssistantsStartDelay(
elapsedSinceLaunch: Date().timeIntervalSince(proactiveMonitoringWarmupAnchor))
log(
"DesktopHomeView: Scheduling screen analysis start in \(String(format: "%.1f", delay))s (\(reason))"
)
let scheduled = viewModelContainer.scheduleSessionWarmup(
id: .proactiveAssistantsStart,
delay: delay,
onCancel: { proactiveMonitoringStartGate.finishAttempt() }
) {
let plugin = ProactiveAssistantsPlugin.shared
guard AssistantSettings.shared.screenAnalysisEnabled, !plugin.isMonitoring else {
proactiveMonitoringStartGate.finishAttempt()
return
}
guard APIKeyService.keysAvailable else {
proactiveMonitoringStartGate.finishAttempt()
log("DesktopHomeView: Screen analysis still deferred after \(reason) — API keys not yet loaded")
return
}
plugin.startMonitoring { success, error in
Task { @MainActor in
proactiveMonitoringStartGate.finishAttempt()
if success {
log("DesktopHomeView: Screen analysis started (\(reason), delayed)")
} else {
log(
"DesktopHomeView: Screen analysis failed to start (\(reason)): \(error ?? "unknown") — setting remains enabled for next launch"
)
}
}
}
}
if !scheduled { proactiveMonitoringStartGate.finishAttempt() }
}
private func restorePersistedCaptureServices(reason: String) {
let settings = AssistantSettings.shared
if PersistedCaptureLaunchPolicy.shouldStartTranscription(
intentEnabled: settings.transcriptionEnabled,
isTranscribing: appState.isTranscribing
) {
log("DesktopHomeView: Restoring transcription from persisted intent (\(reason))")
// Local transcription does not require remote API keys. AppState owns the
// permission and provider checks, so it remains the single start boundary.
appState.startTranscription()
}
let plugin = ProactiveAssistantsPlugin.shared
guard
PersistedCaptureLaunchPolicy.shouldStartScreenAnalysis(
intentEnabled: settings.screenAnalysisEnabled,
isMonitoring: plugin.isMonitoring
)
else { return }
guard APIKeyService.keysAvailable else {
waitForScreenAnalysisKeys(reason: reason)
return
}
plugin.refreshScreenRecordingPermission()
guard plugin.hasScreenRecordingPermission else {
log("DesktopHomeView: Screen recording permission unavailable; retaining capture intent (\(reason))")
return
}
scheduleProactiveMonitoringStart(reason: reason)
}
private func waitForScreenAnalysisKeys(reason: String) {
guard !isWaitingForScreenAnalysisKeys else { return }
isWaitingForScreenAnalysisKeys = true
log("DesktopHomeView: Deferring screen analysis until API keys load (\(reason))")
Task { @MainActor in
await APIKeyService.shared.waitForKeys()
isWaitingForScreenAnalysisKeys = false
guard APIKeyService.keysAvailable else {
log("DesktopHomeView: API keys remain unavailable; retaining capture intent")
return
}
restorePersistedCaptureServices(reason: "key wait completed")
}
}
private func reconcileCaptureServicesAfterSettingsSync() {
let plugin = ProactiveAssistantsPlugin.shared
if !AssistantSettings.shared.screenAnalysisEnabled, plugin.isMonitoring {
log("DesktopHomeView: Stopping screen analysis after server settings sync")
plugin.stopMonitoring()
}
restorePersistedCaptureServices(reason: "settings sync")
}
private func updateStoreActivity(for index: Int) {
viewModelContainer.tasksStore.isActive =
index == SidebarNavItem.dashboard.rawValue || index == SidebarNavItem.tasks.rawValue
viewModelContainer.memoriesViewModel.isActive =
index == SidebarNavItem.memories.rawValue
}
private var mainContent: some View {
HStack(spacing: 0) {
// Sidebar slot: settings sidebar overlays main sidebar
// IMPORTANT: SidebarView is kept alive (but hidden) when in settings to prevent
// EXC_BAD_ACCESS crash in SwiftUI's tooltip system. When the view is conditionally
// removed, its .help() tooltip graph nodes get invalidated, but the macOS tooltip
// tracking system still tries to evaluate them during window key state changes.
if isInSettings {
ZStack {
if showsPrimarySidebar {
SidebarView(
selectedIndex: $selectedIndex,
isCollapsed: $isSidebarCollapsed,
appState: appState
)
.opacity(0)
.allowsHitTesting(false)
}
SettingsSidebar(
selectedSection: $selectedSettingsSection,
highlightedSettingId: $highlightedSettingId,
onBack: {
OmiMotion.withGated(Self.pageNavigationAnimation) {
selectedIndex =
previousIndexBeforeSettings == SidebarNavItem.settings.rawValue
? SidebarNavItem.dashboard.rawValue
: previousIndexBeforeSettings
}