From 7224d7604ecee0151e8395d61ef5a4ba25ac2b2f Mon Sep 17 00:00:00 2001 From: Yigit BALABAN Date: Fri, 30 Oct 2026 23:45:08 +0300 Subject: [PATCH] Detect a dead scroll tap from a background watchdog The revocation guard never fired: scroll events stalled about 10 s and mxd kept running without logging. Either AXIsProcessTrusted stayed true in the running process or the main thread was stuck. Check every 500 ms from a background queue, so a stuck main thread can't stop the check. Also watch the outcome instead of trusting the permission API alone: the HID scroll counter advancing without events reaching the tap for 2 s, the tap staying disabled for 2 s, and two timeouts within 30 s. Log which signal fired. A hard _exit deadline is set first, in case removing the tap blocks. Revocation exits 0 so launchd stays down. A stall exits 1, so a false positive costs only a restart, and a real revocation leaves mxd idle because tapCreate fails. Assisted-by: Claude Sonnet 5.5 Signed-off-by: Yigit BALABAN --- mxd.swift | 96 ++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 77 insertions(+), 19 deletions(-) diff --git a/mxd.swift b/mxd.swift index e79110f..f3e32e9 100644 --- a/mxd.swift +++ b/mxd.swift @@ -263,6 +263,9 @@ final class Smoother { } let smoother = Smoother() var tapPort: CFMachPort? +var scrollEventsSeen = 0 +var lastTimeoutAt: Double? +let watchdogQueue = DispatchQueue(label: "mxd.watchdog", qos: .userInteractive) /// A notch's size, using the first non-zero of point delta, fixed-point delta, line delta (Mos's order). /// The point delta includes macOS's wheel acceleration, which is how fast spins go further. @@ -289,8 +292,19 @@ func targetIgnored(_ pid: pid_t) -> Bool { } let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in - // macOS disables a tap that stalls or on secure input; just turn it back on. - if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput { + if type == .scrollWheel { scrollEventsSeen += 1 } + if type == .tapDisabledByTimeout { + let now = ProcessInfo.processInfo.systemUptime + log("tap timed out") + if let last = lastTimeoutAt, now - last < 30 { + watchdogQueue.async { stopTap(reason: "repeated tap timeouts", restart: true) } + return Unmanaged.passUnretained(event) + } + lastTimeoutAt = now + if let p = tapPort { CGEvent.tapEnable(tap: p, enable: true) } + return Unmanaged.passUnretained(event) + } + if type == .tapDisabledByUserInput { if let p = tapPort { CGEvent.tapEnable(tap: p, enable: true) } return Unmanaged.passUnretained(event) } @@ -651,27 +665,71 @@ if rc != kIOReturnSuccess { log(String(format: "IOHIDManagerOpen failed: 0x%08x — grant Input Monitoring to this binary/terminal", rc)) } -// A tap that outlives its Accessibility grant can stall scroll events, and every later click and key -// queues behind them. So when the grant goes: remove the tap first, restore the buttons, exit. -// Run under launchd with KeepAlive/SuccessfulExit=false, so exit(0) doesn't restart mxd. -func checkPermission() { - guard let port = tapPort, !AXIsProcessTrusted() else { return } - CGEvent.tapEnable(tap: port, enable: false) - CFMachPortInvalidate(port) - tapPort = nil - log("Accessibility revoked: tap removed, exiting") - devices.values.forEach(undivertAll) - exit(0) +struct StallDetector { + var lastSeen = 0, hidAtLastSeen = 0, behindSince: Double? = nil + mutating func update(seen: Int, hid: Int, now: Double, limit: Double) -> Bool { + if seen != lastSeen { + lastSeen = seen; hidAtLastSeen = hid; behindSince = nil + return false + } + if hid > hidAtLastSeen { + if behindSince == nil { behindSince = now } + return now - behindSince! >= limit + } + behindSince = nil + return false + } +} + +func hidScrollCount() -> Int { Int(CGEventSource.counterForEventType(.hidSystemState, eventType: .scrollWheel)) } + +var tapStopped = false +var tapDisabledSince: Double? +var postAccessAtStart = false, listenAccessAtStart = false +var stall = StallDetector() + +func stopTap(reason: String, restart: Bool) { + if tapStopped { return } + tapStopped = true + DispatchQueue.global().asyncAfter(deadline: .now() + 3) { _exit(restart ? 1 : 0) } + log("tap removed: \(reason), exiting") + if let port = tapPort { + CGEvent.tapEnable(tap: port, enable: false) + CFMachPortInvalidate(port) + } + DispatchQueue.main.async { devices.values.forEach(undivertAll); exit(restart ? 1 : 0) } +} + +func checkTap() { + guard let port = tapPort, !tapStopped else { return } + if !AXIsProcessTrusted() { return stopTap(reason: "AXIsProcessTrusted false", restart: false) } + if postAccessAtStart && !CGPreflightPostEventAccess() { return stopTap(reason: "CGPreflightPostEventAccess false", restart: false) } + if listenAccessAtStart && !CGPreflightListenEventAccess() { return stopTap(reason: "CGPreflightListenEventAccess false", restart: false) } + let now = ProcessInfo.processInfo.systemUptime + if CGEvent.tapIsEnabled(tap: port) { tapDisabledSince = nil } + else { + if tapDisabledSince == nil { tapDisabledSince = now } + if now - tapDisabledSince! >= 2 { return stopTap(reason: "tap disabled", restart: true) } + } + if stall.update(seen: scrollEventsSeen, hid: hidScrollCount(), now: now, limit: 2) { + stopTap(reason: "scroll events not reaching tap", restart: true) + } +} + +let watchdogTimer = DispatchSource.makeTimerSource(queue: watchdogQueue) +if !probeOnly && tapPort != nil { + postAccessAtStart = CGPreflightPostEventAccess() + listenAccessAtStart = CGPreflightListenEventAccess() + stall = StallDetector(lastSeen: scrollEventsSeen, hidAtLastSeen: hidScrollCount()) + watchdogTimer.schedule(deadline: .now() + 0.5, repeating: .milliseconds(500)) + watchdogTimer.setEventHandler { checkTap() } + watchdogTimer.resume() } -// The notification is immediate but can fire just before the new state is readable; the timer is the backstop. let permissionObserver = DistributedNotificationCenter.default().addObserver( forName: NSNotification.Name("com.apple.accessibility.api"), object: nil, queue: nil) { _ in - checkPermission() - DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { checkPermission() } + watchdogQueue.async { checkTap() } + watchdogQueue.asyncAfter(deadline: .now() + 0.1) { checkTap() } } -let permissionTimer = Timer(timeInterval: 1, repeats: true) { _ in checkPermission() } -permissionTimer.tolerance = 0.2 -RunLoop.main.add(permissionTimer, forMode: .common) // Clean shutdown: un-divert so buttons work natively again. signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN)