Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466import Foundationimport ParcelConfigimport ParcelCoreimport ParcelIPCimport ParcelPlatformimport Testing
@testable import ParcelEngine
@Suite @MainActorstruct RuleSpaceAssignmentRegressionTests { @Test(arguments: RuleAssignmentGate.allCases) func gatedArrivalsWaitUntilAssignmentsAreAllowed(gate: RuleAssignmentGate) async throws { let spaces = ControlledRuleSpaces() let harness = try EngineHarness(configuration: configuration(), spaceWorld: spaces) try await harness.start() gate.block(harness) try harness.add([1]) await harness.engine.ruleSpaceOperation?.value #expect(spaces.snapshotCalls == 0) #expect(spaces.calls.isEmpty) #expect(harness.engine.attemptedRuleSpaces.isEmpty) gate.unblock(harness) try await settle(harness) #expect(spaces.calls.map(\.desktop) == [2]) #expect(harness.engine.isAutomaticTilingEnabled) await harness.engine.stop() }
@Test(arguments: RuleAssignmentGate.allCases) func gatesChangedDuringSnapshotLeaveTheAssignmentPending(gate: RuleAssignmentGate) async throws { let spaces = ControlledRuleSpaces() spaces.deferSnapshots = true let harness = try EngineHarness(configuration: configuration(), spaceWorld: spaces) try await harness.start() try harness.add([1]) try await waitFor { spaces.pendingSnapshot != nil } gate.block(harness) spaces.deferSnapshots = false spaces.releaseSnapshot() try await settle(harness) #expect(spaces.calls.isEmpty) #expect(harness.engine.attemptedRuleSpaces.isEmpty) gate.unblock(harness) try await settle(harness) #expect(spaces.calls.map(\.desktop) == [2]) await harness.engine.stop() }
@Test func displaySuspensionDefersOnlyThatDisplaysAssignments() async throws { let spaces = ControlledRuleSpaces() var config = configuration() config.rules.append(RuleConfiguration(bundleID: secondEngineApp.bundleID, space: 2, moveToSpace: true)) let harness = try EngineHarness( configuration: config, initialState: engineInitialState(twoDisplays: true), spaceWorld: spaces) try await harness.start() harness.world.emit(.suspendedDisplaysChanged([engineDisplay])) try harness.add([1]) let other = WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)) try harness.add([2], app: secondEngineApp, workspace: other) try await settle(harness) #expect(spaces.calls.map(\.window) == [WindowID(rawValue: 2)]) #expect(harness.engine.attemptedRuleSpaces[WindowID(rawValue: 1)] == nil) harness.world.emit(.suspendedDisplaysChanged([])) try await settle(harness) #expect(spaces.calls.map(\.window) == [WindowID(rawValue: 2), WindowID(rawValue: 1)]) await harness.engine.stop() }
@Test(arguments: [true, false]) func removedRuleCannotMoveAfterSnapshotEvenBeforeReloadFlush(flushReload: Bool) async throws { let spaces = ControlledRuleSpaces() spaces.deferSnapshots = true var config = configuration() let harness = try EngineHarness(configuration: config, spaceWorld: spaces) try await harness.start() try harness.add([1]) try await waitFor { spaces.pendingSnapshot != nil } config.rules = [] try harness.engine.applyConfiguration(config) if flushReload { try harness.scheduler.runReady() } spaces.deferSnapshots = false spaces.releaseSnapshot() try await settle(harness) #expect(spaces.calls.isEmpty) #expect(harness.engine.attemptedRuleSpaces.isEmpty) #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) == engineWorkspace) #expect(!harness.log.diagnostics.contains { if case .internalFailure = $0 { true } else { false } }) await harness.engine.stop() }
@Test func replacementRuleIsScheduledWhenTheObsoleteOperationFinishes() async throws { let spaces = ControlledRuleSpaces() spaces.deferSnapshots = true var config = configuration() let harness = try EngineHarness(configuration: config, spaceWorld: spaces) try await harness.start() try harness.add([1]) try await waitFor { spaces.pendingSnapshot != nil } config.rules = [RuleConfiguration(bundleID: engineApp.bundleID, space: 3, moveToSpace: true)] try harness.engine.applyConfiguration(config) spaces.deferSnapshots = false spaces.releaseSnapshot() try await settle(harness) #expect(spaces.calls.map(\.desktop) == [3]) let destination = WorkspaceKey(display: engineDisplay, space: SpaceID(rawValue: 33)) #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) == destination) await harness.engine.stop() }
@Test func removingARuleWhileWritesDrainPreventsTheNativeMove() async throws { let spaces = ControlledRuleSpaces() var config = configuration() let harness = try EngineHarness(configuration: config, spaceWorld: spaces) harness.world.deferWrites = true try await harness.start() try harness.add([1]) try await waitFor { harness.engine.spaceCommandRunning } config.rules = [] try harness.engine.applyConfiguration(config) try harness.world.completeNextWrite() try await settle(harness) #expect(spaces.calls.isEmpty) #expect(harness.engine.attemptedRuleSpaces.isEmpty) #expect(harness.engine.isAutomaticTilingEnabled) await harness.engine.stop() }
@Test func disablingAutomaticTilingWhileRuleWritesDrainPreventsTheMoveAndSurvivesCompletion() async throws { let spaces = ControlledRuleSpaces() let harness = try EngineHarness(configuration: configuration(), spaceWorld: spaces) harness.world.deferWrites = true try await harness.start() try harness.add([1]) try await waitFor { harness.engine.spaceCommandRunning } #expect(harness.engine.isAutomaticTilingEnabled) harness.engine.setAutomaticTilingEnabled(false) try harness.world.completeNextWrite() try await settle(harness) #expect(spaces.calls.isEmpty) #expect(harness.engine.attemptedRuleSpaces.isEmpty) #expect(!harness.engine.isAutomaticTilingEnabled) await harness.engine.stop() }
@Test func obsoleteMoveCompletionReconcilesWithoutInventingOldRulePlacement() async throws { let spaces = ControlledRuleSpaces() spaces.deferMoves = true var config = configuration() let harness = try EngineHarness(configuration: config, spaceWorld: spaces) try await harness.start() try harness.add([1]) try await waitFor { spaces.pendingMove != nil } config.rules = [] try harness.engine.applyConfiguration(config) try harness.scheduler.runReady() spaces.releaseMove() try await settle(harness) #expect(spaces.calls.map(\.desktop) == [2]) #expect(harness.engine.attemptedRuleSpaces.isEmpty) #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) == engineWorkspace) #expect(!harness.world.reconciliations.isEmpty) #expect(harness.engine.isAutomaticTilingEnabled) await harness.engine.stop() }
@Test func unavailableRequestedDisplayDoesNotMoveTheWindowOnADifferentDisplay() async throws { let spaces = ControlledRuleSpaces() var config = configuration() config.rules[0].display = "missing-display" let harness = try EngineHarness(configuration: config, spaceWorld: spaces) try await harness.start() try harness.add([1]) try await settle(harness) #expect(spaces.calls.isEmpty && spaces.snapshotCalls == 0) #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) == engineWorkspace) #expect( harness.log.diagnostics.contains { if case .configuration(let message) = $0 { message.contains("unavailable") } else { false } }) await harness.engine.stop() }
@Test func spaceDestinationWithoutConsentNeverPostsAMove() async throws { let spaces = ControlledRuleSpaces() var config = configuration() config.rules[0].moveToSpace = false let harness = try EngineHarness(configuration: config, spaceWorld: spaces) try await harness.start() try harness.add([1]) try await settle(harness) #expect(spaces.snapshotCalls == 0) #expect(spaces.calls.isEmpty) #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) == engineWorkspace) await harness.engine.stop() }
@Test func existingStartupWindowsDoNotMoveEvenAfterReloadOrRetile() async throws { let initial = reduce( engineInitialState(), .windowAppeared( engineWindow(1), workspace: engineWorkspace, frame: initialEngineFrame) ).0 let spaces = ControlledRuleSpaces() let harness = try EngineHarness(configuration: configuration(), initialState: initial, spaceWorld: spaces) try await harness.start() try harness.add([1]) var config = configuration() config.rules[0].space = 3 try harness.engine.applyConfiguration(config) harness.engine.send(.commandIssued(.retile)) try await settle(harness) #expect(spaces.calls.isEmpty) #expect(harness.engine.eligibleRuleSpaceWindows.isEmpty) await harness.engine.stop() }
@Test func delayedStartupFactsNeverBecomeEligibleForAutomaticMoves() async throws { let spaces = ControlledRuleSpaces() var config = configuration() let harness = try EngineHarness( configuration: config, spaceWorld: spaces, startupWindowIDs: { [WindowID(rawValue: 1), WindowID(rawValue: 9)] }) try await harness.start() #expect(harness.engine.callbacksPrimed) try harness.add([1]) try await settle(harness) #expect(spaces.calls.isEmpty && spaces.snapshotCalls == 0) config.rules[0].space = 3 try harness.engine.applyConfiguration(config) try await settle(harness) #expect(spaces.calls.isEmpty) try harness.add([2]) try await settle(harness) #expect(spaces.calls.map(\.window) == [WindowID(rawValue: 2)]) #expect(spaces.calls.map(\.desktop) == [3]) #expect(!harness.engine.eligibleRuleSpaceWindows.contains(WindowID(rawValue: 1))) await harness.engine.stop() }
@Test func failingStartupWindowScanStopsBeforeObservingOrMovingWindows() async throws { let spaces = ControlledRuleSpaces() let harness = try EngineHarness( configuration: configuration(), spaceWorld: spaces, startupWindowIDs: { throw RuleAssignmentTestError.startupScanFailed }) await #expect(throws: RuleAssignmentTestError.startupScanFailed) { try await harness.start() } #expect(!harness.engine.isRunning) #expect(harness.world.startCount == 0) #expect(spaces.calls.isEmpty) }
@Test func activeInputDefersWithoutConsumingTheAttempt() async throws { let spaces = ControlledRuleSpaces() spaces.inputBusy = true let harness = try EngineHarness(configuration: configuration(), spaceWorld: spaces) try await harness.start() try harness.add([1]) await harness.engine.ruleSpaceOperation?.value #expect(spaces.calls.isEmpty) #expect(harness.engine.attemptedRuleSpaces.isEmpty) #expect(harness.engine.ruleSpaceMoveHistory.isEmpty) #expect(harness.engine.ruleSpaceRetry != nil) #expect(!harness.engine.isIdle) spaces.inputBusy = false harness.clock.now += 0.36 try await settle(harness) #expect(spaces.calls.map(\.desktop) == [2]) #expect(harness.engine.ruleSpaceMoveHistory.map(\.desktop) == [2]) await harness.engine.stop() }
@Test func savedMoveHistoryPreventsASecondMoveAfterRelaunch() async throws { let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) let store = RuleSpaceMoveStore(fileURL: folder.appendingPathComponent("moves.json")) let firstSpaces = ControlledRuleSpaces() let first = try EngineHarness( configuration: configuration(), spaceWorld: firstSpaces, ruleSpaceMoveStore: store) try await first.start() try first.add([1]) try await settle(first) #expect(firstSpaces.calls.map(\.desktop) == [2]) #expect( try store.load() == [ RuleSpaceMoveRecord( window: 1, pid: 100, bundleID: "test.fixture", display: engineDisplay.rawValue, desktop: 2) ]) await first.engine.stop() let secondSpaces = ControlledRuleSpaces() let second = try EngineHarness( configuration: configuration(), spaceWorld: secondSpaces, ruleSpaceMoveStore: store) try await second.start() try second.add([1]) try await settle(second) #expect(secondSpaces.calls.isEmpty) #expect(secondSpaces.snapshotCalls == 0) await second.engine.stop() try FileManager.default.removeItem(at: folder) }
@Test func failedMoveHistorySaveSurfacesFeedbackWithoutRepeatingTheGesture() async throws { let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) let store = RuleSpaceMoveStore(fileURL: folder.appendingPathComponent("moves.json")) let spaces = ControlledRuleSpaces() let harness = try EngineHarness(configuration: configuration(), spaceWorld: spaces, ruleSpaceMoveStore: store) var failures: [any Error] = [] harness.engine.onFailure = { failures.append($0) } try await harness.start() try FileManager.default.createDirectory(at: store.fileURL, withIntermediateDirectories: true) defer { do { try FileManager.default.removeItem(at: folder) } catch { Issue.record(error) } } try harness.add([1]) try await settle(harness) #expect(spaces.calls.map(\.window) == [WindowID(rawValue: 1)]) #expect( harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) == WorkspaceKey(display: engineDisplay, space: SpaceID(rawValue: 22))) #expect(failures.count == 1) #expect((failures.first as? IPCError)?.code == "space_command_failed") #expect(harness.engine.ruleSpaceMoveHistory.isEmpty) harness.engine.send(.relayout) try await settle(harness) #expect(spaces.calls.map(\.window) == [WindowID(rawValue: 1)]) #expect(failures.count == 1) await harness.engine.stop() }
@Test func revokingConsentWhileSnapshotIsPendingCancelsTheMove() async throws { let spaces = ControlledRuleSpaces() spaces.deferSnapshots = true var config = configuration() let harness = try EngineHarness(configuration: config, spaceWorld: spaces) try await harness.start() try harness.add([1]) try await waitFor { spaces.pendingSnapshot != nil } config.rules[0].moveToSpace = false try harness.engine.applyConfiguration(config) spaces.deferSnapshots = false spaces.releaseSnapshot() try await settle(harness) #expect(spaces.calls.isEmpty) #expect(harness.engine.ruleSpaceMoveHistory.isEmpty) await harness.engine.stop() }
private func configuration() -> ParcelConfiguration { var config = engineConfiguration() config.rules = [RuleConfiguration(bundleID: engineApp.bundleID, space: 2, moveToSpace: true)] return config }
private func waitFor(_ condition: @MainActor () -> Bool) async throws { let deadline = ContinuousClock.now.advanced(by: .seconds(1)) while !condition() { guard ContinuousClock.now < deadline else { throw RuleAssignmentTestError.didNotSettle } await Task.yield() } }
private func settle(_ harness: EngineHarness) async throws { for _ in 0..<10 { try harness.scheduler.runReady() await harness.engine.ruleSpaceOperation?.value try harness.scheduler.runReady() if harness.engine.ruleSpaceOperation == nil { return } } throw RuleAssignmentTestError.didNotSettle }}
private enum RuleAssignmentTestError: Error { case didNotSettle, startupScanFailed }
enum RuleAssignmentGate: CaseIterable, Sendable { case automaticTilingOff, suspension, permission
@MainActor func block(_ harness: EngineHarness) { switch self { case .automaticTilingOff: harness.engine.setAutomaticTilingEnabled(false) case .suspension: harness.world.emit(.suspendedDisplaysChanged([engineDisplay])) case .permission: harness.engine.writesPermitted = false } }
@MainActor func unblock(_ harness: EngineHarness) { switch self { case .automaticTilingOff: harness.engine.setAutomaticTilingEnabled(true) case .suspension: harness.world.emit(.suspendedDisplaysChanged([])) case .permission: harness.engine.writesPermitted = true } harness.engine.send(.relayout) }}
@MainActorprivate final class ControlledRuleSpaces: EngineSpaceWorld { struct Call { let window: WindowID let desktop: Int }
var inputBusy = false var deferSnapshots = false var deferMoves = false var snapshotCalls = 0 var calls: [Call] = [] var pendingSnapshot: CheckedContinuation<[NativeDisplaySpaces], any Error>? var pendingMove: (continuation: CheckedContinuation<SpaceCommandResult, any Error>, result: SpaceCommandResult)?
private var displays: [NativeDisplaySpaces] { [ NativeDisplaySpaces( displayID: engineDisplay.rawValue, currentSpace: 1, spaces: [ NativeSpace(id: 1, kind: .desktop, desktopNumber: 1), NativeSpace(id: 22, kind: .desktop, desktopNumber: 2), NativeSpace(id: 33, kind: .desktop, desktopNumber: 3), ]), NativeDisplaySpaces( displayID: secondEngineDisplay.rawValue, currentSpace: 2, spaces: [ NativeSpace(id: 2, kind: .desktop, desktopNumber: 1), NativeSpace(id: 44, kind: .desktop, desktopNumber: 2), ]), ] }
func spaceSnapshot() async throws -> [NativeDisplaySpaces] { snapshotCalls += 1 if deferSnapshots { return try await withCheckedThrowingContinuation { pendingSnapshot = $0 } } return displays }
func releaseSnapshot() { pendingSnapshot?.resume(returning: displays) pendingSnapshot = nil }
func executeSpaceCommand(_ destination: SpaceDestination, display: DisplayID, window: WindowID?, follow: Bool) async throws -> SpaceCommandResult { guard case .desktop(let desktop) = destination, let window, let native = displays.first(where: { $0.displayID == display.rawValue }), let target = native.spaces.first(where: { $0.desktopNumber == desktop }) else { throw SpaceCommandError.displayUnavailable } #expect(!follow) if inputBusy { throw SpaceCommandError.inputBusy } calls.append(Call(window: window, desktop: desktop)) let result = SpaceCommandResult( displayID: display.rawValue, source: native.currentSpace, destination: target.id, followed: false, verificationSamples: 3) if deferMoves { return try await withCheckedThrowingContinuation { pendingMove = ($0, result) } } return result }
func releaseMove() { if let pendingMove { pendingMove.continuation.resume(returning: pendingMove.result) } pendingMove = nil }}