app-engine
Goal
The part of the app that makes the pieces a running program: the
Engine actor that contracts C1–C3 name as the owner of all shared
state, the Settings model in the PowerToys schema, the mapping from
settings to every lane's config struct (C4), the wiring
tap → edge → switcher → channel → injector, and every recovery row of
C2 implemented end-to-end. It ships mwb as a real NSApplication
(LSUIElement) with a placeholder status item — just enough to run —
so the lead can smoke it headless before the app-ui lane builds the
real menu and settings window. This is the lane that finally answers
the open requests lanes 3, 4 and 5 left for "app-shell".
Assumptions
Engineis oneactorin themwbtarget. It owns:Switcher,PacketSequencer,ReplayFilter,ControlChannel,EventTap,RoutingState,CaptureQueue,Injector,Cursor,Screens,Settings. Nothing else holds a reference to those except through the Engine. TheEngineSinkimplementation is a smallfinal classthat hops into the actor withTask { await engine.… }— ordering between hops is preserved by a singleAsyncStreamof sink events that the actor consumes in order, not by independentTasks.- Draining the capture ring:
EventTap'sonWakeclosure resumes anAsyncStreamcontinuation; the actor's drain loopfor awaits it and callsqueue.drain(), handling eachCapturedInputin order:.edgeCandidate→switcher.crossing(...)timestamped withEventTap.now()(input-capture request);.key/.mouse→ stamp once with the sequencer,channel.forward(packet, to: .peer(desMachineID))or.allin ALL mode (C1);.hotkey→ the actions below;.tapLost/.overflow/.escapedToLocal→ the recovery routine. SwitchActiondispatch (EngineActions.swift) is the port of whatMachineStuff.SwitchToMachine/Helper.HelperThread/Event.csdo around a switch:.send(packet)→ stamp + forward;.parkCursor→Cursor.parkper the consumer rule (move only whendestinationIsRemote || byHideMouseMessage); routing snapshot rewritten withdestination,swallowKeys/swallowMouse= remote and not ALL mode (input-capture request),easyMouse, hotkeys;channel.markControlled(peerID:)on every switch including back to local (control-channel request);injector.releaseAll()on every switch/lock/mode change (MachineStuff.cs:1025,InitAndCleanup.cs:214-243);.persist→ save settings.- Hotkeys:
.switchMachine(slot)→switcher.switchToSlot;.lockMachine→ forwardInjector.lockChord(for:)to the controlled peer as sequencedKeyboardpackets (input-inject request), then lock locally when the double-press rule says ALL (InputHook.cs:539-577);.reconnect→channel.reopenAll();.toggleEasyMouse→ flip the setting, save, rewrite the snapshot;.switchToAll→ ALL mode. - Recovery (
Recovery.swift, C2): onerecoverLocal(reason:)on the actor that routes local inSwitcher, rewrites the snapshot, callsinjector.releaseAll(),cursor.recouple(to: lastLocal),channel.markControlled(nil)and logs the reason. Called from: escape hotkeys (the tap already flipped the snapshot; the actor finishes the job),.tapLost,.overflow, channeldisconnectedfor the controlled peer (any reason),Permissionshealth-check loss, and the quit/crash path. The quit/crash path isAppLifecycle.swift:applicationWillTerminate, plussignal(SIGTERM/SIGINT/SIGHUP)andatexithandlers that call the injector'sreleaseAll()andCursor.recouplesynchronously without the actor (they cannot await) — both are documented as safe from any thread — and sendByeByeviachannel.sayGoodbye()best-effort. - Reopen countdown (control-channel request,
frmScreen.cs:427-461): the actor keeps a 1 s timer; while any matrix name has no connected client, every 10 s it callschannel.reopenAll(); on wake (NSWorkspace.didWakeNotification) and screen change immediately. Settings(MWBCore/Settings.swift): aCodablestruct with the exact PowerToys property names, types and defaults from README §Settings, wrapped in{"name":"MouseWithoutBorders","version":"1.1", "properties":{…}}; unknown keys preserved on save (decode into a dictionary, overlay known keys). Stored at~/Library/Application Support/mwb-mac/settings.json, mode 0600, written atomically (temp + rename). First run generatesSecurityKey(SecurityKey.random()),MachineID(random positiveInt32,Setting.cs:1048-1083),DeviceID(UUID).PackageIDis written fromsequencer.currenton save and on quit (Common.cs:906).MachineMatrixString/MachinePoolround-trip throughMatrix(string:)/MachinePool(string:). ADispatchSourcefile watcher reloads on external change (Setting.cs:197-207); a change of key, port or matrix triggerschannel.reconfigure; others rewrite the snapshot/configs.- Hostname (D7):
gethostname()with.local/domain suffix stripped, ASCII, ≤ 32; otherwise the app refuses to start the channel and shows the reason in the status item. - Placeholder UI:
NSStatusItemwith a title-only menu ("mwb 0.1.0-dev — running" / "— permissions missing: …" / "— hostname invalid"), "Request Permissions…" (the only placePermissions.request()is called, on the user's click), and Quit.app-uireplaces it. - Logging (
MWBMac/Log.swift):os.Loggerplus a rotating file at~/Library/Logs/mwb-mac/mwb.log(1 MB × 3). Never key material, never keystrokes; peer names and statuses are fine. - Single instance:
flockon~/Library/Application Support/mwb-mac/mwb.pid; a second launch exits 1 with a message.
Handshakes
Consumed
Everything published by wire-core, session-matrix, control-channel, input-capture and input-inject, exactly as their Handshakes sections read today. If an API turns out to be missing or wrong, the Dev files a request in this README and stops that item — it does not edit the other lane's files.
Promised (to app-ui, clipboard, extras)
public struct Settings: Codable, Sendable { … every README §Settings property …; static func load(from:) throws -> Settings; func save(to:) throws; var matrix: Matrix; var pool: MachinePool }
public final class SettingsStore { init(url:); var current: Settings; func update(_ f: (inout Settings) -> Void) throws; var onExternalChange: ((Settings) -> Void)? }
actor Engine {
init(settings: SettingsStore) throws
func start() throws; func stop()
func apply(_ settings: Settings) // re-maps every config
var snapshot: EngineSnapshot // for the UI: peers + statuses, controlled machine, permissions, easy mouse on/off, last error
func switchTo(slot: Int); func switchToAll(); func reconnect(); func lockAll(); func toggleEasyMouse()
func recoverLocal(reason: RecoveryReason)
var onSnapshotChange: (@Sendable (EngineSnapshot) -> Void)?
}
public struct EngineSnapshot: Sendable { peers: [PeerStatus]; controlled: String?; permissions: PermissionState; easyMouseEnabled: Bool; hostnameProblem: String?; lastRecovery: (RecoveryReason, Date)? }
Status / TODO
Sources/MWBCore/Settings.swift: schema, defaults, load/save, first-run generation, matrix/pool round-trip, config mapping (C4) (MouseWithoutBordersProperties.cs:165-206,Setting.cs:479-511, 1048-1083,Common.cs:906).Sources/MWBMac/Log.swift: logger + rotating file.Sources/mwb/Engine.swift: the actor, sink stream, drain loop, C1 forwarding, packet dispatch (Receiver.csProcessPackagecases for Mouse, Keyboard, HideMouse, MachineSwitched, NextMachine, Matrix, Heartbeat/Awake/Hello learning, ByeBye).Sources/mwb/EngineActions.swift:SwitchActionand hotkey dispatch per Assumptions (MachineStuff.cs:1007-1050,InputHook.cs:539-658).Sources/mwb/Recovery.swift:recoverLocal, every C2 trigger wired, reopen countdown (frmScreen.cs:427-461).Sources/mwb/AppLifecycle.swift+main.swift:NSApplicationdelegate, placeholder status item, single instance, signal/atexit handlers, wake/screen notifications,--check-permissionsand--versionkept.docs/protocol.md: append §10.6 with anything learned, cited.