Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078import CoreFoundationimport CoreGraphicsimport Darwinimport Foundationimport ParcelCoreimport Synchronizationimport 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..<AppThreadRegistrationBackoff.maximumAttempts { let delay = backoff.nextDelay(now: 0) #expect(delay != nil) } let exhausted = backoff.nextDelay(now: 0) #expect(exhausted == nil) }}
@Suite struct AppThreadSpeculativeTargetTests { private var window: AppThreadCreatedWindow { AppThreadCreatedWindow( windowID: 42, facts: WindowFacts(bundleID: "example.app", role: "AXWindow"), frame: CGRect(x: 10, y: 20, width: 300, height: 200), isOnScreen: true) } private var technology: AssistiveTechnology { AssistiveTechnology(voiceOver: false, switchControl: false) }
@Test func offscreenWindowsNeverConsumeATargetOrWriteFrames() throws { try expectNoSpeculativeWrite(isOnScreen: false, speculate: true) }
@Test func startupWindowsNeverConsumeATargetOrWriteFrames() throws { try expectNoSpeculativeWrite(isOnScreen: true, speculate: false) }
private func expectNoSpeculativeWrite(isOnScreen: Bool, speculate: Bool) throws { let snapshot = AppThreadCreatedWindow( windowID: window.windowID, facts: window.facts, frame: window.frame, isOnScreen: isOnScreen) let reads = Mutex(0) var writes = 0 let placed = try AppThreadSpeculativePlacement.place( snapshot, speculate: speculate, assistiveTechnology: technology, read: { _ in reads.withLock { $0 += 1 } return CGRect(x: 0, y: 0, width: 640, height: 480) }, write: { target in writes += 1; return target }) #expect(placed == snapshot) #expect(reads.withLock { $0 } == 0 && writes == 0) }
@Test func speculativeWriteReturnsTheActualFrameWhilePreservingTheVisibilityAndFacts() throws { let target = CGRect(x: 0, y: 0, width: 640, height: 480) let actual = CGRect(x: 0, y: 0, width: 700, height: 480) var writes: [CGRect] = [] let placed = try AppThreadSpeculativePlacement.place( window, speculate: true, assistiveTechnology: technology, read: { _ in target }, write: { value in writes.append(value); return actual }) #expect(writes == [target]) #expect(placed.windowID == window.windowID && placed.facts == window.facts) #expect(placed.isOnScreen && placed.frame == actual) }
@Test func unavailableAssistiveTechnologyDoesNotInvokeTheSynchronousTargetCallback() throws { let called = Mutex(false) let target = try AppThreadSpeculativePlacement.target(for: window, assistiveTechnology: nil) { _ in called.withLock { $0 = true } return CGRect(x: 0, y: 0, width: 640, height: 480) } #expect(target == nil) #expect(called.withLock { $0 } == false) }
@Test func callbackReceivesOnlyThePlatformSnapshotAndMayConservativelyDecline() throws { let expected = window let target = try AppThreadSpeculativePlacement.target(for: window, assistiveTechnology: technology) { value in #expect(value == expected) return nil } #expect(target == nil) }
@Test(arguments: [ CGRect(x: CGFloat.infinity, y: 0, width: 640, height: 480), CGRect(x: 0, y: 0, width: 0, height: 480), CGRect(x: 0, y: 0, width: 640, height: -1), CGRect(x: 0, y: 0, width: CGFloat.nan, height: 480), ]) func invalidSpeculativeGeometrySurfacesAnError(target: CGRect) { #expect(throws: AXPlatformError.unexpectedValue("Speculative window target")) { try AppThreadSpeculativePlacement.target(for: window, assistiveTechnology: technology) { _ in target } } }
@Test func cachedVoiceOverStateIsAcceptedWithoutAnyMainActorRead() throws { let target = CGRect(x: 0, y: 0, width: 640, height: 480) #expect( try AppThreadSpeculativePlacement.target( for: window, assistiveTechnology: AssistiveTechnology(voiceOver: true, switchControl: false), read: { _ in target }) == target) }}
@Test func reconciliationComparesAllWindowsForOnlyTheRequestedApplication() { let bounds = CGRect(x: 20, y: 30, width: 400, height: 300) let windows = [ WindowServer.Window(number: 3, pid: 42, bounds: .zero, layer: 1, isOnscreen: false), WindowServer.Window(number: 5, pid: 99, bounds: .zero, layer: 0, isOnscreen: true), WindowServer.Window(number: 1, pid: 42, bounds: bounds, layer: 0, isOnscreen: true), ] var requestedOptions: CGWindowListOption? let event = AppThreadWindowReconciler.event(pid: 42, axWindowIDs: [2, 1, 2]) { options in requestedOptions = options return windows } #expect(requestedOptions == .optionAll) guard case .reconciliation(let summary) = event else { Issue.record("Expected a reconciliation summary") return } #expect(summary.axWindowIDs == [1, 2]) #expect(summary.serverWindows.map(\.number) == [1, 3]) #expect(summary.serverWindows[0].bounds == bounds) #expect(summary.serverWindows[1].isOnscreen == false) #expect(summary.axOnly == [2]) #expect(summary.serverOnly == [3])}
@Test func reconciliationSurfacesWindowServerFailures() { let event = AppThreadWindowReconciler.event(pid: 42, axWindowIDs: [1]) { _ in throw WindowServer.ReadError.windowListUnavailable } #expect(event == .failure(.windowServer(WindowServer.ReadError.windowListUnavailable.description)))}
@Test func timeoutTrackerSignalsTransitionsOnce() { var tracker = AppThreadTimeoutTracker(threshold: 3) #expect(tracker.timedOut() == false) #expect(tracker.timedOut() == false) #expect(tracker.timedOut() == true) #expect(tracker.timedOut() == false) #expect(tracker.succeeded() == true) #expect(tracker.succeeded() == false) #expect(tracker.timedOut() == false) #expect(tracker.timedOut() == false) #expect(tracker.timedOut() == true)}
@Test func unrelatedFailureBreaksTimeoutStreakButDoesNotClaimRecovery() { var tracker = AppThreadTimeoutTracker(threshold: 2) #expect(tracker.timedOut() == false) tracker.otherFailure() #expect(tracker.timedOut() == false) #expect(tracker.timedOut() == true) tracker.otherFailure() #expect(tracker.timedOut() == false) #expect(tracker.timedOut() == false) #expect(tracker.succeeded() == true)}
@Test func processObserverReportsExitWithoutAccessibility() async throws { let (terminated, terminationContinuation) = AsyncStream<Void>.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<Void>.makeStream() let (exited, exitContinuation) = AsyncStream<Void>.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<Void>, 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<Value: Sendable>( _ 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<Void>.makeStream() let (stopped, stoppedContinuation) = AsyncStream<Void>.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<Bool>.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<Void>.makeStream() let (stopped, stoppedContinuation) = AsyncStream<Void>.makeStream() let (failed, failedContinuation) = AsyncStream<Void>.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<Bool>.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<Void>.makeStream() let (stopped, stoppedContinuation) = AsyncStream<Void>.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<Bool>.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<Int> = [] } 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<AXCallWatchdog?>(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<Void>.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) }}