// // EscEventProbeTests.swift // MuseionTests // // #109 probe: WHY Esc needs the local monitor. Plain AppKit window → // the row textview's keyDown fires (control). The SAME textview behind // SwiftUI's NSHostingView → neither keyDown nor .onExitCommand fires: // the hosting layer swallows Esc before the responder chain. Hence // NSEvent.addLocalMonitorForEvents in OutlineEditorView — the monitor // sees queue events before SwiftUI does. (The monitor path itself // can't run in this harness — no running NSApp loop means no dequeue — // so it's smoke-tested live in the app.) // import AppKit @testable import Museion import SwiftUI import Testing @MainActor @Suite(.serialized) struct EscEventProbeTests { private func makeEscEvent(window: NSWindow) -> NSEvent? { NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53) } @Test func `esc reaches the row textview in a plain AppKit window (control)`() throws { let tv = RowTextView(frame: NSRect(x: 0, y: 0, width: 200, height: 27)) let bridge = OutlineRowTextView.Coordinator() var received: [OutlineRowTextView.StructureOp] = [] bridge.onStructure = { received.append($0) } tv.bridge = bridge let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 100), styleMask: [.titled], backing: .buffered, defer: false) window.contentView?.addSubview(tv) window.makeKeyAndOrderFront(nil) window.makeFirstResponder(tv) try NSApp.sendEvent(#require(makeEscEvent(window: window))) #expect(received.contains(.deselect)) } @Test func `esc dies in SwiftUI hosting - keyDown and onExitCommand never fire`() throws { let tv = RowTextView(frame: NSRect(x: 0, y: 0, width: 200, height: 27)) let bridge = OutlineRowTextView.Coordinator() var received: [OutlineRowTextView.StructureOp] = [] bridge.onStructure = { received.append($0) } tv.bridge = bridge var exitFired = false let hosted = HostProbe(textView: tv) .onExitCommand { exitFired = true } let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 100), styleMask: [.titled], backing: .buffered, defer: false) window.contentView = NSHostingView(rootView: hosted) window.makeKeyAndOrderFront(nil) window.makeFirstResponder(tv) window.layoutIfNeeded() try NSApp.sendEvent(#require(makeEscEvent(window: window))) // The pinned failure mode: SwiftUI ate it. (If this expectation // ever flips after an OS update, the monitor can be dropped.) #expect(!received.contains(.deselect)) #expect(!exitFired) } } /// Wraps an arbitrary NSView in SwiftUI so the probe can host RowTextView /// behind a real NSHostingView like the app does. private struct HostProbe: NSViewRepresentable { let textView: NSView func makeNSView(context _: Context) -> NSView { textView } func updateNSView(_: NSView, context _: Context) {} }