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,65 @@
import AppKit
import NotifierCore
import SwiftUI
/// Bridges the socket thread to the main-thread UI.
@MainActor
final class AppState: ObservableObject {
@Published private(set) var history: [NotifyEvent] = []
@Published private(set) var unseenCount = 0
@Published var isMuted = false {
didSet { model.isMuted = isMuted }
}
@Published var launchAtLogin = LoginItem.isEnabled {
didSet { if launchAtLogin != LoginItem.isEnabled { LoginItem.set(launchAtLogin) } }
}
@Published private(set) var permission = BannerPermission.unknown
private let model = NotificationCenterModel()
/// Counts every event since launch. History length can't serve: Clear and the cap both shrink it.
private var totalReceived = 0
private var listener: NotifyListener?
func refreshPermission() {
BannerPoster.refreshStatus { [weak self] status in Task { @MainActor in self?.permission = status } }
}
func start() {
BannerClickHandler.install()
BannerPoster.requestPermission { [weak self] status in Task { @MainActor in self?.permission = status } }
let listener = NotifyListener(
path: NotifySocket.defaultPath(),
onEvent: { [weak self] event in Task { @MainActor in self?.receive(event) } },
onProblem: { NSLog("LuxeNotifier: \($0)") }
)
do { try listener.start() } catch { NSLog("LuxeNotifier: cannot listen on socket: \(error)") }
self.listener = listener
}
func markSeen() {
model.markAllSeen()
publish()
}
func clear() {
model.clear()
publish()
}
private func receive(_ event: NotifyEvent) {
totalReceived += 1
NSLog("LuxeNotifier: received \(event.kind.rawValue): \(event.message)")
StatusFile.set("last-event", "\(event.kind.rawValue) at \(event.timestamp)")
StatusFile.set("events-received", "\(totalReceived)")
let showBanner = model.receive(event)
publish()
if showBanner { BannerPoster.post(title: event.title, message: event.message, terminalBundleID: event.terminalBundleID) }
}
private func publish() {
history = model.history
unseenCount = model.unseenCount
}
}

View File

@@ -0,0 +1,28 @@
import Foundation
import UserNotifications
/// Focuses the terminal when a banner is clicked. The delegate must be set before the app finishes
/// launching or macOS drops the click, so it is installed from AppState.start().
final class BannerClickHandler: NSObject, UNUserNotificationCenterDelegate {
static let terminalKey = "terminalBundleID"
static let shared = BannerClickHandler()
static func install() {
guard Bundle.main.bundleIdentifier != nil else { return }
UNUserNotificationCenter.current().delegate = shared
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let id = response.notification.request.content.userInfo[Self.terminalKey] as? String
StatusFile.set("last-banner-click", "terminal=\(id ?? "none")")
DispatchQueue.main.async { TerminalFocuser.focus(bundleID: id) }
completionHandler()
}
/// Show banners even while the app is frontmost (e.g. its menu is open); otherwise macOS hides them.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound])
}
}

View File

@@ -0,0 +1,53 @@
import Foundation
import NotifierCore
import UserNotifications
/// UNUserNotificationCenter crashes without an app bundle, which a bare `swift run` lacks, so
/// fall back to osascript there. The installed .app bundle takes the native path.
enum BannerPoster {
private static var hasBundle: Bool { Bundle.main.bundleIdentifier != nil }
/// Asks once, then reports the resulting status. `onStatus` runs on a background queue.
static func requestPermission(onStatus: @escaping (BannerPermission) -> Void) {
guard hasBundle else { return }
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { _, error in
if let error { StatusFile.set("permission-error", "\(error)") }
refreshStatus(onStatus)
}
}
/// Re-read the setting, since the user can change it in System Settings while the app runs.
static func refreshStatus(_ onStatus: @escaping (BannerPermission) -> Void) {
guard hasBundle else { return }
UNUserNotificationCenter.current().getNotificationSettings { settings in
let status = BannerPermission(authorizationRawValue: settings.authorizationStatus.rawValue)
StatusFile.set("authorization", "\(settings.authorizationStatus.rawValue) -> \(status)")
onStatus(status)
}
}
static func post(title: String, message: String, terminalBundleID: String? = nil) {
guard hasBundle else { return postWithOsascript(title: title, message: message) }
let content = UNMutableNotificationContent()
content.title = title
content.body = message
content.sound = .default
if let terminalBundleID { content.userInfo = [BannerClickHandler.terminalKey: terminalBundleID] }
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error { NSLog("LuxeNotifier: could not post banner: \(error)") }
}
}
private static func postWithOsascript(title: String, message: String) {
let script = "display notification \(quoted(message)) with title \(quoted(title))"
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")
process.arguments = ["-e", script]
do { try process.run() } catch { NSLog("LuxeNotifier: osascript failed: \(error)") }
}
private static func quoted(_ text: String) -> String {
"\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
}

View File

@@ -0,0 +1,21 @@
import Foundation
import ServiceManagement
/// SMAppService only works from an installed .app bundle, so report that plainly instead of failing.
enum LoginItem {
static var isAvailable: Bool { Bundle.main.bundleIdentifier != nil }
static var isEnabled: Bool { isAvailable && SMAppService.mainApp.status == .enabled }
static func set(_ enabled: Bool) {
guard isAvailable else {
NSLog("LuxeNotifier: launch at login needs the installed .app bundle (run `make install`)")
return
}
do {
if enabled { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() }
} catch {
NSLog("LuxeNotifier: could not change launch at login: \(error)")
}
}
}

View File

@@ -0,0 +1,19 @@
import SwiftUI
@main
struct LuxeNotifierApp: App {
@StateObject private var state = AppState()
var body: some Scene {
MenuBarExtra {
MenuContent(state: state)
} label: {
HStack(spacing: 2) {
Image(systemName: state.unseenCount > 0 ? "bell.badge.fill" : "bell")
if state.unseenCount > 0 { Text("\(state.unseenCount)") }
}
.task { state.start() }
}
.menuBarExtraStyle(.window)
}
}

View File

@@ -0,0 +1,60 @@
import AppKit
import NotifierCore
import SwiftUI
struct MenuContent: View {
@ObservedObject var state: AppState
var body: some View {
VStack(alignment: .leading, spacing: 8) {
if let warning = state.permission.warning {
Label(warning, systemImage: "exclamationmark.triangle.fill")
.font(.caption)
.foregroundStyle(.orange)
}
if state.history.isEmpty {
Text("Nothing waiting on you").foregroundStyle(.secondary)
} else {
ForEach(Array(state.history.prefix(10).enumerated()), id: \.offset) { _, event in
Button { TerminalFocuser.focus(bundleID: event.terminalBundleID) } label: {
EventRow(event: event).frame(maxWidth: .infinity, alignment: .leading)
}
.buttonStyle(.plain)
.help(event.terminalBundleID == nil ? "No terminal recorded for this event" : "Bring the terminal forward")
}
}
Divider()
Toggle("Mute banners", isOn: $state.isMuted)
Toggle("Launch at login", isOn: $state.launchAtLogin)
.disabled(!LoginItem.isAvailable)
HStack {
Button("Clear") { state.clear() }.disabled(state.history.isEmpty)
Spacer()
Button("Quit") { NSApplication.shared.terminate(nil) }
}
}
.padding(12)
.frame(width: 320)
.onAppear {
state.markSeen()
state.refreshPermission()
}
}
}
struct EventRow: View {
let event: NotifyEvent
var body: some View {
VStack(alignment: .leading, spacing: 2) {
Text(event.title).font(.headline)
Text(event.message).font(.subheadline)
Text(detail).font(.caption).foregroundStyle(.secondary)
}
}
private var detail: String {
let folder = event.cwd.map { URL(fileURLWithPath: $0).lastPathComponent } ?? "unknown folder"
return "\(folder) · \(event.timestamp.formatted(date: .omitted, time: .shortened))"
}
}

View File

@@ -0,0 +1,28 @@
import Foundation
/// Plain-text record of what the app saw, because a release build's NSLog lines are hard to read
/// back. Lives beside the socket so one folder holds everything the app owns.
enum StatusFile {
static var path: String {
(NotifySocketPathHelper.directory as NSString).appendingPathComponent("status.txt")
}
private static var lines: [String: String] = [:]
private static let lock = NSLock()
static func set(_ key: String, _ value: String) {
lock.lock()
lines[key] = value
let text = lines.sorted { $0.key < $1.key }.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n"
lock.unlock()
do { try text.write(toFile: path, atomically: true, encoding: .utf8) }
catch { NSLog("LuxeNotifier: cannot write status file \(path): \(error)") }
}
}
enum NotifySocketPathHelper {
static var directory: String {
let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
return base.appendingPathComponent("LuxeNotifier").path
}
}

View File

@@ -0,0 +1,34 @@
import AppKit
import Foundation
/// Brings the terminal that owns a luxe session to the front.
enum TerminalFocuser {
/// Returns false when nothing could be activated, so the caller can say so instead of doing nothing.
@discardableResult
static func focus(bundleID: String?) -> Bool {
guard let bundleID else {
NSLog("LuxeNotifier: event carried no terminal; cannot focus")
return false
}
guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID) else {
NSLog("LuxeNotifier: no installed app with bundle id \(bundleID)")
return false
}
let running = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).first
let activated = running?.activate(options: [.activateAllWindows]) ?? false
reopen(url: url, bundleID: bundleID, activated: activated)
return true
}
/// activate() gives an app keyboard focus but does not make it raise a window, which left the
/// terminal's window under other apps' windows. Opening an already-running app sends it a
/// "reopen" request, which apps normally answer by raising or creating a window.
private static func reopen(url: URL, bundleID: String, activated: Bool) {
let configuration = NSWorkspace.OpenConfiguration()
configuration.activates = true
NSWorkspace.shared.openApplication(at: url, configuration: configuration) { _, error in
let outcome = error.map { "failed: \($0)" } ?? "ok"
StatusFile.set("last-focus", "\(bundleID): activate=\(activated), reopen=\(outcome)")
}
}
}