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:
65
Sources/LuxeNotifier/AppState.swift
Normal file
65
Sources/LuxeNotifier/AppState.swift
Normal 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
|
||||
}
|
||||
}
|
||||
28
Sources/LuxeNotifier/BannerClickHandler.swift
Normal file
28
Sources/LuxeNotifier/BannerClickHandler.swift
Normal 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])
|
||||
}
|
||||
}
|
||||
53
Sources/LuxeNotifier/BannerPoster.swift
Normal file
53
Sources/LuxeNotifier/BannerPoster.swift
Normal 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: "\\\"") + "\""
|
||||
}
|
||||
}
|
||||
21
Sources/LuxeNotifier/LoginItem.swift
Normal file
21
Sources/LuxeNotifier/LoginItem.swift
Normal 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)")
|
||||
}
|
||||
}
|
||||
}
|
||||
19
Sources/LuxeNotifier/LuxeNotifierApp.swift
Normal file
19
Sources/LuxeNotifier/LuxeNotifierApp.swift
Normal 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)
|
||||
}
|
||||
}
|
||||
60
Sources/LuxeNotifier/MenuContent.swift
Normal file
60
Sources/LuxeNotifier/MenuContent.swift
Normal 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))"
|
||||
}
|
||||
}
|
||||
28
Sources/LuxeNotifier/StatusFile.swift
Normal file
28
Sources/LuxeNotifier/StatusFile.swift
Normal 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
|
||||
}
|
||||
}
|
||||
34
Sources/LuxeNotifier/TerminalFocuser.swift
Normal file
34
Sources/LuxeNotifier/TerminalFocuser.swift
Normal 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)")
|
||||
}
|
||||
}
|
||||
}
|
||||
29
Sources/NotifierCore/BannerPermission.swift
Normal file
29
Sources/NotifierCore/BannerPermission.swift
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
27
Sources/NotifierCore/NotificationCenterModel.swift
Normal file
27
Sources/NotifierCore/NotificationCenterModel.swift
Normal 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
|
||||
}
|
||||
}
|
||||
31
Sources/NotifierCore/NotifyClient.swift
Normal file
31
Sources/NotifierCore/NotifyClient.swift
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
90
Sources/NotifierCore/NotifyEvent.swift
Normal file
90
Sources/NotifierCore/NotifyEvent.swift
Normal 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: "")
|
||||
}
|
||||
}
|
||||
67
Sources/NotifierCore/NotifyListener.swift
Normal file
67
Sources/NotifierCore/NotifyListener.swift
Normal 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)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
44
Sources/NotifierCore/NotifySocket.swift
Normal file
44
Sources/NotifierCore/NotifySocket.swift
Normal 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)
|
||||
}
|
||||
}
|
||||
21
Sources/NotifierCore/TerminalLocator.swift
Normal file
21
Sources/NotifierCore/TerminalLocator.swift
Normal 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",
|
||||
]
|
||||
}
|
||||
31
Sources/NotifierCore/TurnTimer.swift
Normal file
31
Sources/NotifierCore/TurnTimer.swift
Normal 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)
|
||||
}
|
||||
}
|
||||
73
Sources/luxe-notify/main.swift
Normal file
73
Sources/luxe-notify/main.swift
Normal file
@@ -0,0 +1,73 @@
|
||||
import Foundation
|
||||
import NotifierCore
|
||||
|
||||
// A hook must never block or fail luxe: always exit 0, print nothing on stdout, report on stderr.
|
||||
func warn(_ message: String) {
|
||||
FileHandle.standardError.write(Data("luxe-notify: \(message)\n".utf8))
|
||||
}
|
||||
|
||||
struct Options {
|
||||
var hookPoint = ""
|
||||
var socketPath = NotifySocket.defaultPath()
|
||||
var minimumSeconds = TurnTimer.defaultMinimumSeconds
|
||||
|
||||
/// Flags may appear anywhere; the first bare word is the hook point.
|
||||
static func parse(_ arguments: [String]) -> Options? {
|
||||
var options = Options()
|
||||
var index = 0
|
||||
var sawHookPoint = false
|
||||
while index < arguments.count {
|
||||
let argument = arguments[index]
|
||||
switch argument {
|
||||
case "--min-seconds":
|
||||
guard index + 1 < arguments.count, let value = TimeInterval(arguments[index + 1]) else {
|
||||
warn("--min-seconds needs a number")
|
||||
return nil
|
||||
}
|
||||
options.minimumSeconds = value
|
||||
index += 1
|
||||
case "--socket":
|
||||
guard index + 1 < arguments.count else { warn("--socket needs a path"); return nil }
|
||||
options.socketPath = arguments[index + 1]
|
||||
index += 1
|
||||
default:
|
||||
if !sawHookPoint { options.hookPoint = argument; sawHookPoint = true }
|
||||
}
|
||||
index += 1
|
||||
}
|
||||
return sawHookPoint ? options : nil
|
||||
}
|
||||
}
|
||||
|
||||
func isTurnStart(_ hookPoint: String) -> Bool {
|
||||
hookPoint.lowercased().replacingOccurrences(of: "_", with: "") == "beforeagentstart"
|
||||
}
|
||||
|
||||
func isTurnEnd(_ hookPoint: String) -> Bool {
|
||||
hookPoint.lowercased().replacingOccurrences(of: "_", with: "") == "agentend"
|
||||
}
|
||||
|
||||
guard let options = Options.parse(Array(CommandLine.arguments.dropFirst())) else {
|
||||
warn("usage: luxe-notify <HookPoint> [--min-seconds N] [--socket PATH] (event JSON on stdin)")
|
||||
exit(0)
|
||||
}
|
||||
|
||||
let input = FileHandle.standardInput.readDataToEndOfFile()
|
||||
let appDirectory = (NotifySocket.defaultPath() as NSString).deletingLastPathComponent
|
||||
|
||||
do {
|
||||
if isTurnStart(options.hookPoint) {
|
||||
try TurnTimer.recordStart(at: Date(), directory: appDirectory)
|
||||
exit(0)
|
||||
}
|
||||
if isTurnEnd(options.hookPoint) {
|
||||
let started = TurnTimer.readStart(directory: appDirectory)
|
||||
guard TurnTimer.shouldNotify(startedAt: started, endedAt: Date(), minimumSeconds: options.minimumSeconds) else { exit(0) }
|
||||
}
|
||||
var event = try HookEventParser.parse(input, hookPoint: options.hookPoint, cwd: FileManager.default.currentDirectoryPath)
|
||||
event.terminalBundleID = TerminalLocator.bundleID(from: ProcessInfo.processInfo.environment)
|
||||
try NotifyClient.send(event, to: options.socketPath)
|
||||
} catch {
|
||||
warn("\(error)")
|
||||
}
|
||||
exit(0)
|
||||
Reference in New Issue
Block a user