test(cua-macos): exercise unreadable menus through the owning AppKit process

This commit is contained in:
creatixchu committed 2026-11-12 17:16:33 +08:00
1 parent 06ae2c32fc
commit 413c5363dc
3 files changed
+47 -32

No files matched your search

@@ -8,6 +8,7 @@ import ApplicationServices
var inputLog: URL?
override func accessibilityChildren() -> [Any]? { childList ?? super.accessibilityChildren() }
@objc func paste(_ sender: NSMenuItem) { pressed.append(sender.title) }
@objc func press(_ sender: NSButton) {
pressed.append(sender.title)
if sender.title == "Identify as open panel" { setAccessibilityIdentifier("open-panel") }
@@ -21,6 +22,14 @@ import ApplicationServices
}
}
@MainActor private final class ChildFixtureMenu: NSMenu {
var gapFirst = false
override func accessibilityChildren() -> [Any]? {
let items = super.accessibilityChildren() ?? []
return gapFirst ? [NSNull()] + items : items + [NSNull()]
}
}
@main enum ChildProjectionFixture {
@MainActor static func main() throws {
let app = NSApplication.shared
@@ -42,6 +51,17 @@ import ApplicationServices
group.setAccessibilityRole(.group)
group.setAccessibilityChildren([NSTextField(labelWithString: "Nested child")])
bad.childList = [before, NSNull(), after, group, NSDate(timeIntervalSince1970: 0)]
let menuBar = NSMenu(), editItem = NSMenuItem(), edit = ChildFixtureMenu(title: "Edit")
edit.autoenablesItems = false
func addPaste(_ name: String) {
let item = NSMenuItem(title: name, action: #selector(ChildFixtureWindow.paste(_:)), keyEquivalent: "v")
item.target = bad
edit.addItem(item)
}
addPaste("Paste")
editItem.submenu = edit
menuBar.addItem(editItem)
app.mainMenu = menuBar
good.orderBack(nil)
bad.orderBack(nil)
app.finishLaunching()
@@ -82,6 +102,20 @@ import ApplicationServices
var whole: CFTypeRef?
try check(AXUIElementCopyAttributeValue(badRoot, kAXChildrenAttribute as CFString, &whole) == .failure, "AXChildren must return -25200")
// AppKit can vend a separate menu representation to other processes.
// Reading this application's own menu exercises the overridden AXChildren getter.
for scenario in ["before", "after", "duplicate"] {
edit.gapFirst = scenario == "before"
if scenario == "duplicate" { addPaste("Second Paste") }
do {
let command = try access.pasteCommand(getpid(), maxElements: 2000, maxDepth: 25)
try access.perform(command, "AXPress")
throw NativeFailure(code: "FIXTURE", message: "Dispatched Paste for " + scenario)
} catch let failure as NativeFailure where failure.code == "UNSUPPORTED" {
let reason = scenario == "duplicate" ? "ambiguous" : "incomplete"
try check(failure.message.contains(reason) && failure.message.contains("No input was dispatched"), failure.message)
}
}
let complete = try project(good)
try check(!complete.truncated && !complete.hasUnreadableElements && complete.tree.contains("Healthy window"), "An unrelated window reported missing children")
let partial = try project(bad)
@@ -1,14 +1,6 @@
// A foreground-sensitive Paste receiver records AX command delivery independently of clipboard consumption.
import AppKit
private final class PartialMenu: NSMenu {
var gapFirst = false
override func accessibilityChildren() -> [Any]? {
let items = super.accessibilityChildren() ?? []
return gapFirst ? [NSNull()] + items : items + [NSNull()]
}
}
final class PasteFixture: NSObject, NSApplicationDelegate, NSTextViewDelegate {
let statePath: String
let label: String
@@ -19,18 +11,12 @@ final class PasteFixture: NSObject, NSApplicationDelegate, NSTextViewDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
let menu = NSMenu()
let editItem = NSMenuItem()
let mode = CommandLine.arguments.dropFirst(3).first
let edit: NSMenu
if let mode {
let partial = PartialMenu(title: "Edit")
partial.gapFirst = mode == "before"
edit = partial
} else { edit = NSMenu(title: "Edit") }
let edit = NSMenu(title: "Edit")
edit.autoenablesItems = false
let paste = NSMenuItem(title: "Paste", action: #selector(pasteText(_:)), keyEquivalent: "v")
paste.target = self
edit.addItem(paste)
if mode == "duplicate" {
if CommandLine.arguments.last == "--duplicate" {
let duplicate = NSMenuItem(title: "Second Paste", action: #selector(pasteText(_:)), keyEquivalent: "v")
duplicate.target = self
edit.addItem(duplicate)
@@ -60,26 +60,21 @@ def main():
assert result == {"dispatched": True}, result
foreground = wait_state(root / "target.json", lambda state: state["text"] == "test")
assert foreground["pasteCalls"] == [False, True] and foreground["active"], foreground
for mode in ["before", "after", "duplicate"]:
state_path = root / f"{mode}.json"
receiver = subprocess.Popen([str(binary), str(state_path), f"DSH partial menu {mode}", mode],
stdout=subprocess.PIPE, text=True)
processes.append(receiver)
assert line(receiver).strip() == "READY"
partial = helper.call("getApp", {"selector": str(receiver.pid)})
target = {"appHandle": partial["appHandle"]}
tree = helper.call("getState", {**target, "maxElements": 2000, "maxDepth": 25, "includeMenus": True})
assert tree["hasUnreadableElements"] and any(e["title"] == "Paste" for e in tree["elements"])
error = helper.call("paste", {**params, **target}, "UNSUPPORTED")
reason = "ambiguous" if mode == "duplicate" else "incomplete"
assert reason in error["message"] and "No input was dispatched. Read fresh state" in error["message"], error
state = json.loads(state_path.read_text())
assert state["text"] == "" and state["pasteCalls"] == [], state
duplicate_path = root / "duplicate.json"
duplicate = subprocess.Popen([str(binary), str(duplicate_path), "Duplicate Paste commands", "--duplicate"],
stdout=subprocess.PIPE, text=True)
processes.append(duplicate)
assert line(duplicate).strip() == "READY"
target = helper.call("getApp", {"selector": str(duplicate.pid)})
error = helper.call("paste", {**params, "appHandle": target["appHandle"]}, "UNSUPPORTED")
assert "ambiguous" in error["message"] and "No input was dispatched. Read fresh state" in error["message"], error
state = json.loads(duplicate_path.read_text())
assert state["text"] == "" and state["pasteCalls"] == [], state
if args.artifacts:
args.artifacts.mkdir(parents=True, exist_ok=True)
(args.artifacts / "results.json").write_text(json.dumps({"background": background,
"foreground": foreground, "backgroundElapsedSeconds": elapsed, "error": unread}, indent=2) + "\n")
print(f"PASS: background PASTE_NOT_CONSUMED in {elapsed:.3f}s; foreground paste inserted test; unreadable and ambiguous menus received zero Paste actions")
print(f"PASS: background PASTE_NOT_CONSUMED in {elapsed:.3f}s; foreground paste inserted test; ambiguous menu received zero Paste actions")
finally:
if args.artifacts:
args.artifacts.mkdir(parents=True, exist_ok=True)