# TODO — mwb-mac backlog, by milestone Legend: **(core)** pure logic in `MWBCore`, **(net)** `MWBNet`, **(mac)** `MWBMac`, **(app)** executable/tooling. Section numbers are referenced from `docs/topo.md` and feature READMEs as "TODO §n". Each lane's brief names its files; a lane ticks only its own lines. Milestones are ordered; lanes inside a milestone may run in parallel when `docs/topo.md` §3 says they are independent. --- ## 0. Toolchain and skeleton (M0, serial — `docs/features/bootstrap`) - [x] **Unblock SwiftPM.** `swift build` failed with Command Line Tools only (README §Build). Fixed 2026-09-15 by installing Xcode 27.0; smoke build + XCTest verified. Recorded in the bootstrap README. - [x] `Package.swift` with targets `MWBCore`, `MWBNet`, `MWBMac`, `mwb`, tests `MWBCoreTests`, `MWBNetTests`; Swift 6 language mode; macOS 14 minimum. Layering is enforced by a test in `MWBCoreTests` that greps `Sources/MWBCore` for `import AppKit|CoreGraphics|Network` and fails on any hit. - [x] `tools/gates.sh`: `swift-format lint --strict --recursive Sources Tests`, `swift build -Xswiftc -warnings-as-errors`, `tools/guard.sh -- swift test`. - [x] `tools/bundle.sh`: release build → `dist/mwb.app` (Info.plist with `LSUIElement = true`, bundle id `com.luciochen.mwb-mac`), `codesign --force --sign "$MWB_SIGN_IDENTITY"`; document how to create a self-signed identity once (D5). - [x] `.swift-format` config; `.gitignore` (`.build/`, `dist/`). - [x] Smoke executable: `mwb --version`, `mwb --check-permissions` (prints preflight results, exit 0 when complete, 3 otherwise). - [x] `docs/loop.md` (the Dev → QA → lead procedure with literal prompts), `docs/features/TEMPLATE.md`, `tools/lane.sh`. ## 1. Wire core (M1 — two lanes: `packet-codec` ‖ `cipher-stream`) ### 1.1 packet-codec (core) — `Sources/MWBCore/Packet.swift`, `Framing.swift`, `Tests/MWBCoreTests/PacketTests.swift`, `FramingTests.swift` - [ ] `PackageType` enum, raw `UInt8`, every value from protocol §1.2; `isBig` rule (§1.1) as a table-driven test over all 256 byte values. - [ ] `Packet` value type with the union views (`mouse`, `keyboard`, `nonce`, `postAction`, `machineName`) reading/writing a fixed 32/64-byte little-endian buffer at the documented offsets. - [ ] `MachineName` ASCII, space-padded, trimmed; non-ASCII rejected. - [ ] `Framing.seal(magic:bytes:)` and `Framing.open(magic:bytes:)` exactly as §1.3, including the "only bytes 2..31" checksum and the zeroing of bytes 1–3 on the receive side. - [ ] Golden vectors: hand-assembled bytes for `Handshake`, `Mouse`, `Keyboard`, `Matrix` (slot 4, both flags), `ClipboardText` chunk. Property test: `open(seal(p)) == p` for random packets; flipping any of bytes 2..31 is detected; flipping bytes 32..63 is **not** (pinned as documented behaviour). ### 1.2 cipher-stream (core) — `Sources/MWBCore/MagicHash.swift`, `CipherStream.swift`, `Tests/MWBCoreTests/MagicHashTests.swift`, `CipherStreamTests.swift` - [ ] `magicNumber(for key: String) -> UInt32` per §2.1 (50 001 SHA-512 rounds, the `<< 23` overlap, UTF-16 code unit truncation to a byte). Pin one vector computed independently (Python transcription in `Tests/Fixtures/magic_reference.py`, run once, result committed). - [ ] `deriveKey(password:salt:)` = PBKDF2-HMAC-SHA512, 100 000 rounds, 32 bytes, via CommonCrypto. Vector pinned against Python `hashlib.pbkdf2_hmac`. - [ ] `CipherWriter` / `CipherReader`: emit/consume the 16+16 header, the sacrificial block, then a raw AES-256-CBC no-padding stream (§2.3). Streaming API: `write(Data) -> Data` / `read(Data) -> Data` accumulating partial blocks; a `CipherReader` fed one byte at a time must produce the same plaintext as one fed all at once. - [ ] Round-trip test writer→reader; a wrong key yields garbage, not a throw, and the caller's framing check rejects it (that is the Windows behaviour: `InvalidKey` after >10 bad packets). - [ ] Never log key material: a test asserts `String(describing:)` and `debugDescription` of every crypto type omit key/salt/IV bytes. ## 2. Session logic (M2 — two lanes: `session` ‖ `matrix-edge`) ### 2.1 session (core) — `Sources/MWBCore/Session.swift`, `Tests/MWBCoreTests/SessionTests.swift` - [ ] Sans-I/O `Session` state machine: `feed(bytes)` → `[Event]`, `outgoing()` → bytes; states NA…Connected per §3.2 `SocketStatus`. - [ ] Handshake exactly as §3.2 (10× `Handshake`, nonce complement, `HandshakeAck`, adopt peer name/id, >10 untrusted packets ⇒ InvalidKey, self-connection detection). - [ ] Dedup ring of 50 ids with the four exemptions (§1.4). - [ ] Heartbeat scheduling (60 s / 300 s, `Awake` vs `Heartbeat`), `Hi` probe counting, `ByeBye`, 25 min liveness (§3.3) — all driven by an injected clock. - [ ] Two `Session`s wired back-to-back in a test reach `Connected` both ways and exchange a `Mouse` packet. ### 2.2 matrix-edge (core) — `Sources/MWBCore/Matrix.swift`, `Edge.swift`, `Tests/MWBCoreTests/MatrixTests.swift`, `EdgeTests.swift` - [ ] `Matrix` (4 slots, one/two rows, wrap) and `MachinePool` (serialize/parse `Name:Id,…`, 25 min alive) per §4.1. - [ ] `Matrix` packet encode/decode (slot in `Src`, flags in `Type`) §4.2. - [ ] `LiveMachineMatrix`, moveLeft/Right/Up/Down, `desMachineID` / ALL. - [ ] Edge detection §4.3 with the primary-vs-desktop rectangle rule, 100 ms debounce, corner blocking; coordinate normalization §4.4 with all four rectangle cases, `MOVE_MOUSE_RELATIVE` / `XY_BY_PIXEL` biases, `NextMachine` encoding (id in `WheelDelta`). - [ ] Table tests on 1-, 2- and 3-monitor layouts including a negative- origin monitor left of primary. ## 3. Platform capture (M3 — two lanes: `control-channel` ‖ `event-tap`) ### 3.1 control-channel (net) — `Sources/MWBNet/ControlChannel.swift`, `Resolver.swift`, `Tests/MWBNetTests/LoopbackTests.swift` - [ ] `NWListener` on port+1, all interfaces, IPv4+IPv6; one `NWConnection` client per non-local matrix name; 1 s retry for 30 s; dedup to one client socket per peer (§3.1). - [ ] `Resolver`: `getaddrinfo` + `Name2IP` lines (§7); optional same-/16 check and reverse validation as settings, off by default. - [ ] Each connection owns one `Session` and a `CipherWriter`/`Reader` pair per direction; send serialised through one queue with 500 ms send timeout; receive loop reads 32 then 32. - [ ] Reconnect on path change (`NWPathMonitor`), wake (`NSWorkspace.didWakeNotification` is `mac`; expose a `reopenAll()` the app calls), connection reset, hotkey. - [ ] Loopback test: two channels on 127.0.0.1 with random ports reach `Connected` and pass 1 000 `Mouse` packets in order with no dedup drops; wrong key on one side ends in `InvalidKey`. ### 3.2 event-tap (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Sources/MWBCore/KeyMap.swift`, `Tests/MWBCoreTests/KeyMapTests.swift` - [ ] `Permissions`: preflight/request Accessibility + Input Monitoring; never loops on request; reports per-permission state. - [ ] `EventTap`: session tap, head-insert, default (swallowing) tap for key down/up/flagsChanged, mouse move/drag/buttons/scroll; callback converts to a `CapturedInput` value and enqueues; returns `nil` to swallow when the destination is remote; passes tagged injected events through; re-enables on timeout/user-input disable (invariant 3 and 4). - [ ] Modifier tracking (Cmd/Ctrl/Opt/Shift) and hotkey matching per §4.5 with D4 mapping; the tap reports `.hotkey(...)` events. - [ ] `KeyMap`: macOS keycode → Windows VK and back, `flagsChanged` → modifier VK down/up pairs, `LLKHF` flags, `NSEvent.ModifierFlags` → nothing (VKs carry modifiers themselves). Table pinned by tests: letters, digits, F1–F19, arrows, editing keys, numpad, punctuation on US layout; unknown keys are dropped and counted. - [ ] Mouse: `WM_*` mapping, wheel line deltas × 120, X-buttons, moves as absolute 0..65535 against the primary display (§5.2, §4.4). ## 4. Platform injection and screens (M4 — two lanes: `input-inject` ‖ `screens-cursor`) ### 4.1 input-inject (mac) — `Sources/MWBMac/Injector.swift` - [ ] `Keyboard` packet → `CGEvent` key down/up with VK→keycode; modifier VKs → `flagsChanged` with maintained flag state; `EXTENDED` ignored; autorepeat handled by repeated downs like Windows. - [ ] `Mouse` packet → move (absolute, §4.4 de-normalization onto the desktop bounds), buttons with click-count tracking (double-click = two downs within `NSEvent.doubleClickInterval`, since Windows drops `*DBLCLK`), wheel (`WheelDelta`/120 lines), X-buttons → other mouse buttons 3/4. - [ ] Every posted event tagged with the injected marker (README mapping). - [ ] `ReleaseAllKeys` equivalent on switch/lock. - [ ] Remote Win+L → lock; remote Ctrl+Alt+Del → nothing (documented). ### 4.2 screens-cursor (mac) — `Sources/MWBMac/Screens.swift`, `Cursor.swift` - [ ] `Screens`: active displays, primary (`CGMainDisplayID`), desktop union, corner points for `BlockMouseAtScreenCorners`; refresh on `NSApplication.didChangeScreenParametersNotification`. - [ ] `Cursor`: park at primary centre-x / y=4 (`HideMouse` on) or centre; `CGAssociateMouseAndMouseCursorPosition(false)` while controlling a remote, deltas read from the tap; restore on return to the last local position. - [ ] `HideMouse (50)` packet handling. ## 5. Clipboard and app shell (M5 — two lanes: `clipboard-inband` ‖ `menubar-app`) ### 5.1 clipboard-inband (core + mac) — `Sources/MWBCore/ClipboardCodec.swift`, `Sources/MWBMac/Pasteboard.swift` - [ ] Text codec: `TXT`/`RTF`/`HTM` + SEP, UTF-16LE, raw DEFLATE (§6.1). **First task: prove Foundation `.zlib` == .NET `DeflateStream` on a fixture** (README mapping note); fall back to `compression_stream` with `COMPRESSION_ZLIB` if not. - [ ] 48-byte chunking at offset 16, `ClipboardDataEnd`, zero-padding semantics on decode (§6.2); 1 MB in-band limit. - [ ] Image: PNG from `NSPasteboard` (`.png`, else TIFF → PNG). - [ ] `Pasteboard`: `changeCount` poll at 500 ms, 1 s suppression, write on receive; never write when we were the source. - [ ] Feature flag from `ShareClipboard`. ### 5.2 menubar-app (app + mac) — `Sources/mwb/*`, `Sources/MWBMac/StatusItem.swift`, `Sources/MWBCore/Settings.swift` - [ ] `Settings`: schema per README §Settings, load/save/watch, 0600, random key/`MachineID`/`DeviceID` on first run. - [ ] `NSStatusItem` with per-machine status dots in the documented colours, matrix editor (4 names, one/two rows), key entry, port, toggles; "Reconnect", "Quit". - [ ] Permissions onboarding panel; LaunchAgent install/uninstall. - [ ] Single instance via pid-file lock; log to `~/Library/Logs/mwb-mac/` with rotation, never key material. - [ ] Lock-machine hotkey → `CGSession -suspend` (decide vs `pmset displaysleepnow`; record). ## 6. Bulk transfer and interop (M6 — two lanes: `clipboard-bulk` ‖ `interop-vectors`) ### 6.1 clipboard-bulk (net) — `Sources/MWBNet/BulkChannel.swift` - [ ] Listener on port; `Clipboard (69)` broadcast on big data; pull on `MachineSwitched`, push on `ClipboardAsk` (§6.3). - [ ] Bulk handshake: cipher layout, one 64-byte `DATA` each way, `ResolveID(name) == Src` gate, 1024-byte UTF-16LE header `"*"`, 1 MB chunks, 32-byte file padding, exact-length read, atomic temp-file commit to `~/Desktop/MouseWithoutBorders/`. - [ ] 100 MB file limit, single file only, folders refused with the Windows message; `TransferFile` flag. ### 6.2 interop-vectors (tests) — `Tests/Fixtures/`, `tools/winvectors/` - [ ] A small .NET console program (`tools/winvectors/`, runs **on a Windows machine with the PowerToys tree**) that links the MWB assembly and dumps: `Get24BitHash` for 5 keys, PBKDF2 key for fixed salt, one full encrypted control-stream capture for a scripted handshake with fixed RNG, framed bytes for each packet type, a deflated clipboard text fixture. - [ ] Until a Windows machine is available: a `pcap` of a real Windows↔Windows session (user-provided) plus the typed key lets us decrypt and replay; document how to capture it. - [ ] Every `[transcribed]` mark in `docs/protocol.md` flips to `[verified]` only when a fixture from this lane pins it. ## 7. End to end (M7, serial — needs the real devices) - [ ] `docs/features/end-to-end`: Mac ↔ Windows over the LAN, both directions, checklist: switch by edge, by hotkey, wrap, one/two rows, keyboard incl. modifiers and function keys, wheel, clipboard text/image/file, reconnect on sleep/wake, wrong key, kill the peer mid-control (invariant 3). - [ ] Soak: 8 h with heartbeats and periodic switches under `tools/guard.sh`; memory flat; tap never stays disabled. - [ ] `docs/perf/README.md` filled with measured tap-callback and end-to-end latencies. ## 8. Later (post-v1, ordered by value) - [ ] CI on the existing Gitea runner (`.gitea/workflows/ci.yml` running `tools/gates.sh`) — only once invariant 5 is provably safe on a runner that shares the user's session. - [ ] Keychain storage for `SecurityKey` (D3). - [ ] Easy Mouse fullscreen suppression + excluded apps (`NSWorkspace` frontmost app, `NSWindow` fullscreen detection via Accessibility). - [ ] `Heartbeat_ex` key propagation (§3.3) so a key typed on one machine spreads. - [ ] "Swap ⌘/⌃ when controlling Windows" option. - [ ] Non-US layouts: send VKs by physical position vs by character — needs a decision and a test matrix. - [ ] Sparkle-style updates, notarization, Homebrew cask. ## 9. Out of scope, with reasons (D6) - Windows service / logon-screen / UAC secure desktop control: macOS login window cannot be driven by a user-session event tap. - Explorer drag-and-drop (§6.4): depends on a Windows-shell helper; a Finder equivalent is a separate design. - Screen capture to Paint (`CaptureScreenCommand`, `ClipboardCapture`): niche; packets are ignored and logged. - GPO, telemetry, `ShowOriginalUI`: Windows-only. - Animated fake cursor (`DrawMouse`): cosmetic.