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.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
GitHub pulse: open PRs, CI status and reviews in the notch (#181)
Louisdaa4bec4e227
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex ac7254e1..9a953a0d 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -36,6 +36,9 @@ jobs:- name: Diff engine testsrun: bash scripts/test-diff-engine.sh+ - name: GitHub pulse tests+ run: bash scripts/test-github-pulse.sh+- name: Buildrun: |xcodebuild \diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex 30bb0db3..9e8944b4 100644--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj@@ -29,6 +29,7 @@2DEB459FBD0BA3CEAAA5FDE9 /* ClaudeService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */; };2F36E3C6C073E968A682AFA4 /* NotionPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE03E03D1804B0B92C5C2DAD /* NotionPoller.swift */; };3756B7E1A55D9CEC8C4D34A4 /* IslandStateMachine.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8212018F09EA1E96FBD63CD /* IslandStateMachine.swift */; };+ 38EEB2D3A6EC538958D92575 /* GitHubPulse.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8D3AD61802A32C4833F3EDA /* GitHubPulse.swift */; };3F19756A396F125EC711247F /* IslandTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D3CE3617E9D336DDBA10F7A /* IslandTypes.swift */; };4117E7C8AA231AAE36E7509D /* UploadCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */; };4976F8BF814D6F817370F1D8 /* ChatMarkdownView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFE88A53AEAA637F866D479D /* ChatMarkdownView.swift */; };@@ -51,6 +52,7 @@78B3C6814431B2DD9D1F4949 /* SoundEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BE21C2B315D37AA70ED45E9 /* SoundEngine.swift */; };78FCEDC8F78B683AB10E6529 /* NotionPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE03E03D1804B0B92C5C2DAD /* NotionPoller.swift */; };7C75CCB3DC0116D8D3B12313 /* AskQuestion.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBB84A66045EB20CAC93A8A6 /* AskQuestion.swift */; };+ 862CE6CB220D55E46F646DA9 /* GitHubPulse.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8D3AD61802A32C4833F3EDA /* GitHubPulse.swift */; };878924960FC0F2B3524D48AC /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 192844E7299DEED5C2372067 /* AppDelegate.swift */; };8A6B3688D6B3BF728D106D8B /* UserIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4A13AEE6E06F46CEC9D908C /* UserIdentity.swift */; };8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */; };@@ -134,6 +136,7 @@F1BD8F3CAA60CF37640759E1 /* NotchBuddyApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotchBuddyApp.swift; sourceTree = "<group>"; };F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudePlanCardView.swift; sourceTree = "<group>"; };F4A13AEE6E06F46CEC9D908C /* UserIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserIdentity.swift; sourceTree = "<group>"; };+ F8D3AD61802A32C4833F3EDA /* GitHubPulse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GitHubPulse.swift; sourceTree = "<group>"; };FA02B08886939FF6FE0475DD /* IslandViewContent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandViewContent.swift; sourceTree = "<group>"; };/* End PBXFileReference section */@@ -156,6 +159,7 @@3DB24C2469551040FBAA4DBF /* DiffEngine.swift */,3232F258523DD8D09B670363 /* FileDropView.swift */,8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */,+ F8D3AD61802A32C4833F3EDA /* GitHubPulse.swift */,C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */,79D8DD79C3DD9BBC584B3CB2 /* HookServer.swift */,15A1A8206F73376F4CAF2057 /* IslandRootView.swift */,@@ -336,6 +340,7 @@2DEB459FBD0BA3CEAAA5FDE9 /* ClaudeService.swift in Sources */,6697436AA05A3F92C1DD85C3 /* DiffEngine.swift in Sources */,E776C7D1DE5C62EA8D4BA3E3 /* FileDropView.swift in Sources */,+ 862CE6CB220D55E46F646DA9 /* GitHubPulse.swift in Sources */,C808B654C84D9F71DBF8493A /* GithubPoller.swift in Sources */,8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */,2C798C3837A63B9BB561A1A0 /* HookServer.swift in Sources */,@@ -382,6 +387,7 @@0329E76BA4A8FEEA8A6D76E7 /* ClaudeService.swift in Sources */,C1A29371181553FB4169E195 /* DiffEngine.swift in Sources */,2132477000FD77F7EB234DAA /* FileDropView.swift in Sources */,+ 38EEB2D3A6EC538958D92575 /* GitHubPulse.swift in Sources */,C18227D148D99FE6EE3CC51A /* GithubPoller.swift in Sources */,C0E18D0F6F5F6D131E6066B8 /* GreetingCanvasView.swift in Sources */,9DD56C95ECABDDCE23652D50 /* HookServer.swift in Sources */,diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swiftindex 1b989da2..71f55bc6 100644--- a/NotchBuddy/Sources/App/AppState.swift+++ b/NotchBuddy/Sources/App/AppState.swift@@ -248,6 +248,10 @@ final class AppState: ObservableObject {if let data = try? JSONEncoder().encode(Array(activeIntegrations)) {UserDefaults.standard.set(data, forKey: "activeIntegrations")}+ // Clear stale GitHub data when the integration is disabled+ if !activeIntegrations.contains("integration_github") && oldValue.contains("integration_github") {+ githubPulse = nil+ }}}@@ -261,8 +265,9 @@ final class AppState: ObservableObject {@Published var resendEmails: [ResendEmail] = []@Published var resendTotal: Int? = nil- // GitHub stats (populated by GithubPoller)+ // GitHub stats + pulse (populated by GithubPoller)@Published var githubStats: GitHubStats? = nil+ @Published var githubPulse: GitHubPulse? = nil// Stripe (populated by StripePoller)@Published var stripePayments: [StripePayment] = []@@ -462,6 +467,33 @@ final class AppState: ObservableObject {tasks[idx].pillBadge = nil // clear badge when user brings task to focus}+ func setPillBadge(_ badge: PillBadge, for id: String) {+ guard let idx = tasks.firstIndex(where: { $0.id == id }) else { return }+ tasks[idx].pillBadge = badge+ }++ /// Called on main thread after each GitHub pulse poll. Fires badge + sound based on events.+ func handleGitHubEvents(_ events: [GitHubEvent]) {+ guard !events.isEmpty else { return }+ // Priority: error > question (reviewRequested) > finish (ciPassed)+ var level = 0 // 0 = none, 1 = finish, 2 = question, 3 = error+ var badge: PillBadge?+ var sound: String?+ for event in events {+ switch event {+ case .ciFailed, .mainFailed:+ if level < 3 { level = 3; badge = .error; sound = "error" }+ case .reviewRequested:+ if level < 2 { level = 2; badge = .finished; sound = "question" }+ case .ciPassed:+ if level < 1 { level = 1; badge = .finished; sound = "finish" }+ }+ }+ // Only set badge when the GitHub pill is not currently in focus+ if let b = badge, focusId != "integration_github" { setPillBadge(b, for: "integration_github") }+ if let s = sound { SoundEngine.shared.play(s) }+ }+func syncMode() {// If no tasks and not expanded/peek, go hiddenif tasks.isEmpty && mode == .compact {diff --git a/NotchBuddy/Sources/App/GitHubPulse.swift b/NotchBuddy/Sources/App/GitHubPulse.swiftnew file mode 100644index 00000000..f4e0642f--- /dev/null+++ b/NotchBuddy/Sources/App/GitHubPulse.swift@@ -0,0 +1,221 @@+import Foundation++// MARK: - CIState++enum CIState: String, Equatable {+ case pending, success, failure, unknown++ init(rawGitHub: String?) {+ guard let s = rawGitHub else { self = .unknown; return }+ switch s.uppercased() {+ case "PENDING", "EXPECTED": self = .pending+ case "SUCCESS": self = .success+ case "ERROR", "FAILURE": self = .failure+ default: self = .unknown+ }+ }+}++// MARK: - ReviewState++enum ReviewState: String, Equatable {+ case approved, changesRequested, pending, unknown++ init(rawGitHub: String?) {+ guard let s = rawGitHub else { self = .unknown; return }+ switch s.uppercased() {+ case "APPROVED": self = .approved+ case "CHANGES_REQUESTED": self = .changesRequested+ case "REVIEW_REQUIRED": self = .pending+ default: self = .unknown+ }+ }+}++// MARK: - GitHubPR++struct GitHubPR: Equatable {+ var id: String // "owner/repo#num"+ var title: String+ var url: String+ var repo: String+ var number: Int+ var isDraft: Bool+ var ci: CIState+ var review: ReviewState+}++// MARK: - GitHubRepoCI++struct GitHubRepoCI: Equatable {+ var repo: String+ var url: String+ var branch: String+ var ci: CIState+}++// MARK: - GitHubDetailSection++enum GitHubDetailSection { case myPRs, toReview, mainCI }++// MARK: - GitHubEvent++enum GitHubEvent: Equatable {+ case ciFailed(prId: String)+ case ciPassed(prId: String)+ case mainFailed(repo: String)+ case reviewRequested(prId: String)+}++// MARK: - GitHubPulse++struct GitHubPulse: Equatable {+ var login: String+ var myPRs: [GitHubPR]+ var toReview: [GitHubPR]+ var mainCI: [GitHubRepoCI]+ var fetchedAt: Date++ /// True when at least one PR CI or default-branch CI is pending — triggers 60 s poll cadence.+ var hasPending: Bool {+ myPRs.contains { $0.ci == .pending } ||+ mainCI.contains { $0.ci == .pending }+ }++ // MARK: - Parse++ static func parse(_ data: Data) -> GitHubPulse? {+ guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let dataNode = root["data"] as? [String: Any],+ let viewer = dataNode["viewer"] as? [String: Any] else { return nil }++ let login = viewer["login"] as? String ?? ""++ // My PRs+ var myPRs: [GitHubPR] = []+ if let prConn = viewer["pullRequests"] as? [String: Any],+ let nodes = prConn["nodes"] as? [[String: Any]] {+ var seenPR = Set<String>()+ for node in nodes {+ guard let number = node["number"] as? Int,+ let title = node["title"] as? String,+ let url = node["url"] as? String,+ let repoNode = node["repository"] as? [String: Any],+ let repo = repoNode["nameWithOwner"] as? String else { continue }+ let id = "\(repo)#\(number)"+ 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? = {+ 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+ }()+ myPRs.append(GitHubPR(+ id: id,+ title: title,+ url: url,+ repo: repo,+ number: number,+ isDraft: isDraft,+ ci: CIState(rawGitHub: ciRaw),+ review: ReviewState(rawGitHub: reviewDecision)+ ))+ }+ }++ // Main CI for recently-pushed repos (client-side filter: skip archived)+ var mainCI: [GitHubRepoCI] = []+ if let repoConn = viewer["repositories"] as? [String: Any],+ let nodes = repoConn["nodes"] as? [[String: Any]] {+ for node in nodes {+ let isArchived = node["isArchived"] as? Bool ?? false+ if isArchived { continue }+ guard let repo = node["nameWithOwner"] as? String,+ 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+ }()+ mainCI.append(GitHubRepoCI(repo: repo, url: url, branch: branch,+ ci: CIState(rawGitHub: ciRaw)))+ }+ }++ // To review+ var toReview: [GitHubPR] = []+ if let searchResult = dataNode["reviewRequested"] as? [String: Any],+ let nodes = searchResult["nodes"] as? [[String: Any]] {+ var seenReview = Set<String>()+ for node in nodes {+ guard let number = node["number"] as? Int,+ let title = node["title"] as? String,+ let url = node["url"] as? String,+ let repoNode = node["repository"] as? [String: Any],+ let repo = repoNode["nameWithOwner"] as? String else { continue }+ let id = "\(repo)#\(number)"+ guard seenReview.insert(id).inserted else { continue } // skip duplicates+ let isDraft = node["isDraft"] as? Bool ?? false+ toReview.append(GitHubPR(+ id: id,+ title: title,+ url: url,+ repo: repo,+ number: number,+ isDraft: isDraft,+ ci: .unknown,+ review: .pending+ ))+ }+ }++ return GitHubPulse(login: login, myPRs: myPRs, toReview: toReview,+ mainCI: mainCI, fetchedAt: Date())+ }++ // MARK: - Events++ /// Returns events comparing old → new. If old is nil (first poll after launch) returns empty — no+ /// alerts on initial load, only on subsequent changes.+ static func events(old: GitHubPulse?, new: GitHubPulse) -> [GitHubEvent] {+ guard let old else { return [] }++ var result: [GitHubEvent] = []++ // 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))+ }+ }++ // Default-branch CI failures+ 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))+ }+ }++ // New review requests+ let oldReviewIds = Set(old.toReview.map { $0.id })+ for pr in new.toReview {+ if !oldReviewIds.contains(pr.id) {+ result.append(.reviewRequested(prId: pr.id))+ }+ }++ return result+ }+}diff --git a/NotchBuddy/Sources/App/GithubPoller.swift b/NotchBuddy/Sources/App/GithubPoller.swiftindex 7b51c4cc..22a539dd 100644--- a/NotchBuddy/Sources/App/GithubPoller.swift+++ b/NotchBuddy/Sources/App/GithubPoller.swift@@ -3,18 +3,29 @@ import Foundationfinal class GithubPoller: @unchecked Sendable {static let shared = GithubPoller()private var timer: DispatchSourceTimer?+ // All three properties below are accessed only on the main thread.+ private var pulseInFlight = false+ private var nextPulse: DispatchWorkItem?+ private var tokenGeneration = 0private init() {}func start() {guard timer == nil else { return }+ // Stats poll: every 5 minutes, starting 7 s after launchlet t = DispatchSource.makeTimerSource(queue: .global(qos: .background))- t.schedule(deadline: .now() + 7, repeating: 300) // every 5 minutes- t.setEventHandler { [weak self] in self?.poll() }+ t.schedule(deadline: .now() + 7, repeating: 300)+ t.setEventHandler { [weak self] in self?.pollStats() }t.resume()timer = t+ // First pulse: 10 s after launch, stored in nextPulse so triggerPulseNow can cancel it+ DispatchQueue.main.async { [weak self] in+ self?.scheduleNextPulse(hasPending: false, delay: 10)+ }}- private func poll() {+ // MARK: - Stats (unchanged logic)++ private func pollStats() {guard let token = KeychainStore.shared.get("github-token") else { return }fetchUser(token: token)}@@ -31,13 +42,11 @@ final class GithubPoller: @unchecked Sendable {guard let data, code == 200,let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }- let publicRepos = (json["public_repos"] as? Int) ?? 0+ let publicRepos = (json["public_repos"] as? Int) ?? 0let privateOwned = (json["owned_private_repos"] as? Int)?? (json["total_private_repos"] as? Int)?? 0- let totalRepos = publicRepos + privateOwned-- self.fetchStars(token: token, totalRepos: totalRepos)+ self.fetchStars(token: token, totalRepos: publicRepos + privateOwned)}.resume()}@@ -52,11 +61,149 @@ final class GithubPoller: @unchecked Sendable {guard let data, code == 200,let repos = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return }- let totalStars = repos.reduce(0) { $0 + ((($1["stargazers_count"] as? Int) ?? 0)) }-+ let totalStars = repos.reduce(0) { $0 + (($1["stargazers_count"] as? Int) ?? 0) }DispatchQueue.main.async {AppState.shared.githubStats = GitHubStats(totalRepos: totalRepos, totalStars: totalStars)}}.resume()}++ // MARK: - Pulse (GraphQL, single chain)++ /// Dispatches guards + state reads to main, then fires network on background.+ private func pollPulse() {+ DispatchQueue.main.async { [weak self] in+ guard let self, !self.pulseInFlight else { return }+ guard let token = KeychainStore.shared.get("github-token"),+ AppState.shared.activeIntegrations.contains("integration_github") else {+ self.scheduleNextPulse(hasPending: false)+ return+ }+ self.pulseInFlight = true+ let gen = self.tokenGeneration+ DispatchQueue.global(qos: .background).async { self.fetchPulse(token: token, generation: gen) }+ }+ }++ private func fetchPulse(token: String, generation: Int) {+ guard let url = URL(string: "https://api.github.com/graphql") else {+ finishPulse(hasPending: false); return+ }+ var req = URLRequest(url: url, timeoutInterval: 15)+ req.httpMethod = "POST"+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")+ guard let body = try? JSONSerialization.data(withJSONObject: ["query": Self.graphQLQuery]) else {+ finishPulse(hasPending: false); return+ }+ req.httpBody = body++ URLSession.shared.dataTask(with: req) { [weak self] data, response, _ in+ guard let self else { return }+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0+ guard let data, code == 200 else {+ self.nbLog("pulse HTTP \(code)")+ self.finishPulse(hasPending: false)+ return+ }+ // Partial GraphQL errors: if "data" is present, parse anyway and log error count.+ // Only discard if "data" is absent or null.+ if let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {+ if let errors = root["errors"] as? [[String: Any]], !errors.isEmpty {+ self.nbLog("pulse GraphQL errors: \(errors.count)")+ }+ guard root["data"] is [String: Any] else {+ self.finishPulse(hasPending: false); return+ }+ }+ guard let pulse = GitHubPulse.parse(data) else {+ self.finishPulse(hasPending: false); return+ }+ DispatchQueue.main.async {+ // Discard stale response if token changed while request was in flight+ guard self.tokenGeneration == generation else { return }+ let old = AppState.shared.githubPulse+ let events = GitHubPulse.events(old: old, new: pulse)+ AppState.shared.githubPulse = pulse+ AppState.shared.handleGitHubEvents(events)+ }+ self.finishPulse(hasPending: pulse.hasPending)+ }.resume()+ }++ /// 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.+ /// Safe to call from any thread.+ func triggerPulseNow() {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.tokenGeneration += 1+ self.nextPulse?.cancel()+ self.nextPulse = nil+ guard !self.pulseInFlight else { return }+ self.pollPulse()+ }+ }++ private func nbLog(_ message: String) {+ appendAppLog("github.log", message)+ }++ /// Called from any thread; dispatches cleanup to main then schedules next poll.+ private func finishPulse(hasPending: Bool) {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.pulseInFlight = false+ self.scheduleNextPulse(hasPending: hasPending)+ }+ }++ /// Cancels any pending scheduled poll and schedules a new one on the main queue.+ /// Must run on the main thread.+ private func scheduleNextPulse(hasPending: Bool, delay: Double? = nil) {+ nextPulse?.cancel()+ let work = DispatchWorkItem { [weak self] in self?.pollPulse() }+ nextPulse = work+ let d = delay ?? (hasPending ? 60.0 : 300.0)+ DispatchQueue.main.asyncAfter(deadline: .now() + d, execute: work)+ }++ // MARK: - GraphQL query++ private static let graphQLQuery = """+ query {+ viewer {+ login+ pullRequests(states: OPEN, first: 20, orderBy: {field: UPDATED_AT, direction: DESC}) {+ nodes {+ number title url isDraft reviewDecision+ repository { nameWithOwner url }+ commits(last: 1) {+ nodes { commit { statusCheckRollup { state } } }+ }+ }+ }+ repositories(first: 10, ownerAffiliations: [OWNER], orderBy: {field: PUSHED_AT, direction: DESC}) {+ nodes {+ nameWithOwner url isArchived+ defaultBranchRef {+ name+ target { ... on Commit { statusCheckRollup { state } } }+ }+ }+ }+ }+ reviewRequested: search(query: "is:pr is:open review-requested:@me archived:false", type: ISSUE, first: 20) {+ issueCount+ nodes {+ ... on PullRequest {+ number title url isDraft+ author { login }+ repository { nameWithOwner url }+ }+ }+ }+ }+ """}diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swiftindex 6068cbf7..16163f1f 100644--- a/NotchBuddy/Sources/App/IslandViewContent.swift+++ b/NotchBuddy/Sources/App/IslandViewContent.swift@@ -176,7 +176,7 @@ struct OverviewView: View {case "integration_vercel":NSWorkspace.shared.open(URL(string: "https://vercel.com/dashboard")!)case "integration_github":- NSWorkspace.shared.open(URL(string: "https://github.com")!)+ NSWorkspace.shared.open(URL(string: "https://github.com/pulls")!)case "integration_n8n":if let urlStr = KeychainStore.shared.get("n8n-url"), let url = URL(string: urlStr) {NSWorkspace.shared.open(url)@@ -1549,6 +1549,7 @@ struct IntegrationCardView: View {@Binding var showingDetail: Boolvar onDiffTap: ((Int) -> Void)? = nil@ObservedObject private var appState = AppState.shared+ @State private var githubDetailSection: GitHubDetailSection = .myPRsprivate var isConfigured: Bool {switch task.id {@@ -1642,9 +1643,14 @@ struct IntegrationCardView: View {task.id == "integration_resend" && !appState.resendEmails.isEmpty}- // GitHub with stats loaded+ // GitHub with stats or pulse loadedprivate var githubHasData: Bool {- task.id == "integration_github" && appState.githubStats != nil+ task.id == "integration_github" && (appState.githubPulse != nil || appState.githubStats != nil)+ }++ // GitHub with pulse loaded (richer card)+ private var githubHasPulse: Bool {+ task.id == "integration_github" && appState.githubPulse != nil}// Stripe: show card as soon as first poll completes (balance OR payments)@@ -1750,6 +1756,25 @@ struct IntegrationCardView: View {} else if resendHasData {ResendCardView(emails: appState.resendEmails, total: appState.resendTotal).transition(.opacity)+ } else if showingDetail && githubHasPulse {+ GitHubDetailView(+ section: githubDetailSection,+ pulse: appState.githubPulse!,+ onBack: {+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { showingDetail = false }+ }+ )+ .transition(.opacity)+ } else if githubHasPulse {+ GitHubPulseCardView(+ pulse: appState.githubPulse!,+ stats: appState.githubStats,+ onTapSection: { section in+ githubDetailSection = section+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { showingDetail = true }+ }+ )+ .transition(.opacity)} else if githubHasData {GitHubStatsCardView(stats: appState.githubStats!).transition(.opacity)@@ -2236,6 +2261,344 @@ struct ResendCardView: View {}}+// MARK: - GitHub Pulse Card View++private func ciWorstState(_ prs: [GitHubPR]) -> CIState {+ if prs.contains(where: { $0.ci == .failure }) { return .failure }+ if prs.contains(where: { $0.ci == .pending }) { return .pending }+ if prs.contains(where: { $0.ci == .success }) { return .success }+ return .unknown+}++private func ciColor(_ state: CIState) -> String {+ switch state {+ case .failure: return "#F4505E"+ case .pending: return "#F5A524"+ case .success: return "#22C55E"+ case .unknown: return "#6B7079"+ }+}++private func mainCIWorst(_ repos: [GitHubRepoCI]) -> CIState {+ if repos.contains(where: { $0.ci == .failure }) { return .failure }+ if repos.contains(where: { $0.ci == .pending }) { return .pending }+ if repos.contains(where: { $0.ci == .success }) { return .success }+ return .unknown+}++struct GitHubPulseCardView: View {+ let pulse: GitHubPulse+ let stats: GitHubStats?+ let onTapSection: (GitHubDetailSection) -> Void++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ // Header+ HStack(spacing: 6) {+ Circle()+ .fill(Color(hex: "#F4505E"))+ .frame(width: 7, height: 7)+ Text("GitHub")+ .font(.system(size: 12, weight: .semibold))+ .foregroundColor(Color(hex: "#F5F6F8"))+ if let s = stats {+ Text("★ \(formatCount(s.totalStars)) · \(s.totalRepos) repos")+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#8E939C"))+ .lineLimit(1)+ } else {+ Text("Overview")+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#8E939C"))+ }+ }+ .padding(.top, 6)+ .padding(.leading, 108)+ .padding(.trailing, 36)++ // Stat rows+ VStack(alignment: .leading, spacing: 4) {+ // My PRs+ let prWorst = ciWorstState(pulse.myPRs)+ let prValue: String = {+ let n = pulse.myPRs.count+ if n == 0 { return "0" }+ let failing = pulse.myPRs.filter { $0.ci == .failure }.count+ let pending = pulse.myPRs.filter { $0.ci == .pending }.count+ if failing > 0 { return "\(n) · \(failing) failing" }+ if pending > 0 { return "\(n) · running" }+ return "\(n)"+ }()+ GitHubStatRow(+ icon: "arrow.triangle.pull", iconColor: ciColor(prWorst),+ label: "My PRs", value: prValue+ ) { onTapSection(.myPRs) }++ // To review+ let reviewCount = pulse.toReview.count+ GitHubStatRow(+ icon: "eye",+ iconColor: reviewCount > 0 ? "#8AB4F8" : "#6B7079",+ label: "To review",+ value: "\(reviewCount)"+ ) { onTapSection(.toReview) }++ // Default branch CI+ let mainWorst = mainCIWorst(pulse.mainCI)+ let (ciIcon, ciIconColor, ciValue): (String, String, String) = {+ switch mainWorst {+ case .failure:+ let n = pulse.mainCI.filter { $0.ci == .failure }.count+ return ("xmark.octagon.fill", "#F4505E", "\(n) failing")+ case .pending:+ return ("checkmark.seal.fill", "#F5A524", "running")+ case .success:+ return ("checkmark.seal.fill", "#22C55E", "all green")+ case .unknown:+ return ("checkmark.seal.fill", "#6B7079", pulse.mainCI.isEmpty ? "no repos" : "unknown")+ }+ }()+ GitHubStatRow(+ icon: ciIcon, iconColor: ciIconColor,+ label: "Default branch CI", value: ciValue+ ) { onTapSection(.mainCI) }+ }+ .padding(.top, 6)+ .padding(.leading, 108)+ .padding(.trailing, 12)+ }+ .frame(maxWidth: .infinity, alignment: .topLeading)+ .padding(.top, 4)+ .clipped()+ }++ private func formatCount(_ n: Int) -> String {+ if n >= 1000 { return String(format: "%.1fk", Double(n) / 1000) }+ return "\(n)"+ }+}++private struct GitHubStatRow: View {+ let icon: String+ let iconColor: String+ let label: String+ let value: String+ let action: () -> Void++ var body: some View {+ Button(action: action) {+ HStack(spacing: 7) {+ Image(systemName: icon)+ .font(.system(size: 10))+ .foregroundColor(Color(hex: iconColor))+ .frame(width: 14)+ Text(label)+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#6B7079"))+ Spacer()+ Text(value)+ .font(.system(size: 12, weight: .semibold))+ .foregroundColor(Color(hex: "#C5C8CD"))+ .monospacedDigit()+ }+ .frame(maxWidth: .infinity)+ }+ .buttonStyle(.plain)+ }+}++// MARK: - GitHub Detail View++struct GitHubDetailView: View {+ let section: GitHubDetailSection+ let pulse: GitHubPulse+ let onBack: () -> Void++ private var title: String {+ switch section {+ case .myPRs: return "My PRs"+ case .toReview: return "To review"+ case .mainCI: return "Default branch CI"+ }+ }++ private var items: [GitHubPR] {+ switch section {+ case .myPRs: return pulse.myPRs+ case .toReview: return pulse.toReview+ case .mainCI: return []+ }+ }++ private var repoItems: [GitHubRepoCI] {+ section == .mainCI ? pulse.mainCI : []+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ // Header+ HStack(spacing: 6) {+ Button(action: onBack) {+ HStack(spacing: 3) {+ Image(systemName: "chevron.left")+ .font(.system(size: 8, weight: .medium))+ Text(title)+ .font(.system(size: 12, weight: .semibold))+ }+ .foregroundColor(Color(hex: "#F5F6F8"))+ }+ .buttonStyle(.plain)+ Spacer(minLength: 2)+ }+ .padding(.top, 6)+ .padding(.leading, 108)+ .padding(.trailing, 12)++ // List+ if items.isEmpty && repoItems.isEmpty {+ Text("Nothing here")+ .font(.system(size: 10.5))+ .foregroundColor(Color(hex: "#6B7079"))+ .padding(.top, 8)+ .padding(.leading, 108)+ } else {+ ScrollView(.vertical, showsIndicators: false) {+ VStack(alignment: .leading, spacing: 0) {+ ForEach(items, id: \.id) { pr in+ GitHubPRRowView(pr: pr, showCI: section == .myPRs)+ }+ ForEach(repoItems, id: \.repo) { repo in+ GitHubRepoCIRowView(repo: repo)+ }+ }+ }+ .frame(maxHeight: 60) // 3 rows × 20 pt; rest scrolls+ .mask(+ Group {+ if (items.count + repoItems.count) > 3 {+ LinearGradient(+ stops: [+ .init(color: .black, location: 0),+ .init(color: .black, location: 0.8),+ .init(color: .clear, location: 1.0)+ ],+ startPoint: .top, endPoint: .bottom+ )+ } else {+ Color.black+ }+ }+ )+ .padding(.top, 4)+ .padding(.leading, 108)+ .padding(.trailing, 8)+ }+ }+ .frame(maxWidth: .infinity, alignment: .topLeading)+ .padding(.top, 4)+ .clipped()+ .onExitCommand { onBack() }+ }+}++private func ghCIDot(_ ci: CIState) -> Color {+ switch ci {+ case .failure: return Color(hex: "#F4505E")+ case .pending: return Color(hex: "#F5A524")+ case .success: return Color(hex: "#22C55E")+ case .unknown: return Color.clear+ }+}++private struct GitHubPRRowView: View {+ let pr: GitHubPR+ let showCI: Bool++ var body: some View {+ Button(action: {+ if let url = safeWebURL(pr.url), url.host == "github.com" {+ NSWorkspace.shared.open(url)+ }+ }) {+ HStack(spacing: 5) {+ if showCI {+ Circle()+ .fill(ghCIDot(pr.ci))+ .frame(width: 5, height: 5)+ .opacity(pr.ci == .unknown ? 0 : 1)+ } else {+ Spacer().frame(width: 5)+ }+ Text("\(pr.repo.components(separatedBy: "/").last ?? pr.repo)#\(pr.number)")+ .font(.system(size: 10.5))+ .foregroundColor(Color(hex: "#9398A1"))+ .lineLimit(1)+ Text(pr.title)+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#C5C8CD"))+ .lineLimit(1)+ .truncationMode(.tail)+ if pr.isDraft {+ Text("Draft")+ .font(.system(size: 9.5))+ .foregroundColor(Color(hex: "#6B7079"))+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .frame(height: 20)+ }+ .buttonStyle(.plain)+ }+}++private struct GitHubRepoCIRowView: View {+ let repo: GitHubRepoCI++ private var ciStateWord: String? {+ switch repo.ci {+ case .failure: return "failing"+ case .pending: return "running"+ case .success: return "passing"+ case .unknown: return nil+ }+ }++ var body: some View {+ Button(action: {+ let actionsURL = repo.url.hasSuffix("/") ? repo.url + "actions" : repo.url + "/actions"+ if let url = safeWebURL(actionsURL), url.host == "github.com" {+ NSWorkspace.shared.open(url)+ }+ }) {+ HStack(spacing: 5) {+ Circle()+ .fill(ghCIDot(repo.ci))+ .frame(width: 5, height: 5)+ .opacity(repo.ci == .unknown ? 0 : 1)+ Text(repo.repo.components(separatedBy: "/").last ?? repo.repo)+ .font(.system(size: 10.5))+ .foregroundColor(Color(hex: "#9398A1"))+ .lineLimit(1)+ Text(repo.branch)+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#C5C8CD"))+ .lineLimit(1)+ .truncationMode(.tail)+ Spacer(minLength: 4)+ if let word = ciStateWord {+ Text(word)+ .font(.system(size: 10))+ .foregroundColor(ghCIDot(repo.ci))+ .lineLimit(1)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .frame(height: 20)+ }+ .buttonStyle(.plain)+ }+}+// MARK: - GitHub Stats Card Viewstruct GitHubStatsCardView: View {diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swiftindex d3ea42ac..cb8aae7d 100644--- a/NotchBuddy/Sources/App/SettingsView.swift+++ b/NotchBuddy/Sources/App/SettingsView.swift@@ -765,6 +765,9 @@ struct SettingsView: View {}SecureField("Personal Access Token", text: $githubToken).textFieldStyle(.roundedBorder)+ Text("Classic token with repo scope, or fine-grained with read access to Pull requests, Commit statuses and Actions.")+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#8E939C"))}// Stripe@@ -1072,7 +1075,17 @@ struct SettingsView: View {saveKey("n8n-url", value: n8nUrl)saveKey("n8n-api-key", value: n8nKey)saveKey("vercel-token", value: vercelToken)- saveKey("github-token", value: githubToken)++ // Detect GitHub token changes before writing+ let prevGithubToken = KeychainStore.shared.get("github-token")+ saveKey("github-token", value: githubToken)+ let nextGithubToken = KeychainStore.shared.get("github-token")+ if nextGithubToken != prevGithubToken {+ AppState.shared.githubPulse = nil+ if nextGithubToken == nil { AppState.shared.githubStats = nil }+ if nextGithubToken != nil { GithubPoller.shared.triggerPulseNow() }+ }+saveKey("stripe-api-key", value: stripeKey)saveKey("calcom-api-key", value: calcomKey)saveKey("notion-api-key", value: notionKey)diff --git a/README.md b/README.mdindex 4ccd8070..2c9d5e7f 100644--- a/README.md+++ b/README.md@@ -41,7 +41,7 @@ Meet **Mochi**: a soft little squircle with big eyes that pops out of your notch- 📋 **Declare the tools you use** — open Settings → Active pills and pick your main workspace tool (VS Code, Cursor, Codex or Antigravity), then toggle up to 4 more: Gemini CLI, Anthropic, Google AI, OpenAI, Ollama, LM Studio and service integrations *(macOS)*.- 📎 **Drop a file on the notch** — Mochi turns into a box and swallows it, then ask a question about it or send it by email *(email: macOS, Mail.app)*.- 🪟 **Drag Mochi onto any window** — attach that window as context for Claude *(macOS)*.-- 🔌 **Integrations** — Stripe payments, n8n workflows, GitHub, Vercel deployments, Resend emails, Notion, Cal.com. Each one gets its own little colored Mochi.+- 🔌 **Integrations** — Stripe payments, n8n workflows, GitHub (open PRs, reviews requested, CI status), Vercel deployments, Resend emails, Notion, Cal.com. Each one gets its own little colored Mochi.- 🎵 **Apple Music pill** *(macOS, GitHub build)* — add the Apple Music pill in Settings → Active pills to see what's playing and control playback from the notch; Mochi dances while it plays.- 🎭 **A real character** — idle breathing, blinks, eyes on a sphere that follow your mouse, emotes, 28 handcrafted sounds, a greeting on launch.- 🫥 **Invisible when idle** — hides away when nothing is running, peeks out when you hover the notch (the top edge of the screen on Windows and Linux).diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.mdindex 75318f67..3dd8fe33 100644--- a/docs/INTEGRATIONS.md+++ b/docs/INTEGRATIONS.md@@ -137,6 +137,45 @@ Sur `PostToolUse` pour `Edit`, `MultiEdit` et `Write` (Claude Code, Cursor), l'a---+## 1quater. GitHub (pulse)++**Plateforme** : macOS uniquement (build GitHub)++**Token** : token classique avec scope `repo`, ou token fin avec accès en lecture à Pull requests, Commit statuses et Actions. Stocké dans le Trousseau (`github-token`).++### Données récupérées++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`)+- **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`++**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.++### États CI (`CIState`)++| Valeur GitHub | `CIState` |+|-----------------------|------------|+| `PENDING`, `EXPECTED` | `.pending` |+| `SUCCESS` | `.success` |+| `FAILURE`, `ERROR` | `.failure` |+| `null` ou autre | `.unknown` |++### Alertes++Déclenchées uniquement si l'état **change** entre deux polls (premier poll silencieux) :++| Événement | Badge | Son |+|-----------------------|---------|------------|+| CI PR failure / main | `.error` (rouge) | `error` |+| Nouvelle review demandée | `.finished` (vert) | `question` |+| CI PR success | `.finished` (vert) | `finish` |++Priorité : failure > review demandée > success. Un seul badge/son par cycle.++---+## 2. n8n (workflows de Louis)- Réglages : URL de l'instance (probablement `https://n8nlouis.dcsys.tech`, **à confirmer avec Louis**) et clé API n8n (Trousseau). La clé se crée dans n8n : Settings → n8n API.diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 75d89106..2c5044b3 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -117,6 +117,14 @@ Règles :- Hooks (Gemini CLI, Antigravity, Codex) : `isConfigured` = `HookServer.geminiHooksInstalled()` / `agyHooksInstalled()` / `codexHooksInstalled()` sous `#if !APPSTORE`. La section Codex Hooks dans Settings installe les hooks dans `~/.codex/hooks.json` avec le même flux backup + preview que Gemini CLI. Après l'installation, la carte affiche : « run /hooks in Codex or open Hooks in the app's settings to trust them ». Approbations Codex : carte avec Allow et Deny seulement (pas Always) ; updatedPermissions jamais envoyé ; notes « Handled in Codex. » / « Still waiting in Codex. ».- Pastilles IA (cloud) : `isConfigured` = clé API dans le Keychain. Pastilles IA locales (Ollama, LM Studio) : `isConfigured` = URL serveur non vide (définie via le bouton **Connect** dans Réglages → Chat). Bouton « Chat with… » → change le fournisseur et ouvre la vue `.prompt`.+### Carte GitHub (`GitHubPulseCardView`)++Affichée à la place de `GitHubStatsCardView` quand un `GitHubPulse` est disponible (`githubPulse != nil`). Trois lignes `GitHubStatRow` (My PRs, To review, Default branch CI), chacune tappable → ouvre `GitHubDetailView` avec la section correspondante. En-tête : point rouge + « GitHub » + « Overview » + étoiles / dépôts à droite.++### Vue détail GitHub (`GitHubDetailView`)++Remplace la carte principale quand `showingDetail && githubHasPulse`. En-tête : chevron.left (← ferme) + titre de section. ScrollView hauteur 88 pt, 4 lignes. Section **My PRs** et **To review** → `GitHubPRRowView` (point CI + « repo#N » + titre tronqué + badge Draft). Section **Default branch CI** → `GitHubRepoCIRowView` (point CI + nom court + nom complet). Clic sur une PR → ouvre `https://github.com/…` dans le navigateur (filtré sur `host == "github.com"`). Échap ferme.+### Boutons- Pilule, 12,5 pt medium, fond blanc 9 % (survol 15 %), primaire : fond `#F5F6F8` texte `#0B0C0E`. Appui : échelle 0,94. Raccourcis affichés en petite pastille bordée (Y, N).diff --git a/docs/privacy.html b/docs/privacy.htmlindex e47b1e3d..3a67bc6e 100644--- a/docs/privacy.html+++ b/docs/privacy.html@@ -32,7 +32,7 @@<li><b>Google AI (Gemini API)</b> <i>(macOS)</i> — when you chat using Google AI, the text you type and the current conversation are sent to Google's Gemini API. If you attached a window, the app name, title and URL are also sent. If you attached a file, only its name is sent (file content is only sent to Anthropic or to a local model server you connected). The list of available models is fetched when you open the chat. <a href="https://policies.google.com/privacy">Google privacy policy</a>.</li><li><b>OpenAI</b> <i>(macOS)</i> — when you chat using OpenAI, the text you type and the current conversation are sent to the OpenAI API. If you attached a window, the app name, title and URL are also sent. If you attached a file, only its name is sent (file content is only sent to Anthropic or to a local model server you connected). The list of available models is fetched when you open the chat. <a href="https://openai.com/policies/privacy-policy">OpenAI privacy policy</a>.</li><li><b>Ollama / LM Studio</b> <i>(macOS)</i> — when you chat using a local model, the text you type, the current conversation, and the content of any attached text file (up to 24 000 characters) are sent to the server address you configured in Settings → Chat → Local models. By default that address is <code>127.0.0.1</code> on your Mac — nothing leaves your computer. If you point it at a remote server, that server receives the data. The server address is stored in your Mac's user preferences (not the Keychain). The list of available models is fetched each time you open the model picker.</li>-<li><b>Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n</b> — Coucou reads data from your own accounts (payments, repositories, deployments, emails, pages, bookings, workflow runs) to display them. Coucou only reads from them.</li>+<li><b>Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n</b> — Coucou reads data from your own accounts (payments, repositories, deployments, emails, pages, bookings, workflow runs) to display them. For GitHub specifically, Coucou also reads your open pull requests, reviews requested on you, and CI status of your repositories' default branches; this data is kept in memory and deleted when the app quits. Coucou only reads from them.</li></ul><p>We have no access to these requests or their responses.</p>@@ -88,7 +88,7 @@<li><b>Google AI (API Gemini)</b> <i>(macOS)</i> : quand tu discutes via Google AI, le texte saisi et la conversation en cours sont envoyés à l’API Gemini de Google. Si une fenêtre est attachée, le nom de l’app, le titre et l’URL sont aussi envoyés. Si un fichier est attaché, seul son nom est envoyé (le contenu d’un fichier ne part que chez Anthropic ou vers le serveur de modèle local que tu as connecté). La liste des modèles disponibles est récupérée à l’ouverture du chat. <a href="https://policies.google.com/privacy">Politique de confidentialité de Google</a>.</li><li><b>OpenAI</b> <i>(macOS)</i> : quand tu discutes via OpenAI, le texte saisi et la conversation en cours sont envoyés à l’API OpenAI. Si une fenêtre est attachée, le nom de l’app, le titre et l’URL sont aussi envoyés. Si un fichier est attaché, seul son nom est envoyé (le contenu d’un fichier ne part que chez Anthropic ou vers le serveur de modèle local que tu as connecté). La liste des modèles disponibles est récupérée à l’ouverture du chat. <a href="https://openai.com/policies/privacy-policy">Politique de confidentialité d’OpenAI</a>.</li><li><b>Ollama / LM Studio</b> <i>(macOS)</i> : quand tu discutes via un modèle local, le texte saisi, la conversation en cours et le contenu de tout fichier texte attaché (jusqu’à 24 000 caractères) sont envoyés à l’adresse de serveur configurée dans Réglages → Chat → Local models. Par défaut, cette adresse est <code>127.0.0.1</code> sur ton Mac — rien ne quitte ton ordinateur. Si tu la pointes vers un serveur distant, ce serveur reçoit les données. L’adresse est conservée dans les préférences utilisateur de ton Mac (pas dans le trousseau). La liste des modèles disponibles est récupérée à chaque ouverture du sélecteur de modèle.</li>-<li><b>Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n</b> : Coucou lit les données de tes propres comptes (paiements, dépôts, déploiements, e-mails, pages, rendez-vous, exécutions de workflows) pour les afficher. Coucou ne fait que lire.</li>+<li><b>Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n</b> : Coucou lit les données de tes propres comptes (paiements, dépôts, déploiements, e-mails, pages, rendez-vous, exécutions de workflows) pour les afficher. Pour GitHub spécifiquement, Coucou lit aussi tes pull requests ouvertes, les revues de code qui t'attendent et l'état CI de la branche par défaut de tes dépôts ; ces données sont conservées en mémoire et supprimées à la fermeture de l'app. Coucou ne fait que lire.</li></ul><p>Le développeur n’a accès ni à ces requêtes ni à leurs réponses.</p>diff --git a/scripts/test-github-pulse.sh b/scripts/test-github-pulse.shnew file mode 100755index 00000000..7b6e984a--- /dev/null+++ b/scripts/test-github-pulse.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-github-pulse.XXXXXX")"+trap 'rm -rf "$TEST_DIR"' EXIT+swiftc NotchBuddy/Sources/App/GitHubPulse.swift \+ tests/GitHubPulseTests.swift -o "$TEST_DIR/github-pulse-tests"+"$TEST_DIR/github-pulse-tests"diff --git a/tests/GitHubPulseTests.swift b/tests/GitHubPulseTests.swiftnew file mode 100644index 00000000..b633f3b3--- /dev/null+++ b/tests/GitHubPulseTests.swift@@ -0,0 +1,280 @@+import Foundation++@main+enum GitHubPulseTests {++ static var failures = 0++ static func check(_ label: String, _ got: Bool) {+ if got { print(" ✓ \(label)") }+ else { print(" ✗ \(label)"); failures += 1 }+ }++ // MARK: - Fixture JSON++ // Valid response: PR #42 SUCCESS/APPROVED, PR #43 null CI (unknown)/null review,+ // repo "testuser/myrepo" PENDING, archived repo filtered out,+ // one to-review PR from another repo.+ static let validJSON: Data = """+ {+ "data": {+ "viewer": {+ "login": "testuser",+ "pullRequests": {+ "nodes": [+ {+ "number": 42,+ "title": "Add feature",+ "url": "https://github.com/testuser/myrepo/pull/42",+ "isDraft": false,+ "reviewDecision": "APPROVED",+ "repository": {"nameWithOwner": "testuser/myrepo", "url": "https://github.com/testuser/myrepo"},+ "commits": {"nodes": [{"commit": {"statusCheckRollup": {"state": "SUCCESS"}}}]}+ },+ {+ "number": 43,+ "title": "Fix bug",+ "url": "https://github.com/testuser/myrepo/pull/43",+ "isDraft": true,+ "reviewDecision": null,+ "repository": {"nameWithOwner": "testuser/myrepo", "url": "https://github.com/testuser/myrepo"},+ "commits": {"nodes": [{"commit": {"statusCheckRollup": null}}]}+ }+ ]+ },+ "repositories": {+ "nodes": [+ {+ "nameWithOwner": "testuser/myrepo",+ "url": "https://github.com/testuser/myrepo",+ "isArchived": false,+ "defaultBranchRef": {+ "name": "main",+ "target": {"statusCheckRollup": {"state": "PENDING"}}+ }+ },+ {+ "nameWithOwner": "testuser/archived",+ "url": "https://github.com/testuser/archived",+ "isArchived": true,+ "defaultBranchRef": {+ "name": "main",+ "target": {"statusCheckRollup": {"state": "SUCCESS"}}+ }+ }+ ]+ }+ },+ "reviewRequested": {+ "issueCount": 1,+ "nodes": [+ {+ "number": 7,+ "title": "Review this",+ "url": "https://github.com/other/repo/pull/7",+ "isDraft": false,+ "author": {"login": "otheruser"},+ "repository": {"nameWithOwner": "other/repo", "url": "https://github.com/other/repo"}+ }+ ]+ }+ }+ }+ """.data(using: .utf8)!++ static let emptyJSON: Data = """+ {+ "data": {+ "viewer": {+ "login": "testuser",+ "pullRequests": {"nodes": []},+ "repositories": {"nodes": []}+ },+ "reviewRequested": {"issueCount": 0, "nodes": []}+ }+ }+ """.data(using: .utf8)!++ // MARK: - Main++ static func main() {++ // ── GitHubPulse.parse ─────────────────────────────────────────────────+ print("GitHubPulse.parse")+ do {+ let pulse = GitHubPulse.parse(validJSON)+ check("parse returns non-nil", pulse != nil)+ check("login", pulse?.login == "testuser")+ check("2 myPRs", pulse?.myPRs.count == 2)+ check("PR#42 id", pulse?.myPRs[0].id == "testuser/myrepo#42")+ check("PR#42 ci success", pulse?.myPRs[0].ci == .success)+ check("PR#42 review approved", pulse?.myPRs[0].review == .approved)+ check("PR#43 ci unknown (null rollup)",pulse?.myPRs[1].ci == .unknown)+ check("PR#43 review unknown (null)", pulse?.myPRs[1].review == .unknown)+ check("PR#43 isDraft", pulse?.myPRs[1].isDraft == true)+ check("1 mainCI (archived filtered)", pulse?.mainCI.count == 1)+ check("mainCI repo", pulse?.mainCI[0].repo == "testuser/myrepo")+ check("mainCI ci pending", pulse?.mainCI[0].ci == .pending)+ check("mainCI branch main", pulse?.mainCI[0].branch == "main")+ check("1 toReview", pulse?.toReview.count == 1)+ check("toReview id", pulse?.toReview[0].id == "other/repo#7")+ check("hasPending (mainCI pending)", pulse?.hasPending == true)+ }++ // ── GitHubPulse.parse — empty ─────────────────────────────────────────+ print("GitHubPulse.parse — empty")+ do {+ let pulse = GitHubPulse.parse(emptyJSON)+ check("empty parses ok", pulse != nil)+ check("no myPRs", pulse?.myPRs.isEmpty == true)+ check("no mainCI", pulse?.mainCI.isEmpty == true)+ check("no toReview", pulse?.toReview.isEmpty == true)+ check("!hasPending", pulse?.hasPending == false)+ }++ // ── GitHubPulse.parse — bad data ──────────────────────────────────────+ print("GitHubPulse.parse — bad data")+ do {+ check("garbage → nil", GitHubPulse.parse("garbage".data(using: .utf8)!) == nil)+ check("empty obj → nil", GitHubPulse.parse("{}".data(using: .utf8)!) == nil)+ }++ // ── CIState init ──────────────────────────────────────────────────────+ print("CIState init")+ do {+ check("nil → unknown", CIState(rawGitHub: nil) == .unknown)+ check("PENDING → pending", CIState(rawGitHub: "PENDING") == .pending)+ check("EXPECTED → pending", CIState(rawGitHub: "EXPECTED") == .pending)+ check("SUCCESS → success", CIState(rawGitHub: "SUCCESS") == .success)+ check("FAILURE → failure", CIState(rawGitHub: "FAILURE") == .failure)+ check("ERROR → failure", CIState(rawGitHub: "ERROR") == .failure)+ check("other → unknown", CIState(rawGitHub: "WAITING") == .unknown)+ }++ // ── GitHubPulse.events — first poll silent ────────────────────────────+ print("GitHubPulse.events — first poll silent")+ do {+ let pulse = GitHubPulse.parse(validJSON)!+ let events = GitHubPulse.events(old: nil, new: pulse)+ check("first poll → no events", events.isEmpty)+ }++ // ── GitHubPulse.events — pending → success ────────────────────────────+ print("GitHubPulse.events — pending → success")+ do {+ var oldPulse = GitHubPulse.parse(emptyJSON)!+ oldPulse.myPRs = [GitHubPR(id: "r/p#1", title: "T", url: "", repo: "r/p",+ number: 1, isDraft: false, ci: .pending, review: .unknown)]+ var newPulse = oldPulse+ newPulse.myPRs[0].ci = .success+ let events = GitHubPulse.events(old: oldPulse, new: newPulse)+ check("pending→success → ciPassed", events == [.ciPassed(prId: "r/p#1")])+ }++ // ── GitHubPulse.events — success → failure ────────────────────────────+ print("GitHubPulse.events — success → failure")+ do {+ var oldPulse = GitHubPulse.parse(emptyJSON)!+ oldPulse.myPRs = [GitHubPR(id: "r/p#2", title: "T", url: "", repo: "r/p",+ number: 2, isDraft: false, ci: .success, review: .unknown)]+ var newPulse = oldPulse+ newPulse.myPRs[0].ci = .failure+ let events = GitHubPulse.events(old: oldPulse, new: newPulse)+ check("success→failure → ciFailed", events == [.ciFailed(prId: "r/p#2")])+ }++ // ── GitHubPulse.events — main CI failure ──────────────────────────────+ print("GitHubPulse.events — main CI failure")+ do {+ var oldPulse = GitHubPulse.parse(emptyJSON)!+ oldPulse.mainCI = [GitHubRepoCI(repo: "a/b", url: "", branch: "main", ci: .success)]+ var newPulse = oldPulse+ newPulse.mainCI[0].ci = .failure+ let events = GitHubPulse.events(old: oldPulse, new: newPulse)+ check("main success→failure → mainFailed", events == [.mainFailed(repo: "a/b")])+ }++ // ── GitHubPulse.events — new review request ───────────────────────────+ print("GitHubPulse.events — new review request")+ do {+ let pr = GitHubPR(id: "o/r#7", title: "R", url: "", repo: "o/r",+ number: 7, isDraft: false, ci: .unknown, review: .pending)+ var oldPulse = GitHubPulse.parse(emptyJSON)!+ var newPulse = oldPulse+ newPulse.toReview = [pr]+ let events = GitHubPulse.events(old: oldPulse, new: newPulse)+ check("new review → reviewRequested", events == [.reviewRequested(prId: "o/r#7")])++ // Already-known review: no new event+ oldPulse.toReview = [pr]+ newPulse.toReview = [pr]+ let noEvents = GitHubPulse.events(old: oldPulse, new: newPulse)+ check("known review → no event", noEvents.isEmpty)+ }++ // ── GitHubPulse.parse — duplicate ids ────────────────────────────────────+ print("GitHubPulse.parse — duplicate ids")+ do {+ // JSON with PR #42 duplicated: should keep only first occurrence+ let dupJSON: Data = """+ {+ "data": {+ "viewer": {+ "login": "testuser",+ "pullRequests": {+ "nodes": [+ {+ "number": 42, "title": "Add feature",+ "url": "https://github.com/testuser/myrepo/pull/42",+ "isDraft": false, "reviewDecision": "APPROVED",+ "repository": {"nameWithOwner": "testuser/myrepo", "url": "https://github.com/testuser/myrepo"},+ "commits": {"nodes": [{"commit": {"statusCheckRollup": {"state": "SUCCESS"}}}]}+ },+ {+ "number": 42, "title": "Duplicate entry",+ "url": "https://github.com/testuser/myrepo/pull/42",+ "isDraft": true, "reviewDecision": null,+ "repository": {"nameWithOwner": "testuser/myrepo", "url": "https://github.com/testuser/myrepo"},+ "commits": {"nodes": [{"commit": {"statusCheckRollup": {"state": "FAILURE"}}}]}+ }+ ]+ },+ "repositories": {"nodes": []}+ },+ "reviewRequested": {"issueCount": 0, "nodes": []}+ }+ }+ """.data(using: .utf8)!+ let pulse = GitHubPulse.parse(dupJSON)+ check("dup PR → 1 myPR", pulse?.myPRs.count == 1)+ check("dup PR → keeps first title", pulse?.myPRs[0].title == "Add feature")+ check("dup PR → keeps first ci", pulse?.myPRs[0].ci == .success)+ }++ // ── GitHubPulse.events — duplicate ids in old pulse ───────────────────+ print("GitHubPulse.events — duplicate-safe Dictionary")+ do {+ // OLD has duplicate ids (uniquingKeysWith keeps first); NEW has one entry → fires once+ var oldPulse = GitHubPulse.parse(emptyJSON)!+ let pr1 = GitHubPR(id: "r/p#1", title: "T", url: "", repo: "r/p",+ number: 1, isDraft: false, ci: .pending, review: .unknown)+ oldPulse.myPRs = [pr1, pr1] // intentional duplicate in old+ var newPulse = GitHubPulse.parse(emptyJSON)!+ var pr1Passed = pr1; pr1Passed.ci = .success+ newPulse.myPRs = [pr1Passed] // single entry in new+ let events = GitHubPulse.events(old: oldPulse, new: newPulse)+ check("dup old ids → no crash", true)+ check("dup old ids → ciPassed fires once",+ events.filter { if case .ciPassed = $0 { return true }; return false }.count == 1)+ }++ // ── finish ─────────────────────────────────────────────────────────────+ if failures == 0 {+ print("\nAll tests passed.")+ exit(0)+ } else {+ print("\n\(failures) test(s) failed.")+ exit(1)+ }+ }+}