import Foundation import ParcelConfig import ParcelCore import ParcelIPC import ParcelPlatform import Testing @testable import ParcelEngine @MainActor private final class FakeSpaceWorld: EngineSpaceWorld { struct Call: Equatable { let destination: SpaceDestination let display: DisplayID let window: WindowID? let follow: Bool } var calls: [Call] = [] var error: SpaceCommandError? var suspend = false var cancelled = false var onExecute: (() throws -> Void)? var snapshot = [ NativeDisplaySpaces( displayID: engineDisplay.rawValue, currentSpace: 1, spaces: (1...16).map { NativeSpace(id: UInt64($0), kind: .desktop, desktopNumber: $0) }) ] func spaceSnapshot() async throws -> [NativeDisplaySpaces] { if let error { throw error } return snapshot } func executeSpaceCommand(_ destination: SpaceDestination, display: DisplayID, window: WindowID?, follow: Bool) async throws -> SpaceCommandResult { calls.append(Call(destination: destination, display: display, window: window, follow: follow)) try onExecute?() if let error { throw error } if suspend { // Suspension must not expire while other tests occupy the main actor. let (stream, continuation) = AsyncStream.makeStream() defer { continuation.finish() } do { for await _ in stream {} try Task.checkCancellation() } catch { cancelled = true throw error } } let source = snapshot[0].currentSpace let target: UInt64 if case .desktop(let number) = destination { target = UInt64(number) } else { target = 2 } snapshot[0] = NativeDisplaySpaces( displayID: display.rawValue, currentSpace: follow ? target : source, spaces: snapshot[0].spaces) return SpaceCommandResult( displayID: display.rawValue, source: source, destination: target, followed: follow, verificationSamples: 3) } } @Suite("Native Space routing") @MainActor struct SpaceCommandRoutingTests { @Test(arguments: ConfigCommand.allCases.filter(\.isSpaceCommand)) func everyNativeCommandRoutesOutsideTheReducer(_ command: ConfigCommand) async throws { let spaces = FakeSpaceWorld() let harness = try EngineHarness(spaceWorld: spaces) try await harness.start() try harness.add([1]) spaces.onExecute = { #expect(harness.engine.isAutomaticTilingEnabled) #expect(!harness.engine.isIdle) } let result = try await harness.engine.performConfigured(command) #expect(result.isAccepted) #expect(harness.engine.isAutomaticTilingEnabled) let call = try #require(spaces.calls.first) #expect(call.display == engineDisplay) let destination: SpaceDestination let window: WindowID? let follow: Bool switch command { case .spaceFocus(let n): (destination, window, follow) = (.desktop(n), nil, true) case .spaceNext: (destination, window, follow) = (.next, nil, true) case .spacePrevious: (destination, window, follow) = (.previous, nil, true) case .spaceBackAndForth: (destination, window, follow) = (.backAndForth, nil, true) case .windowToSpace(let n, let value): (destination, window, follow) = (.desktop(n), WindowID(rawValue: 1), value) case .windowToSpaceNext(let value): (destination, window, follow) = (.next, WindowID(rawValue: 1), value) case .windowToSpacePrevious(let value): (destination, window, follow) = (.previous, WindowID(rawValue: 1), value) default: throw SpaceCommandError.malformedSnapshot } #expect( call == FakeSpaceWorld.Call(destination: destination, display: engineDisplay, window: window, follow: follow) ) #expect(harness.engine.lastSpaceCommandResult?.verificationSamples == 3) await harness.engine.stop() } @Test(arguments: ConfigCommand.allCases.filter(\.isSpaceCommand)) func nativeCommandGrammarRoundTrips(_ command: ConfigCommand) throws { let components = command.rawValue.split(separator: " ").map(String.init) let name = try #require(components.first) #expect(try EngineCommandParser.spaceCommand(name, args: Array(components.dropFirst())) == command) #expect(ConfigCommand(rawValue: command.rawValue) == command) } @Test(arguments: [ ["space-focus"], ["space-focus", "0"], ["space-focus", "17"], ["space-focus", "01"], ["space-focus", "2", "--follow"], ["space-next", "2"], ["space-previous", "--follow"], ["window-to-space", "2", "--follow", "--follow"], ["window-to-space-next", "--unknown"], ]) func malformedArgumentsAreRejected(_ components: [String]) throws { let name = try #require(components.first) #expect(throws: IPCError.self) { try EngineCommandParser.spaceCommand(name, args: Array(components.dropFirst())) } } @Test func nonSpaceCommandsStayWithCoreParser() throws { #expect(try EngineCommandParser.spaceCommand("focus-left") == nil) } @Test func missingServiceAndFocusedWindowSurfaceErrors() async throws { let harness = try EngineHarness() try await harness.start() await #expect(throws: IPCError.self) { try await harness.engine.performConfigured(.spaceNext) } let spaces = FakeSpaceWorld() let withSpaces = try EngineHarness(spaceWorld: spaces) try await withSpaces.start() await #expect(throws: IPCError.self) { try await withSpaces.engine.performConfigured(.windowToSpaceNext(follow: true)) } #expect(spaces.calls.isEmpty) await harness.engine.stop() await withSpaces.engine.stop() } @Test func failuresRestoreAutomaticTilingAndExplainSystemSettings() async throws { let spaces = FakeSpaceWorld() spaces.error = .shortcutDisabled(.desktop(2)) let harness = try EngineHarness(spaceWorld: spaces) try await harness.start() do { _ = try await harness.engine.performConfigured(.spaceFocus(2)) Issue.record("Disabled shortcuts must refuse.") } catch let error as IPCError { #expect(error.message.contains("Switch to Desktop 2")) #expect(error.message.contains("System Settings → Keyboard → Keyboard Shortcuts → Mission Control")) } #expect(harness.engine.isAutomaticTilingEnabled) await harness.engine.stop() } @Test func automaticTilingOffIsPreserved() async throws { let spaces = FakeSpaceWorld() let harness = try EngineHarness(spaceWorld: spaces) try await harness.start() harness.engine.setAutomaticTilingEnabled(false) _ = try await harness.engine.performConfigured(.spaceNext) #expect(!harness.engine.isAutomaticTilingEnabled) await harness.engine.stop() } @Test(arguments: [false, true]) func automaticTilingChoiceDuringASpaceCommandSurvivesCompletion(initiallyEnabled: Bool) async throws { let spaces = FakeSpaceWorld() let harness = try EngineHarness(spaceWorld: spaces) harness.engine.setAutomaticTilingEnabled(initiallyEnabled) try await harness.start() let writes = harness.world.allWrites.count spaces.onExecute = { #expect(harness.engine.isAutomaticTilingEnabled == initiallyEnabled) harness.engine.setAutomaticTilingEnabled(!initiallyEnabled) #expect(harness.world.allWrites.count == writes) } _ = try await harness.engine.performConfigured(.spaceNext) #expect(harness.engine.isAutomaticTilingEnabled == !initiallyEnabled) #expect(harness.world.allWrites.count == writes) await harness.engine.stop() } @Test(.timeLimit(.minutes(1))) func stopCancelsPendingSpaceOperationBeforeStoppingWorld() async throws { let spaces = FakeSpaceWorld() spaces.suspend = true let harness = try EngineHarness(spaceWorld: spaces) try await harness.start() let operation = Task { try await harness.engine.performConfigured(.spaceNext) } defer { operation.cancel() } await withCheckedContinuation { continuation in spaces.onExecute = { continuation.resume() } } spaces.onExecute = nil try #require(!spaces.calls.isEmpty) await #expect(throws: IPCError.self) { try await harness.engine.performConfigured(.spaceNext) } await harness.engine.stop() await #expect(throws: CancellationError.self) { try await operation.value } #expect(spaces.cancelled) #expect(!harness.engine.isRunning) } @Test func querySpacesReadsInventoryNotLazyWorkspacesAndKeepsIDsAsStrings() async throws { let spaces = FakeSpaceWorld() let large: UInt64 = 9_007_199_254_740_993 spaces.snapshot = [ NativeDisplaySpaces( displayID: engineDisplay.rawValue, currentSpace: large, spaces: [ NativeSpace(id: large, kind: .desktop, desktopNumber: 1), NativeSpace(id: 20, kind: .fullscreen), ]) ] let harness = try EngineHarness(spaceWorld: spaces) let handler = EngineIPCHandler(engine: harness.engine) let value = try await handler.query(.spaces) guard case .array(let rows) = value, case .object(let first) = rows.first else { Issue.record("Expected native Spaces rows.") return } #expect(rows.count == 2) #expect(first["id"] == .string(String(large))) #expect(first["desktop_number"] == .integer(1)) #expect(first["active"] == .bool(true)) } @Test func ipcAndConfiguredBindingsUseTheSameNativeRoute() async throws { let spaces = FakeSpaceWorld() let harness = try EngineHarness(spaceWorld: spaces) try await harness.start() _ = try await EngineIPCHandler(engine: harness.engine).run(command: "space-focus", args: ["2"]) #expect(spaces.calls.first?.destination == .desktop(2)) await harness.engine.stop() } } @Suite("Native Space layout retention") @MainActor struct NativeSpaceLayoutRetentionTests { @Test func coalescedSpaceRoundTripNeverFocusesTheDepartedWorkspace() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) let other = WorkspaceKey(display: engineDisplay, space: SpaceID(rawValue: 2)) try harness.add([3], workspace: other) try harness.finishMotion() let focusCount = harness.world.focused.count let raiseCount = harness.world.raised.count harness.engine.send(.activeSpaceChanged(display: engineDisplay, space: other.space)) harness.engine.send(.activeSpaceChanged(display: engineDisplay, space: engineSpace)) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.activeSpaces[engineDisplay] == engineSpace) #expect(!harness.world.focused.dropFirst(focusCount).contains(WindowID(rawValue: 3))) #expect(!harness.world.raised.dropFirst(raiseCount).contains(WindowID(rawValue: 3))) #expect(harness.world.focused.count > focusCount) await harness.engine.stop() } @Test func sharedDesktopMapsToEveryPhysicalDisplay() throws { let native = [ NativeDisplaySpaces( displayID: "Main", currentSpace: 3, spaces: [NativeSpace(id: 3, kind: .desktop, desktopNumber: 1)]) ] #expect( try NativeSpaceMapping.currentSpaces(native, displays: [engineDisplay, secondEngineDisplay]) == [ engineDisplay: SpaceID(rawValue: 3), secondEngineDisplay: SpaceID(rawValue: 3), ]) } @Test func missingDisplayIsNotMappedToAnUnrelatedDesktop() throws { let native = [ NativeDisplaySpaces( displayID: engineDisplay.rawValue.lowercased(), currentSpace: 3, spaces: [NativeSpace(id: 3, kind: .desktop, desktopNumber: 1)]) ] #expect( try NativeSpaceMapping.currentSpaces(native, displays: [engineDisplay])[engineDisplay] == SpaceID(rawValue: 3)) #expect(throws: WindowServer.ReadError.currentSpaceUnavailable(displayID: secondEngineDisplay.rawValue)) { try NativeSpaceMapping.currentSpaces(native, displays: [secondEngineDisplay]) } } @Test func changingSpaceKeepsInactiveTreeAndOrder() async throws { let harness = NativeHarness() try await harness.start() let original = try #require(harness.state.workspaces[engineWorkspace]) harness.clearEvents() harness.backend.spaces[engineDisplay] = SpaceID(rawValue: 2) harness.backend.visible.removeAll() harness.backend.emit(.spaceChanged) try await harness.drain() #expect(harness.disappeared.isEmpty) #expect(harness.state.visibleWindows.isEmpty) #expect(harness.state.workspaces[engineWorkspace]?.tree == original.tree) #expect(harness.state.workspaces[engineWorkspace]?.order == original.order) harness.backend.spaces[engineDisplay] = engineSpace harness.backend.visible = [ WindowID(rawValue: 1): initialEngineFrame, WindowID(rawValue: 2): initialEngineFrame, ] harness.backend.emit(.spaceChanged) try await harness.drain() #expect(harness.state.workspaces[engineWorkspace]?.order == original.order) #expect(harness.state.visibleWindows.count == 2) harness.world.stop() } @Test func applicationRefreshDoesNotEraseWindowsOnInactiveSpaces() async throws { let harness = NativeHarness() try await harness.start() harness.backend.spaces[engineDisplay] = SpaceID(rawValue: 2) harness.backend.visible.removeAll() harness.backend.emit(.spaceChanged) try await harness.drain() harness.first.snapshots.removeAll() harness.backend.emit(.activated(NativeApplicationInfo(id: engineApp))) try await harness.drain() #expect(harness.state.workspace(containing: WindowID(rawValue: 1)) == engineWorkspace) harness.first.emit(.windowDestroyed(1)) try await harness.drain() #expect(harness.state.windows[WindowID(rawValue: 1)] == nil) harness.world.stop() } }