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]>
31 KiB
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.
Sessionowns no socket, timer or thread. The caller hands it decrypted packet bytes (feed), asks what to send (drain() -> [Data], already framed and ready forCipherWriter) and what happened (events), and callstick(now:)from its own timer. Time is aTimeIntervalin 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
Sessionper TCP connection, client or server side — Windows runs the sameMainTCPRoutinefor 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 thecontrol-channellane applies its own policy, as this README already said it would. - Trust is per connection and gates everything. Until the
HandshakeAcknonce check passes, the only packetsSessionacts on areHandshake/HandshakeAck; other packets are counted and after 10 the session reports.invalidKeyand 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): aPacketSequencerand aReplayFilterare created once by the app and shared by everySession. The sequencer's start value comes from the persistedPackageIDsetting and the app stores it back; this lane exposescurrentfor that. - Sequence once, distribute unchanged (contracts C1). Application
packets are stamped by the app and handed to each target session via
forward(_:);Sessionstamps only the packets it originates (handshake, heartbeats,Hi,ByeBye). There is no public API to send an unstamped application packet on one connection. - Each
Sessionbeats for its own connection. Windows broadcasts one heartbeat from a global timer to every socket, so a peer pair's two connections carry the sameIdand the receiver's replay ring collapses the second (Common.cs:906-916). Ours stamps a freshIdper session, so a peer processes both copies.AddToMachinePoolis 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) whenBlockScreenSaveris on, elsecount % 3000(300 s) (frmScreen.cs:566-575);Awakeif the user was active within the window, elseHeartbeat(Common.cs:499-513). Machine liveness is 25 min (MachineStuff.cs:32).Heartbeat_exkey propagation is not ported (README D6); those packets are accepted and ignored. MatrixandMachinePoolare value types with the exact persisted string forms (MachineMatrixStringcomma-joined,Name:Id,Name:Id,Name:Id,Name:Id,MachinePoolHelpers.cs:16-43,MachinePool.cs:287-301), soSettingscan 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 fourMatrixpackets — reported asSwitchActions, the app decides to persist and reconnect. This lives onSwitcher, not onSession: the pool and matrix are app-wide and a session is per-connection. - Geometry uses
CGRect/CGPointfrom Foundation (no CoreGraphics import) in the Windows convention: top-left origin, y down, integer pixels. Theinput-capturelane converts from CoreGraphics display bounds, which use the same convention. Foundation gives the types but none of CoreGraphics' members — there is no.zero, nominX, noEquatable— soCoordinatesprovidespoint,rect,bounds,centreandemptyRect, and nothing inMWBCoreextends a CG type (an extension would shadow the real API inMWBMac). All the maths is done in 64-bitIntand truncated, matching C#'sintdivision 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 returnsnilor aJumpnaming 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 inCoordinates; nothing else in the app should know the numbers.
Handshakes
Consumed
wire-core:Packet,PackageType,Framing,MachineID, exactly as published indocs/features/wire-core/README.mdHandshakes.
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.
// 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
.packetbefore the handshake.Sessiondelivers application packets only from a trusted connection, afterFraming.openand after the replay ring (CLAUDE.md invariant 2)..closeis always the last event a session emits; close the socket and drop the session. - One
PacketSequencerand oneReplayFilterper process, shared by everySession, as on Windows. Neither isSendable; nor areSessionandSwitcher. Everything in this lane lives on one queue. Switchernever does I/O. It returns[SwitchAction]; the app performs them in order. A.sendpacket is already sequenced and addressed, so it goes to every connection throughSession.forward(_:), notSession.send(_:)— one broadcast must keep oneIdacross 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 WindowsIsConnectedToanswers yes for it without a socket.Switcher.crossingadds it; a direct caller must too.Edge.crossingreadslastJumpbut never writes it. The debounce clock isSwitcher's, set byprepareToSwitch.
Requested of control-channel (open)
- 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;Sessionreports.invalidKeyand.closeand counts nothing across connections.
Status / TODO
Sources/MWBCore/Sequencing.swift:PacketSequencer,ReplayFilter(Common.cs:906,Receiver.cs:40-82).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 matrix (MachineStuff.cs:883-1006, 935-945).Sources/MWBCore/MachinePool.swift: pool, learning, liveness (MachinePool.cs,MachinePoolHelpers.cs,MachineStuff.cs:712-777). Learning itself lives onSwitcher(it touches the matrix too); the pool owns the storage, the string form and the timeouts.Sources/MWBCore/Switching.swift:desMachineID/ ALL mode /MachineSwitched/HideMouseemission /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 (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.
Not done, deliberately:
Heartbeat_exkey propagation (Receiver.cs:210-243): out of scope per README D6 — the key is typed on both sides.Heartbeat_exis accepted, refunds the untrusted budget exactly asHeartbeatdoes, and is delivered to the app, which ignores it.- The
Hireceive path: nothing to port. Windows never processes aHipacket 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.moveCursorcarries the location; how many callbacks consume it isinput-capture's to decide.ReleaseAllKeys's 2 s rate limit (InitAndCleanup.cs:214-221): it guards aSendInputburst, so it belongs with the injector ininput-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 persistedName:Id,…form.Matrix.swift(242) — the four slots, the neighbour search and the fourMatrixpackets.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:
Switcheris a new type the plan did not name. The plan put switching inSwitching.swiftwithout saying what owned it. Matrix, pool anddesMachineIDare one piece of state on Windows (three sets ofMachineStuffstatics behind one lock), and every switch reads all three, so they are one class here. It returns[SwitchAction]and performs nothing, which is what keepsMWBCoreI/O-free.Sessionis per-connection; the pool and matrix are not. Windows runsAddToMachinePoolfrom 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.feedclassifies and reports,Switcherdecides.Receiver.cs's bigswitchis therefore not ported as a switch — the app dispatches.packetevents toSwitcher, to the injector, or to the clipboard lane later.- 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). CGRect/CGPointunder Foundation alone are bare C structs: no.zero, nominX, noEquatable, though they areSendable. Rather than extend a CoreGraphics type fromMWBCore(which would shadow the real API inMWBMac) the five helpers live onCoordinates.EdgeConfigconsequently cannot beEquatable. 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.Edge.crossingreturns aDirection, not aJump. The planning sketch hadEdge.evaluatetake the matrix and the live names. KeepingEdgeto pure geometry made both it andMatrix.neighbourtestable by eye against the Windows source, and put the one place that needs all three (Switcher.crossing) in the file that owns the state.- 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:MoveDownis two chains whereMoveUpis one. Both reproduced, both written up as protocol §10.2 notes 5 and 6. Hiis dead on the receive side (§10.2 note 2) and aHandshake'sId/Src/Desare random (§10.2 note 1). The second one matters: a receiver that learned the peer id from aHandshakewould learn garbage.- 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:
-
The 10-untrusted-packets rule doesn't count read errors, unlike Windows.
SocketStuff.cs:1330-1338gives a bad/short read its ownerrCount(closes after 6), but thatError-typed package then also falls through theif (package.Type == PackageType.Handshake)check (false) into the untrustedpackageCountbranch (:1379-1521, reached for any non-Handshaketype includingError) — so on Windows a run of malformed reads during handshake also spends the same 10-packet budget as garbage packets, and can tripInvalidKey(oncepackageCount > 5) or the full ">=10⇒ send 10Invalid, close" path before 6 read errors accumulate.Session.noteReceiveError()(Sources/MWBCore/Session.swift:192-199) is wired to a separate counter that never touchescountUntrusted/untrustedCount, so the port always closes a bad-read run via.errorafter 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. -
Switcher.learnpersists the pool on every heartbeat from an already-known peer; Windows does not.AddToMachinePool(MachineStuff.cs:712-745) returnsmachineInfo.Nameimmediately inside theTryFindMachineByNamebranch, before reachingMachineStuff.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 writeMachinePoolto 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.persistMachinePoolfrom that branch) or a documented deviation. -
SwitchAction.parkCursordoesn't carry what Windows needs to decide whether to actually move the OS cursor.HideMouseCursor(Common.cs:1482-1496) only callsSetCursorPoswhen(desMachineID != Common.MachineID && desMachineID != ID.ALL) || byHideMouseMessage.SwitchToMachine(MachineStuff.cs:1008-1028) callsHideMouseCursor(false)after settingCommon.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 whatProcessByeByeMessage,Common.cs:622-625, does by callingSwitchToMachine(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 checkdesMachineID != localID && != ALLbefore actually moving the OS cursor. A straightforwardinput-injectimplementation — 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 atargetIsLocal/shouldMoveCursorflag to the action, or spelling out the gating condition in the doc comment and in acontrol-channel"consumers must" rule alongside the existing ones in Handshakes.
Verdict: REWORK