diff --git a/Sources/MWBCore/Session.swift b/Sources/MWBCore/Session.swift index 8fc42ec..0907f89 100644 --- a/Sources/MWBCore/Session.swift +++ b/Sources/MWBCore/Session.swift @@ -6,7 +6,7 @@ // Ported from App/Class/SocketStuff.cs MainTCPRoutine (1261-1565) and // TcpReceiveData (557-610), App/Core/Receiver.cs PreProcess (40-82), // App/Core/Common.cs SendPackage/SendHeartBeat (499-513), SendAwakeBeat -// (545-558), SendByeBye (612-616) and TestSend (822-847), +// (542-559), SendByeBye (612-616) and TestSend (822-847), // App/Form/frmScreen.cs the 100 ms timer (285-288, 555-575). import Foundation @@ -124,6 +124,14 @@ public final class Session { private var nextHeartbeat: TimeInterval = .greatestFiniteMagnitude private var finished = false + /// The real-input counter as it stood when *this* session last beat — + /// `Common.lastRealInputEventCount` (`Common.cs:543`), re-recorded on the way + /// out of every beat (`:558`). It starts at zero because the Windows field + /// does, so the first beat after the process has seen any input at all is an + /// `Awake`; a spurious `Awake` only wakes a peer's screen, while a missed one + /// lets it lock under the user's hands. + private var beatInputEventCount: UInt64 = 0 + /// The connection's status. public private(set) var status: SocketStatus = .na /// The peer's name, known once the handshake completes. @@ -212,13 +220,24 @@ public final class Session { pending.append(.status(new)) } - /// Heartbeats. `userActive` is whether real input happened since the last - /// tick, which is what turns a `Heartbeat` into an `Awake` - /// (`Common.cs:545-552`). - public func tick(now: TimeInterval, userActive: Bool) { + /// Heartbeats. `inputEventCount` is the raw process-wide real-input counter, + /// which is `Event.RealInputEventCount` on Windows (`Event.cs:51-55`, bumped + /// by the hooks at `InputHook.cs:223, 345`); the owner passes the same value + /// to every session on a tick and never interprets it. + /// + /// The beat is `SendAwakeBeat` (`Common.cs:545-559`): `Awake` when + /// `BlockScreenSaver` is on *and* the counter moved since this session's own + /// previous beat, `Heartbeat` otherwise, and the counter is recorded either + /// way. Keeping the comparison here rather than in the owner is what makes it + /// a since-*this*-connection's-last-beat test — sessions beat on their own + /// schedules, so a shared boundary in the owner would let a connection report + /// `Heartbeat` for input that postdates its own previous beat. + public func tick(now: TimeInterval, inputEventCount: UInt64) { guard status == .connected, !finished, now >= nextHeartbeat else { return } nextHeartbeat = now + heartbeatInterval - let type: PackageType = config.blockScreenSaver && userActive ? .awake : .heartbeat + let moved = inputEventCount != beatInputEventCount + beatInputEventCount = inputEventCount // Common.cs:558 + let type: PackageType = config.blockScreenSaver && moved ? .awake : .heartbeat originate(broadcast(type)) } diff --git a/Sources/MWBNet/ControlChannel.swift b/Sources/MWBNet/ControlChannel.swift index ceeac41..11dc0ae 100644 --- a/Sources/MWBNet/ControlChannel.swift +++ b/Sources/MWBNet/ControlChannel.swift @@ -57,8 +57,6 @@ public final class ControlChannel: @unchecked Sendable { private var blocked: Set = [] private var dialDeadline: TimeInterval = 0 private var inputEventCount: UInt64 = 0 - private var beatInputEventCount: UInt64 = 0 - private var lastBeatAt: TimeInterval = 0 private var controlledPeerID: UInt32? private var lastPathStatus: NWPath.Status? private var connectionCount = 0 @@ -194,10 +192,13 @@ public final class ControlChannel: @unchecked Sendable { } } - /// Tells the channel the user just did something, which is what turns the - /// next `Heartbeat` into an `Awake` (`Common.cs:545-558`). This is our - /// `Event.RealInputEventCount++` (`InputHook.cs:223, 345`): the count is - /// what matters, not when it happened. + /// Tells the channel the user just did something, which is what turns a + /// connection's next `Heartbeat` into an `Awake` (`Common.cs:545-559`). + /// + /// This is exactly our `Event.RealInputEventCount++` (`Event.cs:51-55`, + /// `InputHook.cs:223, 345`) and nothing more: the channel only counts, and + /// each `Session` decides `Awake` against the count it saw at its own + /// previous beat. public func noteUserActivity() { queue.async { [self] in inputEventCount &+= 1 } } @@ -447,25 +448,21 @@ public final class ControlChannel: @unchecked Sendable { source.resume() } - /// `Awake` or `Heartbeat` is decided by whether the real-input counter moved - /// since the *previous* heartbeat, not by a window around `now`: - /// `SendAwakeBeat` sends `Awake` when `lastRealInputEventCount != - /// Event.RealInputEventCount` and records the counter again on its way out - /// (`Common.cs:545-558`). The two counters here are that pair, and the beat - /// they are recorded on is the one global heartbeat Windows's 100 ms timer - /// runs for every socket at once (`frmScreen.cs:565-575`). + /// The tick hands every connection the raw real-input counter and decides + /// nothing about it. `SendAwakeBeat`'s `lastRealInputEventCount != + /// Event.RealInputEventCount` test is a comparison against the counter *as of + /// the previous beat*, and the beat is the send (`Common.cs:545-559`, + /// `frmScreen.cs:565-575`), so the comparison belongs where the send is + /// scheduled: inside each `Session`, which owns its own heartbeat instant. + /// A boundary kept here instead would be out of phase with every connection's + /// own beat and could swallow the input a peer needs to stay awake. private func tick() { guard running else { return } let now = monotonicNow() - let interval = config.blockScreenSaver ? Session.fastHeartbeat : Session.slowHeartbeat - let userActive = inputEventCount != beatInputEventCount - if now - lastBeatAt >= interval { - lastBeatAt = now - beatInputEventCount = inputEventCount - } + let count = inputEventCount for connection in connections { connection.isControlled = connection.peerID != nil && connection.peerID == controlledPeerID - connection.tick(now: now, userActive: userActive) + connection.tick(now: now, inputEventCount: count) } updateClients(now: now) } diff --git a/Sources/MWBNet/PeerConnection.swift b/Sources/MWBNet/PeerConnection.swift index 7a81850..d4d7b36 100644 --- a/Sources/MWBNet/PeerConnection.swift +++ b/Sources/MWBNet/PeerConnection.swift @@ -315,10 +315,11 @@ final class PeerConnection: @unchecked Sendable { // MARK: - Time /// Heartbeats, and the C2 rule that a controlled peer which has gone quiet - /// for 30 s while we are feeding it input is gone. - func tick(now: TimeInterval, userActive: Bool) { + /// for 30 s while we are feeding it input is gone. `inputEventCount` is the + /// channel's raw real-input counter, passed straight through to the session. + func tick(now: TimeInterval, inputEventCount: UInt64) { guard !finished, closing == nil else { return } - session.tick(now: now, userActive: userActive) + session.tick(now: now, inputEventCount: inputEventCount) pump() guard status == .connected, isControlled, lastForward > lastReceive else { return } diff --git a/docs/features/control-channel/README.md b/docs/features/control-channel/README.md index 2daaf29..16a185e 100644 --- a/docs/features/control-channel/README.md +++ b/docs/features/control-channel/README.md @@ -88,16 +88,21 @@ No packet is interpreted here. 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:userActive:)` on every connection (the app - reports input via `noteUserActivity()`, which is our - `Event.RealInputEventCount++`, `InputHook.cs:223, 345`; `userActive` is - then "the counter moved since the previous heartbeat", the test - `SendAwakeBeat` makes and re-records every time it runs - (`Common.cs:545-558`) — not a sliding window around `now`), drains + 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. + 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`. @@ -124,7 +129,12 @@ No packet is interpreted here. - `session-matrix`: `Session`, `SessionConfig`, `SessionEvent`, `SocketStatus`, `InvalidKeyReason`, `PacketSequencer`, `ReplayFilter`. -Nothing in `MWBCore` was changed by this lane. +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) @@ -228,6 +238,14 @@ Rules the consuming lanes must honour: 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 @@ -452,6 +470,72 @@ 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) diff --git a/docs/features/session-matrix/README.md b/docs/features/session-matrix/README.md index 96e6562..9aafb77 100644 --- a/docs/features/session-matrix/README.md +++ b/docs/features/session-matrix/README.md @@ -168,7 +168,7 @@ public final class Session { // not Sendable: one per connecti public func feed(_ plaintext: Data) // 32-then-32 reassembly inside public func noteReceiveError(bytesReceived: Int) // a 0-byte / short read public func report(_ new: SocketStatus) // .resolving, .sendError, … - public func tick(now: TimeInterval, userActive: Bool) + public func tick(now: TimeInterval, inputEventCount: UInt64) public func forward(_ packet: Packet) // app-stamped: Src + framing only public func probe() // Hi public func sayGoodbye() // ByeBye @@ -338,6 +338,23 @@ Rules the consuming lanes must honour: moves unconditionally will jerk the local cursor to the top of the screen every time control comes home — on every `ByeBye` and every peer disconnect (`Common.cs:622-625`). +- **`tick(now:inputEventCount:)` takes the raw process-wide real-input + counter, not a verdict.** `inputEventCount` is our + `Event.RealInputEventCount` (`Event.cs:51-55`, bumped by the hooks at + `InputHook.cs:223, 345`): the caller increments it on every real input + event and hands the *same* value to every session on a tick. Each + `Session` remembers the value it saw at its own previous beat and sends + `Awake (21)` instead of `Heartbeat (20)` iff the counter moved since then + and `blockScreenSaver` is on, re-recording it either way + (`SendAwakeBeat`, `Common.cs:545-559`). A caller must not pre-compute + that comparison on a clock of its own: sessions beat on independent + schedules (`nextHeartbeat` is seeded from each connection's own + `start(now:)`), so a shared boundary in the caller is generally out of + phase with a connection's beat and can report `Heartbeat` for input that + postdates *that* connection's previous beat — which silently disables the + peer's `BlockScreenSaver` (`Receiver.cs:245-248` → + `Common.HumanBeingDetected`). Signature changed 2026-09-16, requested by + control-channel; it was `tick(now:userActive:)`. - **`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.