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

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

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

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

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

View File

@@ -0,0 +1,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)
}
}

View 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") }
}
}

View 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)
}
}

View 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)
}
}

View 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)) }
}
}

View 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)
}
}

View 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)
}
}