import CoreFoundation import CoreGraphics import Darwin import Foundation import ParcelCore import Synchronization import Testing @testable import ParcelPlatform @Suite struct AppThreadFocusFastPathTests { @Test(arguments: ["AXFocusedWindowChanged"]) func windowSelectionNotificationsReadTheCurrentRealWindowID(notification: String) { var reads = 0 let event = AppThreadFocusReader.event(for: notification) { reads += 1 return 32190 } #expect(event == .focusedWindowRead(32190)) #expect(reads == 1) } @Test func mainWindowSelectionRequestsFreshFactsBeforeResolvingFocus() { var reads = 0 let event = AppThreadFocusReader.event(for: "AXMainWindowChanged") { reads += 1 return 32190 } #expect(event == .focusedWindowChanged) #expect(reads == 0) } @Test func controlFocusChangesDoNotRescanWindowSelection() { var reads = 0 let event = AppThreadFocusReader.event(for: "AXFocusedUIElementChanged") { reads += 1 return 32190 } #expect(event == nil) #expect(reads == 0) } @Test func focusResolvesTheFocusedWindowID() throws { let id = try AppThreadFocusReader.read( focusedWindow: { "focused" }, identify: { window in #expect(window == "focused") return 42 }) #expect(id == 42) } @Test(arguments: [AXPlatformError.noValue, .attributeUnsupported]) func absentFocusSkipsTheIDCall(error: AXPlatformError) throws { var calls = 0 let id = try AppThreadFocusReader.read( focusedWindow: { () throws -> Int in calls += 1; throw error }, identify: { _ in calls += 1; return 42 }) #expect(id == nil) #expect(calls == 1) } @Test(arguments: [AXPlatformError.noValue, .attributeUnsupported]) func focusedElementWithoutAnIDRequestsReconciliation(error: AXPlatformError) throws { var calls = 0 let id = try AppThreadFocusReader.read( focusedWindow: { calls += 1; return 1 }, identify: { _ in calls += 1; throw error }) #expect(id == nil) #expect(calls == 2) } @Test(arguments: [AXPlatformError.timedOut, .notPermitted, .elementInvalid, .messagingFailure]) func failedFocusReadEmitsOnlyFailureInsteadOfAFalseNoFocusObservation(error: AXPlatformError) { let event = AppThreadFocusReader.event { throw error } #expect(event == .failure(.accessibility(error))) #expect(event != .focusedWindowRead(nil)) } @Test func genuinelyAbsentFocusStillEmitsTheOptionalIDObservation() { #expect(AppThreadFocusReader.event { nil } == .focusedWindowRead(nil)) } @Test(arguments: [false, true], [AXPlatformError.timedOut, .notPermitted, .elementInvalid, .messagingFailure]) func genuineFocusErrorsAreNotHidden(atIdentification: Bool, error: AXPlatformError) { #expect(throws: error) { try AppThreadFocusReader.read( focusedWindow: { () throws -> Int in if !atIdentification { throw error } return 1 }, identify: { _ in throw error }) } } } @Suite struct AppThreadMotionMailboxTests { private func move(_ id: CGWindowID, x: Int) -> AppThreadEvent { .windowMovedWithFrame( id, frame: CGRect(x: x, y: 20, width: 300, height: 200), origin: .unattributed) } @Test func dirtyStormReadsOnlyAtDeliveryAndAcknowledgmentAndUsesTheFreshestFrame() throws { var mailbox = AppThreadMotionMailbox() var reads = 0 var actual = CGRect(x: 1, y: 20, width: 300, height: 200) let read: (CGWindowID) -> CGRect = { id in #expect(id == 1) reads += 1 return actual } let offered = mailbox.offer(.windowMoved(1, origin: .unattributed)) let first = try #require(offered) #expect(AppThreadMotionMailbox.materialize(first, readFrame: read) == move(1, x: 1)) for x in 2...500 { actual.origin.x = CGFloat(x) #expect(mailbox.offer(.windowMoved(1, origin: .unattributed)) == nil) } #expect(reads == 1) actual.origin.x = 501 let acknowledged = mailbox.acknowledge(1) let pending = try #require(acknowledged) #expect(AppThreadMotionMailbox.materialize(pending, readFrame: read) == move(1, x: 501)) #expect(reads == 2) #expect(mailbox.acknowledge(1) == nil) } @Test(arguments: [AXPlatformError.timedOut, .elementInvalid, .notPermitted]) func dirtyReadFailureIsSurfacedInsteadOfInventingAFrame(error: AXPlatformError) { let event = AppThreadMotionMailbox.materialize(.windowMoved(1, origin: .unattributed)) { _ in throw error } #expect(event == .failure(.accessibility(error))) } @Test func dirtyDeliveryRetainsItsDetectionTraceAndLatestEchoOrigin() throws { let outcomes = Mutex<[DetectionTraceOutcome]>([]) let trace = DetectionTrace(startedAt: 0) { outcome in outcomes.withLock { $0.append(outcome) } } let write = UUID() let marker = AppThreadEvent.detected(.windowResized(1, origin: .possiblySelfGenerated(write)), trace: trace) let frame = CGRect(x: 10, y: 20, width: 640, height: 480) let delivered = AppThreadMotionMailbox.materialize(marker) { _ in frame } #expect( delivered == .detected( .windowResizedWithFrame(1, frame: frame, origin: .possiblySelfGenerated(write)), trace: trace)) #expect(outcomes.withLock { $0 }.isEmpty) delivered.finishDroppedTrace() #expect(outcomes.withLock { $0 } == [.dropped]) } @Test(arguments: [ AppThreadEvent.windowMinimized(1), .windowDestroyed(1), .windowTitleChanged(1), .windowDeminimized(1), ]) func pendingMotionIsDeliveredBeforeEachWindowLifecycleBarrier(barrier: AppThreadEvent) throws { var mailbox = AppThreadMotionMailbox() _ = mailbox.offer(move(1, x: 1)) _ = mailbox.offer(move(1, x: 2)) _ = mailbox.offer(move(2, x: 3)) _ = mailbox.offer(move(2, x: 4)) var delivered: [AppThreadEvent] = [] if let pending = mailbox.flushBefore(barrier) { delivered.append(pending) } if let event = mailbox.offer(barrier) { delivered.append(event) } #expect(delivered == [move(1, x: 2), barrier]) #expect(mailbox.acknowledge(1) == nil) #expect(mailbox.acknowledge(2) == move(2, x: 4)) } @Test func acknowledgmentsBeforeABarrierDoNotReleaseMotionAfterItPrematurely() { var mailbox = AppThreadMotionMailbox() _ = mailbox.offer(move(1, x: 1)) _ = mailbox.offer(move(1, x: 2)) #expect(mailbox.flushBefore(.windowMinimized(1)) == move(1, x: 2)) #expect(mailbox.offer(move(1, x: 3)) == nil) #expect(mailbox.acknowledge(1) == nil) #expect(mailbox.acknowledge(1) == move(1, x: 3)) #expect(mailbox.acknowledge(1) == nil) } @Test func failedDirtyDeliveryKeepsItsTypedWindowLookupFailure() { #expect( AppThreadMotionMailbox.materialize(.windowMoved(1, origin: .unattributed)) { _ in throw AppThreadFailure.windowNotFound(1) } == .failure(.windowNotFound(1))) } @Test func stalledConsumerReceivesTheFinalFrameAfterFiveHundredMoves() { var mailbox = AppThreadMotionMailbox() let first = mailbox.offer(move(1, x: 0)) #expect(first == move(1, x: 0)) for x in 1...500 { let offered = mailbox.offer(move(1, x: x)) #expect(offered == nil) } let latest = mailbox.acknowledge(1) #expect(latest == move(1, x: 500)) let drained = mailbox.acknowledge(1) #expect(drained == nil) let next = mailbox.offer(move(1, x: 501)) #expect(next == move(1, x: 501)) } @Test func windowsDrainIndependentlyAndNonMotionEventsBypassTheMailbox() { var mailbox = AppThreadMotionMailbox() let first = mailbox.offer(move(1, x: 1)) let second = mailbox.offer(move(2, x: 2)) let pendingFirst = mailbox.offer(move(1, x: 3)) let pendingSecond = mailbox.offer(move(2, x: 4)) #expect(first != nil) #expect(second != nil) #expect(pendingFirst == nil) #expect(pendingSecond == nil) let title = mailbox.offer(.windowTitleChanged(1)) #expect(title == .windowTitleChanged(1)) let latestSecond = mailbox.acknowledge(2) #expect(latestSecond == move(2, x: 4)) let latestFirst = mailbox.acknowledge(1) #expect(latestFirst == move(1, x: 3)) } @Test func moveAndResizeRetainTheLatestFrameWithoutLosingUnattributedUserMotion() { var mailbox = AppThreadMotionMailbox() _ = mailbox.offer(move(1, x: 1)) _ = mailbox.offer(move(1, x: 2)) let id = UUID() let resize = AppThreadEvent.windowResizedWithFrame( 1, frame: CGRect(x: 2, y: 20, width: 640, height: 480), origin: .possiblySelfGenerated(id)) let offered = mailbox.offer(resize) #expect(offered == nil) let latest = mailbox.acknowledge(1) #expect( latest == .windowResizedWithFrame( 1, frame: CGRect(x: 2, y: 20, width: 640, height: 480), origin: .unattributed)) } @Test func replacedAndDestroyedPendingTracesFinishAsDroppedWithoutTouchingOtherWindows() { let outcomes = Mutex<[Int]>([]) func traced(_ sequence: Int, window: CGWindowID) -> AppThreadEvent { .detected( move(window, x: sequence), trace: DetectionTrace(startedAt: UInt64(sequence)) { outcome in #expect(outcome == .dropped) outcomes.withLock { $0.append(sequence) } }) } var mailbox = AppThreadMotionMailbox() let first = traced(0, window: 1) let offeredFirst = mailbox.offer(first) let offeredSecond = mailbox.offer(traced(1, window: 1)) let offeredThird = mailbox.offer(traced(2, window: 1)) #expect(offeredFirst == first) #expect(offeredSecond == nil) #expect(offeredThird == nil) #expect(outcomes.withLock { $0 } == [1]) _ = mailbox.offer(move(2, x: 0)) _ = mailbox.offer(traced(3, window: 2)) mailbox.remove(1) #expect(outcomes.withLock { $0 } == [1, 2]) mailbox.removeAll() #expect(outcomes.withLock { $0 } == [1, 2, 3]) first.finishDroppedTrace() #expect(outcomes.withLock { $0 } == [1, 2, 3, 0]) } @Test func coalescingDoesNotFinishADetectionTraceOwnedByAnotherDeliveredSibling() { let outcomes = Mutex<[DetectionTraceOutcome]>([]) let trace = DetectionTrace(startedAt: 0) { outcome in outcomes.withLock { $0.append(outcome) } } trace.retainDelivery() var mailbox = AppThreadMotionMailbox() _ = mailbox.offer(move(1, x: 0)) _ = mailbox.offer(.detected(move(1, x: 1), trace: trace)) _ = mailbox.offer(move(1, x: 2)) #expect(outcomes.withLock { $0 }.isEmpty) trace.enqueue() trace.releaseDelivery() trace.dequeue(.flushed) #expect(outcomes.withLock { $0 } == [.flushed]) } @Test func duplicateAcknowledgmentWithoutPendingWorkDoesNotBlockFutureDelivery() { var mailbox = AppThreadMotionMailbox() let empty = mailbox.acknowledge(1) #expect(empty == nil) _ = mailbox.offer(move(1, x: 1)) let first = mailbox.acknowledge(1) let duplicate = mailbox.acknowledge(1) #expect(first == nil) #expect(duplicate == nil) let next = mailbox.offer(move(1, x: 2)) #expect(next == move(1, x: 2)) } } @Suite struct AppThreadStartupRegistrationTests { @Test func threeTransientFailuresRecoverWithinOneHundredMillisecondsAndEnumerateOnce() { var registration = AppThreadRegistrationTracker() var backoff = AppThreadRegistrationBackoff(now: 0) var created = AppThreadCreatedWindowTracker() var now: UInt64 = 0 var attempts = 0 while registration.needs("created", windowID: nil) { registration.record(attempts < 3 ? .cannotComplete : .success, notification: "created", windowID: nil) attempts += 1 if registration.needs("created", windowID: nil) { guard let delay = backoff.nextDelay(now: now) else { Issue.record("Registration exhausted before transient failures recovered") return } now += UInt64((delay * 1_000_000_000).rounded()) } } #expect(attempts == 4) #expect(now == 35_000_000) let initial = [CGWindowID(1), 2, 1].filter { created.claim($0) } #expect(initial == [1, 2]) let repeated = created.claim(1) #expect(!repeated) created.remove(1) let recycled = created.claim(1) #expect(recycled) } @Test func retryIntervalsGrowThenCapAndEndAtTheOneSecondDeadline() { var backoff = AppThreadRegistrationBackoff(now: 10) var now: UInt64 = 10 var intervals: [Double] = [] while let delay = backoff.nextDelay(now: now) { intervals.append(delay) now += UInt64((delay * 1_000_000_000).rounded()) } #expect(Array(intervals.prefix(5)) == [0.005, 0.01, 0.02, 0.04, 0.08]) #expect(intervals.allSatisfy { $0 <= 0.08 }) #expect(intervals.count <= AppThreadRegistrationBackoff.maximumAttempts) #expect(now == 10 + AppThreadRegistrationBackoff.maximumAgeNanoseconds) let exhausted = backoff.nextDelay(now: now + 1) #expect(exhausted == nil) } @Test func slowRegistrationUsesUpTheBudgetInsteadOfStartingAnotherIdleTimer() { var backoff = AppThreadRegistrationBackoff(now: 100) let exhausted = backoff.nextDelay(now: 100 + AppThreadRegistrationBackoff.maximumAgeNanoseconds) #expect(exhausted == nil) var backwards = AppThreadRegistrationBackoff(now: 100) let invalidClock = backwards.nextDelay(now: 99) #expect(invalidClock == nil) } @Test func retryAttemptCountIsBoundedEvenIfTheInjectedClockDoesNotAdvance() { var backoff = AppThreadRegistrationBackoff(now: 0) for _ in 0...makeStream() let process = Process() process.executableURL = URL(fileURLWithPath: "/bin/sleep") process.arguments = ["30"] process.terminationHandler = { _ in terminationContinuation.yield(()) } try process.run() defer { if process.isRunning { process.terminate() } } let (registered, registrationContinuation) = AsyncStream.makeStream() let (exited, exitContinuation) = AsyncStream.makeStream() let observer = AppProcessObserver( pid: process.processIdentifier, queue: DispatchQueue(label: "parcel-test-process-observer", qos: .userInitiated), onRegistration: { registrationContinuation.yield(()) }, onExit: { exitContinuation.yield(()) } ) defer { observer.cancel() } try await waitForProcessEvent(registered, name: "process source registration") process.terminate() try await waitForProcessEvent(exited, name: "process source exit") try await waitForProcessEvent(terminated, name: "fixture process termination") #expect(!process.isRunning) } private struct ProcessObservationTimeout: Error, CustomStringConvertible { let event: String var description: String { "Timed out waiting for \(event)" } } private func waitForProcessEvent(_ events: AsyncStream, name: String) async throws { try await withThrowingTaskGroup(of: Void.self) { group in group.addTask { var iterator = events.makeAsyncIterator() let event: Void? = await iterator.next() try Task.checkCancellation() try #require(event != nil, "Process event stream ended before \(name)") } group.addTask { try await Task.sleep(for: .seconds(10)) throw ProcessObservationTimeout(event: name) } defer { group.cancelAll() } try await group.next() } } @Test func callWatchdogReportsOnlyAnOperationStillInFlight() { let scheduled = Mutex<[@Sendable () -> Void]>([]) let reports = Mutex(0) let watchdog = AXCallWatchdog( schedule: { action in scheduled.withLock { $0.append(action) } return {} }, overdue: { reports.withLock { $0 += 1 } } ) let completed = watchdog.begin() watchdog.end(completed) let blocked = watchdog.begin() let callbacks = scheduled.withLock { $0 } callbacks[0]() #expect(reports.withLock { $0 } == 0) callbacks[1]() callbacks[1]() #expect(reports.withLock { $0 } == 1) watchdog.end(blocked) let next = watchdog.begin() watchdog.end(blocked) let last = scheduled.withLock { $0[2] } last() #expect(reports.withLock { $0 } == 2) watchdog.end(next) } @Test func windowLookupContinuesPastUnidentifiableWindows() throws { var failures: [AXPlatformError] = [] let result = try AppThreadWindowLookup.find( in: [1, 2, 3], windowID: 3, identify: { value in if value == 1 { throw AXPlatformError.elementInvalid } return CGWindowID(value) }, onFailure: { error in if let error = error as? AXPlatformError { failures.append(error) } } ) #expect(result == 3) #expect(failures == [.elementInvalid]) #expect(throws: AXPlatformError.elementInvalid) { try AppThreadWindowLookup.find( in: [1, 2], windowID: 3, identify: { value in if value == 1 { throw AXPlatformError.elementInvalid } return CGWindowID(value) }, onFailure: { _ in } ) } let absent = try AppThreadWindowLookup.find( in: [1, 2], windowID: 3, identify: { CGWindowID($0) }, onFailure: { _ in } ) #expect(absent == nil) } @Test(arguments: [UInt32(3), UInt32(4), nil] as [UInt32?]) func windowLookupRequiresAnExactFreshFocusedIDWhenInventoryOmitsIt(focusedID: UInt32?) throws { var focusedReads = 0 let result = try AppThreadWindowLookup.find( in: [UInt32(1), 2], windowID: 3, identify: { $0 }, focused: { focusedReads += 1; return focusedID }, onFailure: { _ in Issue.record("Unexpected identity failure") }) #expect(result == (focusedID == 3 ? 3 : nil)) #expect(focusedReads == 1) } @Test func windowLookupDoesNotReadFocusWhenInventoryAlreadyContainsItsTarget() throws { var focusedReads = 0 let result = try AppThreadWindowLookup.find( in: [UInt32(1), 2], windowID: 2, identify: { $0 }, focused: { focusedReads += 1; return 1 }, onFailure: { _ in Issue.record("Unexpected identity failure") }) #expect(result == 2) #expect(focusedReads == 0) } @Test func windowLookupSurfacesAFailedFreshFocusReadInsteadOfGuessing() { #expect(throws: AXPlatformError.timedOut) { try AppThreadWindowLookup.find( in: [UInt32](), windowID: 3, identify: { $0 }, focused: { throw AXPlatformError.timedOut }, onFailure: { _ in }) } } @Test(arguments: [AXPlatformError.other(-25201), .elementInvalid, .noValue, .attributeUnsupported]) func windowSnapshotEnumerationReportsBadEntriesWithoutLosingVerifiedRealIDs(error: AXPlatformError) throws { var failures: [AXPlatformError] = [] let identified = try AppThreadWindowLookup.identified( in: [0, 32190, 32191], identify: { value in if value == 0 { throw error } return CGWindowID(value) }, onFailure: { failure in if let failure = failure as? AXPlatformError { failures.append(failure) } }) #expect(identified.map(\.id) == [32190, 32191]) #expect(identified.map(\.window) == [32190, 32191]) #expect(failures == [error]) } @Test(arguments: [AXPlatformError.notPermitted, .timedOut, .messagingFailure, .unexpectedValue("identity"), .other(-1)]) func appWideIdentificationFailuresDoNotProduceAnIncompleteRetirementSnapshot(error: AXPlatformError) { #expect(throws: error) { try AppThreadWindowLookup.identified( in: [1, 2], identify: { value in if value == 2 { throw error } return CGWindowID(value) }, onFailure: { _ in }) } } @Test func identifiedSnapshotsReadEachElementOnceAndNeverPublishZeroWindowIDs() throws { var reads: [UInt32] = [] var failures: [AXPlatformError] = [] let identified = try AppThreadWindowLookup.identified( in: [UInt32(0), 32190], identify: { value in reads.append(value) return value }, onFailure: { error in if let error = error as? AXPlatformError { failures.append(error) } }) #expect(reads == [0, 32190]) #expect(identified.map(\.id) == [32190]) #expect(failures == [.noValue]) } @Test func applicationOwnersAreExclusiveAndCanBeReleased() async { let registry = AppThreadOwnerRegistry() let results = await withTaskGroup(of: Bool.self, returning: [Bool].self) { group in for _ in 0..<20 { group.addTask { registry.acquire(123) } } var results: [Bool] = [] for await result in group { results.append(result) } return results } #expect(results.filter { $0 }.count == 1) #expect(registry.acquire(456)) registry.release(123) #expect(registry.acquire(123)) #expect(!registry.acquire(456)) } @Test func observerRegistrationsRetryTransientFailuresIndependently() { var tracker = AppThreadRegistrationTracker() #expect(tracker.needs("moved", windowID: 1)) tracker.record(.cannotComplete, notification: "moved", windowID: 1) #expect(tracker.needs("moved", windowID: 1)) tracker.record(.success, notification: "moved", windowID: 1) #expect(!tracker.needs("moved", windowID: 1)) #expect(tracker.needs("resized", windowID: 1)) #expect(tracker.needs("moved", windowID: 2)) tracker.record(.notificationUnsupported, notification: "resized", windowID: 1) #expect(!tracker.needs("resized", windowID: 1)) tracker.record(.notificationAlreadyRegistered, notification: "focused", windowID: nil) #expect(!tracker.needs("focused", windowID: nil)) tracker.remove(windowID: 1) #expect(tracker.needs("moved", windowID: 1)) #expect(tracker.needs("resized", windowID: 1)) #expect(!tracker.needs("focused", windowID: nil)) } @Test func responsivenessRequiresAnActualSuccessfulAXCall() { var tracker = AppThreadTimeoutTracker(threshold: 2) let first = AXCallActivity() first.record(.timedOut) first.record(.timedOut) #expect(tracker.observe(first) == [.unresponsive]) let noCalls = AXCallActivity() #expect(tracker.observe(noCalls).isEmpty) let caughtTimeout = AXCallActivity() caughtTimeout.record(.timedOut) #expect(tracker.observe(caughtTimeout).isEmpty) let success = AXCallActivity() success.record(nil) #expect(tracker.observe(success) == [.responsive]) #expect(tracker.observe(AXCallActivity()).isEmpty) } @Test func frameWriteCandidatesAreWindowSpecificAndTagRepeatedNotifications() { var tracker = AppThreadFrameWriteTracker() let id = UUID() let before = CGRect(x: 0, y: 0, width: 100, height: 100) let actual = CGRect(x: 10, y: 20, width: 120, height: 130) tracker.record(windowID: 1, writeID: id, before: before, actual: actual) #expect(tracker.match(windowID: 2, axis: .position, frame: actual) == .unattributed) #expect(tracker.match(windowID: 1, axis: .position, frame: actual) == .possiblySelfGenerated(id)) #expect(tracker.match(windowID: 1, axis: .position, frame: actual) == .possiblySelfGenerated(id)) #expect(tracker.match(windowID: 1, axis: .size, frame: actual) == .possiblySelfGenerated(id)) #expect(tracker.match(windowID: 1, axis: .size, frame: actual) == .possiblySelfGenerated(id)) #expect(tracker.hasCandidate(windowID: 1, axis: .size) == true) } @Test func mismatchedAndSupersededFrameCandidatesAreNotTagged() { var tracker = AppThreadFrameWriteTracker() let before = CGRect(x: 0, y: 0, width: 100, height: 100) let actual = CGRect(x: 10, y: 20, width: 120, height: 130) let other = CGRect(x: 15, y: 20, width: 120, height: 130) let first = UUID() let second = UUID() tracker.record(windowID: 1, writeID: first, before: before, actual: actual) #expect(tracker.match(windowID: 1, axis: .position, frame: other) == .unattributed) #expect(tracker.hasCandidate(windowID: 1, axis: .size) == false) tracker.record(windowID: 1, writeID: first, before: before, actual: actual) tracker.record(windowID: 1, writeID: second, before: actual, actual: other) #expect(tracker.match(windowID: 1, axis: .position, frame: other) == .possiblySelfGenerated(second)) tracker.record(windowID: 1, writeID: first, before: actual, actual: actual) #expect(tracker.hasCandidate(windowID: 1, axis: .position) == false) tracker.record(windowID: 1, writeID: first, before: before, actual: actual) tracker.clear(windowID: 1) #expect(tracker.hasCandidate(windowID: 1, axis: .size) == false) } @Test func frameWriteCandidateCoversClampedOrPartialWrites() { var tracker = AppThreadFrameWriteTracker() let before = CGRect(x: 0, y: 0, width: 100, height: 100) let requested = CGRect(x: 10, y: 20, width: 120, height: 130) let id = UUID() tracker.record(windowID: 1, writeID: id, before: before, actual: before, attempted: requested) #expect(tracker.match(windowID: 1, axis: .position, frame: before) == .possiblySelfGenerated(id)) #expect(tracker.match(windowID: 1, axis: .size, frame: before) == .possiblySelfGenerated(id)) let userChange = CGRect(x: 20, y: 20, width: 100, height: 100) #expect(tracker.match(windowID: 1, axis: .position, frame: userChange) == .unattributed) #expect(tracker.hasCandidate(windowID: 1, axis: .size) == false) } @Test func frameWriteCandidatesExpireAtBoundedDeadline() { var tracker = AppThreadFrameWriteTracker() let before = CGRect(x: 0, y: 0, width: 100, height: 100) let actual = CGRect(x: 10, y: 20, width: 120, height: 130) let id = UUID() let limit = AppThreadFrameWriteTracker.maximumAgeNanoseconds tracker.record(windowID: 1, writeID: id, before: before, actual: actual, now: 100) #expect( tracker.match(windowID: 1, axis: .position, frame: actual, now: 100 + limit - 1) == .possiblySelfGenerated(id)) #expect(tracker.match(windowID: 1, axis: .size, frame: actual, now: 100 + limit) == .unattributed) #expect(tracker.hasCandidate(windowID: 1, axis: .size, now: 100 + limit) == false) } private func execute( _ executor: AppThreadExecutor, _ operation: @escaping @Sendable () -> Value ) async throws -> Value { try await withCheckedThrowingContinuation { continuation in executor.submit( run: { continuation.resume(returning: operation()) }, cancel: { continuation.resume(throwing: AppThreadFailure.stopped) } ) } } @Test func executorsHaveStableIndependentOwnerThreads() async throws { let first = AppThreadExecutor(start: {}, stop: {}) let second = AppThreadExecutor(start: {}, stop: {}) defer { first.shutdown() second.shutdown() } let firstID = try await execute(first) { pthread_mach_thread_np(pthread_self()) } let secondID = try await execute(second) { pthread_mach_thread_np(pthread_self()) } let again = try await execute(first) { pthread_mach_thread_np(pthread_self()) } #expect(firstID == again) #expect(firstID != secondID) } @Test func shutdownCancelsQueuedJobsAndFinishesAfterInFlightJob() async throws { let (started, startedContinuation) = AsyncStream.makeStream() let (stopped, stoppedContinuation) = AsyncStream.makeStream() let gate = DispatchSemaphore(value: 0) let executor = AppThreadExecutor(start: {}, stop: { stoppedContinuation.yield(()) }) executor.submit( run: { startedContinuation.yield(()) gate.wait() }, cancel: { startedContinuation.finish() } ) var starts = started.makeAsyncIterator() #expect(await starts.next() != nil) let (cancelled, cancelledContinuation) = AsyncStream.makeStream() executor.submit( run: { cancelledContinuation.yield(false) }, cancel: { cancelledContinuation.yield(true) } ) executor.shutdown() executor.shutdown() var cancellations = cancelled.makeAsyncIterator() #expect(await cancellations.next() == true) gate.signal() var stops = stopped.makeAsyncIterator() #expect(await stops.next() != nil) await #expect(throws: AppThreadFailure.stopped) { try await execute(executor) { 1 } } } @Test func unexpectedRunLoopExitCancelsPendingWork() async { let (started, startedContinuation) = AsyncStream.makeStream() let (stopped, stoppedContinuation) = AsyncStream.makeStream() let (failed, failedContinuation) = AsyncStream.makeStream() let gate = DispatchSemaphore(value: 0) let executor = AppThreadExecutor( start: { startedContinuation.yield(()) gate.wait() }, stop: { stoppedContinuation.yield(()) }, failure: { failedContinuation.yield(()) } ) var starts = started.makeAsyncIterator() #expect(await starts.next() != nil) executor.submit(run: { CFRunLoopStop(CFRunLoopGetCurrent()) }, cancel: {}) let (cancelled, cancelledContinuation) = AsyncStream.makeStream() executor.submit( run: { cancelledContinuation.yield(false) }, cancel: { cancelledContinuation.yield(true) } ) gate.signal() var cancellations = cancelled.makeAsyncIterator() #expect(await cancellations.next() == true) var failures = failed.makeAsyncIterator() #expect(await failures.next() != nil) var stops = stopped.makeAsyncIterator() #expect(await stops.next() != nil) } @Test func shutdownBeforeStartupCompletesCancelsPendingWork() async { let (started, startedContinuation) = AsyncStream.makeStream() let (stopped, stoppedContinuation) = AsyncStream.makeStream() let gate = DispatchSemaphore(value: 0) let executor = AppThreadExecutor( start: { startedContinuation.yield(()) gate.wait() }, stop: { stoppedContinuation.yield(()) } ) var starts = started.makeAsyncIterator() #expect(await starts.next() != nil) let (cancelled, cancelledContinuation) = AsyncStream.makeStream() executor.submit( run: { cancelledContinuation.yield(false) }, cancel: { cancelledContinuation.yield(true) } ) executor.shutdown() var cancellations = cancelled.makeAsyncIterator() #expect(await cancellations.next() == true) gate.signal() var stops = stopped.makeAsyncIterator() #expect(await stops.next() != nil) } private final class WatchdogSchedulingQueue: Sendable { private struct State { var callbacks: [@Sendable () -> Void] = [] var cancellations: Set = [] } private let state = Mutex(State()) var scheduledCount: Int { state.withLock { $0.callbacks.count } } var pendingCount: Int { state.withLock { $0.callbacks.count - $0.cancellations.count } } func schedule(_ callback: @escaping @Sendable () -> Void) -> AXCallWatchdog.Cancellation { let index = state.withLock { let index = $0.callbacks.count $0.callbacks.append(callback) return index } return { [self] in state.withLock { _ = $0.cancellations.insert(index) } } } func fire(_ index: Int) { let callback = state.withLock { $0.callbacks[index] } callback() } } @Suite("AX watchdog idle scheduling", .timeLimit(.minutes(1))) struct AXWatchdogIdleSchedulingTests { @Test func idleSchedulesNothingAndCompletedCallsCancelEveryDeadline() { let queue = WatchdogSchedulingQueue() let reports = Mutex(0) let watchdog = AXCallWatchdog( schedule: { queue.schedule($0) }, overdue: { reports.withLock { $0 += 1 } }) #expect(queue.scheduledCount == 0) for _ in 0..<50 { let token = watchdog.begin() watchdog.end(token) } #expect(queue.scheduledCount == 50 && queue.pendingCount == 0) for index in 0..<50 { queue.fire(index) } #expect(reports.withLock { $0 } == 0) #expect(queue.scheduledCount == 50 && queue.pendingCount == 0) } @Test func overdueIsOneShotAndDoesNotScheduleAnotherDeadline() { let queue = WatchdogSchedulingQueue() let reports = Mutex(0) let watchdog = AXCallWatchdog( schedule: { queue.schedule($0) }, overdue: { reports.withLock { $0 += 1 } }) let token = watchdog.begin() queue.fire(0) queue.fire(0) watchdog.end(token) #expect(reports.withLock { $0 } == 1) #expect(queue.scheduledCount == 1 && queue.pendingCount == 0) } @Test func stopCancelsActiveDeadlineAndLateCallbacksCannotReportOrRearm() { let queue = WatchdogSchedulingQueue() let reports = Mutex(0) let watchdog = AXCallWatchdog( schedule: { queue.schedule($0) }, overdue: { reports.withLock { $0 += 1 } }) let token = watchdog.begin() watchdog.stop() watchdog.stop() #expect(queue.pendingCount == 0) queue.fire(0) watchdog.end(token) let afterStop = watchdog.begin() watchdog.end(afterStop) #expect(reports.withLock { $0 } == 0) #expect(queue.scheduledCount == 1) } @Test func replacingActiveCallCancelsOldDeadlineAndStaleEndDoesNotCancelNewOne() { let queue = WatchdogSchedulingQueue() let reports = Mutex(0) let watchdog = AXCallWatchdog( schedule: { queue.schedule($0) }, overdue: { reports.withLock { $0 += 1 } }) let old = watchdog.begin() let current = watchdog.begin() #expect(queue.pendingCount == 1) watchdog.end(old) queue.fire(0) #expect(queue.pendingCount == 1 && reports.withLock { $0 } == 0) watchdog.end(current) queue.fire(1) #expect(queue.pendingCount == 0 && reports.withLock { $0 } == 0) } @Test func deadlineFiringBeforeInstallationStillCancelsItsSource() { let cancellations = Mutex(0) let reports = Mutex(0) let watchdog = AXCallWatchdog( schedule: { action in action() return { cancellations.withLock { $0 += 1 } } }, overdue: { reports.withLock { $0 += 1 } }) let token = watchdog.begin() watchdog.end(token) #expect(cancellations.withLock { $0 } == 1) #expect(reports.withLock { $0 } == 1) } @Test func stopDuringDeadlineInstallationCancelsReturnedSource() { let owner = Mutex(nil) let queue = WatchdogSchedulingQueue() let reports = Mutex(0) let watchdog = AXCallWatchdog( schedule: { action in let current = owner.withLock { $0 } current?.stop() return queue.schedule(action) }, overdue: { reports.withLock { $0 += 1 } }) owner.withLock { $0 = watchdog } let token = watchdog.begin() watchdog.end(token) queue.fire(0) #expect(queue.scheduledCount == 1 && queue.pendingCount == 0) #expect(reports.withLock { $0 } == 0) owner.withLock { $0 = nil } } @Test func releaseCancelsDeadlineWithoutRetainingWatchdog() { let queue = WatchdogSchedulingQueue() weak var released: AXCallWatchdog? do { let watchdog = AXCallWatchdog( schedule: { queue.schedule($0) }, overdue: { Issue.record("Unexpected overdue after release") }) released = watchdog _ = watchdog.begin() } #expect(released == nil && queue.pendingCount == 0) queue.fire(0) #expect(queue.scheduledCount == 1) } @Test func nativeTimerFiresOnceAndCancellationPreventsQueuedDelivery() async throws { let queue = DispatchQueue(label: "parcel.tests.watchdog") let reports = Mutex(0) let (events, continuation) = AsyncStream.makeStream() let timer = AXWatchdogDeadline(deadline: 0.01, queue: queue) { reports.withLock { $0 += 1 } continuation.yield(()) } defer { timer.cancel() } try await waitForProcessEvent(events, name: "watchdog deadline") try await Task.sleep(for: .milliseconds(50)) #expect(reports.withLock { $0 } == 1) queue.suspend() let cancelled = AXWatchdogDeadline(deadline: 0.01, queue: queue) { reports.withLock { $0 += 1 } } cancelled.cancel() queue.resume() try await Task.sleep(for: .milliseconds(50)) #expect(reports.withLock { $0 } == 1) } }