import Foundation import ParcelConfig import ParcelCore import ParcelIPC import ParcelPlatform import Testing @testable import ParcelEngine @Suite @MainActor struct 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) } } @MainActor private 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, 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 } }