-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathWindowState.swift
More file actions
1389 lines (1188 loc) · 52.6 KB
/
Copy pathWindowState.swift
File metadata and controls
1389 lines (1188 loc) · 52.6 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 Combine
import Foundation
import SwiftUI
enum WindowKind: String, Codable {
case standard
case contextBuilder
init(from decoder: Decoder) throws {
let rawValue = try decoder.singleValueContainer().decode(String.self)
switch rawValue {
case Self.standard.rawValue:
self = .standard
case Self.contextBuilder.rawValue, "discoverAgent":
self = .contextBuilder
default:
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Unknown window kind: \(rawValue)"
)
)
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(rawValue)
}
}
enum WindowTitleFormatter {
/// Default window title when no user workspace is active.
/// Mirrors the app's display name so window and tab titles match the running distribution.
static let defaultTitle: String = {
let info = Bundle.main.infoDictionary
let candidates = [info?["CFBundleDisplayName"] as? String, info?["CFBundleName"] as? String]
let resolved = candidates
.compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
.first { !$0.isEmpty }
return resolved ?? "RepoPrompt CE"
}()
static func compose(
workspaceTitle: String,
agentSessionTitle: String?,
duplicateWorkspaceTitle: String? = nil
) -> String {
let trimmedSessionTitle = agentSessionTitle?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !trimmedSessionTitle.isEmpty else { return workspaceTitle }
let duplicateTitles = [workspaceTitle, duplicateWorkspaceTitle]
.compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
guard !duplicateTitles.contains(where: { trimmedSessionTitle.caseInsensitiveCompare($0) == .orderedSame }) else {
return workspaceTitle
}
return "\(trimmedSessionTitle) — \(workspaceTitle)"
}
}
enum PendingInteractionSurface {
case contextualQuestion
case agentQuestion
}
/// Represents a command from CLI or URL
struct AppCommand {
let workspaceName: String?
let fileList: [String]
let promptText: String?
let folderPath: String?
/// NEW: prompt that should be saved to `PromptViewModel`
let newPrompt: (title: String, content: String)?
/// When true, attempt to focus an existing window for the given workspace/folder if already open.
let focus: Bool?
/// When true, do not persist this workspace to disk/index (only keep in memory).
/// If set, you can treat this as "ephemeral" usage.
let ephemeral: Bool?
/// When false, skip saving changes to disk/index. If nil or true, persist by default.
let persist: Bool?
var isEmpty: Bool {
workspaceName == nil
&& fileList.isEmpty
&& promptText == nil
&& folderPath == nil
&& newPrompt == nil // <- include new field
&& focus == nil
&& ephemeral == nil
&& persist == nil
}
}
/// Holds all of the per-window managers/services.
/// Each new window in the app gets a fresh instance of WindowState.
@MainActor
class WindowState: ObservableObject {
// MARK: - Shared Services
/// Single shared MCP service instance across all windows
private static let sharedMCPService = MCPService()
// MARK: - Window identification
private(set) static var windowCounter = 0
let windowID: Int
@Published var kind: WindowKind = .standard
// MARK: - Focus Tracking
@Published var isCurrentlyFocused: Bool = false
/// Per-window teardown guard. Not @Published (we don't want SwiftUI updates during teardown).
private(set) var isClosing: Bool = false
private var focusCancellables = Set<AnyCancellable>()
private weak var focusObservedWindow: NSWindow?
/// Holds Combine subscriptions local to this window state
private var cancellables = Set<AnyCancellable>()
/// Called whenever `isCurrentlyFocused` changes.
var onFocusChanged: ((Bool) -> Void)?
// MARK: - Per-Window View Models
let workspaceFileContextStore: WorkspaceFileContextStore
let workspaceSearchService: WorkspaceSearchService
let selectionCoordinator: WorkspaceSelectionCoordinator
let workspaceFilesViewModel: WorkspaceFilesViewModel
let settingsManager: WindowSettingsManager
let promptManager: PromptViewModel
let oracleViewModel: OracleViewModel
let apiSettingsViewModel: APISettingsViewModel
let contextBuilderAgentViewModel: ContextBuilderAgentViewModel
let agentModeViewModel: AgentModeViewModel
#if DEBUG
let agentChatStressHarness: AgentChatStressHarness?
#endif
// MARK: - MCP Server (one per window)
let mcpServer: MCPServerViewModel
let closeCoordinator: WindowCloseCoordinator
// MARK: - Services and Utilities
let keyManager: KeyManager
let aiQueriesService: AIQueriesService
let chatDataService: ChatDataService
// MARK: - Possibly shared references
let workspaceManager: WorkspaceManagerViewModel
weak var windowStatesManager: WindowStatesManager?
/// Reference to the NSWindow this state is associated with
weak var nsWindow: NSWindow?
private var windowDelegateProxy: InterceptingWindowDelegateProxy?
// MARK: - Agent Mode Titlebar Accessory
/// Titlebar accessory controller for Agent mode ("New Session" button near traffic lights)
private weak var agentTitlebarAccessory: AgentModeTitlebarAccessoryViewController?
/// Whether Agent mode has requested the titlebar accessory be visible
private var wantsAgentTitlebarAccessory: Bool = false
/// Action to call when the "New Session" button is tapped
private var agentNewSessionAction: (() -> Void)?
/// The sticky instance number assigned for this window's current workspace (monotonically increasing per workspace).
/// Nil when no workspace is active yet.
@Published var workspaceInstanceNumber: Int? = nil
/// Convenience: the workspace name with an instance suffix " (N)" when N ≥ 2,
/// except for the default/system workspace which always shows the app name.
var workspaceDisplayName: String {
guard let ws = workspaceManager.activeWorkspace else {
return WindowTitleFormatter.defaultTitle
}
if ws.isSystemWorkspace {
return WindowTitleFormatter.defaultTitle
}
let base = ws.name
if let n = workspaceInstanceNumber, n >= 2 {
return "\(base) (\(n))"
}
return base
}
/// Source of truth for the SwiftUI scene title (window title and native tab name).
/// Published so the scene keeps re-applying it; otherwise SwiftUI falls back to the
/// app display name whenever it refreshes the window chrome.
@Published private(set) var displayedWindowTitle: String = WindowTitleFormatter.defaultTitle
// Cache to survive transient activeWorkspace == nil. This may include Agent session context.
private var lastKnownResolvedTitle: String = WindowTitleFormatter.defaultTitle
private var lastAppliedWindowTitle: String?
private func resolvedWindowTitle() -> String {
guard let ws = workspaceManager.activeWorkspace else {
// If we expect a workspace but it is temporarily unresolved, do not stomp to default.
if workspaceManager.activeWorkspaceID != nil {
return lastKnownResolvedTitle
}
return WindowTitleFormatter.defaultTitle
}
let workspaceTitle = resolvedWorkspaceWindowTitle(for: ws)
let resolvedTitle = WindowTitleFormatter.compose(
workspaceTitle: workspaceTitle,
agentSessionTitle: resolvedAgentSessionTitleForWindowTitle(activeWorkspace: ws),
duplicateWorkspaceTitle: ws.isSystemWorkspace ? WindowTitleFormatter.defaultTitle : ws.name
)
lastKnownResolvedTitle = resolvedTitle
return resolvedTitle
}
private func resolvedWorkspaceWindowTitle(for workspace: WorkspaceModel) -> String {
if workspace.isSystemWorkspace {
return WindowTitleFormatter.defaultTitle
}
let base = workspace.name
if let n = workspaceInstanceNumber, n >= 2 {
return "\(base) (\(n))"
}
return base
}
private func resolvedAgentSessionTitleForWindowTitle(activeWorkspace: WorkspaceModel) -> String? {
guard !activeWorkspace.isSystemWorkspace,
promptManager.activeComposeTabID != nil
else {
return nil
}
let rawTitle = promptManager.activeComposeTabID.flatMap { workspaceManager.composeTabName(with: $0) }
return AgentSessionRestoreSupport.normalizedSessionTitle(rawTitle)
}
enum WindowTitleUpdateReason {
case windowAttached
case workspaceChanged
case focusChanged
case appBecameActive
case activeComposeTabChanged
case agentSessionNameChanged
case explicit
case unspecified
}
/// Command queue to store all pending commands
private var commandQueue: [AppCommand] = []
/// Lazily scheduled task to coalesce window title updates outside of mutation scopes.
private var pendingWindowTitleUpdateTask: Task<Void, Never>?
/// Lazily scheduled task to coalesce focus updates outside of mutation scopes.
private var pendingFocusUpdateTask: Task<Void, Never>?
/// Lazily scheduled task to coalesce focus side-effects outside of mutation scopes.
private var pendingFocusSideEffectsTask: Task<Void, Never>?
private var shouldSuppressObservationSideEffects: Bool {
// Avoid SwiftUI observation churn during teardown/termination.
isClosing || WindowStatesManager.shared.isTerminating
}
func beginClose() {
guard !isClosing else { return }
isClosing = true
let manager = windowStatesManager ?? WindowStatesManager.shared
if !manager.isTerminating {
manager.markWindowAsExplicitlyClosing(windowID: windowID)
}
closeCoordinator.beginClose()
onFocusChanged = nil
removeFocusObservers()
pendingWindowTitleUpdateTask?.cancel()
pendingWindowTitleUpdateTask = nil
pendingFocusUpdateTask?.cancel()
pendingFocusUpdateTask = nil
pendingFocusSideEffectsTask?.cancel()
pendingFocusSideEffectsTask = nil
detachTitlebarAccessoryControllers(from: nsWindow)
clearTitlebarAccessoryRequestsForClose()
apiSettingsViewModel.prepareForWindowClose()
contextBuilderAgentViewModel.prepareForWindowClose()
workspaceManager.prepareForWindowClose()
promptManager.gitViewModel.prepareForWindowClose()
}
private var pendingRestoreEntry: WindowSessionEntry?
private(set) var claimedInitialRefreshDeferralID: UUID?
private(set) var claimedInitialRefreshDeferralWaiterID: UUID?
// MARK: - Initialization
convenience init() {
self.init(
contextBuilderProviderFactory: nil,
loadStoredAPISettingsDataOnInit: true,
codexModelPollingService: .shared
)
}
#if DEBUG
convenience init(contextBuilderProviderFactory: @escaping ContextBuilderAgentViewModel.ProviderFactory) {
self.init(
contextBuilderProviderFactory: Optional(contextBuilderProviderFactory),
loadStoredAPISettingsDataOnInit: true,
codexModelPollingService: .shared
)
}
convenience init(
codexModelPollingService: CodexModelPollingService,
loadStoredAPISettingsDataOnInit: Bool
) {
self.init(
contextBuilderProviderFactory: nil,
loadStoredAPISettingsDataOnInit: loadStoredAPISettingsDataOnInit,
codexModelPollingService: codexModelPollingService
)
}
#endif
private init(
contextBuilderProviderFactory: ContextBuilderAgentViewModel.ProviderFactory?,
loadStoredAPISettingsDataOnInit: Bool,
codexModelPollingService: CodexModelPollingService
) {
// Assign a unique window ID
WindowState.windowCounter += 1
windowID = WindowState.windowCounter
let manager = WindowStatesManager.shared
let claimedInitialRefreshDeferral = manager.claimInitialRefreshDeferralForNewWindow()
let deferredInitialAgentSystemWorkspaceRefresh = claimedInitialRefreshDeferral != nil
claimedInitialRefreshDeferralID = claimedInitialRefreshDeferral?.id
claimedInitialRefreshDeferralWaiterID = claimedInitialRefreshDeferral?.waiterID
// ️⃣ Connect to the global WindowStatesManager singleton
windowStatesManager = manager
let composition = WindowStateCompositionFactory.make(
windowID: windowID,
deferredInitialAgentSystemWorkspaceRefresh: deferredInitialAgentSystemWorkspaceRefresh,
sharedMCPService: Self.sharedMCPService,
contextBuilderProviderFactory: contextBuilderProviderFactory,
loadStoredAPISettingsDataOnInit: loadStoredAPISettingsDataOnInit,
codexModelPollingService: codexModelPollingService
)
workspaceFileContextStore = composition.workspaceFileContextStore
workspaceSearchService = composition.workspaceSearchService
selectionCoordinator = composition.selectionCoordinator
workspaceFilesViewModel = composition.workspaceFilesViewModel
settingsManager = composition.settingsManager
promptManager = composition.promptManager
oracleViewModel = composition.oracleViewModel
apiSettingsViewModel = composition.apiSettingsViewModel
contextBuilderAgentViewModel = composition.contextBuilderAgentViewModel
agentModeViewModel = composition.agentModeViewModel
#if DEBUG
agentChatStressHarness = composition.agentChatStressHarness
#endif
mcpServer = composition.mcpServer
closeCoordinator = composition.closeCoordinator
keyManager = composition.keyManager
aiQueriesService = composition.aiQueriesService
chatDataService = composition.chatDataService
workspaceManager = composition.workspaceManager
// Set up additional actions
setupSendPromptAction()
#if DEBUG
if AppLaunchConfiguration.current.forcesMCPAutoStart {
setupMCPAutoStart()
}
#endif
// Set up workspace switch listener to sync settings and validate prompts
workspaceManager.addWorkspaceDidSwitchListener(label: "windowState") { [weak self] workspace in
guard let self else { return }
promptManager.syncSettingsFromSettingsManager()
// Validate workspace skills for workspace root folders (if previously installed)
let roots = workspace.map(WorkspaceManagerViewModel.loadableRepoPaths(for:)) ?? []
Task.detached(priority: .utility) {
await MCPPromptValidationService.shared.validateWorkspaceSkills(forRoots: roots)
}
}
// Process any queued commands once the workspace is initialized
workspaceManager.onceInitialized { [weak self] in
guard let self else { return }
Task {
self.applyPendingRestoreEntryIfPossible()
await self.processCommands()
}
}
// Keep the window title in sync when this window's active compose tab changes,
// so the Agent session portion of the title does not go stale.
NotificationCenter.default.publisher(for: .activeComposeTabChanged)
.receive(on: RunLoop.main)
.sink { [weak self] notification in
guard let self,
let notifiedWindowID = notification.userInfo?["windowID"] as? Int,
notifiedWindowID == windowID
else { return }
requestWindowTitleUpdate(reason: .activeComposeTabChanged)
}
.store(in: &cancellables)
NotificationCenter.default.publisher(for: .composeTabNameChanged)
.receive(on: RunLoop.main)
.sink { [weak self] notification in
guard let self,
let notifiedWindowID = notification.userInfo?["windowID"] as? Int,
notifiedWindowID == windowID,
let tabID = notification.userInfo?["tabID"] as? UUID,
tabID == promptManager.activeComposeTabID
else { return }
requestWindowTitleUpdate(reason: .agentSessionNameChanged)
}
.store(in: &cancellables)
}
private func setupMCPAutoStart() {
Task { [weak self] in
await self?.mcpServer.startServer()
}
}
private func setupSendPromptAction() {
oracleViewModel.setupSendPromptAction()
}
// MARK: - Window Management
/// Attaches the NSWindow to this state and updates the title.
/// Uses deferred title update to avoid triggering layout during window lifecycle events
/// (REPOPROMPT-1K4 fix).
func attachWindow(_ window: NSWindow?) {
// Detach path (always do the cleanup even if both are nil)
if window == nil {
let oldWindow = nsWindow
detachTitlebarAccessoryControllers(from: oldWindow)
nsWindow = nil
removeFocusObservers()
pendingWindowTitleUpdateTask?.cancel()
pendingWindowTitleUpdateTask = nil
pendingFocusUpdateTask?.cancel()
pendingFocusUpdateTask = nil
scheduleFocusUpdate(false)
return
}
guard let window else { return }
if nsWindow === window {
configureWindowChrome(for: window)
ensureWindowDelegateProxy(for: window)
scheduleFocusUpdate(from: window)
requestWindowTitleUpdate(reason: .windowAttached)
applyAgentTitlebarAccessoryIfPossible()
return
}
if let oldWindow = nsWindow, oldWindow !== window {
detachTitlebarAccessoryControllers(from: oldWindow)
}
nsWindow = window
if AppLaunchConfiguration.current.isUITestSession {
DispatchQueue.main.async {
NSApp.activate(ignoringOtherApps: true)
window.makeKeyAndOrderFront(nil)
}
}
configureWindowChrome(for: window)
installFocusObservers(for: window)
scheduleFocusUpdate(from: window)
ensureWindowDelegateProxy(for: window)
// Use deferred update to avoid recursive layout issues
requestWindowTitleUpdate(reason: .windowAttached)
// Install Agent mode titlebar accessory if requested before window was attached
applyAgentTitlebarAccessoryIfPossible()
}
private func configureWindowChrome(for window: NSWindow) {
// Keep titlebar visually continuous with content (no horizontal separator).
window.toolbar?.showsBaselineSeparator = false
// SwiftUI can recreate toolbar chrome during toolbar updates; re-apply on next runloop.
DispatchQueue.main.async { [weak window] in
window?.toolbar?.showsBaselineSeparator = false
}
}
private func ensureWindowDelegateProxy(for window: NSWindow) {
if let proxy = windowDelegateProxy {
if window.delegate !== proxy {
proxy.forwardedDelegate = window.delegate
window.delegate = proxy
}
} else {
let proxy = InterceptingWindowDelegateProxy(windowState: self, forwardedDelegate: window.delegate)
windowDelegateProxy = proxy
window.delegate = proxy
}
}
private func installFocusObservers(for window: NSWindow) {
guard focusObservedWindow !== window else { return }
removeFocusObservers()
focusObservedWindow = window
let nc = NotificationCenter.default
nc.publisher(for: NSWindow.didBecomeKeyNotification, object: window)
.receive(on: RunLoop.main)
.sink { [weak self] _ in
guard let self else { return }
let appIsActive = NSApplication.shared.isActive
scheduleFocusUpdate(appIsActive)
}
.store(in: &focusCancellables)
nc.publisher(for: NSWindow.didResignKeyNotification, object: window)
.receive(on: RunLoop.main)
.sink { [weak self] _ in
self?.scheduleFocusUpdate(false)
}
.store(in: &focusCancellables)
nc.publisher(for: NSApplication.didBecomeActiveNotification)
.receive(on: RunLoop.main)
.sink { [weak self, weak window] _ in
guard let self, let window else { return }
scheduleFocusUpdate(window.isKeyWindow)
}
.store(in: &focusCancellables)
nc.publisher(for: NSApplication.didResignActiveNotification)
.receive(on: RunLoop.main)
.sink { [weak self] _ in
self?.scheduleFocusUpdate(false)
}
.store(in: &focusCancellables)
}
private func removeFocusObservers() {
focusCancellables.removeAll()
focusObservedWindow = nil
}
private func setFocused(_ focused: Bool) {
guard !shouldSuppressObservationSideEffects else { return }
guard isCurrentlyFocused != focused else { return }
isCurrentlyFocused = focused
workspaceFilesViewModel.setWindowFocused(focused)
scheduleFocusSideEffects(focused)
}
private func scheduleFocusUpdate(from window: NSWindow) {
let focused = NSApplication.shared.isActive && window.isKeyWindow
scheduleFocusUpdate(focused)
}
private func scheduleFocusUpdate(_ focused: Bool) {
guard !shouldSuppressObservationSideEffects else { return }
pendingFocusUpdateTask?.cancel()
pendingFocusUpdateTask = Task { [weak self] in
guard let self else { return }
await Task.yield()
guard !shouldSuppressObservationSideEffects else { return }
applyFocus(focused)
}
}
private func scheduleFocusSideEffects(_ focused: Bool) {
guard !shouldSuppressObservationSideEffects else { return }
pendingFocusSideEffectsTask?.cancel()
pendingFocusSideEffectsTask = Task { [weak self] in
guard let self else { return }
await Task.yield()
guard !shouldSuppressObservationSideEffects else { return }
guard isCurrentlyFocused == focused else { return }
onFocusChanged?(focused)
}
}
@MainActor
private func applyFocus(_ focused: Bool) {
setFocused(focused)
}
/// Safe to call from WindowAccessor notifications; doesn't mutate SwiftUI state.
private func reassertWindowTitle() {
guard !shouldSuppressObservationSideEffects else { return }
applyWindowTitleIfNeeded(resolvedWindowTitle())
}
@MainActor
private func applyWindowTitleIfNeeded(_ title: String) {
if displayedWindowTitle != title {
displayedWindowTitle = title
}
guard let window = nsWindow else { return }
if window.title == title, lastAppliedWindowTitle == title {
return
}
window.title = title
lastAppliedWindowTitle = title
}
func makeCloseImpactSnapshot() -> WindowCloseImpactSnapshot {
let manager = windowStatesManager ?? WindowStatesManager.shared
let allWindows = manager.allWindows
let mcpEnabledWindowIDs = Set(manager.mcpEnabledWindowIDs())
let activityItems = workspaceManager.activeSessionSnapshot().items.map {
WindowCloseActivityItem(
id: $0.id,
count: $0.count,
singularLabel: $0.singularLabel,
pluralLabel: $0.pluralLabel
)
}
return WindowCloseImpactSnapshot(
isTerminating: manager.isTerminating,
isLastAppWindow: allWindows.count == 1 && allWindows.first === self,
isLastMCPEnabledWindow: mcpEnabledWindowIDs.count == 1 && mcpEnabledWindowIDs.contains(windowID),
activeItems: activityItems,
mcp: mcpServer.closeSafetyState
)
}
func closeActiveComposeTabFromShortcut() {
guard let activeTabID = promptManager.activeComposeTabID,
promptManager.canCloseActiveComposeTab
else {
return
}
Task { await promptManager.stashTab(activeTabID) }
}
/// Starts a new Agent session tab (mirrors the titlebar "New Session" control).
func startNewAgentSessionFromGlobalShortcut() {
guard workspaceManager.activeWorkspace?.isSystemWorkspace == false else { return }
Task {
let activeTabID = await MainActor.run { agentModeViewModel.currentTabID }
if await MainActor.run(body: { agentModeViewModel.shouldSwallowNewSessionClick(for: activeTabID) }) {
return
}
await agentModeViewModel.createAndActivateSessionTab()
}
}
func requestClose(authorization: WindowCloseAuthorization? = nil) {
if let authorization {
closeCoordinator.enqueueAuthorization(authorization)
}
nsWindow?.performClose(nil)
}
// MARK: - Agent Mode Titlebar Accessory
@discardableResult
private func removeTitlebarAccessory(
_ accessory: NSTitlebarAccessoryViewController?,
from window: NSWindow? = nil
) -> Bool {
guard let accessory, let window = window ?? nsWindow else { return false }
let indexes = window.titlebarAccessoryViewControllers.enumerated().compactMap { index, candidate in
candidate === accessory ? index : nil
}
guard !indexes.isEmpty else { return false }
for index in indexes.sorted(by: >) {
window.removeTitlebarAccessoryViewController(at: index)
}
configureWindowChrome(for: window)
return true
}
private func detachTitlebarAccessoryControllers(from window: NSWindow?) {
let accessories: [NSTitlebarAccessoryViewController] = [
agentTitlebarAccessory as NSTitlebarAccessoryViewController?
].compactMap(\.self)
if let window, !accessories.isEmpty {
let accessoryIDs = Set(accessories.map { ObjectIdentifier($0) })
let indexes = window.titlebarAccessoryViewControllers.enumerated().compactMap { index, candidate in
accessoryIDs.contains(ObjectIdentifier(candidate)) ? index : nil
}
for index in indexes.sorted(by: >) {
window.removeTitlebarAccessoryViewController(at: index)
}
if !indexes.isEmpty {
configureWindowChrome(for: window)
}
}
agentTitlebarAccessory = nil
}
private func clearTitlebarAccessoryRequestsForClose() {
wantsAgentTitlebarAccessory = false
agentNewSessionAction = nil
}
/// Shows or hides the Agent mode titlebar accessory ("New Session" button near traffic lights).
/// - Parameters:
/// - visible: Whether to show the accessory
/// - onNewSession: Action to call when button is tapped (required when visible is true)
func setAgentTitlebarAccessoryVisible(_ visible: Bool, onNewSession: (() -> Void)? = nil) {
if visible {
guard !shouldSuppressObservationSideEffects else { return }
wantsAgentTitlebarAccessory = true
agentNewSessionAction = onNewSession
applyAgentTitlebarAccessoryIfPossible()
} else {
wantsAgentTitlebarAccessory = false
agentNewSessionAction = nil
removeAgentTitlebarAccessory()
}
}
/// Installs the titlebar accessory if conditions are met (Agent mode active + window attached)
private func applyAgentTitlebarAccessoryIfPossible() {
guard !shouldSuppressObservationSideEffects,
wantsAgentTitlebarAccessory,
let window = nsWindow,
let action = agentNewSessionAction
else {
return
}
if let existing = agentTitlebarAccessory {
existing.update(onNewSession: action)
if !window.titlebarAccessoryViewControllers.contains(where: { $0 === existing }) {
window.addTitlebarAccessoryViewController(existing)
}
} else {
let accessory = AgentModeTitlebarAccessoryViewController(onNewSession: action)
window.addTitlebarAccessoryViewController(accessory)
agentTitlebarAccessory = accessory
}
configureWindowChrome(for: window)
}
/// Removes the titlebar accessory from the window
private func removeAgentTitlebarAccessory() {
let accessory = agentTitlebarAccessory
removeTitlebarAccessory(accessory)
agentTitlebarAccessory = nil
}
func requestWindowTitleUpdate(reason: WindowTitleUpdateReason = .unspecified) {
_ = reason
scheduleWindowTitleUpdate()
}
/// Updates the window title to include the workspace name and instance number
func updateWindowTitleIfPossible() {
requestWindowTitleUpdate(reason: .explicit)
}
/// Only update the window title after a deferred hop to avoid recursive layout issues.
private func scheduleWindowTitleUpdate() {
guard !shouldSuppressObservationSideEffects else { return }
pendingWindowTitleUpdateTask?.cancel()
pendingWindowTitleUpdateTask = Task { [weak self] in
guard let self else { return }
// Ensure this cannot run re-entrantly during a layout/constraints pass.
await Task.yield()
guard !shouldSuppressObservationSideEffects else { return }
performWindowTitleUpdateIfWorkspaceAvailable()
}
}
@MainActor
private func performWindowTitleUpdateIfWorkspaceAvailable() {
applyWindowTitleIfNeeded(resolvedWindowTitle())
}
// ------------------------------------------------------------------
// MARK: – MCP server helpers (simple wrappers)
/// ------------------------------------------------------------------
func startMCPServer() {
Task { try? await WindowState.sharedMCPService.join(windowID: windowID) }
}
func stopMCPServer() {
Task { await WindowState.sharedMCPService.leave(windowID: windowID) }
}
// MARK: - Command handling
/// Decodes percent-encodings and expands '~' in a file path
private func decodeAndExpandTilde(_ rawPath: String) -> String {
// Decode percent-encoded strings, e.g. "%7E" -> "~", "%20" -> " "
guard let decoded = rawPath.removingPercentEncoding else {
return (rawPath as NSString).expandingTildeInPath
}
// Then expand '~'
return (decoded as NSString).expandingTildeInPath
}
func enqueueCommand(_ command: AppCommand) {
commandQueue.append(command)
// If the workspace manager is already initialized, process now
if workspaceManager.isInitialized {
Task { await processCommands() }
}
}
func applyWindowRestoreEntry(_ entry: WindowSessionEntry) {
guard !entry.isEphemeral else { return }
pendingRestoreEntry = entry
applyPendingRestoreEntryIfPossible()
}
private func applyPendingRestoreEntryIfPossible() {
guard workspaceManager.isInitialized else { return }
guard let entry = pendingRestoreEntry else { return }
pendingRestoreEntry = nil
Task {
await restoreWorkspace(from: entry)
}
}
private func restoreWorkspace(from entry: WindowSessionEntry) async {
#if DEBUG
let restoreStartMS = WorkspaceRestorePerfLog.timestampMSIfEnabled()
#endif
if let target = resolveWorkspace(for: entry) {
#if DEBUG
WorkspaceRestorePerfLog.log(
"restore.window workspaceResolved windowID=\(windowID) workspaceID=\(WorkspaceRestorePerfLog.shortID(target.id)) workspaceName=\(target.name) entryWorkspaceID=\(WorkspaceRestorePerfLog.shortID(entry.workspaceID))"
)
#endif
_ = await workspaceManager.requestWorkspaceSwitch(to: target, saveState: true, reason: "restore")
#if DEBUG
if let restoreStartMS {
WorkspaceRestorePerfLog.log(
"restore.window workspaceApplied windowID=\(windowID) workspaceID=\(WorkspaceRestorePerfLog.shortID(target.id)) duration=\(WorkspaceRestorePerfLog.formatElapsedMS(since: restoreStartMS))"
)
}
#endif
return
}
#if DEBUG
if let restoreStartMS {
WorkspaceRestorePerfLog.log(
"restore.window workspaceMissing windowID=\(windowID) entryWorkspaceID=\(WorkspaceRestorePerfLog.shortID(entry.workspaceID)) entryName=\(entry.workspaceName ?? "nil") duration=\(WorkspaceRestorePerfLog.formatElapsedMS(since: restoreStartMS))"
)
}
#endif
// No existing workspace matches; leave the window in its default state.
}
private func resolveWorkspace(for entry: WindowSessionEntry) -> WorkspaceModel? {
let workspaces = workspaceManager.workspaces
if let id = entry.workspaceID, let match = workspaces.first(where: { $0.id == id }) {
return match
}
if let path = entry.primaryRepoPath {
let expanded = (path as NSString).expandingTildeInPath
if let match = workspaces.first(where: { workspace in
workspace.repoPaths.contains { repoPath in
(repoPath as NSString).expandingTildeInPath == expanded
}
}) {
return match
}
}
if let name = entry.workspaceName, !name.isEmpty,
let match = workspaces.first(where: { $0.name == name })
{
return match
}
if entry.isSystemWorkspace,
let match = workspaces.first(where: { $0.isSystemWorkspace })
{
return match
}
return nil
}
// No workspace creation fallback; restoration is best-effort for existing workspaces only.
func processCommands() async {
while !commandQueue.isEmpty {
let command = commandQueue.removeFirst()
await handleCommand(command)
}
}
@MainActor
func routeToAgentSession(_ route: AgentSessionDeepLinkRoute) async -> AgentSessionRouteResult {
await waitForWorkspaceInitializationForRouting()
guard let targetWorkspace = workspaceManager.workspace(withID: route.workspaceID) else {
return .workspaceUnavailable
}
NSApplication.shared.activate(ignoringOtherApps: true)
if let window = nsWindow {
window.makeKeyAndOrderFront(nil)
} else {
focusWindowIfPossible()
}
if workspaceManager.activeWorkspaceID != route.workspaceID {
let switchResult = await workspaceManager.requestWorkspaceSwitch(to: targetWorkspace, saveState: true)
if !switchResult.didSwitch {
return .workspaceSwitchBlocked(switchResult.message)
}
}
guard let activeWorkspace = workspaceManager.activeWorkspace,
activeWorkspace.id == route.workspaceID
else {
return .workspaceUnavailable
}
let tabIsActive = activeWorkspace.composeTabs.contains(where: { $0.id == route.tabID })
let tabIsStashed = activeWorkspace.stashedTabs.contains(where: { $0.tab.id == route.tabID })
guard tabIsActive || tabIsStashed else {
return .tabUnavailable
}
if let sessionID = route.sessionID {
let activationResult = await agentModeViewModel.activateRoutedAgentSession(
tabID: route.tabID,
sessionID: sessionID,
workspace: activeWorkspace
)
guard activationResult == .ready else {
return agentSessionRouteResult(for: activationResult)
}
}
if tabIsStashed {
guard await promptManager.restoreStashedComposeTab(containingTabID: route.tabID) != nil else {
return .tabUnavailable
}
} else if promptManager.activeComposeTabID != route.tabID {
await promptManager.switchComposeTab(route.tabID)
}
guard promptManager.activeComposeTabID == route.tabID else {
return .tabUnavailable
}
guard let finalWorkspace = workspaceManager.activeWorkspace,
finalWorkspace.id == route.workspaceID
else {
return .workspaceUnavailable
}
let finalActivationResult = await agentModeViewModel.activateRoutedAgentSession(
tabID: route.tabID,
sessionID: route.sessionID,
workspace: finalWorkspace
)
guard finalActivationResult == .ready else {
return agentSessionRouteResult(for: finalActivationResult)
}
if let window = nsWindow {
window.makeKeyAndOrderFront(nil)
} else {
focusWindowIfPossible()
}
return .routed
}
@MainActor