Skip to content
Merged
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
43 changes: 43 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 Expand Up @@ -178,6 +188,39 @@ final class EventLogTests: XCTestCase {
XCTAssertTrue(record("anything").matches(""))
}

// MARK: - Live session

private func session(pid: Int, claudeSessionID: String?,
status: SessionStatus = .active) -> Session {
var session = Session(id: pid, pid: pid, agent: "claude",
projectPath: "/Users/x/Workspace/attack-lib", projectName: "attack-lib",
terminalPID: 2, terminalApp: "tmux", elapsed: nil,
customName: nil, status: status,
tabId: nil, tabName: nil, liveTitle: nil, liveTitleSource: nil)
session.claudeSessionID = claudeSessionID
return session
}

func test_liveSessionIsTheRunningSessionWithTheRecordsId() {
let sessions = [session(pid: 10, claudeSessionID: "sess-2"),
session(pid: 11, claudeSessionID: "sess-1")]
XCTAssertEqual(record("x").liveSession(in: sessions)?.pid, 11)
}

// A finished session's pane may be gone or hold something else by now.
func test_noLiveSessionOnceItHasFinished() {
let sessions = [session(pid: 11, claudeSessionID: "sess-1", status: .finished(at: now))]
XCTAssertNil(record("x").liveSession(in: sessions))
}

// Codex and older hooks send no session id; matching on nil would hand the
// row any session that has none either.
func test_aRecordWithoutASessionIdHasNoLiveSession() {
let unnamed = EventRecord(at: now, agent: "codex", kind: "stop", title: "Codex",
message: "x", project: nil, session: nil)
XCTAssertNil(unnamed.liveSession(in: [session(pid: 12, claudeSessionID: nil)]))
}

// The project field holds a full path; users search by the repo name.
func test_projectNameIsTheBasename() {
XCTAssertEqual(record("x").projectName, "attack-lib")
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")
}
}
17 changes: 17 additions & 0 deletions Tests/StackNudgePanelCoreTests/FooterHintTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,17 @@ final class EventsFooterHintsTests: XCTestCase {
XCTAssertEqual(actual[2].keys, ["←"])
}

// ⏎ is offered only while the selected row's session is still running.
func test_historyRowWithALiveSession_leadsWithFocus() {
let actual = PanelContentView.eventsFooterHints(
pane: .history, filterFocused: false, liveQueueEmpty: false,
primaryAction: nil, dismissLabel: "Dismiss", snoozeEnabled: false, muted: false,
historyCanFocus: true)
XCTAssertEqual(actual.map(\.label), ["Focus", "Select", "Filter", "Back"])
XCTAssertEqual(actual[0].keys, ["⏎"])
XCTAssertTrue(actual[0].primary)
}

func test_historyFocused_offersReturnToTheRows() {
// The field editor consumes ← and ↑↓ as caret moves once it has focus,
// so advertising them there would be a lie. ⏎ hands the keyboard back to
Expand Down Expand Up @@ -243,6 +254,12 @@ final class HistoryKeyActionTests: XCTestCase {
XCTAssertEqual(action(125, "\u{F701}"), .moveSelection(1))
}

// 36 ⏎, 76 keypad enter.
func test_returnFocusesTheRowsSession() {
XCTAssertEqual(action(36, "\r"), .focusSession)
XCTAssertEqual(action(76, "\u{3}"), .focusSession)
}

func test_slashFocusesTheFilterWithoutTypingIntoIt() {
XCTAssertEqual(action(44, "/"), .focusFilter)
}
Expand Down
8 changes: 4 additions & 4 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,9 +47,9 @@ 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; `⏎` on a row brings its session's pane forward while that Claude Code session is still running; start typing (or press `/`) to filter, `⏎` in the 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.
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 keeps no pid or pane of its own (its `⏎` finds the session by id, among those still running), so mixing the two would make those keys mean different things depending on which row you happened to land on.

## Sessions

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
Loading
Loading