Round-2 QA finding: the channel reset beatInputEventCount on its own clock, out of phase with every connection's heartbeat instant, so a session could send Heartbeat (20) where Windows sends Awake (21) — and Awake is what drives the peer's Common.HumanBeingDetected() (Receiver.cs:245-248), the default-on BlockScreenSaver mechanism. Windows's beat is the send: SendAwakeBeat() compares lastRealInputEventCount against Event.RealInputEventCount and re-records it in the same call (Common.cs:542-559). So the comparison belongs at the send. Session.tick(now:userActive:) becomes Session.tick(now:inputEventCount:), taking the raw process-wide counter (Event.cs:51-55, InputHook.cs:223, 345) and keeping its own beatInputEventCount — Common.lastRealInputEventCount, Common.cs:543 — recorded on both branches (:558). ControlChannel loses lastBeatAt and beatInputEventCount entirely; noteUserActivity() only increments the counter and tick() hands the same value to every connection. No userActive-shaped name is left in Sources. Sources/MWBCore/Session.swift is session-matrix's file, edited for this fix with the lead's authorisation, as is that lane's Handshakes section. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
784 lines
46 KiB
Markdown
784 lines
46 KiB
Markdown
# control-channel
|
||
|
||
## Goal
|
||
|
||
The sockets. `MWBNet` turns `Session` + `CipherWriter`/`CipherReader`
|
||
into live TCP connections on port+1 (`docs/protocol.md` §3.1, §3.3, §7):
|
||
an `NWListener` for inbound peers, one outbound `NWConnection` per
|
||
non-local matrix name with the Windows retry cadence, name resolution
|
||
with `Name2IP`, the keep-one-client-per-peer rule, reconnect triggers,
|
||
and the bounded queues and stall detection that contracts C2/C3
|
||
require. It reports `SessionEvent`s and connection lifecycle to an
|
||
`EngineSink` protocol; the Engine itself arrives in the app-shell lane.
|
||
No packet is interpreted here.
|
||
|
||
## Assumptions
|
||
|
||
- **Network.framework only** (`NWListener`, `NWConnection`,
|
||
`NWPathMonitor`, `NWEndpoint`); no BSD sockets except `getaddrinfo`
|
||
inside `Resolver` for the `Name2IP`-free path, because
|
||
`NWConnection(host:port:)` already resolves names — prefer it and use
|
||
`getaddrinfo` only for the reverse-lookup validation option.
|
||
*(Shipped differently: `Resolver` does every lookup with `getaddrinfo`
|
||
and hands `NWConnection` a numeric address. See the work log — Windows
|
||
resolves the name itself, filters the address list and dials each
|
||
surviving address in parallel, and neither filter nor the parallel dial
|
||
can be expressed if the connection resolves the name for us.)*
|
||
- **Two listeners are the protocol's shape** (`SocketStuff.cs:475-495`):
|
||
this lane opens the control listener on `port + 1` only; the
|
||
clipboard listener on `port` is the clipboard lane's.
|
||
- **Per connection**: one `PeerConnection` owning `NWConnection`,
|
||
`Session`, `CipherWriter`, `CipherReader`, one serial `DispatchQueue`,
|
||
a bounded outbound queue (512 framed packets) and a 500 ms send
|
||
timeout (`SocketStuff.cs:1286`). The first bytes written are
|
||
`CipherWriter.header` (48 bytes); the first bytes read go into
|
||
`CipherReader`, whose output feeds `Session.feed`. A read that returns
|
||
fewer than 32 bytes at EOF or errors calls
|
||
`Session.noteReceiveError(bytesReceived:)` with the real count
|
||
(contracts, session-matrix Review). **The read is sized to make that
|
||
exact**: 48 bytes once for the peer's preamble, then exactly 32 bytes
|
||
per read, which after the preamble is exactly one Windows
|
||
`ReadEx(buf, 0, PACKAGE_SIZE)` (`docs/protocol.md` §10.3 note 8).
|
||
- **Outbound clients**: for every matrix name that is not the local
|
||
name and has no connected client, dial `name:port+1`; retry every 1 s
|
||
until 30 s have passed (`SocketStuff.cs:158, 276, 1179-1198`), then
|
||
report `.timeout` and wait for the next reconnect trigger. Socket
|
||
options mirror Windows: `NoDelay`, 320 000-byte buffers where
|
||
Network.framework exposes them (`SocketStuff.cs:1283-1286`) — it
|
||
exposes none, so only `NoDelay` is set and the bounded outbox is what
|
||
limits queued bytes.
|
||
- **Name resolution filters each address group on its own**
|
||
(`SocketStuff.cs:928-944, 950, 989-1044`): `Resolver.addresses` runs the
|
||
same control flow `StartNewTcpClient` does, not a filter over the union.
|
||
The `Name2IP` mappings are checked against the same-subnet rule alone,
|
||
and when that check fails Windows returns from `StartNewTcpClient`
|
||
**before** `Dns.GetHostEntry` is called (`:934-937, 950`) — so the name
|
||
is not dialled at all that round and we return `[]`. The DNS group is
|
||
filtered by the reverse lookup and then gets its own same-subnet check
|
||
(`:1037-1040`); failing it drops the DNS addresses only, leaving the
|
||
mapped ones, which Windows has already handed to
|
||
`StartNewTcpClientThread` by then. The reverse lookup never applies to a
|
||
user-supplied mapping (`docs/protocol.md` §10.3 note 6).
|
||
- **Keep one client per peer** (`SocketStuff.cs:1980-2004`): when a
|
||
second connection to the same peer name reaches `.connected`, the
|
||
later *client* connection is closed; inbound (server-side) connections
|
||
are always kept. The channel therefore ends with at most one outbound
|
||
and one inbound connection per peer, and forwards every app packet to
|
||
both — the receiver's replay ring collapses the pair (contracts C1).
|
||
- **Machine-id collision** (`SocketStuff.cs:1984-1992`): if a trusted
|
||
peer reports our own id **over an outbound connection**, the channel
|
||
reports `.idCollision` to the sink; the app regenerates and calls
|
||
`reopenAll()`. Windows force-closes *every* socket in that branch, not
|
||
just the offending one (`docs/protocol.md` §10.3 note 3), and so do we.
|
||
Like the duplicate-client rule, this is client-only: `UpdateTcpSockets`
|
||
runs the whole block under `status == Connected && tcp.IsClient`
|
||
(`:1980-1981`), so an id reported over an inbound connection is
|
||
silently tolerated, here as there.
|
||
- **Failure budget per endpoint** (`SocketStuff.cs:1482-1499`): more
|
||
than 10 `.invalidKey` outcomes from the same remote address ⇒ report
|
||
`.peerRejected(address)` and stop dialling it until `reopenAll()`.
|
||
Keyed by address only, and counting both invalid-key reasons — Windows
|
||
keys by address *and port* and counts only the mismatched ack, which
|
||
makes its counter almost unreachable (`docs/protocol.md` §10.3 note 5).
|
||
- **Reconnect triggers** (§3.3): `NWPathMonitor` status change, an
|
||
explicit `reopenAll()` (the app calls it on wake, display change and
|
||
the reconnect hotkey), a connection reset, and the settings change of
|
||
key/port/matrix (the app calls `reconfigure(_:)`). A key, port, local
|
||
name or local id change reopens everything; a matrix change clears the
|
||
dial state and grants a fresh 30 s budget, so a slot edited after the
|
||
budget expired is actually dialled.
|
||
- **Ticks**: the channel runs one 100 ms `DispatchSourceTimer` that
|
||
calls `Session.tick(now:inputEventCount:)` on every connection, drains
|
||
outboxes and events, and detects the C2 "30 s silence while we are
|
||
sending input" stall: if the connection the sink marked as `controlled`
|
||
receives nothing for 30 s while packets are being forwarded to it,
|
||
close it.
|
||
- **The channel counts input; it does not judge it.**
|
||
`noteUserActivity()` is our `Event.RealInputEventCount++`
|
||
(`Event.cs:51-55`, `InputHook.cs:223, 345`) and the tick passes the raw
|
||
counter to every session unchanged. The `Awake`-or-`Heartbeat` test
|
||
(`lastRealInputEventCount != Event.RealInputEventCount`, re-recorded on
|
||
the way out — `SendAwakeBeat`, `Common.cs:545-559`) lives in `Session`,
|
||
because on Windows the beat *is* the send and each of our sessions
|
||
schedules its own beat. A boundary held here would be out of phase with
|
||
every connection's heartbeat instant and could report `Heartbeat` for
|
||
input that postdates that connection's own previous beat.
|
||
- **`ChannelConfig`** (contracts C4) carries everything: local name,
|
||
local id, port, security key, matrix names, `Name2IP` text,
|
||
`sameSubnetOnly`, `validateRemoteIP`, `blockScreenSaver`.
|
||
- **Threading**: all mutation of channel state happens on one private
|
||
serial queue; `EngineSink` calls are made from that queue and the
|
||
sink is expected to hop to its actor. `PeerConnection` is not
|
||
`Sendable`; it never escapes the channel's queue. *(Shipped as
|
||
`@unchecked Sendable` on both `ControlChannel` and `PeerConnection`,
|
||
because Network.framework's handlers are `@Sendable` closures. The
|
||
confinement is real and unchanged: each `PeerConnection` has its own
|
||
serial queue created with `target: channelQueue`, so every callback in
|
||
the channel is serialised on the one channel queue. See the work log.)*
|
||
- **Time is monotonic.** Every interval here is measured with
|
||
`DispatchTime.now().uptimeNanoseconds`, which is what `Common.GetTick()`
|
||
is on Windows; nothing reads the wall clock, so a clock correction
|
||
cannot make a heartbeat or the stall rule fire.
|
||
|
||
## Handshakes
|
||
|
||
### Consumed
|
||
|
||
- `wire-core`: `CipherWriter`, `CipherReader`, `MagicHash`, `Packet`,
|
||
`Framing` (via `Session`), `packageSize`.
|
||
- `session-matrix`: `Session`, `SessionConfig`, `SessionEvent`,
|
||
`SocketStatus`, `InvalidKeyReason`, `PacketSequencer`, `ReplayFilter`.
|
||
|
||
One `MWBCore` change was made by this lane, with the lead's authorisation
|
||
(rework round 2): `Session.tick(now:userActive:)` became
|
||
`Session.tick(now:inputEventCount:)`, moving `SendAwakeBeat`'s counter
|
||
comparison into the session that owns the heartbeat instant
|
||
(`Common.cs:542-559`). The contract is written up in the session-matrix
|
||
README's Handshakes section; nothing else in `MWBCore` was touched.
|
||
|
||
### Promised (to app-shell, clipboard)
|
||
|
||
As shipped 2026-09-16. Later lanes code against this, not against the
|
||
sketch this section used to hold.
|
||
|
||
```swift
|
||
// ChannelConfig.swift — the vocabulary
|
||
public struct ChannelConfig: Sendable, Equatable {
|
||
public var localName: String, localID: UInt32, port: UInt16 // port + 1 is the control port
|
||
public var securityKey: String, matrixNames: [String], name2IP: String
|
||
public var sameSubnetOnly: Bool, validateRemoteIP: Bool, blockScreenSaver: Bool
|
||
public var controlPort: UInt16 { get }
|
||
public init(localName:localID:port:securityKey:matrixNames:name2IP:
|
||
sameSubnetOnly:validateRemoteIP:blockScreenSaver:) // all but the first two defaulted
|
||
}
|
||
public enum Destination: Sendable, Equatable { case all, peer(UInt32) }
|
||
public enum DisconnectReason: Sendable, Equatable {
|
||
case closed, readError, sendError, invalidKey(InvalidKeyReason), peerRejected,
|
||
stall, duplicateClient, selfConnection, idCollision, timeout, forceClosed
|
||
}
|
||
public struct PeerStatus: Sendable, Equatable {
|
||
public var name: String; public var status: SocketStatus; public var isOutbound: Bool
|
||
public var peerID: UInt32?; public var address: String?
|
||
public init(name:status:isOutbound:peerID:address:)
|
||
}
|
||
public protocol EngineSink: AnyObject, Sendable {
|
||
func channel(_ channel: ControlChannel, connectionStatus: SocketStatus,
|
||
peerName: String?, isOutbound: Bool)
|
||
func channel(_ channel: ControlChannel, connected peerName: String, peerID: UInt32)
|
||
func channel(_ channel: ControlChannel, received packet: Packet, from peerID: UInt32)
|
||
func channel(_ channel: ControlChannel, disconnected peerID: UInt32?,
|
||
peerName: String?, reason: DisconnectReason)
|
||
func channelDetectedIDCollision(_ channel: ControlChannel)
|
||
}
|
||
|
||
// ControlChannel.swift — the sockets
|
||
public final class ControlChannel: @unchecked Sendable {
|
||
public static let connectTimeout: TimeInterval = 30 // SocketStuff.cs:158, 276
|
||
public static let retryInterval: TimeInterval = 1 // :1186
|
||
public static let tickInterval: TimeInterval = 0.1 // frmScreen.cs:285-288
|
||
public static let endpointFailureLimit = 10 // :1487-1497
|
||
public init(config: ChannelConfig, sequencer: PacketSequencer,
|
||
replay: ReplayFilter, sink: EngineSink)
|
||
public func start(); public func stop(); public func sayGoodbye()
|
||
public func reconfigure(_ new: ChannelConfig) // reopens what changed
|
||
public func reopenAll()
|
||
public func forward(_ packet: Packet, to: Destination) // already sequenced (C1)
|
||
public func noteUserActivity()
|
||
public func markControlled(peerID: UInt32?) // arms the 30 s stall rule
|
||
public var statuses: [PeerStatus] { get } // any thread
|
||
}
|
||
|
||
// Resolver.swift — name → addresses, no discovery
|
||
public enum Resolver {
|
||
public static func addresses(for name: String, config: ChannelConfig) -> [String]
|
||
public static func mappedAddresses(for name: String, in name2IP: String) -> [String]
|
||
public static func lookup(_ name: String) -> [String]
|
||
public static func reverseName(for address: String) -> String?
|
||
public static func shortName(for address: String) -> String
|
||
}
|
||
```
|
||
|
||
Rules the consuming lanes must honour:
|
||
|
||
- **Every `EngineSink` call arrives on the channel's serial queue.** Do
|
||
the least possible work in it and hop to the Engine actor; a sink that
|
||
blocks stalls every connection, the heartbeats and the stall rule. The
|
||
channel is handed to the sink as a parameter, so the sink never needs
|
||
to capture it.
|
||
- **`forward(_:to:)` takes an already-sequenced packet** (contracts C1).
|
||
The channel stamps nothing; it fans the identical bytes out, which is
|
||
what makes the receiver's replay ring collapse a peer pair's two
|
||
deliveries. `.all` is filtered by the matrix, exactly as `SkSend` does.
|
||
- **`reopenAll()` is the only way back from a give-up.** After the 30 s
|
||
connect budget expires, or after an address spends its failure budget,
|
||
the channel stops dialling on its own. The app is what turns that
|
||
around, on the reconnect hotkey, on wake, on a display change, and on
|
||
the "no socket established" countdown Windows runs from its 100 ms
|
||
timer (`frmScreen.cs:427-450`). The channel reopens itself only on an
|
||
`NWPathMonitor` status change.
|
||
- **`disconnected` carries optionals.** A connection that dies before the
|
||
handshake has no peer id and possibly no name; `peerID` is `nil` there.
|
||
Do not key recovery on the id alone.
|
||
- **The app owns the machine id.** On `channelDetectedIDCollision` the
|
||
channel has already closed every connection; the app draws a new
|
||
`MachineID`, hands it over in `reconfigure(_:)` and calls `reopenAll()`.
|
||
- **`stop()` does not say goodbye.** Call `sayGoodbye()` first on a clean
|
||
exit (`Common.SendByeBye`, `InitAndCleanup.cs:192`).
|
||
|
||
### Requested of other lanes (open)
|
||
|
||
1. **app-shell**: the reopen countdown is the app's. The channel gives up
|
||
dialling 30 s after `start()`/`reopenAll()` because Windows does
|
||
(`docs/protocol.md` §10.3 notes 1–2); something must call `reopenAll()`
|
||
again while no connection is established, or a machine that boots late
|
||
is never reached. Windows's rule — reopen when no socket is
|
||
established, checked every 30 s — is the one to port
|
||
(`frmScreen.cs:427-450`).
|
||
2. **app-shell**: `markControlled(peerID:)` must be called on every
|
||
switch, including back to local (`nil`). It is what arms the C2 30 s
|
||
stall rule, and nothing else in the channel knows which peer is
|
||
receiving input.
|
||
3. **session-matrix**: the "Heartbeats follow the 100 ms timer cadence"
|
||
bullet in that lane's Assumptions still says `Awake` is sent "if the
|
||
user was active within the window" and cites `Common.cs:499-513`
|
||
(`SendPackage`/`SendHeartBeat`). Both are wrong as of this rework: the
|
||
test is a counter comparison against the session's own previous beat,
|
||
and the citation is `Common.cs:545-559`. This lane's authorisation
|
||
covered that README's Handshakes section only, so the Assumptions
|
||
bullet is left for its owner.
|
||
|
||
### Answered from session-matrix
|
||
|
||
- The duplicate-client-socket policy (`SocketStuff.cs:1980-2004`) and the
|
||
per-endpoint failure budget (`:1482-1499`) are implemented here, keyed
|
||
by peer name and remote address respectively. `Session` still counts
|
||
nothing across connections.
|
||
|
||
## Status / TODO
|
||
|
||
- [x] `Sources/MWBNet/ChannelConfig.swift`: config, `EngineSink`,
|
||
`DisconnectReason`, `PeerStatus`, `Destination`.
|
||
- [x] `Sources/MWBNet/PeerConnection.swift`: one connection — cipher
|
||
header exchange, read loop with 32/64 framing left to `Session`,
|
||
bounded outbox, 500 ms send timeout, stall detection, close
|
||
(`SocketStuff.cs:1261-1565` I/O side, `:1283-1286`).
|
||
- [x] `Sources/MWBNet/Resolver.swift`: `Name2IP` parsing
|
||
(`SocketStuff.cs:904-946, 1258-1259`), same-/16 check
|
||
(`:1065-1107`), reverse validation (`:991-1032`).
|
||
- [x] `Sources/MWBNet/ControlChannel.swift`: listener, dial loop with
|
||
retry (`:797-837, 1169-1198`), one-client-per-peer (`:1980-2004`),
|
||
id collision (`:1984-1992`), per-endpoint failure budget
|
||
(`:1482-1499`), `NWPathMonitor` + `reopenAll` (§3.3), 100 ms tick.
|
||
- [x] Delete `Sources/MWBNet/Placeholder.swift`.
|
||
- [x] `docs/protocol.md`: append §10.3 with anything learned, cited.
|
||
|
||
Not done, deliberately:
|
||
|
||
- **The `Name2IpPolicyList` half of the mapping list**
|
||
(`SocketStuff.cs:906`): it is a Windows GPO-delivered setting, and GPO
|
||
is out of scope (README D6). `Name2IP` alone is parsed, with the same
|
||
grammar.
|
||
- **The bad-IP cache** (`SocketStuff.cs:840-882`): it only memoises the
|
||
reverse-lookup result so a failing address is not looked up again.
|
||
Behaviour is identical without it — a rejected address is simply
|
||
re-checked on the next dial — and the option is off by default.
|
||
- **Socket send/receive buffer sizes** (`:1283-1284`): Network.framework
|
||
exposes neither. The bounded outbox (512 framed packets) is the
|
||
equivalent limit and is what contracts C3 asks for anyway.
|
||
- **Reverse DNS for an inbound peer's display name**
|
||
(`GetMachineNameFromSocket`, `:733-762`): the lookup blocks, and the
|
||
channel queue must not. An inbound connection is labelled by its
|
||
address until the `HandshakeAck` supplies the real name, which is
|
||
within ten packets. `Resolver.shortName(for:)` exists for a lane that
|
||
wants it off the queue.
|
||
- **Windows quitting the app on the eleventh failure from one endpoint**
|
||
(`:1493-1496`): a Mac that silently exits because one peer has a wrong
|
||
key is a worse outcome than one dead peer. We block the address and
|
||
keep running.
|
||
|
||
## Work log
|
||
|
||
### 2026-09-16 — dev (Opus)
|
||
|
||
Four files in `MWBNet`, `Placeholder.swift` deleted, `tools/gates.sh`
|
||
green. What each file is responsible for, in one sentence apiece:
|
||
|
||
- `ChannelConfig.swift` (189 lines) — the vocabulary the channel and the
|
||
app share, and nothing else: config, `Destination`, `DisconnectReason`,
|
||
`PeerStatus`, `EngineSink`.
|
||
- `Resolver.swift` (229 lines) — a machine name to the list of addresses
|
||
worth dialling, including both optional filters. The only file that
|
||
touches `getaddrinfo`/`getifaddrs`, and the only one that blocks.
|
||
- `PeerConnection.swift` (356 lines) — one connection's I/O: the cipher
|
||
preamble, the sized reads, the bounded outbox with its 500 ms timeout,
|
||
and the translation of `SessionEvent` into channel events.
|
||
- `ControlChannel.swift` (505 lines) — everything keyed by endpoint
|
||
rather than by connection: the listener, the dial loop, the
|
||
one-client-per-peer and id-collision rules, the failure budget, the
|
||
reconnect triggers and the 100 ms tick.
|
||
|
||
Decisions and deviations, each with why:
|
||
|
||
1. **Reads are sized, not streamed.** The obvious `receive(min: 1,
|
||
max: 65536)` loop would have made "a read that returned fewer than 32
|
||
bytes" unrepresentable, and that byte count is exactly what
|
||
`Session.noteReceiveError(bytesReceived:)` needs to distinguish
|
||
Windows's `Error` (0 bytes) from `Invalid` (short) package
|
||
(`SocketStuff.cs:574-578`). Instead the reader takes the peer's
|
||
48-byte preamble in one read and then exactly 32 bytes per read. That
|
||
is sound because the stream is packet-aligned after the preamble:
|
||
every write is a whole 32- or 64-byte packet through a no-padding CBC
|
||
stream, so 32 bytes of ciphertext in are always 32 bytes of plaintext
|
||
out (protocol §10.3 note 8). Verified off-line with a no-socket
|
||
harness that runs two `Session`s through real `CipherWriter`/
|
||
`CipherReader` pairs at exactly this chunking: the preamble yields 0
|
||
plaintext bytes, every 32-byte read yields 32, the handshake reaches
|
||
`.connected` on both sides with the right peer name and id, and both
|
||
streams drain to zero leftover.
|
||
2. **One serial queue, per-connection queues that target it.** The brief
|
||
asks for all channel state on one private serial queue; contracts C3
|
||
describes a queue per connection. Both are satisfied by
|
||
`DispatchQueue(label: "mwb.peer.N", target: channelQueue)`: each
|
||
connection has its own FIFO, and the target chain serialises every one
|
||
of them on the channel queue, so there is no lock anywhere in `MWBNet`
|
||
except the one publishing `statuses`.
|
||
3. **`@unchecked Sendable` on `ControlChannel` and `PeerConnection`.**
|
||
Network.framework's state, receive and send handlers are `@Sendable`
|
||
closures, so a non-`Sendable` class cannot be captured by them at all
|
||
under Swift 6. The confinement the README promised is unchanged and is
|
||
the justification: every stored property of both types is touched only
|
||
from the channel queue. `statuses` is the one exception, and it is an
|
||
`OSAllocatedUnfairLock` holding a value copy.
|
||
4. **`Resolver` resolves; `NWConnection` does not.** `NWConnection(host:
|
||
.name(…))` would have been less code, but Windows resolves the name
|
||
itself and then *filters* the address list (same-subnet, reverse
|
||
lookup) and dials every survivor in parallel (`SocketStuff.cs:989-1044`).
|
||
Neither the filter nor the parallel dial survives handing the name to
|
||
Network.framework, so `Resolver` returns numeric addresses and the
|
||
channel dials each one.
|
||
5. **`.waiting` counts as a failed attempt.** Network.framework would
|
||
happily sit in `.waiting` retrying a refused connection on its own
|
||
schedule. Windows retries every second against a 30 s deadline, so the
|
||
connection is cancelled on `.waiting` and the channel's own cadence
|
||
governs (`:1179-1193`).
|
||
6. **The dial loop is polled, Windows's is triggered.** `UpdateTCPClients`
|
||
runs only when something calls it (protocol §10.3 note 2), which works
|
||
there because the 100 ms UI timer also runs a reopen countdown. Ours is
|
||
re-evaluated on the same 100 ms tick, still bounded by the 1 s retry
|
||
interval and the 30 s budget, so the observable cadence is Windows's
|
||
without depending on an app-level countdown that does not exist yet —
|
||
the countdown is still requested of app-shell (Handshakes) because it
|
||
is what recovers after the budget expires.
|
||
7. **The failure budget is keyed by address, not by address:port, and
|
||
counts both invalid-key reasons.** Windows's key includes the remote
|
||
ephemeral port, which is new on every connection, so its counter
|
||
effectively never fires (protocol §10.3 note 5). Keying by address
|
||
makes the guard do what its code plainly intends. And we block that
|
||
address instead of quitting the app (invariant 3: the Mac stays usable).
|
||
8. **`DisconnectReason` has no `.byeBye` case.** The sketch listed one,
|
||
but the channel interprets no packet and therefore cannot know a
|
||
`ByeBye` arrived — `Session` delivers it to the app like any other
|
||
trusted packet, and the app's `Switcher.handleByeBye` already owns the
|
||
behaviour. Windows does not close the socket on `ByeBye` either.
|
||
9. **`disconnected` gained `peerName` and made `peerID` optional.** A
|
||
connection that dies during the handshake has neither an id nor,
|
||
usually, a confirmed name; the promised signature could not describe
|
||
it. The sink needs the name to clear a matrix slot's status.
|
||
10. **`sayGoodbye()` was added.** `Common.SendByeBye` is a broadcast on
|
||
Windows, but session-matrix deliberately made `ByeBye` a
|
||
per-connection originate, so the channel needs an entry point that is
|
||
not `forward(_:to:)`. It is the app's last call before `stop()`.
|
||
|
||
Nothing outside the lane's file list was edited: four new files in
|
||
`Sources/MWBNet`, one deletion, this README, `TODO.md` §3 and
|
||
`docs/protocol.md` §10.3. No `MWBCore` file was touched and no handshake
|
||
request against another lane's files was needed.
|
||
|
||
Verification (no real listening socket was opened at any point, and no
|
||
input event or pasteboard was touched):
|
||
|
||
- `tools/gates.sh` green on the final commit.
|
||
- The no-socket chunking harness described in decision 1.
|
||
- A `Resolver` harness over the public API: `Name2IP` parsing
|
||
(case-insensitive name match, several mappings for one name, malformed
|
||
and non-numeric lines dropped), `lookup` of a name that resolves and
|
||
one that does not, `shortName` of `127.0.0.1`, and `addresses(...)`
|
||
with `sameSubnetOnly` and `validateRemoteIP` on. All as specified.
|
||
|
||
### 2026-09-16 — dev (Opus), rework after QA verdict REWORK
|
||
|
||
One commit per finding, plus a compliance pass. `tools/gates.sh` green on
|
||
the last of them; `xcrun swift-format format -i --recursive Sources
|
||
Package.swift` is a no-op on all four files.
|
||
|
||
1. **`Resolver.addresses` now runs `StartNewTcpClient`'s control flow
|
||
instead of filtering the union.** The mapped (`Name2IP`) group gets the
|
||
same-subnet check on its own and, when it fails, the function returns
|
||
`[]` **without calling `lookup`** — Windows's `return` at
|
||
`SocketStuff.cs:934-937`, which is reached before `Dns.GetHostEntry`
|
||
(`:950`), so nothing is dialled for that name that round. The DNS group
|
||
is then filtered by the reverse lookup (`:989-1032`) and gets its own
|
||
same-subnet check (`:1037-1040`); failing it drops only the DNS
|
||
addresses, because by that point Windows has already handed the mapped
|
||
ones to `StartNewTcpClientThread` (`:941`). Both QA scenarios now match
|
||
Windows: a mapped address out of subnet dials nothing even if DNS has an
|
||
in-subnet address, and an out-of-subnet DNS address is no longer dialled
|
||
just because a mapped address passed. Documented in Assumptions (new
|
||
bullet) and `docs/protocol.md` §10.3 note 6, which now spells out the
|
||
two different failure modes.
|
||
2. **The id-collision check moved inside the `isOutbound` gate.**
|
||
`UpdateTcpSockets` runs the collision branch and the
|
||
keep-the-first-client branch as the two halves of one block gated by
|
||
`status == SocketStatus.Connected && tcp.IsClient`
|
||
(`SocketStuff.cs:1980-1981`), so a server-accepted socket reaches
|
||
neither; the port had the gate on the dedup half only. An inbound peer
|
||
announcing our id is now tolerated silently, as there. §10.3 note 3 said
|
||
only that the collision force-closes everything; it now states the
|
||
client-only gate and points at note 4's observation about the same gate.
|
||
The Assumptions bullet and the `DisconnectReason.idCollision` /
|
||
`channelDetectedIDCollision` doc comments say the same.
|
||
3. **`userActive` is `SendAwakeBeat`'s test, not a sliding window.** The
|
||
channel keeps the pair of counters Windows keeps: `noteUserActivity()`
|
||
increments `inputEventCount` (our `Event.RealInputEventCount++`,
|
||
`InputHook.cs:223, 345`) and the tick reports `inputEventCount !=
|
||
beatInputEventCount`, re-recording the counter on its own heartbeat
|
||
boundary exactly as `SendAwakeBeat` re-records on its way out
|
||
(`Common.cs:545-558`). The boundary is the channel's, which is the one
|
||
global beat Windows's 100 ms timer runs for every socket at once
|
||
(`frmScreen.cs:565-575`); tracking it per connection would need
|
||
`Session` to say when it beat, and `Session` is another lane's file.
|
||
Comparing by count also means a single click 59 s before the beat is
|
||
still an `Awake`, which the old window would have dropped. The stale
|
||
§3.3 citation (`Common.cs:499-513, 662-676` — `SendHeartBeat` and
|
||
screen-capture code) is replaced by `Common.cs:542-559` with the
|
||
`Event.cs:51-55` / `InputHook.cs:223, 345` counter and the
|
||
`IsMyDesktopActive`/desktop conditions named.
|
||
4. **CLAUDE.md re-read of the four files.** Sizes 191/235/356/535 lines,
|
||
every function inside 10–50 (the two longest are `PeerConnection.init`
|
||
at 30 lines and `updateClients` at 28),
|
||
layering, the one-sentence responsibility test, no force-unwrap /
|
||
`try!` / `fatalError` / `precondition`, no logging anywhere in `MWBNet`,
|
||
no packet interpreted, no line over 110 columns. Three citations were
|
||
wrong and are fixed: `Common.SendByeBye` is `Common.cs:611-615`, and
|
||
`SkSend`'s stamp-and-fan-out is `:916-930` with the `Des == ID.ALL`
|
||
matrix test at `:922-930`.
|
||
|
||
No file outside the lane's list was touched: the four `Sources/MWBNet`
|
||
files, this README, `docs/protocol.md` §3.3 and §10.3. No `MWBCore` file
|
||
was edited — finding 3 was answered entirely on the channel side for that
|
||
reason — and `TODO.md` needed no change (its §3 items were already
|
||
ticked). No listener was opened, no input event posted and no pasteboard
|
||
touched during this rework.
|
||
|
||
### 2026-09-16 — dev (Opus), rework round 2 after QA verdict REWORK
|
||
|
||
One finding: the channel-global `lastBeatAt` / `beatInputEventCount` reset
|
||
was not synchronised with any connection's own heartbeat instant, so a
|
||
session could send `Heartbeat (20)` where Windows sends `Awake (21)`, and
|
||
`Awake` is what drives the peer's `Common.HumanBeingDetected()`
|
||
(`Receiver.cs:245-248`) — the `BlockScreenSaver` mechanism, default on.
|
||
QA is right, and right about the cause: Windows's beat *is* the send, one
|
||
`SendAwakeBeat()` call for every socket at once (`Common.cs:545-559`,
|
||
`frmScreen.cs:565-575`), whereas our sessions each schedule their own
|
||
heartbeat from their own handshake-completion time
|
||
(`Session.swift` `start(now:)` / `tick`). A sampling boundary held by the
|
||
channel is therefore out of phase with every one of them by construction.
|
||
The previous entry's claim that the channel's boundary "is the one global
|
||
beat Windows runs for every socket at once" is withdrawn.
|
||
|
||
The fix puts Windows's pair of statics where Windows's beat is — at the
|
||
send:
|
||
|
||
1. **`Session` owns the comparison now.**
|
||
`Session.tick(now:userActive:)` became
|
||
`Session.tick(now:inputEventCount:)`, taking the raw process-wide
|
||
real-input counter (`Event.RealInputEventCount`, `Event.cs:51-55`,
|
||
bumped by the hooks at `InputHook.cs:223, 345`). A new private
|
||
`beatInputEventCount` is `Common.lastRealInputEventCount`
|
||
(`Common.cs:543`): the tick sends `.awake` iff `blockScreenSaver` is on
|
||
**and** the counter differs from the value this session recorded at its
|
||
own previous beat, and re-records it on both branches, which is exactly
|
||
what `SendAwakeBeat` does at `Common.cs:547-548` and `:558`. Because
|
||
the record now happens at the same instant as the send, the
|
||
out-of-phase case QA constructed cannot arise: a click at `t=10` is
|
||
still new to a connection whose own previous beat was at `t=0`,
|
||
whenever between beats the channel happens to tick.
|
||
`beatInputEventCount` starts at `0`, as the Windows static does, so the
|
||
first beat of a session on a machine that has seen any input is an
|
||
`Awake`; that errs towards keeping a peer awake, which is the safe
|
||
direction for this mechanism.
|
||
2. **`ControlChannel` no longer has a beat.** `lastBeatAt` and
|
||
`beatInputEventCount` are gone, along with the heartbeat-interval
|
||
lookup that existed only to drive them. `noteUserActivity()` still just
|
||
increments `inputEventCount` (`&+=`, so it wraps rather than traps),
|
||
and `tick()` reads it once and hands the same value to every
|
||
connection; `PeerConnection.tick(now:inputEventCount:)` passes it
|
||
straight through. No `userActive`-shaped name survives anywhere in
|
||
`Sources` (grep clean), so there is nothing left to reintroduce a
|
||
window against.
|
||
|
||
Scope: this touched `Sources/MWBCore/Session.swift`, which belongs to
|
||
session-matrix — the lead authorised that one file plus that lane's
|
||
Handshakes section for this fix, because the finding cannot be answered on
|
||
the channel side at all (the channel does not and should not know when a
|
||
session beats). `docs/features/session-matrix/README.md` now carries the
|
||
new signature in its Promised block and a rule spelling out that the
|
||
argument is a raw counter and why a caller must not pre-compute the
|
||
verdict. A stale Assumptions bullet in that same README (a "window" and
|
||
the `Common.cs:499-513` citation) is outside the authorisation and is
|
||
filed as open request 3 instead. `docs/protocol.md` §3.3 already describes
|
||
the rule correctly (`Common.cs:542-559`, corrected in the previous round)
|
||
and needed no change; `TODO.md` had nothing to tick.
|
||
|
||
Verification: `xcrun swift-format format -i --recursive Sources
|
||
Package.swift` is a no-op, and `tools/guard.sh -m 8 -t 1800 --
|
||
tools/gates.sh` is green (lint `--strict`, the `MWBCore` layering check,
|
||
`swift build -Xswiftc -warnings-as-errors`); neither guard limit was hit.
|
||
No listener was opened, no `CGEvent` posted and no pasteboard touched.
|
||
|
||
## QA log
|
||
|
||
### 2026-09-16 — QA (Sonnet)
|
||
|
||
Checked, in order: `tools/gates.sh`; every Status/TODO tick against
|
||
`App/Class/SocketStuff.cs` (listeners, `UpdateTCPClients`, `Name2IP`, DNS,
|
||
subnet, connect, options, `MainTCPRoutine` I/O, failure budget,
|
||
dedup/collision), `TcpServer.cs`, `InitAndCleanup.cs:28-31`,
|
||
`frmScreen.cs:427-461`; all four changed files top to bottom for CLAUDE.md
|
||
compliance (size, layering, naming, force-unwraps, retain cycles); that
|
||
`MWBNet` logs nothing and interprets no packet.
|
||
|
||
- `tools/gates.sh`: green (`swift-format lint --strict`, MWBCore layering,
|
||
`swift build -Xswiftc -warnings-as-errors`). No `Tests/` target exists in
|
||
this repo (the user's rule, `TODO.md`/`docs/topo.md` history) so no
|
||
`swift test` gate applies; the work log's harnesses are not committed,
|
||
consistent with that rule.
|
||
- File-by-file read: no force-unwraps, `try!`, `fatalError` or
|
||
`precondition` in any of the four files; no `print`/`Logger`/`os_log`
|
||
calls anywhere in `MWBNet` (invariant 2 — nothing to leak key material or
|
||
packet contents even inadvertently); every closure captured across an
|
||
escaping boundary (`NWConnection`/`NWListener`/`NWPathMonitor`/
|
||
`DispatchSourceTimer`/`DispatchWorkItem` handlers in both
|
||
`PeerConnection` and `ControlChannel`) uses `[weak self]`, so no retain
|
||
cycle. File sizes (189/512/356/229) and every function body are inside
|
||
CLAUDE.md's targets. Confirmed `Session.forward` → `sendDirect` only
|
||
fills `Src` when unset and never touches `Id`
|
||
(`Sources/MWBCore/Session.swift:390-395`), so `forward(_:to:)` truly
|
||
never re-stamps a packet (C1). Confirmed the 48-byte `writer.header` is
|
||
enqueued before `session.start(now:)` in `becameReady()`
|
||
(`PeerConnection.swift:158-159`), and `receiveExactly` passes the real
|
||
`received.count` to `noteReceiveError(bytesReceived:)`
|
||
(`PeerConnection.swift:207-208`). Confirmed `@unchecked Sendable` on both
|
||
types: every stored property is touched only from `queue`/`peerQueue`
|
||
(which targets `queue`), except `statusStore`, which is its own
|
||
`OSAllocatedUnfairLock` — no handler found that touches state off the
|
||
channel queue.
|
||
- Two undocumented behavioural deviations from the Windows source turned
|
||
up from the line-by-line comparison; neither is mentioned in
|
||
`docs/protocol.md` §10.3, the README, or the work log's list of
|
||
deliberate deviations. Filed below.
|
||
- Verified deliberate, documented deviations are in fact what's shipped:
|
||
`Name2IpPolicyList` and the bad-IP cache are absent (`grep` clean), the
|
||
failure budget is keyed by address only and counts every `.invalidKey`
|
||
reason (`ControlChannel.swift:400-406`), Windows's app-quit-on-eleventh
|
||
is replaced with per-address blocking — all as the work log states.
|
||
|
||
Verdict: REWORK
|
||
|
||
Findings:
|
||
|
||
1. **`Resolver.addresses` merges the `Name2IP` and DNS address groups
|
||
before the same-subnet check, instead of checking each group
|
||
separately, and has no equivalent of Windows's early return when the
|
||
`Name2IP` group itself fails that check.**
|
||
`Sources/MWBNet/Resolver.swift:24-41` builds one `found` array from
|
||
`mappedAddresses` then `lookup`, and applies `isSameSubnet` once to the
|
||
union. Windows (`SocketStuff.cs:930-944`) runs `CheckForSameSubNet` on
|
||
the `Name2IP`-mapped addresses alone and, if it fails, `return`s from
|
||
`StartNewTcpClient` **before `Dns.GetHostEntry` is ever called** —
|
||
skipping DNS resolution for that round entirely — then separately runs
|
||
`CheckForSameSubNet` again on the DNS-resolved group
|
||
(`:1035-1044`). Net effect with `sameSubnetOnly` on and a `Name2IP`
|
||
mapping configured: (a) a `Name2IP` address outside the local subnet
|
||
but a DNS address inside it — Windows dials nothing for that name this
|
||
round (the early return skips DNS too); the port dials the DNS
|
||
address. (b) A `Name2IP` address inside the subnet but a DNS address
|
||
outside it — Windows dials only the `Name2IP` address; the port's
|
||
single union check passes (because *some* address in the union
|
||
matches) and dials both, including the out-of-subnet DNS address.
|
||
`docs/protocol.md` §10.3 note 6 documents the reverse-lookup-filter
|
||
half of this same code region but not the subnet-check-per-group
|
||
split or the early return. Both `sameSubnetOnly` and `Name2IP` are
|
||
off/empty by default, so this needs a live peer with both configured
|
||
to reach.
|
||
|
||
2. **Machine-id collision is detected on inbound (server) connections
|
||
too; Windows only detects it on outbound (client) sockets.**
|
||
`Sources/MWBNet/ControlChannel.swift:367-372` (`accept(_:name:id:)`)
|
||
runs `if id == config.localID { sink.channelDetectedIDCollision(...);
|
||
closeAll(.idCollision); return }` for every connection that completes
|
||
its handshake, regardless of `peer.isOutbound`. On Windows,
|
||
`UpdateTcpSockets`'s entire collision-and-dedup block is gated by
|
||
`status == SocketStatus.Connected && tcp.IsClient`
|
||
(`SocketStuff.cs:1981`) — the id check at `:1985` never runs for a
|
||
server-accepted socket. The port gets the *dedup* half of that same
|
||
guard right two lines below (`peer.isOutbound` on the
|
||
`duplicateClient` check, `ControlChannel.swift:375`) but drops the
|
||
guard for the collision half. `docs/protocol.md` §10.3 note 3
|
||
describes the force-close-everything behaviour but not the
|
||
client-only gate, so this reads as faithfully ported when it isn't.
|
||
Practical effect: a Mac can force-close every connection and
|
||
regenerate its machine id reacting to a collision reported over an
|
||
*inbound* connection, a case real Windows silently tolerates — not
|
||
unsafe (invariant 3 is still satisfied, this only affects other
|
||
machines), but an undocumented behavioural difference invariant 1
|
||
requires be either matched or explicitly justified.
|
||
|
||
3. **(Minor, doc-only) The `userActive` heuristic in
|
||
`ControlChannel.tick` is a time-window proxy, not what
|
||
`SendAwakeBeat` actually checks, and the approximation isn't cited
|
||
anywhere.** `ControlChannel.swift:441-442` computes `userActive =
|
||
lastUserActivity > 0 && now - lastUserActivity <= interval` (the
|
||
heartbeat interval itself, 60 s/300 s). Windows's `SendAwakeBeat`
|
||
(`Common.cs:545-558`) instead sends `Awake` when
|
||
`lastRealInputEventCount != Event.RealInputEventCount` — i.e. any new
|
||
real input since the *previous* heartbeat tick, not "within the last N
|
||
seconds of `now`" — plus `IsMyDesktopActive()` and
|
||
not-logon/not-screensaver-desktop checks this lane correctly leaves to
|
||
another lane. The two proxies agree in the steady state (continuous
|
||
activity or continuous idleness) and only diverge at the edges, so
|
||
this is low-impact, but note that `docs/protocol.md` §3.3's own
|
||
citation for this rule (`Common.cs:499-513, 662-676`) is stale — those
|
||
lines are `SendHeartBeat`/screen-capture code, not `SendAwakeBeat` —
|
||
which predates this lane and was inherited rather than checked against
|
||
source. Worth a one-line fix to protocol.md §3.3's citation and a note
|
||
on the approximation next time §3.3 or this file is touched; not
|
||
blocking on its own.
|
||
|
||
### 2026-09-16 — QA (Sonnet), round 2
|
||
|
||
Read the rework Work-log entry, then `git diff 09ca990..HEAD` and
|
||
`git log --oneline 09ca990..HEAD` (five commits). Checked, in order:
|
||
`tools/guard.sh -m 8 -t 600 -- tools/gates.sh`; finding 1 against
|
||
`SocketStuff.cs:920-950, 1030-1046`; finding 2 against `:1975-2005`; finding
|
||
3's citations against `Common.cs:540-562, 605-620, 910-935`, `Event.cs:45-60`,
|
||
`InputHook.cs:218-230, 340-350`, `frmScreen.cs:560-578`; the two corrected
|
||
citations; then read `ChannelConfig.swift`, `ControlChannel.swift`,
|
||
`PeerConnection.swift`, `Resolver.swift` top to bottom for CLAUDE.md
|
||
compliance, and, because finding 3 is about a liveness signal that reaches
|
||
across the `MWBNet`/`MWBCore` boundary, read `Sources/MWBCore/Session.swift`'s
|
||
`start(now:)` and `tick(now:userActive:)` to see how the channel's
|
||
`userActive` is actually consumed.
|
||
|
||
- `tools/guard.sh -m 8 -t 600 -- tools/gates.sh`: green (lint --strict,
|
||
MWBCore layering, warnings-as-errors build). Neither limit was hit.
|
||
- **Finding 1 — fixed, matches Windows.** `Resolver.addresses`
|
||
(`Resolver.swift:33-47`) now checks the mapped group alone
|
||
(`!mapped.isEmpty, config.sameSubnetOnly, !isSameSubnet(mapped)`) and
|
||
returns `[]` before `lookup(name)` is ever called, reproducing
|
||
`SocketStuff.cs:926-937`'s `return` that skips `Dns.GetHostEntry` at `:950`
|
||
entirely. The DNS group is then resolved, reverse-validated, and gets its
|
||
own independent same-subnet check that on failure zeroes only `resolved`
|
||
(`:1035-1044`), so a rejected DNS group no longer suppresses an
|
||
already-accepted mapped group. `CheckForSameSubNet` itself returns `true`
|
||
whenever `!Setting.Values.SameSubNetOnly` or either side has no IPv4
|
||
address (`SocketStuff.cs:1069-1085`), which the Swift gates (`!mapped/
|
||
resolved.isEmpty, config.sameSubnetOnly`) and `isSameSubnet`'s own
|
||
empty-array short-circuits (`Resolver.swift:142, 144`) reproduce. Both QA
|
||
scenarios from round 1 now dial exactly what Windows dials. `docs/protocol.md`
|
||
§10.3 note 6 states the two different failure modes; the citations
|
||
(`:928-944, 950`, `:989-1044`, `:934-937`, `:941, 1037-1040`) all check out
|
||
against the reference file.
|
||
- **Finding 2 — fixed, matches Windows.** `ControlChannel.accept(_:name:id:)`
|
||
(`ControlChannel.swift:377-394`) now runs the id-collision check and the
|
||
keep-the-first-client check as two branches of one `if peer.isOutbound`
|
||
block, reproducing `UpdateTcpSockets`'s `status == Connected && tcp.IsClient`
|
||
gate (`SocketStuff.cs:1980-1981`) around both the id compare (`:1984-1992`)
|
||
and the dedup (`:1993-1997`). An inbound peer announcing our id now falls
|
||
through to `dialers[name] = nil; sink.channel(...)` untouched, same as
|
||
Windows silently accepting it. `docs/protocol.md` §10.3 note 3 states the
|
||
client-only gate and cross-references note 4; the `DisconnectReason
|
||
.idCollision` and `channelDetectedIDCollision` doc comments
|
||
(`ChannelConfig.swift:121-123, 186-189`) say the same. Matches.
|
||
- **Finding 3, the literal ask — fixed.** `ControlChannel.tick()`
|
||
(`:457-471`) now compares `inputEventCount != beatInputEventCount`, two
|
||
counters bumped by `noteUserActivity()` (`:201-203`, our
|
||
`Event.RealInputEventCount++`) and re-snapshotted on a periodic boundary —
|
||
a counter compare, not a sliding window, which is what was asked for.
|
||
`docs/protocol.md` §3.3's citation is now `Common.cs:542-559` (confirmed:
|
||
`SendAwakeBeat` itself, `lastRealInputEventCount`/`lastInputEventCount`
|
||
fields included at `542-543`, function body `545-559`) with
|
||
`Common.cs:547-548` for the `BlockScreenSaver`/`IsMyDesktopActive`/
|
||
logon-desktop conditions — both check out exactly against
|
||
`App/Core/Common.cs`. `Event.cs:51-55` (`RealInputEventCount` property) and
|
||
`InputHook.cs:223, 345` (`Event.RealInputEventCount++` in the mouse and
|
||
keyboard hooks) also check out.
|
||
- **Corrected citations — both right.** `Common.SendByeBye` is
|
||
`Common.cs:611-615` (confirmed exactly: `internal static void
|
||
SendByeBye()` through the closing brace). `SkSend`'s stamp is
|
||
`Common.cs:916` (`data.Id = Interlocked.Increment(...)`) and the fan-out
|
||
loop through the matrix test is `:916-930`, ending at the `sk.TcpSend(t,
|
||
data)` call — the `ChannelConfig.swift:87` doc comment's narrower
|
||
`:922-930` for "the `Des == ID.ALL` matrix test" is the `foreach`-through-
|
||
`TcpSend` sub-range and is consistent with it.
|
||
- Compliance pass: no force-unwrap, `try!`, `fatalError` or `precondition` in
|
||
any of the four files (checked with a grep for bare `!`/`try!`/
|
||
`fatalError`/`precondition(` and manually cleared every hit — all are `!=`,
|
||
`guard !x`, or `!collection.contains`, none are force-unwraps); no
|
||
`print`/`Logger`/`os_log`/`NSLog` anywhere in `MWBNet`. File sizes
|
||
(191/535/356/235) match the work log exactly and stay inside CLAUDE.md's
|
||
targets; `tick()` (15 lines), `accept(_:name:id:)` (18 lines) and
|
||
`Resolver.addresses` (15 lines) are all well inside 10–50.
|
||
|
||
**New finding — finding 3's fix is incomplete: the channel's beat boundary
|
||
that resets `beatInputEventCount` is not the moment any connection actually
|
||
sends its heartbeat, so a connection can report `Heartbeat` when real input
|
||
happened since *its own* previous heartbeat.** `ControlChannel.tick()`
|
||
(`ControlChannel.swift:457-471`) resets `beatInputEventCount` on the
|
||
channel's own clock: `lastBeatAt` starts at `0` (`:61`) and the boundary
|
||
fires every time `now - lastBeatAt >= interval` on the channel's 100 ms
|
||
timer, independent of any connection. But no connection's heartbeat is sent
|
||
on that clock — each `PeerConnection`'s `Session` decides independently,
|
||
via its own `nextHeartbeat` field, set to `now + heartbeatInterval` in
|
||
`start(now:)` (`Sources/MWBCore/Session.swift:167`, `now` there being *that
|
||
connection's* handshake-completion time) and rescheduled the same way from
|
||
its own fire time in `tick(now:userActive:)`
|
||
(`Session.swift:218-223`). Nothing ties the two schedules together
|
||
(`ControlChannel.swift:59-61` has no connection-keyed state at all), so a
|
||
connection's own heartbeat instant is generally out of phase with the
|
||
channel's reset instant. Concrete case: channel resets `beatInputEventCount`
|
||
at `t=50`; a connection's own `nextHeartbeat` fires at `t=60` (phase set by
|
||
when *that* connection's handshake completed, unrelated to `t=50`); the
|
||
user's last click was at `t=10`, nothing since. At `t=50` the reset
|
||
snapshots `beatInputEventCount` to a value that already includes the `t=10`
|
||
click; at the connection's own send at `t=60`, `inputEventCount ==
|
||
beatInputEventCount` (no *new* input since `t=50`), so `userActive` reads
|
||
`false` and the connection sends `Heartbeat (20)` — even though the click at
|
||
`t=10` postdates that connection's own previous heartbeat and Windows's
|
||
single, truly-simultaneous `SendAwakeBeat()` call would have sent `Awake
|
||
(21)` to every socket for it. Round 1's sliding-window version did not have
|
||
this failure mode: `now - lastUserActivity <= interval`, evaluated fresh at
|
||
whatever instant a connection ticked, had no shared reset to be out of phase
|
||
with. `Awake` is not cosmetic: on the peer it drives
|
||
`Common.HumanBeingDetected()` (`Receiver.cs:245-248`), which is the
|
||
mechanism the `BlockScreenSaver` feature (default **on** —
|
||
`ChannelConfig.swift:59`, `blockScreenSaver: Bool = true`) depends on to
|
||
keep a peer from screen-locking while this machine's user is active. The
|
||
work log's claim that "the boundary is the channel's, which is the one
|
||
global beat Windows's 100 ms timer runs for every socket at once"
|
||
(entry 3, and the matching doc comment at `ControlChannel.swift:450-456`)
|
||
overstates this: Windows's beat *is* the send, for every socket, in one call
|
||
(`Common.cs:545-558`, `frmScreen.cs:565-575`); the channel's beat is a
|
||
sampling boundary that no send is pinned to. Not a safety issue (invariants
|
||
2–4 are untouched) and it self-corrects once any two beats in a row see
|
||
continuous activity, but it is a real, default-on regression in exactly the
|
||
mechanism this finding was reworked to fix, and it needs either a
|
||
`Session`-side change (a `session-matrix` handshake — `Session` would have to
|
||
report its own beat, or take the raw counter and do the compare itself) or a
|
||
different `ControlChannel`-side scheme that doesn't rely on a channel-wide
|
||
reset. Flagged, not fixed — outside "verify, don't redesign."
|
||
|
||
Verdict: REWORK
|
||
|
||
## Review
|