§10.4 records ten things the lane established from the Windows source (one-sided hotkey matching, the three meanings of Md.WheelDelta, the virtual cursor and its primary+-1 clamp, the unconditional relative bias, SwitchLocation, synthesised LLKHF bits, the eleven ReleaseAllKeys VKs, the two input counters, monitor enumeration) plus the macOS device masks. The README's Assumptions and Handshakes now describe what shipped, with the nine decisions and three deliberate non-ports in the work log. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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. Three uncontendedOSAllocatedUnfairLockacquisitions per event at most (snapshot, virtual cursor, counters) and no allocation (invariant 4). - 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 when the previous entry is also motion — 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. - 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 }
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 { 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.
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.