Files
mac_without_borders/docs/features/session-matrix/README.md
T
lucioandClaude Fable 5.1 08b243a29a 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]>
2026-09-16 00:54:33 -07:00

561 lines
31 KiB
Markdown

# session-matrix
## Goal
All the protocol *logic* above the bytes and below the sockets, in
`MWBCore` with no I/O: the per-connection `Session` state machine
(handshake, trust, dedup, heartbeats, liveness — `docs/protocol.md` §1.4,
§3.2–§3.3), the machine model (`Matrix`, `MachinePool`, live matrix,
`Matrix` packet replication — §4.1–§4.2), switching (`desMachineID`, ALL
mode, `MachineSwitched`, `NextMachine`) and the pure geometry of edge
detection and coordinate normalisation (§4.3–§4.4). The `control-channel`
lane feeds sockets into `Session`; the `input-capture` lane feeds cursor
points into `Edge`. Both must be able to use this code without reading
the Windows source again.
## Assumptions
- **Sans-I/O.** `Session` owns no socket, timer or thread. The caller
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` 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
10 the session reports `.invalidKey` and asks to close
(`SocketStuff.cs:1387-1406`). Application packets are surfaced to the
caller only from a trusted session (CLAUDE.md invariant 2).
- **Sequence numbers and the replay ring are process-wide**, as on
Windows (`Common.cs:906`, `Receiver.cs:40-82`): a `PacketSequencer`
and a `ReplayFilter` are created once by the app and shared by every
`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
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
was active within the window, else `Heartbeat` (`Common.cs:499-513`).
Machine liveness is 25 min (`MachineStuff.cs:32`). `Heartbeat_ex`
key propagation is **not** ported (README D6); those packets are
accepted and ignored.
- **`Matrix` and `MachinePool` are value types** with the exact
persisted string forms (`MachineMatrixString` comma-joined,
`Name:Id,Name:Id,Name:Id,Name:Id`, `MachinePoolHelpers.cs:16-43`,
`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, 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. **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
0..65535 landing point, computed by the four-case rule of §4.4. The
debounce (100 ms, `MachineStuff.cs:217`) lives here, not in the tap.
- **Relative-move biases** (`MOVE_MOUSE_RELATIVE = 100000`,
`XY_BY_PIXEL = 300000`, `Event.cs:32-33`) are encoded/decoded in
`Coordinates`; nothing else in the app should know the numbers.
## Handshakes
### Consumed
- `wire-core`: `Packet`, `PackageType`, `Framing`, `MachineID`, exactly
as published in `docs/features/wire-core/README.md` Handshakes.
### 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
// 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 ReplayFilter {
public static let windowSize = 50
public init()
public func isDuplicate(_ packet: Packet) -> Bool // 4 exempt types
}
// 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<UInt32>) -> 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>) -> [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<UInt32> // maintained by control-channel
public var connectedNames: Set<String>
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]
}
```
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
- [x] `Sources/MWBCore/Sequencing.swift`: `PacketSequencer`, `ReplayFilter`
(`Common.cs:906`, `Receiver.cs:40-82`).
- [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`).
- [x] `Sources/MWBCore/Matrix.swift`: `Matrix`, `MatrixPackets`, live
matrix (`MachineStuff.cs:883-1006, 935-945`).
- [x] `Sources/MWBCore/MachinePool.swift`: pool, learning, liveness
(`MachinePool.cs`, `MachinePoolHelpers.cs`, `MachineStuff.cs:712-777`).
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`).
- [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`).
- [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 64-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
### 2026-09-16 — QA (Sonnet)
Process: `tools/gates.sh` (green — swift-format lint --strict, MWBCore
layering, `swift build -Xswiftc -warnings-as-errors`), then every
Status/TODO tick read against the cited Windows source
(`SocketStuff.cs` `MainTCPRoutine` 1261-1565, `Receiver.cs`,
`Common.cs`, `MachineStuff.cs`, `MachinePool.cs`/`MachinePoolHelpers.cs`,
`Event.cs`, `Helper.cs`, `frmScreen.cs`), then all seven files read
top to bottom for CLAUDE.md size/layering/naming/force-unwrap/dead-code
concerns, then a check that nothing logs key material or acts on a
packet before trust.
Verified faithful, worth recording since they were the areas flagged
for special attention: the nonce-complement handshake and trust gate
(`Session.swift:159-169, 267-339` vs `SocketStuff.cs:1269-1480` —
`Handshake` always answered regardless of trust, `HandshakeAck` after
trust silently skipped, self-connection close); the untrusted-packet
give-back for `Mouse`/`Heartbeat`/`Heartbeat_ex` past 5
(`Session.swift:303-313` vs `:1502-1521`); the 32-then-32 reassembly
including the invalid-is-64-bytes rule (`Session.swift:174-190`); the
dedup ring's four exemptions (`Sequencing.swift:76-82` vs
`Receiver.cs:58-61`); the one-row vs two-row neighbour search,
including the ascending/descending asymmetry between `MoveRight` and
`MoveLeft`, the "arm chosen before reachability is tested" two-row
quirk, and `MoveDown`'s wrap-overwrites-straight quirk
(`Matrix.swift:108-190` vs `MachineStuff.cs:288-673`, byte-for-byte
arm order checked); `LiveMachineMatrix` blanking in one-row mode only
(`Matrix.swift:94-99` vs `:935-945`); the four-case landing rectangle
rule and the per-direction opposite-edge landing offsets
(`Edge.swift:125-135` vs `MachineStuff.cs:385-421` and the identical
arms in `MoveRight`/`Left`/`Up`/`Down`); the square (not circular)
100 px corner block and the 100 ms debounce ordering
(`Edge.swift:82-100` vs `:203-234`); the relative-move and pixel
biases including the asymmetric `>`/`>=` bias tests
(`Coordinates.swift:109-150` vs `Event.cs:32-33`, `InputHook.cs:271-312`,
`Helper.cs:107-110`); `NextMachine`'s id-in-`WheelDelta` and 100 ms
rate limit (`Switching.swift:229-239` vs `Common.cs:516-539`); the
`Matrix` packet slot/flags encoding and the slot-4 commit rule
(`Matrix.swift:210-241` vs `MachineStuff.cs:952-1006`). No key material
or decrypted keystroke is logged anywhere in these seven files (grepped
for `log`/`Log`/`print`); `Session.deliver` is reached only from the
trusted branch, and nothing else in `Session`/`Switcher` synthesizes
input or touches a pasteboard (both are sans-I/O by construction).
`swift-format`, layering and file/function sizes are all within the
CLAUDE.md targets; no force-unwraps, `try!`, `fatalError` or
`precondition` in any of the seven files.
Three findings, none touching wire bytes or the trust boundary itself:
1. **The 10-untrusted-packets rule doesn't count read errors, unlike
Windows.** `SocketStuff.cs:1330-1338` gives a bad/short read its own
`errCount` (closes after 6), but that `Error`-typed package then
*also* falls through the `if (package.Type == PackageType.Handshake)`
check (false) into the untrusted `packageCount` branch
(`:1379-1521`, reached for any non-`Handshake` type including
`Error`) — so on Windows a run of malformed reads during handshake
also spends the same 10-packet budget as garbage packets, and can
trip `InvalidKey` (once `packageCount > 5`) or the full
"`>=10` ⇒ send 10 `Invalid`, close" path before 6 read errors
accumulate. `Session.noteReceiveError()`
(`Sources/MWBCore/Session.swift:192-199`) is wired to a separate
counter that never touches `countUntrusted`/`untrustedCount`, so the
port always closes a bad-read run via `.error` after 6, never via
`.invalidKey`, and never spends any of the 10-packet budget on it.
Not a trust-boundary or wire bug — the connection still closes either
way — but it is a real behavioural divergence in the exact rule the
brief called out for special attention.
2. **`Switcher.learn` persists the pool on every heartbeat from an
already-known peer; Windows does not.** `AddToMachinePool`
(`MachineStuff.cs:712-745`) returns `machineInfo.Name` immediately
inside the `TryFindMachineByName` branch, *before* reaching
`MachineStuff.UpdateMachinePoolStringSetting()` (the call sits after
the whole if/else, reachable only from the "new machine" branch that
falls through). `Switching.swift:251-258` (`Switcher.learn`) returns
`[.persistMachinePool]` for the known-machine branch too, so the
port asks the app to write `MachinePool` to disk on every heartbeat
cadence tick from a peer it already knows (every 60 s or 300 s, per
connection), not just when a new machine is learned. Harmless
(idempotent, no wire effect) but extra I/O Windows doesn't do, and
worth a one-line fix (drop `.persistMachinePool` from that branch) or
a documented deviation.
3. **`SwitchAction.parkCursor` doesn't carry what Windows needs to
decide whether to actually move the OS cursor.** `HideMouseCursor`
(`Common.cs:1482-1496`) only calls `SetCursorPos` when
`(desMachineID != Common.MachineID && desMachineID != ID.ALL) ||
byHideMouseMessage`. `SwitchToMachine` (`MachineStuff.cs:1008-1028`)
calls `HideMouseCursor(false)` *after* setting
`Common.DesMachineID = id`, so on Windows the real cursor is parked
only when switching control to a **remote** machine — switching
control back to the local machine (exactly what
`ProcessByeByeMessage`, `Common.cs:622-625`, does by calling
`SwitchToMachine(MachineName.Trim())` when the controlling peer says
goodbye) leaves the local cursor alone. `Switcher.switchToMachine`
(`Switching.swift:189-203`) always appends
`.parkCursor(byHideMouseMessage: false)`, and neither the action's
payload nor its doc comment (`Switching.swift:31-34`) tells a
consumer it must additionally check `desMachineID != localID &&
!= ALL` before actually moving the OS cursor. A straightforward
`input-inject` implementation — built, per this README's stated
goal, "without reading the Windows source again" — would park the
real cursor at the primary screen's top-centre every time control
returns home (e.g. on every peer disconnect), which is a visible,
incorrect cursor jump for the local user. Recommend either adding a
`targetIsLocal`/`shouldMoveCursor` flag to the action, or spelling
out the gating condition in the doc comment and in a `control-channel`
"consumers must" rule alongside the existing ones in Handshakes.
Verdict: REWORK