Files

551 lines
31 KiB
Markdown

# input-inject
## Goal
The Mac's side of `InputSimulation.cs`: turn trusted `Keyboard` and
`Mouse` packets into `CGEvent`s posted to the HID event tap, tagged so
our own `EventTap` passes them through, with the click-count, held-key
and cursor-bounds bookkeeping macOS needs and Windows gets for free from
`SendInput`. Also the local reactions to remote chords
(`InputSimulation.cs:358-475`): Win+L locks this Mac, Ctrl+Alt+Del is
ignored, and `releaseAll()` — the `ReleaseAllKeys` of
`InitAndCleanup.cs:214-243` — that contracts C2 calls on every recovery.
## Assumptions
Written before the work; **amended 2026-09-16** where the code shipped
differently. Each amendment is marked *(amended)* and explained in the
work log.
- **One `CGEventSource(stateID: .hidSystemState)` per `Injector`, with
`userData = InputTypes.injectedEventTag`** so every event it creates
carries the tag in `eventSourceUserData` and the tap's `RealData`
check (`InputHook.cs:213-220`) passes it through. Events are posted
with `.post(tap: .cghidEventTap)`, the closest thing to `SendInput`.
- **Keyboard** (`InputSimulation.cs:108-157`): `wVk` →
`KeyMap.keycode(forVK:)`; unknown VKs are dropped and counted (Windows
would `MapVirtualKey` them; we have no keycode to post). `LLKHF.UP`
→ key up. Modifier VKs (`LSHIFT`…`RWIN`, `SHIFT`/`CONTROL`/`MENU`
generic forms mapped to the left key) post as key events for the
modifier keycode, ***(amended)*** **re-typed to `.flagsChanged` before
posting** — macOS does not do that conversion for us, and a `keyDown`
for keycode 56 is not how anything learns that Shift is down
(docs/protocol.md §10.5 note 7). The injector keeps a `KeyState` of
held modifiers and sets `event.flags` on **every** posted key and mouse
event from it, otherwise ⌘C from a Windows keyboard arrives as a bare
C. ***(amended)*** `EXTENDED` is **not** informational: `VK_RETURN`
with the bit set is the keypad's Enter, which is the one key the table
cannot distinguish (`KeyMap.keycode(forVK:)` gives back the main
Return). Repeats arrive as repeated downs and are posted as such with
`keyboardEventAutorepeat = 1` after the first. The 10 ms sleep after
key-up (`Event.cs:268-271`) is the sender's, not ours — and is dead
code there too (docs/protocol.md §10.5 note 1).
- **Caps Lock**: `VK_CAPITAL` down+up toggles; post the keycode pair
and let the system toggle the LED state. ***(amended)*** The pair is
posted as `.flagsChanged` like the other modifiers, and the injector
also tracks the lock itself so `kCGEventFlagMaskAlphaShift` is set on
the events it posts whether or not the hardware state followed.
- **Mouse** (`InputSimulation.cs:160-219`): `dwFlags` is a `WM_*` id.
`WM_MOUSEMOVE` with absolute coordinates → ***(amended)***
`Coordinates.absoluteMove(…)` onto the desktop and then
`fromUniversal` over the **primary** bounds, because
`MOUSEEVENTF_ABSOLUTE` is 0..65535 over the primary monitor and that
second scaling is what `SendMouse` (`:165-173`) is undoing
(docs/protocol.md §10.5 note 5); with the relative bias →
delta applied to the current pointer (`Receiver.cs:147-153`); the
result is clamped to the desktop union. ***(amended)*** Buttons and
wheels are posted at the **current pointer**, never at the packet's
coordinates, because Windows discards those (§10.5 note 4). A move
while a button is held
posts the matching `*MouseDragged` type (macOS needs it for drags;
Windows does not distinguish). Buttons: L/R/M down/up → the CG button
types with `mouseEventButtonNumber` 0/1/2; `WM_XBUTTON*` with
`WheelDelta` 1/2 → `.otherMouseDown/Up` with button number 3/4.
Windows drops `*DBLCLK` (no `MOUSEEVENTF` case); double clicks arrive
as two downs, so **click count is ours**: consecutive downs of the
same button within `NSEvent.doubleClickInterval` and 4 px set
`mouseEventClickState` 2, 3…, reset otherwise.
- **Wheel**: `WM_MOUSEWHEEL` → `CGEvent(scrollWheelEvent2Source:units:
.line, wheelCount: 1, wheel1: WheelDelta / 120)`; `WM_MOUSEHWHEEL` →
`wheelCount: 2, wheel2:`. ***(amended)*** The division keeps a
remainder per axis: a high-resolution wheel sends fractions of a notch
and integer division alone would drop a slow scroll entirely. Sign:
Windows +120 is away from the user,
which is CG line +1. The user's "natural scrolling" preference is
applied by the system to posted events too; whether that matches what
they expect from a remote mouse is a CP1 question, recorded in §10.5.
- **Remote chords** (`InputSimulation.cs:358-475`): the injector tracks
the remote's Win/Ctrl/Alt/Shift from the VKs it receives; Win+L
(`VK_L` with Win held) locks this Mac by running
`/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession -suspend`
rather than injecting the chord (which would open Spotlight-like
shortcuts); Ctrl+Alt+Del is swallowed and logged; Ctrl+Alt+End
(service start) is ignored (README D6). ***(amended)*** A fourth chord
belongs here: the **receiver's own `HotKeyLockMachine`**
(`:406-416`), matched against the remote's modifiers and against
*this* Mac's setting, which is how the lock hotkey actually reaches a
peer (§10.5 note 2). `InjectorConfig.lockMachine` carries it.
Ctrl+Alt+End is not eaten by Windows, so the key still posts here.
***(amended)*** The chord booleans and the lock-hotkey test are fed the
**raw** VK off the wire, never `KeyState.normalise(vk:)`'s output:
`InputProcessKeyEx`'s two switches are side-specific only
(`InputSimulation.cs:372-403` up, `:418-438` down) and `HotkeyMatched`
(`:406`) gets the raw `vkCode`, so a side-less `VK_SHIFT`/`VK_CONTROL`/
`VK_MENU` — which the lock-chord replay sends — moves nothing
(docs/protocol.md §10.5 note 3). `normalise(vk:)` is the posting path alone.
- **Windows' desktop gate on the lock hotkey is considered and
inapplicable, so the hotkey is always eaten and always locks.**
`InputSimulation.cs:408-409` skips the `HotKeyLockMachine` branch when
`Common.RunOnLogonDesktop` or `Common.RunOnScrSaverDesktop` is set.
Those flags are set only where the MWB **service** launches a second
copy of the process onto the `Winlogon` or `Screen-saver` secure
desktop (`Program.cs:150-167`, `Common.cs:176-186`). macOS has no
secure-desktop session split — one process per login session, no copy
of us running behind `loginwindow` or the screen saver, and a
user-space `CGEventTap` neither receives nor posts once the screen is
locked — and the Windows service is out of scope anyway (README D6).
`KeyState.processDown` therefore has no guard: a decision, not an
omission. Recorded as docs/protocol.md §10.5 note 8. (The hardcoded Win+L
branch `:450-460` is ungated on Windows too, so it was never in
question.)
- **`releaseAll()`** posts key-up for every key and button the injector
believes is down — a superset of Windows' fixed modifier list
(`InitAndCleanup.cs:214-243`) because a lost key-up for a letter is as
bad as for Shift — then clears `KeyState`. Rate limit of once per 2 s
(`:218`) is **not** ported: recovery must always work (C2).
***(amended)*** Ordinary keys are released before modifiers, so a
release cannot spell a shortcut on the way out, and the chord booleans
are cleared afterwards (`ResetSystemKeyFlags`, `:477-480`) — Windows
leaves them, but we have just released the keys they describe.
- **Threading**: the injector is driven by the Engine actor and posts
from its own serial `DispatchQueue`; posting is thread-safe but the
bookkeeping is not, so all of it lives on that queue. ***(amended)***
The class is `@unchecked Sendable` (justified in the file header)
rather than non-`Sendable`: `releaseAll()` has to be callable from the
quit and signal handlers (C2, last row), which cannot hop onto an
actor. `inject` is `async` onto the queue; the accessors and
`releaseAll` are `queue.sync`.
- **Cursor bounds** come from `ScreenLayout` passed in with each
packet; the injector never calls `Screens` itself.
## Handshakes
### Consumed
- `input-capture`: `InputTypes.injectedEventTag`, `WindowsMessage`,
`KeyFlag`, `KeyMap.keycode(forVK:)`, `KeyMap` modifier VKs and device
masks, `KeyMap.keypadEnterKeycode`, `Hotkey`/`HotkeyConfig`,
`ModifierState`, `ScreenLayout`, `EventTap.now()` (the lane's
monotonic clock), and the promise that tagged events are passed
through untouched.
- `session-matrix`: `Coordinates.absoluteMove`, `Coordinates.fromUniversal`,
`Coordinates.isRelative` / `untagRelative`, `Coordinates.centre`.
- `wire-core`: `Packet.type`, `Packet.mouse`, `Packet.keyboard`,
`MouseData`, `KeyboardData`.
### Promised (to app-shell)
As shipped 2026-09-16. Two public types in `MWBMac`, both in the lane's
own files; nothing else in the target changed.
```swift
// MWBMac/Injector.swift
public struct InjectorConfig: Sendable, Equatable {
public var lockMachine: Hotkey // HotKeyLockMachine, matched on receive
public init(lockMachine: Hotkey = HotkeyConfig().lock)
}
public final class Injector: @unchecked Sendable {
public static let cgSessionPath: String
public init(config: InjectorConfig = InjectorConfig())
public func reconfigure(_ config: InjectorConfig)
public func inject(_ packet: Packet, layout: ScreenLayout) // .keyboard / .mouse; else ignored
public func releaseAll() // C2; any thread, blocks until posted
public func lockThisMac() // CGSession -suspend
public static func lockChord(for hotkey: Hotkey) -> [KeyboardData] // downs then ups
public var canInject: Bool { get } // false ⇒ no CGEventSource, all injection is a no-op
public var droppedUnmappedKeys: UInt64 { get }
public var remoteModifiers: ModifierState { get }
public var isHoldingAnything: Bool { get }
}
// MWBMac/KeyState.swift
public struct KeyDecision: Sendable, Equatable { // InputProcessKeyEx's verdict
public var eatKey, releaseAllKeys, lockMachine: Bool
public static let inject: KeyDecision
}
public struct KeyState: Sendable {
public static let end, delete, letterL, shift, control, menu: Int32 // VK.cs
public static let modifierVKs: Set<Int32>
public static func reportsAsFlagsChanged(vk: Int32) -> Bool
public static func normalise(vk: Int32) -> Int32 // side-less VK → left key
public static func positionalFlags(forKeycode: Int64) -> UInt64
public static let shiftMask, controlMask, optionMask, commandMask,
numericPadMask, secondaryFnMask: UInt64
public init()
public private(set) var chord: ModifierState // the *remote* keyboard's modifiers
public private(set) var heldKeys: Set<Int32>
public private(set) var heldButtons: [Int64: Int64] // button → click count
public private(set) var capsLockOn: Bool
public mutating func process(vk: Int32, isUp: Bool, lockMachine: Hotkey) -> KeyDecision
public mutating func resetChord(keeping: Hotkey); public mutating func resetChord()
public func isHeld(_ vk: Int32) -> Bool
public mutating func note(vk: Int32, down: Bool)
public func releaseOrder() -> [Int32] // ordinary keys, then modifiers
public mutating func buttonDown(_ number: Int64, clickState: Int64)
public mutating func buttonUp(_ number: Int64) -> Int64
public var draggingButton: Int64? { get }
public func buttonReleaseOrder() -> [(number: Int64, clickState: Int64)]
public var eventFlags: UInt64 { get }
}
public struct ClickTracker: Sendable {
public static let movementTolerance: CGFloat // 4
public var interval: TimeInterval // NSEvent.doubleClickInterval
public init(interval: TimeInterval)
public mutating func click(button: Int64, at: CGPoint, now: TimeInterval) -> Int64
public mutating func reset()
}
```
Four deviations from the shape sketched at planning time, all deliberate:
- **`Injector` takes an `InjectorConfig`.** The receiver matches the
lock hotkey itself (§10.5 note 2), so it needs that one setting; C4
says a lane before app-shell takes a config struct rather than
`Settings`.
- **`Injector` is `@unchecked Sendable`**, so the quit and signal
handlers of C2 can call `releaseAll()`.
- **`KeyState` and `ClickTracker` are public.** They are the injector's
state, but the Engine will want `remoteModifiers` and the menu bar
`isHoldingAnything`, and a value type with no I/O is easier to reason
about public than hidden.
- **`Injector.lockChord(for:)` is a static encoder, not a send.** See the
request below.
### Answering input-capture's open requests
1. *Every posted event carries `InputTypes.injectedEventTag`.* Done: the
tag is on the single `CGEventSource` the injector owns, so every
event it creates carries it, `releaseAll()`'s synthetic ups included.
There is no code path that posts an event from another source.
2. *`Injector` performs `.lockMachine` / `.lockAllMachines` by sending
the chord.* **Partly declined, redirected to app-shell.** The
injector has no peer connections and C1 says only the Engine stamps
and distributes packets, so sending from here would be a contract
violation. What ships instead is `Injector.lockChord(for:)`, the
encoding half — Windows' `GetVkCodesList` order, downs then ups
(`InputHook.cs:485-512, 548-562`) — which the Engine forwards, plus
`lockThisMac()` for the local half.
### Requested of app-shell (open)
1. On `HotkeyAction.lockMachine`, forward `Injector.lockChord(for:
settings.lockMachineShortcut)` to the machine in control. On
`.lockAllMachines`, switch to ALL mode, forward the same chord,
switch back, then call `Injector.lockThisMac()`
(`InputHook.cs:544-566`).
2. Call `injector.releaseAll()` on every C2 recovery row, and on every
switch, mode change and lock — it is the `ReleaseAllKeys` those rows
name.
3. Hand `ScreenLayout` in on every `inject(_:layout:)` from
`Screens.layout`; the injector never reads the displays itself.
4. Map `Settings.HotKeyLockMachine` onto `InjectorConfig.lockMachine`
and call `reconfigure(_:)` when it changes, or a remote lock chord
will be matched against the default ⌘⌃⌥L.
5. `canInject == false` means the process has no `CGEventSource`; show
it next to the permissions state.
## Status / TODO
- [x] `Sources/MWBMac/KeyState.swift`: held keys/buttons, modifier flag
word, click-count tracking, remote-chord state
(`InputSimulation.cs:358-475`, `InitAndCleanup.cs:214-243`).
- [x] `Sources/MWBMac/Injector.swift`: the tagged source, keyboard and
mouse posting per Assumptions, wheel, clamping, `releaseAll`,
`lockThisMac`, Ctrl+Alt+Del handling (`InputSimulation.cs:82-219,
440-475`, `Receiver.cs:147-153`).
- [x] `docs/protocol.md`: append §10.5 with anything learned, cited.
## Work log
### 2026-09-16 — dev (lane `input-inject`, from 3c51e95)
Shipped `Sources/MWBMac/KeyState.swift` (362 lines) and
`Sources/MWBMac/Injector.swift` (425 lines); no other source file
touched. `tools/gates.sh` green. Nothing was run that posts a `CGEvent`,
locks the screen or moves the cursor (CLAUDE.md invariant 5) — this lane
was verified by building and by reading the Windows source, not by
injecting.
**What was ported.**
- `InputSimulation.SendKey` (`:108-157`) → `Injector.injectKey` /
`postKey`: `LLKHF.UP` → key up, `LLKHF.EXTENDED` used to pick the
keypad's Enter over Return, `MapVirtualKey` dropped (macOS needs no
scan code), unknown VKs counted rather than posted.
- `InputSimulation.InputProcessKeyEx` (`:372-480`) → `KeyState.process`:
the four intercepted chords, the side-specific modifier booleans,
`ResetModifiersState`, `ResetSystemKeyFlags`.
- `InputSimulation.SendMouse` (`:160-233`) and `MoveMouseRelative`
(`:283-301`) → `Injector.injectMouse` and the `WM_*` switch, with the
receive-side coordinate rules of `Receiver.cs:147-153`.
- `InitAndCleanup.ReleaseAllKeys` (`:214-243`) → `Injector.releaseAll`.
- `InputHook.GetVkCodesList` (`:485-512`) → `Injector.lockChord(for:)`.
**Decisions and deviations** (the amended Assumptions above say where;
the reasoning here).
1. **Modifiers post as `.flagsChanged`, not as key presses.** The
Assumptions said macOS "delivers" a modifier keycode as
`flagsChanged`; it does not — that conversion has to be made by the
poster. A `keyDown` for keycode 56 leaves every app believing Shift
is up. The event is built with `CGEvent(keyboardEventSource:…)` and
its `type` set to `.flagsChanged`; the flag word is still put on every
other posted event, because injected input gets no global modifier
state on macOS. Recorded as §10.5 note 7.
2. **Absolute moves go through `Coordinates.absoluteMove` *and*
`fromUniversal` over the primary bounds**, not `fromUniversal` over
the desktop as the Assumptions said. `MOUSEEVENTF_ABSOLUTE` is
0..65535 over the primary monitor, which is the whole reason
`SendMouse` rescales the desktop into primary units; skipping the
second step would have produced the right answer only when the
desktop and the primary monitor are the same rectangle. §10.5 note 5.
3. **Buttons and wheels are posted at the current pointer.** Windows
computes a position for them and `SendInput` throws it away
(§10.5 note 4); on macOS the location on a button event is load
bearing, and the current pointer is the position the preceding move
packet already put it at. This also makes the relative-mode path fall
out for free — it is exactly what `Receiver.cs:149-151` does by hand.
4. **`KeyState` keeps the chord booleans and the held-key set apart.**
Folding them together looked tempting and is a bug: the lock hotkey
runs `ResetModifiersState`, which would then delete keys from the
release list while they are still physically down, and a modifier
that is never released is exactly the failure invariant 3 forbids.
Windows keeps them apart too — chord booleans vs `GetAsyncKeyState`.
5. **`releaseAll()` releases ordinary keys before modifiers** and then
clears the chord. Windows releases only its eleven modifier VKs and
leaves the booleans; ours has to cover letters too because we, not
the OS, are the only record of what we posted.
6. **The 10 ms post-key-up sleep is not ported, and the TODO line that
asked for it "only if needed" is answered no.** It is the sender's,
and it is dead code on Windows as well: the condition compares
`LLKHF` bits against `WM_KEYUP`. §10.5 note 1.
7. **Click counting and `NSEvent.doubleClickInterval`** are as the
Assumptions describe; the clock is `EventTap.now()` (monotonic) so an
NTP step cannot manufacture a double click. The click count is
remembered per button so the *up* repeats it, which AppKit requires.
8. **Positional flags** (`NumericPad`, `SecondaryFn`) are synthesised
from the keycode for the keypad, the arrows, the navigation block and
the function keys — real macOS events carry them and some text views
read them. Windows has no equivalent; this is the mirror image of
input-capture synthesising `LLKHF_EXTENDED` (§10.4 note 6).
9. **Wheel deltas keep a per-axis remainder**, mirroring what
`EventTap` does in the other direction, so a high-resolution wheel's
sub-notch deltas are accumulated rather than truncated to nothing.
10. **Two CP1 questions recorded, not decided**: remote ⌘L locks this Mac
(faithful to Win+L with D4's Win=⌘, but ⌘L is a common Mac shortcut),
and whether "natural scrolling" should apply to a remote wheel.
**Open handshake requests** are in Handshakes above: five to app-shell,
and input-capture's request 2 partly declined with a redirect (the
injector encodes the lock chord, the Engine sends it).
### 2026-09-16 — dev, rework after QA (lane `input-inject`, from 22b077b)
Both QA findings addressed, one commit each; `tools/gates.sh` green
after each. Nothing was run that posts a `CGEvent`, locks the screen or
moves the cursor (CLAUDE.md invariant 5) — build-only verification
again. No public name changed, so the Handshakes block above still
describes what ships.
**Finding 1 — normalise-before-chord-match. Accepted, fixed.** The QA
reading is right and the lane's own §10.4 note 3 / §10.5 note 3 already
said so: `InputProcessKeyEx` matches side-specific VKs only, in both
switches (`App/Class/InputSimulation.cs:372-403` for the `LLKHF.UP`
half — `VK.LWIN/RWIN`, `VK.LCONTROL/RCONTROL`, `VK.LMENU/RMENU`,
`VK.LSHIFT/RSHIFT` — and `:418-438` for the down half, same labels), and
`Common.HotkeyMatched` (`:406`) is handed the raw `vkCode`. The side-less
`VK_SHIFT 0x10` / `VK_CONTROL 0x11` / `VK_MENU 0x12` that
`GetVkCodesList` (`App/Class/InputHook.cs:485-512`) puts on the wire
therefore fall through `default` and never move `shiftDown`/`ctrlDown`/
`altDown` on Windows, whereas our `normalise`-first ordering was setting
`chord.control`/`chord.option` from them — so a replayed lock chord
locked a Mac peer for any `HotKeyLockMachine` requiring Ctrl or Alt while
the Windows peer beside it ignored the same bytes (invariant 1).
`Injector.injectKey` (`Sources/MWBMac/Injector.swift`) now passes
`data.virtualKey` unchanged to `state.process(vk:isUp:lockMachine:)` and
calls `KeyState.normalise(vk:)` only afterwards, for
`keycode(for:flags:)`, `postKey` and `state.note` — the posting path,
which is where "macOS has no keycode meaning either Shift" actually
applies. `heldKeys` and therefore `eventFlags` and `releaseOrder()` are
unchanged: they still hold normalised side-specific VKs, so a side-less
key-up off the wire still releases the left modifier we posted. The
contract is now stated at both ends — on `KeyState.process` (raw VK
required, with the `:372-403` / `:418-438` citations) and on
`KeyState.normalise` (posting path only).
**Finding 2 — the `RunOnLogonDesktop`/`RunOnScrSaverDesktop` gate.
Accepted as a documentation gap; considered and inapplicable, now
recorded.** `InputSimulation.cs:408-409` skips the whole
`HotKeyLockMachine` body — `eatKey` included — on those two desktops.
Chased the flags: both are set only in `Program.Main`
(`App/Class/Program.cs:150-167`, properties at `App/Core/Common.cs:176-186`)
when the MWB **service** launches a second copy of the process onto the
Win32 `Winlogon` or `Screen-saver` secure desktop, one instance per
desktop with its own hook. macOS has no such split: one process per
login session, nothing of ours running behind `loginwindow` or the
screen saver, and a user-space `CGEventTap` neither receives nor posts
once the screen is actually locked. The service that creates those
desktops is out of scope in the first place (README D6). So the
condition is unconditionally true for a Mac receiver and
`KeyState.processDown`'s always-eat-and-lock is the faithful port, not
an omission. Written up in the Assumptions above, as
`docs/protocol.md` §10.5 note 8, and as a comment at the site. QA's own
observation that the hardcoded Win+L branch (`:450-460`) is ungated on
Windows too is repeated in all three places. No behaviour change.
Note 8 was **appended** rather than inserted before §10.5's "macOS-side
facts" note, so the existing citations of §10.5 note 7 (Assumptions,
work-log item 1) keep pointing at what they name.
## QA log
### 2026-09-16 — QA (lane `input-inject`, dev from 3c51e95)
`tools/guard.sh -t 600 -- tools/gates.sh` green (swift-format lint
--strict, `MWBCore` layering, `swift build -Xswiftc -warnings-as-errors`).
Nothing was run that posts a `CGEvent`, locks the screen or moves the
cursor (invariant 5) — verified by build and by reading
`Sources/MWBMac/KeyState.swift` and `Sources/MWBMac/Injector.swift`
top to bottom against `App/Class/InputSimulation.cs` (whole file),
`App/Core/Receiver.cs:100-200`, `App/Core/InitAndCleanup.cs:214-243`,
`App/Class/InputHook.cs:485-512` and `App/Core/Event.cs:260-275`.
Confirmed correct and faithfully ported: the injected-event tag on
every posted event including `releaseAll()`'s ups; the modifier flag
word (device + device-independent masks) applied to every posted key
and mouse event, with `state.note` ordered before `state.eventFlags`
so a modifier's own down/up event reports the *post*-transition state;
`Md.WheelDelta`'s three meanings and the X-button 1/2 → macOS 3/4
mapping; wheel `/120` with a per-axis remainder that survives across
calls; click-count tracking via `ClickTracker` keyed off
`EventTap.now()`; the four intercepted chords and their eat/lock/
release-all combinations (Ctrl+Alt+Del eaten no lock, Win+L eaten +
locked, Ctrl+Alt+End not eaten, `HotKeyLockMachine` eaten + locked);
`releaseAll()` with no rate limit, ordinary keys before modifiers,
clearing `KeyState.chord` afterward; all mutable state confined to
`Injector`'s serial `queue`, `@unchecked Sendable` justified in the
file header and actually honoured (every mutation site is reached
only through `queue.async`/`queue.sync`). No key, VK or click content
is logged at any level (`grep log\.` in `Injector.swift` shows three
call sites, none naming a key). The
`Coordinates.absoluteMove(...) → fromUniversal(..., in: primary)`
two-step de-normalisation is the right reading of
`InputSimulation.cs:160-173`: `dx`/`dy` there are computed by scaling
the *desktop* rectangle into *primary*-monitor 0..65535 units and
handed to `SendInput` `MOUSEEVENTF_ABSOLUTE`, which MSDN documents as
primary-monitor-relative whenever `MOUSEEVENTF_VIRTUALDESK` is absent
(confirmed absent, docs/protocol.md §1 framing note and grep of the
module) — `fromUniversal` over `desktop` alone, the plausible
alternative, would be wrong whenever desktop ≠ primary. Verified by
hand-tracing `Sources/MWBCore/Coordinates.swift`
`absoluteMove`/`fromUniversal` against the same four `w/h/l/t`
products Windows computes.
**Findings.**
1. **`KeyState` normalises a side-less modifier VK to its left variant
*before* chord/hotkey matching, so a lock-chord replay now matches
hotkeys Windows would not match from the same bytes.**
`Sources/MWBMac/Injector.swift:123-125` calls
`KeyState.normalise(vk: data.virtualKey)` and passes the
*normalised* result into `state.process(vk:isUp:lockMachine:)`,
whose chord-tracking switches
(`Sources/MWBMac/KeyState.swift:134-140` `releaseChord`,
`:153-157` `processDown`) match on `KeyMap.leftControl` /
`.leftMenu` / `.leftShift`. But
`Injector.lockChord(for:)` (`Injector.swift:361-372`) — the wire
encoding of `InputHook.GetVkCodesList`
(`App/Class/InputHook.cs:485-512`) — emits the *side-less* codes
`VK.MENU` (0x12), `VK.SHIFT` (0x10) and `VK.CONTROL` (0x11) for
Alt/Shift/Ctrl (only Win gets the side-specific `VK.LWIN`), and on
Windows those exact codes reach `InputProcessKeyEx`
(`App/Class/InputSimulation.cs:372-403` the `LLKHF.UP` switch,
`:418-438` the down switch) whose `case` labels are
`VK.LCONTROL`/`VK.RCONTROL`, `VK.LMENU`/`VK.RMENU`,
`VK.LSHIFT`/`VK.RSHIFT` — side-specific only. A side-less
`VK.CONTROL`/`VK.MENU`/`VK.SHIFT` therefore never sets
Windows' `ctrlDown`/`altDown`/`shiftDown`, so
`Common.HotkeyMatched(..., Setting.Values.HotKeyLockMachine)`
(`InputSimulation.cs:406`) can only be satisfied by a lock-chord
replay when the configured `HotKeyLockMachine` requires *no*
modifier other than Win (only `winDown` is reachable via the
side-specific `VK.LWIN` `GetVkCodesList` sends) — for the shipped
default, Win+Ctrl+Alt+L, the general branch on Windows never
matches from a replay at all, and the machine locks only because
the *separate*, hardcoded `case (VK)'L': if (winDown)` branch
(`InputSimulation.cs:450-460`) fires on `winDown` alone. The
port's `normalise`-before-`process` ordering sets `chord.control`
and `chord.option` true on the side-less codes too, so
`lockMachine.matches(...)` in `KeyState.processDown`
(`KeyState.swift:149`) *does* match for any `HotKeyLockMachine`
that requires Ctrl and/or Alt, not only Win. For the shipped
default this happens to be unobservable — both platforms end up
locking, Windows via the hardcoded `'L'` branch, the port via
`lockMachine.matches` — but for any other configured lock hotkey
that requires Ctrl or Alt (a legal, user-settable
`HotKeyLockMachine`), a lock-chord replay would fail to lock the
real Windows peer it targets while locking a Mac peer, which is
exactly the wire-compatibility invariant (CLAUDE.md invariant 1)
this lane is supposed to hold. It also contradicts this lane's own
citation in `docs/protocol.md` §10.4 note 3 and this README's
Assumptions ("the side-less VK_SHIFT/CONTROL/MENU do not touch
[the chord state]... They are a *separate* set of facts from what
the local keyboard is holding") — the code does not implement the
fact the lane itself recorded. Fix direction: match hotkeys and
update the chord on the *raw* `data.virtualKey`, and normalise only
for `keycode(for:)`/`postKey`/`state.note` (the posting path, where
the Assumptions bullet about mapping to the left key actually
applies). **CONFIRMED.**
2. **The configurable lock hotkey is eaten and locks unconditionally;
Windows gates it on desktop state.** `InputSimulation.cs:408-409`
wraps the `HotKeyLockMachine` match in
`if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop)` —
on the logon or screen-saver desktop, `HotkeyMatched` can be true
and `eatKey` still stays `false` (the key is not swallowed and no
lock happens). `KeyState.processDown`
(`Sources/MWBMac/KeyState.swift:147-152`) has no equivalent guard:
`lockMachine.matches(...)` unconditionally eats and locks. This is
not in the Assumptions/Handshakes as an intentional omission, and
`docs/protocol.md` §10.5 does not mention it either. It may be
legitimately inapplicable on macOS (no separate logon-desktop
session the way Windows has one, and `CGEventTap` input injection
is typically blocked outright once the screen is actually locked),
but that reasoning is not recorded anywhere, so the next reader has
no way to tell "considered and N/A" from "missed." Note only — the
Win+L hardcoded branch (`InputSimulation.cs:450-460`) has no such
guard on Windows either, so `KeyState`'s handling of *that* chord
is not in question. **PLAUSIBLE**, record the reasoning either in
Assumptions or as a §10.5 note.
No fixes applied in this pass beyond the log entry itself — both
findings are behavioural, not typos.
Verdict: REWORK
## Review
- 2026-09-16 (lead): inspected per `docs/loop.md` §5 after one rework
round. Gates green run by me; two files in the brief's list plus TODO
§5, protocol §10.5 and this README. Read the rework diff and the
injector's structure: one tagged HID source, every post through it,
raw VK into chord state and normalised VK into posting, `releaseAll`
with no rate limit, bookkeeping on one queue. The only log line in
the lane is a static string. QA confirmed the primary-bounds reading
of `SendMouse`. Verdict: **merge**. Carry into app-engine: the five
requests in this README's Handshakes (lock chord forwarding,
`releaseAll` on every C2 row, layout into every `inject`,
`HotKeyLockMachine` → `InjectorConfig.lockMachine`, `canInject`).
CP1 questions: remote ⌘L locks this Mac; natural scrolling.