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]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-09-16 03:35:37 -07:00
1 parent c4741fcfeb
commit fc7a54b40a
5 files changed
+464 -108

No files matched your search

+4 -4
View File
@@ -5,7 +5,7 @@
// Ported from App/Core/MachineStuff.cs `SwitchToMachine` (1008-1028) and
// `SwitchToMultipleMode` (1030-1050), App/Core/Helper.cs `HelperThread`
// (73-127), App/Class/InputHook.cs `ProcessHotKeys` (516-621) and `Switch2`
// (623-655), App/Core/InitAndCleanup.cs `ReleaseAllKeys` (214-243).
// (626-655), App/Core/InitAndCleanup.cs `ReleaseAllKeys` (214-243).
import AppKit
import Foundation
@@ -126,14 +126,14 @@ extension Engine {
}
}
/// `Switch2` (`InputHook.cs:623-655`): release everything, then hand control
/// `Switch2` (`InputHook.cs:626-655`): release everything, then hand control
/// to the machine in that matrix slot. An empty slot does nothing.
public func switchTo(slot: Int) {
let names = switcher.matrix.names
guard slot >= 0, slot < names.count else { return }
let name = names[slot].trimmingCharacters(in: .whitespaces)
guard !name.isEmpty else { return }
injector.releaseAll() // InputHook.cs:632
injector.releaseAll() // InputHook.cs:635
perform(switcher.switchToMachine(named: name, now: EventTap.now()))
}
@@ -170,7 +170,7 @@ extension Engine {
forwardLockChord(to: des)
}
/// A double press (`InputHook.cs:546-566`): broadcast the chord to everyone,
/// A double press (`InputHook.cs:544-566`): broadcast the chord to everyone,
/// come back out of ALL mode, then lock this Mac too.
public func lockAll() {
perform(switcher.switchToBroadcast(true, centerCursor: true))
+9 -5
View File
@@ -8,7 +8,8 @@
// 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/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).
@@ -28,10 +29,13 @@ extension Engine {
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.
// `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())
+5 -5
View File
@@ -118,28 +118,28 @@ concurrency, shared constants, checkpoints) is fixed in `docs/contracts.md`.
## 6. app-engine (app + core) — `Sources/mwb/main.swift`, `Sources/mwb/Engine.swift`, `Sources/mwb/EngineActions.swift`, `Sources/mwb/Recovery.swift`, `Sources/mwb/AppLifecycle.swift`, `Sources/MWBCore/Settings.swift`, `Sources/MWBMac/Log.swift`
- [ ] `Settings`: PowerToys schema (README §Settings), JSON load/save at
- [x] `Settings`: PowerToys schema (README §Settings), JSON load/save at
`~/Library/Application Support/mwb-mac/settings.json` (0600),
file watch, random key / `MachineID` / `DeviceID` on first run,
`LastX/LastY/PackageID` persistence, hostname validation (D7);
mapping to `SessionConfig`/`ChannelConfig`/`EdgeConfig`/
`CaptureConfig`/`InjectorConfig` (C4).
- [ ] The `Engine` actor (C3): owns Switcher, sequencer, replay filter,
- [x] The `Engine` actor (C3): owns Switcher, sequencer, replay filter,
channel, tap, routing state, capture queue, injector, cursor,
screens; publishes the routing snapshot; drains the capture ring;
stamps ids once and forwards to every target (C1); dispatches
`.packet` events to injector / switcher; applies every
`SwitchAction`.
- [ ] Recovery wiring (C2): every trigger row end-to-end — escape
- [x] Recovery wiring (C2): every trigger row end-to-end — escape
hotkeys, controlled-peer disconnect, 30 s silence, outbound stall,
tap disable, permission loss, quit/crash handler — each ending in
route-local + `releaseAll` + `Cursor.recouple`.
- [ ] Open requests from lanes 3–5: reopen countdown while nothing is
- [x] Open requests from lanes 3–5: reopen countdown while nothing is
connected; `markControlled` on every switch; `EventTap.now()`
timestamps; swallow flags (false in ALL mode); lock chord
forwarding; layout into every `inject`; `HotKeyLockMachine` →
`InjectorConfig`; `Screens.startObserving()` on main; `canInject`.
- [ ] `mwb` runs as an `NSApplication` (LSUIElement) with a minimal
- [x] `mwb` runs as an `NSApplication` (LSUIElement) with a minimal
status item showing only "mwb: running / permissions missing"
and Quit — enough to run headless for CP0 smoke by the lead; the
real UI is lane 7. `mwb --check-permissions` kept. Single
+378 -94
View File
@@ -19,134 +19,418 @@ the open requests lanes 3, 4 and 5 left for "app-shell".
`PacketSequencer`, `ReplayFilter`, `ControlChannel`, `EventTap`,
`RoutingState`, `CaptureQueue`, `Injector`, `Cursor`, `Screens`,
`Settings`. Nothing else holds a reference to those except through
the Engine. The `EngineSink` implementation is a small
`final class` that hops into the actor with `Task { await engine.… }`
— ordering between hops is preserved by a single `AsyncStream` of
sink events that the actor consumes in order, not by independent
`Task`s.
- **Draining the capture ring**: `EventTap`'s `onWake` closure resumes
an `AsyncStream` continuation; the actor's drain loop `for await`s it
and calls `queue.drain()`, handling each `CapturedInput` in order:
`.edgeCandidate` → `switcher.crossing(...)` timestamped with
`EventTap.now()` (input-capture request); `.key`/`.mouse` → stamp once
with the sequencer, `channel.forward(packet, to: .peer(desMachineID))`
or `.all` in ALL mode (C1); `.hotkey` → the actions below;
`.tapLost`/`.overflow`/`.escapedToLocal` → the recovery routine.
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)` → stamp + forward; `.parkCursor`
→ `Cursor.park` per the consumer rule (move only when
`destinationIsRemote || byHideMouseMessage`); routing snapshot
rewritten with `destination`, `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` → forward `Injector.lockChord(for:)` to the controlled
peer as sequenced `Keyboard` packets (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.
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 that routes local in `Switcher`, rewrites the snapshot, calls
`injector.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`, channel `disconnected` for the
controlled peer (any reason), `Permissions` health-check loss, and the
quit/crash path. The quit/crash path is `AppLifecycle.swift`:
`applicationWillTerminate`, plus `signal(SIGTERM/SIGINT/SIGHUP)` and
`atexit` handlers that call the injector's `releaseAll()` and
`Cursor.recouple` **synchronously without the actor** (they cannot
await) — both are documented as safe from any thread — and send
`ByeBye` via `channel.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 calls `channel.reopenAll()`; on wake
(`NSWorkspace.didWakeNotification`) and screen change immediately.
- **`Settings`** (`MWBCore/Settings.swift`): a `Codable` struct 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
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 atomically (temp + rename). First run generates
`SecurityKey` (`SecurityKey.random()`), `MachineID` (random positive
`Int32`, `Setting.cs:1048-1083`), `DeviceID` (UUID).
`PackageID` is written from `sequencer.current` on save and on quit
(`Common.cs:906`). `MachineMatrixString` / `MachinePool` round-trip
through `Matrix(string:)` / `MachinePool(string:)`. A
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 change of key, port or matrix triggers
`channel.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**: `NSStatusItem` with a title-only menu ("mwb
0.1.0-dev — running" / "— permissions missing: …" / "— hostname
invalid"), "Request Permissions…" (the only place `Permissions.request()`
is called, on the user's click), and Quit. `app-ui` replaces it.
(`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). Never key material,
never keystrokes; peer names and statuses are fine.
`~/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
exits 1 with a message.
writes one line to stderr and exits 1.
## 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.
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)
```swift
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)? }
As shipped 2026-09-16. Later lanes code against this, not against the
sketch this section used to hold.
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)?
```swift
// 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
}
public struct EngineSnapshot: Sendable { peers: [PeerStatus]; controlled: String?; permissions: PermissionState; easyMouseEnabled: Bool; hostnameProblem: String?; lastRecovery: (RecoveryReason, Date)? }
```
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,
- [x] `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,
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.
- [x] `Sources/MWBMac/Log.swift`: logger + rotating file.
- [x] `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).
- [ ] `Sources/mwb/EngineActions.swift`: `SwitchAction` and 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`: `NSApplication`
**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).
- [x] `Sources/mwb/EngineActions.swift`: `SwitchAction` and hotkey
dispatch per Assumptions (`MachineStuff.cs:1008-1050`,
`InputHook.cs:516-655`).
- [x] `Sources/mwb/Recovery.swift`: `recoverLocal`, every C2 trigger
wired, reopen countdown (`frmScreen.cs:425-449`).
- [x] `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`: append §10.6 with anything learned, cited.
- [x] `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 `Task`s.** 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 `CGEvent`s. 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
+68
View File
@@ -870,3 +870,71 @@ sees them. One subsection per lane, appended, never rewritten.
desktops is out of scope in the first place (README D6). Note that the
hardcoded Win+L branch (`:450-460`) carries no such gate on Windows either, so
only the configurable hotkey was ever gated.
### 10.6 app-engine (2026-09-16)
1. **A switch moves the pointer only when the target is the local machine.**
`Event.PrepareToSwitchToMachine` records `MachineStuff.SwitchLocation` and sets
`EvSwitch` (`Event.cs:180-184`); the cursor work is all done afterwards by
`Helper.HelperThread` (`Helper.cs:75-127`), which branches on
`NewDesMachineID`: a *remote* target gets `HideMouseCursor(false)` and the
parked dot, and only `NewDesMachineID == MachineID` reads `SwitchLocation` and
calls `MoveMouse`/`MoveMouseEx` (`Helper.cs:96-113`). So `SwitchAction.moveCursor` is a landing for
*this* machine; consuming it unconditionally would throw the user's pointer at
the far machine's landing coordinates every time control left. The same thread
calls `ReleaseAllKeys()` whenever `NewDesMachineID == MachineID` (`Helper.cs:120-123`),
which is the third place Windows releases keys on a switch home.
2. **A `Mouse` packet addressed to us takes control back by assignment, not by
switching.** `Receiver.cs:122-125` sets `NewDesMachineID = DesMachineID =
MachineID` inline: no `HideMouse` to the machine we were driving, no cursor
move, no `MachineSwitched`. It is a defensive line for the crossed state where
two machines each think they are the controller. A port that reaches for
`SwitchToMachine(MachineName)` here must drop that call's cursor move, or the
jump to the primary screen's centre will fight the mouse packet that is about
to be injected.
3. **In relative mode the *controlled* machine does the edge detection.**
`Receiver.cs:147-172`: after `MoveMouseRelative`, the receiver reads
`GetCursorPos` and runs `MoveToMyNeighbourIfNeeded(..., Common.MachineID)`
itself, then `SendNextMachine(package.Src, newDesMachineIdEx, p)` back to the
controller, which treats it like an edge crossing of its own
(`Receiver.cs:195-201` → `PrepareToSwitchToMachine`). That is the only reason
`NextMachine (121)` exists, and it is why the receiving side needs a
"where is the pointer right now" read that nothing else on the receive path
needs. The acceptance test on the controller is
`Event.IsSwitchingByMouseEnabled()` — `EasyMouse == Enable` **or** the Ctrl /
Shift Easy-Mouse key being held (`InputHook.EasyMouseKeyDown`,
`InputHook.cs:92, 404, 467-473`), not the setting alone.
4. **The reconnect countdown is 30 s and is gated on "no socket established".**
`frmScreen.HelperTimer_Tick` runs every 100 ms (`:285-288`). The reopen block
is inside `if ((count % 2) == 0)` and fires on `count % 300 == 0`
(`frmScreen.cs:425-427`) — 30 s — and only when `!Common.AtLeastOneSocketEstablished()`;
when a socket *is* established it clears `PleaseReopenSocket` instead
(`frmScreen.cs:446-449`). `PleaseReopenSocket` is a counter with two sentinel values, not a
flag: `REOPEN_WHEN_HOTKEY = -10055` and `REOPEN_WHEN_WSAECONNRESET = -10054`
(`InitAndCleanup.cs:28-29`), handled separately at `frmScreen.cs:452-462`. 30 s is also the
connect budget the control channel gives up after (§10.3 notes 1–2), so the two
line up: the countdown fires exactly as the budget expires.
5. **The settings file's JSON shapes, exactly.** The envelope is
`{"name":"MouseWithoutBorders","version":"1.1","properties":{…}}`
(`MouseWithoutBordersSettings.cs:27-34`) and the property names are the C#
property names verbatim — no naming policy is set on the serializer
(`MouseWithoutBordersSettings.cs:20-25`). Inside `properties`:
- every `bool` goes through `BoolPropertyJsonConverter` and every `IntProperty`
/ `StringProperty` / `GenericProperty` is a record with one `value` field, so
they are all written as `{"value": …}` — `"WrapMouse": {"value": true}`,
`"TCPPort": {"value": 15100}`;
- `MachineMatrixString` is the exception: a bare `List<string>`, so a plain
JSON array (`MouseWithoutBordersProperties.cs:85-86`). The MWB app joins and
splits it on `,` (`Setting.cs:216-236`), which is where the
`"a,b,c,d"` form in `MachineMatrixString` comes from;
- the four shortcuts are `HotkeySettings`, whose fields carry explicit
lower-case names: `{"win":…,"ctrl":…,"alt":…,"shift":…,"code":…,"key":""}`
(`HotkeySettings.cs:121-136`). `win` is ⌘ and `alt` is ⌥ on a Mac (README D4);
- `MachineID` is seeded from `Encryption.Ran.Next()` (`Setting.cs:1058`), i.e.
`System.Random.Next()`, so it is always a **non-negative** `Int32` — never 0
after generation, because 0 is the "not set yet" sentinel the getter tests.
6. **`Heartbeat` and `Awake` are 64-byte packets.** Not new, but worth stating
where the receiver is described: `MachineStuff.AddToMachinePool` reads
`package.MachineName` (`:712-777`), which only exists on a big packet, so a
32-byte heartbeat would teach the peer nothing. `PackageType.isBig` already
lists them (§1.2).