Ariver
2026-06-06 5c054407508d90811f2498522d4511c520b10c4c
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
import AppKit
import QuartzCore
import AlignerCore
 
@MainActor
final class QuickSwitchSessionController {
    static let overlayTitle = "Aligner Quick Switch"
 
    private let view = QuickSwitchRootView()
    private let snapshotLoader: any QuickSwitchSnapshotLoading
    private let screenshotProvider: any ScreenshotProviderProtocol
    private let windowActivationService: any WindowActivationServiceProtocol
    private let systemCriticalWindowDetector: any SystemCriticalWindowDetecting
    private let disableScreenshotRefresh: Bool
    private let debugOverlayWidth: CGFloat?
    private let debugKeySequence: [String]
    private let debugMouseSequence: [String]
    private let debugSystemCriticalAfter: TimeInterval?
    private lazy var coordinator = WindowCoordinator(
        contentView: view,
        title: Self.overlayTitle,
        debugOverlayWidth: debugOverlayWidth
    )
    private var currentSnapshot: QuickSwitchSnapshot?
    private var currentViewModel: QuickSwitchViewModel?
    private var lastSnapshotError: String?
    private var snapshotTask: Task<Void, Never>?
    private var screenshotTask: Task<Void, Never>?
    private var systemCriticalMonitorTimer: Timer?
    private var debugSystemCriticalTimer: Timer?
    private var screenshotSession = ScreenshotCaptureSession()
    private var sessionGeneration = 0
    private var showStartTime: CFTimeInterval?
    private var overlayOpenElapsedMilliseconds: Double?
    private var snapshotStartElapsedMilliseconds: Double?
    private var snapshotDurationMilliseconds: Double?
    private var snapshotRanOnMainThread: Bool?
    private var lastCommittedSelection: QuickSwitchSelection?
    private var lastCommitSource: QuickSwitchCommitSource?
    private var lastActivationWindowID: UInt32?
    private var lastActivationResult: WindowActivationResult?
    private var lastActivationError: String?
    private var lastDismissReason: DismissReason?
    private var lastSystemCriticalAction: String?
    private var lastSystemCriticalMonitorSource: String?
    private var lastSystemCriticalWindowCount = 0
    private var lastSystemCriticalWindowTitleHashes: [String] = []
    private var lastSystemCriticalWindowTitleLengths: [Int] = []
    private var lastSystemCriticalWindowTitleIsEmpty: [Bool] = []
    private var lastSystemCriticalWindowOwners: [String] = []
    private var lastSystemCriticalOverlayLevel: CGWindowLevel?
    private var systemCriticalDetectionCount = 0
    private var lifecycleTargetCycles = 0
    private var lifecycleCompletedCycles = 0
    private var lifecycleMaximumOverlayWindows = 0
    private var lifecycleMaximumVisibleOverlayWindows = 0
    private var lifecycleResidualOverlayWindows = 0
    private var lifecycleResidualVisibleOverlayWindows = 0
    var onSnapshotUpdated: (() -> Void)?
 
    init(
        snapshotLoader: any QuickSwitchSnapshotLoading = LiveQuickSwitchSnapshotLoader(),
        screenshotProvider: any ScreenshotProviderProtocol = ScreenCaptureKitScreenshotProvider(
            debugLogger: StderrScreenshotDebugLogger()
        ),
        windowActivationService: any WindowActivationServiceProtocol = CGWindowAXWindowService(
            spaceIDsByWindowIDProvider: { _ in [:] }
        ),
        systemCriticalWindowDetector: any SystemCriticalWindowDetecting = CGWindowSystemCriticalWindowDetector(),
        disableScreenshotRefresh: Bool = false,
        debugHoveredAppGroupIndex: Int? = nil,
        debugOverlayWidth: CGFloat? = nil,
        debugKeySequence: [String] = [],
        debugMouseSequence: [String] = [],
        debugSystemCriticalAfter: TimeInterval? = nil
    ) {
        self.snapshotLoader = snapshotLoader
        self.screenshotProvider = screenshotProvider
        self.windowActivationService = windowActivationService
        self.systemCriticalWindowDetector = systemCriticalWindowDetector
        self.disableScreenshotRefresh = disableScreenshotRefresh
        self.debugOverlayWidth = debugOverlayWidth
        self.debugKeySequence = debugKeySequence
        self.debugMouseSequence = debugMouseSequence
        self.debugSystemCriticalAfter = debugSystemCriticalAfter
        view.setDebugHoveredAppGroupIndex(debugHoveredAppGroupIndex)
    }
 
    var isVisible: Bool {
        coordinator.isQuickSwitchVisible
    }
 
    func show() {
        sessionGeneration += 1
        let generation = sessionGeneration
        DevelopmentDiagnostics.log("quickSwitch.session.show.start", [
            "generation": generation,
            "wasVisible": isVisible
        ])
        showStartTime = CACurrentMediaTime()
        overlayOpenElapsedMilliseconds = nil
        snapshotStartElapsedMilliseconds = nil
        snapshotDurationMilliseconds = nil
        snapshotRanOnMainThread = nil
        lastCommittedSelection = nil
        lastCommitSource = nil
        lastActivationWindowID = nil
        lastActivationResult = nil
        lastActivationError = nil
        lastDismissReason = nil
        lastSystemCriticalAction = nil
        lastSystemCriticalMonitorSource = nil
        lastSystemCriticalWindowCount = 0
        lastSystemCriticalWindowTitleHashes = []
        lastSystemCriticalWindowTitleLengths = []
        lastSystemCriticalWindowTitleIsEmpty = []
        lastSystemCriticalWindowOwners = []
        lastSystemCriticalOverlayLevel = nil
        systemCriticalDetectionCount = 0
        invalidateSystemCriticalMonitoring()
        screenshotTask?.cancel()
        screenshotTask = nil
        screenshotSession = ScreenshotCaptureSession()
        clearSnapshotState()
        view.onEscape = { [weak self] in
            self?.hide(reason: .escape)
        }
        view.onCommitSelection = { [weak self] selection, source in
            self?.commitSelection(selection, source: source)
        }
        view.apply(viewModel: nil)
        view.beginPerformanceFirstFrameMeasurement()
        coordinator.openQuickSwitch()
        coordinator.promoteForTextInput()
        view.window?.makeFirstResponder(view)
        overlayOpenElapsedMilliseconds = elapsedSinceShowStart()
        updateLifecycleWindowHighWaterMark()
        startSystemCriticalMonitoring()
        scheduleSnapshotRefresh(for: generation)
        DevelopmentDiagnostics.log("quickSwitch.session.show.end", [
            "generation": generation,
            "overlayOpenElapsedMilliseconds": overlayOpenElapsedMilliseconds,
            "overlayLevel": coordinator.currentLevel,
            "windowVisible": view.window?.isVisible ?? false
        ])
    }
 
    func hide(reason: DismissReason = .userClosed) {
        DevelopmentDiagnostics.log("quickSwitch.session.hide.start", [
            "reason": Self.dismissReasonString(reason),
            "wasVisible": isVisible,
            "generation": sessionGeneration
        ])
        sessionGeneration += 1
        lastDismissReason = reason
        snapshotTask?.cancel()
        snapshotTask = nil
        screenshotTask?.cancel()
        screenshotTask = nil
        invalidateSystemCriticalMonitoring()
        coordinator.closeQuickSwitch(reason: reason)
        lifecycleResidualOverlayWindows = overlayWindowCount()
        lifecycleResidualVisibleOverlayWindows = visibleOverlayWindowCount()
        updateLifecycleWindowHighWaterMark()
        DevelopmentDiagnostics.log("quickSwitch.session.hide.end", [
            "reason": Self.dismissReasonString(reason),
            "generation": sessionGeneration,
            "residualOverlayWindows": lifecycleResidualOverlayWindows,
            "residualVisibleOverlayWindows": lifecycleResidualVisibleOverlayWindows
        ])
    }
 
    func refocus() {
        DevelopmentDiagnostics.log("quickSwitch.session.refocus")
        coordinator.promoteForTextInput()
        view.window?.makeFirstResponder(view)
    }
 
    func retriggerFromShortcut() {
        DevelopmentDiagnostics.log("quickSwitch.session.retriggerFromShortcut")
        show()
    }
 
    func reportDictionary() -> [String: Any] {
        let spaceCount = currentViewModel?.spaceCount ?? 0
        let appCount = currentViewModel?.appShelf.count ?? 0
        let columnCount = currentViewModel?.waterfallColumns.count ?? 0
        let windowCount = currentViewModel?.windowCount ?? 0
 
        return [
            "snapshotLoaded": currentSnapshot != nil,
            "snapshotError": lastSnapshotError ?? NSNull(),
            "quickSwitchVisible": isVisible,
            "diagnosticLogLocationKind": DevelopmentDiagnostics.pathSummary(DevelopmentDiagnostics.logPath)["locationKind"] ?? "unknown",
            "diagnosticLogBasename": DevelopmentDiagnostics.pathSummary(DevelopmentDiagnostics.logPath)["basename"] ?? "aligner-dev.log",
            "displayCount": currentViewModel?.displays.count ?? 0,
            "spaceCount": spaceCount,
            "appCount": appCount,
            "columnCount": columnCount,
            "windowCount": windowCount,
            "initialSelectionWindowID": currentViewModel?.initialSelection?.windowID ?? NSNull(),
            "appShelfNames": currentViewModel?.appShelf.map(\.app.name) ?? [],
            "spaceLabels": currentViewModel?.displays.flatMap { $0.spaces.map(\.label) } ?? [],
            "overlayOpenElapsedMilliseconds": overlayOpenElapsedMilliseconds ?? NSNull(),
            "snapshotStartElapsedMilliseconds": snapshotStartElapsedMilliseconds ?? NSNull(),
            "snapshotDurationMilliseconds": snapshotDurationMilliseconds ?? NSNull(),
            "snapshotRanOnMainThread": snapshotRanOnMainThread ?? NSNull(),
            "lastCommittedAppGroupIndex": lastCommittedSelection?.appGroupIndex ?? NSNull(),
            "lastCommittedWindowIndex": lastCommittedSelection?.windowIndex ?? NSNull(),
            "lastCommittedWindowID": lastCommittedSelection?.windowID ?? NSNull(),
            "lastCommitSource": lastCommitSource?.rawValue ?? NSNull(),
            "lastActivationWindowID": lastActivationWindowID ?? NSNull(),
            "lastActivationResult": lastActivationResult.map(Self.activationResultString) ?? NSNull(),
            "lastActivationError": lastActivationError ?? NSNull(),
            "lastDismissReason": lastDismissReason.map(Self.dismissReasonString) ?? NSNull(),
            "overlayLevel": Int(coordinator.currentLevel),
            "overlayMainMenuLevel": Int(CGWindowLevelForKey(.mainMenuWindow)),
            "overlayBelowRescueSystemWindows": coordinator.currentLevel < CGWindowLevelForKey(.mainMenuWindow),
            "lastSystemCriticalAction": lastSystemCriticalAction ?? NSNull(),
            "lastSystemCriticalMonitorSource": lastSystemCriticalMonitorSource ?? NSNull(),
            "lastSystemCriticalWindowCount": lastSystemCriticalWindowCount,
            "lastSystemCriticalWindowTitleHashes": lastSystemCriticalWindowTitleHashes,
            "lastSystemCriticalWindowTitleLengths": lastSystemCriticalWindowTitleLengths,
            "lastSystemCriticalWindowTitleIsEmpty": lastSystemCriticalWindowTitleIsEmpty,
            "lastSystemCriticalWindowOwners": lastSystemCriticalWindowOwners,
            "lastSystemCriticalOverlayLevel": lastSystemCriticalOverlayLevel.map { Int($0) } ?? NSNull(),
            "systemCriticalDetectionCount": systemCriticalDetectionCount,
            "lifecycleTargetCycles": lifecycleTargetCycles,
            "lifecycleCompletedCycles": lifecycleCompletedCycles,
            "lifecycleMaximumOverlayWindows": lifecycleMaximumOverlayWindows,
            "lifecycleMaximumVisibleOverlayWindows": lifecycleMaximumVisibleOverlayWindows,
            "lifecycleResidualOverlayWindows": lifecycleResidualOverlayWindows,
            "lifecycleResidualVisibleOverlayWindows": lifecycleResidualVisibleOverlayWindows,
            "lifecycleGatePassed": lifecycleTargetCycles == 0
                || (
                    lifecycleCompletedCycles == lifecycleTargetCycles
                        && lifecycleMaximumOverlayWindows <= 1
                        && lifecycleMaximumVisibleOverlayWindows <= 1
                        && lifecycleResidualOverlayWindows <= 1
                        && lifecycleResidualVisibleOverlayWindows == 0
                ),
            "rootView": view.reportDictionary()
        ]
    }
 
    func prepareLifecycleRun(targetCycles: Int) {
        lifecycleTargetCycles = max(0, targetCycles)
        lifecycleCompletedCycles = 0
        lifecycleMaximumOverlayWindows = 0
        lifecycleMaximumVisibleOverlayWindows = 0
        lifecycleResidualOverlayWindows = 0
        lifecycleResidualVisibleOverlayWindows = 0
        view.resetPerformanceMeasurements()
    }
 
    func markLifecycleCycleCompleted() {
        lifecycleCompletedCycles += 1
        updateLifecycleWindowHighWaterMark()
    }
 
    func finalizeLifecycleRun() {
        lifecycleResidualOverlayWindows = overlayWindowCount()
        lifecycleResidualVisibleOverlayWindows = visibleOverlayWindowCount()
        updateLifecycleWindowHighWaterMark()
    }
 
    private func scheduleSnapshotRefresh(for generation: Int) {
        DevelopmentDiagnostics.log("quickSwitch.snapshot.schedule", [
            "generation": generation,
            "visible": isVisible
        ])
        snapshotTask?.cancel()
        let loader = snapshotLoader
        let showStartTime = showStartTime
        snapshotTask = Task { [weak self] in
            guard let self, !Task.isCancelled else { return }
 
            let loadTask = Task.detached(priority: .userInitiated) {
                SnapshotLoadResult.load(using: loader, showStartTime: showStartTime)
            }
            let result = await withTaskCancellationHandler {
                await loadTask.value
            } onCancel: {
                loadTask.cancel()
            }
 
            guard !Task.isCancelled else { return }
            self.applySnapshotResult(result, generation: generation)
        }
    }
 
    private func clearSnapshotState() {
        currentSnapshot = nil
        currentViewModel = nil
        lastSnapshotError = nil
    }
 
    private func startSystemCriticalMonitoring() {
        invalidateSystemCriticalMonitoring()
        checkForSystemCriticalWindows(source: "initial")
        guard isVisible else { return }
 
        let monitorTimer = Timer(timeInterval: 0.20, repeats: true) { [weak self] _ in
            Task { @MainActor [weak self] in
                self?.checkForSystemCriticalWindows(source: "poll")
            }
        }
        RunLoop.main.add(monitorTimer, forMode: .common)
        systemCriticalMonitorTimer = monitorTimer
 
        if let debugSystemCriticalAfter {
            let debugTimer = Timer(timeInterval: debugSystemCriticalAfter, repeats: false) { [weak self] _ in
                Task { @MainActor [weak self] in
                    self?.handleSystemCriticalWindows(
                        [
                            SystemCriticalWindowRecord(
                                ownerName: "SecurityAgent",
                                title: "Debug Security Confirmation",
                                processIdentifier: 0,
                                layer: Int(CGWindowLevelForKey(.mainMenuWindow)),
                                bounds: .zero
                            )
                        ],
                        source: "debug"
                    )
                }
            }
            RunLoop.main.add(debugTimer, forMode: .common)
            debugSystemCriticalTimer = debugTimer
        }
    }
 
    private func invalidateSystemCriticalMonitoring() {
        systemCriticalMonitorTimer?.invalidate()
        systemCriticalMonitorTimer = nil
        debugSystemCriticalTimer?.invalidate()
        debugSystemCriticalTimer = nil
    }
 
    private func checkForSystemCriticalWindows(source: String) {
        guard isVisible else { return }
 
        let criticalWindows = systemCriticalWindowDetector.visibleSystemCriticalWindows()
        guard !criticalWindows.isEmpty else { return }
 
        handleSystemCriticalWindows(criticalWindows, source: source)
    }
 
    private func handleSystemCriticalWindows(_ windows: [SystemCriticalWindowRecord], source: String) {
        guard isVisible, !windows.isEmpty else { return }
 
        systemCriticalDetectionCount += 1
        lastSystemCriticalAction = "closeOverlay"
        lastSystemCriticalMonitorSource = source
        lastSystemCriticalWindowCount = windows.count
        lastSystemCriticalWindowTitleHashes = windows.map { DevelopmentDiagnostics.stableFingerprint($0.title) }
        lastSystemCriticalWindowTitleLengths = windows.map { $0.title.count }
        lastSystemCriticalWindowTitleIsEmpty = windows.map { $0.title.isEmpty }
        lastSystemCriticalWindowOwners = windows.map(\.ownerName)
        lastSystemCriticalOverlayLevel = coordinator.currentLevel
        hide(reason: .systemCriticalWindow)
        onSnapshotUpdated?()
    }
 
    private func commitSelection(_ selection: QuickSwitchSelection, source: QuickSwitchCommitSource) {
        DevelopmentDiagnostics.log("quickSwitch.activation.commit.start", [
            "source": source.rawValue,
            "appGroupIndex": selection.appGroupIndex,
            "windowIndex": selection.windowIndex,
            "windowID": selection.windowID
        ])
        lastCommittedSelection = selection
        lastCommitSource = source
        lastActivationWindowID = selection.windowID
        lastActivationError = nil
 
        guard let window = window(for: selection) else {
            lastActivationResult = .windowNotFound
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.windowNotFound", [
                "source": source.rawValue,
                "appGroupIndex": selection.appGroupIndex,
                "windowIndex": selection.windowIndex,
                "windowID": selection.windowID
            ])
            onSnapshotUpdated?()
            return
        }
 
        DevelopmentDiagnostics.log("quickSwitch.activation.commit.hideBeforeActivation", [
            "source": source.rawValue,
            "windowID": window.id
        ])
        hide(reason: .userClosed)
 
        do {
            lastActivationResult = try windowActivationService.activate(window: window)
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.result", [
                "source": source.rawValue,
                "windowID": window.id,
                "appName": window.app.name,
                "appPID": window.app.processIdentifier,
                "titleHash": DevelopmentDiagnostics.stableFingerprint(window.title),
                "titleLength": window.title.count,
                "titleIsEmpty": window.title.isEmpty,
                "result": lastActivationResult.map(Self.activationResultString)
            ])
        } catch {
            let errorSummary = DevelopmentDiagnostics.errorSummaryString(error)
            lastActivationResult = .failed(errorSummary)
            lastActivationError = errorSummary
            var fields: [String: CustomStringConvertible?] = [
                "source": source.rawValue,
                "windowID": window.id,
                "appName": window.app.name,
                "titleHash": DevelopmentDiagnostics.stableFingerprint(window.title),
                "titleLength": window.title.count,
                "titleIsEmpty": window.title.isEmpty
            ]
            DevelopmentDiagnostics.errorSummaryFields(error).forEach { fields[$0.key] = $0.value }
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.error", fields)
        }
 
        if shouldCloseAfterActivation(lastActivationResult) {
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.closeAfterActivation", [
                "result": lastActivationResult.map(Self.activationResultString)
            ])
        } else {
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.refreshAfterActivation", [
                "result": lastActivationResult.map(Self.activationResultString)
            ])
        }
        onSnapshotUpdated?()
    }
 
    private func shouldCloseAfterActivation(_ result: WindowActivationResult?) -> Bool {
        switch result {
        case .activated, .restored, .appActivatedOnly:
            return true
        case .windowNotFound, .unsupported, .activationFailed, .failed, nil:
            return false
        }
    }
 
    private func window(for selection: QuickSwitchSelection) -> AlignerWindow? {
        currentViewModel?
            .waterfallColumns
            .flatMap(\.windows)
            .first { card in
                card.appGroupIndex == selection.appGroupIndex
                    && card.windowIndex == selection.windowIndex
                    && card.window.id == selection.windowID
            }?
            .window
    }
 
    private func applySnapshotResult(_ result: SnapshotLoadResult, generation: Int) {
        guard generation == sessionGeneration, isVisible else {
            DevelopmentDiagnostics.log("quickSwitch.snapshot.drop", [
                "resultGeneration": generation,
                "currentGeneration": sessionGeneration,
                "visible": isVisible
            ])
            return
        }
 
        switch result {
        case .success(let success):
            currentSnapshot = success.snapshot
            currentViewModel = success.viewModel
            lastSnapshotError = nil
            snapshotStartElapsedMilliseconds = success.timing.startElapsedMilliseconds
            snapshotDurationMilliseconds = success.timing.durationMilliseconds
            snapshotRanOnMainThread = success.timing.ranOnMainThread
            view.apply(viewModel: success.viewModel)
            view.recordPerformanceFirstFrameIfNeeded()
            view.performDebugKeyboardCommands(debugKeySequence)
            view.performDebugMouseCommands(debugMouseSequence)
            DevelopmentDiagnostics.log("quickSwitch.snapshot.success", [
                "generation": generation,
                "displayCount": success.viewModel.displays.count,
                "spaceCount": success.viewModel.spaceCount,
                "appCount": success.viewModel.appShelf.count,
                "windowCount": success.viewModel.windowCount,
                "durationMilliseconds": success.timing.durationMilliseconds,
                "ranOnMainThread": success.timing.ranOnMainThread,
                "initialSelectionWindowID": success.viewModel.initialSelection?.windowID
            ])
            guard isVisible else { return }
            if disableScreenshotRefresh {
                view.markScreenshotsNotRequested(for: success.viewModel, reason: "disabledByLaunchOption")
                screenshotTask?.cancel()
                screenshotTask = nil
                DevelopmentDiagnostics.log("quickSwitch.screenshot.disabledByLaunchOption", [
                    "generation": generation
                ])
            } else {
                scheduleScreenshotRefresh(for: success.viewModel, generation: generation)
            }
        case .failure(let failure):
            currentSnapshot = nil
            currentViewModel = nil
            lastSnapshotError = failure.message
            snapshotStartElapsedMilliseconds = failure.timing.startElapsedMilliseconds
            snapshotDurationMilliseconds = failure.timing.durationMilliseconds
            snapshotRanOnMainThread = failure.timing.ranOnMainThread
            view.apply(viewModel: nil)
            screenshotTask?.cancel()
            screenshotTask = nil
            DevelopmentDiagnostics.log("quickSwitch.snapshot.failure", [
                "generation": generation,
                "message": failure.message,
                "durationMilliseconds": failure.timing.durationMilliseconds,
                "ranOnMainThread": failure.timing.ranOnMainThread
            ])
        }
 
        onSnapshotUpdated?()
    }
 
    private func scheduleScreenshotRefresh(
        for viewModel: QuickSwitchViewModel,
        generation: Int
    ) {
        screenshotTask?.cancel()
        let provider = screenshotProvider
        let session = screenshotSession
        let allWindows = viewModel.waterfallColumns.flatMap { column in
            column.windows.map(\.window)
        }
        let windows = allWindows.filter(Self.shouldRequestScreenshot)
        let skippedWindows = allWindows.filter { !Self.shouldRequestScreenshot(for: $0) }
        DevelopmentDiagnostics.log("quickSwitch.screenshot.schedule", [
            "generation": generation,
            "eligibleCount": windows.count,
            "skippedCount": skippedWindows.count
        ])
 
        for window in skippedWindows {
            view.markScreenshotNotRequested(for: window.id, reason: "skeletonPreferred")
        }
        if !skippedWindows.isEmpty {
            onSnapshotUpdated?()
        }
        guard !windows.isEmpty else {
            screenshotTask = nil
            return
        }
 
        screenshotTask = Task { [weak self] in
            guard let self else { return }
 
            var retryWindows: [AlignerWindow] = []
            for window in windows {
                guard !Task.isCancelled else { return }
                let resolution = await provider.resolvedScreenshot(for: window, in: session)
                guard !Task.isCancelled, generation == self.sessionGeneration, self.isVisible else { return }
                self.view.applyScreenshot(resolution, for: window.id)
                DevelopmentDiagnostics.log("quickSwitch.screenshot.resolved", [
                    "generation": generation,
                    "windowID": window.id,
                    "appName": window.app.name,
                    "source": Self.screenshotSourceString(resolution.source)
                ])
                self.onSnapshotUpdated?()
 
                if case .skeletonFallback(let reason) = resolution.source,
                   Self.shouldRetryScreenshot(after: reason) {
                    retryWindows.append(window)
                }
            }
 
            for window in retryWindows {
                guard !Task.isCancelled else { return }
                let retryResolution = await provider.resolvedScreenshot(for: window, in: session)
                guard !Task.isCancelled, generation == self.sessionGeneration, self.isVisible else { return }
                self.view.applyScreenshot(retryResolution, for: window.id)
                DevelopmentDiagnostics.log("quickSwitch.screenshot.retryResolved", [
                    "generation": generation,
                    "windowID": window.id,
                    "appName": window.app.name,
                    "source": Self.screenshotSourceString(retryResolution.source)
                ])
                self.onSnapshotUpdated?()
            }
        }
    }
 
    private static func shouldRequestScreenshot(for window: AlignerWindow) -> Bool {
        switch ThumbnailPolicy.preferredStrategy(for: window.app.category) {
        case .screenshotPreferred:
            return true
        case .skeletonPreferred, .fallbackSkeleton:
            return false
        }
    }
 
    private static func shouldRetryScreenshot(after reason: ScreenshotFallbackReason) -> Bool {
        switch reason {
        case .screenRecordingDenied, .syntheticWindowID, .retryLimitReached:
            return false
        case .captureFailed, .timedOut, .invalidCapture:
            return true
        }
    }
 
    private func elapsedSinceShowStart() -> Double? {
        guard let showStartTime else { return nil }
        return (CACurrentMediaTime() - showStartTime) * 1000
    }
 
    private func updateLifecycleWindowHighWaterMark() {
        lifecycleMaximumOverlayWindows = max(
            lifecycleMaximumOverlayWindows,
            overlayWindowCount()
        )
        lifecycleMaximumVisibleOverlayWindows = max(
            lifecycleMaximumVisibleOverlayWindows,
            visibleOverlayWindowCount()
        )
    }
 
    private func overlayWindowCount() -> Int {
        NSApp.windows.filter { window in
            window.title == Self.overlayTitle
        }.count
    }
 
    private func visibleOverlayWindowCount() -> Int {
        NSApp.windows.filter { window in
            window.title == Self.overlayTitle && window.isVisible
        }.count
    }
 
    private static func activationResultString(_ result: WindowActivationResult) -> String {
        switch result {
        case .activated:
            return "activated"
        case .restored:
            return "restored"
        case .appActivatedOnly:
            return "appActivatedOnly"
        case .windowNotFound:
            return "windowNotFound"
        case .unsupported:
            return "unsupported"
        case .activationFailed:
            return "activationFailed"
        case .failed(let message):
            return "failed(\(message))"
        }
    }
 
    private static func screenshotSourceString(_ source: ScreenshotResolutionSource) -> String {
        switch source {
        case .realScreenshot:
            return "realScreenshot"
        case .skeletonFallback(let reason):
            return "skeletonFallback(\(reason))"
        }
    }
 
    private static func dismissReasonString(_ reason: DismissReason) -> String {
        switch reason {
        case .escape:
            return "escape"
        case .focusLost:
            return "focusLost"
        case .systemCriticalWindow:
            return "systemCriticalWindow"
        case .timeout:
            return "timeout"
        case .userClosed:
            return "userClosed"
        }
    }
 
}
 
private struct SnapshotLoadTiming: Sendable {
    let startElapsedMilliseconds: Double?
    let durationMilliseconds: Double
    let ranOnMainThread: Bool
}
 
private struct SnapshotLoadSuccess: Sendable {
    let snapshot: QuickSwitchSnapshot
    let viewModel: QuickSwitchViewModel
    let timing: SnapshotLoadTiming
}
 
private struct SnapshotLoadFailure: Sendable {
    let message: String
    let timing: SnapshotLoadTiming
}
 
private enum SnapshotLoadResult: Sendable {
    case success(SnapshotLoadSuccess)
    case failure(SnapshotLoadFailure)
 
    static func load(
        using loader: any QuickSwitchSnapshotLoading,
        showStartTime: CFTimeInterval?
    ) -> SnapshotLoadResult {
        let startedAt = CACurrentMediaTime()
        let startedOnMainThread = Thread.isMainThread
 
        do {
            let load = try loader.snapshot()
            let viewModel = QuickSwitchViewModelBuilder.viewModel(
                from: load.snapshot,
                currentSpaceIDs: load.currentSpaceIDs
            )
            return .success(SnapshotLoadSuccess(
                snapshot: load.snapshot,
                viewModel: viewModel,
                timing: SnapshotLoadTiming(
                    startElapsedMilliseconds: showStartTime.map { (startedAt - $0) * 1000 },
                    durationMilliseconds: (CACurrentMediaTime() - startedAt) * 1000,
                    ranOnMainThread: startedOnMainThread
                )
            ))
        } catch {
            return .failure(SnapshotLoadFailure(
                message: DevelopmentDiagnostics.errorSummaryString(error),
                timing: SnapshotLoadTiming(
                    startElapsedMilliseconds: showStartTime.map { (startedAt - $0) * 1000 },
                    durationMilliseconds: (CACurrentMediaTime() - startedAt) * 1000,
                    ranOnMainThread: startedOnMainThread
                )
            ))
        }
    }
}
 
struct Round1QuickSwitchLaunchOptions {
    let openQuickSwitch: Bool
    let simulateAccessibilityDenied: Bool
    let simulateScreenRecordingDenied: Bool
    let autoHideAfter: TimeInterval?
    let quitAfter: TimeInterval?
    let reportPath: String?
    let snapshotLoadDelay: TimeInterval?
    let fixtureAppCount: Int?
    let fixtureWindowsPerApp: Int?
    let fixtureCandidateFiltering: Bool
    let fixtureActivation: Bool
    let debugHoveredAppGroupIndex: Int?
    let debugOverlayWidth: CGFloat?
    let debugKeySequence: [String]
    let debugMouseSequence: [String]
    let debugSystemCriticalAfter: TimeInterval?
    let debugWindowActivation: Bool
    let disableScreenshotRefresh: Bool
    let lifecycleCycles: Int?
    let lifecycleInterval: TimeInterval
    let lifecycleVisibleDuration: TimeInterval
 
    static func parse(arguments: [String]) -> Round1QuickSwitchLaunchOptions {
        Round1QuickSwitchLaunchOptions(
            openQuickSwitch: arguments.contains("--round01-open-quick-switch"),
            simulateAccessibilityDenied: arguments.contains("--round01-simulate-accessibility-denied"),
            simulateScreenRecordingDenied: arguments.contains("--round01-simulate-screen-recording-denied"),
            autoHideAfter: timeInterval(for: "--round01-quick-switch-auto-hide-after", in: arguments),
            quitAfter: timeInterval(for: "--round01-quick-switch-quit-after", in: arguments),
            reportPath: stringValue(for: "--round01-quick-switch-report", in: arguments),
            snapshotLoadDelay: timeInterval(for: "--round01-snapshot-load-delay", in: arguments),
            fixtureAppCount: intValue(for: "--round01-fixture-app-count", in: arguments),
            fixtureWindowsPerApp: intValue(for: "--round01-fixture-windows-per-app", in: arguments),
            fixtureCandidateFiltering: arguments.contains("--round01-fixture-candidate-filtering"),
            fixtureActivation: arguments.contains("--round01-fixture-window-activation"),
            debugHoveredAppGroupIndex: intValue(for: "--round01-debug-hover-app-index", in: arguments),
            debugOverlayWidth: cgFloatValue(for: "--round01-debug-overlay-width", in: arguments),
            debugKeySequence: stringListValue(for: "--round01-debug-key-sequence", in: arguments),
            debugMouseSequence: stringListValue(for: "--round01-debug-mouse-sequence", in: arguments),
            debugSystemCriticalAfter: timeInterval(for: "--round01-debug-system-critical-after", in: arguments),
            debugWindowActivation: arguments.contains("--round01-debug-window-activation"),
            disableScreenshotRefresh: arguments.contains("--round01-disable-screenshot-refresh"),
            lifecycleCycles: intValue(for: "--round01-quick-switch-lifecycle-cycles", in: arguments),
            lifecycleInterval: timeInterval(for: "--round01-quick-switch-lifecycle-interval", in: arguments) ?? 0.02,
            lifecycleVisibleDuration: timeInterval(for: "--round01-quick-switch-lifecycle-visible-duration", in: arguments) ?? 0.16
        )
    }
 
    private static func timeInterval(for key: String, in arguments: [String]) -> TimeInterval? {
        let prefix = "\(key)="
        guard let argument = arguments.first(where: { $0.hasPrefix(prefix) }) else {
            return nil
        }
 
        return TimeInterval(argument.dropFirst(prefix.count))
    }
 
    private static func stringValue(for key: String, in arguments: [String]) -> String? {
        let prefix = "\(key)="
        guard let argument = arguments.first(where: { $0.hasPrefix(prefix) }) else {
            return nil
        }
 
        return String(argument.dropFirst(prefix.count))
    }
 
    private static func intValue(for key: String, in arguments: [String]) -> Int? {
        stringValue(for: key, in: arguments).flatMap(Int.init)
    }
 
    private static func cgFloatValue(for key: String, in arguments: [String]) -> CGFloat? {
        stringValue(for: key, in: arguments)
            .flatMap(Double.init)
            .map { CGFloat($0) }
    }
 
    private static func stringListValue(for key: String, in arguments: [String]) -> [String] {
        guard let value = stringValue(for: key, in: arguments) else { return [] }
 
        return value
            .split(separator: ",")
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { !$0.isEmpty }
    }
}
 
@MainActor
private final class StderrScreenshotDebugLogger: ScreenshotDebugLogging {
    func record(_ event: ScreenshotDebugEvent) {
        DevelopmentDiagnostics.log("quickSwitch.screenshot.debug", [
            "event": event.diagnosticDescription
        ])
        fputs("Round01 screenshot debug: \(event.diagnosticDescription)\n", stderr)
    }
}