import ParcelConfig import ParcelCore import ParcelIPC import ParcelPlatform import Testing @testable import ParcelEngine @Suite @MainActor struct RuleActionTests { @Test func alwaysFloatWritesRuleThroughKeyboardAndIPCPaths() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) var written: [WindowID] = [] harness.engine.onAlwaysFloat = { written.append($0.id) } let configured = try await ruleTurn(harness) { try await harness.engine.performConfigured(.alwaysFloat) } #expect(configured.isAccepted) let result = try await ruleTurn(harness) { try await EngineIPCHandler(engine: harness.engine).run(command: "always-float", args: []) } guard case .object(let values) = result else { Issue.record("Expected command result") return } #expect(values["accepted"] == .bool(true)) harness.engine.send(.commandIssued(.alwaysFloat)) try harness.scheduler.runReady() for operation in harness.engine.windowOperations.values { await operation.task.value } #expect(written == [WindowID(rawValue: 1), WindowID(rawValue: 1), WindowID(rawValue: 1)]) await harness.engine.stop() } @Test func targetSpecificFloatingRuleDoesNotUseTheFocusedWindow() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) var written: [WindowID] = [] harness.engine.onAlwaysFloat = { written.append($0.id) } let target = WindowID(rawValue: 1) let focused = harness.engine.snapshot.focusedWindow #expect(try await harness.engine.alwaysFloat(window: target).isAccepted) #expect(written == [target]) #expect(harness.engine.snapshot.focusedWindow == focused) await #expect(throws: IPCError.self) { try await harness.engine.alwaysFloat(window: WindowID(rawValue: 99)) } await harness.engine.stop() await #expect(throws: EngineError.self) { try await harness.engine.alwaysFloat(window: target) } } @Test(.timeLimit(.minutes(1))) func targetSpecificFloatingRuleIsBusyAndCancellable() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) let target = WindowID(rawValue: 1) let world = harness.world world.deferWindowCommands = true let started = AsyncStream.makeStream(of: Void.self) defer { started.continuation.finish() } world.onWindowCommandPending = { started.continuation.yield(()) } harness.engine.onAlwaysFloat = { window in try await world.close(window.id) } let task = Task { try await harness.engine.alwaysFloat(window: target) } var operations: [Task] = [] do { try await waitForRuleStart(started.stream) try #require(world.pendingWindowCommandCount == 1) #expect(world.closed == [target]) operations = harness.engine.windowOperations.values.map(\.task) try #require(operations.count == 1) await #expect(throws: EngineWindowCommandError.busy(target)) { try await harness.engine.alwaysFloat(window: target) } task.cancel() await #expect(throws: CancellationError.self) { try await task.value } #expect(world.pendingWindowCommandCount == 1) try world.completeWindowCommand() for operation in operations { await operation.value } #expect(harness.engine.windowOperations.isEmpty) } catch { await finishRuleTest(harness, task: task, operations: operations) throw error } await finishRuleTest(harness, task: task, operations: operations) } @Test(.timeLimit(.minutes(1))) func canceledRuleWriterPreservesALaterManualTile() async throws { var configuration = engineConfiguration() configuration.rules = [RuleConfiguration(bundleID: engineApp.bundleID, action: .float)] let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1]) let target = WindowID(rawValue: 1) let world = harness.world world.deferWindowCommands = true let started = AsyncStream.makeStream(of: Void.self) defer { started.continuation.finish() } world.onWindowCommandPending = { started.continuation.yield(()) } harness.engine.onAlwaysFloat = { window in do { try await world.close(window.id) } catch is CancellationError {} } let task = Task { try await harness.engine.alwaysFloat(window: target) } var operations: [Task] = [] do { try await waitForRuleStart(started.stream) operations = harness.engine.windowOperations.values.map(\.task) try #require(operations.count == 1) task.cancel() await #expect(throws: CancellationError.self) { try await task.value } harness.engine.send(.commandIssued(.tileWindow(target))) try harness.scheduler.runReady() try #require(harness.engine.manualFloating[target] == false) try world.completeWindowCommand() for operation in operations { await operation.value } try harness.scheduler.runReady() #expect(harness.engine.manualFloating[target] == false) #expect(harness.engine.snapshot.state.windows[target]?.isFloating == false) #expect(harness.engine.classifications[target]?.reason == .manual) } catch { await finishRuleTest(harness, task: task, operations: operations) throw error } await finishRuleTest(harness, task: task, operations: operations) } @Test(.timeLimit(.minutes(1))) func canceledRuleWriterCannotReapplyToANewEngineLifetime() async throws { var configuration = engineConfiguration() configuration.rules = [RuleConfiguration(bundleID: engineApp.bundleID, action: .float)] let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1]) let target = WindowID(rawValue: 1) let world = harness.world world.deferWindowCommands = true let started = AsyncStream.makeStream(of: Void.self) defer { started.continuation.finish() } world.onWindowCommandPending = { started.continuation.yield(()) } var writerSawCancellation = false harness.engine.onAlwaysFloat = { window in do { try await world.close(window.id) } catch is CancellationError { writerSawCancellation = true } } let task = Task { try await harness.engine.alwaysFloat(window: target) } var operations: [Task] = [] do { try await waitForRuleStart(started.stream) try #require(world.pendingWindowCommandCount == 1) operations = harness.engine.windowOperations.values.map(\.task) try #require(operations.count == 1) await harness.engine.stop() await #expect(throws: EngineError.stopped) { try await task.value } try await harness.start() try harness.add([1]) try #require(harness.engine.snapshot.state.windows[target]?.isFloating == true) harness.engine.send(.commandIssued(.tileWindow(target))) try harness.scheduler.runReady() try #require(harness.engine.manualFloating[target] == false) try world.completeWindowCommand() for operation in operations { await operation.value } #expect(writerSawCancellation) #expect(harness.engine.manualFloating[target] == false) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[target]?.isFloating == false) #expect(harness.engine.classifications[target]?.reason == .manual) } catch { await finishRuleTest(harness, task: task, operations: operations) throw error } await finishRuleTest(harness, task: task, operations: operations) } @Test func factRefreshDoesNotUndoAUserLayoutChoice() async throws { var config = engineConfiguration() config.rules = [RuleConfiguration(bundleID: engineApp.bundleID, layout: .rows)] let harness = try EngineHarness(configuration: config) try await harness.start() try harness.add([1]) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.layout == .rows) harness.engine.send(.commandIssued(.setLayout(.columns))) try harness.scheduler.runReady() harness.world.appear(engineWindow(1)) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.layout == .columns) await harness.engine.stop() } @Test func ruleEditsPreserveManualChoicesUntilAnExplicitAppReapply() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) try harness.add([2], app: secondEngineApp) harness.engine.send(.focusChanged(WindowID(rawValue: 2))) harness.engine.send(.commandIssued(.toggleFloat)) try harness.scheduler.runReady() var config = harness.engine.configuration config.rules = [RuleConfiguration(bundleID: engineApp.bundleID, action: .float)] try harness.engine.applyConfiguration(config) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 2)]?.isFloating == true) #expect(harness.engine.classifications[WindowID(rawValue: 2)]?.reason == .manual) config.rules.append(RuleConfiguration(bundleID: secondEngineApp.bundleID, action: .tile)) try harness.engine.applyConfiguration(config) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 2)]?.isFloating == true) try harness.engine.reapplyRules(for: secondEngineApp.bundleID) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 2)]?.isFloating == false) #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 1)]?.isFloating == true) #expect(throws: MinimumSizeLearningError.self) { try harness.engine.reapplyRules(for: "") } await harness.engine.stop() #expect(throws: EngineError.self) { try harness.engine.reapplyRules(for: secondEngineApp.bundleID) } } @Test func explicitAppRuleReapplyArrangesWhileAutomaticTilingIsOff() async throws { var configuration = engineConfiguration() configuration.rules = [RuleConfiguration(bundleID: engineApp.bundleID, action: .float)] let harness = try EngineHarness( configuration: configuration, initialState: engineInitialState(twoDisplays: true)) try await harness.start() try harness.add([1, 2]) let other = WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)) try harness.add([3], app: secondEngineApp, workspace: other) harness.engine.setAutomaticTilingEnabled(false) let writes = harness.world.allWrites.count configuration.rules = [] try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() #expect(harness.world.allWrites.count == writes) let otherFrame = harness.world.frames[WindowID(rawValue: 3)] try harness.engine.reapplyRules(for: engineApp.bundleID) try harness.scheduler.runReady() try harness.finishMotion() for id in [WindowID(rawValue: 1), WindowID(rawValue: 2)] { #expect(harness.engine.snapshot.state.windows[id]?.isFloating == false) #expect(harness.world.frames[id] == harness.engine.snapshot.state.frames[id]) #expect(harness.world.frames[id] != initialEngineFrame) } #expect(harness.world.frames[WindowID(rawValue: 3)] == otherFrame) #expect(!harness.world.allWrites.dropFirst(writes).contains { $0.window == WindowID(rawValue: 3) }) #expect(!harness.engine.isAutomaticTilingEnabled) await harness.engine.stop() } @Test func savingAndRemovingAFloatRulePreservesAnExistingManualFloat() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) let window = WindowID(rawValue: 1) harness.engine.send(.commandIssued(.toggleFloat)) try harness.scheduler.runReady() harness.engine.onAlwaysFloat = { [weak engine = harness.engine] _ in guard let engine else { throw EngineError.stopped } var config = engine.configuration config.rules = [RuleConfiguration(bundleID: engineApp.bundleID, action: .float)] try engine.applyConfiguration(config) } _ = try await ruleTurn(harness) { try await harness.engine.perform(.alwaysFloat) } try harness.scheduler.runReady() var config = harness.engine.configuration config.rules = [] try harness.engine.applyConfiguration(config) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[window]?.isFloating == true) #expect(harness.engine.classifications[window]?.reason == .manual) await harness.engine.stop() } @Test func repeatedAlwaysFloatReappliesAnExistingRuleAfterManualTiling() async throws { var config = engineConfiguration() config.rules = [RuleConfiguration(bundleID: engineApp.bundleID, action: .float)] let harness = try EngineHarness(configuration: config) try await harness.start() try harness.add([1]) let window = WindowID(rawValue: 1) harness.engine.send(.commandIssued(.tileWindow(window))) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[window]?.isFloating == false) harness.engine.onAlwaysFloat = { _ in } _ = try await ruleTurn(harness) { try await harness.engine.perform(.alwaysFloat) } try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[window]?.isFloating == true) await harness.engine.stop() } @Test func missingWriterAndFailedPersistenceAreNotAccepted() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) var failures: [EngineError] = [] harness.engine.onFailure = { if let error = $0 as? EngineError { failures.append(error) } } await #expect(throws: EngineError.settingsUnavailable) { try await ruleTurn(harness) { try await harness.engine.perform(.alwaysFloat) } } #expect(failures == [.settingsUnavailable]) harness.engine.onAlwaysFloat = { _ in throw RuleTestFailure.write } await #expect(throws: RuleTestFailure.self) { try await ruleTurn(harness) { try await harness.engine.perform(.alwaysFloat) } } #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 1)]?.isFloating == false) await harness.engine.stop() } @Test func undoLastRuleUsesWriterWithoutAFocusedWindow() async throws { let harness = try EngineHarness() try await harness.start() var undoCount = 0 harness.engine.onUndoLastRule = { undoCount += 1 } let result = try await ruleTurn(harness) { try await harness.engine.performConfigured(.undoLastRule) } #expect(result.isAccepted) #expect(undoCount == 1) #expect(harness.engine.snapshot.focusedWindow == nil) let ipc = EngineIPCHandler(engine: harness.engine) _ = try await ruleTurn(harness) { try await ipc.run(command: "undo-last-rule", args: []) } #expect(undoCount == 2) harness.engine.onUndoLastRule = nil await #expect(throws: EngineError.settingsUnavailable) { try await ruleTurn(harness) { try await harness.engine.perform(.undoLastRule) } } await harness.engine.stop() } @Test func nativeSpaceRuleUsesVerifiedMoveWithoutFollowingAndAppliesDestinationLayout() async throws { let spaces = RuleSpaces() var configuration = engineConfiguration() configuration.rules = [ RuleConfiguration(bundleID: engineApp.bundleID, layout: .rows, space: 2, moveToSpace: true) ] let harness = try EngineHarness(configuration: configuration, spaceWorld: spaces) try await harness.start() try harness.add([1]) await harness.engine.ruleSpaceOperation?.value try harness.scheduler.runReady() #expect(spaces.calls == [WindowID(rawValue: 1)]) let destination = WorkspaceKey(display: engineDisplay, space: SpaceID(rawValue: 22)) #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) == destination) #expect(harness.engine.snapshot.state.workspaces[destination]?.layout == .rows) #expect(harness.engine.snapshot.state.activeSpaces[engineDisplay] == SpaceID(rawValue: 1)) #expect(harness.engine.isAutomaticTilingEnabled) #expect(harness.engine.snapshot.focusedWindow == nil) harness.engine.send(.relayout) try harness.scheduler.runReady() await harness.engine.ruleSpaceOperation?.value #expect(spaces.calls.count == 1) await harness.engine.stop() } @Test(arguments: [ SpaceCommandResult( displayID: "another-display", source: 1, destination: 22, followed: false, verificationSamples: 3), SpaceCommandResult( displayID: engineDisplay.rawValue, source: 1, destination: 33, followed: false, verificationSamples: 3), SpaceCommandResult( displayID: engineDisplay.rawValue, source: 1, destination: 22, followed: true, verificationSamples: 3), SpaceCommandResult( displayID: engineDisplay.rawValue, source: 1, destination: 22, followed: false, verificationSamples: 0), ]) func mismatchedMoveReadbackCannotInventPlacementOrSuccessfulHistory(result: SpaceCommandResult) async throws { let spaces = RuleSpaces() spaces.resultOverride = result var config = engineConfiguration() config.rules = [RuleConfiguration(bundleID: engineApp.bundleID, space: 2, moveToSpace: true)] let harness = try EngineHarness(configuration: config, spaceWorld: spaces) var failures: [IPCError] = [] harness.engine.onFailure = { error in guard let failure = error as? IPCError else { Issue.record("Expected a Space command failure") return } failures.append(failure) } try await harness.start() try harness.add([1]) await harness.engine.ruleSpaceOperation?.value try harness.scheduler.runReady() #expect(spaces.calls == [WindowID(rawValue: 1)]) #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) == engineWorkspace) #expect(harness.engine.ruleSpaceMoveHistory.isEmpty) #expect(failures.count == 1 && failures.first?.code == "space_command_failed") #expect(harness.engine.isAutomaticTilingEnabled) harness.engine.send(.relayout) try harness.scheduler.runReady() await harness.engine.ruleSpaceOperation?.value #expect(spaces.calls == [WindowID(rawValue: 1)]) await harness.engine.stop() } @Test func unavailableOrUnverifiedSpacesSurfaceFailureAndDoNotInventPlacement() async throws { for unverified in [false, true] { let spaces = RuleSpaces() spaces.unverified = unverified spaces.missing = !unverified var config = engineConfiguration() config.rules = [RuleConfiguration(bundleID: engineApp.bundleID, space: 2, moveToSpace: true)] let harness = try EngineHarness(configuration: config, spaceWorld: spaces) var failures: [IPCError] = [] harness.engine.onFailure = { error in guard let failure = error as? IPCError else { Issue.record("Expected a Space command failure") return } failures.append(failure) } try await harness.start() try harness.add([1]) await harness.engine.ruleSpaceOperation?.value try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) == engineWorkspace) #expect(harness.log.diagnostics.contains { if case .internalFailure = $0 { true } else { false } }) #expect(failures.count == 1) #expect(failures.first?.code == "space_command_failed") #expect(failures.first?.message.isEmpty == false) #expect(harness.engine.isAutomaticTilingEnabled) harness.engine.send(.relayout) try harness.scheduler.runReady() await harness.engine.ruleSpaceOperation?.value #expect(spaces.calls.count == (unverified ? 1 : 0)) await harness.engine.stop() } } } private func waitForRuleStart(_ starts: AsyncStream) async throws { var iterator = starts.makeAsyncIterator() guard let _ = await iterator.next() else { throw RuleTestFailure.observationEnded } } @MainActor private func finishRuleTest( _ harness: EngineHarness, task: Task, operations: [Task] ) async { task.cancel() let pendingOperations = operations + harness.engine.windowOperations.values.map(\.task) await harness.engine.stop() while harness.world.pendingWindowCommandCount > 0 { do { try harness.world.completeWindowCommand() } catch { Issue.record(error) break } } for operation in pendingOperations { await operation.value } _ = await task.result } @MainActor private func ruleTurn(_ harness: EngineHarness, action: @escaping @MainActor () async throws -> Value) async throws -> Value { var completed = false let task = Task { defer { completed = true } return try await action() } for _ in 0..<1000 where !completed { await Task.yield() try harness.scheduler.runReady() } guard completed else { task.cancel() throw RuleTestFailure.timeout } return try await task.value } private enum RuleTestFailure: Error { case write, timeout, observationEnded } @MainActor private final class RuleSpaces: EngineSpaceWorld { var missing = false var unverified = false var resultOverride: SpaceCommandResult? var calls: [WindowID] = [] func spaceSnapshot() async throws -> [NativeDisplaySpaces] { [ NativeDisplaySpaces( displayID: engineDisplay.rawValue, currentSpace: 1, spaces: missing ? [] : [ NativeSpace(id: 1, kind: .desktop, desktopNumber: 1), NativeSpace(id: 22, kind: .desktop, desktopNumber: 2), ]) ] } func executeSpaceCommand(_ destination: SpaceDestination, display: DisplayID, window: WindowID?, follow: Bool) async throws -> SpaceCommandResult { #expect(destination == .desktop(2)) #expect(!follow) calls.append(try #require(window)) return resultOverride ?? SpaceCommandResult( displayID: display.rawValue, source: 1, destination: 22, followed: false, verificationSamples: unverified ? 0 : 3) } }