import Foundation import ParcelConfig import ParcelCore import ParcelIPC import Testing @testable import ParcelEngine private let configuredEngineCommands: [(ConfigCommand, Command)] = [ (.focusLeft, .focus(.left)), (.focusRight, .focus(.right)), (.focusUp, .focus(.up)), (.focusDown, .focus(.down)), (.swapLeft, .swap(.left)), (.swapRight, .swap(.right)), (.swapUp, .swap(.up)), (.swapDown, .swap(.down)), (.moveLeft, .move(.left)), (.moveRight, .move(.right)), (.moveUp, .move(.up)), (.moveDown, .move(.down)), (.layoutGrid, .setLayout(.grid)), (.layoutColumns, .setLayout(.columns)), (.layoutRows, .setLayout(.rows)), (.layoutSide, .setLayout(.side)), (.layoutTree, .setLayout(.tree)), (.layoutBSP, .setLayout(.bsp)), (.layoutAccordion, .setLayout(.accordion)), (.splitHorizontal, .split(.horizontal)), (.splitVertical, .split(.vertical)), (.joinLeft, .join(.left)), (.joinRight, .join(.right)), (.joinUp, .join(.up)), (.joinDown, .join(.down)), (.balance, .balance), (.rotate, .rotate), (.mirrorHorizontal, .mirror(.horizontal)), (.mirrorVertical, .mirror(.vertical)), (.ratioIncrease, .nudgeRatio(0.05)), (.ratioDecrease, .nudgeRatio(-0.05)), (.ratioHalf, .setRatio(.half)), (.ratioThreeFifths, .setRatio(.threeFifths)), (.ratioTwoThirds, .setRatio(.twoThirds)), (.floatToggle, .toggleFloat), (.retile, .retile), (.stack, .stack(.right)), (.stackNext, .focusNextInStack), (.stackPrevious, .focusPreviousInStack), (.displayMoveLeft, .moveToDisplay(.left)), (.displayMoveRight, .moveToDisplay(.right)), (.displayMoveUp, .moveToDisplay(.up)), (.displayMoveDown, .moveToDisplay(.down)), (.makePrimary, .makePrimary), (.windowNext, .focusNextWindow), (.windowPrevious, .focusPreviousWindow), (.resetSizes, .resetSizes), (.unstack, .unstack), (.close, .close), (.toggleFullscreen, .toggleFullscreen), (.alwaysFloat, .alwaysFloat), (.undoLastRule, .undoLastRule), (.toggleFocus, .toggleFocus), (.toggleNoPeek, .toggleNoPeek), (.toggleCleanSpace, .toggleCleanSpace), (.toggleBorders, .toggleBorders), (.toggleHoverFocus, .toggleHoverFocus), (.undo, .undo), ] + (0...5).map { (ConfigCommand.setWindowCap($0), Command.setWindowCap($0)) } + SnapAction.allCases.compactMap { action in ConfigCommand(rawValue: "snap-\(action.rawValue)").map { ($0, .snap(action)) } } private let shellCommands: Set = [ .openSettings, .toggleAutomaticTiling, .quit, .tabView, .windowControls, ] @Suite("Engine command parser") struct ParcelEngineParserTests { @Test func everyConfigCommandHasExplicitMappingOrShellRejection() throws { let nativeCommands = Set(ConfigCommand.allCases.filter(\.isSpaceCommand)) #expect(configuredEngineCommands.count == 85) #expect(Set(configuredEngineCommands.map { $0.0 }).count == 85) #expect(shellCommands.count == 5) #expect(nativeCommands.count == 55) #expect( Set(configuredEngineCommands.map { $0.0 }).union(shellCommands).union(nativeCommands) == Set(ConfigCommand.allCases)) for (configured, expected) in configuredEngineCommands { #expect(try EngineCommandParser.command(configured) == expected) #expect(try EngineCommandParser.parse(configured.rawValue) == expected) } for command in shellCommands { do { _ = try EngineCommandParser.command(command) Issue.record("\(command) must stay with the app shell") } catch let error as IPCError { #expect(error.code == "shell_command") } } } @Test func directionalAndLayoutArgumentsAreMappedExhaustively() throws { for direction in Direction.allCases { #expect(try EngineCommandParser.parse("focus", args: [direction.rawValue]) == .focus(direction)) #expect(try EngineCommandParser.parse("swap", args: [direction.rawValue]) == .swap(direction)) #expect(try EngineCommandParser.parse("move", args: [direction.rawValue]) == .move(direction)) #expect(try EngineCommandParser.parse("stack", args: [direction.rawValue]) == .stack(direction)) #expect( try EngineCommandParser.parse("move-to-display", args: [direction.rawValue]) == .moveToDisplay(direction)) } for action in SnapAction.allCases { #expect(try EngineCommandParser.parse("snap", args: [action.rawValue]) == .snap(action)) } for layout in Layout.allCases { #expect(try EngineCommandParser.parse("set-layout", args: [layout.rawValue]) == .setLayout(layout)) } #expect(try EngineCommandParser.parse("enter-mode", args: ["resize"]) == .enterMode("resize")) #expect(try EngineCommandParser.parse("exit-mode") == .enterMode(nil)) #expect(try EngineCommandParser.parse("cycle-layout") == .cycleLayout) #expect(try EngineCommandParser.parse("toggle-float") == .toggleFloat) #expect(try EngineCommandParser.parse("unstack") == .unstack) #expect(try EngineCommandParser.parse("focus-next-in-stack") == .focusNextInStack) #expect(try EngineCommandParser.parse("focus-previous-in-stack") == .focusPreviousInStack) #expect(try EngineCommandParser.parse("set-ratio", args: ["0.2"]) == .setRatio(MainRatio(0.2))) #expect(try EngineCommandParser.parse("set-ratio", args: ["0.8"]) == .setRatio(MainRatio(0.8))) #expect(try EngineCommandParser.parse("nudge-ratio", args: ["-0.05"]) == .nudgeRatio(-0.05)) #expect(try EngineCommandParser.parse("set-window-cap", args: ["12"]) == .setWindowCap(12)) } @Test func invalidCommandsArgumentsAndNonfiniteNumbersAreRejected() { let invalid: [(String, [String])] = [ ("unknown", []), ("", []), ("enter-mode", []), ("enter-mode", [" "]), ("enter-mode", ["resize", "other"]), ("exit-mode", ["extra"]), ("snap", []), ("snap", ["unknown"]), ("snap", ["left-half", "right-half"]), ("focus", []), ("focus", ["left", "right"]), ("focus", ["Left"]), ("swap", ["diagonal"]), ("move", [""]), ("set-layout", ["spiral"]), ("cycle-layout", ["grid"]), ("layout-grid", ["rows"]), ("retile", ["extra"]), ("set-ratio", ["0.19"]), ("set-ratio", ["0.81"]), ("set-ratio", ["nan"]), ("set-ratio", ["inf"]), ("nudge-ratio", ["nan"]), ("nudge-ratio", ["-inf"]), ("nudge-ratio", ["text"]), ("set-window-cap", ["1.5"]), ("set-window-cap", ["999999999999999999999999999999"]), ] for (command, args) in invalid { #expect(throws: IPCError.self) { try EngineCommandParser.parse(command, args: args) } } } } private func engineJSON(_ value: some Encodable) throws -> JSONValue { try JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(value)) } @MainActor private func expectEngineIPCError(_ code: String, action: @MainActor () async throws -> JSONValue) async throws { do { _ = try await action() Issue.record("Expected IPC rejection with code \(code)") } catch let error as IPCError { #expect(error.code == code) #expect(!error.message.isEmpty) } } @MainActor private func waitForEngineTurn(_ harness: EngineHarness) async throws { for _ in 0..<100 where harness.scheduler.readyCount == 0 { await Task.yield() } try #require(harness.scheduler.readyCount > 0, "IPC action did not enter the engine queue") } @Suite("Engine IPC handler") @MainActor struct ParcelEngineIPCTests { @Test func windowQuerySeparatesAcceptedGeometryFromItsLayoutTarget() async throws { let harness = try EngineHarness() harness.world.behaviors[engineApp] = .init(widthMultiple: 7) try await harness.start() try harness.add([1]) let id = WindowID(rawValue: 1) let target = try #require(harness.engine.snapshot.state.frames[id]) let accepted = try #require(harness.engine.snapshot.readbackFrames[id]) #expect(accepted != target) let handler = EngineIPCHandler(engine: harness.engine) guard case .array(let windows) = try await handler.query(.windows), let first = windows.first, case .object(let fields) = first else { Issue.record("Expected a window query"); return } #expect(fields["frame"] == (try engineJSON(accepted))) #expect(fields["target_frame"] == (try engineJSON(target))) await harness.engine.stop() } @Test func windowQueryDoesNotPresentAnUnwrittenTargetAsObservedGeometry() async throws { let harness = try EngineHarness() try await harness.start() harness.world.deferWrites = true try harness.add([1]) let handler = EngineIPCHandler(engine: harness.engine) guard case .array(let windows) = try await handler.query(.windows), let first = windows.first, case .object(let fields) = first else { Issue.record("Expected a window query"); return } #expect(fields["frame"] == (try engineJSON(initialEngineFrame))) #expect(fields["target_frame"] == (try engineJSON(engineScreen))) harness.world.deferWrites = false try harness.world.completeNextWrite() await harness.engine.stop() } @Test func windowQueryUsesTheLatestObservedFrameEvenWithoutAFinalReceipt() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) let id = WindowID(rawValue: 1) let observed = Rect(x: 20, y: 40, width: 600, height: 500) harness.engine.actualFrames[id] = observed let handler = EngineIPCHandler(engine: harness.engine) guard case .array(let windows) = try await handler.query(.windows), let first = windows.first, case .object(let fields) = first else { Issue.record("Expected a window query"); return } #expect(fields["frame"] == (try engineJSON(observed))) #expect(fields["target_frame"] == (try engineJSON(engineScreen))) await harness.engine.stop() } @Test func allQueryPayloadsExposeSortedTypedSnapshotFields() async throws { let harness = try EngineHarness() try await harness.start() let first = ManagedWindow( id: WindowID(rawValue: 9), app: engineApp, title: "Inspecteur café", minimumSize: Size(width: 100, height: 80)) harness.world.appear(first) harness.world.appear(engineWindow(1, app: secondEngineApp, floating: true, title: "Floating")) try harness.scheduler.runReady() let handler = EngineIPCHandler( engine: harness.engine, configPath: "/tmp/parcel-test.toml", version: "test-version") let workspaceID = JSONValue.object(["display": .string(engineDisplay.rawValue), "space": .string("1")]) let windows = try await handler.query(.windows) #expect( windows == .array([ .object([ "id": .integer(1), "pid": .integer(200), "bundle_id": .string(secondEngineApp.bundleID), "title": .string("Floating"), "role": .string("AXWindow"), "floating": .bool(true), "focused": .bool(true), "frame": try engineJSON(initialEngineFrame), "target_frame": try engineJSON(initialEngineFrame), "minimum": .null, "workspace": workspaceID, ]), .object([ "id": .integer(9), "pid": .integer(100), "bundle_id": .string(engineApp.bundleID), "title": .string("Inspecteur café"), "role": .string("AXWindow"), "floating": .bool(false), "focused": .bool(false), "frame": try engineJSON(engineScreen), "target_frame": try engineJSON(engineScreen), "minimum": try engineJSON(LearnedMinimumSize(size: Size(width: 100, height: 80))), "workspace": workspaceID, ]), ])) let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect( try await handler.query(.workspaces) == .array([ .object([ "id": workspaceID, "active": .bool(true), "layout": .string("columns"), "ratio": .number(0.5), "window_cap": .integer(3), "effective_window_cap": .integer(3), "layout_variant": .string("standard"), "when_full": .string("stack"), "focus_modes": try engineJSON(FocusModes()), "windows": .array([.integer(9), .integer(1)]), "tiles": try engineJSON(try #require(workspace.tree)), ]) ])) #expect( try await handler.query(.displays) == .array([ .object([ "id": .string(engineDisplay.rawValue), "frame": try engineJSON(engineScreen), "active_space": .string("1"), ]) ])) #expect( try await handler.query(.config) == .object([ "path": .string("/tmp/parcel-test.toml"), "version": .string("test-version"), "schema_version": .integer(1), "active_mode": .null, "hover_focus": .bool(false), "automatic_tiling": .bool(true), "shortcuts_enabled": .bool(true), "when_display_full": .string("swap"), "focus-modes": .object([ "no-peek-level": .number(0.25), "no-peek-blur": .bool(true), "clean-space-color": .string("graphite"), ]), "motion": .object([ "enabled": .bool(true), "level": .string("playful"), "speed": .number(1), "transitions": .string("snap"), ]), ])) await harness.engine.stop() } @Test func emptyQueriesAndDisplayWithoutActiveSpaceUseExplicitNulls() async throws { let state = State(displays: [Display(id: engineDisplay, frame: engineScreen)]) let harness = try EngineHarness(initialState: state) try await harness.start() let handler = EngineIPCHandler(engine: harness.engine) #expect(try await handler.query(.windows) == .array([])) #expect(try await handler.query(.workspaces) == .array([])) #expect( try await handler.query(.displays) == .array([ .object([ "id": .string(engineDisplay.rawValue), "frame": try engineJSON(engineScreen), "active_space": .null, ]) ])) await harness.engine.stop() } @Test func inactiveWorkspacesRemainQueryable() async throws { let harness = try EngineHarness() try await harness.start() let hiddenKey = WorkspaceKey(display: engineDisplay, space: SpaceID(rawValue: 99)) harness.world.appear(engineWindow(5), workspace: hiddenKey) try harness.scheduler.runReady() let handler = EngineIPCHandler(engine: harness.engine) let payload = try await handler.query(.workspaces) guard case .array(let workspaces) = payload else { Issue.record("Workspace query must return an array") return } #expect(workspaces.count == 2) guard case .object(let hidden) = workspaces[1] else { Issue.record("Workspace query elements must be objects") return } #expect(hidden["active"] == .bool(false)) #expect(hidden["windows"] == .array([.integer(5)])) #expect(hidden["id"] == .object(["display": .string(engineDisplay.rawValue), "space": .string("99")])) await harness.engine.stop() } @Test func actionRoutesThroughAsyncPerformAndReturnsRevisionAndReports() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) let handler = EngineIPCHandler(engine: harness.engine) let action = Task { @MainActor in try await handler.run(command: "set-layout", args: ["rows"]) } try await waitForEngineTurn(harness) let previousRevision = harness.engine.snapshot.revision try harness.scheduler.runReady() #expect( try await action.value == .object([ "accepted": .bool(true), "revision": .string(String(previousRevision + 1)), "reports": .array([]), ])) #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) let rejected = Task { @MainActor in try await handler.run(command: "focus", args: ["right"]) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() #expect( try await rejected.value == .object([ "accepted": .bool(false), "revision": .string(String(previousRevision + 2)), "reports": try engineJSON([Report.noNeighbor(.right)]), ])) await harness.engine.stop() } @Test func parserAndShellRejectionsDoNotReachReducer() async throws { let harness = try EngineHarness() try await harness.start() let handler = EngineIPCHandler(engine: harness.engine) let before = harness.engine.snapshot try await expectEngineIPCError("invalid_command") { try await handler.run(command: "set-ratio", args: ["nan"]) } try await expectEngineIPCError("shell_command") { try await handler.run(command: "open-settings", args: []) } #expect(harness.engine.snapshot == before) #expect(harness.scheduler.pendingCount == 0) await harness.engine.stop() await #expect(throws: EngineError.stopped) { try await handler.run(command: "retile", args: []) } } @Test(arguments: ["close", "toggle-fullscreen"]) func nativeWindowCommandsAwaitCompletionWithoutOptimisticRemoval(command: String) async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) let window = WindowID(rawValue: 2) harness.world.deferWindowCommands = true let handler = EngineIPCHandler(engine: harness.engine) let action = Task { @MainActor in try await handler.run(command: command, args: []) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() for _ in 0..<100 where harness.world.pendingWindowCommandCount == 0 { await Task.yield() } try #require(harness.world.pendingWindowCommandCount == 1) #expect(!harness.engine.isIdle) #expect(harness.engine.snapshot.state.windows[window] != nil) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.order == [WindowID(rawValue: 1), window]) let writes = harness.world.writes(for: window).count harness.engine.send(.relayout) try harness.scheduler.runReady() #expect(harness.world.writes(for: window).count == writes) try harness.world.completeWindowCommand() guard case .object(let value) = try await action.value else { Issue.record("Window commands must return a typed result") await harness.engine.stop() return } #expect(value["accepted"] == .bool(true)) #expect(harness.world.closed == (command == "close" ? [window] : [])) #expect(harness.world.fullscreenToggles == (command == "toggle-fullscreen" ? [window] : [])) #expect(harness.engine.snapshot.state.windows[window] != nil) harness.world.disappear(window) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[window] == nil) #expect(harness.engine.snapshot.state.frames[WindowID(rawValue: 1)] == engineScreen) await harness.engine.stop() } @Test(arguments: ["close", "toggle-fullscreen"]) func nativeWindowFailuresReachIPCAndDoNotPretendSuccess(command: String) async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) let failure = EnginePlatformFailure.accessibility(engineApp, window: WindowID(rawValue: 1), cause: .timedOut) harness.world.commandError = failure let handler = EngineIPCHandler(engine: harness.engine) let action = Task { @MainActor in try await handler.run(command: command, args: []) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() try await expectEngineIPCError("window_command_failed") { try await action.value } #expect(harness.log.platformFailures.contains(failure)) #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 1)] != nil) await harness.engine.stop() } @Test(arguments: ["close", "toggle-fullscreen"]) func excludedFocusedWindowUsesInspectionInsteadOfTheStaleCoreFocus(command: String) async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) var fullscreen = engineWindow(99) fullscreen.facts = WindowFacts(bundleID: engineApp.bundleID, role: "AXWindow", isFullScreen: true) harness.world.commandWindow = fullscreen let before = harness.engine.snapshot let handler = EngineIPCHandler(engine: harness.engine) _ = try await handler.run(command: command, args: []) #expect(harness.world.closed == (command == "close" ? [fullscreen.id] : [])) #expect(harness.world.fullscreenToggles == (command == "toggle-fullscreen" ? [fullscreen.id] : [])) #expect(harness.engine.snapshot == before) harness.world.commandWindowError = EnginePlatformFailure.timedOut(engineApp) try await expectEngineIPCError("window_command_failed") { try await handler.run(command: command, args: []) } #expect(harness.world.closed.count + harness.world.fullscreenToggles.count == 1) await harness.engine.stop() } @Test(arguments: ["close", "toggle-fullscreen"]) func trackedNativeFocusedWindowOverridesAStaleCoreFocus(command: String) async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) #expect(harness.engine.snapshot.focusedWindow == WindowID(rawValue: 2)) harness.world.commandWindow = engineWindow(1) let before = harness.engine.snapshot _ = try await EngineIPCHandler(engine: harness.engine).run(command: command, args: []) #expect(harness.world.closed == (command == "close" ? [WindowID(rawValue: 1)] : [])) #expect(harness.world.fullscreenToggles == (command == "toggle-fullscreen" ? [WindowID(rawValue: 1)] : [])) #expect(harness.engine.snapshot == before) await harness.engine.stop() } @Test(arguments: ["float-toggle", "always-float"]) func floatingCommandsCaptureFreshNativeFocusInsteadOfTheStaleCoreWindow(command: String) async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) #expect(harness.engine.snapshot.focusedWindow == WindowID(rawValue: 2)) harness.world.commandWindow = engineWindow(1) var saved: [WindowID] = [] harness.engine.onAlwaysFloat = { saved.append($0.id) } let action = Task { @MainActor in try await EngineIPCHandler(engine: harness.engine).run(command: command, args: []) } if command == "float-toggle" { try await waitForEngineTurn(harness) } harness.engine.send(.focusChanged(WindowID(rawValue: 2))) try harness.scheduler.runReady() _ = try await action.value if command == "float-toggle" { #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 1)]?.isFloating == true) #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 2)]?.isFloating == false) } else { #expect(saved == [WindowID(rawValue: 1)]) } await harness.engine.stop() } @Test(arguments: ["float-toggle", "always-float"]) func failedNativeFocusReadNeverFloatsOrSavesTheStaleWindow(command: String) async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) harness.world.commandWindowError = EngineWindowCommandError.noFocusedWindow var saved: [WindowID] = [] harness.engine.onAlwaysFloat = { saved.append($0.id) } let before = harness.engine.snapshot let action = Task { @MainActor in try await EngineIPCHandler(engine: harness.engine).run(command: command, args: []) } for _ in 0..<100 { await Task.yield(); try harness.scheduler.runReady() } try await expectEngineIPCError("window_command_failed") { try await action.value } #expect(harness.engine.snapshot == before) #expect(saved.isEmpty) await harness.engine.stop() } @Test(arguments: ["float-toggle", "always-float"]) func anUnmanagedNativeFocusCannotRedirectFloatingToThePreviousWindow(command: String) async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) harness.world.commandWindow = engineWindow(99) var saved: [WindowID] = [] harness.engine.onAlwaysFloat = { saved.append($0.id) } if command == "always-float" { try await expectEngineIPCError("window_not_found") { try await EngineIPCHandler(engine: harness.engine).run(command: command, args: []) } } else { let action = Task { @MainActor in try await EngineIPCHandler(engine: harness.engine).run(command: command, args: []) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() guard case .object(let result) = try await action.value else { Issue.record("Expected command result"); return } #expect(result["accepted"] == .bool(false)) } #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 1)]?.isFloating == false) #expect(saved.isEmpty) await harness.engine.stop() } @Test(arguments: [false, true]) func cancellingOrStoppingNativeCommandRejectsItsReplyAndIgnoresLateCompletion(stop: Bool) async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) harness.world.deferWindowCommands = true let action = Task { @MainActor in try await harness.engine.perform(.close) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() for _ in 0..<100 where harness.world.pendingWindowCommandCount == 0 { await Task.yield() } try #require(harness.world.pendingWindowCommandCount == 1) if stop { await harness.engine.stop() await #expect(throws: EngineError.stopped) { try await action.value } } else { action.cancel() await #expect(throws: CancellationError.self) { try await action.value } } let snapshot = harness.engine.snapshot try harness.world.completeWindowCommand() for _ in 0..<10 { await Task.yield() } #expect(harness.engine.snapshot == snapshot) #expect(harness.engine.windowOperations.isEmpty) await harness.engine.stop() } @Test func overlappingCommandsForOneWindowFailInsteadOfTogglingTwice() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1]) harness.world.deferWindowCommands = true let first = Task { @MainActor in try await harness.engine.perform(.toggleFullscreen) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() for _ in 0..<100 where harness.world.pendingWindowCommandCount == 0 { await Task.yield() } try #require(harness.world.pendingWindowCommandCount == 1) let second = Task { @MainActor in try await harness.engine.perform(.toggleFullscreen) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() await #expect(throws: EngineWindowCommandError.busy(WindowID(rawValue: 1))) { try await second.value } #expect(harness.world.fullscreenToggles == [WindowID(rawValue: 1)]) try harness.world.completeWindowCommand() #expect(try await first.value.isAccepted) await harness.engine.stop() } @Test(arguments: [false, true]) func hoverFocusCommandsAreAcceptedOverIPCWithoutFocus(initiallyEnabled: Bool) async throws { var configuration = engineConfiguration() configuration.mouse.focusFollowsMouse = initiallyEnabled let harness = try EngineHarness(configuration: configuration) try await harness.start() #expect(harness.engine.snapshot.state.focusedWindow == nil) let handler = EngineIPCHandler(engine: harness.engine) let action = Task { @MainActor in try await handler.run(command: "hover-focus-toggle", args: []) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() guard case .object(let value) = try await action.value else { throw HarnessError.missingAction } #expect(value["accepted"] == .bool(true)) #expect(value["reports"] == .array([])) #expect(harness.engine.snapshot.state.hoverFocusEnabled == !initiallyEnabled) await harness.engine.stop() } @Test(arguments: ["borders-toggle"]) func appOwnedCommandsReachReducerAndReportUnsupported(command: String) async throws { let harness = try EngineHarness() try await harness.start() let handler = EngineIPCHandler(engine: harness.engine) let action = Task { @MainActor in try await handler.run(command: command, args: []) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() guard case .object(let value) = try await action.value else { Issue.record("App-owned commands must return a result") await harness.engine.stop() return } #expect(value["accepted"] == .bool(false)) #expect(value["reports"] == (try engineJSON([Report.unsupported]))) await harness.engine.stop() } @Test(arguments: [false, true]) func explicitNoLimitRefillsAutomaticSlotsWhileOffButNewArrivalsDoNotMoveWindows(existingOverflow: Bool) async throws { let harness = try EngineHarness() try await harness.start() try harness.add(existingOverflow ? [1, 2, 3, 4, 5, 6] : [1, 2]) let existingWindowCount = existingOverflow ? 6 : 2 let before = harness.world.frames harness.engine.setAutomaticTilingEnabled(false) let handler = EngineIPCHandler(engine: harness.engine) let action = Task { @MainActor in try await handler.run(command: "set-window-cap", args: ["0"]) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() guard case .object(let result) = try await action.value else { throw HarnessError.missingAction } try harness.finishMotion() #expect(result["accepted"] == .bool(true)) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.windowCap == Int.max) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.visibleWindows.count == existingWindowCount) #expect(existingOverflow ? harness.world.frames != before : harness.world.frames == before) let afterLimit = harness.world.frames let writes = harness.world.allWrites.count try harness.add(existingOverflow ? [7, 8, 9] : [3, 4, 5, 6]) #expect(harness.world.allWrites.count == writes) #expect( harness.engine.snapshot.state.workspaces[engineWorkspace]?.visibleWindows.count == (existingOverflow ? 9 : 6)) #expect(afterLimit.allSatisfy { harness.world.frames[$0.key] == $0.value }) let retile = Task { @MainActor in try await handler.run(command: "retile", args: []) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() try harness.finishMotion() guard case .object(let retiled) = try await retile.value else { throw HarnessError.missingAction } #expect(retiled["accepted"] == .bool(true)) #expect(harness.world.frames == harness.engine.snapshot.state.frames) #expect(!harness.engine.isAutomaticTilingEnabled) await harness.engine.stop() } @Test(arguments: [-1, 101, 100000, Int.max]) func invalidIntegerCapsAreCoreFailuresRatherThanParserFailures(cap: Int) async throws { let harness = try EngineHarness() try await harness.start() let handler = EngineIPCHandler(engine: harness.engine) let action = Task { @MainActor in try await handler.run(command: "set-window-cap", args: [String(cap)]) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() guard case .object(let value) = try await action.value else { throw HarnessError.missingAction } #expect(value["accepted"] == .bool(false)) #expect(value["reports"] == (try engineJSON([Report.invalidWindowCap(cap)]))) await harness.engine.stop() } @Test func limitAndFullSpaceReportsAreAcceptedFeedback() { for report in [ Report.maximumSizeReached, .minimumSizeReached, .spaceFull(WindowID(rawValue: 1)), .atWindowCap(3), ] { #expect(!report.isFailure) } #expect(Report.unsupported.isFailure) #expect(Report.invalidWindowCap(0).isFailure) } @Test func resetSizesClearsOnlyActiveWorkspaceFrameAdjustments() async throws { let harness = try EngineHarness(initialState: engineInitialState(twoDisplays: true)) try await harness.start() try harness.add([1], workspace: WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2))) try harness.add([2]) let adjustment = EngineFrameAdjustment(requested: engineScreen, accepted: initialEngineFrame) harness.engine.frameAdjustments = [WindowID(rawValue: 1): adjustment, WindowID(rawValue: 2): adjustment] let action = Task { @MainActor in try await harness.engine.perform(.resetSizes) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() #expect(try await action.value.isAccepted) #expect(harness.engine.frameAdjustments[WindowID(rawValue: 1)] == adjustment) #expect(harness.engine.frameAdjustments[WindowID(rawValue: 2)] == nil) #expect(harness.announcer.announcements.contains(.sizesReset)) await harness.engine.stop() } @Test func reloadWithoutStoreIsRejected() async throws { let harness = try EngineHarness() try await harness.start() let handler = EngineIPCHandler(engine: harness.engine) try await expectEngineIPCError("config_unavailable") { try await handler.reloadConfig() } #expect(harness.scheduler.pendingCount == 0) await harness.engine.stop() } @Test func reloadAppliesGoodFileAndRejectsBadFileKeepingLastGood() async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent( "parcel-engine-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } let file = directory.appendingPathComponent("config.toml") let source = "[layout]\ndefault = \"side\"\nratio = 0.7\n[motion]\nenabled = false\n" try source.write(to: file, atomically: true, encoding: .utf8) let store = ConfigStore(fileURL: file) let harness = try EngineHarness() try await harness.start() let handler = EngineIPCHandler(engine: harness.engine, configStore: store) #expect(try await handler.reloadConfig() == .object(["path": .string(file.path), "reloaded": .bool(true)])) try harness.scheduler.runReady() let lastGood = harness.engine.configuration #expect(lastGood.layout.global.defaultLayout == .side) #expect(lastGood.layout.global.ratio == 0.7) #expect(!lastGood.motion.enabled) #expect(harness.engine.snapshot.layouts[engineDisplay] == .side) try "[layout]\nratio = 8\n".write(to: file, atomically: true, encoding: .utf8) try await expectEngineIPCError("config_rejected") { try await handler.reloadConfig() } #expect(harness.engine.configuration == lastGood) #expect(harness.engine.snapshot.layouts[engineDisplay] == .side) #expect(harness.scheduler.pendingCount == 0) let rejected = await store.snapshot #expect(rejected.loadState == .rejected) #expect(rejected.lastGoodDocument?.render() == source) await harness.engine.stop() } }