Files
mac_without_borders/docs/features/app-engine
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
..

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

  • Engine is one actor in the mwb target. 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 with Task { await … } at all: the channel's EngineSink, 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 an EngineEvent into one AsyncStream, and a single Task started 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's onWake closure bumps a DispatchSourceUserDataAdd (the shape input-capture asked for: no allocation, no blocking, invariant 4); that source's handler yields .capturedInput, and the actor calls queue.drain() and handles each CapturedInput in order: .edgeCandidate → switcher.crossing(...) timestamped with EventTap.now(); .key/.mouse → stamp once with the sequencer and forward to .peer(desMachineID) or .all in ALL mode (C1); .hotkey → the actions below; .tapLost/.overflow → recoverLocal(reason:). One drain that saw any real input calls channel.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 what SendAwakeBeat needs.
  • SwitchAction dispatch (EngineActions.swift) is the port of what MachineStuff.SwitchToMachine / Helper.HelperThread / Event.cs do around a switch: .send(packet) → forwarded unchanged (Switcher already stamped it); .parkCursor → Cursor.park per the consumer rule (move only when destinationIsRemote || byHideMouseMessage); .moveCursor → recorded, and applied only when the machine being switched to is this one, which is what Helper.HelperThread does (protocol §10.6 note 1); the routing snapshot is rewritten with destination and swallowKeys/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() then switcher.switchToMachine (InputHook.cs:626-655); .lockMachine → forward Injector.lockChord(for:) to the machine in control as sequenced Keyboard packets (input-inject request 1); .lockAllMachines → ALL mode, chord, back out of ALL mode, then Injector.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): one recoverLocal(reason:) on the actor. It routes the snapshot local, and — when control was remote — performs switcher.switchToMachine(named: localName), which is what Windows does on a ByeBye (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-1563 only 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 what Switcher.connectionLost already does. Then injector.releaseAll(), cursor.recouple(to: nil) (show and re-associate without moving — a .tapLost while 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, and Engine.stop(). The quit/crash path is AppLifecycle.swift's EmergencyRelease: applicationWillTerminate, an atexit handler and a DispatchSourceSignal for SIGTERM/SIGINT/SIGHUP, all of which call Cursor.restoreEverything() and Injector.releaseAll() synchronously, without the actor — both are documented safe from any thread by their own lanes. Engine.stop() sends ByeBye, 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 % 300 on a 100 ms timer) and the channel's own connect budget. Also immediately on NSWorkspace.didWakeNotification and on a display change.
  • Settings (MWBCore/Settings.swift): the raw properties tree 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, HotkeySettings shape 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 generates SecurityKey (SecurityKey.random()), MachineID (Int32.random(in: 1...max), Setting.cs:1048-1070) and DeviceID (UUID). PackageID, LastX, LastY, the pool and the matrix are written on exit. A DispatchSource file 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: NSStatusItem with 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 to Permissions.request() in the repository, on the user's click), "Reconnect" and Quit. app-ui replaces it.
  • Logging (MWBMac/Log.swift): os.Logger plus a rotating file at ~/Library/Logs/mwb-mac/mwb.log (1 MB × 3). No API in the file can take a KeyboardData or a key string; peer names and statuses are all that is written.
  • Single instance: flock on ~/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.init takes localName and hostnameProblem, not just the store, and does not throw. 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.init is the throwing part, and AppDelegate catches it.
  • Settings.pool is pool(now:) + setPool(_:), not a var. MachinePool(string:now:) needs a clock and MWBCore has none.
  • SettingsStore.onExternalChange is a method, not a settable property, so the store needs no lock discipline at the call site.
  • Engine.stop() is async — it waits 150 ms between sayGoodbye() and stop() so the ByeBye reaches the wire, which is the Windows order (InitAndCleanup.cs:192-215).
  • observe(_:) replaces var onSnapshotChange: a settable closure property on an actor is await-only to set and awkward to call.
  • lastRecovery is a RecoveryNote struct, not a tuple, so the snapshot stays Sendable and 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.
  • Settings round-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)

  1. PacketSequencer is 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 calls sequencer.next() on the actor while each Session calls it on the channel's queue for its own Handshake/heartbeat/Hi/ByeBye (Session.swift:402-403). next() is value = value &+ 1 with no synchronisation, so a lost update can hand two packets the same Id and the receiver's replay ring will drop the second. It cannot be fixed from this lane's files: please make PacketSequencer hold its counter in an OSAllocatedUnfairLock (or Atomic<Int32>) and declare it Sendable. ReplayFilter is only ever touched on the channel's queue and is fine as it is.

Requested of input-capture (open)

  1. PermissionState has no public initialiser. It declares public let listen / public let post and no init, so the memberwise one is internal and no other target can build a value — EngineSnapshot's default has to call Permissions.preflight(), which is a TCC query. Please add public init(listen: Bool, post: Bool).
  2. Cursor publishes no "where is the pointer now". The relative-mode NextMachine path needs GetCursorPos on the receiving side (Receiver.cs:154, protocol §10.6 note 3), so Engine.pointerPosition() reads it with CGEvent(source: nil)?.location. A Cursor.position would keep the one remaining CoreGraphics call out of mwb.

Requested of control-channel (open)

  1. No way to send a Heartbeat on demand. Receiver.cs:253 answers a peer's Hello with Common.SendHeartBeat() so the peer learns us immediately. Our Session already sends one right after the handshake (Session.swift:381), so nothing is broken today, but the Hello case in Engine.dispatch is a no-op where Windows replies.

Requested of app-ui (open)

  1. 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.
  2. EngineSnapshot.hostnameProblem, .permissions and .canInject are 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). The ChannelConfig/CaptureConfig/ InjectorConfig half of the mapping lives in mwb/EngineActions.swift, because those types are in MWBNet and MWBMac and MWBCore may 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.cs ProcessPackage cases for Mouse, Keyboard, HideMouse, MachineSwitched, NextMachine, Matrix, Heartbeat/Awake/Hello learning, ByeBye). Not done, deliberately, with reasons: MachineSwitched and every Clipboard* case are the clipboard lane's; Awake does not yet call the equivalent of Common.HumanBeingDetected() (it needs IOPMAssertionDeclareUserActivity, i.e. IOKit, which this lane may not import, and the receive half of BlockScreenSaverOnOtherMachines is the extras lane, CP3); Heartbeat_ex/_l2/_l3 key propagation is out of scope (README D6).
  • Sources/mwb/EngineActions.swift: SwitchAction and 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: NSApplication delegate, placeholder status item, single instance, signal/atexit handlers, wake/screen notifications, --check-permissions and --version kept.
  • docs/protocol.md: appended §10.6 with six findings, cited.

Work log

  • 2026-09-16 (dev) — lane built in one pass on main from ca9be2e; three commits. Gates green on the last one.

    What was built. MWBCore/Settings.swift (the PowerToys schema over a raw property tree, plus SettingsStore), MWBMac/Log.swift (os.Logger + a 1 MB × 3 file), and the four mwb files: Engine.swift (the actor, the single AsyncStream every callback funnels through, the capture drain, and the ProcessPackage port), EngineActions.swift (SwitchAction, the hotkeys, and Settings → every lane's config), Recovery.swift (C2 and the reopen countdown) and AppLifecycle.swift (single instance, NSApplication, the placeholder status item and the emergency release), with main.swift gaining the no-argument "run the app" case.

    Key decisions.

    1. One AsyncStream, not per-callback Tasks. The brief allowed Task { await engine.… } hops; an unbounded AsyncStream plus a pump Task started 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.
    2. The tap wake-up goes through a DispatchSourceUserDataAdd. AsyncStream.Continuation.yield allocates; 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.
    3. .moveCursor is recorded, not obeyed. Reading Helper.HelperThread closely (protocol §10.6 note 1) showed the Windows pointer only goes to SwitchLocation when 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. noteCursorLanding therefore stores a target and syncRouting applies it when it recouples.
    4. syncRouting() is the tail of every perform(_:). The routing snapshot, markControlled and the cursor's coupling are three things that must always agree with Switcher.desMachineID; deriving all three in one place after the actions have run is the only way to be sure a new SwitchAction cannot forget one of them.
    5. recoverLocal ends with cursor.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 .tapLost or a revoked grant fired while control was already local. nil means "show and re-associate, do not move", and it is idempotent.
    6. DispatchSourceSignal, not signal(2). A C signal handler may only call async-signal-safe functions, and the emergency release does queue.sync and posts CGEvents. A dispatch signal source runs the same code on an ordinary queue, which is both safe and still catches SIGTERM/SIGINT/SIGHUP. atexit keeps the C handler because atexit handlers 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 % 300 on 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.init signature and five smaller API shapes: listed under Handshakes with reasons.
    • NextMachine is accepted only while EasyMouse == 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 with MoveMouseRelatively; 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.swift is 628 lines and Engine.swift 598 — 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.sh green (lint --strict, MWBCore layering, build with warnings-as-errors); .build/debug/mwb --version and --check-permissions both 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 from NSApplication.run() inwards — the status item, the tap, the channel, every C2 row — is unexercised and is CP1's job.

QA log

Review