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
Mail pill: the latest messages of Apple Mail in the notch
Claude32565c52f526
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex a337e02c..5b747f30 100644--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj@@ -46,6 +46,8 @@1C2BB61FA83015C42B321E0E /* PillColors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37564F5F041B38C976DF3DEF /* PillColors.swift */; };1D23613B270FE8B11C5E27A7 /* IslandDisplayChoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A09E73F1E58019EF6EA2A62 /* IslandDisplayChoice.swift */; };1D4CE0CCD2B5A0FFE50C7F06 /* TerminalTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */; };+ AE2F7E3B42815ADC7EE77B8D /* MailViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCFDE7CC2BD8BCA9A6C9DF45 /* MailViews.swift */; };+ 56D42241B003E714A77CF838 /* MailController.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB502629F8A6EE9E8A647B2E /* MailController.swift */; };65F11D3911C3240BD89CF1C5 /* ApprovalQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5077E908D307285474CA87C /* ApprovalQueue.swift */; };9CF7070265B7CDC933FD9776 /* PillSessionRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */; };1DAB0704A136FF8E6FB34191 /* ClaudeResponseText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 444604C7E2C530B664849EF9 /* ClaudeResponseText.swift */; };@@ -127,6 +129,8 @@65CB53E20B2289CA3AC3E8FE /* TurnSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A1C4152EBDBD7C24CABFFD7 /* TurnSnapshot.swift */; };6613EB914852E6EEB1FF37BF /* IntentParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = F39753CFF90B494D449CCD95 /* IntentParser.swift */; };6726F74966EDE7F82BFE89B2 /* TerminalTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */; };+ F6D1C30750D5232B70F678C1 /* MailViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCFDE7CC2BD8BCA9A6C9DF45 /* MailViews.swift */; };+ 2B2706A9D900EE525E470A6F /* MailController.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB502629F8A6EE9E8A647B2E /* MailController.swift */; };3E808AC02E35ABF5801BEBEC /* ApprovalQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5077E908D307285474CA87C /* ApprovalQueue.swift */; };11363898DA837388E2823E7F /* PillSessionRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */; };68A950E3C23FD612639D9776 /* IslandViewContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA02B08886939FF6FE0475DD /* IslandViewContent.swift */; };@@ -440,6 +444,8 @@871CA2BADC67D97C97C7009D /* error.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = error.wav; sourceTree = "<group>"; };8790ACE9F73BD74640A0F20C /* LocalChat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalChat.swift; sourceTree = "<group>"; };87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalTarget.swift; sourceTree = "<group>"; };+ DCFDE7CC2BD8BCA9A6C9DF45 /* MailViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MailViews.swift; sourceTree = "<group>"; };+ AB502629F8A6EE9E8A647B2E /* MailController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MailController.swift; sourceTree = "<group>"; };E5077E908D307285474CA87C /* ApprovalQueue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApprovalQueue.swift; sourceTree = "<group>"; };30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PillSessionRegistry.swift; sourceTree = "<group>"; };888B3E1420BCB6292BDC8117 /* WeeklyRecapView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeeklyRecapView.swift; sourceTree = "<group>"; };@@ -585,6 +591,8 @@914A792788D403F836BEB570 /* SpotifyViews.swift */,2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */,87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */,+ DCFDE7CC2BD8BCA9A6C9DF45 /* MailViews.swift */,+ AB502629F8A6EE9E8A647B2E /* MailController.swift */,E5077E908D307285474CA87C /* ApprovalQueue.swift */,30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */,244A7909EEDA4BFF4C2EA9B5 /* TerminalTarget+AppKit.swift */,@@ -1059,6 +1067,8 @@1558BB00C530B721172F6E65 /* StripePoller.swift in Sources */,9EA178EA395B116336C1FA10 /* TerminalTarget+AppKit.swift in Sources */,1D4CE0CCD2B5A0FFE50C7F06 /* TerminalTarget.swift in Sources */,+ AE2F7E3B42815ADC7EE77B8D /* MailViews.swift in Sources */,+ 56D42241B003E714A77CF838 /* MailController.swift in Sources */,65F11D3911C3240BD89CF1C5 /* ApprovalQueue.swift in Sources */,9CF7070265B7CDC933FD9776 /* PillSessionRegistry.swift in Sources */,8551E592C5FFC6A0A7458A26 /* TurnEndPolicy.swift in Sources */,@@ -1253,6 +1263,8 @@E4B9986674F4D425826F15A8 /* StripePoller.swift in Sources */,11F14DB97C93CF84DF9D5C43 /* TerminalTarget+AppKit.swift in Sources */,6726F74966EDE7F82BFE89B2 /* TerminalTarget.swift in Sources */,+ F6D1C30750D5232B70F678C1 /* MailViews.swift in Sources */,+ 2B2706A9D900EE525E470A6F /* MailController.swift in Sources */,3E808AC02E35ABF5801BEBEC /* ApprovalQueue.swift in Sources */,11363898DA837388E2823E7F /* PillSessionRegistry.swift in Sources */,ABE0CEF17018F1BAD8F7DBFA /* TurnEndPolicy.swift in Sources */,diff --git a/NotchBuddy/Resources/Localizable.xcstrings b/NotchBuddy/Resources/Localizable.xcstringsindex 793883c1..0f450893 100644--- a/NotchBuddy/Resources/Localizable.xcstrings+++ b/NotchBuddy/Resources/Localizable.xcstrings@@ -26206,6 +26206,582 @@}}}+ },+ "Inbox": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "البريد الوارد"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "ইনবক্স"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Inbox"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Bandeja de entrada"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Boîte de réception"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "इनबॉक्स"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Kotak masuk"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Caixa de entrada"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Входящие"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "收件箱"+ }+ }+ }+ },+ "%lld unread": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld غير مقروءة"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld অপঠিত"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld unread"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld sin leer"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld non lus"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld अपठित"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld belum dibaca"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld não lidos"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Непрочитанных: %lld"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld 封未读"+ }+ }+ }+ },+ "No messages": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "لا توجد رسائل"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "কোনো বার্তা নেই"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "No messages"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "No hay mensajes"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Aucun message"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "कोई संदेश नहीं"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Tidak ada pesan"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Nenhuma mensagem"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Нет сообщений"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "没有邮件"+ }+ }+ }+ },+ "Open in Mail": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "فتح في Mail"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail-এ খুলুন"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Open in Mail"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Abrir en Mail"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Ouvrir dans Mail"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail में खोलें"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Buka di Mail"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Abrir no Mail"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Открыть в Почте"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "在“邮件”中打开"+ }+ }+ }+ },+ "Reply": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "رد"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "উত্তর দিন"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Reply"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Responder"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Répondre"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "जवाब दें"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Balas"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Responder"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Ответить"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "回复"+ }+ }+ }+ },+ "Mark as read": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "وضع علامة كمقروءة"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "পঠিত হিসেবে চিহ্নিত করুন"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Mark as read"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Marcar como leído"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Marquer comme lu"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "पढ़ा हुआ चिह्नित करें"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Tandai sudah dibaca"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Marcar como lido"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Отметить как прочитанное"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "标为已读"+ }+ }+ }+ },+ "Mail is closed": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "تطبيق Mail مغلق"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail বন্ধ আছে"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail is closed"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail está cerrado"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail est fermé"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail बंद है"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail ditutup"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "O Mail está fechado"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Почта закрыта"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "“邮件”未打开"+ }+ }+ }+ },+ "Open Mail": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "فتح Mail"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail খুলুন"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Open Mail"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Abrir Mail"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Ouvrir Mail"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "Mail खोलें"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Buka Mail"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Abrir o Mail"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Открыть Почту"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "打开“邮件”"+ }+ }+ }+ },+ "mail.now": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "الآن"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "এখন"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "now"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "ahora"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "à l’instant"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "अभी"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "baru saja"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "agora"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "сейчас"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "刚刚"+ }+ }+ }}},"version": "1.0"diff --git a/NotchBuddy/Sources/App/AppDelegate.swift b/NotchBuddy/Sources/App/AppDelegate.swiftindex 1814a5e7..8c926779 100644--- a/NotchBuddy/Sources/App/AppDelegate.swift+++ b/NotchBuddy/Sources/App/AppDelegate.swift@@ -217,6 +217,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {#if !APPSTORE_ = MusicController.shared_ = SpotifyController.shared+ MailController.shared.start()#endif}}diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swiftindex 824d47d6..d21033fc 100644--- a/NotchBuddy/Sources/App/IslandViewContent.swift+++ b/NotchBuddy/Sources/App/IslandViewContent.swift@@ -221,6 +221,10 @@ struct OverviewView: View {}case "integration_resend":NSWorkspace.shared.open(URL(string: "https://resend.com/emails")!)+ case "integration_mail":+ #if !APPSTORE+ MailController.shared.openMail()+ #endifcase "integration_vercel":NSWorkspace.shared.open(URL(string: "https://vercel.com/dashboard")!)case "integration_github":@@ -1770,6 +1774,9 @@ struct IntegrationCardView: View {var onDiffTap: ((Int) -> Void)? = nil@ObservedObject private var appState = AppState.shared@State private var githubDetailSection: GitHubDetailSection = .myPRs+ #if !APPSTORE+ @ObservedObject private var mailController = MailController.shared+ #endifprivate var isConfigured: Bool {switch task.id {@@ -1833,6 +1840,12 @@ struct IntegrationCardView: View {#elsereturn false#endif+ case "integration_mail":+ #if !APPSTORE+ return true // Apple Mail is always installed on macOS: nothing to set up+ #else+ return false+ #endifcase "ai_anthropic": return KeychainStore.shared.get("anthropic-api-key") != nilcase "ai_google": return KeychainStore.shared.get("google-api-key") != nilcase "ai_openai": return KeychainStore.shared.get("openai-api-key") != nil@@ -1924,6 +1937,17 @@ struct IntegrationCardView: View {#endif}+ // Apple Mail: the message list once Mail is open and allowed (else the idle card says why)+ private var mailHasData: Bool {+ #if !APPSTORE+ guard task.id == "integration_mail" else { return false }+ let mail = MailController.shared+ return mail.isMailRunning && !mail.automationDenied+ #else+ return false+ #endif+ }+// Spotify: its own card for every state (playing, idle, not installed, Automation denied)private var isSpotify: Bool {#if !APPSTORE@@ -1940,6 +1964,12 @@ struct IntegrationCardView: View {return appState.musicPlaying ? Color(hex: "#FA2D48") : Color(hex: "#22C55E")}#endif+ #if !APPSTORE+ if task.id == "integration_mail" {+ if mailController.automationDenied { return Color(hex: "#F4505E") }+ return mailController.isMailRunning ? Color(hex: "#22C55E") : Color(hex: "#6B7079")+ }+ #endifif PillCatalog.definition(for: task.id)?.comingSoon == true { return Color(hex: "#6B7079") }let svcErr = task.id == "integration_stripe" ? appState.stripeError: task.id == "integration_calcom" ? appState.calcomError@@ -1956,6 +1986,12 @@ struct IntegrationCardView: View {return String(localized: "Not playing")}#endif+ #if !APPSTORE+ if task.id == "integration_mail" {+ if mailController.automationDenied { return String(localized: "Automation not allowed") }+ return mailController.isMailRunning ? String(localized: "Loading…") : String(localized: "Mail is closed")+ }+ #endifif PillCatalog.definition(for: task.id)?.comingSoon == true { return String(localized: "Coming soon") }let svcErr = task.id == "integration_stripe" ? appState.stripeError: task.id == "integration_calcom" ? appState.calcomError@@ -2058,6 +2094,11 @@ struct IntegrationCardView: View {MusicCardView().transition(.opacity)#endif+ } else if mailHasData {+ #if !APPSTORE+ MailCardView()+ .transition(.opacity)+ #endif} else if isSpotify {#if !APPSTORESpotifyCardView()@@ -2187,6 +2228,19 @@ struct IntegrationCardView: View {.buttonStyle(.plain)}#endif+ } else if task.id == "integration_mail" {+ #if !APPSTORE+ Button("Open Mail") { MailController.shared.openMail() }+ .font(.system(size: 11, weight: .medium))+ .foregroundColor(Color(hex: task.color).opacity(0.85))+ .buttonStyle(.plain)+ if mailController.automationDenied {+ Button("Open Settings…") { MailController.shared.openAutomationSettings() }+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#8E939C"))+ .buttonStyle(.plain)+ }+ #endif} else if n8nHasActivity {// Clickable pill — tap to open execution detaillet success = task.state == .finished@@ -2232,7 +2286,8 @@ struct IntegrationCardView: View {if !isConfigured&& task.id != "agent_cursor"&& task.id != "agent_codex"- && task.id != "integration_music" {+ && task.id != "integration_music"+ && task.id != "integration_mail" {Button("Settings…") {let section: Stringswitch PillCatalog.definition(for: task.id)?.category {diff --git a/NotchBuddy/Sources/App/MailController.swift b/NotchBuddy/Sources/App/MailController.swiftnew file mode 100644index 00000000..574027d0--- /dev/null+++ b/NotchBuddy/Sources/App/MailController.swift@@ -0,0 +1,404 @@+#if !APPSTORE+import Foundation+import AppKit+import Combine++// MARK: - Mail message++/// One message of an inbox, as Apple Mail reports it.+struct MailMessage: Identifiable, Equatable, Sendable {+ /// Mail's own id of the message (unique within its mailbox).+ let messageId: Int+ let account: String+ let mailbox: String+ /// Raw sender, "Name <address>" or just the address.+ let sender: String+ let subject: String+ let date: Date+ var isRead: Bool++ var id: String { "\(account)/\(mailbox)/\(messageId)" }++ /// "Name" from "Name <address>", else the address before "@".+ var senderName: String {+ let raw = sender.trimmingCharacters(in: .whitespaces)+ if let lt = raw.firstIndex(of: "<") {+ let name = raw[..<lt].trimmingCharacters(in: CharacterSet(charactersIn: " \""))+ if !name.isEmpty { return name }+ let address = raw[raw.index(after: lt)...].trimmingCharacters(in: CharacterSet(charactersIn: "> "))+ return String(address.split(separator: "@").first ?? Substring(address))+ }+ return String(raw.split(separator: "@").first ?? Substring(raw))+ }++ /// The address alone, from "Name <address>".+ var senderAddress: String {+ let raw = sender.trimmingCharacters(in: .whitespaces)+ if let lt = raw.firstIndex(of: "<"), let gt = raw.lastIndex(of: ">"), lt < gt {+ return String(raw[raw.index(after: lt)..<gt])+ }+ return raw+ }++ var timeAgo: String {+ let diff = Date().timeIntervalSince(date)+ if diff < 60 { return String(localized: "mail.now") }+ if diff < 3600 { return "\(Int(diff / 60))m" }+ if diff < 86400 { return "\(Int(diff / 3600))h" }+ return "\(Int(diff / 86400))d"+ }+}++// MARK: - Mail Controller++/// Reads the inboxes of Apple Mail (every account added to Mail, Gmail included) through+/// Apple Events: unread count, latest messages, and a message's text on demand.+/// Read-only except for the user's own clicks (mark as read, reply window, open in Mail);+/// it never sends anything. Mail is never launched by Coucou: nothing is read while Mail+/// is closed. Polls every 60 s, only while the pill is active and Mail is open.+/// GitHub build only (Apple Events are not allowed in the App Store build).+@MainActor+final class MailController: ObservableObject {+ static let shared = MailController()+ nonisolated static let pillId = "integration_mail"+ nonisolated static let bundleId = "com.apple.mail"++ /// Latest messages of all inboxes, newest first.+ @Published private(set) var messages: [MailMessage] = []+ /// Unread messages in all inboxes (Mail's own count), nil before the first read.+ @Published private(set) var unreadCount: Int?+ @Published private(set) var loaded = false+ @Published private(set) var isMailRunning = false+ @Published private(set) var automationDenied = false+ /// Text of the messages opened in the card, by message id.+ @Published private(set) var previews: [String: String] = [:]++ /// How many messages are kept for the card (the newest across all inboxes).+ nonisolated static let keep = 12++ private var notifTokens: [Any] = []+ private var cancellables = Set<AnyCancellable>()+ private var timer: Timer?+ private var fetching = false+ private var lastFetch: Date = .distantPast+ private let queue = DispatchQueue(label: "fr.louisraille.coucou.mail")++ private var isPillActive: Bool {+ AppState.shared.activeIntegrations.contains(Self.pillId)+ }++ private init() {+ isMailRunning = Self.mailRunning()++ let ws = NSWorkspace.shared.notificationCenter+ notifTokens.append(ws.addObserver(forName: NSWorkspace.didLaunchApplicationNotification,+ object: nil, queue: .main) { [weak self] notif in+ let bundleId = (notif.userInfo?[NSWorkspace.applicationUserInfoKey]+ as? NSRunningApplication)?.bundleIdentifier+ guard bundleId == Self.bundleId else { return }+ Task { @MainActor [weak self] in+ self?.isMailRunning = true+ self?.updatePolling()+ }+ })+ notifTokens.append(ws.addObserver(forName: NSWorkspace.didTerminateApplicationNotification,+ object: nil, queue: .main) { [weak self] notif in+ let bundleId = (notif.userInfo?[NSWorkspace.applicationUserInfoKey]+ as? NSRunningApplication)?.bundleIdentifier+ guard bundleId == Self.bundleId else { return }+ Task { @MainActor [weak self] in+ self?.isMailRunning = false+ self?.updatePolling()+ }+ })++ // Pill turned on → first read; turned off → stop and forget everything.+ AppState.shared.$activeIntegrations+ .map { $0.contains(Self.pillId) }+ .removeDuplicates()+ .sink { [weak self] _ in+ // The sink runs before the property changes: decide on the next turn.+ DispatchQueue.main.async { self?.updatePolling() }+ }+ .store(in: &cancellables)+ }++ /// Called once at launch so the controller starts observing.+ func start() { updatePolling() }++ // MARK: - Polling++ private static func mailRunning() -> Bool {+ NSWorkspace.shared.runningApplications.contains { $0.bundleIdentifier == bundleId }+ }++ private func updatePolling() {+ if isPillActive && isMailRunning {+ if timer == nil {+ let t = Timer(timeInterval: 60, repeats: true) { _ in+ MainActor.assumeIsolated { MailController.shared.refresh() }+ }+ t.tolerance = 10+ RunLoop.main.add(t, forMode: .common)+ timer = t+ }+ refresh()+ } else {+ timer?.invalidate()+ timer = nil+ if !isPillActive {+ messages = []+ unreadCount = nil+ previews = [:]+ loaded = false+ }+ }+ }++ /// Reads the inboxes again unless that was done in the last `minAge` seconds.+ func refreshIfStale(minAge: TimeInterval = 15) {+ guard Date().timeIntervalSince(lastFetch) > minAge else { return }+ refresh()+ }++ /// Reads the unread count and the latest messages of every inbox.+ func refresh() {+ guard isPillActive, Self.mailRunning(), !fetching else { return }+ isMailRunning = true+ fetching = true+ lastFetch = Date()+ Task {+ let result = await runAppleScript(Self.listScript(perInbox: Self.keep))+ fetching = false+ guard case .success(let values) = result, let text = values.first else { return }+ let parsed = Self.parseList(text)+ unreadCount = parsed.unread+ let newest = Array(parsed.messages.sorted { $0.date > $1.date }.prefix(Self.keep))+ if newest != messages { messages = newest }+ loaded = true+ }+ }++ // MARK: - Actions (each one follows a click)++ /// The message's text (first 1,200 characters), read once and cached.+ func loadPreview(_ message: MailMessage) {+ guard previews[message.id] == nil, Self.mailRunning() else { return }+ Task {+ let script = Self.messageScript(message, body: """+ set c to ""+ try+ set c to content of m+ end try+ if (length of c) > 1200 then set c to text 1 thru 1200 of c+ return c+ """)+ let result = await runAppleScript(script)+ if case .success(let values) = result {+ let text = (values.first ?? "")+ .replacingOccurrences(of: "\r", with: "\n")+ .replacingOccurrences(of: "\u{FFFC}", with: "") // attachment placeholders+ .replacingOccurrences(of: "\n\n\n", with: "\n\n")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ previews[message.id] = text+ } else {+ previews[message.id] = ""+ }+ }+ }++ func markAsRead(_ message: MailMessage) {+ guard Self.mailRunning() else { return }+ if let i = messages.firstIndex(where: { $0.id == message.id }) {+ if !messages[i].isRead, let u = unreadCount { unreadCount = max(0, u - 1) }+ messages[i].isRead = true+ }+ Task {+ await runAppleScript(Self.messageScript(message, body: "set read status of m to true"))+ }+ }++ /// Opens Mail's own reply window for the message. Nothing is sent: the user writes+ /// and sends from Mail.+ func reply(_ message: MailMessage) {+ guard Self.mailRunning() else { return }+ Task {+ await runAppleScript(Self.messageScript(message, body: """+ reply m with opening window+ activate+ """))+ }+ }++ func openInMail(_ message: MailMessage) {+ guard Self.mailRunning() else { openMail(); return }+ Task {+ await runAppleScript(Self.messageScript(message, body: """+ open m+ activate+ """))+ }+ }++ func openMail() {+ if let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: Self.bundleId) {+ NSWorkspace.shared.openApplication(at: url, configuration: .init(), completionHandler: nil)+ }+ }++ func openAutomationSettings() {+ if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Automation") {+ NSWorkspace.shared.open(url)+ }+ }++ // MARK: - Scripts++ /// Field and record separators: characters that never appear in a subject or a name.+ nonisolated static let fieldSep: Character = "\u{1F}"+ nonisolated static let recordSep: Character = "\u{1E}"++ /// Unread count, then for each account's inbox its newest `perInbox` messages:+ /// id, account, mailbox, sender, subject, date (ISO), read status.+ nonisolated static func listScript(perInbox: Int) -> String {+ """+ set RS to character id 30+ set US to character id 31+ tell application id "com.apple.mail"+ set uc to 0+ try+ set uc to unread count of inbox+ end try+ set out to (uc as string)+ set accs to {}+ try+ set accs to (every account whose enabled is true)+ on error+ try+ set accs to every account+ end try+ end try+ repeat with acc in accs+ set mb to missing value+ try+ set mb to mailbox "INBOX" of acc+ on error+ try+ set mb to mailbox "Inbox" of acc+ end try+ end try+ if mb is not missing value then+ set n to 0+ try+ set n to count of messages of mb+ end try+ if n > 0 then+ set k to \(perInbox)+ if n < k then set k to n+ -- Newest first when message 1 is the most recent, else read from the end.+ set a to 1+ set b to k+ try+ if (date received of message 1 of mb) < (date received of message n of mb) then+ set a to n - k + 1+ set b to n+ end if+ end try+ -- One request per field for the whole range (not one per message).+ try+ set ids to id of messages a thru b of mb+ set subs to subject of messages a thru b of mb+ set snds to sender of messages a thru b of mb+ set dts to date received of messages a thru b of mb+ set rds to read status of messages a thru b of mb+ repeat with i from 1 to count of ids+ try+ set s to item i of subs+ if s is missing value then set s to ""+ set f to item i of snds+ if f is missing value then set f to ""+ set d to ""+ try+ set d to ((item i of dts) as «class isot» as string)+ end try+ set out to out & RS & ((item i of ids) as string) & US & (name of acc) & US & (name of mb) & US & f & US & s & US & d & US & ((item i of rds) as string)+ end try+ end repeat+ end try+ end if+ end if+ end repeat+ return out+ end tell+ """+ }++ /// A script that finds `message` in its mailbox as `m`, then runs `body`.+ nonisolated static func messageScript(_ message: MailMessage, body: String) -> String {+ """+ tell application id "com.apple.mail"+ set mb to mailbox "\(escape(message.mailbox))" of account "\(escape(message.account))"+ set m to first message of mb whose id is \(message.messageId)+ \(body)+ end tell+ """+ }++ nonisolated static func escape(_ s: String) -> String {+ s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")+ }++ /// Parses the list script's output (see listScript). Malformed records are skipped.+ nonisolated static func parseList(_ text: String) -> (unread: Int?, messages: [MailMessage]) {+ let records = text.split(separator: recordSep, omittingEmptySubsequences: false)+ guard let head = records.first else { return (nil, []) }+ let unread = Int(head.trimmingCharacters(in: .whitespaces))+ let iso = DateFormatter()+ iso.locale = Locale(identifier: "en_US_POSIX")+ iso.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"+ var seen = Set<String>()+ var out: [MailMessage] = []+ for record in records.dropFirst() {+ let f = record.split(separator: fieldSep, omittingEmptySubsequences: false).map(String.init)+ guard f.count >= 7, let id = Int(f[0]) else { continue }+ let msg = MailMessage(messageId: id, account: f[1], mailbox: f[2], sender: f[3],+ subject: f[4], date: iso.date(from: f[5]) ?? .distantPast,+ isRead: f[6] == "true")+ guard seen.insert(msg.id).inserted else { continue }+ out.append(msg)+ }+ return (unread, out)+ }++ // MARK: - AppleScript runner++ enum ScriptResult { case success([String]), denied, error }++ @discardableResult+ private func runAppleScript(_ source: String) async -> ScriptResult {+ await withCheckedContinuation { cont in+ queue.async {+ guard let script = NSAppleScript(source: source) else {+ cont.resume(returning: .error)+ return+ }+ var errDict: NSDictionary?+ let desc = script.executeAndReturnError(&errDict)+ if let errDict {+ let code = (errDict[NSAppleScript.errorNumber] as? Int) ?? 0+ if code == -1743 {+ Task { @MainActor in MailController.shared.automationDenied = true }+ cont.resume(returning: .denied)+ } else {+ cont.resume(returning: .error)+ }+ return+ }+ Task { @MainActor in MailController.shared.automationDenied = false }+ // Extract the values on this queue before resuming (NSAppleEventDescriptor is not Sendable).+ cont.resume(returning: .success([desc.stringValue ?? ""]))+ }+ }+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/MailViews.swift b/NotchBuddy/Sources/App/MailViews.swiftnew file mode 100644index 00000000..0571a439--- /dev/null+++ b/NotchBuddy/Sources/App/MailViews.swift@@ -0,0 +1,222 @@+#if !APPSTORE+import SwiftUI+import AppKit++// MARK: - Mail card (Apple Mail pill)++/// Accent of the Mail pill (the catalog colour, before any colour the user picked).+private let mailAccent = "#2F8CFF"++/// The latest messages of every inbox in Apple Mail, newest first, unread ones highlighted.+/// A click on a message opens it in the card (sender, subject, text) with Open in Mail,+/// Reply (Mail's own reply window: nothing is sent from Coucou) and Mark as read.+struct MailCardView: View {+ @ObservedObject private var mail = MailController.shared+ @State private var openId: String? = nil++ private var openMessage: MailMessage? {+ guard let openId else { return nil }+ return mail.messages.first { $0.id == openId }+ }++ var body: some View {+ Group {+ if let message = openMessage {+ MailDetailView(message: message) {+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { openId = nil }+ }+ .transition(.opacity)+ } else {+ list+ .transition(.opacity)+ }+ }+ .onAppear { mail.refreshIfStale() }+ }++ private var list: some View {+ VStack(alignment: .leading, spacing: 0) {+ // Header+ HStack(spacing: 6) {+ Circle()+ .fill(Color(hex: mailAccent))+ .frame(width: 7, height: 7)+ Text(verbatim: "Mail")+ .font(.system(size: 12, weight: .semibold))+ .foregroundColor(Color(hex: "#F5F6F8"))+ Text("Inbox")+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#8E939C"))+ if let unread = mail.unreadCount, unread > 0 {+ Text(String(format: String(localized: "%lld unread"), Int64(unread)))+ .font(.system(size: 10, weight: .semibold))+ .foregroundColor(Color(hex: mailAccent))+ .monospacedDigit()+ .padding(.horizontal, 6).padding(.vertical, 1)+ .background(Color(hex: mailAccent).opacity(0.14))+ .clipShape(Capsule())+ }+ Spacer(minLength: 2)+ }+ .padding(.top, 6)+ .padding(.leading, 108)+ .padding(.trailing, 36)++ // Message rows: three in view, the rest a scroll away.+ if mail.messages.isEmpty {+ Group {+ if mail.loaded { Text("No messages") } else { Text("Loading…") }+ }+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#6B7079"))+ .padding(.top, 8)+ .padding(.leading, 116)+ } else {+ ScrollView(.vertical, showsIndicators: false) {+ VStack(alignment: .leading, spacing: 3) {+ ForEach(mail.messages) { message in+ MailRow(message: message) {+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) {+ openId = message.id+ }+ }+ }+ }+ }+ .padding(.top, 5)+ .padding(.leading, 108)+ .padding(.trailing, 12)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ .padding(.top, 4)+ }+}++/// One message in the list: sender, age, subject. Unread ones are tinted, with a dot.+private struct MailRow: View {+ let message: MailMessage+ let onOpen: () -> Void+ @State private var hovered = false++ var body: some View {+ let accent = Color(hex: mailAccent)+ Button(action: onOpen) {+ HStack(spacing: 5) {+ Circle()+ .fill(message.isRead ? Color.clear : accent)+ .overlay(Circle().stroke(Color(hex: "#4D5159"), lineWidth: message.isRead ? 1 : 0))+ .frame(width: 5, height: 5)+ Text(message.senderName)+ .font(.system(size: 11, weight: message.isRead ? .regular : .semibold))+ .foregroundColor(Color(hex: message.isRead ? "#9398A1" : "#E8E9EC"))+ .lineLimit(1).truncationMode(.tail)+ .frame(maxWidth: 82, alignment: .leading)+ .layoutPriority(1)+ Text(message.timeAgo)+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#6B7079"))+ .fixedSize()+ Text(message.subject)+ .font(.system(size: 10))+ .foregroundColor(Color(hex: message.isRead ? "#4D5159" : "#8E939C"))+ .lineLimit(1).truncationMode(.tail)+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 8).padding(.vertical, 3)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(+ RoundedRectangle(cornerRadius: 5)+ .fill(message.isRead+ ? Color.white.opacity(hovered ? 0.05 : 0)+ : accent.opacity(hovered ? 0.14 : 0.08))+ )+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .onHover { hovered = $0 }+ }+}++// MARK: - Mail detail++/// One message opened in the card: sender, subject, the start of its text, and actions.+struct MailDetailView: View {+ let message: MailMessage+ let onClose: () -> Void+ @ObservedObject private var mail = MailController.shared++ var body: some View {+ let accent = Color(hex: mailAccent)+ VStack(alignment: .leading, spacing: 4) {+ // Header: back, sender, age+ HStack(spacing: 6) {+ Button(action: onClose) {+ Image(systemName: "chevron.left")+ .font(.system(size: 10, weight: .semibold))+ .foregroundColor(Color(hex: "#6B7079"))+ .frame(width: 20, height: 20)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)++ Circle()+ .fill(message.isRead ? Color(hex: "#4D5159") : accent)+ .frame(width: 6, height: 6)+ Text(message.senderName)+ .font(.system(size: 11, weight: .semibold))+ .foregroundColor(Color(hex: "#F5F6F8"))+ .lineLimit(1).truncationMode(.tail)+ .layoutPriority(1)+ .help(message.senderAddress)+ Spacer(minLength: 2)+ Text(message.timeAgo)+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#6B7079"))+ .fixedSize()+ }++ Text(message.subject.isEmpty ? " " : message.subject)+ .font(.system(size: 11, weight: .medium))+ .foregroundColor(Color(hex: "#C5C8CD"))+ .lineLimit(1).truncationMode(.tail)++ // The start of the message, scrollable.+ ScrollView(.vertical, showsIndicators: false) {+ Group {+ if let text = mail.previews[message.id] {+ Text(text.isEmpty ? " " : text)+ } else {+ Text("Loading…")+ }+ }+ .font(.system(size: 10.5))+ .foregroundColor(Color(hex: "#9398A1"))+ .frame(maxWidth: .infinity, alignment: .leading)+ .textSelection(.enabled)+ }+ .frame(height: 28)++ // Actions: each one is the user's own click. Nothing is ever sent from here.+ HStack(spacing: 12) {+ Button("Open in Mail") { mail.openInMail(message) }+ .foregroundColor(accent.opacity(0.9))+ Button("Reply") { mail.reply(message) }+ .foregroundColor(Color(hex: "#C5C8CD"))+ if !message.isRead {+ Button("Mark as read") { mail.markAsRead(message) }+ .foregroundColor(Color(hex: "#8E939C"))+ }+ }+ .font(.system(size: 11, weight: .medium))+ .buttonStyle(.plain)+ }+ .padding(.top, 4)+ .padding(.leading, 108)+ .padding(.trailing, 12)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ .contentShape(Rectangle())+ .onAppear { mail.loadPreview(message) }+ }+}+#endifdiff --git a/NotchBuddy/Sources/CoucouKit/PillCatalog.swift b/NotchBuddy/Sources/CoucouKit/PillCatalog.swiftindex 61063ae4..2d511824 100644--- a/NotchBuddy/Sources/CoucouKit/PillCatalog.swift+++ b/NotchBuddy/Sources/CoucouKit/PillCatalog.swift@@ -124,6 +124,8 @@ enum PillCatalog {category: .service, subtitle: "Integration", source: .n8n, githubOnly: true),.init(id: "integration_spotify", name: "Spotify", color: "#1DB954",category: .service, subtitle: "Integration", source: .n8n, githubOnly: true),+ .init(id: "integration_mail", name: "Mail", color: "#2F8CFF",+ category: .service, subtitle: "Integration", source: .n8n, githubOnly: true),]/// Pills available in the current build target.