diff --git a/Tests/StackNudgePanelCoreTests/AgentQuestionTests.swift b/Tests/StackNudgePanelCoreTests/AgentQuestionTests.swift new file mode 100644 index 0000000..d28b440 --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/AgentQuestionTests.swift @@ -0,0 +1,43 @@ +import XCTest + +@testable import StackNudgePanelCore + +final class AgentQuestionTests: XCTestCase { + + func testAClosingQuestionIsTheQuestion() { + XCTAssertEqual(AgentQuestion.question(in: "Should I raise it?"), "Should I raise it?") + XCTAssertEqual(AgentQuestion.question(in: "Tests pass. Want me to open the PR?\n\n"), + "Want me to open the PR?") + } + + func testOnlyTheLastLineCounts() { + XCTAssertNil(AgentQuestion.question(in: "Which one did you mean?\n\nI went with the first. Done.")) + XCTAssertNil(AgentQuestion.question(in: "Raised #291.")) + XCTAssertNil(AgentQuestion.question(in: "")) + XCTAssertNil(AgentQuestion.question(in: nil)) + XCTAssertNil(AgentQuestion.question(in: "?")) + } + + func testMarkupAroundTheQuestionIsIgnored() { + XCTAssertEqual(AgentQuestion.question(in: "**Want me to go ahead?**"), "Want me to go ahead?") + XCTAssertEqual(AgentQuestion.question(in: "Options:\n- Rebase now\n- Or wait for CI?"), "Or wait for CI?") + XCTAssertEqual(AgentQuestion.question(in: "1. Merge it?"), "Merge it?") + XCTAssertEqual(AgentQuestion.question(in: "> Ship it?"), "Ship it?") + XCTAssertEqual(AgentQuestion.question(in: "(Or should I leave it?)"), "Or should I leave it?") + } + + // "Shall I run this?" above the command is still the turn's question. + func testATrailingCodeBlockIsSkipped() { + let reply = "Shall I run this?\n\n```bash\nmake release\n```\n" + XCTAssertEqual(AgentQuestion.question(in: reply), "Shall I run this?") + XCTAssertNil(AgentQuestion.question(in: "```\nonly code?\n```")) + XCTAssertNil(AgentQuestion.question(in: "cut off mid-block\nis this?\n```")) + } + + func testALongQuestionIsCut() { + let long = String(repeating: "word ", count: 60) + "ok?" + let question = AgentQuestion.question(in: long) + XCTAssertEqual(question?.count, AgentQuestion.maxLength) + XCTAssertEqual(question?.last, "…") + } +} diff --git a/Tests/StackNudgePanelCoreTests/EventListenerTests.swift b/Tests/StackNudgePanelCoreTests/EventListenerTests.swift index 9dd07bb..6bdaf12 100644 --- a/Tests/StackNudgePanelCoreTests/EventListenerTests.swift +++ b/Tests/StackNudgePanelCoreTests/EventListenerTests.swift @@ -57,6 +57,31 @@ final class EventListenerTests: XCTestCase { XCTAssertTrue(e.hasActionButton) } + func test_parseEvents_stopEndingOnAQuestionShowsTheQuestion() { + let data = payload(#"{"agent":"claude-code","event":"stop","title":"Claude Code","message":"Done","last_message":"Tests pass.\n\nWant me to raise the PR?"}"#) + let event = EventListener.parseEvents(data)[0] + XCTAssertTrue(event.asksQuestion) + XCTAssertEqual(event.message, "Want me to raise the PR?") + } + + func test_parseEvents_stopWithoutAQuestionStaysDone() { + let finished = payload(#"{"agent":"codex","event":"stop","title":"Codex","message":"Done","last_message":"Raised #12."}"#) + let silent = payload(#"{"agent":"gemini","event":"stop","title":"Gemini","message":"Done"}"#) + for data in [finished, silent] { + let event = EventListener.parseEvents(data)[0] + XCTAssertFalse(event.asksQuestion) + XCTAssertEqual(event.message, "Done") + } + } + + // A prompt keeps its own message, and only a Stop is a finished turn. + func test_parseEvents_lastMessageIsReadOnlyOnStop() { + let data = payload(#"{"agent":"claude-code","event":"permission","title":"Claude Code","message":"rm -rf build","last_message":"Shall I?"}"#) + let event = EventListener.parseEvents(data)[0] + XCTAssertFalse(event.asksQuestion) + XCTAssertEqual(event.message, "rm -rf build") + } + func test_parseEvents_missingTimestampDefaultsToNow() { let before = Date() let data = payload(#""" diff --git a/Tests/StackNudgePanelCoreTests/EventLogTests.swift b/Tests/StackNudgePanelCoreTests/EventLogTests.swift index c7f6dda..5e200ce 100644 --- a/Tests/StackNudgePanelCoreTests/EventLogTests.swift +++ b/Tests/StackNudgePanelCoreTests/EventLogTests.swift @@ -25,6 +25,16 @@ final class EventLogTests: XCTestCase { XCTAssertEqual(EventLog.parse(line), [original]) } + func test_aQuestionRoundTripsAndIsFoundByTheWordQuestion() { + var asked = record("Want me to raise the PR?") + asked.question = true + guard let line = EventLog.encode(asked) else { return XCTFail("encode failed") } + XCTAssertEqual(EventLog.parse(line), [asked]) + XCTAssertTrue(asked.matches("question")) + XCTAssertFalse(record("Done").matches("question")) + XCTAssertFalse(EventLog.encode(record("Done"))?.contains("question") ?? true) + } + // One record per line is the format's only invariant — a pretty-printed // encoder would silently corrupt every subsequent read. func test_encodeProducesASingleLine() { diff --git a/Tests/StackNudgePanelCoreTests/EventsListTests.swift b/Tests/StackNudgePanelCoreTests/EventsListTests.swift index c11e690..e080111 100644 --- a/Tests/StackNudgePanelCoreTests/EventsListTests.swift +++ b/Tests/StackNudgePanelCoreTests/EventsListTests.swift @@ -13,6 +13,11 @@ final class EventsListTests: XCTestCase { timestamp: at) } + private func stop(asks: Bool) -> NudgeEvent { + NudgeEvent(agent: "claude-code", kind: .stop, title: "Claude Code", + message: asks ? "Want me to raise it?" : "Done", asksQuestion: asks) + } + private func prompt() -> NudgeEvent { NudgeEvent(agent: "claude-code", kind: .permission, title: "Claude Code", message: "Bash(ls)") } @@ -20,7 +25,7 @@ final class EventsListTests: XCTestCase { // MARK: Tag filter func testFilterStartsShowingEverythingAndChipsToggle() { - var filter = FeedTagFilter() + var filter = EventTagFilter() XCTAssertTrue(filter.shows("ci")) filter.toggle("ci") XCTAssertFalse(filter.shows("ci")) @@ -29,7 +34,7 @@ final class EventsListTests: XCTestCase { func testShowOnlyAndAllNone() { let present = ["ci", "review", "ready"] - var filter = FeedTagFilter() + var filter = EventTagFilter() filter.showOnly("review", among: present) XCTAssertEqual(present.filter(filter.shows), ["review"]) filter.toggleAll(among: present) @@ -40,7 +45,7 @@ final class EventsListTests: XCTestCase { func testApplyTogglesOrShowsOnlyAndAllNoneIgnoresOnly() { let present = ["ci", "review", "ready"] - var filter = FeedTagFilter() + var filter = EventTagFilter() filter.apply(.tag("ci"), only: false, among: present) XCTAssertEqual(present.filter(filter.shows), ["review", "ready"]) filter.apply(.tag("ci"), only: false, among: present) @@ -116,6 +121,49 @@ final class EventsListTests: XCTestCase { XCTAssertEqual(store.selectedID, visible.last) } + func testAgentTurnsFileUnderQuestionsAndDoneButPromptsHaveNoChip() { + let asked = stop(asks: true) + let finished = stop(asks: false) + XCTAssertEqual(EventTagFilter.key(for: asked), EventTagFilter.questionKey) + XCTAssertEqual(EventTagFilter.key(for: finished), EventTagFilter.doneKey) + XCTAssertNil(EventTagFilter.key(for: prompt())) + XCTAssertEqual(EventTagFilter.label(EventTagFilter.questionKey), "Questions") + XCTAssertEqual(EventTagFilter.label(EventTagFilter.doneKey), "Done") + } + + func testAgentChipsComeBeforeFeedTagsAndOnlyWhenPresent() { + let events = [feed("rev", tag: "review", key: "1"), stop(asks: false), feed("ci", key: "2"), stop(asks: true)] + XCTAssertEqual(EventTagFilter.present(in: events), + [EventTagFilter.questionKey, EventTagFilter.doneKey, "ci", "review"]) + XCTAssertEqual(EventTagFilter.present(in: [stop(asks: false), prompt()]), [EventTagFilter.doneKey]) + XCTAssertEqual(EventTagFilter.present(in: [prompt()]), []) + } + + func testOnlyQuestionsKeepsPromptsInView() { + let store = EventStore() + let asked = stop(asks: true) + let finished = stop(asks: false) + let waiting = prompt() + let ci = feed("ci", key: "1") + [finished, ci, waiting, asked].forEach(store.append) + store.tagFilter.showOnly(EventTagFilter.questionKey, among: store.presentTags) + XCTAssertEqual(Set(store.visibleEvents.map(\.id)), [asked.id, waiting.id]) + } + + func testFiltersHintNeedsOnlyAChipNotAFeed() { + let hints = PanelContentView.eventsFooterHints( + pane: .live, filterFocused: false, liveQueueEmpty: false, + primaryAction: "Open", dismissLabel: "Dismiss", snoozeEnabled: false, + muted: false, feed: FeedFooterState(hasChips: true)) + XCTAssertEqual(hints.filter { $0.shedOrder.map { $0 < 0 } == true }.map(\.keys), [["F"]]) + } + + func testQuestionAndDoneRowsShareTheirChipsColours() { + XCTAssertEqual(FeedStyle.color(tag: EventTagFilter.questionKey, source: .agent), .blue) + XCTAssertEqual(FeedStyle.color(tag: EventTagFilter.doneKey, source: .agent), .green) + XCTAssertEqual(FeedStyle.symbol(tag: EventTagFilter.questionKey, source: .agent), "questionmark.bubble.fill") + } + // MARK: Read state func testFeedStartsUnreadAndPromptsAreNotPartOfIt() { @@ -322,8 +370,9 @@ final class EventsListTests: XCTestCase { muted: false, feed: feed) } XCTAssertFalse(hints(FeedFooterState()).contains { $0.keys == ["F"] }) - XCTAssertEqual(hints(FeedFooterState(feedCount: 2)).first { $0.keys == ["F"] }?.label, "Filters") - let withFeed = hints(FeedFooterState(unread: 1, feedCount: 2, selectedIsFeed: true)) + XCTAssertEqual(hints(FeedFooterState(feedCount: 2, hasChips: true)).first { $0.keys == ["F"] }?.label, + "Filters") + let withFeed = hints(FeedFooterState(unread: 1, feedCount: 2, selectedIsFeed: true, hasChips: true)) XCTAssertEqual(withFeed.filter { $0.shedOrder.map { $0 < 0 } == true }.map(\.keys), [["F"], ["U"], ["A"], ["C"]]) let confirm = hints(FeedFooterState(feedCount: 2, confirmingClear: true)) @@ -340,9 +389,9 @@ final class EventsListTests: XCTestCase { } func testChipLabelsKeepAcronymsInCapitals() { - XCTAssertEqual(FeedTagFilter.label("ci"), "CI") - XCTAssertEqual(FeedTagFilter.label("pr-closed"), "PR closed") - XCTAssertEqual(FeedTagFilter.label("review-request"), "Review request") - XCTAssertEqual(FeedTagFilter.label("mcp"), "MCP") + XCTAssertEqual(EventTagFilter.label("ci"), "CI") + XCTAssertEqual(EventTagFilter.label("pr-closed"), "PR closed") + XCTAssertEqual(EventTagFilter.label("review-request"), "Review request") + XCTAssertEqual(EventTagFilter.label("mcp"), "MCP") } } diff --git a/docs/panel.md b/docs/panel.md index 510fea9..e2e2b24 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -24,7 +24,7 @@ Outside a text field, `←` is back a level on sub-pages and detail panes: out o ## Events -Recent nudges in chronological order. Each shows agent, message, project name, time. What happens to a permission prompt, reminders, feed events and Slack are in [notifications.md](notifications.md). +Recent nudges in chronological order. Each shows agent, message, project name, time. A finished turn that ended on a question to you shows the question instead of "Done", with a speech-bubble icon. The **Questions** and **Done** chips above the list filter those turns, beside one chip per feed tag (shift-⏎ or option-click a chip to show only that). Permission prompts have no chip and are never hidden. Spotting the question needs the agent's last reply, which Claude Code and Codex send on Stop; other agents' turns always read as done. What happens to a permission prompt, reminders, feed events and Slack are in [notifications.md](notifications.md). | Key | Action | |-----|--------| @@ -35,7 +35,7 @@ Recent nudges in chronological order. Each shows agent, message, project name, t | `M` | Mute all notifications for the configured duration (press again to resume) | | `⌫` / `⌦` / `R` | Dismiss the selected nudge locally | | `H` | Open the searchable history pane | -| `F` | Focus the tag chips above the list (feed events only); `F` or `↓` returns to the list | +| `F` | Focus the filter chips above the list; `F` or `↓` returns to the list | | `← →` `⏎` `Space` `⇧⏎` | On the chips: move, toggle the chip (or All/None), show only that tag | | `U` | Mark the selected feed event read or unread | | `A` | Mark all feed events read | @@ -47,7 +47,7 @@ When you press `⏎` on a permission event in a VS Code / Cursor terminal pane, **Mute for a while.** Press `M` (or use the bell button in the panel header, or the menu-bar **Mute notifications** submenu) to silence *everything* — banner, sound, voice, and the focus jump — for a set duration, **including permission prompts**. Events keep flowing into the panel while muted; only the interruptions are suppressed. A live countdown shows on the header bell and the menu-bar icon (the compact widget just shows a muted-bell glyph), and the mute lifts itself when the timer runs out (or immediately if you press `M` / **Resume** again). The default duration is configurable (`STACKNUDGE_MUTE_DURATION_MIN`, one of 15 / 30 / 60 / 120, default 30) and can be cycled in Settings. Mute is in-memory only — it resets on relaunch. -**History.** The list above is a live triage queue — capped, pruned per session, and gone when you quit. Press `H` for the durable log behind it: every nudge, newest first, with a filter box that matches on message, agent, and repo. `↑↓` and `⌘↑↓` walk the rows; start typing (or press `/`) to filter, `⏎` hands the keyboard back to the rows, and `←` steps back to the queue. +**History.** The list above is a live triage queue — capped, pruned per session, and gone when you quit. Press `H` for the durable log behind it: every nudge, newest first, with a filter box that matches on message, agent, and repo, and on `question` for the turns that asked you something. `↑↓` and `⌘↑↓` walk the rows; start typing (or press `/`) to filter, `⏎` hands the keyboard back to the rows, and `←` steps back to the queue. History is deliberately a separate pane rather than more rows in the queue. The queue is an action list — `⏎` approves, `⌫` dismisses — and a replayed record has no FIFO to answer and no process to focus, so mixing the two would make those keys mean different things depending on which row you happened to land on. diff --git a/notify.sh b/notify.sh index f775e81..5a61560 100755 --- a/notify.sh +++ b/notify.sh @@ -698,8 +698,9 @@ post_to_panel() { # Cap what the exec carries: env and argv share ARG_MAX (1 MiB on macOS), and a # PermissionRequest payload can hold a whole file's contents in tool_input. # Overflowing it fails the python3 exec, which would lose the event entirely. - # The fields read from it are a few hundred bytes deep in a Stop payload, so a - # 32 KiB cap never bites for the events that need them. + # A Stop payload also carries the agent's whole last reply, so a reply over + # the cap loses the fields read from it, the question check included; the + # event itself still arrives. local hook_json="$HOOK_JSON" (( ${#hook_json} > 32768 )) && hook_json="" @@ -762,6 +763,16 @@ def hook_field(name): value = parsed.get(name) return value if isinstance(value, str) and value else None +# The end of the agent's last reply (Claude Code and Codex send it on Stop), so +# the app can tell a turn that ends on a question from one that finished. Only +# the tail is needed, and it keeps the socket line small. A subagent's reply is +# addressed to the agent that launched it, never to you. +def last_message(): + if env["NUDGE_EVENT"] != "stop" or hook_field("hook_event_name") == "SubagentStop": + return None + reply = hook_field("last_assistant_message") + return reply[-2000:] if reply else None + out = { "agent": env["NUDGE_AGENT"], "event": env["NUDGE_EVENT"], @@ -789,6 +800,7 @@ optional = { "iterm_tab_name": env.get("NUDGE_ITERM_TAB_NAME"), "claude_session_id": hook_field("session_id"), "transcript_path": hook_field("transcript_path"), + "last_message": last_message(), "voice_message": env.get("NUDGE_VOICE_MESSAGE"), "voice_template": env.get("NUDGE_VOICE_TEMPLATE"), "sound_name": env.get("NUDGE_SOUND"), diff --git a/panel/AgentQuestion.swift b/panel/AgentQuestion.swift new file mode 100644 index 0000000..75d1bc8 --- /dev/null +++ b/panel/AgentQuestion.swift @@ -0,0 +1,72 @@ +import Foundation + +// Whether an agent's turn ended on a question to you, read from the end of its +// last reply. The hook sends that tail on Stop (Claude Code and Codex both put +// the reply in `last_assistant_message`); an agent that sends nothing is done. +// +// Deliberately a heuristic on the closing line rather than a reading of the +// whole reply: an agent that asks something asks it last, and one that asked +// mid-reply and went on to finish the work is not waiting on you. +enum AgentQuestion { + + // Long enough for any closing question, short enough that the banner and + // the row still read as one line or two. + static let maxLength = 160 + + // The question the reply ends on, ready to show in place of "Done", or nil + // when the turn ended on anything else. + static func question(in reply: String?) -> String? { + guard let reply, let line = closingLine(of: reply) else { return nil } + let text = strippedMarkup(line) + guard text.hasSuffix("?") else { return nil } + let sentence = lastSentence(of: text) + guard sentence.count > 1 else { return nil } + return truncated(sentence) + } + + // The last line of prose. A trailing code block is skipped, since a reply + // that asks "Shall I run this?" above the command still asks it. + private static func closingLine(of reply: String) -> String? { + var lines = reply.components(separatedBy: .newlines) + .map { $0.trimmingCharacters(in: .whitespaces) } + while let last = lines.last { + if last.isEmpty { + lines.removeLast() + } else if last.hasPrefix("```") { + lines.removeLast() + guard let opener = lines.lastIndex(where: { $0.hasPrefix("```") }) else { return nil } + lines.removeSubrange(opener...) + } else { + return last + } + } + return nil + } + + // List markers, quote markers, emphasis and wrapping punctuation would hide + // the closing "?" ("**Want me to raise it?**", "- Or wait for CI?)"). + private static func strippedMarkup(_ line: String) -> String { + var text = line + for marker in ["> ", "- ", "* ", "+ "] where text.hasPrefix(marker) { + text.removeFirst(marker.count) + } + if let range = text.range(of: #"^\d+[.)] "#, options: .regularExpression) { + text.removeSubrange(range) + } + let wrapping = CharacterSet(charactersIn: "*_`\"'“”‘’()[]").union(.whitespaces) + return text.trimmingCharacters(in: wrapping) + } + + // "Done, tests pass. Want me to raise the PR?" shows the question alone. + private static func lastSentence(of text: String) -> String { + let body = text.dropLast() + guard let boundary = body.range(of: #"[.!?:]\s"#, options: [.regularExpression, .backwards]) + else { return text } + return String(text[boundary.upperBound...]).trimmingCharacters(in: .whitespaces) + } + + private static func truncated(_ sentence: String) -> String { + guard sentence.count > maxLength else { return sentence } + return String(sentence.prefix(maxLength - 1)).trimmingCharacters(in: .whitespaces) + "…" + } +} diff --git a/panel/EventListener.swift b/panel/EventListener.swift index f7b1e40..ad21453 100644 --- a/panel/EventListener.swift +++ b/panel/EventListener.swift @@ -177,6 +177,9 @@ private struct NudgeEventDTO: Decodable { // Populated only for Claude Code hook events; nil for other agents. let claude_session_id: String? let transcript_path: String? + // The end of the agent's last reply, sent on Stop so the app can tell a + // turn that asks you something from one that finished. + let last_message: String? // Feed fields, for scripts posting their own events. All optional; an // agent hook sends none of them. let source: String? @@ -229,13 +232,15 @@ private struct NudgeEventDTO: Decodable { func toNudgeEvent() -> NudgeEvent { let isFeed = Self.feedSource(source) != .agent + // A feed is never a prompt, whatever it claims, so it also loses the + // fields that make a prompt answerable. + let kind: NudgeKind = isFeed ? .other : NudgeKind(rawWireValue: event) + let question = kind == .stop ? AgentQuestion.question(in: last_message) : nil return NudgeEvent( agent: agent, - // A feed is never a prompt, whatever it claims, so it also loses - // the fields that make a prompt answerable. - kind: isFeed ? .other : NudgeKind(rawWireValue: event), + kind: kind, title: title, - message: message, + message: question ?? message, projectPath: project_path, bundleID: bundle_id, windowTitle: window_title, @@ -257,6 +262,7 @@ private struct NudgeEventDTO: Decodable { bypassMute: bypass_mute ?? false, claudeSessionID: claude_session_id, transcriptPath: transcript_path, + asksQuestion: question != nil, source: Self.feedSource(source), tag: tag, severity: severity.flatMap(EventSeverity.init(rawValue:)) ?? .info, diff --git a/panel/EventLog.swift b/panel/EventLog.swift index 398fb4a..b2b17fd 100644 --- a/panel/EventLog.swift +++ b/panel/EventLog.swift @@ -34,6 +34,9 @@ struct EventRecord: Codable, Equatable, Identifiable { var removed: Bool? = nil // The service extension a feed event came from, for source "extension". var extensionID: String? = nil + // A Stop that ended on a question (NudgeEvent.asksQuestion). Absent rather + // than false otherwise, so a done turn's line is unchanged. + var question: Bool? = nil static let markerKind = "state" @@ -61,7 +64,9 @@ struct EventRecord: Codable, Equatable, Identifiable { let q = needle.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) guard !q.isEmpty else { return true } - for field in [message, title, agent, projectName ?? "", source ?? "", tag ?? ""] { + // "question" finds the turns that asked you something, whatever they asked. + let kindWord = question == true ? "question" : "" + for field in [message, title, agent, projectName ?? "", source ?? "", tag ?? "", kindWord] { if field.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil).contains(q) { return true } } diff --git a/panel/EventStore.swift b/panel/EventStore.swift index 33a17e9..72371e1 100644 --- a/panel/EventStore.swift +++ b/panel/EventStore.swift @@ -127,6 +127,10 @@ struct NudgeEvent: Identifiable, Equatable { // Code hook events; nil for other agents. let claudeSessionID: String? let transcriptPath: String? + // A Stop whose reply ended on a question to you (AgentQuestion), so the + // Events filter can tell "waiting on your answer" from "finished". The + // question itself is in `message`, in place of "Done". + let asksQuestion: Bool // Feed fields; all nil or default for agent events. let source: EventSource // Groups feed events for filters and icons ("review", "ci", "calendar"). @@ -167,6 +171,7 @@ struct NudgeEvent: Identifiable, Equatable { bypassMute: Bool = false, claudeSessionID: String? = nil, transcriptPath: String? = nil, + asksQuestion: Bool = false, source: EventSource = .agent, tag: String? = nil, severity: EventSeverity = .info, @@ -206,6 +211,7 @@ struct NudgeEvent: Identifiable, Equatable { self.bypassMute = bypassMute self.claudeSessionID = claudeSessionID self.transcriptPath = transcriptPath + self.asksQuestion = asksQuestion self.source = source self.tag = tag self.severity = severity @@ -275,6 +281,7 @@ struct NudgeEvent: Identifiable, Equatable { bypassMute: bypassMute, claudeSessionID: claudeSessionID, transcriptPath: transcriptPath, + asksQuestion: asksQuestion, source: source, tag: tag, severity: severity, url: url, repo: repo, pr: pr, key: key, isRead: isRead, members: members, @@ -291,7 +298,7 @@ final class EventStore: ObservableObject { @Published var selectedID: NudgeEvent.ID? // Per session, never persisted: a filter left on from yesterday would hide // today's events with no sign of why. - @Published var tagFilter = FeedTagFilter() { + @Published var tagFilter = EventTagFilter() { didSet { if !visibleEvents.contains(where: { $0.id == selectedID }) { selectedID = visibleEvents.first?.id @@ -439,7 +446,8 @@ final class EventStore: ObservableObject { repo: event.repo, pr: event.pr, key: event.key, - extensionID: event.extensionID)) + extensionID: event.extensionID, + question: event.asksQuestion ? true : nil)) onAppend?(event) if ProcessInfo.processInfo.environment["STACKNUDGE_PANEL_DEBUG"] != nil { FileHandle.standardError.write(Data( @@ -538,7 +546,7 @@ final class EventStore: ObservableObject { var pendingCount: Int { events.filter { !$0.isFeed || !$0.isRead }.count } func unreadCount(forTag tag: String) -> Int { - events.filter { $0.isUnread && FeedTagFilter.key(for: $0) == tag }.count + events.filter { $0.isUnread && EventTagFilter.key(for: $0) == tag }.count } func setRead(id: NudgeEvent.ID, _ read: Bool) { @@ -624,15 +632,15 @@ final class EventStore: ObservableObject { // MARK: - Filtering - // Agent events are never filtered: a hidden permission prompt would leave - // an agent blocked with nothing on screen to say so. + // Permission prompts are never filtered: a hidden one would leave an agent + // blocked with nothing on screen to say so. EventTagFilter gives them no key. var visibleEvents: [NudgeEvent] { - events.filter { !$0.isFeed || tagFilter.shows(FeedTagFilter.key(for: $0)) } + events.filter { event in EventTagFilter.key(for: event).map(tagFilter.shows) ?? true } } - // Feed tags in the list, in the order chips show them. + // Filter keys in the list, in the order chips show them. var presentTags: [String] { - FeedTagFilter.present(in: events) + EventTagFilter.present(in: events) } // Replace the event in-place with a new copy that has snoozedUntil set diff --git a/panel/EventsList.swift b/panel/EventsList.swift index 2d65263..240759f 100644 --- a/panel/EventsList.swift +++ b/panel/EventsList.swift @@ -1,18 +1,34 @@ import SwiftUI -// Which feed tags the Events tab shows. Agent events are never filtered, so -// this only ever narrows the feed rows. -struct FeedTagFilter: Equatable { +// Which rows the Events tab shows: a chip per feed tag, and Questions and Done +// for the turns agents ended. Permission prompts never have a chip, so they are +// never hidden (see EventStore.visibleEvents). +struct EventTagFilter: Equatable { private(set) var hidden: Set = [] - // Feeds send open-ended tags; an untagged event files under "other". - static func key(for event: NudgeEvent) -> String { + // Feed tags are whatever the feed sends, so the agent keys carry a prefix + // no feed is expected to use. + static let questionKey = "agent:question" + static let doneKey = "agent:done" + + // The chip a row files under, or nil for a row no chip may hide. Feeds send + // open-ended tags; an untagged feed event files under "other". + static func key(for event: NudgeEvent) -> String? { + guard event.isFeed else { + guard event.kind == .stop else { return nil } + return event.asksQuestion ? questionKey : doneKey + } let tag = event.tag?.trimmingCharacters(in: .whitespaces) ?? "" return tag.isEmpty ? "other" : tag } // "review-request" reads as "Review request"; acronyms stay in capitals ("CI", "PR closed"). static func label(_ tag: String) -> String { + switch tag { + case questionKey: return "Questions" + case doneKey: return "Done" + default: break + } let words = tag.split(separator: "-").map { word in acronyms.contains(word.lowercased()) ? word.uppercased() : String(word) }.joined(separator: " ") @@ -21,9 +37,13 @@ struct FeedTagFilter: Equatable { private static let acronyms: Set = ["ci", "pr", "ai", "ui", "api", "mcp"] - // Tags of the feed events in the list, in the order chips show them. + // Keys of the rows in the list, in the order chips show them: the agent + // chips first, as they are the ones that answer "who is waiting on me". static func present(in events: [NudgeEvent]) -> [String] { - Array(Set(events.filter(\.isFeed).map(key(for:)))).sorted { label($0) < label($1) } + let keys = Set(events.compactMap(key(for:))) + let agent = [questionKey, doneKey].filter(keys.contains) + let feed = keys.subtracting(agent).sorted { label($0) < label($1) } + return agent + feed } func shows(_ tag: String) -> Bool { !hidden.contains(tag) } @@ -168,7 +188,7 @@ struct EventTimeLabel: View { } } -// One chip per feed tag present, plus All/None. Option-click shows that tag +// One chip per filter key present, plus All/None. Option-click shows that tag // only. `focused` is the chip the keyboard is on, nil while the list has it. struct FeedTagChips: View { @ObservedObject var store: EventStore @@ -203,7 +223,7 @@ struct FeedTagChips: View { private func tagChip(_ tag: String, present: [String]) -> some View { let source = sourceForTag(tag) - return chip(.tag(tag), label: FeedTagFilter.label(tag), + return chip(.tag(tag), label: EventTagFilter.label(tag), symbol: FeedStyle.symbol(tag: tag, source: source), count: store.unreadCount(forTag: tag), color: FeedStyle.color(tag: tag, source: source), @@ -212,7 +232,7 @@ struct FeedTagChips: View { // A tag the style table does not know gets its source's icon and colour. private func sourceForTag(_ tag: String) -> EventSource { - store.events.first { $0.isFeed && FeedTagFilter.key(for: $0) == tag }?.source ?? .script + store.events.first { EventTagFilter.key(for: $0) == tag }?.source ?? .script } // Included: the tag's colour, softly filled. Excluded: outlined in it with diff --git a/panel/FeedStyle.swift b/panel/FeedStyle.swift index 982ea2c..f3cdd2e 100644 --- a/panel/FeedStyle.swift +++ b/panel/FeedStyle.swift @@ -22,6 +22,8 @@ enum FeedStyle { case "deploy": return "shippingbox.fill" case "pipeline": return "arrow.triangle.branch" case "calendar": return "calendar" + case EventTagFilter.questionKey: return "questionmark.bubble.fill" + case EventTagFilter.doneKey: return "checkmark.circle.fill" default: return sourceSymbol(source) } } @@ -41,6 +43,8 @@ enum FeedStyle { case "calendar": return .mint case "plan": return .teal case "audit": return .pink + case EventTagFilter.questionKey: return .blue + case EventTagFilter.doneKey: return .green default: return sourceColor(source) } } diff --git a/panel/Panel.swift b/panel/Panel.swift index 95044ea..2d676a0 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -746,7 +746,8 @@ struct PanelContentView: View { selectedExpandable: store.selectedEvent?.members.isEmpty == false, selectedExpanded: store.selectedID.map(store.expandedIDs.contains) == true, confirmingClear: nav.confirmingClear, - chipsFocused: chipFocus != nil) + chipsFocused: chipFocus != nil, + hasChips: !store.presentTags.isEmpty) ) return PageFooter { ForEach(hints.indices, id: \.self) { FooterHintRow(spec: hints[$0]) } @@ -834,9 +835,12 @@ struct PanelContentView: View { hints.append(FooterHintSpec(label: muteLabel, keys: ["M"])) hints.append(FooterHintSpec(label: "History", keys: ["H"])) // Feed shortcuts only exist while there is a feed to act on, and - // they shed before anything the bar already advertised. - if feed.feedCount > 0 { + // they shed before anything the bar already advertised. Filters + // also covers agent turns, so it needs only a chip to focus. + if feed.hasChips { hints.append(FooterHintSpec(label: "Filters", keys: ["F"], shedOrder: -4)) + } + if feed.feedCount > 0 { if feed.selectedExpandable { hints.append(FooterHintSpec(label: feed.selectedExpanded ? "Collapse" : "Expand", keys: ["Space"], shedOrder: -5)) @@ -890,7 +894,8 @@ private struct HistoryRow: View { var body: some View { HStack(alignment: .firstTextBaseline, spacing: 8) { Image(systemName: record.source.flatMap(EventSource.init(rawValue:)).map(FeedStyle.sourceSymbol) - ?? (record.kind == "permission" ? "hand.raised.fill" : "checkmark.circle")) + ?? (record.kind == "permission" ? "hand.raised.fill" + : record.question == true ? "questionmark.bubble" : "checkmark.circle")) .font(.caption2) .foregroundStyle(.tertiary) .frame(width: 14) @@ -936,6 +941,7 @@ struct FeedFooterState: Equatable { var selectedExpanded = false var confirmingClear = false var chipsFocused = false + var hasChips = false } struct EventRow: View { @@ -1151,13 +1157,16 @@ struct EventRow: View { private var glyph: String { if isSnoozed { return "moon.zzz.fill" } if event.isFeed { return FeedStyle.symbol(for: event) } - return event.kind == .permission ? "questionmark.circle.fill" : "checkmark.circle.fill" + if event.kind == .permission { return "questionmark.circle.fill" } + // A finished turn shares its icon and colour with its filter chip. + return FeedStyle.symbol(tag: EventTagFilter.key(for: event), source: .agent) } private var glyphColor: Color { if isSnoozed { return .gray } if event.isFeed { return FeedStyle.color(tag: event.tag, source: event.source) } - return event.kind == .permission ? .orange : .green + if event.kind == .permission { return .orange } + return FeedStyle.color(tag: EventTagFilter.key(for: event) ?? EventTagFilter.doneKey, source: .agent) } } diff --git a/panel/ScreenshotRenderer.swift b/panel/ScreenshotRenderer.swift index 250364b..9f13ad7 100644 --- a/panel/ScreenshotRenderer.swift +++ b/panel/ScreenshotRenderer.swift @@ -6,7 +6,7 @@ import SwiftUI // pages (`integrations`) and the MCP server's screens (`mcp`), for reviewers to // see each screen without installing anything. // -// StackNudge.app/Contents/MacOS/stack-nudge --render-screenshots [readme|extensions|integrations|mcp] +// StackNudge.app/Contents/MacOS/stack-nudge --render-screenshots [readme|events|extensions|integrations|mcp] // // The real SwiftUI views, at the panel's default size, in dark appearance, in // an offscreen window captured with cacheDisplay, which needs no Screen @@ -345,6 +345,15 @@ enum ScreenshotRenderer { let f = PanelFixture(mode: .events) return (f.view, { f.store.selectedID = f.store.events.first?.id }) }, + // Not a README picture: the Events filter narrowed to the turns that + // asked something. The prompt stays, as prompts are never filtered. + Scenario(name: "events-questions", set: "events", height: panelHeight) { + let f = PanelFixture(mode: .events) + return (f.view, { + f.store.tagFilter.showOnly(EventTagFilter.questionKey, among: f.store.presentTags) + f.store.selectFirst() + }) + }, Scenario(name: "sessions", set: "readme", height: panelHeight) { let f = PanelFixture(mode: .sessions) return (f.view, {}) @@ -442,8 +451,10 @@ enum ScreenshotRenderer { source: .github, tag: "review-request", severity: .action, url: URL(string: "https://github.com/acme/api/pull/318"), repo: "acme/api", pr: 318)) - store.append(NudgeEvent(agent: "claude", kind: .stop, title: "Claude Code", message: "Done", - projectPath: path("docs"), timestamp: now.addingTimeInterval(-3 * 60))) + store.append(NudgeEvent(agent: "claude", kind: .stop, title: "Claude Code", + message: "Want me to open the PR, or wait for CI first?", + projectPath: path("docs"), timestamp: now.addingTimeInterval(-3 * 60), + asksQuestion: true)) store.append(NudgeEvent(agent: "claude", kind: .permission, title: "Claude Code", message: "npm test -- --coverage", projectPath: path("web-app"), hasActionButton: true, timestamp: now.addingTimeInterval(-20), diff --git a/scripts/render-screenshots.sh b/scripts/render-screenshots.sh index f7f78cf..6216677 100755 --- a/scripts/render-screenshots.sh +++ b/scripts/render-screenshots.sh @@ -5,7 +5,7 @@ # installing anything. # Dev-only: see panel/ScreenshotRenderer.swift. # -# scripts/render-screenshots.sh [outdir] [readme|extensions|integrations|mcp] # default: build/screenshots, every set +# scripts/render-screenshots.sh [outdir] [readme|events|extensions|integrations|mcp] # default: build/screenshots, every set # # Builds the app, then runs its binary with --render-screenshots. Nothing is # read from or written to ~/.stack-nudge. The README's pictures are copied into