Files
mac_without_borders/Sources/mwb/Recovery.swift
T
lucioandClaude Opus 5 c4741fcfeb app-engine: the Engine actor, its actions, recovery and the app shell
Engine.swift is the actor contracts C3 names: it owns the Switcher, the
sequencer, the replay filter, the channel, the tap, the routing state,
the capture ring, the injector, the cursor and the screens, and it is
the only thing that stamps an Id (contracts C1). Every callback — the
channel's sink, the tap's wake-up, the timers, the workspace and
settings observers — funnels through one AsyncStream so four queues are
serialised once instead of racing as free Tasks. `dispatch` is the port
of Receiver.ProcessPackage (Receiver.cs:86-390), long on purpose.

EngineActions.swift performs [SwitchAction] (MachineStuff.cs:1008-1050,
Helper.cs:73-127), the hotkeys (InputHook.cs:516-655) and the mapping
from Settings onto every lane's config struct (contracts C4).

Recovery.swift is contracts C2 end to end: escape hotkey, controlled
peer lost, tap lost, capture overflow, revoked permission, quit — each
ending in route-local, releaseAll and a pointer that is coupled again —
plus the reopen countdown (frmScreen.cs:427-450).

AppLifecycle.swift is the process: flock single instance, the
LSUIElement NSApplication with a placeholder status item, the
DispatchSourceSignal + atexit emergency release, and hostname
validation (README D7).

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

120 lines
5.2 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/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 uses on every one of
// these rows (`Common.cs:626`, `MachineStuff.cs:691`), 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.
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
}
}
}