41 KiB
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 that lands control back on this Mac — the tail ofperform(_ actions:), so theByeBye, edge-crossing andNextMachinepaths are covered as well as the hotkeys (Helper.cs:120-123,MachineStuff.cs:1047,InitAndCleanup.cs:214-243) — and on every lock and mode change;.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. The three signal handlers then callEmergencyRelease.sayGoodbye(), which queuesByeByeon the channel and waits 150 ms for it, so contracts C2's last row holds on that path too:ControlChannelisSendableand hops to its own queue, so it is the one piece of Engine-owned state a handler may touch.Engine.stop()does the same thing on the graceful path, waiting 150 ms for the wire (InitAndCleanup.cs:192-215) before it 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, with the mode set again on the final path afterwards so a file that arrived from elsewhere at 0644 does not stay there. 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 (answered 2026-09-16)
PacketSequenceris used from two queues by design and was 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()wasvalue = value &+ 1with no synchronisation, so a lost update could hand two packets the sameIdand the receiver's replay ring would drop the second. Done, as a cross-lane edit the lead authorised:next()andcurrenthold anNSLock(Foundation only, so MWBCore's layering holds) andPacketSequenceris@unchecked Sendable(Sources/MWBCore/Sequencing.swift). The session-matrix Handshakes section says so.ReplayFilteris only ever touched on the channel's queue and is unchanged.
Requested of input-capture (1 answered 2026-09-16, 2 open)
PermissionStatehad no public initialiser. It declaredpublic let listen/public let postand noinit, so the memberwise one wasinternaland no other target could build a value —EngineSnapshot's default had to callPermissions.preflight(), which is a TCC query. Done, as a cross-lane edit the lead authorised:public init(listen: Bool, post: Bool)(Sources/MWBMac/Permissions.swift), andEngineSnapshot.permissionsnow defaults toPermissionState(listen: false, post: false).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.- The permission health check installs the tap, not just reports it.
The 5 s check already had to notice a revoked grant (C2); noticing
the grant arriving and retrying
EventTap.start()costs four lines and means the user does not have to restart the app after ticking the box in System Settings. 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.swiftandEngine.swiftare both a little over 600 lines — over the 300–600 target, well under the 800 "consider splitting" line. (No count is quoted here on purpose: the last one went stale within a commit.wc -lis the authority.) 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
-
2026-09-16 (dev, rework) — the QA verdict's three findings, the two cross-lane requests the lead authorised, and the stale number. Six commits, one per item; gates green on the last.
- Finding 1,
settings.jsonmode.Settings.save(to:)now passes.usingNewMetadataOnlytoreplaceItemAtand sets.posixPermissions: 0o600on the path it actually wrote, with the reason in a comment. QA was right about the mechanism: without the optionreplaceItemAtcopies the original item's metadata onto the replacement, so a file copied in from a PC (README D3) kept its mode for the life of the install,SecurityKeyand all. The belt-and- bracessetAttributesafterwards means the guarantee no longer depends on which of the two branches wrote the file, nor on Foundation's documented behaviour staying documented. (Sources/MWBCore/Settings.swift.) - Finding 2,
releaseAll()on the other switch-to-local paths. Fixed rather than documented.perform(_ actions:)remembersdesMachineID/isBroadcastingbefore running the actions and callsinjector.releaseAll()afterwards when the destination moved and the new destination is this Mac — which is whatHelper.HelperThreaddoes (Helper.cs:120-123), since its event is set bySwitchToMachine(MachineStuff.cs:1024) andPrepareToSwitchToMachine(Event.cs:203). That covers the receivedByeBye, the edge crossing and theNextMachinepacket. The one deliberate narrowing, in the doc comment: it fires only when the destination actually moved. OurreleaseAll()releases the keys this Mac injected, so an unconditional call on a switch that left control local — a matrix edit while a peer is driving us — would drop that peer's modifiers mid-keystroke. Windows has no equivalent hazard because its release is physical-key based. (Sources/mwb/EngineActions.swift.) - Finding 3,
ByeByeon the signal path. Implemented, not documented away, and it is the few lines the lead hoped for:EmergencyReleasegainsarm(channel:)andsayGoodbye(), the Engine arms it instartChannel()and disarms it instop(), and the SIGTERM/SIGINT/SIGHUP handler callsrun()thensayGoodbye()then exits. Nothing here wakes the actor:ControlChannelisSendableand every method hops to its own serial queue, which is precisely the property the rest of the Engine's state lacks. The 150 ms wait is the same graceEngine.stop()gives the packet (InitAndCleanup.cs:192-215); keys and pointer are already back before it starts, so invariant 3 is not traded for it. Best effort by construction — a stuck channel queue loses the packet and the peer falls back to socket-level detection (SocketStuff.cs:1561-1563).docs/contracts.mdneeded no amendment. (Sources/mwb/AppLifecycle.swift,Engine.swift.) - Request 1,
PacketSequencer. Cross-lane edit, authorised: the counter is under anNSLockand the class is@unchecked Sendable(Sources/MWBCore/Sequencing.swift).NSLockis Foundation, so MWBCore's layering gate is untouched. The session-matrix README's Handshakes signature block and its "one sequencer per process" rule both now say it is thread-safe, and why (C1: one sequencer, two queues). - Request 2,
PermissionState.init. Cross-lane edit, authorised:public init(listen:post:)added (Sources/MWBMac/Permissions.swift), and the workaround removed —EngineSnapshot.permissionsdefaults toPermissionState(listen: false, post: false)instead of running a TCC query to obtain a value. The input-capture README's signature line carries the new init. - The stale "598 lines". Replaced with prose and no number at all;
quoting a count in a work log guarantees it is wrong by the next
commit, and the judgement it supported (both files under 800, no
split) is unchanged. Today's counts, for the record only:
Settings.swift644,Engine.swift611.
Verification.
xcrun swift-format format -i --recursive Sources Package.swiftthentools/gates.shgreen (lint --strict, MWBCore layering, build with warnings-as-errors)..build/debug/mwb --versionstill prints its line. The app was not launched — unchanged from the first pass, and for the same reason (CLAUDE.md invariant 5): every path touched here (the signal handlers, the switch tail, the channel arming) posts events or opens sockets when exercised, so it is CP1's job with the user present.Settings.savewas not exercised against a real file either; the reasoning is Foundation's documentedreplaceItemAtbehaviour plus QA's own empirical check, and thesetAttributesline is there so the result does not depend on that reasoning being right. - Finding 1,
QA log
-
2026-09-16 (QA) — reviewed against CLAUDE.md,
docs/contracts.mdC1–C5,docs/protocol.md§10.6, and the Windows source (Core/Receiver.cs,Core/MachineStuff.cs:1007-1050,Core/Helper.cs,Class/InputHook.cs:539-658,Form/frmScreen.cs:285-300, 425-461,Class/Setting.cs,MouseWithoutBordersProperties.cs:165-206,MouseWithoutBordersSettings.cs). No test suite exists for this lane yet (swift testnot run — none of the gates call for it); build-only per CLAUDE.md invariant 5. The app itself was never launched; only.build/debug/mwb --versionand--check-permissionswere run (confirmed both create no settings file, log file or tap — checked~/Library/Application Support/mwb-mac/and~/Library/Logs/mwb-mac/stay absent after both).Gates.
tools/gates.shgreen:swift-format lint --strictclean,MWBCorelayering clean,swift build -Xswiftc -warnings-as-errorsclean.Verified clean. Every Status/TODO tick has code behind it. C1 (single
PacketSequencer/ReplayFilter, ids stamped once inSwitcher/Engine. stampAndForward,Sessionre-stamps only its own connection packets) holds; the open thread-safety request against session-matrix is correctly filed, not silently worked around. C3's actor/routing-snapshot/queue shape matches, andswift build -warnings-as-errors(Swift 6 strict concurrency) accepting the file rules out illegal actor-isolation escapes; the only two@unchecked Sendabletypes (SettingsStore,LogFile) are lock- or queue-disciplined and justified in a doc comment, matchingEmergencyRelease. No force-unwrap,try!,fatalErrororpreconditionin any changed file. No log call inLog.swift/Engine.swift/EngineActions.swift/Recovery.swifttakes aKeyboardDataor key string — grepped everyLog.*call site by hand.Permissions.request()has exactly one call site (AppLifecycle.swift:271, the status-item click). C4's config mapping is complete:ChannelConfig,CaptureConfig,EdgeConfigandInjectorConfigeach have every field populated fromSettingsinEngineActions.swift/Engine.init, matched field-by-field against the struct definitions. Settings JSON matchesMouseWithoutBordersProperties.cs:165-206andHotkeySettings.cs:121-136property-by-property (envelope,{"value":…}boxing, the bare-array exception forMachineMatrixString, lower-case hotkey field names, non-negativeMachineID). Hostname validation (D7) matches the table exactly and gatesEngine.start(). Single instance (flock) runs before anything else touches the tap or a socket.Findings.
-
[correctness/security, CONFIRMED]
Settings.save(to:)does not reliably enforce 0600 on a pre-existing file.Sources/MWBCore/Settings.swift:437-438callsFileManager.default.replaceItemAt(url, withItemAt: temp)with no options.FileManager.replaceItemAt's documented default behaviour is to preserve the original item's metadata (permissions included) onto the replacement unless.usingNewMetadataOnlyis passed — I confirmed this empirically with a standalone Swift snippet (create a 0644 file, replace it with a 0600 temp file viareplaceItemAtwith no options: the result stays 0644). The first-ever write for a brand-new install goes through themoveItembranch instead (no pre-existing destination), so a fresh install does end up at 0600 and stays 0600 on every laterupdate(), because the filereplaceItemAtis "preserving metadata from" is by then already 0600. But README's own §Settings advertises copyingsettings.jsonbetween a Mac and a PC as a supported way to share aSecurityKeyand matrix (D3) — a file arriving that way (scp, AirDrop, a shared drive, restored from a backup) will generally not already be 0600, and every subsequentSettingsStore.update()(a matrix edit, a pool update,persistOnExit,replaceMachineID, …) will silently keep whatever permissive mode it arrived with, forever, becausereplaceItemAtkeeps re-propagating the old mode forward. The file storesSecurityKeyin the clear. Fix is one line:.usingNewMetadataOnlyon thereplaceItemAtcall, or an explicitsetAttributesonurlafter it. Windows side:Setting.cswrites the file with no special ACL either, but that is a difference worth having on our side, not a reason to drop the 0600 promise this port's own README (## Assumptions, "Stored at … mode 0600") makes. -
[correctness, PLAUSIBLE] the third place Windows releases held keys on a switch (
Helper.cs:120-123, cited by this lane's owndocs/protocol.md§10.6 note 1) is wired for some switch-to-local paths and not others.injector.releaseAll()runs on the hotkey path (EngineActions.swift:136,switchTo(slot:)), on the broadcast toggle (Switching.swift:236,switchToBroadcast's.releaseAllKeysaction) and unconditionally inrecoverLocal(Recovery.swift:43). It does not run when a receivedByeByepacket ends control locally (Engine.swift:509-510,case .byeBye: perform(switcher. handleByeBye(packet, now: now))→Switching.swift:307-313→switchToMachine, which never appends.releaseAllKeys), nor when an edge crossing or aNextMachinepacket lands the target back on this machine (Engine.swift:460-464considerCrossing,:489-497the.nextMachinecase →Switching.swift:172-197prepareToSwitch, same gap). On Windows,SwitchToMachineandPrepareToSwitchToMachineboth callCommon.EvSwitch.Set()unconditionally (MachineStuff.cs:1024,Event.cs:203), which always wakesHelper.HelperThread, which always callsReleaseAllKeys()onceNewDesMachineID == MachineID— i.e. on every one of these paths, not just three of five. Two mitigating facts keep this from being a CONFIRMED finding: theByeBye-packet gap is almost always covered moments later when the socket actually closes andnoteDisconnectedcallsrecoverLocal(idempotent); and this port'sInjector.releaseAll()only clears state this Mac itself injected (Injector.swift:44-49doc comment — it is the controlled-side release, not a Windows-styleGetAsyncKeyState-based physical-key release), so on the edge-crossing path there is normally nothing for it to release anyway. Still, the asymmetry is undocumented (no line in "Deviations from the brief" says this is intentional) and inconsistent with the belt-and-braces style the rest ofRecovery.swiftuses (e.g.cursor.recouple(to: nil)unconditionally, "Idempotent" in the doc comment) — worth either a one-line call or a documented reason not to. -
[completeness, PLAUSIBLE, low] contracts C2's last row ("sockets send ByeBye" on the atexit/signal path) is not implemented for SIGTERM/SIGINT/SIGHUP.
AppLifecycle.swift:199-213(installSignalHandlers) only callsEmergencyRelease.shared.run()(cursor + injector, synchronous, no actor — correctly matches CLAUDE.md invariant 3 and this file's own header comment) and thenexit(0); it never attemptschannel?.sayGoodbye(). This looks architecturally forced rather than an oversight —channelis actor-isolated state and the header comment is explicit that this path must not touch the actor — but the contract table literally promises ByeBye on this row and nothing in the README flags the gap as a deliberate deviation the way other trade-offs in the Work log are flagged. A peer that was being driven when the app receives SIGTERM (e.g. akill, or logout sending SIGTERM to background apps) will only learn we're gone via its own socket-level detection, not aByeBye. Worth either attemptingNSApp.terminate(nil)(the graceful path already sendsByeByeand has 150 ms of headroom) for the three catchable signals, or amendingdocs/contracts.mdC2 to say so. -
[docs, trivial, not fixed] stale line count. The Work log says "
Engine.swift598" lines;wc -lon the reviewed tree gives 606. Both numbers are well under the 800-line "consider splitting" line CLAUDE.md sets, so the judgment the entry draws from it (no split needed) still holds — the number is just stale, most likely from a commit after the one the prose was written against. Not fixed (not a comment, and the line the instructions permit me to fix without a finding is typos/wrong comments, not a work-log narrative number); left for the dev to correct or drop.
Judgement on the two >600-line files.
Sources/MWBCore/Settings.swift(628) andSources/mwb/Engine.swift(606) are both under the 800-line "consider splitting" mark, so CLAUDE.md does not require a reason to be written down at all, let alone a split — the README documents the choice anyway. Read top to bottom, both pass the one-sentence test:Settings. swiftis "the settings schema and the file that stores it" (mostly mechanical get/set pairs, one per PowerToys property — a split by property group would just scatter that repetition across files without changing what a reader needs to hold in their head);Engine.swiftis "the actor plus its event pump and packet dispatch" (theEngineActions.swift/Recovery.swiftextension-file split already pulled the two things that do read as separate responsibilities — switch/hotkey handling and C2 recovery — out of it). No split recommended.Verdict: REWORK
-
Review
- 2026-09-16 (lead): inspected per
docs/loop.md§5 after one rework round. Gates green run by me; diff limited to the brief's files plus the three authorised cross-lane edits (Sequencing.swiftlock,PermissionState.init, two README lines), TODO §6, protocol §10.6. Read the drain loop,stampAndForward,inputDestination,considerCrossing,reportEdgeToControllerandSwitcher. nextMachinePacket: every application packet is stamped exactly once (Engine or Switcher, both through the one locked sequencer) and forwarded unchanged — C1 holds. Sink, tap wake, ticker and watchers funnel through oneAsyncStream— C3 holds. QA walked C2's rows and C4's mappings. Files at 644/611 lines are under the 800 mark with reasons recorded. Verdict: merge. Carry into app-ui: settings are edited only throughSettingsStore.update;Engine.observeis the one feed for the UI;Permissions.request()only on a click. Unexercised until CP1: everything fromNSApplication.run()inwards.