Files
lucioandClaude Opus 5 fc7a54b40a app-engine: protocol §10.6, the lane README and TODO §6
§10.6 records six things the Windows source says that §1-§9 did not:
that a switch moves the pointer only when the target is the local
machine (Helper.cs:75-127), that a Mouse packet addressed to us takes
control back by assignment rather than by switching (Receiver.cs:122-125),
that relative mode puts the edge detection on the controlled machine
(Receiver.cs:147-172), that the reconnect countdown is 30 s and gated on
"no socket established" (frmScreen.cs:425-449), the exact JSON shapes of
the settings file, and why Heartbeat has to be a 64-byte packet.

The README's Handshakes section now documents the API as shipped, six
deliberate deviations, the answers to all eleven open requests from
lanes 3-5, and four new requests: PacketSequencer is used from two
queues and is not thread-safe (session-matrix), PermissionState has no
public initialiser and Cursor publishes no pointer position
(input-capture), and there is no way to send a Heartbeat on demand
(control-channel).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 03:35:37 -07:00

124 lines
5.4 KiB
Swift

// Getting the keyboard and the mouse back: every row of contracts C2, and the
// countdown that keeps dialling when nothing is connected.
//
// CLAUDE.md invariant 3 is what this file exists for. Each row ends the same
// way — control local, held keys released, pointer re-associated — and none of
// it waits on the network: `recoverLocal` touches the routing snapshot, the
// injector and the cursor, all of which are local and lock-free enough to run
// from a disconnect callback or a signal handler.
//
// Ported from App/Core/Common.cs `ProcessByeByeMessage` (622-630),
// App/Class/SocketStuff.cs (1561-1563) and App/Core/MachineStuff.cs
// `RemoveDeadMachines` (675-694),
// App/Core/InitAndCleanup.cs `ReleaseAllKeys` (214-243) and `Cleanup` (192-215),
// App/Form/frmScreen.cs `HelperTimer_Tick` (427-461).
import Foundation
import MWBCore
import MWBMac
import MWBNet
extension Engine {
/// Brings control home and puts this Mac back in a usable state.
///
/// Idempotent: calling it while control is already local still releases held
/// keys and re-associates the pointer, which is exactly what `.tapLost` and
/// a revoked permission need — after either of those the held-key state is
/// unknown even though nothing switched.
public func recoverLocal(reason: RecoveryReason) {
routing.routeLocal()
// `SwitchToMachine(MachineName)` is what Windows does on a `ByeBye`
// (`Common.cs:626`), so control comes home the same way a hotkey would:
// the machine we were driving is told to park, and our own pointer lands
// in the middle of the primary screen. On a plain socket error Windows
// only marks the machine dead (`SocketStuff.cs:1561-1563`) and lets its
// 100 ms timer take control home once nothing is connected
// (`frmScreen.cs:442`); contracts C2 requires it immediately.
var actions: [SwitchAction] = []
if switcher.desMachineID != switcher.localID {
actions = switcher.switchToMachine(named: switcher.localName, now: EventTap.now())
}
injector.releaseAll()
perform(actions)
// Belt and braces for CLAUDE.md invariant 3: this shows the pointer and
// re-associates it with the mouse **without moving it**, and is a no-op
// when `syncRouting` has already done so. A recovery that fires while
// control was never remote (`.tapLost`, a revoked grant) must not jerk
// the user's own pointer anywhere.
cursor.recouple(to: nil)
lastRecovery = RecoveryNote(reason: reason, at: Date())
Log.engine.info("control back on this Mac: \(reason.text)")
publish()
}
/// A connection ended, for any of the reasons in contracts C2's table: a
/// `ByeBye`, a socket close, a read or send error, an invalid key, the 30 s
/// stall rule or a force close.
func noteDisconnected(peerID: UInt32?, peerName: String?, reason: DisconnectReason) {
if let peerName { switcher.connectedNames.remove(peerName) }
guard let peerID else {
// Died before the handshake named it: nothing was ever controlled by
// it, so there is nothing to recover from (control-channel Handshakes).
Log.engine.debug("connection to \(peerName ?? "?") ended: \(reason)")
publish()
return
}
let wasDriving = peerID == switcher.desMachineID
switcher.connectedIDs.remove(peerID)
perform(switcher.connectionLost(id: peerID, now: EventTap.now()))
Log.engine.info("\(peerName ?? peerNames[peerID] ?? "peer") disconnected: \(reason)")
peerNames[peerID] = nil
if wasDriving {
recoverLocal(reason: .controlledPeerLost(peerName))
} else {
publish()
}
}
/// The 1 s timer: the reopen countdown, and nothing else.
///
/// `Session` beats on the channel's own 100 ms tick and the stall rule is
/// armed by `markControlled`, so neither needs anything from here.
func tick() {
reopenCountdown()
}
/// `frmScreen.cs:427-450`: while no socket is established, dial again.
///
/// The channel stops dialling 30 s after `start()` or `reopenAll()`
/// (control-channel Handshakes, request 1), so without this a machine that
/// boots late is never reached. Windows re-checks on its 100 ms timer every
/// `count % 300` ticks — 30 s — which is also the channel's connect budget,
/// so the two line up exactly.
private func reopenCountdown() {
guard channel != nil else { return }
guard switcher.connectedIDs.isEmpty else {
secondsWithoutConnection = 0
return
}
secondsWithoutConnection += 1
guard secondsWithoutConnection >= Engine.reopenAfterSecondsIdle else { return }
secondsWithoutConnection = 0
Log.engine.info("nothing connected; reopening sockets")
channel?.reopenAll()
}
/// What `Setting.Values` holds on exit: the packet counter so ids keep
/// rising across restarts (`Common.cs:906`), the pointer's last position and
/// the machine pool.
func persistOnExit() {
persist { settings in
settings.packageID = self.sequencer.current
settings.lastX = self.switcher.edge.lastX
settings.lastY = self.switcher.edge.lastY
settings.setPool(self.switcher.pool)
settings.matrix = self.switcher.matrix
}
}
}