# 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. 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. - **`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. - **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 `~/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 `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. - **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. - **Single instance**: `flock` on `~/Library/Application Support/mwb-mac/mwb.pid`; a second launch exits 1 with a message. ## Handshakes ### Consumed Everything published by wire-core, session-matrix, control-channel, input-capture and input-inject, exactly as their Handshakes sections read today. If an API turns out to be missing or wrong, the Dev files a request in this README and stops that item — it does not edit the other lane's files. ### Promised (to app-ui, clipboard, extras) ```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)? } actor Engine { init(settings: SettingsStore) throws func start() throws; func stop() func apply(_ settings: Settings) // re-maps every config var snapshot: EngineSnapshot // for the UI: peers + statuses, controlled machine, permissions, easy mouse on/off, last error func switchTo(slot: Int); func switchToAll(); func reconnect(); func lockAll(); func toggleEasyMouse() func recoverLocal(reason: RecoveryReason) var onSnapshotChange: (@Sendable (EngineSnapshot) -> Void)? } public struct EngineSnapshot: Sendable { peers: [PeerStatus]; controlled: String?; permissions: PermissionState; easyMouseEnabled: Bool; hostnameProblem: String?; lastRecovery: (RecoveryReason, Date)? } ``` ## Status / TODO - [ ] `Sources/MWBCore/Settings.swift`: schema, defaults, load/save, first-run generation, matrix/pool round-trip, config mapping (C4) (`MouseWithoutBordersProperties.cs:165-206`, `Setting.cs:479-511, 1048-1083`, `Common.cs:906`). - [ ] `Sources/MWBMac/Log.swift`: logger + rotating file. - [ ] `Sources/mwb/Engine.swift`: the actor, sink stream, drain loop, C1 forwarding, packet dispatch (`Receiver.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` 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. ## Work log ## QA log ## Review