diff --git a/Sources/MWBCore/Session.swift b/Sources/MWBCore/Session.swift index a523246..9a2d5c5 100644 --- a/Sources/MWBCore/Session.swift +++ b/Sources/MWBCore/Session.swift @@ -225,6 +225,15 @@ public final class Session { sendDirect(p) } + /// Queues a packet that already carries its `Id`, for a broadcast the app + /// sequenced once and is sending to several connections — which is what + /// `SkSend` does with one `Id` and many sockets (`Common.cs:912-930`), and + /// what keeps the receiver's replay ring collapsing a peer pair's two + /// copies into one. `Src` is still filled in if it is `NONE`. + public func forward(_ packet: Packet) { + sendDirect(packet) + } + /// The liveness probe Windows writes before trusting a socket's "connected" /// state (`Hi`, `TestSend`, `Common.cs:822-847`). Not sequenced, like every /// `TcpSend`-only packet. diff --git a/Sources/MWBCore/Switching.swift b/Sources/MWBCore/Switching.swift index 3e06171..aee7d4f 100644 --- a/Sources/MWBCore/Switching.swift +++ b/Sources/MWBCore/Switching.swift @@ -235,9 +235,7 @@ public final class Switcher { var p = Packet(type: .nextMachine) p.des = controller p.mouse = MouseData(x: landing.x, y: landing.y, wheelDelta: Int32(bitPattern: target)) - p.id = sequencer.next() - p.src = localID - return p + return stamped(p) // Common.cs:534 goes out through SkSend } /// Learns the sender of a `Heartbeat`, `Awake` or `Hello` diff --git a/TODO.md b/TODO.md index 00831f4..e7e0d92 100644 --- a/TODO.md +++ b/TODO.md @@ -35,23 +35,25 @@ ones in §Out of scope. - [x] Key rules §2.4: 16-char minimum, generator with the four charsets, display grouping. -## 2. session-matrix (core) — `Sources/MWBCore/Session.swift`, `Matrix.swift`, `MachinePool.swift`, `Edge.swift`, `Coordinates.swift` +## 2. session-matrix (core) — `Sources/MWBCore/Sequencing.swift`, `Session.swift`, `Matrix.swift`, `MachinePool.swift`, `Switching.swift`, `Edge.swift`, `Coordinates.swift` — done 2026-09-16 -- [ ] `Session`: sans-I/O state machine, `feed(bytes) -> [Event]`, +- [x] `Session`: sans-I/O state machine, `feed(bytes) -> [Event]`, `outgoing() -> Data`, `SocketStatus` NA…Connected §3.2, injected clock. -- [ ] Handshake §3.2: 10× `Handshake`, nonce complement, `HandshakeAck`, +- [x] Handshake §3.2: 10× `Handshake`, nonce complement, `HandshakeAck`, adopt peer name/id, >10 untrusted ⇒ InvalidKey, self-connect close, - >10 failures ⇒ give up. -- [ ] Dedup ring of 50 ids with the four exemptions §1.4; `Id` counter + >10 failures ⇒ give up. *(The per-endpoint failure counter is the + control-channel's — see that lane's §3 and the session-matrix + Handshakes request.)* +- [x] Dedup ring of 50 ids with the four exemptions §1.4; `Id` counter persisted via settings hook. -- [ ] Heartbeat 60 s / 300 s, `Awake` vs `Heartbeat`, `Hi`, `ByeBye`, +- [x] Heartbeat 60 s / 300 s, `Awake` vs `Heartbeat`, `Hi`, `ByeBye`, 25 min liveness §3.3. -- [ ] `Matrix` (4 slots, one/two rows, wrap) and `MachinePool` +- [x] `Matrix` (4 slots, one/two rows, wrap) and `MachinePool` (`Name:Id,…`, alive) §4.1; `Matrix` packet encode/decode §4.2; learning peers from Heartbeat/Hello/Awake; `LiveMachineMatrix`. -- [ ] Switching: move left/right/up/down, `desMachineID`, ALL mode, +- [x] Switching: move left/right/up/down, `desMachineID`, ALL mode, `MachineSwitched`, `NextMachine` (id in `WheelDelta`) §4.4. -- [ ] Edge detection §4.3 (primary-vs-desktop rule, 100 ms debounce, +- [x] Edge detection §4.3 (primary-vs-desktop rule, 100 ms debounce, corner blocking) and coordinate normalisation §4.4 (four rectangle cases, `MOVE_MOUSE_RELATIVE` / `XY_BY_PIXEL` biases). diff --git a/docs/features/session-matrix/README.md b/docs/features/session-matrix/README.md index c1cab87..3c55d3a 100644 --- a/docs/features/session-matrix/README.md +++ b/docs/features/session-matrix/README.md @@ -19,11 +19,19 @@ the Windows source again. hands it decrypted packet bytes (`feed`), asks what to send (`drain() -> [Data]`, already framed and ready for `CipherWriter`) and what happened (`events`), and calls `tick(now:)` from its own timer. - Time is a `TimeInterval` the caller supplies; nothing reads the clock. + Time is a `TimeInterval` in **seconds** that the caller supplies; + nothing in this lane reads a clock. Windows counts milliseconds + (`Common.GetTick`), so every ported constant is divided by 1000 and + cited with its millisecond value. - **One `Session` per TCP connection**, client or server side — Windows runs the same `MainTCPRoutine` for both (`SocketStuff.cs:1261-1565`). Which of a peer's two connections is kept is the net lane's policy (`SocketStuff.cs:1980-2004`), not this lane's. +- **The duplicate-client check is not here.** Windows drops a second + client socket to the same peer inside `MainTCPRoutine` + (`SocketStuff.cs:1421-1428`) using state only the socket layer has. This + lane emits `.connected(peerName:peerID:)` and the `control-channel` lane + applies its own policy, as this README already said it would. - **Trust is per connection and gates everything.** Until the `HandshakeAck` nonce check passes, the only packets `Session` acts on are `Handshake`/`HandshakeAck`; other packets are counted and after @@ -36,6 +44,13 @@ 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. +- **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 + collapses the second (`Common.cs:906-916`). Ours stamps a fresh `Id` per + session, so a peer processes both copies. `AddToMachinePool` is + idempotent, so the observable behaviour is identical; it costs one extra + 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 @@ -49,13 +64,22 @@ the Windows source again. `MachinePool.cs:287-301`), so `Settings` can round-trip them unchanged from a PowerToys machine. - **Learning peers** from `Heartbeat`/`Hello`/`Awake` - (`MachineStuff.cs:712-777`) adds to the pool and, if the matrix has a - free slot and the name is new, to the matrix, then requests a matrix - re-send — reported as an event, the app decides to persist. + (`MachineStuff.cs:712-777`) adds to the pool and, when the name is new, + rebuilds the matrix from the pool slot-for-slot so control is + bidirectional at once, then queues the four `Matrix` packets — reported + as `SwitchAction`s, the app decides to persist and reconnect. This lives + on `Switcher`, not on `Session`: the pool and matrix are app-wide and a + session is per-connection. - **Geometry uses `CGRect`/`CGPoint` from Foundation** (no CoreGraphics import) in the Windows convention: top-left origin, y down, integer pixels. The `input-capture` lane converts from CoreGraphics display - bounds, which use the same convention. + bounds, which use the same convention. **Foundation gives the types but + none of CoreGraphics' members** — there is no `.zero`, no `minX`, no + `Equatable` — so `Coordinates` provides `point`, `rect`, `bounds`, + `centre` and `emptyRect`, and nothing in `MWBCore` extends a CG type + (an extension would shadow the real API in `MWBMac`). All the maths is + done in 64-bit `Int` and truncated, matching C#'s `int` division for + every realistic screen while never trapping. - **Edge decisions are pure**: `Edge.evaluate(point:now:)` on a struct holding the rectangles, the mode flags and the last-jump time returns `nil` or a `Jump` naming the direction and the universal @@ -74,70 +98,349 @@ the Windows source again. ### Promised (to control-channel, input-capture, input-inject, app-shell) +As shipped 2026-09-16. Later lanes code against this, not against the +sketch this section used to hold. Seven files in `MWBCore`; nothing here +does I/O, reads a clock or logs. + ```swift -public final class PacketSequencer { public init(start: Int32); public func next() -> Int32; public var current: Int32 } -public final class ReplayFilter { public init(); public func isDuplicate(_ p: Packet) -> Bool } // ring of 50, 4 exemptions - -public enum SocketStatus: Int, Sendable { case na = 0, resolving, connecting, handshaking, error, forceClosed, invalidKey, timeout, sendError, connected } - -public struct SessionConfig: Sendable { localName: String; localID: UInt32; magic: UInt32; blockScreenSaver: Bool } -public enum SessionEvent: Sendable { - case status(SocketStatus) - case connected(peerName: String, peerID: UInt32) - case packet(Packet) // trusted application packet, framing already checked, dedup applied - case invalidKey // close the socket - case selfConnection // peer name == our name: close - case close +// Sequencing.swift — the two process-wide counters (§1.4) +public final class PacketSequencer { // not Sendable: app-wide, one queue + public init(start: Int32 = 0) // resumes the PackageID setting + public func next() -> Int32 // pre-increment, wrapping + public var current: Int32 { get } // persist this back } -public final class Session { - public init(config: SessionConfig, sequencer: PacketSequencer, replay: ReplayFilter, isClient: Bool) - public func start(now: TimeInterval) // queues the 10 Handshake packets - public func feed(_ plaintext: Data) // decrypted socket bytes; handles the 32-then-32 rule internally - public func send(_ p: Packet) // stamps Id/Src, frames, queues (any type; used by the app for Mouse/Keyboard/etc.) - public func tick(now: TimeInterval, userActive: Bool) // heartbeats, timeouts - public func drain() -> [Data] // bytes to write through CipherWriter, in order - public func events() -> [SessionEvent] - public var status: SocketStatus { get } - public var peerName: String?; public var peerID: UInt32? +public final class ReplayFilter { + public static let windowSize = 50 + public init() + public func isDuplicate(_ packet: Packet) -> Bool // 4 exempt types } -public struct Matrix: Sendable, Equatable { public var names: [String] (4); oneRow: Bool; wrap: Bool; init(string:), var string: String; slot(of:), neighbour(of:direction:live:) } -public struct MachinePool: Sendable { init(string:), var string; resolveID(name:) -> UInt32?; name(for:) -> String?; learn(name:id:now:); isAlive(id:now:) } -public enum MatrixPackets { static func encode(_ m: Matrix, sequencer:) -> [Packet] (4); static func apply(_ p: Packet, to: inout Matrix, pending: inout [String?]) -> Bool /* true when slot 4 commits */ } -public enum Direction { case left, right, up, down } -public struct Jump: Sendable { direction: Direction; targetSlot: Int; universal: (x: Int32, y: Int32) } -public struct EdgeConfig { desktop: CGRect; primary: CGRect; corners: [CGPoint]; blockCorners: Bool; moveRelatively: Bool } -public struct Edge { init(config:); mutating func evaluate(point: CGPoint, localIsController: Bool, controllerOwnsCursor: Bool, matrix: Matrix, liveNames: Set, now: TimeInterval) -> Jump? } -public enum Coordinates { toUniversal(_:in:) ; fromUniversal(_:desktop:primarySize:) ; relative bias encode/decode ; nextMachinePacket(...) } +// Session.swift — one TCP control connection (§3.2-§3.3) +public enum SocketStatus: Int, Sendable { + case na = 0, resolving, connecting, handshaking, error, forceClosed, + invalidKey, timeout, sendError, connected +} +public enum InvalidKeyReason: Sendable, Equatable { + case tooManyUntrustedPackets, handshakeAckMismatch +} +public enum SessionEvent: Sendable, Equatable { + case status(SocketStatus) + case connected(peerName: String, peerID: UInt32) + case packet(Packet) // trusted, framed, de-duplicated + case invalidKey(InvalidKeyReason) + case selfConnection + case close // always the last event +} +public struct SessionConfig: Sendable { + public var localName: String, magic: UInt32, localID: UInt32 + public var blockScreenSaver: Bool // 60 s vs 300 s heartbeats + public var peerNameHint: String? // DNS name; HandshakeAck wins + public init(localName:localID:magic:blockScreenSaver:peerNameHint:) +} +public final class Session { // not Sendable: one per connection + public static let fastHeartbeat: TimeInterval = 60 + public static let slowHeartbeat: TimeInterval = 300 + public static let untrustedPacketLimit = 10 + public init(config:sequencer:replay:isClient:) + public func start(now: TimeInterval) // queues 10 Handshake packets + public func feed(_ plaintext: Data) // 32-then-32 reassembly inside + public func noteReceiveError() // a 0-byte / short read + public func report(_ new: SocketStatus) // .resolving, .sendError, … + public func tick(now: TimeInterval, userActive: Bool) + public func send(_ packet: Packet) // stamps Id + Src, frames, queues + public func forward(_ packet: Packet) // already sequenced: Src only + public func probe() // Hi + public func sayGoodbye() // ByeBye + public func drain() -> [Data] // write these through CipherWriter + public func events() -> [SessionEvent] + public var status: SocketStatus { get } + public var peerName: String? { get } + public var peerID: UInt32? { get } + public var isOutbound: Bool { get } +} + +// MachinePool.swift — who is out there (§4.1) +public struct MachineInfo: Sendable, Equatable { public var name: String + public var id: UInt32; public var lastSeen: TimeInterval } +public struct MachinePool: Sendable, Equatable { + public static let maxMachines = 4 + public static let heartbeatTimeout: TimeInterval = 1500 // 25 min + public init(); public init(string: String, now: TimeInterval) + public var string: String { get } // "Name:Id,…" + public var all: [MachineInfo] { get } + public func machine(named: String) -> MachineInfo? // case-insensitive + public func resolveID(name: String) -> UInt32? // nil for ID.NONE + public func name(for id: UInt32) -> String? + public mutating func learn(_ name: String, keeping matrix: Matrix) -> Bool + public mutating func updateID(name:id:updateTimestamp:now:) -> Bool + public mutating func setDisconnected(name:now:) -> Bool + public mutating func setDisconnected(id:now:) -> Bool + public func isAlive(_ info:, now:, connectedIDs: Set) -> Bool + public mutating func resetDeadMachineIDs(localName:matrix:now:connectedIDs:firstLoaded:) +} + +// Matrix.swift — the four slots and their packets (§4.1-§4.2) +public enum Direction: Sendable, Equatable { case left, right, up, down } +public struct Matrix: Sendable, Equatable { + public static let slotCount = 4 + public private(set) var names: [String] // always exactly 4 + public var oneRow: Bool // MatrixOneRow + public var wrap: Bool // MatrixCircle / WrapMouse + public init(names: [String] = [], oneRow: Bool = true, wrap: Bool = true) + public init(string: String, oneRow: Bool = true, wrap: Bool = true) + public var string: String { get } + public mutating func setName(_ name: String, at slot: Int) + public func slot(of name: String) -> Int? + public func contains(_ name: String) -> Bool + public func live(connectedNames: Set) -> [String] // must include us + public func neighbour(of: String, direction: Direction, live: [String], + isReachable: (String) -> Bool) -> String? +} +public enum MatrixPackets { + public static func encode(_ matrix: Matrix) -> [Packet] // 4, slot order + public static func apply(_ packet: Packet, to: inout Matrix) -> Bool // true on slot 4 +} + +// Coordinates.swift — pixels ↔ 0..65535, and the two biases (§4.4) +public struct UniversalPoint: Sendable, Equatable { public var x, y: Int32 } +public enum Coordinates { + public static let universalMax: Int32 = 65535 + public static let relativeBias: Int32 = 100_000 // MOVE_MOUSE_RELATIVE + public static let pixelBias: Int32 = 300_000 // XY_BY_PIXEL + public static func toUniversal(_ p: CGPoint, in rect: CGRect) -> UniversalPoint + public static func fromUniversal(_ u: UniversalPoint, in rect: CGRect) -> CGPoint + public static func mouseMove(_ p: CGPoint, primary: CGRect) -> UniversalPoint + public static func absoluteMove(_ u:, desktop:, primary:) -> UniversalPoint + public static func tagRelative(dx: Int32, dy: Int32) -> UniversalPoint + public static func isRelative(_ u: UniversalPoint) -> Bool + public static func untagRelative(_ u: UniversalPoint) -> UniversalPoint + public static func tagPixels(_ p: CGPoint) -> UniversalPoint + public static func isPixels(_ u: UniversalPoint) -> Bool + public static func untagPixels(_ u: UniversalPoint) -> CGPoint + // CG helpers, because Foundation gives the types without the members: + public static func point(_ x: Int, _ y: Int) -> CGPoint + public static func rect(left: Int, top: Int, right: Int, bottom: Int) -> CGRect + public static func bounds(_ rect: CGRect) -> (left: Int, top: Int, right: Int, bottom: Int) + public static func centre(of rect: CGRect) -> CGPoint + public static let emptyRect: CGRect +} + +// Edge.swift — did the cursor leave, and where does it land (§4.3-§4.4) +public struct EdgeConfig: Sendable { // not Equatable: CGRect is not + public var desktop, primary: CGRect + public var corners: [CGPoint] // every monitor's four corners + public var blockCorners, moveRelatively: Bool + public init(desktop:primary:corners:blockCorners:moveRelatively:) +} +public struct Edge: Sendable { + public static let skipPixels = 1, jumpPixels = 2, cornerRadius = 100 + public static let jumpDebounce: TimeInterval = 0.1 + public var config: EdgeConfig + public private(set) var lastX, lastY: Int32 // the LastX/LastY settings + public init(config: EdgeConfig) + public mutating func crossing(at point: CGPoint, cursorIsLocal: Bool, + broadcasting: Bool, lastJump: TimeInterval, now: TimeInterval) -> Direction? + public func landing(direction:, from point:, targetIsLocal:, cursorIsLocal:) + -> UniversalPoint +} + +// Switching.swift — which machine has the keyboard and mouse +public struct Jump: Sendable, Equatable { + public var direction: Direction; public var targetID: UInt32 + public var targetName: String; public var landing: UniversalPoint +} +public enum SwitchAction: Sendable, Equatable { + case send(Packet) // already addressed + case parkCursor(byHideMouseMessage: Bool) + case moveCursor(UniversalPoint) // pixel-tagged means pixels + case releaseAllKeys + case desMachineChanged(id: UInt32, name: String?) + case persistMatrix, persistMachinePool, reopenSockets + case remoteClipboardWanted +} +public final class Switcher { // not Sendable: app-wide + public init(localName:localID:matrix:pool:edge:sequencer:) + public let localName: String; public let localID: UInt32 + public private(set) var matrix: Matrix + public private(set) var pool: MachinePool + public var edge: Edge // app updates .config on display change + public var connectedIDs: Set // maintained by control-channel + public var connectedNames: Set + public private(set) var desMachineID: UInt32 + public private(set) var desMachineName: String? + public private(set) var newDesMachineID: UInt32 + public var isBroadcasting: Bool { get } + public func isConnected(to id: UInt32) -> Bool + public func crossing(at point: CGPoint, now: TimeInterval) -> Jump? + public func prepareToSwitch(to:landing:now:) -> [SwitchAction] + public func switchToMachine(named:now:) -> [SwitchAction] + public func switchToBroadcast(_ on: Bool, centerCursor: Bool) -> [SwitchAction] + public func nextMachinePacket(toController:target:landing:now:) -> Packet? + public func learn(from packet: Packet, now:) -> [SwitchAction] + public func applyMatrix(_ packet: Packet) -> [SwitchAction] + public func handleByeBye(_ packet: Packet, now:) -> [SwitchAction] + public func handleHideMouse() -> [SwitchAction] + public func connectionLost(id:now:) -> [SwitchAction] + public func setMatrix(_ new: Matrix) -> [SwitchAction] +} ``` -Exact spelling may change during the lane; this README is updated in -the same change and later lanes code against it. +Rules the consuming lanes must honour: + +- **Nothing reaches `.packet` before the handshake.** `Session` delivers + application packets only from a trusted connection, after `Framing.open` + and after the replay ring (CLAUDE.md invariant 2). `.close` is always the + last event a session emits; close the socket and drop the session. +- **One `PacketSequencer` and one `ReplayFilter` per process**, shared by + every `Session`, as on Windows. Neither is `Sendable`; nor are `Session` + and `Switcher`. Everything in this lane lives on one queue. +- **`Switcher` never does I/O.** It returns `[SwitchAction]`; the app + performs them in order. A `.send` packet is already sequenced and + addressed, so it goes to every connection through `Session.forward(_:)`, + **not** `Session.send(_:)` — one broadcast must keep one `Id` across a + peer's two connections or the receiver's replay ring will not collapse + the duplicate. +- **`Matrix.live(connectedNames:)` must be given the local machine's own + name**, because the Windows `IsConnectedTo` answers yes for it without a + socket. `Switcher.crossing` adds it; a direct caller must too. +- **`Edge.crossing` reads `lastJump` but never writes it.** The debounce + clock is `Switcher`'s, set by `prepareToSwitch`. + +### Requested of control-channel (open) + +1. The duplicate-client-socket policy (`SocketStuff.cs:1980-2004`) and the + ">10 failed attempts from one endpoint ⇒ quit" counter + (`SocketStuff.cs:1482-1499`) are keyed by remote endpoint and belong to + the channel; `Session` reports `.invalidKey` and `.close` and counts + nothing across connections. ## Status / TODO -- [ ] `Sources/MWBCore/Sequencing.swift`: `PacketSequencer`, `ReplayFilter` +- [x] `Sources/MWBCore/Sequencing.swift`: `PacketSequencer`, `ReplayFilter` (`Common.cs:906`, `Receiver.cs:40-82`). -- [ ] `Sources/MWBCore/Session.swift`: state machine, handshake, trust +- [x] `Sources/MWBCore/Session.swift`: state machine, handshake, trust guards, 32-then-32 reassembly with the invalid-is-64-bytes rule (protocol §10.1), heartbeats/liveness, `Hi`/`ByeBye` (`SocketStuff.cs:1261-1565`, `Common.cs:499-513, 662-676, 822-847`, `Receiver.cs:200-270`). -- [ ] `Sources/MWBCore/Matrix.swift`: `Matrix`, `MatrixPackets`, live +- [x] `Sources/MWBCore/Matrix.swift`: `Matrix`, `MatrixPackets`, live matrix (`MachineStuff.cs:883-1006, 935-945`). -- [ ] `Sources/MWBCore/MachinePool.swift`: pool, learning, liveness +- [x] `Sources/MWBCore/MachinePool.swift`: pool, learning, liveness (`MachinePool.cs`, `MachinePoolHelpers.cs`, `MachineStuff.cs:712-777`). -- [ ] `Sources/MWBCore/Switching.swift`: `desMachineID` / ALL mode / + Learning itself lives on `Switcher` (it touches the matrix too); the + pool owns the storage, the string form and the timeouts. +- [x] `Sources/MWBCore/Switching.swift`: `desMachineID` / ALL mode / `MachineSwitched` / `HideMouse` emission / `NextMachine` (`MachineStuff.cs:1030-1050`, `Common.cs:559-585`, `Event.cs:212-231`, `Receiver.cs:156-170, 284-291, 383-388`). -- [ ] `Sources/MWBCore/Edge.swift` + `Coordinates.swift`: §4.3–§4.4 +- [x] `Sources/MWBCore/Edge.swift` + `Coordinates.swift`: §4.3–§4.4 (`MachineStuff.cs:181-283, 325-478`, `Event.cs:105-113`, `InputSimulation.cs:160-173`, `Receiver.cs:147-153`). -- [ ] `docs/protocol.md`: append a §10.2 with anything learned, cited. +- [x] `docs/protocol.md`: append a §10.2 with anything learned, cited. + +Not done, deliberately: + +- **`Heartbeat_ex` key propagation** (`Receiver.cs:210-243`): out of scope + per README D6 — the key is typed on both sides. `Heartbeat_ex` is + accepted, refunds the untrusted budget exactly as `Heartbeat` does, and + is delivered to the app, which ignores it. +- **The `Hi` receive path**: nothing to port. Windows never processes a + `Hi` packet at all (protocol §10.2 note 2); `Session.probe()` exists for + the send side, which is the part that has an effect. +- **`SwitchLocation.Count`** (`MouseLocation.cs`, `InputHook.cs:267-283`): + the counter that makes the *next* hook callback report the switch + location instead of the real cursor is a property of the event tap, not + of this lane. `SwitchAction.moveCursor` carries the location; how many + callbacks consume it is `input-capture`'s to decide. +- **`ReleaseAllKeys`'s 2 s rate limit** (`InitAndCleanup.cs:214-221`): it + guards a `SendInput` burst, so it belongs with the injector in + `input-inject`. This lane only says `.releaseAllKeys`. ## Work log +### 2026-09-16 — dev (Opus) + +Ported all seven files; `tools/gates.sh` green. One sentence each: + +- `Sequencing.swift` (83) — the two process-wide counters that decide a + packet's identity. +- `Session.swift` (386) — one connection's handshake, trust gate, + reassembly and heartbeat. +- `MachinePool.swift` (208) — who is out there, in the persisted + `Name:Id,…` form. +- `Matrix.swift` (242) — the four slots, the neighbour search and the four + `Matrix` packets. +- `Coordinates.swift` (201) — pixels ↔ 0..65535 and the two biases. +- `Edge.swift` (144) — did the cursor leave the screen, and where does it + land. +- `Switching.swift` (345) — which machine has the keyboard and mouse. + +Decisions and deviations: + +1. **`Switcher` is a new type the plan did not name.** The plan put + switching in `Switching.swift` without saying what owned it. Matrix, + pool and `desMachineID` are one piece of state on Windows (three sets of + `MachineStuff` statics behind one lock), and every switch reads all + three, so they are one class here. It returns `[SwitchAction]` and + performs nothing, which is what keeps `MWBCore` I/O-free. +2. **`Session` is per-connection; the pool and matrix are not.** Windows + runs `AddToMachinePool` from inside the receive loop against global + state. Splitting it this way is the only change of shape in the lane and + it is the one CLAUDE.md asks for: `Session.feed` classifies and reports, + `Switcher` decides. `Receiver.cs`'s big `switch` is therefore not ported + as a switch — the app dispatches `.packet` events to `Switcher`, to the + injector, or to the clipboard lane later. +3. **Heartbeats are per session, not per broadcast** — see Assumptions. + `Session.forward(_:)` was added so the app can still send one sequenced + broadcast to several connections where that matters (matrix + replication, `HideMouse`, `MachineSwitched`). +4. **`CGRect`/`CGPoint` under Foundation alone are bare C structs**: no + `.zero`, no `minX`, no `Equatable`, though they *are* `Sendable`. Rather + than extend a CoreGraphics type from `MWBCore` (which would shadow the + real API in `MWBMac`) the five helpers live on `Coordinates`. + `EdgeConfig` consequently cannot be `Equatable`. This is a change to + topo.md handshakes 4 and 6 in spelling only — the coordinate convention + is unchanged — and is flagged for the lead. +5. **`Edge.crossing` returns a `Direction`, not a `Jump`.** The planning + sketch had `Edge.evaluate` take the matrix and the live names. Keeping + `Edge` to pure geometry made both it and `Matrix.neighbour` testable by + eye against the Windows source, and put the one place that needs all + three (`Switcher.crossing`) in the file that owns the state. +6. **The two-row neighbour chains stop at the first matching arm.** Found + while porting: the arms are `else if`, so an arm whose target has no id + ends the search, whereas the one-row loops step over such a slot. Also + found: `MoveDown` is two chains where `MoveUp` is one. Both reproduced, + both written up as protocol §10.2 notes 5 and 6. +7. **`Hi` is dead on the receive side** (§10.2 note 2) and **a + `Handshake`'s `Id`/`Src`/`Des` are random** (§10.2 note 1). The second + one matters: a receiver that learned the peer id from a `Handshake` + would learn garbage. +8. **Time is seconds.** Windows counts milliseconds; every constant is + divided by 1000 in the code and cited with its millisecond original. + +Verified by hand (no test suites, per CLAUDE.md — the user tests the app). +A throwaway `swiftc` build of `MWBCore` plus a 63-assertion scratchpad +program, all passing: matrix string round-trips and the one-row/two-row +neighbour search including wrap, empty and unreachable slots; the four +`Matrix` packets replicating a two-row wrapping matrix into a fresh +`Matrix`; pool string round-trip, case-insensitive resolution, duplicate-id +reset and the 25-minute liveness rule; universal-value scaling against the +C# integer expression written out by hand, the `Point.Empty` quirk and both +bias round-trips; every branch of `crossing` (desktop vs primary rectangle, +ALL mode, the 100 ms debounce, corner blocking) and a landing point two +pixels inside the far edge; a two-`Session` loopback that reaches +`Connected` both ways, learns both names and ids, delivers a `Mouse` packet +once and drops its replay; a **wrong-key** loopback that ends in +`InvalidKey` + `.close` having delivered no `.packet` at all; a +self-connection closing; heartbeat timing at 59 s / 61 s / 130 s with +`Awake` vs `Heartbeat`; and a `Switcher` edge crossing that moves control, +emits `MachineSwitched`, comes home with `HideMouse`, and rate-limits +`NextMachine` to 100 ms with the target id in `WheelDelta`. + +No macOS permission was requested, no `CGEvent` was posted, no pasteboard +was touched. Nothing in these files logs, so no key material can leak +through one. + ## QA log ## Review