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:
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
.build/
|
||||
.luxe/
|
||||
*.sock
|
||||
41
Makefile
Normal file
41
Makefile
Normal file
@@ -0,0 +1,41 @@
|
||||
APP_NAME := LuxeNotifier
|
||||
BUILD_DIR := .build/release-bundle
|
||||
APP_BUNDLE := $(BUILD_DIR)/$(APP_NAME).app
|
||||
BIN_DIR := $(HOME)/.local/bin
|
||||
APPS_DIR := $(HOME)/Applications
|
||||
|
||||
.PHONY: build bundle install uninstall test
|
||||
|
||||
build:
|
||||
swift build -c release
|
||||
|
||||
# Notifications and launch-at-login only work from a real bundle, so ad-hoc sign one.
|
||||
bundle: build
|
||||
rm -rf $(APP_BUNDLE)
|
||||
mkdir -p $(APP_BUNDLE)/Contents/MacOS
|
||||
cp Resources/Info.plist $(APP_BUNDLE)/Contents/Info.plist
|
||||
cp "$$(swift build -c release --show-bin-path)/$(APP_NAME)" $(APP_BUNDLE)/Contents/MacOS/$(APP_NAME)
|
||||
codesign --force --sign - $(APP_BUNDLE)
|
||||
|
||||
install: bundle
|
||||
mkdir -p $(BIN_DIR) $(APPS_DIR)
|
||||
cp "$$(swift build -c release --show-bin-path)/luxe-notify" $(BIN_DIR)/luxe-notify
|
||||
rm -rf $(APPS_DIR)/$(APP_NAME).app
|
||||
cp -R $(APP_BUNDLE) $(APPS_DIR)/$(APP_NAME).app
|
||||
@echo "Installed. Open it with: open $(APPS_DIR)/$(APP_NAME).app"
|
||||
|
||||
uninstall:
|
||||
-pkill $(APP_NAME)
|
||||
rm -f $(BIN_DIR)/luxe-notify
|
||||
rm -rf $(APPS_DIR)/$(APP_NAME).app
|
||||
rm -rf "$(HOME)/Library/Application Support/LuxeNotifier"
|
||||
|
||||
# The first test build after a change sometimes fails with "plugin for module 'TestingMacros' not
|
||||
# found" under Command Line Tools (no Xcode) and passes on an immediate retry. Cause not found; this
|
||||
# retries once and only when that exact error appears, so real failures still fail.
|
||||
test:
|
||||
@swift test 2>&1 | tee .build/last-test.log | grep -v -E '^\[[0-9]+ / [0-9]+\]'; \
|
||||
status=$${PIPESTATUS[0]}; \
|
||||
if [ $$status -ne 0 ] && grep -q "plugin for module 'TestingMacros' not found" .build/last-test.log; then \
|
||||
echo "retrying once: known TestingMacros first-build error"; swift test; \
|
||||
else exit $$status; fi
|
||||
72
PLAN.md
Normal file
72
PLAN.md
Normal file
@@ -0,0 +1,72 @@
|
||||
# luxe Notifier: a macOS menu bar app for "luxe needs you"
|
||||
|
||||
A native Swift/SwiftUI menu bar app that tells you when luxe is waiting on you. luxe hooks
|
||||
(`~/.config/luxe/hooks.json`) run a tiny CLI, `luxe-notify`, which sends one JSON line over a Unix
|
||||
socket to the app. The app posts a macOS notification, keeps a badge and a history list in the
|
||||
menu bar, and can bring the right terminal forward. Built with Swift Package Manager so everything
|
||||
builds and tests from the terminal.
|
||||
|
||||
Decided with the user: menu bar app plus hook CLI, Swift and SwiftUI, Unix socket transport.
|
||||
|
||||
Hook points used (from `luxe docs hooks`): `PermissionRequested` (approval prompt),
|
||||
`AgentEnd` (turn finished, waiting on your next message), `Error` (turn failed).
|
||||
Open item to verify in Phase 0: whether luxe's `question` tool fires any hook.
|
||||
|
||||
## Phase 0 — Verify hook behavior and scaffold
|
||||
Build: a SwiftPM package with three targets: `NotifierCore` (library), `luxe-notify` (CLI),
|
||||
`LuxeNotifier` (app). Write a throwaway hook that logs stdin to a file for `PermissionRequested`,
|
||||
`AgentEnd`, `Error`, and trigger each in luxe, including a `question` prompt.
|
||||
Done when: `swift build` succeeds; the logged payloads are saved under `docs/hook-payloads/`;
|
||||
`PLAN.md` is updated if the `question` tool fires no hook (then fall back to `AgentEnd`).
|
||||
|
||||
## Phase 1 — Event model and socket protocol (NotifierCore)
|
||||
Build: `NotifyEvent` (kind, title, message, cwd, timestamp, terminal hint) with JSON
|
||||
encode/decode, parsing from raw hook stdin, and a socket path helper
|
||||
(`~/Library/Application Support/LuxeNotifier/notify.sock`).
|
||||
Done when: `swift test` passes cases for each hook payload shape, malformed JSON (rejected with a
|
||||
clear error), and unknown event kinds (kept as a generic event, not dropped).
|
||||
|
||||
## Phase 2 — luxe-notify CLI
|
||||
Build: reads the hook event from stdin, maps it to a `NotifyEvent`, writes one JSON line to the
|
||||
socket, prints nothing on stdout (so luxe sees "no opinion"), and exits 0 even when the app isn't
|
||||
running (a hook must never block luxe). Failures go to stderr.
|
||||
Done when: `echo '<payload>' | swift run luxe-notify` delivers to a test listener
|
||||
(`nc -U`), and exits 0 with a stderr message when no socket exists. Tests cover both.
|
||||
|
||||
## Phase 3 — Menu bar app: listener and notifications
|
||||
Build: `MenuBarExtra` app that listens on the socket, posts a `UserNotifications` banner per
|
||||
event, and keeps an in-memory list. First launch requests notification permission.
|
||||
Done when: with the app running, the Phase 2 command shows a real banner; two quick events show
|
||||
two entries; the app handles a client disconnecting mid-write. Listener logic has unit tests.
|
||||
|
||||
## Phase 4 — Menu UI: badge, history, actions
|
||||
Build: badge count of unseen events, a history list (newest first, clear all), a click action
|
||||
that activates the terminal app owning the session, mute toggle, and launch at login.
|
||||
Done when: manual walkthrough passes (badge rises and clears, mute suppresses banners, click
|
||||
focuses the terminal) and logic is covered by view-model tests.
|
||||
|
||||
## Phase 5 — Install and wire into luxe
|
||||
Build: `make install` (builds release, copies `luxe-notify` to `~/.local/bin`, app to
|
||||
`~/Applications`), a documented `hooks.json` snippet, and a short README.
|
||||
Done when: from a clean state, a real luxe session raises a notification on a permission prompt
|
||||
and when a turn ends, and `README.md` has the exact install and uninstall steps.
|
||||
|
||||
## Follow-up work (done after the original six phases)
|
||||
|
||||
Built and verified against the real app, with screenshots and the app's own `status.txt`:
|
||||
|
||||
- Permission-denied warning in the menu (`BannerPermission`, unit-tested and mutation-checked).
|
||||
- Badge count next to the bell.
|
||||
- Turn-length suppression for `AgentEnd` (`TurnTimer`, `--min-seconds`, driven by `BeforeAgentStart`).
|
||||
- Click-to-focus: a banner click activates and reopens the terminal named by the event's
|
||||
`terminalBundleID`. Tested with one Ghostty window and Finder in front.
|
||||
- Question notifications: luxe's `question` tool fires `BeforeToolUse` (found by logging real hook
|
||||
payloads), parsed into a `question` event. Confirmed with a real banner.
|
||||
- Turn-length rule confirmed in real luxe: a 28s turn was suppressed, a 45s turn notified.
|
||||
|
||||
Still open:
|
||||
|
||||
- Clicking a history row (same code path as the banner, but not exercised).
|
||||
- Multiple windows, minimized windows and other terminals for click-to-focus.
|
||||
- The icon can be hidden by macOS on a crowded menu bar. No code fix known.
|
||||
- `TestingMacros` first-build error under Command Line Tools. `make test` retries once; cause unknown.
|
||||
17
Package.swift
Normal file
17
Package.swift
Normal file
@@ -0,0 +1,17 @@
|
||||
// swift-tools-version:5.9
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "LuxeNotifier",
|
||||
platforms: [.macOS(.v13)],
|
||||
products: [
|
||||
.executable(name: "luxe-notify", targets: ["luxe-notify"]),
|
||||
.executable(name: "LuxeNotifier", targets: ["LuxeNotifier"]),
|
||||
],
|
||||
targets: [
|
||||
.target(name: "NotifierCore"),
|
||||
.executableTarget(name: "luxe-notify", dependencies: ["NotifierCore"]),
|
||||
.executableTarget(name: "LuxeNotifier", dependencies: ["NotifierCore"]),
|
||||
.testTarget(name: "NotifierCoreTests", dependencies: ["NotifierCore"]),
|
||||
]
|
||||
)
|
||||
112
README.md
Normal file
112
README.md
Normal file
@@ -0,0 +1,112 @@
|
||||
# luxe Notifier
|
||||
|
||||
A 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 the app. The app shows a macOS banner, keeps a badge
|
||||
count and a short history in the menu bar, and can mute banners. Clicking a banner or a history
|
||||
row brings your terminal to the front.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
make install
|
||||
open ~/Applications/LuxeNotifier.app
|
||||
```
|
||||
|
||||
This builds a release, puts `luxe-notify` in `~/.local/bin` (make sure that's on your `PATH`), and
|
||||
installs an ad-hoc signed `LuxeNotifier.app` in `~/Applications`. The first launch asks for
|
||||
notification permission. Turn on "Launch at login" in the menu if you want it.
|
||||
|
||||
Needs the Swift toolchain (Command Line Tools are enough).
|
||||
|
||||
If banners don't show, open the menu: a warning appears when macOS has notifications blocked for
|
||||
the app. Allow it under System Settings > Notifications.
|
||||
|
||||
## Wire it into luxe
|
||||
|
||||
Add this to `~/.config/luxe/hooks.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"PermissionRequested": [
|
||||
{ "command": ["luxe-notify", "PermissionRequested"] }
|
||||
],
|
||||
"BeforeAgentStart": [
|
||||
{ "command": ["luxe-notify", "BeforeAgentStart"] }
|
||||
],
|
||||
"BeforeToolUse": [
|
||||
{ "matcher": "question", "command": ["luxe-notify", "BeforeToolUse"] }
|
||||
],
|
||||
"AgentEnd": [
|
||||
{ "command": ["luxe-notify", "AgentEnd", "--min-seconds", "30"] }
|
||||
],
|
||||
"Error": [
|
||||
{ "command": ["luxe-notify", "Error"] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
If luxe can't find `luxe-notify`, use its full path (`/Users/you/.local/bin/luxe-notify`).
|
||||
|
||||
- `PermissionRequested`: luxe is waiting on an approval.
|
||||
- `BeforeToolUse` with `"matcher": "question"`: luxe asked you a question. Keep the matcher: without
|
||||
it every tool call would run the hook. The banner shows the question text.
|
||||
- `BeforeAgentStart`: records when a turn begins. Sends nothing.
|
||||
- `AgentEnd`: a turn finished, so luxe is waiting for your next message. Only notifies if the turn
|
||||
took at least `--min-seconds` (default 30), so quick turns don't buzz you. If no start was
|
||||
recorded it notifies anyway.
|
||||
- `Error`: a turn failed.
|
||||
|
||||
`luxe-notify` always exits 0 and prints nothing to stdout, so it can never block or change a
|
||||
luxe call. If the app isn't running, it writes a one-line reason to stderr and moves on.
|
||||
|
||||
Options: `--min-seconds N` and `--socket PATH`, anywhere after the hook point.
|
||||
|
||||
## Try it without luxe
|
||||
|
||||
```bash
|
||||
echo '{"Other":{"tool":"bash"}}' | luxe-notify PermissionRequested
|
||||
```
|
||||
|
||||
## Debugging
|
||||
|
||||
The app writes `~/Library/Application Support/LuxeNotifier/status.txt` with the notification
|
||||
permission state, the last event, and the last banner click. Start there if something is silent.
|
||||
|
||||
## Known limits
|
||||
|
||||
- **A crowded menu bar can hide the icon.** macOS drops status items that don't fit, and the app
|
||||
can't prevent it. Seen once: the item sat off-screen until other menu bar apps were quit. If the
|
||||
bell is missing, free up space or use a menu bar manager.
|
||||
- **`question` prompts** notify through the `BeforeToolUse` hook, which isn't documented as a
|
||||
question hook: it was found by logging real hook payloads. If a luxe update changes how `question`
|
||||
reports itself, those notifications could stop; `PermissionRequested` and `AgentEnd` would still work.
|
||||
- **Clicking a banner brings the terminal app forward, not a specific window or tab.** It needs the
|
||||
terminal's bundle id, which comes from the `__CFBundleIdentifier` or `TERM_PROGRAM` variables the
|
||||
hook inherits. With neither, the click does nothing. The app activates the terminal and also asks
|
||||
macOS to "reopen" it (what clicking its Dock icon does): activating alone gave Ghostty keyboard
|
||||
focus but left its window under other windows. Reopen never closes or quits anything, but what an
|
||||
app does with it is up to the app. Tested only with one Ghostty window and Finder in front; multiple
|
||||
windows, minimized windows and other terminals are untested. Clicking a history row uses the same
|
||||
code but was not tested.
|
||||
- Native banners only work from the installed `.app`. The bare binary falls back to `osascript`.
|
||||
|
||||
## Uninstall
|
||||
|
||||
```bash
|
||||
make uninstall
|
||||
```
|
||||
|
||||
Remove the entries from `hooks.json` too.
|
||||
|
||||
## Develop
|
||||
|
||||
```bash
|
||||
make test # 35 tests: hook parsing, socket round trip, menu model, turn timer, terminal lookup
|
||||
```
|
||||
|
||||
On Command Line Tools without Xcode, the first test build after a change can fail with
|
||||
`plugin for module 'TestingMacros' not found` and then pass on retry. `make test` retries once for
|
||||
that exact error. The cause isn't known.
|
||||
|
||||
Code is split into `NotifierCore` (events, socket, menu model, timers), `luxe-notify` (the hook
|
||||
CLI), and `LuxeNotifier` (the SwiftUI app).
|
||||
15
Resources/Info.plist
Normal file
15
Resources/Info.plist
Normal file
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key><string>dev.luxe.notifier</string>
|
||||
<key>CFBundleName</key><string>LuxeNotifier</string>
|
||||
<key>CFBundleDisplayName</key><string>luxe Notifier</string>
|
||||
<key>CFBundleExecutable</key><string>LuxeNotifier</string>
|
||||
<key>CFBundlePackageType</key><string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key><string>0.1.0</string>
|
||||
<key>CFBundleVersion</key><string>1</string>
|
||||
<key>LSMinimumSystemVersion</key><string>13.0</string>
|
||||
<key>LSUIElement</key><true/>
|
||||
</dict>
|
||||
</plist>
|
||||
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)
|
||||
25
Tests/NotifierCoreTests/BannerPermissionTests.swift
Normal file
25
Tests/NotifierCoreTests/BannerPermissionTests.swift
Normal file
@@ -0,0 +1,25 @@
|
||||
import Testing
|
||||
@testable import NotifierCore
|
||||
|
||||
struct BannerPermissionTests {
|
||||
@Test func deniedWarnsAndNamesTheSettingToChange() {
|
||||
let warning = BannerPermission(authorizationRawValue: 1).warning
|
||||
#expect(warning?.contains("System Settings") == true)
|
||||
}
|
||||
|
||||
@Test func notDeterminedSaysItIsWaiting() {
|
||||
#expect(BannerPermission(authorizationRawValue: 0).warning?.contains("Waiting") == true)
|
||||
}
|
||||
|
||||
@Test func authorizedStatusesStayQuiet() {
|
||||
for raw in [2, 3, 4] {
|
||||
#expect(BannerPermission(authorizationRawValue: raw) == .allowed)
|
||||
#expect(BannerPermission(authorizationRawValue: raw).warning == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func anUnrecognizedStatusIsUnknownAndStaysQuiet() {
|
||||
#expect(BannerPermission(authorizationRawValue: 99) == .unknown)
|
||||
#expect(BannerPermission(authorizationRawValue: 99).warning == nil)
|
||||
}
|
||||
}
|
||||
50
Tests/NotifierCoreTests/HookEventParserTests.swift
Normal file
50
Tests/NotifierCoreTests/HookEventParserTests.swift
Normal file
@@ -0,0 +1,50 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import NotifierCore
|
||||
|
||||
struct HookEventParserTests {
|
||||
private func parse(_ json: String, point: String) throws -> NotifyEvent {
|
||||
try HookEventParser.parse(Data(json.utf8), hookPoint: point, cwd: "/work")
|
||||
}
|
||||
|
||||
@Test func permissionRequestedNamesTheTool() throws {
|
||||
let event = try parse(#"{"Other":{"tool":"bash","phase":"requested"}}"#, point: "PermissionRequested")
|
||||
#expect(event.kind == .permission)
|
||||
#expect(event.message.contains("bash"))
|
||||
#expect(event.cwd == "/work")
|
||||
}
|
||||
|
||||
@Test func agentEndMeansWaitingOnYou() throws {
|
||||
let event = try parse(#"{"Other":{"effective_context_percent":12.5}}"#, point: "AgentEnd")
|
||||
#expect(event.kind == .turnEnded)
|
||||
}
|
||||
|
||||
@Test func errorCarriesTheMessage() throws {
|
||||
let event = try parse(#"{"Other":{"message":"provider timed out"}}"#, point: "Error")
|
||||
#expect(event.kind == .error)
|
||||
#expect(event.message == "provider timed out")
|
||||
}
|
||||
|
||||
@Test func hookPointMatchingIsLooseLikeLuxe() throws {
|
||||
#expect(try parse("{}", point: "permission_requested").kind == .permission)
|
||||
}
|
||||
|
||||
@Test func unknownHookPointIsKeptAsGenericNotDropped() throws {
|
||||
let event = try parse("{}", point: "SessionStart")
|
||||
#expect(event.kind == .generic)
|
||||
#expect(event.message.contains("SessionStart"))
|
||||
}
|
||||
|
||||
@Test func malformedJSONIsRejectedWithAReason() {
|
||||
do {
|
||||
_ = try parse("not json", point: "AgentEnd")
|
||||
Issue.record("expected a parse error")
|
||||
} catch {
|
||||
#expect("\(error)".contains("not valid JSON"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func nonObjectJSONIsRejected() {
|
||||
#expect(throws: HookParseError.notAnObject) { try parse("[1,2]", point: "AgentEnd") }
|
||||
}
|
||||
}
|
||||
52
Tests/NotifierCoreTests/NotificationCenterModelTests.swift
Normal file
52
Tests/NotifierCoreTests/NotificationCenterModelTests.swift
Normal file
@@ -0,0 +1,52 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import NotifierCore
|
||||
|
||||
struct NotificationCenterModelTests {
|
||||
private func event(_ message: String) -> NotifyEvent {
|
||||
NotifyEvent(kind: .generic, title: "t", message: message)
|
||||
}
|
||||
|
||||
@Test func newestEventComesFirstAndRaisesTheBadge() {
|
||||
let model = NotificationCenterModel()
|
||||
model.receive(event("a"))
|
||||
model.receive(event("b"))
|
||||
#expect(model.history.map(\.message) == ["b", "a"])
|
||||
#expect(model.unseenCount == 2)
|
||||
}
|
||||
|
||||
@Test func markingSeenClearsBadgeButKeepsHistory() {
|
||||
let model = NotificationCenterModel()
|
||||
model.receive(event("a"))
|
||||
model.markAllSeen()
|
||||
#expect(model.unseenCount == 0)
|
||||
#expect(model.history.count == 1)
|
||||
}
|
||||
|
||||
@Test func mutedEventsAreRecordedButNoBannerIsRequested() {
|
||||
let model = NotificationCenterModel()
|
||||
model.isMuted = true
|
||||
#expect(model.receive(event("a")) == false)
|
||||
#expect(model.history.count == 1)
|
||||
#expect(model.unseenCount == 1)
|
||||
}
|
||||
|
||||
@Test func unmutedEventsRequestABanner() {
|
||||
#expect(NotificationCenterModel().receive(event("a")) == true)
|
||||
}
|
||||
|
||||
@Test func historyIsCappedAndDropsTheOldest() {
|
||||
let model = NotificationCenterModel()
|
||||
model.maxHistory = 2
|
||||
["a", "b", "c"].forEach { model.receive(event($0)) }
|
||||
#expect(model.history.map(\.message) == ["c", "b"])
|
||||
}
|
||||
|
||||
@Test func clearEmptiesHistoryAndBadge() {
|
||||
let model = NotificationCenterModel()
|
||||
model.receive(event("a"))
|
||||
model.clear()
|
||||
#expect(model.history.isEmpty)
|
||||
#expect(model.unseenCount == 0)
|
||||
}
|
||||
}
|
||||
39
Tests/NotifierCoreTests/QuestionEventTests.swift
Normal file
39
Tests/NotifierCoreTests/QuestionEventTests.swift
Normal file
@@ -0,0 +1,39 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import NotifierCore
|
||||
|
||||
struct QuestionEventTests {
|
||||
private func parse(_ json: String) throws -> NotifyEvent {
|
||||
try HookEventParser.parse(Data(json.utf8), hookPoint: "BeforeToolUse", cwd: "/work")
|
||||
}
|
||||
|
||||
private let questionPayload = #"{"ToolUse":{"tool_name":"question","args":{"prompt":"Restart luxe now?","options":[]}}}"#
|
||||
|
||||
@Test func aQuestionToolCallBecomesAQuestionEvent() throws {
|
||||
let event = try parse(questionPayload)
|
||||
#expect(event.kind == .question)
|
||||
#expect(event.message == "Restart luxe now?")
|
||||
#expect(event.title == "luxe has a question")
|
||||
}
|
||||
|
||||
@Test func aQuestionWithNoPromptStillNotifiesWithAFallback() throws {
|
||||
let event = try parse(#"{"ToolUse":{"tool_name":"question","args":{}}}"#)
|
||||
#expect(event.kind == .question)
|
||||
#expect(!event.message.isEmpty)
|
||||
}
|
||||
|
||||
@Test func aVeryLongPromptIsTruncatedForTheBanner() throws {
|
||||
let long = String(repeating: "x", count: 500)
|
||||
let event = try parse(#"{"ToolUse":{"tool_name":"question","args":{"prompt":"\#(long)"}}}"#)
|
||||
#expect(event.message.count <= 200)
|
||||
}
|
||||
|
||||
@Test func otherToolsAreNotTurnedIntoQuestions() throws {
|
||||
let event = try parse(#"{"ToolUse":{"tool_name":"bash","args":{"command":"ls"}}}"#)
|
||||
#expect(event.kind == .generic)
|
||||
}
|
||||
|
||||
@Test func aToolUsePayloadWithoutAToolNameIsNotAQuestion() throws {
|
||||
#expect(try parse(#"{"ToolUse":{"args":{"prompt":"hi"}}}"#).kind == .generic)
|
||||
}
|
||||
}
|
||||
84
Tests/NotifierCoreTests/SocketRoundTripTests.swift
Normal file
84
Tests/NotifierCoreTests/SocketRoundTripTests.swift
Normal file
@@ -0,0 +1,84 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import NotifierCore
|
||||
|
||||
/// Collects listener callbacks and lets a test wait for a count, without XCTest expectations.
|
||||
final class Inbox: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private(set) var events: [NotifyEvent] = []
|
||||
private(set) var problems: [String] = []
|
||||
|
||||
func add(_ event: NotifyEvent) { lock.lock(); events.append(event); lock.unlock() }
|
||||
func add(problem: String) { lock.lock(); problems.append(problem); lock.unlock() }
|
||||
|
||||
private func reached(_ wanted: Int, _ wantedProblems: Int) -> Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return events.count >= wanted && problems.count >= wantedProblems
|
||||
}
|
||||
|
||||
func waitFor(events wanted: Int = 0, problems wantedProblems: Int = 0) async -> Bool {
|
||||
for _ in 0..<200 {
|
||||
if reached(wanted, wantedProblems) { return true }
|
||||
try? await Task.sleep(nanoseconds: 10_000_000)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
struct SocketRoundTripTests {
|
||||
// Unix socket paths cap near 104 bytes, so keep them short.
|
||||
private func freshPath() -> String { "/tmp/luxe-notifier-\(UUID().uuidString.prefix(8)).sock" }
|
||||
|
||||
private func startListener(_ path: String, _ inbox: Inbox) throws -> NotifyListener {
|
||||
let listener = NotifyListener(path: path, onEvent: { inbox.add($0) }, onProblem: { inbox.add(problem: $0) })
|
||||
try listener.start()
|
||||
return listener
|
||||
}
|
||||
|
||||
@Test func eventSentByClientArrivesAtListener() async throws {
|
||||
let path = freshPath()
|
||||
let inbox = Inbox()
|
||||
let listener = try startListener(path, inbox)
|
||||
defer { listener.stop() }
|
||||
|
||||
let sent = NotifyEvent(kind: .permission, title: "t", message: "m", cwd: "/x", timestamp: Date(timeIntervalSince1970: 1_700_000_000))
|
||||
try NotifyClient.send(sent, to: path)
|
||||
|
||||
#expect(await inbox.waitFor(events: 1))
|
||||
#expect(inbox.events.first == sent)
|
||||
}
|
||||
|
||||
@Test func malformedLineIsReportedAndListenerKeepsWorking() async throws {
|
||||
let path = freshPath()
|
||||
let inbox = Inbox()
|
||||
let listener = try startListener(path, inbox)
|
||||
defer { listener.stop() }
|
||||
|
||||
try rawSend("garbage\n", to: path)
|
||||
#expect(await inbox.waitFor(problems: 1))
|
||||
try NotifyClient.send(NotifyEvent(kind: .generic, title: "t", message: "m"), to: path)
|
||||
#expect(await inbox.waitFor(events: 1))
|
||||
}
|
||||
|
||||
@Test func sendingWithNoListenerThrowsAConnectError() {
|
||||
let path = freshPath()
|
||||
#expect(throws: SocketError.self) {
|
||||
try NotifyClient.send(NotifyEvent(kind: .generic, title: "t", message: "m"), to: path)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func overlongSocketPathIsRejectedClearly() {
|
||||
#expect(throws: SocketError.self) { try NotifySocket.makeAddress("/tmp/" + String(repeating: "a", count: 200)) }
|
||||
}
|
||||
|
||||
private func rawSend(_ text: String, to path: String) throws {
|
||||
let fd = socket(AF_UNIX, SOCK_STREAM, 0)
|
||||
defer { close(fd) }
|
||||
var address = try NotifySocket.makeAddress(path)
|
||||
_ = withUnsafePointer(to: &address) {
|
||||
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
|
||||
}
|
||||
_ = text.withCString { write(fd, $0, strlen($0)) }
|
||||
}
|
||||
}
|
||||
41
Tests/NotifierCoreTests/TerminalLocatorTests.swift
Normal file
41
Tests/NotifierCoreTests/TerminalLocatorTests.swift
Normal file
@@ -0,0 +1,41 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import NotifierCore
|
||||
|
||||
struct TerminalLocatorTests {
|
||||
@Test func theExportedBundleIdentifierWins() {
|
||||
let env = ["__CFBundleIdentifier": "com.mitchellh.ghostty", "TERM_PROGRAM": "iTerm.app"]
|
||||
#expect(TerminalLocator.bundleID(from: env) == "com.mitchellh.ghostty")
|
||||
}
|
||||
|
||||
@Test func termProgramIsUsedWhenThereIsNoBundleIdentifier() {
|
||||
#expect(TerminalLocator.bundleID(from: ["TERM_PROGRAM": "iTerm.app"]) == "com.googlecode.iterm2")
|
||||
}
|
||||
|
||||
@Test func anUnknownTermProgramReturnsNilInsteadOfGuessing() {
|
||||
#expect(TerminalLocator.bundleID(from: ["TERM_PROGRAM": "mystery-term"]) == nil)
|
||||
}
|
||||
|
||||
@Test func anEmptyBundleIdentifierFallsThrough() {
|
||||
let env = ["__CFBundleIdentifier": "", "TERM_PROGRAM": "ghostty"]
|
||||
#expect(TerminalLocator.bundleID(from: env) == "com.mitchellh.ghostty")
|
||||
}
|
||||
|
||||
@Test func noHintsAtAllReturnsNil() {
|
||||
#expect(TerminalLocator.bundleID(from: [:]) == nil)
|
||||
}
|
||||
}
|
||||
|
||||
struct EventCompatibilityTests {
|
||||
@Test func anOlderEventWithoutTheTerminalFieldStillDecodes() throws {
|
||||
let line = Data(#"{"kind":"permission","title":"t","message":"m","timestamp":"2026-10-25T02:23:19Z"}"#.utf8)
|
||||
let event = try NotifySocket.decodeLine(line)
|
||||
#expect(event.terminalBundleID == nil)
|
||||
}
|
||||
|
||||
@Test func theTerminalFieldSurvivesTheSocketEncoding() throws {
|
||||
let sent = NotifyEvent(kind: .permission, title: "t", message: "m", timestamp: Date(timeIntervalSince1970: 1_700_000_000), terminalBundleID: "com.mitchellh.ghostty")
|
||||
let line = try NotifySocket.encodeLine(sent)
|
||||
#expect(try NotifySocket.decodeLine(line.dropLast()) == sent)
|
||||
}
|
||||
}
|
||||
42
Tests/NotifierCoreTests/TurnTimerTests.swift
Normal file
42
Tests/NotifierCoreTests/TurnTimerTests.swift
Normal file
@@ -0,0 +1,42 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import NotifierCore
|
||||
|
||||
struct TurnTimerTests {
|
||||
private let start = Date(timeIntervalSince1970: 1_000)
|
||||
|
||||
@Test func aTurnLongerThanTheMinimumNotifies() {
|
||||
#expect(TurnTimer.shouldNotify(startedAt: start, endedAt: start.addingTimeInterval(45), minimumSeconds: 30))
|
||||
}
|
||||
|
||||
@Test func aQuickTurnIsSuppressed() {
|
||||
#expect(!TurnTimer.shouldNotify(startedAt: start, endedAt: start.addingTimeInterval(5), minimumSeconds: 30))
|
||||
}
|
||||
|
||||
@Test func aTurnExactlyAtTheMinimumNotifies() {
|
||||
#expect(TurnTimer.shouldNotify(startedAt: start, endedAt: start.addingTimeInterval(30), minimumSeconds: 30))
|
||||
}
|
||||
|
||||
@Test func aMissingStartErrsTowardNotifying() {
|
||||
#expect(TurnTimer.shouldNotify(startedAt: nil, endedAt: start, minimumSeconds: 30))
|
||||
}
|
||||
|
||||
@Test func recordedStartIsReadBack() throws {
|
||||
let directory = NSTemporaryDirectory() + "turntimer-\(UUID().uuidString)"
|
||||
defer { try? FileManager.default.removeItem(atPath: directory) }
|
||||
try TurnTimer.recordStart(at: start, directory: directory)
|
||||
#expect(TurnTimer.readStart(directory: directory) == start)
|
||||
}
|
||||
|
||||
@Test func aMissingStartFileReadsAsNil() {
|
||||
#expect(TurnTimer.readStart(directory: "/tmp/does-not-exist-\(UUID().uuidString)") == nil)
|
||||
}
|
||||
|
||||
@Test func aCorruptStartFileReadsAsNilInsteadOfCrashing() throws {
|
||||
let directory = NSTemporaryDirectory() + "turntimer-\(UUID().uuidString)"
|
||||
defer { try? FileManager.default.removeItem(atPath: directory) }
|
||||
try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true)
|
||||
try "not a number".write(toFile: TurnTimer.startFilePath(directory: directory), atomically: true, encoding: .utf8)
|
||||
#expect(TurnTimer.readStart(directory: directory) == nil)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user