Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

feat: headSha-aware GitHub alerts and refresh-on-open (#185)

Louis28d045ca06aa
diff --git a/NotchBuddy/Sources/App/GitHubPulse.swift b/NotchBuddy/Sources/App/GitHubPulse.swift
index f4e0642f..c4ab5349 100644
--- a/NotchBuddy/Sources/App/GitHubPulse.swift
+++ b/NotchBuddy/Sources/App/GitHubPulse.swift
@@ -43,6 +43,7 @@ struct GitHubPR: Equatable {
var isDraft: Bool
var ci: CIState
var review: ReviewState
+ var headSha: String? = nil // oid of last commit; nil if not fetched
}
// MARK: - GitHubRepoCI
@@ -52,6 +53,7 @@ struct GitHubRepoCI: Equatable {
var url: String
var branch: String
var ci: CIState
+ var headSha: String? = nil // oid of HEAD commit; nil if not fetched
}
// MARK: - GitHubDetailSection
@@ -106,23 +108,18 @@ struct GitHubPulse: Equatable {
guard seenPR.insert(id).inserted else { continue } // skip duplicates
let isDraft = node["isDraft"] as? Bool ?? false
let reviewDecision = node["reviewDecision"] as? String
- let ciRaw: String? = {
+ let (ciRaw, headSha): (String?, String?) = {
guard let commits = node["commits"] as? [String: Any],
let cNodes = commits["nodes"] as? [[String: Any]],
let last = cNodes.last,
- let commit = last["commit"] as? [String: Any],
- let rollup = commit["statusCheckRollup"] as? [String: Any] else { return nil }
- return rollup["state"] as? String
+ let commit = last["commit"] as? [String: Any] else { return (nil, nil) }
+ let rollup = commit["statusCheckRollup"] as? [String: Any]
+ return (rollup?["state"] as? String, commit["oid"] as? String)
}()
myPRs.append(GitHubPR(
- id: id,
- title: title,
- url: url,
- repo: repo,
- number: number,
- isDraft: isDraft,
- ci: CIState(rawGitHub: ciRaw),
- review: ReviewState(rawGitHub: reviewDecision)
+ id: id, title: title, url: url, repo: repo, number: number,
+ isDraft: isDraft, ci: CIState(rawGitHub: ciRaw),
+ review: ReviewState(rawGitHub: reviewDecision), headSha: headSha
))
}
}
@@ -138,13 +135,13 @@ struct GitHubPulse: Equatable {
let url = node["url"] as? String,
let branchRef = node["defaultBranchRef"] as? [String: Any],
let branch = branchRef["name"] as? String else { continue }
- let ciRaw: String? = {
- guard let target = branchRef["target"] as? [String: Any],
- let rollup = target["statusCheckRollup"] as? [String: Any] else { return nil }
- return rollup["state"] as? String
+ let (ciRaw, headSha): (String?, String?) = {
+ guard let target = branchRef["target"] as? [String: Any] else { return (nil, nil) }
+ let rollup = target["statusCheckRollup"] as? [String: Any]
+ return (rollup?["state"] as? String, target["oid"] as? String)
}()
mainCI.append(GitHubRepoCI(repo: repo, url: url, branch: branch,
- ci: CIState(rawGitHub: ciRaw)))
+ ci: CIState(rawGitHub: ciRaw), headSha: headSha))
}
}
@@ -183,6 +180,12 @@ struct GitHubPulse: Equatable {
/// Returns events comparing old → new. If old is nil (first poll after launch) returns empty — no
/// alerts on initial load, only on subsequent changes.
+ ///
+ /// headSha logic (catches fast CIs missed between polls):
+ /// - Same SHA (or both nil): classic transition rules apply.
+ /// - Different SHA or PR/repo absent in old: fire immediately if CI is already done.
+ /// If still pending, nothing — next poll with the same SHA will catch the result.
+ /// - Main CI: no "green" alert, only .mainFailed on new failure.
static func events(old: GitHubPulse?, new: GitHubPulse) -> [GitHubEvent] {
guard let old else { return [] }
@@ -191,20 +194,32 @@ struct GitHubPulse: Equatable {
// PR CI transitions
let oldPRmap = Dictionary(old.myPRs.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
for pr in new.myPRs {
- guard let prev = oldPRmap[pr.id] else { continue }
- if pr.ci == .failure && prev.ci != .failure {
- result.append(.ciFailed(prId: pr.id))
- } else if pr.ci == .success && prev.ci == .pending {
- result.append(.ciPassed(prId: pr.id))
+ if let prev = oldPRmap[pr.id], prev.headSha == pr.headSha {
+ // Same commit: classic state-transition rules
+ if pr.ci == .failure && prev.ci != .failure {
+ result.append(.ciFailed(prId: pr.id))
+ } else if pr.ci == .success && prev.ci == .pending {
+ result.append(.ciPassed(prId: pr.id))
+ }
+ } else {
+ // New PR or new commit: alert if CI already finished
+ if pr.ci == .success { result.append(.ciPassed(prId: pr.id)) }
+ else if pr.ci == .failure { result.append(.ciFailed(prId: pr.id)) }
+ // pending → nothing; same-SHA rule catches it next poll
}
}
- // Default-branch CI failures
+ // Default-branch CI
let oldRepoMap = Dictionary(old.mainCI.map { ($0.repo, $0) }, uniquingKeysWith: { a, _ in a })
for repo in new.mainCI {
- guard let prev = oldRepoMap[repo.repo] else { continue }
- if repo.ci == .failure && prev.ci != .failure {
- result.append(.mainFailed(repo: repo.repo))
+ if let prev = oldRepoMap[repo.repo], prev.headSha == repo.headSha {
+ // Same commit: classic rule (failure transition only)
+ if repo.ci == .failure && prev.ci != .failure {
+ result.append(.mainFailed(repo: repo.repo))
+ }
+ } else {
+ // New repo or new commit: only alert on failure (no "green" event for main)
+ if repo.ci == .failure { result.append(.mainFailed(repo: repo.repo)) }
}
}
@@ -218,4 +233,12 @@ struct GitHubPulse: Equatable {
return result
}
+
+ // MARK: - Staleness
+
+ /// Pure predicate: true when fetchedAt is nil or older than maxAge seconds before now.
+ static func isStale(fetchedAt: Date?, now: Date = Date(), maxAge: TimeInterval) -> Bool {
+ guard let t = fetchedAt else { return true }
+ return now.timeIntervalSince(t) > maxAge
+ }
}
diff --git a/NotchBuddy/Sources/App/GithubPoller.swift b/NotchBuddy/Sources/App/GithubPoller.swift
index 22a539dd..1ceddcc0 100644
--- a/NotchBuddy/Sources/App/GithubPoller.swift
+++ b/NotchBuddy/Sources/App/GithubPoller.swift
@@ -131,6 +131,19 @@ final class GithubPoller: @unchecked Sendable {
}.resume()
}
+ /// Refreshes pulse data immediately if the last fetch is older than maxAge seconds (or absent).
+ /// No-op when a request is already in flight. Safe to call from any thread.
+ func refreshIfStale(maxAge: TimeInterval = 60) {
+ DispatchQueue.main.async { [weak self] in
+ guard let self, !self.pulseInFlight else { return }
+ guard GitHubPulse.isStale(fetchedAt: AppState.shared.githubPulse?.fetchedAt,
+ maxAge: maxAge) else { return }
+ self.nextPulse?.cancel()
+ self.nextPulse = nil
+ self.pollPulse()
+ }
+ }
+
/// Cancels any scheduled next poll, increments tokenGeneration to invalidate in-flight
/// responses, then fires pollPulse immediately. If a request is already in flight,
/// does not launch another — finishPulse will reschedule.
@@ -180,7 +193,7 @@ final class GithubPoller: @unchecked Sendable {
number title url isDraft reviewDecision
repository { nameWithOwner url }
commits(last: 1) {
- nodes { commit { statusCheckRollup { state } } }
+ nodes { commit { oid statusCheckRollup { state } } }
}
}
}
@@ -189,7 +202,7 @@ final class GithubPoller: @unchecked Sendable {
nameWithOwner url isArchived
defaultBranchRef {
name
- target { ... on Commit { statusCheckRollup { state } } }
+ target { ... on Commit { oid statusCheckRollup { state } } }
}
}
}
diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swift
index 16163f1f..92e6b0ec 100644
--- a/NotchBuddy/Sources/App/IslandViewContent.swift
+++ b/NotchBuddy/Sources/App/IslandViewContent.swift
@@ -144,21 +144,27 @@ struct OverviewView: View {
AgentPillsView(state: state)
}
}
- .onChange(of: state.focusId) { _, _ in
+ .onChange(of: state.focusId) { _, new in
showingN8nDetail = false
activeDiffId = nil
#if !APPSTORE
withAnimation(.easeIn(duration: 0.16)) { state.showingPlanDetail = false }
#endif
+ if new == "integration_github" { GithubPoller.shared.refreshIfStale() }
}
#if !APPSTORE
.onChange(of: state.view) { _, v in
if v != .overview { state.showingPlanDetail = false; activeDiffId = nil }
}
+ #endif
.onChange(of: state.mode) { _, m in
+ #if !APPSTORE
if m != .expanded { state.showingPlanDetail = false; activeDiffId = nil }
+ #endif
+ if m == .expanded && state.focusId == "integration_github" {
+ GithubPoller.shared.refreshIfStale()
+ }
}
- #endif
}
private func openAgentTarget(_ task: AgentTask?) {
@@ -2497,6 +2503,7 @@ struct GitHubDetailView: View {
.frame(maxWidth: .infinity, alignment: .topLeading)
.padding(.top, 4)
.clipped()
+ .onAppear { GithubPoller.shared.refreshIfStale() }
.onExitCommand { onBack() }
}
}
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
index 3dd8fe33..6a35ec80 100644
--- a/docs/INTEGRATIONS.md
+++ b/docs/INTEGRATIONS.md
@@ -147,12 +147,14 @@ Sur `PostToolUse` pour `Edit`, `MultiEdit` et `Write` (Claude Code, Cursor), l'a
Une seule requête GraphQL (POST `https://api.github.com/graphql`) :
-- **Mes PRs ouvertes** (20 dernières par date de mise à jour) : numéro, titre, URL, isDraft, `reviewDecision`, état CI du dernier commit (`statusCheckRollup.state`)
+- **Mes PRs ouvertes** (20 dernières par date de mise à jour) : numéro, titre, URL, isDraft, `reviewDecision`, `oid` du dernier commit, état CI du dernier commit (`statusCheckRollup.state`)
- **PRs à reviewer** (recherche `is:pr is:open review-requested:@me`, 20 max) : numéro, titre, URL, auteur
-- **CI branche par défaut** (10 derniers dépôts propres, non archivés) : état CI du dernier commit sur `defaultBranchRef`
+- **CI branche par défaut** (10 derniers dépôts propres, non archivés) : `oid` et état CI du commit HEAD sur `defaultBranchRef`
**Cadence** : 5 min (pas de PRs en attente) ou 60 s (au moins une PR/CI en état `PENDING` ou `EXPECTED`). La première requête part 10 s après le lancement.
+**Rafraîchissement à l'ouverture** : `GithubPoller.refreshIfStale(maxAge: 60)` est appelé dès que l'intégration prend le focus, quand l'île s'étend avec GitHub en focus, et à l'ouverture d'une vue détail GitHub. Si la dernière réponse date de moins de 60 s (ou si une requête est déjà en vol), l'appel est ignoré.
+
### États CI (`CIState`)
| Valeur GitHub | `CIState` |
@@ -164,7 +166,16 @@ Une seule requête GraphQL (POST `https://api.github.com/graphql`) :
### Alertes
-Déclenchées uniquement si l'état **change** entre deux polls (premier poll silencieux) :
+Premier poll après lancement : toujours silencieux. Polls suivants :
+
+**Même `headSha` (oid) qu'au poll précédent** — règles classiques de transition :
+- CI passe de `!failure` → `failure` : `.ciFailed` / `.mainFailed`
+- CI passe de `pending` → `success` : `.ciPassed`
+
+**`headSha` différent ou PR/dépôt absent au poll précédent** (nouveau commit ou nouvelle PR, CI déjà terminée avant le poll) :
+- CI = `success` → `.ciPassed` (PR uniquement ; pas d'alerte vert pour main)
+- CI = `failure` → `.ciFailed` / `.mainFailed`
+- CI = `pending` → rien (le poll suivant, même sha, verra la transition)
| Événement | Badge | Son |
|-----------------------|---------|------------|
diff --git a/tests/GitHubPulseTests.swift b/tests/GitHubPulseTests.swift
index b633f3b3..b3d74236 100644
--- a/tests/GitHubPulseTests.swift
+++ b/tests/GitHubPulseTests.swift
@@ -268,6 +268,81 @@ enum GitHubPulseTests {
events.filter { if case .ciPassed = $0 { return true }; return false }.count == 1)
}
+ // ── GitHubPulse.events — headSha: new PR already green ───────────────
+ print("GitHubPulse.events — headSha: new PR already green")
+ do {
+ let old = GitHubPulse.parse(emptyJSON)!
+ var newPulse = old
+ newPulse.myPRs = [GitHubPR(id: "r/p#10", title: "T", url: "", repo: "r/p",
+ number: 10, isDraft: false, ci: .success, review: .unknown,
+ headSha: "abc111")]
+ let events = GitHubPulse.events(old: old, new: newPulse)
+ check("new PR green → ciPassed", events == [.ciPassed(prId: "r/p#10")])
+ }
+
+ // ── GitHubPulse.events — headSha: new PR pending → nothing ───────────
+ print("GitHubPulse.events — headSha: new PR pending → nothing")
+ do {
+ let old = GitHubPulse.parse(emptyJSON)!
+ var newPulse = old
+ newPulse.myPRs = [GitHubPR(id: "r/p#11", title: "T", url: "", repo: "r/p",
+ number: 11, isDraft: false, ci: .pending, review: .unknown,
+ headSha: "abc222")]
+ let events = GitHubPulse.events(old: old, new: newPulse)
+ check("new PR pending → no events", events.isEmpty)
+ }
+
+ // ── GitHubPulse.events — headSha: new commit already red ─────────────
+ print("GitHubPulse.events — headSha: new commit already red → ciFailed")
+ do {
+ var oldPulse = GitHubPulse.parse(emptyJSON)!
+ oldPulse.myPRs = [GitHubPR(id: "r/p#12", title: "T", url: "", repo: "r/p",
+ number: 12, isDraft: false, ci: .success, review: .unknown,
+ headSha: "sha-old")]
+ var newPulse = oldPulse
+ newPulse.myPRs[0].ci = .failure
+ newPulse.myPRs[0].headSha = "sha-new"
+ let events = GitHubPulse.events(old: oldPulse, new: newPulse)
+ check("new commit red → ciFailed", events == [.ciFailed(prId: "r/p#12")])
+ }
+
+ // ── GitHubPulse.events — headSha: same sha success→success → nothing ─
+ print("GitHubPulse.events — headSha: same sha success→success → nothing")
+ do {
+ var oldPulse = GitHubPulse.parse(emptyJSON)!
+ oldPulse.myPRs = [GitHubPR(id: "r/p#13", title: "T", url: "", repo: "r/p",
+ number: 13, isDraft: false, ci: .success, review: .unknown,
+ headSha: "same")]
+ let newPulse = oldPulse // identical SHA and CI
+ let events = GitHubPulse.events(old: oldPulse, new: newPulse)
+ check("same sha success→success → no event", events.isEmpty)
+ }
+
+ // ── GitHubPulse.events — headSha: new commit on main red → mainFailed ─
+ print("GitHubPulse.events — headSha: new commit on main red → mainFailed")
+ do {
+ var oldPulse = GitHubPulse.parse(emptyJSON)!
+ oldPulse.mainCI = [GitHubRepoCI(repo: "a/b", url: "", branch: "main",
+ ci: .success, headSha: "sha-old")]
+ var newPulse = oldPulse
+ newPulse.mainCI[0].ci = .failure
+ newPulse.mainCI[0].headSha = "sha-new"
+ let events = GitHubPulse.events(old: oldPulse, new: newPulse)
+ check("new commit on main red → mainFailed", events == [.mainFailed(repo: "a/b")])
+ }
+
+ // ── GitHubPulse.isStale ───────────────────────────────────────────────
+ print("GitHubPulse.isStale")
+ do {
+ let now = Date()
+ check("nil fetchedAt → stale",
+ GitHubPulse.isStale(fetchedAt: nil, now: now, maxAge: 60))
+ check("fresh (same instant) → not stale",
+ !GitHubPulse.isStale(fetchedAt: now, now: now, maxAge: 60))
+ check("61 s ago → stale",
+ GitHubPulse.isStale(fetchedAt: now.addingTimeInterval(-61), now: now, maxAge: 60))
+ }
+
// ── finish ─────────────────────────────────────────────────────────────
if failures == 0 {
print("\nAll tests passed.")