From bd35b083132ce15e197178182a7a9431c38437c3 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Fri, 27 Nov 2026 16:38:45 +0000 Subject: [PATCH 1/2] feat(events): spot a turn that ends on a question, and filter on it --- .../AgentQuestionTests.swift | 43 +++++++++++ .../EventListenerTests.swift | 25 +++++++ .../EventLogTests.swift | 10 +++ .../EventsListTests.swift | 67 ++++++++++++++--- docs/panel.md | 6 +- notify.sh | 16 ++++- panel/AgentQuestion.swift | 72 +++++++++++++++++++ panel/EventListener.swift | 14 ++-- panel/EventLog.swift | 7 +- panel/EventStore.swift | 24 ++++--- panel/EventsList.swift | 40 ++++++++--- panel/FeedStyle.swift | 4 ++ panel/Panel.swift | 21 ++++-- panel/ScreenshotRenderer.swift | 17 ++++- scripts/render-screenshots.sh | 2 +- 15 files changed, 321 insertions(+), 47 deletions(-) create mode 100644 Tests/StackNudgePanelCoreTests/AgentQuestionTests.swift create mode 100644 panel/AgentQuestion.swift diff --git a/Tests/StackNudgePanelCoreTests/AgentQuestionTests.swift b/Tests/StackNudgePanelCoreTests/AgentQuestionTests.swift new file mode 100644 index 00000000..d28b4404 --- /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 9dd07bbc..6bdaf120 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 c7f6dda6..5e200ce9 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 c11e6909..e080111d 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 510fea9f..e2e2b247 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 f775e81b..5a61560f 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 00000000..75d1bc84 --- /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 f7b1e408..ad214539 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 398fb4ad..b2b17fd4 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 33a17e9c..72371e10 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 2d652630..240759f7 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 982ea2c4..f3cdd2e2 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 95044ead..2d676a0f 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 250364b4..9f13ad7a 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 f7f78cf3..6216677b 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 From aae96b09c1bc78bda5497bd45cf07e04a0dc6ff4 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Mon, 30 Nov 2026 00:02:43 +0000 Subject: [PATCH 2/2] feat(history): return on a row focuses its session while it runs --- .../EventLogTests.swift | 33 +++++++++++++++++++ .../FooterHintTests.swift | 17 ++++++++++ docs/panel.md | 4 +-- panel/EventLog.swift | 10 ++++++ panel/Panel.swift | 29 ++++++++++++---- panel/PanelNav.swift | 12 ++++--- 6 files changed, 92 insertions(+), 13 deletions(-) diff --git a/Tests/StackNudgePanelCoreTests/EventLogTests.swift b/Tests/StackNudgePanelCoreTests/EventLogTests.swift index 5e200ce9..2c3504a7 100644 --- a/Tests/StackNudgePanelCoreTests/EventLogTests.swift +++ b/Tests/StackNudgePanelCoreTests/EventLogTests.swift @@ -188,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") diff --git a/Tests/StackNudgePanelCoreTests/FooterHintTests.swift b/Tests/StackNudgePanelCoreTests/FooterHintTests.swift index d8e88b6e..7b15254d 100644 --- a/Tests/StackNudgePanelCoreTests/FooterHintTests.swift +++ b/Tests/StackNudgePanelCoreTests/FooterHintTests.swift @@ -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 @@ -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) } diff --git a/docs/panel.md b/docs/panel.md index e2e2b247..502ad87b 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -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 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.** 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 diff --git a/panel/EventLog.swift b/panel/EventLog.swift index b2b17fd4..0416644e 100644 --- a/panel/EventLog.swift +++ b/panel/EventLog.swift @@ -9,6 +9,7 @@ import Foundation // hooks — that is meaningless once the process it referred to has exited. // Persisting only the descriptive fields means a replayed record cannot // masquerade as actionable: it has no FIFO to answer and no PID to focus. +// Focus goes through `liveSession`, which finds the session still running. struct EventRecord: Codable, Equatable, Identifiable { let at: Date let agent: String @@ -72,6 +73,15 @@ struct EventRecord: Codable, Equatable, Identifiable { } return false } + + // The running session this record came from, found by its Claude session id + // rather than anything stored about the pane: a pid or a tab id outlives + // its process and can be reused, but a session id belongs to one session. + // nil once that session has ended, and for agents whose hook sends no id. + func liveSession(in sessions: [Session]) -> Session? { + guard let session, !session.isEmpty else { return nil } + return sessions.first { $0.status == .active && $0.claudeSessionID == session } + } } // Reads and writes the JSONL log. File I/O is confined to `append` and `load`; diff --git a/panel/Panel.swift b/panel/Panel.swift index 2d676a0f..9496217f 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -546,9 +546,10 @@ struct PanelContentView: View { } } - // Durable log, newest first. Read-only by design: these records have no - // FIFO and no PID, so there is nothing here to approve or focus — which is - // exactly why they live behind the live queue rather than inside it. + // Durable log, newest first. These records have no FIFO and no PID, so + // there is nothing here to approve — which is exactly why they live behind + // the live queue rather than inside it. ⏎ can still bring a row's session + // forward, found among the running sessions by its id (EventRecord.liveSession). private var historyPane: some View { VStack(alignment: .leading, spacing: 0) { HStack(spacing: 6) { @@ -739,6 +740,7 @@ struct PanelContentView: View { dismissLabel: dismissLabel, snoozeEnabled: snoozeEnabled, muted: nav.isMuted, + historyCanFocus: nav.selectedHistoryRecord?.liveSession(in: sessions.sessions) != nil, feed: FeedFooterState(unread: store.unreadCount, feedCount: store.events.filter(\.isFeed).count, selectedIsFeed: store.selectedEvent?.isFeed == true, @@ -768,6 +770,7 @@ struct PanelContentView: View { dismissLabel: String, snoozeEnabled: Bool, muted: Bool, + historyCanFocus: Bool = false, feed: FeedFooterState = FeedFooterState()) -> [FooterHintSpec] { // "Mute" toggles to "Resume" while a timed mute is active — mirrors the // header bell and the menu-bar "Resume notifications" item. @@ -781,15 +784,18 @@ struct PanelContentView: View { // Focused, the field editor owns the keyboard and ↑↓ are caret // moves, so ⏎ hands it back to the rows without clearing what's been // typed. Unfocused, which is how the pane opens, the rows have the - // keyboard and / claims the field. + // keyboard and / claims the field. ⏎ on a row is offered only while + // that row's session is still running, since that is all it can reach. guard !filterFocused else { return [FooterHintSpec(label: "Rows", keys: ["⏎"])] } - return [ + let rowHints = [ FooterHintSpec(label: "Select", keys: ["↑↓", "⌘↑↓"]), FooterHintSpec(label: "Filter", keys: ["/"]), FooterHintSpec(label: "Back", keys: ["←"]), ] + guard historyCanFocus else { return rowHints } + return [FooterHintSpec(label: "Focus", keys: ["⏎"], primary: true)] + rowHints case .live where feed.confirmingClear: return [ @@ -4079,7 +4085,8 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, title: event.title, message: event.message, project: event.projectPath, - session: event.claudeSessionID), + session: event.claudeSessionID, + question: event.asksQuestion ? true : nil), at: 0) // Same ceiling the file gets, applied live. Without it a long-uptime // machine grows past the on-disk cap until relaunch, and the History @@ -5437,6 +5444,10 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, nav.focusHistoryFilter() case .moveSelection(let delta): nav.moveHistorySelection(delta) + case .focusSession: + if let session = nav.selectedHistoryRecord?.liveSession(in: sessions.sessions) { + focusSession(session) + } case .swallow: break } @@ -5550,8 +5561,10 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // ↑↓ by one row. ⌘↑↓ never reaches here — it's dispatched earlier via // jumpToEdge, which every page shares. case moveSelection(Int) + // ⏎ brings the selected row's session forward, while it is still running. + case focusSession // Never falls through to the live queue's shortcuts — they don't apply - // to a read-only log, and a → key repeat landing in the filter is + // to a log, and a → key repeat landing in the filter is // exactly what this stops. case swallow } @@ -5836,6 +5849,8 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, return .moveSelection(-1) case KeyCode.downArrow: return .moveSelection(1) + case KeyCode.returnKey, KeyCode.numpadEnter: + return .focusSession default: guard let characters, isFilterInput(characters) else { return .swallow } return .appendToFilter(characters) diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index 20acf094..032f7ade 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -1217,10 +1217,10 @@ final class PanelNav: ObservableObject { // Loaded once at launch and appended to in memory as events arrive, so the // pane never re-reads the file while the panel is open. @Published var historyRecords: [EventRecord] = [] - // Selected row in the history pane. The records carry no FIFO and no PID so - // there is nothing to act on, but ↑↓ / ⌘↑↓ moving a selection is how every - // other list in the panel reads, and it's the only way to walk a 30-day log - // from the keyboard. + // Selected row in the history pane. ↑↓ / ⌘↑↓ moving a selection is how + // every other list in the panel reads, and it's the only way to walk a + // 30-day log from the keyboard. ⏎ brings the row's session forward while it + // is still running; the record itself carries no FIFO and no PID. @Published var historySelectedID: EventRecord.ID? // Settings → Event history. Off stops recording; what's already on disk // stays readable until the user clears it. @@ -1228,6 +1228,10 @@ final class PanelNav: ObservableObject { func focusHistoryFilter() { historyFilterFocusRequests += 1 } + var selectedHistoryRecord: EventRecord? { + historySelectedID.flatMap { id in historyRecords.first { $0.id == id } } + } + // The rows the history pane is showing. Lives here rather than in the view // so the key handler moves the selection over exactly what's on screen. var filteredHistory: [EventRecord] {