import ParcelCore import ParcelPlatform import Testing @testable import ParcelEngine @MainActor struct NativeFocusFreshnessTests { @Test func alreadyPresentedWindowNeedsNoUnsupportedRaise() async throws { let window = WindowID(rawValue: 1) var raised = false try await NativeRaiseVerification.perform( window: window, app: engineApp, read: { NativeRaiseReadback(foregroundPID: engineApp.pid, focusedWindow: window, frontWindow: window) }, raise: { raised = true; throw AXPlatformError.attributeUnsupported }) #expect(!raised) } @Test func unsupportedRaiseRequiresIndependentFocusAndWindowServerProof() async throws { let window = WindowID(rawValue: 1) var raised = false var clock = 0.0 try await NativeRaiseVerification.perform( window: window, app: engineApp, read: { NativeRaiseReadback( foregroundPID: clock >= 0.02 ? engineApp.pid : secondEngineApp.pid, focusedWindow: window, frontWindow: window) }, raise: { raised = true; throw AXPlatformError.attributeUnsupported }, now: { clock }, wait: { clock += 0.01 }) #expect(raised && clock >= 0.02) } @Test(arguments: ["foreground", "focused", "front"]) func unsupportedRaiseWithMissingEvidenceStillFails(missing: String) async { let window = WindowID(rawValue: 1) var clock = 0.0 await #expect(throws: AXPlatformError.attributeUnsupported) { try await NativeRaiseVerification.perform( window: window, app: engineApp, timeout: 0.02, read: { NativeRaiseReadback( foregroundPID: missing == "foreground" ? secondEngineApp.pid : engineApp.pid, focusedWindow: missing == "focused" ? WindowID(rawValue: 2) : window, frontWindow: missing == "front" ? WindowID(rawValue: 2) : window) }, raise: { throw AXPlatformError.attributeUnsupported }, now: { clock }, wait: { clock += 0.01 }) } } @Test func successfulBackgroundRaiseKeepsItsExistingNonactivatingBehavior() async throws { let window = WindowID(rawValue: 1) var raised = false var reads = 0 try await NativeRaiseVerification.perform( window: window, app: engineApp, read: { reads += 1 return NativeRaiseReadback( foregroundPID: secondEngineApp.pid, focusedWindow: window, frontWindow: WindowID(rawValue: 2)) }, raise: { raised = true }) #expect(raised && reads == 1) } @Test func unrelatedRaiseFailuresAreNeverHiddenByLaterFocus() async { let window = WindowID(rawValue: 1) await #expect(throws: AXPlatformError.notPermitted) { try await NativeRaiseVerification.perform( window: window, app: engineApp, read: { NativeRaiseReadback(foregroundPID: nil, focusedWindow: nil, frontWindow: nil) }, raise: { throw AXPlatformError.notPermitted }) } } @Test(arguments: [false, true]) func aSpaceNotificationCancelsQueuedNativeFocusAndRaise(raise: Bool) async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } let window = WindowID(rawValue: 1) harness.first.error = EngineOperationFailure.activationRefused(engineApp) let failure: EnginePlatformFailure? = await withCheckedContinuation { continuation in let completion: @MainActor (EnginePlatformFailure?) -> Void = { continuation.resume(returning: $0) } if raise { harness.world.raise(window, completion: completion) } else { harness.world.focus(window, completion: completion) } harness.backend.spaces[engineDisplay] = SpaceID(rawValue: 2) harness.backend.emit(.spaceChanged) } #expect(failure == nil) } enum FocusCancellation: CaseIterable { case spaceChange, appExit, stop } @Test(arguments: [false, true], FocusCancellation.allCases) func invalidationCancelsFocusAndRaiseWaitingForTheOwner(raise: Bool, cause: FocusCancellation) async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } harness.clearEvents() var queued: CheckedContinuation? var attempted = false var returned = false harness.first.beforeFocusOrRaise = { defer { returned = true } await withCheckedContinuation { queued = $0 } try Task.checkCancellation() attempted = true } let window = WindowID(rawValue: 1) var replies: [EnginePlatformFailure?] = [] let completion: @MainActor (EnginePlatformFailure?) -> Void = { replies.append($0) } if raise { harness.world.raise(window, completion: completion) } else { harness.world.focus(window, completion: completion) } try await harness.drain() let owner = try #require(queued) switch cause { case .spaceChange: harness.backend.emit(.spaceChanged) case .appExit: harness.backend.emit(.terminated(engineApp)) case .stop: harness.world.stop() } try await harness.drain() #expect(replies == [nil]) owner.resume() try await harness.drain() #expect(returned && !attempted) #expect(replies == [nil]) #expect(harness.failures.isEmpty) } @Test func startupReadsNativeFocusWithoutWaitingForAnActivationNotification() async throws { let harness = NativeHarness() harness.backend.frontmost = secondEngineApp try await harness.start() defer { harness.world.stop() } #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 2)) #expect(harness.state.focusedWindow == WindowID(rawValue: 2)) #expect(harness.first.focusReads == 0 && harness.second.focusReads == 1) #expect(!harness.world.hasPendingReconciliation) } @Test(arguments: [false, true]) func aSupersededSpaceReadPreservesTheNewestPendingFocus(reactivateFirst: Bool) async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } harness.backend.deferVisibleRead = true harness.backend.emit(.activated(NativeApplicationInfo(id: secondEngineApp))) harness.backend.emit(.spaceChanged) try await harness.drain() try #require(harness.backend.hasPendingVisible) harness.backend.emit(.spaceChanged) if reactivateFirst { harness.backend.emit(.activated(NativeApplicationInfo(id: engineApp))) } harness.clearEvents() harness.backend.deferVisibleRead = false try harness.backend.completeVisible() try await harness.drainReconciliation() let expected = WindowID(rawValue: reactivateFirst ? 1 : 2) #expect(harness.world.observedFocusedWindow == expected) let focus = harness.events.compactMap { if case .observed(.focusChanged(let window)) = $0 { window } else { nil } } #expect(focus == [expected]) } @Test(arguments: [false, true]) func startupFocusFollowsTheLastBackgroundInventoryAdmission(activationDuringStartup: Bool) async throws { let harness = NativeHarness() harness.backend.frontmost = secondEngineApp harness.first.deferWindowRead = true try await harness.start() defer { harness.world.stop() } try #require(harness.first.hasPendingWindows) #expect(harness.second.focusReads == 0) if activationDuringStartup { harness.backend.emit(.activated(NativeApplicationInfo(id: secondEngineApp))) try await harness.drain() #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 2)) } harness.first.deferWindowRead = false try harness.first.completeWindows() try await harness.drain() #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 2)) #expect(harness.state.focusedWindow == WindowID(rawValue: 2)) #expect(harness.first.focusReads == 0) #expect(harness.second.focusReads == (activationDuringStartup ? 2 : 1)) let backgroundAdmission = try #require( harness.events.lastIndex { if case .observed(.windowAppeared(let window, _, _)) = $0 { window.app == engineApp } else { false } }) let finalFocus = try #require( harness.events.lastIndex { if case .observed(.focusChanged(WindowID(rawValue: 2))) = $0 { true } else { false } }) #expect(backgroundAdmission < finalFocus) #expect(!harness.world.hasPendingReconciliation) } @Test func startupFocusReadsTheCurrentAppAfterInventoryRatherThanTheInitiallyFrontmostApp() async throws { let harness = NativeHarness() harness.first.deferWindowRead = true try await harness.start() defer { harness.world.stop() } try #require(harness.first.hasPendingWindows) harness.backend.frontmost = secondEngineApp harness.first.deferWindowRead = false try harness.first.completeWindows() try await harness.drain() #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 2)) #expect(harness.state.focusedWindow == WindowID(rawValue: 2)) #expect(harness.first.focusReads == 0 && harness.second.focusReads == 1) #expect(!harness.world.hasPendingReconciliation) } @Test(arguments: [false, true]) func unavailableOrTerminatedStartupWorkerDoesNotHoldTheFinalFocusRead(unavailable: Bool) async throws { let harness = NativeHarness() harness.backend.frontmost = secondEngineApp harness.first.deferWindowRead = true try await harness.start() defer { harness.world.stop() } try #require(harness.first.hasPendingWindows) if unavailable { harness.first.emit(.failure(.runLoopUnavailable)) } else { harness.backend.emit(.terminated(engineApp)) } try await harness.drain() #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 2)) #expect(harness.state.focusedWindow == WindowID(rawValue: 2)) #expect(!harness.world.hasPendingReconciliation) } @Test(arguments: [false, true]) func delayedWorkspaceActivationCannotSupersedeCurrentNativeFocus(awaitingRead: Bool) async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } harness.clearEvents() harness.second.deferFocusRead = awaitingRead harness.backend.emit(.activated(NativeApplicationInfo(id: secondEngineApp))) if awaitingRead { try await harness.drain() try #require(harness.second.hasPendingFocus) } let staleReads = harness.first.focusReads harness.backend.emit(.activated(NativeApplicationInfo(id: engineApp)), changesFrontmost: false) if awaitingRead { try harness.second.completeFocus(WindowID(rawValue: 2)) } try await harness.drain() #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 2)) #expect(harness.state.focusedWindow == WindowID(rawValue: 2)) #expect(harness.first.focusReads == staleReads) #expect(!harness.world.hasPendingReconciliation) } @Test func delayedActivationFromAnotherPIDInTheSameBundleCannotSupersedeFocus() async throws { let harness = NativeHarness() let otherPID = AppID(pid: secondEngineApp.pid, bundleID: engineApp.bundleID) harness.second.snapshots = [ NativeWindowSnapshot(window: engineWindow(2, app: otherPID), frame: initialEngineFrame) ] harness.backend.infos = [NativeApplicationInfo(id: engineApp), NativeApplicationInfo(id: otherPID)] harness.backend.apps = [engineApp: harness.first, otherPID: harness.second] try await harness.start() defer { harness.world.stop() } harness.backend.emit(.activated(NativeApplicationInfo(id: otherPID))) harness.backend.emit(.activated(NativeApplicationInfo(id: engineApp)), changesFrontmost: false) try await harness.drain() #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 2)) #expect(harness.state.focusedWindow == WindowID(rawValue: 2)) } @Test(arguments: [engineApp, AppID(pid: 999, bundleID: "test.helper")], [false, true]) func unrelatedTerminationCannotInvalidateCurrentNativeFocus(exited: AppID, awaitingRead: Bool) async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } harness.second.deferFocusRead = awaitingRead harness.backend.emit(.activated(NativeApplicationInfo(id: secondEngineApp))) if awaitingRead { try await harness.drain() try #require(harness.second.hasPendingFocus) } harness.backend.emit(.terminated(exited)) if awaitingRead { try harness.second.completeFocus(WindowID(rawValue: 2)) } try await harness.drain() #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 2)) #expect(harness.state.focusedWindow == WindowID(rawValue: 2)) #expect(!harness.world.hasPendingReconciliation) } @Test func delayedOldAppFocusReadCannotClearTheCurrentAppFocus() async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } harness.clearEvents() harness.backend.frontmost = secondEngineApp harness.first.emit(.focusedWindowRead(nil)) harness.second.emit(.focusedWindowRead(2)) try await harness.drain() let focus = harness.events.compactMap { event -> WindowID?? in if case .observed(.focusChanged(let window)) = event { return .some(window) } return nil } #expect(focus == [WindowID(rawValue: 2)]) } @Test func awaitedFocusReadIsDiscardedIfItsAppIsNoLongerFrontmost() async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } harness.clearEvents() harness.first.deferFocusRead = true harness.backend.emit(.activated(NativeApplicationInfo(id: engineApp))) try await harness.drain() try #require(harness.first.hasPendingFocus) harness.backend.frontmost = secondEngineApp try harness.first.completeFocus(WindowID(rawValue: 1)) try await harness.drain() #expect(!harness.events.contains { if case .observed(.focusChanged) = $0 { true } else { false } }) } @Test func inactiveAppWindowChangedDoesNotScheduleAStaleFocusRead() async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } let reads = harness.first.focusReads harness.backend.frontmost = secondEngineApp harness.first.emit(.focusedWindowChanged) try await harness.drain() #expect(harness.first.focusReads == reads) } @Test(arguments: [false, true]) func inactiveFocusActivityStillReconcilesNewWindowsWithoutStealingFocus(typed: Bool) async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } harness.backend.frontmost = secondEngineApp harness.second.emit(.focusedWindowRead(2)) try await harness.drain() harness.clearEvents() harness.first.snapshots.append(NativeWindowSnapshot(window: engineWindow(3), frame: initialEngineFrame)) harness.backend.visible[WindowID(rawValue: 3)] = initialEngineFrame harness.first.emit(typed ? .focusedWindowRead(3) : .focusedWindowChanged) try await harness.drain() #expect(harness.appeared.map(\.window.id) == [WindowID(rawValue: 3)]) #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 2)) #expect(!harness.events.contains { if case .observed(.focusChanged) = $0 { true } else { false } }) } @Test(arguments: [false, true]) func delayedSameAppFocusPayloadIsVerifiedAgainstCurrentAXFocus(emptyPayload: Bool) async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } harness.first.snapshots.append(NativeWindowSnapshot(window: engineWindow(3), frame: initialEngineFrame)) harness.backend.visible[WindowID(rawValue: 3)] = initialEngineFrame harness.world.reconcile([engineApp]) try await harness.drain() harness.clearEvents() harness.first.focused = WindowID(rawValue: 3) harness.first.emit(.focusedWindowRead(emptyPayload ? nil : 1)) try await harness.drain() #expect(harness.world.observedFocusedWindow == WindowID(rawValue: 3)) #expect(!harness.events.contains { if case .observed(.focusChanged(nil)) = $0 { true } else { false } }) } @Test func currentAppCanStillReportNoFocusedWindow() async throws { let harness = NativeHarness() try await harness.start() defer { harness.world.stop() } harness.clearEvents() harness.backend.frontmost = secondEngineApp harness.second.focused = nil harness.second.emit(.focusedWindowRead(nil)) try await harness.drain() #expect(harness.events.contains { if case .observed(.focusChanged(nil)) = $0 { true } else { false } }) } }