QA finding 3. contracts C2's last row promises the sockets send `ByeBye` however the process ends, and the signal path only released the keys and the pointer. `ControlChannel` is `Sendable` and each of its methods hops to its own serial queue, so the handler can hold the channel and queue the goodbye itself without waking the Engine actor — which the header comment on `EmergencyRelease` forbids, and rightly. The 150 ms wait afterwards is the same grace `Engine.stop()` gives the packet (`InitAndCleanup.cs:192-215`); it is best effort, and it runs after the keys are already back. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
322 lines
13 KiB
Swift
322 lines
13 KiB
Swift
// The process: one instance, one `NSApplication`, one placeholder status item,
|
|
// and the handlers that make sure a crash or a `kill` never leaves this Mac with
|
|
// a frozen pointer or a stuck modifier key.
|
|
//
|
|
// Ported from App/Class/Program.cs (`Main`, the single-instance check at
|
|
// 139-175), App/Core/InitAndCleanup.cs (`Cleanup`, 192-215) and
|
|
// App/Form/frmScreen.cs (the tray icon and its menu). The menu here is
|
|
// deliberately the smallest thing that can run — the real one is the app-ui
|
|
// lane; this is enough for the lead to smoke the app (TODO §6).
|
|
|
|
import AppKit
|
|
import Foundation
|
|
import MWBCore
|
|
import MWBMac
|
|
import MWBNet
|
|
|
|
/// This Mac's name on the wire (README D7).
|
|
///
|
|
/// Protocol §1.1 gives the field 32 ASCII bytes and the Windows side resolves us
|
|
/// by exactly this string (§7), so a name that does not fit, or is not ASCII, is
|
|
/// refused up front rather than silently mangled by `Packet.setMachineName`.
|
|
enum Hostname {
|
|
/// The longest name a `DATA` packet can carry.
|
|
static let maximumLength = 32
|
|
|
|
/// The name, plus a sentence explaining why it is unusable when it is.
|
|
static func local() -> (name: String, problem: String?) {
|
|
var buffer = [CChar](repeating: 0, count: 256)
|
|
guard gethostname(&buffer, buffer.count - 1) == 0 else {
|
|
return ("", "gethostname() failed")
|
|
}
|
|
let bytes = buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }
|
|
let full = String(decoding: bytes, as: UTF8.self)
|
|
// `my-mac.local` and `my-mac.example.com` are both `my-mac` on the wire.
|
|
let name = full.split(separator: ".").first.map(String.init) ?? full
|
|
if name.isEmpty {
|
|
return (name, "this Mac has no host name; set one in System Settings > General > Sharing")
|
|
}
|
|
if !name.allSatisfy(\.isASCII) {
|
|
return (name, "host name \"\(name)\" is not ASCII; the protocol allows ASCII only")
|
|
}
|
|
if name.count > maximumLength {
|
|
return (name, "host name \"\(name)\" is longer than \(maximumLength) characters")
|
|
}
|
|
return (name, nil)
|
|
}
|
|
}
|
|
|
|
/// The `flock` that makes a second launch exit instead of fighting over the tap.
|
|
///
|
|
/// Windows uses a named window title (`MachineStuff.CheckSecondInstance`,
|
|
/// `:1052-1062`); a lock file is the boring macOS equivalent and releases itself
|
|
/// when the process dies, however it dies.
|
|
enum SingleInstance {
|
|
/// `~/Library/Application Support/mwb-mac/mwb.pid`.
|
|
static func pidFileURL() -> URL {
|
|
Settings.defaultURL().deletingLastPathComponent().appendingPathComponent("mwb.pid")
|
|
}
|
|
|
|
/// Takes the lock, returning the descriptor to hold open for the process's
|
|
/// lifetime, or `nil` if another copy already holds it.
|
|
static func acquire(at url: URL) -> Int32? {
|
|
try? FileManager.default.createDirectory(
|
|
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
let descriptor = open(url.path, O_CREAT | O_RDWR, 0o600)
|
|
guard descriptor >= 0 else { return nil }
|
|
guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else {
|
|
close(descriptor)
|
|
return nil
|
|
}
|
|
ftruncate(descriptor, 0)
|
|
let pid = "\(ProcessInfo.processInfo.processIdentifier)\n"
|
|
_ = pid.withCString { write(descriptor, $0, strlen($0)) }
|
|
return descriptor
|
|
}
|
|
}
|
|
|
|
/// The last thing that runs, however the process ends (contracts C2, last row).
|
|
///
|
|
/// Everything here is **synchronous and never touches the Engine actor**: an
|
|
/// `atexit` handler cannot `await`, and a Mac left with held modifiers or a
|
|
/// pointer still disassociated from the mouse is exactly the failure CLAUDE.md
|
|
/// invariant 3 forbids. `Injector.releaseAll()` and `Cursor.restoreEverything()`
|
|
/// are both documented safe from any thread by their own lanes.
|
|
final class EmergencyRelease: @unchecked Sendable {
|
|
static let shared = EmergencyRelease()
|
|
|
|
/// How long the signal path gives a queued `ByeBye` to reach the wire — the
|
|
/// same wait `Engine.stop()` makes on the graceful path
|
|
/// (`InitAndCleanup.cs:192-215`).
|
|
static let goodbyeGrace: TimeInterval = 0.15
|
|
|
|
private let lock = NSLock()
|
|
private var injector: Injector?
|
|
private var cursor: Cursor?
|
|
private var channel: ControlChannel?
|
|
private var done = false
|
|
|
|
/// Hands over the two objects the handlers may touch. Called once, at start.
|
|
func arm(injector: Injector, cursor: Cursor) {
|
|
lock.lock()
|
|
self.injector = injector
|
|
self.cursor = cursor
|
|
lock.unlock()
|
|
}
|
|
|
|
/// Hands over the channel, so the signal path can keep contracts C2's last
|
|
/// row ("sockets send `ByeBye`") without waking the Engine actor.
|
|
///
|
|
/// `ControlChannel` is `Sendable` and every one of its methods hops to its
|
|
/// own serial queue, so this is a reference the handlers may hold and call
|
|
/// from any thread — unlike everything else the Engine owns.
|
|
func arm(channel: ControlChannel?) {
|
|
lock.lock()
|
|
self.channel = channel
|
|
lock.unlock()
|
|
}
|
|
|
|
/// Best-effort `ByeBye` on the way out: queue it on every trusted
|
|
/// connection, then give it `goodbyeGrace` to be written.
|
|
///
|
|
/// Best effort in the literal sense — the write happens on the channel's
|
|
/// queue, so a stuck queue loses the packet and the peer falls back to its
|
|
/// own socket-level detection (`SocketStuff.cs:1561-1563`). Blocking the
|
|
/// caller for 150 ms is only acceptable because the caller is about to
|
|
/// `exit(0)`; the keys and the pointer are already back by then.
|
|
func sayGoodbye() {
|
|
lock.lock()
|
|
let channel = self.channel
|
|
lock.unlock()
|
|
guard let channel else { return }
|
|
channel.sayGoodbye()
|
|
Thread.sleep(forTimeInterval: EmergencyRelease.goodbyeGrace)
|
|
}
|
|
|
|
/// Releases every held key and gives the pointer back. Idempotent.
|
|
func run() {
|
|
lock.lock()
|
|
let alreadyDone = done
|
|
done = true
|
|
let injector = self.injector
|
|
let cursor = self.cursor
|
|
lock.unlock()
|
|
guard !alreadyDone else { return }
|
|
cursor?.restoreEverything()
|
|
injector?.releaseAll()
|
|
}
|
|
}
|
|
|
|
/// The app.
|
|
@MainActor
|
|
final class AppDelegate: NSObject, NSApplicationDelegate {
|
|
private var engine: Engine?
|
|
private var store: SettingsStore?
|
|
private var statusItem: NSStatusItem?
|
|
private var titleItem: NSMenuItem?
|
|
private var lockDescriptor: Int32?
|
|
private var signalSources: [any DispatchSourceSignal] = []
|
|
private var terminating = false
|
|
|
|
func applicationDidFinishLaunching(_ notification: Notification) {
|
|
guard let descriptor = SingleInstance.acquire(at: SingleInstance.pidFileURL()) else {
|
|
FileHandle.standardError.write(Data("mwb: another instance is already running\n".utf8))
|
|
exit(1)
|
|
}
|
|
lockDescriptor = descriptor
|
|
|
|
Log.startFileLogging()
|
|
Log.app.info("mwb \(MWBVersion.string) starting")
|
|
|
|
buildStatusItem()
|
|
installSignalHandlers()
|
|
atexit { EmergencyRelease.shared.run() }
|
|
|
|
do {
|
|
try startEngine()
|
|
} catch {
|
|
Log.app.error("could not start: \(error)")
|
|
setTitle("mwb — settings error")
|
|
}
|
|
}
|
|
|
|
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
|
|
guard let engine, !terminating else { return .terminateNow }
|
|
terminating = true
|
|
Task {
|
|
await engine.stop()
|
|
NSApp.reply(toApplicationShouldTerminate: true)
|
|
}
|
|
return .terminateLater
|
|
}
|
|
|
|
func applicationWillTerminate(_ notification: Notification) {
|
|
EmergencyRelease.shared.run()
|
|
Log.stopFileLogging()
|
|
}
|
|
|
|
// MARK: - Startup
|
|
|
|
private func startEngine() throws {
|
|
let store = try SettingsStore()
|
|
self.store = store
|
|
|
|
let host = Hostname.local()
|
|
let engine = Engine(store: store, localName: host.name, hostnameProblem: host.problem)
|
|
self.engine = engine
|
|
EmergencyRelease.shared.arm(injector: engine.injector, cursor: engine.cursor)
|
|
|
|
// input-capture request 4: display-change observation is main-thread work
|
|
// and needs `NSApplication.shared` to exist first.
|
|
engine.screens.startObserving()
|
|
observeWorkspace(engine)
|
|
store.onExternalChange { [emit = engine.emit] settings in emit(.settingsChanged(settings)) }
|
|
store.startWatching()
|
|
|
|
// A `@MainActor` class is `Sendable`, so the snapshot callback may hold
|
|
// the delegate and hop back to the main actor to draw.
|
|
Task { [weak self] in
|
|
await engine.observe { snapshot in
|
|
Task { @MainActor in self?.render(snapshot) }
|
|
}
|
|
await engine.start()
|
|
}
|
|
}
|
|
|
|
private func observeWorkspace(_ engine: Engine) {
|
|
NSWorkspace.shared.notificationCenter.addObserver(
|
|
forName: NSWorkspace.didWakeNotification, object: nil, queue: .main
|
|
) { [emit = engine.emit] _ in
|
|
emit(.systemWoke)
|
|
}
|
|
}
|
|
|
|
private func installSignalHandlers() {
|
|
// `DispatchSourceSignal` rather than `signal(2)`: the handler then runs
|
|
// on an ordinary queue, where posting key-ups and talking to the window
|
|
// server are legal, instead of in signal context where they are not.
|
|
for number in [SIGTERM, SIGINT, SIGHUP] {
|
|
signal(number, SIG_IGN)
|
|
let source = DispatchSource.makeSignalSource(signal: number, queue: .main)
|
|
source.setEventHandler {
|
|
// Keys and pointer first (CLAUDE.md invariant 3), then contracts
|
|
// C2's last row: the peers are told we are gone. Neither call
|
|
// touches the Engine actor — the channel is its own lock.
|
|
EmergencyRelease.shared.run()
|
|
EmergencyRelease.shared.sayGoodbye()
|
|
exit(0)
|
|
}
|
|
source.resume()
|
|
signalSources.append(source)
|
|
}
|
|
}
|
|
|
|
// MARK: - The placeholder status item (app-ui replaces all of this)
|
|
|
|
private func buildStatusItem() {
|
|
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
|
|
item.button?.title = "mwb"
|
|
let menu = NSMenu()
|
|
let title = NSMenuItem(title: "mwb \(MWBVersion.string) — starting", action: nil, keyEquivalent: "")
|
|
title.isEnabled = false
|
|
menu.addItem(title)
|
|
menu.addItem(.separator())
|
|
menu.addItem(
|
|
NSMenuItem(
|
|
title: "Request Permissions…", action: #selector(requestPermissions),
|
|
keyEquivalent: ""))
|
|
menu.addItem(
|
|
NSMenuItem(title: "Reconnect", action: #selector(reconnect), keyEquivalent: ""))
|
|
menu.addItem(.separator())
|
|
menu.addItem(NSMenuItem(title: "Quit mwb", action: #selector(quit), keyEquivalent: "q"))
|
|
for entry in menu.items where entry.action != nil { entry.target = self }
|
|
item.menu = menu
|
|
statusItem = item
|
|
titleItem = title
|
|
}
|
|
|
|
/// One line of state: what the lead needs to see that the app is alive.
|
|
func render(_ snapshot: EngineSnapshot) {
|
|
if let problem = snapshot.hostnameProblem {
|
|
setTitle("mwb — host name unusable: \(problem)")
|
|
statusItem?.button?.title = "mwb!"
|
|
return
|
|
}
|
|
var parts: [String] = []
|
|
if !snapshot.permissions.isComplete {
|
|
var missing: [String] = []
|
|
if !snapshot.permissions.listen { missing.append("Input Monitoring") }
|
|
if !snapshot.permissions.post { missing.append("Accessibility") }
|
|
parts.append("permissions missing: \(missing.joined(separator: ", "))")
|
|
} else if !snapshot.canInject {
|
|
parts.append("cannot inject events")
|
|
} else {
|
|
parts.append("running")
|
|
}
|
|
let connected = snapshot.peers.filter { $0.status == .connected }.count
|
|
parts.append("\(connected) connected")
|
|
if let controlled = snapshot.controlled { parts.append("controlling \(controlled)") }
|
|
setTitle("mwb \(MWBVersion.string) — " + parts.joined(separator: " — "))
|
|
statusItem?.button?.title = snapshot.controlled == nil ? "mwb" : "mwb →"
|
|
}
|
|
|
|
private func setTitle(_ text: String) {
|
|
titleItem?.title = text
|
|
}
|
|
|
|
/// CLAUDE.md, Workflow: the **only** call to `Permissions.request()` in the
|
|
/// repository, and it happens because the user clicked this item.
|
|
@objc private func requestPermissions() {
|
|
_ = Permissions.request()
|
|
}
|
|
|
|
@objc private func reconnect() {
|
|
guard let engine else { return }
|
|
Task { await engine.reconnect() }
|
|
}
|
|
|
|
@objc private func quit() {
|
|
NSApp.terminate(nil)
|
|
}
|
|
}
|