contracts: sequencing, recovery, concurrency, shared constants, checkpoints

Written after an external review of the plan found cross-module
behaviour under-specified. TODO, topo, loop and the session-matrix
brief now reference docs/contracts.md.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-16 00:54:33 -07:00
1 parent e588f1f71c
commit 08b243a29a
6 files changed
+179 -32

No files matched your search

+3 -2
View File
@@ -4,8 +4,9 @@ mwb-mac is a macOS port of PowerToys "Mouse Without Borders" (MWB): one
keyboard and mouse shared across up to four machines on a LAN, with
clipboard sharing, that **interoperates on the wire with the unmodified
Windows MWB**. Read `README.md` for architecture, `docs/loop.md` for how
work is done, `docs/topo.md` for the dependency map and `TODO.md` for
the backlog before doing anything. The reference implementation is
work is done, `docs/contracts.md` for the behaviour that spans modules
(sequencing, recovery, concurrency), `docs/topo.md` for the dependency
map and `TODO.md` for the backlog before doing anything. The reference implementation is
checked out at `/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/`
(commit `3104d5c`, tag v0.101.2572.0) — read it, cite it, never edit it.
+40 -15
View File
@@ -7,7 +7,8 @@ are no test-writing items: the user tests the app (CLAUDE.md).
Target: a native macOS app with a menu-bar status item and a settings
window that supports every function of the PowerToys module except the
ones in §Out of scope.
ones in §Out of scope. Cross-module behaviour (sequencing, recovery,
concurrency, shared constants, checkpoints) is fixed in `docs/contracts.md`.
---
@@ -59,6 +60,10 @@ ones in §Out of scope.
## 3. control-channel (net) — `Sources/MWBNet/ControlChannel.swift`, `PeerConnection.swift`, `Resolver.swift`
- [ ] `ChannelConfig` struct (C4); bounded outbound queue of 512 with
500 ms send timeout, overflow/timeout closes the connection (C3);
per-connection read queue; events forwarded to an `EngineSink`
protocol the app implements (the Engine itself arrives in lane 6).
- [ ] `NWListener` on port+1, both IP families; one client per non-local
matrix name; 1 s retry for 30 s; one connected client per peer §3.1.
- [ ] `PeerConnection`: one `Session` + cipher pair; serialised sends with
@@ -69,12 +74,22 @@ ones in §Out of scope.
hotkey; `reopenAll()`; delete `Placeholder.swift`.
- [ ] Machine-ID collision ⇒ regenerate and reopen (§1.5).
## 4. input-capture (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Screens.swift`, `Cursor.swift`, `Hotkeys.swift`, `Sources/MWBCore/KeyMap.swift`
## 4. input-capture (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Screens.swift`, `Cursor.swift`, `Hotkeys.swift`, `Sources/MWBCore/KeyMap.swift`, `Sources/MWBCore/InputTypes.swift`
- [ ] `Permissions.request…` added to the preflight file.
- [ ] Session-level head-insert swallowing `CGEventTap` for keys, flags,
mouse, scroll; classify → enqueue → return; pass tagged injected
events; re-enable on timeout/user-input disable (invariants 3, 4).
- [ ] `InputTypes.swift` (core): `CapturedInput`, `RoutingSnapshot`, the
injected-event tag constant, the escape-hotkey definitions
(contracts C3, C4) — defined here so input-inject can consume them.
- [ ] `Permissions.request…` added to the preflight file; health check
every 5 s reporting revocation (C2).
- [ ] Session-level head-insert swallowing `CGEventTap` on its own
run-loop thread for keys, flags, mouse, scroll; reads the routing
snapshot under `OSAllocatedUnfairLock` to decide swallowing
synchronously; appends to the bounded capture ring (4096, motion
coalesced, transitions never dropped — on overflow route local);
passes tagged injected events; on `tapDisabledByTimeout/UserInput`
re-enables **and** routes local (C2, C3, invariants 3, 4).
- [ ] Escape: switch-machine hotkey naming the local slot and ⌃⌥⌘Escape
flip the snapshot to local inside the callback, then notify (C2).
- [ ] `KeyMap`: macOS keycode ↔ Windows VK, `flagsChanged` → modifier VK
pairs, `LLKHF` flags §5.1; `WM_*` mouse mapping, wheel ×120,
X-buttons, absolute 0..65535 moves §5.2.
@@ -93,9 +108,10 @@ ones in §Out of scope.
Windows only if needed.
- [ ] `Mouse` packet → absolute move (de-normalise onto desktop bounds
§4.4), buttons with click-count, wheel (`WheelDelta`/120), X-buttons.
- [ ] Injected-event tag (shared constant with the tap);
`ReleaseAllKeys` on switch/lock/mode change; remote Win+L ⇒ lock
(`CGSession -suspend`); remote Ctrl+Alt+Del ⇒ ignored, logged.
- [ ] Reads the injected-event tag from `InputTypes.swift` (C4); tracks
held keys/buttons; `releaseAll()` = `ReleaseAllKeys` for every
recovery row in C2 plus switch/lock/mode change; remote Win+L ⇒
lock (`CGSession -suspend`); remote Ctrl+Alt+Del ⇒ ignored, logged.
## 6. app-shell (app + core + mac) — `Sources/mwb/*`, `Sources/MWBCore/Settings.swift`, `Sources/MWBMac/StatusItem.swift`, `Sources/MWBMac/SettingsWindow/*.swift`, `Sources/MWBMac/Notifications.swift`
@@ -114,12 +130,19 @@ ones in §Out of scope.
Settings" buttons, LaunchAgent toggle.
- [ ] Status messages (`ShowClipboardAndNetworkStatusMessages`) via
`UserNotifications`.
- [ ] Wiring: tap → edge → session → channel → injector; single instance;
logs at `~/Library/Logs/mwb-mac/` without key material.
- [ ] **Hand `dist/mwb.app` to the user** (docs/loop.md §7) with a
checklist: switch by edge and hotkey, wrap, one/two rows, keyboard
with modifiers and function keys, wheel, reconnect after sleep,
wrong key, peer killed mid-control.
- [ ] The `Engine` actor (C3): owns Switcher, sequencer, replay filter,
connections, held-key state; publishes the routing snapshot; drains
the capture ring (coalescing motion); stamps ids once and forwards
to every target session (C1); dispatches `.packet` events.
- [ ] Recovery wiring (C2): every trigger row implemented end-to-end —
escape hotkeys, controlled-peer disconnect, 30 s silence while
sending input, outbound stall, tap disable, permission loss,
quit/crash handler.
- [ ] Single instance; logs at `~/Library/Logs/mwb-mac/` without key material.
- [ ] **Checkpoint CP1 (contracts C5)**: hand `dist/mwb.app` to the user
with the checklist: switch by edge and hotkey, wrap, one/two rows,
keyboard with modifiers and function keys, wheel, reconnect after
sleep, wrong key, and every C2 recovery row.
## 7. clipboard (core + net + mac) — `Sources/MWBCore/ClipboardCodec.swift`, `Sources/MWBMac/Pasteboard.swift`, `Sources/MWBNet/BulkChannel.swift`, `Sources/MWBMac/ReceivedFile.swift`
@@ -136,6 +159,7 @@ ones in §Out of scope.
100 MB limit, folders refused, `TransferFile` flag; reveal in Finder.
- [ ] `Pasteboard`: `changeCount` poll 500 ms, 1 s suppression, write on
receive (text/RTF/HTML/PNG/file URL), `ShareClipboard` flag.
- [ ] **Checkpoint CP2** (C5): clipboard both ways, in-band and bulk.
## 8. extras (mac + core) — `Sources/MWBMac/Awake.swift`, `Sources/MWBMac/Fullscreen.swift`, `Sources/MWBMac/FakeCursor.swift`
@@ -151,6 +175,7 @@ ones in §Out of scope.
user sees where the pointer went (Windows `CustomCursor.cs`).
- [ ] `BlockMouseAtScreenCorners` end-to-end; `MoveMouseRelatively`
end-to-end with `NextMachine` §4.4.
- [ ] **Checkpoint CP3** (C5).
## 9. polish — driven by the user's testing
+111
View File
@@ -0,0 +1,111 @@
# contracts.md — cross-module behaviour every lane must honour
**Purpose.** Feature READMEs specify one module each; this file specifies
the behaviour that spans modules — sequencing, recovery, concurrency and
who owns shared constants. It was written 2026-09-16 after the
session-matrix review found these under-specified. A lane that cannot
satisfy a contract here files a Handshake request; it does not
reinterpret the contract.
## C1. Sequence once, distribute unchanged
Windows stamps one `Id` per logical packet and writes the same bytes to
every matching socket (`Common.cs:906`, `SocketStuff.cs` `TcpSend`);
the receiver's 50-entry replay ring (`Receiver.cs:40-82`) then drops the
second delivery when a peer pair has two connections. We do the same:
- `PacketSequencer` and `ReplayFilter` are **process singletons owned by
the Engine (C3)**; no `Session` creates its own.
- The app stamps `Id` (and `Src`) **once** and hands the identical
`Packet` to every target session via `Session.forward(_:)`.
`Session` never re-stamps a packet it forwards.
- `Session` stamps ids itself only for packets it originates
(`Handshake`, `HandshakeAck`, heartbeats, `Hi`, `ByeBye`); those are
per-connection by nature on Windows too.
- Input (`Mouse`, `Keyboard`), `HideMouse`, `MachineSwitched`,
`NextMachine`, `Matrix` and clipboard chunks are **always** app-stamped
and forwarded. A `Session` API that lets a caller send an unstamped
application packet to one connection is a defect.
## C2. Local recovery — who does what
Invariant 3 (CLAUDE.md) in concrete tasks. "Route local" means: the
Switcher's `desMachineID` becomes the local id, the tap stops swallowing,
the cursor is re-associated and moved to the last local position, and
every key and mouse button we believe is down is released locally with
synthetic up events (Windows `ReleaseAllKeys`, `InitAndCleanup.cs:214-243`).
| trigger | detected by | action |
|---|---|---|
| **Escape shortcut** while control is remote: the switch-machine hotkey naming the local slot (⌃⌥F<n>, `InputHook.cs:611-658`), and additionally **⌃⌥⌘Escape** (mac-only hard escape, always local, never forwarded) | EventTap, synchronously in the callback | route local immediately (the tap flips the routing snapshot itself, then notifies the Engine); the Engine releases keys and sends `HideMouse`/`MachineSwitched` housekeeping afterwards |
| Controlled peer disconnects (`ByeBye`, socket close, read error, `.invalidKey`) | PeerConnection → Engine | route local, release keys |
| Controlled peer stops answering: no packet for 30 s **while we are sending it input** (tighter than the 25 min pool liveness, which is for the UI) | Engine timer | close that connection, route local |
| Outbound stall: a `send` on the controlled peer does not complete within 500 ms (`SocketStuff.cs:1286` `SendTimeout`) or its bounded queue overflows (C3) | PeerConnection | close the connection → the disconnect row |
| Event tap disabled by timeout or by user input (`kCGEventTapDisabledByTimeout` / `ByUserInput`) | EventTap callback | re-enable the tap **and** route local — a tap that was disabled has lost events, so held-key state is unknown |
| Tap cannot be created or permission revoked at runtime (`CGPreflightListenEventAccess` turns false) | EventTap health check every 5 s | route local, show the permissions state in the menu bar |
| App quits or crashes | `atexit`/signal handler in `mwb` | best effort: re-associate the cursor and release keys; sockets send `ByeBye` |
Recovery must not depend on the network: every action in the table is
local, and none waits on a queue that could be stuck.
## C3. Concurrency: the Engine, the routing snapshot, and bounded queues
- **The Engine** is one Swift `actor` in `mwb` (app-shell lane) that
owns all mutable shared state: `Switcher` (matrix, pool,
`desMachineID`), `PacketSequencer`, `ReplayFilter`, the set of
`PeerConnection`s, the `Injector`'s held-key state. Everything that
changes that state is an `await engine.…` call. `MWBCore` types stay
plain values/classes with no locking; the actor is the lock.
- **The routing snapshot** is the one piece of state read *outside* the
actor: a tiny value (`destination: local | remote(peerID)`,
`swallowKeys`, `swallowMouse`, `escapeHotkeys`) held in an
`OSAllocatedUnfairLock<RoutingSnapshot>` (`os` module, macOS 13+),
written by the Engine on every switch and read by the tap callback so
it can decide **synchronously** whether to swallow an event. The lock
is uncontended and held for a copy; that is within invariant 4.
- **Capture queue**: the tap callback appends a `CapturedInput` value to
a bounded ring (capacity 4096) and returns. The Engine drains it on
its own task. Overflow policy: mouse *motion* is coalesced (only the
latest position per drain is kept; wheel deltas are summed); key and
button *transitions* are never dropped — if a transition cannot be
enqueued, the tap routes local (C2) and stops swallowing, because
losing a key-up on a remote machine is worse than losing control.
- **Outbound queue**: per connection, bounded to 512 framed packets
(Windows: a 320 000-byte socket buffer, `SocketStuff.cs:1283-1284`).
Sends are serialised on the connection's own queue with a 500 ms
completion timeout. Overflow or timeout closes the connection (C2).
- **Inbound**: each connection reads on its own queue, decrypts with its
`CipherReader`, feeds `Session`, and forwards `SessionEvent`s to the
Engine. Only the Engine dispatches `.packet` events to the injector,
pasteboard or switcher.
- The `CGEventTap` callback runs on a dedicated `CFRunLoop` thread
created for it, never on the main thread, so a busy UI cannot stall it.
## C4. Shared constants and configuration are defined before first use
- **Injected-event tag** (`CGEventField.eventSourceUserData` value the
tap must pass through untouched): defined in
`MWBCore/InputTypes.swift` by the **input-capture** lane, which is
also where `CapturedInput`, `RoutingSnapshot` and the escape-hotkey
definitions live. `input-inject` reads it from there.
- **Configuration**: lanes before app-shell take lane-specific config
structs (`SessionConfig`, `EdgeConfig`, `ChannelConfig`,
`CaptureConfig`); none of them import a `Settings` type. app-shell
defines `Settings` and maps it onto those structs. Changing a
behaviour flag at runtime = building a new config struct and handing
it to the owner via the Engine.
- **Status colours and names** (`SocketStatus`): `MWBCore` (session-matrix);
the UI maps them to colours from `doc/devdocs/modules/mousewithoutborders.md`.
## C5. Manual acceptance checkpoints
The user tests; the schedule says when. Each checkpoint means: the
lead runs `tools/bundle.sh`, hands over `dist/mwb.app` and a checklist,
and the findings become `TODO.md` lines for the next lane.
| after lane | checkpoint |
|---|---|
| 6 app-shell | **CP1** — menu bar, settings window, keyboard and mouse across two Macs and Mac ↔ Windows, every recovery row in C2 |
| 7 clipboard | **CP2** — text/RTF/HTML/image/file both ways, in-band and bulk |
| 8 extras | **CP3** — screensaver blocking, fullscreen rule, drawn cursor, corners, relative mode |
| 9 polish | continuous, one checkpoint per batch of fixes |
+5
View File
@@ -44,6 +44,11 @@ the Windows source again.
`Session`. The sequencer's start value comes from the persisted
`PackageID` setting and the app stores it back; this lane exposes
`current` for that.
- **Sequence once, distribute unchanged (contracts C1).** Application
packets are stamped by the app and handed to each target session via
`forward(_:)`; `Session` stamps only the packets it originates
(handshake, heartbeats, `Hi`, `ByeBye`). There is no public API to
send an unstamped application packet on one connection.
- **Each `Session` beats for its own connection.** Windows broadcasts one
heartbeat from a global timer to every socket, so a peer pair's two
connections carry the *same* `Id` and the receiver's replay ring
+9 -9
View File
@@ -69,8 +69,8 @@ eyes and runs `tools/gates.sh` before writing the Review section.
```
You are the Dev for lane `<name>` of mwb-mac. Work in the repository
/Users/guoliangchen/repo/mac_without_borders on main. Read, in order: CLAUDE.md,
README.md, docs/protocol.md, docs/topo.md, docs/features/<name>/README.md.
The README's Status/TODO is your task list and its file list is the only
README.md, docs/protocol.md, docs/contracts.md, docs/topo.md,
docs/features/<name>/README.md. The README's Status/TODO is your task list and its file list is the only
set of files you may create or edit, plus: docs/features/<name>/README.md
(Assumptions, Handshakes, Status/TODO, Work log), TODO.md (tick your own
lines only) and docs/protocol.md (append citations you verified, in your
@@ -157,19 +157,19 @@ Strictly one at a time, in this order (mirrors `TODO.md`):
| 3 | control-channel | |
| 4 | input-capture | |
| 5 | input-inject | |
| 6 | app-shell | first user-testable build: menu bar + settings window + mouse/keyboard sharing |
| 7 | clipboard | |
| 8 | extras | screensaver blocking, fullscreen Easy Mouse rule, drawn cursor |
| 9 | polish | driven by the user's testing |
| 6 | app-shell | **CP1**: first manual acceptance checkpoint (contracts C5) |
| 7 | clipboard | **CP2** |
| 8 | extras | **CP3** |
| 9 | polish | driven by the checkpoints' findings |
## 7. Escalations — things only the user can do
- **Grant permissions** (Accessibility, Input Monitoring) to
`dist/mwb.app` in System Settings, and create the self-signed
`MWB_SIGN_IDENTITY` once (`tools/bundle.sh` header).
- **Test the app.** After lane 9 and after every lane thereafter the
lead hands the user a `dist/mwb.app` and a short checklist of what
changed; findings come back as TODO lines for the next lane.
- **Test the app** at the checkpoints in `docs/contracts.md` C5 (after
lanes 6, 7 and 8): the lead hands over `dist/mwb.app` and a short
checklist; findings come back as TODO lines for the next lane.
- **Provide a Windows machine** with PowerToys for real interop checks.
## 8. Lane log
+11 -6
View File
@@ -8,8 +8,8 @@ break — every edge below is one.
Sources of truth this document is derived from (and defers to on
conflict): `Package.swift`, each `docs/features/<name>/README.md`
(**Handshakes** in particular), `README.md`, `CLAUDE.md`,
`docs/protocol.md`. Drafted 2026-09-15 at planning time; updated the same day after the
(**Handshakes** in particular), `docs/contracts.md`, `README.md`,
`CLAUDE.md`, `docs/protocol.md`. Drafted 2026-09-15 at planning time; updated the same day after the
bootstrap merge (skeleton exists, file ownership tables below reflect it).
The lead updates it after every merged lane.
@@ -124,15 +124,20 @@ inspection.
returns a `Switch?` decision. Debounce lives in `Edge` with the
injected clock; the tap only supplies points and timestamps.
5. **input-capture ◀──▶ input-inject**: the injected-event tag value
(`eventSourceUserData`) is one constant defined in `MWBMac/Injector.swift`
and read by `EventTap.swift`.
(`eventSourceUserData`) is one constant defined in
`MWBCore/InputTypes.swift` by input-capture and read by
`Injector.swift` (contracts C4).
6. **input-capture ◀──▶ input-inject**: `Screens.desktopBounds` and
`primaryBounds` in CG coordinates (top-left origin, points).
7. **clipboard ◀──▶ clipboard**: the `"<len>*<name>"`
header codec and the text tag/SEP codec live in `ClipboardCodec.swift`
and are reused by bulk unchanged.
8. **app-shell ◀──▶ everyone**: `Settings` is the one struct passed
down; lanes read fields, never the file.
8. **app-shell ◀──▶ everyone**: earlier lanes take lane-specific config
structs (`SessionConfig`, `EdgeConfig`, `ChannelConfig`,
`CaptureConfig`); app-shell's `Settings` maps onto them (contracts C4).
9. **Engine (app-shell) ◀──▶ session-matrix, control-channel,
input-capture, input-inject**: the actor that owns shared state, the
routing snapshot, the bounded queues and recovery (contracts C1–C3).
## 3. Lane order