Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Tests/StackNudgePanelCoreTests/AgentQuestionTests.swift
Original file line number Diff line number Diff line change
@@ -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, "…")
}
}
25 changes: 25 additions & 0 deletions Tests/StackNudgePanelCoreTests/EventListenerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(#"""
Expand Down
10 changes: 10 additions & 0 deletions Tests/StackNudgePanelCoreTests/EventLogTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
67 changes: 58 additions & 9 deletions Tests/StackNudgePanelCoreTests/EventsListTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,19 @@ 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)")
}

// MARK: Tag filter

func testFilterStartsShowingEverythingAndChipsToggle() {
var filter = FeedTagFilter()
var filter = EventTagFilter()
XCTAssertTrue(filter.shows("ci"))
filter.toggle("ci")
XCTAssertFalse(filter.shows("ci"))
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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))
Expand All @@ -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")
}
}
6 changes: 3 additions & 3 deletions docs/panel.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|-----|--------|
Expand All @@ -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 |
Expand All @@ -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.

Expand Down
16 changes: 14 additions & 2 deletions notify.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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=""

Expand Down Expand Up @@ -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"],
Expand Down Expand Up @@ -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"),
Expand Down
72 changes: 72 additions & 0 deletions panel/AgentQuestion.swift
Original file line number Diff line number Diff line change
@@ -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) + "…"
}
}
Loading
Loading