From 60deb31b771735d54d904ce2dab1b7084c9b1a35 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 2 Nov 2026 23:22:18 -0500 Subject: [PATCH 01/11] Wait for callback process events Signed-off-by: Vincent Taverna --- Sources/ParcelApp/AppCallbackProcess.swift | 154 +++++++++++++++++--- Tests/ParcelAppTests/AppCallbackTests.swift | 62 +++++++- 2 files changed, 193 insertions(+), 23 deletions(-) diff --git a/Sources/ParcelApp/AppCallbackProcess.swift b/Sources/ParcelApp/AppCallbackProcess.swift index b6d72d0c..95383b78 100644 --- a/Sources/ParcelApp/AppCallbackProcess.swift +++ b/Sources/ParcelApp/AppCallbackProcess.swift @@ -42,6 +42,7 @@ final class AppCallbackProcess: Sendable { private let startedAt: ContinuousClock.Instant private let standardOutput: Int32 private let standardError: Int32 + private let eventQueue: Int32 private let signals: AppCallbackSignalOperations private let groupMembers: @Sendable (pid_t) throws -> [AppCallbackGroupMember] private let stopRequested = Mutex(false) @@ -50,13 +51,14 @@ final class AppCallbackProcess: Sendable { private init( pid: pid_t, startedAt: ContinuousClock.Instant, standardOutput: Int32, standardError: Int32, - signals: AppCallbackSignalOperations, + eventQueue: Int32, signals: AppCallbackSignalOperations, groupMembers: @escaping @Sendable (pid_t) throws -> [AppCallbackGroupMember] ) { self.pid = pid self.startedAt = startedAt self.standardOutput = standardOutput self.standardError = standardError + self.eventQueue = eventQueue self.signals = signals self.groupMembers = groupMembers } @@ -64,6 +66,7 @@ final class AppCallbackProcess: Sendable { deinit { Self.closeDescriptor(standardOutput) Self.closeDescriptor(standardError) + Self.closeDescriptor(eventQueue) } static func spawn( @@ -86,6 +89,8 @@ final class AppCallbackProcess: Sendable { closeDescriptor(error.write) if !transferred { closeDescriptor(error.read) } } + let eventQueue = try makeEventQueue(output: output.read, error: error.read) + defer { if !transferred { closeDescriptor(eventQueue) } } var actions: posix_spawn_file_actions_t? try check(posix_spawn_file_actions_init(&actions), "posix_spawn_file_actions_init") defer { destroy(posix_spawn_file_actions_destroy(&actions), "posix_spawn_file_actions_destroy") } @@ -118,22 +123,41 @@ final class AppCallbackProcess: Sendable { } transferred = true return AppCallbackProcess( - pid: pid, startedAt: startedAt, standardOutput: output.read, standardError: error.read, signals: signals, - groupMembers: groupMembers) + pid: pid, startedAt: startedAt, standardOutput: output.read, standardError: error.read, + eventQueue: eventQueue, signals: signals, groupMembers: groupMembers) } - func requestStop() { stopRequested.withLock { $0 = true } } + func requestStop() { + let wasRequested = stopRequested.withLock { + let previous = $0 + $0 = true + return previous + } + guard !wasRequested else { return } + do { + try Self.updateEventQueue( + eventQueue, + event: Self.event(ident: 1, filter: Int16(EVFILT_USER), flags: 0, notes: UInt32(NOTE_TRIGGER))) + } catch { Self.logCleanup(error) } + } func collect( timeout: Duration, onCollected: @escaping @Sendable (Swift.Result, Duration) -> Void = { _, _ in } + ) async throws -> Result { + try await collect(timeout: timeout, onWaiting: {}, onCollected: onCollected) + } + + func collect( + timeout: Duration, onWaiting: @escaping @Sendable () -> Void, + onCollected: @escaping @Sendable (Swift.Result, Duration) -> Void ) async throws -> Result { try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in - // poll and waitpid must not occupy Swift's cooperative executor. + // Blocking process and pipe waits must not occupy Swift's cooperative executor. let thread = Thread { let start = ContinuousClock.now - let result = Swift.Result { try self.collectOnThread(timeout: timeout) } + let result = Swift.Result { try self.collectOnThread(timeout: timeout, onWaiting: onWaiting) } onCollected(result, ContinuousClock.now - start) continuation.resume(with: result) } @@ -145,7 +169,7 @@ final class AppCallbackProcess: Sendable { } } - private func collectOnThread(timeout: Duration) throws -> Result { + private func collectOnThread(timeout: Duration, onWaiting: @Sendable () -> Void) throws -> Result { let deadline = startedAt.advanced(by: timeout) var status: Int32? var leaderOwned = true @@ -157,17 +181,21 @@ final class AppCallbackProcess: Sendable { var error = AppCallbackOutput() var outputOpen = true var errorOpen = true + var checkLeader = true do { + // Registration precedes the first readback so an exit cannot slip between observation and waiting. + try observeLeaderExit(leaderOwned: &leaderOwned) while true { - if status == nil { + if status == nil && checkLeader { + checkLeader = false var info = siginfo_t() - let waited = waitid(P_PID, id_t(pid), &info, WEXITED | WNOHANG | WNOWAIT) - if waited == -1 && errno != EINTR { + while waitid(P_PID, id_t(pid), &info, WEXITED | WNOHANG | WNOWAIT) == -1 { + if errno == EINTR { continue } let code = errno if code == ECHILD { leaderOwned = false } throw AppCallbackSystemFailure(operation: "waitid", code: code) } - if waited == 0 && info.si_pid == pid { + if info.si_pid == pid { // Keep the zombie leader waitable until its group is killed, preventing PID reuse. leaderExited = true try terminateGroup(leaderExited: true, leaderOwned: &leaderOwned) @@ -200,21 +228,20 @@ final class AppCallbackProcess: Sendable { if status == nil && leaderExitDeadline.map({ ContinuousClock.now >= $0 }) == true { throw AppCallbackSystemFailure(operation: "callback leader exit (\(pid))", code: ETIMEDOUT) } - if outputOpen { outputOpen = try drain(standardOutput, into: &output) } - if errorOpen { errorOpen = try drain(standardError, into: &error) } + if outputOpen { outputOpen = try drainObservedPipe(standardOutput, into: &output) } + if errorOpen { errorOpen = try drainObservedPipe(standardError, into: &error) } if let completion, status != nil, (!outputOpen && !errorOpen) || finalDrainDeadline.map({ ContinuousClock.now >= $0 }) == true { return Result(completion: completion, standardOutput: output, standardError: error) } - var descriptors = [ - pollfd(fd: outputOpen ? standardOutput : -1, events: Int16(POLLIN), revents: 0), - pollfd(fd: errorOpen ? standardError : -1, events: Int16(POLLIN), revents: 0), - ] - let ready = poll(&descriptors, nfds_t(descriptors.count), 10) - if ready == -1 && errno != EINTR { - throw AppCallbackSystemFailure(operation: "poll", code: errno) - } + let nextDeadline: ContinuousClock.Instant? = + if status != nil { finalDrainDeadline } else if completion != nil { leaderExitDeadline } else { + deadline + } + guard let nextDeadline else { preconditionFailure("Missing callback wait deadline") } + onWaiting() + checkLeader = try waitForEvents(until: nextDeadline) } } catch { var failures: [any Error] = [error] @@ -234,6 +261,55 @@ final class AppCallbackProcess: Sendable { } } + private func observeLeaderExit(leaderOwned: inout Bool) throws { + var event = Self.event( + ident: UInt64(pid), filter: Int16(EVFILT_PROC), flags: UInt16(EV_ADD | EV_ONESHOT), notes: NOTE_EXIT) + while kevent64(eventQueue, &event, 1, nil, 0, 0, nil) == -1 { + if errno == EINTR { continue } + let code = errno + // A callback can already be a zombie when collection starts. Verify ownership without reaping it. + if code == ESRCH, try leaderHasExited(leaderOwned: &leaderOwned) { return } + throw AppCallbackSystemFailure(operation: "observe callback leader exit", code: code) + } + } + + private func waitForEvents(until deadline: ContinuousClock.Instant) throws -> Bool { + var events = [kevent64_s](repeating: kevent64_s(), count: 4) + while true { + let remaining = max(.zero, ContinuousClock.now.duration(to: deadline)).components + let nanoseconds = (remaining.attoseconds + 999_999_999) / 1_000_000_000 + var timeout = timespec( + tv_sec: Int(remaining.seconds + nanoseconds / 1_000_000_000), + tv_nsec: Int(nanoseconds % 1_000_000_000)) + let count = events.withUnsafeMutableBufferPointer { + kevent64(eventQueue, nil, 0, $0.baseAddress, Int32($0.count), 0, &timeout) + } + guard count >= 0 else { + if errno == EINTR { continue } + throw AppCallbackSystemFailure(operation: "wait for callback events", code: errno) + } + var leaderExited = false + for event in events.prefix(Int(count)) { + if event.flags & UInt16(EV_ERROR) != 0 && event.data != 0 { + throw AppCallbackSystemFailure(operation: "callback event", code: Int32(event.data)) + } + if event.filter == Int16(EVFILT_PROC) && event.fflags & NOTE_EXIT != 0 { leaderExited = true } + } + return leaderExited + } + } + + private func drainObservedPipe(_ descriptor: Int32, into output: inout AppCallbackOutput) throws -> Bool { + let open = try drain(descriptor, into: &output) + if !open { + // EOF is level-triggered too; remove it or closed pipes would spin while the leader remains alive. + try Self.updateEventQueue( + eventQueue, + event: Self.event(ident: UInt64(descriptor), filter: Int16(EVFILT_READ), flags: UInt16(EV_DELETE))) + } + return open + } + private func terminateGroup(leaderExited: Bool = false, leaderOwned: inout Bool) throws { var failures: [any Error] = [] do { @@ -357,6 +433,40 @@ final class AppCallbackProcess: Sendable { return true } + private static func makeEventQueue(output: Int32, error: Int32) throws -> Int32 { + let descriptor = kqueue() + guard descriptor >= 0 else { throw AppCallbackSystemFailure(operation: "callback kqueue", code: errno) } + do { + guard fcntl(descriptor, F_SETFD, FD_CLOEXEC) != -1 else { + throw AppCallbackSystemFailure(operation: "callback kqueue close-on-exec", code: errno) + } + try updateEventQueue( + descriptor, + event: event(ident: 1, filter: Int16(EVFILT_USER), flags: UInt16(EV_ADD | EV_CLEAR))) + for pipe in [output, error] { + try updateEventQueue( + descriptor, + event: event(ident: UInt64(pipe), filter: Int16(EVFILT_READ), flags: UInt16(EV_ADD))) + } + return descriptor + } catch { + closeDescriptor(descriptor) + throw error + } + } + + private static func event(ident: UInt64, filter: Int16, flags: UInt16, notes: UInt32 = 0) -> kevent64_s { + kevent64_s(ident: ident, filter: filter, flags: flags, fflags: notes, data: 0, udata: 0, ext: (0, 0)) + } + + private static func updateEventQueue(_ descriptor: Int32, event: kevent64_s) throws { + var event = event + while kevent64(descriptor, &event, 1, nil, 0, 0, nil) == -1 { + if errno == EINTR { continue } + throw AppCallbackSystemFailure(operation: "update callback events", code: errno) + } + } + private static func makePipe() throws -> (read: Int32, write: Int32) { var descriptors: [Int32] = [0, 0] guard pipe(&descriptors) == 0 else { throw AppCallbackSystemFailure(operation: "pipe", code: errno) } @@ -401,7 +511,7 @@ final class AppCallbackProcess: Sendable { private static func closeDescriptor(_ descriptor: Int32) { if Darwin.close(descriptor) == -1 { - logCleanup(AppCallbackSystemFailure(operation: "close callback pipe", code: errno)) + logCleanup(AppCallbackSystemFailure(operation: "close callback descriptor", code: errno)) } } diff --git a/Tests/ParcelAppTests/AppCallbackTests.swift b/Tests/ParcelAppTests/AppCallbackTests.swift index f1b46ec0..71071f7d 100644 --- a/Tests/ParcelAppTests/AppCallbackTests.swift +++ b/Tests/ParcelAppTests/AppCallbackTests.swift @@ -1,4 +1,5 @@ import Darwin +import Dispatch import Foundation import ParcelConfig import ParcelEngine @@ -316,7 +317,9 @@ struct AppCallbackTests { let started = directory.appendingPathComponent("started") let process = try AppCallbackProcess.spawn( arguments: [ - "/bin/sh", "-c", "printf '%s\\n' \"$$\" > \"$1\"; exit 7", "callback", started.path, + "/bin/sh", "-c", + "printf '%s\\n' \"$$\" > \"$1\"; printf already-exited; printf already-exited-error >&2; exit 7", + "callback", started.path, ], environment: ["PATH": "/usr/bin:/bin", "HOME": directory.path, "LANG": "C"]) var collected = false do { @@ -335,6 +338,8 @@ struct AppCallbackTests { collected = true let result = try await process.collect(timeout: .seconds(3)) #expect(result.completion == .exited(7)) + #expect(result.standardOutput.tail() == "already-exited") + #expect(result.standardError.tail() == "already-exited-error") #expect(processIsGone(pid)) #expect(groupIsGone(pid)) } catch { @@ -656,6 +661,61 @@ struct AppCallbackTests { try await expectGroupGone((leader: pid, child: pid)) } + @Test(arguments: [false, true]) + func silentCallbacksBlockWithoutPollingAndStopWakesPromptly(closePipes: Bool) async throws { + let arguments = + if closePipes { ["/bin/sh", "-c", "exec 1>&- 2>&-; exec /bin/sleep 600"] } else { ["/bin/sleep", "600"] } + let process = try AppCallbackProcess.spawn(arguments: arguments, environment: [:]) + let pid = process.processIdentifier + let waits = Mutex(0) + let stoppedAt = Mutex(nil) + let stopElapsed = Mutex(nil) + let result = try await process.collect( + timeout: .seconds(30), + onWaiting: { + let firstWait = waits.withLock { + $0 += 1 + return $0 == 1 + } + if firstWait { + // Schedule stop independently of the cooperative pool and measure it on the collecting thread. + DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .milliseconds(100)) { + stoppedAt.withLock { $0 = ContinuousClock.now } + process.requestStop() + } + } + }, + onCollected: { _, _ in + let now = ContinuousClock.now + stopElapsed.withLock { $0 = stoppedAt.withLock { $0.map { now - $0 } } } + }) + #expect(result.completion == .stopped) + #expect(result.standardOutput.bytes.isEmpty) + #expect(result.standardError.bytes.isEmpty) + // Each pipe's EOF, stop, and leader exit may wake once; silence must not add recurring waits. + #expect(waits.withLock { $0 } <= 4) + #expect(try #require(stopElapsed.withLock { $0 }) < .seconds(1)) + try await expectGroupGone((leader: pid, child: pid)) + } + + @Test func closedPipesDoNotFinishCollectionBeforeTheLeaderExits() async throws { + let process = try AppCallbackProcess.spawn( + arguments: ["/bin/sh", "-c", "exec 1>&- 2>&-; /bin/sleep 0.1; exit 7"], environment: [:]) + let result = try await process.collect(timeout: .seconds(3)) + #expect(result.completion == .exited(7)) + #expect(result.standardOutput.bytes.isEmpty) + #expect(result.standardError.bytes.isEmpty) + try await expectGroupGone((leader: process.processIdentifier, child: process.processIdentifier)) + } + + @Test func stopRequestedImmediatelyBeforeTheNativeWaitIsNotLost() async throws { + let process = try AppCallbackProcess.spawn(arguments: ["/bin/sleep", "600"], environment: [:]) + let result = try await process.collect( + timeout: .seconds(30), onWaiting: { process.requestStop() }, onCollected: { _, _ in }) + #expect(result.completion == .stopped) + try await expectGroupGone((leader: process.processIdentifier, child: process.processIdentifier)) + } + @Test func cancellationBeforeCollectionStillStopsAndReapsTheChild() async throws { let process = try AppCallbackProcess.spawn(arguments: ["/bin/sleep", "600"], environment: [:]) let collection = Task { try await process.collect(timeout: .seconds(30)) } -- knotmirror 0.0.1 From 70295b4b53399ec65ce2560259011c0e793c0c1c Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 2 Nov 2026 23:27:06 -0500 Subject: [PATCH 02/11] Cache per-window resize fits Remember verified grid steps and minimums on the owning app thread, invalidate missed hints, and bound ordinary fitting to 11 size writes. A plateau ends the regular search; one lower-bound probe distinguishes a minimum from a larger grid. Repeat only unchanged correction replies: a one-write-late reply can otherwise certify the preceding candidate and leave a frame overflowing its tile. The delayed-grid regression covers that necessary confirmation; cached repeats need at most two size writes. Signed-off-by: Vincent Taverna --- Sources/ParcelPlatform/AppFrameWrites.swift | 123 +++++++++++++++--- Tests/Lanes/unit.txt | 5 + .../AppFrameWriteTests.swift | 116 +++++++++++++++-- 3 files changed, 218 insertions(+), 26 deletions(-) diff --git a/Sources/ParcelPlatform/AppFrameWrites.swift b/Sources/ParcelPlatform/AppFrameWrites.swift index 8ea83a6d..e9d15ea7 100644 --- a/Sources/ParcelPlatform/AppFrameWrites.swift +++ b/Sources/ParcelPlatform/AppFrameWrites.swift @@ -163,6 +163,7 @@ final class AppThreadFrameWriter { } private var active: [CGWindowID: Motion] = [:] private var generations: [CGWindowID: Generation] = [:] + private var sizeFits: [CGWindowID: FrameSizeFit] = [:] private var enhancedUI: EnhancedUIBurstGuard init(onEnhancedUIDisableUnsupported: @escaping (AXPlatformError) -> Void = EnhancedUIBurstGuard.reportUnsupported) { @@ -207,6 +208,7 @@ final class AppThreadFrameWriter { func forget(_ id: CGWindowID, application: Application) throws { // A queued old write must not acquire a recycled window ID. + sizeFits[id] = nil try cancel(windowIDs: [id], application: application) } @@ -259,9 +261,11 @@ final class AppThreadFrameWriter { if request.phase == .final { AppThreadWriteTrace.frameRead(window: request.windowID, reason: "final") } + var fit = sizeFits[request.windowID] ?? FrameSizeFit() actual = try executeMotionFrameWrite( request.target, window: window, current: current, final: request.phase == .final, - preservingSize: request.preservesSize) + preservingSize: request.preservesSize, fit: &fit) + sizeFits[request.windowID] = fit } if request.phase == .ongoing { active[request.windowID] = Motion( @@ -273,6 +277,7 @@ final class AppThreadFrameWriter { } receipts.append(AppThreadFrameWriteReceipt(request, before: before, actual: actual, error: nil)) } catch { + sizeFits[request.windowID] = nil if attemptedWrite, let resolved { do { actual = try resolved.frame } catch let readError { cleanupErrors.append(readError) } } @@ -377,8 +382,58 @@ struct EnhancedUIBurstGuard { func executeMotionFrameWrite( _ target: CGRect, window: Window, current: CGRect, final: Bool, preservingSize: Bool = false ) throws -> CGRect? { - let resized = !preservingSize && current.size != target.size - if resized { try window.setSize(target.size) } + var fit = FrameSizeFit() + return try executeMotionFrameWrite( + target, window: window, current: current, final: final, preservingSize: preservingSize, fit: &fit) +} + +struct FrameSizeFit { + struct Axis { + let anchor: CGFloat + let step: CGFloat? + let minimum: Bool + + func prediction(_ limit: CGFloat) -> (request: CGFloat, actual: CGFloat)? { + if minimum { return limit < anchor ? (limit, anchor) : nil } + guard let step else { return nil } + let size = anchor + ((limit - anchor) / step).rounded(.down) * step + return size > 0 ? (size, size) : nil + } + } + + var width: Axis? + var height: Axis? + + func matches(_ actual: CGSize, target: CGSize) -> Bool { + let w = width?.prediction(target.width) + let h = height?.prediction(target.height) + return (w == nil || w?.actual == actual.width) && (h == nil || h?.actual == actual.height) + } + + func accepts(_ actual: CGSize, target: CGSize) -> Bool { + matches(actual, target: target) + && (actual.width <= target.width || width?.prediction(target.width)?.actual == actual.width) + && (actual.height <= target.height || height?.prediction(target.height)?.actual == actual.height) + } + + func prediction(_ size: CGSize) -> (request: CGSize, actual: CGSize) { + let w = width?.prediction(size.width) + let h = height?.prediction(size.height) + return ( + CGSize(width: w?.request ?? size.width, height: h?.request ?? size.height), + CGSize(width: w?.actual ?? size.width, height: h?.actual ?? size.height) + ) + } +} + +private func executeMotionFrameWrite( + _ target: CGRect, window: Window, current: CGRect, final: Bool, preservingSize: Bool, + fit: inout FrameSizeFit +) throws -> CGRect? { + let prediction = fit.prediction(target.size) + let requested = final && !preservingSize ? prediction.request : target.size + let resized = !preservingSize && current.size != requested + if resized { try window.setSize(requested) } if resized || current.origin != target.origin { try window.setPosition(target.origin) } if final { var actual = try window.frame @@ -389,7 +444,11 @@ func executeMotionFrameWrite( } return actual } - if actual.size != target.size { + if actual.size != prediction.actual { + actual = try readAfterSizeWrite(requested, origin: target.origin, window: window) + } + if !fit.matches(actual.size, target: target.size) { + fit = FrameSizeFit() actual = try readAfterSizeWrite(target.size, origin: target.origin, window: window) } // The motion cache records requests, not what the app accepted. @@ -400,7 +459,17 @@ func executeMotionFrameWrite( actual = try readAfterSizeWrite(target.size, origin: target.origin, window: window) } } - return try fitFinalFrame(target, actual: actual, window: window) + if !fit.matches(actual.size, target: target.size) { fit = FrameSizeFit() } + if fit.accepts(actual.size, target: target.size), fit.width != nil || fit.height != nil { return actual } + // Settle a large stale reply before using its overshoot to choose any probe. + if actual.width - target.width > 32 || actual.height - target.height > 32 { + for _ in 0..<2 { + let next = try readAfterSizeWrite(target.size, origin: target.origin, window: window) + if next.size == target.size { return next } + actual = next + } + } + return try fitFinalFrame(target, actual: actual, window: window, fit: &fit) } if resized, try window.size != target.size { try window.setSize(target.size) } return nil @@ -417,35 +486,38 @@ private func readAfterSizeWrite( } private func fitFinalFrame( - _ target: CGRect, actual: CGRect, window: Window + _ target: CGRect, actual: CGRect, window: Window, fit: inout FrameSizeFit ) throws -> CGRect { guard actual.width > target.width || actual.height > target.height else { return actual } var width = FrameSizeFitSearch(limit: target.width, actual: actual.width) var height = FrameSizeFitSearch(limit: target.height, actual: actual.height) var actual = actual - // A lagging AX reply is not an app's resize increment. Probe outward from the target in bounded steps. for attempt in 0..<8 { let nextWidth = width.next let nextHeight = height.next guard nextWidth != nil || nextHeight != nil else { break } let size = CGSize(width: nextWidth ?? width.best, height: nextHeight ?? height.best) - actual = try confirmedSizeCorrection(size, origin: target.origin, window: window, attempt: attempt) + actual = try sizeCorrection( + size, previous: actual.size, origin: target.origin, window: window, attempt: attempt) width.observe(request: size.width, actual: actual.width) height.observe(request: size.height, actual: actual.height) } let best = CGSize(width: width.best, height: height.best) if width.needsRestore || height.needsRestore { - actual = try confirmedSizeCorrection(best, origin: target.origin, window: window, attempt: 8) + actual = try sizeCorrection(best, previous: actual.size, origin: target.origin, window: window, attempt: 8) } + fit.width = width.learned ?? fit.width + fit.height = height.learned ?? fit.height return actual } -private func confirmedSizeCorrection( - _ size: CGSize, origin: CGPoint, window: Window, attempt: Int +private func sizeCorrection( + _ size: CGSize, previous: CGSize, origin: CGPoint, window: Window, attempt: Int ) throws -> CGRect { let first = try readAfterSizeWrite(size, origin: origin, window: window) window.recordSizeCorrection(size, actual: first, attempt: attempt * 2) - // Repeat the same candidate so a one-write-late reply cannot be paired with a different request. + guard first.size == previous else { return first } + // Only an unchanged reply can still belong to the preceding size write. let confirmed = try readAfterSizeWrite(size, origin: origin, window: window) window.recordSizeCorrection(size, actual: confirmed, attempt: attempt * 2 + 1) return confirmed @@ -454,34 +526,55 @@ private func confirmedSizeCorrection( private struct FrameSizeFitSearch { let limit: CGFloat private var contained: CGFloat? + private var containedActual: CGFloat? private var rejected: CGFloat - private var step: CGFloat = 1 + private var rejectedActual: CGFloat + private var step: CGFloat = 16 private var lastRequest: CGFloat + private var minimumProbe = false + private var minimum: CGFloat? init(limit: CGFloat, actual: CGFloat) { self.limit = limit contained = actual <= limit ? limit : nil + containedActual = actual <= limit ? actual : nil rejected = limit + rejectedActual = actual lastRequest = limit } var best: CGFloat { contained ?? limit } var needsRestore: Bool { lastRequest != best } + var learned: FrameSizeFit.Axis? { + if let minimum { return FrameSizeFit.Axis(anchor: minimum, step: nil, minimum: true) } + guard let contained, let containedActual, rejected - contained <= 1, + rejectedActual > limit, rejectedActual > containedActual + else { return nil } + return FrameSizeFit.Axis(anchor: containedActual, step: rejectedActual - containedActual, minimum: false) + } + var next: CGFloat? { + if minimum != nil { return nil } if let contained { return rejected - contained > 1 ? (contained + rejected) / 2 : nil } - let candidate = rejected - step - return candidate > 0 ? candidate : nil + if minimumProbe { return 1 } + return max(1, rejected - step) } mutating func observe(request: CGFloat, actual: CGFloat) { lastRequest = request if actual <= limit { contained = request + containedActual = actual + } else if request == 1 { + minimum = actual } else { + // A plateau may be a large grid, not a minimum. One lower-bound readback distinguishes them. + minimumProbe = actual == rejectedActual rejected = request + rejectedActual = actual step *= 2 } } diff --git a/Tests/Lanes/unit.txt b/Tests/Lanes/unit.txt index acf4df70..6b6870c4 100644 --- a/Tests/Lanes/unit.txt +++ b/Tests/Lanes/unit.txt @@ -602,6 +602,8 @@ ParcelEngineTests.unknownModesAreRejectedAtEveryEngineEntryPoint() ParcelPlatformTests.aFailedEnhancedUIGuardCannotBeSkippedByTheNextWindow(error:) ParcelPlatformTests.aFailedInitialFrameReadDoesNotRetryOrTouchEnhancedUI() ParcelPlatformTests.aFailedWriteCanRetryWithoutRetiringOwnership() +ParcelPlatformTests.aLargeResizeGridPlateauIsNotMistakenForAMinimum() +ParcelPlatformTests.aOneWriteLateGridReplyCannotCertifyThePreviousCandidate() ParcelPlatformTests.aReadOnlyEnhancedUIAttributeDoesNotBlockVerifiedFrameWrites() ParcelPlatformTests.accessibilityStatusUsesCurrentTrustAndPreviousEvidence(isTrusted:wasPreviouslyGranted:expected:) ParcelPlatformTests.activationDuringBatchRestoresBeforeNextWindow() @@ -652,6 +654,7 @@ ParcelPlatformTests.finalRepairsPositionChangedByTheSecondSizeWrite() ParcelPlatformTests.finalRetriesTransientPositionRefusalBeforeRestoringEnhancedUI() ParcelPlatformTests.finalSizeCorrectionFailureRetainsRealFrameAndRestoresEnhancedUI() ParcelPlatformTests.finalSizeCorrectionRestoresPositionChangedByNativeResize() +ParcelPlatformTests.forgettingAWindowDropsItsLearnedGrid() ParcelPlatformTests.frameWriteCandidateCoversClampedOrPartialWrites() ParcelPlatformTests.frameWriteCandidatesAreWindowSpecificAndTagRepeatedNotifications() ParcelPlatformTests.frameWriteCandidatesExpireAtBoundedDeadline() @@ -662,6 +665,7 @@ ParcelPlatformTests.frameWriteReportsDisableAndRestoreFailures() ParcelPlatformTests.frameWriteRestoresAfterUncertainDisable() ParcelPlatformTests.frameWriteRestoresEnhancedUIAndRechecksSize() ParcelPlatformTests.identifiedSnapshotsReadEachElementOnceAndNeverPublishZeroWindowIDs() +ParcelPlatformTests.learnedMinimumStopsRepeatedProbesAndIsInvalidatedWhenItChanges() ParcelPlatformTests.mapsAccessibilityErrors(error:expected:) ParcelPlatformTests.mismatchedAndSupersededFrameCandidatesAreNotTagged() ParcelPlatformTests.missingWindowServerEntryIsNotOnScreen() @@ -685,6 +689,7 @@ ParcelPlatformTests.reconciliationSurfacesWindowServerFailures() ParcelPlatformTests.rejectsEmptyDisplayID() ParcelPlatformTests.rejectsMalformedDisplaySpaces() ParcelPlatformTests.rejectsMissingAndMalformedWindowFields() +ParcelPlatformTests.repeatedGridFittingUsesTheLearnedStepAndInvalidatesOnAMiss(roundsUp:height:) ParcelPlatformTests.resizedFrameChecksSizeTwice() ParcelPlatformTests.responsivenessRequiresAnActualSuccessfulAXCall() ParcelPlatformTests.roundedOngoingMotionOnlyFitsItsFinalReadback() diff --git a/Tests/ParcelPlatformTests/AppFrameWriteTests.swift b/Tests/ParcelPlatformTests/AppFrameWriteTests.swift index fe5b3dce..bb5f2e98 100644 --- a/Tests/ParcelPlatformTests/AppFrameWriteTests.swift +++ b/Tests/ParcelPlatformTests/AppFrameWriteTests.swift @@ -196,7 +196,7 @@ private func write( let result = write(writer, probe, [request(phase: .final)]) #expect(probe.rectangle.origin == request().target.origin) #expect(result.windows.first?.actual == request().target) - #expect(probe.writtenSizes.count <= 20) + #expect(probe.writtenSizes.count <= 11) #expect(probe.operations.last == "position") #expect(probe.enabled) } @@ -389,7 +389,7 @@ private func snappedSize(_ size: CGSize, roundsUp: Bool = false) -> CGSize { #expect(receipt.error == nil) #expect(receipt.actual == CGRect(x: 16, y: 54, width: 1474, height: 847)) #expect(probe.writtenSizes.filter { $0.height != target.height }.isEmpty) - #expect(probe.writtenSizes.count <= 20) + #expect(probe.writtenSizes.count <= 11) #expect(probe.toggles == [false, true]) } @@ -404,7 +404,100 @@ func finalGridReadbackChoosesTheLargestContainedNativeSize(roundsUp: Bool, offse #expect(actual.width <= target.width && actual.height <= target.height) #expect(target.width - actual.width < 7) #expect(target.height - actual.height < 14) - #expect(probe.writtenSizes.count <= 20) + #expect(probe.writtenSizes.count <= 11) +} + +@Test(arguments: [false, true], [854, 856]) +func repeatedGridFittingUsesTheLearnedStepAndInvalidatesOnAMiss(roundsUp: Bool, height: Int) throws { + let probe = BurstWriteProbe() + probe.sizeTransform = { snappedSize($0, roundsUp: roundsUp) } + let writer = AppThreadFrameWriter() + for generation in 1...4 { + let target = CGRect(x: 16, y: 54, width: 1480 + generation * 7, height: height + generation * 14) + let count = probe.writtenSizes.count + let result = write( + writer, probe, + [AppThreadFrameWrite(windowID: 1, target: target, generation: UInt64(generation), phase: .final)]) + let actual = try #require(result.windows.first?.actual) + #expect(actual.width <= target.width && target.width - actual.width < 7) + #expect(actual.height <= target.height && target.height - actual.height < 14) + #expect(probe.writtenSizes.count - count <= (generation == 1 ? 11 : 2)) + } + probe.sizeTransform = { size in + CGSize( + width: 2 + ((size.width - 2) / 5).rounded(.up) * 5, + height: 3 + ((size.height - 3) / 9).rounded(.up) * 9) + } + let target = CGRect(x: 16, y: 54, width: 1518, height: 913) + let changed = write( + writer, probe, [AppThreadFrameWrite(windowID: 1, target: target, generation: 5, phase: .final)]) + let actual = try #require(changed.windows.first?.actual) + #expect(actual.width <= target.width && target.width - actual.width < 5) + #expect(actual.height <= target.height && target.height - actual.height < 9) + let count = probe.writtenSizes.count + let next = target.offsetBy(dx: 1, dy: 1) + let result = write( + writer, probe, [AppThreadFrameWrite(windowID: 1, target: next, generation: 6, phase: .final)]) + #expect(result.windows.first?.actual == actual.offsetBy(dx: 1, dy: 1)) + #expect(probe.writtenSizes.count - count <= 2) +} + +@Test func aOneWriteLateGridReplyCannotCertifyThePreviousCandidate() throws { + let probe = BurstWriteProbe() + probe.sizeTransform = { snappedSize($0, roundsUp: true) } + probe.sizeWriteDelay = 1 + let target = CGRect(x: 16, y: 54, width: 1480, height: 856) + let actual = try executeFrameWrite( + target, window: probe, application: probe, assistiveTechnology: noAssistiveTechnology) + #expect(actual == CGRect(x: 16, y: 54, width: 1474, height: 847)) + #expect(probe.writtenSizes.count <= 16) + #expect(probe.corrections.contains { $0.attempt % 2 == 1 }) +} + +@Test func learnedMinimumStopsRepeatedProbesAndIsInvalidatedWhenItChanges() throws { + let probe = BurstWriteProbe() + probe.sizeTransform = { CGSize(width: max(500, $0.width), height: max(400, $0.height)) } + let writer = AppThreadFrameWriter() + for generation in 1...3 { + let target = CGRect(x: 16, y: 54, width: 361 + generation, height: 300 + generation) + let count = probe.writtenSizes.count + let result = write( + writer, probe, + [AppThreadFrameWrite(windowID: 1, target: target, generation: UInt64(generation), phase: .final)]) + #expect(result.windows.first?.actual?.size == CGSize(width: 500, height: 400)) + #expect(probe.writtenSizes.count - count <= (generation == 1 ? 11 : 2)) + } + probe.sizeTransform = { $0 } + let target = CGRect(x: 16, y: 54, width: 365, height: 305) + let result = write( + writer, probe, [AppThreadFrameWrite(windowID: 1, target: target, generation: 4, phase: .final)]) + #expect(result.windows.first?.actual == target) +} + +@Test func forgettingAWindowDropsItsLearnedGrid() throws { + let probe = BurstWriteProbe() + probe.sizeTransform = { snappedSize($0) } + let writer = AppThreadFrameWriter() + let target = CGRect(x: 16, y: 54, width: 1480, height: 856) + _ = write(writer, probe, [AppThreadFrameWrite(windowID: 1, target: target, generation: 1, phase: .final)]) + try writer.forget(1, application: probe) + probe.sizeTransform = { $0 } + let count = probe.writtenSizes.count + let next = target.offsetBy(dx: 1, dy: 1) + let result = write( + writer, probe, [AppThreadFrameWrite(windowID: 1, target: next, generation: 2, phase: .final)]) + #expect(result.windows.first?.actual == next) + #expect(probe.writtenSizes.count - count == 1) +} + +@Test func aLargeResizeGridPlateauIsNotMistakenForAMinimum() throws { + let probe = BurstWriteProbe() + probe.sizeTransform = { CGSize(width: max(64, ($0.width / 64).rounded(.up) * 64), height: $0.height) } + let target = CGRect(x: 16, y: 54, width: 191, height: 400) + let actual = try executeFrameWrite( + target, window: probe, application: probe, assistiveTechnology: noAssistiveTechnology) + #expect(actual.width == 128) + #expect(actual.height == target.height) } @Test func roundedOngoingMotionOnlyFitsItsFinalReadback() throws { @@ -445,11 +538,12 @@ func delayedResizeCannotTurnStaleOversizingIntoATinyRequest(delay: Int, nativeGr #expect(actual.width <= target.width && target.width - actual.width < 7) #expect(actual.height <= target.height && target.height - actual.height < 14) #expect(probe.writtenSizes.allSatisfy { $0.width >= target.width - 7 }) - #expect(probe.writtenSizes.count <= 20) - #expect(!probe.corrections.isEmpty) - for pair in stride(from: 0, to: probe.corrections.count, by: 2) { - #expect(probe.corrections[pair].requested == probe.corrections[pair + 1].requested) - #expect(probe.corrections[pair + 1].attempt == probe.corrections[pair].attempt + 1) + #expect(probe.writtenSizes.count <= 11) + #expect(probe.writtenSizes.prefix(delay + 1).allSatisfy { $0 == target.size }) + for index in probe.corrections.indices where probe.corrections[index].attempt % 2 == 1 { + let previous = probe.corrections[index - 1] + #expect(previous.requested == probe.corrections[index].requested) + #expect(probe.corrections[index].attempt == previous.attempt + 1) } #expect(probe.enabled) } @@ -463,7 +557,7 @@ func delayedResizeCannotTurnStaleOversizingIntoATinyRequest(delay: Int, nativeGr target, window: probe, application: probe, assistiveTechnology: noAssistiveTechnology) #expect(actual.size == CGSize(width: 1480, height: 854)) #expect(probe.writtenSizes.suffix(2) == [target.size, target.size]) - #expect(probe.writtenSizes.count <= 20) + #expect(probe.writtenSizes.count <= 11) #expect(probe.enabled) } @@ -474,7 +568,7 @@ func delayedResizeCannotTurnStaleOversizingIntoATinyRequest(delay: Int, nativeGr let actual = try executeFrameWrite( target, window: probe, application: probe, assistiveTechnology: noAssistiveTechnology) #expect(actual == CGRect(x: 16, y: 54, width: 500, height: 400)) - #expect(probe.writtenSizes.count <= 20) + #expect(probe.writtenSizes.count <= 11) #expect(probe.writtenSizes.allSatisfy { $0.width > 0 && $0.height > 0 }) } @@ -502,7 +596,7 @@ func nativeMinimumOnOneAxisDoesNotPreventFittingTheOther(widthHasMinimum: Bool) target, window: probe, application: probe, assistiveTechnology: noAssistiveTechnology) #expect(actual.origin == target.origin) #expect(actual.size == CGSize(width: widthHasMinimum ? 1500 : 1474, height: widthHasMinimum ? 847 : 900)) - #expect(probe.writtenSizes.count <= 20) + #expect(probe.writtenSizes.count <= 11) } @Test func finalSizeCorrectionFailureRetainsRealFrameAndRestoresEnhancedUI() throws { -- knotmirror 0.0.1 From 20b2cf05ced2e886253164ca08ce5b80e3c47994 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 2 Nov 2026 23:27:38 -0500 Subject: [PATCH 03/11] Drop activity baselines when apps exit Signed-off-by: Vincent Taverna --- Sources/ParcelEngine/EngineEvents.swift | 6 ++- .../ActivityBaselineRegressionTests.swift | 37 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/Sources/ParcelEngine/EngineEvents.swift b/Sources/ParcelEngine/EngineEvents.swift index fc4c22a2..eebd65a6 100644 --- a/Sources/ParcelEngine/EngineEvents.swift +++ b/Sources/ParcelEngine/EngineEvents.swift @@ -121,8 +121,10 @@ extension ParcelEngine { for window in Set(windows) { enqueue(.windowDisappeared(window), detections: detections) } coalescer.removeApp(app.motionID) busyApps.remove(app.motionID) - if let batch = activeBatches.removeValue(forKey: app.motionID), openWrites.remove(batch) != nil { - trace?.end(.write, transaction: batch) + for window in Set(windows) { activityPlacements[window] = nil } + if let batch = activeBatches.removeValue(forKey: app.motionID) { + activityBatchGenerations[batch] = nil + if openWrites.remove(batch) != nil { trace?.end(.write, transaction: batch) } } } diff --git a/Tests/ParcelEngineTests/ActivityBaselineRegressionTests.swift b/Tests/ParcelEngineTests/ActivityBaselineRegressionTests.swift index 80392480..6f1ac128 100644 --- a/Tests/ParcelEngineTests/ActivityBaselineRegressionTests.swift +++ b/Tests/ParcelEngineTests/ActivityBaselineRegressionTests.swift @@ -11,6 +11,43 @@ struct ActivityBaselineRegressionTests { case unchanged, reset, offAndOn } + @Test func appExitDropsBaselinesBeforeALateWriteCanComplete() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + "parcel-activity-exit-\(UUID())") + defer { + if FileManager.default.fileExists(atPath: directory.path) { + do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } + } + } + let harness = try EngineHarness(configuration: engineConfiguration(glide: false)) + let collector = ActivityCollector( + store: ActivityStore(fileURL: directory.appendingPathComponent("activity.json")), + scheduler: harness.scheduler, clock: harness.clock) + collector.configure(enabled: true) + harness.engine.activity = collector + try await harness.start() + harness.world.deferWrites = true + do { + try harness.add([1, 2]) + try #require(!harness.engine.activityBatchGenerations.isEmpty) + try #require(!harness.engine.activityPlacements.isEmpty) + harness.world.emit(.appExited(engineApp)) + #expect(harness.engine.activityBatchGenerations.isEmpty) + #expect(harness.engine.activityPlacements.isEmpty) + try harness.scheduler.runReady() + while harness.world.pendingWriteCount > 0 { try harness.world.completeNextWrite() } + #expect(harness.engine.activityBatchGenerations.isEmpty) + #expect(harness.engine.activityPlacements.isEmpty) + #expect(collector.ledger.allTime.other == 0) + } catch { + await harness.engine.stop() + collector.flushOnQuit() + throw error + } + await harness.engine.stop() + collector.flushOnQuit() + } + @Test(arguments: [false, true], CollectionBoundary.allCases) func automaticReplanningRetainsOnlyTheCurrentCollectionBaseline(glide: Bool, boundary: CollectionBoundary) async throws -- knotmirror 0.0.1 From e28d4e88dfff0c5b9b43ffd4c532aff74ce9827c Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 2 Nov 2026 23:27:41 -0500 Subject: [PATCH 04/11] Gate reality checks on screen ownership Missing scenario preconditions visibly skip only that scenario. Keep external availability markers outside the lane, and check native resize grids across repeated gap changes and Retile using real frame readback. Signed-off-by: Vincent Taverna --- .../NoticeLocalizationRegressionTests.swift | 2 +- .../RealityConfigurationTests.swift | 15 ++++++++++ .../PseudoLocalizationScreenshotTests.swift | 5 ++-- Tests/Reality/MotionSpeedReality.swift | 29 ++++++++++++++----- Tests/Reality/README.md | 11 +++++-- Tests/Reality/RealityRecovery.swift | 4 +-- Tests/Reality/RealityScenarios.swift | 22 ++++++++++++++ 7 files changed, 72 insertions(+), 16 deletions(-) diff --git a/Tests/ParcelAppTests/NoticeLocalizationRegressionTests.swift b/Tests/ParcelAppTests/NoticeLocalizationRegressionTests.swift index 04a3c72d..0d6ba6cd 100644 --- a/Tests/ParcelAppTests/NoticeLocalizationRegressionTests.swift +++ b/Tests/ParcelAppTests/NoticeLocalizationRegressionTests.swift @@ -234,7 +234,7 @@ extension AppKitTestSuite { } private func requireUnlockedConsole() throws { - try #require(FileManager.default.fileExists(atPath: "/tmp/parcel-m3-free")) + try #require(NativeHostAvailability.unavailableReason == nil) let session = try #require(CGSessionCopyCurrentDictionary()) let data = try PropertyListSerialization.data(fromPropertyList: session, format: .binary, options: 0) let state = try PropertyListDecoder().decode(ConsoleState.self, from: data) diff --git a/Tests/ParcelRealitySupportTests/RealityConfigurationTests.swift b/Tests/ParcelRealitySupportTests/RealityConfigurationTests.swift index acab308b..961cb966 100644 --- a/Tests/ParcelRealitySupportTests/RealityConfigurationTests.swift +++ b/Tests/ParcelRealitySupportTests/RealityConfigurationTests.swift @@ -7,6 +7,21 @@ import Testing @testable import ParcelRealityTests @Suite @MainActor struct RealityConfigurationTests { + @Test(arguments: [nil, "", "screen", "screen 1", "screen 41", "screen 42 extra"] as [String?]) + func missingScreenOwnershipSkipsOnlyTheCurrentScenario(_ owner: String?) throws { + do { + try RealityScreenPrecondition.requireOwner(owner, parentPID: 42) + Issue.record("Missing screen ownership was accepted") + } catch let skip as RealitySkip { + #expect(!RealityLaneDecision.afterScenario(failures: [skip], cleanupFailed: false).stopsLane) + } + } + + @Test(arguments: ["screen 42", "screen 42\n", "screen\t42\n"]) + func screenOwnerAllowsTheExistingLockWithoutAnExternalMarker(_ owner: String) throws { + try RealityScreenPrecondition.requireOwner(owner, parentPID: 42) + } + @Test func runningParcelInstancesBlockRealityRuns() throws { try RealityMain.rejectRunningInstances(0) #expect(throws: RealityError.self) { try RealityMain.rejectRunningInstances(1) } diff --git a/Tests/ParcelUITests/PseudoLocalizationScreenshotTests.swift b/Tests/ParcelUITests/PseudoLocalizationScreenshotTests.swift index dd773dc2..abdc52a0 100644 --- a/Tests/ParcelUITests/PseudoLocalizationScreenshotTests.swift +++ b/Tests/ParcelUITests/PseudoLocalizationScreenshotTests.swift @@ -3,6 +3,7 @@ import CoreGraphics import Foundation import ParcelConfig import ParcelCore +import ParcelTestSupport import ScreenCaptureKit import SwiftUI import Testing @@ -223,8 +224,8 @@ extension AppKitTestSuite { private func requireUnlockedConsole() throws { try #require( - FileManager.default.fileExists(atPath: "/tmp/parcel-m3-free"), - "The user screen guard has not been released for native screenshot work.") + NativeHostAvailability.unavailableReason == nil, + "Native screenshot work requires Scripts/screen-lock.sh and an unlocked console.") let session = try #require(CGSessionCopyCurrentDictionary(), "Cannot inspect the console session.") let data = try PropertyListSerialization.data(fromPropertyList: session, format: .binary, options: 0) let state = try PropertyListDecoder().decode(ConsoleState.self, from: data) diff --git a/Tests/Reality/MotionSpeedReality.swift b/Tests/Reality/MotionSpeedReality.swift index 3eea875a..5c801490 100644 --- a/Tests/Reality/MotionSpeedReality.swift +++ b/Tests/Reality/MotionSpeedReality.swift @@ -72,16 +72,31 @@ enum MotionSpeedOracle { } } -private func requireMotionSpeedConsole() throws { - guard FileManager.default.fileExists(atPath: "/tmp/parcel-m3-free") else { - throw RealityError("Safety stop: the motion speed scenario requires the screen gate") +enum RealityScreenPrecondition { + static func requireOwner(_ owner: String?, parentPID: Int32) throws { + let fields = owner?.split(whereSeparator: \.isWhitespace) ?? [] + guard fields.count == 2, parentPID > 1, Int32(fields[1]) == parentPID else { + throw RealitySkip("This scenario requires ownership of Scripts/screen-lock.sh") + } + } + + static func requireAvailableConsole() throws { + let environment = ProcessInfo.processInfo.environment + let path = environment["PARCEL_SCREEN_LOCK_PATH"] ?? "/tmp/parcel-screen.lock" + let owner: String + do { owner = try String(contentsOfFile: "\(path)/owner", encoding: .utf8) } catch { + throw RealitySkip("Screen-lock ownership could not be verified: \(error)") + } + try requireOwner(owner, parentPID: getppid()) + do { try TabViewConsoleSession.requireUnlockedConsole() } catch { + throw RealitySkip("This scenario requires an active, unlocked console: \(error)") + } } - try TabViewConsoleSession.requireUnlockedConsole() } @MainActor func checkMotionSpeed(_ session: RealitySession) async throws { - try requireMotionSpeedConsole() + try RealityScreenPrecondition.requireAvailableConsole() guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else { throw RealitySkip("Reduce Motion is enabled; window transitions intentionally snap") } @@ -109,7 +124,7 @@ func checkMotionSpeed(_ session: RealitySession) async throws { @MainActor private func setMotionSpeed(_ speed: Double, session: RealitySession) async throws { - try requireMotionSpeedConsole() + try RealityScreenPrecondition.requireAvailableConsole() guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else { throw RealitySkip("Reduce Motion became enabled during the motion speed scenario") } @@ -142,7 +157,7 @@ private func measureMotionSwap( _ session: RealitySession, windows: [OwnedWindow], from: [ScreenRect], to: [ScreenRect], forward: Bool, speed: Double ) async throws -> MotionSpeedMeasurement { - try requireMotionSpeedConsole() + try RealityScreenPrecondition.requireAvailableConsole() try await session.apps.focus(windows[0]) try await session.expect("Motion swap starts at its independently observed CG baseline") { MotionSpeedOracle.matches(try FrameOracle.frames($0, ids: windows.map(\.id)), from) diff --git a/Tests/Reality/README.md b/Tests/Reality/README.md index a43c7bc9..3770443a 100644 --- a/Tests/Reality/README.md +++ b/Tests/Reality/README.md @@ -64,7 +64,7 @@ session off. A skip is not a live accessibility pass. | app-safari | Fresh owned local-page Safari window is tiled | | app-firefox | Fresh local-page browser window in an isolated temporary profile is tiled | | position-refusal | A shifted browser frame returns inside its column with no one-point overflow | -| app-terminal | Fresh owned Terminal window is tiled | +| app-terminal | Fresh owned Terminal window fits its measured resize grid across repeated gap changes and Retile | | app-notes | Notes window from a newly launched process is tiled | | app-calculator | Default exclusion preserves Calculator's real frame | | app-systemSettings | Default exclusion preserves System Settings' real frame | @@ -257,10 +257,15 @@ Recovery accepts exactly one active Finder entry from this worktree's ownership ledger, rechecks the PID/CG ID, and records disappearance plus `recovery.json`. It never quits Finder or resets Parcel state. Missing, broad, or outside ledgers fail. +Motion-speed checks and key recovery require verified ownership of the shared +screen lock and an active, unlocked console. A missing scenario precondition is a +visible skip for that scenario, not a reason to stop later scenarios. Any external +screen-availability marker is an orchestration convention, not a lane requirement. + For an explicitly approved stuck virtual key, `mise run reality -- --recover-key 123` opens one fresh owned FixtureApp window, posts exactly one key-up, reads the combined -session state back, and closes its fixture. It requires the shared screen lock and -`/tmp/parcel-m3-free`; physical-down keys, modifiers, and unowned targets are refused. +session state back, and closes its fixture. Physical-down keys, modifiers, and +unowned targets are refused. Recovery runs alone, before capturing a new lane baseline. Its evidence stays under `build/reality/key-recovery-*`. diff --git a/Tests/Reality/RealityRecovery.swift b/Tests/Reality/RealityRecovery.swift index 4fae491e..530c5a6a 100644 --- a/Tests/Reality/RealityRecovery.swift +++ b/Tests/Reality/RealityRecovery.swift @@ -46,9 +46,7 @@ func recoverOwnedFinder(directory: URL, driver: RealityDriver) async throws { @MainActor func recoverHeldKey(_ key: UInt16, driver: RealityDriver) async throws { - guard FileManager.default.fileExists(atPath: "/tmp/parcel-m3-free") else { - throw RealityError("Safety stop: key recovery requires the owner's screen availability marker") - } + try RealityScreenPrecondition.requireAvailableConsole() try DriverCommand.recoverKey(pid: 1, windowID: 1, virtualKey: key).validate() let directory = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) .appendingPathComponent("build/reality/key-recovery-\(UUID().uuidString)") diff --git a/Tests/Reality/RealityScenarios.swift b/Tests/Reality/RealityScenarios.swift index 08835fc7..a38d1c19 100644 --- a/Tests/Reality/RealityScenarios.swift +++ b/Tests/Reality/RealityScenarios.swift @@ -157,6 +157,24 @@ extension RealityScenario { FrameOracle.incrementFit( try FrameOracle.frames($0, ids: [owned[0].id])[0], tile: tile, increment: increment) } + for gap in [17.0, 23.0, 16.0] { + try session.configure(outerGap: gap) + let reload = try await session.cli(["reload", "--json"]) + guard reload.status == 0 else { + throw RealityError("Resize-grid config reload failed: \(reload.errors)") + } + let resizedTile = session.visible.inset(gap) + try await session.expect("Repeated grid fitting stays within the measured increment at gap \(gap)") + { + FrameOracle.incrementFit( + try FrameOracle.frames($0, ids: [owned[0].id])[0], tile: resizedTile, increment: increment) + } + try await session.command("retile") + try await session.expect("Retile preserves the contained native grid frame at gap \(gap)") { + FrameOracle.incrementFit( + try FrameOracle.frames($0, ids: [owned[0].id])[0], tile: resizedTile, increment: increment) + } + } } else if excluded { try await session.expect( "Default-excluded app keeps \(before[1]); adjacent document fills the usable frame" @@ -177,6 +195,10 @@ extension RealityScenario { try await session.start() if name == "minimum-size" { try await session.tiles(owned) + for _ in 0..<2 { + try await session.command("retile") + try await session.tiles(owned) + } } else { let fixed = owned[2] try await session.expect("Calculator retains \(before[2]); two neighbors tile without the fixed app") { -- knotmirror 0.0.1 From 26c771a9a45139c66091abdeacf6e9196077a500 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 2 Nov 2026 23:28:25 -0500 Subject: [PATCH 05/11] Partition screen-free tests and benchmark skips Signed-off-by: Vincent Taverna --- Scripts/tests/test-runner.sh | 18 +++- Tests/Lanes/bench.txt | 6 ++ Tests/Lanes/unit.txt | 6 ++ .../BenchmarkRegressionProbeTests.swift | 4 +- .../DisplayEventBenchmarks.swift | 97 ++++++++++--------- Tests/ParcelUITests/SettingsTests.swift | 13 +-- Tests/TestSelection/main.swift | 6 +- 7 files changed, 87 insertions(+), 63 deletions(-) create mode 100644 Tests/Lanes/bench.txt diff --git a/Scripts/tests/test-runner.sh b/Scripts/tests/test-runner.sh index bd9cfced..b2954273 100755 --- a/Scripts/tests/test-runner.sh +++ b/Scripts/tests/test-runner.sh @@ -16,8 +16,8 @@ import sys from pathlib import Path from xml.etree.ElementTree import Element, SubElement, ElementTree suites = [s for s in Path(sys.argv[1]).read_text().splitlines() if s and not s.startswith('#')] -native = [s for s in Path(sys.argv[1]).with_name('native-host.txt').read_text().splitlines() if s and not s.startswith('#')] -Path(sys.argv[2]).write_text('\n'.join(s if s.endswith(')') else s + '/example()' for s in suites + native) + '\n') +other = [s for lane in ['native-host', 'bench'] for s in Path(sys.argv[1]).with_name(lane + '.txt').read_text().splitlines() if s and not s.startswith('#')] +Path(sys.argv[2]).write_text('\n'.join(s if s.endswith(')') else s + '/example()' for s in suites + other) + '\n') root = Element('testsuites') for suite in suites: if suite.endswith(')'): @@ -74,13 +74,25 @@ check fails_with 2 bash "$runner" --package-path /other check fails_with 2 bash "$runner" --filter check fails_with 2 bash "$runner" --skip unsafe check fails_with 1 bash "$runner" --filter 'NoSuchTest' -check fails_with 1 bash "$runner" --filter 'AppKitTestSuite|ParcelE2ETests|ParcelPerformanceTests' +check fails_with 1 bash "$runner" --filter 'AppKitTestSuite|ParcelPerformanceTests' check fails_with 17 env TEST_BUILD_STATUS=17 bash "$runner" check fails_with 19 env TEST_LIST_STATUS=19 bash "$runner" --skip-build check fails_with 7 env TEST_SWIFT_STATUS=7 bash "$runner" --skip-build --xunit-output "$work/failed.xml" check test -f "$work/failed.xml" check fails_with 1 env TEST_NO_REPORT=1 bash "$runner" --skip-build cp "$TEST_DISCOVERY" "$work/saved-discovery" +for identifier in 'ParcelE2ETests.NewScreenFreeTests/escape()' 'ParcelPerformanceTests.NewBenchmarkTests/escape()'; do + printf '%s\n' "$identifier" >> "$TEST_DISCOVERY" + check fails_with 1 bash "$runner" --skip-build + cp "$work/saved-discovery" "$TEST_DISCOVERY" +done +cp "$work/project/Tests/Lanes/unit.txt" "$work/saved-unit" +printf 'ParcelPerformanceTests.PerformanceTestSuite\n' >> "$work/project/Tests/Lanes/unit.txt" +check fails_with 1 bash "$runner" --skip-build +cp "$work/saved-unit" "$work/project/Tests/Lanes/unit.txt" +"$TEST_BIN/ParcelTestSelection" select "$work/project/Tests/Lanes/bench.txt" "$TEST_DISCOVERY" '' "$TEST_REPORT" > "$work/bench-filter" +check grep -Fq 'ParcelPerformanceTests\.PerformanceTestSuite' "$work/bench-filter" +check grep -Fq 'ParcelE2ETests.FixtureReplyTests' "$work/project/Tests/Lanes/unit.txt" : > "$TEST_DISCOVERY" check fails_with 1 bash "$runner" --skip-build cp "$work/saved-discovery" "$TEST_DISCOVERY" diff --git a/Tests/Lanes/bench.txt b/Tests/Lanes/bench.txt new file mode 100644 index 00000000..c9fc52a7 --- /dev/null +++ b/Tests/Lanes/bench.txt @@ -0,0 +1,6 @@ +# Suite IDs assigned exclusively to the benchmark CI lane. +ParcelPerformanceTests.AXWriteBenchmarks +ParcelPerformanceTests.EngineCorePerformanceTests +ParcelPerformanceTests.PerformanceTestSuite +ParcelPerformanceTests.WriteMotionBenchmarks +ParcelPerformanceTests.WriteSchedulingBenchmarks diff --git a/Tests/Lanes/unit.txt b/Tests/Lanes/unit.txt index 6b6870c4..068aa187 100644 --- a/Tests/Lanes/unit.txt +++ b/Tests/Lanes/unit.txt @@ -119,6 +119,12 @@ ParcelCoreTests.WindowControlTests ParcelCoreTests.WindowGestureTests ParcelCoreTests.WorkspaceCommandTests ParcelCoreTests.WorkspaceMemoryTests +ParcelE2ETests.FixtureHoverInputTests +ParcelE2ETests.FixtureInputRecorderTests +ParcelE2ETests.FixtureReplyTests +ParcelE2ETests.FixtureStackInputTests +ParcelE2ETests.IdleFullscreenFocusReceiptTests +ParcelE2ETests.StartupSpaceFailureReceiptTests ParcelEngineTests.ActivityBaselineRegressionTests ParcelEngineTests.ActivityCollectorTests ParcelEngineTests.ActivityPlacementTests diff --git a/Tests/ParcelPerformanceTests/BenchmarkRegressionProbeTests.swift b/Tests/ParcelPerformanceTests/BenchmarkRegressionProbeTests.swift index 31ddf782..b857cef9 100644 --- a/Tests/ParcelPerformanceTests/BenchmarkRegressionProbeTests.swift +++ b/Tests/ParcelPerformanceTests/BenchmarkRegressionProbeTests.swift @@ -14,8 +14,8 @@ extension PerformanceTestSuite { return consume(copy) } - @Test func extraFrameCopiesFailTheInstructionGate() throws { - guard ProcessInfo.processInfo.environment["PARCEL_BENCH_REGRESSION_PROBE"] == "1" else { return } + @Test(.enabled(if: ProcessInfo.processInfo.environment["PARCEL_BENCH_REGRESSION_PROBE"] == "1")) + func extraFrameCopiesFailTheInstructionGate() throws { #if DEBUG throw BenchmarkFailure.debugBuild #else diff --git a/Tests/ParcelPerformanceTests/DisplayEventBenchmarks.swift b/Tests/ParcelPerformanceTests/DisplayEventBenchmarks.swift index 9f367924..20d8576e 100644 --- a/Tests/ParcelPerformanceTests/DisplayEventBenchmarks.swift +++ b/Tests/ParcelPerformanceTests/DisplayEventBenchmarks.swift @@ -107,56 +107,63 @@ } } - extension AppKitTestSuite { + extension PerformanceTestSuite { @Suite("Display event benchmarks", .tags(.benchmark)) @MainActor struct DisplayEventBenchmarkTests { - @Test func displayChangeLatency() async throws { + @Test( + .enabled( + if: ProcessInfo.processInfo.environment["PARCEL_DISPLAY_BENCH"] == "1" + || ProcessInfo.processInfo.environment["PARCEL_BENCH_SMOKE"] == "1")) + func displayChangeLatency() async throws { let environment = ProcessInfo.processInfo.environment - guard environment["PARCEL_DISPLAY_BENCH"] == "1" else { return } - #if DEBUG - throw BenchmarkFailure.debugBuild - #else - let counters = BenchmarkCounters.startup(full: true, hosted: false) - var harness = BenchmarkHarness(full: true, counters: counters) - var samples: [DisplayEventBenchmarkSample] = [] - try await DisplayEventBenchmarks.run(&harness) { samples.append($0) } - let machine = try BenchmarkMachine.current() - let report = try BenchmarkReport( - version: BenchmarkReport.currentVersion, machine: machine.identity, - host: machine.host(source: counters.source), results: harness.results) - let names = Set(report.results.map(\.name)) - let path = - environment["PARCEL_DISPLAY_BENCH_OUTPUT"] ?? "/tmp/parcel-perf-events-display-results.json" - if let baselinePath = environment["PARCEL_DISPLAY_BENCH_BASELINE"] { - let baseline = try JSONDecoder().decode( - BenchmarkReport.self, from: Data(contentsOf: URL(fileURLWithPath: baselinePath))) - try baseline.validate(caseNames: Set(baseline.results.map(\.name))) - #expect(baseline.host.compatibilityKey == report.host.compatibilityKey) - for reference in baseline.results { - let result = try #require(report.results.first { $0.name == reference.name }) - guard !result.reportingOnly else { continue } - let before = try #require( - reference.instructionsPerOp ?? reference.proofMetrics["process-instructions-p50"]) - let after = try #require( - result.instructionsPerOp ?? result.proofMetrics["process-instructions-p50"]) - #expect(after <= before * 1.03, "\(result.name): instructions \(before) -> \(after)") - } - } - let output = URL(fileURLWithPath: path) - try BenchmarkBaselines.write(report, to: output, caseNames: names) - let encoder = JSONEncoder() - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - try encoder.encode(samples).write( - to: output.deletingPathExtension().appendingPathExtension("samples.json"), options: .atomic) - for result in report.results { - let instructions = - result.instructionsPerOp.map(String.init(describing:)) ?? "async process counters in proof" - print( - "DISPLAY_BENCH \(result.name) instructions.p50=\(instructions) wall.p50.ns=\(result.wallMedianNanoseconds) proof=\(result.proofMetrics)" - ) + let hosted = environment["GITHUB_ACTIONS"] == "true" || environment["PARCEL_BENCH_SMOKE"] == "1" + let full = environment["PARCEL_DISPLAY_BENCH"] == "1" && !hosted + if full && _isDebugAssertConfiguration() { throw BenchmarkFailure.debugBuild } + let counters = BenchmarkCounters.startup(full: full, hosted: hosted) + var harness = BenchmarkHarness(full: full, counters: counters) + var samples: [DisplayEventBenchmarkSample] = [] + try await DisplayEventBenchmarks.run(&harness) { samples.append($0) } + let machine = try BenchmarkMachine.current() + let report = try BenchmarkReport( + version: BenchmarkReport.currentVersion, machine: machine.identity, + host: machine.host(source: counters.source), results: harness.results) + let names = Set(report.results.map(\.name)) + #expect( + names == [ + "DisplayChangeScheduling/screen-only", "DisplayChangeLatency/screen-only", + "DisplayChangeLatency", + ]) + #expect(!samples.isEmpty) + let path = environment["PARCEL_DISPLAY_BENCH_OUTPUT"] ?? "build/bench-display.json" + if full, let baselinePath = environment["PARCEL_DISPLAY_BENCH_BASELINE"] { + let baseline = try JSONDecoder().decode( + BenchmarkReport.self, from: Data(contentsOf: URL(fileURLWithPath: baselinePath))) + try baseline.validate(caseNames: Set(baseline.results.map(\.name))) + #expect(baseline.host.compatibilityKey == report.host.compatibilityKey) + for reference in baseline.results { + let result = try #require(report.results.first { $0.name == reference.name }) + guard !result.reportingOnly else { continue } + let before = try #require( + reference.instructionsPerOp ?? reference.proofMetrics["process-instructions-p50"]) + let after = try #require( + result.instructionsPerOp ?? result.proofMetrics["process-instructions-p50"]) + #expect(after <= before * 1.03, "\(result.name): instructions \(before) -> \(after)") } - #endif + } + let output = URL(fileURLWithPath: path) + try BenchmarkBaselines.write(report, to: output, caseNames: names) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + try encoder.encode(samples).write( + to: output.deletingPathExtension().appendingPathExtension("samples.json"), options: .atomic) + for result in report.results { + let instructions = + result.instructionsPerOp.map(String.init(describing:)) ?? "async process counters in proof" + print( + "DISPLAY_BENCH \(result.name) instructions.p50=\(instructions) wall.p50.ns=\(result.wallMedianNanoseconds) proof=\(result.proofMetrics)" + ) + } } } } diff --git a/Tests/ParcelUITests/SettingsTests.swift b/Tests/ParcelUITests/SettingsTests.swift index de5619e8..141a93c0 100644 --- a/Tests/ParcelUITests/SettingsTests.swift +++ b/Tests/ParcelUITests/SettingsTests.swift @@ -608,16 +608,9 @@ struct SettingsTests { } } - @Test(arguments: ConfigCommand.allCases.filter { !$0.isBindable }) - func unavailableCommandsCannotBeRecorded(command: ConfigCommand) async throws { - try await withSettings(source: "") { model, file in - let chord = KeyChord(modifiers: [.cmd, .fn], key: .keypad9) - await #expect(throws: SettingsFailure.self) { try await model.setShortcut(chord, for: command) } - #expect(model.configuration.keybindings[command] == nil) - #expect(model.error?.message.contains("not available yet") == true) - let saved = try file.read() - #expect(saved.isEmpty) - } + @Test func everyCommandIsAvailableForRecording() { + #expect(ConfigCommand.allCases.filter { !$0.isBindable }.isEmpty) + #expect(ConfigCommand.bindableCases == ConfigCommand.allCases) } @Test(arguments: ConfigCommand.bindableCases) diff --git a/Tests/TestSelection/main.swift b/Tests/TestSelection/main.swift index 4a2c21fa..26f0dc08 100644 --- a/Tests/TestSelection/main.swift +++ b/Tests/TestSelection/main.swift @@ -63,7 +63,7 @@ private func run() throws { } let discovered = try String(contentsOfFile: args[2], encoding: .utf8) let directory = URL(fileURLWithPath: args[1]).deletingLastPathComponent() - let lanes = try ["unit", "native-host"].map { lane in + let lanes = try ["unit", "native-host", "bench"].map { lane in try TestLaneSelection( manifest: String(contentsOf: directory.appendingPathComponent("\(lane).txt"), encoding: .utf8), discovered: discovered) @@ -71,8 +71,8 @@ private func run() throws { try TestLaneSelection.validatePartition( lanes, discovered: discovered, excluding: [ - "ParcelE2ETests.", "ParcelPerformanceTests.", "NameGuardTests.", "ParcelDevTests.", - "ParcelTestSupport.AppKitTestSuite/DisplayEventBenchmarkTests/", + "ParcelE2ETests.RealAppEndToEndTests/", "ParcelE2ETests.RealAppEndToEndTestsPreflight/", + "NameGuardTests.", "ParcelDevTests.", ]) let selection = try TestLaneSelection( manifest: String(contentsOfFile: args[1], encoding: .utf8), -- knotmirror 0.0.1 From 73426c28f78ede3252ed51c9eab6486cddc12364 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 2 Nov 2026 23:29:31 -0500 Subject: [PATCH 06/11] Align local checks with CI and keep pushes short Signed-off-by: Vincent Taverna --- .github/workflows/ci.yml | 13 ++--- CONTRIBUTING.md | 39 +++++++++++--- Scripts/tests/measure-tasks.sh | 13 +++-- Scripts/tests/task-dispatch.sh | 51 +++++++++++++++++-- .../WorkflowContractTests.swift | 10 ++-- lefthook.yml | 5 +- mise.toml | 18 +++++-- 7 files changed, 117 insertions(+), 32 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 33ba327c..fd5d578a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,9 +102,7 @@ jobs: uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: junit-unit - path: | - build/junit*.xml - build/unit-*.txt + path: build/junit*.xml if-no-files-found: error retention-days: 7 @@ -221,16 +219,15 @@ jobs: - uses: ./.github/actions/swift - uses: ./.github/actions/restore-build - name: Debug smoke reuses the root build; does not certify performance budgets - env: - PARCEL_BENCH_SMOKE: '1' - PARCEL_BENCH_OUTPUT: build/bench-smoke.json - run: swift test --skip-build --no-parallel --filter ParcelPerformanceTests + run: mise run bench:smoke - name: Save benchmark results if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: benchmark-smoke - path: build/bench-smoke.json + path: | + build/bench-smoke.json + build/bench-display*.json if-no-files-found: error retention-days: 7 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f896c5b5..4dcbce24 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,7 +21,9 @@ Setup installs the versions in `mise.toml`, builds the native developer tool, and installs worktree-local lefthook hooks, then runs `mise run doctor`. It refuses to replace foreign hooks. Pre-commit formats and restages changed Swift files and checks names, shell scripts, and workflows. Commit messages require DCO -sign-off. Pre-push runs the build, unit tests, and full lint. See +sign-off. Pre-push runs full lint only: we choose short, warm pushes (about a +minute or less) over rebuilding and rerunning every CI lane in the hook. Run the +[local CI parity tasks](#sending-a-change) deliberately before pushing. See [guard maintenance](Scripts/Names.md). Normal mise tasks run offline: update checks and automatic tool installs are @@ -50,6 +52,8 @@ Give it a read before a big change. | `mise run test` / `mise run e2e` | Unit tests / opt-in live-window tests | | `mise run lint` / `mise run format` | Check / apply formatting and repository guards | | `mise run test:scripts` | Tooling and packaging regressions | +| `mise run audit` | Redacted full-history secret scan, shipped locales, and dependency licenses | +| `mise run bench:smoke` | Debug benchmark smoke, identical to CI; no performance certification | | `mise run check-app` | Check and smoke-launch a relocated bundle | | `mise run dmg` / `mise run release-dry-run` | Package a release / exercise disposable signing | | `mise run remote-test your-mac` | Test on another Mac | @@ -89,15 +93,20 @@ PARCEL_NATIVE_HOST=1 Scripts/test-native-host.sh The wrapper takes `Scripts/screen-lock.sh`; tests also verify lock ancestry and an unlocked console. Native input needs an existing Accessibility grant for the test process, never a consent prompt. Missing permission is a visible skip, not -an early-return pass; skips do not certify that capability. Both manifests must -be kept current when adding suites: unclassified or overlapping suites fail the -inventory check. JUnit uses Swift Testing directly, not an empty XCTest report. -Plain `swift test` remains screen-free by -default: the shared AppKit ancestor and native input tests require explicit +an early-return pass; skips do not certify that capability. The unit, native-host, +and [benchmark manifests](Tests/Lanes/bench.txt) must be kept current when adding +suites: unclassified or overlapping suites fail the inventory check. Screen-free +FixtureApp decoding and input-validation suites belong to unit, even though they +live in `ParcelE2ETests`; only the real-app suites are exempt for the live lane. +JUnit uses Swift Testing directly, not an empty XCTest report. +Plain `swift test` remains screen-free by default: the shared AppKit ancestor and +native input tests require explicit opt-in and the mutex, even when the test process already has Accessibility. Suites retain `.e2e`, `.benchmark`, and `.appKit` tags for test plans. `mise run bench` runs the complete performance suite in release, serially; record -a baseline with `make bench-record` on a quiet machine first. +a baseline with `make bench-record` on a quiet machine first. `mise run bench:smoke` +uses debug locally and in CI, including the screen-free display event benchmark. +Set `PARCEL_TEST_SKIP_BUILD=1` to reuse a debug `swift build --build-tests`. `mise run e2e` builds the real bundle and drives it through FixtureApp. Only `build/Parcel.app` needs Accessibility; the test runner needs neither Accessibility nor Screen Recording. A missing grant fails preflight @@ -150,7 +159,21 @@ compiled catalogs, including plurals and format arguments. - Keep pull requests small and focused, with tests. If it moves a window, it needs an e2e scenario too. - Every motion change needs a Reduce Motion path, and every new shortcut goes through config. -- Run `mise run check` and `mise run test:scripts` before you push. +- Pre-push checks lint, not full CI parity. Run these before pushing; the hook + deliberately leaves builds, tests, secret/license audits, and benchmark smoke + to this explicit check rather than making every push wait for them: + + ```sh + mise run check + mise run test:scripts + mise run audit + mise run bench:smoke + ``` + + `audit` scans all locally available Git history, like CI's full checkout; a + shallow clone cannot certify missing history. Reports go to `build/gitleaks.sarif` + and `build/ci-audits`. Packaging changes also need `mise run release-dry-run`; + live-window changes need the locked e2e/reality checks described above. ## Releasing diff --git a/Scripts/tests/measure-tasks.sh b/Scripts/tests/measure-tasks.sh index ead3d760..105daee7 100755 --- a/Scripts/tests/measure-tasks.sh +++ b/Scripts/tests/measure-tasks.sh @@ -21,12 +21,12 @@ done cat > "$work/bin/swift" <<'MOCK' #!/bin/bash set -euo pipefail -printf '%s|%s|%s\n' "$*" "${PARCEL_BENCH_SMOKE:-}" "${PARCEL_BENCH_OUTPUT:-}" >> "$TASK_LOG" +printf '%s|%s|%s|%s\n' "$*" "${PARCEL_BENCH_SMOKE:-}" "${PARCEL_BENCH_OUTPUT:-}" "${PARCEL_DISPLAY_BENCH_OUTPUT:-}" >> "$TASK_LOG" exit "${TASK_STATUS:-0}" MOCK chmod +x "$work/bin/swift" export PATH="$work/bin:$PATH" MISE_TRUSTED_CONFIG_PATHS="$work/project" TASK_LOG="$work/tasks.log" -unset PARCEL_BENCH_QUIET PARCEL_E2E_FILTER +unset PARCEL_BENCH_QUIET PARCEL_E2E_FILTER PARCEL_TEST_SKIP_BUILD PARCEL_DISPLAY_BENCH_OUTPUT cd "$work/project" count=0 check() { @@ -44,7 +44,14 @@ for task in bench-ab bench-remote idle-report soak leaks trace trace-e2e quiet-c check grep -Fxq -- "$expected" "$TASK_LOG" done check mise run bench:smoke -check grep -Fxq 'test -c release --no-parallel --filter ParcelPerformanceTests|1|build/bench-smoke.json' "$TASK_LOG" +check grep -Fxq 'test -c debug --no-parallel --filter ParcelPerformanceTests|1|build/bench-smoke.json|build/bench-display.json' "$TASK_LOG" +printf '' > "$TASK_LOG" +check env PARCEL_TEST_SKIP_BUILD=1 mise run bench:smoke +check grep -Fxq 'test -c debug --skip-build --no-parallel --filter ParcelPerformanceTests|1|build/bench-smoke.json|build/bench-display.json' "$TASK_LOG" +printf '' > "$TASK_LOG" +check env PARCEL_TEST_SKIP_BUILD=0 mise run bench:smoke +check grep -Fxq 'test -c debug --no-parallel --filter ParcelPerformanceTests|1|build/bench-smoke.json|build/bench-display.json' "$TASK_LOG" +check fails env TASK_STATUS=7 mise run bench:smoke check make bench-ab BASE='topic branch' check grep -Fxq 'bench-ab.sh|topic branch||' "$TASK_LOG" check make bench-remote HOST=authorized.local TASK=bench-ab BASE='topic branch' diff --git a/Scripts/tests/task-dispatch.sh b/Scripts/tests/task-dispatch.sh index a76a2183..e3406b06 100755 --- a/Scripts/tests/task-dispatch.sh +++ b/Scripts/tests/task-dispatch.sh @@ -1,10 +1,21 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")/../.." -work=$(mktemp -d "${TMPDIR:-/tmp}/task-dispatch.XXXXXX") +temp=${TMPDIR:-/tmp} +work=$(mktemp -d "${temp%/}/task-dispatch.XXXXXX") trap 'rm -rf "$work"' EXIT mkdir -p "$work/Scripts" "$work/bin" -cp mise.toml "$work/" +cp mise.toml lefthook.yml "$work/" +# The isolated dispatcher uses mock executables, not mise's pinned scanners. +python3 -I - "$work/mise.toml" <<'PY' +import sys +from pathlib import Path +config = Path(sys.argv[1]) +text = config.read_text() +start = text.index('[tools]\n') +end = text.index('\n[tasks.', start) +config.write_text(text[:start] + text[end:]) +PY cp Scripts/app-task.sh "$work/Scripts/" cat > "$work/Scripts/test-unit.sh" <<'MOCK' #!/bin/bash @@ -15,6 +26,18 @@ for command in bundle check-bundle lint; do # shellcheck disable=SC2016 printf '#!/bin/bash\nset -euo pipefail\nprintf "%%s\\n" "%s" "$@" >> "$TASK_LOG"\n' "$command" > "$work/Scripts/$command.sh" done +cat > "$work/Scripts/check-ci-audits.sh" <<'MOCK' +#!/bin/bash +set -euo pipefail +printf '%s\n' audit "$@" >> "$TASK_LOG" +exit "${AUDIT_STATUS:-0}" +MOCK +cat > "$work/bin/gitleaks" <<'MOCK' +#!/bin/bash +set -euo pipefail +printf '%s\n' gitleaks "$@" >> "$TASK_LOG" +exit "${SECRET_STATUS:-0}" +MOCK for command in open swift; do # shellcheck disable=SC2016 printf '#!/bin/bash\nset -euo pipefail\nprintf "%%s\\n" "%s" "$@" >> "$TASK_LOG"\n' "$command" > "$work/bin/$command" @@ -22,6 +45,7 @@ done chmod +x "$work/Scripts/"*.sh "$work/bin/"* export PATH="$work/bin:$PATH" MISE_TRUSTED_CONFIG_PATHS="$work" TASK_LOG="$work/log" cd "$work" +project=$PWD mise run build -- -c release printf '%s\n' swift build -c release > "$work/expected" cmp "$work/expected" "$TASK_LOG" @@ -46,4 +70,25 @@ build_line=$(grep -n -m 1 -Fx build "$TASK_LOG" | cut -d: -f1) test_line=$(grep -n -m 1 -Fx test "$TASK_LOG" | cut -d: -f1) lint_line=$(grep -n -m 1 -Fx lint "$TASK_LOG" | cut -d: -f1) [[ $build_line -lt $test_line && $test_line -lt $lint_line ]] -printf 'Task dispatch checks passed: 6\n' +printf '' > "$TASK_LOG" +mise run audit +printf '%s\n' gitleaks git --redact --report-format sarif --report-path build/gitleaks.sarif . audit "$project" "$project/build/ci-audits" > "$work/expected" +diff -u "$work/expected" "$TASK_LOG" +for gate in SECRET AUDIT; do + printf '' > "$TASK_LOG" + status=0 + env "${gate}_STATUS=9" mise run audit > "$work/failure.log" 2>&1 || status=$? + [[ $status != 0 ]] + if [[ $gate == SECRET ]] && grep -Fxq audit "$TASK_LOG"; then + printf 'Audit continued after the secret scan failed.\n' >&2 + exit 1 + fi +done +python3 -I - lefthook.yml <<'PY' +import sys +from pathlib import Path +hook = Path(sys.argv[1]).read_text().split('pre-push:\n', 1)[1] +assert 'run: mise run lint' in hook +assert 'mise run check' not in hook and 'mise run test:scripts' not in hook +PY +printf 'Task dispatch checks passed: 10\n' diff --git a/Tests/ParcelDevTests/WorkflowContractTests.swift b/Tests/ParcelDevTests/WorkflowContractTests.swift index cbb2aa04..ae69a5a1 100644 --- a/Tests/ParcelDevTests/WorkflowContractTests.swift +++ b/Tests/ParcelDevTests/WorkflowContractTests.swift @@ -105,10 +105,8 @@ extension WorkflowValue { let jobs = try load("ci")["jobs"] let bench = jobs["bench"] let smoke = try #require( - bench["steps"].sequence.first(where: { $0["run"].text?.contains("--filter ParcelPerformanceTests") == true } - )) - #expect(smoke["run"].text?.contains("--skip-build --no-parallel") == true) - #expect(smoke["env"]["PARCEL_BENCH_SMOKE"].text == "1") + bench["steps"].sequence.first(where: { $0["run"].text == "mise run bench:smoke" })) + #expect(bench["env"]["PARCEL_TEST_SKIP_BUILD"].text == "1") #expect(smoke["name"].text?.contains("does not certify performance budgets") == true) let cache = try #require(uses(jobs["build"], "actions/cache/restore").first)["with"] #expect(cache["path"].text == ".build") @@ -133,6 +131,10 @@ extension WorkflowValue { #expect(report["with"]["if-no-files-found"].text == "error") #expect(report["with"]["retention-days"].text == "7") } + let unit = try #require(uses(jobs["unit"], "actions/upload-artifact").first)["with"]["path"].text + #expect(unit == "build/junit*.xml") + let benchmark = try #require(uses(bench, "actions/upload-artifact").first)["with"]["path"].text ?? "" + #expect(benchmark.contains("build/bench-smoke.json") && benchmark.contains("build/bench-display*.json")) let scripts = try #require(uses(jobs["scripts"], "actions/upload-artifact").first)["with"]["path"].text ?? "" #expect(scripts.contains("build/script-results.json") && scripts.contains("build/junit*.xml")) let restore = try WorkflowTools.load( diff --git a/lefthook.yml b/lefthook.yml index f255fcef..9b55740a 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -22,7 +22,8 @@ commit-msg: - name: message run: Scripts/check-commit-message.sh {1} +# Keep warm pushes under about a minute; run the full parity tasks deliberately. pre-push: jobs: - - name: check - run: mise run check + - name: lint + run: mise run lint diff --git a/mise.toml b/mise.toml index 63583076..dcb17959 100644 --- a/mise.toml +++ b/mise.toml @@ -47,9 +47,16 @@ run = "Scripts/test-unit.sh --no-parallel" run = "Scripts/test-scripts.sh" [tasks.check] -description = "Build, unit tests, and full lint before pushing" +description = "Build, unit tests, and full lint for local CI parity" run = ["mise run build", "mise run test", "mise run lint"] +[tasks.audit] +description = "Scan history for secrets and audit shipped locales and dependency licenses" +run = [ + "mkdir -p build && gitleaks git --redact --report-format sarif --report-path build/gitleaks.sarif .", + 'Scripts/check-ci-audits.sh "$PWD" "$PWD/build/ci-audits"', +] + [tasks.e2e] description = "Live-window tests; build/Parcel.app needs Accessibility" run = "Scripts/test-e2e.sh" @@ -66,9 +73,12 @@ run = "Scripts/bench.sh compare" run = "Scripts/bench.sh record" [tasks."bench:smoke"] -description = "Exercise benchmarks without certifying performance budgets" -env = { PARCEL_BENCH_SMOKE = "1", PARCEL_BENCH_OUTPUT = "build/bench-smoke.json" } -run = "swift test -c release --no-parallel --filter ParcelPerformanceTests" +description = "Debug benchmark smoke, matching CI without certifying performance budgets" +env = { PARCEL_BENCH_SMOKE = "1", PARCEL_BENCH_OUTPUT = "build/bench-smoke.json", PARCEL_DISPLAY_BENCH_OUTPUT = "build/bench-display.json" } +run = ''' +if [ "${PARCEL_TEST_SKIP_BUILD:-0}" = 1 ]; then set -- --skip-build; else set --; fi +swift test -c debug "$@" --no-parallel --filter ParcelPerformanceTests +''' [tasks."bench-ab"] run = "Scripts/bench-ab.sh" -- knotmirror 0.0.1 From aaf604862907b73e84324c14f560bc3a37fe15b8 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 2 Nov 2026 23:47:15 -0500 Subject: [PATCH 07/11] Start callback fixtures without task hops Signed-off-by: Vincent Taverna --- Sources/ParcelApp/AppCallbackProcess.swift | 29 ++- Tests/ParcelAppTests/AppCallbackTests.swift | 206 ++++++++++++++++---- 2 files changed, 187 insertions(+), 48 deletions(-) diff --git a/Sources/ParcelApp/AppCallbackProcess.swift b/Sources/ParcelApp/AppCallbackProcess.swift index 95383b78..003d8639 100644 --- a/Sources/ParcelApp/AppCallbackProcess.swift +++ b/Sources/ParcelApp/AppCallbackProcess.swift @@ -154,21 +154,32 @@ final class AppCallbackProcess: Sendable { ) async throws -> Result { try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in - // Blocking process and pipe waits must not occupy Swift's cooperative executor. - let thread = Thread { - let start = ContinuousClock.now - let result = Swift.Result { try self.collectOnThread(timeout: timeout, onWaiting: onWaiting) } - onCollected(result, ContinuousClock.now - start) - continuation.resume(with: result) - } - thread.name = "Parcel callback \(pid)" - thread.start() + startCollecting( + timeout: timeout, onWaiting: onWaiting, + onCollected: { result, elapsed in + onCollected(result, elapsed) + continuation.resume(with: result) + }) } } onCancel: { self.requestStop() } } + func startCollecting( + timeout: Duration, onWaiting: @escaping @Sendable () -> Void = {}, + onCollected: @escaping @Sendable (Swift.Result, Duration) -> Void + ) { + // Blocking process and pipe waits must not occupy Swift's cooperative executor. + let thread = Thread { + let start = ContinuousClock.now + let result = Swift.Result { try self.collectOnThread(timeout: timeout, onWaiting: onWaiting) } + onCollected(result, ContinuousClock.now - start) + } + thread.name = "Parcel callback \(pid)" + thread.start() + } + private func collectOnThread(timeout: Duration, onWaiting: @Sendable () -> Void) throws -> Result { let deadline = startedAt.advanced(by: timeout) var status: Int32? diff --git a/Tests/ParcelAppTests/AppCallbackTests.swift b/Tests/ParcelAppTests/AppCallbackTests.swift index 71071f7d..fc5bc2f2 100644 --- a/Tests/ParcelAppTests/AppCallbackTests.swift +++ b/Tests/ParcelAppTests/AppCallbackTests.swift @@ -596,36 +596,131 @@ struct AppCallbackTests { #expect(groupIsGone(process.processIdentifier)) } - @Test(arguments: [1, ProcessInfo.processInfo.activeProcessorCount + 1]) - func blockedCollectorsLeaveFixtureReadinessAndCancellationRunnable(count: Int) async throws { - try await withDirectory { directory in - var processes: [AppCallbackProcess] = [] - var collections: [Task] = [] - do { - for index in 0.. + let waitedOnNativeThread: Bool + } + + private nonisolated func forkedPIDsOnThread( + _ started: URL, deadline: ContinuousClock.Instant, isCancelled: () -> Bool + ) throws -> (leader: pid_t, child: pid_t) { + while true { + if isCancelled() { throw CancellationError() } + if FileManager.default.fileExists(atPath: started.path) { + let contents = try String(contentsOf: started, encoding: .utf8) + let numbers = contents.split(separator: "\n") + if contents.hasSuffix("\n") && numbers.count == 2 { + guard let leader = pid_t(numbers[0]), let child = pid_t(numbers[1]), leader > 1, child > 1 else { + throw E2EError(description: "Callback did not report valid process IDs") + } + return (leader, child) } - for group in pids { try await expectGroupGone(group) } - } catch { - for collection in collections { collection.cancel() } - for process in processes { process.requestStop() } - for collection in collections { - do { _ = try await collection.value } catch { Issue.record(error) } + } + guard ContinuousClock.now < deadline else { + throw E2EError(description: "Timed out waiting for callback fixture output") + } + Thread.sleep(forTimeInterval: 0.02) + } + } + + private nonisolated func collectBlockedFixtures( + arguments: [[String]], directory: URL + ) async throws -> [BlockedFixtureResult] { + let state = Mutex<(processes: [AppCallbackProcess], stopped: Bool)>(([], false)) + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + let driver = Thread { + let completed = DispatchGroup() + let collected = Mutex<[Int: Result]>([:]) + let nativeWaits = Mutex<[Int: Bool]>([:]) + let deadline = ContinuousClock.now.advanced(by: .seconds(30)) + do { + for (index, command) in arguments.enumerated() { + if state.withLock({ $0.stopped }) { throw CancellationError() } + let process = try AppCallbackProcess.spawn(arguments: command, environment: [:]) + let stopped = state.withLock { + $0.processes.append(process) + return $0.stopped + } + if stopped { process.requestStop() } + completed.enter() + process.startCollecting( + timeout: .seconds(30), + onWaiting: { + nativeWaits.withLock { + $0[index] = + Thread.current.name == "Parcel callback \(process.processIdentifier)" + } + }, + onCollected: { result, _ in + collected.withLock { $0[index] = result } + completed.leave() + }) + } + var pids: [(leader: pid_t, child: pid_t)] = [] + for index in arguments.indices { + pids.append( + try self.forkedPIDsOnThread( + directory.appendingPathComponent("started-\(index)"), deadline: deadline, + isCancelled: { state.withLock { $0.stopped } })) + } + while nativeWaits.withLock({ $0.count }) < arguments.count { + if state.withLock({ $0.stopped }) { throw CancellationError() } + guard ContinuousClock.now < deadline else { + throw E2EError(description: "Timed out waiting for native callback collectors") + } + Thread.sleep(forTimeInterval: 0.001) + } + for process in state.withLock({ $0.processes }) { process.requestStop() } + completed.wait() + let results = pids.enumerated().map { index, pids in + guard let result = collected.withLock({ $0[index] }) else { + preconditionFailure("Missing native callback fixture result") + } + return BlockedFixtureResult( + pids: pids, collected: result, + waitedOnNativeThread: nativeWaits.withLock { $0[index] == true }) + } + continuation.resume(returning: results) + } catch { + for process in state.withLock({ $0.processes }) { process.requestStop() } + completed.wait() + let cleanupFailures = collected.withLock { + $0.values.compactMap { result -> String? in + if case .failure(let error) = result { return error.localizedDescription } + return nil + } + } + continuation.resume( + throwing: E2EError( + description: ([error.localizedDescription] + cleanupFailures).joined(separator: "\n"))) + } } - throw error + driver.name = "Parcel callback readiness fixture" + driver.start() + } + } onCancel: { + let processes = state.withLock { + $0.stopped = true + return $0.processes + } + for process in processes { process.requestStop() } + } + } + + @Test(arguments: [1, ProcessInfo.processInfo.activeProcessorCount + 1]) + func blockedCollectorsKeepFixtureReadinessAndStopOffTheCooperativePool(count: Int) async throws { + try await withDirectory { directory in + let arguments = (0.. Void, + onCollected: @escaping @Sendable (Result, Duration) -> Void = { _, _ in } + ) async throws -> (process: AppCallbackProcess, result: AppCallbackProcess.Result) { + let state = Mutex<(process: AppCallbackProcess?, stopped: Bool)>((nil, false)) + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + do { + // Spawn and install the native collector without an intervening task hop. + let process = try AppCallbackProcess.spawn(arguments: arguments, environment: [:]) + let stopped = state.withLock { + $0.process = process + return $0.stopped + } + if stopped { process.requestStop() } + process.startCollecting( + timeout: timeout, onWaiting: { onWaiting(process) }, + onCollected: { result, elapsed in + onCollected(result, elapsed) + continuation.resume(with: result.map { (process, $0) }) + }) + } catch { continuation.resume(throwing: error) } + } + } onCancel: { + let process = state.withLock { + $0.stopped = true + return $0.process + } + process?.requestStop() + } + } + @Test(arguments: [false, true]) func silentCallbacksBlockWithoutPollingAndStopWakesPromptly(closePipes: Bool) async throws { let arguments = if closePipes { ["/bin/sh", "-c", "exec 1>&- 2>&-; exec /bin/sleep 600"] } else { ["/bin/sleep", "600"] } - let process = try AppCallbackProcess.spawn(arguments: arguments, environment: [:]) - let pid = process.processIdentifier let waits = Mutex(0) let stoppedAt = Mutex(nil) let stopElapsed = Mutex(nil) - let result = try await process.collect( - timeout: .seconds(30), - onWaiting: { + let (process, result) = try await collectFreshFixture( + arguments: arguments, timeout: .seconds(30), + onWaiting: { process in let firstWait = waits.withLock { $0 += 1 return $0 == 1 } if firstWait { - // Schedule stop independently of the cooperative pool and measure it on the collecting thread. - DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .milliseconds(100)) { + // Keep the stop timer independent of both task and dispatch-pool scheduling. + let stopper = Thread { + Thread.sleep(forTimeInterval: 0.1) stoppedAt.withLock { $0 = ContinuousClock.now } process.requestStop() } + stopper.name = "Parcel callback stop fixture \(process.processIdentifier)" + stopper.start() } }, onCollected: { _, _ in @@ -695,7 +824,7 @@ struct AppCallbackTests { // Each pipe's EOF, stop, and leader exit may wake once; silence must not add recurring waits. #expect(waits.withLock { $0 } <= 4) #expect(try #require(stopElapsed.withLock { $0 }) < .seconds(1)) - try await expectGroupGone((leader: pid, child: pid)) + try await expectGroupGone((leader: process.processIdentifier, child: process.processIdentifier)) } @Test func closedPipesDoNotFinishCollectionBeforeTheLeaderExits() async throws { @@ -709,9 +838,8 @@ struct AppCallbackTests { } @Test func stopRequestedImmediatelyBeforeTheNativeWaitIsNotLost() async throws { - let process = try AppCallbackProcess.spawn(arguments: ["/bin/sleep", "600"], environment: [:]) - let result = try await process.collect( - timeout: .seconds(30), onWaiting: { process.requestStop() }, onCollected: { _, _ in }) + let (process, result) = try await collectFreshFixture( + arguments: ["/bin/sleep", "600"], timeout: .seconds(30), onWaiting: { $0.requestStop() }) #expect(result.completion == .stopped) try await expectGroupGone((leader: process.processIdentifier, child: process.processIdentifier)) } -- knotmirror 0.0.1 From 3e27a1a919bdb8c36604c5eb63c3f2dacb39588a Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 2 Nov 2026 23:55:26 -0500 Subject: [PATCH 08/11] Reuse accepted resize requests with offset readbacks Keep the request anchor separate from its observed size, so an AX readback offset does not turn every cached grid write into a miss. Cover repeated fitting with an offset and the same 11-write initial, two-write cached ceilings. Signed-off-by: Vincent Taverna --- Sources/ParcelPlatform/AppFrameWrites.swift | 9 ++++++--- Tests/Lanes/unit.txt | 1 + .../AppFrameWriteTests.swift | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/Sources/ParcelPlatform/AppFrameWrites.swift b/Sources/ParcelPlatform/AppFrameWrites.swift index e9d15ea7..17acc616 100644 --- a/Sources/ParcelPlatform/AppFrameWrites.swift +++ b/Sources/ParcelPlatform/AppFrameWrites.swift @@ -390,6 +390,7 @@ func executeMotionFrameWrite( struct FrameSizeFit { struct Axis { let anchor: CGFloat + let requestAnchor: CGFloat let step: CGFloat? let minimum: Bool @@ -397,7 +398,8 @@ struct FrameSizeFit { if minimum { return limit < anchor ? (limit, anchor) : nil } guard let step else { return nil } let size = anchor + ((limit - anchor) / step).rounded(.down) * step - return size > 0 ? (size, size) : nil + let request = requestAnchor + size - anchor + return size > 0 && request > 0 ? (request, size) : nil } } @@ -547,11 +549,12 @@ private struct FrameSizeFitSearch { var needsRestore: Bool { lastRequest != best } var learned: FrameSizeFit.Axis? { - if let minimum { return FrameSizeFit.Axis(anchor: minimum, step: nil, minimum: true) } + if let minimum { return FrameSizeFit.Axis(anchor: minimum, requestAnchor: 1, step: nil, minimum: true) } guard let contained, let containedActual, rejected - contained <= 1, rejectedActual > limit, rejectedActual > containedActual else { return nil } - return FrameSizeFit.Axis(anchor: containedActual, step: rejectedActual - containedActual, minimum: false) + return FrameSizeFit.Axis( + anchor: containedActual, requestAnchor: contained, step: rejectedActual - containedActual, minimum: false) } var next: CGFloat? { diff --git a/Tests/Lanes/unit.txt b/Tests/Lanes/unit.txt index 068aa187..6c41cd0f 100644 --- a/Tests/Lanes/unit.txt +++ b/Tests/Lanes/unit.txt @@ -630,6 +630,7 @@ ParcelPlatformTests.brightnessResetEnumeratesWindows() ParcelPlatformTests.builds() ParcelPlatformTests.burstGuardRemainsUntilLastWindowFinishes() ParcelPlatformTests.cachedAssistiveTechnologyNotifiesOnlyOnChange() +ParcelPlatformTests.cachedGridRequestsPreserveTheMeasuredReadbackOffset() ParcelPlatformTests.callWatchdogReportsOnlyAnOperationStillInFlight() ParcelPlatformTests.cancellationInterruptsPollingSleep() ParcelPlatformTests.cancellationRestoresAndCanRetryFailedRestoration() diff --git a/Tests/ParcelPlatformTests/AppFrameWriteTests.swift b/Tests/ParcelPlatformTests/AppFrameWriteTests.swift index bb5f2e98..118b4c84 100644 --- a/Tests/ParcelPlatformTests/AppFrameWriteTests.swift +++ b/Tests/ParcelPlatformTests/AppFrameWriteTests.swift @@ -442,6 +442,24 @@ func repeatedGridFittingUsesTheLearnedStepAndInvalidatesOnAMiss(roundsUp: Bool, #expect(probe.writtenSizes.count - count <= 2) } +@Test func cachedGridRequestsPreserveTheMeasuredReadbackOffset() throws { + let probe = BurstWriteProbe() + probe.sizeTransform = { snappedSize($0, roundsUp: true) } + probe.inclusiveWidthOffset = 1 + let writer = AppThreadFrameWriter() + for generation in 1...3 { + let target = CGRect(x: 16, y: 54, width: 1480 + generation * 7, height: 856 + generation * 14) + let count = probe.writtenSizes.count + let result = write( + writer, probe, + [AppThreadFrameWrite(windowID: 1, target: target, generation: UInt64(generation), phase: .final)]) + let actual = try #require(result.windows.first?.actual) + #expect(actual.width <= target.width && target.width - actual.width < 7) + #expect(actual.height <= target.height && target.height - actual.height < 14) + #expect(probe.writtenSizes.count - count <= (generation == 1 ? 11 : 2)) + } +} + @Test func aOneWriteLateGridReplyCannotCertifyThePreviousCandidate() throws { let probe = BurstWriteProbe() probe.sizeTransform = { snappedSize($0, roundsUp: true) } -- knotmirror 0.0.1 From c08e3341083d6a050d243f1e47b29f13085bf15a Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Tue, 3 Nov 2026 00:18:47 -0500 Subject: [PATCH 09/11] Verify callback exit visibility before cleanup Signed-off-by: Vincent Taverna --- Sources/ParcelApp/AppCallbackProcess.swift | 21 ++++++++++++++++----- Tests/ParcelAppTests/AppCallbackTests.swift | 13 +++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/Sources/ParcelApp/AppCallbackProcess.swift b/Sources/ParcelApp/AppCallbackProcess.swift index 003d8639..995c1bc0 100644 --- a/Sources/ParcelApp/AppCallbackProcess.swift +++ b/Sources/ParcelApp/AppCallbackProcess.swift @@ -197,7 +197,9 @@ final class AppCallbackProcess: Sendable { // Registration precedes the first readback so an exit cannot slip between observation and waiting. try observeLeaderExit(leaderOwned: &leaderOwned) while true { - if status == nil && checkLeader { + // Reuse one deadline snapshot so a late wake cannot skip the final exit readback. + let leaderExitExpired = leaderExitDeadline.map { ContinuousClock.now >= $0 } == true + if status == nil && (checkLeader || leaderExitExpired) { checkLeader = false var info = siginfo_t() while waitid(P_PID, id_t(pid), &info, WEXITED | WNOHANG | WNOWAIT) == -1 { @@ -236,7 +238,7 @@ final class AppCallbackProcess: Sendable { leaderExitDeadline = ContinuousClock.now.advanced(by: .milliseconds(250)) } } - if status == nil && leaderExitDeadline.map({ ContinuousClock.now >= $0 }) == true { + if status == nil && leaderExitExpired { throw AppCallbackSystemFailure(operation: "callback leader exit (\(pid))", code: ETIMEDOUT) } if outputOpen { outputOpen = try drainObservedPipe(standardOutput, into: &output) } @@ -273,14 +275,23 @@ final class AppCallbackProcess: Sendable { } private func observeLeaderExit(leaderOwned: inout Bool) throws { + let deadline = ContinuousClock.now.advanced(by: .milliseconds(250)) var event = Self.event( ident: UInt64(pid), filter: Int16(EVFILT_PROC), flags: UInt16(EV_ADD | EV_ONESHOT), notes: NOTE_EXIT) while kevent64(eventQueue, &event, 1, nil, 0, 0, nil) == -1 { if errno == EINTR { continue } let code = errno - // A callback can already be a zombie when collection starts. Verify ownership without reaping it. - if code == ESRCH, try leaderHasExited(leaderOwned: &leaderOwned) { return } - throw AppCallbackSystemFailure(operation: "observe callback leader exit", code: code) + guard code == ESRCH else { + throw AppCallbackSystemFailure(operation: "observe callback leader exit", code: code) + } + // Exit can remove the process from kqueue lookup before its owned zombie becomes waitable. + if try leaderHasExited(leaderOwned: &leaderOwned) { return } + guard ContinuousClock.now < deadline else { + throw AppCallbackSystemFailure(operation: "observe callback leader exit", code: code) + } + if poll(nil, 0, 1) == -1 && errno != EINTR { + throw AppCallbackSystemFailure(operation: "poll callback exit observation", code: errno) + } } } diff --git a/Tests/ParcelAppTests/AppCallbackTests.swift b/Tests/ParcelAppTests/AppCallbackTests.swift index fc5bc2f2..a7af0816 100644 --- a/Tests/ParcelAppTests/AppCallbackTests.swift +++ b/Tests/ParcelAppTests/AppCallbackTests.swift @@ -827,6 +827,19 @@ struct AppCallbackTests { try await expectGroupGone((leader: process.processIdentifier, child: process.processIdentifier)) } + @Test(arguments: ["/usr/bin/true", "/usr/bin/env"]) + func repeatedImmediateExitsAreCollectedWithoutLosingOwnership(executable: String) async throws { + for _ in 0..<64 { + let (process, result) = try await collectFreshFixture( + arguments: [executable], timeout: .seconds(3), onWaiting: { _ in }) + #expect(result.completion == .exited(0)) + #expect(result.standardOutput.bytes.isEmpty) + #expect(result.standardError.bytes.isEmpty) + #expect(processIsGone(process.processIdentifier)) + #expect(groupIsGone(process.processIdentifier)) + } + } + @Test func closedPipesDoNotFinishCollectionBeforeTheLeaderExits() async throws { let process = try AppCallbackProcess.spawn( arguments: ["/bin/sh", "-c", "exec 1>&- 2>&-; /bin/sleep 0.1; exit 7"], environment: [:]) -- knotmirror 0.0.1 From 9175d62c8a8f159e87c86afd0236e620d966762e Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Tue, 3 Nov 2026 00:37:15 -0500 Subject: [PATCH 10/11] Retain callback exit notices until readback Signed-off-by: Vincent Taverna --- Sources/ParcelApp/AppCallbackProcess.swift | 63 +++++++++++++++++++-- Tests/ParcelAppTests/AppCallbackTests.swift | 12 +++- 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/Sources/ParcelApp/AppCallbackProcess.swift b/Sources/ParcelApp/AppCallbackProcess.swift index 995c1bc0..0dce4533 100644 --- a/Sources/ParcelApp/AppCallbackProcess.swift +++ b/Sources/ParcelApp/AppCallbackProcess.swift @@ -32,10 +32,19 @@ final class AppCallbackProcess: Sendable { case stopped } + struct Diagnostics: Sendable { + let collectionDelay: Duration + let exitNoticeReceived: Bool + let exitNoticeBeforeTermination: Bool + let exitReadbackAttempts: Int + let normalDeadlineReadback: Bool + } + struct Result: Sendable { let completion: Completion let standardOutput: AppCallbackOutput let standardError: AppCallbackOutput + let diagnostics: Diagnostics } private let pid: pid_t @@ -181,6 +190,7 @@ final class AppCallbackProcess: Sendable { } private func collectOnThread(timeout: Duration, onWaiting: @Sendable () -> Void) throws -> Result { + let collectionDelay = ContinuousClock.now - startedAt let deadline = startedAt.advanced(by: timeout) var status: Int32? var leaderOwned = true @@ -193,14 +203,22 @@ final class AppCallbackProcess: Sendable { var outputOpen = true var errorOpen = true var checkLeader = true + var exitNoticeReceived = false + var exitNoticeBeforeTermination = false + var exitReadbackAttempts = 0 + var normalDeadlineReadback = false do { // Registration precedes the first readback so an exit cannot slip between observation and waiting. try observeLeaderExit(leaderOwned: &leaderOwned) while true { // Reuse one deadline snapshot so a late wake cannot skip the final exit readback. - let leaderExitExpired = leaderExitDeadline.map { ContinuousClock.now >= $0 } == true - if status == nil && (checkLeader || leaderExitExpired) { + let now = ContinuousClock.now + let leaderExitExpired = leaderExitDeadline.map { now >= $0 } == true + let callbackDeadlineExpired = completion == nil && now >= deadline + if status == nil && (checkLeader || exitNoticeReceived || leaderExitExpired || callbackDeadlineExpired) + { checkLeader = false + normalDeadlineReadback = normalDeadlineReadback || callbackDeadlineExpired var info = siginfo_t() while waitid(P_PID, id_t(pid), &info, WEXITED | WNOHANG | WNOWAIT) == -1 { if errno == EINTR { continue } @@ -208,7 +226,14 @@ final class AppCallbackProcess: Sendable { if code == ECHILD { leaderOwned = false } throw AppCallbackSystemFailure(operation: "waitid", code: code) } - if info.si_pid == pid { + var waitable = info.si_pid == pid + if !waitable && exitNoticeReceived { + try waitForExitReadback( + leaderOwned: &leaderOwned, attempts: &exitReadbackAttempts, exitDeadline: leaderExitDeadline + ) + waitable = true + } + if waitable { // Keep the zombie leader waitable until its group is killed, preventing PID reuse. leaderExited = true try terminateGroup(leaderExited: true, leaderOwned: &leaderOwned) @@ -232,7 +257,7 @@ final class AppCallbackProcess: Sendable { completion = .stopped try terminateGroup(leaderOwned: &leaderOwned) leaderExitDeadline = ContinuousClock.now.advanced(by: .milliseconds(250)) - } else if ContinuousClock.now >= deadline { + } else if callbackDeadlineExpired { completion = .timedOut try terminateGroup(leaderOwned: &leaderOwned) leaderExitDeadline = ContinuousClock.now.advanced(by: .milliseconds(250)) @@ -246,7 +271,12 @@ final class AppCallbackProcess: Sendable { if let completion, status != nil, (!outputOpen && !errorOpen) || finalDrainDeadline.map({ ContinuousClock.now >= $0 }) == true { - return Result(completion: completion, standardOutput: output, standardError: error) + return Result( + completion: completion, standardOutput: output, standardError: error, + diagnostics: Diagnostics( + collectionDelay: collectionDelay, exitNoticeReceived: exitNoticeReceived, + exitNoticeBeforeTermination: exitNoticeBeforeTermination, + exitReadbackAttempts: exitReadbackAttempts, normalDeadlineReadback: normalDeadlineReadback)) } let nextDeadline: ContinuousClock.Instant? = if status != nil { finalDrainDeadline } else if completion != nil { leaderExitDeadline } else { @@ -255,6 +285,11 @@ final class AppCallbackProcess: Sendable { guard let nextDeadline else { preconditionFailure("Missing callback wait deadline") } onWaiting() checkLeader = try waitForEvents(until: nextDeadline) + // NOTE_EXIT is one-shot; retain it until exit status becomes waitable. + if checkLeader { + exitNoticeReceived = true + exitNoticeBeforeTermination = exitNoticeBeforeTermination || completion == nil + } } } catch { var failures: [any Error] = [error] @@ -295,6 +330,24 @@ final class AppCallbackProcess: Sendable { } } + private func waitForExitReadback( + leaderOwned: inout Bool, attempts: inout Int, exitDeadline: ContinuousClock.Instant? + ) throws { + let transitionDeadline = ContinuousClock.now.advanced(by: .milliseconds(250)) + let deadline = exitDeadline.map { min($0, transitionDeadline) } ?? transitionDeadline + while true { + attempts += 1 + if try leaderHasExited(leaderOwned: &leaderOwned) { return } + guard ContinuousClock.now < deadline else { + throw AppCallbackSystemFailure( + operation: "readback callback exit notice (\(pid); attempts=\(attempts))", code: ETIMEDOUT) + } + if poll(nil, 0, 1) == -1 && errno != EINTR { + throw AppCallbackSystemFailure(operation: "poll callback exit readback", code: errno) + } + } + } + private func waitForEvents(until deadline: ContinuousClock.Instant) throws -> Bool { var events = [kevent64_s](repeating: kevent64_s(), count: 4) while true { diff --git a/Tests/ParcelAppTests/AppCallbackTests.swift b/Tests/ParcelAppTests/AppCallbackTests.swift index a7af0816..f0c000d1 100644 --- a/Tests/ParcelAppTests/AppCallbackTests.swift +++ b/Tests/ParcelAppTests/AppCallbackTests.swift @@ -507,6 +507,8 @@ struct AppCallbackTests { arguments: ["/bin/sleep", "600"], environment: [:], signals: signals) let result = try await process.collect(timeout: .milliseconds(20)) #expect(result.completion == .timedOut) + #expect(result.diagnostics.normalDeadlineReadback) + #expect(!result.diagnostics.exitNoticeBeforeTermination) #expect(processIsGone(process.processIdentifier)) #expect(groupIsGone(process.processIdentifier)) } @@ -829,10 +831,16 @@ struct AppCallbackTests { @Test(arguments: ["/usr/bin/true", "/usr/bin/env"]) func repeatedImmediateExitsAreCollectedWithoutLosingOwnership(executable: String) async throws { - for _ in 0..<64 { + for iteration in 0..<64 { let (process, result) = try await collectFreshFixture( arguments: [executable], timeout: .seconds(3), onWaiting: { _ in }) - #expect(result.completion == .exited(0)) + #expect( + result.completion == .exited(0), + """ + Iteration \(iteration), PID \(process.processIdentifier): native start delay=\(result.diagnostics.collectionDelay) + Exit notice=\(result.diagnostics.exitNoticeReceived), before termination=\(result.diagnostics.exitNoticeBeforeTermination) + Waitable probes=\(result.diagnostics.exitReadbackAttempts), normal deadline peek=\(result.diagnostics.normalDeadlineReadback) + """) #expect(result.standardOutput.bytes.isEmpty) #expect(result.standardError.bytes.isEmpty) #expect(processIsGone(process.processIdentifier)) -- knotmirror 0.0.1 From 4c6199369a19c46646fc253a7c0521999a60fd48 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Tue, 3 Nov 2026 01:34:58 -0500 Subject: [PATCH 11/11] Preserve cached candidates while fitting other axes Start each axis search from the size request that produced its readback, not the raw tile limit. Confirm unchanged smaller replies before accepting large growth. Both failures have red-to-green regressions, while ordinary grid/minimum and cached write ceilings stay intact. The real fitting scenario drives explicit Retile after each gap reload and checks CG frames, including reversal. Automatic replay of a previously used configuration value is a separate recorded follow-up; it is not certified by this scenario. Signed-off-by: Vincent Taverna --- Sources/ParcelPlatform/AppFrameWrites.swift | 36 ++++++++++++------- Tests/Lanes/unit.txt | 2 ++ .../AppFrameWriteTests.swift | 34 ++++++++++++++++++ Tests/Reality/RealityScenarios.swift | 4 +-- 4 files changed, 62 insertions(+), 14 deletions(-) diff --git a/Sources/ParcelPlatform/AppFrameWrites.swift b/Sources/ParcelPlatform/AppFrameWrites.swift index 17acc616..ccf0c763 100644 --- a/Sources/ParcelPlatform/AppFrameWrites.swift +++ b/Sources/ParcelPlatform/AppFrameWrites.swift @@ -433,7 +433,7 @@ private func executeMotionFrameWrite( fit: inout FrameSizeFit ) throws -> CGRect? { let prediction = fit.prediction(target.size) - let requested = final && !preservingSize ? prediction.request : target.size + var requested = final && !preservingSize ? prediction.request : target.size let resized = !preservingSize && current.size != requested if resized { try window.setSize(requested) } if resized || current.origin != target.origin { try window.setPosition(target.origin) } @@ -449,29 +449,41 @@ private func executeMotionFrameWrite( if actual.size != prediction.actual { actual = try readAfterSizeWrite(requested, origin: target.origin, window: window) } + // An unchanged smaller reply can be lag, not a contained resize result. + if actual.size == current.size, + prediction.actual.width - current.width > 16 || prediction.actual.height - current.height > 16 + { + for _ in 0..<2 { + actual = try readAfterSizeWrite(requested, origin: target.origin, window: window) + if actual.size != current.size { break } + } + } if !fit.matches(actual.size, target: target.size) { fit = FrameSizeFit() - actual = try readAfterSizeWrite(target.size, origin: target.origin, window: window) + requested = target.size + actual = try readAfterSizeWrite(requested, origin: target.origin, window: window) } // The motion cache records requests, not what the app accepted. if actual.origin != target.origin { try window.setPosition(target.origin) actual = try window.frame if actual.size != target.size { - actual = try readAfterSizeWrite(target.size, origin: target.origin, window: window) + requested = target.size + actual = try readAfterSizeWrite(requested, origin: target.origin, window: window) } } if !fit.matches(actual.size, target: target.size) { fit = FrameSizeFit() } if fit.accepts(actual.size, target: target.size), fit.width != nil || fit.height != nil { return actual } // Settle a large stale reply before using its overshoot to choose any probe. if actual.width - target.width > 32 || actual.height - target.height > 32 { + requested = target.size for _ in 0..<2 { - let next = try readAfterSizeWrite(target.size, origin: target.origin, window: window) + let next = try readAfterSizeWrite(requested, origin: target.origin, window: window) if next.size == target.size { return next } actual = next } } - return try fitFinalFrame(target, actual: actual, window: window, fit: &fit) + return try fitFinalFrame(target, requested: requested, actual: actual, window: window, fit: &fit) } if resized, try window.size != target.size { try window.setSize(target.size) } return nil @@ -488,11 +500,11 @@ private func readAfterSizeWrite( } private func fitFinalFrame( - _ target: CGRect, actual: CGRect, window: Window, fit: inout FrameSizeFit + _ target: CGRect, requested: CGSize, actual: CGRect, window: Window, fit: inout FrameSizeFit ) throws -> CGRect { guard actual.width > target.width || actual.height > target.height else { return actual } - var width = FrameSizeFitSearch(limit: target.width, actual: actual.width) - var height = FrameSizeFitSearch(limit: target.height, actual: actual.height) + var width = FrameSizeFitSearch(limit: target.width, request: requested.width, actual: actual.width) + var height = FrameSizeFitSearch(limit: target.height, request: requested.height, actual: actual.height) var actual = actual for attempt in 0..<8 { let nextWidth = width.next @@ -536,13 +548,13 @@ private struct FrameSizeFitSearch { private var minimumProbe = false private var minimum: CGFloat? - init(limit: CGFloat, actual: CGFloat) { + init(limit: CGFloat, request: CGFloat, actual: CGFloat) { self.limit = limit - contained = actual <= limit ? limit : nil + contained = actual <= limit ? request : nil containedActual = actual <= limit ? actual : nil - rejected = limit + rejected = actual > limit ? request : limit rejectedActual = actual - lastRequest = limit + lastRequest = request } var best: CGFloat { contained ?? limit } diff --git a/Tests/Lanes/unit.txt b/Tests/Lanes/unit.txt index 6c41cd0f..19ed39dc 100644 --- a/Tests/Lanes/unit.txt +++ b/Tests/Lanes/unit.txt @@ -640,6 +640,7 @@ ParcelPlatformTests.cancelledStaleBatchDoesNotCloseNewerGeneration() ParcelPlatformTests.changedFramePlansSizePositionSize() ParcelPlatformTests.decodesDisplaySpaces() ParcelPlatformTests.decodesWindowRecords() +ParcelPlatformTests.delayedGrowthMustNotCertifyAnUnchangedSmallerFrame(delay:) ParcelPlatformTests.delayedResizeCannotTurnStaleOversizingIntoATinyRequest(delay:nativeGrid:) ParcelPlatformTests.destroyedWindowOwnershipCannotWriteARecycledWindowID() ParcelPlatformTests.displayChangeBurstExtendsDeadline() @@ -661,6 +662,7 @@ ParcelPlatformTests.finalRepairsPositionChangedByTheSecondSizeWrite() ParcelPlatformTests.finalRetriesTransientPositionRefusalBeforeRestoringEnhancedUI() ParcelPlatformTests.finalSizeCorrectionFailureRetainsRealFrameAndRestoresEnhancedUI() ParcelPlatformTests.finalSizeCorrectionRestoresPositionChangedByNativeResize() +ParcelPlatformTests.fittingAnotherAxisPreservesTheCachedContainedRequest() ParcelPlatformTests.forgettingAWindowDropsItsLearnedGrid() ParcelPlatformTests.frameWriteCandidateCoversClampedOrPartialWrites() ParcelPlatformTests.frameWriteCandidatesAreWindowSpecificAndTagRepeatedNotifications() diff --git a/Tests/ParcelPlatformTests/AppFrameWriteTests.swift b/Tests/ParcelPlatformTests/AppFrameWriteTests.swift index 118b4c84..0db00d9c 100644 --- a/Tests/ParcelPlatformTests/AppFrameWriteTests.swift +++ b/Tests/ParcelPlatformTests/AppFrameWriteTests.swift @@ -566,6 +566,40 @@ func delayedResizeCannotTurnStaleOversizingIntoATinyRequest(delay: Int, nativeGr #expect(probe.enabled) } +@Test func fittingAnotherAxisPreservesTheCachedContainedRequest() throws { + let probe = BurstWriteProbe() + probe.sizeTransform = { snappedSize($0) } + let writer = AppThreadFrameWriter() + for (index, gap) in [16, 17, 23, 16].enumerated() { + if index == 2 { + probe.sizeTransform = { size in + CGSize(width: snappedSize(size).width, height: snappedSize(size, roundsUp: true).height) + } + } + let target = CGRect(x: gap, y: 38 + gap, width: 1512 - gap * 2, height: 886 - gap * 2) + let result = write( + writer, probe, + [AppThreadFrameWrite(windowID: 1, target: target, generation: UInt64(index + 1), phase: .final)]) + let actual = try #require(result.windows.first?.actual) + #expect(actual.origin == target.origin) + #expect(actual.width <= target.width && target.width - actual.width < 7) + #expect(actual.height <= target.height && target.height - actual.height < 14) + } +} + +@Test(arguments: [2, 3]) +func delayedGrowthMustNotCertifyAnUnchangedSmallerFrame(delay: Int) throws { + let probe = BurstWriteProbe() + probe.rectangle = CGRect(x: 80, y: 108, width: 300, height: 200) + probe.sizeWriteDelay = delay + let target = CGRect(x: 16, y: 54, width: 361, height: 854) + let actual = try executeFrameWrite( + target, window: probe, application: probe, assistiveTechnology: noAssistiveTechnology) + #expect(actual == target) + #expect(probe.writtenSizes.count <= 4) + #expect(probe.writtenSizes.allSatisfy { $0 == target.size }) +} + @Test func unconfirmedFittingRestoresTheTargetInsteadOfLeavingTheSmallestProbe() throws { let probe = BurstWriteProbe() probe.sizeWriteDelay = 100 diff --git a/Tests/Reality/RealityScenarios.swift b/Tests/Reality/RealityScenarios.swift index a38d1c19..25fa6324 100644 --- a/Tests/Reality/RealityScenarios.swift +++ b/Tests/Reality/RealityScenarios.swift @@ -164,8 +164,8 @@ extension RealityScenario { throw RealityError("Resize-grid config reload failed: \(reload.errors)") } let resizedTile = session.visible.inset(gap) - try await session.expect("Repeated grid fitting stays within the measured increment at gap \(gap)") - { + try await session.command("retile") + try await session.expect("Explicit Retile fits the measured resize increment at gap \(gap)") { FrameOracle.incrementFit( try FrameOracle.frames($0, ids: [owned[0].id])[0], tile: resizedTile, increment: increment) } -- knotmirror 0.0.1