control-channel: close lane (lead review); brief: input-capture

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-16 01:57:56 -07:00
1 parent c03b8cdbcf
commit 1c24c9f67c
5 files changed
+197 -5

No files matched your search

+16
View File
@@ -781,3 +781,19 @@ reset. Flagged, not fixed — outside "verify, don't redesign."
Verdict: REWORK
## Review
- 2026-09-16 (lead): inspected per `docs/loop.md` §5 after two rework
rounds. Gates green run by me; diff limited to the four `MWBNet`
files, `Session.tick` (authorised cross-lane change), TODO §3,
protocol §10.3 and the two READMEs. Read `PeerConnection.swift` in
full and `ControlChannel.swift`'s structure: 48-byte preamble first,
sized reads with the real count passed to `noteReceiveError`, bounded
outbox and 500 ms deadline, stall rule armed by `markControlled`, all
state on one queue, `[weak self]` throughout, nothing logged, nothing
interpreted. QA round 2's heartbeat finding is fixed at the right
place (`Session` compares the raw counter against its own last beat,
`Common.cs:542-559`). Verdict: **merge**. Carry into app-shell: the
three open requests in this README — call `reopenAll()` on a
countdown while nothing is connected (`frmScreen.cs:427-450`), call
`markControlled(peerID:)` on every switch including back to local,
and (done at close) the session-matrix Assumptions wording.
+164
View File
@@ -0,0 +1,164 @@
# 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
- **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, scroll wheel,
plus `tapDisabledByTimeout`/`tapDisabledByUserInput`. The run-loop
source is added to a `CFRunLoop` on a dedicated `Thread`, never the
main thread (C3). A `.defaultTap` needs Accessibility; listening to
keys needs Input Monitoring (README §Permissions).
- **The callback does four things and returns**: (1) if the event
carries the injected tag (`CGEventField.eventSourceUserData ==
InputTypes.injectedEventTag`) return it untouched — the Windows
`RealData` flag (`InputHook.cs:213-220, 340-343`); (2) read the
`RoutingSnapshot`; (3) match hotkeys — the escape set (`InputTypes`)
flips the snapshot to local *inside the callback* and is swallowed;
other hotkeys are queued as `.hotkey` and swallowed; (4) if the
destination is remote, convert to `CapturedInput`, push, return `nil`
(swallow: `InputHook.cs:361-368` keyboard, `:322-325` mouse); if local,
push mouse *moves only* (so `Edge` can watch for a crossing) and pass
everything through. No allocation-heavy work, no locks beyond the
snapshot's uncontended `OSAllocatedUnfairLock` (invariant 4).
- **The queue is a bounded ring of 4096 `CapturedInput`s** in
`MWBMac/CaptureQueue.swift` (it needs a lock, which `MWBCore` may not
import). Motion is coalesced on push when the previous entry is also
motion (latest position wins, wheel deltas summed); a key/button
transition that finds the ring full triggers local recovery: the tap
flips the snapshot to local and reports `.overflow` (C3).
- **Keyboard encoding**: `wVk` from `KeyMap.vk(forKeycode:)`; `dwFlags`
= `LLKHF` bits (`WM.cs:47-54`): `UP 0x80` on key-up, `EXTENDED 0x01`
for the keys Windows marks extended (right Ctrl/Alt, arrows, Ins/Del/
Home/End/PgUp/PgDn, numpad Enter/divide, Win keys), `ALTDOWN 0x20`
while either Option is down. Autorepeat (`CGEventField.keyboardEventAutorepeat`)
is sent as repeated key-downs, which is what the Windows hook sees.
- **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`) into
down/up pairs of `VK_LCONTROL 0xA2`/`RCONTROL 0xA3`, `LSHIFT 0xA0`/
`RSHIFT 0xA1`, `LWIN 0x5B`/`RWIN 0x5C` (⌘ = Win, README D4),
`LMENU 0xA4`/`RMENU 0xA5` (⌥ = Alt). Caps Lock is `VK_CAPITAL 0x14` as
a down+up pair on each toggle; `fn` is ignored.
- **`KeyMap` is a static table in `MWBCore`** keyed by macOS virtual
keycode (the `kVK_*` numbers written as literals with their names in
comments — `Carbon` may not be imported there) for a US layout:
letters, digits, F1–F19, arrows, editing keys, numpad, punctuation,
Return/Tab/Space/Escape/Delete/ForwardDelete. Keys with no VK are
dropped and counted. The reverse map is what `input-inject` uses.
- **Mouse encoding** (`InputHook.cs:245-260`, `WM.cs:27-40`): `dwFlags` =
the `WM_*` id; buttons 0/1/2 = L/R/M, buttons 3/4 = `WM_XBUTTON*` with
`WheelDelta` = 1/2; moves are absolute 0..65535 against the **primary**
display (`Event.cs:112-113`) — or, in `MoveMouseRelatively` mode,
`mouseEventDeltaX/Y` biased by `Coordinates` (§4.4). Scroll: the
fixed-point line delta × 120 accumulated into a remainder so trackpad
scrolling emits whole 120-unit steps (`WM_MOUSEWHEEL` axis 1,
`WM_MOUSEHWHEEL` axis 2, sign as Windows: up/away = +120).
- **Hotkeys** (`InputHook.cs:539-658`, `MouseWithoutBordersProperties.cs`):
switch-machine = ⌃⌥ + `HotKeySwitchMachine` VK 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; ignored when Shift or ⌘ is also held with ⌃⌥ alone
(`InputHook.cs:604-610`). Escape set (C2): switch-machine naming the
local slot, and ⌃⌥⌘Escape. Hotkey definitions arrive in
`CaptureConfig` as VK + modifier set; the tap compares against the
live modifier state it tracks.
- **Easy Mouse** (`EasyMouseOption.cs`, `InputHook.cs:467-473`): the tap
pushes `.edgeCandidate(point)` moves only when the mode allows it —
always for `Enable`, only while ⌃ / ⇧ is held for those modes, never
for `Disable`; the fullscreen rule is the extras lane's.
- **Screens** (`WinAPI.cs:70-80, 115-184`): `CGGetActiveDisplayList` +
`CGDisplayBounds`; primary = `CGMainDisplayID()`; desktop = union;
`screenWidth/Height` = primary size; corner points = every display's
four corners (`MonitorEnumProc`'s sensitive points). Refreshed on
`NSApplication.didChangeScreenParametersNotification` and reported to
the Engine so it can rebuild `EdgeConfig`.
- **Cursor** (`Common.cs:1482-1496`, `InputHook.cs:293-309`): while a
remote is controlled, `CGAssociateMouseAndMouseCursorPosition(false)`
keeps the real pointer parked (deltas still arrive) and
`CGDisplayHideCursor` hides it; parking = warp to (primary centre-x,
y = 4) when `HideMouse` is on, else primary centre; on return,
re-associate, show, warp to the last local position. `parkCursor`
actions from `Switcher` are applied by the consumer rule in the
session-matrix Handshakes (move only when `destinationIsRemote ||
byHideMouseMessage`).
- **Permissions**: `Permissions.preflight()` stays; `request()` calls
`CGRequestListenEventAccess()` / `CGRequestPostEventAccess()` and is
invoked only from a UI action the user clicks (app-shell); a 5 s
health check re-preflights and reports loss (C2). Agents never call
`request()` themselves.
- **Tap loss** (`InputHook.cs` has no equivalent; C2): on
`tapDisabledByTimeout`/`ByUserInput` the callback re-enables the tap
with `CGEvent.tapEnable` **and** flips the snapshot to local, then
reports `.tapLost`; the Engine releases keys.
## Handshakes
### Consumed
- `session-matrix`: `Coordinates` (universal/relative encoding), `EdgeConfig`
shape, `Direction`, `SwitchAction.parkCursor` consumer rule.
- `wire-core`: `Packet`, `MouseData`/`KeyboardData` field layout for the
values `CapturedInput` carries.
### Promised (to input-inject, app-shell, extras)
```swift
// MWBCore/InputTypes.swift
public enum InputTypes { public static let injectedEventTag: Int64 } // C4
public struct RoutingSnapshot: Sendable { destination: Destination (.local | .remote(UInt32)); swallowKeys, swallowMouse: Bool; easyMouse: EasyMouseMode; hotkeys: HotkeyConfig }
public enum CapturedInput: Sendable { key(vk: Int32, flags: Int32); mouse(MouseData) /* WM_* + coords */; edgeCandidate(CGPoint, now: TimeInterval); hotkey(Hotkey); tapLost; overflow }
public struct HotkeyConfig: Sendable { switchMachineVK, lock, reconnect, toggleEasyMouse, switchToAll: Hotkey? }
public enum EasyMouseMode: Int, Sendable { disable = 0, enable = 1, ctrl = 2, shift = 3 }
public enum KeyMap { static func vk(forKeycode: Int64) -> Int32?; static func keycode(forVK: Int32) -> Int64?; static func isExtended(vk:) -> Bool; static func modifierTransitions(old: UInt64, new: UInt64) -> [(vk: Int32, down: Bool)] }
// MWBMac
public final class RoutingState { func read() -> RoutingSnapshot; func write(_:) } // OSAllocatedUnfairLock
public final class CaptureQueue { init(capacity: Int = 4096); func push(_:) -> Bool; func drain() -> [CapturedInput] }
public final class EventTap { init(routing: RoutingState, queue: CaptureQueue, screens: Screens, config: CaptureConfig, onWake: @escaping @Sendable () -> Void); func start() throws; func stop(); func reconfigure(_:) }
public struct ScreenLayout: Sendable { displays: [CGRect]; primary: CGRect; desktop: CGRect; corners: [CGPoint] }
public final class Screens { var layout: ScreenLayout; func refresh(); var onChange: (() -> Void)? }
public final class Cursor { func decouple(parkHidden: Bool, layout: ScreenLayout); func recouple(to: CGPoint?); func park(hideMouse: Bool, layout: ScreenLayout) }
public enum Permissions { static func preflight() -> PermissionState; static func request(); static func startHealthCheck(onLoss:) }
```
## 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`: add `request()` and the
health check.
- [ ] `docs/protocol.md`: append §10.4 with anything learned, cited.
## Work log
## QA log
## Review
+4 -2
View File
@@ -71,8 +71,10 @@ the Windows source again.
32-byte packet per peer per minute.
- **Heartbeats follow the 100 ms timer cadence** exactly:
`count % 600 == 0` (60 s) when `BlockScreenSaver` is on, else
`count % 3000` (300 s) (`frmScreen.cs:566-575`); `Awake` if the user
was active within the window, else `Heartbeat` (`Common.cs:499-513`).
`count % 3000` (300 s) (`frmScreen.cs:566-575`); `Awake` when
`BlockScreenSaver` is on and the raw real-input counter moved since
this session's own previous beat, else `Heartbeat`
(`SendAwakeBeat`, `Common.cs:542-559`; counter `Event.cs:51-55`).
Machine liveness is 25 min (`MachineStuff.cs:32`). `Heartbeat_ex`
key propagation is **not** ported (README D6); those packets are
accepted and ignored.
+12 -2
View File
@@ -154,8 +154,8 @@ Strictly one at a time, in this order (mirrors `TODO.md`):
| 0 | bootstrap | merged 2026-09-15 (lead, solo) |
| 1 | wire-core | merged 2026-09-16 (worktree; the last lane to use one) |
| 2 | session-matrix | merged 2026-09-16 (one rework) |
| 3 | control-channel | in progress from b085023 |
| 4 | input-capture | |
| 3 | control-channel | merged 2026-09-16 (two reworks) |
| 4 | input-capture | in progress |
| 5 | input-inject | |
| 6 | app-shell | **CP1**: first manual acceptance checkpoint (contracts C5) |
| 7 | clipboard | **CP2** |
@@ -174,6 +174,16 @@ Strictly one at a time, in this order (mirrors `TODO.md`):
## 8. Lane log
- **2026-09-16, lane 3 (control-channel)** — Dev (Opus); QA (Sonnet)
REWORK (Name2IP/DNS subnet flow, id collision gated to clients,
Awake rule); Dev rework; QA round 2 REWORK (the Awake fix moved the
comparison to a channel-global beat that no session shares); Dev
rework 2 with an authorised one-method change in `Session`; lead
inspected the second rework directly instead of a third QA round.
What the brief got wrong: it put `userActive` on the channel's tick,
which invited exactly the global-window bug. Lesson: a per-session
rule belongs in `Session`, and briefs should say which side owns a
comparison, not just the value.
- **2026-09-16, lane 2 (session-matrix)** — Dev (Opus), QA (Sonnet)
REWORK with three findings (read-error budget, persist-on-learn,
parkCursor gating); an external plan review the same day produced
+1 -1
View File
@@ -118,7 +118,7 @@ inspection.
sacrificial block handled inside the cipher types, not by the
channel. Closed when control-channel lands.
3. **session-matrix ◀──▶ control-channel**: `Session.feed(_:)`,
`noteReceiveError(bytesReceived:)`, `tick(now:userActive:)`,
`noteReceiveError(bytesReceived:)`, `tick(now:inputEventCount:)`,
`drain() -> [Data]`, `events() -> [SessionEvent]`, `forward(_:)`
(contracts C1). The channel never inspects packet bytes and must
pass read byte counts through, never collapse them.