diff --git a/Makefile b/Makefile index 6693769..8a27062 100644 --- a/Makefile +++ b/Makefile @@ -79,7 +79,7 @@ typecheck-tests: test-without-xcode: @./scripts/run-tests-without-xcode.sh $(NAME) -# One-shot dev cycle: rebuild, reinstall the app, refresh notify.sh in +# One-shot dev cycle: rebuild, reinstall the app, refresh notify.sh and the CLI in # ~/.stack-nudge so hook-side changes propagate, kickstart the daemon. # Build output goes to $(BUILD_LOG); on failure, last 20 lines tail to stderr. .PHONY: reload @@ -95,6 +95,7 @@ reload: cp -R "$(BUILT_APP)" "$(APP)"; \ if [ -d "$$HOME/.stack-nudge" ]; then \ cp notify.sh "$$HOME/.stack-nudge/notify.sh"; \ + cp stack-nudge.sh "$$HOME/.stack-nudge/stack-nudge"; \ if [ -d phrases ]; then \ rm -rf "$$HOME/.stack-nudge/phrases"; \ cp -R phrases "$$HOME/.stack-nudge/phrases"; \ diff --git a/PRIVACY.md b/PRIVACY.md index 8d26642..411a127 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -59,6 +59,14 @@ StackNudge identifier, because there isn't one. about 350 MB and lands in `~/.cache/stackvox/`, outside `~/.stack-nudge/` — worth knowing if you are removing stack-nudge by deleting that directory. +## The local command line + +`~/.stack-nudge/stack-nudge` sends commands (`say`, `focus`, `state`, `poll`, +`busy`, `settings`, `ping`) to the running panel over `~/.stack-nudge/panel.sock`, +a Unix socket readable and writable only by your user. Nothing leaves your +machine. The macOS Focus state is pushed in by a Shortcuts automation you set +up; stack-nudge never reads it from the system. + ## Tools it runs on your behalf Usage tracking (`STACKNUDGE_QUOTA_TRACKING`) reads your quota by shelling out to diff --git a/Package.swift b/Package.swift index b202184..33e9a1c 100644 --- a/Package.swift +++ b/Package.swift @@ -31,6 +31,7 @@ let package = Package( "install.sh", "uninstall.sh", "notify.sh", + "stack-nudge.sh", "notify.conf.example", "README.md", "LICENSE", diff --git a/Tests/StackNudgePanelCoreTests/BootstrapTests.swift b/Tests/StackNudgePanelCoreTests/BootstrapTests.swift index f0b41b3..7603809 100644 --- a/Tests/StackNudgePanelCoreTests/BootstrapTests.swift +++ b/Tests/StackNudgePanelCoreTests/BootstrapTests.swift @@ -212,3 +212,33 @@ final class BootstrapTests: XCTestCase { return dir } } + +// The stack-nudge CLI is copied beside notify.sh and kept equal to the bundle's. +final class BootstrapCLITests: XCTestCase { + + private func tempDir() throws -> URL { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: dir) } + return dir + } + + func test_installCLI_writesAnExecutableCopy() throws { + let path = try tempDir().appendingPathComponent("stack-nudge").path + XCTAssertTrue(Bootstrap.installCLI(bundled: "#!/bin/sh\necho new\n", at: path)) + XCTAssertEqual(try String(contentsOfFile: path, encoding: .utf8), "#!/bin/sh\necho new\n") + XCTAssertTrue(FileManager.default.isExecutableFile(atPath: path)) + } + + func test_installCLI_replacesAnOutdatedCopyAndLeavesAnEqualOne() throws { + let path = try tempDir().appendingPathComponent("stack-nudge").path + try "old".write(toFile: path, atomically: true, encoding: .utf8) + XCTAssertTrue(Bootstrap.installCLI(bundled: "new", at: path)) + XCTAssertFalse(Bootstrap.installCLI(bundled: "new", at: path)) + } + + func test_installCLI_skipsAMachineWithNoInstallDirectory() { + XCTAssertFalse(Bootstrap.installCLI(bundled: "x", at: "/nonexistent-\(UUID().uuidString)/stack-nudge")) + XCTAssertFalse(Bootstrap.installCLI(bundled: nil, at: "/tmp/never")) + } +} diff --git a/Tests/StackNudgePanelCoreTests/CommandChannelTests.swift b/Tests/StackNudgePanelCoreTests/CommandChannelTests.swift new file mode 100644 index 0000000..e087ce6 --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/CommandChannelTests.swift @@ -0,0 +1,300 @@ +import XCTest + +@testable import StackNudgePanelCore + +// The request/reply form of the panel socket: the router on its own, then the +// real listener and the stack-nudge CLI against it. +@MainActor +final class CommandChannelTests: XCTestCase { + + private final class Recorder { + var posted: [NudgeEvent] = [] + var focus: Bool? + var pose: PoseOverride? + var settings: SettingsCategory?? + var busy: [BusyItem] = [] + var poll: ((@escaping (Int) -> Void) -> Void)? + } + + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + private func router(_ recorder: Recorder) -> CommandRouter { + var hooks = CommandHooks() + hooks.post = { recorder.posted.append($0) } + hooks.setFocus = { recorder.focus = $0 } + hooks.focusStatus = { ["focus": recorder.focus ?? false, "held": 0] } + hooks.poll = { recorder.poll } + hooks.setPose = { recorder.pose = $0 } + hooks.busy = { recorder.busy } + hooks.openSettings = { category in + recorder.settings = .some(category) + return category ?? .notifications + } + hooks.now = { self.now } + return CommandRouter(hooks: hooks) + } + + private func run(_ router: CommandRouter, _ json: String) -> [String: Any] { + var out = "" + router.handle(Data(json.utf8)) { out = $0 } + return (try? JSONSerialization.jsonObject(with: Data(out.utf8)) as? [String: Any]) ?? [:] + } + + // MARK: - Detecting a command + + func test_isCommand_onlyALineWithACmdKey() { + XCTAssertTrue(CommandRouter.isCommand(Data(#"{"cmd":"ping"}"#.utf8))) + XCTAssertFalse(CommandRouter.isCommand(Data(#"{"agent":"claude-code","event":"stop","title":"x","message":"y"}"#.utf8))) + XCTAssertFalse(CommandRouter.isCommand(Data("not json".utf8))) + XCTAssertFalse(CommandRouter.isCommand(Data(#"{"cmd":5}"#.utf8))) + } + + // MARK: - Commands + + func test_ping() { + let reply = run(router(Recorder()), #"{"cmd":"ping"}"#) + XCTAssertEqual(reply["ok"] as? Bool, true) + XCTAssertEqual(reply["pong"] as? Bool, true) + } + + func test_unknownCommandFails() { + let reply = run(router(Recorder()), #"{"cmd":"nope"}"#) + XCTAssertEqual(reply["ok"] as? Bool, false) + XCTAssertEqual(reply["error"] as? String, "unknown command nope") + } + + func test_say_postsAScriptFeedEvent() { + let recorder = Recorder() + let reply = run(router(recorder), #"{"cmd":"say","title":"Deploy done","body":"v2","url":"https://example.com/d","severity":"action","tag":"deploy","key":"deploy:1"}"#) + XCTAssertEqual(reply["ok"] as? Bool, true) + let event = recorder.posted.first + XCTAssertEqual(recorder.posted.count, 1) + XCTAssertEqual(event?.title, "Deploy done") + XCTAssertEqual(event?.message, "v2") + XCTAssertEqual(event?.source, .script) + XCTAssertEqual(event?.kind, .other) + XCTAssertEqual(event?.severity, .action) + XCTAssertEqual(event?.tag, "deploy") + XCTAssertEqual(event?.key, "deploy:1") + XCTAssertEqual(event?.url?.absoluteString, "https://example.com/d") + } + + func test_say_dropsANonWebLinkAndNeverMakesAnAgentEvent() { + let recorder = Recorder() + _ = run(router(recorder), #"{"cmd":"say","title":"x","url":"file:///etc/passwd"}"#) + XCTAssertNil(recorder.posted.first?.url) + XCTAssertTrue(recorder.posted.first?.isFeed ?? false) + } + + func test_say_rejectsBadInput() { + let recorder = Recorder() + let r = router(recorder) + XCTAssertEqual(run(r, #"{"cmd":"say"}"#)["ok"] as? Bool, false) + XCTAssertEqual(run(r, #"{"cmd":"say","title":"x","severity":"loud"}"#)["ok"] as? Bool, false) + XCTAssertEqual(run(r, #"{"cmd":"say","title":"x","source":"agent"}"#)["ok"] as? Bool, false) + XCTAssertTrue(recorder.posted.isEmpty) + } + + func test_focus_setsAndReadsState() { + let recorder = Recorder() + let r = router(recorder) + XCTAssertEqual(run(r, #"{"cmd":"focus","state":"on"}"#)["ok"] as? Bool, true) + XCTAssertEqual(recorder.focus, true) + XCTAssertEqual(run(r, #"{"cmd":"focus","state":"off"}"#)["focus"] as? Bool, false) + XCTAssertEqual(recorder.focus, false) + recorder.focus = nil + XCTAssertEqual(run(r, #"{"cmd":"focus"}"#)["ok"] as? Bool, true) + XCTAssertNil(recorder.focus, "status must not change the state") + XCTAssertEqual(run(r, #"{"cmd":"focus","state":"maybe"}"#)["ok"] as? Bool, false) + } + + func test_poll_saysNoPollerUntilOneIsWired() { + let recorder = Recorder() + let r = router(recorder) + XCTAssertEqual(run(r, #"{"cmd":"poll"}"#)["error"] as? String, "no poller") + recorder.poll = { $0(3) } + let reply = run(r, #"{"cmd":"poll"}"#) + XCTAssertEqual(reply["ok"] as? Bool, true) + XCTAssertEqual(reply["newEvents"] as? Int, 3) + } + + func test_state_storesTheOverrideWithItsExpiry() { + let recorder = Recorder() + let reply = run(router(recorder), #"{"cmd":"state","state":"sleeping","ttlSeconds":120}"#) + XCTAssertEqual(reply["ok"] as? Bool, true) + XCTAssertEqual(recorder.pose, PoseOverride(pose: "sleeping", expiresAt: now.addingTimeInterval(120))) + } + + func test_state_defaultsAndClampsTheTTL() { + let recorder = Recorder() + let r = router(recorder) + _ = run(r, #"{"cmd":"state","state":"alert"}"#) + XCTAssertEqual(recorder.pose?.expiresAt, now.addingTimeInterval(30)) + _ = run(r, #"{"cmd":"state","state":"alert","ttlSeconds":99999}"#) + XCTAssertEqual(recorder.pose?.expiresAt, now.addingTimeInterval(3600)) + _ = run(r, #"{"cmd":"state","state":"alert","ttlSeconds":0}"#) + XCTAssertEqual(recorder.pose?.expiresAt, now.addingTimeInterval(1)) + XCTAssertEqual(run(r, #"{"cmd":"state","state":"a b"}"#)["ok"] as? Bool, false) + XCTAssertEqual(run(r, #"{"cmd":"state"}"#)["ok"] as? Bool, false) + } + + func test_poseOverride_isActiveUntilItExpires() { + let pose = PoseOverride(pose: "alert", expiresAt: now.addingTimeInterval(10)) + XCTAssertTrue(pose.isActive(at: now)) + XCTAssertFalse(pose.isActive(at: now.addingTimeInterval(10))) + } + + func test_busy_reportsTheRegisteredSources() { + let recorder = Recorder() + let r = router(recorder) + XCTAssertEqual(run(r, #"{"cmd":"busy"}"#)["busy"] as? Bool, false) + recorder.busy = [BusyItem(kind: "session", target: "repo", since: nil)] + let reply = run(r, #"{"cmd":"busy"}"#) + XCTAssertEqual(reply["busy"] as? Bool, true) + let items = reply["items"] as? [[String: String]] + XCTAssertEqual(items?.first?["kind"], "session") + XCTAssertEqual(items?.first?["target"], "repo") + } + + func test_busySources_mergeAndSortProviders() { + let sources = BusySources() + sources.register("b") { [BusyItem(kind: "run", target: "z", since: nil)] } + sources.register("a") { [BusyItem(kind: "poll", target: "", since: nil)] } + XCTAssertEqual(sources.items().map(\.kind), ["poll", "run"]) + } + + func test_settings_opensACategoryAndRejectsAnUnknownOne() { + let recorder = Recorder() + let r = router(recorder) + let reply = run(r, #"{"cmd":"settings","category":"focus"}"#) + XCTAssertEqual(reply["current"] as? String, "focus") + XCTAssertEqual(recorder.settings, .some(.focus)) + XCTAssertTrue((reply["categories"] as? [String])?.contains("voice") ?? false) + _ = run(r, #"{"cmd":"settings"}"#) + XCTAssertEqual(recorder.settings, .some(nil)) + XCTAssertEqual(run(r, #"{"cmd":"settings","category":"nope"}"#)["ok"] as? Bool, false) + } + + // MARK: - Real socket + + private final class Box: @unchecked Sendable { + private let lock = NSLock() + private var stored: String? + private var finished = false + func finish(_ value: String?) { lock.lock(); stored = value; finished = true; lock.unlock() } + var isFinished: Bool { lock.lock(); defer { lock.unlock() }; return finished } + var value: String? { lock.lock(); defer { lock.unlock() }; return stored } + } + + // Runs `work` off the main thread while this one keeps servicing the main + // queue, which is where the listener hands commands to the router. + private func offMain(_ work: @escaping @Sendable () -> String?) -> String? { + let box = Box() + DispatchQueue.global().async { box.finish(work()) } + let deadline = Date().addingTimeInterval(10) + while !box.isFinished, Date() < deadline { + RunLoop.current.run(until: Date().addingTimeInterval(0.01)) + } + return box.value + } + + private nonisolated static func connect(_ path: String) -> Int32? { + let fd = socket(AF_UNIX, SOCK_STREAM, 0) + var addr = sockaddr_un() + addr.sun_family = sa_family_t(AF_UNIX) + let bytes = Array(path.utf8CString) + withUnsafeMutableBytes(of: &addr.sun_path) { $0.copyBytes(from: bytes.map { UInt8(bitPattern: $0) }) } + let status = withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Darwin.connect(fd, $0, socklen_t(MemoryLayout.size)) + } + } + guard status == 0 else { close(fd); return nil } + return fd + } + + // Next to this checkout's Tests directory; the no-Xcode runner stages the + // test files elsewhere, but runs from the repo root. + private static func cliScript() -> String { + let beside = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("stack-nudge.sh").path + if FileManager.default.fileExists(atPath: beside) { return beside } + return FileManager.default.currentDirectoryPath + "/stack-nudge.sh" + } + + private func startListener(_ recorder: Recorder) throws -> (EventListener, String, EventStore) { + let path = "/tmp/sn-\(UUID().uuidString.prefix(8)).sock" + let store = EventStore() + let listener = EventListener(store: store, socketPath: path, commands: router(recorder)) + try listener.start() + return (listener, path, store) + } + + func test_socket_answersACommandWithoutTheClientClosing() throws { + let (listener, path, _) = try startListener(Recorder()) + defer { listener.stop() } + let reply = offMain { + guard let fd = Self.connect(path) else { return nil } + defer { close(fd) } + let line = Array("{\"cmd\":\"ping\"}\n".utf8) + _ = write(fd, line, line.count) + var buf = [UInt8](repeating: 0, count: 256) + let n = read(fd, &buf, buf.count) + return n > 0 ? String(decoding: buf.prefix(n), as: UTF8.self) : nil + } + XCTAssertEqual(reply, "{\"ok\":true,\"pong\":true}\n") + } + + func test_socket_stillTakesAnEventThatClosesWithoutReading() throws { + let (listener, path, store) = try startListener(Recorder()) + defer { listener.stop() } + _ = offMain { + guard let fd = Self.connect(path) else { return nil } + let line = Array("{\"agent\":\"claude-code\",\"event\":\"stop\",\"title\":\"Done\",\"message\":\"ok\"}\n".utf8) + _ = write(fd, line, line.count) + close(fd) + return "sent" + } + let deadline = Date().addingTimeInterval(5) + while store.events.isEmpty, Date() < deadline { + RunLoop.current.run(until: Date().addingTimeInterval(0.01)) + } + XCTAssertEqual(store.events.first?.title, "Done") + } + + func test_cli_sendsCommandsThroughTheSocket() throws { + let recorder = Recorder() + let (listener, path, _) = try startListener(recorder) + defer { listener.stop() } + let script = Self.cliScript() + + let reply = offMain { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = [script, "say", "Deploy \"done\"", "--severity", "action", "--tag", "deploy"] + process.environment = ["STACKNUDGE_SOCK": path, "PATH": "/usr/bin:/bin"] + try? process.run() + process.waitUntilExit() + return String(process.terminationStatus) + } + XCTAssertEqual(reply, "0") + XCTAssertEqual(recorder.posted.first?.title, "Deploy \"done\"") + XCTAssertEqual(recorder.posted.first?.severity, .action) + XCTAssertEqual(recorder.posted.first?.tag, "deploy") + } + + func test_cli_exitsQuietlyForSayWhenThePanelIsDown() { + let script = Self.cliScript() + let status = offMain { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = [script, "focus", "on"] + process.environment = ["STACKNUDGE_SOCK": "/tmp/sn-missing.sock", "PATH": "/usr/bin:/bin"] + try? process.run() + process.waitUntilExit() + return String(process.terminationStatus) + } + XCTAssertEqual(status, "0") + } +} diff --git a/Tests/StackNudgePanelCoreTests/CompactGlanceTests.swift b/Tests/StackNudgePanelCoreTests/CompactGlanceTests.swift index 019b316..3d33706 100644 --- a/Tests/StackNudgePanelCoreTests/CompactGlanceTests.swift +++ b/Tests/StackNudgePanelCoreTests/CompactGlanceTests.swift @@ -38,7 +38,7 @@ final class CompactGlanceTests: XCTestCase { var exitedCompact = false nav.actions = SettingsActions( checkPermissions: {}, openConfig: {}, editPhrases: {}, - browseExtensions: {}, openExtensionSources: {}, openExtension: { _ in }, + browseExtensions: {}, openExtensionSources: {}, editNotifyTags: {}, openExtension: { _ in }, openReleaseNotes: {}, checkForUpdates: {}, beginUpdate: {}, runUpdate: {}, beginUninstall: {}, runUninstall: {}, runBootstrap: {}, quit: {}, expandFromCompact: { modeWhenExpanded = nav.mode }, diff --git a/Tests/StackNudgePanelCoreTests/FocusModeTests.swift b/Tests/StackNudgePanelCoreTests/FocusModeTests.swift new file mode 100644 index 0000000..96201fb --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/FocusModeTests.swift @@ -0,0 +1,138 @@ +import XCTest + +@testable import StackNudgePanelCore + +// Focus as a mute source and the per-tag "Notify me about" filter. The socket +// command that drives them is covered in CommandChannelTests. +@MainActor +final class FocusModeTests: XCTestCase { + + private func feed(_ tag: String?, source: EventSource = .github, title: String = "t") -> NudgeEvent { + .feed(source: source, tag: tag, title: title, message: "") + } + + private let agentEvent = NudgeEvent(agent: "claude-code", kind: .stop, title: "Done", message: "") + + // MARK: - Policy + + func test_policy_holdsEverythingWhileFocusedAndRespected() { + let policy = FocusPolicy(focused: true, respect: true, meetingsPass: false) + XCTAssertTrue(policy.holds(feed("review"))) + XCTAssertTrue(policy.holds(agentEvent)) + XCTAssertTrue(policy.holds(feed("calendar", source: .calendar))) + } + + func test_policy_holdsNothingWhenNotFocusedOrNotRespected() { + XCTAssertFalse(FocusPolicy(focused: false, respect: true, meetingsPass: false).holds(feed("ci"))) + XCTAssertFalse(FocusPolicy(focused: true, respect: false, meetingsPass: false).holds(feed("ci"))) + } + + func test_policy_meetingRemindersPassWhenAllowed() { + let meeting = feed("calendar", source: .calendar) + XCTAssertFalse(FocusPolicy(focused: true, respect: true, meetingsPass: true).holds(meeting)) + XCTAssertTrue(FocusPolicy(focused: true, respect: true, meetingsPass: true).holds(feed("review"))) + } + + // MARK: - Tracker + + func test_tracker_returnsWhatItHeldWhenFocusEnds() { + var focus = FocusTracker() + XCTAssertTrue(focus.set(true).isEmpty) + focus.hold(feed("review", title: "a")) + focus.hold(feed("ci", title: "b")) + XCTAssertEqual(focus.held.count, 2) + XCTAssertEqual(focus.set(false).map(\.title), ["a", "b"]) + XCTAssertTrue(focus.held.isEmpty) + XCTAssertFalse(focus.active) + } + + func test_tracker_repeatingTheCurrentStateIsANoOp() { + var focus = FocusTracker() + _ = focus.set(true) + focus.hold(feed("review")) + XCTAssertTrue(focus.set(true).isEmpty) + XCTAssertEqual(focus.held.count, 1, "a repeated on must not drop what was held") + XCTAssertTrue(focus.set(false).count == 1) + XCTAssertTrue(focus.set(false).isEmpty) + } + + func test_tracker_remembersWhenItLastChanged() { + var focus = FocusTracker() + XCTAssertNil(focus.lastChange) + let at = Date(timeIntervalSince1970: 1_800_000_000) + _ = focus.set(true, now: at) + XCTAssertEqual(focus.lastChange, at) + } + + // MARK: - Digest + + func test_digest_nothingHeldIsNoNotice() { + XCTAssertNil(FocusDigest.text(for: [])) + } + + func test_digest_oneEventKeepsItsTitle() { + XCTAssertEqual(FocusDigest.text(for: [feed("review", title: "PR #1 approved")]), + "While Focus was on: PR #1 approved") + } + + func test_digest_countsByTagMostFirst() { + let held = [feed("review"), feed("ci"), feed("review"), feed("review")] + XCTAssertEqual(FocusDigest.text(for: held), "While Focus was on: 3 review, 1 CI") + } + + func test_digest_untaggedEventsCountUnderTheirSource() { + let held = [agentEvent, agentEvent, feed(nil, source: .script)] + XCTAssertEqual(FocusDigest.text(for: held), "While Focus was on: 2 agent, 1 script") + } + + // MARK: - Quiet tags + + func test_quietTags_roundTripThroughTheConfigValue() { + let tags: Set = ["ci", "review-request"] + XCTAssertEqual(QuietTags.serialize(tags), "ci,review-request") + XCTAssertEqual(QuietTags.parse("ci, review-request,,"), tags) + XCTAssertEqual(QuietTags.parse(nil), []) + } + + func test_quietTags_onlyAMatchingTagIsQuiet() { + let quiet: Set = ["ci"] + XCTAssertTrue(QuietTags.isQuiet(feed("ci"), in: quiet)) + XCTAssertFalse(QuietTags.isQuiet(feed("review"), in: quiet)) + XCTAssertFalse(QuietTags.isQuiet(feed(nil), in: quiet)) + XCTAssertFalse(QuietTags.isQuiet(agentEvent, in: quiet)) + } + + func test_quietTags_knownListKeepsBuiltinsThenSeenThenOff() { + let known = QuietTags.known(seen: ["zeta", "ci"], quiet: ["alpha", "ci"]) + XCTAssertEqual(Array(known.prefix(QuietTags.builtin.count)), QuietTags.builtin) + XCTAssertEqual(Array(known.dropFirst(QuietTags.builtin.count)), ["zeta", "alpha"]) + } + + // MARK: - Nav + + func test_interrupts_isFalseForAQuietTagAndForAFocusHeldEvent() { + let nav = PanelNav() + XCTAssertTrue(nav.interrupts(feed("ci"))) + nav.quietTags = ["ci"] + XCTAssertFalse(nav.interrupts(feed("ci"))) + XCTAssertTrue(nav.interrupts(feed("review"))) + _ = nav.focus.set(true) + XCTAssertFalse(nav.interrupts(feed("review"))) + nav.respectFocus = false + XCTAssertTrue(nav.interrupts(feed("review"))) + } + + func test_focusRowsAreInTheirOwnCategory() { + let nav = PanelNav() + XCTAssertEqual(nav.rows(in: .focus), [.respectFocus, .focusMeetings]) + XCTAssertTrue(nav.rows(in: .notifications).contains(.notifyTagsPage)) + } + + func test_notifyTagSelectionClampsToTheList() { + let nav = PanelNav() + nav.moveNotifyTagSelection(by: -1) + XCTAssertEqual(nav.notifyTagSelection, 0) + nav.moveNotifyTagSelection(by: 1000) + XCTAssertEqual(nav.notifyTagSelection, nav.notifyTagList.count - 1) + } +} diff --git a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift index 21486f7..17bb74d 100644 --- a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift +++ b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift @@ -196,7 +196,8 @@ final class SettingsCategoryTests: XCTestCase { ) -> SettingsActions { SettingsActions( checkPermissions: checkPermissions, openConfig: {}, editPhrases: {}, - browseExtensions: {}, openExtensionSources: openExtensionSources, openExtension: openExtension, + browseExtensions: {}, openExtensionSources: openExtensionSources, editNotifyTags: {}, + openExtension: openExtension, openReleaseNotes: {}, checkForUpdates: {}, beginUpdate: {}, runUpdate: {}, beginUninstall: {}, runUninstall: {}, runBootstrap: {}, quit: {}, expandFromCompact: {}, exitCompactMode: {}, diff --git a/Tests/StackNudgePanelCoreTests/SettingsRowTests.swift b/Tests/StackNudgePanelCoreTests/SettingsRowTests.swift index c2cdb22..c52db15 100644 --- a/Tests/StackNudgePanelCoreTests/SettingsRowTests.swift +++ b/Tests/StackNudgePanelCoreTests/SettingsRowTests.swift @@ -74,7 +74,7 @@ final class SettingsRowTests: XCTestCase { var browsed = 0 nav.actions = SettingsActions( checkPermissions: {}, openConfig: {}, editPhrases: {}, - browseExtensions: { browsed += 1 }, openExtensionSources: {}, openExtension: { _ in }, + browseExtensions: { browsed += 1 }, openExtensionSources: {}, editNotifyTags: {}, openExtension: { _ in }, openReleaseNotes: {}, checkForUpdates: {}, beginUpdate: {}, runUpdate: {}, beginUninstall: {}, runUninstall: {}, runBootstrap: {}, quit: {}, expandFromCompact: {}, exitCompactMode: {}, @@ -165,7 +165,7 @@ final class SettingsRowTests: XCTestCase { var resets = 0 nav.actions = SettingsActions( checkPermissions: {}, openConfig: {}, editPhrases: {}, - browseExtensions: {}, openExtensionSources: {}, openExtension: { _ in }, + browseExtensions: {}, openExtensionSources: {}, editNotifyTags: {}, openExtension: { _ in }, openReleaseNotes: {}, checkForUpdates: {}, beginUpdate: {}, runUpdate: {}, beginUninstall: {}, runUninstall: {}, runBootstrap: {}, quit: {}, expandFromCompact: {}, exitCompactMode: {}, @@ -283,7 +283,7 @@ final class SettingsRowTests: XCTestCase { var mutes: [Int] = [] nav.actions = SettingsActions( checkPermissions: {}, openConfig: {}, editPhrases: {}, - browseExtensions: {}, openExtensionSources: {}, openExtension: { _ in }, + browseExtensions: {}, openExtensionSources: {}, editNotifyTags: {}, openExtension: { _ in }, openReleaseNotes: {}, checkForUpdates: {}, beginUpdate: {}, runUpdate: {}, beginUninstall: {}, runUninstall: {}, runBootstrap: {}, quit: {}, expandFromCompact: {}, exitCompactMode: {}, diff --git a/build.sh b/build.sh index 80623ea..35b397d 100755 --- a/build.sh +++ b/build.sh @@ -37,6 +37,8 @@ build_app() { repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cp "$repo_root/notify.sh" "$contents/Resources/notify.sh" chmod +x "$contents/Resources/notify.sh" + cp "$repo_root/stack-nudge.sh" "$contents/Resources/stack-nudge" + chmod +x "$contents/Resources/stack-nudge" # The hooks this version wants per agent; reconciled on every launch. cp "$repo_root/hook-manifest.json" "$contents/Resources/hook-manifest.json" if [[ -d "$repo_root/phrases" ]]; then diff --git a/docs/notifications.md b/docs/notifications.md index 4ddaed5..c9484c3 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -71,6 +71,49 @@ Each source keeps its own 20 most recent events, so a busy feed can't push a per Records live in `~/.stack-nudge/events.jsonl` (mode 0600), one JSON object per line, holding timestamp, agent, kind, title, message, repo path, and session id — the descriptive fields only, never the FIFO paths or PIDs. They're kept for 30 days or 10,000 records, whichever binds first, trimmed once per launch. **The log contains prompt and tool text**, so if that isn't something you want on disk, turn it off in Settings → **Event history** (`STACKNUDGE_EVENT_HISTORY=false`); Settings → **Clear event history** deletes the file outright. Nothing is ever sent anywhere — this is a local file, same as the rest of `~/.stack-nudge`. +## Command line (macOS) + +`~/.stack-nudge/stack-nudge` talks to the running panel over the same Unix socket `notify.sh` posts events to (`~/.stack-nudge/panel.sock`, mode 0600, so only your user can reach it). The app installs it on first launch and refreshes it on every launch. Put it on your `PATH` if you like: `ln -s ~/.stack-nudge/stack-nudge ~/.local/bin/stack-nudge`. + +```sh +stack-nudge say "Deploy done" --url https://example.com/deploys/42 --severity info +stack-nudge focus on|off|status +stack-nudge state --ttl 30 +stack-nudge settings [category] +stack-nudge poll +stack-nudge busy +stack-nudge ping +``` + +| Command | What it does | +|---------|--------------| +| `say "title"` | Posts an event from a script: `--body`, `--url` (http or https only), `--severity info\|action\|alert`, `--source github\|calendar\|script` (default `script`), `--tag`, `--key` (a later event with the same key replaces the earlier one). | +| `focus on\|off\|status` | Sets or reads the macOS Focus state (see below). | +| `state --ttl ` | Asks the companion to hold a pose for a while (default 30, 1 to 3600). The panel stores the override and its expiry; the companion decides what the pose looks like. | +| `settings [category]` | Opens the panel on Settings, on that category when given (`notifications`, `focus`, `voice`, `appearance`, `companion`, `usage`, `integrations`, `extensions`, `panel`, `events`, `actions`, `about`). | +| `poll` | Polls the feeds now. Replies `no poller` when none is set up. | +| `busy` | Whether an agent session or other work is in flight, so a script can wait before restarting the app. | +| `ping` | `{"ok":true,"pong":true}` when the panel is up. | + +`say`, `state` and `focus on|off` exit 0 without output when the panel is not running, so a script or automation never fails for that. Anything else prints a short message and exits 1. + +## Focus and Do Not Disturb (macOS) + +While a macOS Focus is on, the panel holds back banners, sounds and voice. Events still land in the list and the counts still update. Meeting reminders still show unless you turn that off (Settings > Focus). When the Focus ends, one notice such as `While Focus was on: 3 review, 1 CI` replaces the held banners. The menu shows `☾ Focus on` and a moon after the menu-bar icon, and the compact widget shows a small moon. The timed mute wins over Focus: a muted panel stays muted. + +macOS gives an app no way to read the Focus state, so a Shortcuts automation tells the panel. Once: + +1. Open Shortcuts, then the Automation tab, then the + button, then New Automation. +2. Choose Do Not Disturb (or the Focus you use; repeat for each one). Pick "Is Turned On", Run Immediately, Next. +3. Add the Run Shell Script action with `~/.stack-nudge/stack-nudge focus on`, then Done. +4. Repeat for "Is Turned Off" with `~/.stack-nudge/stack-nudge focus off`. + +Check with `~/.stack-nudge/stack-nudge focus status`. Settings > Focus has **Respect Focus / Do Not Disturb** (`STACKNUDGE_RESPECT_FOCUS`, default on) and **Meetings still show** (`STACKNUDGE_FOCUS_MEETINGS`, default on). The state lives in memory only: if you quit the panel during a Focus it starts as off until the next switch, so a missed "off" cannot hold banners for good. + +## Notify me about + +Settings > Notifications > **Notify me about…** lists the feed tags (`review`, `ci`, `deploy`, and any other tag a feed or `stack-nudge say --tag` has used since launch) with a toggle each. A tag turned off still lists its events in the Events tab, but they pop no banner, play no sound or voice and do not move the companion. The off tags are stored as `STACKNUDGE_QUIET_TAGS`, comma-separated (for example `ci,review-request`). + ## Permission prompts **Answering elsewhere clears the prompt.** A permission prompt is tracked by two things: the FIFO notify.sh creates for your decision, and the hook process waiting to read it. Both are required. The FIFO alone isn't proof — its cleanup is skipped entirely on `SIGKILL`, which is what the agent does to the hook when you answer in its own UI. (It was also skipped on a clean exit until recently — the trap referenced a variable that had gone out of scope by the time it fired — so answered and timed-out prompts leaked their FIFO directory until the half-hourly sweep collected it.) So approving a plan in the terminal used to leave the panel convinced the prompt was still blocking, keeping it in the menu-bar count and re-nudging you (and Slack) for the full 550 seconds. Now a prompt whose hook has gone is retired within a tick, because there's nobody left to read a decision. diff --git a/docs/panel.md b/docs/panel.md index 510fea9..e18cfe2 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -151,7 +151,8 @@ Reachable from the tab strip, `Cmd+,`, or the last `Cmd`-number. A sidebar of ca | Category | Rows | |----------|------| -| **Notifications** | Banner notifications, Mute when focused, Mute / Resume notifications, Mute duration, Remind unanswered, Flag stalled after, Sound enabled, and the Agent done / Permission sounds (preview as you cycle) | +| **Notifications** | Banner notifications, Mute when focused, Mute / Resume notifications, Mute duration, Remind unanswered, Flag stalled after, Sound enabled, and the Agent done / Permission sounds (preview as you cycle), and **Notify me about…**, a page of per-tag toggles (see [notifications.md](notifications.md#notify-me-about)) | +| **Focus** | Respect Focus / Do Not Disturb, Meetings still show (see [notifications.md](notifications.md#focus-and-do-not-disturb-macos)) | | **Voice** | Voice notifications, the read-aloud shortcut, then Voice and Speed (preview as you cycle) once the voice model is downloaded, or **Download voice model** until it is | | **Appearance** | Floating widget (`Pill`, `Companion` or `Off`), then the pill's own rows: Snap to corners, Widget corner, Widget opacity, Widget type, Mascot, Accent color | | **Companion** | Size, Count badge, Preview pose, Reset position; **Turn on companion** while it's off. See [Companion](#companion) | @@ -299,6 +300,7 @@ When the panel daemon is running, the StackNudge mark appears in your menu bar, | `Settings…` (⌘,) | Opens the panel straight on Settings | | `Check permissions…` | Opens the Permissions page in the panel (see [Permissions](setup.md#permissions-macos)) | | `Open config file…` | Opens `~/.stack-nudge/config` in your default editor | +| `☾ Focus on · …` | Appears only while a macOS Focus is on and tells you banners are held (info only). | | `Quit StackNudge panel` (⌘Q) | Exits the daemon | Menu changes take effect immediately for the next nudge — no daemon restart needed. diff --git a/install.sh b/install.sh index 4eed1ee..e237674 100755 --- a/install.sh +++ b/install.sh @@ -233,6 +233,11 @@ chmod +x "$INSTALL_DIR/.notify.sh.new" mv -f "$INSTALL_DIR/.notify.sh.new" "$INSTALL_DIR/notify.sh" echo " Installed notify.sh -> $INSTALL_DIR/notify.sh" +cp "$SCRIPT_DIR/stack-nudge.sh" "$INSTALL_DIR/.stack-nudge.new" +chmod +x "$INSTALL_DIR/.stack-nudge.new" +mv -f "$INSTALL_DIR/.stack-nudge.new" "$INSTALL_DIR/stack-nudge" +echo " Installed stack-nudge -> $INSTALL_DIR/stack-nudge" + # jq is optional: the socket payload is parsed by python3, but the permission # banner's "what needs approval" detail still reads the hook JSON with jq. if ! command -v jq >/dev/null 2>&1; then diff --git a/notify.conf.example b/notify.conf.example index ac126db..59d624f 100644 --- a/notify.conf.example +++ b/notify.conf.example @@ -51,6 +51,23 @@ # Default: 30 #STACKNUDGE_MUTE_DURATION_MIN=30 +# Hold banners, sound and voice while a macOS Focus is on. The Focus state is +# pushed in by a Shortcuts automation running `~/.stack-nudge/stack-nudge focus +# on|off` (see the README). Set to false to ignore it. +# Default: true +#STACKNUDGE_RESPECT_FOCUS=false + +# Let meeting reminders through while a Focus is on. Only applies when +# STACKNUDGE_RESPECT_FOCUS is true. +# Default: true +#STACKNUDGE_FOCUS_MEETINGS=false + +# Feed tags that still list their events but pop no banner, sound or voice and +# do not move the companion. Comma-separated; also set from Settings > +# Notifications > Notify me about. +# Default: none +#STACKNUDGE_QUIET_TAGS=ci,review-request + # Pill widget accent color preset. Also settable from Settings → Widget → # "Accent color". Allowed: cyan, violet, mint, rose, system (system follows # the macOS accent and matches the banner color). diff --git a/panel/Bootstrap.swift b/panel/Bootstrap.swift index 529e05b..7917c52 100644 --- a/panel/Bootstrap.swift +++ b/panel/Bootstrap.swift @@ -75,6 +75,8 @@ enum Bootstrap { static let installDir = "\(NSHomeDirectory())/.stack-nudge" static let notifyPath = "\(NSHomeDirectory())/.stack-nudge/notify.sh" + // The command-line client: ~/.stack-nudge/stack-nudge say|focus|poll|... + static let cliPath = "\(NSHomeDirectory())/.stack-nudge/stack-nudge" static let venvSymlinkPath = "\(NSHomeDirectory())/.stack-nudge/venv" static let configPath = "\(NSHomeDirectory())/.stack-nudge/config" static let phrasesDir = "\(NSHomeDirectory())/.stack-nudge/phrases" @@ -191,6 +193,32 @@ enum Bootstrap { } } + // The `stack-nudge` CLI this bundle ships, nil on a build that didn't bundle it. + static func bundledCLIScript() -> String? { + guard let url = Bundle.main.url(forResource: "stack-nudge", withExtension: nil) + else { return nil } + return try? String(contentsOf: url, encoding: .utf8) + } + + // Keep the installed CLI equal to the bundled one. Unlike notify.sh it carries + // no hook-trust hash and no version stamp, so a plain content compare is the + // whole rule. Skips a machine with no install directory, like the refresh above. + @discardableResult + static func installCLI(bundled script: String?, at path: String = cliPath) -> Bool { + guard let script, + FileManager.default.fileExists( + atPath: (path as NSString).deletingLastPathComponent), + (try? String(contentsOfFile: path, encoding: .utf8)) != script + else { return false } + do { + try writeNotifyScript(script, to: path) + return true + } catch { + log("failed to install the stack-nudge CLI: \(error.localizedDescription)") + return false + } + } + // Whether the refresh above would actually rewrite the installed script. // Two gates: the stamp must differ (a matching stamp means "same protocol, // leave local tweaks alone"), AND the logic must have genuinely changed. The @@ -689,6 +717,12 @@ enum Bootstrap { else { throw BootstrapError.bundleResourceMissing("notify.sh") } try writeNotifyScript(notifyScript) + progress("Copying the stack-nudge CLI…") + guard let cliScript = bundledCLIScript() else { + throw BootstrapError.bundleResourceMissing("stack-nudge") + } + try writeNotifyScript(cliScript, to: cliPath) + progress("Copying phrase pools…") // Wipe then recopy so reinstalls pick up new phrases. try? fm.removeItem(atPath: phrasesDir) diff --git a/panel/CommandChannel.swift b/panel/CommandChannel.swift new file mode 100644 index 0000000..241491f --- /dev/null +++ b/panel/CommandChannel.swift @@ -0,0 +1,188 @@ +import Foundation + +// The request/reply form of the panel socket. A connection that sends one JSON +// line carrying a "cmd" key is a command; the reply is one JSON line and then +// the panel closes. Anything without "cmd" is an agent or feed event, exactly as +// before (no agent event has a "cmd" field), so notify.sh and extensions are +// untouched. The socket is chmod 0600 inside ~/.stack-nudge, so only the local +// user reaches it; commands add no new trust. + +// A pose the companion should hold until `expiresAt`, set by the `state` +// command. The panel only stores it; the companion reads `PanelNav.poseOverride` +// (or sets `onPoseOverride`) and ignores it once `isActive` is false. +struct PoseOverride: Equatable { + let pose: String + let expiresAt: Date + + static let defaultTTL: TimeInterval = 30 + static let ttlRange: ClosedRange = 1...3600 + + func isActive(at now: Date = Date()) -> Bool { expiresAt > now } +} + +struct BusyItem: Equatable { + let kind: String + let target: String + let since: Date? +} + +// What is in flight, for deciding whether a relaunch would cut work off. Each +// subsystem registers its own provider by name (agent sessions here, AI runs and +// the poller on the branches that add them), so none edits another's list. +final class BusySources { + private var providers: [String: () -> [BusyItem]] = [:] + + func register(_ name: String, _ provider: @escaping () -> [BusyItem]) { + providers[name] = provider + } + + func items() -> [BusyItem] { + providers.values.flatMap { $0() }.sorted { ($0.kind, $0.target) < ($1.kind, $1.target) } + } +} + +struct CommandHooks { + var post: (NudgeEvent) -> Void = { _ in } + var setFocus: (Bool) -> Void = { _ in } + var focusStatus: () -> [String: Any] = { [:] } + // Resolved per request, and nil until the GitHub branch wires a poller. The + // closure it returns gets how many new events the poll found. + var poll: () -> ((@escaping (Int) -> Void) -> Void)? = { nil } + var setPose: (PoseOverride) -> Void = { _ in } + var busy: () -> [BusyItem] = { [] } + // Opens the panel on Settings, on `category` when given, and returns the + // category it is showing. + var openSettings: (SettingsCategory?) -> SettingsCategory = { $0 ?? .notifications } + var now: () -> Date = { Date() } +} + +final class CommandRouter { + private let hooks: CommandHooks + + init(hooks: CommandHooks) { self.hooks = hooks } + + // Whether a wire line is a command rather than an event. + static func isCommand(_ line: Data) -> Bool { + guard let object = try? JSONSerialization.jsonObject(with: line) as? [String: Any] + else { return false } + return object["cmd"] is String + } + + // Runs on the main thread. `reply` gets the one reply line (no newline), and + // may be called later than this returns, from any thread. + func handle(_ line: Data, reply: @escaping (String) -> Void) { + guard let request = try? JSONSerialization.jsonObject(with: line) as? [String: Any], + let cmd = request["cmd"] as? String + else { return reply(Self.encode(Self.failure("bad request"))) } + + switch cmd { + case "ping": + reply(Self.encode(["ok": true, "pong": true])) + case "say": + reply(Self.encode(say(request))) + case "focus": + reply(Self.encode(focus(request))) + case "poll": + guard let poll = hooks.poll() else { return reply(Self.encode(Self.failure("no poller"))) } + poll { reply(Self.encode(["ok": true, "newEvents": $0])) } + case "state": + reply(Self.encode(state(request))) + case "busy": + reply(Self.encode(busy())) + case "settings": + reply(Self.encode(settings(request))) + default: + reply(Self.encode(Self.failure("unknown command \(cmd)"))) + } + } + + static func failure(_ message: String) -> [String: Any] { + ["ok": false, "error": message] + } + + static func encode(_ reply: [String: Any]) -> String { + guard let data = try? JSONSerialization.data(withJSONObject: reply, options: [.sortedKeys]), + let text = String(data: data, encoding: .utf8) + else { return #"{"error":"unencodable reply","ok":false}"# } + return text + } + + // MARK: - Commands + + private static let sayFeedSources: Set = ["github", "calendar", "script"] + + // Built as the wire event a script would post and decoded through the same + // DTO, so the URL scheme check and the rule that a feed is never an agent + // are the socket's own, not a second copy. + private func say(_ request: [String: Any]) -> [String: Any] { + let title = (request["title"] as? String) ?? "" + guard !title.isEmpty else { return Self.failure("say needs a title") } + + let source = (request["source"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? "script" + guard Self.sayFeedSources.contains(source) else { + return Self.failure("unknown source \(source)") + } + let severity = (request["severity"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? "info" + guard EventSeverity(rawValue: severity) != nil else { + return Self.failure("severity must be info, action or alert") + } + + var wire: [String: Any] = [ + "agent": "script", "event": "other", "title": title, + "message": (request["body"] as? String) ?? "", + "source": source, "severity": severity, + "timestamp": hooks.now().timeIntervalSince1970, + ] + for field in ["url", "tag", "key"] { + if let value = request[field] as? String, !value.isEmpty { wire[field] = value } + } + guard let data = try? JSONSerialization.data(withJSONObject: wire), + let event = EventListener.parseEvents(data).first + else { return Self.failure("could not build the event") } + hooks.post(event) + return ["ok": true] + } + + private func focus(_ request: [String: Any]) -> [String: Any] { + switch (request["state"] as? String) ?? "status" { + case "on": hooks.setFocus(true) + case "off": hooks.setFocus(false) + case "status": break + default: return Self.failure("focus state must be on, off or status") + } + var reply = hooks.focusStatus() + reply["ok"] = true + return reply + } + + private func state(_ request: [String: Any]) -> [String: Any] { + let pose = (request["state"] as? String) ?? "" + guard !pose.isEmpty, pose.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" }) + else { return Self.failure("state needs a pose name") } + let raw = (request["ttlSeconds"] as? Double) ?? PoseOverride.defaultTTL + let ttl = min(max(raw, PoseOverride.ttlRange.lowerBound), PoseOverride.ttlRange.upperBound) + hooks.setPose(PoseOverride(pose: pose, expiresAt: hooks.now().addingTimeInterval(ttl))) + return ["ok": true, "state": pose, "ttlSeconds": ttl] + } + + private func busy() -> [String: Any] { + let items = hooks.busy() + let iso = ISO8601DateFormatter() + return ["ok": true, "busy": !items.isEmpty, + "items": items.map { ["kind": $0.kind, "target": $0.target, + "since": $0.since.map(iso.string(from:)) ?? ""] }] + } + + private func settings(_ request: [String: Any]) -> [String: Any] { + var category: SettingsCategory? + if let name = request["category"] as? String, !name.isEmpty { + guard let found = SettingsCategory(key: name) else { + return Self.failure("unknown category \(name)") + } + category = found + } + let shown = hooks.openSettings(category) + return ["ok": true, "current": shown.key, + "categories": SettingsCategory.allCases.map(\.key)] + } +} diff --git a/panel/CompactView.swift b/panel/CompactView.swift index a73ca5d..6ebbf30 100644 --- a/panel/CompactView.swift +++ b/panel/CompactView.swift @@ -361,7 +361,7 @@ struct CompactView: View { } // Passive muted signal on the pill — a dimmed bell.slash while a timed - // mute is active, nothing otherwise. Reads nav.muteTick so it clears the + // mute is active, a dimmed moon while Focus holds banners, nothing otherwise. Reads nav.muteTick so it clears the // instant the mute lifts (the controller's timer bumps it). @ViewBuilder private var muteIndicator: some View { let _ = nav.muteTick @@ -371,6 +371,12 @@ struct CompactView: View { .foregroundStyle(.secondary) .help("Notifications muted") } + if nav.focusHolding { + Image(systemName: "moon.fill") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.secondary) + .help("Focus is on: banners held") + } } private var separator: some View { diff --git a/panel/EventListener.swift b/panel/EventListener.swift index f7b1e40..b62860e 100644 --- a/panel/EventListener.swift +++ b/panel/EventListener.swift @@ -3,6 +3,10 @@ import Foundation // Unix-domain socket server. notify.sh writes one JSON object per connection // (newline-terminated). The wire shape mirrors the existing CLI args to // stack-nudge.app — same fields, just JSON-serialised. +// +// A line with a "cmd" key is a command instead (CommandChannel.swift): the +// panel answers it with one JSON line as soon as that first line is complete, +// without waiting for the client to close. final class EventListener { // 64 KiB is two orders of magnitude above the largest realistic nudge @@ -12,6 +16,7 @@ final class EventListener { private let store: EventStore private let socketPath: String + private let commands: CommandRouter? private var serverFD: Int32 = -1 private let queue = DispatchQueue(label: "stack-nudge.panel.listener") private let decoder = JSONDecoder() @@ -21,9 +26,10 @@ final class EventListener { // bundle's shutdown otherwise removes the new bundle's socket file. private var boundInode: ino_t? - init(store: EventStore, socketPath: String) { + init(store: EventStore, socketPath: String, commands: CommandRouter? = nil) { self.store = store self.socketPath = socketPath + self.commands = commands } func start() throws { @@ -101,16 +107,23 @@ final class EventListener { } private func handleClient(_ fd: Int32) { - defer { close(fd) } var buffer = Data() let chunkSize = 4096 var chunk = [UInt8](repeating: 0, count: chunkSize) + var firstLineChecked = false while true { let n = read(fd, &chunk, chunkSize) if n <= 0 { break } buffer.append(chunk, count: n) - if buffer.count > Self.maxPayloadBytes { return } + if buffer.count > Self.maxPayloadBytes { close(fd); return } + if !firstLineChecked, buffer.contains(0x0A) { + firstLineChecked = true + if let line = Self.commandLine(in: buffer) { return serveCommand(fd, line) } + } } + // A command whose client closed before sending a newline. + if !firstLineChecked, let line = Self.commandLine(in: buffer) { return serveCommand(fd, line) } + close(fd) guard !buffer.isEmpty else { return } for event in Self.parseEvents(buffer) { @@ -130,6 +143,32 @@ final class EventListener { } } + // The buffer's first line when it is a command, else nil. + static func commandLine(in buffer: Data) -> Data? { + let line = Data(buffer.prefix { $0 != 0x0A }) + return CommandRouter.isCommand(line) ? line : nil + } + + // Takes ownership of `fd`: it is closed once the reply is written. + private func serveCommand(_ fd: Int32, _ line: Data) { + var one: Int32 = 1 + setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, socklen_t(MemoryLayout.size)) + let finish: (String) -> Void = { reply in + let out = Array((reply + "\n").utf8) + var sent = 0 + while sent < out.count { + let n = out.withUnsafeBytes { write(fd, $0.baseAddress! + sent, out.count - sent) } + if n <= 0 { break } + sent += n + } + close(fd) + } + guard let commands else { + return finish(CommandRouter.encode(CommandRouter.failure("commands unavailable"))) + } + DispatchQueue.main.async { commands.handle(line, reply: finish) } + } + // Pure parser: newline-split the wire buffer and decode each non-empty // line as a NudgeEvent. Malformed lines are silently skipped (drop the // bad line, keep the rest) — handleClient already enforced the payload diff --git a/panel/FocusMode.swift b/panel/FocusMode.swift new file mode 100644 index 0000000..7a32010 --- /dev/null +++ b/panel/FocusMode.swift @@ -0,0 +1,100 @@ +import Foundation + +// macOS Focus (Do Not Disturb included) as an automatic mute source, separate +// from the timed mute: events still land in the list and the badges still count, +// only the banner, sound and voice are held. macOS gives an app no public way to +// read Focus, so a Shortcuts automation pushes the state in through the +// `focus on|off` socket command. +struct FocusPolicy: Equatable { + var focused: Bool + var respect: Bool + var meetingsPass: Bool + + func holds(_ event: NudgeEvent) -> Bool { + focused && respect && !(meetingsPass && Self.isMeetingReminder(event)) + } + + // The one place that decides what a meeting reminder is, so the calendar + // feed can be matched here without touching the policy. + static func isMeetingReminder(_ event: NudgeEvent) -> Bool { + event.source == .calendar + } +} + +// The pushed state plus what it held back. In memory only: a missed "off" must +// not hold banners for good, so a relaunch during a Focus starts as off. +struct FocusTracker: Equatable { + private(set) var active = false + private(set) var held: [NudgeEvent] = [] + private(set) var lastChange: Date? + + mutating func hold(_ event: NudgeEvent) { + held.append(event) + } + + // Returns what the Focus held when it just ended, else nothing. Repeating + // the state it is already in is a no-op, because a Shortcuts automation can + // fire twice. + mutating func set(_ on: Bool, now: Date = Date()) -> [NudgeEvent] { + guard on != active else { return [] } + active = on + lastChange = now + guard !on else { return [] } + defer { held = [] } + return held + } +} + +enum FocusDigest { + // The one notice shown when Focus ends, in place of replaying every held + // banner. A single event keeps its own title. + static func text(for events: [NudgeEvent]) -> String? { + guard let first = events.first else { return nil } + let prefix = "While Focus was on: " + if events.count == 1 { return prefix + first.title } + let byLabel = Dictionary(grouping: events, by: label(for:)).sorted { + $0.value.count != $1.value.count ? $0.value.count > $1.value.count : $0.key < $1.key + } + return prefix + byLabel.map { "\($0.value.count) \($0.key)" }.joined(separator: ", ") + } + + private static func label(for event: NudgeEvent) -> String { + guard let tag = event.tag, !tag.isEmpty else { + return event.source == .agent ? "agent" : event.source.label.lowercased() + } + return tag == "ci" ? "CI" : tag + } +} + +// Per-tag "Notify me about". A tag listed here still lists its events, but they +// do not pop a banner or change the companion pose. Stored comma-separated as +// STACKNUDGE_QUIET_TAGS. +enum QuietTags { + static let configKey = "STACKNUDGE_QUIET_TAGS" + + // The tags the shipped feeds use; the page also lists any other tag seen + // since launch and any already turned off. + static let builtin = ["review", "review-request", "ci", "ready", "deploy", + "pipeline", "calendar", "plan", "audit"] + + static func parse(_ raw: String?) -> Set { + Set((raw ?? "").split(separator: ",") + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty }) + } + + static func serialize(_ tags: Set) -> String { + tags.sorted().joined(separator: ",") + } + + static func isQuiet(_ event: NudgeEvent, in quiet: Set) -> Bool { + guard let tag = event.tag, !tag.isEmpty else { return false } + return quiet.contains(tag) + } + + static func known(seen: [String], quiet: Set) -> [String] { + var all = builtin + for tag in seen.sorted() + quiet.sorted() where !all.contains(tag) { all.append(tag) } + return all + } +} diff --git a/panel/MenuBar.swift b/panel/MenuBar.swift index 4beacd1..7c8895a 100644 --- a/panel/MenuBar.swift +++ b/panel/MenuBar.swift @@ -309,6 +309,7 @@ final class MenuBarController: NSObject, NSMenuDelegate { menu.addItem(.separator()) addMuteSection(to: menu) + addFocusSection(to: menu) menu.addItem(.separator()) if let nav = panelController?.nav, nav.companionEnabled { @@ -366,6 +367,17 @@ final class MenuBarController: NSObject, NSMenuDelegate { } } + // Shown only while a Focus is on, so the menu explains why banners stopped. + private func addFocusSection(to menu: NSMenu) { + guard let nav = panelController?.nav, nav.focus.active else { return } + let title = nav.respectFocus + ? "☾ Focus on · banners held (\(nav.focus.held.count))" + : "☾ Focus on · not holding banners" + let info = NSMenuItem(title: title, action: nil, keyEquivalent: "") + info.isEnabled = false + menu.addItem(info) + } + private func muteDurationLabel(_ minutes: Int) -> String { minutes % 60 == 0 ? "\(minutes / 60)h" : "\(minutes)m" } @@ -375,7 +387,7 @@ final class MenuBarController: NSObject, NSMenuDelegate { // permission prompts still blocking an agent rides alongside either way — // that count is the only trace left once a banner has expired into // Notification Center, so it must survive a mute. - func refreshStatusBadge(muteUntil: Date?, pendingPrompts: Int) { + func refreshStatusBadge(muteUntil: Date?, pendingPrompts: Int, focusHolding: Bool = false) { guard let button = statusItem.button else { return } let muted = muteUntil.map { $0 > Date() } ?? false var parts: [String] = [] @@ -393,6 +405,7 @@ final class MenuBarController: NSObject, NSMenuDelegate { if pendingPrompts > 0 { parts.append("\(pendingPrompts)⏳") } + if focusHolding { parts.append("☾") } button.imagePosition = .imageLeft button.title = parts.isEmpty ? "" : " " + parts.joined(separator: " ") button.toolTip = pendingPrompts > 0 diff --git a/panel/NotifyTagsView.swift b/panel/NotifyTagsView.swift new file mode 100644 index 0000000..9f6e484 --- /dev/null +++ b/panel/NotifyTagsView.swift @@ -0,0 +1,96 @@ +import SwiftUI + +// Settings > Notifications > "Notify me about…". One toggle per feed tag. A tag +// turned off still lists its events in the Events tab; it just stops popping a +// banner, speaking and moving the companion. +struct NotifyTagsView: View { + + @ObservedObject var nav: PanelNav + let onBack: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + header + Divider().opacity(0.4) + ScrollViewReader { proxy in + ScrollView { + VStack(alignment: .leading, spacing: 6) { + Text("Turn a tag off and its events still land in the list, but stop popping banners.") + .font(.caption2) + .foregroundStyle(.tertiary) + .padding(.bottom, 4) + let tags = nav.notifyTagList + ForEach(tags.indices, id: \.self) { index in + tagRow(tags[index], selected: index == nav.notifyTagSelection) + .id(index) + } + } + .padding(.horizontal, 14) + .padding(.vertical, 14) + .background(ThinScrollers()) + } + .onChange(of: nav.notifyTagSelection) { index in + withAnimation(.easeOut(duration: 0.15)) { proxy.scrollTo(index, anchor: .center) } + } + } + footer + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + + private var header: some View { + HStack(spacing: 8) { + Button(action: onBack) { + HStack(spacing: 4) { + Image(systemName: "chevron.left") + .font(.caption.weight(.semibold)) + Text("Settings") + .font(.caption) + } + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + + Text("Notify me about") + .font(.subheadline.weight(.medium)) + .padding(.leading, 6) + + Spacer() + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + } + + private func tagRow(_ tag: String, selected: Bool) -> some View { + let quiet = nav.quietTags.contains(tag) + return HStack(spacing: 8) { + Image(systemName: quiet ? "circle" : "checkmark.circle.fill") + .font(.callout) + .foregroundStyle(quiet ? Color.secondary.opacity(0.6) : Color.accentColor.opacity(0.8)) + .frame(width: 18, alignment: .center) + Text(tag) + .font(.callout) + .foregroundStyle(quiet ? .tertiary : .secondary) + Spacer() + } + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background( + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(selected ? Color.accentColor.opacity(0.22) : Color.primary.opacity(quiet ? 0.03 : 0.06)) + ) + .contentShape(Rectangle()) + .onTapGesture { + nav.notifyTagSelection = nav.notifyTagList.firstIndex(of: tag) ?? 0 + nav.toggleQuietTag(tag) + } + } + + private var footer: some View { + PageFooter { + FooterHint(label: "Toggle", keys: ["␣"], primary: true) + FooterHint(label: "Move", keys: ["↑↓"]) + FooterHint(label: "Back", keys: ["←"]) + } + } +} diff --git a/panel/Panel.swift b/panel/Panel.swift index 95044ea..46c0e67 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -223,6 +223,7 @@ struct PanelContentView: View { .onAppear { if runsOnAppear { extensionCatalog.loadIfNeeded() } } case .phrases: PhrasesView(model: phrases) { nav.mode = .settings } case .permissions: permissionsPage + case .notifyTags: NotifyTagsView(nav: nav) { nav.mode = .settings } case .extensions: ExtensionsView(catalog: extensionCatalog, host: extensions, @@ -282,7 +283,7 @@ struct PanelContentView: View { case .extensionTab(let id): return nav.extensionTab(id: id)?.label ?? id // Listed, not defaulted: a new tab should fail to compile here rather // than render an unlabelled one. - case .phrases, .permissions, .extensions, .extensionSources, .updateConfirm, .updating, + case .phrases, .permissions, .notifyTags, .extensions, .extensionSources, .updateConfirm, .updating, .postUpdate, .bootstrap, .uninstall: return "" } @@ -428,7 +429,7 @@ struct PanelContentView: View { static func tabStripAnchor(for mode: PanelMode, in tabs: [PanelMode]) -> PanelMode? { if tabs.contains(mode) { return mode } switch mode { - case .phrases, .permissions, .extensions, .extensionSources, .updateConfirm, .uninstall: + case .phrases, .permissions, .notifyTags, .extensions, .extensionSources, .updateConfirm, .uninstall: return tabs.contains(.settings) ? .settings : nil // No strip is drawn in these, so there is nothing to bring into view. case .updating, .postUpdate, .bootstrap: @@ -1603,6 +1604,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // removed, our commands repointed to the current path and arg). Codex wants a re-trust after either: a changed // notify.sh, or a changed entry in its hooks.json. let scriptRefreshed = Bootstrap.refreshNotifyScriptIfNeeded() != nil + Bootstrap.installCLI(bundled: Bootstrap.bundledCLIScript()) let rewired = Bootstrap.reconcileWiredAgents() if scriptRefreshed || rewired.contains(.codex), FileManager.default.fileExists(atPath: "\(NSHomeDirectory())/.codex/hooks.json") { @@ -1711,6 +1713,10 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, }, browseExtensions: { [weak self] in self?.nav.mode = .extensions }, openExtensionSources: { [weak self] in self?.openExtensionSources() }, + editNotifyTags: { [weak self] in + self?.nav.notifyTagSelection = 0 + self?.nav.mode = .notifyTags + }, openExtension: { [weak self] id in self?.openExtension(id) }, openReleaseNotes: { // Versioned tag URL when we know the bundle version, @@ -1760,6 +1766,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, setupNotificationCenter() store.onAppend = { [weak self] event in self?.lastEventArrivalAt = Date() + if let tag = event.tag, !tag.isEmpty { self?.nav.seenTags.insert(tag) } self?.postBannerIfNeeded(event) // Register the watch now rather than waiting up to 5s, so the // menu-bar count appears with the banner. @@ -1767,12 +1774,16 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, self?.refreshTranscriptStats(for: event) self?.captureHandoff(for: event) self?.noteHistory(event) - self?.nav.reactToEvent(event.kind) if let (name, data) = MCPAppEvents.occurrence(for: event) { self?.mcpServer?.emit(name, data: data, eventID: event.id.uuidString) } - // Only live arrivals reach onAppend, so events restored at launch never nod. - MainActor.assumeIsolated { self?.companion?.noteArrival(event) } + // Same rule as the banner, so a quiet tag or a Focus-held event + // does not move the companion either. + if self?.nav.interrupts(event) ?? true { + self?.nav.reactToEvent(event.kind) + // Only live arrivals reach onAppend, so events restored at launch never nod. + MainActor.assumeIsolated { self?.companion?.noteArrival(event) } + } } nav.loadFromConfig() // populate panelPinned + other live values up-front // After the config, so the server's first view of the settings is the @@ -3635,6 +3646,14 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // PanelNav.mutes). if nav.mutes(event) { return } + // Focus holds the banner, sound and voice but not the list entry, and + // remembers what it held for the summary when it ends. + if nav.focusPolicy.holds(event) { + nav.focus.hold(event) + return + } + if QuietTags.isQuiet(event, in: nav.quietTags) { return } + let config = PanelConfig.load() // Mascot/ripple still fire — they're driven from onAppend, not here. @@ -3870,6 +3889,57 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, refreshStatusBadge() } + // MARK: - Focus + + // Driven by the `focus` socket command. Turning it off posts one summary + // notice for what it held, instead of replaying every banner. + func setFocus(_ on: Bool) { + let released = nav.focus.set(on) + if on { UNUserNotificationCenter.current().removeAllDeliveredNotifications() } + refreshStatusBadge() + // Dismissed events are not worth reporting. + let live = Set(store.events.map(\.id)) + guard let text = FocusDigest.text(for: released.filter { live.contains($0.id) }) else { return } + store.append(NudgeEvent(agent: "stack-nudge", kind: .other, title: text, message: "", + source: .script, tag: "focus", key: "focus-digest")) + } + + func focusStatus() -> [String: Any] { + [ + "focus": nav.focus.active, + "respect": nav.respectFocus, + "meetings": nav.focusMeetings, + "holding": nav.focusHolding, + "held": nav.focus.held.count, + "lastChange": nav.focus.lastChange.map { ISO8601DateFormatter().string(from: $0) } ?? "", + ] + } + + // MARK: - Command channel + + private func makeCommandRouter() -> CommandRouter { + nav.busySources.register("sessions") { [weak self] in + (self?.sessions.sessions ?? []).filter { $0.liveStatus == "busy" } + .map { BusyItem(kind: "session", target: $0.projectName ?? $0.agent, since: nil) } + } + var hooks = CommandHooks() + hooks.post = { [weak self] event in self?.store.append(event) } + hooks.setFocus = { [weak self] on in self?.setFocus(on) } + hooks.focusStatus = { [weak self] in self?.focusStatus() ?? [:] } + hooks.poll = { [weak self] in self?.nav.pollNow } + hooks.setPose = { [weak self] override in + self?.nav.poseOverride = override + self?.nav.onPoseOverride?(override) + } + hooks.busy = { [weak self] in self?.nav.busySources.items() ?? [] } + hooks.openSettings = { [weak self] category in + guard let self else { return category ?? .notifications } + self.showSettings(category: category) + return self.nav.settingsCategory + } + return CommandRouter(hooks: hooks) + } + // MARK: - Slack private let slackNotifier = SlackNotifier() @@ -4227,7 +4297,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // reminder too made the two inconsistent: muted users got the opening // Slack DM and then silence. Local cues are still gated, below. // Reminders are all for prompts, which an MCP client's mute spares. - let localEligible = !nav.isMuted || nav.muteSparesPrompts + let localEligible = (!nav.isMuted || nav.muteSparesPrompts) && !nav.focusHolding let slackEligible = nav.slackEnabled && nav.slackTokenPresent && nav.slackMemberID != nil // Nothing can be delivered, so don't spend a reminder from the budget — // the prompt should still get its nudges once the mute lifts. @@ -4301,7 +4371,8 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // icon when muted, and the pending-prompt count rides alongside either way. private func refreshStatusBadge() { menuBar?.refreshStatusBadge(muteUntil: nav.muteUntil, - pendingPrompts: nav.pendingPromptCount) + pendingPrompts: nav.pendingPromptCount, + focusHolding: nav.focusHolding) } // Snooze: mark the event, schedule a Timer to clear the snooze flag and @@ -4322,7 +4393,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // directly, bypassing postBannerIfNeeded's mute gate, so guard it // here too. The snooze flag is already cleared, so the event stays // visible in the panel — only the banner interruption is dropped. - guard !self.nav.mutes(current) else { return } + guard !self.nav.mutes(current), !self.nav.focusHolding else { return } self.postBanner(for: current.with(snoozedUntil: nil)) } } @@ -5134,6 +5205,27 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, return true } + // Notify me about: ↑/↓ move, Space or Enter toggles the tag, ← returns. + if nav.mode == .notifyTags { + let plain = mods.intersection([.command, .control, .option, .shift]).isEmpty + guard plain else { return false } + switch event.keyCode { + case KeyCode.leftArrow: + nav.mode = .settings + case KeyCode.upArrow: + nav.moveNotifyTagSelection(by: -1) + case KeyCode.downArrow: + nav.moveNotifyTagSelection(by: 1) + case KeyCode.space, KeyCode.returnKey, KeyCode.numpadEnter: + let tags = nav.notifyTagList + guard tags.indices.contains(nav.notifyTagSelection) else { return true } + nav.toggleQuietTag(tags[nav.notifyTagSelection]) + default: + return false + } + return true + } + // Phrases mode: ↑/↓ navigate every row (defaults + custom), // Space toggles the selected default, ⌘⌫ removes the selected // custom, ← returns to Settings. Typing / Tab / Enter for @@ -6178,6 +6270,8 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, top ? nav.selectPrevCategory() : nav.selectNextCategory() case .phrases: top ? phrases.selectFirst() : phrases.selectLast() + case .notifyTags: + nav.notifyTagSelection = top ? 0 : max(0, nav.notifyTagList.count - 1) case .extensionSources: extensionSources.jump(toLast: !top) case .permissions: @@ -6552,7 +6646,8 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, atPath: installDir, withIntermediateDirectories: true) let socketPath = (installDir as NSString) .appendingPathComponent("panel.sock") - listener = EventListener(store: store, socketPath: socketPath) + listener = EventListener(store: store, socketPath: socketPath, + commands: makeCommandRouter()) do { try listener?.start() nav.listenerError = nil diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index 20acf09..12d33b8 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -55,6 +55,9 @@ enum PanelMode: Hashable { // Settings → Extensions → Other catalogues: the extra repositories the // browser reads. Another sub-page of Settings. case extensionSources + // "Notify me about": one toggle per feed tag, a sub-page of Settings like + // .phrases. + case notifyTags // Confirmation step after the user clicks the "Update available" row. // Shows release notes (when available) + Cancel / Update Now buttons. case updateConfirm @@ -204,6 +207,7 @@ enum SettingsRow: Hashable { case extensionUpdates case banner, muteWhenFocused, mute, muteDuration, remindUnanswered, stalledSessions, tabTitleNames, pinPanel, keepOpenWhenEmpty, launchAtLogin + case respectFocus, focusMeetings, notifyTagsPage case floatingWidget, snapToCorners, widgetCorner, widgetOpacity, widgetContent, mascot, theme case companionTurnOn, companionSize, companionBadge, companionPreviewPose, companionResetPosition case eventHistory, clearHistory @@ -264,6 +268,7 @@ extension SettingsRow: CaseIterable { .permissions, .update, .extensionUpdates, .hotkey, .banner, .muteWhenFocused, .mute, .muteDuration, .remindUnanswered, .stalledSessions, .tabTitleNames, .pinPanel, .keepOpenWhenEmpty, .launchAtLogin, + .respectFocus, .focusMeetings, .notifyTagsPage, .floatingWidget, .snapToCorners, .widgetCorner, .widgetOpacity, .widgetContent, .mascot, .theme, .companionTurnOn, .companionSize, .companionBadge, .companionPreviewPose, .companionResetPosition, @@ -290,6 +295,7 @@ struct SettingsActions { let editPhrases: () -> Void let browseExtensions: () -> Void let openExtensionSources: () -> Void + let editNotifyTags: () -> Void let openExtension: (String) -> Void let openReleaseNotes: () -> Void let checkForUpdates: () -> Void @@ -387,6 +393,45 @@ final class PanelNav: ObservableObject { // reference it so a value-less change still refreshes them). @Published var muteUntil: Date? @Published var muteTick: Int = 0 + // macOS Focus, pushed in by a Shortcuts automation through the socket. Kept + // apart from muteUntil: it ends by itself, and it summarises what it held. + @Published var focus = FocusTracker() + @Published var respectFocus: Bool = true + @Published var focusMeetings: Bool = true + // Tags turned off under "Notify me about", and every tag seen since launch + // so the page can offer ones the shipped list does not know. + @Published var quietTags: Set = [] + @Published var seenTags: Set = [] + @Published var notifyTagSelection: Int = 0 + // Hooks for branches that own the thing behind a socket command. All inert + // until wired: `poll` replies "no poller" while pollNow is nil. + var pollNow: ((@escaping (Int) -> Void) -> Void)? + var onPoseOverride: ((PoseOverride) -> Void)? + let busySources = BusySources() + // Set through the `state` socket command. The companion reads it; it is + // inert until then. + @Published var poseOverride: PoseOverride? + var focusPolicy: FocusPolicy { + FocusPolicy(focused: focus.active, respect: respectFocus, meetingsPass: focusMeetings) + } + var focusHolding: Bool { focus.active && respectFocus } + // Whether an event may pop a banner, speak or move the companion. Mute is + // checked separately by the callers, which already gate on it. + func interrupts(_ event: NudgeEvent) -> Bool { + !focusPolicy.holds(event) && !QuietTags.isQuiet(event, in: quietTags) + } + var notifyTagList: [String] { + QuietTags.known(seen: Array(seenTags), quiet: quietTags) + } + func toggleQuietTag(_ tag: String) { + if quietTags.contains(tag) { quietTags.remove(tag) } else { quietTags.insert(tag) } + ConfigFile.write(key: QuietTags.configKey, value: QuietTags.serialize(quietTags)) + } + func moveNotifyTagSelection(by delta: Int) { + let count = notifyTagList.count + guard count > 0 else { return } + notifyTagSelection = min(max(notifyTagSelection + delta, 0), count - 1) + } // Persistent default duration (minutes) the bell button and menu use. @Published var muteDurationMinutes: Int = 30 static let muteDurationOptions: [Int] = [15, 30, 60, 120] @@ -1677,7 +1722,10 @@ final class PanelNav: ObservableObject { case .notifications: return [.banner, .muteWhenFocused, .mute, .muteDuration, .remindUnanswered, .stalledSessions, - .soundEnabled, .agentDoneSound, .permissionSound] + .soundEnabled, .agentDoneSound, .permissionSound, + .notifyTagsPage] + case .focus: + return [.respectFocus, .focusMeetings] case .voice: return [.voiceEnabled, .speakHotkey] + (voiceModelCached ? [.voice, .voiceSpeed] : [.downloadVoiceModel]) @@ -1966,6 +2014,9 @@ final class PanelNav: ObservableObject { soundEnabled = ConfigFile.bool(config, "STACKNUDGE_SOUND", default: true) voiceEnabled = ConfigFile.bool(config, "STACKNUDGE_VOICE", default: false) muteWhenFocused = ConfigFile.bool(config, "STACKNUDGE_MUTE_WHEN_FOCUSED", default: true) + respectFocus = ConfigFile.bool(config, "STACKNUDGE_RESPECT_FOCUS", default: true) + focusMeetings = ConfigFile.bool(config, "STACKNUDGE_FOCUS_MEETINGS", default: true) + quietTags = QuietTags.parse(config[QuietTags.configKey]) tabTitleNames = ConfigFile.bool(config, "STACKNUDGE_TAB_TITLE_NAMES", default: false) // Persistent default only — the live `muteUntil` is transient and // intentionally left untouched here so config reloads never clear it. @@ -2300,6 +2351,7 @@ final class PanelNav: ObservableObject { case .editPhrases: actions?.editPhrases() case .browseExtensions: actions?.browseExtensions() case .extensionSources: actions?.openExtensionSources() + case .notifyTagsPage: actions?.editNotifyTags() // Listed explicitly. This switch ends in `default: applyCycle`, so an // omission here is not a build error — it is Enter quietly doing // nothing, on the one row whose whole purpose is being opened. @@ -2354,7 +2406,7 @@ final class PanelNav: ObservableObject { switch selectedRow { case .wireAgents, .dismissAgents, .connectGithub, .disconnectGithub, .editPhrases, .browseExtensions, .extensionSources, - .installedExtension, .integration, .mcpSetupClients, .mcpClient, + .installedExtension, .integration, .mcpSetupClients, .mcpClient, .notifyTagsPage, .checkPermissions, .openConfig, .releaseNotes, .checkUpdates, .uninstall, .quit, .clearHistory, .slackPaste, .slackIdentity, .slackTest, .openRepo, .companionResetPosition, .companionTurnOn, .none: @@ -2363,7 +2415,7 @@ final class PanelNav: ObservableObject { return extensionConfigKey(id, key)?.kind.isPicker ?? false case .extensionUpdate, .extensionRemove: return false - case .banner, .muteWhenFocused, .mute, .tabTitleNames, .pinPanel, + case .banner, .muteWhenFocused, .mute, .respectFocus, .focusMeetings, .tabTitleNames, .pinPanel, .keepOpenWhenEmpty, .launchAtLogin, .snapToCorners, .companionBadge, .soundEnabled, .voiceEnabled, .quotaTracking, .quotaAlerts, .showRemaining, @@ -2541,6 +2593,12 @@ final class PanelNav: ObservableObject { case .muteWhenFocused: muteWhenFocused.toggle() ConfigFile.write(key: "STACKNUDGE_MUTE_WHEN_FOCUSED", value: muteWhenFocused ? "true" : "false") + case .respectFocus: + respectFocus.toggle() + ConfigFile.write(key: "STACKNUDGE_RESPECT_FOCUS", value: respectFocus ? "true" : "false") + case .focusMeetings: + focusMeetings.toggle() + ConfigFile.write(key: "STACKNUDGE_FOCUS_MEETINGS", value: focusMeetings ? "true" : "false") case .tabTitleNames: tabTitleNames.toggle() ConfigFile.write(key: "STACKNUDGE_TAB_TITLE_NAMES", value: tabTitleNames ? "true" : "false") @@ -2752,7 +2810,7 @@ final class PanelNav: ObservableObject { case .wireAgents, .dismissAgents, .permissions, .update, .extensionUpdates, .hotkey, .speakHotkey, .downloadVoiceModel, .connectGithub, .disconnectGithub, .editPhrases, .browseExtensions, .extensionSources, - .installedExtension, .integration, .mcpSetupClients, .mcpClient, + .installedExtension, .integration, .mcpSetupClients, .mcpClient, .notifyTagsPage, .checkPermissions, .openConfig, .releaseNotes, .checkUpdates, .uninstall, .quit, .clearHistory, .slackPaste, .slackIdentity, .slackTest, .openRepo, .companionResetPosition, .companionTurnOn, .none: @@ -3009,7 +3067,7 @@ struct ExtensionTab: Equatable, Identifiable { // one, in install order, and are listed by PanelNav.settingsCategories, since // only nav knows what is installed. `allCases` is the built-in ones alone. enum SettingsCategory: Hashable, CaseIterable { - case notifications, voice, appearance, companion, usage, integrations, extensions, mcp, panel, events, + case notifications, focus, voice, appearance, companion, usage, integrations, extensions, mcp, panel, events, actions, about // One extension's page, a level below Extensions. Not in the sidebar. case extensionPage(String) @@ -3020,15 +3078,28 @@ enum SettingsCategory: Hashable, CaseIterable { case mcpSetupPage static let allCases: [SettingsCategory] = [ - .notifications, .voice, .appearance, .companion, .usage, .integrations, .extensions, + .notifications, .focus, .voice, .appearance, .companion, .usage, .integrations, .extensions, .mcp, .panel, .events, .actions, .about, ] + // The name the `settings` socket command uses: the case name for a built-in + // page. An extension's page can be shown but not asked for by name. + var key: String { + if case .extensionPage(let id) = self { return "extension:\(id)" } + return String(describing: self) + } + + init?(key: String) { + guard let found = Self.allCases.first(where: { $0.key == key }) else { return nil } + self = found + } + // Kept short: the sidebar is ~120pt. An extension's page is titled by its // name, which PanelNav.label(for:) knows; this falls back to the id. var label: String { switch self { case .notifications: return "Notifications" + case .focus: return "Focus" case .voice: return "Voice" case .appearance: return "Appearance" case .companion: return "Companion" diff --git a/panel/Settings.swift b/panel/Settings.swift index b367b80..b3429fe 100644 --- a/panel/Settings.swift +++ b/panel/Settings.swift @@ -104,6 +104,10 @@ struct SettingsView: View { } } + private var notifyTagsRowValue: String { + nav.quietTags.isEmpty ? "All" : "\(nav.quietTags.count) off" + } + // Trailing value for the .mute action row: the live countdown while // muted (re-rendered by nav.muteTick every 30s), empty otherwise so the // row reads as a plain "Mute notifications" affordance. @@ -875,6 +879,11 @@ struct SettingsView: View { case .soundEnabled: row(.soundEnabled, label: "Sound enabled", kind: .toggle, value: nav.soundEnabled ? "On" : "Off") case .agentDoneSound: row(.agentDoneSound, label: "Agent done", kind: .cycle, value: nav.soundStop, enabled: nav.soundEnabled) case .permissionSound: row(.permissionSound, label: "Permission", kind: .cycle, value: nav.soundPermission, enabled: nav.soundEnabled) + case .notifyTagsPage: row(.notifyTagsPage, label: "Notify me about…", kind: .action, value: notifyTagsRowValue) + + // Focus + case .respectFocus: row(.respectFocus, label: "Respect Focus / Do Not Disturb", kind: .toggle, value: nav.respectFocus ? "On" : "Off") + case .focusMeetings: row(.focusMeetings, label: "Meetings still show", kind: .toggle, value: nav.focusMeetings ? "On" : "Off", enabled: nav.respectFocus) // Voice case .voiceEnabled: row(.voiceEnabled, label: "Voice notifications", kind: .toggle, value: nav.voiceEnabled ? "On" : "Off") diff --git a/stack-nudge.sh b/stack-nudge.sh new file mode 100755 index 0000000..35a5ffd --- /dev/null +++ b/stack-nudge.sh @@ -0,0 +1,117 @@ +#!/bin/sh +# Talks to the running StackNudge panel over its Unix socket. say, state and +# focus on|off exit 0 quietly when the app is down, so a script or a Shortcuts +# automation never fails because the panel is not running. +# +# Installed as ~/.stack-nudge/stack-nudge beside notify.sh. The socket is the +# same one notify.sh posts events to; a line with a "cmd" key is a command and +# gets one JSON line back. +SOCK="${STACKNUDGE_SOCK:-$HOME/.stack-nudge/panel.sock}" + +usage() { + cat >&2 <<'USAGE' +usage: stack-nudge say "title" [--body ..] [--url ..] [--severity info|action|alert] + [--source github|calendar|script] [--tag ..] [--key ..] + stack-nudge focus on|off|status + stack-nudge state [--ttl seconds] + stack-nudge settings [category] + stack-nudge poll | busy | ping +USAGE + exit 2 +} + +esc() { + printf '%s' "$1" | awk 'BEGIN{ORS=""} {gsub(/\\/,"\\\\"); gsub(/"/,"\\\""); gsub(/\t/,"\\t"); gsub(/\r/,""); if (NR>1) print "\\n"; print}' +} + +[ $# -ge 1 ] || usage +cmd=$1 +shift +quiet=0 +wait=5 + +case "$cmd" in + say) + [ $# -ge 1 ] || usage + title=$1 + shift + body='' url='' severity='' source='' tag='' key='' + while [ $# -gt 0 ]; do + [ $# -ge 2 ] || usage + case "$1" in + --body) body=$2 ;; + --url) url=$2 ;; + --severity) severity=$2 ;; + --source) source=$2 ;; + --tag) tag=$2 ;; + --key) key=$2 ;; + *) usage ;; + esac + shift 2 + done + json="{\"cmd\":\"say\",\"title\":\"$(esc "$title")\",\"body\":\"$(esc "$body")\",\"url\":\"$(esc "$url")\"" + [ -n "$severity" ] && json="$json,\"severity\":\"$(esc "$severity")\"" + [ -n "$source" ] && json="$json,\"source\":\"$(esc "$source")\"" + [ -n "$tag" ] && json="$json,\"tag\":\"$(esc "$tag")\"" + [ -n "$key" ] && json="$json,\"key\":\"$(esc "$key")\"" + json="$json}" + quiet=1 + ;; + state) + [ $# -ge 1 ] || usage + name=$1 + shift + ttl=30 + if [ "${1:-}" = "--ttl" ]; then + [ $# -eq 2 ] || usage + ttl=$2 + elif [ $# -gt 0 ]; then + usage + fi + case "$ttl" in '' | *[!0-9.]*) usage ;; esac + json="{\"cmd\":\"state\",\"state\":\"$(esc "$name")\",\"ttlSeconds\":$ttl}" + quiet=1 + ;; + focus) + [ $# -eq 1 ] || usage + case "$1" in on | off | status) ;; *) usage ;; esac + json="{\"cmd\":\"focus\",\"state\":\"$1\"}" + [ "$1" = status ] || quiet=1 + ;; + settings) + [ $# -le 1 ] || usage + json="{\"cmd\":\"settings\",\"category\":\"$(esc "${1:-}")\"}" + ;; + poll) + json='{"cmd":"poll"}' + wait=240 + ;; + busy) + json='{"cmd":"busy"}' + ;; + ping) + json='{"cmd":"ping"}' + ;; + *) + usage + ;; +esac + +down() { + [ "$quiet" = 1 ] && exit 0 + echo "stack-nudge: the panel is not running (open StackNudge.app)" >&2 + exit 1 +} + +[ -S "$SOCK" ] || down +reply=$(printf '%s\n' "$json" | nc -U -w "$wait" "$SOCK" 2>/dev/null) || down +[ -n "$reply" ] || down +case "$reply" in + *'"ok":true'*) + [ "$quiet" = 1 ] || echo "$reply" + ;; + *) + echo "$reply" >&2 + exit 1 + ;; +esac