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
Crypto pill: live prices from Coinbase or OKX, with an optional move alert
Clauded18e06e0d987
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex 5b747f30..87d4df8f 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 */; };+ AA4B191682537CC92C899BC9 /* CryptoViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 036DE9440154C95E2B90C1EA /* CryptoViews.swift */; };+ 91ECF9F7C5C7E5F6886FA02F /* CryptoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 033D87BF740911193C67D94D /* CryptoController.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 */; };@@ -129,6 +131,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 */; };+ A42BEDAC04B72921BF113A2C /* CryptoViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 036DE9440154C95E2B90C1EA /* CryptoViews.swift */; };+ BA41CE5D1739D3024B4F3214 /* CryptoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 033D87BF740911193C67D94D /* CryptoController.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 */; };@@ -444,6 +448,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>"; };+ 036DE9440154C95E2B90C1EA /* CryptoViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CryptoViews.swift; sourceTree = "<group>"; };+ 033D87BF740911193C67D94D /* CryptoController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CryptoController.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>"; };@@ -591,6 +597,8 @@914A792788D403F836BEB570 /* SpotifyViews.swift */,2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */,87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */,+ 036DE9440154C95E2B90C1EA /* CryptoViews.swift */,+ 033D87BF740911193C67D94D /* CryptoController.swift */,DCFDE7CC2BD8BCA9A6C9DF45 /* MailViews.swift */,AB502629F8A6EE9E8A647B2E /* MailController.swift */,E5077E908D307285474CA87C /* ApprovalQueue.swift */,@@ -1067,6 +1075,8 @@1558BB00C530B721172F6E65 /* StripePoller.swift in Sources */,9EA178EA395B116336C1FA10 /* TerminalTarget+AppKit.swift in Sources */,1D4CE0CCD2B5A0FFE50C7F06 /* TerminalTarget.swift in Sources */,+ AA4B191682537CC92C899BC9 /* CryptoViews.swift in Sources */,+ 91ECF9F7C5C7E5F6886FA02F /* CryptoController.swift in Sources */,AE2F7E3B42815ADC7EE77B8D /* MailViews.swift in Sources */,56D42241B003E714A77CF838 /* MailController.swift in Sources */,65F11D3911C3240BD89CF1C5 /* ApprovalQueue.swift in Sources */,@@ -1263,6 +1273,8 @@E4B9986674F4D425826F15A8 /* StripePoller.swift in Sources */,11F14DB97C93CF84DF9D5C43 /* TerminalTarget+AppKit.swift in Sources */,6726F74966EDE7F82BFE89B2 /* TerminalTarget.swift in Sources */,+ A42BEDAC04B72921BF113A2C /* CryptoViews.swift in Sources */,+ BA41CE5D1739D3024B4F3214 /* CryptoController.swift in Sources */,F6D1C30750D5232B70F678C1 /* MailViews.swift in Sources */,2B2706A9D900EE525E470A6F /* MailController.swift in Sources */,3E808AC02E35ABF5801BEBEC /* ApprovalQueue.swift in Sources */,diff --git a/NotchBuddy/Resources/Localizable.xcstrings b/NotchBuddy/Resources/Localizable.xcstringsindex 0f450893..37205b3e 100644--- a/NotchBuddy/Resources/Localizable.xcstrings+++ b/NotchBuddy/Resources/Localizable.xcstrings@@ -26782,6 +26782,518 @@}}}+ },+ "crypto.exchange": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "المنصة"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "এক্সচেঞ্জ"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Exchange"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Plataforma"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Plateforme"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "एक्सचेंज"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Bursa"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Corretora"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Биржа"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "交易所"+ }+ }+ }+ },+ "crypto.currency": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "العملة"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "মুদ্রা"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Currency"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Moneda"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Monnaie"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "मुद्रा"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Mata uang"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Moeda"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Валюта"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "货币"+ }+ }+ }+ },+ "crypto.coins-placeholder": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "العملات (BTC, ETH, SOL…)"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "কয়েন (BTC, ETH, SOL…)"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Coins (BTC, ETH, SOL…)"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Monedas (BTC, ETH, SOL…)"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Cryptos (BTC, ETH, SOL…)"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "कॉइन (BTC, ETH, SOL…)"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Koin (BTC, ETH, SOL…)"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Moedas (BTC, ETH, SOL…)"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Монеты (BTC, ETH, SOL…)"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "币种(BTC, ETH, SOL…)"+ }+ }+ }+ },+ "crypto.alert %lld": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "نبّهني عندما تتحرك عملة بنسبة %lld %%"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "কোনো কয়েন %lld %% ওঠানামা করলে জানাও"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Alert me when a coin moves %lld %%"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Avisarme cuando una moneda se mueva un %lld %%"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "M’alerter quand une crypto bouge de %lld %%"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "कोई कॉइन %lld %% हिले तो सूचित करें"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Beri tahu saat koin bergerak %lld %%"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Avisar quando uma moeda variar %lld %%"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Сообщать, если монета изменится на %lld %%"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "币价变动 %lld %% 时提醒我"+ }+ }+ }+ },+ "crypto.hint": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "أسعار عامة من المنصة: بلا حساب ولا مفتاح. تُقرأ كل دقيقة، فقط حين تكون الحبة مفعّلة."+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "এক্সচেঞ্জের পাবলিক দাম: কোনো অ্যাকাউন্ট বা কী লাগে না। পিলটি চালু থাকলেই শুধু প্রতি মিনিটে পড়া হয়।"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Public prices from the exchange: no account, no key. Read every minute, only while the pill is on."+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Precios públicos de la plataforma: sin cuenta ni clave. Se leen cada minuto, solo con la píldora activa."+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Cours publics de la plateforme : ni compte ni clé. Lus chaque minute, seulement quand la pilule est active."+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "एक्सचेंज की सार्वजनिक कीमतें: न खाता, न कुंजी। पिल चालू होने पर ही हर मिनट पढ़ी जाती हैं।"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Harga publik dari bursa: tanpa akun, tanpa kunci. Dibaca tiap menit, hanya saat pil aktif."+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Preços públicos da corretora: sem conta nem chave. Lidos a cada minuto, só com a pílula ativa."+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Публичные цены биржи: без аккаунта и ключа. Обновляются раз в минуту, только когда пилюля включена."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "来自交易所的公开行情:无需账户和密钥。仅在启用该胶囊时每分钟读取一次。"+ }+ }+ }+ },+ "crypto.no-coins": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "أضف عملات في الإعدادات ← التكاملات"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "সেটিংস → ইন্টিগ্রেশনে কয়েন যোগ করুন"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Add coins in Settings → Integrations"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Añade monedas en Ajustes → Integraciones"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Ajoute des cryptos dans Réglages → Intégrations"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "सेटिंग्स → इंटीग्रेशन में कॉइन जोड़ें"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Tambahkan koin di Pengaturan → Integrasi"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Adicione moedas em Ajustes → Integrações"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Добавьте монеты в Настройки → Интеграции"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "在“设置 → 集成”中添加币种"+ }+ }+ }+ },+ "crypto.unavailable %@": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "لم يستجب %@"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ সাড়া দেয়নি"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ did not answer"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ no respondió"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ n’a pas répondu"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ ने जवाब नहीं दिया"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ tidak merespons"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ não respondeu"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ не отвечает"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ 未响应"+ }+ }+ }+ },+ "crypto.not-listed %@": {+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "غير مدرجة في هذه المنصة: %@"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "এই এক্সচেঞ্জে নেই: %@"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Not on this exchange: %@"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "No está en esta plataforma: %@"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Absente de cette plateforme : %@"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "इस एक्सचेंज पर नहीं: %@"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Tidak ada di bursa ini: %@"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Não está nesta corretora: %@"+ }+ },+ "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 8c926779..03f3ee80 100644--- a/NotchBuddy/Sources/App/AppDelegate.swift+++ b/NotchBuddy/Sources/App/AppDelegate.swift@@ -219,6 +219,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {_ = SpotifyController.sharedMailController.shared.start()#endif+ CryptoController.shared.start()}}diff --git a/NotchBuddy/Sources/App/CryptoController.swift b/NotchBuddy/Sources/App/CryptoController.swiftnew file mode 100644index 00000000..38abab45--- /dev/null+++ b/NotchBuddy/Sources/App/CryptoController.swift@@ -0,0 +1,328 @@+import Foundation+import Combine++// MARK: - Crypto quote++/// A coin's price on the chosen exchange, its price 24 h ago and the last 24 hourly closes.+struct CryptoQuote: Identifiable, Equatable, Sendable {+ let symbol: String+ let price: Double+ let open24h: Double+ /// Hourly closes over the last 24 h, oldest first (empty until the candles are read).+ var spark: [Double] = []++ var id: String { symbol }++ /// Change over 24 h, in percent.+ var change: Double { open24h > 0 ? (price - open24h) / open24h * 100 : 0 }+}++// MARK: - Exchange++/// Public market data of an exchange: no account, no key.+enum CryptoExchange: String, CaseIterable, Sendable {+ case coinbase, okx++ var name: String {+ switch self {+ case .coinbase: return "Coinbase"+ case .okx: return "OKX"+ }+ }++ /// Trading pair for a coin in a currency. OKX quotes dollars in USDT.+ func pair(_ symbol: String, _ currency: String) -> String {+ switch self {+ case .coinbase: return "\(symbol)-\(currency)"+ case .okx: return "\(symbol)-\(currency == "USD" ? "USDT" : currency)"+ }+ }++ func tickerURL(_ pair: String) -> URL? {+ switch self {+ case .coinbase: return URL(string: "https://api.exchange.coinbase.com/products/\(pair)/stats")+ case .okx: return URL(string: "https://www.okx.com/api/v5/market/ticker?instId=\(pair)")+ }+ }++ func candlesURL(_ pair: String) -> URL? {+ switch self {+ case .coinbase: return URL(string: "https://api.exchange.coinbase.com/products/\(pair)/candles?granularity=3600")+ case .okx: return URL(string: "https://www.okx.com/api/v5/market/candles?instId=\(pair)&bar=1H&limit=24")+ }+ }++ /// The coin's market page on the exchange's site.+ func tradeURL(_ pair: String) -> URL? {+ switch self {+ case .coinbase: return URL(string: "https://www.coinbase.com/advanced-trade/spot/\(pair)")+ case .okx: return URL(string: "https://www.okx.com/trade-spot/\(pair.lowercased())")+ }+ }++ /// (price, price 24 h ago) from the ticker answer.+ func parseTicker(_ data: Data) -> (Double, Double)? {+ guard let json = try? JSONSerialization.jsonObject(with: data) else { return nil }+ switch self {+ case .coinbase:+ guard let d = json as? [String: Any],+ let last = Self.number(d["last"]), let open = Self.number(d["open"]) else { return nil }+ return (last, open)+ case .okx:+ guard let d = json as? [String: Any], (d["code"] as? String) == "0",+ let row = (d["data"] as? [[String: Any]])?.first,+ let last = Self.number(row["last"]), let open = Self.number(row["open24h"]) else { return nil }+ return (last, open)+ }+ }++ /// Hourly closes, oldest first, from the candles answer (both exchanges send newest first).+ func parseCandles(_ data: Data) -> [Double] {+ guard let json = try? JSONSerialization.jsonObject(with: data) else { return [] }+ let rows: [[Any]]+ switch self {+ case .coinbase: rows = (json as? [[Any]]) ?? []+ case .okx: rows = ((json as? [String: Any])?["data"] as? [[Any]]) ?? []+ }+ // Close: index 4 on both (Coinbase: time, low, high, open, close; OKX: ts, o, h, l, c).+ let closes = rows.prefix(24).compactMap { $0.count > 4 ? Self.number($0[4]) : nil }+ return closes.reversed()+ }++ private static func number(_ v: Any?) -> Double? {+ if let d = v as? Double { return d }+ if let s = v as? String { return Double(s) }+ if let n = v as? NSNumber { return n.doubleValue }+ return nil+ }+}++// MARK: - Crypto settings++enum CryptoSettings {+ static let exchangeKey = "cryptoExchange"+ static let currencyKey = "cryptoCurrency"+ static let coinsKey = "cryptoCoins"+ static let alertKey = "cryptoAlertEnabled"+ static let alertPercentKey = "cryptoAlertPercent"++ static let defaultCoins = "BTC, ETH, SOL"+ static let maxCoins = 8++ static var exchange: CryptoExchange {+ CryptoExchange(rawValue: UserDefaults.standard.string(forKey: exchangeKey) ?? "") ?? .coinbase+ }+ static var currency: String {+ let c = UserDefaults.standard.string(forKey: currencyKey) ?? "EUR"+ return c == "USD" ? "USD" : "EUR"+ }+ /// "btc, Eth;sol" → ["BTC", "ETH", "SOL"]: letters and digits only, no repeats.+ static func parseCoins(_ raw: String) -> [String] {+ var seen = Set<String>()+ return raw.uppercased()+ .split(whereSeparator: { !$0.isLetter && !$0.isNumber })+ .map(String.init)+ .filter { $0.count <= 10 && seen.insert($0).inserted }+ .prefix(maxCoins)+ .map { $0 }+ }+ static var coins: [String] {+ parseCoins(UserDefaults.standard.string(forKey: coinsKey) ?? defaultCoins)+ }+ static var alertEnabled: Bool { UserDefaults.standard.bool(forKey: alertKey) }+ static var alertPercent: Double {+ let v = UserDefaults.standard.double(forKey: alertPercentKey)+ return v > 0 ? v : 5+ }+}++// MARK: - Crypto Controller++/// Prices of the coins the user picked, from Coinbase or OKX public market data (no key,+/// no account). Read every 60 s and the 24 h curve every 10 min, only while the pill is+/// on: nothing goes over the network otherwise. An opt-in alert reveals the island when a+/// coin moves more than the chosen percentage since the last alert.+@MainActor+final class CryptoController: ObservableObject {+ static let shared = CryptoController()+ nonisolated static let pillId = "integration_crypto"++ /// Quotes in the order the coins were listed; a coin the exchange doesn't list is absent.+ @Published private(set) var quotes: [CryptoQuote] = []+ /// Coins the exchange did not answer for (unknown pair, or no network).+ @Published private(set) var missing: [String] = []+ @Published private(set) var loaded = false+ @Published private(set) var lastUpdate: Date?+ /// The coin that set off the last alert, for the card to show it first.+ @Published private(set) var alertSymbol: String?++ private var timer: Timer?+ private var fetching = false+ private var lastCandles: Date = .distantPast+ /// Price each coin had at the last alert (or when first seen).+ private var reference: [String: Double] = [:]+ private var cancellables = Set<AnyCancellable>()+ private var lastSettings = ""++ private var isPillActive: Bool {+ AppState.shared.activeIntegrations.contains(Self.pillId)+ }++ private init() {+ 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)+ }++ func start() { updatePolling() }++ /// Exchange, currency or coins changed in Settings: start over with the new list.+ func settingsChanged() {+ let key = "\(CryptoSettings.exchange.rawValue)|\(CryptoSettings.currency)|\(CryptoSettings.coins.joined(separator: ","))"+ guard key != lastSettings else { return }+ lastSettings = key+ quotes = []+ missing = []+ loaded = false+ reference = [:]+ lastCandles = .distantPast+ refresh()+ }++ private func updatePolling() {+ if isPillActive {+ if timer == nil {+ let t = Timer(timeInterval: 60, repeats: true) { _ in+ MainActor.assumeIsolated { CryptoController.shared.refresh() }+ }+ t.tolerance = 10+ RunLoop.main.add(t, forMode: .common)+ timer = t+ }+ lastSettings = "\(CryptoSettings.exchange.rawValue)|\(CryptoSettings.currency)|\(CryptoSettings.coins.joined(separator: ","))"+ refresh()+ } else {+ timer?.invalidate()+ timer = nil+ quotes = []+ missing = []+ loaded = false+ lastUpdate = nil+ reference = [:]+ alertSymbol = nil+ lastCandles = .distantPast+ }+ }++ func refreshIfStale(minAge: TimeInterval = 20) {+ guard Date().timeIntervalSince(lastUpdate ?? .distantPast) > minAge else { return }+ refresh()+ }++ func refresh() {+ guard isPillActive, !fetching else { return }+ let exchange = CryptoSettings.exchange+ let currency = CryptoSettings.currency+ let coins = CryptoSettings.coins+ guard !coins.isEmpty else {+ quotes = []; missing = []; loaded = true+ return+ }+ let withCandles = Date().timeIntervalSince(lastCandles) > 600+ fetching = true+ Task {+ var fresh: [CryptoQuote] = []+ var notFound: [String] = []+ await withTaskGroup(of: (Int, CryptoQuote?).self) { group in+ for (i, coin) in coins.enumerated() {+ group.addTask {+ (i, await Self.fetch(coin, exchange: exchange, currency: currency, candles: withCandles))+ }+ }+ var byIndex: [Int: CryptoQuote] = [:]+ for await (i, q) in group {+ if let q { byIndex[i] = q } else { notFound.append(coins[i]) }+ }+ fresh = coins.indices.compactMap { byIndex[$0] }+ }+ fetching = false+ // Keep the previous curve until a new one is read.+ let previous = Dictionary(uniqueKeysWithValues: quotes.map { ($0.symbol, $0.spark) })+ for i in fresh.indices where fresh[i].spark.isEmpty {+ fresh[i].spark = previous[fresh[i].symbol] ?? []+ }+ if withCandles && !fresh.isEmpty { lastCandles = Date() }+ if fresh != quotes { quotes = fresh }+ missing = notFound.sorted { (coins.firstIndex(of: $0) ?? 0) < (coins.firstIndex(of: $1) ?? 0) }+ loaded = true+ lastUpdate = Date()+ checkAlerts()+ }+ }++ private nonisolated static func fetch(_ coin: String, exchange: CryptoExchange, currency: String,+ candles: Bool) async -> CryptoQuote? {+ let pair = exchange.pair(coin, currency)+ guard let url = exchange.tickerURL(pair) else { return nil }+ var req = URLRequest(url: url, timeoutInterval: 10)+ req.setValue("application/json", forHTTPHeaderField: "Accept")+ guard let (data, response) = try? await URLSession.shared.data(for: req),+ (response as? HTTPURLResponse)?.statusCode == 200,+ let (price, open) = exchange.parseTicker(data) else { return nil }+ var quote = CryptoQuote(symbol: coin, price: price, open24h: open)+ if candles, let curl = exchange.candlesURL(pair) {+ var creq = URLRequest(url: curl, timeoutInterval: 10)+ creq.setValue("application/json", forHTTPHeaderField: "Accept")+ if let (cdata, cresp) = try? await URLSession.shared.data(for: creq),+ (cresp as? HTTPURLResponse)?.statusCode == 200 {+ quote.spark = exchange.parseCandles(cdata)+ }+ }+ return quote+ }++ // MARK: - Alerts++ /// A coin that moved more than the chosen percentage since the last alert (or since it+ /// was first seen) plays a sound and reveals the island on the Crypto pill. Off by default.+ private func checkAlerts() {+ for q in quotes {+ guard let ref = reference[q.symbol], ref > 0 else {+ reference[q.symbol] = q.price+ continue+ }+ let move = abs(q.price - ref) / ref * 100+ guard CryptoSettings.alertEnabled, move >= CryptoSettings.alertPercent else { continue }+ reference[q.symbol] = q.price+ alertSymbol = q.symbol+ let state = AppState.shared+ if state.mode != .expanded, state.tasks.contains(where: { $0.id == Self.pillId }) {+ state.focusId = Self.pillId+ }+ NotificationCenter.default.post(name: .hookReveal, object: nil)+ break // one alert at a time+ }+ }++ // MARK: - Formatting++ /// "62 140 €", "3 120,55 €", "0,4312 $" in the user's locale.+ static func format(_ value: Double, currency: String) -> String {+ let f = NumberFormatter()+ f.numberStyle = .currency+ f.currencyCode = currency+ let digits = value >= 1000 ? 0 : value >= 1 ? 2 : 4+ f.minimumFractionDigits = digits+ f.maximumFractionDigits = digits+ return f.string(from: NSNumber(value: value)) ?? String(format: "%.2f", value)+ }++ static func formatChange(_ pct: Double) -> String {+ String(format: "%@%.2f %%", pct >= 0 ? "+" : "−", abs(pct))+ }+}diff --git a/NotchBuddy/Sources/App/CryptoViews.swift b/NotchBuddy/Sources/App/CryptoViews.swiftnew file mode 100644index 00000000..68bc5366--- /dev/null+++ b/NotchBuddy/Sources/App/CryptoViews.swift@@ -0,0 +1,162 @@+import SwiftUI+import AppKit++// MARK: - Crypto card++/// The coins picked in Settings with their price, 24 h curve and 24 h change, from Coinbase+/// or OKX public data. Three in view, the rest a scroll away; a click opens the coin's page+/// on the exchange.+struct CryptoCardView: View {+ @ObservedObject private var crypto = CryptoController.shared++ private var accent: Color {+ Color(hex: PillCatalog.definition(for: CryptoController.pillId)?.color ?? "#F7931A")+ }++ /// The coin of the last alert first, then the others in their order.+ private var ordered: [CryptoQuote] {+ guard let s = crypto.alertSymbol, let i = crypto.quotes.firstIndex(where: { $0.symbol == s }) else {+ return crypto.quotes+ }+ var q = crypto.quotes+ q.insert(q.remove(at: i), at: 0)+ return q+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ // Header+ HStack(spacing: 6) {+ Circle()+ .fill(accent)+ .frame(width: 7, height: 7)+ Text(verbatim: "Crypto")+ .font(.system(size: 12, weight: .semibold))+ .foregroundColor(Color(hex: "#F5F6F8"))+ Text(verbatim: CryptoSettings.exchange.name)+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#8E939C"))+ Text(verbatim: "24h")+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#6B7079"))+ Spacer(minLength: 2)+ }+ .padding(.top, 6)+ .padding(.leading, 108)+ .padding(.trailing, 36)++ if crypto.quotes.isEmpty {+ Group {+ if !crypto.loaded {+ Text("Loading…")+ } else if CryptoSettings.coins.isEmpty {+ Text("crypto.no-coins")+ } else {+ Text(String(format: String(localized: "crypto.unavailable %@"),+ CryptoSettings.exchange.name))+ }+ }+ .font(.system(size: 11))+ .foregroundColor(Color(hex: "#6B7079"))+ .padding(.top, 8)+ .padding(.leading, 116)+ .padding(.trailing, 12)+ } else {+ ScrollView(.vertical, showsIndicators: false) {+ VStack(alignment: .leading, spacing: 3) {+ ForEach(ordered) { quote in+ CryptoRow(quote: quote, highlighted: quote.symbol == crypto.alertSymbol)+ }+ if !crypto.missing.isEmpty {+ Text(String(format: String(localized: "crypto.not-listed %@"),+ crypto.missing.joined(separator: ", ")))+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#4D5159"))+ .lineLimit(1).truncationMode(.tail)+ .padding(.horizontal, 8)+ }+ }+ }+ .padding(.top, 5)+ .padding(.leading, 108)+ .padding(.trailing, 12)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ .padding(.top, 4)+ .onAppear { crypto.refreshIfStale() }+ }+}++/// One coin: symbol, 24 h curve, price, change. A click opens its page on the exchange.+private struct CryptoRow: View {+ let quote: CryptoQuote+ let highlighted: Bool+ @State private var hovered = false++ var body: some View {+ let up = quote.change >= 0+ let tone = Color(hex: up ? "#22C55E" : "#F4505E")+ Button {+ let exchange = CryptoSettings.exchange+ if let url = exchange.tradeURL(exchange.pair(quote.symbol, CryptoSettings.currency)) {+ NSWorkspace.shared.open(url)+ }+ } label: {+ HStack(spacing: 6) {+ Text(verbatim: quote.symbol)+ .font(.system(size: 11, weight: .semibold))+ .foregroundColor(Color(hex: "#E8E9EC"))+ .lineLimit(1)+ .frame(width: 30, alignment: .leading)+ CryptoSparkline(values: quote.spark, color: tone)+ .frame(width: 30, height: 12)+ Spacer(minLength: 2)+ Text(verbatim: CryptoController.format(quote.price, currency: CryptoSettings.currency))+ .font(.system(size: 11, weight: .medium))+ .foregroundColor(Color(hex: "#C5C8CD"))+ .monospacedDigit()+ .lineLimit(1)+ .fixedSize()+ Text(verbatim: CryptoController.formatChange(quote.change))+ .font(.system(size: 10, weight: .medium))+ .foregroundColor(tone)+ .monospacedDigit()+ .lineLimit(1)+ .fixedSize()+ }+ .padding(.horizontal, 8).padding(.vertical, 3)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(+ RoundedRectangle(cornerRadius: 5)+ .fill(highlighted ? tone.opacity(hovered ? 0.16 : 0.10)+ : Color.white.opacity(hovered ? 0.05 : 0))+ )+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .onHover { hovered = $0 }+ }+}++/// The last 24 hourly closes as a thin line. Drawn once per new curve (no animation).+struct CryptoSparkline: View {+ let values: [Double]+ let color: Color++ var body: some View {+ GeometryReader { geo in+ if values.count >= 2, let lo = values.min(), let hi = values.max() {+ let span = max(hi - lo, hi * 0.0001)+ Path { p in+ for (i, v) in values.enumerated() {+ let x = geo.size.width * CGFloat(i) / CGFloat(values.count - 1)+ let y = geo.size.height * (1 - CGFloat((v - lo) / span))+ if i == 0 { p.move(to: CGPoint(x: x, y: y)) } else { p.addLine(to: CGPoint(x: x, y: y)) }+ }+ }+ .stroke(color.opacity(0.85), style: StrokeStyle(lineWidth: 1.2, lineCap: .round, lineJoin: .round))+ }+ }+ }+}diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swiftindex d21033fc..8cc2d25e 100644--- a/NotchBuddy/Sources/App/IslandViewContent.swift+++ b/NotchBuddy/Sources/App/IslandViewContent.swift@@ -225,6 +225,12 @@ struct OverviewView: View {#if !APPSTOREMailController.shared.openMail()#endif+ case "integration_crypto":+ let exchange = CryptoSettings.exchange+ if let first = CryptoSettings.coins.first,+ let url = exchange.tradeURL(exchange.pair(first, CryptoSettings.currency)) {+ NSWorkspace.shared.open(url)+ }case "integration_vercel":NSWorkspace.shared.open(URL(string: "https://vercel.com/dashboard")!)case "integration_github":@@ -1846,6 +1852,8 @@ struct IntegrationCardView: View {#elsereturn false#endif+ case "integration_crypto":+ return true // public market data: no key, nothing to set upcase "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@@ -2094,6 +2102,10 @@ struct IntegrationCardView: View {MusicCardView().transition(.opacity)#endif+ } else if task.id == "integration_crypto" {+ // Its own card in every state (loading, no coins, prices).+ CryptoCardView()+ .transition(.opacity)} else if mailHasData {#if !APPSTOREMailCardView()diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swiftindex 402ae235..05d4c4c3 100644--- a/NotchBuddy/Sources/App/SettingsView.swift+++ b/NotchBuddy/Sources/App/SettingsView.swift@@ -103,6 +103,11 @@ struct SettingsView: View {@State private var stripeKey: String = KeychainStore.shared.get("stripe-api-key") ?? ""@State private var calcomKey: String = KeychainStore.shared.get("calcom-api-key") ?? ""@State private var notionKey: String = KeychainStore.shared.get("notion-api-key") ?? ""+ @AppStorage(CryptoSettings.exchangeKey) private var cryptoExchange = CryptoExchange.coinbase.rawValue+ @AppStorage(CryptoSettings.currencyKey) private var cryptoCurrency = "EUR"+ @AppStorage(CryptoSettings.coinsKey) private var cryptoCoins = CryptoSettings.defaultCoins+ @AppStorage(CryptoSettings.alertKey) private var cryptoAlert = false+ @AppStorage(CryptoSettings.alertPercentKey) private var cryptoAlertPercent = 5.0// Hotkey@State private var hotkeyFlags: UInt = AppState.shared.hotkeyFlags@@ -1246,7 +1251,45 @@ struct SettingsView: View {.textFieldStyle(.roundedBorder)}- Button(String(localized: "integrations.save")) { saveIntegrations() }+ // Crypto: public prices, no key. Changes apply at once.+ VStack(alignment: .leading, spacing: 5) {+ HStack(spacing: 6) {+ Circle().fill(Color(hex: "#F7931A")).frame(width: 8, height: 8)+ Text(verbatim: "Crypto").font(.system(size: 12, weight: .semibold))+ }+ Picker(String(localized: "crypto.exchange"), selection: $cryptoExchange) {+ ForEach(CryptoExchange.allCases, id: \.rawValue) { ex in+ Text(verbatim: ex.name).tag(ex.rawValue)+ }+ }+ .pickerStyle(.segmented)+ Picker(String(localized: "crypto.currency"), selection: $cryptoCurrency) {+ Text(verbatim: "EUR €").tag("EUR")+ Text(verbatim: "USD $").tag("USD")+ }+ .pickerStyle(.segmented)+ TextField(String(localized: "crypto.coins-placeholder"), text: $cryptoCoins)+ .textFieldStyle(.roundedBorder)+ .onSubmit { CryptoController.shared.settingsChanged() }+ HStack(spacing: 8) {+ Toggle(String(format: String(localized: "crypto.alert %lld"), Int64(cryptoAlertPercent)),+ isOn: $cryptoAlert)+ if cryptoAlert {+ Stepper("", value: $cryptoAlertPercent, in: 1...50, step: 1)+ .labelsHidden()+ }+ }+ Text(String(localized: "crypto.hint"))+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#8E939C"))+ }+ .onChange(of: cryptoExchange) { _, _ in CryptoController.shared.settingsChanged() }+ .onChange(of: cryptoCurrency) { _, _ in CryptoController.shared.settingsChanged() }++ Button(String(localized: "integrations.save")) {+ saveIntegrations()+ CryptoController.shared.settingsChanged()+ }.buttonStyle(.borderedProminent)}.padding(6)diff --git a/NotchBuddy/Sources/CoucouKit/PillCatalog.swift b/NotchBuddy/Sources/CoucouKit/PillCatalog.swiftindex 2d511824..f12fa833 100644--- a/NotchBuddy/Sources/CoucouKit/PillCatalog.swift+++ b/NotchBuddy/Sources/CoucouKit/PillCatalog.swift@@ -126,6 +126,8 @@ enum PillCatalog {category: .service, subtitle: "Integration", source: .n8n, githubOnly: true),.init(id: "integration_mail", name: "Mail", color: "#2F8CFF",category: .service, subtitle: "Integration", source: .n8n, githubOnly: true),+ .init(id: "integration_crypto", name: "Crypto", color: "#F7931A",+ category: .service, subtitle: "Integration", source: .n8n),]/// Pills available in the current build target.