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
40 changes: 40 additions & 0 deletions Tests/StackNudgePanelCoreTests/EventsListTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,46 @@ final class EventsListTests: XCTestCase {
XCTAssertEqual(store.events.count, 3)
}

// GitHub's approved and changes-requested decisions are keyed review events.
// Folded into the comment row they vanished there and gave it their key,
// so the next decision replaced every comment.
func testAKeyedReviewEventStaysOutOfTheCommentGroup() {
let store = EventStore()
store.append(feed("first", tag: "review", repo: "o/r", pr: 7))
store.append(feed("second", tag: "review", repo: "o/r", pr: 7))
store.append(feed("approved", tag: "review", key: "decision:o/r#7", repo: "o/r", pr: 7))
XCTAssertEqual(store.events.count, 2)
XCTAssertEqual(store.events.first { $0.key == nil }?.members.count, 2)

store.append(feed("changes requested", tag: "review", key: "decision:o/r#7", repo: "o/r", pr: 7))
XCTAssertEqual(store.events.count, 2, "the decision replaces only itself")
XCTAssertEqual(store.events.first { $0.key == nil }?.members.count, 2, "the comments survive it")
XCTAssertEqual(store.events.first { $0.key != nil }?.message, "changes requested")
}

// MARK: Clear all

// A held C autorepeats, and the first repeat used to be read as the
// confirmation, clearing the feed without ever asking.
func testAHeldCDoesNotConfirmClearAll() {
// KeyCode is private to Panel.swift: C is 8 and ⌫ is 51.
let c: UInt16 = 8
XCTAssertEqual(PanelController.clearConfirmKeyAction(keyCode: c, shifted: false, isRepeat: true), .ignoreRepeat)
XCTAssertEqual(PanelController.clearConfirmKeyAction(keyCode: c, shifted: false, isRepeat: false), .clear)
XCTAssertEqual(PanelController.clearConfirmKeyAction(keyCode: c, shifted: true, isRepeat: false), .cancel)
XCTAssertEqual(PanelController.clearConfirmKeyAction(keyCode: 51, shifted: false, isRepeat: false),
.cancel)
}

func testLeavingEventsDisarmsClearAll() {
let nav = PanelNav()
nav.mode = .events
nav.confirmingClear = true
nav.mode = .sessions
nav.mode = .events
XCTAssertFalse(nav.confirmingClear)
}

func testMembersAreBoundedAndExpansionOnlyForGroups() {
let store = EventStore()
for i in 0..<(EventStore.maxMembers + 10) {
Expand Down
4 changes: 2 additions & 2 deletions Tests/StackNudgePanelCoreTests/GitHubFeedTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -287,13 +287,13 @@ final class GitHubCLITests: XCTestCase {

func testNumbersUseTypedFields() {
let args = GitHubCLI.graphQLArguments(body: #"{"query":"q","variables":{"n":3}}"#)
XCTAssertEqual(args, ["api", "graphql", "-f", "query=q", "-F", "n=3"])
XCTAssertEqual(args, ["api", "graphql", "--hostname", "github.com", "-f", "query=q", "-F", "n=3"])
}

// A first page sends `after: null`; refusing it failed every paged query.
func testNullVariablesAreLeftOut() {
let args = GitHubCLI.graphQLArguments(body: #"{"query":"q","variables":{"q":"x","after":null}}"#)
XCTAssertEqual(args, ["api", "graphql", "-f", "query=q", "-f", "q=x"])
XCTAssertEqual(args, ["api", "graphql", "--hostname", "github.com", "-f", "query=q", "-f", "q=x"])
}

func testAnythingElseIsRefused() {
Expand Down
45 changes: 45 additions & 0 deletions Tests/StackNudgePanelCoreTests/IntegrationPageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,51 @@ final class IntegrationPageTests: XCTestCase {
XCTAssertEqual(nav.selectedRow, .githubLinks)
}

// MARK: - The gh login

// `gh auth status` checks its token with github.com. It used to run on main
// at every config load for anyone with gh installed, GitHub on or not.
private func navCheckingGh(_ answer: Bool, asked: @escaping () -> Void) -> PanelNav {
let nav = PanelNav()
nav.checkGitHubCLILogin = { asked(); return answer }
nav.runOffMain = { $0() }
nav.runOnMain = { $0() }
return nav
}

func testTheGhLoginIsNotAskedWithGitHubOff() {
var asked = 0
let nav = navCheckingGh(true) { asked += 1 }
var done = false
nav.refreshGitHubCLILogin { done = true }
XCTAssertEqual(asked, 0)
XCTAssertFalse(nav.githubUsesCLILogin)
XCTAssertTrue(done, "the follow-up still runs")
}

func testTheGhLoginIsAskedOffMainOnceGitHubIsOn() {
var asked = 0
let nav = navCheckingGh(true) { asked += 1 }
var offMain = 0
nav.runOffMain = { offMain += 1; $0() }
nav.githubActivityEnabled = true
nav.refreshGitHubCLILogin()
XCTAssertEqual(asked, 1)
XCTAssertEqual(offMain, 1, "gh is asked off main")
XCTAssertTrue(nav.githubUsesCLILogin)
XCTAssertTrue(nav.githubSignedIn)
}

func testTurningGhOffInTheConfigSkipsTheCheck() {
var asked = 0
let nav = navCheckingGh(true) { asked += 1 }
nav.githubLinkingEnabled = true
nav.githubUseGH = false
nav.refreshGitHubCLILogin()
XCTAssertEqual(asked, 0)
XCTAssertFalse(nav.githubUsesCLILogin)
}

// MARK: - Status

func testSlackStatusSaysWhatsMissingBeforeWhetherItsOn() {
Expand Down
56 changes: 51 additions & 5 deletions Tests/StackNudgePanelCoreTests/SessionLauncherTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,26 @@ final class RecentSessionsTests: XCTestCase {
try line(["type": "user", "cwd": cwd, "message": ["content": name]])
.write(toFile: "\(project)/\(name).jsonl", atomically: true, encoding: .utf8)
}
try write("keep", cwd: existing)
try write("running", cwd: existing)
let keep = "0a1b2c3d-0000-4000-8000-000000000001"
let running = "0a1b2c3d-0000-4000-8000-000000000002"
try write(keep, cwd: existing)
try write(running, cwd: existing)
try write("agent-sub", cwd: existing)
try write("gone", cwd: root + "/deleted")
let ids = RecentSessions.load(root: root, excluding: ["running"]).map(\.id)
XCTAssertEqual(ids, ["keep"])
try write("0a1b2c3d-0000-4000-8000-000000000004", cwd: root + "/deleted")
let ids = RecentSessions.load(root: root, excluding: [running]).map(\.id)
XCTAssertEqual(ids, [keep])
}

// The id is typed into a shell, so a transcript named anything but the
// UUID Claude Code writes is not offered.
func testLoadSkipsATranscriptNotNamedLikeASession() throws {
let root = NSTemporaryDirectory() + "recent-\(UUID().uuidString)"
let project = root + "/-repo"
try FileManager.default.createDirectory(atPath: project, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(atPath: root) }
try line(["type": "user", "cwd": root, "message": ["content": "x"]])
.write(toFile: "\(project)/x$(touch pwned).jsonl", atomically: true, encoding: .utf8)
XCTAssertEqual(RecentSessions.load(root: root).map(\.id), [])
}
}

Expand All @@ -68,6 +82,38 @@ final class SessionLauncherTests: XCTestCase {
XCTAssertEqual(SessionLauncher.shellQuoted("it's"), "'it'\\''s'")
}

// Terminal and iTerm get `cd '<folder>'` typed into the login shell. A
// quote, a backslash or a control character could end the quoting early
// in some shells (fish reads \' inside single quotes as an escape), so
// such a folder is refused there. Ghostty takes the folder as a property.
func testAFolderThatCantBeTypedSafelyIsRefused() {
for folder in ["/r/it's", "/r/back\\slash", "/r/new\nline", "/r/bell\u{07}"] {
XCTAssertNil(SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .terminal), folder)
XCTAssertNil(SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .iterm), folder)
XCTAssertNotNil(SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .ghostty), folder)
}
}

// The folder and command reach osascript as arguments after `--`, never
// spliced into the script's source.
func testTheFolderAndCommandAreArgumentsNotScript() {
let folder = "/r/a \"b\" $(c)"
let terminal = SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .terminal)
XCTAssertEqual(terminal, ["-e", SessionLauncher.terminalScript, "--", "cd '/r/a \"b\" $(c)' && claude"])
let ghostty = SessionLauncher.osascriptArguments(cwd: folder, command: "claude", in: .ghostty)
XCTAssertEqual(ghostty, ["-e", SessionLauncher.ghosttyScript, "--", folder, "claude"])
for script in [SessionLauncher.terminalScript, SessionLauncher.itermScript, SessionLauncher.ghosttyScript] {
XCTAssertFalse(script.contains(folder))
}
}

func testOnlyAUUIDIsASessionID() {
XCTAssertTrue(SessionLauncher.isSessionID("0a1b2c3d-0000-4000-8000-000000000001"))
for id in ["-c", "-ac", "abc-123", "0a1b2c3d00004000800000000000001", ""] {
XCTAssertFalse(SessionLauncher.isSessionID(id), id)
}
}

func testResumeCommandQuotesTheID() {
let session = RecentSession(id: "abc-123", cwd: "/r", title: "t", date: Date())
XCTAssertEqual(SessionLauncher.resumeCommand(session), "claude --resume 'abc-123'")
Expand Down
9 changes: 7 additions & 2 deletions panel/EventStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -396,9 +396,14 @@ final class EventStore: ObservableObject {

// MARK: - Feed grouping

// Review feedback on the same PR from the same source.
// Review feedback on the same PR from the same source. Keyed events are
// never comments: a key means "this replaces its earlier self" (GitHub's
// approved and changes-requested decisions carry one), and folding one into
// the comment row would hide it there and hand the row its key, so the
// next decision would replace every comment with it.
static func groups(_ existing: NudgeEvent, with incoming: NudgeEvent) -> Bool {
guard existing.isFeed, incoming.isFeed,
incoming.key == nil, existing.key == nil,
incoming.tag == "review", existing.tag == "review",
existing.source == incoming.source,
let repo = incoming.repo, !repo.isEmpty, existing.repo == repo,
Expand All @@ -421,7 +426,7 @@ final class EventStore: ObservableObject {
? incoming.severity : previous.severity,
title: "\(all.count) new comments on \(name)#\(incoming.pr ?? 0)",
message: incoming.message, url: incoming.url ?? previous.url,
repo: incoming.repo, pr: incoming.pr, key: incoming.key ?? previous.key,
repo: incoming.repo, pr: incoming.pr, key: nil,
timestamp: incoming.timestamp, members: all, id: incoming.id)
}

Expand Down
4 changes: 3 additions & 1 deletion panel/GitHubCLI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ enum GitHubCLI {
guard let object = try? JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any],
let query = object["query"] as? String
else { return nil }
var args = ["api", "graphql", "-f", "query=\(query)"]
// github.com always: gh otherwise takes its host from GH_HOST, which
// the app inherits from whatever launched it.
var args = ["api", "graphql", "--hostname", "github.com", "-f", "query=\(query)"]
let variables = object["variables"] as? [String: Any] ?? [:]
for key in variables.keys.sorted() {
switch variables[key] {
Expand Down
29 changes: 25 additions & 4 deletions panel/Panel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4643,6 +4643,21 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,
isRepeat: event.isARepeat)
}

enum ClearConfirmKeyAction: Equatable {
case clear
case cancel
case ignoreRepeat
}

// The key that answers "Clear all?". A held C autorepeats, and its first
// repeat lands here about half a second after the press that asked, so a
// repeat answers nothing and the question stays up (AGENTS.md: destructive
// keys ignore autorepeat). A fresh C clears; any other key backs out.
static func clearConfirmKeyAction(keyCode: UInt16, shifted: Bool, isRepeat: Bool) -> ClearConfirmKeyAction {
if isRepeat { return .ignoreRepeat }
return keyCode == KeyCode.cKey && !shifted ? .clear : .cancel
}

enum SessionLaunchKeyAction: Equatable {
case resume
case newSession
Expand Down Expand Up @@ -5376,8 +5391,12 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,
// Clear all asks first. C confirms; anything else backs out, and the
// key is swallowed so a stray ⌫ can't also deny a prompt.
if nav.confirmingClear {
nav.confirmingClear = false
if event.keyCode == KeyCode.cKey, !shifted { store.clearFeed() }
switch Self.clearConfirmKeyAction(keyCode: event.keyCode, shifted: shifted,
isRepeat: event.isARepeat) {
case .clear: nav.confirmingClear = false; store.clearFeed()
case .cancel: nav.confirmingClear = false
case .ignoreRepeat: break
}
return true
}

Expand Down Expand Up @@ -5431,7 +5450,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,
case KeyCode.aKey:
store.markAllRead()
case KeyCode.cKey:
if store.events.contains(where: \.isFeed) { nav.confirmingClear = true }
if !event.isARepeat, store.events.contains(where: \.isFeed) { nav.confirmingClear = true }
case KeyCode.upArrow:
store.selectPrevious()
case KeyCode.downArrow:
Expand Down Expand Up @@ -5968,8 +5987,10 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,

private func launch(cwd: String, command: String) {
let terminal = SessionLauncher.terminal(configured: ConfigFile.read()["STACKNUDGE_SESSION_TERMINAL"])
// Refused (a folder that can't be typed safely in this terminal): the
// panel stays up and beeps rather than vanishing with nothing opened.
guard SessionLauncher.open(cwd: cwd, command: command, in: terminal) else { return NSSound.beep() }
hidePanel()
SessionLauncher.open(cwd: cwd, command: command, in: terminal)
}

private struct SessionMenuItem {
Expand Down
49 changes: 46 additions & 3 deletions panel/PanelNav.swift
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,9 @@ final class PanelNav: ObservableObject {
// when a tab is picked and when the panel reopens on a different tab.
didSet {
if mode != .settings, extensionTextEdit != nil { cancelExtensionTextEdit() }
if mode != .events { chipsFocused = false }
// An armed Clear all doesn't survive leaving the page: coming back
// and pressing C must ask again, not clear.
if mode != .events { chipsFocused = false; confirmingClear = false }
guard mode != oldValue else { return }
modeJustChanged = true
dropUpdateConfirmationIfLeft()
Expand Down Expand Up @@ -634,8 +636,15 @@ final class PanelNav: ObservableObject {
// (STACKNUDGE_GITHUB_ACTIVITY). Needs the same GitHub sign-in.
@Published var githubActivityEnabled: Bool = false
// STACKNUDGE_GITHUB_USE_GH, and whether the gh login is what's in use.
// The second is only ever known once a GitHub feature is on: see
// refreshGitHubCLILogin.
@Published var githubUseGH = true
@Published var githubUsesCLILogin = false
// `gh auth status` and the queues it runs across, injectable so a test can
// answer it without spawning gh.
var checkGitHubCLILogin: () -> Bool = { GitHubCLI.isLoggedIn() }
var runOffMain: (@escaping () -> Void) -> Void = { DispatchQueue.global(qos: .utility).async(execute: $0) }
var runOnMain: (@escaping () -> Void) -> Void = { DispatchQueue.main.async(execute: $0) }
// The PRs tab's data: the latest poll's snapshot and whose it is.
@Published var pullRequestSnapshot: GitHubFeed.Snapshot?
@Published var pullRequestLogin: String?
Expand Down Expand Up @@ -1937,8 +1946,8 @@ final class PanelNav: ObservableObject {
githubActivityEnabled = ConfigFile.bool(config, "STACKNUDGE_GITHUB_ACTIVITY", default: false)
hideShippedTickets = ConfigFile.bool(config, "STACKNUDGE_HIDE_SHIPPED", default: false)
githubUseGH = ConfigFile.bool(config, "STACKNUDGE_GITHUB_USE_GH", default: true)
githubUsesCLILogin = githubUseGH && GitHubCLI.isLoggedIn()
githubSignedIn = githubUsesCLILogin || GitHubAuth.token() != nil
refreshGitHubCLILogin()
quotaTrackingEnabled = ConfigFile.bool(config, "STACKNUDGE_QUOTA_TRACKING", default: true)
quotaAlertsEnabled = ConfigFile.bool(config, "STACKNUDGE_QUOTA_ALERTS", default: true)
quotaShowRemaining = ConfigFile.bool(config, "STACKNUDGE_QUOTA_SHOW_REMAINING", default: false)
Expand Down Expand Up @@ -2398,12 +2407,45 @@ final class PanelNav: ObservableObject {
// kicks an immediate PR fetch so chips appear without waiting for the next
// tab visit, on disable drops cached PR state so chips revert to the local
// outcome.
// Whether the gh login is in use. `gh auth status` checks its token with
// github.com, so it runs off main, where a slow network can't freeze the
// panel, and only once PR links or activity is on: nobody who never
// turned GitHub on has it contacted (PRIVACY.md). `then` runs on main
// with the answer applied.
func refreshGitHubCLILogin(then: (() -> Void)? = nil) {
guard githubUseGH, githubLinkingEnabled || githubActivityEnabled else {
applyGitHubCLILogin(false)
then?()
return
}
let check = checkGitHubCLILogin
let toMain = runOnMain
runOffMain { [weak self] in
let loggedIn = check()
toMain {
self?.applyGitHubCLILogin(loggedIn)
then?()
}
}
}

private func applyGitHubCLILogin(_ loggedIn: Bool) {
if githubUsesCLILogin != loggedIn { githubUsesCLILogin = loggedIn }
let signedIn = loggedIn || GitHubAuth.token() != nil
if githubSignedIn != signedIn { githubSignedIn = signedIn }
}

func toggleGithubLinking() {
githubLinkingEnabled.toggle()
ConfigFile.write(key: "STACKNUDGE_GITHUB",
value: githubLinkingEnabled ? "true" : "false")
if githubLinkingEnabled {
if githubSignedIn { refreshPullRequestsNow?() } else { startGithubSignIn?() }
// The gh login isn't known until a GitHub feature is on, so ask
// before deciding whether a sign-in is needed at all.
refreshGitHubCLILogin { [weak self] in
guard let self, self.githubLinkingEnabled else { return }
if self.githubSignedIn { self.refreshPullRequestsNow?() } else { self.startGithubSignIn?() }
}
} else {
pullRequestByBranch = [:]
githubSignIn = .idle
Expand Down Expand Up @@ -2588,6 +2630,7 @@ final class PanelNav: ObservableObject {
case .githubActivity:
githubActivityEnabled.toggle()
ConfigFile.write(key: "STACKNUDGE_GITHUB_ACTIVITY", value: githubActivityEnabled ? "true" : "false")
refreshGitHubCLILogin()
case .hideShipped:
toggleHideShipped()
case .slackEnabled:
Expand Down
Loading
Loading