Cross-lane edit, authorised by the lead. The struct declared two public lets and no init, so the memberwise one was internal and no other target could build a value — `EngineSnapshot.permissions` had to default to `Permissions.preflight()`, i.e. a TCC query, just to have a value to hold. The default is now `PermissionState(listen: false, post: false)`, which is also the honest value before `start()` has read anything. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
36 KiB
input-capture
Goal
The Mac's side of InputHook.cs: a CGEventTap that sees every key,
modifier, mouse and scroll event, decides synchronously whether the
event stays on this Mac or is swallowed for a remote one, turns it into
the Windows encoding (docs/protocol.md §5), matches the hotkeys (§4.5)
and hands everything to the Engine through a bounded queue (contracts
C3). With it come the pieces the tap needs and the injector will share:
the Windows-VK ↔ macOS-keycode table, the screen geometry that feeds
Edge, the cursor parking/decoupling that keeps the real pointer still
while a remote machine is controlled, and the permission preflight/
request wrapper. Invariants 3 and 4 (CLAUDE.md) and contract C2 are
this lane's.
Assumptions
Written at planning time, revised 2026-09-16 to what shipped. Anything the code does not enforce is here.
- One tap, on its own thread.
CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap, options: .defaultTap, …)for key down/up, flagsChanged, mouse moved/dragged, all button down/up and scroll wheel. The run-loop source is added to theCFRunLoopof a dedicatedThreadat.userInteractive, never the main thread (contracts C3). A.defaultTapneeds Accessibility; listening to keys needs Input Monitoring (README §Permissions).tapDisabledByTimeout/tapDisabledByUserInputarrive whatever the mask says, so they are not in it. - The callback does five things and returns: (1) handle a disabled tap;
(2) if the event carries the injected tag (
CGEventField.eventSourceUserData == InputTypes.injectedEventTag) return it untouched — the WindowsRealDataflag (InputHook.cs:213-220, 340-343); (3) read theRoutingSnapshot; (4) match hotkeys — the escape set flips the snapshot to local inside the callback and is swallowed, other hotkeys are queued and swallowed; (5) if the destination is remote, convert toCapturedInput, push and swallow (InputHook.cs:361-368keyboard,:322-325mouse); if local, push mouse moves only soEdgecan watch for a crossing, and pass everything through. No allocation on any of it (invariant 4). - Four locks are reachable from the callback, all uncontended
OSAllocatedUnfairLocks held only for a struct copy:EventTap.counters,RoutingState's box (the snapshot and the virtual cursor share it),Screens' layout andCaptureQueue's ring. Counted from the code, per event, on the four paths that matter:- local key: 2 —
counters, snapshot read. An unmapped key adds onecounters; a matched hotkey adds one ring push, and an escape hotkey one moreRoutingStatewrite. - local mouse move: 3 —
counters, snapshot read, virtual-cursor write; 4 when Easy Mouse lets the move be offered as an.edgeCandidate(one ring push).Screensis not read on this path. - remote key: 3 —
counters, snapshot read, one ring push. AflagsChangedpushes once per modifier transition instead, and twice more for a Caps Lock toggle. - remote mouse move: 6 —
counters, snapshot read, virtual-cursor advance,Screens' layout, then two ring pushes (.mouseand.edgeCandidate); 5 when the candidate is suppressed. This is the worst path in the file.
- local key: 2 —
- Swallowing is a separate flag from the destination. ALL-machines mode
sends input to every peer and keeps it locally (
InputHook.cs:361), soswallowKeys/swallowMouseare set by the Engine, not derived here. - The queue is a bounded ring of 4096
CapturedInputs inMWBMac/CaptureQueue.swift(it needs a lock, whichMWBCoremay not import). Motion is coalesced on push against either of the last two entries — two, because one physical move queues a.mouseand an.edgeCandidatewhile a peer is controlled — stopping at the first entry that is not motion, so a transition is never reordered past. Latest position wins for an absolute move, deltas are summed for a relative one, and wheel deltas of the same axis are summed. A push that cannot be satisfied routes control local and raises.overflow, whichdrain()reports even when the ring is full (contracts C3). - Keyboard encoding:
wVkfromKeyMap.vk(forKeycode:);dwFlags=LLKHFbits (WM.cs:47-54):UP 0x80on key-up,EXTENDED 0x01for the keys Windows marks extended (right Ctrl/Alt, arrows, Ins/Del/Home/End/ PgUp/PgDn, numpad Enter and divide, Num Lock, both Windows keys),ALTDOWN 0x20while either Option is down. Autorepeat (CGEventField.keyboardEventAutorepeat) is sent as repeated key-downs, which is what the Windows hook sees; hotkeys are not matched on repeats. - Modifiers come from
flagsChanged, diffed against the previous device-specific flag word (NX_DEVICELCTLKEYMASK 0x01,LSHIFT 0x02,RSHIFT 0x04,LCMD 0x08,RCMD 0x10,LALT 0x20,RALT 0x40,RCTL 0x2000) into down/up pairs ofVK_LCONTROL 0xA2/RCONTROL 0xA3,LSHIFT 0xA0/RSHIFT 0xA1,LWIN 0x5B/RWIN 0x5C(⌘ = Win, README D4),LMENU 0xA4/RMENU 0xA5(⌥ = Alt). Caps Lock isVK_CAPITAL 0x14as a down+up pair on each toggle ofNX_ALPHASHIFTMASK 0x10000;fnis ignored. KeyMapis a static table inMWBCorekeyed by macOS virtual keycode (thekVK_*numbers written as literals with their names in comments —Carbonmay not be imported there) for a US ANSI layout: letters, digits, F1–F20, arrows, editing keys, keypad, punctuation, volume, Return/Tab/Space/Escape/Delete/ForwardDelete and the eight modifiers. Keys with no VK are passed through to this Mac and counted (EventTap.unmappedKeyCount). The reverse map is whatinput-injectuses.- Mouse encoding (
InputHook.cs:245-260,WM.cs:27-40):dwFlags= theWM_*id; buttons 0/1/2 = L/R/M, buttons 3/4 =WM_XBUTTON*withWheelDelta= 1/2, higher buttons stay local; dragging is a move, as the Windows hook reports it. Moves are absolute 0..65535 against the primary display (Event.cs:112-113) — or, inMoveMouseRelativelymode,mouseEventDeltaX/Ytagged byCoordinates.tagRelative(§4.4). Scroll: the fixed-point line delta × 120 accumulated into a per-axis remainder so trackpad scrolling emits whole 120-unit notches (WM_MOUSEWHEELaxis 1,WM_MOUSEHWHEELaxis 2). The axis-2 sign against Windows' "positive means scroll right" is unverified — a CP1 question (docs/protocol.md §10.4 note 10). - The virtual cursor. While a remote machine is controlled the real pointer
is frozen, so the tap keeps its own position: seeded from the real pointer on
every local move, advanced by
mouseEventDeltaX/Y, clamped toprimary ± 1 pxexactly asInputHook.cs:293-309does. That is what goes on the wire and what edge detection sees. - Hotkeys (
InputHook.cs:539-658,MouseWithoutBordersProperties.cs): switch-machine = ⌃⌥ +HotKeySwitchMachineVK offset by slot (F1..F4 → slots 0..3); lock = ⌘⌃⌥L (twice within 500 ms ⇒ ALL + lock); reconnect = ⌘⌃⌥R; toggle Easy Mouse = ⌘⌃⌥E; switch-to-all = disabled by default; switch-machine is ignored when Shift or ⌘ is also held (InputHook.cs:604-610). Escape set (contracts C2): switch-machine naming the local slot while control is remote, and ⌃⌥⌘Escape, which is checked first so no veto can shadow it. Switch-to-all is the one hotkey that is not always swallowed: its branch inProcessHotKeys(InputHook.cs:518-522) falls through instead of returningfalse, so on Windows a chord that does not itself hold Ctrl+Alt toggles ALL mode and reaches the OS.HotkeyMatch.swallowsreproduces that: true unlessswitchToAllrequires neither ⌃ nor ⌥, in which case the tap queues the action and then handles the key as an ordinary keystroke. app-shell inherits this the moment it exposes a hotkey editor — the shortcut ships empty (MouseWithoutBordersProperties.cs:30) and an empty hotkey never matches (Common.cs:127-129), so nothing reaches it today. Windows' own swallow is narrower still (the fall-through is caught only when the VK also lands in the switch-machine range,:611-620); the ⌃⌥ test is the honest approximation and the residual case is a hotkey editor's problem, not the wire's. - Easy Mouse (
EasyMouseOption.cs,InputHook.cs:467-473): the tap pushes.edgeCandidate(point:now:)on moves only when the mode allows it — always forEnable, while ⌃ / ⇧ is held for those modes, never forDisable— and never while controlling a remote in relative mode (Event.cs:73). The fullscreen rule is the extras lane's. - Screens (
WinAPI.cs:70-80, 115-184):CGGetActiveDisplayList+CGDisplayBounds; primary =CGMainDisplayID(); desktop = union; corner points = every display's four corners, half-open asSensitivePointsis. Refreshed onNSApplication.didChangeScreenParametersNotification;ScreenLayout.edgeConfig(blockCorners:moveRelatively:)hands the Engine a readyEdgeConfig. - Cursor (
Common.cs:1482-1496,InputHook.cs:293-309): while a remote is controlled,CGAssociateMouseAndMouseCursorPosition(false)keeps the real pointer parked (deltas still arrive) andCGDisplayHideCursorhides it; parking = warp to (primary centre-x, y = 4) whenHideMouseis on, else primary centre; on return, show, re-associate, warp to the last local position — in that order, so a queued delta cannot beat the warp.Cursor.parkapplies thedestinationIsRemote || byHideMouseMessagegate itself, so aSwitchAction.parkCursormaps onto it one-to-one (session-matrix Handshakes). - Permissions:
preflight()stays;request()callsCGRequestListenEventAccess()/CGRequestPostEventAccess()and is invoked only from a UI action the user clicks (app-shell); a 5 s health check re-preflights and reports any change (contracts C2). Agents never callrequest(). - Tap loss (contracts C2): on
tapDisabledByTimeout/ByUserInputthe callback re-enables the tap withCGEvent.tapEnableand flips the snapshot to local, forgets the modifier state, then raises.tapLost; the Engine releases keys. - Clocks.
.edgeCandidatetimestamps come fromEventTap.now()(mach_absolute_time). The Engine must use the same function forSwitcher/Edge, or the 100 ms jump debounce compares two clocks.
Handshakes
Consumed
session-matrix:Coordinates(universal/relative encoding, the CG helpers),EdgeConfig,Direction, theSwitchAction.parkCursorconsumer rule.wire-core:MouseDatafor the valuesCapturedInputcarries.
Promised (to input-inject, app-shell, extras)
As shipped 2026-09-16. Later lanes code against this, not against the sketch this section used to hold.
// MWBCore/InputTypes.swift
public enum InputTypes { public static let injectedEventTag: Int64 } // C4
public enum WindowsMessage { // WM.cs:27-40
static let mouseMove, leftDown, leftUp, leftDoubleClick, rightDown, rightUp,
rightDoubleClick, middleDown, middleUp, middleDoubleClick, wheel,
extraDown, extraUp, horizontalWheel: Int32
static let wheelDelta: Int32 // 120
}
public enum KeyFlag { static let extended, injected, altDown, up: Int32 } // WM.cs:47-54
public enum Destination: Sendable, Equatable { case local, remote(UInt32); var isRemote: Bool }
public enum EasyMouseMode: Int, Sendable, Equatable { case disable, enable, ctrl, shift }
public struct ModifierState: Sendable, Equatable { var command, control, option, shift: Bool }
public struct Hotkey: Sendable, Equatable {
var vk: Int32; var command, control, option, shift: Bool
var isEmpty: Bool
func matches(vk: Int32, modifiers: ModifierState) -> Bool
}
public struct HotkeyConfig: Sendable, Equatable {
var switchMachineVK: Int32; var lock, reconnect, toggleEasyMouse, switchToAll: Hotkey
static let switchMachineSlots: Int // 4
static let escape: Hotkey // ⌃⌥⌘Escape, mac-only
}
public enum HotkeyAction: Sendable, Equatable {
case switchToSlot(Int), lockMachine, lockAllMachines, reconnect,
toggleEasyMouse, toggleSwitchToAll, escapedToLocal
}
public enum CapturedInput: Sendable {
case key(vk: Int32, flags: Int32)
case mouse(MouseData)
case edgeCandidate(point: CGPoint, now: TimeInterval)
case hotkey(HotkeyAction)
case tapLost
case overflow
}
public struct RoutingSnapshot: Sendable, Equatable {
var destination: Destination
var swallowKeys, swallowMouse: Bool
var easyMouse: EasyMouseMode
var moveMouseRelatively: Bool
var hotkeys: HotkeyConfig
var localSlot: Int?
func routedLocal() -> RoutingSnapshot
}
// MWBCore/KeyMap.swift
public enum KeyMap {
static let back, `return`, capital, escape, leftWin, rightWin, leftShift, rightShift,
leftControl, rightControl, leftMenu, rightMenu: Int32
static let keypadEnterKeycode: Int64
static func vk(forKeycode: Int64) -> Int32?
static func keycode(forVK: Int32) -> Int64?
static func isExtended(vk: Int32, keycode: Int64) -> Bool
static let leftControlMask, leftShiftMask, rightShiftMask, leftCommandMask,
rightCommandMask, leftOptionMask, rightOptionMask, rightControlMask,
capsLockMask: UInt64 // NX_DEVICE* / NX_ALPHASHIFT
static func modifiers(from flags: UInt64) -> ModifierState
static func forEachModifierTransition(old: UInt64, new: UInt64, _ body: (Int32, Bool) -> Void)
static func modifierTransitions(old: UInt64, new: UInt64) -> [(vk: Int32, down: Bool)]
static func capsLockToggled(old: UInt64, new: UInt64) -> Bool
}
// MWBMac
public final class RoutingState: Sendable {
init(_ snapshot: RoutingSnapshot = .init(), virtualCursor: CGPoint = …)
func read() -> RoutingSnapshot
func write(_ snapshot: RoutingSnapshot)
func update(_ body: @Sendable (inout RoutingSnapshot) -> Void)
@discardableResult func routeLocal() -> Bool
var virtualCursor: CGPoint { get set }
func advanceVirtualCursor(dx: Double, dy: Double, clampedTo primary: CGRect) -> CGPoint
}
public enum CaptureNotice: Sendable { case tapLost, overflow }
public final class CaptureQueue: Sendable {
static let defaultCapacity: Int // 4096
init(capacity: Int = defaultCapacity)
@discardableResult func push(_ input: CapturedInput) -> Bool
func signal(_ notice: CaptureNotice)
func drain() -> [CapturedInput]
var depth: Int { get }
}
public struct CaptureConfig: Sendable, Equatable {
var hotkeys: HotkeyConfig; var easyMouse: EasyMouseMode
var moveMouseRelatively: Bool; var localSlot: Int?
}
public enum EventTapError: Error, Equatable { case creationFailed, runLoopSourceFailed }
public final class EventTap: @unchecked Sendable {
init(routing: RoutingState, queue: CaptureQueue, screens: Screens,
config: CaptureConfig = .init(), onWake: @escaping @Sendable () -> Void)
func start() throws
func stop()
var isRunning: Bool { get }
func reconfigure(_ config: CaptureConfig)
var realInputEventCount: UInt64 { get } // Session.tick takes this
var unmappedKeyCount: UInt64 { get }
static func now() -> TimeInterval // the lane's clock
}
public struct HotkeyMatch: Sendable, Equatable {
var action: HotkeyAction; var routesLocal: Bool; var swallows: Bool
}
public struct HotkeyMatcher: Sendable {
static let lockDoublePressWindow: TimeInterval // 0.5
var config: HotkeyConfig
mutating func match(vk: Int32, modifiers: ModifierState, localSlot: Int?,
destinationIsRemote: Bool, now: TimeInterval) -> HotkeyMatch?
mutating func resetLockTimer()
}
public struct ScreenLayout: Sendable {
var displays: [CGRect]; var primary, desktop: CGRect; var corners: [CGPoint]
static func current() -> ScreenLayout
func edgeConfig(blockCorners: Bool, moveRelatively: Bool) -> EdgeConfig
}
public final class Screens: @unchecked Sendable {
init(onChange: (@Sendable () -> Void)? = nil)
var layout: ScreenLayout { get }
func refresh()
func startObserving() // main thread
func stopObserving() // main thread
}
public final class Cursor: Sendable {
static func parkPosition(hideMouse: Bool, in layout: ScreenLayout) -> CGPoint
@discardableResult func park(hideMouse: Bool, layout: ScreenLayout,
destinationIsRemote: Bool, byHideMouseMessage: Bool) -> CGPoint
@discardableResult func decouple(parkHidden: Bool, layout: ScreenLayout) -> CGPoint
func recouple(to point: CGPoint?)
func warp(to point: CGPoint)
func hide(); func show() // balanced
var isDecoupled: Bool { get }
func restoreEverything() // atexit / signal handler
}
public struct PermissionState: Equatable, Sendable { public init(listen: Bool, post: Bool)
let listen, post: Bool; var isComplete: Bool }
public enum Permissions {
static let healthCheckInterval: TimeInterval // 5
static func preflight() -> PermissionState
@discardableResult static func request() -> PermissionState // user-initiated only
static func startHealthCheck(interval: TimeInterval = healthCheckInterval,
onChange: @escaping @Sendable (PermissionState) -> Void) -> PermissionHealthCheck
}
public final class PermissionHealthCheck: @unchecked Sendable { func cancel() }
Five deviations from the shape sketched at planning time, all deliberate:
isExtendedtakes the keycode as well as the VK. The keypad's Enter and Return shareVK_RETURN, and the extended bit is the only thing that tells them apart (docs/protocol.md §10.4 note 6); avk-only predicate cannot.RoutingSnapshotcarrieseasyMouse,moveMouseRelatively,hotkeysandlocalSlotas well as the routing. The callback needs all of them and there is no second lock;reconfigure(_:)writes that half and leaves the routing half alone.Screens.onChangeis an init parameter, not a settable property, so the class needs no lock around a closure.CapturedInputis notEquatable.CGPointis not, in a Foundation-only target.- The tap owns the two counters
Event.InputEventCount/RealInputEventCountstand for —realInputEventCountis the valueSession.tickwants (docs/protocol.md §10.4 note 8).
Requested of input-inject (open)
Injectormust stampCGEventField.eventSourceUserDatawithInputTypes.injectedEventTagon every event it posts, including the synthetic key-ups ofreleaseAll(). An untagged event is captured and echoed straight back to the peer.InjectorperformsHotkeyAction.lockMachine/.lockAllMachinesby sending the chord — the tap swallowed the keys, so nothing reaches the peer otherwise (InputHook.cs:548-562).
Requested of app-shell (open)
- The Engine must timestamp
Switcher/EdgewithEventTap.now(). - The Engine owns
swallowKeys/swallowMouse: set them false in ALL-machines mode, true for a single remote destination. - On
.tapLost,.overflowand.hotkey(.escapedToLocal)the tap has already routed local; the Engine still owesreleaseAllKeys,Cursor.recoupleand theHideMouse/MachineSwitchedhousekeeping (contracts C2). Screens.startObserving()andstopObserving()must be called on the main thread, afterNSApplication.sharedexists.
Status / TODO
Sources/MWBCore/InputTypes.swift: tag,RoutingSnapshot,CapturedInput,HotkeyConfig,Hotkey,EasyMouseMode(C3, C4).Sources/MWBCore/KeyMap.swift: keycode ↔ VK table, extended set, modifier transitions (VK.cs,WM.cs:47-54,InputHook.cs:371-473).Sources/MWBMac/CaptureQueue.swift: bounded ring, coalescing, overflow policy (C3).Sources/MWBMac/RoutingState.swift: the snapshot lock.Sources/MWBMac/EventTap.swift: the tap on its own run loop, callback per Assumptions, mouse/keyboard/scroll encoding (InputHook.cs:110-133, 213-368), tap-loss handling (C2).Sources/MWBMac/Hotkeys.swift: matching, double-press lock rule, the ignore-with-Shift/⌘ rule, escape set (InputHook.cs:539-658).Sources/MWBMac/Screens.swift,Cursor.swift: layout, corners, change notification; decouple/park/recouple (WinAPI.cs:70-184,Common.cs:1482-1496,InputHook.cs:293-309).Sources/MWBMac/Permissions.swift: addrequest()and the health check.docs/protocol.md: append §10.4 with anything learned, cited.- Not done, deliberately: the
SwitchLocation.Countmechanic (InputHook.cs:268-284). See the work log. - Not done, deliberately: Ctrl+Alt+Delete as a switch-to-local trigger
(
InputHook.cs:427-448). See the work log. - Not done, deliberately:
HotKeyExitMM(InputHook.cs:588-603), disabled by default on Windows and not in TODO §4.
Work log
2026-09-16 — dev (Opus), the whole lane
Nine files: two in MWBCore (InputTypes.swift, KeyMap.swift), seven in
MWBMac (RoutingState.swift, CaptureQueue.swift, Screens.swift,
Cursor.swift, Hotkeys.swift, EventTap.swift, Permissions.swift).
tools/gates.sh green; nothing in this lane was run, by instruction — no
event tap was created, no CGEvent posted, no cursor warped, no permission
requested. The user tests.
Decisions, in the order they were made:
- Config lives in the routing snapshot. The callback needs
easyMouse,moveMouseRelatively,hotkeysandlocalSloton every event, and a second lock for them would double the per-event cost for no gain.reconfigure(_:)writes only those fields, so a settings change cannot race a switch. - The virtual cursor is explicit. Windows gets it for free: its hook sees
the real pointer, which the OS keeps moving, and it clamps a copy
(
InputHook.cs:287-309). On macOS the pointer is frozen byCGAssociateMouseAndMouseCursorPosition(false), so the same clamped position is kept inRoutingStateand advanced frommouseEventDeltaX/Y. It is seeded on every local mouse move from the real pointer, which means the Engine does not have to seed it at a switch. SwitchLocation.Countis not ported. On Windows the first couple of mouse events after a switch have their coordinates replaced by the landing point (InputHook.cs:268-284). Because the virtual cursor is ours, the same effect is reached by the Engine writingRoutingState.virtualCursorto the landing point when it appliesSwitchAction.moveCursor, and the next move packet then carries landing + delta rather than landing exactly. One packet differs by one mouse delta; nothing else does. The counter, its reset and theEvent.cs:97suppression all disappear with it.- Easy Mouse is read from the live modifier state, not from the
"last key event was a Ctrl/Shift down" latch of
InputHook.cs:375, 467-473. Windows clears the latch on any key-up, so on Windows typing while holding Ctrl in Ctrl mode silently disables edge switching until Ctrl is released and pressed again. Readingmodifiers.controlis simpler and strictly better; the wire is unaffected. - Hotkeys are not matched on auto-repeat. Windows matches every repeated
WM_KEYDOWN, so holding ⌘⌃⌥L there reads as the 500 ms double press (InputHook.cs:544) and locks every machine. Skipping repeats costs nothing and removes an accident. - Overflow always routes local, transition or not. contracts C3 only demands it for transitions, but a ring that cannot take a coalesced motion event means the Engine has stopped draining entirely, and the safe state for a Mac whose Engine is stuck is to have its own keyboard back (invariant 3).
- Ctrl+Alt+Delete is not special. On Windows it is a switch-to-local
trigger (
InputHook.cs:427-448) because the secure attention sequence is about to take the desktop away. macOS has no equivalent; ⌃⌥⌘Escape is the mac escape, and it is checked before every veto so nothing can shadow it. Cursor.parkapplies the gate itself. The session-matrix Handshakes require thedestinationIsRemote || byHideMouseMessagetest (Common.cs:1488) before the pointer moves, and pushing it into the one function that moves the pointer means no consumer can forget it.parkreturns the position either way, because Windows recordsLastPosunconditionally.- A relative move is coalesced by summing. The first version replaced the
older entry, which is right for an absolute position and loses motion for a
MOVE_MOUSE_RELATIVEdelta. Fixed in the same lane. - Coalescing looks back two entries. The first version matched only the
last one, and in remote mode every physical move queues a
.mousefollowed by an.edgeCandidate, so the kinds alternate and nothing ever merged — the ring would have filled at two entries per move under a stalled Engine, which is precisely the case coalescing exists to survive. The scan stops at the first non-motion entry, so a button or key transition is never reordered past.
Deviations from the brief: the brief listed the device masks 0x01..0x40 and
omitted NX_DEVICERCTLKEYMASK 0x2000, without which the right Control key
never produces a transition; it is in KeyMap and in §10.4 note 10. The brief
also asked for isExtended(vk:); it takes the keycode too, for the reason in
Handshakes.
Unverified, for CP1: the sign of scrollWheelEventFixedPtDeltaAxis2 against
Windows' WM_MOUSEHWHEEL (§10.4 note 10), and the kVK_Help → VK_INSERT
and kVK_ANSI_KeypadClear → VK_NUMLOCK choices, which map by physical
position rather than by label.
2026-09-16 — dev (Opus), rework after the QA verdict
Four commits, one per finding, build-only verification again: no tap was
created, no CGEvent posted, no cursor moved, no permission requested or
preflighted. xcrun swift-format format -i --recursive Sources Package.swift
then tools/guard.sh -m 8 -t 900 -- tools/gates.sh — green on each commit.
EventTap.threadis now locked.runLoopLockis renamedstateLockand guardsrunLoopStorageandthread, so the class comment's claim that every cross-thread field is behind a lock is true andstop()really is callable from any thread — including the contracts-C2 signal-handler path.start()'s check-and-claim is one critical section rather than a plain read of avar, so two concurrent starts cannot both install a tap; the failure path clears the field under the same lock. Nothing else moved:machPort, the modifier bookkeeping and the wheel remainders are still tap-thread-only.handleMousereadsscreens.layoutonly when the destination is remote. The read moved inside theisRemotebranch — the only code that uses it — so the local branch, which is what runs for every mouse event on a Mac that is not controlling a peer, no longer pays for a discarded lock acquisition (invariant 4). This is the shapehandleScrollalready had.- The lock claim is now counted, not asserted. The old "three
acquisitions at most (snapshot, virtual cursor, counters)" named two of the
four reachable lock objects and undercounted every path. Replaced by a
bullet listing all four (
EventTap.counters,RoutingState's box,Screens' layout,CaptureQueue's ring) and the per-event count on each path: local key 2, local move 3 (4 with an edge candidate), remote key 3, remote move 6 (5 when the candidate is suppressed) — with the extras (unmapped key, matched hotkey, escape, one push per modifier transition) spelled out. The counts are post-fix-2; the remote-move worst case is unchanged because that path did need the layout. - Switch-to-all is no longer unconditionally swallowed.
ProcessHotKeys(InputHook.cs:518-522) is the one branch that does not returnfalseon a match, so the key reaches the OS unless the chord itself holds Ctrl+Alt and theif (CtrlDown && altDown)block below catches it.HotkeyMatchgainsswallows; theswitchToAllbranch sets it fromcontrol && option, andhandleKeyqueues the action and then falls through to ordinary key encoding when it is false — which mirrorsProcessHotKeysreturningtrueand leaving the key toKeyboardEventplusCallNextHookEx. Written up in docs/protocol.md §4.5 and in the Hotkeys assumption, together with the one narrowing that remains: Windows' actual swallow additionally requires the VK to sit in the switch-machine range (:611-620), which the ⌃⌥ test approximates. Nothing reaches this today —Switch2AllPCShortcutships empty (MouseWithoutBordersProperties.cs:30) and an empty hotkey never matches (Common.cs:127-129) — so it is app-shell's hotkey editor that inherits it.
HotkeyMatch gained a field, so the Handshakes block was updated with it. No
other promised signature changed; no other lane's files were touched.
QA log
2026-09-16 — QA (Sonnet)
tools/guard.sh -m 8 -t 600 -- tools/gates.sh green (swift-format lint
--strict, MWBCore layering, swift build -Xswiftc -warnings-as-errors). No
event tap was created, no CGEvent posted, no cursor warped, no permission
requested or preflighted — build/read-only per instruction.
Checked every Status/TODO tick against its Windows source
(Class/InputHook.cs whole file, Core/Event.cs, Core/VK.cs, Core/WM.cs,
Core/WinAPI.cs:70-184, Core/Common.cs:1482-1496,
Class/EasyMouseOption.cs, MouseWithoutBordersProperties.cs) and against
docs/protocol.md §4.3–§4.5, §5, §10.4 and docs/contracts.md C2–C4:
- Spot-checked 30+
KeyMapentries againstVK.csand the standard Win32 VK list (letters, digits, punctuation/OEM keys, F1–F20, keypad, volume, all eight modifiers, Insert/Delete/Help, Num Lock) — all correct, including the ones VK.cs itself doesn't define (OEM_4/5/6/7/102, F13–F20, volume), which are real Win32 constants InputSimulation.cs would still accept. - Hotkey defaults (
HotkeyConfig.init) cross-checked againstMouseWithoutBordersProperties.cs:33-39,188,192andHotkeySettings(win,ctrl,alt,shift,code)atHotkeySettings.cs:51-59— Win+Ctrl+Alt (no Shift) for lock/reconnect/toggle-EasyMouse,0x70for switch-machine, Switch2AllPC disabled — all match. - Modifier device masks,
rightControlMask 0x2000, Caps Lock toggle, wheel×120 accumulation and sign, absolute-move formula (Event.cs:112-113), Easy Mouse gating (Event.cs:71-79,InputHook.cs:467-473), the Shift/⌘ veto scoped to the switch-machine family only (InputHook.cs:604-610vsCommon.HotkeyMatched,Common.cs:127-129), the 500 ms double-press lock rule,Cursor.park'sHideMouseCursorgate (Common.cs:1482-1496,1488), andScreens' corner half-open convention vsMonitorEnumProc(WinAPI.cs:70-113) — all reproduce the cited Windows behaviour. Nothing in the nine files logs a keystroke, a VK, or a modifier state.
Four findings, none of them wire/protocol breaks — all host-side Mac code-quality issues, listed most to least severe:
EventTap.threadis unguarded shared state, and the class's own safety comment says otherwise.EventTap.swift:82declaresprivate var thread: Thread?, read at:112and written at:118, :122(both instart()) and:133(instop()) — none of it behind a lock.stop()is documented "Safe to call from any thread" (:127), which is exactly the shape of the contracts-C2 crash/signal-handler recovery row ("best effort: re-associate the cursor and release keys" — the handler would callEventTap.stop()/Cursor.restoreEverything()off the tap thread), and the class-level comment at:60-67asserts "every field that crosses a thread boundary is behind a lock" — true ofrunLoopStorage(guarded byrunLoopLock) but not ofthread, which sits right next to it and isn't. Astart()racing a signal-handlerstop()is a genuine, if narrow, data race on a plainvar, not proven safe by anything in this file. Fix: foldthreadintorunLoopLock(or its own lock) the same wayrunLoopStoragealready is.screens.layoutis fetched unconditionally on the single hottest path through the callback, for a value the majority case never reads.EventTap.swift:346callsscreens.layout(a locked read ofScreens'OSAllocatedUnfairLock<ScreenLayout>) before branching onsnapshot.destination.isRemote;layoutis only actually used inside thatisRemotebranch (:352-353). Theelse(local) branch (:361-367) — which is what runs for essentially every mouse move on a Mac that isn't currently controlling a peer, i.e. most of the time this tap is live — never toucheslayout, so it pays for a lock acquisition it throws away.handleScrollgets this right: it checkssnapshot.destination.isRemoteat:438before readingscreens.layoutat:441. Move thehandleMouseread inside theisRemotebranch to match.- The README's per-event lock-count claim doesn't match the code.
docs/features/input-capture/README.md:40says "Three uncontendedOSAllocatedUnfairLockacquisitions per event at most (snapshot, virtual cursor, counters)." A remote mouse-move event actually acquires:counters(1),RoutingState's box lock twice (routing.read()+routing.advanceVirtualCursor),Screens' lock (finding 2), andCaptureQueue's ring lock once or twice (.mouseand, on a move,.edgeCandidateare two separateenqueue()calls) — up to 6 acquisitions across 4 distinct lock objects, two of which (Screens,CaptureQueue) the claim never mentions at all. Not a functional bug (all four locks are uncontended, per-process, non-blocking), but it's a concrete, checkable claim in a feature README that CLAUDE.md's own perf rule ("Budget is measured, not asserted") says should be either accurate or removed. - A Windows quirk this port doesn't reproduce, reachable only with a
non-default
Switch2AllPCShortcut.InputHook.ProcessHotKeys(InputHook.cs:518-522) never returnsfalsefor a matchedHotKeySwitch2AllPC, unlike every other hotkey branch — so on Windows, if that hotkey is configured to something that doesn't also require Ctrl+Alt, the key reaches the OS (CallNextHookEx) in addition to toggling ALL-machines mode.HotkeyMatcher.match(Hotkeys.swift:65-67) andEventTap.handleKey(EventTap.swift:280-284) always swallow a matched hotkey. Unreachable today —Switch2AllPCShortcutships disabled (Code=0,MouseWithoutBordersProperties.cs:30) andCommon.HotkeyMatchedrequires!hotkey.IsEmpty()(Common.cs:127-129) — so this only matters once app-shell exposes a hotkey editor and a user picks a non-default, non-Ctrl+Alt combo for it. Worth a one-line note in the Assumptions section so app-shell doesn't have to rediscover it.
No typos or trivially-wrong comments found to fix directly; all four findings need an actual code or prose change, so none were applied here.
Verdict: REWORK
Review
- 2026-09-16 (lead): inspected per
docs/loop.md§5 after one rework round. Gates green run by me; nine files in the brief's list plus TODO §4, protocol §10.4 and this README. Read the tap callback in full: injected tag passes through first, tap-loss re-enables and routes local before anything else, hotkeys matched on press only, escape flips routing inside the callback, unmapped keys stay local and are counted,swallowKeys/swallowMousedecide the return. QA spot-checked 30+ VK values and the encodings. Verdict: merge. Carry into input-inject: tag every posted event via the source'suserData, includingreleaseAll()key-ups; perform the lock hotkeys by chord;isExtended(vk:keycode:)exists because keypad Enter sharesVK_RETURN. Carry into app-shell: the open requests in this README (EventTap.now()timestamps, ownership of the swallow flags,releaseAll+Cursor.recoupleafter.tapLost/.overflow/.escapedToLocal,Screens.startObserving()on the main thread). Unverified until CP1: horizontal wheel sign,kVK_Help→VK_INSERT,KeypadClear→VK_NUMLOCK(protocol §10.4 note 10).