Add luxe Notifier: macOS menu bar app that tells you when luxe needs you

A luxe hook runs luxe-notify, which sends one JSON line over a Unix socket to
a SwiftUI menu bar app. The app shows a banner, keeps a badge count and
history, and brings the terminal forward when you click a banner.

Notifies on approvals (PermissionRequested), question prompts
(BeforeToolUse, matched to the question tool), errors, and turns that run at
least --min-seconds (default 30, timed from BeforeAgentStart to AgentEnd).

The menu warns when macOS has notifications blocked for the app. The app
writes status.txt beside its socket for debugging.

Known limits are in README.md and PLAN.md: a crowded menu bar can hide the
icon, and the first test build after a change can fail with a TestingMacros
error under Command Line Tools, which make test retries once.
This commit is contained in:
2026-10-24 22:41:42 -04:00
commit ced6a44ed0
30 changed files with 1314 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
import Foundation
/// What the menu should tell the user about banner delivery. Pure so it can be tested without
/// UserNotifications, which only exists inside an app bundle.
public enum BannerPermission: Equatable {
case unknown
case allowed
case denied
case notDetermined
/// `rawValue` is UNAuthorizationStatus: 0 notDetermined, 1 denied, 2 authorized, 3 provisional, 4 ephemeral.
public init(authorizationRawValue: Int) {
switch authorizationRawValue {
case 0: self = .notDetermined
case 1: self = .denied
case 2, 3, 4: self = .allowed
default: self = .unknown
}
}
/// Nil when nothing needs saying. Unknown stays quiet so the bare-binary dev path shows no warning.
public var warning: String? {
switch self {
case .denied: return "Banners are blocked. Allow luxe Notifier in System Settings > Notifications."
case .notDetermined: return "Waiting for notification permission."
case .allowed, .unknown: return nil
}
}
}

View File

@@ -0,0 +1,27 @@
import Foundation
/// Holds what the menu shows. Kept free of UI types so the badge and mute rules can be tested.
public final class NotificationCenterModel {
public private(set) var history: [NotifyEvent] = []
public private(set) var unseenCount = 0
public var isMuted = false
public var maxHistory = 50
public init() {}
/// Returns true when a banner should be shown for this event.
@discardableResult
public func receive(_ event: NotifyEvent) -> Bool {
history.insert(event, at: 0)
if history.count > maxHistory { history.removeLast(history.count - maxHistory) }
unseenCount += 1
return !isMuted
}
public func markAllSeen() { unseenCount = 0 }
public func clear() {
history.removeAll()
unseenCount = 0
}
}

View File

@@ -0,0 +1,31 @@
import Foundation
public enum NotifyClient {
/// Sends one event line. Throws a descriptive error when the app is not listening, so the CLI can
/// report it on stderr while still exiting 0.
public static func send(_ event: NotifyEvent, to path: String) throws {
let line = try NotifySocket.encodeLine(event)
let descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
guard descriptor >= 0 else { throw SocketError.syscall("socket", errno) }
defer { close(descriptor) }
var address = try NotifySocket.makeAddress(path)
let connected = withUnsafePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
}
}
guard connected == 0 else { throw SocketError.syscall("connect to \(path)", errno) }
try writeAll(line, to: descriptor)
}
private static func writeAll(_ data: Data, to descriptor: Int32) throws {
var sent = 0
try data.withUnsafeBytes { buffer in
while sent < data.count {
let count = write(descriptor, buffer.baseAddress!.advanced(by: sent), data.count - sent)
guard count > 0 else { throw SocketError.syscall("write", errno) }
sent += count
}
}
}
}

View File

@@ -0,0 +1,90 @@
import Foundation
public enum NotifyKind: String, Codable, Equatable {
case permission
case question
case turnEnded
case error
case generic
}
public struct NotifyEvent: Codable, Equatable {
public var kind: NotifyKind
public var title: String
public var message: String
public var cwd: String?
public var timestamp: Date
/// App that owns the terminal running luxe, e.g. com.mitchellh.ghostty. Optional so events from
/// older senders still decode, and so a hook without the variable still notifies.
public var terminalBundleID: String?
public init(kind: NotifyKind, title: String, message: String, cwd: String? = nil, timestamp: Date = Date(), terminalBundleID: String? = nil) {
self.kind = kind
self.title = title
self.message = message
self.cwd = cwd
self.timestamp = timestamp
self.terminalBundleID = terminalBundleID
}
}
public enum HookParseError: Error, CustomStringConvertible, Equatable {
case notJSON(String)
case notAnObject
public var description: String {
switch self {
case .notJSON(let reason): return "hook stdin is not valid JSON: \(reason)"
case .notAnObject: return "hook stdin must be a JSON object"
}
}
}
public enum HookEventParser {
/// `hookPoint` comes from the CLI's argument, because luxe's stdin payload does not name the point.
public static func parse(_ raw: Data, hookPoint: String, cwd: String? = nil, now: Date = Date()) throws -> NotifyEvent {
let object = try decodeObject(raw)
let other = object["Other"] as? [String: Any]
switch normalize(hookPoint) {
case "permissionrequested":
let tool = other?["tool"] as? String ?? "a tool"
return NotifyEvent(kind: .permission, title: "luxe needs approval", message: "Approve or reject \(tool)", cwd: cwd, timestamp: now)
case "agentend":
return NotifyEvent(kind: .turnEnded, title: "luxe is waiting", message: "The turn finished; it needs your next message", cwd: cwd, timestamp: now)
case "error":
let detail = other?["message"] as? String ?? "a turn failed"
return NotifyEvent(kind: .error, title: "luxe hit an error", message: detail, cwd: cwd, timestamp: now)
case "beforetooluse":
return toolUseEvent(object, hookPoint: hookPoint, cwd: cwd, now: now)
default:
return NotifyEvent(kind: .generic, title: "luxe", message: "Event: \(hookPoint)", cwd: cwd, timestamp: now)
}
}
/// Only the `question` tool means luxe is waiting on the user. Any other tool stays generic, so a
/// hook configured without a matcher cannot turn every tool call into a "question".
private static func toolUseEvent(_ object: [String: Any], hookPoint: String, cwd: String?, now: Date) -> NotifyEvent {
let toolUse = object["ToolUse"] as? [String: Any]
guard toolUse?["tool_name"] as? String == "question" else {
return NotifyEvent(kind: .generic, title: "luxe", message: "Event: \(hookPoint)", cwd: cwd, timestamp: now)
}
let args = toolUse?["args"] as? [String: Any]
let prompt = (args?["prompt"] as? String) ?? "luxe is waiting for your answer"
return NotifyEvent(kind: .question, title: "luxe has a question", message: String(prompt.prefix(200)), cwd: cwd, timestamp: now)
}
private static func decodeObject(_ raw: Data) throws -> [String: Any] {
let value: Any
do {
value = try JSONSerialization.jsonObject(with: raw)
} catch {
throw HookParseError.notJSON(error.localizedDescription)
}
guard let object = value as? [String: Any] else { throw HookParseError.notAnObject }
return object
}
private static func normalize(_ point: String) -> String {
point.lowercased().replacingOccurrences(of: "_", with: "")
}
}

View File

@@ -0,0 +1,67 @@
import Foundation
/// Accepts connections and calls `onEvent` once per valid line. Bad lines are reported, never fatal,
/// because one malformed client must not take the menu bar app down.
public final class NotifyListener {
private let path: String
private let onEvent: (NotifyEvent) -> Void
private let onProblem: (String) -> Void
private var descriptor: Int32 = -1
private let queue = DispatchQueue(label: "luxe-notifier.listener", attributes: .concurrent)
public init(path: String, onEvent: @escaping (NotifyEvent) -> Void, onProblem: @escaping (String) -> Void) {
self.path = path
self.onEvent = onEvent
self.onProblem = onProblem
}
public func start() throws {
try FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
unlink(path)
descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
guard descriptor >= 0 else { throw SocketError.syscall("socket", errno) }
var address = try NotifySocket.makeAddress(path)
let bound = withUnsafePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
bind(descriptor, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
}
}
guard bound == 0 else { throw SocketError.syscall("bind \(path)", errno) }
guard listen(descriptor, 16) == 0 else { throw SocketError.syscall("listen", errno) }
let listening = descriptor
Thread.detachNewThread { [weak self] in self?.acceptLoop(listening) }
}
public func stop() {
if descriptor >= 0 { close(descriptor) }
descriptor = -1
unlink(path)
}
private func acceptLoop(_ listening: Int32) {
while true {
let client = accept(listening, nil, nil)
if client < 0 { return }
queue.async { [weak self] in self?.read(client) }
}
}
private func read(_ client: Int32) {
defer { close(client) }
var collected = Data()
var chunk = [UInt8](repeating: 0, count: 4096)
while true {
let count = Foundation.read(client, &chunk, chunk.count)
if count <= 0 { break }
collected.append(chunk, count: count)
}
deliver(collected)
}
private func deliver(_ collected: Data) {
for line in collected.split(separator: UInt8(ascii: "\n")) where !line.isEmpty {
do { onEvent(try NotifySocket.decodeLine(Data(line))) }
catch { onProblem("dropped a malformed event line: \(error)") }
}
}
}

View File

@@ -0,0 +1,44 @@
import Foundation
public enum SocketError: Error, CustomStringConvertible {
case pathTooLong(String)
case syscall(String, Int32)
public var description: String {
switch self {
case .pathTooLong(let path): return "socket path is too long for a Unix socket (\(path.utf8.count) bytes): \(path)"
case .syscall(let name, let code): return "\(name) failed: \(String(cString: strerror(code)))"
}
}
}
public enum NotifySocket {
public static func defaultPath() -> String {
let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
return base.appendingPathComponent("LuxeNotifier/notify.sock").path
}
public static func makeAddress(_ path: String) throws -> sockaddr_un {
var address = sockaddr_un()
address.sun_family = sa_family_t(AF_UNIX)
let capacity = MemoryLayout.size(ofValue: address.sun_path)
guard path.utf8.count < capacity else { throw SocketError.pathTooLong(path) }
withUnsafeMutablePointer(to: &address.sun_path) { pointer in
pointer.withMemoryRebound(to: CChar.self, capacity: capacity) { _ = strcpy($0, path) }
}
return address
}
/// One JSON line per event keeps framing trivial and lets `nc -U` act as a test listener.
public static func encodeLine(_ event: NotifyEvent) throws -> Data {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
return try encoder.encode(event) + Data("\n".utf8)
}
public static func decodeLine(_ line: Data) throws -> NotifyEvent {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(NotifyEvent.self, from: line)
}
}

View File

@@ -0,0 +1,21 @@
import Foundation
/// Which app to bring forward when the user clicks an event.
public enum TerminalLocator {
/// Prefer the macOS bundle id the terminal exports. `TERM_PROGRAM` is a fallback because it names
/// the program, not its bundle, so only well-known values are mapped; an unknown one returns nil
/// rather than guessing at an app to activate.
public static func bundleID(from environment: [String: String]) -> String? {
if let id = environment["__CFBundleIdentifier"], !id.isEmpty { return id }
guard let program = environment["TERM_PROGRAM"] else { return nil }
return knownTerminals[program.lowercased()]
}
static let knownTerminals: [String: String] = [
"ghostty": "com.mitchellh.ghostty",
"apple_terminal": "com.apple.Terminal",
"iterm.app": "com.googlecode.iterm2",
"wezterm": "com.github.wez.wezterm",
"vscode": "com.microsoft.VSCode",
]
}

View File

@@ -0,0 +1,31 @@
import Foundation
/// Decides whether a finished turn is worth a notification. A quick turn means you are probably
/// still at the keyboard, so notifying would just be noise.
public enum TurnTimer {
public static let defaultMinimumSeconds: TimeInterval = 30
public static func shouldNotify(startedAt: Date?, endedAt: Date, minimumSeconds: TimeInterval) -> Bool {
// No recorded start (hook not installed, or app restarted mid-turn): err toward telling the user.
guard let startedAt else { return true }
return endedAt.timeIntervalSince(startedAt) >= minimumSeconds
}
public static func startFilePath(directory: String) -> String {
(directory as NSString).appendingPathComponent("turn-start")
}
public static func recordStart(at date: Date, directory: String) throws {
try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true)
let text = String(date.timeIntervalSince1970)
try text.write(toFile: startFilePath(directory: directory), atomically: true, encoding: .utf8)
}
/// Returns nil when no start was recorded or the file is unreadable, never throws, so a damaged
/// file cannot stop a notification.
public static func readStart(directory: String) -> Date? {
guard let text = try? String(contentsOfFile: startFilePath(directory: directory), encoding: .utf8),
let seconds = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines)) else { return nil }
return Date(timeIntervalSince1970: seconds)
}
}