From 12372151cfb3b32a1aed505ad28cc2d7862c139f Mon Sep 17 00:00:00 2001 From: xcv58 Date: Wed, 25 Nov 2026 16:48:51 -0500 Subject: [PATCH 1/5] fix(window-switcher): rank newly launched foreground windows --- .../Sources/WindowSwitcherAppCatalog.swift | 238 ++++++++- .../WindowSwitcherApplicationInventory.swift | 10 +- .../Sources/WindowSwitcherProcessWorker.swift | 4 +- .../WindowSwitcherPublishedWindows.swift | 5 + .../Sources/WindowSwitcherSession.swift | 24 +- .../Sources/WindowSwitcherWindowRecords.swift | 108 ++-- .../Tests/WindowSwitcherAppCatalogTests.swift | 485 +++++++++++++++++- .../WindowSwitcherWindowRecordsTests.swift | 19 + .../window-switcher-launch-recency.md | 6 + 9 files changed, 784 insertions(+), 115 deletions(-) create mode 100644 changes/unreleased/window-switcher-launch-recency.md diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift index 6b09b100f..0ef6ac4ed 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift @@ -66,10 +66,28 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { struct DiscoveryEnvironment { var applications: (() -> [Application])? = nil + var foregroundProcessIdentifier: () -> pid_t? = { NSWorkspace.shared.frontmostApplication?.processIdentifier } var isAccessibilityTrusted: () -> Bool = { AXIsProcessTrusted() } var isDragging: () -> Bool = { CGEventSource.buttonState(.combinedSessionState, button: .left) } } + private struct FocusObservation { + let workerPID: pid_t + let id: String? + let windowNumber: CGWindowID? + let unavailable: Bool + let reportedFocusedWindow: Bool + var canInfer: Bool { !unavailable && !reportedFocusedWindow } + + init(workerPID: pid_t, scan: WindowSwitcherScan) { + self.workerPID = workerPID + id = scan.focusedID + windowNumber = scan.focusedID.flatMap { id in scan.windows.first { $0.id == id }?.windowNumber } + unavailable = scan.unavailable + reportedFocusedWindow = scan.reportedFocusedWindow + } + } + var onChange: (() -> Void)? private(set) var isInitialDiscoveryComplete = false private(set) var isInvocationReady = false @@ -107,14 +125,19 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var publicationTask: Task? private var publicationDirty = false private var removedProcesses: Set = [] - private var pendingFocus: [pid_t: (id: String?, unavailable: Bool)] = [:] + private var pendingFocus: [pid_t: [pid_t: FocusObservation]] = [:] + private var inferredFocusWorkerLifetime: UUID? private var windowRecordsPending = false private var sleeping = false private var sessionInactive = false private var suspended: Bool { sleeping || sessionInactive } private var invocationGeneration = UUID() + private var invocationInProgress = false private var invocationRequiredHosts: Set = [] + private var invocationScansStarted: Set = [] + private var queuedInvocationRetryHost: pid_t? private var invocationRequiresRecords = false + private var invocationCanRetryForegroundDiscovery = false private let allSpacesCatalog: WindowSwitcherWindowRecords private let discovery: DiscoveryEnvironment private var publication = WindowSwitcherPublishedWindows() @@ -204,11 +227,16 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { publicationDirty = false removedProcesses.removeAll() pendingFocus.removeAll() + inferredFocusWorkerLifetime = nil applicationInventory?.stop() allSpacesGeneration = UUID() invocationGeneration = UUID() + invocationInProgress = false invocationRequiredHosts.removeAll() + invocationScansStarted.removeAll() + queuedInvocationRetryHost = nil invocationRequiresRecords = false + invocationCanRetryForegroundDiscovery = false isInvocationReady = false windowRecordsPending = false allSpacesRefreshTask?.cancel(); allSpacesRefreshTask = nil @@ -276,12 +304,22 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { func prepareForInvocation() { guard running else { return } invocationGeneration = UUID() + invocationInProgress = true isInvocationReady = false + pendingFocus.removeAll() + inferredFocusWorkerLifetime = nil + publication.recency.clearInference() applicationInventory?.reconcile(notify: false) + if let pid = discovery.foregroundProcessIdentifier() { + applicationInventory?.reload(processIdentifier: pid, notify: false) + } reloadApplications() applyInvalidations() invocationRequiredHosts = expectedHostPIDs + invocationScansStarted.removeAll() + queuedInvocationRetryHost = nil invocationRequiresRecords = true + invocationCanRetryForegroundDiscovery = true dirtyHosts.formUnion(expectedHostPIDs) windowRecordsPending = true markPublicationDirty() @@ -330,6 +368,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } dirtyHosts.formIntersection(expectedHostPIDs) invocationRequiredHosts.formIntersection(expectedHostPIDs) + invocationScansStarted.formIntersection(expectedHostPIDs) + if let queuedInvocationRetryHost, !expectedHostPIDs.contains(queuedInvocationRetryHost) { + self.queuedInvocationRetryHost = nil + } dirtyHosts.formUnion(expectedHostPIDs.filter { snapshots[$0] == nil }) } @@ -342,10 +384,15 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // Preserve pending work during tracking; the short retry exists only // while a user drag prevents a requested refresh from proceeding. guard !discovery.isDragging() else { scheduleRefresh(); return } - if windowRecordsPending { refreshAllSpaces() } + // Finish publishing the invocation's visibility snapshot before + // servicing any refreshes queued behind it. + if windowRecordsPending, !invocationInProgress || invocationRequiresRecords { + refreshAllSpaces() + } + let foregroundHostPID = foregroundTarget()?.hostPID let pids = dirtyHosts.sorted { - let lhsActive = activeWorkerPID(for: $0) != nil - let rhsActive = activeWorkerPID(for: $1) != nil + let lhsActive = $0 == foregroundHostPID + let rhsActive = $1 == foregroundHostPID return lhsActive == rhsActive ? $0 < $1 : lhsActive } for pid in pids { @@ -353,6 +400,11 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { guard !inFlight.contains(pid), let application = applicationsByPID[pid] else { continue } let worker = ensureWorker(pid: pid, launchDate: application.launchDate, applicationLifetime: application.lifetime) dirtyHosts.remove(pid) + if invocationInProgress { invocationScansStarted.insert(pid) } + if queuedInvocationRetryHost == pid { + queuedInvocationRetryHost = nil + pendingInvalidations.remove(pid) + } inFlight.insert(pid) activeScanCount += 1 let app = application.withPresentation() @@ -368,7 +420,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { guard let self, running, workers[pid] === worker else { return } var entries = windowEntries(from: result, app: app, ownerPID: pid) var helperUnavailable = false - var helperFocusIDs: [pid_t: String] = [:] + var focusObservations = [pid: FocusObservation(workerPID: pid, scan: result)] for helperPID in (helperPIDsByHost[pid] ?? []).sorted() { guard let helperApp = applicationsByPID[helperPID] else { continue } let helperWorker = ensureWorker(pid: helperPID, launchDate: helperApp.launchDate, @@ -377,7 +429,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { guard running, workers[pid] === worker else { return } guard workers[helperPID] === helperWorker else { continue } if helperScan.unavailable { helperUnavailable = true } - helperFocusIDs[helperPID] = helperScan.focusedID + focusObservations[helperPID] = FocusObservation(workerPID: helperPID, scan: helperScan) entries = WindowSwitcherListing.preferringUniqueWindowNumbers( entries + windowEntries(from: helperScan, app: app, ownerPID: helperPID)) } @@ -398,12 +450,11 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } snapshots[pid] = entries if previous != entries { markPublicationDirty() } - if let activePID = activeWorkerPID(for: pid) { - pendingFocus[pid] = (activePID == pid ? result.focusedID : helperFocusIDs[activePID], unavailableScan) - markPublicationDirty() - } if invocation == invocationGeneration { - invocationRequiredHosts.remove(pid) + if queuedInvocationRetryHost != pid { invocationRequiredHosts.remove(pid) } + if let target = foregroundTarget(), target.hostPID == pid { + pendingFocus[pid] = focusObservations + } } schedulePublication() } @@ -411,13 +462,12 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { schedulePublication() } - private func activeWorkerPID(for hostPID: pid_t) -> pid_t? { - if let helperPID = (helperPIDsByHost[hostPID] ?? []).sorted().first(where: { - applicationsByPID[$0]?.isActive == true - }) { - return helperPID - } - return applicationsByPID[hostPID]?.isActive == true ? hostPID : nil + private func foregroundTarget() -> (hostPID: pid_t, workerPID: pid_t)? { + guard let foregroundPID = discovery.foregroundProcessIdentifier() else { return nil } + let hostPID = processMapping.host(for: foregroundPID) + guard expectedHostPIDs.contains(hostPID), + foregroundPID == hostPID || helperPIDsByHost[hostPID]?.contains(foregroundPID) == true else { return nil } + return (hostPID, foregroundPID) } func entries(sortMode: WindowSwitcherSortMode) -> [WindowSwitcherAppEntry] { @@ -493,6 +543,125 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } } + private func inferredForegroundWindowID(in entries: [WindowSwitcherAppEntry], + target: (hostPID: pid_t, workerPID: pid_t)) -> String? { + guard allSpacesRecordsAreFresh, !entries.isEmpty else { return nil } + let onscreenWindowNumbers = foregroundOnscreenWindowNumbers(target: target) + guard !hasUnresolvedOnscreenWindow(onscreenWindowNumbers, in: entries) else { return nil } + // A fresh WindowServer snapshot can distinguish a visible window from + // windows that are still restoring or live on other Spaces. + let screenVisibility = Dictionary(allSpacesRecords.compactMap { record in + record.isOnScreen.map { (record.windowNumber, $0) } + }, uniquingKeysWith: { first, _ in first }) + let candidates = entries.filter { entry in + (entry.axWorkerPID == target.workerPID || entry.owningProcessIdentifier == target.workerPID) + && isUsableWindow(entry) + && !publication.lostAXConfirmation(entry) + && entry.windowNumber.flatMap { screenVisibility[$0] } != false + } + if candidates.count == 1 { return candidates.first?.id } + let onscreen = candidates.filter { $0.windowNumber.flatMap { screenVisibility[$0] } == true } + return onscreen.count == 1 ? onscreen.first?.id : nil + } + + private func isUsableWindow(_ entry: WindowSwitcherAppEntry) -> Bool { + entry.isWindowEntry && !entry.isHidden && !entry.isMinimized + && !entry.isOnOtherDesktop && !entry.metadataUnavailable + } + + private func foregroundOnscreenWindowNumbers(target: (hostPID: pid_t, workerPID: pid_t)) -> Set { + let ownerPIDs = target.workerPID == target.hostPID + ? (helperPIDsByHost[target.hostPID] ?? []).union([target.workerPID]) + : [target.workerPID] + return Set(allSpacesRecords.lazy.filter { + $0.isOnScreen == true && $0.isOnActiveSpace != false && ownerPIDs.contains($0.processIdentifier) + }.map(\.windowNumber)) + } + + private func hasUnresolvedOnscreenWindow(_ onscreen: Set, in entries: [WindowSwitcherAppEntry], + requiresAXConfirmation: Bool = false) -> Bool { + let listed = Set(entries.filter { entry in + isUsableWindow(entry) && (entry.windowElement != nil + || (!requiresAXConfirmation && !publication.lostAXConfirmation(entry))) + }.compactMap(\.windowNumber)) + return !onscreen.isSubset(of: listed) + } + + private func exactWindowID(for focus: FocusObservation, in entries: [WindowSwitcherAppEntry]) -> String? { + // Deduplication can keep the host's AX row for a helper-owned window. + entries.first { entry in + (entry.workerWindowID ?? entry.id) == focus.id + || (entry.owningProcessIdentifier == focus.workerPID + && focus.windowNumber != nil && entry.windowNumber == focus.windowNumber) + }?.id + } + + private func publishForegroundFocus() -> Bool { + guard inferredFocusWorkerLifetime != nil || !pendingFocus.isEmpty else { return false } + let target = foregroundTarget() + let workerLifetime = target.flatMap { workers[$0.workerPID]?.lifetime } + if let inferredFocusWorkerLifetime, inferredFocusWorkerLifetime != workerLifetime { + self.inferredFocusWorkerLifetime = nil + publication.recency.clearInference() + } + guard !pendingFocus.isEmpty else { return false } + let observations = target.flatMap { pendingFocus[$0.hostPID] } + pendingFocus.removeAll() + guard let target, let observations, let focus = observations[target.workerPID] else { + publication.recency.clearInference() + inferredFocusWorkerLifetime = nil + return false + } + let entries = publication.entries.filter { $0.processIdentifier == target.hostPID } + var exactID = exactWindowID(for: focus, in: entries) + // Workspace can report the host for a focused helper. A cached active + // flag permits checking a helper's exact AX focus, but cannot infer it. + if exactID == nil, !focus.reportedFocusedWindow, target.workerPID == target.hostPID { + exactID = helperPIDsByHost[target.hostPID]?.sorted().lazy.compactMap { pid -> String? in + guard self.applicationsByPID[pid]?.isActive == true, let helperFocus = observations[pid] else { return nil } + return self.exactWindowID(for: helperFocus, in: entries) + }.first + } + let shouldInfer = exactID == nil && focus.canInfer + let unresolvedReportedFocus = exactID == nil && focus.reportedFocusedWindow + // AX can finish before the current WindowServer read. Keep the focus + // observation for publication when the matching visibility is available. + let visibilityPending = invocationInProgress + ? invocationRequiresRecords || !invocationRequiredHosts.isEmpty + : windowRecordsPending || allSpacesRefreshTask != nil + if shouldInfer || unresolvedReportedFocus, visibilityPending { + pendingFocus[target.hostPID] = observations + publication.recency.clearInference() + inferredFocusWorkerLifetime = nil + return false + } + let inferredID = shouldInfer ? inferredForegroundWindowID(in: entries, target: target) : nil + inferredFocusWorkerLifetime = inferredID == nil ? nil : workerLifetime + publication.recency.observeForeground(entries: entries, focusedWindowID: exactID, + inferredWindowID: inferredID, unavailable: focus.unavailable) + return unresolvedReportedFocus + } + + private func retryForegroundDiscoveryIfNeeded(unresolvedReportedFocus: Bool) { + guard invocationCanRetryForegroundDiscovery else { return } + invocationCanRetryForegroundDiscovery = false + // A launch can put a window onscreen before the app publishes its AX + // window list. Retry the scan while keeping the normal listing rules. + guard allSpacesRecordsAreFresh, let target = foregroundTarget() else { return } + let entries = publication.entries.filter { $0.processIdentifier == target.hostPID } + let onscreen = foregroundOnscreenWindowNumbers(target: target) + let hasConfirmedOnscreenFocus = entries.contains { entry in + entry.id == publication.recency.confirmedFocusID + && entry.windowNumber.map(onscreen.contains) == true + } + guard !hasConfirmedOnscreenFocus, + hasUnresolvedOnscreenWindow(onscreen, in: entries, requiresAXConfirmation: unresolvedReportedFocus) + else { return } + queuedInvocationRetryHost = target.hostPID + invocationRequiredHosts.insert(target.hostPID) + invalidate(processIdentifiers: [target.hostPID], windowRecords: false) + } + private func markPublicationDirty() { publicationDirty = true schedulePublication() @@ -514,18 +683,18 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { removedProcesses.removeAll() rebuildPublication() } - for (pid, focus) in pendingFocus where activeWorkerPID(for: pid) != nil { - let entries = publication.entries.filter { $0.processIdentifier == pid } - let id = entries.first { ($0.workerWindowID ?? $0.id) == focus.id }?.id - publication.recency.observeForeground(entries: entries, focusedWindowID: id, unavailable: focus.unavailable) - } - pendingFocus.removeAll() + let unresolvedReportedFocus = publishForegroundFocus() isInitialDiscoveryComplete = didReadAllSpaces && expectedHostPIDs.allSatisfy { snapshots[$0] != nil } - isInvocationReady = isInitialDiscoveryComplete && !invocationRequiresRecords && invocationRequiredHosts.isEmpty + let discoveryIsReady = isInitialDiscoveryComplete && !invocationRequiresRecords && invocationRequiredHosts.isEmpty + if discoveryIsReady { retryForegroundDiscoveryIfNeeded(unresolvedReportedFocus: unresolvedReportedFocus) } + isInvocationReady = discoveryIsReady && invocationRequiredHosts.isEmpty && pendingFocus.isEmpty + let completedInvocation = invocationInProgress && isInvocationReady + if completedInvocation { invocationInProgress = false } if oldEntries != publication.entries || oldFocus != publication.recency.focusedID || wasComplete != isInitialDiscoveryComplete || wasReady != isInvocationReady { onChange?() } + if completedInvocation, windowRecordsPending { drainRefreshes() } } } @@ -534,9 +703,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { windowRecordsPending = false let generation = allSpacesGeneration let invocation = invocationGeneration + let isInvocationCapture = invocationInProgress && invocationRequiresRecords allSpacesRefreshTask = Task { [weak self] in guard let self else { return } - let result = await allSpacesCatalog.freshWindowRecordSnapshot() + let result = await allSpacesCatalog.freshWindowRecordSnapshot(requiresNewCapture: isInvocationCapture) guard !Task.isCancelled, running, allSpacesGeneration == generation else { return } allSpacesRefreshTask = nil let oldRecords = Dictionary(grouping: allSpacesRecords, by: \.processIdentifier) @@ -551,17 +721,29 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { helperPIDsByHost = processMapping.helpersByHost(owningWindowsIn: allSpacesRecords) allSpacesRecordsAreFresh = result.isFresh if oldHelpers != helperPIDsByHost { reloadApplications() } + let foregroundRetryHost = isInvocationCapture && invocation == invocationGeneration + ? foregroundTarget()?.hostPID : nil // New helper ownership and missing AX events must schedule a scoped // scan, including when another read of that host is already active. for pid in expectedHostPIDs { let changed = changedOwners.contains { processMapping.host(for: $0) == pid } if oldHelpers[pid] != helperPIDsByHost[pid] || (changed && snapshots[pid] != nil) { dirtyHosts.insert(pid) + // The current visibility read already requested another + // foreground AX pass. It consumes this invocation's retry. + if pid == foregroundRetryHost, invocationCanRetryForegroundDiscovery, + invocationScansStarted.contains(pid) { + invocationCanRetryForegroundDiscovery = false + queuedInvocationRetryHost = pid + invocationRequiredHosts.insert(pid) + } } } didReadAllSpaces = true - if invocation == invocationGeneration { invocationRequiresRecords = false } - if !isInvocationReady { invocationRequiredHosts.formUnion(dirtyHosts) } + if invocation == invocationGeneration { + invocationRequiresRecords = false + if !invocationInProgress, !isInvocationReady { invocationRequiredHosts.formUnion(dirtyHosts) } + } schedulePublication() drainRefreshes() } diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift index b677938df..8ea4ea63d 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift @@ -101,26 +101,26 @@ final class WindowSwitcherApplicationInventory { if notify, !changed.isEmpty { onChange?(changed) } } - func reload(processIdentifier: pid_t) { + func reload(processIdentifier: pid_t, notify: Bool = true) { for identity in entries.keys where entries[identity]?.application.processIdentifier == processIdentifier { - reload(identity) + reload(identity, notify: notify) break } } - private func reload(_ identity: AnyHashable) { + private func reload(_ identity: AnyHashable, notify: Bool = true) { guard running, var entry = entries[identity] else { return } let old = entry.application guard var application = entry.source.load(), application.processIdentifier > 0 else { entries.removeValue(forKey: identity) - onChange?([old.processIdentifier]) + if notify { onChange?([old.processIdentifier]) } return } application.lifetime = application.processIdentifier == old.processIdentifier ? old.lifetime : UUID() entry.application = application entries[identity] = entry - onChange?([old.processIdentifier, application.processIdentifier]) + if notify { onChange?([old.processIdentifier, application.processIdentifier]) } } private static func source(_ app: NSRunningApplication) -> Source { diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift index ae8731327..cd099fd56 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift @@ -20,6 +20,7 @@ struct WindowSwitcherScan: Sendable { var focusedID: String? var unavailable: Bool var windowListReadSucceeded = true + var reportedFocusedWindow = false } struct WindowSwitcherAXIdentity: Hashable { @@ -184,7 +185,8 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { cursor = count == 0 ? 0 : (cursor + didRead) % count let focused = uptime() < deadline ? copyElement(app, kAXFocusedWindowAttribute) : nil let focusedID = focused.flatMap { element in records.first { CFEqual($0.element, element) }?.id } - return WindowSwitcherScan(windows: records, focusedID: focusedID, unavailable: metadataFailed || didRead < count) + return WindowSwitcherScan(windows: records, focusedID: focusedID, + unavailable: metadataFailed || didRead < count, reportedFocusedWindow: focused != nil) } private enum Admission { case eligible(WindowSwitcherWindowSnapshot), excluded, unavailable } diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherPublishedWindows.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherPublishedWindows.swift index 17dd7c516..bac69898b 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherPublishedWindows.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherPublishedWindows.swift @@ -10,6 +10,11 @@ struct WindowSwitcherPublishedWindows { private var confirmedAXWindowNumbers: [pid_t: Set] = [:] private var axAliases: [pid_t: [String: String]] = [:] + func lostAXConfirmation(_ entry: WindowSwitcherAppEntry) -> Bool { + guard entry.windowElement == nil, let number = entry.windowNumber else { return false } + return confirmedAXWindowNumbers[entry.processIdentifier]?.contains(number) == true + } + mutating func removeProcess(_ pid: pid_t) { knownWindowIDs.removeValue(forKey: pid) axAliases.removeValue(forKey: pid) diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift index b47c3a243..4e9616256 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift @@ -133,30 +133,38 @@ struct WindowSwitcherSession { struct WindowSwitcherRecency { private(set) var ids: [String] = [] - private(set) var focusedID: String? + private(set) var confirmedFocusID: String? + private var inferredFocusID: String? + var focusedID: String? { inferredFocusID ?? confirmedFocusID } - mutating func observeForeground(entries: [WindowSwitcherAppEntry], focusedWindowID: String?, unavailable: Bool) { + mutating func observeForeground(entries: [WindowSwitcherAppEntry], focusedWindowID: String?, + inferredWindowID: String? = nil, unavailable: Bool) { if let focusedWindowID, entries.contains(where: { $0.id == focusedWindowID }) { record(focusedWindowID) } else if !unavailable, entries.count == 1, let fallback = entries.first, !fallback.isWindowEntry { record(fallback.id) } else { - // An unknown foreground target must not keep another app's window - // marked current. Keep its recency position, but clear the anchor. - focusedID = nil + // Inferred focus can lead the current order without changing history. + confirmedFocusID = nil + inferredFocusID = inferredWindowID } } + mutating func clearInference() { inferredFocusID = nil } + mutating func record(_ id: String) { - focusedID = id + clearInference() + confirmedFocusID = id ids.removeAll { $0 == id } ids.insert(id, at: 0) } mutating func retain(_ live: Set) { ids.removeAll { !live.contains($0) } - if let focusedID, !live.contains(focusedID) { self.focusedID = nil } + if let confirmedFocusID, !live.contains(confirmedFocusID) { self.confirmedFocusID = nil } + if let inferredFocusID, !live.contains(inferredFocusID) { clearInference() } } func sort(_ entries: [WindowSwitcherAppEntry]) -> [WindowSwitcherAppEntry] { - let ranks = Dictionary(uniqueKeysWithValues: ids.enumerated().map { ($0.element, $0.offset) }) + var ranks = Dictionary(uniqueKeysWithValues: ids.enumerated().map { ($0.element, $0.offset) }) + if let inferredFocusID { ranks[inferredFocusID] = -1 } return entries.enumerated().sorted { let lhs = ranks[$0.element.id] ?? Int.max let rhs = ranks[$1.element.id] ?? Int.max diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift index ddec1f790..02545e4f9 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift @@ -137,15 +137,20 @@ struct WindowSwitcherWindowRecordSnapshot: Sendable { /// Slow system reads are bounded and stale data can never authorize an action. @MainActor final class WindowSwitcherWindowRecords { + private struct Capture { + let task: Task<[WindowSwitcherWindowRecord]?, Never> + let timeout: Task + var waiters: [UUID: CheckedContinuation] = [:] + } + private static let maxWindowRecordRefreshesInFlight = 2 private let windowRecordProvider: @Sendable () -> [WindowSwitcherWindowRecord]? private let windowRecordRefreshTimeout: TimeInterval private var windowRecords: [WindowSwitcherWindowRecord] = [] - private var windowRecordRefreshTask: Task<[WindowSwitcherWindowRecord]?, Never>? + private var captures: [UInt64: Capture] = [:] private var windowRecordRefreshGeneration: UInt64 = 0 + private var cachedGeneration: UInt64 = 0 private var windowRecordRefreshInFlightCount = 0 - private var timeoutTask: Task? - private var waiters: [UUID: CheckedContinuation] = [:] init(windowRecordRefreshTimeout: TimeInterval = 0.75, windowRecordProvider: @escaping @Sendable () -> [WindowSwitcherWindowRecord]? = { @@ -158,13 +163,11 @@ final class WindowSwitcherWindowRecords { } func stop() { - windowRecordRefreshGeneration &+= 1 - windowRecordRefreshTask?.cancel() - windowRecordRefreshTask = nil - timeoutTask?.cancel() - timeoutTask = nil windowRecords.removeAll() - finishWaiters(isFresh: false) + cachedGeneration = 0 + for generation in Array(captures.keys) { + finishCapture(generation, records: nil) + } } func windowRecordsSnapshot() async -> [WindowSwitcherWindowRecord] { @@ -213,12 +216,8 @@ final class WindowSwitcherWindowRecords { return record } - private func refreshWindowRecords() { - guard windowRecordRefreshTask == nil, - windowRecordRefreshInFlightCount < Self.maxWindowRecordRefreshesInFlight - else { - return - } + private func startCapture() -> UInt64? { + guard windowRecordRefreshInFlightCount < Self.maxWindowRecordRefreshesInFlight else { return nil } windowRecordRefreshGeneration &+= 1 let generation = windowRecordRefreshGeneration @@ -227,87 +226,62 @@ final class WindowSwitcherWindowRecords { let task = Task.detached(priority: .userInitiated) { provider() } - windowRecordRefreshTask = task - let timeout = windowRecordRefreshTimeout - timeoutTask = Task { [weak self] in - do { try await Task.sleep(for: .seconds(timeout)) } catch { return } - self?.abandonWindowRecordRefresh(generation: generation) + let timeout = Task { [weak self, windowRecordRefreshTimeout] in + do { try await Task.sleep(for: .seconds(windowRecordRefreshTimeout)) } catch { return } + self?.finishCapture(generation, records: nil) } + captures[generation] = Capture(task: task, timeout: timeout) Task { @MainActor [weak self] in let records = await task.value - guard let self, - self.windowRecordRefreshInFlightCount > 0 - else { - return - } - self.windowRecordRefreshInFlightCount -= 1 - - guard self.windowRecordRefreshGeneration == generation else { - return - } - - guard self.windowRecordRefreshTask != nil else { - return - } - - self.windowRecordRefreshTask = nil - self.timeoutTask?.cancel() - self.timeoutTask = nil - // Failure is not a successful empty scan. Retain the last snapshot - // for presentation, but never mark it fresh enough for an action. - if let records { - self.windowRecords = records - } - self.finishWaiters(isFresh: records != nil) + guard let self else { return } + windowRecordRefreshInFlightCount -= 1 + finishCapture(generation, records: records) } + return generation } private func freshWindowRecords() async -> [WindowSwitcherWindowRecord] { await freshWindowRecordSnapshot().records } - func freshWindowRecordSnapshot() async -> WindowSwitcherWindowRecordSnapshot { + func freshWindowRecordSnapshot(requiresNewCapture: Bool = false) async -> WindowSwitcherWindowRecordSnapshot { guard !Task.isCancelled else { return .init(records: windowRecords, isFresh: false) } - refreshWindowRecords() - guard windowRecordRefreshTask != nil else { + let generation = requiresNewCapture ? startCapture() : captures.keys.max() ?? startCapture() + guard let generation else { return WindowSwitcherWindowRecordSnapshot(records: windowRecords, isFresh: false) } let id = UUID() return await withTaskCancellationHandler { await withCheckedContinuation { continuation in - guard !Task.isCancelled else { + guard !Task.isCancelled, captures[generation] != nil else { continuation.resume(returning: .init(records: windowRecords, isFresh: false)) return } - waiters[id] = continuation + captures[generation]?.waiters[id] = continuation } } onCancel: { Task { @MainActor [weak self] in guard let self else { return } - waiters.removeValue(forKey: id)?.resume(returning: .init(records: windowRecords, isFresh: false)) + captures[generation]?.waiters.removeValue(forKey: id)? + .resume(returning: .init(records: windowRecords, isFresh: false)) } } } - private func abandonWindowRecordRefresh(generation: UInt64) { - guard windowRecordRefreshGeneration == generation else { - return + private func finishCapture(_ generation: UInt64, records: [WindowSwitcherWindowRecord]?) { + guard let capture = captures.removeValue(forKey: generation) else { return } + capture.timeout.cancel() + if records == nil { capture.task.cancel() } + // An older capture can finish after a new invocation has already + // published its own result. Keep the cache ordered by capture start. + if let records, generation > cachedGeneration { + cachedGeneration = generation + windowRecords = records } - - windowRecordRefreshTask?.cancel() - windowRecordRefreshTask = nil - windowRecordRefreshGeneration &+= 1 - timeoutTask?.cancel() - timeoutTask = nil - finishWaiters(isFresh: false) - } - - private func finishWaiters(isFresh: Bool) { - let pending = waiters - waiters.removeAll() - let snapshot = WindowSwitcherWindowRecordSnapshot(records: windowRecords, isFresh: isFresh) - for continuation in pending.values { continuation.resume(returning: snapshot) } + let snapshot = WindowSwitcherWindowRecordSnapshot(records: windowRecords, + isFresh: records != nil && generation == cachedGeneration) + for continuation in capture.waiters.values { continuation.resume(returning: snapshot) } } } diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift index 3c98f089b..b5ba1c07c 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift @@ -14,18 +14,25 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable private let lock = NSLock() private var state: State private let window: AXUIElement + private let replacement: AXUIElement? + private let replacementNumber: CGWindowID? let observesSystemNotifications = false - init(number: CGWindowID?, elementPID: pid_t) { + init(number: CGWindowID?, elementPID: pid_t, replacementNumber: CGWindowID? = nil) { state = State(number: number) window = AXUIElementCreateApplication(elementPID) + self.replacementNumber = replacementNumber + replacement = replacementNumber.map { _ in AXUIElementCreateApplication(elementPID + 100) } } func update(_ body: (inout State) -> Void) { lock.lock(); defer { lock.unlock() }; body(&state) } func read(_ body: (State) -> T) -> T { lock.lock(); defer { lock.unlock() }; return body(state) } func windows(of application: AXUIElement) -> [AXUIElement]? { update { $0.reads += 1 } read { $0.beforeRead }?() - return read { $0.number == nil ? [] : [window] } + return read { state in + guard let number = state.number else { return [] } + return [number == replacementNumber ? replacement ?? window : window] + } } func element(_ owner: AXUIElement, attribute: String) -> AXUIElement? { if attribute == kAXFocusedWindowAttribute, read({ $0.focused }) { return window } @@ -152,6 +159,331 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(numbers(catalog), [9]) } + func testNewlyLaunchedForegroundWindowRanksFirstBeforeAccessibilityReportsFocus() async throws { + let first = CatalogAXAccess(number: 7, elementPID: 201) + first.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + var launchedExists = false + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? first : launched }, + allSpacesCatalog: .init(windowRecordProvider: { [] }), + discovery: .init(applications: { + let first = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "first", localizedName: "First", isActive: true) + let launched = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched") + return launchedExists ? [first, launched] : [first] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + launchedExists = true + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + + foregroundPID = 42 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7, 8]) + } + + func testInvocationRetriesForegroundDiscoveryOnceWhenWindowServerSeesAWindow() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + launched.update { + $0.beforeRead = { [weak launched] in + launched?.update { state in + guard state.reads == 2 else { return } + state.number = 8 + state.focused = true + } + } + } + var launchedExists = false + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Launched", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600))] + }), + discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let launched = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched") + return launchedExists ? [previous, launched] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + launchedExists = true + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 2) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [8, 7]) + + launched.update { + $0.number = nil + $0.focused = false + $0.beforeRead = nil + } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 4) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7]) + } + + func testOffscreenAXWindowDoesNotSuppressRetryForAnUnlistedOnscreenWindow() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + launched.update { + $0.beforeRead = { [weak launched] in + launched?.update { state in + guard state.reads == 2 else { return } + state.number = 9 + state.focused = true + } + } + } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: false, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), isOnActiveSpace: true), + .init(windowNumber: 9, processIdentifier: 43, title: "", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600), titleIsAvailable: false)] + }), + discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched") + return foregroundPID == 43 ? [prior, new] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 2) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [9, 7]) + } + + func testInvocationPublishesBeforeQueuedBackgroundVisibilityReadCompletes() async throws { + let access = CatalogAXAccess(number: 7, elementPID: 201) + let blockRead = DispatchSemaphore(value: 0) + let readStarted = DispatchSemaphore(value: 0) + let releaseRead = DispatchSemaphore(value: 0) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { _ in access }, + allSpacesCatalog: .init(windowRecordRefreshTimeout: 5, windowRecordProvider: { + if blockRead.wait(timeout: .now()) == .success { + readStarted.signal() + _ = releaseRead.wait(timeout: .now() + 5) + } + return [] + }), + discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "fixture", localizedName: "Fixture")] + }, foregroundProcessIdentifier: { 42 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseRead.signal(); releaseRead.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + blockRead.signal() + blockRead.signal() + catalog.prepareForInvocation() + try await waitUntil { readStarted.wait(timeout: .now()) == .success } + XCTAssertFalse(catalog.isInvocationReady) + catalog.refresh() + releaseRead.signal() + + try await waitUntil { readStarted.wait(timeout: .now()) == .success } + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.first?.windowNumber, 7) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + + func testInvocationStartsFreshCaptureAndUsesOnlyOneVisibilityDrivenRetry() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + let holdOlderCapture = DispatchSemaphore(value: 0) + let olderCaptureStarted = DispatchSemaphore(value: 0) + let releaseOlderCapture = DispatchSemaphore(value: 0) + let holdInvocationCapture = DispatchSemaphore(value: 0) + let invocationCaptureStarted = DispatchSemaphore(value: 0) + let releaseInvocationCapture = DispatchSemaphore(value: 0) + let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 5, windowRecordProvider: { + if holdOlderCapture.wait(timeout: .now()) == .success { + olderCaptureStarted.signal() + _ = releaseOlderCapture.wait(timeout: .now() + 5) + return [] + } + guard holdInvocationCapture.wait(timeout: .now()) == .success else { return [] } + invocationCaptureStarted.signal() + _ = releaseInvocationCapture.wait(timeout: .now() + 5) + return [.init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: false, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), + .init(windowNumber: 9, processIdentifier: 43, title: "", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600), titleIsAvailable: false)] + }) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, allSpacesCatalog: reader, + discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let launched = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched") + return foregroundPID == 43 ? [previous, launched] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { + releaseOlderCapture.signal() + releaseInvocationCapture.signal() + catalog.stop() + } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + holdOlderCapture.signal() + let activation = Task { await reader.freshRecordsForActivation() } + try await waitUntil { olderCaptureStarted.wait(timeout: .now()) == .success } + activation.cancel() + + holdInvocationCapture.signal() + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { invocationCaptureStarted.wait(timeout: .now()) == .success } + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 } } + XCTAssertEqual(launched.read { $0.reads }, 1) + XCTAssertFalse(catalog.isInvocationReady) + releaseInvocationCapture.signal() + + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 2) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7, 8]) + XCTAssertNil(catalog.focusedWindowID) + } + + func testForegroundChangeDropsInferenceBeforeInvocationBecomesReady() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let first = CatalogAXAccess(number: 8, elementPID: 202) + let second = CatalogAXAccess(number: 9, elementPID: 203) + let slow = CatalogAXAccess(number: 11, elementPID: 204) + let release = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 41 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 41: previous + case 42: first + case 43: second + default: slow + } + }, allSpacesCatalog: .init(windowRecordProvider: { [] }), + discovery: .init(applications: { + (41...44).map { pid in + .init(processIdentifier: pid_t(pid), bundleIdentifier: "fixture.\(pid)", localizedName: "Fixture \(pid)") + } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { release.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + slow.update { $0.beforeRead = { _ = release.wait(timeout: .now() + 2) } } + second.update { + $0.number = 10 + $0.focused = true + } + foregroundPID = 42 + catalog.prepareForInvocation() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 10 } } + XCTAssertFalse(catalog.isInvocationReady) + + foregroundPID = 43 + catalog.invalidate(processIdentifiers: [43], windowRecords: true) + release.signal() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertNotEqual(entries.first?.windowNumber, 8) + XCTAssertNotEqual(catalog.focusedWindowID, entries.first { $0.windowNumber == 8 }?.id) + } + + func testRecentUseWaitsForVisibilityAndKeepsInferenceOutOfHistory() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + let failNextRead = DispatchSemaphore(value: 0) + let delayNextRead = DispatchSemaphore(value: 0) + let releaseRead = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordRefreshTimeout: 2, windowRecordProvider: { + if failNextRead.wait(timeout: .now()) == .success { return nil } + if delayNextRead.wait(timeout: .now()) == .success { + _ = releaseRead.wait(timeout: .now() + 2) + } + return [.init(windowNumber: 9, processIdentifier: 43, title: "Onscreen", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600))] + }), + discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous"), + .init(processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched")] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseRead.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + failNextRead.signal() + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).last?.metadataUnavailable, true) + + foregroundPID = 43 + launched.update { $0.number = 8 } + delayNextRead.signal() + catalog.prepareForInvocation() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 } } + XCTAssertFalse(catalog.isInvocationReady) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 7) + releaseRead.signal() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [9, 7, 8]) + + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 9) + + launched.update { $0.focused = true } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7, 9]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + var session = WindowSwitcherSession(entries: entries, selectedID: catalog.focusedWindowID, + isPersistent: false, originalWindowID: catalog.focusedWindowID) + session.advance(1) + XCTAssertEqual(session.selected?.windowNumber, 7) + } + func testWakeAndSpaceChangesDoNotResumeAnInactiveSession() async throws { let first = CatalogAXAccess(number: 7, elementPID: 201) let second = CatalogAXAccess(number: 8, elementPID: 202) @@ -181,7 +513,7 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { discovery: .init(applications: { [.init(processIdentifier: 42, bundleIdentifier: "first", bundlePath: "/First.app", localizedName: "First"), .init(processIdentifier: 43, bundleIdentifier: "second", bundlePath: "/Second.app", localizedName: "Second")] - }, isAccessibilityTrusted: { true }, isDragging: isDragging)) + }, foregroundProcessIdentifier: { nil }, isAccessibilityTrusted: { true }, isDragging: isDragging)) } private func makeCatalog(host: CatalogAXAccess, helper: CatalogAXAccess, @@ -198,15 +530,19 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { [.init(processIdentifier: 42, bundleIdentifier: "fixture.host", bundlePath: "/Fixture.app", localizedName: "Fixture"), .init(processIdentifier: 43, bundleIdentifier: "fixture.host.helper", bundlePath: "/Fixture.app/Helper.app", localizedName: "Helper", isRegular: false, isActive: helperIsActive)] - }, isAccessibilityTrusted: { true }, isDragging: { false })) + }, foregroundProcessIdentifier: { helperIsActive ? 42 : nil }, + isAccessibilityTrusted: { true }, isDragging: { false })) } private func waitUntil(_ condition: () -> Bool, file: StaticString = #filePath, line: UInt = #line) async throws { let deadline = ContinuousClock.now + .seconds(2) - while !condition(), ContinuousClock.now < deadline { + while !condition() { + guard ContinuousClock.now < deadline else { + XCTFail("Condition was not met before the deadline", file: file, line: line) + return + } try await Task.sleep(for: .milliseconds(5)) } - XCTAssertTrue(condition(), file: file, line: line) } private func numbers(_ catalog: WindowSwitcherAppCatalog) -> Set { @@ -284,4 +620,141 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.id, focused) XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.axWorkerPID, 43) } + + func testCachedHelperActivationDoesNotOverrideExactForegroundHostFocus() async throws { + let host = CatalogAXAccess(number: 7, elementPID: 201) + host.update { $0.focused = true } + let helper = CatalogAXAccess(number: 8, elementPID: 202) + let catalog = makeCatalog(host: host, helper: helper, helperIsActive: true) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [7, 8]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + + func testUnlistedHostFocusRetriesBeforeConsideringCachedHelperFocus() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + launched.update { + $0.focused = true + $0.beforeRead = { [weak launched] in + launched?.update { state in + if state.reads == 2 { state.number = 9 } + } + } + } + let helper = CatalogAXAccess(number: 8, elementPID: 203) + helper.update { $0.focused = true } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: helper + } + }, allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 9, processIdentifier: 43, title: "New foreground window", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600)), + .init(windowNumber: 8, processIdentifier: 44, title: "Helper", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600))] + }), discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + guard foregroundPID == 43 else { return [previous] } + return [previous, + .init(processIdentifier: 43, bundleIdentifier: "launched", bundlePath: "/Launched.app", + localizedName: "Launched"), + .init(processIdentifier: 44, bundleIdentifier: "launched.helper", + bundlePath: "/Launched.app/Helper.app", localizedName: "Helper", isRegular: false, isActive: true)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 2) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [9, 7, 8]) + } + + func testPreviouslyAXListedWindowCannotBecomeAnchorAfterItsAXRowDisappears() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let foreground = CatalogAXAccess(number: 9, elementPID: 202, replacementNumber: 8) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : foreground }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Offscreen", isOnScreen: false, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true), + .init(windowNumber: 9, processIdentifier: 43, title: "Previously listed window", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600), hasSpace: true)] + }), + discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous"), + .init(processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground")] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + XCTAssertNotNil(catalog.entries(sortMode: .fixed).first { $0.windowNumber == 9 }?.windowElement) + + foreground.update { $0.number = 8 } + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + let fallback = try XCTUnwrap(entries.first { $0.windowNumber == 9 }) + XCTAssertNil(fallback.windowElement) + XCTAssertNil(catalog.focusedWindowID) + XCTAssertEqual(entries.first?.windowNumber, 7) + } + + func testForegroundHelperUsesOnlyWindowsTiedToItsProcess() async throws { + let host = CatalogAXAccess(number: 7, elementPID: 201) + let helper = CatalogAXAccess(number: nil, elementPID: 202) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? host : helper }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), titleIsAvailable: false)] + }), + discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "fixture.host", bundlePath: "/Fixture.app", + localizedName: "Fixture"), + .init(processIdentifier: 43, bundleIdentifier: "fixture.host.helper", bundlePath: "/Fixture.app/Helper.app", + localizedName: "Helper", isRegular: false)] + }, foregroundProcessIdentifier: { 43 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7]) + XCTAssertNil(catalog.focusedWindowID) + + host.update { $0.number = 8 } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entry = try XCTUnwrap(catalog.entries(sortMode: .recentUse).first) + XCTAssertEqual(entry.owningProcessIdentifier, 43) + XCTAssertEqual(entry.axWorkerPID, 42) + XCTAssertEqual(catalog.focusedWindowID, entry.id) + + helper.update { $0.focused = true } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertNil(catalog.focusedWindowID) + + helper.update { $0.number = 8 } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.focusedWindowID, entry.id) + } } diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift index 9ec000a0e..aa0b022e1 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift @@ -56,6 +56,25 @@ final class WindowSwitcherWindowRecordsTests: XCTestCase { XCTAssertEqual(snapshot.records.map(\.windowNumber), [1]) } + func testNewCaptureSupersedesAnOlderCaptureThatFinishesLater() async throws { + let provider = BlockingWindowRecords() + let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 2, windowRecordProvider: { provider.read() }) + defer { provider.release.signal(); reader.stop() } + let older = Task { await reader.freshWindowRecordSnapshot() } + try await waitUntil { provider.counts.started == 1 } + + provider.unblock() + let current = await reader.freshWindowRecordSnapshot(requiresNewCapture: true) + XCTAssertTrue(current.isFresh) + XCTAssertEqual(current.records.map(\.windowNumber), [2]) + XCTAssertEqual(provider.counts.completed, 1) + + provider.release.signal() + let superseded = await older.value + XCTAssertFalse(superseded.isFresh) + XCTAssertEqual(superseded.records.map(\.windowNumber), [2]) + } + func testTimeoutKeepsPhysicalQueriesBoundedAndIgnoresTheirLateResults() async throws { let provider = BlockingWindowRecords() let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 0.03, windowRecordProvider: { provider.read() }) diff --git a/changes/unreleased/window-switcher-launch-recency.md b/changes/unreleased/window-switcher-launch-recency.md new file mode 100644 index 000000000..7cb9496eb --- /dev/null +++ b/changes/unreleased/window-switcher-launch-recency.md @@ -0,0 +1,6 @@ +--- +release: plugin +type: fixed +--- + +Window Switcher puts a newly launched foreground window first in Recent Use when the window can be identified while Accessibility is still catching up. From ef5b2884badcb4ba5d0858002b143f6b92ef726d Mon Sep 17 00:00:00 2001 From: xcv58 Date: Wed, 25 Nov 2026 17:45:21 -0500 Subject: [PATCH 2/5] fix(window-switcher): reconcile foreground changes during discovery --- .../Sources/WindowSwitcherAppCatalog.swift | 140 +++++++++++++---- .../WindowSwitcherApplicationInventory.swift | 3 +- .../Sources/WindowSwitcherPlugin.swift | 2 + .../Sources/WindowSwitcherProcessWorker.swift | 22 ++- .../Sources/WindowSwitcherSession.swift | 4 + .../Sources/WindowSwitcherWindowRecords.swift | 5 +- .../Tests/WindowSwitcherAppCatalogTests.swift | 144 ++++++++++++++++-- .../Tests/WindowSwitcherLifecycleTests.swift | 3 + .../WindowSwitcherWindowRecordsTests.swift | 9 +- 9 files changed, 282 insertions(+), 50 deletions(-) diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift index 0ef6ac4ed..926743e71 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift @@ -13,6 +13,7 @@ protocol WindowSwitcherCatalog: AnyObject { func stop() func refresh() func prepareForInvocation() + func cancelInvocation() func entries(sortMode: WindowSwitcherSortMode) -> [WindowSwitcherAppEntry] func activate(_ entry: WindowSwitcherAppEntry, intent: WindowSwitcherActivationIntent) async -> WindowSwitcherActionResult func closeWindow(_ entry: WindowSwitcherAppEntry) async -> WindowSwitcherActionResult @@ -22,6 +23,7 @@ protocol WindowSwitcherCatalog: AnyObject { extension WindowSwitcherCatalog { var isInvocationReady: Bool { isInitialDiscoveryComplete } func prepareForInvocation() { refresh() } + func cancelInvocation() {} var listingPolicy: WindowSwitcherListingPolicy { get { .default } @@ -47,6 +49,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { var launchDate: Date? = nil var lifetime: UUID? = nil var isRegular = true + var isFinishedLaunching = true var isHidden = false var isActive = false var loadPresentation: (() -> Presentation)? = nil @@ -108,6 +111,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var observers: [NSObjectProtocol] = [] private var workers: [pid_t: WindowSwitcherProcessWorker] = [:] private var snapshots: [pid_t: [WindowSwitcherAppEntry]] = [:] + private var excludedWindowNumbersByHost: [pid_t: Set] = [:] private var inFlight: Set = [] // Kept across stop/start until the actual worker returns. private var activeScanCount = 0 @@ -133,11 +137,14 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var suspended: Bool { sleeping || sessionInactive } private var invocationGeneration = UUID() private var invocationInProgress = false + private var invocationForegroundPID: pid_t? + private var invocationCanRescanForeground = false private var invocationRequiredHosts: Set = [] private var invocationScansStarted: Set = [] private var queuedInvocationRetryHost: pid_t? private var invocationRequiresRecords = false private var invocationCanRetryForegroundDiscovery = false + private var invocationRetryTask: Task? private let allSpacesCatalog: WindowSwitcherWindowRecords private let discovery: DiscoveryEnvironment private var publication = WindowSwitcherPublishedWindows() @@ -230,13 +237,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { inferredFocusWorkerLifetime = nil applicationInventory?.stop() allSpacesGeneration = UUID() - invocationGeneration = UUID() - invocationInProgress = false - invocationRequiredHosts.removeAll() - invocationScansStarted.removeAll() - queuedInvocationRetryHost = nil - invocationRequiresRecords = false - invocationCanRetryForegroundDiscovery = false + resetInvocation() isInvocationReady = false windowRecordsPending = false allSpacesRefreshTask?.cancel(); allSpacesRefreshTask = nil @@ -259,6 +260,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { observers.forEach(notificationCenter.removeObserver); observers.removeAll() workers.values.forEach { $0.stop() }; workers.removeAll() snapshots.removeAll(); inFlight.removeAll(); unavailable.removeAll() + excludedWindowNumbersByHost.removeAll() unavailableApplicationCount = 0 } @@ -303,21 +305,17 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { func prepareForInvocation() { guard running else { return } - invocationGeneration = UUID() + resetInvocation() invocationInProgress = true + invocationForegroundPID = discovery.foregroundProcessIdentifier() + invocationCanRescanForeground = true isInvocationReady = false pendingFocus.removeAll() inferredFocusWorkerLifetime = nil publication.recency.clearInference() - applicationInventory?.reconcile(notify: false) - if let pid = discovery.foregroundProcessIdentifier() { - applicationInventory?.reload(processIdentifier: pid, notify: false) - } - reloadApplications() + reloadForegroundApplication(invocationForegroundPID) applyInvalidations() invocationRequiredHosts = expectedHostPIDs - invocationScansStarted.removeAll() - queuedInvocationRetryHost = nil invocationRequiresRecords = true invocationCanRetryForegroundDiscovery = true dirtyHosts.formUnion(expectedHostPIDs) @@ -326,6 +324,34 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { drainRefreshes() } + func cancelInvocation() { + guard invocationInProgress else { return } + resetInvocation() + pendingFocus.removeAll() + applyInvalidations() + drainRefreshes() + } + + private func resetInvocation() { + invocationGeneration = UUID() + invocationInProgress = false + invocationForegroundPID = nil + invocationCanRescanForeground = false + invocationRequiredHosts.removeAll() + invocationScansStarted.removeAll() + queuedInvocationRetryHost = nil + invocationRequiresRecords = false + invocationCanRetryForegroundDiscovery = false + invocationRetryTask?.cancel() + invocationRetryTask = nil + } + + private func reloadForegroundApplication(_ pid: pid_t?) { + applicationInventory?.reconcile(notify: false) + if let pid { applicationInventory?.reload(processIdentifier: pid, notify: false) } + reloadApplications() + } + private func reloadApplications() { let oldMapping = processMapping let ownPID = ProcessInfo.processInfo.processIdentifier @@ -354,6 +380,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { inFlight.remove(pid) unavailable.remove(pid) snapshots.removeValue(forKey: pid) + excludedWindowNumbersByHost.removeValue(forKey: pid) pendingFocus.removeValue(forKey: pid) removedProcesses.insert(pid) dirtyHosts.insert(oldMapping.host(for: pid)) @@ -363,6 +390,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } for pid in Array(snapshots.keys) where !expectedHostPIDs.contains(pid) { snapshots.removeValue(forKey: pid) + excludedWindowNumbersByHost.removeValue(forKey: pid) removedProcesses.insert(pid) markPublicationDirty() } @@ -419,6 +447,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let result = await worker.scan() guard let self, running, workers[pid] === worker else { return } var entries = windowEntries(from: result, app: app, ownerPID: pid) + var excludedWindowNumbers = result.excludedWindowNumbers var helperUnavailable = false var focusObservations = [pid: FocusObservation(workerPID: pid, scan: result)] for helperPID in (helperPIDsByHost[pid] ?? []).sorted() { @@ -430,6 +459,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { guard workers[helperPID] === helperWorker else { continue } if helperScan.unavailable { helperUnavailable = true } focusObservations[helperPID] = FocusObservation(workerPID: helperPID, scan: helperScan) + excludedWindowNumbers.formUnion(helperScan.excludedWindowNumbers) entries = WindowSwitcherListing.preferringUniqueWindowNumbers( entries + windowEntries(from: helperScan, app: app, ownerPID: helperPID)) } @@ -449,9 +479,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { entries = previous.map { var entry = $0; entry.metadataUnavailable = true; return entry } } snapshots[pid] = entries + excludedWindowNumbersByHost[pid] = excludedWindowNumbers if previous != entries { markPublicationDirty() } - if invocation == invocationGeneration { - if queuedInvocationRetryHost != pid { invocationRequiredHosts.remove(pid) } + if invocation == invocationGeneration, queuedInvocationRetryHost != pid { + invocationRequiredHosts.remove(pid) if let target = foregroundTarget(), target.hostPID == pid { pendingFocus[pid] = focusObservations } @@ -553,10 +584,12 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let screenVisibility = Dictionary(allSpacesRecords.compactMap { record in record.isOnScreen.map { (record.windowNumber, $0) } }, uniquingKeysWith: { first, _ in first }) + let excluded = excludedWindowNumbersByHost[target.hostPID] ?? [] let candidates = entries.filter { entry in (entry.axWorkerPID == target.workerPID || entry.owningProcessIdentifier == target.workerPID) && isUsableWindow(entry) && !publication.lostAXConfirmation(entry) + && (entry.windowElement != nil || entry.windowNumber.map(excluded.contains) != true) && entry.windowNumber.flatMap { screenVisibility[$0] } != false } if candidates.count == 1 { return candidates.first?.id } @@ -575,7 +608,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { : [target.workerPID] return Set(allSpacesRecords.lazy.filter { $0.isOnScreen == true && $0.isOnActiveSpace != false && ownerPIDs.contains($0.processIdentifier) - }.map(\.windowNumber)) + }.map(\.windowNumber)).subtracting(excludedWindowNumbersByHost[target.hostPID] ?? []) } private func hasUnresolvedOnscreenWindow(_ onscreen: Set, in entries: [WindowSwitcherAppEntry], @@ -597,6 +630,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } private func publishForegroundFocus() -> Bool { + if invocationInProgress, discovery.foregroundProcessIdentifier() != invocationForegroundPID { return false } guard inferredFocusWorkerLifetime != nil || !pendingFocus.isEmpty else { return false } let target = foregroundTarget() let workerLifetime = target.flatMap { workers[$0.workerPID]?.lifetime } @@ -642,6 +676,32 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { return unresolvedReportedFocus } + private func reconcileInvocationForeground() { + guard invocationInProgress else { return } + let current = discovery.foregroundProcessIdentifier() + guard current != invocationForegroundPID else { return } + invocationForegroundPID = current + publication.recency.clearFocus() + inferredFocusWorkerLifetime = nil + pendingFocus.removeAll() + // A background scan can read the app's previous key window. Resolve + // focus while it is foreground, once per invocation. + guard invocationCanRescanForeground else { return } + invocationCanRescanForeground = false + reloadForegroundApplication(current) + guard let target = foregroundTarget() else { return } + invocationRequiresRecords = true + windowRecordsPending = true + requireInvocationScan(for: target.hostPID) + } + + private func requireInvocationScan(for pid: pid_t) { + queuedInvocationRetryHost = pid + invocationRequiredHosts.insert(pid) + dirtyHosts.insert(pid) + drainRefreshes() + } + private func retryForegroundDiscoveryIfNeeded(unresolvedReportedFocus: Bool) { guard invocationCanRetryForegroundDiscovery else { return } invocationCanRetryForegroundDiscovery = false @@ -654,12 +714,27 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { entry.id == publication.recency.confirmedFocusID && entry.windowNumber.map(onscreen.contains) == true } - guard !hasConfirmedOnscreenFocus, - hasUnresolvedOnscreenWindow(onscreen, in: entries, requiresAXConfirmation: unresolvedReportedFocus) - else { return } - queuedInvocationRetryHost = target.hostPID - invocationRequiredHosts.insert(target.hostPID) - invalidate(processIdentifiers: [target.hostPID], windowRecords: false) + let missingAX = !hasConfirmedOnscreenFocus + && hasUnresolvedOnscreenWindow(onscreen, in: entries, requiresAXConfirmation: unresolvedReportedFocus) + // LaunchServices can report a foreground app before its window + // appears in either source. Recapture visibility in that case too. + let awaitingFirstWindow = onscreen.isEmpty + && !entries.contains { $0.id == publication.recency.focusedID && isUsableWindow($0) } + && applicationsByPID[target.workerPID].map { app in + !app.isFinishedLaunching || app.launchDate.map { Date().timeIntervalSince($0) < 2 } == true + } == true + guard missingAX || awaitingFirstWindow else { return } + invocationRetryTask = Task { [weak self] in + do { try await Task.sleep(for: .milliseconds(100)) } catch { return } + guard !Task.isCancelled, let self else { return } + invocationRetryTask = nil + guard foregroundTarget()?.workerPID == target.workerPID else { schedulePublication(); return } + if awaitingFirstWindow { + invocationRequiresRecords = true + windowRecordsPending = true + } + requireInvocationScan(for: target.hostPID) + } } private func markPublicationDirty() { @@ -683,11 +758,15 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { removedProcesses.removeAll() rebuildPublication() } - let unresolvedReportedFocus = publishForegroundFocus() isInitialDiscoveryComplete = didReadAllSpaces && expectedHostPIDs.allSatisfy { snapshots[$0] != nil } - let discoveryIsReady = isInitialDiscoveryComplete && !invocationRequiresRecords && invocationRequiredHosts.isEmpty + let scansAreReady = isInitialDiscoveryComplete && !invocationRequiresRecords + && invocationRequiredHosts.isEmpty && invocationRetryTask == nil + if scansAreReady { reconcileInvocationForeground() } + let unresolvedReportedFocus = publishForegroundFocus() + let discoveryIsReady = scansAreReady && invocationRequiredHosts.isEmpty if discoveryIsReady { retryForegroundDiscoveryIfNeeded(unresolvedReportedFocus: unresolvedReportedFocus) } - isInvocationReady = discoveryIsReady && invocationRequiredHosts.isEmpty && pendingFocus.isEmpty + isInvocationReady = discoveryIsReady && invocationRequiredHosts.isEmpty + && pendingFocus.isEmpty && invocationRetryTask == nil let completedInvocation = invocationInProgress && isInvocationReady if completedInvocation { invocationInProgress = false } if oldEntries != publication.entries || oldFocus != publication.recency.focusedID @@ -727,10 +806,11 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // scan, including when another read of that host is already active. for pid in expectedHostPIDs { let changed = changedOwners.contains { processMapping.host(for: $0) == pid } - if oldHelpers[pid] != helperPIDsByHost[pid] || (changed && snapshots[pid] != nil) { + if oldHelpers[pid] != helperPIDsByHost[pid] + || (changed && pid != foregroundRetryHost && snapshots[pid] != nil) { dirtyHosts.insert(pid) - // The current visibility read already requested another - // foreground AX pass. It consumes this invocation's retry. + // A newly mapped helper already requires a second AX pass + // for the foreground. It consumes the discovery retry. if pid == foregroundRetryHost, invocationCanRetryForegroundDiscovery, invocationScansStarted.contains(pid) { invocationCanRetryForegroundDiscovery = false diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift index 8ea4ea63d..7ca7a5d16 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift @@ -182,7 +182,8 @@ final class WindowSwitcherApplicationInventory { let active = application.isActive return Application(processIdentifier: pid, bundleIdentifier: metadata.bundleIdentifier, bundlePath: metadata.bundlePath, localizedName: nil, launchDate: metadata.launchDate, - isRegular: application.activationPolicy == .regular, isHidden: hidden, isActive: active, + isRegular: application.activationPolicy == .regular, isFinishedLaunching: application.isFinishedLaunching, + isHidden: hidden, isActive: active, loadPresentation: { self.value(isHidden: hidden, isActive: active) }) } diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherPlugin.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherPlugin.swift index be0f85946..8885769a2 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherPlugin.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherPlugin.swift @@ -829,6 +829,7 @@ final class WindowSwitcherPlugin: MacToolsPlugin, AccessibilityPermissionRefresh } private func cancelSession() { + let wasWaitingForDiscovery = pendingInvocation != nil shortcutTap.setSessionActive(false) shortcutTap.setEditing(false) sessionGeneration += 1 @@ -837,6 +838,7 @@ final class WindowSwitcherPlugin: MacToolsPlugin, AccessibilityPermissionRefresh pendingInvocation = nil; pendingRelease = false; pendingSteps = 0 overlayController.hide() session = nil + if wasWaitingForDiscovery { appCatalog.cancelInvocation() } } private func ensureAccessibilityForInvocation() -> Bool { diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift index cd099fd56..8f4293081 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift @@ -21,6 +21,7 @@ struct WindowSwitcherScan: Sendable { var unavailable: Bool var windowListReadSucceeded = true var reportedFocusedWindow = false + var excludedWindowNumbers: Set = [] } struct WindowSwitcherAXIdentity: Hashable { @@ -158,6 +159,7 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { } var indexes = Dictionary(uniqueKeysWithValues: records.enumerated().map { (WindowSwitcherAXIdentity(element: $0.element.element), $0.offset) }) var excluded = Set() + var excludedWindowNumbers = Set() var didRead = 0 var metadataFailed = false let count = windows.count @@ -173,8 +175,9 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { if let oldIndex { records[oldIndex] = snapshot } else { indexes[key] = records.count; records.append(snapshot) } if uptime() < deadline { observe(window) } - case .excluded: + case let .excluded(number): if let oldIndex { excluded.insert(records[oldIndex].id) } + if let number { excludedWindowNumbers.insert(number) } case .unavailable: metadataFailed = true if let oldIndex { records[oldIndex].unavailable = true } @@ -186,27 +189,32 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { let focused = uptime() < deadline ? copyElement(app, kAXFocusedWindowAttribute) : nil let focusedID = focused.flatMap { element in records.first { CFEqual($0.element, element) }?.id } return WindowSwitcherScan(windows: records, focusedID: focusedID, - unavailable: metadataFailed || didRead < count, reportedFocusedWindow: focused != nil) + unavailable: metadataFailed || didRead < count, reportedFocusedWindow: focused != nil, + excludedWindowNumbers: excludedWindowNumbers) } - private enum Admission { case eligible(WindowSwitcherWindowSnapshot), excluded, unavailable } + private enum Admission { + case eligible(WindowSwitcherWindowSnapshot) + case excluded(CGWindowID? = nil) + case unavailable + } private func snapshot(_ window: AXUIElement, id: String) -> Admission { guard let values = access.windowAttributes(window), values.count == 6, let role = values[0] as? String else { return .unavailable } // A process root masquerading as a window is invalid AX data, not // evidence that the app has no user windows. if role == kAXApplicationRole as String { return .unavailable } - guard role == kAXWindowRole as String else { return .excluded } + guard role == kAXWindowRole as String else { return .excluded() } if let subrole = values[1] as? String, ![kAXStandardWindowSubrole as String, kAXDialogSubrole as String, "AXFullScreenWindow"].contains(subrole) { - return .excluded + return .excluded() } guard let minimized = values[3] as? Bool, let point = decodePoint(values[4]), let size = decodeSize(values[5]) else { return .unavailable } guard point.x.isFinite, point.y.isFinite, size.width.isFinite, size.height.isFinite, size.width >= 0, size.height >= 0 else { return .unavailable } - guard minimized || (size.width >= 80 && size.height >= 60) else { return .excluded } + guard minimized || (size.width >= 80 && size.height >= 60) else { return .excluded() } let title = values[2] as? String ?? "" if !minimized, values[1] as? String == kAXDialogSubrole as String, @@ -217,7 +225,7 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { // Some apps expose empty, unfocused compositor surfaces as AX // dialogs even while WindowServer marks them visible. A dialog // with content or foreground status remains a selectable window. - return .excluded + return .excluded(access.windowNumber(window)) } let snapshot = WindowSwitcherWindowSnapshot(id: id, element: window, title: title, minimized: minimized, bounds: CGRect(origin: point, size: size), diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift index 4e9616256..24dddfc36 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift @@ -150,6 +150,10 @@ struct WindowSwitcherRecency { } } mutating func clearInference() { inferredFocusID = nil } + mutating func clearFocus() { + confirmedFocusID = nil + clearInference() + } mutating func record(_ id: String) { clearInference() diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift index 02545e4f9..8dcabd46d 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift @@ -247,7 +247,10 @@ final class WindowSwitcherWindowRecords { func freshWindowRecordSnapshot(requiresNewCapture: Bool = false) async -> WindowSwitcherWindowRecordSnapshot { guard !Task.isCancelled else { return .init(records: windowRecords, isFresh: false) } - let generation = requiresNewCapture ? startCapture() : captures.keys.max() ?? startCapture() + // An older read can still be physically running after a newer one + // completes. Joining it cannot provide fresh validation. + let joinable = captures.keys.max().flatMap { $0 > cachedGeneration ? $0 : nil } + let generation = requiresNewCapture ? startCapture() : joinable ?? startCapture() guard let generation else { return WindowSwitcherWindowRecordSnapshot(records: windowRecords, isFresh: false) } diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift index b5ba1c07c..df0e7fd14 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift @@ -16,13 +16,18 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable private let window: AXUIElement private let replacement: AXUIElement? private let replacementNumber: CGWindowID? + private let emptyDialog: AXUIElement? + private let emptyDialogNumber: CGWindowID? let observesSystemNotifications = false - init(number: CGWindowID?, elementPID: pid_t, replacementNumber: CGWindowID? = nil) { + init(number: CGWindowID?, elementPID: pid_t, replacementNumber: CGWindowID? = nil, + emptyDialogNumber: CGWindowID? = nil) { state = State(number: number) window = AXUIElementCreateApplication(elementPID) self.replacementNumber = replacementNumber replacement = replacementNumber.map { _ in AXUIElementCreateApplication(elementPID + 100) } + self.emptyDialogNumber = emptyDialogNumber + emptyDialog = emptyDialogNumber.map { _ in AXUIElementCreateApplication(elementPID + 200) } } func update(_ body: (inout State) -> Void) { lock.lock(); defer { lock.unlock() }; body(&state) } func read(_ body: (State) -> T) -> T { lock.lock(); defer { lock.unlock() }; return body(state) } @@ -30,8 +35,8 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable update { $0.reads += 1 } read { $0.beforeRead }?() return read { state in - guard let number = state.number else { return [] } - return [number == replacementNumber ? replacement ?? window : window] + let main = state.number.map { $0 == replacementNumber ? replacement ?? window : window } + return [main, emptyDialog].compactMap { $0 } } } func element(_ owner: AXUIElement, attribute: String) -> AXUIElement? { @@ -39,12 +44,20 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable return attribute == kAXCloseButtonAttribute ? owner : nil } func windowAttributes(_ window: AXUIElement) -> [Any]? { - var point = CGPoint(x: 20, y: 20) - var size = CGSize(width: 800, height: 600) - return [kAXWindowRole, kAXStandardWindowSubrole, "Fixture", false, + let isDialog = emptyDialog.map { CFEqual($0, window) } == true + var point = isDialog ? CGPoint(x: 30, y: 30) : CGPoint(x: 20, y: 20) + var size = isDialog ? CGSize(width: 400, height: 300) : CGSize(width: 800, height: 600) + return [kAXWindowRole, isDialog ? kAXDialogSubrole : kAXStandardWindowSubrole, isDialog ? "" : "Fixture", false, AXValueCreate(.cgPoint, &point)!, AXValueCreate(.cgSize, &size)!] } - func windowNumber(_ window: AXUIElement) -> CGWindowID? { read { $0.number } } + func windowNumber(_ window: AXUIElement) -> CGWindowID? { + if emptyDialog.map({ CFEqual($0, window) }) == true { return emptyDialogNumber } + return read { $0.number } + } + func boolValue(_ window: AXUIElement, attribute: String) -> Bool? { + emptyDialog.map { CFEqual($0, window) } == true ? false : nil + } + func childCount(_ window: AXUIElement) -> Int? { emptyDialog.map { CFEqual($0, window) } == true ? 0 : nil } func minimized(_ window: AXUIElement) -> Bool? { false } func set(_ element: AXUIElement, attribute: String, value: Bool) -> AXError { .success } func perform(_ element: AXUIElement, action: String) -> AXError { @@ -243,6 +256,79 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7]) } + func testColdLaunchRecapturesWindowServerWhenNeitherSourceHasAWindowYet() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + let emptyCaptures = DispatchSemaphore(value: 2) + defer { emptyCaptures.signal(); emptyCaptures.signal() } + let record = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Launched", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + launched.update { + $0.beforeRead = { [weak launched] in + launched?.update { state in + if state.reads == 2 { state.number = 8; state.focused = true } + } + } + } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + emptyCaptures.wait(timeout: .now()) == .success ? [] : [record] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched", + isFinishedLaunching: false) + return foregroundPID == 43 ? [prior, new] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 2) + } + + func testExcludedOnscreenDialogDoesNotPreventInferringTheForegroundWindow() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let foreground = CatalogAXAccess(number: 8, elementPID: 202, emptyDialogNumber: 9) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : foreground }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Foreground", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), + .init(windowNumber: 9, processIdentifier: 43, title: "", isOnScreen: true, + bounds: CGRect(x: 30, y: 30, width: 400, height: 300))] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground") + return foregroundPID == 43 ? [prior, new] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(foreground.read { $0.reads }, 1) + } + func testOffscreenAXWindowDoesNotSuppressRetryForAnUnlistedOnscreenWindow() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } @@ -319,6 +405,40 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) } + func testCancellingInvocationLetsAQueuedVisibilityRefreshRunWhileAXIsPending() async throws { + let access = CatalogAXAccess(number: 7, elementPID: 201) + let axStarted = DispatchSemaphore(value: 0) + let releaseAX = DispatchSemaphore(value: 0) + let recordsStarted = DispatchSemaphore(value: 0) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { _ in access }, allSpacesCatalog: .init(windowRecordProvider: { + recordsStarted.signal() + return [] + }), discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "fixture", localizedName: "Fixture")] + }, foregroundProcessIdentifier: { 42 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseAX.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + try await waitUntil { recordsStarted.wait(timeout: .now()) == .success } + + access.update { + $0.beforeRead = { + axStarted.signal() + _ = releaseAX.wait(timeout: .now() + 5) + } + } + catalog.prepareForInvocation() + try await waitUntil { axStarted.wait(timeout: .now()) == .success } + try await waitUntil { recordsStarted.wait(timeout: .now()) == .success } + XCTAssertFalse(catalog.isInvocationReady) + catalog.refresh() + catalog.cancelInvocation() + + try await waitUntil { recordsStarted.wait(timeout: .now()) == .success } + access.update { $0.beforeRead = nil } + } + func testInvocationStartsFreshCaptureAndUsesOnlyOneVisibilityDrivenRetry() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } @@ -381,7 +501,7 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertNil(catalog.focusedWindowID) } - func testForegroundChangeDropsInferenceBeforeInvocationBecomesReady() async throws { + func testForegroundChangeUsesNewFocusBeforeInvocationBecomesReady() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } let first = CatalogAXAccess(number: 8, elementPID: 202) @@ -422,8 +542,12 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { release.signal() try await waitUntil { catalog.isInvocationReady } let entries = catalog.entries(sortMode: .recentUse) - XCTAssertNotEqual(entries.first?.windowNumber, 8) - XCTAssertNotEqual(catalog.focusedWindowID, entries.first { $0.windowNumber == 8 }?.id) + XCTAssertEqual(entries.first?.windowNumber, 10) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + var session = WindowSwitcherSession(entries: entries, selectedID: catalog.focusedWindowID, + isPersistent: false, originalWindowID: catalog.focusedWindowID) + session.advance(1) + XCTAssertEqual(session.selected?.windowNumber, 7) } func testRecentUseWaitsForVisibilityAndKeepsInferenceOutOfHistory() async throws { diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherLifecycleTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherLifecycleTests.swift index ad857fa62..d5d516442 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherLifecycleTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherLifecycleTests.swift @@ -30,6 +30,8 @@ private final class ControlledSwitcherCatalog: WindowSwitcherCatalog { var isInvocationReady: Bool { invocationReady ?? isInitialDiscoveryComplete } var prepareInvocation: (() -> Void)? func prepareForInvocation() { prepareInvocation?() } + var cancelledInvocations = 0 + func cancelInvocation() { cancelledInvocations += 1 } var windows: [WindowSwitcherAppEntry] = [] var activated: [String] = [] var activationResult: WindowSwitcherActionResult = .succeeded @@ -338,6 +340,7 @@ final class WindowSwitcherLifecycleTests: XCTestCase { XCTAssertNil(plugin.session) XCTAssertNil(plugin.pendingInvocation) XCTAssertTrue(catalog.activated.isEmpty) + XCTAssertEqual(catalog.cancelledInvocations, 1) } func testModifierReleaseAfterEnteringSearchDoesNotCommit() async throws { diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift index aa0b022e1..4c4404563 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift @@ -69,10 +69,17 @@ final class WindowSwitcherWindowRecordsTests: XCTestCase { XCTAssertEqual(current.records.map(\.windowNumber), [2]) XCTAssertEqual(provider.counts.completed, 1) + let entry = WindowSwitcherAppEntry(id: "latest", processIdentifier: 42, bundleIdentifier: "fixture", + appName: "Fixture", windowTitle: "Fixture", icon: nil, windowElement: nil, isMinimized: false, + windowNumber: 3, windowBounds: CGRect(x: 0, y: 30, width: 800, height: 600), shortcutToken: nil) + let validated = await reader.isCurrentFallback(entry) + XCTAssertTrue(validated) + XCTAssertEqual(provider.counts.completed, 2) + provider.release.signal() let superseded = await older.value XCTAssertFalse(superseded.isFresh) - XCTAssertEqual(superseded.records.map(\.windowNumber), [2]) + XCTAssertEqual(superseded.records.map(\.windowNumber), [3]) } func testTimeoutKeepsPhysicalQueriesBoundedAndIgnoresTheirLateResults() async throws { From 372e2222982b1ae102ed9a6bbcc617dbd86c3fca Mon Sep 17 00:00:00 2001 From: xcv58 Date: Wed, 25 Nov 2026 19:01:02 -0500 Subject: [PATCH 3/5] fix(window-switcher): keep launch focus recovery bounded --- .../Sources/WindowSwitcherAppCatalog.swift | 275 ++++++--- .../Sources/WindowSwitcherProcessWorker.swift | 8 +- .../Sources/WindowSwitcherWindowRecords.swift | 16 +- .../Tests/WindowSwitcherAppCatalogTests.swift | 574 +++++++++++++++++- .../WindowSwitcherWindowRecordsTests.swift | 27 + 5 files changed, 788 insertions(+), 112 deletions(-) diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift index 926743e71..178ca4274 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift @@ -74,12 +74,24 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { var isDragging: () -> Bool = { CGEventSource.buttonState(.combinedSessionState, button: .left) } } + private struct ForegroundTarget { + let hostPID: pid_t + let workerPID: pid_t + } + + private enum FocusIssue: Equatable { + case unmatchedAXFocus, incompleteAX, offscreenAX + + var requiresAXConfirmation: Bool { self != .offscreenAX } + } + private struct FocusObservation { let workerPID: pid_t let id: String? let windowNumber: CGWindowID? let unavailable: Bool let reportedFocusedWindow: Bool + let reportedFocusWasExcluded: Bool var canInfer: Bool { !unavailable && !reportedFocusedWindow } init(workerPID: pid_t, scan: WindowSwitcherScan) { @@ -88,6 +100,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { windowNumber = scan.focusedID.flatMap { id in scan.windows.first { $0.id == id }?.windowNumber } unavailable = scan.unavailable reportedFocusedWindow = scan.reportedFocusedWindow + reportedFocusWasExcluded = scan.reportedFocusWasExcluded } } @@ -111,6 +124,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var observers: [NSObjectProtocol] = [] private var workers: [pid_t: WindowSwitcherProcessWorker] = [:] private var snapshots: [pid_t: [WindowSwitcherAppEntry]] = [:] + private var scannedHelperPIDs: [pid_t: Set] = [:] private var excludedWindowNumbersByHost: [pid_t: Set] = [:] private var inFlight: Set = [] // Kept across stop/start until the actual worker returns. @@ -138,13 +152,14 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var invocationGeneration = UUID() private var invocationInProgress = false private var invocationForegroundPID: pid_t? - private var invocationCanRescanForeground = false + private var contradictedInvocationFocusID: String? private var invocationRequiredHosts: Set = [] - private var invocationScansStarted: Set = [] private var queuedInvocationRetryHost: pid_t? + private var deferredForegroundRefreshes: Set = [] private var invocationRequiresRecords = false private var invocationCanRetryForegroundDiscovery = false private var invocationRetryTask: Task? + private var invocationVisibilityRetryPID: pid_t? private let allSpacesCatalog: WindowSwitcherWindowRecords private let discovery: DiscoveryEnvironment private var publication = WindowSwitcherPublishedWindows() @@ -260,6 +275,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { observers.forEach(notificationCenter.removeObserver); observers.removeAll() workers.values.forEach { $0.stop() }; workers.removeAll() snapshots.removeAll(); inFlight.removeAll(); unavailable.removeAll() + scannedHelperPIDs.removeAll() excludedWindowNumbersByHost.removeAll() unavailableApplicationCount = 0 } @@ -306,9 +322,12 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { func prepareForInvocation() { guard running else { return } resetInvocation() + // Release any older background waiter. The new invocation can use the + // second reader slot while that physical query finishes. + allSpacesRefreshTask?.cancel() + allSpacesRefreshTask = nil invocationInProgress = true invocationForegroundPID = discovery.foregroundProcessIdentifier() - invocationCanRescanForeground = true isInvocationReady = false pendingFocus.removeAll() inferredFocusWorkerLifetime = nil @@ -333,17 +352,19 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } private func resetInvocation() { + pendingInvalidations.formUnion(deferredForegroundRefreshes) + deferredForegroundRefreshes.removeAll() invocationGeneration = UUID() invocationInProgress = false invocationForegroundPID = nil - invocationCanRescanForeground = false + contradictedInvocationFocusID = nil invocationRequiredHosts.removeAll() - invocationScansStarted.removeAll() queuedInvocationRetryHost = nil invocationRequiresRecords = false invocationCanRetryForegroundDiscovery = false invocationRetryTask?.cancel() invocationRetryTask = nil + invocationVisibilityRetryPID = nil } private func reloadForegroundApplication(_ pid: pid_t?) { @@ -380,6 +401,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { inFlight.remove(pid) unavailable.remove(pid) snapshots.removeValue(forKey: pid) + scannedHelperPIDs.removeValue(forKey: oldMapping.host(for: pid)) excludedWindowNumbersByHost.removeValue(forKey: pid) pendingFocus.removeValue(forKey: pid) removedProcesses.insert(pid) @@ -390,13 +412,14 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } for pid in Array(snapshots.keys) where !expectedHostPIDs.contains(pid) { snapshots.removeValue(forKey: pid) + scannedHelperPIDs.removeValue(forKey: pid) excludedWindowNumbersByHost.removeValue(forKey: pid) removedProcesses.insert(pid) markPublicationDirty() } dirtyHosts.formIntersection(expectedHostPIDs) invocationRequiredHosts.formIntersection(expectedHostPIDs) - invocationScansStarted.formIntersection(expectedHostPIDs) + deferredForegroundRefreshes.formIntersection(expectedHostPIDs) if let queuedInvocationRetryHost, !expectedHostPIDs.contains(queuedInvocationRetryHost) { self.queuedInvocationRetryHost = nil } @@ -418,6 +441,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { refreshAllSpaces() } let foregroundHostPID = foregroundTarget()?.hostPID + let hostAwaitingVisibility = invocationVisibilityRetryPID.flatMap { foregroundTarget(for: $0)?.hostPID } let pids = dirtyHosts.sorted { let lhsActive = $0 == foregroundHostPID let rhsActive = $1 == foregroundHostPID @@ -425,10 +449,11 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } for pid in pids { guard activeScanCount < Self.maximumConcurrentScans else { break } - guard !inFlight.contains(pid), let application = applicationsByPID[pid] else { continue } + guard pid != hostAwaitingVisibility, !inFlight.contains(pid), + let application = applicationsByPID[pid] else { continue } let worker = ensureWorker(pid: pid, launchDate: application.launchDate, applicationLifetime: application.lifetime) dirtyHosts.remove(pid) - if invocationInProgress { invocationScansStarted.insert(pid) } + deferredForegroundRefreshes.remove(pid) if queuedInvocationRetryHost == pid { queuedInvocationRetryHost = nil pendingInvalidations.remove(pid) @@ -479,6 +504,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { entries = previous.map { var entry = $0; entry.metadataUnavailable = true; return entry } } snapshots[pid] = entries + scannedHelperPIDs[pid] = Set(focusObservations.keys).subtracting([pid]) excludedWindowNumbersByHost[pid] = excludedWindowNumbers if previous != entries { markPublicationDirty() } if invocation == invocationGeneration, queuedInvocationRetryHost != pid { @@ -493,12 +519,16 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { schedulePublication() } - private func foregroundTarget() -> (hostPID: pid_t, workerPID: pid_t)? { + private func foregroundTarget() -> ForegroundTarget? { guard let foregroundPID = discovery.foregroundProcessIdentifier() else { return nil } + return foregroundTarget(for: foregroundPID) + } + + private func foregroundTarget(for foregroundPID: pid_t) -> ForegroundTarget? { let hostPID = processMapping.host(for: foregroundPID) guard expectedHostPIDs.contains(hostPID), foregroundPID == hostPID || helperPIDsByHost[hostPID]?.contains(foregroundPID) == true else { return nil } - return (hostPID, foregroundPID) + return ForegroundTarget(hostPID: hostPID, workerPID: foregroundPID) } func entries(sortMode: WindowSwitcherSortMode) -> [WindowSwitcherAppEntry] { @@ -575,25 +605,23 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } private func inferredForegroundWindowID(in entries: [WindowSwitcherAppEntry], - target: (hostPID: pid_t, workerPID: pid_t)) -> String? { + target: ForegroundTarget) -> String? { guard allSpacesRecordsAreFresh, !entries.isEmpty else { return nil } let onscreenWindowNumbers = foregroundOnscreenWindowNumbers(target: target) guard !hasUnresolvedOnscreenWindow(onscreenWindowNumbers, in: entries) else { return nil } // A fresh WindowServer snapshot can distinguish a visible window from // windows that are still restoring or live on other Spaces. - let screenVisibility = Dictionary(allSpacesRecords.compactMap { record in - record.isOnScreen.map { (record.windowNumber, $0) } - }, uniquingKeysWith: { first, _ in first }) let excluded = excludedWindowNumbersByHost[target.hostPID] ?? [] - let candidates = entries.filter { entry in - (entry.axWorkerPID == target.workerPID || entry.owningProcessIdentifier == target.workerPID) - && isUsableWindow(entry) - && !publication.lostAXConfirmation(entry) - && (entry.windowElement != nil || entry.windowNumber.map(excluded.contains) != true) - && entry.windowNumber.flatMap { screenVisibility[$0] } != false + let candidates = entries.compactMap { entry -> (id: String, onscreen: Bool)? in + guard entry.axWorkerPID == target.workerPID || entry.owningProcessIdentifier == target.workerPID, + isUsableWindow(entry), !publication.lostAXConfirmation(entry), + entry.windowElement != nil || entry.windowNumber.map(excluded.contains) != true else { return nil } + let record = visibilityRecord(for: entry, among: entries) + guard record?.isOnScreen != false, record?.isOnActiveSpace != false else { return nil } + return (entry.id, record?.isOnScreen == true) } if candidates.count == 1 { return candidates.first?.id } - let onscreen = candidates.filter { $0.windowNumber.flatMap { screenVisibility[$0] } == true } + let onscreen = candidates.filter(\.onscreen) return onscreen.count == 1 ? onscreen.first?.id : nil } @@ -602,7 +630,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { && !entry.isOnOtherDesktop && !entry.metadataUnavailable } - private func foregroundOnscreenWindowNumbers(target: (hostPID: pid_t, workerPID: pid_t)) -> Set { + private func foregroundOnscreenWindowNumbers(target: ForegroundTarget) -> Set { let ownerPIDs = target.workerPID == target.hostPID ? (helperPIDsByHost[target.hostPID] ?? []).union([target.workerPID]) : [target.workerPID] @@ -613,11 +641,37 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private func hasUnresolvedOnscreenWindow(_ onscreen: Set, in entries: [WindowSwitcherAppEntry], requiresAXConfirmation: Bool = false) -> Bool { - let listed = Set(entries.filter { entry in + let usable = entries.filter { entry in isUsableWindow(entry) && (entry.windowElement != nil || (!requiresAXConfirmation && !publication.lostAXConfirmation(entry))) - }.compactMap(\.windowNumber)) - return !onscreen.isSubset(of: listed) + } + let represented = Set(usable.compactMap { + $0.windowNumber ?? visibilityRecord(for: $0, among: entries)?.windowNumber + }) + return !onscreen.isSubset(of: represented) + } + + private func visibilityRecord(for entry: WindowSwitcherAppEntry, + among entries: [WindowSwitcherAppEntry]) -> WindowSwitcherWindowRecord? { + if let number = entry.windowNumber { + return allSpacesRecords.first { $0.windowNumber == number } + } + guard entry.windowElement != nil else { return nil } + // Unique geometry can inform visibility only. Preserve exact IDs for + // listing and actions. Check all Spaces for competing matches. + let excluded = excludedWindowNumbersByHost[entry.processIdentifier] ?? [] + let matches = allSpacesRecords.lazy.filter { + $0.processIdentifier == entry.owningProcessIdentifier + && !excluded.contains($0.windowNumber) && Self.sameBounds($0.bounds, entry.bounds) + }.prefix(2) + guard matches.count == 1, let record = matches.first else { return nil } + let competingEntry = entries.contains { + $0.id != entry.id && ($0.windowNumber == record.windowNumber + || ($0.windowNumber == nil && $0.windowElement != nil + && $0.owningProcessIdentifier == record.processIdentifier + && Self.sameBounds($0.bounds, record.bounds))) + } + return competingEntry ? nil : record } private func exactWindowID(for focus: FocusObservation, in entries: [WindowSwitcherAppEntry]) -> String? { @@ -629,22 +683,22 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { }?.id } - private func publishForegroundFocus() -> Bool { - if invocationInProgress, discovery.foregroundProcessIdentifier() != invocationForegroundPID { return false } - guard inferredFocusWorkerLifetime != nil || !pendingFocus.isEmpty else { return false } + private func publishForegroundFocus() -> FocusIssue? { + if invocationInProgress, discovery.foregroundProcessIdentifier() != invocationForegroundPID { return nil } + guard inferredFocusWorkerLifetime != nil || !pendingFocus.isEmpty else { return nil } let target = foregroundTarget() let workerLifetime = target.flatMap { workers[$0.workerPID]?.lifetime } if let inferredFocusWorkerLifetime, inferredFocusWorkerLifetime != workerLifetime { self.inferredFocusWorkerLifetime = nil publication.recency.clearInference() } - guard !pendingFocus.isEmpty else { return false } + guard !pendingFocus.isEmpty else { return nil } let observations = target.flatMap { pendingFocus[$0.hostPID] } pendingFocus.removeAll() guard let target, let observations, let focus = observations[target.workerPID] else { publication.recency.clearInference() inferredFocusWorkerLifetime = nil - return false + return nil } let entries = publication.entries.filter { $0.processIdentifier == target.hostPID } var exactID = exactWindowID(for: focus, in: entries) @@ -656,24 +710,53 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { return self.exactWindowID(for: helperFocus, in: entries) }.first } - let shouldInfer = exactID == nil && focus.canInfer - let unresolvedReportedFocus = exactID == nil && focus.reportedFocusedWindow // AX can finish before the current WindowServer read. Keep the focus // observation for publication when the matching visibility is available. + let awaitingInvocationVisibility = invocationInProgress && invocationRequiresRecords let visibilityPending = invocationInProgress ? invocationRequiresRecords || !invocationRequiredHosts.isEmpty : windowRecordsPending || allSpacesRefreshTask != nil - if shouldInfer || unresolvedReportedFocus, visibilityPending { + var issue: FocusIssue? + if exactID == nil, !focus.reportedFocusWasExcluded { + if focus.reportedFocusedWindow { + issue = .unmatchedAXFocus + } else if invocationInProgress, focus.unavailable { + issue = .incompleteAX + } + } + if awaitingInvocationVisibility + || (visibilityPending && exactID == nil && (focus.canInfer || issue != nil)) { pendingFocus[target.hostPID] = observations publication.recency.clearInference() inferredFocusWorkerLifetime = nil - return false + return nil + } + // A background AX notification can arrive before its replacement + // capture. The previous capture cannot contradict that report. + if let exactID, let entry = entries.first(where: { $0.id == exactID }) { + let record = visibilityRecord(for: entry, among: entries) + let contradictsFocus = (invocationInProgress || !visibilityPending) && allSpacesRecordsAreFresh + && (record?.isOnScreen == false || record?.isOnActiveSpace == false) + && !foregroundOnscreenWindowNumbers(target: target).isEmpty + let verifiedOnscreen = allSpacesRecordsAreFresh + && record?.isOnScreen == true && record?.isOnActiveSpace != false + let repeatsUnverifiedFocus = invocationInProgress && exactID == contradictedInvocationFocusID + && !verifiedOnscreen + if contradictsFocus || repeatsUnverifiedFocus { + issue = .offscreenAX + if invocationInProgress { contradictedInvocationFocusID = exactID } + } + } + if issue == .offscreenAX, invocationInProgress, !invocationRequiredHosts.isEmpty { + pendingFocus[target.hostPID] = observations + return nil } - let inferredID = shouldInfer ? inferredForegroundWindowID(in: entries, target: target) : nil + let inferredID = exactID == nil && focus.canInfer + ? inferredForegroundWindowID(in: entries, target: target) : nil inferredFocusWorkerLifetime = inferredID == nil ? nil : workerLifetime - publication.recency.observeForeground(entries: entries, focusedWindowID: exactID, + publication.recency.observeForeground(entries: entries, focusedWindowID: issue == .offscreenAX ? nil : exactID, inferredWindowID: inferredID, unavailable: focus.unavailable) - return unresolvedReportedFocus + return issue } private func reconcileInvocationForeground() { @@ -686,54 +769,88 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { pendingFocus.removeAll() // A background scan can read the app's previous key window. Resolve // focus while it is foreground, once per invocation. - guard invocationCanRescanForeground else { return } - invocationCanRescanForeground = false - reloadForegroundApplication(current) - guard let target = foregroundTarget() else { return } - invocationRequiresRecords = true - windowRecordsPending = true - requireInvocationScan(for: target.hostPID) + guard invocationCanRetryForegroundDiscovery, let current, + current != ProcessInfo.processInfo.processIdentifier else { return } + invocationCanRetryForegroundDiscovery = false + scheduleForegroundRetry(for: current) } - private func requireInvocationScan(for pid: pid_t) { + private func queueInvocationScan(for pid: pid_t) { queuedInvocationRetryHost = pid invocationRequiredHosts.insert(pid) dirtyHosts.insert(pid) - drainRefreshes() + pendingFocus.removeValue(forKey: pid) } - private func retryForegroundDiscoveryIfNeeded(unresolvedReportedFocus: Bool) { + private func retryForegroundDiscoveryIfNeeded(focusIssue: FocusIssue?) { guard invocationCanRetryForegroundDiscovery else { return } invocationCanRetryForegroundDiscovery = false + guard let foregroundPID = discovery.foregroundProcessIdentifier() else { return } + guard let target = foregroundTarget(for: foregroundPID) else { + guard foregroundPID != ProcessInfo.processInfo.processIdentifier else { return } + let replacesPreviousFocus = publication.recency.focusedID != nil + publication.recency.clearFocus() + let visible = allSpacesRecordsAreFresh && allSpacesRecords.contains { + $0.processIdentifier == foregroundPID && $0.isOnScreen == true && $0.isOnActiveSpace != false + } + let app = applicationsByPID[foregroundPID] + // A newly foreground accessory can become regular during launch. + // After its first attempt the old app no longer owns the anchor. + if visible || app.map(isLaunching) != false || (replacesPreviousFocus && app?.isRegular == false) { + scheduleForegroundRetry(for: foregroundPID) + } + return + } + let launching = applicationsByPID[target.workerPID].map(isLaunching) == true + // Launch discovery can be incomplete before either source has a + // reliable answer. Confirm focus on the single retry. + if launching, + focusIssue == .unmatchedAXFocus || focusIssue == .incompleteAX { + scheduleForegroundRetry(for: foregroundPID) + return + } // A launch can put a window onscreen before the app publishes its AX // window list. Retry the scan while keeping the normal listing rules. - guard allSpacesRecordsAreFresh, let target = foregroundTarget() else { return } + guard allSpacesRecordsAreFresh else { return } let entries = publication.entries.filter { $0.processIdentifier == target.hostPID } let onscreen = foregroundOnscreenWindowNumbers(target: target) let hasConfirmedOnscreenFocus = entries.contains { entry in entry.id == publication.recency.confirmedFocusID - && entry.windowNumber.map(onscreen.contains) == true + && visibilityRecord(for: entry, among: entries).map { onscreen.contains($0.windowNumber) } == true } let missingAX = !hasConfirmedOnscreenFocus - && hasUnresolvedOnscreenWindow(onscreen, in: entries, requiresAXConfirmation: unresolvedReportedFocus) + && hasUnresolvedOnscreenWindow(onscreen, in: entries, + requiresAXConfirmation: focusIssue?.requiresAXConfirmation == true) + let missingHelper = !(helperPIDsByHost[target.hostPID] ?? []) + .isSubset(of: scannedHelperPIDs[target.hostPID] ?? []) // LaunchServices can report a foreground app before its window // appears in either source. Recapture visibility in that case too. - let awaitingFirstWindow = onscreen.isEmpty + let awaitingFirstWindow = launching && onscreen.isEmpty && !entries.contains { $0.id == publication.recency.focusedID && isUsableWindow($0) } - && applicationsByPID[target.workerPID].map { app in - !app.isFinishedLaunching || app.launchDate.map { Date().timeIntervalSince($0) < 2 } == true - } == true - guard missingAX || awaitingFirstWindow else { return } + if missingAX || awaitingFirstWindow || focusIssue == .offscreenAX || missingHelper { + scheduleForegroundRetry(for: foregroundPID) + } + } + + private func isLaunching(_ app: Application) -> Bool { + !app.isFinishedLaunching || app.launchDate.map { Date().timeIntervalSince($0) < 2 } == true + } + + private func scheduleForegroundRetry(for foregroundPID: pid_t) { + invocationVisibilityRetryPID = foregroundPID invocationRetryTask = Task { [weak self] in do { try await Task.sleep(for: .milliseconds(100)) } catch { return } guard !Task.isCancelled, let self else { return } invocationRetryTask = nil - guard foregroundTarget()?.workerPID == target.workerPID else { schedulePublication(); return } - if awaitingFirstWindow { - invocationRequiresRecords = true - windowRecordsPending = true + guard discovery.foregroundProcessIdentifier() == foregroundPID else { + invocationVisibilityRetryPID = nil + schedulePublication() + return } - requireInvocationScan(for: target.hostPID) + reloadForegroundApplication(foregroundPID) + invocationRequiresRecords = true + windowRecordsPending = true + drainRefreshes() } } @@ -762,13 +879,18 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let scansAreReady = isInitialDiscoveryComplete && !invocationRequiresRecords && invocationRequiredHosts.isEmpty && invocationRetryTask == nil if scansAreReady { reconcileInvocationForeground() } - let unresolvedReportedFocus = publishForegroundFocus() + let focusIssue = publishForegroundFocus() let discoveryIsReady = scansAreReady && invocationRequiredHosts.isEmpty - if discoveryIsReady { retryForegroundDiscoveryIfNeeded(unresolvedReportedFocus: unresolvedReportedFocus) } + if discoveryIsReady { retryForegroundDiscoveryIfNeeded(focusIssue: focusIssue) } isInvocationReady = discoveryIsReady && invocationRequiredHosts.isEmpty && pendingFocus.isEmpty && invocationRetryTask == nil let completedInvocation = invocationInProgress && isInvocationReady - if completedInvocation { invocationInProgress = false } + if completedInvocation { + invocationInProgress = false + let deferred = deferredForegroundRefreshes + deferredForegroundRefreshes.removeAll() + if !deferred.isEmpty { invalidate(processIdentifiers: deferred, windowRecords: false) } + } if oldEntries != publication.entries || oldFocus != publication.recency.focusedID || wasComplete != isInitialDiscoveryComplete || wasReady != isInvocationReady { onChange?() @@ -783,6 +905,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let generation = allSpacesGeneration let invocation = invocationGeneration let isInvocationCapture = invocationInProgress && invocationRequiresRecords + let foregroundAtCapture = isInvocationCapture ? foregroundTarget()?.hostPID : nil allSpacesRefreshTask = Task { [weak self] in guard let self else { return } let result = await allSpacesCatalog.freshWindowRecordSnapshot(requiresNewCapture: isInvocationCapture) @@ -806,22 +929,28 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // scan, including when another read of that host is already active. for pid in expectedHostPIDs { let changed = changedOwners.contains { processMapping.host(for: $0) == pid } - if oldHelpers[pid] != helperPIDsByHost[pid] - || (changed && pid != foregroundRetryHost && snapshots[pid] != nil) { + let readingForeground = (pid == foregroundAtCapture || pid == foregroundRetryHost) + && inFlight.contains(pid) + guard oldHelpers[pid] != helperPIDsByHost[pid] + || (changed && (snapshots[pid] != nil || readingForeground)) else { continue } + // A required retry covers this change. Otherwise let the + // foreground host refresh after the chooser opens. + if pid == foregroundRetryHost { + deferredForegroundRefreshes.insert(pid) + } else { dirtyHosts.insert(pid) - // A newly mapped helper already requires a second AX pass - // for the foreground. It consumes the discovery retry. - if pid == foregroundRetryHost, invocationCanRetryForegroundDiscovery, - invocationScansStarted.contains(pid) { - invocationCanRetryForegroundDiscovery = false - queuedInvocationRetryHost = pid - invocationRequiredHosts.insert(pid) - } } } didReadAllSpaces = true if invocation == invocationGeneration { invocationRequiresRecords = false + if isInvocationCapture, let retryPID = invocationVisibilityRetryPID { + invocationVisibilityRetryPID = nil + if discovery.foregroundProcessIdentifier() == retryPID, + let target = foregroundTarget(for: retryPID) { + queueInvocationScan(for: target.hostPID) + } + } if !invocationInProgress, !isInvocationReady { invocationRequiredHosts.formUnion(dirtyHosts) } } schedulePublication() diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift index 8f4293081..101c1baa0 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift @@ -21,6 +21,7 @@ struct WindowSwitcherScan: Sendable { var unavailable: Bool var windowListReadSucceeded = true var reportedFocusedWindow = false + var reportedFocusWasExcluded = false var excludedWindowNumbers: Set = [] } @@ -158,7 +159,7 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { windowSubscriptions.removeValue(forKey: old) } var indexes = Dictionary(uniqueKeysWithValues: records.enumerated().map { (WindowSwitcherAXIdentity(element: $0.element.element), $0.offset) }) - var excluded = Set() + var excluded = Set() var excludedWindowNumbers = Set() var didRead = 0 var metadataFailed = false @@ -176,7 +177,7 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { else { indexes[key] = records.count; records.append(snapshot) } if uptime() < deadline { observe(window) } case let .excluded(number): - if let oldIndex { excluded.insert(records[oldIndex].id) } + excluded.insert(key) if let number { excludedWindowNumbers.insert(number) } case .unavailable: metadataFailed = true @@ -184,12 +185,13 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { } didRead += 1 } - records.removeAll { excluded.contains($0.id) } + records.removeAll { excluded.contains(WindowSwitcherAXIdentity(element: $0.element)) } cursor = count == 0 ? 0 : (cursor + didRead) % count let focused = uptime() < deadline ? copyElement(app, kAXFocusedWindowAttribute) : nil let focusedID = focused.flatMap { element in records.first { CFEqual($0.element, element) }?.id } return WindowSwitcherScan(windows: records, focusedID: focusedID, unavailable: metadataFailed || didRead < count, reportedFocusedWindow: focused != nil, + reportedFocusWasExcluded: focused.map { excluded.contains(WindowSwitcherAXIdentity(element: $0)) } == true, excludedWindowNumbers: excludedWindowNumbers) } diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift index 8dcabd46d..5fd8116ff 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift @@ -149,7 +149,6 @@ final class WindowSwitcherWindowRecords { private var windowRecords: [WindowSwitcherWindowRecord] = [] private var captures: [UInt64: Capture] = [:] private var windowRecordRefreshGeneration: UInt64 = 0 - private var cachedGeneration: UInt64 = 0 private var windowRecordRefreshInFlightCount = 0 init(windowRecordRefreshTimeout: TimeInterval = 0.75, @@ -164,7 +163,6 @@ final class WindowSwitcherWindowRecords { func stop() { windowRecords.removeAll() - cachedGeneration = 0 for generation in Array(captures.keys) { finishCapture(generation, records: nil) } @@ -249,7 +247,8 @@ final class WindowSwitcherWindowRecords { guard !Task.isCancelled else { return .init(records: windowRecords, isFresh: false) } // An older read can still be physically running after a newer one // completes. Joining it cannot provide fresh validation. - let joinable = captures.keys.max().flatMap { $0 > cachedGeneration ? $0 : nil } + let latest = windowRecordRefreshGeneration + let joinable = captures[latest] == nil ? nil : latest let generation = requiresNewCapture ? startCapture() : joinable ?? startCapture() guard let generation else { return WindowSwitcherWindowRecordSnapshot(records: windowRecords, isFresh: false) @@ -276,14 +275,11 @@ final class WindowSwitcherWindowRecords { guard let capture = captures.removeValue(forKey: generation) else { return } capture.timeout.cancel() if records == nil { capture.task.cancel() } - // An older capture can finish after a new invocation has already - // published its own result. Keep the cache ordered by capture start. - if let records, generation > cachedGeneration { - cachedGeneration = generation - windowRecords = records - } + // A newer attempt supersedes an older capture even if it fails. + let isFresh = records != nil && generation == windowRecordRefreshGeneration + if isFresh, let records { windowRecords = records } let snapshot = WindowSwitcherWindowRecordSnapshot(records: windowRecords, - isFresh: records != nil && generation == cachedGeneration) + isFresh: isFresh) for continuation in capture.waiters.values { continuation.resume(returning: snapshot) } } } diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift index df0e7fd14..3e75b9fdc 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift @@ -7,6 +7,13 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable struct State { var number: CGWindowID? var focused = false + var exposesWindowNumber = true + var exposesSecondaryWindowNumber = true + var includesSecondaryWindow = true + var focusesSecondaryWindow = false + var secondaryWindowIsSmall = false + var secondaryMetadataUnavailable = false + var windowListUnavailable = false var beforeRead: (() -> Void)? var reads = 0 var actions: [String] = [] @@ -18,16 +25,20 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable private let replacementNumber: CGWindowID? private let emptyDialog: AXUIElement? private let emptyDialogNumber: CGWindowID? + private let secondaryWindow: AXUIElement? + private let secondaryWindowNumber: CGWindowID? let observesSystemNotifications = false init(number: CGWindowID?, elementPID: pid_t, replacementNumber: CGWindowID? = nil, - emptyDialogNumber: CGWindowID? = nil) { + emptyDialogNumber: CGWindowID? = nil, secondaryWindowNumber: CGWindowID? = nil) { state = State(number: number) window = AXUIElementCreateApplication(elementPID) self.replacementNumber = replacementNumber replacement = replacementNumber.map { _ in AXUIElementCreateApplication(elementPID + 100) } self.emptyDialogNumber = emptyDialogNumber emptyDialog = emptyDialogNumber.map { _ in AXUIElementCreateApplication(elementPID + 200) } + self.secondaryWindowNumber = secondaryWindowNumber + secondaryWindow = secondaryWindowNumber.map { _ in AXUIElementCreateApplication(elementPID + 300) } } func update(_ body: (inout State) -> Void) { lock.lock(); defer { lock.unlock() }; body(&state) } func read(_ body: (State) -> T) -> T { lock.lock(); defer { lock.unlock() }; return body(state) } @@ -35,24 +46,39 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable update { $0.reads += 1 } read { $0.beforeRead }?() return read { state in + guard !state.windowListUnavailable else { return nil } let main = state.number.map { $0 == replacementNumber ? replacement ?? window : window } - return [main, emptyDialog].compactMap { $0 } + let other = state.includesSecondaryWindow && state.number != secondaryWindowNumber ? secondaryWindow : nil + return [main, emptyDialog, other].compactMap { $0 } } } func element(_ owner: AXUIElement, attribute: String) -> AXUIElement? { - if attribute == kAXFocusedWindowAttribute, read({ $0.focused }) { return window } + if attribute == kAXFocusedWindowAttribute { + return read { state in + if state.focusesSecondaryWindow { return secondaryWindow } + return state.focused ? window : nil + } + } return attribute == kAXCloseButtonAttribute ? owner : nil } func windowAttributes(_ window: AXUIElement) -> [Any]? { let isDialog = emptyDialog.map { CFEqual($0, window) } == true - var point = isDialog ? CGPoint(x: 30, y: 30) : CGPoint(x: 20, y: 20) + let isSecondary = secondaryWindow.map { CFEqual($0, window) } == true + if isSecondary, read({ $0.secondaryMetadataUnavailable }) { return nil } + var point = CGPoint(x: 20, y: 20) + if isDialog { point = CGPoint(x: 30, y: 30) } + if isSecondary { point = CGPoint(x: 60, y: 60) } var size = isDialog ? CGSize(width: 400, height: 300) : CGSize(width: 800, height: 600) + if isSecondary, read({ $0.secondaryWindowIsSmall }) { size = CGSize(width: 40, height: 30) } return [kAXWindowRole, isDialog ? kAXDialogSubrole : kAXStandardWindowSubrole, isDialog ? "" : "Fixture", false, AXValueCreate(.cgPoint, &point)!, AXValueCreate(.cgSize, &size)!] } func windowNumber(_ window: AXUIElement) -> CGWindowID? { if emptyDialog.map({ CFEqual($0, window) }) == true { return emptyDialogNumber } - return read { $0.number } + if secondaryWindow.map({ CFEqual($0, window) }) == true { + return read { $0.exposesSecondaryWindowNumber ? secondaryWindowNumber : nil } + } + return read { $0.exposesWindowNumber ? $0.number : nil } } func boolValue(_ window: AXUIElement, attribute: String) -> Bool? { emptyDialog.map { CFEqual($0, window) } == true ? false : nil @@ -257,6 +283,16 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { } func testColdLaunchRecapturesWindowServerWhenNeitherSourceHasAWindowYet() async throws { + try await verifyRetryUsesNewVisibility(initialRecords: []) + } + + func testRetryReplacesSplashVisibilityBeforeInferringFocus() async throws { + let splash = WindowSwitcherWindowRecord(windowNumber: 9, processIdentifier: 43, title: "", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600), titleIsAvailable: false) + try await verifyRetryUsesNewVisibility(initialRecords: [splash]) + } + + private func verifyRetryUsesNewVisibility(initialRecords: [WindowSwitcherWindowRecord]) async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } let launched = CatalogAXAccess(number: nil, elementPID: 202) @@ -264,18 +300,18 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { defer { emptyCaptures.signal(); emptyCaptures.signal() } let record = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Launched", isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) - launched.update { - $0.beforeRead = { [weak launched] in - launched?.update { state in - if state.reads == 2 { state.number = 8; state.focused = true } - } - } - } + let retryCaptureStarted = DispatchSemaphore(value: 0) + let finishRetryCapture = DispatchSemaphore(value: 0) + defer { finishRetryCapture.signal() } var foregroundPID: pid_t = 42 let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), accessFactory: { $0 == 42 ? previous : launched }, allSpacesCatalog: .init(windowRecordProvider: { - emptyCaptures.wait(timeout: .now()) == .success ? [] : [record] + if emptyCaptures.wait(timeout: .now()) == .success { return initialRecords } + retryCaptureStarted.signal() + _ = finishRetryCapture.wait(timeout: .now() + 1) + launched.update { $0.number = 8; $0.focused = initialRecords.isEmpty } + return [record] }), discovery: .init(applications: { let prior = WindowSwitcherAppCatalog.Application( processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") @@ -290,6 +326,9 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { foregroundPID = 43 catalog.prepareForInvocation() + try await waitUntil { retryCaptureStarted.wait(timeout: .now()) == .success } + XCTAssertEqual(launched.read { $0.reads }, 1) + finishRetryCapture.signal() try await waitUntil { catalog.isInvocationReady } let entries = catalog.entries(sortMode: .recentUse) XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) @@ -297,6 +336,201 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(launched.read { $0.reads }, 2) } + func testSingleForegroundAXWindowWithoutNumberDoesNotNeedAnExtraScan() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + launched.update { $0.exposesWindowNumber = false } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Foreground", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600))] + }), discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground") + return foregroundPID == 43 ? [previous, new] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + for reportedFocus in [false, true] { + let readsBeforeInvocation = launched.read { $0.reads } + launched.update { $0.focused = reportedFocus } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.map(\.processIdentifier), [43, 42]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertNil(entries.first?.windowNumber) + XCTAssertEqual(launched.read { $0.reads }, readsBeforeInvocation + 1) + } + } + + func testVisibilityCountsNumberedAndUnnumberedOnscreenRowsAsSeparateCandidates() async throws { + try await verifyTwoAXWindows(secondaryOnscreen: true, secondaryNumbered: true) + } + + func testVisibilityCanIdentifyTheOnlyOnscreenUnnumberedAXWindow() async throws { + try await verifyTwoAXWindows(secondaryOnscreen: false, secondaryNumbered: false) + } + + private func verifyTwoAXWindows(secondaryOnscreen: Bool, secondaryNumbered: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) + launched.update { + $0.exposesWindowNumber = false + $0.exposesSecondaryWindowNumber = secondaryNumbered + } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + [ + .init(windowNumber: 8, processIdentifier: 43, title: "First", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), + .init(windowNumber: 9, processIdentifier: 43, title: "Second", isOnScreen: secondaryOnscreen, + bounds: CGRect(x: 60, y: 60, width: 800, height: 600), hasSpace: true, + isOnActiveSpace: secondaryOnscreen), + ] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + return foregroundPID == 43 + ? [prior, .init(processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground")] + : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + if secondaryOnscreen { + XCTAssertNil(catalog.focusedWindowID) + XCTAssertEqual(entries.first?.windowNumber, 7) + } else { + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(entries.first?.processIdentifier, 43) + XCTAssertEqual(entries.first?.bounds.origin, CGPoint(x: 20, y: 20)) + XCTAssertNil(entries.first?.windowNumber) + } + } + + func testInvocationReconcilesForegroundAppThatJoinsInventoryAfterPreparation() async throws { + try await verifyLateForegroundEligibility(startsAsAccessory: false) + } + + func testInvocationReconcilesAccessoryAppThatBecomesRegularDuringLaunch() async throws { + try await verifyLateForegroundEligibility(startsAsAccessory: true) + } + + private func verifyLateForegroundEligibility(startsAsAccessory: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + launched.update { $0.focused = true } + var foregroundPID: pid_t = 42 + var isRegular = false + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, allSpacesCatalog: .init(windowRecordProvider: { [] }), + discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched", isRegular: isRegular) + return isRegular || startsAsAccessory ? [previous, new] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + XCTAssertNotNil(catalog.focusedWindowID) + + foregroundPID = 43 + catalog.prepareForInvocation() + isRegular = true + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 1) + } + + func testUnnumberedAXWindowWithAmbiguousBoundsCannotBecomeAnchor() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let restoring = CatalogAXAccess(number: 8, elementPID: 202) + restoring.update { $0.exposesWindowNumber = false } + let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : restoring }, + allSpacesCatalog: .init(windowRecordProvider: { + [ + .init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: false, + bounds: bounds, hasSpace: true, isOnActiveSpace: false), + .init(windowNumber: 9, processIdentifier: 43, title: "Foreground", isOnScreen: true, + bounds: bounds, hasSpace: true, isOnActiveSpace: true), + ] + }), discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground") + return foregroundPID == 43 ? [previous, new] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 7) + XCTAssertNil(catalog.focusedWindowID) + XCTAssertEqual(restoring.read { $0.reads }, 2) + } + + func testBackgroundExactFocusIgnoresVisibilityAwaitingReplacement() async throws { + let foreground = CatalogAXAccess(number: 9, elementPID: 201) + foreground.update { $0.focused = true } + let initialCapture = DispatchSemaphore(value: 1) + let releaseCapture = DispatchSemaphore(value: 0) + let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { _ in foreground }, + allSpacesCatalog: .init(windowRecordProvider: { + let initial = initialCapture.wait(timeout: .now()) == .success + if !initial { _ = releaseCapture.wait(timeout: .now() + 2) } + let current: CGWindowID = initial ? 9 : 8 + return [8, 9].map { number in + .init(windowNumber: number, processIdentifier: 42, title: "Window", isOnScreen: number == current, + bounds: bounds, hasSpace: true, isOnActiveSpace: number == current) + } + }), discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "foreground", localizedName: "Foreground")] + }, foregroundProcessIdentifier: { 42 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { initialCapture.signal(); releaseCapture.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foreground.update { $0.number = 8 } + catalog.refresh() + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 && $0.windowElement != nil } + } + let focused = catalog.entries(sortMode: .recentUse).first { $0.id == catalog.focusedWindowID } + XCTAssertEqual(focused?.windowNumber, 8) + } + func testExcludedOnscreenDialogDoesNotPreventInferringTheForegroundWindow() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } @@ -329,14 +563,110 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(foreground.read { $0.reads }, 1) } - func testOffscreenAXWindowDoesNotSuppressRetryForAnUnlistedOnscreenWindow() async throws { + func testOffscreenReportedFocusRetriesBeforeRecordingRecentUse() async throws { + try await verifyLaunchFocusRecovery(partialAX: false, failsRetryCapture: false) + } + + func testPartiallyReadableForegroundAXRetriesBeforeRelyingOnCGFallback() async throws { + try await verifyLaunchFocusRecovery(partialAX: true, failsRetryCapture: false) + } + + func testFailedRetryCaptureDoesNotConfirmRepeatedOffscreenAXFocus() async throws { + try await verifyLaunchFocusRecovery(partialAX: false, failsRetryCapture: true) + } + + func testReportedLaunchFocusRetriesWhenVisibilityOnlyShowsAnOlderListedWindow() async throws { + let splash = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Splash", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + try await verifyLaunchWindowRetry(records: [splash]) + } + + func testIncompleteLaunchAXRetriesWhenVisibilityOnlyShowsAnOlderListedWindow() async throws { + let splash = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Splash", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + try await verifyLaunchWindowRetry(records: [splash], partialInitialAXRead: true) + } + + func testReportedLaunchFocusRetriesWhenVisibilityCaptureFails() async throws { + try await verifyLaunchWindowRetry(records: nil) + } + + func testLaunchRetriesWhenBothInitialWindowSourcesFail() async throws { + try await verifyLaunchWindowRetry(records: nil, failsInitialAXRead: true) + } + + func testLaunchFocusOnAnAlreadyExcludedWindowDoesNotRetry() async throws { + let primary = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Primary", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + try await verifyLaunchWindowRetry(records: [primary], secondaryWindowIsSmall: true) + } + + private func verifyLaunchWindowRetry(records: [WindowSwitcherWindowRecord]?, + secondaryWindowIsSmall: Bool = false, + failsInitialAXRead: Bool = false, + partialInitialAXRead: Bool = false) async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } - let launched = CatalogAXAccess(number: 8, elementPID: 202) + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) launched.update { + $0.includesSecondaryWindow = secondaryWindowIsSmall || partialInitialAXRead + $0.focusesSecondaryWindow = !partialInitialAXRead + $0.secondaryWindowIsSmall = secondaryWindowIsSmall + $0.secondaryMetadataUnavailable = partialInitialAXRead + $0.windowListUnavailable = failsInitialAXRead $0.beforeRead = { [weak launched] in launched?.update { state in - guard state.reads == 2 else { return } + if state.reads == 2 { + state.windowListUnavailable = false + state.includesSecondaryWindow = true + state.secondaryMetadataUnavailable = false + state.focusesSecondaryWindow = true + } + } + } + } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { records }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched", + isFinishedLaunching: false) + return foregroundPID == 43 ? [prior, new] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + if secondaryWindowIsSmall { + XCTAssertEqual(entries.compactMap(\.windowNumber), [7, 8]) + XCTAssertNil(catalog.focusedWindowID) + XCTAssertEqual(launched.read { $0.reads }, 1) + } else { + XCTAssertEqual(entries.compactMap(\.windowNumber), [9, 7, 8]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 2) + } + } + + private func verifyLaunchFocusRecovery(partialAX: Bool, failsRetryCapture: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: partialAX ? 9 : nil) + let initialCaptures = DispatchSemaphore(value: 2) + defer { initialCaptures.signal(); initialCaptures.signal() } + launched.update { + $0.focused = !partialAX + $0.secondaryMetadataUnavailable = partialAX + $0.beforeRead = { [weak launched] in + launched?.update { state in + guard state.reads == 2, !failsRetryCapture else { return } state.number = 9 state.focused = true } @@ -346,10 +676,11 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), accessFactory: { $0 == 42 ? previous : launched }, allSpacesCatalog: .init(windowRecordProvider: { - [.init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: false, - bounds: CGRect(x: 20, y: 20, width: 800, height: 600), isOnActiveSpace: true), - .init(windowNumber: 9, processIdentifier: 43, title: "", isOnScreen: true, - bounds: CGRect(x: 40, y: 40, width: 800, height: 600), titleIsAvailable: false)] + if initialCaptures.wait(timeout: .now()) != .success, failsRetryCapture { return nil } + return [.init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: false, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true, isOnActiveSpace: false), + .init(windowNumber: 9, processIdentifier: 43, title: "Launched", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600))] }), discovery: .init(applications: { let prior = WindowSwitcherAppCatalog.Application( @@ -366,7 +697,14 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { catalog.prepareForInvocation() try await waitUntil { catalog.isInvocationReady } XCTAssertEqual(launched.read { $0.reads }, 2) - XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [9, 7]) + let entries = catalog.entries(sortMode: .recentUse) + if failsRetryCapture { + XCTAssertEqual(entries.first?.windowNumber, 7) + XCTAssertNil(catalog.focusedWindowID) + } else { + XCTAssertEqual(entries.compactMap(\.windowNumber), [9, 7, 8]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } } func testInvocationPublishesBeforeQueuedBackgroundVisibilityReadCompletes() async throws { @@ -405,6 +743,103 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) } + func testVisibilityChangeWithConfirmedFocusRefreshesOtherWindowAfterReadiness() async throws { + try await verifyVisibilityChangeRefreshesAfterReadiness(hasPriorSnapshot: true) + } + + func testVisibilityChangeDuringFirstAXReadRefreshesOtherWindowAfterReadiness() async throws { + try await verifyVisibilityChangeRefreshesAfterReadiness(hasPriorSnapshot: false) + } + + func testVisibilityChangeDuringCancelledFirstAXReadStillRefreshesOtherWindow() async throws { + try await verifyVisibilityChangeRefreshesAfterReadiness(hasPriorSnapshot: false, cancelsInvocation: true) + } + + private func verifyVisibilityChangeRefreshesAfterReadiness(hasPriorSnapshot: Bool, + cancelsInvocation: Bool = false) async throws { + let previous = CatalogAXAccess(number: 6, elementPID: 200) + previous.update { $0.focused = true } + let app = CatalogAXAccess(number: 7, elementPID: 201, secondaryWindowNumber: 8) + let firstAXStarted = DispatchSemaphore(value: 0) + let releaseFirstAX = DispatchSemaphore(value: 0) + let discoveryRead = hasPriorSnapshot ? 2 : 1 + app.update { + $0.focused = true + $0.includesSecondaryWindow = false + $0.beforeRead = { [weak app] in + if !hasPriorSnapshot, app?.read({ $0.reads }) == 1 { + firstAXStarted.signal() + _ = releaseFirstAX.wait(timeout: .now() + 1) + } + app?.update { state in + if state.reads > discoveryRead { state.includesSecondaryWindow = true } + } + } + } + let initialCapture = DispatchSemaphore(value: 1) + let captureStarted = DispatchSemaphore(value: 0) + let releaseCapture = DispatchSemaphore(value: 0) + let primary = WindowSwitcherWindowRecord(windowNumber: 7, processIdentifier: 42, title: "Document", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + let secondary = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 42, title: "", isOnScreen: true, + bounds: CGRect(x: 60, y: 60, width: 800, height: 600), titleIsAvailable: false) + let priorBounds = CGRect(x: 100, y: 100, width: 800, height: 600) + let priorVisible = WindowSwitcherWindowRecord(windowNumber: 6, processIdentifier: 41, title: "Prior", + isOnScreen: true, bounds: priorBounds) + let priorOffscreen = WindowSwitcherWindowRecord(windowNumber: 6, processIdentifier: 41, title: "Prior", + isOnScreen: false, bounds: priorBounds, hasSpace: true, isOnActiveSpace: false) + var foregroundPID: pid_t = hasPriorSnapshot ? 42 : 41 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? app : previous }, + allSpacesCatalog: .init(windowRecordProvider: { + if initialCapture.wait(timeout: .now()) == .success { + return hasPriorSnapshot ? [primary] : [priorVisible] + } + captureStarted.signal() + _ = releaseCapture.wait(timeout: .now() + 1) + return hasPriorSnapshot ? [primary, secondary] : [priorOffscreen, primary, secondary] + }), discovery: .init(applications: { + let host = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "fixture", localizedName: "Fixture") + if hasPriorSnapshot { return [host] } + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 41, bundleIdentifier: "prior", localizedName: "Prior") + return foregroundPID == 42 ? [prior, host] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { initialCapture.signal(); releaseCapture.signal(); releaseFirstAX.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + var windowsAtReadiness: [CGWindowID]? + catalog.onChange = { [weak catalog] in + guard let catalog, catalog.isInvocationReady, windowsAtReadiness == nil else { return } + windowsAtReadiness = catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber) + } + foregroundPID = 42 + catalog.prepareForInvocation() + try await waitUntil { captureStarted.wait(timeout: .now()) == .success } + if hasPriorSnapshot { + try await waitUntil { app.read { $0.reads } == discoveryRead } + } else { + try await waitUntil { firstAXStarted.wait(timeout: .now()) == .success } + } + if cancelsInvocation { catalog.cancelInvocation() } + releaseCapture.signal() + if !hasPriorSnapshot { + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 6 && $0.isOnOtherDesktop } + } + releaseFirstAX.signal() + } + + let expectedAtReadiness: [CGWindowID] = hasPriorSnapshot ? [7] : [7, 6] + try await waitUntil { + catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber) == expectedAtReadiness + [8] + } + if !cancelsInvocation { XCTAssertEqual(windowsAtReadiness, expectedAtReadiness) } + XCTAssertEqual(app.read { $0.reads }, discoveryRead + 1) + } + func testCancellingInvocationLetsAQueuedVisibilityRefreshRunWhileAXIsPending() async throws { let access = CatalogAXAccess(number: 7, elementPID: 201) let axStarted = DispatchSemaphore(value: 0) @@ -455,9 +890,12 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { _ = releaseOlderCapture.wait(timeout: .now() + 5) return [] } - guard holdInvocationCapture.wait(timeout: .now()) == .success else { return [] } - invocationCaptureStarted.signal() - _ = releaseInvocationCapture.wait(timeout: .now() + 5) + if holdInvocationCapture.wait(timeout: .now()) == .success { + invocationCaptureStarted.signal() + _ = releaseInvocationCapture.wait(timeout: .now() + 5) + } else if launched.read({ $0.reads }) == 0 { + return [] + } return [.init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: false, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), .init(windowNumber: 9, processIdentifier: 43, title: "", isOnScreen: true, @@ -482,9 +920,8 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { try await waitUntil { catalog.isInvocationReady } holdOlderCapture.signal() - let activation = Task { await reader.freshRecordsForActivation() } + catalog.refresh() try await waitUntil { olderCaptureStarted.wait(timeout: .now()) == .success } - activation.cancel() holdInvocationCapture.signal() foregroundPID = 43 @@ -550,6 +987,44 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(session.selected?.windowNumber, 7) } + func testForegroundHandoffAndIncompleteAXShareOneRetry() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + let holdInvocationCapture = DispatchSemaphore(value: 0) + let invocationCaptureStarted = DispatchSemaphore(value: 0) + let releaseCapture = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + if holdInvocationCapture.wait(timeout: .now()) == .success { + invocationCaptureStarted.signal() + _ = releaseCapture.wait(timeout: .now() + 2) + } + return [.init(windowNumber: 8, processIdentifier: 43, title: "Launched", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600))] + }), discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous"), + .init(processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched")] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseCapture.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + let initialReads = launched.read { $0.reads } + + holdInvocationCapture.signal() + catalog.prepareForInvocation() + try await waitUntil { invocationCaptureStarted.wait(timeout: .now()) == .success } + try await waitUntil { launched.read { $0.reads } == initialReads + 1 } + foregroundPID = 43 + releaseCapture.signal() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, initialReads + 2) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7]) + XCTAssertNil(catalog.focusedWindowID) + } + func testRecentUseWaitsForVisibilityAndKeepsInferenceOutOfHistory() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } @@ -809,6 +1284,53 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [9, 7, 8]) } + func testHelperDiscoveredDuringHostReadDoesNotCauseARedundantRetry() async throws { + let host = CatalogAXAccess(number: 7, elementPID: 201) + host.update { $0.focused = true } + let helper = CatalogAXAccess(number: 8, elementPID: 202) + let initialCapture = DispatchSemaphore(value: 1) + let hostReadStarted = DispatchSemaphore(value: 0) + let releaseHostRead = DispatchSemaphore(value: 0) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? host : helper }, + allSpacesCatalog: .init(windowRecordProvider: { + if initialCapture.wait(timeout: .now()) == .success { return [] } + return [ + .init(windowNumber: 7, processIdentifier: 42, title: "Host", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), + .init(windowNumber: 8, processIdentifier: 43, title: "Helper", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600)), + ] + }), discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "fixture.host", bundlePath: "/Fixture.app", + localizedName: "Fixture"), + .init(processIdentifier: 43, bundleIdentifier: "fixture.host.helper", + bundlePath: "/Fixture.app/Helper.app", localizedName: "Helper", isRegular: false)] + }, foregroundProcessIdentifier: { 42 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { initialCapture.signal(); releaseHostRead.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + let initialHostReads = host.read { $0.reads } + host.update { + $0.beforeRead = { + hostReadStarted.signal() + _ = releaseHostRead.wait(timeout: .now() + 1) + } + } + + catalog.prepareForInvocation() + try await waitUntil { hostReadStarted.wait(timeout: .now()) == .success } + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 } } + host.update { $0.beforeRead = nil } + releaseHostRead.signal() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [7, 8]) + XCTAssertEqual(entries.first { $0.windowNumber == 8 }?.axWorkerPID, 43) + XCTAssertEqual(host.read { $0.reads }, initialHostReads + 1) + XCTAssertEqual(helper.read { $0.reads }, 1) + } + func testPreviouslyAXListedWindowCannotBecomeAnchorAfterItsAXRowDisappears() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift index 4c4404563..4452c3894 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift @@ -15,8 +15,11 @@ private final class BlockingWindowRecords: @unchecked Sendable { private var calls = 0 private var completions = 0 private var blocked = true + private let failingCall: Int? let release = DispatchSemaphore(value: 0) + init(failingCall: Int? = nil) { self.failingCall = failingCall } + var counts: (started: Int, completed: Int) { lock.lock(); defer { lock.unlock() } return (calls, completions) @@ -32,6 +35,7 @@ private final class BlockingWindowRecords: @unchecked Sendable { lock.unlock() if shouldWait { _ = release.wait(timeout: .now() + 3) } lock.lock(); completions += 1; lock.unlock() + if number == failingCall { return nil } return [.init(windowNumber: UInt32(number), processIdentifier: 42, title: "Fixture", isOnScreen: true, bounds: CGRect(x: 0, y: 30, width: 800, height: 600))] } @@ -104,6 +108,29 @@ final class WindowSwitcherWindowRecordsTests: XCTestCase { XCTAssertEqual(current.records.map(\.windowNumber), [3]) } + func testFailedNewCaptureDoesNotMakeOlderRecordsFreshForAnAction() async throws { + let provider = BlockingWindowRecords(failingCall: 2) + let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 2, windowRecordProvider: { provider.read() }) + defer { provider.release.signal(); reader.stop() } + let older = Task { await reader.freshWindowRecordSnapshot() } + try await waitUntil { provider.counts.started == 1 } + + provider.unblock() + let failed = await reader.freshWindowRecordSnapshot(requiresNewCapture: true) + XCTAssertFalse(failed.isFresh) + let entry = WindowSwitcherAppEntry(id: "latest", processIdentifier: 42, bundleIdentifier: "fixture", + appName: "Fixture", windowTitle: "Fixture", icon: nil, windowElement: nil, isMinimized: false, + windowNumber: 3, windowBounds: CGRect(x: 0, y: 30, width: 800, height: 600), shortcutToken: nil) + let validated = await reader.isCurrentFallback(entry) + XCTAssertTrue(validated) + XCTAssertEqual(provider.counts.completed, 2) + + provider.release.signal() + let superseded = await older.value + XCTAssertFalse(superseded.isFresh) + XCTAssertEqual(superseded.records.map(\.windowNumber), [3]) + } + func testStopResumesWaitersWithoutWaitingForSystemQuery() async throws { let provider = BlockingWindowRecords() let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 2, windowRecordProvider: { provider.read() }) From 0122252311acab874387c0dffbc38b78021044cc Mon Sep 17 00:00:00 2001 From: xcv58 Date: Wed, 25 Nov 2026 20:06:02 -0500 Subject: [PATCH 4/5] fix(window-switcher): preserve confirmed focus during launch discovery --- .../Sources/WindowSwitcherAppCatalog.swift | 222 ++++++++++--- .../Tests/WindowSwitcherAppCatalogTests.swift | 313 +++++++++++++++++- 2 files changed, 476 insertions(+), 59 deletions(-) diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift index 178ca4274..b2a0660dd 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift @@ -74,7 +74,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { var isDragging: () -> Bool = { CGEventSource.buttonState(.combinedSessionState, button: .left) } } - private struct ForegroundTarget { + private struct ForegroundTarget: Equatable { let hostPID: pid_t let workerPID: pid_t } @@ -85,6 +85,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { var requiresAXConfirmation: Bool { self != .offscreenAX } } + private enum FocusVisibility { + case onscreen, offscreen + } + private struct FocusObservation { let workerPID: pid_t let id: String? @@ -104,6 +108,14 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } } + private struct PendingFocus { + let target: ForegroundTarget + let foregroundAtScanStart: ForegroundTarget? + let observations: [pid_t: FocusObservation] + let focusChangeAfterCapture: Int? + var confirmedOnly = false + } + var onChange: (() -> Void)? private(set) var isInitialDiscoveryComplete = false private(set) var isInvocationReady = false @@ -131,6 +143,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var activeScanCount = 0 private var dirtyHosts: Set = [] private var pendingInvalidations: Set = [] + private var focusChangesAfterCapture: [pid_t: Int] = [:] private var pendingRecordsInvalidation = false private var applicationsByPID: [pid_t: Application] = [:] private var mappingCandidates: [WindowSwitcherProcessMapping.Candidate] = [] @@ -143,7 +156,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var publicationTask: Task? private var publicationDirty = false private var removedProcesses: Set = [] - private var pendingFocus: [pid_t: [pid_t: FocusObservation]] = [:] + private var pendingFocus: [pid_t: PendingFocus] = [:] private var inferredFocusWorkerLifetime: UUID? private var windowRecordsPending = false private var sleeping = false @@ -153,6 +166,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var invocationInProgress = false private var invocationForegroundPID: pid_t? private var contradictedInvocationFocusID: String? + private var cancelledFocus: (generation: UUID, target: ForegroundTarget, contradictedID: String?)? private var invocationRequiredHosts: Set = [] private var queuedInvocationRetryHost: pid_t? private var deferredForegroundRefreshes: Set = [] @@ -167,6 +181,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var allSpacesRecordsAreFresh = false private var allSpacesRecords: [WindowSwitcherWindowRecord] = [] private var allSpacesRefreshTask: Task? + private var pendingVisibilityInvocation: UUID? + private var captureSequence = 0 + private var lastPublishedCapture = 0 + private var invocationVisibility: (generation: UUID, capture: Int, records: [WindowSwitcherWindowRecord]?)? private var allSpacesGeneration = UUID() private var didReadAllSpaces = false @@ -256,6 +274,8 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { isInvocationReady = false windowRecordsPending = false allSpacesRefreshTask?.cancel(); allSpacesRefreshTask = nil + pendingVisibilityInvocation = nil + invocationVisibility = nil allSpacesCatalog.stop() allSpacesRecords.removeAll() publication = WindowSwitcherPublishedWindows() @@ -270,6 +290,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { helperPIDsByHost.removeAll() dirtyHosts.removeAll() pendingInvalidations.removeAll() + focusChangesAfterCapture.removeAll() pendingRecordsInvalidation = false timer?.invalidate(); timer = nil observers.forEach(notificationCenter.removeObserver); observers.removeAll() @@ -282,9 +303,13 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { /// Coalesces events by owner. A dirty host remains queued when a scan is in /// flight, so changes arriving during that scan get one follow-up read. - func invalidate(processIdentifiers: Set, windowRecords: Bool) { + func invalidate(processIdentifiers: Set, windowRecords: Bool, focusChanged: Bool = false) { guard running else { return } - pendingInvalidations.formUnion(processIdentifiers.map { processMapping.host(for: $0) }.filter { expectedHostPIDs.contains($0) }) + let hosts = Set(processIdentifiers.map { processMapping.host(for: $0) }).intersection(expectedHostPIDs) + pendingInvalidations.formUnion(hosts) + if focusChanged { + for host in hosts { focusChangesAfterCapture[host] = captureSequence } + } pendingRecordsInvalidation = pendingRecordsInvalidation || windowRecords if processIdentifiers.contains(ProcessInfo.processInfo.processIdentifier) { markPublicationDirty() } scheduleRefresh() @@ -326,6 +351,8 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // second reader slot while that physical query finishes. allSpacesRefreshTask?.cancel() allSpacesRefreshTask = nil + pendingVisibilityInvocation = nil + invocationVisibility = nil invocationInProgress = true invocationForegroundPID = discovery.foregroundProcessIdentifier() isInvocationReady = false @@ -345,8 +372,24 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { func cancelInvocation() { guard invocationInProgress else { return } + let target = foregroundTarget() + let capturedFocus = target.flatMap { pendingFocus[$0.hostPID] } + let generation = invocationGeneration + let contradictedID = contradictedInvocationFocusID + let canPreserveFocus = target?.workerPID == invocationForegroundPID resetInvocation() pendingFocus.removeAll() + publication.recency.clearInference() + inferredFocusWorkerLifetime = nil + // Cancelling the chooser still allows a genuine foreground observation + // to enter history if the app and its focus scan have not changed. + if let target, canPreserveFocus { + cancelledFocus = (generation, target, contradictedID) + if var capturedFocus, capturedFocus.target == target, capturedFocus.foregroundAtScanStart == target { + capturedFocus.confirmedOnly = true + pendingFocus[target.hostPID] = capturedFocus + } + } applyInvalidations() drainRefreshes() } @@ -358,6 +401,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { invocationInProgress = false invocationForegroundPID = nil contradictedInvocationFocusID = nil + cancelledFocus = nil invocationRequiredHosts.removeAll() queuedInvocationRetryHost = nil invocationRequiresRecords = false @@ -403,7 +447,8 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { snapshots.removeValue(forKey: pid) scannedHelperPIDs.removeValue(forKey: oldMapping.host(for: pid)) excludedWindowNumbersByHost.removeValue(forKey: pid) - pendingFocus.removeValue(forKey: pid) + pendingFocus.removeValue(forKey: oldMapping.host(for: pid)) + focusChangesAfterCapture.removeValue(forKey: oldMapping.host(for: pid)) removedProcesses.insert(pid) dirtyHosts.insert(oldMapping.host(for: pid)) markPublicationDirty() @@ -440,7 +485,8 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { if windowRecordsPending, !invocationInProgress || invocationRequiresRecords { refreshAllSpaces() } - let foregroundHostPID = foregroundTarget()?.hostPID + let foregroundAtScanStart = foregroundTarget() + let foregroundHostPID = foregroundAtScanStart?.hostPID let hostAwaitingVisibility = invocationVisibilityRetryPID.flatMap { foregroundTarget(for: $0)?.hostPID } let pids = dirtyHosts.sorted { let lhsActive = $0 == foregroundHostPID @@ -462,6 +508,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { activeScanCount += 1 let app = application.withPresentation() let invocation = invocationGeneration + let focusChangeAfterCapture = focusChangesAfterCapture.removeValue(forKey: pid) Task { [weak self] in defer { if let self { @@ -507,10 +554,17 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { scannedHelperPIDs[pid] = Set(focusObservations.keys).subtracting([pid]) excludedWindowNumbersByHost[pid] = excludedWindowNumbers if previous != entries { markPublicationDirty() } - if invocation == invocationGeneration, queuedInvocationRetryHost != pid { + let isCurrentScan = invocation == invocationGeneration && queuedInvocationRetryHost != pid + if isCurrentScan { invocationRequiredHosts.remove(pid) - if let target = foregroundTarget(), target.hostPID == pid { - pendingFocus[pid] = focusObservations + } + if let target = foregroundTarget(), target.hostPID == pid { + let wasCancelled = cancelledFocus?.generation == invocation && cancelledFocus?.target == target + && foregroundAtScanStart == target + if isCurrentScan || wasCancelled { + pendingFocus[pid] = PendingFocus(target: target, foregroundAtScanStart: foregroundAtScanStart, + observations: focusObservations, focusChangeAfterCapture: focusChangeAfterCapture, + confirmedOnly: wasCancelled) } } schedulePublication() @@ -558,7 +612,8 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { applicationLifetime: applicationLifetime, access: accessFactory(pid)) { [weak self] event in Task { @MainActor [weak self] in guard let self, workers[event.processIdentifier]?.lifetime == event.lifetime else { return } - invalidate(processIdentifiers: [event.processIdentifier], windowRecords: event.kind.requiresWindowRecords) + invalidate(processIdentifiers: [event.processIdentifier], windowRecords: event.kind.requiresWindowRecords, + focusChanged: event.kind == .focus) } } workers[pid] = created @@ -612,17 +667,22 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // A fresh WindowServer snapshot can distinguish a visible window from // windows that are still restoring or live on other Spaces. let excluded = excludedWindowNumbersByHost[target.hostPID] ?? [] - let candidates = entries.compactMap { entry -> (id: String, onscreen: Bool)? in - guard entry.axWorkerPID == target.workerPID || entry.owningProcessIdentifier == target.workerPID, + let ownerPIDs = foregroundOwnerPIDs(target: target) + let candidates = entries.compactMap { entry -> (id: String, onscreen: Bool, belongsToForeground: Bool)? in + guard ownerPIDs.contains(entry.owningProcessIdentifier) + || entry.axWorkerPID.map(ownerPIDs.contains) == true, isUsableWindow(entry), !publication.lostAXConfirmation(entry), entry.windowElement != nil || entry.windowNumber.map(excluded.contains) != true else { return nil } let record = visibilityRecord(for: entry, among: entries) guard record?.isOnScreen != false, record?.isOnActiveSpace != false else { return nil } - return (entry.id, record?.isOnScreen == true) + return (entry.id, record?.isOnScreen == true, + entry.axWorkerPID == target.workerPID || entry.owningProcessIdentifier == target.workerPID) } - if candidates.count == 1 { return candidates.first?.id } - let onscreen = candidates.filter(\.onscreen) - return onscreen.count == 1 ? onscreen.first?.id : nil + let likely = candidates.count == 1 ? candidates : candidates.filter(\.onscreen) + // A helper can make the host ambiguous without being inferred as the + // focused window when Workspace identifies the host. + guard likely.count == 1, let candidate = likely.first, candidate.belongsToForeground else { return nil } + return candidate.id } private func isUsableWindow(_ entry: WindowSwitcherAppEntry) -> Bool { @@ -630,11 +690,16 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { && !entry.isOnOtherDesktop && !entry.metadataUnavailable } - private func foregroundOnscreenWindowNumbers(target: ForegroundTarget) -> Set { - let ownerPIDs = target.workerPID == target.hostPID + private func foregroundOwnerPIDs(target: ForegroundTarget) -> Set { + target.workerPID == target.hostPID ? (helperPIDsByHost[target.hostPID] ?? []).union([target.workerPID]) : [target.workerPID] - return Set(allSpacesRecords.lazy.filter { + } + + private func foregroundOnscreenWindowNumbers(target: ForegroundTarget, + records: [WindowSwitcherWindowRecord]? = nil) -> Set { + let ownerPIDs = foregroundOwnerPIDs(target: target) + return Set((records ?? allSpacesRecords).lazy.filter { $0.isOnScreen == true && $0.isOnActiveSpace != false && ownerPIDs.contains($0.processIdentifier) }.map(\.windowNumber)).subtracting(excludedWindowNumbersByHost[target.hostPID] ?? []) } @@ -652,15 +717,17 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } private func visibilityRecord(for entry: WindowSwitcherAppEntry, - among entries: [WindowSwitcherAppEntry]) -> WindowSwitcherWindowRecord? { + among entries: [WindowSwitcherAppEntry], + records: [WindowSwitcherWindowRecord]? = nil) -> WindowSwitcherWindowRecord? { + let records = records ?? allSpacesRecords if let number = entry.windowNumber { - return allSpacesRecords.first { $0.windowNumber == number } + return records.first { $0.windowNumber == number } } guard entry.windowElement != nil else { return nil } // Unique geometry can inform visibility only. Preserve exact IDs for // listing and actions. Check all Spaces for competing matches. let excluded = excludedWindowNumbersByHost[entry.processIdentifier] ?? [] - let matches = allSpacesRecords.lazy.filter { + let matches = records.lazy.filter { $0.processIdentifier == entry.owningProcessIdentifier && !excluded.contains($0.windowNumber) && Self.sameBounds($0.bounds, entry.bounds) }.prefix(2) @@ -683,6 +750,24 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { }?.id } + private func activeHelperFocusIDs(in entries: [WindowSwitcherAppEntry], pending: PendingFocus) -> [String] { + let target = pending.target + guard target.workerPID == target.hostPID else { return [] } + return (helperPIDsByHost[target.hostPID] ?? []).sorted().compactMap { pid in + guard applicationsByPID[pid]?.isActive == true, let focus = pending.observations[pid] else { return nil } + return exactWindowID(for: focus, in: entries) + } + } + + private func focusVisibility(of entry: WindowSwitcherAppEntry, in entries: [WindowSwitcherAppEntry], + target: ForegroundTarget, records: [WindowSwitcherWindowRecord]) -> FocusVisibility? { + guard let record = visibilityRecord(for: entry, among: entries, records: records) else { return nil } + if record.isOnScreen == true && record.isOnActiveSpace != false { return .onscreen } + if record.isOnScreen == false || record.isOnActiveSpace == false, + !foregroundOnscreenWindowNumbers(target: target, records: records).isEmpty { return .offscreen } + return nil + } + private func publishForegroundFocus() -> FocusIssue? { if invocationInProgress, discovery.foregroundProcessIdentifier() != invocationForegroundPID { return nil } guard inferredFocusWorkerLifetime != nil || !pendingFocus.isEmpty else { return nil } @@ -693,9 +778,9 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { publication.recency.clearInference() } guard !pendingFocus.isEmpty else { return nil } - let observations = target.flatMap { pendingFocus[$0.hostPID] } + let pending = target.flatMap { pendingFocus[$0.hostPID] } pendingFocus.removeAll() - guard let target, let observations, let focus = observations[target.workerPID] else { + guard let target, let pending, pending.target == target, let focus = pending.observations[target.workerPID] else { publication.recency.clearInference() inferredFocusWorkerLifetime = nil return nil @@ -705,14 +790,14 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // Workspace can report the host for a focused helper. A cached active // flag permits checking a helper's exact AX focus, but cannot infer it. if exactID == nil, !focus.reportedFocusedWindow, target.workerPID == target.hostPID { - exactID = helperPIDsByHost[target.hostPID]?.sorted().lazy.compactMap { pid -> String? in - guard self.applicationsByPID[pid]?.isActive == true, let helperFocus = observations[pid] else { return nil } - return self.exactWindowID(for: helperFocus, in: entries) - }.first + exactID = activeHelperFocusIDs(in: entries, pending: pending).first } // AX can finish before the current WindowServer read. Keep the focus // observation for publication when the matching visibility is available. + let pairedInvocation = pending.confirmedOnly ? cancelledFocus?.generation + : invocationInProgress ? invocationGeneration : nil let awaitingInvocationVisibility = invocationInProgress && invocationRequiresRecords + || (pairedInvocation != nil && pairedInvocation == pendingVisibilityInvocation) let visibilityPending = invocationInProgress ? invocationRequiresRecords || !invocationRequiredHosts.isEmpty : windowRecordsPending || allSpacesRefreshTask != nil @@ -725,30 +810,60 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } } if awaitingInvocationVisibility - || (visibilityPending && exactID == nil && (focus.canInfer || issue != nil)) { - pendingFocus[target.hostPID] = observations + || (!pending.confirmedOnly && visibilityPending && exactID == nil && (focus.canInfer || issue != nil)) { + pendingFocus[target.hostPID] = pending publication.recency.clearInference() inferredFocusWorkerLifetime = nil return nil } - // A background AX notification can arrive before its replacement - // capture. The previous capture cannot contradict that report. + // A focus event can use a capture started after the event, including + // when another invalidation requests that capture in the same refresh. + let pairedCapture = invocationVisibility.flatMap { $0.generation == pairedInvocation ? $0 : nil } + let backgroundFocusCanUseCapture = pairedInvocation == nil && !visibilityPending + && pending.focusChangeAfterCapture.map { lastPublishedCapture > $0 } != false + let cancelledFocusHasNewerCapture = pending.confirmedOnly + && pairedCapture.map { lastPublishedCapture > $0.capture } == true + let latestRecords = allSpacesRecordsAreFresh && (backgroundFocusCanUseCapture || cancelledFocusHasNewerCapture) + ? allSpacesRecords : nil + let pairedRecords = pairedCapture?.records + var helperVerificationRecords = pairedRecords if let exactID, let entry = entries.first(where: { $0.id == exactID }) { - let record = visibilityRecord(for: entry, among: entries) - let contradictsFocus = (invocationInProgress || !visibilityPending) && allSpacesRecordsAreFresh - && (record?.isOnScreen == false || record?.isOnActiveSpace == false) - && !foregroundOnscreenWindowNumbers(target: target).isEmpty - let verifiedOnscreen = allSpacesRecordsAreFresh - && record?.isOnScreen == true && record?.isOnActiveSpace != false - let repeatsUnverifiedFocus = invocationInProgress && exactID == contradictedInvocationFocusID - && !verifiedOnscreen - if contradictsFocus || repeatsUnverifiedFocus { + // When cancelled, prefer a newer decisive observation and fall + // back to the paired capture if the new snapshot is inconclusive. + let latestVisibility = latestRecords.flatMap { focusVisibility(of: entry, in: entries, target: target, records: $0) } + let visibility = latestVisibility + ?? pairedRecords.flatMap { focusVisibility(of: entry, in: entries, target: target, records: $0) } + if cancelledFocusHasNewerCapture, latestVisibility != nil { helperVerificationRecords = latestRecords } + let contradictedID = pending.confirmedOnly ? cancelledFocus?.contradictedID : contradictedInvocationFocusID + let repeatsUnverifiedFocus = pairedInvocation != nil && exactID == contradictedID + && visibility != .onscreen + if visibility == .offscreen || repeatsUnverifiedFocus { issue = .offscreenAX if invocationInProgress { contradictedInvocationFocusID = exactID } } } - if issue == .offscreenAX, invocationInProgress, !invocationRequiredHosts.isEmpty { - pendingFocus[target.hostPID] = observations + if issue == .offscreenAX { + if let helperVerificationRecords { + let onscreen = foregroundOnscreenWindowNumbers(target: target, records: helperVerificationRecords) + let helperIDs = Set(activeHelperFocusIDs(in: entries, pending: pending)) + let verifiedHelpers = entries.filter { + $0.id != exactID && helperIDs.contains($0.id) && $0.windowElement != nil && isUsableWindow($0) + && $0.windowNumber.map(onscreen.contains) == true + } + if verifiedHelpers.count == 1 { + exactID = verifiedHelpers.first?.id + issue = nil + } + } + if issue == .offscreenAX, invocationInProgress, !invocationRequiredHosts.isEmpty { + pendingFocus[target.hostPID] = pending + return nil + } + } + if pending.confirmedOnly { + if issue != .offscreenAX, let exactID { + publication.recency.observeForeground(entries: entries, focusedWindowID: exactID, unavailable: focus.unavailable) + } return nil } let inferredID = exactID == nil && focus.canInfer @@ -759,11 +874,11 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { return issue } - private func reconcileInvocationForeground() { + private func reconcileInvocationForeground(_ current: pid_t?) { guard invocationInProgress else { return } - let current = discovery.foregroundProcessIdentifier() guard current != invocationForegroundPID else { return } invocationForegroundPID = current + contradictedInvocationFocusID = nil publication.recency.clearFocus() inferredFocusWorkerLifetime = nil pendingFocus.removeAll() @@ -842,12 +957,15 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { do { try await Task.sleep(for: .milliseconds(100)) } catch { return } guard !Task.isCancelled, let self else { return } invocationRetryTask = nil - guard discovery.foregroundProcessIdentifier() == foregroundPID else { + let current = discovery.foregroundProcessIdentifier() + reconcileInvocationForeground(current) + guard let current, current != ProcessInfo.processInfo.processIdentifier else { invocationVisibilityRetryPID = nil schedulePublication() return } - reloadForegroundApplication(foregroundPID) + invocationVisibilityRetryPID = current + reloadForegroundApplication(current) invocationRequiresRecords = true windowRecordsPending = true drainRefreshes() @@ -878,7 +996,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { isInitialDiscoveryComplete = didReadAllSpaces && expectedHostPIDs.allSatisfy { snapshots[$0] != nil } let scansAreReady = isInitialDiscoveryComplete && !invocationRequiresRecords && invocationRequiredHosts.isEmpty && invocationRetryTask == nil - if scansAreReady { reconcileInvocationForeground() } + if scansAreReady { reconcileInvocationForeground(discovery.foregroundProcessIdentifier()) } let focusIssue = publishForegroundFocus() let discoveryIsReady = scansAreReady && invocationRequiredHosts.isEmpty if discoveryIsReady { retryForegroundDiscoveryIfNeeded(focusIssue: focusIssue) } @@ -906,11 +1024,15 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let invocation = invocationGeneration let isInvocationCapture = invocationInProgress && invocationRequiresRecords let foregroundAtCapture = isInvocationCapture ? foregroundTarget()?.hostPID : nil + captureSequence += 1 + let capture = captureSequence + pendingVisibilityInvocation = isInvocationCapture ? invocation : nil allSpacesRefreshTask = Task { [weak self] in guard let self else { return } let result = await allSpacesCatalog.freshWindowRecordSnapshot(requiresNewCapture: isInvocationCapture) guard !Task.isCancelled, running, allSpacesGeneration == generation else { return } allSpacesRefreshTask = nil + pendingVisibilityInvocation = nil let oldRecords = Dictionary(grouping: allSpacesRecords, by: \.processIdentifier) let newRecords = Dictionary(grouping: result.records, by: \.processIdentifier) let changedOwners = Set(oldRecords.keys).union(newRecords.keys).filter { @@ -922,6 +1044,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { allSpacesRecords = result.records helperPIDsByHost = processMapping.helpersByHost(owningWindowsIn: allSpacesRecords) allSpacesRecordsAreFresh = result.isFresh + lastPublishedCapture = capture + if isInvocationCapture { + invocationVisibility = (invocation, capture, result.isFresh ? result.records : nil) + } if oldHelpers != helperPIDsByHost { reloadApplications() } let foregroundRetryHost = isInvocationCapture && invocation == invocationGeneration ? foregroundTarget()?.hostPID : nil diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift index 3e75b9fdc..02eac77a2 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift @@ -500,6 +500,14 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { } func testBackgroundExactFocusIgnoresVisibilityAwaitingReplacement() async throws { + try await verifyBackgroundExactFocus(refreshesVisibility: true) + } + + func testBackgroundFocusOnlyEventIgnoresStaleVisibility() async throws { + try await verifyBackgroundExactFocus(refreshesVisibility: false) + } + + private func verifyBackgroundExactFocus(refreshesVisibility: Bool) async throws { let foreground = CatalogAXAccess(number: 9, elementPID: 201) foreground.update { $0.focused = true } let initialCapture = DispatchSemaphore(value: 1) @@ -523,7 +531,11 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { try await waitUntil { catalog.isInvocationReady } foreground.update { $0.number = 8 } - catalog.refresh() + if refreshesVisibility { + catalog.refresh() + } else { + catalog.invalidate(processIdentifiers: [42], windowRecords: false, focusChanged: true) + } try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 && $0.windowElement != nil } } @@ -762,19 +774,9 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { let app = CatalogAXAccess(number: 7, elementPID: 201, secondaryWindowNumber: 8) let firstAXStarted = DispatchSemaphore(value: 0) let releaseFirstAX = DispatchSemaphore(value: 0) - let discoveryRead = hasPriorSnapshot ? 2 : 1 app.update { $0.focused = true $0.includesSecondaryWindow = false - $0.beforeRead = { [weak app] in - if !hasPriorSnapshot, app?.read({ $0.reads }) == 1 { - firstAXStarted.signal() - _ = releaseFirstAX.wait(timeout: .now() + 1) - } - app?.update { state in - if state.reads > discoveryRead { state.includesSecondaryWindow = true } - } - } } let initialCapture = DispatchSemaphore(value: 1) let captureStarted = DispatchSemaphore(value: 0) @@ -809,6 +811,19 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { defer { initialCapture.signal(); releaseCapture.signal(); releaseFirstAX.signal(); catalog.stop() } catalog.start() try await waitUntil { catalog.isInvocationReady } + // Startup can already have reconciled an AX read with WindowServer. + let discoveryRead = app.read { $0.reads } + 1 + app.update { + $0.beforeRead = { [weak app] in + if !hasPriorSnapshot, app?.read({ $0.reads }) == discoveryRead { + firstAXStarted.signal() + _ = releaseFirstAX.wait(timeout: .now() + 1) + } + app?.update { state in + if state.reads > discoveryRead { state.includesSecondaryWindow = true } + } + } + } var windowsAtReadiness: [CGWindowID]? catalog.onChange = { [weak catalog] in @@ -987,6 +1002,227 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(session.selected?.windowNumber, 7) } + func testCancelledInvocationKeepsConfirmedForegroundHistory() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + launched.update { $0.focused = true } + let next = CatalogAXAccess(number: 9, elementPID: 203) + next.update { $0.focused = true } + let scanStarted = DispatchSemaphore(value: 0) + let releaseScan = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + var didLaunch = false + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: next + } + }, allSpacesCatalog: .init(windowRecordProvider: { [] }), + discovery: .init(applications: { + let pids: [pid_t] = didLaunch ? [42, 43, 44] : [42, 44] + return pids.map { .init(processIdentifier: $0, localizedName: "Fixture \($0)") } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseScan.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + launched.update { + $0.beforeRead = { + scanStarted.signal() + _ = releaseScan.wait(timeout: .now() + 2) + } + } + didLaunch = true + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { scanStarted.wait(timeout: .now()) == .success } + catalog.cancelInvocation() + launched.update { $0.beforeRead = nil } + releaseScan.signal() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 } } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 8) + + foregroundPID = 44 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [9, 8, 7]) + var session = WindowSwitcherSession(entries: entries, selectedID: catalog.focusedWindowID, + isPersistent: false, originalWindowID: catalog.focusedWindowID) + session.advance(1) + XCTAssertEqual(session.selected?.windowNumber, 8) + } + + func testRoutineRefreshDoesNotRestoreOffscreenFocus() async throws { + try await verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: false) + } + + func testCancelledFocusStillUsesItsVisibilityAfterQueuedRefresh() async throws { + try await verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: true) + } + + func testCoalescedFocusEventUsesFreshVisibilityFromRoutineRefresh() async throws { + try await verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: false, coalescesFocusChange: true) + } + + func testNewVisibilityCanRejectFocusFromCancelledInvocation() async throws { + try await verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: true, wasOnscreenAtInvocation: true) + } + + private func verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: Bool, coalescesFocusChange: Bool = false, + wasOnscreenAtInvocation: Bool = false) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) + launched.update { + $0.focused = true + $0.includesSecondaryWindow = false + } + let holdCapture = DispatchSemaphore(value: 0) + let invocationCaptureStarted = DispatchSemaphore(value: 0) + let releaseCapture = DispatchSemaphore(value: 0) + let showBackgroundCapture = DispatchSemaphore(value: 0) + let axStarted = DispatchSemaphore(value: 0) + let holdFirstAX = DispatchSemaphore(value: 1) + let releaseAX = DispatchSemaphore(value: 0) + let releaseFollowupAX = DispatchSemaphore(value: 0) + let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + let background = showBackgroundCapture.wait(timeout: .now()) == .success + if holdCapture.wait(timeout: .now()) == .success { + invocationCaptureStarted.signal() + _ = releaseCapture.wait(timeout: .now() + 2) + } + let reportedWindowIsOnscreen = wasOnscreenAtInvocation && !background + return [.init(windowNumber: 7, processIdentifier: 42, title: "Previous", isOnScreen: !background, + bounds: bounds, hasSpace: true, isOnActiveSpace: !background), + .init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: reportedWindowIsOnscreen, + bounds: bounds, hasSpace: true, isOnActiveSpace: reportedWindowIsOnscreen), + .init(windowNumber: 9, processIdentifier: 43, title: "Launched", isOnScreen: !reportedWindowIsOnscreen, + bounds: bounds, hasSpace: true, isOnActiveSpace: !reportedWindowIsOnscreen)] + }), discovery: .init(applications: { + let pids: [pid_t] = foregroundPID == 43 ? [42, 43] : [42] + return pids.map { .init(processIdentifier: $0, localizedName: "Fixture \($0)") } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { + catalog.stop() + releaseCapture.signal() + releaseAX.signal() + releaseFollowupAX.signal() + holdFirstAX.signal() + } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + let holdFocusScan = { + launched.update { + $0.beforeRead = { + if holdFirstAX.wait(timeout: .now()) == .success { + axStarted.signal() + _ = releaseAX.wait(timeout: .now() + 2) + } else { + _ = releaseFollowupAX.wait(timeout: .now() + 2) + } + } + } + } + foregroundPID = 43 + if cancelsInvocation { + holdCapture.signal() + holdFocusScan() + } + catalog.prepareForInvocation() + if cancelsInvocation { + try await waitUntil { invocationCaptureStarted.wait(timeout: .now()) == .success } + try await waitUntil { axStarted.wait(timeout: .now()) == .success } + showBackgroundCapture.signal() + catalog.invalidate(processIdentifiers: [], windowRecords: true) + catalog.cancelInvocation() + releaseCapture.signal() + } else { + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 7) + holdFocusScan() + showBackgroundCapture.signal() + if coalescesFocusChange { + catalog.invalidate(processIdentifiers: [43], windowRecords: false, focusChanged: true) + } + catalog.refresh() + try await waitUntil { axStarted.wait(timeout: .now()) == .success } + } + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 7 && $0.isOnOtherDesktop } + } + launched.update { + $0.includesSecondaryWindow = true + } + releaseAX.signal() + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 9 && $0.windowElement != nil } + } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 7) + } + + func testForegroundHandoffWhileWaitingForRetryUsesNewForeground() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 11) + launched.update { + $0.focusesSecondaryWindow = true + $0.includesSecondaryWindow = false + } + let next = CatalogAXAccess(number: 9, elementPID: 203) + let releaseLaunchScan = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + var didLaunch = false + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: next + } + }, allSpacesCatalog: .init(windowRecordProvider: { [] }), + discovery: .init(applications: { + let pids: [pid_t] = didLaunch ? [42, 43, 44] : [42, 44] + return pids.map { + .init(processIdentifier: $0, localizedName: "Fixture \($0)", isFinishedLaunching: $0 != 43) + } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseLaunchScan.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + let initialReads = next.read { $0.reads } + + launched.update { $0.beforeRead = { _ = releaseLaunchScan.wait(timeout: .now() + 2) } } + next.update { $0.number = 10 } + catalog.onChange = { [weak catalog] in + guard let catalog else { return } + let numbers = catalog.entries(sortMode: .fixed).compactMap(\.windowNumber) + if numbers.contains(10) { releaseLaunchScan.signal() } + if foregroundPID == 43, numbers.contains(8), !catalog.isInvocationReady { + foregroundPID = 44 + next.update { $0.focused = true } + } + } + didLaunch = true + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(foregroundPID, 44) + XCTAssertEqual(entries.first?.windowNumber, 10) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(next.read { $0.reads }, initialReads + 2) + XCTAssertEqual(launched.read { $0.reads }, 1) + } + func testForegroundHandoffAndIncompleteAXShareOneRetry() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } @@ -1236,6 +1472,61 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) } + func testActiveHelperExactFocusWinsAfterHostFocusIsContradicted() async throws { + try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: true) + } + + func testVisibleHelperPreventsInferringHostFocus() async throws { + try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: false) + } + + private func verifyForegroundHostWithActiveHelper(hostIsOffscreen: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let host = CatalogAXAccess(number: 8, elementPID: 202) + host.update { $0.focused = hostIsOffscreen } + let helper = CatalogAXAccess(number: 9, elementPID: 203) + helper.update { $0.focused = hostIsOffscreen } + var foregroundPID: pid_t = 42 + let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: host + default: helper + } + }, allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Host", isOnScreen: !hostIsOffscreen, + bounds: bounds, hasSpace: true, isOnActiveSpace: !hostIsOffscreen), + .init(windowNumber: 9, processIdentifier: 44, title: "Helper", isOnScreen: true, + bounds: bounds, hasSpace: true, isOnActiveSpace: true)] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application(processIdentifier: 42, localizedName: "Previous") + guard foregroundPID == 43 else { return [prior] } + return [prior, + .init(processIdentifier: 43, bundleIdentifier: "host", bundlePath: "/Host.app", localizedName: "Host"), + .init(processIdentifier: 44, bundleIdentifier: "host.helper", bundlePath: "/Host.app/Helper.app", + localizedName: "Helper", isRegular: false, isActive: true)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(Set(entries.compactMap(\.windowNumber)), [7, 8, 9]) + XCTAssertEqual(entries.first?.windowNumber, hostIsOffscreen ? 9 : 7) + if hostIsOffscreen { + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(entries.first?.axWorkerPID, 44) + } else { + XCTAssertNil(catalog.focusedWindowID) + } + } + func testUnlistedHostFocusRetriesBeforeConsideringCachedHelperFocus() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } From e4afbb2cc464b87fa71fa9552018d253cdb02808 Mon Sep 17 00:00:00 2001 From: xcv58 Date: Wed, 25 Nov 2026 22:44:41 -0500 Subject: [PATCH 5/5] fix(window-switcher): bound foreground discovery to one check --- .../Sources/WindowSwitcherAppCatalog.swift | 448 ++++++++++------- .../Sources/WindowSwitcherProcessWorker.swift | 8 +- .../Tests/WindowSwitcherAppCatalogTests.swift | 450 ++++++++++++++++-- 3 files changed, 693 insertions(+), 213 deletions(-) diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift index b2a0660dd..4e7cee227 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift @@ -79,16 +79,41 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let workerPID: pid_t } + private struct ForegroundCheck { + enum Phase: Equatable { + case initialCapture, initialScan + case retryDelay, retryCapture, retryQueued(pid_t), retryScan + + var needsCapture: Bool { self == .initialCapture || self == .retryCapture } + var canFinish: Bool { self == .initialScan || self == .retryScan } + + var queuedHost: pid_t? { + if case let .retryQueued(pid) = self { return pid } + return nil + } + } + + var pid: pid_t? + var phase = Phase.initialCapture + var focusRead: (target: ForegroundTarget, startedAt: ContinuousClock.Instant)? + var conflict: FocusConflict? + var deferredRefreshes: Set = [] + } + private enum FocusIssue: Equatable { - case unmatchedAXFocus, incompleteAX, offscreenAX + case unmatchedAXFocus, incompleteAX, offscreenAX, excludedAXFocus - var requiresAXConfirmation: Bool { self != .offscreenAX } + var requiresAXConfirmation: Bool { self == .unmatchedAXFocus || self == .incompleteAX } } private enum FocusVisibility { case onscreen, offscreen } + private enum LaunchVisibilityCheck { + case none, initial, retry + } + private struct FocusObservation { let workerPID: pid_t let id: String? @@ -96,6 +121,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let unavailable: Bool let reportedFocusedWindow: Bool let reportedFocusWasExcluded: Bool + let readStartedAt: ContinuousClock.Instant? var canInfer: Bool { !unavailable && !reportedFocusedWindow } init(workerPID: pid_t, scan: WindowSwitcherScan) { @@ -105,9 +131,27 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { unavailable = scan.unavailable reportedFocusedWindow = scan.reportedFocusedWindow reportedFocusWasExcluded = scan.reportedFocusWasExcluded + readStartedAt = scan.focusReadStartedAt } } + private struct FocusChange { + let receivedAt: ContinuousClock.Instant + let capture: Int + } + + private struct FocusConflict { + let id: String + let capture: Int + } + + private struct InvocationVisibility { + let generation: UUID + let foregroundPID: pid_t? + let capture: Int + let records: [WindowSwitcherWindowRecord]? + } + private struct PendingFocus { let target: ForegroundTarget let foregroundAtScanStart: ForegroundTarget? @@ -143,7 +187,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var activeScanCount = 0 private var dirtyHosts: Set = [] private var pendingInvalidations: Set = [] - private var focusChangesAfterCapture: [pid_t: Int] = [:] + private var focusChanges: [pid_t: FocusChange] = [:] private var pendingRecordsInvalidation = false private var applicationsByPID: [pid_t: Application] = [:] private var mappingCandidates: [WindowSwitcherProcessMapping.Candidate] = [] @@ -163,17 +207,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var sessionInactive = false private var suspended: Bool { sleeping || sessionInactive } private var invocationGeneration = UUID() - private var invocationInProgress = false - private var invocationForegroundPID: pid_t? - private var contradictedInvocationFocusID: String? - private var cancelledFocus: (generation: UUID, target: ForegroundTarget, contradictedID: String?)? - private var invocationRequiredHosts: Set = [] - private var queuedInvocationRetryHost: pid_t? - private var deferredForegroundRefreshes: Set = [] - private var invocationRequiresRecords = false - private var invocationCanRetryForegroundDiscovery = false - private var invocationRetryTask: Task? - private var invocationVisibilityRetryPID: pid_t? + private var foregroundCheck: ForegroundCheck? + private var foregroundRetryDelay: Task? + private var cancelledFocus: (generation: UUID, target: ForegroundTarget, conflict: FocusConflict?)? + private var requiredCatalogScans: Set = [] private let allSpacesCatalog: WindowSwitcherWindowRecords private let discovery: DiscoveryEnvironment private var publication = WindowSwitcherPublishedWindows() @@ -184,7 +221,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var pendingVisibilityInvocation: UUID? private var captureSequence = 0 private var lastPublishedCapture = 0 - private var invocationVisibility: (generation: UUID, capture: Int, records: [WindowSwitcherWindowRecord]?)? + private var invocationVisibility: InvocationVisibility? private var allSpacesGeneration = UUID() private var didReadAllSpaces = false @@ -290,7 +327,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { helperPIDsByHost.removeAll() dirtyHosts.removeAll() pendingInvalidations.removeAll() - focusChangesAfterCapture.removeAll() + focusChanges.removeAll() pendingRecordsInvalidation = false timer?.invalidate(); timer = nil observers.forEach(notificationCenter.removeObserver); observers.removeAll() @@ -308,7 +345,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let hosts = Set(processIdentifiers.map { processMapping.host(for: $0) }).intersection(expectedHostPIDs) pendingInvalidations.formUnion(hosts) if focusChanged { - for host in hosts { focusChangesAfterCapture[host] = captureSequence } + let change = FocusChange(receivedAt: .now, capture: captureSequence) + for pid in processIdentifiers where hosts.contains(processMapping.host(for: pid)) { + focusChanges[pid] = change + } } pendingRecordsInvalidation = pendingRecordsInvalidation || windowRecords if processIdentifiers.contains(ProcessInfo.processInfo.processIdentifier) { markPublicationDirty() } @@ -353,17 +393,15 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { allSpacesRefreshTask = nil pendingVisibilityInvocation = nil invocationVisibility = nil - invocationInProgress = true - invocationForegroundPID = discovery.foregroundProcessIdentifier() + let foregroundPID = discovery.foregroundProcessIdentifier() + foregroundCheck = ForegroundCheck(pid: foregroundPID) isInvocationReady = false pendingFocus.removeAll() inferredFocusWorkerLifetime = nil publication.recency.clearInference() - reloadForegroundApplication(invocationForegroundPID) + reloadForegroundApplication(foregroundPID) applyInvalidations() - invocationRequiredHosts = expectedHostPIDs - invocationRequiresRecords = true - invocationCanRetryForegroundDiscovery = true + requiredCatalogScans = expectedHostPIDs dirtyHosts.formUnion(expectedHostPIDs) windowRecordsPending = true markPublicationDirty() @@ -371,12 +409,11 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } func cancelInvocation() { - guard invocationInProgress else { return } + guard let check = foregroundCheck else { return } let target = foregroundTarget() let capturedFocus = target.flatMap { pendingFocus[$0.hostPID] } let generation = invocationGeneration - let contradictedID = contradictedInvocationFocusID - let canPreserveFocus = target?.workerPID == invocationForegroundPID + let canPreserveFocus = target?.workerPID == check.pid resetInvocation() pendingFocus.removeAll() publication.recency.clearInference() @@ -384,7 +421,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // Cancelling the chooser still allows a genuine foreground observation // to enter history if the app and its focus scan have not changed. if let target, canPreserveFocus { - cancelledFocus = (generation, target, contradictedID) + cancelledFocus = (generation, target, check.conflict) if var capturedFocus, capturedFocus.target == target, capturedFocus.foregroundAtScanStart == target { capturedFocus.confirmedOnly = true pendingFocus[target.hostPID] = capturedFocus @@ -395,20 +432,13 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } private func resetInvocation() { - pendingInvalidations.formUnion(deferredForegroundRefreshes) - deferredForegroundRefreshes.removeAll() + if let check = foregroundCheck { pendingInvalidations.formUnion(check.deferredRefreshes) } + foregroundCheck = nil + foregroundRetryDelay?.cancel() + foregroundRetryDelay = nil invocationGeneration = UUID() - invocationInProgress = false - invocationForegroundPID = nil - contradictedInvocationFocusID = nil cancelledFocus = nil - invocationRequiredHosts.removeAll() - queuedInvocationRetryHost = nil - invocationRequiresRecords = false - invocationCanRetryForegroundDiscovery = false - invocationRetryTask?.cancel() - invocationRetryTask = nil - invocationVisibilityRetryPID = nil + requiredCatalogScans.removeAll() } private func reloadForegroundApplication(_ pid: pid_t?) { @@ -448,7 +478,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { scannedHelperPIDs.removeValue(forKey: oldMapping.host(for: pid)) excludedWindowNumbersByHost.removeValue(forKey: pid) pendingFocus.removeValue(forKey: oldMapping.host(for: pid)) - focusChangesAfterCapture.removeValue(forKey: oldMapping.host(for: pid)) + focusChanges.removeValue(forKey: pid) removedProcesses.insert(pid) dirtyHosts.insert(oldMapping.host(for: pid)) markPublicationDirty() @@ -463,10 +493,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { markPublicationDirty() } dirtyHosts.formIntersection(expectedHostPIDs) - invocationRequiredHosts.formIntersection(expectedHostPIDs) - deferredForegroundRefreshes.formIntersection(expectedHostPIDs) - if let queuedInvocationRetryHost, !expectedHostPIDs.contains(queuedInvocationRetryHost) { - self.queuedInvocationRetryHost = nil + requiredCatalogScans.formIntersection(expectedHostPIDs) + foregroundCheck?.deferredRefreshes.formIntersection(expectedHostPIDs) + if let host = foregroundCheck?.phase.queuedHost, !expectedHostPIDs.contains(host) { + foregroundCheck?.phase = .retryScan } dirtyHosts.formUnion(expectedHostPIDs.filter { snapshots[$0] == nil }) } @@ -482,12 +512,17 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { guard !discovery.isDragging() else { scheduleRefresh(); return } // Finish publishing the invocation's visibility snapshot before // servicing any refreshes queued behind it. - if windowRecordsPending, !invocationInProgress || invocationRequiresRecords { + if windowRecordsPending, foregroundCheck?.phase.needsCapture != false { refreshAllSpaces() } let foregroundAtScanStart = foregroundTarget() let foregroundHostPID = foregroundAtScanStart?.hostPID - let hostAwaitingVisibility = invocationVisibilityRetryPID.flatMap { foregroundTarget(for: $0)?.hostPID } + let hostAwaitingVisibility: pid_t? + if let check = foregroundCheck, check.phase == .retryDelay || check.phase == .retryCapture { + hostAwaitingVisibility = check.pid.flatMap { foregroundTarget(for: $0)?.hostPID } + } else { + hostAwaitingVisibility = nil + } let pids = dirtyHosts.sorted { let lhsActive = $0 == foregroundHostPID let rhsActive = $1 == foregroundHostPID @@ -499,16 +534,15 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let application = applicationsByPID[pid] else { continue } let worker = ensureWorker(pid: pid, launchDate: application.launchDate, applicationLifetime: application.lifetime) dirtyHosts.remove(pid) - deferredForegroundRefreshes.remove(pid) - if queuedInvocationRetryHost == pid { - queuedInvocationRetryHost = nil + foregroundCheck?.deferredRefreshes.remove(pid) + if foregroundCheck?.phase.queuedHost == pid { + foregroundCheck?.phase = .retryScan pendingInvalidations.remove(pid) } inFlight.insert(pid) activeScanCount += 1 let app = application.withPresentation() let invocation = invocationGeneration - let focusChangeAfterCapture = focusChangesAfterCapture.removeValue(forKey: pid) Task { [weak self] in defer { if let self { @@ -554,14 +588,22 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { scannedHelperPIDs[pid] = Set(focusObservations.keys).subtracting([pid]) excludedWindowNumbersByHost[pid] = excludedWindowNumbers if previous != entries { markPublicationDirty() } - let isCurrentScan = invocation == invocationGeneration && queuedInvocationRetryHost != pid - if isCurrentScan { - invocationRequiredHosts.remove(pid) - } + let isCurrentScan = invocation == invocationGeneration && foregroundCheck?.phase.queuedHost != pid + if isCurrentScan { requiredCatalogScans.remove(pid) } if let target = foregroundTarget(), target.hostPID == pid { let wasCancelled = cancelledFocus?.generation == invocation && cancelledFocus?.target == target && foregroundAtScanStart == target if isCurrentScan || wasCancelled { + let focusChange = focusChanges[target.workerPID] + let focusRead = focusObservations[target.workerPID]?.readStartedAt + // Compare the event with the focus read, including events + // delivered while window enumeration was in progress. + let focusChangeAfterCapture: Int? + if let focusChange, let focusRead, focusChange.receivedAt <= focusRead { + focusChangeAfterCapture = focusChange.capture + } else { + focusChangeAfterCapture = nil + } pendingFocus[pid] = PendingFocus(target: target, foregroundAtScanStart: foregroundAtScanStart, observations: focusObservations, focusChangeAfterCapture: focusChangeAfterCapture, confirmedOnly: wasCancelled) @@ -652,6 +694,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { publication.update(snapshots: snapshots, records: allSpacesRecords, recordsAreFresh: allSpacesRecordsAreFresh, localEntries: hostWindows.entries(), helperProcessIdentifiers: helperPIDsByHost, displayContext: { self.displayContext(for: $0) }) + recordLocalFocus() + } + + private func recordLocalFocus() { if NSApp.isActive, let focusedID = hostWindows.focusedID { publication.recency.observeForeground(entries: publication.entries.filter { $0.processIdentifier == ProcessInfo.processInfo.processIdentifier @@ -660,7 +706,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } private func inferredForegroundWindowID(in entries: [WindowSwitcherAppEntry], - target: ForegroundTarget) -> String? { + target: ForegroundTarget, requiresOnscreen: Bool) -> String? { guard allSpacesRecordsAreFresh, !entries.isEmpty else { return nil } let onscreenWindowNumbers = foregroundOnscreenWindowNumbers(target: target) guard !hasUnresolvedOnscreenWindow(onscreenWindowNumbers, in: entries) else { return nil } @@ -681,7 +727,8 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let likely = candidates.count == 1 ? candidates : candidates.filter(\.onscreen) // A helper can make the host ambiguous without being inferred as the // focused window when Workspace identifies the host. - guard likely.count == 1, let candidate = likely.first, candidate.belongsToForeground else { return nil } + guard likely.count == 1, let candidate = likely.first, candidate.belongsToForeground, + !requiresOnscreen || candidate.onscreen else { return nil } return candidate.id } @@ -721,7 +768,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { records: [WindowSwitcherWindowRecord]? = nil) -> WindowSwitcherWindowRecord? { let records = records ?? allSpacesRecords if let number = entry.windowNumber { - return records.first { $0.windowNumber == number } + return records.first { $0.windowNumber == number && $0.processIdentifier == entry.owningProcessIdentifier } } guard entry.windowElement != nil else { return nil } // Unique geometry can inform visibility only. Preserve exact IDs for @@ -760,18 +807,32 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } private func focusVisibility(of entry: WindowSwitcherAppEntry, in entries: [WindowSwitcherAppEntry], - target: ForegroundTarget, records: [WindowSwitcherWindowRecord]) -> FocusVisibility? { - guard let record = visibilityRecord(for: entry, among: entries, records: records) else { return nil } - if record.isOnScreen == true && record.isOnActiveSpace != false { return .onscreen } - if record.isOnScreen == false || record.isOnActiveSpace == false, - !foregroundOnscreenWindowNumbers(target: target, records: records).isEmpty { return .offscreen } - return nil + target: ForegroundTarget, records: [WindowSwitcherWindowRecord], + launchCheck: LaunchVisibilityCheck) -> FocusVisibility? { + let record = visibilityRecord(for: entry, among: entries, records: records) + if record?.isOnScreen == true && record?.isOnActiveSpace != false { return .onscreen } + if launchCheck != .none, record?.isOnActiveSpace == false, !entry.isMinimized { return .offscreen } + let missingLaunchWindow = launchCheck == .initial && record == nil && !entry.isMinimized + guard record?.isOnScreen == false || record?.isOnActiveSpace == false || missingLaunchWindow else { return nil } + let onscreen = foregroundOnscreenWindowNumbers(target: target, records: records) + guard !onscreen.isEmpty else { return nil } + if missingLaunchWindow, entry.windowNumber == nil { + // With no window number, a different AX-backed visible row + // provides the evidence needed to question the launch focus. + guard entries.contains(where: { other in + other.id != entry.id && other.windowElement != nil && isUsableWindow(other) + && other.windowNumber.map(onscreen.contains) == true + && !Self.sameBounds(entry.bounds, other.bounds) + }) else { return nil } + } + return .offscreen } - private func publishForegroundFocus() -> FocusIssue? { - if invocationInProgress, discovery.foregroundProcessIdentifier() != invocationForegroundPID { return nil } + private func publishForegroundFocus(for foregroundPID: pid_t?) -> FocusIssue? { + let check = foregroundCheck + if let check, foregroundPID != check.pid { return nil } guard inferredFocusWorkerLifetime != nil || !pendingFocus.isEmpty else { return nil } - let target = foregroundTarget() + let target = foregroundPID.flatMap { foregroundTarget(for: $0) } let workerLifetime = target.flatMap { workers[$0.workerPID]?.lifetime } if let inferredFocusWorkerLifetime, inferredFocusWorkerLifetime != workerLifetime { self.inferredFocusWorkerLifetime = nil @@ -795,22 +856,25 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // AX can finish before the current WindowServer read. Keep the focus // observation for publication when the matching visibility is available. let pairedInvocation = pending.confirmedOnly ? cancelledFocus?.generation - : invocationInProgress ? invocationGeneration : nil - let awaitingInvocationVisibility = invocationInProgress && invocationRequiresRecords + : check != nil ? invocationGeneration : nil + let awaitingInvocationVisibility = check?.phase.needsCapture == true || (pairedInvocation != nil && pairedInvocation == pendingVisibilityInvocation) - let visibilityPending = invocationInProgress - ? invocationRequiresRecords || !invocationRequiredHosts.isEmpty + let visibilityPending = check != nil + ? awaitingInvocationVisibility || !requiredCatalogScans.isEmpty : windowRecordsPending || allSpacesRefreshTask != nil var issue: FocusIssue? - if exactID == nil, !focus.reportedFocusWasExcluded { - if focus.reportedFocusedWindow { + if exactID == nil { + if focus.reportedFocusWasExcluded { + issue = .excludedAXFocus + } else if focus.reportedFocusedWindow { issue = .unmatchedAXFocus - } else if invocationInProgress, focus.unavailable { + } else if check != nil, focus.unavailable { issue = .incompleteAX } } if awaitingInvocationVisibility - || (!pending.confirmedOnly && visibilityPending && exactID == nil && (focus.canInfer || issue != nil)) { + || (!pending.confirmedOnly && visibilityPending && exactID == nil + && (focus.canInfer || issue?.requiresAXConfirmation == true)) { pendingFocus[target.hostPID] = pending publication.recency.clearInference() inferredFocusWorkerLifetime = nil @@ -818,28 +882,45 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } // A focus event can use a capture started after the event, including // when another invalidation requests that capture in the same refresh. - let pairedCapture = invocationVisibility.flatMap { $0.generation == pairedInvocation ? $0 : nil } - let backgroundFocusCanUseCapture = pairedInvocation == nil && !visibilityPending - && pending.focusChangeAfterCapture.map { lastPublishedCapture > $0 } != false - let cancelledFocusHasNewerCapture = pending.confirmedOnly + let pairedCapture = invocationVisibility.flatMap { capture in + capture.generation == pairedInvocation && capture.foregroundPID == target.workerPID ? capture : nil + } + let latestCaptureFollowsFocusChange = pending.focusChangeAfterCapture.map { lastPublishedCapture > $0 } != false + let backgroundFocusCanUseCapture = pairedInvocation == nil && !visibilityPending && latestCaptureFollowsFocusChange + let cancelledFocusHasNewerCapture = pending.confirmedOnly && latestCaptureFollowsFocusChange && pairedCapture.map { lastPublishedCapture > $0.capture } == true let latestRecords = allSpacesRecordsAreFresh && (backgroundFocusCanUseCapture || cancelledFocusHasNewerCapture) ? allSpacesRecords : nil - let pairedRecords = pairedCapture?.records + let pairedRecords = pairedCapture.flatMap { capture in + pending.focusChangeAfterCapture.map { capture.capture > $0 } != false ? capture.records : nil + } var helperVerificationRecords = pairedRecords + let launching = applicationsByPID[target.workerPID].map(isLaunching) == true if let exactID, let entry = entries.first(where: { $0.id == exactID }) { // When cancelled, prefer a newer decisive observation and fall // back to the paired capture if the new snapshot is inconclusive. - let latestVisibility = latestRecords.flatMap { focusVisibility(of: entry, in: entries, target: target, records: $0) } - let visibility = latestVisibility - ?? pairedRecords.flatMap { focusVisibility(of: entry, in: entries, target: target, records: $0) } - if cancelledFocusHasNewerCapture, latestVisibility != nil { helperVerificationRecords = latestRecords } - let contradictedID = pending.confirmedOnly ? cancelledFocus?.contradictedID : contradictedInvocationFocusID - let repeatsUnverifiedFocus = pairedInvocation != nil && exactID == contradictedID - && visibility != .onscreen + let launchCheck: LaunchVisibilityCheck + if !launching || pairedInvocation == nil { + launchCheck = .none + } else { + launchCheck = check?.phase == .initialScan || pending.confirmedOnly ? .initial : .retry + } + let latestVisibility = latestRecords.flatMap { + focusVisibility(of: entry, in: entries, target: target, records: $0, launchCheck: launchCheck) + } + let visibility = latestVisibility ?? pairedRecords.flatMap { + focusVisibility(of: entry, in: entries, target: target, records: $0, launchCheck: launchCheck) + } + if latestVisibility != nil { helperVerificationRecords = latestRecords } + let conflict = pending.confirmedOnly ? cancelledFocus?.conflict : check?.conflict + let repeatsUnverifiedFocus = pairedInvocation != nil && conflict.map { conflict in + exactID == conflict.id && pending.focusChangeAfterCapture.map { conflict.capture > $0 } != false + } == true && visibility != .onscreen if visibility == .offscreen || repeatsUnverifiedFocus { issue = .offscreenAX - if invocationInProgress { contradictedInvocationFocusID = exactID } + if visibility == .offscreen, let pairedCapture { + foregroundCheck?.conflict = FocusConflict(id: exactID, capture: pairedCapture.capture) + } } } if issue == .offscreenAX { @@ -848,14 +929,15 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let helperIDs = Set(activeHelperFocusIDs(in: entries, pending: pending)) let verifiedHelpers = entries.filter { $0.id != exactID && helperIDs.contains($0.id) && $0.windowElement != nil && isUsableWindow($0) - && $0.windowNumber.map(onscreen.contains) == true + && visibilityRecord(for: $0, among: entries, records: helperVerificationRecords) + .map { onscreen.contains($0.windowNumber) } == true } if verifiedHelpers.count == 1 { exactID = verifiedHelpers.first?.id issue = nil } } - if issue == .offscreenAX, invocationInProgress, !invocationRequiredHosts.isEmpty { + if issue == .offscreenAX, check != nil, !requiredCatalogScans.isEmpty { pendingFocus[target.hostPID] = pending return nil } @@ -866,43 +948,46 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } return nil } - let inferredID = exactID == nil && focus.canInfer - ? inferredForegroundWindowID(in: entries, target: target) : nil + foregroundCheck?.focusRead = focus.readStartedAt.map { (target, $0) } + let canInferFromVisibility = check != nil ? pairedRecords != nil : latestCaptureFollowsFocusChange + let inferredID = exactID == nil && focus.canInfer && canInferFromVisibility + ? inferredForegroundWindowID(in: entries, target: target, requiresOnscreen: check != nil && launching) : nil inferredFocusWorkerLifetime = inferredID == nil ? nil : workerLifetime publication.recency.observeForeground(entries: entries, focusedWindowID: issue == .offscreenAX ? nil : exactID, inferredWindowID: inferredID, unavailable: focus.unavailable) return issue } - private func reconcileInvocationForeground(_ current: pid_t?) { - guard invocationInProgress else { return } - guard current != invocationForegroundPID else { return } - invocationForegroundPID = current - contradictedInvocationFocusID = nil + @discardableResult + private func updateForegroundTarget(_ current: pid_t?) -> Bool { + guard let check = foregroundCheck, current != check.pid else { return false } + foregroundCheck?.pid = current + foregroundCheck?.focusRead = nil + foregroundCheck?.conflict = nil publication.recency.clearFocus() inferredFocusWorkerLifetime = nil + let observedFocus = current.flatMap { foregroundTarget(for: $0) }.flatMap { target in + pendingFocus[target.hostPID].flatMap { pending in + pending.target == target && pending.foregroundAtScanStart == target ? pending : nil + } + } pendingFocus.removeAll() - // A background scan can read the app's previous key window. Resolve - // focus while it is foreground, once per invocation. - guard invocationCanRetryForegroundDiscovery, let current, - current != ProcessInfo.processInfo.processIdentifier else { return } - invocationCanRetryForegroundDiscovery = false - scheduleForegroundRetry(for: current) - } - - private func queueInvocationScan(for pid: pid_t) { - queuedInvocationRetryHost = pid - invocationRequiredHosts.insert(pid) - dirtyHosts.insert(pid) - pendingFocus.removeValue(forKey: pid) + if current == ProcessInfo.processInfo.processIdentifier { + recordLocalFocus() + return false + } + if let observedFocus { + pendingFocus[observedFocus.target.hostPID] = observedFocus + } + // An observation started in the background can report the app's + // previous key window. A handoff needs a read started in foreground. + return current != nil + && observedFocus.flatMap { $0.observations[$0.target.workerPID]?.id } == nil } - private func retryForegroundDiscoveryIfNeeded(focusIssue: FocusIssue?) { - guard invocationCanRetryForegroundDiscovery else { return } - invocationCanRetryForegroundDiscovery = false - guard let foregroundPID = discovery.foregroundProcessIdentifier() else { return } + private func needsForegroundRetry(for foregroundPID: pid_t, focusIssue: FocusIssue?) -> Bool { guard let target = foregroundTarget(for: foregroundPID) else { - guard foregroundPID != ProcessInfo.processInfo.processIdentifier else { return } + guard foregroundPID != ProcessInfo.processInfo.processIdentifier else { return false } let replacesPreviousFocus = publication.recency.focusedID != nil publication.recency.clearFocus() let visible = allSpacesRecordsAreFresh && allSpacesRecords.contains { @@ -911,23 +996,22 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let app = applicationsByPID[foregroundPID] // A newly foreground accessory can become regular during launch. // After its first attempt the old app no longer owns the anchor. - if visible || app.map(isLaunching) != false || (replacesPreviousFocus && app?.isRegular == false) { - scheduleForegroundRetry(for: foregroundPID) - } - return + return visible || app.map(isLaunching) != false || (replacesPreviousFocus && app?.isRegular == false) } + // A focus event can arrive after the foreground read while discovery + // is still waiting on another app. Resolve it before opening the chooser. + if let read = foregroundCheck?.focusRead, read.target == target, + let change = focusChanges[target.workerPID], change.receivedAt > read.startedAt { return true } + let entries = publication.entries.filter { $0.processIdentifier == target.hostPID } let launching = applicationsByPID[target.workerPID].map(isLaunching) == true - // Launch discovery can be incomplete before either source has a - // reliable answer. Confirm focus on the single retry. - if launching, - focusIssue == .unmatchedAXFocus || focusIssue == .incompleteAX { - scheduleForegroundRetry(for: foregroundPID) - return + let hasUsableFocus = entries.contains { $0.id == publication.recency.focusedID && isUsableWindow($0) } + // A launch may have no confirmed focus even after both reads finish. + // Give it the same one retry, unless AX identified an excluded window. + if launching, focusIssue?.requiresAXConfirmation == true + || (focusIssue != .excludedAXFocus && !hasUsableFocus) { + return true } - // A launch can put a window onscreen before the app publishes its AX - // window list. Retry the scan while keeping the normal listing rules. - guard allSpacesRecordsAreFresh else { return } - let entries = publication.entries.filter { $0.processIdentifier == target.hostPID } + guard allSpacesRecordsAreFresh else { return false } let onscreen = foregroundOnscreenWindowNumbers(target: target) let hasConfirmedOnscreenFocus = entries.contains { entry in entry.id == publication.recency.confirmedFocusID @@ -938,40 +1022,81 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { requiresAXConfirmation: focusIssue?.requiresAXConfirmation == true) let missingHelper = !(helperPIDsByHost[target.hostPID] ?? []) .isSubset(of: scannedHelperPIDs[target.hostPID] ?? []) - // LaunchServices can report a foreground app before its window - // appears in either source. Recapture visibility in that case too. - let awaitingFirstWindow = launching && onscreen.isEmpty - && !entries.contains { $0.id == publication.recency.focusedID && isUsableWindow($0) } - if missingAX || awaitingFirstWindow || focusIssue == .offscreenAX || missingHelper { - scheduleForegroundRetry(for: foregroundPID) - } + return missingAX || focusIssue == .offscreenAX || missingHelper } private func isLaunching(_ app: Application) -> Bool { !app.isFinishedLaunching || app.launchDate.map { Date().timeIntervalSince($0) < 2 } == true } - private func scheduleForegroundRetry(for foregroundPID: pid_t) { - invocationVisibilityRetryPID = foregroundPID - invocationRetryTask = Task { [weak self] in + private func startForegroundRetry() { + foregroundCheck?.phase = .retryDelay + foregroundRetryDelay = Task { [weak self] in do { try await Task.sleep(for: .milliseconds(100)) } catch { return } guard !Task.isCancelled, let self else { return } - invocationRetryTask = nil + foregroundRetryDelay = nil let current = discovery.foregroundProcessIdentifier() - reconcileInvocationForeground(current) + updateForegroundTarget(current) guard let current, current != ProcessInfo.processInfo.processIdentifier else { - invocationVisibilityRetryPID = nil + foregroundCheck?.phase = .retryScan schedulePublication() return } - invocationVisibilityRetryPID = current reloadForegroundApplication(current) - invocationRequiresRecords = true + foregroundCheck?.phase = .retryCapture windowRecordsPending = true drainRefreshes() } } + private func finishedForegroundCapture() { + guard let check = foregroundCheck else { return } + if check.phase == .initialCapture { + foregroundCheck?.phase = .initialScan + return + } + + foregroundCheck?.phase = .retryScan + let current = discovery.foregroundProcessIdentifier() + if current != check.pid { + reloadForegroundApplication(current) + updateForegroundTarget(current) + } + guard let current, let target = foregroundTarget(for: current), + current == check.pid || pendingFocus[target.hostPID]?.observations[target.workerPID]?.id == nil else { return } + foregroundCheck?.phase = .retryQueued(target.hostPID) + requiredCatalogScans.insert(target.hostPID) + dirtyHosts.insert(target.hostPID) + pendingFocus.removeValue(forKey: target.hostPID) + } + + /// Owns the chooser's readiness and the transition that spends its one retry. + /// Background scans can still publish windows and confirmed focus while it waits. + private func advanceForegroundCheck() -> Bool { + let current = discovery.foregroundProcessIdentifier() + let scansAreReady = isInitialDiscoveryComplete && requiredCatalogScans.isEmpty + && foregroundCheck?.phase.canFinish != false + let needsHandoffScan = scansAreReady && updateForegroundTarget(current) + let focusIssue = publishForegroundFocus(for: current) + guard scansAreReady, requiredCatalogScans.isEmpty else { + isInvocationReady = false + return false + } + if foregroundCheck?.phase == .initialScan, let current, + needsHandoffScan || needsForegroundRetry(for: current, focusIssue: focusIssue) { + startForegroundRetry() + isInvocationReady = false + return false + } + isInvocationReady = pendingFocus.isEmpty + guard isInvocationReady, let check = foregroundCheck else { return false } + foregroundCheck = nil + if !check.deferredRefreshes.isEmpty { + invalidate(processIdentifiers: check.deferredRefreshes, windowRecords: false) + } + return true + } + private func markPublicationDirty() { publicationDirty = true schedulePublication() @@ -994,21 +1119,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { rebuildPublication() } isInitialDiscoveryComplete = didReadAllSpaces && expectedHostPIDs.allSatisfy { snapshots[$0] != nil } - let scansAreReady = isInitialDiscoveryComplete && !invocationRequiresRecords - && invocationRequiredHosts.isEmpty && invocationRetryTask == nil - if scansAreReady { reconcileInvocationForeground(discovery.foregroundProcessIdentifier()) } - let focusIssue = publishForegroundFocus() - let discoveryIsReady = scansAreReady && invocationRequiredHosts.isEmpty - if discoveryIsReady { retryForegroundDiscoveryIfNeeded(focusIssue: focusIssue) } - isInvocationReady = discoveryIsReady && invocationRequiredHosts.isEmpty - && pendingFocus.isEmpty && invocationRetryTask == nil - let completedInvocation = invocationInProgress && isInvocationReady - if completedInvocation { - invocationInProgress = false - let deferred = deferredForegroundRefreshes - deferredForegroundRefreshes.removeAll() - if !deferred.isEmpty { invalidate(processIdentifiers: deferred, windowRecords: false) } - } + let completedInvocation = advanceForegroundCheck() if oldEntries != publication.entries || oldFocus != publication.recency.focusedID || wasComplete != isInitialDiscoveryComplete || wasReady != isInvocationReady { onChange?() @@ -1022,8 +1133,9 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { windowRecordsPending = false let generation = allSpacesGeneration let invocation = invocationGeneration - let isInvocationCapture = invocationInProgress && invocationRequiresRecords - let foregroundAtCapture = isInvocationCapture ? foregroundTarget()?.hostPID : nil + let isInvocationCapture = foregroundCheck?.phase.needsCapture == true + let foregroundPIDAtCapture = isInvocationCapture ? discovery.foregroundProcessIdentifier() : nil + let foregroundAtCapture = foregroundPIDAtCapture.flatMap { foregroundTarget(for: $0)?.hostPID } captureSequence += 1 let capture = captureSequence pendingVisibilityInvocation = isInvocationCapture ? invocation : nil @@ -1046,7 +1158,8 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { allSpacesRecordsAreFresh = result.isFresh lastPublishedCapture = capture if isInvocationCapture { - invocationVisibility = (invocation, capture, result.isFresh ? result.records : nil) + invocationVisibility = InvocationVisibility(generation: invocation, foregroundPID: foregroundPIDAtCapture, + capture: capture, records: result.isFresh ? result.records : nil) } if oldHelpers != helperPIDsByHost { reloadApplications() } let foregroundRetryHost = isInvocationCapture && invocation == invocationGeneration @@ -1062,22 +1175,15 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // A required retry covers this change. Otherwise let the // foreground host refresh after the chooser opens. if pid == foregroundRetryHost { - deferredForegroundRefreshes.insert(pid) + foregroundCheck?.deferredRefreshes.insert(pid) } else { dirtyHosts.insert(pid) } } didReadAllSpaces = true if invocation == invocationGeneration { - invocationRequiresRecords = false - if isInvocationCapture, let retryPID = invocationVisibilityRetryPID { - invocationVisibilityRetryPID = nil - if discovery.foregroundProcessIdentifier() == retryPID, - let target = foregroundTarget(for: retryPID) { - queueInvocationScan(for: target.hostPID) - } - } - if !invocationInProgress, !isInvocationReady { invocationRequiredHosts.formUnion(dirtyHosts) } + if isInvocationCapture { finishedForegroundCapture() } + if foregroundCheck == nil, !isInvocationReady { requiredCatalogScans.formUnion(dirtyHosts) } } schedulePublication() drainRefreshes() diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift index 101c1baa0..1c1444ee7 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift @@ -23,6 +23,7 @@ struct WindowSwitcherScan: Sendable { var reportedFocusedWindow = false var reportedFocusWasExcluded = false var excludedWindowNumbers: Set = [] + var focusReadStartedAt: ContinuousClock.Instant? } struct WindowSwitcherAXIdentity: Hashable { @@ -187,12 +188,13 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { } records.removeAll { excluded.contains(WindowSwitcherAXIdentity(element: $0.element)) } cursor = count == 0 ? 0 : (cursor + didRead) % count - let focused = uptime() < deadline ? copyElement(app, kAXFocusedWindowAttribute) : nil + let focusReadStartedAt: ContinuousClock.Instant? = uptime() < deadline ? .now : nil + let focused = focusReadStartedAt != nil ? copyElement(app, kAXFocusedWindowAttribute) : nil let focusedID = focused.flatMap { element in records.first { CFEqual($0.element, element) }?.id } return WindowSwitcherScan(windows: records, focusedID: focusedID, unavailable: metadataFailed || didRead < count, reportedFocusedWindow: focused != nil, reportedFocusWasExcluded: focused.map { excluded.contains(WindowSwitcherAXIdentity(element: $0)) } == true, - excludedWindowNumbers: excludedWindowNumbers) + excludedWindowNumbers: excludedWindowNumbers, focusReadStartedAt: focusReadStartedAt) } private enum Admission { @@ -209,7 +211,7 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { guard role == kAXWindowRole as String else { return .excluded() } if let subrole = values[1] as? String, ![kAXStandardWindowSubrole as String, kAXDialogSubrole as String, "AXFullScreenWindow"].contains(subrole) { - return .excluded() + return .excluded(access.windowNumber(window)) } guard let minimized = values[3] as? Bool, let point = decodePoint(values[4]), diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift index 02eac77a2..cbc8a0602 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift @@ -12,6 +12,7 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable var includesSecondaryWindow = true var focusesSecondaryWindow = false var secondaryWindowIsSmall = false + var secondaryWindowIsFloating = false var secondaryMetadataUnavailable = false var windowListUnavailable = false var beforeRead: (() -> Void)? @@ -70,7 +71,9 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable if isSecondary { point = CGPoint(x: 60, y: 60) } var size = isDialog ? CGSize(width: 400, height: 300) : CGSize(width: 800, height: 600) if isSecondary, read({ $0.secondaryWindowIsSmall }) { size = CGSize(width: 40, height: 30) } - return [kAXWindowRole, isDialog ? kAXDialogSubrole : kAXStandardWindowSubrole, isDialog ? "" : "Fixture", false, + let subrole = isDialog ? kAXDialogSubrole + : isSecondary && read({ $0.secondaryWindowIsFloating }) ? "AXFloatingWindow" : kAXStandardWindowSubrole + return [kAXWindowRole, subrole, isDialog ? "" : "Fixture", false, AXValueCreate(.cgPoint, &point)!, AXValueCreate(.cgSize, &size)!] } func windowNumber(_ window: AXUIElement) -> CGWindowID? { @@ -507,9 +510,17 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { try await verifyBackgroundExactFocus(refreshesVisibility: false) } - private func verifyBackgroundExactFocus(refreshesVisibility: Bool) async throws { - let foreground = CatalogAXAccess(number: 9, elementPID: 201) - foreground.update { $0.focused = true } + func testFollowupAXRefreshKeepsFocusNewerThanVisibility() async throws { + try await verifyBackgroundExactFocus(refreshesVisibility: false, followsUpWithoutVisibility: true) + } + + private func verifyBackgroundExactFocus(refreshesVisibility: Bool, followsUpWithoutVisibility: Bool = false) async throws { + let foreground = CatalogAXAccess(number: 9, elementPID: 201, + secondaryWindowNumber: followsUpWithoutVisibility ? 10 : nil) + foreground.update { + $0.focused = true + $0.includesSecondaryWindow = false + } let initialCapture = DispatchSemaphore(value: 1) let releaseCapture = DispatchSemaphore(value: 0) let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) @@ -541,20 +552,40 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { } let focused = catalog.entries(sortMode: .recentUse).first { $0.id == catalog.focusedWindowID } XCTAssertEqual(focused?.windowNumber, 8) + + if followsUpWithoutVisibility { + foreground.update { $0.includesSecondaryWindow = true } + catalog.invalidate(processIdentifiers: [42], windowRecords: false) + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 10 && $0.windowElement != nil } + } + XCTAssertEqual(catalog.focusedWindowID, focused?.id) + } } func testExcludedOnscreenDialogDoesNotPreventInferringTheForegroundWindow() async throws { + try await verifyExcludedOnscreenSurface(floating: false) + } + + func testExcludedFloatingPanelCannotBecomeInferredFocus() async throws { + try await verifyExcludedOnscreenSurface(floating: true) + } + + private func verifyExcludedOnscreenSurface(floating: Bool) async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } - let foreground = CatalogAXAccess(number: 8, elementPID: 202, emptyDialogNumber: 9) + let foreground = CatalogAXAccess(number: 8, elementPID: 202, emptyDialogNumber: floating ? nil : 9, + secondaryWindowNumber: floating ? 9 : nil) + foreground.update { $0.secondaryWindowIsFloating = floating } var foregroundPID: pid_t = 42 let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), accessFactory: { $0 == 42 ? previous : foreground }, allSpacesCatalog: .init(windowRecordProvider: { - [.init(windowNumber: 8, processIdentifier: 43, title: "Foreground", isOnScreen: true, - bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), - .init(windowNumber: 9, processIdentifier: 43, title: "", isOnScreen: true, - bounds: CGRect(x: 30, y: 30, width: 400, height: 300))] + [.init(windowNumber: 8, processIdentifier: 43, title: "Foreground", isOnScreen: !floating, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true, isOnActiveSpace: !floating), + .init(windowNumber: 9, processIdentifier: 43, title: floating ? "Tools" : "", isOnScreen: true, + bounds: floating ? CGRect(x: 60, y: 60, width: 800, height: 600) + : CGRect(x: 30, y: 30, width: 400, height: 300))] }), discovery: .init(applications: { let prior = WindowSwitcherAppCatalog.Application( processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") @@ -570,11 +601,24 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { catalog.prepareForInvocation() try await waitUntil { catalog.isInvocationReady } let entries = catalog.entries(sortMode: .recentUse) - XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) - XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + if floating { + XCTAssertEqual(entries.first?.windowNumber, 7) + XCTAssertNil(catalog.focusedWindowID) + } else { + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } XCTAssertEqual(foreground.read { $0.reads }, 1) } + func testMissingSplashInFreshVisibilityRetriesBeforeRecordingRecentUse() async throws { + try await verifyLaunchFocusRecovery(partialAX: false, failsRetryCapture: false, omitsSplash: true) + } + + func testForeignWindowServerOwnerCannotConfirmLaunchFocus() async throws { + try await verifyLaunchFocusRecovery(partialAX: false, failsRetryCapture: false, splashHasForeignOwner: true) + } + func testOffscreenReportedFocusRetriesBeforeRecordingRecentUse() async throws { try await verifyLaunchFocusRecovery(partialAX: false, failsRetryCapture: false) } @@ -607,28 +651,125 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { try await verifyLaunchWindowRetry(records: nil, failsInitialAXRead: true) } + func testLaunchRetriesWhenAccessibilityListsTwoWindowsWithoutFocus() async throws { + let records: [WindowSwitcherWindowRecord] = [ + .init(windowNumber: 8, processIdentifier: 43, title: "Primary", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), + .init(windowNumber: 9, processIdentifier: 43, title: "Document", + isOnScreen: true, bounds: CGRect(x: 60, y: 60, width: 800, height: 600)), + ] + try await verifyLaunchWindowRetry(records: records, waitsForFocus: true) + } + + func testLaunchRetriesWhenVisibilityFailsAndAccessibilityReturnsAnEmptyList() async throws { + try await verifyLaunchWindowRetry(records: nil, initiallyEmpty: true) + } + func testLaunchFocusOnAnAlreadyExcludedWindowDoesNotRetry() async throws { let primary = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Primary", isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) try await verifyLaunchWindowRetry(records: [primary], secondaryWindowIsSmall: true) } + func testUncorroboratedLaunchSplashStillAllowsTheRetry() async throws { + try await verifyLaunchFocusAppearingAfterRetryCapture(.inferredSplash) + } + + func testOffSpaceLaunchFocusDoesNotEnterHistoryBeforeRetry() async throws { + try await verifyLaunchFocusAppearingAfterRetryCapture(.offSpaceRestoration) + } + + func testOffSpaceFocusReportedOnRetryDoesNotEnterLaunchHistory() async throws { + try await verifyLaunchFocusAppearingAfterRetryCapture(.offSpaceFocusOnRetry) + } + + func testUnnumberedSplashDoesNotDisplaceAnAXBackedLaunchDocument() async throws { + try await verifyLaunchFocusAppearingAfterRetryCapture(.unnumberedSplash) + } + + private enum LaunchFocusFixture { + case inferredSplash, offSpaceRestoration, offSpaceFocusOnRetry, unnumberedSplash + } + + private func verifyLaunchFocusAppearingAfterRetryCapture(_ fixture: LaunchFocusFixture) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, replacementNumber: 9, secondaryWindowNumber: 9) + launched.update { + $0.focused = fixture == .offSpaceRestoration || fixture == .unnumberedSplash + $0.exposesWindowNumber = fixture != .unnumberedSplash + $0.includesSecondaryWindow = fixture == .unnumberedSplash + } + let initialCaptures = DispatchSemaphore(value: 2) + defer { initialCaptures.signal(); initialCaptures.signal() } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + let restored = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Restored elsewhere", + isOnScreen: false, bounds: CGRect(x: 20, y: 20, width: 800, height: 600), + hasSpace: true, isOnActiveSpace: false) + let origin = fixture == .inferredSplash ? CGPoint(x: 20, y: 20) : CGPoint(x: 60, y: 60) + let document = WindowSwitcherWindowRecord(windowNumber: 9, processIdentifier: 43, title: "Actual window", + isOnScreen: true, bounds: CGRect(origin: origin, size: CGSize(width: 800, height: 600))) + let restoredWindows = fixture == .offSpaceRestoration || fixture == .offSpaceFocusOnRetry ? [restored] : [] + if initialCaptures.wait(timeout: .now()) == .success { + return fixture == .unnumberedSplash ? [document] : restoredWindows + } + if fixture == .offSpaceFocusOnRetry { + launched.update { $0.focused = true } + return restoredWindows + } + launched.update { + if fixture == .inferredSplash { + $0.number = 9 + } else { + $0.includesSecondaryWindow = true + $0.focusesSecondaryWindow = true + } + } + return restoredWindows + [document] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application(processIdentifier: 42, localizedName: "Previous") + guard foregroundPID == 43 else { return [prior] } + return [prior, .init(processIdentifier: 43, localizedName: "Launched", isFinishedLaunching: false)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + if fixture == .offSpaceFocusOnRetry { + XCTAssertEqual(entries.compactMap(\.windowNumber), [7, 8]) + XCTAssertNil(catalog.focusedWindowID) + } else { + XCTAssertEqual(entries.compactMap(\.windowNumber), fixture == .offSpaceRestoration ? [9, 7, 8] : [9, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + XCTAssertEqual(launched.read { $0.reads }, 2) + } + private func verifyLaunchWindowRetry(records: [WindowSwitcherWindowRecord]?, secondaryWindowIsSmall: Bool = false, failsInitialAXRead: Bool = false, - partialInitialAXRead: Bool = false) async throws { + partialInitialAXRead: Bool = false, waitsForFocus: Bool = false, + initiallyEmpty: Bool = false) async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } - let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) + let launched = CatalogAXAccess(number: initiallyEmpty ? nil : 8, elementPID: 202, secondaryWindowNumber: 9) launched.update { - $0.includesSecondaryWindow = secondaryWindowIsSmall || partialInitialAXRead - $0.focusesSecondaryWindow = !partialInitialAXRead + $0.includesSecondaryWindow = secondaryWindowIsSmall || partialInitialAXRead || waitsForFocus + $0.focusesSecondaryWindow = !partialInitialAXRead && !waitsForFocus && !initiallyEmpty $0.secondaryWindowIsSmall = secondaryWindowIsSmall $0.secondaryMetadataUnavailable = partialInitialAXRead $0.windowListUnavailable = failsInitialAXRead $0.beforeRead = { [weak launched] in launched?.update { state in if state.reads == 2 { + state.number = 8 state.windowListUnavailable = false state.includesSecondaryWindow = true state.secondaryMetadataUnavailable = false @@ -667,7 +808,8 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { } } - private func verifyLaunchFocusRecovery(partialAX: Bool, failsRetryCapture: Bool) async throws { + private func verifyLaunchFocusRecovery(partialAX: Bool, failsRetryCapture: Bool, omitsSplash: Bool = false, + splashHasForeignOwner: Bool = false) async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: partialAX ? 9 : nil) @@ -689,16 +831,20 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { accessFactory: { $0 == 42 ? previous : launched }, allSpacesCatalog: .init(windowRecordProvider: { if initialCaptures.wait(timeout: .now()) != .success, failsRetryCapture { return nil } - return [.init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: false, - bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true, isOnActiveSpace: false), - .init(windowNumber: 9, processIdentifier: 43, title: "Launched", isOnScreen: true, - bounds: CGRect(x: 40, y: 40, width: 800, height: 600))] + let splash = WindowSwitcherWindowRecord(windowNumber: 8, + processIdentifier: splashHasForeignOwner ? 44 : 43, title: "Restoring", + isOnScreen: splashHasForeignOwner, bounds: CGRect(x: 20, y: 20, width: 800, height: 600), + hasSpace: true, isOnActiveSpace: splashHasForeignOwner) + let document = WindowSwitcherWindowRecord(windowNumber: 9, processIdentifier: 43, title: "Launched", + isOnScreen: true, bounds: CGRect(x: 40, y: 40, width: 800, height: 600)) + return omitsSplash ? [document] : [splash, document] }), discovery: .init(applications: { let prior = WindowSwitcherAppCatalog.Application( processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") let new = WindowSwitcherAppCatalog.Application( - processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched") + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched", + isFinishedLaunching: !omitsSplash && !splashHasForeignOwner) return foregroundPID == 43 ? [prior, new] : [prior] }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) defer { catalog.stop() } @@ -714,7 +860,7 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(entries.first?.windowNumber, 7) XCTAssertNil(catalog.focusedWindowID) } else { - XCTAssertEqual(entries.compactMap(\.windowNumber), [9, 7, 8]) + XCTAssertEqual(entries.compactMap(\.windowNumber), omitsSplash || splashHasForeignOwner ? [9, 7] : [9, 7, 8]) XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) } } @@ -1002,6 +1148,57 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(session.selected?.windowNumber, 7) } + func testFocusChangeAfterInitialReadUsesRetryBeforeInvocationBecomesReady() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) + launched.update { $0.focused = true } + let slow = CatalogAXAccess(number: 10, elementPID: 203) + let releaseScan = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: slow + } + }, allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "First", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true, isOnActiveSpace: true), + .init(windowNumber: 9, processIdentifier: 43, title: "Second", isOnScreen: true, + bounds: CGRect(x: 60, y: 60, width: 800, height: 600), hasSpace: true, isOnActiveSpace: true)] + }), discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application(processIdentifier: 42, localizedName: "Previous") + let other = WindowSwitcherAppCatalog.Application(processIdentifier: 44, localizedName: "Other") + guard foregroundPID == 43 else { return [previous, other] } + return [previous, other, + .init(processIdentifier: 43, localizedName: "Launched", isFinishedLaunching: false)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseScan.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + slow.update { $0.beforeRead = { _ = releaseScan.wait(timeout: .now() + 2) } } + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { + catalog.entries(sortMode: .recentUse).first { $0.id == catalog.focusedWindowID }?.windowNumber == 8 + } + XCTAssertFalse(catalog.isInvocationReady) + + launched.update { $0.focusesSecondaryWindow = true } + catalog.invalidate(processIdentifiers: [43], windowRecords: false, focusChanged: true) + slow.update { $0.beforeRead = nil } + releaseScan.signal() + try await waitUntil { catalog.isInvocationReady } + + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [9, 8, 7, 10]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 2) + } + func testCancelledInvocationKeepsConfirmedForegroundHistory() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } @@ -1057,23 +1254,28 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { } func testRoutineRefreshDoesNotRestoreOffscreenFocus() async throws { - try await verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: false) + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: false) } func testCancelledFocusStillUsesItsVisibilityAfterQueuedRefresh() async throws { - try await verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: true) + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: true) } func testCoalescedFocusEventUsesFreshVisibilityFromRoutineRefresh() async throws { - try await verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: false, coalescesFocusChange: true) + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: false, coalescesFocusChange: true) } func testNewVisibilityCanRejectFocusFromCancelledInvocation() async throws { - try await verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: true, wasOnscreenAtInvocation: true) + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: true, wasOnscreenAtInvocation: true) + } + + func testCancelledFocusUsesNewerAXEventWhenQueuedVisibilityPredatesIt() async throws { + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: true, focusChangesAfterQueuedCapture: true) } - private func verifyOffscreenFocusStaysOutOfHistory(cancelsInvocation: Bool, coalescesFocusChange: Bool = false, - wasOnscreenAtInvocation: Bool = false) async throws { + private func verifyFocusAfterQueuedRefresh(cancelsInvocation: Bool, coalescesFocusChange: Bool = false, + wasOnscreenAtInvocation: Bool = false, + focusChangesAfterQueuedCapture: Bool = false) async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) @@ -1099,7 +1301,7 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { invocationCaptureStarted.signal() _ = releaseCapture.wait(timeout: .now() + 2) } - let reportedWindowIsOnscreen = wasOnscreenAtInvocation && !background + let reportedWindowIsOnscreen = focusChangesAfterQueuedCapture || (wasOnscreenAtInvocation && !background) return [.init(windowNumber: 7, processIdentifier: 42, title: "Previous", isOnScreen: !background, bounds: bounds, hasSpace: true, isOnActiveSpace: !background), .init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: reportedWindowIsOnscreen, @@ -1161,15 +1363,27 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { } launched.update { $0.includesSecondaryWindow = true + $0.focusesSecondaryWindow = focusChangesAfterQueuedCapture + } + if focusChangesAfterQueuedCapture { + catalog.invalidate(processIdentifiers: [43], windowRecords: false, focusChanged: true) } releaseAX.signal() try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 9 && $0.windowElement != nil } } - XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 7) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, focusChangesAfterQueuedCapture ? 9 : 7) } func testForegroundHandoffWhileWaitingForRetryUsesNewForeground() async throws { + try await verifyForegroundHandoff(duringRetryCapture: false) + } + + func testForegroundHandoffDuringRetryCaptureUsesNewForeground() async throws { + try await verifyForegroundHandoff(duringRetryCapture: true) + } + + private func verifyForegroundHandoff(duringRetryCapture: Bool) async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 11) @@ -1179,6 +1393,9 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { } let next = CatalogAXAccess(number: 9, elementPID: 203) let releaseLaunchScan = DispatchSemaphore(value: 0) + let initialCaptures = DispatchSemaphore(value: 2) + let retryCaptureStarted = DispatchSemaphore(value: 0) + let releaseCapture = DispatchSemaphore(value: 0) var foregroundPID: pid_t = 42 var didLaunch = false let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), @@ -1188,14 +1405,26 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { case 43: launched default: next } - }, allSpacesCatalog: .init(windowRecordProvider: { [] }), + }, allSpacesCatalog: .init(windowRecordProvider: { + if duringRetryCapture, initialCaptures.wait(timeout: .now()) != .success { + retryCaptureStarted.signal() + _ = releaseCapture.wait(timeout: .now() + 2) + } + return [] + }), discovery: .init(applications: { let pids: [pid_t] = didLaunch ? [42, 43, 44] : [42, 44] return pids.map { .init(processIdentifier: $0, localizedName: "Fixture \($0)", isFinishedLaunching: $0 != 43) } }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) - defer { releaseLaunchScan.signal(); catalog.stop() } + defer { + catalog.stop() + releaseLaunchScan.signal() + initialCaptures.signal() + initialCaptures.signal() + releaseCapture.signal() + } catalog.start() try await waitUntil { catalog.isInvocationReady } let initialReads = next.read { $0.reads } @@ -1206,7 +1435,7 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { guard let catalog else { return } let numbers = catalog.entries(sortMode: .fixed).compactMap(\.windowNumber) if numbers.contains(10) { releaseLaunchScan.signal() } - if foregroundPID == 43, numbers.contains(8), !catalog.isInvocationReady { + if !duringRetryCapture, foregroundPID == 43, numbers.contains(8), !catalog.isInvocationReady { foregroundPID = 44 next.update { $0.focused = true } } @@ -1214,6 +1443,12 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { didLaunch = true foregroundPID = 43 catalog.prepareForInvocation() + if duringRetryCapture { + try await waitUntil { retryCaptureStarted.wait(timeout: .now()) == .success } + foregroundPID = 44 + next.update { $0.focused = true } + releaseCapture.signal() + } try await waitUntil { catalog.isInvocationReady } let entries = catalog.entries(sortMode: .recentUse) XCTAssertEqual(foregroundPID, 44) @@ -1223,6 +1458,126 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(launched.read { $0.reads }, 1) } + func testConfirmedHandoffDuringRetryAXSurvivesPublication() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + let next = CatalogAXAccess(number: 10, elementPID: 203) + let retryStarted = DispatchSemaphore(value: 0) + let releaseRetry = DispatchSemaphore(value: 0) + launched.update { + $0.beforeRead = { [weak launched] in + guard launched?.read({ $0.reads }) == 2 else { return } + retryStarted.signal() + _ = releaseRetry.wait(timeout: .now() + 2) + } + } + var foregroundPID: pid_t = 42 + var didLaunch = false + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: next + } + }, allSpacesCatalog: .init(windowRecordProvider: { [] }), discovery: .init(applications: { + let pids: [pid_t] = didLaunch ? [42, 43, 44] : [42, 44] + return pids.map { .init(processIdentifier: $0, localizedName: "Fixture \($0)", isFinishedLaunching: $0 != 43) } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseRetry.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + didLaunch = true + catalog.prepareForInvocation() + try await waitUntil { retryStarted.wait(timeout: .now()) == .success } + foregroundPID = 44 + next.update { $0.number = 11; $0.focused = true } + catalog.refresh() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 11 } } + XCTAssertFalse(catalog.isInvocationReady) + releaseRetry.signal() + try await waitUntil { catalog.isInvocationReady } + + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [11, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + + func testRetryCaptureCannotContradictAnExactFocusEventFromTheNextSpace() async throws { + try await verifyRetryFocusEvent(duringAccessibility: false) + } + + func testRetryAXReadUsesAFocusChangeThatArrivesDuringEnumeration() async throws { + try await verifyRetryFocusEvent(duringAccessibility: true) + } + + private func verifyRetryFocusEvent(duringAccessibility: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) + let initialCaptures = DispatchSemaphore(value: 2) + let retryStarted = DispatchSemaphore(value: 0) + let releaseRetry = DispatchSemaphore(value: 0) + launched.update { + $0.windowListUnavailable = true + if duringAccessibility { + $0.beforeRead = { [weak launched] in + guard launched?.read({ $0.reads }) == 2 else { return } + retryStarted.signal() + _ = releaseRetry.wait(timeout: .now() + 2) + } + } + } + let changedSpace = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + let onNextSpace = changedSpace.wait(timeout: .now()) == .success + if !duringAccessibility, initialCaptures.wait(timeout: .now()) != .success, !onNextSpace { + retryStarted.signal() + _ = releaseRetry.wait(timeout: .now() + 2) + } + return [ + .init(windowNumber: 8, processIdentifier: 43, title: "Previous Space", isOnScreen: !onNextSpace, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true, isOnActiveSpace: !onNextSpace), + .init(windowNumber: 9, processIdentifier: 43, title: "Next Space", isOnScreen: onNextSpace, + bounds: CGRect(x: 60, y: 60, width: 800, height: 600), hasSpace: true, isOnActiveSpace: onNextSpace), + ] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application(processIdentifier: 42, localizedName: "Previous") + guard foregroundPID == 43 else { return [prior] } + return [prior, .init(processIdentifier: 43, localizedName: "Launched", isFinishedLaunching: false)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { + catalog.stop() + initialCaptures.signal() + initialCaptures.signal() + releaseRetry.signal() + } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { retryStarted.wait(timeout: .now()) == .success } + launched.update { + $0.windowListUnavailable = false + $0.focusesSecondaryWindow = true + } + changedSpace.signal() + catalog.invalidate(processIdentifiers: [43], windowRecords: true, focusChanged: true) + releaseRetry.signal() + + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.first?.windowNumber, 9) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 2) + } + func testForegroundHandoffAndIncompleteAXShareOneRetry() async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } @@ -1476,17 +1831,29 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: true) } + func testBackgroundRefreshRecordsExactHelperFocusAfterHostFocusIsContradicted() async throws { + try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: true, refreshesInBackground: true) + } + + func testUnnumberedHelperExactFocusCanUseItsUniqueVisibilityMatch() async throws { + try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: true, exposesHelperNumber: false) + } + func testVisibleHelperPreventsInferringHostFocus() async throws { try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: false) } - private func verifyForegroundHostWithActiveHelper(hostIsOffscreen: Bool) async throws { + private func verifyForegroundHostWithActiveHelper(hostIsOffscreen: Bool, refreshesInBackground: Bool = false, + exposesHelperNumber: Bool = true) async throws { let previous = CatalogAXAccess(number: 7, elementPID: 201) previous.update { $0.focused = true } let host = CatalogAXAccess(number: 8, elementPID: 202) host.update { $0.focused = hostIsOffscreen } let helper = CatalogAXAccess(number: 9, elementPID: 203) - helper.update { $0.focused = hostIsOffscreen } + helper.update { + $0.focused = hostIsOffscreen + $0.exposesWindowNumber = exposesHelperNumber + } var foregroundPID: pid_t = 42 let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), @@ -1514,11 +1881,16 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { try await waitUntil { catalog.isInvocationReady } foregroundPID = 43 - catalog.prepareForInvocation() - try await waitUntil { catalog.isInvocationReady } + if refreshesInBackground { + catalog.refresh() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.axWorkerPID == 44 } } + } else { + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + } let entries = catalog.entries(sortMode: .recentUse) - XCTAssertEqual(Set(entries.compactMap(\.windowNumber)), [7, 8, 9]) - XCTAssertEqual(entries.first?.windowNumber, hostIsOffscreen ? 9 : 7) + XCTAssertEqual(Set(entries.compactMap(\.windowNumber)), exposesHelperNumber ? [7, 8, 9] : [7, 8]) + XCTAssertEqual(entries.first?.windowNumber, hostIsOffscreen ? (exposesHelperNumber ? 9 : nil) : 7) if hostIsOffscreen { XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) XCTAssertEqual(entries.first?.axWorkerPID, 44)