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 pill: contribution grid (#187)
Louis86fbb79238a1
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 9a953a0d..92d1bc3b 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -39,6 +39,9 @@ jobs:- name: GitHub pulse testsrun: bash scripts/test-github-pulse.sh+ - name: GitHub activity tests+ run: bash scripts/test-github-activity.sh+- name: Buildrun: |xcodebuild \diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex 9e8944b4..2d201e05 100644--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj@@ -42,6 +42,7 @@61CB7049490F61CFA1B36B64 /* AppLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F6D7015D6A77AA59323C0E7 /* AppLog.swift */; };61F73B27A7E3AFF584B2CC22 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2E4F18AA940EFF7E047B9F7 /* AppState.swift */; };62C4EE3F74DAA59764729E62 /* UploadCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */; };+ 63093DC288B68F7F17249517 /* GitHubActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 168A9A73B519018FAB0AA465 /* GitHubActivity.swift */; };63F9F3AAC881D3EDDDD8AED9 /* UserIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4A13AEE6E06F46CEC9D908C /* UserIdentity.swift */; };651FA3F09608DE5D02D61CCE /* BotCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */; };6697436AA05A3F92C1DD85C3 /* DiffEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DB24C2469551040FBAA4DBF /* DiffEngine.swift */; };@@ -77,6 +78,7 @@D58B1E93AF65DE404C40E21E /* PillCatalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B6A38B5686C4A1F15AB5D29 /* PillCatalog.swift */; };D82E93014C8087AE81511E40 /* IslandTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D3CE3617E9D336DDBA10F7A /* IslandTypes.swift */; };D861479F6E7EAD07A6AC2105 /* ClaudePlanGauge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */; };+ D9FF132804EB458F6FA69116 /* GitHubActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 168A9A73B519018FAB0AA465 /* GitHubActivity.swift */; };DCAC390FF9EC65B945A15B24 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 506824380E9C80B9BC6DCE72 /* Assets.xcassets */; };DE05D09A32117582AC93A24A /* NotchBuddyApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1BD8F3CAA60CF37640759E1 /* NotchBuddyApp.swift */; };E4B9986674F4D425826F15A8 /* StripePoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */; };@@ -95,6 +97,7 @@/* Begin PBXFileReference section */15A1A8206F73376F4CAF2057 /* IslandRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandRootView.swift; sourceTree = "<group>"; };+ 168A9A73B519018FAB0AA465 /* GitHubActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GitHubActivity.swift; sourceTree = "<group>"; };192844E7299DEED5C2372067 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };1BE21C2B315D37AA70ED45E9 /* SoundEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SoundEngine.swift; sourceTree = "<group>"; };2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StripePoller.swift; sourceTree = "<group>"; };@@ -158,6 +161,7 @@A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */,3DB24C2469551040FBAA4DBF /* DiffEngine.swift */,3232F258523DD8D09B670363 /* FileDropView.swift */,+ 168A9A73B519018FAB0AA465 /* GitHubActivity.swift */,8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */,F8D3AD61802A32C4833F3EDA /* GitHubPulse.swift */,C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */,@@ -340,6 +344,7 @@2DEB459FBD0BA3CEAAA5FDE9 /* ClaudeService.swift in Sources */,6697436AA05A3F92C1DD85C3 /* DiffEngine.swift in Sources */,E776C7D1DE5C62EA8D4BA3E3 /* FileDropView.swift in Sources */,+ D9FF132804EB458F6FA69116 /* GitHubActivity.swift in Sources */,862CE6CB220D55E46F646DA9 /* GitHubPulse.swift in Sources */,C808B654C84D9F71DBF8493A /* GithubPoller.swift in Sources */,8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */,@@ -387,6 +392,7 @@0329E76BA4A8FEEA8A6D76E7 /* ClaudeService.swift in Sources */,C1A29371181553FB4169E195 /* DiffEngine.swift in Sources */,2132477000FD77F7EB234DAA /* FileDropView.swift in Sources */,+ 63093DC288B68F7F17249517 /* GitHubActivity.swift in Sources */,38EEB2D3A6EC538958D92575 /* GitHubPulse.swift in Sources */,C18227D148D99FE6EE3CC51A /* GithubPoller.swift in Sources */,C0E18D0F6F5F6D131E6066B8 /* GreetingCanvasView.swift in Sources */,diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swiftindex 71f55bc6..11b3dd78 100644--- a/NotchBuddy/Sources/App/AppState.swift+++ b/NotchBuddy/Sources/App/AppState.swift@@ -251,6 +251,7 @@ final class AppState: ObservableObject {// Clear stale GitHub data when the integration is disabledif !activeIntegrations.contains("integration_github") && oldValue.contains("integration_github") {githubPulse = nil+ githubActivity = nil}}}@@ -265,9 +266,10 @@ final class AppState: ObservableObject {@Published var resendEmails: [ResendEmail] = []@Published var resendTotal: Int? = nil- // GitHub stats + pulse (populated by GithubPoller)+ // GitHub stats + pulse + activity (populated by GithubPoller)@Published var githubStats: GitHubStats? = nil@Published var githubPulse: GitHubPulse? = nil+ @Published var githubActivity: GitHubActivity? = nil// Stripe (populated by StripePoller)@Published var stripePayments: [StripePayment] = []diff --git a/NotchBuddy/Sources/App/GitHubActivity.swift b/NotchBuddy/Sources/App/GitHubActivity.swiftnew file mode 100644index 00000000..0ce7fab9--- /dev/null+++ b/NotchBuddy/Sources/App/GitHubActivity.swift@@ -0,0 +1,72 @@+import Foundation++// MARK: - ContributionDay++struct ContributionDay: Equatable {+ var date: String // YYYY-MM-DD+ var count: Int+ var level: Int // 0…4 (NONE, FIRST_QUARTILE, SECOND_QUARTILE, THIRD_QUARTILE, FOURTH_QUARTILE)+ var weekday: Int // 0 = Sunday … 6 = Saturday+}++// MARK: - GitHubActivity++struct GitHubActivity: Equatable {+ var total: Int+ var weeks: [[ContributionDay]]+ var fetchedAt: Date++ // MARK: - Parse++ static func parse(_ data: Data) -> GitHubActivity? {+ 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],+ let cc = viewer["contributionsCollection"] as? [String: Any],+ let cal = cc["contributionCalendar"] as? [String: Any],+ let total = cal["totalContributions"] as? Int,+ let weeksRaw = cal["weeks"] as? [[String: Any]] else { return nil }++ var weeks: [[ContributionDay]] = []+ for weekRaw in weeksRaw {+ guard let daysRaw = weekRaw["contributionDays"] as? [[String: Any]] else { continue }+ var days: [ContributionDay] = []+ for dayRaw in daysRaw {+ guard let date = dayRaw["date"] as? String,+ let count = dayRaw["contributionCount"] as? Int,+ let levelStr = dayRaw["contributionLevel"] as? String,+ let weekday = dayRaw["weekday"] as? Int else { continue }+ let level: Int+ switch levelStr {+ case "FIRST_QUARTILE": level = 1+ case "SECOND_QUARTILE": level = 2+ case "THIRD_QUARTILE": level = 3+ case "FOURTH_QUARTILE": level = 4+ default: level = 0 // NONE or unknown+ }+ days.append(ContributionDay(date: date, count: count, level: level, weekday: weekday))+ }+ if !days.isEmpty { weeks.append(days) }+ }++ return GitHubActivity(total: total, weeks: weeks, fetchedAt: Date())+ }++ // MARK: - Helpers++ /// Returns the last n weeks in chronological order (oldest first).+ /// The last week may be incomplete (current week in progress).+ func lastWeeks(_ n: Int) -> [[ContributionDay]] {+ guard n > 0 else { return [] }+ let start = max(0, weeks.count - n)+ return Array(weeks[start...])+ }++ /// Returns the last n days in chronological order (oldest first).+ func lastDays(_ n: Int) -> [ContributionDay] {+ guard n > 0 else { return [] }+ let all = weeks.flatMap { $0 }+ let start = max(0, all.count - n)+ return Array(all[start...])+ }+}diff --git a/NotchBuddy/Sources/App/GitHubPulse.swift b/NotchBuddy/Sources/App/GitHubPulse.swiftindex c4ab5349..6cb21d49 100644--- a/NotchBuddy/Sources/App/GitHubPulse.swift+++ b/NotchBuddy/Sources/App/GitHubPulse.swift@@ -58,7 +58,7 @@ struct GitHubRepoCI: Equatable {// MARK: - GitHubDetailSection-enum GitHubDetailSection { case myPRs, toReview, mainCI }+enum GitHubDetailSection { case myPRs, toReview, mainCI, activity }// MARK: - GitHubEventdiff --git a/NotchBuddy/Sources/App/GithubPoller.swift b/NotchBuddy/Sources/App/GithubPoller.swiftindex 1ceddcc0..538ac2e1 100644--- a/NotchBuddy/Sources/App/GithubPoller.swift+++ b/NotchBuddy/Sources/App/GithubPoller.swift@@ -3,10 +3,12 @@ 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.+ // All properties below are accessed only on the main thread.private var pulseInFlight = falseprivate var nextPulse: DispatchWorkItem?private var tokenGeneration = 0+ private var activityInFlight = false+ private var nextActivity: DispatchWorkItem?private init() {}func start() {@@ -17,10 +19,14 @@ final class GithubPoller: @unchecked Sendable {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+ // First pulse: 10 s after launchDispatchQueue.main.async { [weak self] inself?.scheduleNextPulse(hasPending: false, delay: 10)}+ // First activity: 15 s after launch, then every 30 min+ DispatchQueue.main.async { [weak self] in+ self?.scheduleNextActivity(delay: 15)+ }}// MARK: - Stats (unchanged logic)@@ -182,7 +188,91 @@ final class GithubPoller: @unchecked Sendable {DispatchQueue.main.asyncAfter(deadline: .now() + d, execute: work)}- // MARK: - GraphQL query+ // MARK: - Activity (contribution calendar, 30 min cadence)++ private func pollActivity() {+ DispatchQueue.main.async { [weak self] in+ guard let self, !self.activityInFlight else { return }+ guard let token = KeychainStore.shared.get("github-token"),+ AppState.shared.activeIntegrations.contains("integration_github") else {+ self.scheduleNextActivity()+ return+ }+ self.activityInFlight = true+ let gen = self.tokenGeneration+ DispatchQueue.global(qos: .background).async { self.fetchActivity(token: token, generation: gen) }+ }+ }++ private func fetchActivity(token: String, generation: Int) {+ guard let url = URL(string: "https://api.github.com/graphql") else {+ finishActivity(); 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.activityQuery]) else {+ finishActivity(); 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("activity HTTP \(code)")+ self.finishActivity()+ return+ }+ if let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {+ if let errors = root["errors"] as? [[String: Any]], !errors.isEmpty {+ self.nbLog("activity GraphQL errors: \(errors.count)")+ }+ guard root["data"] is [String: Any] else {+ self.finishActivity(); return+ }+ }+ guard let activity = GitHubActivity.parse(data) else {+ self.finishActivity(); return+ }+ DispatchQueue.main.async {+ guard self.tokenGeneration == generation else { return }+ AppState.shared.githubActivity = activity+ }+ self.finishActivity()+ }.resume()+ }++ /// Refreshes activity data immediately if stale. Safe to call from any thread.+ func refreshActivityIfStale(maxAge: TimeInterval = 300) {+ DispatchQueue.main.async { [weak self] in+ guard let self, !self.activityInFlight else { return }+ guard GitHubPulse.isStale(fetchedAt: AppState.shared.githubActivity?.fetchedAt,+ maxAge: maxAge) else { return }+ self.nextActivity?.cancel()+ self.nextActivity = nil+ self.pollActivity()+ }+ }++ private func finishActivity() {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.activityInFlight = false+ self.scheduleNextActivity()+ }+ }++ private func scheduleNextActivity(delay: Double? = nil) {+ nextActivity?.cancel()+ let work = DispatchWorkItem { [weak self] in self?.pollActivity() }+ nextActivity = work+ let d = delay ?? 1800.0 // 30 minutes+ DispatchQueue.main.asyncAfter(deadline: .now() + d, execute: work)+ }++ // MARK: - GraphQL queriesprivate static let graphQLQuery = """query {@@ -219,4 +309,22 @@ final class GithubPoller: @unchecked Sendable {}}"""++ private static let activityQuery = """+ query {+ viewer {+ login+ contributionsCollection {+ contributionCalendar {+ totalContributions+ weeks {+ contributionDays {+ date contributionCount contributionLevel weekday+ }+ }+ }+ }+ }+ }+ """}diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swiftindex 92e6b0ec..73ce2df7 100644--- a/NotchBuddy/Sources/App/IslandViewContent.swift+++ b/NotchBuddy/Sources/App/IslandViewContent.swift@@ -1766,6 +1766,8 @@ struct IntegrationCardView: View {GitHubDetailView(section: githubDetailSection,pulse: appState.githubPulse!,+ activity: appState.githubActivity,+ stats: appState.githubStats,onBack: {withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { showingDetail = false }}@@ -1775,6 +1777,7 @@ struct IntegrationCardView: View {GitHubPulseCardView(pulse: appState.githubPulse!,stats: appState.githubStats,+ activity: appState.githubActivity,onTapSection: { section ingithubDetailSection = sectionwithAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { showingDetail = true }@@ -2295,6 +2298,7 @@ private func mainCIWorst(_ repos: [GitHubRepoCI]) -> CIState {struct GitHubPulseCardView: View {let pulse: GitHubPulselet stats: GitHubStats?+ let activity: GitHubActivity?let onTapSection: (GitHubDetailSection) -> Voidvar body: some View {@@ -2308,10 +2312,37 @@ struct GitHubPulseCardView: View {.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)+ // Stars + 7-day mini-row → opens Activity detail+ Button(action: { onTapSection(.activity) }) {+ HStack(spacing: 4) {+ Text("★ \(formatCount(s.totalStars))")+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#8E939C"))+ .lineLimit(1)+ if let act = activity {+ HStack(spacing: 2) {+ ForEach(act.lastDays(7), id: \.date) { day in+ RoundedRectangle(cornerRadius: 1.5)+ .fill(contributionColor(day.level))+ .frame(width: 7, height: 7)+ }+ }+ }+ }+ }+ .buttonStyle(.plain)+ } else if let act = activity {+ // No stats yet but activity loaded — show mini-row only+ Button(action: { onTapSection(.activity) }) {+ HStack(spacing: 2) {+ ForEach(act.lastDays(7), id: \.date) { day in+ RoundedRectangle(cornerRadius: 1.5)+ .fill(contributionColor(day.level))+ .frame(width: 7, height: 7)+ }+ }+ }+ .buttonStyle(.plain)} else {Text("Overview").font(.system(size: 11))@@ -2418,13 +2449,16 @@ private struct GitHubStatRow: View {struct GitHubDetailView: View {let section: GitHubDetailSectionlet pulse: GitHubPulse+ let activity: GitHubActivity?+ let stats: GitHubStats?let onBack: () -> Voidprivate var title: String {switch section {- case .myPRs: return "My PRs"+ case .myPRs: return "My PRs"case .toReview: return "To review"- case .mainCI: return "Default branch CI"+ case .mainCI: return "Default branch CI"+ case .activity: return "Activity"}}@@ -2432,7 +2466,7 @@ struct GitHubDetailView: View {switch section {case .myPRs: return pulse.myPRscase .toReview: return pulse.toReview- case .mainCI: return []+ case .mainCI, .activity: return []}}@@ -2440,6 +2474,114 @@ struct GitHubDetailView: View {section == .mainCI ? pulse.mainCI : []}+ var body: some View {+ if section == .activity {+ GitHubActivityDetailContent(+ activity: activity,+ stats: stats,+ login: pulse.login,+ onBack: onBack+ )+ } else {+ 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()+ .onAppear { GithubPoller.shared.refreshIfStale() }+ .onExitCommand { onBack() }+ }+ }+}++// MARK: - GitHub Activity Detail++private struct GitHubActivityDetailContent: View {+ let activity: GitHubActivity?+ let stats: GitHubStats?+ let login: String+ let onBack: () -> Void++ @State private var hoveredDay: ContributionDay? = nil++ // Dynamic grid: s=7pt, spacing=1.5pt; numWeeks = floor((202 + 1.5) / (7 + 1.5)) = 23+ private let squareSize: CGFloat = 7+ private let spacing: CGFloat = 1.5+ private var numWeeks: Int { Int((202 + spacing) / (squareSize + spacing)) }++ private var headerRight: String {+ if let day = hoveredDay {+ let label: String+ switch day.count {+ case 0: label = "No contributions"+ case 1: label = "1 contribution"+ default: label = "\(day.count) contributions"+ }+ return "\(activityDateLabel(day.date)) · \(label)"+ }+ guard let act = activity else { return "" }+ let total = activityTotalLabel(act.total)+ if let s = stats { return "\(total) past year · \(s.totalRepos) repos" }+ return "\(total) past year"+ }+var body: some View {VStack(alignment: .leading, spacing: 0) {// Header@@ -2448,64 +2590,97 @@ struct GitHubDetailView: View {HStack(spacing: 3) {Image(systemName: "chevron.left").font(.system(size: 8, weight: .medium))- Text(title)+ Text("Activity").font(.system(size: 12, weight: .semibold))}.foregroundColor(Color(hex: "#F5F6F8"))}.buttonStyle(.plain)Spacer(minLength: 2)+ if activity != nil {+ Button(action: {+ let urlStr = "https://github.com/\(login)"+ if let url = safeWebURL(urlStr), url.host == "github.com" {+ NSWorkspace.shared.open(url)+ }+ }) {+ Text(headerRight)+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#8E939C"))+ .lineLimit(1)+ }+ .buttonStyle(.plain)+ }}.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)+ // Grid+ if let act = activity {+ let weeks = act.lastWeeks(numWeeks)+ HStack(alignment: .top, spacing: spacing) {+ ForEach(weeks.indices, id: \.self) { wi in+ VStack(spacing: spacing) {+ ForEach(0..<7, id: \.self) { dow in+ if let day = weeks[wi].first(where: { $0.weekday == dow }) {+ RoundedRectangle(cornerRadius: 1.5)+ .fill(contributionColor(day.level))+ .frame(width: squareSize, height: squareSize)+ .onHover { hovering in hoveredDay = hovering ? day : nil }+ .onTapGesture {+ hoveredDay = (hoveredDay?.date == day.date) ? nil : day+ }+ } else {+ Color.clear.frame(width: squareSize, height: squareSize)+ }+ }}}}- .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(.top, 5).padding(.leading, 108)- .padding(.trailing, 8)+ .padding(.trailing, 12)+ } else {+ Text("Loading…")+ .font(.system(size: 10.5))+ .foregroundColor(Color(hex: "#6B7079"))+ .padding(.top, 8)+ .padding(.leading, 108)}}.frame(maxWidth: .infinity, alignment: .topLeading).padding(.top, 4).clipped()- .onAppear { GithubPoller.shared.refreshIfStale() }+ .onAppear { GithubPoller.shared.refreshActivityIfStale() }.onExitCommand { onBack() }}++ private func activityDateLabel(_ dateStr: String) -> String {+ let parts = dateStr.split(separator: "-")+ guard parts.count == 3,+ let month = Int(parts[1]), month >= 1 && month <= 12,+ let day = Int(parts[2]) else { return dateStr }+ let months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]+ return "\(months[month - 1]) \(day)"+ }++ private func activityTotalLabel(_ n: Int) -> String {+ let nf = NumberFormatter()+ nf.numberStyle = .decimal+ nf.locale = Locale(identifier: "en_US")+ return nf.string(from: NSNumber(value: n)) ?? "\(n)"+ }+}++private func contributionColor(_ level: Int) -> Color {+ switch level {+ case 1: return Color(hex: "#0E4429")+ case 2: return Color(hex: "#006D32")+ case 3: return Color(hex: "#26A641")+ case 4: return Color(hex: "#39D353")+ default: return Color.white.opacity(0.06)+ }}private func ghCIDot(_ ci: CIState) -> Color {diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swiftindex cb8aae7d..93c6c852 100644--- a/NotchBuddy/Sources/App/SettingsView.swift+++ b/NotchBuddy/Sources/App/SettingsView.swift@@ -1082,8 +1082,12 @@ struct SettingsView: View {let nextGithubToken = KeychainStore.shared.get("github-token")if nextGithubToken != prevGithubToken {AppState.shared.githubPulse = nil+ AppState.shared.githubActivity = nilif nextGithubToken == nil { AppState.shared.githubStats = nil }- if nextGithubToken != nil { GithubPoller.shared.triggerPulseNow() }+ if nextGithubToken != nil {+ GithubPoller.shared.triggerPulseNow()+ GithubPoller.shared.refreshActivityIfStale()+ }}saveKey("stripe-api-key", value: stripeKey)diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.mdindex 6a35ec80..138e0183 100644--- a/docs/INTEGRATIONS.md+++ b/docs/INTEGRATIONS.md@@ -145,15 +145,30 @@ Sur `PostToolUse` pour `Edit`, `MultiEdit` et `Write` (Claude Code, Cursor), l'a### Données récupérées-Une seule requête GraphQL (POST `https://api.github.com/graphql`) :+Deux requêtes GraphQL séparées (POST `https://api.github.com/graphql`, même token, même en-tête) :+**Requête pulse** :- **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) : `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.+**Cadence pulse** : 5 min (pas de PRs en attente) ou 60 s (au moins une PR/CI en état `PENDING` ou `EXPECTED`). Première requête 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é.+**Rafraîchissement pulse à l'ouverture** : `GithubPoller.refreshIfStale(maxAge: 60)` appelé quand `integration_github` prend le focus, quand l'île s'étend avec GitHub en focus, et à l'ouverture d'une vue détail (sauf Activity). Si données < 60 s ou requête en vol, ignoré.++**Requête activité** (`contributionCalendar`) :+```graphql+query { viewer { login contributionsCollection { contributionCalendar {+ totalContributions weeks { contributionDays { date contributionCount contributionLevel weekday } }+} } } }+```+- `contributionLevel` : NONE → 0, FIRST_QUARTILE → 1, SECOND_QUARTILE → 2, THIRD_QUARTILE → 3, FOURTH_QUARTILE → 4. Valeur inconnue → 0.++**Cadence activité** : 30 min, première requête 15 s après le lancement.++**Rafraîchissement activité à l'ouverture** : `GithubPoller.refreshActivityIfStale(maxAge: 300)` appelé à l'ouverture de la vue Activity. Si données < 5 min ou requête en vol, ignoré.++Données gardées en mémoire (`AppState.githubActivity`). Remises à nil si token change ou si `integration_github` est désactivé.### États CI (`CIState`)diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 2c5044b3..e1dec489 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -119,11 +119,15 @@ Règles :### 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.+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 » + bouton « ★ N.Nk » (étoiles) + rangée de 7 carrés de contribution (7 derniers jours, 7 pt, espacement 2 pt) si `githubActivity != nil` → ouvre la section `.activity`. Sans stats : « Overview ».### 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.+Remplace la carte principale quand `showingDetail && githubHasPulse`. En-tête : chevron.left (← ferme) + titre de section. Sections **My PRs**, **To review** → `GitHubPRRowView` (point CI + « repo#N » + titre tronqué + badge Draft), ScrollView maxHeight 60 pt (3 lignes × 20 pt), fondu bas si > 3 éléments. Section **Default branch CI** → `GitHubRepoCIRowView` (point CI + nom court + branche + état). Clic sur une PR → ouvre `https://github.com/…` (filtré `host == "github.com"`). Échap ferme.++### Section Activity (`GitHubActivityDetailContent`)++Section `.activity` de `GitHubDetailView`. En-tête : chevron.left + « Activity » à gauche ; à droite (11 pt #8E939C) : « 1,234 past year · N repos » (clic → `github.com/<login>`). Au survol / clic sur un carré : texte remplacé par « Oct 3 · 12 contributions » (ou « 1 contribution », ou « No contributions »). Grille de contributions : colonnes = semaines (la plus ancienne à gauche, ~20 semaines à 8 pt avec espacement 2 pt), lignes = jours de la semaine (dimanche = ligne 0). Couleurs des niveaux : 0 = blanc 6 %, 1 = `#0E4429`, 2 = `#006D32`, 3 = `#26A641`, 4 = `#39D353`. Pas de ScrollView, `.clipped()`. `refreshActivityIfStale()` à l'apparition.### 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 3a67bc6e..2f044b09 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. 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>+<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, CI status of your repositories' default branches, and your contribution calendar (the green squares on your profile); this data is kept in memory only 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. 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>+<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, l'état CI de la branche par défaut de tes dépôts et ton calendrier de contributions (les carrés verts de ton profil) ; ces données sont conservées uniquement 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-activity.sh b/scripts/test-github-activity.shnew file mode 100755index 00000000..b09de356--- /dev/null+++ b/scripts/test-github-activity.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-github-activity.XXXXXX")"+trap 'rm -rf "$TEST_DIR"' EXIT+swiftc NotchBuddy/Sources/App/GitHubActivity.swift \+ tests/GitHubActivityTests.swift -o "$TEST_DIR/github-activity-tests"+"$TEST_DIR/github-activity-tests"diff --git a/tests/GitHubActivityTests.swift b/tests/GitHubActivityTests.swiftnew file mode 100644index 00000000..861abef7--- /dev/null+++ b/tests/GitHubActivityTests.swift@@ -0,0 +1,157 @@+import Foundation++@main+enum GitHubActivityTests {++ static var failures = 0++ static func check(_ label: String, _ got: Bool) {+ if got { print(" ✓ \(label)") }+ else { print(" ✗ \(label)"); failures += 1 }+ }++ // MARK: - Fixture JSON+ //+ // Week 1 (complete, Jan 5–11 2026):+ // Jan 5 wd=0 NONE(0), Jan 6 wd=1 FIRST_QUARTILE(1), Jan 7 wd=2 SECOND_QUARTILE(2),+ // Jan 8 wd=3 THIRD_QUARTILE(3), Jan 9 wd=4 FOURTH_QUARTILE(4),+ // Jan 10 wd=5 FIRST_QUARTILE(1), Jan 11 wd=6 NONE(0)+ // counts: 0+1+4+8+12+2+0 = 27+ //+ // Week 2 (incomplete, Jan 12–13 2026):+ // Jan 12 wd=0 SECOND_QUARTILE(2), Jan 13 wd=1 THIRD_QUARTILE(3)+ // counts: 5+10 = 15+ //+ // Total: 42+ static let validJSON: Data = """+ {+ "data": {+ "viewer": {+ "login": "testuser",+ "contributionsCollection": {+ "contributionCalendar": {+ "totalContributions": 42,+ "weeks": [+ {+ "contributionDays": [+ {"date": "2026-01-05", "contributionCount": 0, "contributionLevel": "NONE", "weekday": 0},+ {"date": "2026-01-06", "contributionCount": 1, "contributionLevel": "FIRST_QUARTILE", "weekday": 1},+ {"date": "2026-01-07", "contributionCount": 4, "contributionLevel": "SECOND_QUARTILE", "weekday": 2},+ {"date": "2026-01-08", "contributionCount": 8, "contributionLevel": "THIRD_QUARTILE", "weekday": 3},+ {"date": "2026-01-09", "contributionCount": 12, "contributionLevel": "FOURTH_QUARTILE", "weekday": 4},+ {"date": "2026-01-10", "contributionCount": 2, "contributionLevel": "FIRST_QUARTILE", "weekday": 5},+ {"date": "2026-01-11", "contributionCount": 0, "contributionLevel": "NONE", "weekday": 6}+ ]+ },+ {+ "contributionDays": [+ {"date": "2026-01-12", "contributionCount": 5, "contributionLevel": "SECOND_QUARTILE", "weekday": 0},+ {"date": "2026-01-13", "contributionCount": 10, "contributionLevel": "THIRD_QUARTILE", "weekday": 1}+ ]+ }+ ]+ }+ }+ }+ }+ }+ """.data(using: .utf8)!++ static let unknownLevelJSON: Data = """+ {+ "data": {+ "viewer": {+ "login": "testuser",+ "contributionsCollection": {+ "contributionCalendar": {+ "totalContributions": 1,+ "weeks": [+ {+ "contributionDays": [+ {"date": "2026-03-01", "contributionCount": 1, "contributionLevel": "EXTRA_SPECIAL", "weekday": 0}+ ]+ }+ ]+ }+ }+ }+ }+ }+ """.data(using: .utf8)!++ // MARK: - Main++ static func main() {++ // ── GitHubActivity.parse ──────────────────────────────────────────────+ print("GitHubActivity.parse")+ do {+ let act = GitHubActivity.parse(validJSON)+ check("parse returns non-nil", act != nil)+ check("total == 42", act?.total == 42)+ check("2 weeks", act?.weeks.count == 2)+ check("week 0 has 7 days", act?.weeks[0].count == 7)+ check("week 1 has 2 days (incomplete)", act?.weeks[1].count == 2)+ // Level mapping+ check("NONE → level 0", act?.weeks[0][0].level == 0)+ check("FIRST_QUARTILE → level 1", act?.weeks[0][1].level == 1)+ check("SECOND_QUARTILE → level 2", act?.weeks[0][2].level == 2)+ check("THIRD_QUARTILE → level 3", act?.weeks[0][3].level == 3)+ check("FOURTH_QUARTILE → level 4", act?.weeks[0][4].level == 4)+ // Dates and counts+ check("first day date", act?.weeks[0][0].date == "2026-01-05")+ check("first day count", act?.weeks[0][0].count == 0)+ check("first day wd", act?.weeks[0][0].weekday == 0)+ check("last day date", act?.weeks[1][1].date == "2026-01-13")+ check("last day count", act?.weeks[1][1].count == 10)+ }++ // ── GitHubActivity.parse — unknown level ─────────────────────────────+ print("GitHubActivity.parse — unknown level → 0")+ do {+ let act = GitHubActivity.parse(unknownLevelJSON)+ check("unknown level → 0", act?.weeks[0][0].level == 0)+ }++ // ── GitHubActivity.parse — bad data → nil ────────────────────────────+ print("GitHubActivity.parse — bad data")+ do {+ check("garbage → nil", GitHubActivity.parse("garbage".data(using: .utf8)!) == nil)+ check("no data key → nil", GitHubActivity.parse("{}".data(using: .utf8)!) == nil)+ }++ // ── GitHubActivity.lastWeeks ─────────────────────────────────────────+ print("GitHubActivity.lastWeeks")+ do {+ let act = GitHubActivity.parse(validJSON)!+ check("lastWeeks(2) returns both", act.lastWeeks(2).count == 2)+ check("lastWeeks(1) returns last week", act.lastWeeks(1).count == 1)+ check("lastWeeks(1)[0] is incomplete", act.lastWeeks(1)[0].count == 2)+ check("lastWeeks(1)[0][0].date", act.lastWeeks(1)[0][0].date == "2026-01-12")+ check("lastWeeks(99) clamps to available", act.lastWeeks(99).count == 2)+ check("lastWeeks(0) returns empty", act.lastWeeks(0).isEmpty)+ }++ // ── GitHubActivity.lastDays ──────────────────────────────────────────+ print("GitHubActivity.lastDays")+ do {+ let act = GitHubActivity.parse(validJSON)!+ // All 9 days flat, last 3 = Jan 11, Jan 12, Jan 13+ check("lastDays(3) count", act.lastDays(3).count == 3)+ check("lastDays(3)[0].date", act.lastDays(3)[0].date == "2026-01-11")+ check("lastDays(3)[2].date", act.lastDays(3)[2].date == "2026-01-13")+ check("lastDays(9) all days", act.lastDays(9).count == 9)+ check("lastDays(99) clamps to all", act.lastDays(99).count == 9)+ check("lastDays(0) empty", act.lastDays(0).isEmpty)+ }++ // ── finish ────────────────────────────────────────────────────────────+ if failures == 0 {+ print("\nAll tests passed.")+ exit(0)+ } else {+ print("\n\(failures) test(s) failed.")+ exit(1)+ }+ }+}