// 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 } } }