From af37959b2f6d46cae3af1134a37cd680df3a0e82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20De=20Freitas?= <6485562+adefreitas@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:30:53 +0000 Subject: [PATCH 1/5] feat(calendar): meeting reminders, changes and a morning summary from Calendar.app Port Hounder's calendar features. With Settings > Calendar on, stack-nudge reads the calendars synced into Calendar.app through EventKit and posts feed events (source calendar, tag calendar). Nothing leaves the Mac, and macOS is only asked for calendar access once the setting is turned on. - Heads-up before each meeting (5, 10 or 15 minutes, default 10) as one keyed row, meeting::. It is an action at the heads-up, is replaced by an alert at the start, opens the meeting link, and is removed when you join or five minutes after the start. A moved or cancelled meeting loses its row. - Meeting added, changed and cancelled rows, with Hounder's diff rules: late synced meetings and re-issued ids stay quiet, and a cancellation waits out a five minute grace. - Morning summary on weekdays at a set time, once a day, until noon, with the optional empty-day row. - Join detection: Meet tabs (including meet.google.com/meet/) via osascript in running browsers, Zoom via the CptHost process, Teams by window title. It needs Automation per browser and has its own setting. - Today's meetings are published on PanelNav.todaysMeetings for a view to read. EventStore gains remove(key:) for feed events, and its duplicate check now compares titles so two meetings at the same time both land. Info.plist gains the calendar usage strings and a broader Apple Events string; the entitlements gain the calendars entitlement a hardened-runtime build needs for EventKit. The calendar selection is the config key STACKNUDGE_CALENDARS (no picker). Co-Authored-By: Claude Opus 5.5 --- PRIVACY.md | 10 + .../CalendarWatcherTests.swift | 182 ++++++++++ .../FeedEventTests.swift | 33 ++ .../JoinDetectorTests.swift | 205 +++++++++++ .../MeetingDiffTests.swift | 287 +++++++++++++++ .../MeetingLinksTests.swift | 57 +++ .../SettingsCategoryTests.swift | 45 +++ docs/notifications.md | 22 ++ docs/panel.md | 1 + notify.conf.example | 31 ++ panel/CalendarWatcher.swift | 326 ++++++++++++++++++ panel/EventStore.swift | 8 + panel/Info.plist | 6 +- panel/JoinDetector.swift | 207 +++++++++++ panel/JoinWatcher.swift | 109 ++++++ panel/Meeting.swift | 315 +++++++++++++++++ panel/MeetingLinks.swift | 111 ++++++ panel/Panel.swift | 31 ++ panel/PanelNav.swift | 90 ++++- panel/Settings.swift | 16 + panel/entitlements.plist | 11 + 21 files changed, 2099 insertions(+), 4 deletions(-) create mode 100644 Tests/StackNudgePanelCoreTests/CalendarWatcherTests.swift create mode 100644 Tests/StackNudgePanelCoreTests/JoinDetectorTests.swift create mode 100644 Tests/StackNudgePanelCoreTests/MeetingDiffTests.swift create mode 100644 Tests/StackNudgePanelCoreTests/MeetingLinksTests.swift create mode 100644 panel/CalendarWatcher.swift create mode 100644 panel/JoinDetector.swift create mode 100644 panel/JoinWatcher.swift create mode 100644 panel/Meeting.swift create mode 100644 panel/MeetingLinks.swift diff --git a/PRIVACY.md b/PRIVACY.md index 8d26642a..77b7450d 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -51,6 +51,16 @@ StackNudge identifier, because there isn't one. **whatever network calls it makes are its own**. What each of the app's own extensions reads and sends is in the marketplace's [PRIVACY.md](https://github.com/StackOneHQ/stack-nudge-extensions-marketplace/blob/main/PRIVACY.md). +- **Calendar** (`STACKNUDGE_CALENDAR`). Reads your calendars on this Mac + through Apple's EventKit, after macOS has asked you for access. Meeting + titles, times, locations, organisers and notes are read locally and are never + sent anywhere: the feature makes no network calls. The last snapshot of the + next seven days is kept in `~/.stack-nudge/calendar.json`. **Join detection** + (`STACKNUDGE_CALENDAR_JOIN`) reads the tab addresses of browsers that are + already running (through `osascript`, after you grant Automation), the + process list for Zoom's helper, and, if you have granted Screen Recording, + Teams window titles. It compares them with the meeting link, stores none of + them, and writes only error lines to `~/.stack-nudge/join.log`. - **Voice** (`STACKNUDGE_VOICE`). Downloading a voice model runs `stackvox` in the bundled Python environment, which fetches the model over the network. That download is the only part that leaves your machine: synthesis runs diff --git a/Tests/StackNudgePanelCoreTests/CalendarWatcherTests.swift b/Tests/StackNudgePanelCoreTests/CalendarWatcherTests.swift new file mode 100644 index 00000000..e53826c6 --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/CalendarWatcherTests.swift @@ -0,0 +1,182 @@ +import XCTest + +@testable import StackNudgePanelCore + +// The watcher's decisions, driven through `apply` so no test touches EventKit, +// the real calendar or ~/.stack-nudge. +@MainActor +final class CalendarWatcherTests: XCTestCase { + + private let t0 = Date(timeIntervalSince1970: 1_800_000_000) + private var dir = "" + private var store = EventStore() + private var settings = CalendarSettings() + + override func setUpWithError() throws { + dir = NSTemporaryDirectory() + "calendar-watcher-" + UUID().uuidString + store = EventStore() + settings = CalendarSettings() + settings.summary.enabled = false + addTeardownBlock { [dir] in try? FileManager.default.removeItem(atPath: dir) } + } + + private func watcher(detector: JoinDetector = FakeJoinDetector(.unknown), at now: @escaping () -> Date) -> CalendarWatcher { + CalendarWatcher(events: store, settings: { [unowned self] in settings }, clock: now, stateDir: dir, + detector: detector, background: { $0() }, deliver: { $0() }, autoSchedule: false) + } + + private func meeting(_ id: String = "a", in minutes: Double, join: String = "") -> Meeting { + let start = t0.addingTimeInterval(minutes * 60) + return Meeting(id: id, itemId: id, title: "Standup", start: start, end: start.addingTimeInterval(1800), + location: "", organizer: "Ana", joinUrl: join, calendar: "Work") + } + + private func reminders() -> [NudgeEvent] { + store.events.filter { $0.key?.hasPrefix("meeting:") == true } + } + + func testTheFirstRefreshSeedsWithoutAnnouncing() { + let w = watcher { self.t0 } + w.apply(current: [meeting(in: 120)], signature: "x", now: t0) + XCTAssertTrue(store.events.isEmpty) + } + + func testAMeetingAddedLaterIsAnnounced() { + let w = watcher { self.t0 } + w.apply(current: [], signature: "x", now: t0) + w.apply(current: [meeting(in: 120)], signature: "x", now: t0.addingTimeInterval(60)) + XCTAssertEqual(store.events.map(\.title), ["New meeting: Standup"]) + XCTAssertEqual(store.events.first?.source, .calendar) + } + + func testTheHeadsUpIsAnActionRowThatTheStartAlertReplaces() { + let m = meeting(in: 10) + var now = t0 + let w = watcher { now } + w.apply(current: [m], signature: "x", now: now) + XCTAssertEqual(reminders().map(\.severity), [.action]) + XCTAssertEqual(reminders().first?.title, "Standup starts in 10 min") + XCTAssertEqual(reminders().first?.key, MeetingDiff.dueKey(m)) + + now = m.start + w.apply(current: [m], signature: "x", now: now) + XCTAssertEqual(reminders().map(\.severity), [.alert], "same key, so one row") + XCTAssertEqual(reminders().first?.title, "Standup is starting now") + + w.apply(current: [m], signature: "x", now: now.addingTimeInterval(60)) + XCTAssertEqual(store.events.count, 1, "the alert fires once") + } + + func testTheReminderOpensTheMeetingLink() { + let m = meeting(in: 10, join: "https://meet.google.com/abc-defg-hij") + let w = watcher { self.t0 } + w.apply(current: [m], signature: "x", now: t0) + XCTAssertEqual(reminders().first?.url?.absoluteString, "https://meet.google.com/abc-defg-hij") + } + + func testTheReminderGoesFiveMinutesAfterTheStart() { + let m = meeting(in: 10) + let w = watcher { self.t0 } + w.apply(current: [m], signature: "x", now: t0) + w.apply(current: [m], signature: "x", now: m.start) + w.apply(current: [m], signature: "x", now: m.start.addingTimeInterval(299)) + XCTAssertEqual(reminders().count, 1) + w.apply(current: [m], signature: "x", now: m.start.addingTimeInterval(300)) + XCTAssertTrue(reminders().isEmpty) + w.apply(current: [m], signature: "x", now: m.start.addingTimeInterval(360)) + XCTAssertTrue(reminders().isEmpty, "an expired reminder does not come back") + } + + func testJoiningClearsTheReminderAndSuppressesTheStartAlert() { + let m = meeting(in: 4, join: "https://meet.google.com/abc-defg-hij") + var now = t0 + let detector = FakeJoinDetector(.joined) + let w = watcher(detector: detector) { now } + w.apply(current: [m], signature: "x", now: now) + XCTAssertTrue(reminders().isEmpty, "joined inside the first check") + XCTAssertEqual(detector.calls, ["https://meet.google.com/abc-defg-hij"]) + + now = m.start + w.apply(current: [m], signature: "x", now: now) + XCTAssertTrue(reminders().isEmpty, "no start alert for a meeting already joined") + } + + func testNotJoiningLeavesTheAlertUpUntilItExpires() { + let m = meeting(in: 4, join: "https://meet.google.com/abc-defg-hij") + var now = t0 + let w = watcher(detector: FakeJoinDetector(.notJoined)) { now } + w.apply(current: [m], signature: "x", now: now) + now = m.start + w.apply(current: [m], signature: "x", now: now) + XCTAssertEqual(reminders().map(\.severity), [.alert]) + now = m.start.addingTimeInterval(120) + w.apply(current: [m], signature: "x", now: now) + XCTAssertEqual(reminders().map(\.severity), [.alert]) + } + + func testDetectionOffNeverLooksAtTheBrowser() { + settings.detectJoin = false + let m = meeting(in: 4, join: "https://meet.google.com/abc-defg-hij") + let detector = FakeJoinDetector(.joined) + let w = watcher(detector: detector) { self.t0 } + w.apply(current: [m], signature: "x", now: t0) + XCTAssertTrue(detector.calls.isEmpty) + XCTAssertEqual(reminders().count, 1) + } + + func testAMovedMeetingLosesItsOldReminder() { + let m = meeting(in: 10) + let w = watcher { self.t0 } + w.apply(current: [m], signature: "x", now: t0) + XCTAssertEqual(reminders().count, 1) + var moved = m + moved.start = m.start.addingTimeInterval(3600) + moved.end = m.end.addingTimeInterval(3600) + w.apply(current: [moved], signature: "x", now: t0.addingTimeInterval(60)) + XCTAssertTrue(reminders().isEmpty) + XCTAssertEqual(store.events.map(\.title), ["Meeting changed: Standup"]) + } + + func testTheLeadTimeSettingMovesTheHeadsUp() { + settings.leadMinutes = 5 + let m = meeting(in: 8) + let w = watcher { self.t0 } + w.apply(current: [m], signature: "x", now: t0) + XCTAssertTrue(reminders().isEmpty) + w.apply(current: [m], signature: "x", now: t0.addingTimeInterval(3 * 60)) + XCTAssertEqual(reminders().first?.title, "Standup starts in 5 min") + } + + func testTheSummaryIsOneInfoRowOncePerDay() { + let cal = Calendar.current + let nine = cal.date(from: DateComponents(year: 2026, month: 10, day: 21, hour: 9, minute: 5))! + var s = CalendarSettings() + s.summary.weekdaysOnly = false + settings = s + let start = cal.date(from: DateComponents(year: 2026, month: 10, day: 21, hour: 14))! + let m = Meeting(id: "a", itemId: "a", title: "Retro", start: start, end: start.addingTimeInterval(1800), + location: "", organizer: "", joinUrl: "", calendar: "Work") + let w = watcher { nine } + w.apply(current: [m], signature: "x", now: nine) + w.apply(current: [m], signature: "x", now: nine.addingTimeInterval(60)) + XCTAssertEqual(store.events.map(\.title), ["Today: 1 meeting"]) + XCTAssertEqual(store.events.first?.severity, .info) + XCTAssertEqual(store.events.first?.message, "14:00 Retro") + } + + func testTodaysMeetingsAreReportedForAView() { + let cal = Calendar.current + let noon = cal.date(from: DateComponents(year: 2026, month: 10, day: 21, hour: 12))! + func at(_ day: Int, _ hour: Int, _ id: String) -> Meeting { + let s = cal.date(from: DateComponents(year: 2026, month: 10, day: day, hour: hour))! + return Meeting(id: id, itemId: id, title: id, start: s, end: s.addingTimeInterval(1800), + location: "", organizer: "", joinUrl: "", calendar: "Work") + } + var reported: [Meeting] = [] + let w = CalendarWatcher(events: store, settings: { [unowned self] in settings }, clock: { noon }, stateDir: dir, + detector: FakeJoinDetector(.unknown), background: { $0() }, deliver: { $0() }, + autoSchedule: false, onToday: { reported = $0 }) + w.apply(current: [at(21, 15, "late"), at(21, 9, "early"), at(22, 9, "tomorrow")], signature: "x", now: noon) + XCTAssertEqual(reported.map(\.id), ["early", "late"]) + } +} diff --git a/Tests/StackNudgePanelCoreTests/FeedEventTests.swift b/Tests/StackNudgePanelCoreTests/FeedEventTests.swift index efa9fc54..75a9c53d 100644 --- a/Tests/StackNudgePanelCoreTests/FeedEventTests.swift +++ b/Tests/StackNudgePanelCoreTests/FeedEventTests.swift @@ -222,6 +222,39 @@ final class FeedEventTests: XCTestCase { XCTAssertNil(event?.feedAction) } + func testRemovingByKeyDropsOnlyThatFeedEvent() { + let store = EventStore() + let waiting = prompt() + store.append(waiting) + store.append(feed("CI failing", key: "pr:1:ci")) + store.append(feed("other", key: "pr:2:ci")) + store.remove(key: "pr:1:ci") + XCTAssertEqual(store.events.map(\.message).sorted(), ["Bash(ls)", "other"]) + store.remove(key: "pr:1:ci") + store.remove(key: "nobody") + XCTAssertEqual(store.events.count, 2, "an unknown key removes nothing") + } + + func testRemovingByKeyMovesTheSelectionOffTheRemovedRow() { + let store = EventStore() + let event = feed("CI failing", key: "pr:1:ci") + store.append(event) + XCTAssertEqual(store.selectedID, event.id) + store.remove(key: "pr:1:ci") + XCTAssertNil(store.selectedID) + } + + // Two meetings at the same time differ only in their title. + func testTwoFeedEventsWithTheSameBodyButDifferentTitlesBothLand() { + let store = EventStore() + func meeting(_ title: String) -> NudgeEvent { + .feed(source: .calendar, tag: "calendar", severity: .action, title: title, message: "10:00 to 10:30") + } + store.append(meeting("Standup starts in 10 min")) + store.append(meeting("Retro starts in 10 min")) + XCTAssertEqual(store.events.count, 2) + } + func testUnkeyedFeedEventsStack() { let store = EventStore() store.append(feed("one", key: nil)) diff --git a/Tests/StackNudgePanelCoreTests/JoinDetectorTests.swift b/Tests/StackNudgePanelCoreTests/JoinDetectorTests.swift new file mode 100644 index 00000000..3c58128b --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/JoinDetectorTests.swift @@ -0,0 +1,205 @@ +import XCTest + +@testable import StackNudgePanelCore + +final class FakeJoinDetector: JoinDetector, @unchecked Sendable { + private let lock = NSLock() + private var _state: JoinState + private var _calls: [String] = [] + init(_ state: JoinState) { _state = state } + + var state: JoinState { + get { lock.withLock { _state } } + set { lock.withLock { _state = newValue } } + } + var calls: [String] { lock.withLock { _calls } } + + func check(url: String) -> JoinState { + lock.withLock { _calls.append(url) } + return state + } +} + +final class JoinTargetTests: XCTestCase { + + func testMeetCodesInVariousUrlShapes() { + let code = JoinTarget.meetCode(in:) + XCTAssertEqual(code("https://meet.google.com/abc-defg-hij"), "abc-defg-hij") + XCTAssertEqual(code("https://meet.google.com/abc-defg-hij?authuser=1"), "abc-defg-hij") + XCTAssertEqual(code("https://meet.google.com/abc-defg-hij?authuser=1&hs=122&pli=1"), "abc-defg-hij") + XCTAssertEqual(code("https://meet.google.com/u/2/abc-defg-hij"), "abc-defg-hij") + XCTAssertEqual(code("https://meet.google.com/ABC-defg-hij#x"), "abc-defg-hij") + // the shape newer Meet tabs show while you are in the call + XCTAssertEqual(code("https://meet.google.com/meet/emh-pjrs-fxk"), "emh-pjrs-fxk") + XCTAssertEqual(code("https://meet.google.com/u/1/meet/emh-pjrs-fxk?authuser=1"), "emh-pjrs-fxk") + XCTAssertTrue(JoinTarget.of("https://meet.google.com/emh-pjrs-fxk").matches(tab: "https://meet.google.com/meet/emh-pjrs-fxk")) + XCTAssertNil(code("https://meet.google.com/home")) + XCTAssertNil(code("https://meet.google.com/landing")) + XCTAssertNil(code("https://meet.google.com/")) + XCTAssertNil(code("https://example.com/abc-defg-hij")) + } + + func testZoomIdsFromJoinLinks() { + XCTAssertEqual(JoinTarget.zoomId(in: "https://us02web.zoom.us/j/81234567890?pwd=abc"), "81234567890") + XCTAssertEqual(JoinTarget.zoomId(in: "https://zoom.us/j/81234567890"), "81234567890") + XCTAssertEqual(JoinTarget.zoomId(in: "https://app.zoom.us/wc/81234567890/join"), "81234567890") + XCTAssertNil(JoinTarget.zoomId(in: "https://zoom.us/my/ana")) + } + + func testTargetsByProvider() { + XCTAssertEqual(JoinTarget.of("https://meet.google.com/abc-defg-hij?authuser=1"), .meet(code: "abc-defg-hij")) + XCTAssertEqual(JoinTarget.of("https://us02web.zoom.us/j/81234567890"), .zoom(id: "81234567890")) + XCTAssertEqual(JoinTarget.of("https://zoom.us/my/ana"), .zoom(id: nil)) + XCTAssertEqual(JoinTarget.of("https://teams.microsoft.com/l/meetup-join/19%3a"), .teams) + XCTAssertEqual(JoinTarget.of("https://acme.webex.com/meet/x"), .unsupported) + } + + func testTabMatchesOnlyTheSameMeeting() { + let t = JoinTarget.meet(code: "abc-defg-hij") + XCTAssertTrue(t.matches(tab: "https://meet.google.com/abc-defg-hij?authuser=3")) + XCTAssertFalse(t.matches(tab: "https://meet.google.com/zzz-yyyy-xxx")) + XCTAssertFalse(t.matches(tab: "https://calendar.google.com/abc-defg-hij")) + } + + func testDecisionNeedsAReadableBrowserToSayNotJoined() { + let t = JoinTarget.meet(code: "abc-defg-hij") + let open = TabRead.urls(["https://meet.google.com/abc-defg-hij?authuser=1"]) + func decide(_ reads: [TabRead]) -> JoinState { JoinDecision.decide(t, reads: reads, zoomInMeeting: false, teamsWindow: false) } + XCTAssertEqual(decide([.urls(["https://example.com"]), open]), .joined) + XCTAssertEqual(decide([.urls(["https://example.com"])]), .notJoined) + XCTAssertEqual(decide([.denied]), .unknown) + XCTAssertEqual(decide([.denied, .urls([])]), .notJoined) + XCTAssertEqual(decide([]), .unknown) + } + + func testZoomJoinedFromTheHelperProcess() { + let t = JoinTarget.zoom(id: "81234567890") + XCTAssertEqual(JoinDecision.decide(t, reads: [], zoomInMeeting: true, teamsWindow: false), .joined) + XCTAssertEqual(JoinDecision.decide(t, reads: [], zoomInMeeting: false, teamsWindow: false), .notJoined) + XCTAssertEqual(JoinDecision.decide(t, reads: [.denied], zoomInMeeting: false, teamsWindow: false), .unknown) + XCTAssertEqual(JoinDecision.decide(t, reads: [.urls(["https://app.zoom.us/wc/81234567890/start"])], zoomInMeeting: false, teamsWindow: false), .joined) + XCTAssertEqual(JoinDecision.decide(.unsupported, reads: [], zoomInMeeting: false, teamsWindow: false), .unknown) + } + + func testTeamsJoinedFromItsWindowTitle() { + XCTAssertEqual(JoinDecision.decide(.teams, reads: [], zoomInMeeting: false, teamsWindow: true), .joined) + XCTAssertEqual(JoinDecision.decide(.teams, reads: [.urls([])], zoomInMeeting: false, teamsWindow: false), .notJoined) + XCTAssertEqual(JoinDecision.decide(.teams, reads: [], zoomInMeeting: false, teamsWindow: false), .unknown) + } +} + +@MainActor +final class JoinWatcherTests: XCTestCase { + + private let start = Date(timeIntervalSince1970: 1_800_000_000) + private let meet = "https://meet.google.com/abc-defg-hij" + + private func reminder(_ id: String = "m", url: String? = nil) -> JoinCandidate { + JoinCandidate(id: id, url: url ?? meet, start: start) + } + + private final class Harness { + var now: Date + var joined: [String] = [] + var notJoined: [String] = [] + let detector: FakeJoinDetector + var watcher: JoinWatcher! + init(now: Date, state: JoinState) { + self.now = now + detector = FakeJoinDetector(state) + } + } + + private func harness(at offset: TimeInterval, _ state: JoinState, enabled: Bool = true) -> Harness { + let h = Harness(now: start.addingTimeInterval(offset), state: state) + h.watcher = JoinWatcher( + detector: h.detector, clock: { [unowned h] in h.now }, enabled: { enabled }, + background: { $0() }, deliver: { $0() }, autoSchedule: false, + onJoined: { [unowned h] in h.joined.append($0.id) }, onNotJoined: { [unowned h] in h.notJoined.append($0.id) }) + return h + } + + func testJoinInsideTheWindowResolvesTheReminder() { + let h = harness(at: -120, .joined) + h.watcher.sync([reminder()]) + XCTAssertEqual(h.joined, ["m"]) + h.now = start.addingTimeInterval(-60) + h.watcher.sync([reminder()]) + XCTAssertEqual(h.detector.calls.count, 1) + } + + func testNotJoinedAtTheStartReportsOnceAndKeepsPolling() { + let h = harness(at: -60, .notJoined) + h.watcher.sync([reminder()]) + XCTAssertTrue(h.notJoined.isEmpty) + h.now = start.addingTimeInterval(1) + h.watcher.poll() + h.now = start.addingTimeInterval(20) + h.watcher.poll() + XCTAssertEqual(h.notJoined, ["m"]) + XCTAssertTrue(h.joined.isEmpty) + XCTAssertEqual(h.detector.calls.count, 3) + + h.detector.state = .joined + h.now = start.addingTimeInterval(40) + h.watcher.poll() + XCTAssertEqual(h.joined, ["m"]) + } + + func testUnknownChangesNothing() { + let h = harness(at: 10, .unknown) + h.watcher.sync([reminder()]) + XCTAssertTrue(h.joined.isEmpty && h.notJoined.isEmpty) + } + + func testPollsAtMostEveryFifteenSeconds() { + let h = harness(at: -200, .notJoined) + h.watcher.sync([reminder()]) + for s in stride(from: -198.0, through: -186, by: 2) { + h.now = start.addingTimeInterval(s) + h.watcher.poll() + } + XCTAssertEqual(h.detector.calls.count, 1) + h.now = start.addingTimeInterval(-185) + h.watcher.poll() + XCTAssertEqual(h.detector.calls.count, 2) + } + + func testOnlyPollsInsideTheWindow() { + let early = harness(at: -301, .notJoined) + early.watcher.sync([reminder()]) + XCTAssertTrue(early.detector.calls.isEmpty) + early.now = start.addingTimeInterval(-300) + early.watcher.poll() + early.watcher.sync([reminder()]) + XCTAssertEqual(early.detector.calls.count, 1) + + let late = harness(at: 299, .notJoined) + late.watcher.sync([reminder()]) + XCTAssertEqual(late.detector.calls.count, 1) + late.now = start.addingTimeInterval(300) + late.watcher.poll() + late.watcher.sync([reminder()]) + XCTAssertEqual(late.detector.calls.count, 1) + } + + func testIgnoresLinklessRemindersAndTheDisabledSetting() { + let h = harness(at: 0, .joined) + h.watcher.sync([reminder("b", url: "ical://ekevent/x?method=show"), reminder("c", url: "")]) + XCTAssertTrue(h.detector.calls.isEmpty) + + let off = harness(at: 0, .joined, enabled: false) + off.watcher.sync([reminder()]) + XCTAssertTrue(off.detector.calls.isEmpty) + } + + func testAJoinedMeetingIsNeverCheckedAgain() { + let h = harness(at: 0, .joined) + h.watcher.sync([reminder()]) + h.now = start.addingTimeInterval(60) + h.watcher.sync([reminder()]) + h.watcher.poll() + XCTAssertEqual(h.detector.calls.count, 1) + XCTAssertEqual(h.joined, ["m"]) + } +} diff --git a/Tests/StackNudgePanelCoreTests/MeetingDiffTests.swift b/Tests/StackNudgePanelCoreTests/MeetingDiffTests.swift new file mode 100644 index 00000000..d5d2146b --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/MeetingDiffTests.swift @@ -0,0 +1,287 @@ +import XCTest + +@testable import StackNudgePanelCore + +// The meeting rules ported from Hounder: what counts as added, changed or +// cancelled, when a heads-up is due, and when the morning summary goes out. +final class MeetingDiffTests: XCTestCase { + + private let now = Date(timeIntervalSince1970: 1_800_000_000) + private let lead: TimeInterval = 600 + + private func meeting(_ id: String, title: String = "Standup", in minutes: Double = 120, length: Double = 30, + location: String = "", organizer: String = "Ana") -> Meeting { + let start = now.addingTimeInterval(minutes * 60) + return Meeting(id: id, itemId: id, title: title, start: start, end: start.addingTimeInterval(length * 60), + location: location, organizer: organizer, joinUrl: "", calendar: "Work") + } + + func testDuplicateCalendarCopiesCollapse() { + var a = meeting("a", title: "Engineering Standup") + var b = meeting("b", title: "Engineering Standup") + b.calendar = "Product Engineering" + b.joinUrl = "https://meet.google.com/abc-defg-hij" + a.joinUrl = "" + let out = [a, b, meeting("c", title: "Retro", in: 300)].dedupedByOccurrence() + XCTAssertEqual(out.count, 2) + XCTAssertEqual(out.first?.joinUrl, "https://meet.google.com/abc-defg-hij") + } + + func testLateSyncedOldMeetingIsNotAnnounced() { + var m = meeting("old") + m.created = now.addingTimeInterval(-86_400 * 3) + XCTAssertTrue(MeetingDiff.diff(old: [], new: [m], now: now, since: now.addingTimeInterval(-60)).isEmpty) + m.created = now.addingTimeInterval(-30) + XCTAssertEqual(MeetingDiff.diff(old: [], new: [m], now: now, since: now.addingTimeInterval(-60)).count, 1) + } + + func testBriefDropDuringSyncIsNotACancellation() { + let m = meeting("a") + // First refresh without it: held, nothing announced. + XCTAssertTrue(MeetingDiff.diff(old: [m], new: [], now: now, missingSince: [:]).isEmpty) + let held = MeetingDiff.held(old: [m], new: [], now: now, missingSince: [:]) + XCTAssertEqual(held["a"], now) + // Still missing a minute later: still held. + let later = now.addingTimeInterval(60) + XCTAssertTrue(MeetingDiff.diff(old: [m], new: [], now: later, missingSince: held).isEmpty) + // Missing past the grace period: cancelled, and no longer held. + let past = now.addingTimeInterval(MeetingDiff.cancelGrace + 1) + XCTAssertEqual(MeetingDiff.diff(old: [m], new: [], now: past, missingSince: held).map(\.kind), ["meeting-cancelled"]) + XCTAssertTrue(MeetingDiff.held(old: [m], new: [], now: past, missingSince: held).isEmpty) + } + + func testNewIdForTheSameMeetingIsNeitherCancelledNorAdded() { + var moved = meeting("new-id") + moved.created = now + XCTAssertTrue(MeetingDiff.diff(old: [meeting("old-id")], new: [moved], now: now, since: now.addingTimeInterval(-60)).isEmpty) + XCTAssertTrue(MeetingDiff.missing(old: [meeting("old-id")], new: [moved], now: now).isEmpty) + } + + func testAdded() { + let out = MeetingDiff.diff(old: [], new: [meeting("a")], now: now) + XCTAssertEqual(out.map(\.kind), ["meeting-added"]) + XCTAssertEqual(out[0].title, "New meeting: Standup") + XCTAssertEqual(out[0].severity, .info) + XCTAssertTrue(out[0].body.hasSuffix(", Ana")) + } + + func testMovedWithinDayIsActionWhenSoon() { + let old = meeting("a") + var new = old + new.start = old.start.addingTimeInterval(90 * 60) + new.end = old.end.addingTimeInterval(90 * 60) + let out = MeetingDiff.diff(old: [old], new: [new], now: now) + XCTAssertEqual(out.map(\.kind), ["meeting-changed"]) + XCTAssertEqual(out[0].severity, .action) + let c = MeetingDiff.clock + XCTAssertEqual(out[0].body, "\(c(old.start))\u{2013}\(c(old.end)) \u{2192} \(c(new.start))\u{2013}\(c(new.end))") + } + + func testRenamedAndLocationFarAwayIsInfo() { + let old = meeting("a", in: 60 * 48) + var new = old + new.title = "Sync" + new.location = "Room 2" + let out = MeetingDiff.diff(old: [old], new: [new], now: now) + XCTAssertEqual(out[0].severity, .info) + XCTAssertEqual(out[0].body, "Was \u{201C}\(old.title)\u{201D}\nLocation: \(old.location.isEmpty ? "none" : old.location) \u{2192} Room 2") + } + + func testJoinLinkChangeAloneIsQuiet() { + let old = meeting("a") + var new = old + new.joinUrl = "https://meet.google.com/abc-defg-hij" + XCTAssertTrue(MeetingDiff.diff(old: [old], new: [new], now: now).isEmpty) + } + + func testCancelledOnlyWhileUpcoming() { + let upcoming = meeting("a") + let finished = meeting("b", in: -120) + let out = MeetingDiff.diff(old: [upcoming, finished], new: [], now: now) + XCTAssertEqual(out.map(\.kind), ["meeting-cancelled"]) + XCTAssertEqual(out[0].title, "Meeting cancelled: Standup") + } + + func testUnchangedIsQuiet() { + let m = meeting("a") + XCTAssertTrue(MeetingDiff.diff(old: [m], new: [m], now: now).isEmpty) + } + + func testNoticeBecomesACalendarFeedEvent() { + let out = MeetingDiff.diff(old: [], new: [meeting("a")], now: now) + let event = out[0].event(now: now) + XCTAssertEqual(event.source, .calendar) + XCTAssertEqual(event.tag, "calendar") + XCTAssertEqual(event.severity, .info) + XCTAssertTrue(event.url?.absoluteString.hasPrefix("ical://ekevent/a") == true) + } + + // MARK: Heads-up + + func testSoonFiresOnceAndSchedulesNext() { + let m = meeting("a", in: 9) + let later = meeting("b", in: 60) + XCTAssertEqual(MeetingDiff.due([m, later], fired: [], lead: lead, now: now).map(\.id), ["a"]) + XCTAssertTrue(MeetingDiff.due([m], fired: [MeetingDiff.dueKey(m)], lead: lead, now: now).isEmpty) + XCTAssertEqual(MeetingDiff.nextDue([m, later], fired: [MeetingDiff.dueKey(m)], lead: lead, now: now), + later.start.addingTimeInterval(-600)) + let n = MeetingDiff.soonNotice(meeting("a", in: 10), now: now) + XCTAssertEqual(n.title, "Standup starts in 10 min") + XCTAssertEqual(n.severity, .action) + } + + func testLeadTimeWidensTheHeadsUpWindow() { + let m = meeting("a", in: 14) + XCTAssertTrue(MeetingDiff.due([m], fired: [], lead: 600, now: now).isEmpty) + XCTAssertEqual(MeetingDiff.due([m], fired: [], lead: 900, now: now).map(\.id), ["a"]) + XCTAssertEqual(MeetingDiff.nextDue([m], fired: [], lead: 900, now: now.addingTimeInterval(-3600)), + m.start.addingTimeInterval(-900)) + } + + func testReminderKeyNamesTheMeetingAndItsStart() { + let m = meeting("a") + XCTAssertEqual(MeetingDiff.dueKey(m), "meeting:a:\(Int(m.start.timeIntervalSince1970))") + XCTAssertEqual(MeetingDiff.soonNotice(m, now: now).key, MeetingDiff.dueKey(m)) + } + + func testStartAlertReplacesTheHeadsUpAtAlertSeverity() { + let m = meeting("a", in: 10) + let soon = MeetingDiff.soonNotice(m, now: now) + let started = MeetingDiff.startNotice(m) + XCTAssertEqual(started.key, soon.key) + XCTAssertEqual(started.severity, .alert) + XCTAssertEqual(started.title, "Standup is starting now") + } + + func testStartAlertNeedsAHeadsUpAndFiresOnce() { + let m = meeting("a", in: 0) + let key = MeetingDiff.dueKey(m) + XCTAssertTrue(MeetingDiff.startDue([m], fired: [], started: [], now: now).isEmpty, "never warned, so no alert") + XCTAssertEqual(MeetingDiff.startDue([m], fired: [key], started: [], now: now).map(\.id), ["a"]) + XCTAssertTrue(MeetingDiff.startDue([m], fired: [key], started: [key], now: now).isEmpty) + XCTAssertTrue(MeetingDiff.startDue([m], fired: [key], started: [], now: now.addingTimeInterval(-1)).isEmpty) + XCTAssertTrue(MeetingDiff.startDue([m], fired: [key], started: [], now: now.addingTimeInterval(MeetingDiff.reminderTail)).isEmpty) + } + + func testReminderExpiresFiveMinutesAfterTheStart() { + let m = meeting("a", in: 0) + let key = MeetingDiff.dueKey(m) + XCTAssertTrue(MeetingDiff.expired([m], fired: [key], now: now.addingTimeInterval(299)).isEmpty) + XCTAssertEqual(MeetingDiff.expired([m], fired: [key], now: now.addingTimeInterval(300)).map(\.id), ["a"]) + XCTAssertTrue(MeetingDiff.expired([m], fired: [], now: now.addingTimeInterval(300)).isEmpty) + } + + func testNextReminderStepWalksStartThenExpiry() { + let m = meeting("a", in: 5) + let key = MeetingDiff.dueKey(m) + XCTAssertNil(MeetingDiff.nextReminderStep([m], fired: [], started: [], now: now)) + XCTAssertEqual(MeetingDiff.nextReminderStep([m], fired: [key], started: [], now: now), m.start) + XCTAssertEqual(MeetingDiff.nextReminderStep([m], fired: [key], started: [key], now: now), m.start.addingTimeInterval(300)) + XCTAssertNil(MeetingDiff.nextReminderStep([m], fired: [key], started: [key], now: m.start.addingTimeInterval(300))) + } + + func testLinkFallsBackToCalendarDeepLink() { + XCTAssertTrue(meeting("a").link.hasPrefix("ical://ekevent/a")) + var m = meeting("a") + m.joinUrl = "https://zoom.us/j/1" + XCTAssertEqual(m.link, "https://zoom.us/j/1") + } + + func testJoinUrlExtraction() { + XCTAssertEqual(MeetingDiff.joinUrl(in: [nil, "", "Join: https://meet.google.com/abc-defg-hij?authuser=0."]), + "https://meet.google.com/abc-defg-hij?authuser=0") + XCTAssertEqual(MeetingDiff.joinUrl(in: ["see https://acme.zoom.us/j/123456?pwd=x, ok"]), "https://acme.zoom.us/j/123456?pwd=x") + XCTAssertTrue(MeetingDiff.joinUrl(in: ["https://teams.microsoft.com/l/meetup-join/19%3a"]).contains("meetup-join")) + XCTAssertTrue(MeetingDiff.joinUrl(in: ["https://acme.webex.com/meet/ana"]).contains("webex.com")) + XCTAssertEqual(MeetingDiff.joinUrl(in: ["https://example.com/x"]), "") + } + + func testNotesSnippetIsOnePlainTruncatedLine() { + var m = meeting("a") + XCTAssertEqual(m.notesSnippet(), "") + m.notes = "

Agenda & goals

  • One
  • Two
" + XCTAssertEqual(m.notesSnippet(), "Agenda & goals - One - Two") + m.notes = String(repeating: "word ", count: 100) + XCTAssertEqual(m.notesSnippet(limit: 20).count, 20) + XCTAssertTrue(m.notesSnippet(limit: 20).hasSuffix("\u{2026}")) + } + + // MARK: Morning summary + + private var cal: Calendar { Calendar.current } + + // Local time, matching `clock`. 2026-10-21 is a Wednesday; 2026-10-24 a Saturday. + private func date(_ day: Int, _ hour: Int, _ minute: Int = 0) -> Date { + cal.date(from: DateComponents(year: 2026, month: 10, day: day, hour: hour, minute: minute))! + } + + private func at(_ day: Int, _ hour: Int, _ minute: Int, title: String) -> Meeting { + let start = date(day, hour, minute) + return Meeting(id: "\(title)\(day)\(hour)\(minute)", itemId: "x", title: title, start: start, + end: start.addingTimeInterval(1800), location: "", organizer: "", joinUrl: "", calendar: "Work") + } + + private func due(_ now: Date, _ s: SummarySettings = SummarySettings(), last: String? = nil) -> Bool { + MeetingDiff.summaryDue(now: now, settings: s, lastDate: last, calendar: cal) + } + + func testAgendaListsThreeThenCount() { + let three = [at(21, 10, 0, title: "Standup"), at(21, 11, 30, title: "Design review"), at(21, 14, 0, title: "1:1 with Sam")] + XCTAssertEqual(MeetingDiff.agenda(three), "10:00 Standup, 11:30 Design review, 14:00 1:1 with Sam") + let five = three + [at(21, 15, 0, title: "A"), at(21, 16, 0, title: "B")] + XCTAssertEqual(MeetingDiff.agenda(five), "10:00 Standup, 11:30 Design review, 14:00 1:1 with Sam, +2 more") + } + + func testSummaryNoticeCountsOnlyToday() throws { + let meetings = [at(21, 14, 0, title: "Late"), at(21, 10, 0, title: "Early"), at(22, 9, 0, title: "Tomorrow")] + let n = try XCTUnwrap(MeetingDiff.summaryNotice(meetings, now: date(21, 9), announceEmpty: false, calendar: cal)) + XCTAssertEqual(n.title, "Today: 2 meetings") + XCTAssertEqual(n.body, "10:00 Early, 14:00 Late") + XCTAssertEqual(n.kind, "meeting-summary") + XCTAssertEqual(n.severity, .info) + XCTAssertEqual(n.url, "ical://") + XCTAssertEqual(n.key, "meeting-summary:2026-10-21") + let one = try XCTUnwrap(MeetingDiff.summaryNotice([at(21, 10, 0, title: "Solo")], now: date(21, 9), announceEmpty: false, calendar: cal)) + XCTAssertEqual(one.title, "Today: 1 meeting") + } + + func testEmptyDaySkippedUnlessWanted() throws { + let tomorrow = [at(22, 9, 0, title: "Tomorrow")] + XCTAssertNil(MeetingDiff.summaryNotice(tomorrow, now: date(21, 9), announceEmpty: false, calendar: cal)) + let n = try XCTUnwrap(MeetingDiff.summaryNotice(tomorrow, now: date(21, 9), announceEmpty: true, calendar: cal)) + XCTAssertEqual(n.title, "No meetings today") + } + + func testSummaryDueWindow() { + XCTAssertFalse(due(date(21, 8, 59))) + XCTAssertTrue(due(date(21, 9, 0))) + XCTAssertTrue(due(date(21, 11, 59))) + XCTAssertFalse(due(date(21, 12, 0))) + XCTAssertFalse(due(date(21, 9, 0), SummarySettings(enabled: false))) + XCTAssertFalse(due(date(21, 9, 0), SummarySettings(minutes: 10 * 60))) + XCTAssertTrue(due(date(21, 10, 0), SummarySettings(minutes: 10 * 60))) + } + + func testSummaryOncePerDay() { + XCTAssertFalse(due(date(21, 9, 5), last: MeetingDiff.dayKey(date(21, 9), calendar: cal))) + XCTAssertTrue(due(date(21, 9, 5), last: "2026-10-20")) + } + + func testSummarySkipsWeekendsByDefault() { + XCTAssertFalse(due(date(24, 9, 5))) + XCTAssertTrue(due(date(24, 9, 5), SummarySettings(weekdaysOnly: false))) + } + + func testNextSummaryDueSchedulesAcrossDays() { + let s = SummarySettings() + func next(_ now: Date, _ s: SummarySettings = s, last: String? = nil) -> Date? { + MeetingDiff.nextSummaryDue(now: now, settings: s, lastDate: last, calendar: cal) + } + XCTAssertEqual(next(date(21, 7)), date(21, 9)) + XCTAssertEqual(next(date(21, 9, 30), last: "2026-10-21"), date(22, 9)) + XCTAssertEqual(next(date(21, 9, 30)), date(22, 9)) + XCTAssertEqual(next(date(23, 12)), date(26, 9)) + XCTAssertEqual(next(date(24, 8), SummarySettings(weekdaysOnly: false)), date(24, 9)) + XCTAssertNil(next(date(21, 7), SummarySettings(enabled: false))) + } +} diff --git a/Tests/StackNudgePanelCoreTests/MeetingLinksTests.swift b/Tests/StackNudgePanelCoreTests/MeetingLinksTests.swift new file mode 100644 index 00000000..e3cf446c --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/MeetingLinksTests.swift @@ -0,0 +1,57 @@ +import XCTest + +@testable import StackNudgePanelCore + +final class MeetingLinksTests: XCTestCase { + + func testClassifiesGoogleDocTypes() { + let text = """ + https://docs.google.com/document/d/abc/edit + https://docs.google.com/spreadsheets/d/def/edit#gid=0 + https://docs.google.com/presentation/d/ghi/edit + https://drive.google.com/file/d/jkl/view?usp=sharing + https://drive.google.com/drive/folders/mno + """ + let links = MeetingText.links(in: [text]) + XCTAssertEqual(links.docs.map(\.kind), [.doc, .sheet, .slides, .drive, .drive]) + XCTAssertTrue(links.others.isEmpty) + } + + func testExcludesJoinLinksAndCalendarChrome() { + let text = """ + Join: https://meet.google.com/abc-defg-hij + https://acme.zoom.us/j/12345?pwd=x + https://calendar.google.com/calendar/event?action=VIEW&eid=zzz + https://example.com/agenda + """ + let links = MeetingText.links(in: [text], joinUrl: "https://example.com/other") + XCTAssertTrue(links.docs.isEmpty) + XCTAssertEqual(links.others, ["https://example.com/agenda"]) + } + + func testExcludesTheJoinUrlItself() { + let links = MeetingText.links(in: ["https://example.com/room"], joinUrl: "https://example.com/room") + XCTAssertTrue(links.isEmpty) + } + + func testUnwrapsTrackingRedirects() { + let wrapped = "https://www.google.com/url?q=https://docs.google.com/document/d/abc/edit&sa=D&source=calendar" + let links = MeetingText.links(in: [wrapped]) + XCTAssertEqual(links.docs, [DocLink(kind: .doc, url: "https://docs.google.com/document/d/abc/edit")]) + } + + func testReadsHrefsDecodesEntitiesAndDedupes() { + let html = #"Sheet https://docs.google.com/spreadsheets/d/x/edit?a=1&b=2."# + let links = MeetingText.links(in: [html]) + XCTAssertEqual(links.docs, [DocLink(kind: .sheet, url: "https://docs.google.com/spreadsheets/d/x/edit?a=1&b=2")]) + } + + func testPlainTextStripsMarkupAndEntities() { + let html = "

Hello & welcome

  • One
  • Café A




Bye <3" + XCTAssertEqual(MeetingText.plain(html), "Hello & welcome\n- One\n- Café A\n\nBye <3") + } + + func testPlainTextCollapsesWhitespaceOnPlainNotes() { + XCTAssertEqual(MeetingText.plain(" a \t b \r\n\r\n\r\n\r\n c "), "a b\n\nc") + } +} diff --git a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift index 21486f7b..42b3cc5e 100644 --- a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift +++ b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift @@ -250,6 +250,51 @@ final class SettingsCategoryTests: XCTestCase { XCTAssertEqual(nav.selectedRow, .browseExtensions) } + func testTheCalendarCategoryFollowsIntegrationsAndHoldsItsRows() { + let all = SettingsCategory.allCases + XCTAssertEqual(SettingsCategory.calendar.label, "Calendar") + XCTAssertEqual(all.firstIndex(of: .calendar), all.firstIndex(of: .integrations).map { $0 + 1 }) + XCTAssertEqual(PanelNav().rows(in: .calendar), + [.calendarEnabled, .calendarLead, .calendarSummary, .calendarSummaryTime, + .calendarWeekdaysOnly, .calendarSummaryEmpty, .calendarDetectJoin]) + } + + // Every calendar row is a toggle or a cycle, so arrows act on it. + func testArrowsActOnEveryCalendarRow() { + let nav = PanelNav() + nav.settingsCategory = .calendar + for row in nav.rows(in: .calendar) { + nav.selectedSettingIndex = nav.index(of: row) ?? 0 + XCTAssertEqual(nav.selectedRow, row) + XCTAssertTrue(nav.selectedRowRespondsToArrows, "\(row)") + } + } + + func testCalendarDefaultsAreOffWithTheSummaryOnWeekdaysAtNine() { + let nav = PanelNav() + XCTAssertFalse(nav.calendarEnabled) + XCTAssertEqual(nav.calendarSettings, CalendarSettings()) + XCTAssertEqual(nav.calendarSettings.leadMinutes, 10) + XCTAssertEqual(nav.calendarSettings.summary.minutes, 9 * 60) + XCTAssertTrue(nav.calendarSettings.summary.weekdaysOnly) + XCTAssertTrue(nav.calendarSettings.detectJoin) + XCTAssertTrue(nav.calendarSettings.calendarIds.isEmpty) + } + + func testSummaryTimeSnapsToTheNearestOfferedTime() { + XCTAssertEqual(PanelNav.summaryMinutes("09:00"), 9 * 60) + XCTAssertEqual(PanelNav.summaryMinutes("8:30"), 8 * 60 + 30) + XCTAssertEqual(PanelNav.summaryMinutes("09:20"), 9 * 60 + 30) + XCTAssertEqual(PanelNav.summaryMinutes("noon"), 9 * 60) + XCTAssertEqual(PanelNav.summaryMinutes(nil), 9 * 60) + } + + func testCalendarSelectionIsACommaSeparatedListWhereEmptyMeansAll() { + XCTAssertEqual(PanelNav.calendarIds("A1, B2 ,,C3"), ["A1", "B2", "C3"]) + XCTAssertTrue(PanelNav.calendarIds("").isEmpty) + XCTAssertTrue(PanelNav.calendarIds(nil).isEmpty) + } + private func row(_ id: String) -> ExtensionRow { ExtensionRow(id: id, name: id, description: "", installedVersion: "1.0.0", availableVersion: nil, refusedReason: nil, requires: [], config: []) diff --git a/docs/notifications.md b/docs/notifications.md index 4ddaed5a..91be4832 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -71,6 +71,28 @@ 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`. +## Calendar + +**Meetings in the Events tab.** Off by default. Turn on Settings → **Calendar** and stack-nudge reads the calendars synced into Calendar.app (Google, iCloud, Exchange and so on) through EventKit. macOS asks for calendar access the first time, and only then. Everything is read locally; nothing is sent anywhere. + +- **Heads-up.** One row per meeting, ` starts in N min`, at the lead time you set. At the start it is replaced by `<title> is starting now`, in the alert colour. ⏎ opens the meeting link (Meet, Zoom, Teams, Webex), else the event in Calendar.app. The row goes away when you join, or five minutes after the start. +- **Changes.** A meeting added, moved, renamed, relocated or cancelled gets its own row. A change to a meeting starting within 24 hours is flagged for action. A meeting missing for under five minutes is not called cancelled, because a calendar re-sync can drop events briefly. +- **Morning summary.** One row on weekdays, `Today: 3 meetings`, listing the first three. It is sent at the set time, or on the first refresh after it if the Mac was asleep, but never after noon. +- **Join detection.** From five minutes before the start, stack-nudge checks every 15 seconds whether you are already in the meeting: an open Meet tab in a running browser (read with `osascript`), Zoom's `CptHost` helper process, or a Teams window titled "meeting". If so, the heads-up is removed. Reading browser tabs needs the Automation permission for each browser, which macOS asks for the first time; refuse it and the row simply stays until it expires. Teams window titles are only readable with Screen Recording granted, so Teams detection is best effort. + +| Setting | Key | Default | +|---|---|---| +| Calendar | `STACKNUDGE_CALENDAR` | off | +| Heads-up before meetings | `STACKNUDGE_CALENDAR_LEAD_MIN` | `10` (5, 10 or 15) | +| Morning summary | `STACKNUDGE_CALENDAR_SUMMARY` | on | +| Summary time | `STACKNUDGE_CALENDAR_SUMMARY_TIME` | `09:00` (08:00 to 10:00, half-hourly) | +| Weekdays only | `STACKNUDGE_CALENDAR_WEEKDAYS_ONLY` | on | +| Summary on empty days | `STACKNUDGE_CALENDAR_SUMMARY_EMPTY` | off | +| Detect joining (Automation) | `STACKNUDGE_CALENDAR_JOIN` | on, when Calendar is on | +| Calendars to watch | `STACKNUDGE_CALENDARS` | empty, meaning all. Comma-separated calendar identifiers, listed in `calendar.log` when access is first granted; config file only, there is no picker | + +All-day events and meetings you have declined are ignored. If access is refused, the Calendar row says so; allow it under System Settings → Privacy & Security → Calendars. The last snapshot and a short log are kept in `~/.stack-nudge/calendar.json` and `calendar.log`, join checks log to `join.log`. + ## 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 510fea9f..837f1e48 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -157,6 +157,7 @@ Reachable from the tab strip, `Cmd+,`, or the last `Cmd`-number. A sidebar of ca | **Companion** | Size, Count badge, Preview pose, Reset position; **Turn on companion** while it's off. See [Companion](#companion) | | **Usage** | Quota tracking, Quota alerts, Alert threshold, Poll frequency, Context alert, Show remaining, and the two pi budgets | | **Integrations** | A card each for Slack and GitHub, with where it stands on the right; `→` or `⏎` opens its page. Slack's: paste setup, detected user, test message, on/off, idle threshold, message text, finished turns. GitHub's: PR links, GitHub activity, Hide shipped, Connect GitHub (or Disconnect once signed in). Each page's first line says what it's doing or what's wrong | +| **Calendar** | Calendar, Heads-up before meetings, Morning summary, Summary time, Weekdays only, Summary on empty days, Detect joining (see [notifications.md](notifications.md#calendar)) | | **Extensions** | What's installed, then **Browse extensions** (see [Extensions](#extensions)) | | **MCP** | **Set up for…**, whose page has a card each for Claude Code, Claude Desktop and Codex: `⏎` copies what adds stack-nudge to it, and a tick shows once its config has it. Then MCP clients can change settings. See [the local MCP server](design/local-mcp.md) | | **Panel** | Hotkey, Pin panel, Keep open when empty, Launch at login, Name from tab titles | diff --git a/notify.conf.example b/notify.conf.example index ac126dbe..cfe66f3c 100644 --- a/notify.conf.example +++ b/notify.conf.example @@ -130,6 +130,37 @@ STACKNUDGE_FLOATING_WIDGET=companion #STACKNUDGE_PI_API_BUDGET=1500000 #STACKNUDGE_PI_LOCAL_BUDGET=500000 +# Meetings from your calendar (Calendar.app, read locally through EventKit; +# nothing is sent anywhere). Turning it on asks macOS for calendar access. +# Also settable in Settings → Calendar, which writes back here. +# Default: false +#STACKNUDGE_CALENDAR=true + +# Minutes before a meeting for the heads-up. 5, 10 or 15. +# Default: 10 +#STACKNUDGE_CALENDAR_LEAD_MIN=10 + +# Morning summary of today's meetings: on/off, the time (08:00 to 10:00 in +# half hours), weekdays only, and whether a day with no meetings gets one too. +# A summary missed because the Mac was asleep is still sent until noon. +# Defaults: true, 09:00, true, false +#STACKNUDGE_CALENDAR_SUMMARY=true +#STACKNUDGE_CALENDAR_SUMMARY_TIME=09:00 +#STACKNUDGE_CALENDAR_WEEKDAYS_ONLY=true +#STACKNUDGE_CALENDAR_SUMMARY_EMPTY=false + +# Clear a meeting's reminder when you have joined it: an open Meet tab in a +# running browser, Zoom's helper process, a Teams meeting window. Reading +# browser tabs needs the Automation permission for each browser. +# Default: true (when the calendar is on) +#STACKNUDGE_CALENDAR_JOIN=true + +# Which calendars to watch, as comma-separated calendar identifiers. Empty +# watches all of them. There is no picker: ~/.stack-nudge/calendar.log lists +# every calendar's identifier the first time access is granted. +# Default: empty +#STACKNUDGE_CALENDARS= + # Log a debug line (to the launchd log) explaining voice decisions — useful # when a notification played silently and you want to know why. # Default: false diff --git a/panel/CalendarWatcher.swift b/panel/CalendarWatcher.swift new file mode 100644 index 00000000..d6f04d96 --- /dev/null +++ b/panel/CalendarWatcher.swift @@ -0,0 +1,326 @@ +import AppKit +import EventKit +import Foundation + +// What the watcher reads from Settings, as one value so a change is one comparison. +struct CalendarSettings: Equatable { + var leadMinutes = 10 + var summary = SummarySettings() + var detectJoin = true + // Calendar identifiers to watch; empty means every calendar. + var calendarIds: [String] = [] + + static let leadOptions = [5, 10, 15] +} + +enum CalendarAccess: Equatable { + case granted, notDetermined, denied +} + +// Persisted as ~/.stack-nudge/calendar.json. +struct CalendarState: Codable { + var version = 1 + var updatedAt: Date + var calendars: String + var events: [Meeting] + var soonFired: [String] + // Meetings whose start alert went out, or that were joined before it did. + var startFired: [String]? = nil + // Day key (yyyy-MM-dd) of the last morning summary, sent or skipped for having no meetings. + var summaryDate: String? = nil + // Meetings missing since a refresh, held in `events` until `MeetingDiff.cancelGrace` confirms the cancellation. + var missingSince: [String: Date]? = nil +} + +// Mirrors the user's synced calendars from EventKit into meeting events. +// Read-only and local: no calendar API, nothing leaves the Mac. Main thread only. +final class CalendarWatcher { + private static let window: TimeInterval = 7 * 24 * 3600 + private static let notesCap = 8000 + private static let staleAfter: TimeInterval = 24 * 3600 + + private let events: EventStore + private let settings: () -> CalendarSettings + private let clock: () -> Date + private let stateDir: String + private let onToday: ([Meeting]) -> Void + private let onAccess: (CalendarAccess) -> Void + private var joinWatcher: JoinWatcher! + // Lazy so that building the watcher never touches the calendar; EventKit is + // first reached from start(), i.e. once the user has turned the feature on. + private lazy var ek = EKEventStore() + private var statePath: String { stateDir + "/calendar.json" } + private var logPath: String { stateDir + "/calendar.log" } + + private var state: CalendarState? + private var started = false + private var requested = false + private var observer: NSObjectProtocol? + private var refreshTimer: Timer? + private var soonTimer: Timer? + private var debounce: DispatchWorkItem? + private(set) var granted = false + private(set) var access: CalendarAccess = .notDetermined + + init(events: EventStore, settings: @escaping () -> CalendarSettings, + clock: @escaping () -> Date = { Date() }, + stateDir: String = NSHomeDirectory() + "/.stack-nudge", + detector: JoinDetector = SystemJoinDetector(), + background: @escaping JoinWatcher.Background = { work in DispatchQueue.global(qos: .utility).async(execute: work) }, + deliver: @escaping JoinWatcher.Deliver = { work in DispatchQueue.main.async(execute: work) }, + autoSchedule: Bool = true, + onToday: @escaping ([Meeting]) -> Void = { _ in }, + onAccess: @escaping (CalendarAccess) -> Void = { _ in }) { + self.events = events; self.settings = settings; self.clock = clock; self.stateDir = stateDir + self.onToday = onToday; self.onAccess = onAccess + joinWatcher = JoinWatcher( + detector: detector, clock: clock, enabled: { [weak self] in self?.settings().detectJoin ?? false }, + background: background, deliver: deliver, autoSchedule: autoSchedule, + onJoined: { [weak self] in self?.joined($0) }) + } + + func start() { + guard !started else { return } + started = true + state = loadState() + observer = NotificationCenter.default.addObserver(forName: .EKEventStoreChanged, object: ek, queue: .main) { [weak self] _ in + self?.scheduleRefresh() + } + checkAccess() + refreshTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in self?.tick() } + refreshTimer?.tolerance = 10 + } + + func stop() { + guard started else { return } + started = false + if let observer { NotificationCenter.default.removeObserver(observer) } + observer = nil + refreshTimer?.invalidate() + refreshTimer = nil + soonTimer?.invalidate() + soonTimer = nil + debounce?.cancel() + debounce = nil + joinWatcher.sync([]) + onToday([]) + } + + // A setting changed: re-read the calendar so the new lead time, summary and selection apply now. + func settingsChanged() { + guard started else { return } + tick() + } + + // MARK: Access + + private func checkAccess() { + let status = EKEventStore.authorizationStatus(for: .event) + let ok: Bool + if #available(macOS 14.0, *) { ok = status == .fullAccess } else { ok = status == .authorized } + let next: CalendarAccess = ok ? .granted : status == .notDetermined ? .notDetermined : .denied + if next != access { + log("access \(next) (raw \(status.rawValue))") + // The identifiers STACKNUDGE_CALENDARS takes; there is no picker to read them from. + if ok { log("calendars: " + ek.calendars(for: .event).map { "\($0.title) [\($0.source.title)] id=\($0.calendarIdentifier)" }.joined(separator: "; ")) } + access = next + onAccess(next) + } + granted = ok + if ok { + refresh() + } else if status == .notDetermined, !requested { + requested = true + requestAccess() + } + } + + private func requestAccess() { + Task { @MainActor in + do { + if #available(macOS 14.0, *) { + _ = try await ek.requestFullAccessToEvents() + } else { + _ = try await ek.requestAccess(to: .event) + } + } catch { + log("access request failed: \(error.localizedDescription)") + } + ek.reset() + if started { checkAccess() } + } + } + + // MARK: Calendars + + var calendars: [EKCalendar] { + granted ? ek.calendars(for: .event).sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == .orderedAscending } : [] + } + + // MARK: Refresh + + private func tick() { + if granted { refresh() } else { checkAccess() } + } + + private func scheduleRefresh() { + debounce?.cancel() + let work = DispatchWorkItem { [weak self] in self?.tick() } + debounce = work + DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: work) + } + + private func snapshot(now: Date, calendars: [EKCalendar]) -> [Meeting] { + guard !calendars.isEmpty else { return [] } + // From midnight, so today's finished meetings stay available to a view of the day. + let predicate = ek.predicateForEvents(withStart: Calendar.current.startOfDay(for: now), end: now.addingTimeInterval(Self.window), calendars: calendars) + var seen = Set<String>() + return ek.events(matching: predicate).compactMap { e -> Meeting? in + guard !e.isAllDay, e.status != .canceled, e.startDate != nil, e.endDate != nil else { return nil } + if e.attendees?.contains(where: { $0.isCurrentUser && $0.participantStatus == .declined }) == true { return nil } + let itemId = e.calendarItemIdentifier + let recurring = e.hasRecurrenceRules || e.isDetached + let occurrence = e.occurrenceDate ?? e.startDate! + let id = recurring ? "\(itemId)@\(Int(occurrence.timeIntervalSince1970))" : itemId + guard seen.insert(id).inserted else { return nil } + return Meeting( + id: id, itemId: itemId, title: e.title ?? "(no title)", start: e.startDate, end: e.endDate, + location: e.location ?? "", organizer: Self.organizer(e), + joinUrl: MeetingDiff.joinUrl(in: [e.url?.absoluteString, e.location, e.notes]), + calendar: e.calendar.title, created: e.creationDate, + notes: e.notes.map { String($0.prefix(Self.notesCap)) }, eventUrl: e.url?.absoluteString, attendeeCount: e.attendees?.count) + }.sorted { $0.start < $1.start }.dedupedByOccurrence() + } + + private static func organizer(_ e: EKEvent) -> String { + guard let o = e.organizer else { return "" } + if let name = o.name, !name.isEmpty { return name } + return o.url.absoluteString.replacingOccurrences(of: "mailto:", with: "") + } + + private func refresh() { + guard granted else { return } + let ids = Set(settings().calendarIds) + let selected = calendars.filter { ids.isEmpty || ids.contains($0.calendarIdentifier) } + let signature = selected.map(\.calendarIdentifier).sorted().joined(separator: ",") + let now = clock() + apply(current: snapshot(now: now, calendars: selected), signature: signature, now: now) + } + + // Everything after the calendar has been read: diffs, reminders, the summary and the join check. + func apply(current: [Meeting], signature: String, now: Date) { + let s = settings() + let lead = TimeInterval(s.leadMinutes * 60) + + // The first run, a changed calendar selection or a long gap rebases silently instead of flooding. + let previous = state.flatMap { $0.calendars == signature && now.timeIntervalSince($0.updatedAt) < Self.staleAfter ? $0 : nil } + let missingSince = state?.missingSince ?? [:] + let notices = previous.map { MeetingDiff.diff(old: $0.events, new: current, now: now, since: $0.updatedAt, missingSince: missingSince) } ?? [] + let held = previous.map { MeetingDiff.held(old: $0.events, new: current, now: now, missingSince: missingSince) } ?? [:] + let heldMeetings = previous?.events.filter { held[$0.id] != nil } ?? [] + + // A reminder for a meeting that was moved, cancelled or dropped goes with it. + let live = Set(current.map(MeetingDiff.dueKey)) + let firedBefore = Set(state?.soonFired ?? []) + for key in firedBefore.subtracting(live) { events.remove(key: key) } + var fired = firedBefore.intersection(live) + var startFired = Set(state?.startFired ?? []).intersection(live) + + for n in notices { emit(n, now: now) } + for m in MeetingDiff.due(current, fired: fired, lead: lead, now: now) { + emit(MeetingDiff.soonNotice(m, now: now), now: now) + fired.insert(MeetingDiff.dueKey(m)) + } + for m in MeetingDiff.startDue(current, fired: fired, started: startFired, now: now) { + emit(MeetingDiff.startNotice(m), now: now) + startFired.insert(MeetingDiff.dueKey(m)) + } + for m in MeetingDiff.expired(current, fired: fired, now: now) { events.remove(key: MeetingDiff.dueKey(m)) } + + var summaryDate = state?.summaryDate + if MeetingDiff.summaryDue(now: now, settings: s.summary, lastDate: summaryDate) { + if let n = MeetingDiff.summaryNotice(current, now: now, announceEmpty: s.summary.announceEmpty) { emit(n, now: now) } + summaryDate = MeetingDiff.dayKey(now) + } + + onToday(MeetingDiff.todaysMeetings(current, now: now)) + state = CalendarState(updatedAt: now, calendars: signature, events: current + heldMeetings, soonFired: fired.sorted(), + startFired: startFired.isEmpty ? nil : startFired.sorted(), summaryDate: summaryDate, + missingSince: held.isEmpty ? nil : held) + saveState() + joinWatcher.sync(current.filter { fired.contains(MeetingDiff.dueKey($0)) } + .map { JoinCandidate(id: MeetingDiff.dueKey($0), url: $0.joinUrl, start: $0.start) }) + scheduleNext(current, fired: fired, startFired: startFired, summaryDate: summaryDate, settings: s, now: now) + if previous == nil || !notices.isEmpty { + log("refresh: \(current.count) meetings, \(notices.count) changes\(previous == nil ? " (seed)" : "")") + } + } + + // One timer for whatever is due next: a heads-up, a start alert, an expiry, + // the summary, or the moment a join check opens. + private func scheduleNext(_ meetings: [Meeting], fired: Set<String>, startFired: Set<String>, summaryDate: String?, settings s: CalendarSettings, now: Date) { + soonTimer?.invalidate() + soonTimer = nil + let joinChecks = meetings.filter { fired.contains(MeetingDiff.dueKey($0)) && !$0.joinUrl.isEmpty } + .map { $0.start.addingTimeInterval(-JoinWatcher.lead) }.filter { $0 > now }.min() + let candidates = [ + MeetingDiff.nextDue(meetings, fired: fired, lead: TimeInterval(s.leadMinutes * 60), now: now), + MeetingDiff.nextReminderStep(meetings, fired: fired, started: startFired, now: now), + MeetingDiff.nextSummaryDue(now: now, settings: s.summary, lastDate: summaryDate), + joinChecks, + ] + guard let next = candidates.compactMap({ $0 }).min() else { return } + soonTimer = Timer.scheduledTimer(withTimeInterval: max(1, next.timeIntervalSince(now)), repeats: false) { [weak self] _ in + self?.tick() + } + } + + private func emit(_ n: MeetingNotice, now: Date) { + events.append(n.event(now: now)) + } + + // MARK: Joining + + private func joined(_ c: JoinCandidate) { + events.remove(key: c.id) + // Recorded so the start alert does not come back for a meeting already joined. + let keys = Set(state?.startFired ?? []).union([c.id]) + state?.startFired = keys.sorted() + saveState() + } + + // MARK: Persistence + + private static var encoder: JSONEncoder { + let e = JSONEncoder() + e.dateEncodingStrategy = .iso8601 + e.outputFormatting = [.prettyPrinted, .sortedKeys] + return e + } + + private func loadState() -> CalendarState? { + guard let data = FileManager.default.contents(atPath: statePath) else { return nil } + let d = JSONDecoder() + d.dateDecodingStrategy = .iso8601 + return try? d.decode(CalendarState.self, from: data) + } + + private func saveState() { + guard let state, let data = try? Self.encoder.encode(state) else { return } + try? FileManager.default.createDirectory(atPath: stateDir, withIntermediateDirectories: true) + try? data.write(to: URL(fileURLWithPath: statePath), options: .atomic) + } + + private func log(_ line: String) { + let stamp = ISO8601DateFormatter().string(from: Date()) + guard let data = "\(stamp) \(line)\n".data(using: .utf8) else { return } + try? FileManager.default.createDirectory(atPath: stateDir, withIntermediateDirectories: true) + if let h = FileHandle(forWritingAtPath: logPath) { + h.seekToEndOfFile() + h.write(data) + try? h.close() + } else { + try? data.write(to: URL(fileURLWithPath: logPath)) + } + } +} diff --git a/panel/EventStore.swift b/panel/EventStore.swift index 33a17e9c..06b49f42 100644 --- a/panel/EventStore.swift +++ b/panel/EventStore.swift @@ -381,6 +381,7 @@ final class EventStore: ObservableObject { && existing.agent == event.agent && existing.kind == event.kind && existing.source == event.source + // Two meetings starting together differ only in their title. && existing.title == event.title && existing.message == event.message && existing.claudeSessionID == event.claudeSessionID @@ -635,6 +636,13 @@ final class EventStore: ObservableObject { FeedTagFilter.present(in: events) } + // Drops a feed event by its key, for a feed that knows its own event is + // stale (a meeting reminder once the meeting is joined). Agent events have + // no key, so none can be removed this way. + func remove(key: String) { + for id in events.filter({ $0.isFeed && $0.key == key }).map(\.id) { remove(id: id) } + } + // Replace the event in-place with a new copy that has snoozedUntil set // (or cleared with nil). Triggers SwiftUI updates because @Published. func setSnoozedUntil(id: NudgeEvent.ID, _ until: Date?) { diff --git a/panel/Info.plist b/panel/Info.plist index e1e259e0..aea0778c 100644 --- a/panel/Info.plist +++ b/panel/Info.plist @@ -27,6 +27,10 @@ <key>NSBluetoothAlwaysUsageDescription</key> <string>StackNudge listens for your phone's Bluetooth signal to tell when you've stepped away from your Mac, if you install the Away extension.</string> <key>NSAppleEventsUsageDescription</key> - <string>StackNudge uses System Events to focus the correct window when you act on a notification.</string> + <string>StackNudge uses System Events to focus the correct window when you act on a notification, and, if you turn on calendar join detection, reads the open tab addresses of your browser to see whether you have joined a meeting.</string> + <key>NSCalendarsFullAccessUsageDescription</key> + <string>StackNudge reads your calendar on this Mac to remind you before meetings and to tell you when one is added, moved or cancelled. Nothing leaves your Mac.</string> + <key>NSCalendarsUsageDescription</key> + <string>StackNudge reads your calendar on this Mac to remind you before meetings and to tell you when one is added, moved or cancelled. Nothing leaves your Mac.</string> </dict> </plist> diff --git a/panel/JoinDetector.swift b/panel/JoinDetector.swift new file mode 100644 index 00000000..937e1454 --- /dev/null +++ b/panel/JoinDetector.swift @@ -0,0 +1,207 @@ +import AppKit +import Foundation + +enum JoinState: Equatable { + case joined, notJoined, unknown +} + +// Answers "is the user in this meeting right now?" from its join link. `check` blocks, so call it off the main thread. +protocol JoinDetector: Sendable { + func check(url: String) -> JoinState +} + +// What a join link points at, reduced to what can be recognised on this Mac. +enum JoinTarget: Equatable { + case meet(code: String) + case zoom(id: String?) + case teams + case unsupported + + private static func first(_ pattern: String, in text: String) -> String? { + guard let re = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]), + let m = re.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)), + m.numberOfRanges > 1, let r = Range(m.range(at: 1), in: text) else { return nil } + return String(text[r]).lowercased() + } + + // The code after meet.google.com/, past an optional `/u/N` account prefix and the `/meet/` segment newer Meet tabs + // carry (`meet.google.com/meet/abc-defg-hij`); query and fragment are ignored. + static func meetCode(in url: String) -> String? { + guard let code = first(#"https?://meet\.google\.com/(?:u/\d+/)?(?:meet/)?([a-z0-9][a-z0-9-]*)"#, in: url), + !["landing", "new", "home", "meet"].contains(code) else { return nil } + return code + } + + // The numeric meeting id of `/j/<id>`, `/wc/<id>/...` and `/wc/join/<id>` links. + static func zoomId(in url: String) -> String? { + first(#"zoom\.(?:us|com)/(?:j/|wc/(?:join/)?)(\d{8,12})"#, in: url) + } + + static func of(_ url: String) -> JoinTarget { + if let code = meetCode(in: url) { return .meet(code: code) } + if url.range(of: #"https?://[\w.-]*zoom\.(?:us|com)/"#, options: [.regularExpression, .caseInsensitive]) != nil { return .zoom(id: zoomId(in: url)) } + if url.range(of: #"https?://teams\.(?:microsoft|live)\.com/"#, options: [.regularExpression, .caseInsensitive]) != nil { return .teams } + return .unsupported + } + + // A tab that shows this meeting, which for Meet includes the lobby. + func matches(tab: String) -> Bool { + switch self { + case .meet(let code): return Self.meetCode(in: tab) == code + case .zoom(let id): return id != nil && Self.zoomId(in: tab) == id + case .teams: + return tab.range(of: #"https?://teams\.(?:microsoft|live)\.com/.*(?:meetingjoin|pre-join|calling)"#, options: [.regularExpression, .caseInsensitive]) != nil + case .unsupported: return false + } + } +} + +enum TabRead: Equatable { + case urls([String]) + case denied + case failed +} + +enum JoinDecision { + // A meeting that was not found is `notJoined` only when everything that could show it was readable. + static func decide(_ target: JoinTarget, reads: [TabRead], zoomInMeeting: Bool, teamsWindow: Bool) -> JoinState { + let tabs = reads.flatMap { read -> [String] in if case .urls(let u) = read { return u } else { return [] } } + let unreadable = reads.contains { !$0.isUrls } + switch target { + case .unsupported: return .unknown + case .meet: + if tabs.contains(where: target.matches) { return .joined } + return reads.contains { $0.isUrls } ? .notJoined : .unknown + case .zoom: + if zoomInMeeting || tabs.contains(where: target.matches) { return .joined } + return unreadable ? .unknown : .notJoined + case .teams: + if teamsWindow || tabs.contains(where: target.matches) { return .joined } + return reads.contains { $0.isUrls } ? .notJoined : .unknown + } + } +} + +private extension TabRead { + var isUrls: Bool { if case .urls = self { return true } else { return false } } +} + +// Reads the Mac: browser tabs through AppleScript, Zoom and Teams through their processes and windows. +struct SystemJoinDetector: JoinDetector { + static let browsers: [(name: String, bundleId: String)] = [ + ("Google Chrome", "com.google.Chrome"), ("Arc", "company.thebrowser.Browser"), ("Safari", "com.apple.Safari"), + ("Brave", "com.brave.Browser"), ("Microsoft Edge", "com.microsoft.edgemac"), ("Vivaldi", "com.vivaldi.Vivaldi"), + ("Opera", "com.operasoftware.Opera"), ("Chromium", "org.chromium.Chromium"), + ] + + private static let scriptTimeout: TimeInterval = 8 + private static let denialLogged = Locked(false) + + func check(url: String) -> JoinState { + let target = JoinTarget.of(url) + guard target != .unsupported else { return .unknown } + var reads: [TabRead] = [] + if target != .zoom(id: nil) { + let running = Set(NSWorkspace.shared.runningApplications.compactMap(\.bundleIdentifier)) + reads = Self.browsers.filter { running.contains($0.bundleId) }.map { Self.tabs(of: $0.bundleId, name: $0.name) } + } + let zoom = target.isZoom && Self.processExists("CptHost") + let teams = target == .teams && Self.teamsMeetingWindow() + return JoinDecision.decide(target, reads: reads, zoomInMeeting: zoom, teamsWindow: teams) + } + + private static func tabs(of bundleId: String, name: String) -> TabRead { + let script = "tell application id \"\(bundleId)\" to get URL of tabs of windows" + guard let (status, out, err) = run("/usr/bin/osascript", ["-ss", "-e", script], timeout: scriptTimeout) else { + JoinLog.write("\(name): tab read timed out") + return .failed + } + guard status == 0 else { + if err.contains("-1743") { + if denialLogged.setOnce() { JoinLog.write("\(name): browser access denied, join detection falls back to the clock only") } + return .denied + } + JoinLog.write("\(name): tab read failed: \(err.trimmingCharacters(in: .whitespacesAndNewlines))") + return .failed + } + let re = try? NSRegularExpression(pattern: #""([^"]*)""#) + let urls = re?.matches(in: out, range: NSRange(out.startIndex..., in: out)).compactMap { m in + Range(m.range(at: 1), in: out).map { String(out[$0]) } + } ?? [] + return .urls(urls) + } + + private static func processExists(_ name: String) -> Bool { + run("/usr/bin/pgrep", ["-x", name], timeout: 2)?.status == 0 + } + + // Window titles are only readable with Screen Recording; without it this answers false. + private static func teamsMeetingWindow() -> Bool { + let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] ?? [] + return list.contains { w in + (w[kCGWindowOwnerName as String] as? String)?.contains("Teams") == true + && (w[kCGWindowName as String] as? String)?.range(of: "meeting", options: .caseInsensitive) != nil + } + } + + private static func run(_ path: String, _ args: [String], timeout: TimeInterval) -> (status: Int32, out: String, err: String)? { + let p = Process() + p.executableURL = URL(fileURLWithPath: path) + p.arguments = args + let out = Pipe(), err = Pipe() + p.standardOutput = out + p.standardError = err + let done = DispatchSemaphore(value: 0) + p.terminationHandler = { _ in done.signal() } + do { try p.run() } catch { return nil } + // Reading to EOF first keeps a large tab list from filling the pipe and stalling the child. + var outData = Data(), errData = Data() + let group = DispatchGroup() + group.enter() + DispatchQueue.global().async { outData = out.fileHandleForReading.readDataToEndOfFile(); group.leave() } + group.enter() + DispatchQueue.global().async { errData = err.fileHandleForReading.readDataToEndOfFile(); group.leave() } + if done.wait(timeout: .now() + timeout) == .timedOut { + p.terminate() + return nil + } + group.wait() + return (p.terminationStatus, String(decoding: outData, as: UTF8.self), String(decoding: errData, as: UTF8.self)) + } +} + +private extension JoinTarget { + var isZoom: Bool { if case .zoom = self { return true } else { return false } } +} + +// One flag behind a lock, for "log this once". +final class Locked: @unchecked Sendable { + private var value: Bool + private let lock = NSLock() + init(_ value: Bool) { self.value = value } + + // True the first time only. + func setOnce() -> Bool { + lock.lock() + defer { lock.unlock() } + let first = !value + value = true + return first + } +} + +enum JoinLog { + static func write(_ line: String) { + let dir = NSHomeDirectory() + "/.stack-nudge" + let path = dir + "/join.log" + guard let data = "\(ISO8601DateFormatter().string(from: Date())) \(line)\n".data(using: .utf8) else { return } + try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + if let h = FileHandle(forWritingAtPath: path) { + h.seekToEndOfFile() + h.write(data) + try? h.close() + } else { + try? data.write(to: URL(fileURLWithPath: path)) + } + } +} diff --git a/panel/JoinWatcher.swift b/panel/JoinWatcher.swift new file mode 100644 index 00000000..1e93a9f4 --- /dev/null +++ b/panel/JoinWatcher.swift @@ -0,0 +1,109 @@ +import Foundation + +// A reminder worth checking: its queue key, the link to look for, and the start. +struct JoinCandidate: Equatable { + let id: String + let url: String + let start: Date +} + +// Polls a detector for the meeting reminders inside their check window and +// reports who joined. Main thread only. +final class JoinWatcher { + typealias Background = (@escaping @Sendable () -> Void) -> Void + typealias Deliver = (@escaping @Sendable () -> Void) -> Void + + static let interval: TimeInterval = 15 + static let lead: TimeInterval = 300 + static let tail: TimeInterval = 300 + + private let detector: JoinDetector + private let clock: () -> Date + private let enabled: () -> Bool + private let background: Background + private let deliver: Deliver + private let autoSchedule: Bool + private let onJoined: (JoinCandidate) -> Void + private let onNotJoined: (JoinCandidate) -> Void + + private var candidates: [String: JoinCandidate] = [:] + private var lastCheck: [String: Date] = [:] + private var inFlight: Set<String> = [] + private var joined: Set<String> = [] + private var reportedAfterStart: Set<String> = [] + private var timer: Timer? + + init(detector: JoinDetector, clock: @escaping () -> Date = { Date() }, enabled: @escaping () -> Bool = { true }, + background: @escaping Background = { work in DispatchQueue.global(qos: .utility).async(execute: work) }, + deliver: @escaping Deliver = { work in DispatchQueue.main.async(execute: work) }, + autoSchedule: Bool = true, + onJoined: @escaping (JoinCandidate) -> Void, + onNotJoined: @escaping (JoinCandidate) -> Void = { _ in }) { + self.detector = detector; self.clock = clock; self.enabled = enabled; self.background = background; self.deliver = deliver + self.autoSchedule = autoSchedule; self.onJoined = onJoined; self.onNotJoined = onNotJoined + } + + // Reminders worth checking: a join link, and from 5 minutes before the start to 5 minutes after. + static func inWindow(_ c: JoinCandidate, at now: Date) -> Bool { + guard MeetingDiff.isJoinUrl(c.url) else { return false } + return now >= c.start.addingTimeInterval(-lead) && now < c.start.addingTimeInterval(tail) + } + + // Called with the live reminders whenever the calendar refreshes. + func sync(_ reminders: [JoinCandidate]) { + let now = clock() + let live = enabled() ? reminders.filter { Self.inWindow($0, at: now) && !joined.contains($0.id) } : [] + candidates = Dictionary(live.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) + lastCheck = lastCheck.filter { candidates[$0.key] != nil } + if candidates.isEmpty { + timer?.invalidate() + timer = nil + return + } + poll() + if autoSchedule, timer == nil { + let t = Timer.scheduledTimer(withTimeInterval: Self.interval, repeats: true) { [weak self] _ in + self?.poll() + } + t.tolerance = 2 + timer = t + } + } + + // Checks every candidate not checked in the last interval; a candidate whose window has passed is dropped. + func poll() { + let now = clock() + candidates = candidates.filter { Self.inWindow($0.value, at: now) } + if candidates.isEmpty || !enabled() { + candidates = [:] + timer?.invalidate() + timer = nil + return + } + for (id, candidate) in candidates where !inFlight.contains(id) && now.timeIntervalSince(lastCheck[id] ?? .distantPast) >= Self.interval { + lastCheck[id] = now + inFlight.insert(id) + let (detector, deliver, url) = (detector, deliver, candidate.url) + let finish: @Sendable (JoinState) -> Void = { [weak self] state in self?.finish(candidate, state) } + background { + let state = detector.check(url: url) + deliver { finish(state) } + } + } + } + + private func finish(_ candidate: JoinCandidate, _ state: JoinState) { + inFlight.remove(candidate.id) + guard candidates[candidate.id] != nil else { return } + switch state { + case .joined: + joined.insert(candidate.id) + candidates[candidate.id] = nil + onJoined(candidate) + case .notJoined: + if clock() >= candidate.start, reportedAfterStart.insert(candidate.id).inserted { onNotJoined(candidate) } + case .unknown: + break + } + } +} diff --git a/panel/Meeting.swift b/panel/Meeting.swift new file mode 100644 index 00000000..c407b79e --- /dev/null +++ b/panel/Meeting.swift @@ -0,0 +1,315 @@ +import Foundation + +// One upcoming meeting occurrence. `id` is the calendar item plus the original +// occurrence start for recurring events. +struct Meeting: Codable, Equatable { + var id: String + var itemId: String + var title: String + var start: Date + var end: Date + var location: String + var organizer: String + var joinUrl: String + var calendar: String + // When the event was created in the calendar; nil for snapshots saved before this field existed. + var created: Date? = nil + var notes: String? = nil + var eventUrl: String? = nil + var attendeeCount: Int? = nil + + // What opening it goes to: the join link, else the event in Calendar.app + // (which just opens Calendar if the id is unknown). + var link: String { joinUrl.isEmpty ? calendarUrl : joinUrl } + + var calendarUrl: String { + let escaped = itemId.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? itemId + return "ical://ekevent/\(escaped)?method=show" + } + + // Notes as one plain line, for a row that has no room for the invite's HTML. + func notesSnippet(limit: Int = 160) -> String { + guard let notes else { return "" } + let flat = MeetingText.plain(notes).replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression) + return flat.count > limit ? String(flat.prefix(limit - 1)) + "\u{2026}" : flat + } +} + +// What the app says about a meeting. `key` is set when a later notice about the +// same thing should replace this one in the queue rather than stack. +struct MeetingNotice: Equatable { + let kind: String + let severity: EventSeverity + let title: String + let body: String + let url: String + var key: String? = nil + + func event(now: Date = Date()) -> NudgeEvent { + .feed(source: .calendar, tag: "calendar", severity: severity, title: title, message: body, + url: URL(string: url), key: key, timestamp: now) + } +} + +enum MeetingDiff { + static let horizon: TimeInterval = 24 * 3600 + + // A reminder stays up this long after the start, then goes: by then the + // meeting is either joined or missed. + static let reminderTail: TimeInterval = 300 + + private static func format(_ date: Date, _ template: String) -> String { + let f = DateFormatter() + f.locale = Locale(identifier: "en_GB") + f.dateFormat = template + return f.string(from: date) + } + + static func clock(_ date: Date) -> String { format(date, "HH:mm") } + static func weekdayTime(_ date: Date) -> String { format(date, "EEE HH:mm") } + + // How long a meeting must stay missing before it counts as cancelled; a + // calendar re-sync can drop events briefly. + static let cancelGrace: TimeInterval = 300 + + // The same meeting under a new id: a re-sync can reissue EventKit identifiers. + static func sameSlot(_ a: Meeting, _ b: Meeting) -> Bool { a.title == b.title && a.start == b.start && a.end == b.end } + + // Upcoming meetings missing from `new` by id that are not the same meeting under a new id. + static func missing(old: [Meeting], new: [Meeting], now: Date) -> [Meeting] { + let ids = Set(new.map(\.id)) + return old.filter { m in !ids.contains(m.id) && m.end > now && !new.contains { sameSlot($0, m) } } + } + + // Missing meetings not yet past the grace period: kept in the saved snapshot with when they first went missing. + static func held(old: [Meeting], new: [Meeting], now: Date, missingSince: [String: Date]) -> [String: Date] { + var out: [String: Date] = [:] + for m in missing(old: old, new: new, now: now) { + let since = missingSince[m.id] ?? now + if now.timeIntervalSince(since) < cancelGrace { out[m.id] = since } + } + return out + } + + // `since` is the previous refresh: a meeting that only shows up now but was + // created long before arrived through a slow initial sync, so it is not + // announced as new. `missingSince` (when given) holds cancellations back + // until a meeting has been missing for `cancelGrace`. + static func diff(old: [Meeting], new: [Meeting], now: Date, since: Date? = nil, missingSince: [String: Date]? = nil) -> [MeetingNotice] { + let oldById = Dictionary(old.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) + var out: [MeetingNotice] = [] + + for m in new.sorted(by: { $0.start < $1.start }) { + guard let before = oldById[m.id] else { + guard m.start > now, !old.contains(where: { sameSlot($0, m) }) else { continue } + if let created = m.created, let since, created < since.addingTimeInterval(-600) { continue } + out.append(MeetingNotice(kind: "meeting-added", severity: .info, + title: "New meeting: \(m.title)", + body: [weekdayTime(m.start), m.organizer].filter { !$0.isEmpty }.joined(separator: ", "), + url: m.link)) + continue + } + let changes = describe(from: before, to: m) + guard !changes.isEmpty, m.end > now else { continue } + let soon = m.start > now && m.start.timeIntervalSince(now) <= horizon + out.append(MeetingNotice(kind: "meeting-changed", severity: soon ? .action : .info, + title: "Meeting changed: \(m.title)", body: changes.joined(separator: "\n"), url: m.link)) + } + + for m in missing(old: old, new: new, now: now).sorted(by: { $0.start < $1.start }) { + if let missingSince, now.timeIntervalSince(missingSince[m.id] ?? now) < cancelGrace { continue } + out.append(MeetingNotice(kind: "meeting-cancelled", severity: .info, + title: "Meeting cancelled: \(m.title)", body: weekdayTime(m.start), url: m.link)) + } + return out + } + + // One "before → after" line per changed field; the title already carries the new name. + static func describe(from a: Meeting, to b: Meeting) -> [String] { + var changes: [String] = [] + if a.start != b.start || a.end != b.end { + let sameDay = Calendar.current.isDate(a.start, inSameDayAs: b.start) + func span(_ m: Meeting) -> String { "\(sameDay ? clock(m.start) : weekdayTime(m.start))\u{2013}\(clock(m.end))" } + changes.append("\(span(a)) \u{2192} \(span(b))") + } + if a.title != b.title { changes.append("Was \u{201C}\(a.title)\u{201D}") } + if a.location != b.location { + func place(_ s: String) -> String { s.isEmpty ? "none" : (s.count > 40 ? String(s.prefix(39)) + "\u{2026}" : s) } + changes.append("Location: \(place(a.location)) \u{2192} \(place(b.location))") + } + return changes + } + + static func isJoinUrl(_ url: String) -> Bool { + let range = NSRange(url.startIndex..., in: url) + return joinPatterns.contains { $0.firstMatch(in: url, range: range) != nil } + } + + // Also the queue key of the meeting's reminder, so the heads-up, the start + // alert and the removal on joining all name the same row. + static func dueKey(_ m: Meeting) -> String { "meeting:\(m.id):\(Int(m.start.timeIntervalSince1970))" } + + // Meetings inside their heads-up window that have not fired yet. + static func due(_ meetings: [Meeting], fired: Set<String>, lead: TimeInterval, now: Date) -> [Meeting] { + meetings.filter { $0.start > now && $0.start.timeIntervalSince(now) <= lead && !fired.contains(dueKey($0)) } + } + + // When the single heads-up timer should next fire. + static func nextDue(_ meetings: [Meeting], fired: Set<String>, lead: TimeInterval, now: Date) -> Date? { + meetings.filter { !fired.contains(dueKey($0)) } + .map { $0.start.addingTimeInterval(-lead) } + .filter { $0 > now } + .min() + } + + // Meetings that have started, were warned about, and have not had their start alert yet. + static func startDue(_ meetings: [Meeting], fired: Set<String>, started: Set<String>, now: Date) -> [Meeting] { + meetings.filter { + let key = dueKey($0) + return fired.contains(key) && !started.contains(key) && $0.start <= now && now < $0.start.addingTimeInterval(reminderTail) + } + } + + // Warned-about meetings whose reminder is past its tail and should leave the queue. + static func expired(_ meetings: [Meeting], fired: Set<String>, now: Date) -> [Meeting] { + meetings.filter { fired.contains(dueKey($0)) && now >= $0.start.addingTimeInterval(reminderTail) } + } + + // The next start alert or expiry among warned-about meetings, for the shared timer. + static func nextReminderStep(_ meetings: [Meeting], fired: Set<String>, started: Set<String>, now: Date) -> Date? { + meetings.filter { fired.contains(dueKey($0)) }.flatMap { m -> [Date] in + var steps = [m.start.addingTimeInterval(reminderTail)] + if !started.contains(dueKey(m)) { steps.append(m.start) } + return steps + }.filter { $0 > now }.min() + } + + static func soonNotice(_ m: Meeting, now: Date) -> MeetingNotice { + let minutes = max(1, Int((m.start.timeIntervalSince(now) / 60).rounded(.up))) + return MeetingNotice(kind: "meeting-soon", severity: .action, title: "\(m.title) starts in \(minutes) min", + body: soonBody(m), url: m.link, key: dueKey(m)) + } + + // Replaces the heads-up under the same key, so it is one row that escalates. + static func startNotice(_ m: Meeting) -> MeetingNotice { + MeetingNotice(kind: "meeting-started", severity: .alert, title: "\(m.title) is starting now", + body: soonBody(m), url: m.link, key: dueKey(m)) + } + + private static func soonBody(_ m: Meeting) -> String { + ["\(clock(m.start)) to \(clock(m.end))", m.location].filter { !$0.isEmpty }.joined(separator: ", ") + } + + private static let joinPatterns: [NSRegularExpression] = [ + #"https?://meet\.google\.com/[a-z0-9-]+[^\s"'<>)]*"#, + #"https?://[\w.-]*zoom\.(?:us|com)/(?:j|my|wc|s)/[^\s"'<>)]+"#, + #"https?://teams\.(?:microsoft|live)\.com/(?:l/meetup-join|meet)/[^\s"'<>)]+"#, + #"https?://[\w.-]*webex\.com/[^\s"'<>)]+"#, + ].compactMap { try? NSRegularExpression(pattern: $0, options: [.caseInsensitive]) } + + // First conferencing link in the given texts, tried in order (url field, location, notes). + static func joinUrl(in texts: [String?]) -> String { + for text in texts.compactMap({ $0 }) where !text.isEmpty { + let range = NSRange(text.startIndex..., in: text) + for re in joinPatterns { + if let m = re.firstMatch(in: text, range: range), let r = Range(m.range, in: text) { + return String(text[r]).trimmingCharacters(in: CharacterSet(charactersIn: ".,;:")) + } + } + } + return "" + } +} + +// Morning summary preferences; read from the nav settings, never persisted here. +struct SummarySettings: Equatable { + var enabled = true + var minutes = 9 * 60 + var weekdaysOnly = true + var announceEmpty = false + + static let times = [8 * 60, 8 * 60 + 30, 9 * 60, 9 * 60 + 30, 10 * 60] + + static func label(_ minutes: Int) -> String { String(format: "%02d:%02d", minutes / 60, minutes % 60) } +} + +extension MeetingDiff { + // A late summary (after wake or a relaunch) is dropped once it is past this hour. + static let summaryCutoffHour = 12 + static let summaryMaxListed = 3 + + static func dayKey(_ date: Date, calendar: Calendar = .current) -> String { + let c = calendar.dateComponents([.year, .month, .day], from: date) + return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0) + } + + private static func at(_ date: Date, minutes: Int, calendar: Calendar) -> Date { + calendar.date(bySettingHour: minutes / 60, minute: minutes % 60, second: 0, of: date) ?? date + } + + private static func allowed(_ day: Date, _ s: SummarySettings, calendar: Calendar) -> Bool { + !(s.weekdaysOnly && calendar.isDateInWeekend(day)) + } + + // Whether today's summary should go out on this refresh: past the set time, before noon, once per day. + static func summaryDue(now: Date, settings s: SummarySettings, lastDate: String?, calendar: Calendar = .current) -> Bool { + guard s.enabled, allowed(now, s, calendar: calendar), lastDate != dayKey(now, calendar: calendar) else { return false } + return now >= at(now, minutes: s.minutes, calendar: calendar) && now < at(now, minutes: summaryCutoffHour * 60, calendar: calendar) + } + + // When the summary next becomes due, for the shared timer; nil when disabled. + static func nextSummaryDue(now: Date, settings s: SummarySettings, lastDate: String?, calendar: Calendar = .current) -> Date? { + guard s.enabled else { return nil } + for offset in 0...8 { + guard let day = calendar.date(byAdding: .day, value: offset, to: now), allowed(day, s, calendar: calendar) else { continue } + if offset == 0, lastDate == dayKey(now, calendar: calendar) { continue } + let due = at(day, minutes: s.minutes, calendar: calendar) + if due > now { return due } + } + return nil + } + + // Today's meetings from the snapshot, in start order. + static func todaysMeetings(_ meetings: [Meeting], now: Date, calendar: Calendar = .current) -> [Meeting] { + meetings.filter { calendar.isDate($0.start, inSameDayAs: now) }.sorted { $0.start < $1.start } + } + + static func agenda(_ meetings: [Meeting]) -> String { + var parts = meetings.prefix(summaryMaxListed).map { "\(clock($0.start)) \($0.title)" } + if meetings.count > summaryMaxListed { parts.append("+\(meetings.count - summaryMaxListed) more") } + return parts.joined(separator: ", ") + } + + // nil when there is nothing to say (no meetings and empty days not wanted). + static func summaryNotice(_ meetings: [Meeting], now: Date, announceEmpty: Bool, calendar: Calendar = .current) -> MeetingNotice? { + let today = todaysMeetings(meetings, now: now, calendar: calendar) + let key = "meeting-summary:\(dayKey(now, calendar: calendar))" + if today.isEmpty { + return announceEmpty ? MeetingNotice(kind: "meeting-summary", severity: .info, title: "No meetings today", body: "", url: summaryUrl, key: key) : nil + } + let title = today.count == 1 ? "Today: 1 meeting" : "Today: \(today.count) meetings" + return MeetingNotice(kind: "meeting-summary", severity: .info, title: title, body: agenda(today), url: summaryUrl, key: key) + } + + static let summaryUrl = "ical://" +} + +extension Array where Element == Meeting { + // The same meeting often appears in two selected calendars (a shared team + // calendar plus the user's own invite copy). Keep one per title and time, + // preferring the copy with a join link. + func dedupedByOccurrence() -> [Meeting] { + var best: [String: Meeting] = [:] + var order: [String] = [] + for m in self { + let key = "\(m.title.lowercased())|\(Int(m.start.timeIntervalSince1970))|\(Int(m.end.timeIntervalSince1970))" + if let kept = best[key] { + if kept.joinUrl.isEmpty && !m.joinUrl.isEmpty { best[key] = m } + } else { + best[key] = m + order.append(key) + } + } + return order.compactMap { best[$0] } + } +} diff --git a/panel/MeetingLinks.swift b/panel/MeetingLinks.swift new file mode 100644 index 00000000..3aff0e94 --- /dev/null +++ b/panel/MeetingLinks.swift @@ -0,0 +1,111 @@ +import Foundation + +enum DocKind: Equatable { + case doc, sheet, slides, form, drive + + var symbol: String { + switch self { + case .doc: return "doc.text" + case .sheet: return "tablecells" + case .slides: return "rectangle.on.rectangle" + case .form: return "list.bullet.rectangle" + case .drive: return "folder" + } + } +} + +struct DocLink: Equatable { + let kind: DocKind + let url: String +} + +struct MeetingLinks: Equatable { + var docs: [DocLink] = [] + var others: [String] = [] + var isEmpty: Bool { docs.isEmpty && others.isEmpty } +} + +// Pure text helpers for a meeting's notes: to plain text, and link extraction. +enum MeetingText { + private static let entities = ["amp": "&", "lt": "<", "gt": ">", "quot": "\"", "apos": "'", "nbsp": " ", "#39": "'"] + private static let tag = try? NSRegularExpression(pattern: "<[^>]+>") + private static let entity = try? NSRegularExpression(pattern: "&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);") + private static let urlPattern = try? NSRegularExpression(pattern: #"https?://[^\s"'<>\])]+"#, options: [.caseInsensitive]) + // Calendar chrome Google appends to every invite; never worth a button. + private static let noiseHosts: Set<String> = ["calendar.google.com", "support.google.com", "accounts.google.com"] + + // Notes with markup removed, entities decoded and whitespace collapsed (paragraph breaks survive). + static func plain(_ notes: String) -> String { + var s = notes.replacingOccurrences(of: "\r", with: "") + s = s.replacingOccurrences(of: "<br\\s*/?>|</(p|div|li|tr|h[1-6])>", with: "\n", options: [.regularExpression, .caseInsensitive]) + s = s.replacingOccurrences(of: "<li[^>]*>", with: "- ", options: [.regularExpression, .caseInsensitive]) + s = replace(tag, in: s) { _ in "" } + s = decode(s) + s = s.replacingOccurrences(of: "[ \t\u{00A0}]+", with: " ", options: .regularExpression) + s = s.replacingOccurrences(of: " ?\n ?", with: "\n", options: .regularExpression) + s = s.replacingOccurrences(of: "\n{3,}", with: "\n\n", options: .regularExpression) + return s.trimmingCharacters(in: .whitespacesAndNewlines) + } + + static func decode(_ s: String) -> String { + replace(entity, in: s) { name in + if name.hasPrefix("#x"), let n = UInt32(name.dropFirst(2), radix: 16), let u = Unicode.Scalar(n) { return String(Character(u)) } + if name.hasPrefix("#"), let n = UInt32(name.dropFirst()), let u = Unicode.Scalar(n) { return String(Character(u)) } + return entities[name.lowercased()] + } + } + + // Docs and other links from the texts, in order and without duplicates; `joinUrl` and conferencing links are left out. + static func links(in texts: [String?], joinUrl: String = "") -> MeetingLinks { + var out = MeetingLinks() + var seen = Set<String>() + for text in texts.compactMap({ $0 }) where !text.isEmpty { + let decoded = decode(text) + let range = NSRange(decoded.startIndex..., in: decoded) + for m in urlPattern?.matches(in: decoded, range: range) ?? [] { + guard let r = Range(m.range, in: decoded) else { continue } + let raw = String(decoded[r]).trimmingCharacters(in: CharacterSet(charactersIn: ".,;:!?")) + let url = unwrap(raw) + guard url != joinUrl, !MeetingDiff.isJoinUrl(url), seen.insert(url).inserted, + let host = URL(string: url)?.host?.lowercased(), !noiseHosts.contains(host) else { continue } + if let kind = docKind(url) { out.docs.append(DocLink(kind: kind, url: url)) } else { out.others.append(url) } + } + } + return out + } + + // The target of a google.com/url?q= tracking redirect; any other URL is returned unchanged. + static func unwrap(_ url: String) -> String { + guard let c = URLComponents(string: url), c.host?.lowercased().hasSuffix("google.com") == true, c.path == "/url", + let target = c.queryItems?.first(where: { $0.name == "q" || $0.name == "url" })?.value, + target.lowercased().hasPrefix("http") else { return url } + return target + } + + static func docKind(_ url: String) -> DocKind? { + guard let u = URL(string: url), let host = u.host?.lowercased() else { return nil } + if host == "docs.google.com" { + let path = u.path + if path.hasPrefix("/document") { return .doc } + if path.hasPrefix("/spreadsheets") { return .sheet } + if path.hasPrefix("/presentation") { return .slides } + if path.hasPrefix("/forms") { return .form } + return .doc + } + return host == "drive.google.com" ? .drive : nil + } + + private static func replace(_ re: NSRegularExpression?, in s: String, with f: (String) -> String?) -> String { + guard let re else { return s } + var out = "" + var last = s.startIndex + for m in re.matches(in: s, range: NSRange(s.startIndex..., in: s)) { + guard let whole = Range(m.range, in: s) else { continue } + out += s[last..<whole.lowerBound] + let name = m.numberOfRanges > 1 ? Range(m.range(at: 1), in: s).map { String(s[$0]) } ?? "" : "" + out += f(name) ?? String(s[whole]) + last = whole.upperBound + } + return out + s[last...] + } +} diff --git a/panel/Panel.swift b/panel/Panel.swift index 95044ead..c4ccf56d 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -1358,6 +1358,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, private var updateChecker: UpdateChecker? private var updater: Updater? private var extensionCheckTimer: Timer? + private var calendarWatcher: CalendarWatcher? private let claudeCliQuotaProbe = ClaudeCliQuotaProbe() // Claude logins other than the default one, by config dir. See // refreshOtherClaudeAccounts. @@ -1814,6 +1815,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, extensions.load() startEventHistory() startSlack() + startCalendar() // The pill (CompactView) reads sessions.sessions for the busy/idle // headline and mascot state, so polling has to run as soon as the // app is up — not gated on the Sessions tab being visible. Sessions @@ -4455,6 +4457,35 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, } + // MARK: - Calendar + + // The watcher exists from launch but touches nothing until the setting is + // on: start() is what first reaches EventKit and asks for access. + private func startCalendar() { + let watcher = CalendarWatcher( + events: store, + settings: { [weak self] in self?.nav.calendarSettings ?? CalendarSettings() }, + onToday: { [weak self] meetings in self?.nav.todaysMeetings = meetings }, + onAccess: { [weak self] access in self?.nav.calendarAccess = access }) + calendarWatcher = watcher + nav.$calendarEnabled + .removeDuplicates() + .sink { enabled in + if enabled { watcher.start() } else { watcher.stop() } + } + .store(in: &cancellables) + // objectWillChange fires before the value is stored, so the read is + // deferred a turn; duplicates drop out every change that is not ours. + nav.objectWillChange + .receive(on: DispatchQueue.main) + .compactMap { [weak self] in self?.nav.calendarSettings } + .prepend(nav.calendarSettings) + .removeDuplicates() + .dropFirst() + .sink { _ in watcher.settingsChanged() } + .store(in: &cancellables) + } + // MARK: - Config file watcher private var configWatcher: DispatchSourceFileSystemObject? diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index 20acf094..651612b1 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -215,6 +215,8 @@ enum SettingsRow: Hashable { case piApiBudget, piLocalBudget case awayLock case githubLinks, githubActivity, hideShipped, connectGithub, disconnectGithub + case calendarEnabled, calendarLead, calendarSummary, calendarSummaryTime, + calendarWeekdaysOnly, calendarSummaryEmpty, calendarDetectJoin case historyPerSession case editPhrases, checkPermissions, openConfig, releaseNotes, updateChannel, checkUpdates, uninstall, quit // The local MCP server (docs/design/local-mcp.md): the door to the page of @@ -276,6 +278,8 @@ extension SettingsRow: CaseIterable { .contextAlert, .showRemaining, .piApiBudget, .piLocalBudget, .awayLock, .githubLinks, .githubActivity, .hideShipped, .connectGithub, .disconnectGithub, + .calendarEnabled, .calendarLead, .calendarSummary, .calendarSummaryTime, + .calendarWeekdaysOnly, .calendarSummaryEmpty, .calendarDetectJoin, .historyPerSession, .editPhrases, .checkPermissions, .openConfig, .releaseNotes, .updateChannel, .checkUpdates, .uninstall, .quit, @@ -1184,6 +1188,31 @@ final class PanelNav: ObservableObject { @Published var slackIncludeDetail: Bool = false @Published var slackNotifyOnStop: Bool = false + // Calendar (STACKNUDGE_CALENDAR*). Off by default: turning it on is what + // asks macOS for calendar access. + @Published var calendarEnabled: Bool = false + @Published var calendarLeadMinutes: Int = 10 + @Published var calendarSummaryEnabled: Bool = true + @Published var calendarSummaryMinutes: Int = 9 * 60 + @Published var calendarWeekdaysOnly: Bool = true + @Published var calendarSummaryEmpty: Bool = false + @Published var calendarDetectJoin: Bool = true + // Calendar identifiers to watch (STACKNUDGE_CALENDARS); empty is all of them. + // Edited in the config file: there is no picker. + @Published var calendarIds: [String] = [] + @Published var calendarAccess: CalendarAccess = .notDetermined + // Today's meetings, finished ones included, in start order. Written by the + // CalendarWatcher on every refresh; a view of the day reads it. + @Published var todaysMeetings: [Meeting] = [] + + var calendarSettings: CalendarSettings { + CalendarSettings( + leadMinutes: calendarLeadMinutes, + summary: SummarySettings(enabled: calendarSummaryEnabled, minutes: calendarSummaryMinutes, + weekdaysOnly: calendarWeekdaysOnly, announceEmpty: calendarSummaryEmpty), + detectJoin: calendarDetectJoin, calendarIds: calendarIds) + } + // Which pane of the Events tab is showing. `live` is the triage queue — // capped, prunable, and gone on quit. `history` is the durable log behind // it. Deliberately a second pane rather than merged into the queue: the @@ -1721,6 +1750,10 @@ final class PanelNav: ObservableObject { return [.mcpSetupClients, .mcpWrites] case .mcpSetupPage: return MCPClient.allCases.map { .mcpClient($0) } + case .calendar: + return [.calendarEnabled, .calendarLead, .calendarSummary, + .calendarSummaryTime, .calendarWeekdaysOnly, + .calendarSummaryEmpty, .calendarDetectJoin] // Its own category rather than a row under Actions: extensions declare // STACKNUDGE_EXT_ keys, so per-extension configuration needs somewhere // to live, and it should not arrive by growing an unrelated category. @@ -1958,6 +1991,18 @@ final class PanelNav: ObservableObject { } } + // "HH:MM" to minutes since midnight, snapped to the nearest offered time so a + // hand-edited value can't desync the cycle row's selection. + static func summaryMinutes(_ raw: String?) -> Int { + let parts = (raw ?? "").split(separator: ":").compactMap { Int($0) } + let minutes = parts.count == 2 ? parts[0] * 60 + parts[1] : 9 * 60 + return SummarySettings.times.min(by: { abs($0 - minutes) < abs($1 - minutes) }) ?? 9 * 60 + } + + static func calendarIds(_ raw: String?) -> [String] { + (raw ?? "").split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + } + func loadFromConfig() { let config = ConfigFile.read() hotkeyDisplay = config["STACKNUDGE_PANEL_HOTKEY"] ?? "cmd+opt+n" @@ -1989,6 +2034,15 @@ final class PanelNav: ObservableObject { githubUseGH = ConfigFile.bool(config, "STACKNUDGE_GITHUB_USE_GH", default: true) githubSignedIn = githubUsesCLILogin || GitHubAuth.token() != nil refreshGitHubCLILogin() + calendarEnabled = ConfigFile.bool(config, "STACKNUDGE_CALENDAR", default: false) + let rawLead = Int(config["STACKNUDGE_CALENDAR_LEAD_MIN"] ?? "") ?? 10 + calendarLeadMinutes = CalendarSettings.leadOptions.min(by: { abs($0 - rawLead) < abs($1 - rawLead) }) ?? 10 + calendarSummaryEnabled = ConfigFile.bool(config, "STACKNUDGE_CALENDAR_SUMMARY", default: true) + calendarSummaryMinutes = Self.summaryMinutes(config["STACKNUDGE_CALENDAR_SUMMARY_TIME"]) + calendarWeekdaysOnly = ConfigFile.bool(config, "STACKNUDGE_CALENDAR_WEEKDAYS_ONLY", default: true) + calendarSummaryEmpty = ConfigFile.bool(config, "STACKNUDGE_CALENDAR_SUMMARY_EMPTY", default: false) + calendarDetectJoin = ConfigFile.bool(config, "STACKNUDGE_CALENDAR_JOIN", default: true) + calendarIds = Self.calendarIds(config["STACKNUDGE_CALENDARS"]) quotaTrackingEnabled = ConfigFile.bool(config, "STACKNUDGE_QUOTA_TRACKING", default: true) quotaAlertsEnabled = ConfigFile.bool(config, "STACKNUDGE_QUOTA_ALERTS", default: true) quotaShowRemaining = ConfigFile.bool(config, "STACKNUDGE_QUOTA_SHOW_REMAINING", default: false) @@ -2368,6 +2422,8 @@ final class PanelNav: ObservableObject { .soundEnabled, .voiceEnabled, .quotaTracking, .quotaAlerts, .showRemaining, .githubLinks, .githubActivity, .hideShipped, .eventHistory, + .calendarEnabled, .calendarSummary, .calendarWeekdaysOnly, .calendarSummaryEmpty, + .calendarDetectJoin, .slackEnabled, .slackDetail, .slackStop, .awayLock, .mcpWrites: return false case .permissions, .update, .extensionUpdates, .hotkey, .speakHotkey, .downloadVoiceModel: @@ -2378,7 +2434,7 @@ final class PanelNav: ObservableObject { .voice, .voiceSpeed, .alertThreshold, .pollFrequency, .contextAlert, .piApiBudget, .piLocalBudget, - .historyPerSession, + .historyPerSession, .calendarLead, .calendarSummaryTime, .slackIdle, .updateChannel: return true } @@ -2714,6 +2770,33 @@ final class PanelNav: ObservableObject { refreshGitHubCLILogin() case .hideShipped: toggleHideShipped() + case .calendarEnabled: + calendarEnabled.toggle() + ConfigFile.write(key: "STACKNUDGE_CALENDAR", value: calendarEnabled ? "true" : "false") + case .calendarLead: + let list = CalendarSettings.leadOptions + let idx = list.firstIndex(of: calendarLeadMinutes) ?? 1 + let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count + calendarLeadMinutes = list[next] + ConfigFile.write(key: "STACKNUDGE_CALENDAR_LEAD_MIN", value: String(calendarLeadMinutes)) + case .calendarSummary: + calendarSummaryEnabled.toggle() + ConfigFile.write(key: "STACKNUDGE_CALENDAR_SUMMARY", value: calendarSummaryEnabled ? "true" : "false") + case .calendarSummaryTime: + let list = SummarySettings.times + let idx = list.firstIndex(of: calendarSummaryMinutes) ?? 2 + let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count + calendarSummaryMinutes = list[next] + ConfigFile.write(key: "STACKNUDGE_CALENDAR_SUMMARY_TIME", value: SummarySettings.label(calendarSummaryMinutes)) + case .calendarWeekdaysOnly: + calendarWeekdaysOnly.toggle() + ConfigFile.write(key: "STACKNUDGE_CALENDAR_WEEKDAYS_ONLY", value: calendarWeekdaysOnly ? "true" : "false") + case .calendarSummaryEmpty: + calendarSummaryEmpty.toggle() + ConfigFile.write(key: "STACKNUDGE_CALENDAR_SUMMARY_EMPTY", value: calendarSummaryEmpty ? "true" : "false") + case .calendarDetectJoin: + calendarDetectJoin.toggle() + ConfigFile.write(key: "STACKNUDGE_CALENDAR_JOIN", value: calendarDetectJoin ? "true" : "false") case .slackEnabled: slackEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_SLACK", value: slackEnabled ? "true" : "false") @@ -3009,7 +3092,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, voice, appearance, companion, usage, integrations, calendar, extensions, mcp, panel, events, actions, about // One extension's page, a level below Extensions. Not in the sidebar. case extensionPage(String) @@ -3020,7 +3103,7 @@ enum SettingsCategory: Hashable, CaseIterable { case mcpSetupPage static let allCases: [SettingsCategory] = [ - .notifications, .voice, .appearance, .companion, .usage, .integrations, .extensions, + .notifications, .voice, .appearance, .companion, .usage, .integrations, .calendar, .extensions, .mcp, .panel, .events, .actions, .about, ] @@ -3034,6 +3117,7 @@ enum SettingsCategory: Hashable, CaseIterable { case .companion: return "Companion" case .usage: return "Usage" case .integrations: return "Integrations" + case .calendar: return "Calendar" case .extensions: return "Extensions" case .mcp: return "MCP" case .mcpSetupPage: return "Set up for" diff --git a/panel/Settings.swift b/panel/Settings.swift index b367b801..12dc6338 100644 --- a/panel/Settings.swift +++ b/panel/Settings.swift @@ -364,6 +364,13 @@ struct SettingsView: View { } } + // Access is asked for on the first enable, so a denial shows here rather + // than as a row that looks on but never reports anything. + private var calendarValue: String { + guard nav.calendarEnabled else { return "Off" } + return nav.calendarAccess == .denied ? "On, no access (System Settings > Privacy)" : "On" + } + private var checkForUpdatesStatus: String { switch nav.updateCheckStatus { case .idle: return "" @@ -969,6 +976,15 @@ struct SettingsView: View { .padding(.horizontal, 14).padding(.top, 2) } + // Calendar + case .calendarEnabled: row(.calendarEnabled, label: "Calendar", kind: .toggle, value: calendarValue) + case .calendarLead: row(.calendarLead, label: "Heads-up before meetings", kind: .cycle, value: "\(nav.calendarLeadMinutes) min", enabled: nav.calendarEnabled) + case .calendarSummary: row(.calendarSummary, label: "Morning summary", kind: .toggle, value: nav.calendarSummaryEnabled ? "On" : "Off", enabled: nav.calendarEnabled) + case .calendarSummaryTime: row(.calendarSummaryTime, label: "Summary time", kind: .cycle, value: SummarySettings.label(nav.calendarSummaryMinutes), enabled: nav.calendarEnabled && nav.calendarSummaryEnabled) + case .calendarWeekdaysOnly: row(.calendarWeekdaysOnly, label: "Weekdays only", kind: .toggle, value: nav.calendarWeekdaysOnly ? "On" : "Off", enabled: nav.calendarEnabled && nav.calendarSummaryEnabled) + case .calendarSummaryEmpty: row(.calendarSummaryEmpty, label: "Summary on empty days", kind: .toggle, value: nav.calendarSummaryEmpty ? "On" : "Off", enabled: nav.calendarEnabled && nav.calendarSummaryEnabled) + case .calendarDetectJoin: row(.calendarDetectJoin, label: "Detect joining (Automation)", kind: .toggle, value: nav.calendarDetectJoin ? "On" : "Off", enabled: nav.calendarEnabled) + // Panel case .hotkey: row(.hotkey, label: "Panel shortcut", kind: .cycle, diff --git a/panel/entitlements.plist b/panel/entitlements.plist index 420db393..4af1949b 100644 --- a/panel/entitlements.plist +++ b/panel/entitlements.plist @@ -52,5 +52,16 @@ --> <key>com.apple.security.automation.apple-events</key> <true/> + + <!-- + Calendar access for the optional meeting reminders (EventKit). + + Without this a hardened-runtime build is refused calendar access + outright, with no prompt, so the Calendar setting could never be + granted. Unsigned local builds are unaffected. The app still reads + nothing until the user turns the setting on and approves the prompt. + --> + <key>com.apple.security.personal-information.calendars</key> + <true/> </dict> </plist> From 4ad327fc9cee64afc2dbb6e0e1ea85954e4fb33a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20De=20Freitas?= <6485562+adefreitas@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:34:14 +0000 Subject: [PATCH 2/5] test(calendar): place Calendar after Integrations without requiring adjacency Other integration categories (GitHub) may sit between them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift index 42b3cc5e..d905fb08 100644 --- a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift +++ b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift @@ -253,7 +253,9 @@ final class SettingsCategoryTests: XCTestCase { func testTheCalendarCategoryFollowsIntegrationsAndHoldsItsRows() { let all = SettingsCategory.allCases XCTAssertEqual(SettingsCategory.calendar.label, "Calendar") - XCTAssertEqual(all.firstIndex(of: .calendar), all.firstIndex(of: .integrations).map { $0 + 1 }) + // After Integrations, not necessarily next to it: other integration + // categories (GitHub) may sit between them. + XCTAssertGreaterThan(all.firstIndex(of: .calendar) ?? -1, all.firstIndex(of: .integrations) ?? Int.max) XCTAssertEqual(PanelNav().rows(in: .calendar), [.calendarEnabled, .calendarLead, .calendarSummary, .calendarSummaryTime, .calendarWeekdaysOnly, .calendarSummaryEmpty, .calendarDetectJoin]) From cf4b776287df2ab497c98e34f2bec8da06ee9740 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20De=20Freitas?= <6485562+adefreitas@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:42:52 +0000 Subject: [PATCH 3/5] feat(calendar): a Today tab with the day's meetings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Shown while Calendar is on. Lists today's meetings from the watcher in order with times, title, location or organizer, and a notes snippet; past ones dimmed, the one in progress marked Now, and the tab opens on it or the next one. ↑↓ select, ⏎ or a click joins through the meeting link, else opens the event in Calendar. Without calendar access it says so and links to the Calendar settings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../TodayRowsTests.swift | 30 +++++ docs/panel.md | 9 ++ panel/Panel.swift | 17 +++ panel/PanelNav.swift | 20 +++ panel/TodayView.swift | 127 ++++++++++++++++++ 5 files changed, 203 insertions(+) create mode 100644 Tests/StackNudgePanelCoreTests/TodayRowsTests.swift create mode 100644 panel/TodayView.swift diff --git a/Tests/StackNudgePanelCoreTests/TodayRowsTests.swift b/Tests/StackNudgePanelCoreTests/TodayRowsTests.swift new file mode 100644 index 00000000..94f9255f --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/TodayRowsTests.swift @@ -0,0 +1,30 @@ +import XCTest + +@testable import StackNudgePanelCore + +final class TodayRowsTests: XCTestCase { + + private let nine = Date(timeIntervalSince1970: 1_800_000_000) + + private func meeting(_ id: String, startsIn minutes: Double, lasting: Double = 30) -> Meeting { + let start = nine.addingTimeInterval(minutes * 60) + return Meeting(id: id, itemId: id, title: id, start: start, end: start.addingTimeInterval(lasting * 60), + location: "", organizer: "", joinUrl: "", calendar: "Work") + } + + func testPhasesFollowTheClock() { + XCTAssertEqual(TodayRows.phase(meeting("a", startsIn: -60), now: nine), .past) + XCTAssertEqual(TodayRows.phase(meeting("b", startsIn: -10), now: nine), .now) + XCTAssertEqual(TodayRows.phase(meeting("c", startsIn: 30), now: nine), .upcoming) + } + + // Opening the tab lands on what matters now: the meeting in progress, or + // the next one, or the day's last when all are over. + func testTheTabOpensOnTheCurrentOrNextMeeting() { + let day = [meeting("a", startsIn: -120), meeting("b", startsIn: -10), meeting("c", startsIn: 60)] + XCTAssertEqual(TodayRows.defaultIndex(day, now: nine), 1) + XCTAssertEqual(TodayRows.defaultIndex(Array(day.prefix(1)) + [day[2]], now: nine), 1) + XCTAssertEqual(TodayRows.defaultIndex(Array(day.prefix(2)), now: nine.addingTimeInterval(3600)), 1) + XCTAssertEqual(TodayRows.defaultIndex([], now: nine), 0) + } +} diff --git a/docs/panel.md b/docs/panel.md index 837f1e48..b0efbe58 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -239,6 +239,15 @@ If the GitHub CLI (`gh`) is installed and logged in, these requests and PR links The same check fills a **PRs** tab, shown while GitHub activity is on: your open PRs (with draft, review, CI and conflict chips) and the PRs waiting on your review, asked of you by name first, then through your teams (marked with the team). `↑↓` select, `⏎` or a click opens the PR, `⌘↑` / `⌘↓` jump to the first / last row, `Esc` hides. +## Today + +With Calendar on (see [notifications.md](notifications.md#calendar)), a **Today** tab lists the day's meetings in order: times, title, where or who, and a notes snippet. Past meetings are dimmed, the one in progress is marked Now, and the tab opens on it (or the next). + +| Key | Action | +|-----|--------| +| `↑ ↓` | Move selection | +| `⏎` | Join through the meeting link, or open the event in Calendar when it has none | + ## Extensions **Settings → Extensions** lists what's installed: name, a one-line description, and a status (Update x.y, Running, Present / Away, Broken, Tab ⌘N…). `→` or `⏎` opens an extension's page: its status, its settings, what it's allowed, where it appears, and **Update** / **Remove**. The catalogues are checked for updates in the background, a minute after launch and then hourly, so an extension update shows without opening Settings: an **Extension update** row above every category names each one and the version it would get, and `⏎` on it opens the browser. Nothing installs from there without the browser's two presses. **Browse extensions**, below them, says how many are available and opens the catalogue: updates first, then what you haven't installed, ten at a time until you search, which matches names and descriptions. diff --git a/panel/Panel.swift b/panel/Panel.swift index c4ccf56d..4a23831c 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -207,6 +207,7 @@ struct PanelContentView: View { case .usage: UsageView(nav: nav) case .outcomes: OutcomesTabView(nav: nav) case .prs: PullRequestsView(nav: nav) + case .today: TodayView(nav: nav) // .id(id) or the two extension tabs share one view identity: a // ViewBuilder switch case is a single branch, and the associated // value isn't part of identity, so switching between them reused @@ -278,6 +279,7 @@ struct PanelContentView: View { case .usage: return "Usage" case .outcomes: return "Outcomes" case .prs: return "PRs" + case .today: return "Today" case .settings: return "Settings" case .extensionTab(let id): return nav.extensionTab(id: id)?.label ?? id // Listed, not defaulted: a new tab should fail to compile here rather @@ -294,6 +296,7 @@ struct PanelContentView: View { case .sessions: return sessions.liveSessions.count case .outcomes: return ticketGroupCount case .prs: return nav.pullRequestRows.count + case .today: return nav.todaysMeetings.filter { $0.end > Date() }.count default: return 0 } } @@ -5426,6 +5429,18 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, return true } + if nav.mode == .today { + let plain = mods.intersection([.command, .control, .option, .shift]).isEmpty + guard plain else { return false } + switch event.keyCode { + case KeyCode.upArrow: nav.moveTodaySelection(-1) + case KeyCode.downArrow: nav.moveTodaySelection(1) + case KeyCode.returnKey, KeyCode.numpadEnter: nav.openSelectedMeeting() + default: break + } + return true + } + // Only Events gets what follows. Without this, a mode that declined a // key fell through to bindings that include Return → approve. guard Self.eventsOwnsKeyboard(nav.mode) else { return false } @@ -6199,6 +6214,8 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, } case .prs: nav.jumpPullRequestSelection(toLast: !top) + case .today: + nav.jumpTodaySelection(toLast: !top) case .outcomes: // Overview pane scrolls; the tickets list jumps its selection. if nav.outcomesPane == .overview { scrollDetailToEdge(top: top) } diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index 651612b1..d8d26f40 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -42,6 +42,8 @@ enum PanelMode: Hashable { case outcomes // Your open PRs and reviews waiting on you; shown while GitHub activity is on. case prs + // Today's meetings; shown while Calendar is on. + case today // A tab contributed by an installed extension, keyed by its id. case extensionTab(String) case settings @@ -1204,6 +1206,23 @@ final class PanelNav: ObservableObject { // Today's meetings, finished ones included, in start order. Written by the // CalendarWatcher on every refresh; a view of the day reads it. @Published var todaysMeetings: [Meeting] = [] + @Published var todaySelectedIndex = 0 + + func moveTodaySelection(_ delta: Int) { + guard !todaysMeetings.isEmpty else { return } + todaySelectedIndex = max(0, min(todaysMeetings.count - 1, todaySelectedIndex + delta)) + } + + func jumpTodaySelection(toLast: Bool) { + todaySelectedIndex = toLast ? max(0, todaysMeetings.count - 1) : 0 + } + + // The meeting link when there is one, else the event in Calendar.app. + func openSelectedMeeting() { + guard todaysMeetings.indices.contains(todaySelectedIndex), + let url = URL(string: todaysMeetings[todaySelectedIndex].link) else { return } + NSWorkspace.shared.open(url) + } var calendarSettings: CalendarSettings { CalendarSettings( @@ -1490,6 +1509,7 @@ final class PanelNav: ObservableObject { var orderedTabs: [PanelMode] { var tabs: [PanelMode] = [.events, .sessions, .usage, .outcomes] if githubActivityEnabled { tabs.append(.prs) } + if calendarEnabled { tabs.append(.today) } // First id wins. Two tabs sharing one id are structurally equal, so // ForEach drops a row, firstIndex(of:) can never reach the second, and // the lookup returns the first one's label for both. diff --git a/panel/TodayView.swift b/panel/TodayView.swift new file mode 100644 index 00000000..eefa26fc --- /dev/null +++ b/panel/TodayView.swift @@ -0,0 +1,127 @@ +import SwiftUI + +// The Today tab: today's meetings from the calendar watcher, in order, with +// the one in progress marked and the next one selected. ⏎ or a click opens +// the meeting link, or the calendar event when there is none. + +enum TodayRows { + enum Phase: Equatable { case past, now, upcoming } + + static func phase(_ meeting: Meeting, now: Date) -> Phase { + if meeting.end <= now { return .past } + return meeting.start <= now ? .now : .upcoming + } + + // What the tab selects when it opens: the meeting in progress, else the + // next one, else the last of the day. + static func defaultIndex(_ meetings: [Meeting], now: Date) -> Int { + meetings.firstIndex { phase($0, now: now) != .past } ?? max(0, meetings.count - 1) + } + + static func timeRange(_ meeting: Meeting) -> String { + let format = DateFormatter() + format.timeStyle = .short + format.dateStyle = .none + return "\(format.string(from: meeting.start)) to \(format.string(from: meeting.end))" + } +} + +struct TodayView: View { + @ObservedObject var nav: PanelNav + + var body: some View { + VStack(spacing: 0) { + content + PageFooter { + FooterHint(label: "Select", keys: ["↑↓"]) + FooterDivider() + FooterHint(label: "Join / open", keys: ["⏎"], primary: true) + } + } + .onAppear { nav.todaySelectedIndex = TodayRows.defaultIndex(nav.todaysMeetings, now: Date()) } + } + + @ViewBuilder + private var content: some View { + let meetings = nav.todaysMeetings + if nav.calendarAccess != .granted { + VStack(spacing: 8) { + Text("Calendar access is needed for today's meetings").font(.subheadline.weight(.medium)) + Text("Turn Calendar on in Settings and allow access when macOS asks.") + .font(.caption).foregroundStyle(.secondary) + Button("Open Calendar settings") { + nav.settingsCategory = .calendar + nav.mode = .settings + } + } + .padding(24) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if meetings.isEmpty { + Text("No meetings today") + .font(.subheadline.weight(.medium)) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + // Re-evaluated each minute so "Now" and the dimming move with the clock. + TimelineView(.everyMinute) { timeline in + ScrollViewReader { proxy in + ScrollView { + VStack(alignment: .leading, spacing: 2) { + ForEach(Array(meetings.enumerated()), id: \.element.id) { index, meeting in + row(meeting, phase: TodayRows.phase(meeting, now: timeline.date), + selected: index == nav.todaySelectedIndex) + .id(index) + .onTapGesture { + nav.todaySelectedIndex = index + nav.openSelectedMeeting() + } + } + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + } + .onChange(of: nav.todaySelectedIndex) { proxy.scrollTo($0) } + } + } + } + } + + private func row(_ meeting: Meeting, phase: TodayRows.Phase, selected: Bool) -> some View { + HStack(alignment: .top, spacing: 10) { + Text(TodayRows.timeRange(meeting)) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + .frame(width: 118, alignment: .leading) + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 6) { + Text(meeting.title).font(.subheadline.weight(.medium)).lineLimit(1) + if phase == .now { + Text("Now") + .font(.caption2.weight(.semibold)) + .foregroundStyle(nav.theme.color) + .padding(.horizontal, 6).padding(.vertical, 1) + .background(Capsule().fill(nav.theme.color.opacity(0.16))) + } + if !meeting.joinUrl.isEmpty { + Image(systemName: "video.fill").font(.caption2).foregroundStyle(.secondary) + } + } + let detail = [meeting.location, meeting.organizer].first { !$0.isEmpty } ?? meeting.calendar + if !detail.isEmpty { + Text(detail).font(.caption).foregroundStyle(.secondary).lineLimit(1) + } + let notes = meeting.notesSnippet(limit: 120) + if !notes.isEmpty { + Text(notes).font(.caption).foregroundStyle(.tertiary).lineLimit(2) + } + } + Spacer(minLength: 0) + } + .padding(.horizontal, 8) + .padding(.vertical, 7) + .frame(maxWidth: .infinity, alignment: .leading) + .background(RoundedRectangle(cornerRadius: 6) + .fill(selected ? nav.theme.color.opacity(0.18) : Color.clear)) + .opacity(phase == .past ? 0.45 : 1) + .contentShape(Rectangle()) + } +} From b0fa589aae79acb2bbefc74c0d9016539ba2a9d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20De=20Freitas?= <6485562+adefreitas@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:35:53 +0000 Subject: [PATCH 4/5] test(calendar): express arrows-never-change-a-setting for the calendar rows --- .../SettingsCategoryTests.swift | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift index d905fb08..a5e86da8 100644 --- a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift +++ b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift @@ -261,14 +261,31 @@ final class SettingsCategoryTests: XCTestCase { .calendarWeekdaysOnly, .calendarSummaryEmpty, .calendarDetectJoin]) } - // Every calendar row is a toggle or a cycle, so arrows act on it. - func testArrowsActOnEveryCalendarRow() { + // Toggles flip on Space / ⏎ and ignore the arrows. The two value rows (lead + // time, summary time) pick: arrows step them only once Space has started it. + func testOnlyTheCalendarValueRowsPickAndArrowsLeaveThemAloneUntilThen() { let nav = PanelNav() nav.settingsCategory = .calendar + let pickers: [SettingsRow] = [.calendarLead, .calendarSummaryTime] for row in nav.rows(in: .calendar) { nav.selectedSettingIndex = nav.index(of: row) ?? 0 XCTAssertEqual(nav.selectedRow, row) - XCTAssertTrue(nav.selectedRowRespondsToArrows, "\(row)") + XCTAssertEqual(nav.selectedRowIsPicker, pickers.contains(row), "\(row)") + } + + let lead = nav.calendarLeadMinutes + let time = nav.calendarSummaryMinutes + for row in pickers { + nav.selectedSettingIndex = nav.index(of: row) ?? 0 + nav.cycleForward() + nav.cycleBackward() + XCTAssertEqual(nav.calendarLeadMinutes, lead, "arrows must not step \(row) nobody picked") + XCTAssertEqual(nav.calendarSummaryMinutes, time, "arrows must not step \(row) nobody picked") + XCTAssertFalse(nav.pickingValue) + nav.activate() + XCTAssertTrue(nav.pickingValue, "\(row) starts picking on ⏎") + nav.activate() + XCTAssertFalse(nav.pickingValue) } } From 174b6b35dba033307fdee6b447cf39e5847d0e54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20De=20Freitas?= <6485562+adefreitas@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:23:10 +0000 Subject: [PATCH 5/5] test(calendar): calendar events replace by key and reach MCP as nudges --- .../StackNudgePanelCoreTests/FeedEventTests.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Tests/StackNudgePanelCoreTests/FeedEventTests.swift b/Tests/StackNudgePanelCoreTests/FeedEventTests.swift index 75a9c53d..1fd2b4be 100644 --- a/Tests/StackNudgePanelCoreTests/FeedEventTests.swift +++ b/Tests/StackNudgePanelCoreTests/FeedEventTests.swift @@ -244,6 +244,21 @@ final class FeedEventTests: XCTestCase { XCTAssertNil(store.selectedID) } + func testCalendarEventsReplaceByKeyAndReachMCPAsNudges() { + let store = EventStore() + func meeting(_ title: String) -> NudgeEvent { + .feed(source: .calendar, tag: "calendar", severity: .action, title: title, message: "10:00 to 10:30", + key: "meeting:1") + } + let first = meeting("Standup starts in 10 min") + store.append(first) + store.append(meeting("Standup moved to 11:00")) + XCTAssertEqual(store.events.map(\.title), ["Standup moved to 11:00"], "a keyed calendar event replaces, never groups") + let occurrence = MCPAppEvents.occurrence(for: first) + XCTAssertEqual(occurrence?.name, "nudge.raised") + XCTAssertEqual(occurrence?.data["source"] as? String, "calendar") + } + // Two meetings at the same time differ only in their title. func testTwoFeedEventsWithTheSameBodyButDifferentTitlesBothLand() { let store = EventStore()