import AppKit import CoreGraphics import Foundation import ParcelConfig import ParcelCore import ParcelIPC import ParcelUI import Testing @testable import ParcelApp @testable import ParcelEngine @testable import ParcelPlatform @MainActor private final class AppLogTestClock: EngineClock { let now: Double = 0 } @MainActor @Suite("App runtime regressions") struct AppRuntimeRegressionTests { @Test func tabViewFailuresHaveActionableMessages() { let id = WindowID(rawValue: 1) #expect( AppText.humanFailure(AppTabViewLayout.Failure.missingFrame(id)) == "Tab View could not open. Try again after windows settle.") #expect( AppText.humanFailure(TabViewSelection.ValidationError.invalidFrame(id)) == "Tab View could not open. Try again after windows settle.") #expect( AppText.humanFailure(MinimizedWindowRestoreError.staleWindow(id)) == "That window is no longer available.") #expect(AppText.humanFailure(MinimizedWindowRestoreError.busy(id)) == "That window is already being restored.") #expect( AppText.humanFailure(MinimizedWindowRestoreError.unconfirmed(id)) == "The window did not restore. Try again.") } @Test(arguments: [ (PermissionStatus.missing, "Turn on Accessibility for Parcel to use Tab View."), (.checking, "Parcel is checking Accessibility access. Try Tab View again in a moment."), (.granted, "Parcel is not running. Try Tab View again after Parcel starts."), ]) func tabViewUnavailableExplainsTheActualCause(status: PermissionStatus, message: String) { #expect(AppText.humanFailure(NativeAppRuntime.tabViewUnavailable(permission: status)) == message) } @Test func modeTransitionsFenceQueuedHotkeys() throws { var gate = HotkeyDispatchGate() let oldTicket = gate.begin(.command(.focusLeft)) let old = try #require(oldTicket) let transitionTicket = gate.begin(.enterMode("resize")) let transition = try #require(transitionTicket) #expect(!gate.allows(old)) #expect(gate.allows(transition)) let blockedCommand = gate.begin(.command(.focusRight)) #expect(blockedCommand == nil) gate.finish(.command(.focusLeft)) let blockedExit = gate.begin(.exitMode) #expect(blockedExit == nil) gate.finish(.enterMode("resize")) let nextTicket = gate.begin(.command(.focusRight)) let next = try #require(nextTicket) gate.invalidate() #expect(!gate.allows(next)) } @Test func conflictingReloadKeepsUnchangedKeysAndTheOldBinding() throws { let backend = KeyBackend() let registrar = backend.registrar() var configuration = ParcelConfiguration.defaults configuration.keybindings = [ .focusLeft: try KeyChord(parsing: "ctrl-alt-a"), .focusRight: try KeyChord(parsing: "ctrl-alt-s"), ] #expect(registrar.reload(configuration).conflicts.isEmpty) backend.operations.removeAll() let old = try #require(configuration.keybindings[.focusLeft]) let conflicting = try KeyChord(parsing: "ctrl-alt-d") configuration.keybindings[.focusLeft] = conflicting configuration.keybindings[.retile] = try KeyChord(parsing: "ctrl-alt-f") backend.failed = [NativeAppRuntime.hotkey(conflicting)] let result = registrar.reload(configuration) #expect(result.conflicts.map(\.chord) == [conflicting]) #expect(registrar.bindings[NativeAppRuntime.hotkey(old)] == .command(.focusLeft)) #expect(result.active[.focusLeft] == old) #expect( registrar.bindings[NativeAppRuntime.hotkey(try #require(configuration.keybindings[.focusRight]))] == .command(.focusRight)) #expect(backend.operations.allSatisfy { !$0.hasPrefix("unregister") }) #expect(result.active[.retile] != nil) backend.failed = [] backend.operations.removeAll() #expect(registrar.reload(configuration).conflicts.isEmpty) #expect(registrar.bindings[NativeAppRuntime.hotkey(old)] == nil) #expect(backend.operations.first?.hasPrefix("register") == true) #expect(backend.operations.last?.hasPrefix("unregister") == true) } @Test func defaultShortcutsAreCheckedAgainstSystemAndMenuBindings() throws { let bindings = DefaultKeybindings.bindings() let swap = NativeAppRuntime.hotkey(try #require(bindings[.swapLeft])) let retile = NativeAppRuntime.hotkey(try #require(bindings[.retile])) let system = SymbolicHotKey(id: 42, isEnabled: true, hotKey: swap) let menu = MenuShortcut(pid: 100, path: ["Window", "Retile"], hotKey: retile) let keys = bindings.values.map(NativeAppRuntime.hotkey) let conflicts = ShortcutConflicts.detect(hotKeys: keys, symbolicHotKeys: [system], menuShortcuts: [menu]) #expect(conflicts.count == 2) #expect(conflicts.contains { $0.hotKey == swap && $0.owner == .system(symbolicID: 42) }) #expect(conflicts.contains { $0.hotKey == retile && $0.owner == .application(pid: 100, menuPath: menu.path) }) } @Test(arguments: [ConfigCommand.swapLeft, .swapRight, .swapUp, .swapDown]) func defaultSwapsRegisterWithoutRepeat(_ command: ConfigCommand) throws { let backend = KeyBackend() let registrar = backend.registrar() let configuration = ParcelConfiguration.defaults let chord = try #require(configuration.keybindings[command]) let key = NativeAppRuntime.hotkey(chord) #expect(registrar.reload(configuration).conflicts.isEmpty) #expect(backend.repeats[key] == false) #expect(registrar.action(for: HotKeyPress(hotKey: key, isRepeat: false)) == .command(command)) } @Test func unchangedChordCanChangeCommandAndRepeatPolicyWithoutRegistration() throws { let backend = KeyBackend() let registrar = backend.registrar() let chord = try KeyChord(parsing: "ctrl-alt-a") var configuration = ParcelConfiguration.defaults configuration.keybindings = [.focusLeft: chord] _ = registrar.reload(configuration) backend.operations.removeAll() configuration.keybindings = [.quit: chord] _ = registrar.reload(configuration) #expect(backend.operations.isEmpty) #expect(registrar.bindings[NativeAppRuntime.hotkey(chord)] == .command(.quit)) #expect(backend.repeats[NativeAppRuntime.hotkey(chord)] == false) } @Test func removedKeysAreUnregisteredOnlyAfterNewKeysAreRegistered() throws { let backend = KeyBackend() let registrar = backend.registrar() var configuration = ParcelConfiguration.defaults configuration.keybindings = [.focusLeft: try KeyChord(parsing: "ctrl-alt-a")] _ = registrar.reload(configuration) backend.operations.removeAll() configuration.keybindings = [.focusRight: try KeyChord(parsing: "ctrl-alt-s")] _ = registrar.reload(configuration) #expect(backend.operations.count == 2) #expect(backend.operations[0].hasPrefix("register")) #expect(backend.operations[1].hasPrefix("unregister")) } @Test func modeTransitionsReplaceBindingsAndResetHeldRepeats() throws { let backend = KeyBackend() let registrar = backend.registrar() let entry = try KeyChord(parsing: "ctrl-alt-m") let shared = try KeyChord(parsing: "ctrl-alt-a") let escape = try KeyChord(parsing: "escape") let extra = try KeyChord(parsing: "ctrl-alt-d") var configuration = ParcelConfiguration.defaults configuration.keybindings = [.focusLeft: shared, .retile: extra] configuration.defaultModeEntries = ["resize": entry] configuration.modes = ["resize": [.command(.focusLeft): shared, .exitMode: escape]] #expect(registrar.reload(configuration).conflicts.isEmpty) #expect(registrar.bindings[NativeAppRuntime.hotkey(entry)] == .enterMode("resize")) backend.repeatUpdates.removeAll() #expect(registrar.reload(configuration, mode: "resize").conflicts.isEmpty) #expect(registrar.bindings[NativeAppRuntime.hotkey(entry)] == nil) #expect(registrar.bindings[NativeAppRuntime.hotkey(extra)] == nil) #expect(registrar.bindings[NativeAppRuntime.hotkey(escape)] == .exitMode) let sharedKey = NativeAppRuntime.hotkey(shared) #expect(backend.repeatUpdates.filter { $0.0 == sharedKey }.map(\.1) == [false, true]) #expect(registrar.action(for: HotKeyPress(hotKey: sharedKey, isRepeat: true)) == nil) #expect(registrar.action(for: HotKeyPress(hotKey: sharedKey, isRepeat: false)) == .command(.focusLeft)) #expect(registrar.action(for: HotKeyPress(hotKey: sharedKey, isRepeat: true)) == .command(.focusLeft)) #expect(registrar.reload(configuration).conflicts.isEmpty) #expect(registrar.action(for: HotKeyPress(hotKey: sharedKey, isRepeat: true)) == nil) #expect(registrar.bindings[NativeAppRuntime.hotkey(escape)] == nil) #expect(registrar.bindings[NativeAppRuntime.hotkey(entry)] == .enterMode("resize")) } @Test func failedModeTransitionNeverKeepsPreviousActionsAndRetriesRemoval() throws { let backend = KeyBackend() let registrar = backend.registrar() let old = try KeyChord(parsing: "ctrl-alt-a") let replacement = try KeyChord(parsing: "ctrl-alt-s") var configuration = ParcelConfiguration.defaults configuration.keybindings = [.focusLeft: old] configuration.modes = ["resize": [.command(.focusLeft): replacement]] _ = registrar.reload(configuration) let oldKey = NativeAppRuntime.hotkey(old) backend.failed = [NativeAppRuntime.hotkey(replacement)] backend.failedUnregister = [oldKey] let failed = registrar.reload(configuration, mode: "resize") #expect(Set(failed.conflicts.map(\.chord)) == Set([old, replacement])) #expect(registrar.bindings.isEmpty) #expect(backend.repeats[oldKey] == false) backend.failed = [] backend.failedUnregister = [] #expect(registrar.reload(configuration, mode: "resize").conflicts.isEmpty) #expect(registrar.bindings[oldKey] == nil) #expect(registrar.bindings[NativeAppRuntime.hotkey(replacement)] == .command(.focusLeft)) #expect(backend.repeats[oldKey] == nil) } @Test func activeModeReloadReplacesChangedModeBindings() throws { let backend = KeyBackend() let registrar = backend.registrar() let old = try KeyChord(parsing: "ctrl-alt-a") let updated = try KeyChord(parsing: "ctrl-alt-s") var configuration = ParcelConfiguration.defaults configuration.modes = ["resize": [.exitMode: old]] _ = registrar.reload(configuration, mode: "resize") configuration.modes["resize"] = [.exitMode: updated] #expect(registrar.reload(configuration, mode: "resize").conflicts.isEmpty) #expect(registrar.bindings[NativeAppRuntime.hotkey(old)] == nil) #expect(registrar.bindings[NativeAppRuntime.hotkey(updated)] == .exitMode) } @Test func exitModeUsesOnlyItsConfiguredChord() throws { let backend = KeyBackend() let registrar = backend.registrar() let exit = try KeyChord(parsing: "ctrl-alt-x") let escape = try KeyChord(parsing: "escape") var configuration = ParcelConfiguration.defaults configuration.keybindings = [:] configuration.modes = ["resize": [.exitMode: exit]] #expect(registrar.reload(configuration, mode: "resize").conflicts.isEmpty) #expect(registrar.bindings[NativeAppRuntime.hotkey(exit)] == .exitMode) #expect(registrar.bindings[NativeAppRuntime.hotkey(escape)] == nil) #expect(backend.repeats[NativeAppRuntime.hotkey(exit)] == false) #expect(registrar.reload(configuration).conflicts.isEmpty) #expect(registrar.bindings.isEmpty) } @Test func treeLayoutAnnouncementsAreLocalized() { #expect(AppText.string("tree") == "Tree layout.") #expect(AppText.string("bsp") == "BSP layout.") #expect(AppText.string("accordion") == "Accordion layout.") } @Test func capabilityLimitIsNotAnApplicationFailure() { var failures: [AppNotices.Kind] = [] let log = AppEngineLog() log.failure = { _, kind in failures.append(kind) } log.record(.core(.layoutCapabilityLimit(layout: .grid, maximum: 4))) log.record(.core(.atWindowCap(4))) #expect(failures.isEmpty) } @Test func snapshotsKeepFullDisplayCapabilitiesAndAllActiveWorkspaceLayoutsForSettings() async throws { let firstUUID = UUID() let secondUUID = UUID() let first = DisplayID(rawValue: firstUUID.uuidString) let second = DisplayID(rawValue: secondUUID.uuidString) let space = SpaceID(rawValue: 1) let otherSpace = SpaceID(rawValue: 2) let firstKey = WorkspaceKey(display: first, space: space) let secondKey = WorkspaceKey(display: second, space: space) let otherKey = WorkspaceKey(display: first, space: otherSpace) let usable = Rect(width: 2560, height: 980) let full = Rect(width: 2560, height: 1080) var state = State( displays: [ ParcelCore.Display(id: first, frame: usable, fullFrame: full), ParcelCore.Display(id: second, frame: Rect(width: 1920, height: 1080)), ], activeSpaces: [first: space, second: space], workspaces: [ firstKey: Workspace(key: firstKey, layout: .side), secondKey: Workspace(key: secondKey, layout: .grid), otherKey: Workspace(key: otherKey, layout: .columns), ], activeDisplay: first) state.focusModes = [firstKey: FocusModes(focusedWindow: WindowID(rawValue: 1), noPeek: true, cleanSpace: true)] let services = EngineShellServices() let settings = SettingsModel(store: ConfigStore()) services.publish(EngineSnapshot(revision: 1, state: state), settings: settings) var snapshots = services.snapshots().makeAsyncIterator() let published = try #require(await snapshots.next()) #expect(published.bounds == CGRect(x: 0, y: 0, width: 2560, height: 980)) #expect(published.capabilityBounds == CGRect(x: 0, y: 0, width: 2560, height: 1080)) #expect(published.layout == .side) #expect(published.isFocused) #expect(published.noPeek) #expect(published.cleanSpace) #expect(settings.runningLayout(for: nil) == .side) #expect(settings.runningLayout(for: firstUUID) == .side) #expect(settings.runningLayout(for: secondUUID) == .grid) state.activeSpaces[first] = otherSpace services.publish(EngineSnapshot(revision: 2, state: state), settings: settings) let switched = try #require(await snapshots.next()) #expect(!switched.isFocused) #expect(!switched.noPeek) #expect(!switched.cleanSpace) #expect(switched.capabilityBounds == published.capabilityBounds) #expect(settings.runningLayout(for: nil) == .columns) #expect(settings.runningLayout(for: firstUUID) == .columns) state.displays.removeValue(forKey: first) state.activeDisplay = second services.publish(EngineSnapshot(revision: 3, state: state), settings: settings) #expect(settings.runningLayout(for: firstUUID) == nil) #expect(settings.runningLayout(for: nil) == .grid) } @Test func carbonChordConflictDoesNotFallBackToAnEventTap() { let backend = CarbonBackend() backend.status = -9878 let center = HotKeyCenter(backend: backend, onPress: { _ in }, onFailure: { _ in }) #expect(throws: InputError.self) { try center.register(HotKey(keyCode: 0, modifiers: [.control, .option])) } #expect(backend.tapStarts == 0) #expect(center.registrations.isEmpty) } @Test func repeatPolicyChangesCancelHeldRepeatsWithoutReplacingRegistration() throws { let backend = CarbonBackend() var presses = 0 var tick: (@MainActor () -> Void)? let center = HotKeyCenter( backend: backend, onPress: { _ in presses += 1 }, onFailure: { _ in }, scheduleRepeat: { action in tick = action return { tick = nil } }) let key = HotKey(keyCode: 0, modifiers: [.control, .option]) try center.register(key, repeats: true) let id = try #require(backend.id) backend.onCarbonEvent?(id, true) tick?() #expect(presses == 2) center.updateRepeats(key, enabled: true) #expect(tick != nil) center.updateRepeats(key, enabled: false) #expect(tick == nil) #expect(backend.registerCount == 1) #expect(center.registrations.count == 1) backend.onCarbonEvent?(id, false) backend.onCarbonEvent?(id, true) #expect(presses == 3) #expect(tick == nil) try center.stop() } @Test func appEngineLogAggregatesFailuresAndForwardsLifecycleFlushes() { var messages: [String] = [] let sink = SystemEngineLog(clock: AppLogTestClock(), scheduler: RunLoopEngineScheduler()) { messages.append($0) } let log = AppEngineLog(log: sink) let app = AppID(pid: 123, bundleID: "test.document") log.record(.platform(.timedOut(app))) log.record(.platform(.timedOut(app))) #expect(messages.count == 1) #expect(messages.first?.hasSuffix("[count=1 total=1]") == true) log.flush() #expect(messages.count == 2) #expect(messages.last?.hasSuffix("[count=1 total=2]") == true) log.forgetFailures(for: app) log.record(.platform(.timedOut(app))) #expect(messages.count == 3) #expect(messages.last?.hasSuffix("[count=1 total=1]") == true) } @Test func appEngineLogAggregationNeverSuppressesNoticesOrCommandFeedback() { var messages: [String] = [] let sink = SystemEngineLog(clock: AppLogTestClock(), scheduler: RunLoopEngineScheduler()) { messages.append($0) } let log = AppEngineLog(log: sink) var notices: [AppNotices.Kind] = [] var refusals: [Direction] = [] log.failure = { _, kind in notices.append(kind) } log.refusal = { refusals.append($0) } let app = AppID(pid: 123, bundleID: "test.document") log.record(.platform(.accessibility(app, window: nil, cause: .notPermitted))) log.record(.platform(.accessibility(app, window: nil, cause: .notPermitted))) #expect(messages.count == 1) #expect(notices == [.permission, .permission]) log.record(.core(.noNeighbor(.left))) log.record(.core(.noNeighbor(.left))) #expect(refusals == [.left, .left]) log.flush() #expect(messages.count == 4) } @Test func transientEngineDiagnosticsStayOutOfNotices() { let log = AppEngineLog() var kinds: [AppNotices.Kind] = [] log.failure = { _, kind in kinds.append(kind) } let app = AppID(pid: 123, bundleID: "fixture") log.record(.platform(.timedOut(app))) log.record(.platform(.vanished(WindowID(rawValue: 1)))) log.record(.platform(.accessibility(app, window: nil, cause: .timedOut))) log.record(.platform(.appUnavailable(app))) log.record(.platform(.unexpected(EngineUnexpectedFailure(cause: AXPlatformError.timedOut)))) log.record(.internalFailure(AXPlatformError.elementInvalid)) #expect(kinds.isEmpty) log.record(.platform(.permissionLost)) log.record(.configuration("invalid config")) log.record(.internalFailure(AppFailure(message: "internal"))) #expect(kinds == [.permission, .configuration, .internalFailure]) } @Test func engineDiagnosticNoticesPreserveActionableErrorsInsteadOfGenericCopy() { let log = AppEngineLog() let notices = AppNotices() var reports: [AppNotices.Report] = [] log.failure = { error, kind in guard !notices.recordDiagnosticIfNeeded(error, kind: kind) else { return } reports.append(notices.report(error, kind: kind)) } log.record(.internalFailure(NSError(domain: "FirstLaunch", code: -1))) log.record(.internalFailure(TourSetupFailure.unavailable)) log.record( .platform( .unexpected(EngineUnexpectedFailure(cause: AXPlatformError.unavailable("fixture menu unavailable"))))) #expect(reports.isEmpty) log.record(.internalFailure(EngineError.settingsUnavailable)) log.record(.platform(.unexpected(EngineUnexpectedFailure(cause: EngineError.stopped)))) #expect( reports.map(\.message) == [ EngineError.settingsUnavailable.localizedDescription, EngineError.stopped.localizedDescription, ]) #expect(reports.allSatisfy { $0.message != AppNotices.Kind.internalFailure.message }) } @Test func snapshotsPublishOnlyChangedTopics() { var changes = AppSnapshotChanges() var state = State() #expect(Set(changes.receive(EngineSnapshot(revision: 0, state: state))) == Set(IPCTopic.allCases)) #expect(changes.receive(EngineSnapshot(revision: 1, state: state)).isEmpty) state.focusedWindow = WindowID(rawValue: 1) #expect(changes.receive(EngineSnapshot(revision: 2, state: state)) == [.focus]) state.frames[WindowID(rawValue: 1)] = Rect(width: 400, height: 300) #expect(changes.receive(EngineSnapshot(revision: 3, state: state)) == [.layout]) state.windows[WindowID(rawValue: 1)] = ManagedWindow( id: WindowID(rawValue: 1), app: AppID(pid: 123, bundleID: "fixture")) #expect(changes.receive(EngineSnapshot(revision: 4, state: state)) == [.window]) state.activeSpaces[DisplayID(rawValue: "display")] = SpaceID(rawValue: 2) #expect(changes.receive(EngineSnapshot(revision: 5, state: state)) == [.workspace]) } @Test func automaticTilingChoicePersistsAcrossAppInstances() throws { let suite = "dev.vinnymac.parcel.tests.\(UUID())" let defaults = try #require(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } let first = EngineShellServices(defaults: defaults) first.setAutomaticTilingEnabled(false) let second = EngineShellServices(defaults: defaults) #expect(!second.isAutomaticTilingEnabled) second.setAutomaticTilingEnabled(true) #expect(EngineShellServices(defaults: defaults).isAutomaticTilingEnabled) } @Test(arguments: [false, true]) func legacyPausePreferenceMigratesOnceWithoutChangingTheChoice(paused: Bool) throws { let suite = "dev.vinnymac.parcel.tests.\(UUID())" let defaults = try #require(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } defaults.set(paused, forKey: "tilingPaused") let services = EngineShellServices(defaults: defaults) #expect(services.isAutomaticTilingEnabled == !paused) #expect(defaults.bool(forKey: "automaticTilingEnabled") == !paused) #expect(defaults.object(forKey: "tilingPaused") == nil) defaults.set(!paused, forKey: "tilingPaused") #expect(EngineShellServices(defaults: defaults).isAutomaticTilingEnabled == !paused) #expect(defaults.object(forKey: "tilingPaused") == nil) } @Test func problemPriorityKeepsActionableFailuresAheadOfInformation() { let configuration = MenuProblem.configuration(reason: "Shortcut registration failed") #expect( NativeAppRuntime.menuProblem( shortcutsOff: true, secureInput: true, secureInputOwner: "Fixture", updateReady: true, configuration: configuration ) == .shortcutsOff) #expect( NativeAppRuntime.menuProblem( shortcutsOff: false, secureInput: true, secureInputOwner: "Fixture", updateReady: true, configuration: configuration ) == configuration) #expect( NativeAppRuntime.menuProblem( shortcutsOff: false, secureInput: true, secureInputOwner: "Fixture", updateReady: true, configuration: nil ) == .secureInput(ownerName: "Fixture")) #expect( NativeAppRuntime.menuProblem( shortcutsOff: false, secureInput: false, secureInputOwner: nil, updateReady: true, configuration: nil ) == .updateReady) #expect( NativeAppRuntime.menuProblem( shortcutsOff: false, secureInput: true, secureInputOwner: "Fixture", updateReady: false, configuration: nil ) == .secureInput(ownerName: "Fixture")) #expect( NativeAppRuntime.menuProblem( shortcutsOff: false, secureInput: false, secureInputOwner: nil, updateReady: false, configuration: nil ) == nil) } @Test(arguments: [ ([NoticeAction.retryStartup], NoticeAction.retryStartup), ([.accessibilitySettings, .retryStartup], .retryStartup), ([.useAlternatePrefix, .inputMonitoringSettings], .useAlternatePrefix), ([.useAlternatePrefix, .retryStartup], .retryStartup), ]) func shortcutProblemPreservesStartupAndVoiceOverRepairActions(actions: [NoticeAction], expected: NoticeAction) { #expect(NativeAppRuntime.shortcutRepairAction(actions) == expected) } @Test(arguments: [ ([NoticeAction.retryStartup], MenuProblem.startupFailure), ([.useAlternatePrefix], .voiceOverShortcutConflict), ([.useAlternatePrefix, .retryStartup], .startupFailure), ]) func repairNoticesHaveSpecificProblemKinds(actions: [NoticeAction], expected: MenuProblem) { #expect( NativeAppRuntime.menuProblem( shortcutsOff: true, secureInput: true, secureInputOwner: "Fixture", updateReady: true, configuration: .configuration(reason: "Invalid shortcut"), noticeActions: actions) == expected) } @Test func applicationMenuShortcutsRemainPresentedWithVoiceOverAndSecureInput() throws { let configuration = ParcelConfiguration.defaults let presented = NativeAppRuntime.shortcutPresentation( configuration, secureInput: true, voiceOverEnabled: true) for command in [ConfigCommand.openSettings, .quit] { let chord = try #require(configuration.keybindings[command]) #expect(DefaultKeybindings.isApplicationMenuShortcut(for: command, chord: chord)) #expect(presented.keybindings[command] == chord) } #expect(configuration == ParcelConfiguration.defaults) } @Test(arguments: [ ("first\nsecond\nthird", 2, NSRange(location: 6, length: 7)), ("👋🏽\r\nsecond\r\n", 2, NSRange(location: 6, length: 8)), ("first\n", 3, NSRange(location: 6, length: 0)), ("", 1, NSRange(location: 0, length: 0)), ]) func configurationViewerSelectsTheDiagnosticLine(contents: String, line: Int, expected: NSRange) { #expect(AppConfigViewer.lineRange(in: contents, line: line) == expected) } } @MainActor private final class KeyBackend { var operations: [String] = [] var failed: Set = [] var failedUnregister: Set = [] var repeats: [HotKey: Bool] = [:] var repeatUpdates: [(HotKey, Bool)] = [] func registrar() -> AppHotkeys { AppHotkeys( register: { [self] key, repeating in operations.append("register \(key)") if failed.contains(key) { throw AppFailure(message: "conflict") } repeats[key] = repeating }, unregister: { [self] key in operations.append("unregister \(key)") if failedUnregister.contains(key) { throw AppFailure(message: "unregister failed") } repeats.removeValue(forKey: key) }, updateRepeats: { [self] key, repeating in repeatUpdates.append((key, repeating)) repeats[key] = repeating }) } } @MainActor private final class IdleDisplayLink: EngineDisplayLink { let frameRate: Double = 120 var isRunning = false func start(tick: @escaping @MainActor (Double) -> Void) { isRunning = true } func stop() { isRunning = false } } @MainActor private final class CarbonBackend: HotKeyBackend { var onCarbonEvent: (@MainActor (UInt32, Bool) -> Void)? var onTapEvent: (@MainActor (CGEventType, CGEvent) -> Bool)? var onFailure: (@MainActor (InputError) -> Void)? var status: Int32 = 0 var tapStarts = 0 var registerCount = 0 var unregisterCount = 0 var id: UInt32? func registerCarbon(_ key: HotKey, id: UInt32) throws -> Int32 { registerCount += 1 self.id = id return status } func unregisterCarbon(id: UInt32) throws { unregisterCount += 1 } func isPressed(_ key: HotKey) -> Bool? { true } func startTap() throws { tapStarts += 1 } func stopTap() {} } extension AppKitTestSuite { @Suite("AppKit runtime regressions") @MainActor struct AppKitRuntimeRegressionTests { @Test(arguments: [ (MenuProblem.voiceOverShortcutConflict, "VoiceOver is on — Use ⌥⌘"), (.startupFailure, "Parcel could not start tiling — Try again"), ]) func repairProblemsRenderExactAccessibleActions(problem: MenuProblem, title: String) throws { _ = NSApplication.shared let controller = try MenuBarController(invoke: { _ in }) defer { controller.stop() } var requested: [MenuProblem] = [] controller.onProblemRequested = { requested.append($0) } controller.update( snapshot: LayoutSnapshot( layout: .grid, bounds: CGRect(x: 0, y: 0, width: 1000, height: 800), tiles: []), configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false, problem: problem) controller.menu.delegate?.menuNeedsUpdate?(controller.menu) let item = try #require(controller.menu.items.first { $0.identifier?.rawValue == "menu.problem" }) #expect(item.title == title) #expect(item.accessibilityLabel() == title) #expect(item.isEnabled) controller.menu.performActionForItem(at: controller.menu.index(of: item)) #expect(requested == [problem]) } @Test(arguments: [2, nil] as [Int?]) func configViewerShowsTheReasonAndSelectsOnlyADiagnosticLine(line: Int?) throws { _ = NSApplication.shared let file = FileManager.default.temporaryDirectory.appendingPathComponent("config-viewer-\(UUID()).toml") let contents = "[layout]\nwindow-cap = bad\n" try contents.write(to: file, atomically: true, encoding: .utf8) defer { do { try FileManager.default.removeItem(at: file) } catch { Issue.record(error) } } let viewer = AppConfigViewer(onFailure: { Issue.record($0) }) defer { viewer.close() } let reason = "Shortcuts could not be registered. Choose different chords in Settings." try viewer.show(fileURL: file, line: line, reason: reason) let window = try #require( NSApplication.shared.windows.first { $0.isVisible && $0.title == "Configuration File" }) let stack = try #require(window.contentView as? NSStackView) let scroll = try #require(stack.arrangedSubviews.compactMap { $0 as? NSScrollView }.first) let text = try #require(scroll.documentView as? NSTextView) #expect(text.string == contents) let problem = try #require(stack.arrangedSubviews.compactMap { $0 as? NSTextField }.first) #expect(problem.stringValue == reason) #expect(problem.isSelectable) #expect(problem.accessibilityIdentifier() == "config-file.problem") let selection = line.map { AppConfigViewer.lineRange(in: contents, line: $0) } ?? NSRange(location: 0, length: 0) #expect(text.selectedRange() == selection) #expect(text.bounds.width > 300 && text.bounds.height > 200) #expect(!text.isEditable && text.isSelectable) #expect(window.firstResponder === text) } @Test func modeAnnouncementsSynchronizeBeforePublishingAccessibility() { _ = NSApplication.shared var changes = 0 let announcer = AppAnnouncer { changes += 1 } announcer.announce(.modeChanged("resize")) announcer.announce(.modeChanged(nil)) announcer.announce(.layoutChanged(.grid)) #expect(changes == 2) } @Test func rejectedEngineReloadStillAppliesPaletteAndColorMode() throws { let application = NSApplication.shared let previous = application.appearance defer { OverlayPaletteSource.shared.configure(.init()) application.appearance = previous } let baseline = ParcelConfiguration.defaults let engine = try ParcelEngine( world: RecordingWorld(), clock: SystemEngineClock(), scheduler: RunLoopEngineScheduler(), displayLink: { _ in throw AppFailure(message: "This test never starts a display link") }, announcer: AppAnnouncer(onModeChange: {}), log: AppEngineLog(), configuration: baseline, trace: nil, reduceMotionSource: nil) let runtime = NativeAppRuntime(store: ConfigStore(), socketPath: "/tmp/appearance-reload-unused.sock") runtime.services.engine = engine let choices: [(ConfigAppearancePalette, ConfigAppearanceMode, NSAppearance.Name?)] = [ (.kiln, .dark, .darkAqua), (.tide, .light, .aqua), (.rose, .system, nil), ] for (palette, mode, name) in choices { var rejected = baseline rejected.version = 2 rejected.appearance = .init(palette: palette, mode: mode) #expect(throws: EngineError.invalidConfiguration("Unsupported configuration version")) { try runtime.applyConfiguration(rejected) } #expect(engine.configuration == baseline) #expect(application.appearance?.name == name) let expected = OverlayPaletteSource(configuration: rejected.appearance) for drawingName in [NSAppearance.Name.aqua, .darkAqua] { let appearance = try #require(NSAppearance(named: drawingName)) let actual = OverlayPaletteSource.shared.resolve(for: appearance, accessibility: .init()) let resolved = expected.resolve(for: appearance, accessibility: .init()) #expect(actual.activeBorder == resolved.activeBorder) #expect(actual.chipBackground == resolved.chipBackground) } } } @Test func tabViewOpensAndFocusesWithoutAutomaticTiling() async throws { _ = NSApplication.shared let suite = "dev.vinnymac.parcel.tests.\(UUID())" let defaults = try #require(UserDefaults(suiteName: suite)) defaults.set(false, forKey: "automaticTilingEnabled") defaults.set(true, forKey: "guidedTour.v2.completed") defaults.set(true, forKey: "onboardingCompleted") defer { defaults.removePersistentDomain(forName: suite) } let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) defer { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } let world = RecordingWorld() let display = DisplayID(rawValue: "tab-view-display") let space = SpaceID(rawValue: 1) let key = WorkspaceKey(display: display, space: space) world.startingEvents = [ .observed(.displaySetChanged([Display(id: display, frame: Rect(width: 1200, height: 800))])), .observed(.activeSpaceChanged(display: display, space: space)), ] let runtime = NativeAppRuntime( store: ConfigStore(fileURL: directory.appendingPathComponent("config.toml")), socketPath: directory.appendingPathComponent("unused.sock").path, defaults: defaults, fixtureOnly: true, makeWindowWorld: { world }, makeDisplayLink: { _ in IdleDisplayLink() }) var configuration = ParcelConfiguration.defaults configuration.motion.enabled = false try await runtime.startEngine(configuration: configuration) let backend = CarbonBackend() let center = HotKeyCenter(backend: backend, onPress: { _ in }, onFailure: { _ in }) runtime.tabView = AppTabView(hotkeys: center, choose: { _, _ in }) let hotkey = HotKey(keyCode: 48, modifiers: .option) try runtime.openTabView(HotKeyPress(hotKey: hotkey, isRepeat: false)) #expect(backend.tapStarts == 1) let engine = try #require(runtime.services.engine) #expect(!engine.isAutomaticTilingEnabled) let window = ManagedWindow(id: WindowID(rawValue: 1), app: AppID(pid: 123, bundleID: "fixture")) world.receive?(.observed(.windowAppeared(window, workspace: key, frame: Rect(width: 400, height: 300)))) let deadline = ContinuousClock.now + .seconds(2) while engine.snapshot.state.workspace(containing: window.id) == nil { guard ContinuousClock.now < deadline else { throw AppFailure(message: "Window did not appear") } try await Task.sleep(for: .milliseconds(5)) } try await runtime.selectTabViewWindow(window.id, minimized: false, cached: nil) #expect(world.focused == window.id) #expect(world.raised == window.id) #expect(world.writes.isEmpty) #expect(!engine.isAutomaticTilingEnabled) runtime.tabView = nil do { try runtime.openTabView(HotKeyPress(hotKey: hotkey, isRepeat: false)) Issue.record("Tab View should fail when its shortcuts are unavailable") } catch let failure as AppFailure { #expect(failure.message == "Tab View is unavailable. Try again after shortcuts start.") } try await runtime.restoreAndStopEngine() try center.stop() } @Test(arguments: [false, true]) func disabledAutomaticTilingAndTourHoldPreventStartupWrites(firstRun: Bool) async throws { _ = NSApplication.shared let suite = "dev.vinnymac.parcel.tests.\(UUID())" let defaults = try #require(UserDefaults(suiteName: suite)) defaults.set(firstRun, forKey: "automaticTilingEnabled") defaults.set(!firstRun, forKey: "guidedTour.v2.completed") defaults.set(!firstRun, forKey: "onboardingCompleted") let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) defer { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } defer { defaults.removePersistentDomain(forName: suite) } let world = RecordingWorld() let display = DisplayID(rawValue: "pause-display") let space = SpaceID(rawValue: 1) world.startingEvents = [ .observed(.displaySetChanged([Display(id: display, frame: Rect(width: 1200, height: 800))])), .observed(.activeSpaceChanged(display: display, space: space)), .observed( .windowAppeared( ManagedWindow(id: WindowID(rawValue: 1), app: AppID(pid: 123, bundleID: "fixture")), workspace: WorkspaceKey(display: display, space: space), frame: Rect(width: 400, height: 300))), ] let runtime = NativeAppRuntime( store: ConfigStore(fileURL: directory.appendingPathComponent("config.toml")), socketPath: "/tmp/paused-unused.sock", defaults: defaults, makeWindowWorld: { world }, makeDisplayLink: { _ in IdleDisplayLink() }) var configuration = ParcelConfiguration.defaults configuration.motion.enabled = false try await runtime.startEngine(configuration: configuration) let engine = try #require(runtime.services.engine) _ = try await engine.perform(.enterMode(nil)) #expect(!engine.isAutomaticTilingEnabled) #expect(runtime.acceptsHotkeyInput == !firstRun) #expect(world.writes.isEmpty) #expect(runtime.services.isTourUnresolved == firstRun) if firstRun { await #expect(throws: AppFailure.self) { try await runtime.services.send(.toggleAutomaticTiling) } await #expect(throws: AppFailure.self) { try await runtime.services.send(.focusRight) } let handler = AppIPCHandler( services: runtime.services, configPath: "/tmp/unused.toml", permission: { true }) await #expect(throws: AppFailure.self) { _ = try await handler.run(command: "retile", args: []) } await #expect(throws: AppFailure.self) { _ = try await handler.run(command: "drop", args: ["1", "2"]) } #expect(!engine.isAutomaticTilingEnabled) #expect(world.writes.isEmpty) runtime.services.resolveTour() #expect(runtime.services.isAutomaticTilingEnabled) } runtime.services.setAutomaticTilingEnabled(true) #expect(runtime.acceptsHotkeyInput) _ = try await engine.perform(.retile) let deadline = ContinuousClock.now + .seconds(2) while world.writes.isEmpty { guard ContinuousClock.now < deadline else { throw AppFailure(message: "Resume did not write a frame") } await Task.yield() } #expect(!world.writes.isEmpty) let backend = CarbonBackend() var presses: [HotKeyPress] = [] let center = HotKeyCenter( backend: backend, onPress: { presses.append($0) }, onFailure: { Issue.record($0) }, isActive: { runtime.acceptsHotkeyInput }) defer { do { try center.stop() } catch { Issue.record(error) } } let carbon = NativeAppRuntime.hotkey(try KeyChord(parsing: "ctrl-alt-a")) let arrow = NativeAppRuntime.hotkey(try KeyChord(parsing: "ctrl-alt-left")) try center.register(carbon) try center.register(arrow) #expect(backend.registerCount == 1) runtime.services.setAutomaticTilingEnabled(false) #expect(runtime.acceptsHotkeyInput) try center.refreshActivity() #expect(backend.unregisterCount == 0) #expect(center.isAvailable(carbon) && center.isAvailable(arrow)) let carbonID = try #require(backend.id) backend.onCarbonEvent?(carbonID, true) backend.onCarbonEvent?(carbonID, false) #expect(presses.map(\.hotKey) == [carbon]) presses.removeAll() for down in [true, false] { let event = try #require(CGEvent(keyboardEventSource: nil, virtualKey: arrow.keyCode, keyDown: down)) event.flags = arrow.modifiers.eventFlags #expect(backend.onTapEvent?(down ? .keyDown : .keyUp, event) == true) } #expect(presses.map(\.hotKey) == [arrow]) try center.unregister(arrow) for down in [true, false] { let event = try #require(CGEvent(keyboardEventSource: nil, virtualKey: arrow.keyCode, keyDown: down)) event.flags = arrow.modifiers.eventFlags #expect(backend.onTapEvent?(down ? .keyDown : .keyUp, event) == false) } #expect(presses.map(\.hotKey) == [arrow]) try await runtime.services.send(.retile) #expect(runtime.acceptsHotkeyInput) try await runtime.restoreAndStopEngine() #expect(!runtime.acceptsHotkeyInput) } } } extension AppKitTestSuite { @MainActor struct AdaptiveFeedbackPresentationTests { @Test(arguments: [2, 3]) func stackedWindowsStayQuietWhileExplicitChangesRemainAnnounced(count: Int) throws { let display = DisplayID(rawValue: "feedback-display") let key = WorkspaceKey(display: display, space: SpaceID(rawValue: 1)) let windows = (1...count).map { ManagedWindow(id: WindowID(rawValue: UInt32($0)), app: AppID(pid: 123, bundleID: "fixture")) } let state = reduce( State( displays: [Display(id: display, frame: Rect(width: 1000, height: 800))], activeSpaces: [display: key.space], workspaces: [key: Workspace(key: key, windowCap: 1, order: windows.map(\.id))], windows: Dictionary(uniqueKeysWithValues: windows.map { ($0.id, $0) }), focusedWindow: windows[0].id), .relayout ).0 #expect(state.workspaces[key]?.tree?.tileCount == 1) let model = FeedbackModel() var announced: [String] = [] let controller = FeedbackController( model: model, announce: { announced.append($0) }, onFailure: { _ in Issue.record("Unexpected feedback failure") }) defer { controller.stop() } let announcer = AppAnnouncer( postAnnouncement: { announced.append($0) }, onModeChange: {}) announcer.announce(.tilesMerged(count: 1, limit: 3)) announcer.announce(.stackChanged(window: windows[0].id, count: count)) #expect(model.current == nil && announced.isEmpty) announcer.announce(.windowsStacked(window: windows[0].id, count: count)) #expect(model.current == nil) #expect(announced.isEmpty) announcer.announce(.stackChanged(window: windows[0].id, count: 1)) announcer.announce(.ratioChanged(.half)) #expect(model.recent.isEmpty) #expect(announced == ["Window stack changed.", "Main window ratio changed."]) } } }