Exit when Accessibility is revoked

A tap that outlives its Accessibility grant can stall scroll events,
and every later click and key queues behind them. When the grant goes,
remove the tap, restore the buttons and exit.

Assisted-by: Claude
Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
This commit is contained in:
yigid committed 2026-10-30 23:06:52 +03:00
1 parent cbbb631f3c
commit 719866a2a7
1 file changed
+22
+22
View File
@@ -560,6 +560,28 @@ if rc != kIOReturnSuccess {
log(String(format: "IOHIDManagerOpen failed: 0x%08x — grant Input Monitoring to this binary/terminal", rc)) 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)
}
// 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() }
}
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. // Clean shutdown: un-divert so buttons work natively again.
signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN) signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN)
let sigSources = [SIGINT, SIGTERM].map { s -> DispatchSourceSignal in let sigSources = [SIGINT, SIGTERM].map { s -> DispatchSourceSignal in