§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]>
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. As shipped, the sinks do not hop withTask { await … }at all: the channel'sEngineSink, the tap's wake-up, the 1 s timer, the permission health check,NSWorkspace.didWakeNotification, the display-change observer and the settings file watcher all push anEngineEventinto oneAsyncStream, and a singleTaskstarted inside the actor (so it inherits its isolation) drains that stream in order. Four callback queues are therefore serialised exactly once.- Draining the capture ring:
EventTap'sonWakeclosure bumps aDispatchSourceUserDataAdd(the shape input-capture asked for: no allocation, no blocking, invariant 4); that source's handler yields.capturedInput, and the actor callsqueue.drain()and handles eachCapturedInputin order:.edgeCandidate→switcher.crossing(...)timestamped withEventTap.now();.key/.mouse→ stamp once with the sequencer and forward to.peer(desMachineID)or.allin ALL mode (C1);.hotkey→ the actions below;.tapLost/.overflow→recoverLocal(reason:). One drain that saw any real input callschannel.noteUserActivity()once — the sessions only ask whether the counter moved since their own previous beat (Common.cs:545-559), so one bump per drain says exactly whatSendAwakeBeatneeds. SwitchActiondispatch (EngineActions.swift) is the port of whatMachineStuff.SwitchToMachine/Helper.HelperThread/Event.csdo around a switch:.send(packet)→ forwarded unchanged (Switcheralready stamped it);.parkCursor→Cursor.parkper the consumer rule (move only whendestinationIsRemote || byHideMouseMessage);.moveCursor→ recorded, and applied only when the machine being switched to is this one, which is whatHelper.HelperThreaddoes (protocol §10.6 note 1); the routing snapshot is rewritten withdestinationandswallowKeys/swallowMouse= remote and not ALL mode (input-capture request 2);channel.markControlled(peerID:)on every switch including back to local (control-channel request 2);injector.releaseAll()on every switch, lock and mode change (MachineStuff.cs:1047,InitAndCleanup.cs:214-243);.persistMatrix/.persistMachinePool→SettingsStore.update.- Hotkeys:
.switchToSlot(n)→releaseAll()thenswitcher.switchToMachine(InputHook.cs:626-655);.lockMachine→ forwardInjector.lockChord(for:)to the machine in control as sequencedKeyboardpackets (input-inject request 1);.lockAllMachines→ ALL mode, chord, back out of ALL mode, thenInjector.lockThisMac()(InputHook.cs:544-566);.reconnect→channel.reopenAll();.toggleEasyMouse→ flip the setting between Disable and Enable only, save, re-apply the configs;.toggleSwitchToAll→ ALL mode;.escapedToLocal→recoverLocal(.escapeHotkey). - Recovery (
Recovery.swift, C2): onerecoverLocal(reason:)on the actor. It routes the snapshot local, and — when control was remote — performsswitcher.switchToMachine(named: localName), which is what Windows does on aByeBye(Common.cs:626), so the machine we were driving is told to park and our own pointer lands in the middle of the primary screen. Windows reaches the same place more slowly on a plain socket error —SocketStuff.cs:1561-1563only marks the machine dead and the 100 ms timer takes control home once nothing is connected (frmScreen.cs:442) — but contracts C2 requires it at once, which is whatSwitcher.connectionLostalready does. Theninjector.releaseAll(),cursor.recouple(to: nil)(show and re-associate without moving — a.tapLostwhile control was already local must not jerk the user's pointer),markControlled(nil)and a log line. Called from: the escape hotkeys,.tapLost,.overflow, a disconnect of the controlled peer for any reason (.closed,.readError,.sendError,.invalidKey,.stall,.timeout, …), Input Monitoring being revoked, andEngine.stop(). The quit/crash path isAppLifecycle.swift'sEmergencyRelease:applicationWillTerminate, anatexithandler and aDispatchSourceSignalfor SIGTERM/SIGINT/SIGHUP, all of which callCursor.restoreEverything()andInjector.releaseAll()synchronously, without the actor — both are documented safe from any thread by their own lanes.Engine.stop()sendsByeBye, waits 150 ms for it to reach the wire (InitAndCleanup.cs:192-215) and then closes. - Reopen countdown (control-channel request 1): a 1 s timer on the
actor; while nothing is connected,
channel.reopenAll()every 30 s, which is both Windows' cadence (frmScreen.cs:425-427,count % 300on a 100 ms timer) and the channel's own connect budget. Also immediately onNSWorkspace.didWakeNotificationand on a display change. Settings(MWBCore/Settings.swift): the rawpropertiestree is what is stored, with typed accessors over it, so properties this port does not implement round-trip untouched and a file shared with a Windows machine never loses the Windows side's settings. Exact PowerToys names,{"value": …}boxing,HotkeySettingsshape and defaults (protocol §10.6 note 5). Stored at~/Library/Application Support/mwb-mac/settings.json, mode 0600, written to a temp file and renamed. First run generatesSecurityKey(SecurityKey.random()),MachineID(Int32.random(in: 1...max),Setting.cs:1048-1070) andDeviceID(UUID).PackageID,LastX,LastY, the pool and the matrix are written on exit. ADispatchSourcefile watcher reloads on external change (Setting.cs:197-207); a key, port, name or id change reopens the sockets, a matrix change is replicated to the peers, everything else rewrites the configs.- Hostname (D7):
gethostname()with the domain suffix stripped, ASCII, ≤ 32. A name that fails is not fatal to the process — the status item says why — but the Engine starts nothing, because a machine nobody can resolve cannot usefully join a matrix. - Placeholder UI:
NSStatusItemwith a title-only first item ("mwb 0.1.0-dev — running — 1 connected — controlling …", or "— permissions missing: …", or "— host name unusable: …"), "Request Permissions…" (the only call toPermissions.request()in the repository, on the user's click), "Reconnect" and Quit.app-uireplaces it. - Logging (
MWBMac/Log.swift):os.Loggerplus a rotating file at~/Library/Logs/mwb-mac/mwb.log(1 MB × 3). No API in the file can take aKeyboardDataor a key string; peer names and statuses are all that is written. - Single instance:
flockon~/Library/Application Support/mwb-mac/mwb.pid; a second launch writes one line to stderr and exits 1.
Handshakes
Consumed
Everything published by wire-core, session-matrix, control-channel, input-capture and input-inject, as their Handshakes sections read on 2026-09-16. Two gaps found while consuming them are filed below.
Promised (to app-ui, clipboard, extras)
As shipped 2026-09-16. Later lanes code against this, not against the sketch this section used to hold.
// MWBCore/Settings.swift
public enum JSONValue: Sendable, Equatable, Codable { case null, bool, int, double, string, array, object }
public enum SettingsError: Error, Equatable { case malformed(String) }
public struct Settings: Sendable, Equatable, Codable {
public static let schemaName: String // "MouseWithoutBorders"
public static let schemaVersion: String // "1.1"
public init() // the PowerToys defaults
// scalars, all PowerToys names:
public var securityKey, machinePoolString, name2IP, deviceID: String
public var wrapMouse, shareClipboard, transferFile, hideMouseAtScreenEdge: Bool
public var validateRemoteMachineIP, sameSubnetOnly, blockScreenSaverOnOtherMachines: Bool
public var moveMouseRelatively, blockMouseAtScreenCorners: Bool
public var showClipboardAndNetworkStatusMessages, disableEasyMouseWhenFullscreen: Bool
public var matrixOneRow: Bool
public var easyMouse: EasyMouseMode
public var easyMouseFullscreenExcludedApps, machineMatrixNames: [String]
public var machineID, lastX, lastY, packageID, hotKeySwitchMachine: Int32
public var tcpPort: UInt16
public var toggleEasyMouseShortcut, lockMachineShortcut, reconnectShortcut,
switch2AllPCShortcut: Hotkey
// derived:
public var matrix: Matrix // get and set
public func pool(now: TimeInterval) -> MachinePool
public mutating func setPool(_ pool: MachinePool)
public var hotkeys: HotkeyConfig // read-only, for CaptureConfig
@discardableResult public mutating func generateMissingIdentities() -> Bool
public static func defaultURL() -> URL
public static func load(from url: URL) throws -> Settings
public func save(to url: URL) throws // atomic, 0600
}
public final class SettingsStore: @unchecked Sendable {
public init(url: URL = Settings.defaultURL()) throws
public var fileURL: URL { get }
public var current: Settings { get } // any thread
public func update(_ body: (inout Settings) -> Void) throws
public func onExternalChange(_ handler: @escaping @Sendable (Settings) -> Void)
public func startWatching(); public func stopWatching()
}
// MWBMac/Log.swift
public struct Log: Sendable {
public static let engine, app, settings: Log
public static let subsystem: String
public init(category: String)
public func info(_ message: String); public func error(_ message: String)
public func debug(_ message: String) // os.Logger only, never the file
public static func fileURL() -> URL
public static func startFileLogging(); public static func stopFileLogging()
}
// mwb/Engine.swift
public enum RecoveryReason: Sendable, Equatable {
case escapeHotkey, tapLost, captureOverflow, controlledPeerLost(String?),
permissionsLost, quitting
public var text: String
}
public struct RecoveryNote: Sendable, Equatable { public var reason: RecoveryReason; public var at: Date }
public struct EngineSnapshot: Sendable {
public var peers: [PeerStatus]; public var controlled: String?; public var broadcasting: Bool
public var permissions: PermissionState; public var tapRunning, canInject: Bool
public var easyMouse: EasyMouseMode; public var localName: String
public var hostnameProblem: String?; public var lastRecovery: RecoveryNote?
}
public actor Engine {
public init(store: SettingsStore, localName: String, hostnameProblem: String? = nil)
public func start()
public func stop() async
public func observe(_ handler: @escaping @Sendable (EngineSnapshot) -> Void)
public var snapshot: EngineSnapshot { get }
public func apply(_ new: Settings) // after an external settings change
public func switchTo(slot: Int); public func switchToAll()
public func reconnect(); public func toggleEasyMouse()
public func lockControlledMachine(); public func lockAll()
public func recoverLocal(reason: RecoveryReason)
// `let` properties of Sendable type, so they read without `await`:
let injector: Injector; let cursor: Cursor; let screens: Screens
}
Six deviations from the shape sketched at planning time, all deliberate:
Engine.inittakeslocalNameandhostnameProblem, not just the store, and does notthrow. Resolving and validating the host name is the process's job (D7) and its failure has to be reportable in the menu bar; an Engine that threw would leave nothing to report with.SettingsStore.initis the throwing part, andAppDelegatecatches it.Settings.poolispool(now:)+setPool(_:), not avar.MachinePool(string:now:)needs a clock andMWBCorehas none.SettingsStore.onExternalChangeis a method, not a settable property, so the store needs no lock discipline at the call site.Engine.stop()isasync— it waits 150 ms betweensayGoodbye()andstop()so theByeByereaches the wire, which is the Windows order (InitAndCleanup.cs:192-215).observe(_:)replacesvar onSnapshotChange: a settable closure property on an actor isawait-only to set and awkward to call.lastRecoveryis aRecoveryNotestruct, not a tuple, so the snapshot staysSendableand printable.
Rules the consuming lanes must honour:
- Nothing but the Engine stamps a packet
Id(contracts C1). A lane that wants to send something adds an Engine method; it does not reach for the sequencer or the channel. Settingsround-trips unknown properties. Never rebuild the properties dictionary from a fixed list — adding a property means adding an accessor, and the Windows side's settings survive.Permissions.request()may be called from exactly one place, the menu item the user clicks (CLAUDE.md, Workflow).
Requested of session-matrix (open)
PacketSequenceris used from two queues by design and is not thread-safe. Contracts C1 says the process has one sequencer and that the app stamps application packets; the Engine therefore callssequencer.next()on the actor while eachSessioncalls it on the channel's queue for its ownHandshake/heartbeat/Hi/ByeBye(Session.swift:402-403).next()isvalue = value &+ 1with no synchronisation, so a lost update can hand two packets the sameIdand the receiver's replay ring will drop the second. It cannot be fixed from this lane's files: please makePacketSequencerhold its counter in anOSAllocatedUnfairLock(orAtomic<Int32>) and declare itSendable.ReplayFilteris only ever touched on the channel's queue and is fine as it is.
Requested of input-capture (open)
PermissionStatehas no public initialiser. It declarespublic let listen/public let postand noinit, so the memberwise one isinternaland no other target can build a value —EngineSnapshot's default has to callPermissions.preflight(), which is a TCC query. Please addpublic init(listen: Bool, post: Bool).Cursorpublishes no "where is the pointer now". The relative-modeNextMachinepath needsGetCursorPoson the receiving side (Receiver.cs:154, protocol §10.6 note 3), soEngine.pointerPosition()reads it withCGEvent(source: nil)?.location. ACursor.positionwould keep the one remaining CoreGraphics call out ofmwb.
Requested of control-channel (open)
- No way to send a
Heartbeaton demand.Receiver.cs:253answers a peer'sHellowithCommon.SendHeartBeat()so the peer learns us immediately. OurSessionalready sends one right after the handshake (Session.swift:381), so nothing is broken today, but theHellocase inEngine.dispatchis a no-op where Windows replies.
Requested of app-ui (open)
- The matrix, the pool and the security key are edited through
SettingsStore.update; the Engine notices through the file watcher and re-applies everything. There is no second path, and there must not be one. EngineSnapshot.hostnameProblem,.permissionsand.canInjectare the three states that mean "this app cannot do its job" and all three want a visible colour, not a log line.
Answering the earlier lanes' open requests
| request | answer |
|---|---|
| control-channel 1: reopen countdown | Recovery.reopenCountdown(), 30 s while connectedIDs is empty, plus wake and display change |
control-channel 2: markControlled on every switch |
EngineActions.syncRouting(), which every perform(_:) ends with — including back to local (nil) |
input-capture 1: EventTap.now() timestamps |
every Switcher/Edge call in the Engine uses it |
| input-capture 2: Engine owns the swallow flags | syncRouting(): swallowKeys/swallowMouse = destinationIsRemote, so false in ALL mode |
input-capture 3: releaseAll + recouple + housekeeping after .tapLost/.overflow/.escapedToLocal |
all three land in recoverLocal(reason:) |
input-capture 4: Screens.startObserving() on the main thread |
AppDelegate.startEngine(), after NSApplication.shared exists |
| input-inject 1: lock chord forwarding | EngineActions.forwardLockChord(to:), single press and double press |
input-inject 2: releaseAll() on every C2 row, switch, mode change and lock |
recoverLocal, SwitchAction.releaseAllKeys, switchTo(slot:) |
input-inject 3: ScreenLayout into every inject |
Engine.dispatch passes screens.layout |
input-inject 4: HotKeyLockMachine → InjectorConfig.lockMachine |
applyConfiguration(), re-applied on every settings change |
input-inject 5: show canInject |
EngineSnapshot.canInject, rendered in the status item |
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). TheChannelConfig/CaptureConfig/InjectorConfighalf of the mapping lives inmwb/EngineActions.swift, because those types are inMWBNetandMWBMacandMWBCoremay not import either.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). Not done, deliberately, with reasons:MachineSwitchedand everyClipboard*case are the clipboard lane's;Awakedoes not yet call the equivalent ofCommon.HumanBeingDetected()(it needsIOPMAssertionDeclareUserActivity, i.e. IOKit, which this lane may not import, and the receive half ofBlockScreenSaverOnOtherMachinesis the extras lane, CP3);Heartbeat_ex/_l2/_l3key propagation is out of scope (README D6).Sources/mwb/EngineActions.swift:SwitchActionand hotkey dispatch per Assumptions (MachineStuff.cs:1008-1050,InputHook.cs:516-655).Sources/mwb/Recovery.swift:recoverLocal, every C2 trigger wired, reopen countdown (frmScreen.cs:425-449).Sources/mwb/AppLifecycle.swift+main.swift:NSApplicationdelegate, placeholder status item, single instance, signal/atexit handlers, wake/screen notifications,--check-permissionsand--versionkept.docs/protocol.md: appended §10.6 with six findings, cited.
Work log
-
2026-09-16 (dev) — lane built in one pass on
mainfromca9be2e; three commits. Gates green on the last one.What was built.
MWBCore/Settings.swift(the PowerToys schema over a raw property tree, plusSettingsStore),MWBMac/Log.swift(os.Logger+ a 1 MB × 3 file), and the fourmwbfiles:Engine.swift(the actor, the singleAsyncStreamevery callback funnels through, the capture drain, and theProcessPackageport),EngineActions.swift(SwitchAction, the hotkeys, andSettings→ every lane's config),Recovery.swift(C2 and the reopen countdown) andAppLifecycle.swift(single instance,NSApplication, the placeholder status item and the emergency release), withmain.swiftgaining the no-argument "run the app" case.Key decisions.
- One
AsyncStream, not per-callbackTasks. The brief allowedTask { await engine.… }hops; an unboundedAsyncStreamplus a pumpTaskstarted inside the actor is strictly better — it inherits the actor's isolation, so ordering across the channel queue, the tap thread, two timers and three notification observers is guaranteed by construction rather than by hope. - The tap wake-up goes through a
DispatchSourceUserDataAdd.AsyncStream.Continuation.yieldallocates;source.add(data: 1)is an atomic add. That is the shape input-capture asked for and keeps invariant 4 honest, and it coalesces many wake-ups into one drain. .moveCursoris recorded, not obeyed. ReadingHelper.HelperThreadclosely (protocol §10.6 note 1) showed the Windows pointer only goes toSwitchLocationwhen the machine being switched to is the local one; obeying it unconditionally would throw the user's pointer at the remote landing coordinates on every switch away.noteCursorLandingtherefore stores a target andsyncRoutingapplies it when it recouples.syncRouting()is the tail of everyperform(_:). The routing snapshot,markControlledand the cursor's coupling are three things that must always agree withSwitcher.desMachineID; deriving all three in one place after the actions have run is the only way to be sure a newSwitchActioncannot forget one of them.recoverLocalends withcursor.recouple(to: nil). An early draft recoupled to the remembered park position, which would have jerked the pointer to the top of the screen whenever.tapLostor a revoked grant fired while control was already local.nilmeans "show and re-associate, do not move", and it is idempotent.DispatchSourceSignal, notsignal(2). A C signal handler may only call async-signal-safe functions, and the emergency release doesqueue.syncand postsCGEvents. A dispatch signal source runs the same code on an ordinary queue, which is both safe and still catches SIGTERM/SIGINT/SIGHUP.atexitkeeps the C handler becauseatexithandlers do not run in signal context.
Deviations from the brief and the Assumptions as written.
- Reopen countdown is 30 s, not the 10 s this README sketched.
Windows checks
count % 300on a 100 ms timer (frmScreen.cs:427) and the control-channel lane's request 1 says 30 s explicitly; 30 s also coincides with the channel's own connect budget, so the countdown fires exactly as the budget expires instead of resetting a live one every 10 s. Engine.initsignature and five smaller API shapes: listed under Handshakes with reasons.NextMachineis accepted only whileEasyMouse == Enable. Windows also accepts it while the Ctrl/Shift Easy-Mouse key is held (Event.IsSwitchingByMouseEnabled), but that flag lives inside the tap and is not published. Affects only the two non-default Easy Mouse modes combined withMoveMouseRelatively; noted in protocol §10.6 note 3 and worth a line in the extras lane.- An empty matrix is seeded with this Mac's own name in slot 0 at first start, so the settings file is self-explanatory. Windows shows its setup form instead; a peer's name still has to be added by hand (or by app-ui) before anything is dialled.
Settings.swiftis 628 lines andEngine.swift598 — over the 300–600 target, under the 800 "consider splitting" line. Splitting either would mean a file outside this lane's list.
Verification.
tools/gates.shgreen (lint --strict, MWBCore layering, build with warnings-as-errors);.build/debug/mwb --versionand--check-permissionsboth behave as before (the latter exits 3 on this machine, which has neither grant). The app itself was not launched: doing so would create an event tap, post events and trigger TCC prompts (CLAUDE.md invariant 5 and the lane brief). Everything fromNSApplication.run()inwards — the status item, the tap, the channel, every C2 row — is unexercised and is CP1's job. - One