import Foundation import Testing @testable import ParcelCore @Suite struct SetupOpeningTests { private let display = DisplayID(rawValue: "setup-main") private let otherDisplay = DisplayID(rawValue: "setup-secondary") private let space = SpaceID(rawValue: 7) private var key: WorkspaceKey { WorkspaceKey(display: display, space: space) } private var otherKey: WorkspaceKey { WorkspaceKey(display: otherDisplay, space: space) } private let screen = Rect(width: 1200, height: 800) private let salt = Data(repeating: 42, count: 32) private func id(_ value: UInt32) -> WindowID { WindowID(rawValue: value) } private func window( _ value: UInt32, live: Bool = false, title: String? = nil, bundle: String? = nil, floating: Bool = false ) -> ManagedWindow { ManagedWindow( id: id(value + (live ? 100 : 0)), app: AppID( pid: Int32(value + (live ? 1000 : 10)), bundleID: bundle ?? "setup.app.\(value)"), title: title ?? "Private document \(value)", subrole: "AXStandardWindow", isFloating: floating) } private func source() -> State { var workspace = Workspace( key: key, layout: .tree, ratio: .threeFifths, gaps: Gaps(inner: 8, outer: Insets(10)), reservedEdges: Insets(top: 20), windowCap: 2, order: [id(1), id(2), id(3)], whenFull: .stack) workspace.tree = .split( axis: .horizontal, fraction: 0.35, first: .tile(WindowStack(id(1))), second: .tile(WindowStack(id(2)))) let other = Workspace(key: otherKey, layout: .rows, gaps: Gaps(inner: 4), windowCap: 3, order: [id(4)]) return State( displays: [ Display(id: display, frame: screen), Display(id: otherDisplay, frame: Rect(x: 1200, width: 1200, height: 800)), ], activeSpaces: [display: space, otherDisplay: space], workspaces: [key: workspace, otherKey: other], windows: [id(1): window(1), id(2): window(2), id(3): window(3, floating: true), id(4): window(4)], frames: [id(3): Rect(x: 120, y: 160, width: 400, height: 300)]) } private func setup(_ source: State? = nil) throws -> SavedSetup { try SavedSetup.capture(name: "Work", state: source ?? self.source(), titleSalt: salt) } private func live(_ values: [UInt32] = [1, 2, 3, 4], crossed: Bool = false) -> State { let windows = values.map { window($0, live: true, floating: crossed && $0 == 1) } let main = windows.filter { crossed ? $0.id != id(101) : $0.id != id(104) } let secondary = windows.filter { crossed ? $0.id == id(101) : $0.id == id(104) } var first = Workspace(key: key, layout: .columns, windowCap: 8, order: main.reversed().map(\.id)) var second = Workspace(key: otherKey, layout: .grid, windowCap: 8, order: secondary.map(\.id)) if crossed { first.tree = first.tree?.removing(id(101)) second.tree = second.tree?.removing(id(101)) } var state = State( displays: Array(source().displays.values), activeSpaces: source().activeSpaces, workspaces: [key: first, otherKey: second], windows: Dictionary(uniqueKeysWithValues: windows.map { ($0.id, $0) }), activeDisplay: display, focusedWindow: main.first?.id, frames: crossed ? [id(101): Rect(x: 1300, y: 100, width: 500, height: 400)] : [:]) state = reduce(state, .relayout).0 return state } @Test func captureIsHMACOnlyFreshAndIncludesInactiveRetainedWorkspaces() throws { var state = source() state.activeSpaces[otherDisplay] = SpaceID(rawValue: 99) let saved = try setup(state) let text = String(decoding: try JSONEncoder().encode(saved), as: UTF8.self) #expect(!text.contains("Private document")) #expect(!text.contains("\"title\"")) #expect(!text.contains("\"pid\"")) #expect(saved.memory.titleSalt == salt) #expect(saved.memory.records.count == 2) #expect(saved.memory.records.allSatisfy { $0.lastSeen == 0 }) let another = try SavedSetup.capture(name: "Another", state: state, titleSalt: Data(repeating: 43, count: 32)) #expect( saved.memory.records.first?.windows.first?.titleDigest != another.memory.records.first?.windows.first?.titleDigest) #expect(throws: WorkspaceMemoryError.invalidTitleSalt) { try SavedSetup.capture(name: "Bad", state: state, titleSalt: Data(repeating: 1, count: 31)) } } @Test func openingAcrossDisplaysRestoresTilesFloatingFramesAndEveryWorkspaceSetting() throws { let saved = try setup() var state = live(crossed: true) let before = state #expect(saved.memory.windowMapping(in: state)[id(1)] == nil) #expect(saved.memory.windowMapping(in: state, acrossDisplays: true)[id(1)] == id(101)) var opening = try SetupOpening(setup: saved, state: state) let effects = state.applySetupOpening(&opening) #expect(opening.missingWindows.isEmpty) #expect(state.workspace(containing: id(101)) == key) #expect(state.workspace(containing: id(104)) == otherKey) #expect(state.workspaces[key]?.layout == .tree) #expect(state.workspaces[key]?.windowCap == 2) #expect(state.workspaces[key]?.gaps == source().workspaces[key]?.gaps) #expect(state.workspaces[key]?.whenFull == .stack) #expect(state.workspaces[otherKey]?.layout == .rows) #expect(state.workspaces[otherKey]?.windowCap == 3) #expect(state.windows[id(101)]?.isFloating == false) #expect(state.windows[id(103)]?.isFloating == true) #expect(state.frames[id(103)] == source().frames[id(3)]) #expect(state.workspaces[key]?.tree == source().workspaces[key]?.tree?.memoryRemapping(opening.matchedWindows)) #expect( effects.contains { if case .setFrames(let writes) = $0 { writes.contains { $0.window == id(103) } } else { false } }) #expect(state.undoHistory == nil) #expect(saved.matches(state)) _ = opening.finish(in: &state) #expect(state.undoHistory?.count(for: id(101)) == 1) #expect(state.undoHistory?.count(for: id(104)) == 1) let result = reduce(state, .commandIssued(.undo)) #expect(!result.1.contains(.report(.undoConflict(id(101))))) #expect(result.0.workspaces[key]?.order == before.workspaces[key]?.order) #expect(result.0.workspaces[otherKey]?.order == before.workspaces[otherKey]?.order) #expect(result.0.workspaces[key]?.layout == .columns) #expect(result.0.workspaces[otherKey]?.layout == .grid) #expect(result.0.windows[id(101)]?.isFloating == true) #expect(result.0.windows[id(103)]?.isFloating == false) #expect(result.0.undoHistory?.windows.isEmpty == true) #expect(try JSONDecoder().decode(State.self, from: JSONEncoder().encode(state)) == state) } @Test(arguments: [false, true]) func distinctActiveDisplaySpacesRestoreAndUndoTheirOriginalSources(cancel: Bool) throws { let secondSpace = SpaceID(rawValue: 8) let destination = WorkspaceKey(display: otherDisplay, space: secondSpace) var recorded = source() recorded.activeSpaces[otherDisplay] = secondSpace recorded.workspaces[otherKey] = nil recorded.workspaces[destination] = Workspace(key: destination, layout: .rows, windowCap: 3, order: [id(4)]) let saved = try setup(recorded) var state = live(crossed: true) state.activeSpaces[otherDisplay] = secondSpace let removed = state.workspaces.removeValue(forKey: otherKey) let previous = try #require(removed) var current = Workspace(key: destination, layout: .grid, windowCap: 8, order: previous.order) current.tree = previous.tree state.workspaces[destination] = current state = reduce(state, .relayout).0 let before = state #expect(saved.memory.windowMapping(in: state, acrossDisplays: true)[id(1)] == nil) #expect(saved.memory.windowMapping(in: state, acrossDisplays: true, activeOnly: true)[id(1)] == id(101)) var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) #expect(state.workspace(containing: id(101)) == key) #expect(state.workspace(containing: id(104)) == destination) #expect(opening.missingWindows.isEmpty) #expect(saved.matches(state)) if cancel { _ = opening.cancel(in: &state) } else { _ = opening.finish(in: &state) } #expect(state.undoHistory?.count(for: id(101)) == 1) #expect(state.undoHistory?.count(for: id(104)) == 1) state = reduce(state, .commandIssued(.undo)).0 #expect(state.workspace(containing: id(101)) == destination) #expect(state.workspace(containing: id(104)) == key) #expect(state.workspaces[key]?.undoPlacement == before.workspaces[key]?.undoPlacement) #expect(state.workspaces[destination]?.undoPlacement == before.workspaces[destination]?.undoPlacement) #expect(state.windows[id(101)]?.isFloating == true) #expect(state.activeSpaces == before.activeSpaces) #expect(state.undoHistory?.windows.isEmpty == true) } @Test func delayedArrivalRebuildsOriginalTopologyAndRecordsOnlyOneUndo() throws { let saved = try setup() var state = live([1]) var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) #expect(opening.pendingBundleIDs == ["setup.app.2", "setup.app.3", "setup.app.4"]) for value: UInt32 in [2, 3, 4] { let target = value == 4 ? otherKey : key let event = Event.windowAppeared(window(value, live: true), workspace: target, frame: screen) opening.observe(event) state = reduce(state, event).0 _ = opening.apply(to: &state) #expect(state.undoHistory == nil) } #expect(saved.matches(state)) #expect(opening.unresolvedCount == 0) _ = opening.finish(in: &state) #expect(opening.isFinished) #expect(opening.phase == .finished) #expect(state.undoHistory?.count(for: id(101)) == 1) #expect(state.undoHistory?.count(for: id(103)) == 1) state = reduce(state, .commandIssued(.undo)).0 #expect(state.workspaces[key]?.layout == .columns) #expect(state.workspaces[otherKey]?.layout == .grid) #expect(Set(state.workspaces[key]?.order ?? []) == [id(101), id(102), id(103)]) #expect(state.windows[id(103)]?.isFloating == false) #expect(state.undoHistory?.windows.isEmpty == true) } @Test func exactTitlesAndUniqueNewTitleFallbackReuseMemoryRules() throws { var state = live([1]) state.windows[id(101)]?.title = "A reopened document" var opening = try SetupOpening(setup: setup(), state: state) _ = opening.apply(to: &state) #expect(opening.matchedWindows[id(1)] == id(101)) state.windows[id(101)]?.title = "Another title after pinning" _ = opening.apply(to: &state) #expect(opening.matchedWindows[id(1)] == id(101)) } @Test func ambiguousIdentitiesAreNotAssignedByEnumerationOrCandidateFiltering() throws { var original = source() let savedApp = try #require(original.windows[id(1)]).app original.windows[id(2)]?.app = savedApp original.windows[id(2)]?.title = "Private document 1" let saved = try setup(original) var state = live([1, 2]) let liveApp = try #require(state.windows[id(101)]).app state.windows[id(102)]?.app = liveApp state.windows[id(102)]?.title = "Private document 1" #expect(saved.memory.windowMapping(in: state, candidates: [id(101)], acrossDisplays: true).isEmpty) var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) #expect(opening.matchedWindows.isEmpty) #expect(opening.missingWindows.filter { $0.reason == .ambiguous }.count == 2) } @Test func exactTitlesDisambiguateSameAppWindowsAcrossDisplays() throws { var original = source() let savedApp = try #require(original.windows[id(1)]).app original.windows[id(4)]?.app = savedApp let saved = try setup(original) var state = live([1, 4], crossed: true) let liveApp = try #require(state.windows[id(101)]).app state.windows[id(104)]?.app = liveApp var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) #expect(opening.matchedWindows[id(1)] == id(101)) #expect(opening.matchedWindows[id(4)] == id(104)) #expect(state.workspace(containing: id(101)) == key) #expect(state.workspace(containing: id(104)) == otherKey) } @Test func unsupportedSavedIdentityCannotMakeFallbackLookUnique() throws { var original = source() let savedApp = try #require(original.windows[id(1)]).app original.windows[id(4)]?.app = savedApp let saved = try setup(original) var state = live([1]) state.displays[otherDisplay] = nil state.windows[id(101)]?.title = "An unknown reopened document" var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) #expect(opening.matchedWindows[id(1)] == nil) #expect(opening.missingWindows.first?.reason == .ambiguous) #expect(opening.missingWindows.last?.reason == .disconnectedDisplay) } @Test func savedStackReappearsWithoutInventingTileSlots() throws { var original = source() original.windows[id(5)] = window(5) original.workspaces[otherKey] = Workspace(key: otherKey, layout: .rows, windowCap: 1, order: [id(4), id(5)]) let saved = try setup(original) var state = live([1, 2, 3, 4, 5]) var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) #expect(state.workspaces[otherKey]?.tree?.tileCount == 1) #expect(state.workspaces[otherKey]?.tree?.stacks.first?.windows == [id(104), id(105)]) #expect(state.workspaces[key]?.tree?.tileCount == 2) #expect(saved.matches(state)) } @Test func roleAndSubroleMustMatchAndBlankTitlesCannotFallback() throws { var state = live([1, 2, 3]) state.windows[id(101)]?.role = "AXSheet" state.windows[id(102)]?.subrole = "AXDialog" state.windows[id(103)]?.title = " " var opening = try SetupOpening(setup: setup(), state: state) _ = opening.apply(to: &state) #expect(opening.matchedWindows.isEmpty) } @Test func disconnectedInactiveAndUnusableDestinationsAreExplicitAndNeverMoveAcrossSpaces() throws { let saved = try setup() var state = live() state.displays[otherDisplay] = nil state.activeSpaces[display] = SpaceID(rawValue: 99) let before = state.workspaces var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) #expect(opening.matchedWindows.isEmpty) #expect(opening.missingWindows.filter { $0.reason == .inactiveSpace }.count == 3) #expect(opening.missingWindows.filter { $0.reason == .disconnectedDisplay }.count == 1) #expect(state.workspaces == before) state.activeSpaces[display] = space state.displays[display]?.frame = Rect() _ = opening.apply(to: &state) #expect(opening.missingWindows.filter { $0.reason == .suspendedDisplay }.count == 3) } @Test func anotherNativeSpaceIsNeverUsedAsAnIdentityCandidate() throws { var state = live([1]) let elsewhere = WorkspaceKey(display: display, space: SpaceID(rawValue: 99)) state.workspaces[key]?.remove(id(101)) state.workspaces[elsewhere] = Workspace(key: elsewhere, order: [id(101)]) var opening = try SetupOpening(setup: setup(), state: state) _ = opening.apply(to: &state) #expect(opening.matchedWindows.isEmpty) #expect(state.workspace(containing: id(101)) == elsewhere) #expect(opening.missingWindows.first?.reason == .notFound) } @Test func disappearanceAndSameProcessIDReuseRetirePinsAndKeepFinalUndoValid() throws { var state = live([1, 2]) var opening = try SetupOpening(setup: setup(), state: state) _ = opening.apply(to: &state) let old = try #require(state.windows[id(101)]) let disappearance = Event.windowDisappeared(old.id) opening.observe(disappearance) state = reduce(state, disappearance).0 let replacement = ManagedWindow(id: old.id, app: old.app, title: "Private document 1", subrole: old.subrole) state = reduce(state, .windowAppeared(replacement, workspace: otherKey, frame: screen)).0 _ = opening.apply(to: &state) #expect(opening.matchedWindows[id(1)] == nil) #expect(opening.missingWindows.first?.reason == .identityChanged) #expect(state.workspace(containing: old.id) == otherKey) _ = opening.finish(in: &state) #expect(try JSONDecoder().decode(State.self, from: JSONEncoder().encode(state)) == state) } @Test func hiddenOutsidersArePrunedBeforeFinalUndo() throws { var state = live([1, 2]) let outsider = window(9, live: true) state = reduce(state, .windowAppeared(outsider, workspace: key, frame: screen)).0 var opening = try SetupOpening(setup: setup(), state: state) _ = opening.apply(to: &state) let event = Event.windowDisappeared(outsider.id) opening.observe(event) state = reduce(state, event).0 _ = opening.finish(in: &state) #expect(state.undoHistory?.windows.contains(outsider.id) == false) let result = reduce(state, .commandIssued(.undo)) #expect(result.0.workspaces[key]?.layout == .columns) #expect(result.0.windows[outsider.id] == nil) #expect(!result.1.contains(.report(.undoConflict(id(101))))) } @Test func cancellationFreezesPartialOpeningWithSingleUndoAndNoFurtherWrites() throws { var state = live([1]) var opening = try SetupOpening(setup: setup(), state: state) _ = opening.apply(to: &state) _ = opening.cancel(in: &state) #expect(opening.phase == .cancelled) #expect(opening.pendingBundleIDs.isEmpty) #expect(state.undoHistory?.count(for: id(101)) == 1) let frozen = state #expect(opening.apply(to: &state).isEmpty) #expect(opening.finish(in: &state).isEmpty) #expect(opening.cancel(in: &state).isEmpty) #expect(state == frozen) state = reduce(state, .commandIssued(.undo)).0 #expect(state.workspaces[key]?.layout == .columns) } @Test func emptyUnsupportedWorkspaceIsStillMissingAndNoOpOpenAddsNoUndo() throws { let empty = State(displays: Array(source().displays.values), activeSpaces: source().activeSpaces) let saved = try setup(empty) var state = empty state.displays[otherDisplay] = nil var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) #expect(opening.missingWindows.isEmpty) #expect(opening.missingWorkspaces.count == 1) #expect(opening.missingWorkspaces.first?.reason == .disconnectedDisplay) #expect(opening.unresolvedCount == 1) _ = opening.finish(in: &state) #expect(state.undoHistory == nil) } @Test func filteringInactiveApplicationsPreservesValidTilesAndTitlePrivacy() throws { let memory = try setup().memory let record = try #require(memory.records.first { $0.workspace.key == key }) #expect(record.retainingApplications(Set(record.windows.map(\.bundleID))) == record) let retained = record.retainingApplications(["setup.app.1"]) try WorkspaceMemory(records: [retained], titleSalt: salt).validate() #expect(retained.workspace.order == [id(1)]) #expect(retained.workspace.tree?.windows == [id(1)]) #expect(retained.windows.count == 1) #expect(!String(decoding: try JSONEncoder().encode(retained), as: UTF8.self).contains("Private document")) let empty = record.retainingApplications([]) try WorkspaceMemory(records: [empty], titleSalt: salt).validate() #expect(empty.workspace.order.isEmpty && empty.workspace.tree == nil && empty.windows.isEmpty) } @Test func setupCaptureKeepsEveryConnectedSpaceBeyondLayoutMemoryPruningLimit() throws { let keys = (1...130).map { WorkspaceKey(display: display, space: SpaceID(rawValue: UInt64($0))) } let state = State( displays: [Display(id: display, frame: screen)], activeSpaces: [display: space], workspaces: Dictionary(uniqueKeysWithValues: keys.map { ($0, Workspace(key: $0)) })) #expect(try WorkspaceMemory.capture(state, titleSalt: salt).records.count == 128) let saved = try setup(state) #expect(saved.memory.records.count == 130) #expect(Set(saved.memory.records.map { $0.workspace.key }) == Set(keys)) } enum SetupSetting: Sendable, CaseIterable { case gaps, reservedEdges, whenFull, configuredRatio, layout } @Test(arguments: SetupSetting.allCases, [false, true]) func everyWorkspaceSettingHasSingleUndoEvenWithoutTiledOwners(setting: SetupSetting, floating: Bool) throws { var state = live([1]) if floating { state.windows[id(101)]?.isFloating = true state.workspaces[key]?.removeTile(id(101)) state.frames[id(101)] = Rect(x: 100, y: 100, width: 400, height: 300) state = reduce(state, .relayout).0 } let before = state var savedState = state savedState.modifyWorkspace(key) { workspace in switch setting { case .gaps: workspace.gaps = Gaps(inner: 8, outer: Insets(10)) case .reservedEdges: workspace.reservedEdges = Insets(top: 20) case .whenFull: workspace.whenFull = .float case .configuredRatio: workspace.configuredRatio = .twoThirds case .layout: workspace.changeLayout(.rows) } } var opening = try SetupOpening(setup: setup(savedState), state: state) _ = opening.apply(to: &state) _ = opening.finish(in: &state) #expect(state.undoHistory?.count(for: id(101)) == 1) state = reduce(state, .commandIssued(.undo)).0 #expect(state.workspaces[key]?.undoPlacement == before.workspaces[key]?.undoPlacement) #expect(state.windows[id(101)]?.isFloating == floating) #expect(state.undoHistory?.windows.isEmpty == true) } @Test(arguments: [false, true]) func disconnectedDisplayRebasesSurvivorsBeforeFinalUndo(cancel: Bool) throws { var state = live([1]) var opening = try SetupOpening(setup: setup(), state: state) _ = opening.apply(to: &state) let remaining = try #require(state.displays[otherDisplay]) state = reduce(state, .displaySetChanged([remaining])).0 #expect(state.workspace(containing: id(101)) == otherKey) if cancel { _ = opening.cancel(in: &state) } else { _ = opening.finish(in: &state) } #expect(opening.isFinished) #expect(try JSONDecoder().decode(State.self, from: JSONEncoder().encode(state)) == state) #expect(state.undoHistory?.count(for: id(101)) == 1) state = reduce(state, .commandIssued(.undo)).0 #expect(state.workspace(containing: id(101)) == otherKey) #expect(state.workspaces[otherKey]?.layout == .grid) #expect(state.undoHistory?.windows.isEmpty == true) } @Test(arguments: [false, true]) func externalNativeSpaceRelocationNeverReplaysAnUnsafeBaseline(cancel: Bool) throws { var state = live([1]) var opening = try SetupOpening(setup: setup(), state: state) _ = opening.apply(to: &state) let elsewhere = WorkspaceKey(display: display, space: SpaceID(rawValue: 99)) state = reduce(state, .activeSpaceChanged(display: display, space: elsewhere.space)).0 let moved = try #require(state.windows[id(101)]) state = reduce(state, .windowAppeared(moved, workspace: elsewhere, frame: screen)).0 if cancel { _ = opening.cancel(in: &state) } else { _ = opening.finish(in: &state) } #expect(opening.isFinished) #expect(state.workspace(containing: moved.id) == elsewhere) #expect(state.undoHistory == nil) #expect(try JSONDecoder().decode(State.self, from: JSONEncoder().encode(state)) == state) } @Test func existingUndoHistoryIsRetainedBelowTheOpeningTransaction() throws { var state = live() state = reduce(state, .workspaceCommandIssued(.setLayout(.rows), workspace: key)).0 let previousCount = state.undoHistory?.count(for: id(101)) ?? 0 var opening = try SetupOpening(setup: setup(), state: state) _ = opening.apply(to: &state) _ = opening.finish(in: &state) #expect(state.undoHistory?.count(for: id(101)) == previousCount + 1) state = reduce(state, .commandIssued(.undo)).0 #expect(state.workspaces[key]?.layout == .rows) #expect(state.undoHistory?.count(for: id(101)) == previousCount) } @Test(arguments: [UInt32(101), UInt32(103)]) func semanticMatchDetectsReadbackDisturbanceWithoutTreeChanges(window: UInt32) throws { let saved = try setup() var state = live() var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) let tree = state.workspaces[key]?.tree let originalFrame = try #require(state.frames[id(window)]) let disturbed = Rect( x: originalFrame.minX + 40, y: originalFrame.minY, width: originalFrame.size.width, height: originalFrame.size.height) state.frames[id(window)] = disturbed #expect(state.workspaces[key]?.tree == tree) #expect(!saved.matches(state)) state.frames[id(window)] = nil state.observedFrames[id(window)] = disturbed #expect(!saved.matches(state)) state.observedFrames[id(window)] = originalFrame #expect(saved.matches(state)) } @Test func semanticMatchIgnoresFocusAndNumbersButDetectsArrangementChanges() throws { let saved = try setup() var state = live() var opening = try SetupOpening(setup: saved, state: state) _ = opening.apply(to: &state) #expect(saved.matches(state)) state = reduce(state, .focusChanged(id(101))).0 #expect(saved.matches(state)) state.workspaces[key]?.setWindowCap(1) #expect(!saved.matches(state)) } }